The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // @effect-diagnostics globalTimers:off globalDate:off - The tracker runs in atom subscriptions, outside an Effect runtime. |
| 2 | import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; |
| 3 | import { AsyncResult, Atom } from "effect/reactivity"; |
| 4 | |
| 5 | import { parseThreadKey, threadKey } from "./entities.ts"; |
| 6 | import { type AtomCommand, runAtomCommand } from "./runtime.ts"; |
| 7 | import { claimThreadOpen } from "./threadSearch.ts"; |
| 8 | import type { VisitThreadInput } from "../operations/commands.ts"; |
| 9 | |
| 10 | // During an active turn the thread's updatedAt advances several times per |
| 11 | // second, and every server-side visit is a full command dispatch plus a |
| 12 | // broadcast to all shell subscribers. |
| 13 | export const VISIT_DISPATCH_THROTTLE_MS = 10_000; |
| 14 | |
| 15 | const IDLE_TRACKER: Atom.Atom<void> = Atom.make(undefined).pipe( |
| 16 | Atom.withLabel("thread-visit-tracker:idle"), |
| 17 | ); |
| 18 | |
| 19 | interface VisitedShell { |
| 20 | readonly environmentId: EnvironmentId; |
| 21 | readonly id: ThreadId; |
| 22 | readonly updatedAt: string; |
| 23 | readonly lastVisitedAt?: string | null | undefined; |
| 24 | readonly latestRun: { readonly completedAt: string | null } | null; |
| 25 | /** |
| 26 | * When a scheduled wake the user is looking at took effect. A wake later |
| 27 | * than `updatedAt` is an update the server never sent, so the watermark |
| 28 | * advances to it, and at once: leaving within the throttle would cancel |
| 29 | * the dispatch and keep the thread marked Woke. |
| 30 | */ |
| 31 | readonly wokeAt?: string | null | undefined; |
| 32 | } |
| 33 | |
| 34 | export interface ThreadVisitTrackerOptions { |
| 35 | readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<VisitedShell | null>; |
| 36 | readonly sessionGenerationAtom: (environmentId: EnvironmentId) => Atom.Atom<number>; |
| 37 | readonly visit: AtomCommand< |
| 38 | { readonly environmentId: EnvironmentId; readonly input: VisitThreadInput }, |
| 39 | unknown, |
| 40 | unknown |
| 41 | >; |
| 42 | /** |
| 43 | * Servers without visit tracking leave `lastVisitedAt` undefined; a client |
| 44 | * that keeps its own watermark for them records the visit here instead. |
| 45 | */ |
| 46 | readonly markLocalVisit?: (ref: ScopedThreadRef, visitedAt: string) => void; |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * While mounted, a tracker counts as the user viewing the thread: mounting it |
| 51 | * records one open (which also feeds search ranking), and every shell update |
| 52 | * after that advances the visit watermark, throttled while a run streams. |
| 53 | */ |
| 54 | export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) { |
| 55 | const family = Atom.family((key: string) => { |
| 56 | const ref = parseThreadKey(key); |
| 57 | return Atom.make((get) => { |
| 58 | const registry = get.registry; |
| 59 | // Showing the thread is the open, whether or not its shell has arrived; |
| 60 | // the shell only decides when the server hears about it. |
| 61 | // Recorded even when the server cannot take opens, so recents follow |
| 62 | // it. A palette pick already sent the open with its query. |
| 63 | let openPending = claimThreadOpen(ref.environmentId, ref.threadId, Date.now()); |
| 64 | // Dedupe per watermark: the shell updates again before the command's echo |
| 65 | // lands. It also keeps a mark-unread on the open thread sticky, since the |
| 66 | // rewind leaves updatedAt untouched. |
| 67 | let lastDispatchedUpdatedAt: string | null = null; |
| 68 | let lastAcceptedUpdatedAt: string | null = null; |
| 69 | let retryPending = false; |
| 70 | const sessionGenerationAtom = options.sessionGenerationAtom(ref.environmentId); |
| 71 | let lastDispatchGeneration = registry.get(sessionGenerationAtom); |
| 72 | let active = true; |
| 73 | let lastDispatchAt = 0; |
| 74 | let timer: ReturnType<typeof setTimeout> | undefined; |
| 75 | const clearTimer = () => { |
| 76 | if (timer === undefined) return; |
| 77 | clearTimeout(timer); |
| 78 | timer = undefined; |
| 79 | }; |
| 80 | get.addFinalizer(() => { |
| 81 | active = false; |
| 82 | clearTimer(); |
| 83 | }); |
| 84 | |
| 85 | const accept = (visitedAt: string) => { |
| 86 | const visitedAtMs = Date.parse(visitedAt); |
| 87 | if (Number.isNaN(visitedAtMs)) return; |
| 88 | if (lastAcceptedUpdatedAt === null || visitedAtMs > Date.parse(lastAcceptedUpdatedAt)) |
| 89 | lastAcceptedUpdatedAt = visitedAt; |
| 90 | }; |
| 91 | |
| 92 | const dispatch = (shell: VisitedShell, visitedAt: string, opened: boolean) => { |
| 93 | clearTimer(); |
| 94 | retryPending = false; |
| 95 | lastDispatchedUpdatedAt = visitedAt; |
| 96 | lastDispatchAt = Date.now(); |
| 97 | lastDispatchGeneration = registry.get(sessionGenerationAtom); |
| 98 | void runAtomCommand( |
| 99 | registry, |
| 100 | options.visit, |
| 101 | { |
| 102 | environmentId: shell.environmentId, |
| 103 | input: { |
| 104 | threadId: shell.id, |
| 105 | visitedAt, |
| 106 | ...(opened ? { opened: true } : {}), |
| 107 | }, |
| 108 | }, |
| 109 | { reportFailure: false }, |
| 110 | ).then((result) => { |
| 111 | if (!active) return; |
| 112 | if (!AsyncResult.isFailure(result)) { |
| 113 | accept(visitedAt); |
| 114 | return; |
| 115 | } |
| 116 | // Keep acceptance across a subsequent mark-unread, even if the ack was lost. |
| 117 | if ( |
| 118 | lastAcceptedUpdatedAt !== null && |
| 119 | Date.parse(lastAcceptedUpdatedAt) >= Date.parse(visitedAt) |
| 120 | ) |
| 121 | return; |
| 122 | if (lastDispatchedUpdatedAt !== visitedAt) return; |
| 123 | if (opened) openPending = true; |
| 124 | retryPending = true; |
| 125 | onShell(registry.get(options.threadShellAtom(ref))); |
| 126 | }); |
| 127 | }; |
| 128 | |
| 129 | const onShell = (shell: VisitedShell | null) => { |
| 130 | clearTimer(); |
| 131 | if (shell === null) return; |
| 132 | |
| 133 | const shellUpdatedAtMs = Date.parse(shell.updatedAt); |
| 134 | if (Number.isNaN(shellUpdatedAtMs)) return; |
| 135 | const wokeAtMs = shell.wokeAt ? Date.parse(shell.wokeAt) : NaN; |
| 136 | const wakeIsLatest = wokeAtMs > shellUpdatedAtMs; |
| 137 | const visitedAt = wakeIsLatest && shell.wokeAt ? shell.wokeAt : shell.updatedAt; |
| 138 | const updatedAtMs = wakeIsLatest ? wokeAtMs : shellUpdatedAtMs; |
| 139 | if (shell.lastVisitedAt === undefined) { |
| 140 | options.markLocalVisit?.(ref, visitedAt); |
| 141 | return; |
| 142 | } |
| 143 | if (shell.lastVisitedAt) accept(shell.lastVisitedAt); |
| 144 | if ( |
| 145 | retryPending && |
| 146 | lastAcceptedUpdatedAt !== null && |
| 147 | lastDispatchedUpdatedAt !== null && |
| 148 | Date.parse(lastAcceptedUpdatedAt) >= Date.parse(lastDispatchedUpdatedAt) |
| 149 | ) { |
| 150 | retryPending = false; |
| 151 | openPending = false; |
| 152 | } |
| 153 | // A rejected visit waits for a new session, even if streaming changes the shell. |
| 154 | if (retryPending && registry.get(sessionGenerationAtom) === lastDispatchGeneration) return; |
| 155 | const elapsed = Date.now() - lastDispatchAt; |
| 156 | if (retryPending && elapsed < VISIT_DISPATCH_THROTTLE_MS) { |
| 157 | timer = setTimeout( |
| 158 | () => onShell(registry.get(options.threadShellAtom(ref))), |
| 159 | VISIT_DISPATCH_THROTTLE_MS - elapsed, |
| 160 | ); |
| 161 | return; |
| 162 | } |
| 163 | // The open rides on the first visit the server hears, however late |
| 164 | // the shell arrives, so it still counts toward search ranking. |
| 165 | if (openPending) { |
| 166 | openPending = false; |
| 167 | dispatch(shell, visitedAt, true); |
| 168 | return; |
| 169 | } |
| 170 | const lastVisitedAtMs = shell.lastVisitedAt ? Date.parse(shell.lastVisitedAt) : NaN; |
| 171 | if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= updatedAtMs) { |
| 172 | // Already seen, so a later mark-unread stays sticky even when no open was sent. |
| 173 | if (lastDispatchedUpdatedAt === null || Date.parse(lastDispatchedUpdatedAt) < updatedAtMs) |
| 174 | lastDispatchedUpdatedAt = visitedAt; |
| 175 | return; |
| 176 | } |
| 177 | if ( |
| 178 | !retryPending && |
| 179 | lastDispatchedUpdatedAt !== null && |
| 180 | Date.parse(lastDispatchedUpdatedAt) >= updatedAtMs |
| 181 | ) |
| 182 | return; |
| 183 | |
| 184 | const completedAtMs = shell.latestRun?.completedAt |
| 185 | ? Date.parse(shell.latestRun.completedAt) |
| 186 | : NaN; |
| 187 | const hasUnseenCompletion = |
| 188 | !Number.isNaN(completedAtMs) && |
| 189 | (Number.isNaN(lastVisitedAtMs) || completedAtMs > lastVisitedAtMs); |
| 190 | if (hasUnseenCompletion || wakeIsLatest || elapsed >= VISIT_DISPATCH_THROTTLE_MS) { |
| 191 | dispatch(shell, visitedAt, false); |
| 192 | return; |
| 193 | } |
| 194 | timer = setTimeout( |
| 195 | () => dispatch(shell, visitedAt, false), |
| 196 | VISIT_DISPATCH_THROTTLE_MS - elapsed, |
| 197 | ); |
| 198 | }; |
| 199 | |
| 200 | // `subscribe`, not `get`: a rebuild would reset the open and throttle |
| 201 | // state on every streaming tick. |
| 202 | get.subscribe(options.threadShellAtom(ref), onShell, { immediate: true }); |
| 203 | get.subscribe(sessionGenerationAtom, () => |
| 204 | onShell(registry.get(options.threadShellAtom(ref))), |
| 205 | ); |
| 206 | }).pipe(Atom.withLabel(`thread-visit-tracker:${key}`)); |
| 207 | }); |
| 208 | return (ref: ScopedThreadRef | null) => (ref === null ? IDLE_TRACKER : family(threadKey(ref))); |
| 209 | } |