Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadVisits.ts

219 lines9.0 KB

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