The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 17:00 UTC
refactor(mobile): thread visits are tracked outside React (#24973)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 25, 2026 at 15:27 UTC
d99776351c20ad00d88b61fa583981c0df514921
4 files changed
+337
-127
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+38
-127
@@ -6,9 +6,11 @@ import {
6
settlePromise,
7
squashAtomCommandFailure,
8
} from "@t3tools/client-runtime/state/runtime";
9
-import { AsyncResult } from "effect/reactivity";
9
+import { AsyncResult, Atom } from "effect/reactivity";
10
import * as Dialog from "../../components/ui/Dialog";
11
-import { useAtomValue } from "@effect/atom-react";
11
+import { useAtomMount, useAtomValue } from "@effect/atom-react";
12
+import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entities";
13
+import { createThreadVisitTracker } from "@t3tools/client-runtime/state/thread-visits";
14
import {
15
useChildThreadInputs,
16
useThreadReportedModelSelection,
@@ -142,7 +144,6 @@ import { ThreadBrowserFloat } from "../browser/ThreadBrowserFloat";
144
import { useThreadServerBrowserTabs } from "../../state/preview";
145
import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
146
import { scopedThreadKey } from "../../lib/scopedEntities";
145
-import { claimThreadOpen } from "@t3tools/client-runtime/state/thread-search";
147
import {
148
finishThreadMessageJump,
149
pendingThreadMessageJump,
@@ -152,7 +153,7 @@ import {
153
clearThreadComposerError,
154
threadComposerErrorsAtom,
155
} from "../../state/thread-composer-error";
155
-import { threadEnvironment } from "../../state/threads";
156
+import { environmentThreadShells, threadEnvironment } from "../../state/threads";
157
import { useAtomCommand } from "../../state/use-atom-command";
158
import { useDelayedStatus } from "../../lib/useDelayedStatus";
159
import type {
@@ -380,125 +381,32 @@ const USER_INPUT_TOGGLE_TIMING = {
381
easing: Easing.out(Easing.cubic),
382
};
383
383
-// The visit watermark follows the shell's updatedAt, which ticks while a run
384
-// streams. Keeping it in a leaf lets the screen read the quiet shell.
385
-function ThreadVisitWatermark(props: {
386
- readonly environmentId: EnvironmentId;
387
- readonly selectedThread: EnvironmentThreadShell;
388
- readonly showContent: boolean;
389
-}) {
390
- const liveThread = useThreadShell({
391
- environmentId: props.environmentId,
392
- threadId: props.selectedThread.id,
393
- });
394
- const thread = liveThread ?? props.selectedThread;
395
- const showContent = props.showContent;
396
- const selectedThreadKey = scopedThreadKey(props.environmentId, thread.id);
397
- const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
398
- const lastDispatchedVisitRef = useRef<string | null>(null);
399
- const lastVisitDispatchRef = useRef({ threadKey: selectedThreadKey, at: 0 });
400
- const selectedThreadId = thread.id;
401
- const snoozedUntil = thread.snoozedUntil;
402
- // Keep the clock in state so React Compiler invalidates the wake calculation.
403
- const [wakeNow, setWakeNow] = useState(() => new Date().toISOString());
404
- useEffect(() => {
405
- if (!showContent || snoozedUntil == null) return;
406
- const delay = Date.parse(snoozedUntil) - Date.now();
407
- if (!Number.isFinite(delay)) return;
408
- const timer = setTimeout(() => setWakeNow(new Date().toISOString()), Math.max(0, delay) + 50);
409
- return () => clearTimeout(timer);
410
- }, [showContent, snoozedUntil]);
411
- const selectedThreadWokeAt = threadWokeAt(thread, {
412
- now: wakeNow,
413
- });
414
- // A scheduled wake can happen without a newer server update.
415
- const selectedThreadUpdatedAt =
416
- selectedThreadWokeAt !== null && Date.parse(selectedThreadWokeAt) > Date.parse(thread.updatedAt)
417
- ? selectedThreadWokeAt
418
- : thread.updatedAt;
419
- const wakeIsLatestUpdate = selectedThreadUpdatedAt === selectedThreadWokeAt;
420
- const selectedThreadLastVisitedAt = thread.lastVisitedAt;
421
- const selectedThreadCompletedAt = thread.latestRun?.completedAt;
422
- // Opening a thread is one visit that also counts toward search ranking; a
423
- // palette pick already sent it with the query. The watermark effect below
424
- // skips it.
425
- const recordedOpenRef = useRef<string | null>(null);
426
- useEffect(() => {
427
- if (!showContent) return;
428
- if (recordedOpenRef.current === selectedThreadKey) return;
429
- recordedOpenRef.current = selectedThreadKey;
430
- // Recorded here even when the server cannot take opens, so recents follow it.
431
- const claimed = claimThreadOpen(props.environmentId, selectedThreadId, Date.now());
432
- if (!claimed || selectedThreadLastVisitedAt === undefined) return;
433
- lastDispatchedVisitRef.current = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
434
- lastVisitDispatchRef.current = { threadKey: selectedThreadKey, at: Date.now() };
435
- void visitThread({
436
- environmentId: props.environmentId,
437
- input: {
438
- threadId: selectedThreadId,
439
- visitedAt: selectedThreadUpdatedAt,
440
- opened: true,
441
- },
442
- });
443
- }, [
444
- props.environmentId,
445
- selectedThreadId,
446
- selectedThreadKey,
447
- selectedThreadLastVisitedAt,
448
- selectedThreadUpdatedAt,
449
- showContent,
450
- visitThread,
451
- ]);
452
- useEffect(() => {
453
- if (!showContent || selectedThreadLastVisitedAt === undefined) return;
454
- const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
455
- if (Number.isNaN(threadUpdatedAtMs)) return;
456
- const lastVisitedAtMs = selectedThreadLastVisitedAt
457
- ? Date.parse(selectedThreadLastVisitedAt)
458
- : NaN;
459
- if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
460
- const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
461
- if (lastDispatchedVisitRef.current === dispatchKey) return;
462
- const dispatch = () => {
463
- lastDispatchedVisitRef.current = dispatchKey;
464
- lastVisitDispatchRef.current = { threadKey: selectedThreadKey, at: Date.now() };
465
- void visitThread({
466
- environmentId: props.environmentId,
467
- input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
468
- });
469
- };
470
- const completedAtMs = selectedThreadCompletedAt ? Date.parse(selectedThreadCompletedAt) : NaN;
471
- const hasUnseenCompletion =
472
- !Number.isNaN(completedAtMs) &&
473
- (Number.isNaN(lastVisitedAtMs) || completedAtMs > lastVisitedAtMs);
474
- const previous = lastVisitDispatchRef.current;
475
- const elapsed = Date.now() - previous.at;
476
- // Like a completion, a wake the user is looking at must not wait out the throttle:
477
- // leaving within it would cancel the dispatch and keep Woke in the list.
478
- if (
479
- previous.threadKey !== selectedThreadKey ||
480
- hasUnseenCompletion ||
481
- wakeIsLatestUpdate ||
482
- elapsed >= 10_000
483
- ) {
484
- dispatch();
485
- return;
384
+// A scheduled wake can happen without a newer server update, so the tracker
385
+// is told when one takes effect. The shell's updatedAt ticks while a run
386
+// streams; the tracker follows it outside React.
387
+const wakeAwareVisitShell = Atom.family((key: string) => {
388
+ const ref = parseThreadKey(key);
389
+ return Atom.make((get) => {
390
+ const shell = get(environmentThreadShells.threadShellAtom(ref));
391
+ if (shell === null) return null;
392
+ const nowMs = Date.now();
393
+ const wokeAt = threadWokeAt(shell, { now: new Date(nowMs).toISOString() });
394
+ const wakeAtMs = shell.snoozedUntil == null ? NaN : Date.parse(shell.snoozedUntil);
395
+ if (wokeAt === null && wakeAtMs > nowMs) {
396
+ const timer = setTimeout(
397
+ () => get.refreshSelf(),
398
+ Math.min(wakeAtMs - nowMs + 50, 2_147_483_647),
399
+ );
400
+ get.addFinalizer(() => clearTimeout(timer));
401
}
487
- const timer = setTimeout(dispatch, 10_000 - elapsed);
488
- return () => clearTimeout(timer);
489
- }, [
490
- props.environmentId,
491
- selectedThreadId,
492
- selectedThreadKey,
493
- selectedThreadLastVisitedAt,
494
- selectedThreadCompletedAt,
495
- selectedThreadUpdatedAt,
496
- showContent,
497
- visitThread,
498
- wakeIsLatestUpdate,
499
- ]);
500
- return null;
501
-}
402
+ return { ...shell, wokeAt };
403
+ }).pipe(Atom.withLabel(`mobile-thread-visit-shell:${key}`));
404
+});
405
+
406
+const threadVisitTracker = createThreadVisitTracker({
407
+ threadShellAtom: (ref) => wakeAwareVisitShell(threadKey(ref)),
408
+ visit: threadEnvironment.visit,
409
+});
410
411
// Past the composer's 180 ms height animation.
412
const COMPOSER_HEIGHT_SETTLE_MS = 220;
@@ -1171,6 +1079,14 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1079
userInputInsetProgress.set(1);
1080
}, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
1081
const showContent = props.showContent ?? true;
1082
+ // Showing the thread counts as viewing it, before its live shell arrives too.
1083
+ useAtomMount(
1084
+ threadVisitTracker(
1085
+ showContent && !props.draftMode
1086
+ ? { environmentId: props.environmentId, threadId: props.selectedThread.id }
1087
+ : null,
1088
+ ),
1089
+ );
1090
const layoutVariant = props.layoutVariant ?? "compact";
1091
const isSplitLayout = layoutVariant === "split";
1092
const contentMaxWidth =
@@ -1439,11 +1355,6 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1355
return (
1356
<View className="flex-1" onLayout={handleScreenLayout}>
1357
{!usesNativeWorkspaceColumns ? <NativeLayoutObserver onChange={setScreenMetrics} /> : null}
1442
- <ThreadVisitWatermark
1443
- environmentId={props.environmentId}
1444
- selectedThread={props.selectedThread}
1445
- showContent={showContent && !props.draftMode}
1446
- />
1358
{props.draftMode ? (
1359
props.draftMode.content(
1360
navigationHeaderHeight,
packages/client-runtime/package.json
+4
@@ -335,6 +335,10 @@
335
"types": "./src/state/threadSearch.ts",
336
"default": "./src/state/threadSearch.ts"
337
},
338
+ "./state/thread-visits": {
339
+ "types": "./src/state/threadVisits.ts",
340
+ "default": "./src/state/threadVisits.ts"
341
+ },
342
"./state/turn-item-presentation": {
343
"types": "./src/state/turnItemPresentation.ts",
344
"default": "./src/state/turnItemPresentation.ts"
packages/client-runtime/src/state/threadVisits.test.ts
new
+151
@@ -0,0 +1,151 @@
1
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
3
+import { expect, it, vi } from "vite-plus/test";
4
+
5
+import type { VisitThreadInput } from "./threadCommands.ts";
6
+import { claimThreadOpen } from "./threadSearch.ts";
7
+import { createThreadVisitTracker, VISIT_DISPATCH_THROTTLE_MS } from "./threadVisits.ts";
8
+
9
+const environmentId = EnvironmentId.make("env-visits");
10
+
11
+interface Shell {
12
+ readonly environmentId: EnvironmentId;
13
+ readonly id: ThreadId;
14
+ readonly updatedAt: string;
15
+ readonly lastVisitedAt?: string | null;
16
+ readonly latestRun: { readonly completedAt: string | null } | null;
17
+ readonly wokeAt?: string | null;
18
+}
19
+
20
+function at(seconds: number) {
21
+ return `2026-01-01T00:00:${String(seconds).padStart(2, "0")}.000Z`;
22
+}
23
+
24
+// claimThreadOpen dedupes per thread in module state, so each test opens its own thread.
25
+function setup(threadName: string, initial: Omit<Shell, "environmentId" | "id"> | null) {
26
+ vi.useFakeTimers({ now: Date.UTC(2026, 0, 1) });
27
+ const threadId = ThreadId.make(threadName);
28
+ const ref = { environmentId, threadId };
29
+ const shellAtom = Atom.make<Shell | null>(
30
+ initial === null ? null : { environmentId, id: threadId, ...initial },
31
+ );
32
+ const visits: Array<VisitThreadInput> = [];
33
+ const localVisits: Array<string> = [];
34
+ const tracker = createThreadVisitTracker({
35
+ threadShellAtom: () => shellAtom,
36
+ visit: {
37
+ label: "test-visit",
38
+ run: async (_registry, value) => {
39
+ visits.push(value.input);
40
+ return AsyncResult.success(undefined);
41
+ },
42
+ },
43
+ markLocalVisit: (_ref, visitedAt) => localVisits.push(visitedAt),
44
+ });
45
+ const registry = AtomRegistry.make();
46
+ return {
47
+ ref,
48
+ visits,
49
+ localVisits,
50
+ mount: () => registry.mount(tracker(ref)),
51
+ update: (patch: Partial<Shell>) => {
52
+ const current = registry.get(shellAtom);
53
+ registry.set(shellAtom, {
54
+ environmentId,
55
+ id: threadId,
56
+ updatedAt: at(0),
57
+ latestRun: null,
58
+ ...current,
59
+ ...patch,
60
+ });
61
+ },
62
+ [Symbol.dispose]: () => vi.useRealTimers(),
63
+ };
64
+}
65
+
66
+it("records the open once, then throttles streaming visits", () => {
67
+ using t = setup("thread-throttle", {
68
+ updatedAt: at(10),
69
+ lastVisitedAt: at(0),
70
+ latestRun: null,
71
+ });
72
+ t.mount();
73
+ expect(t.visits).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10), opened: true }]);
74
+
75
+ vi.advanceTimersByTime(1_000);
76
+ t.update({ updatedAt: at(11) });
77
+ t.update({ updatedAt: at(12) });
78
+ expect(t.visits).toHaveLength(1);
79
+
80
+ vi.advanceTimersByTime(VISIT_DISPATCH_THROTTLE_MS - 1_000);
81
+ expect(t.visits.slice(1)).toEqual([{ threadId: t.ref.threadId, visitedAt: at(12) }]);
82
+});
83
+
84
+it("sends an unseen completion without waiting for the throttle", () => {
85
+ using t = setup("thread-completion", {
86
+ updatedAt: at(10),
87
+ lastVisitedAt: at(0),
88
+ latestRun: null,
89
+ });
90
+ t.mount();
91
+ t.update({ updatedAt: at(20), latestRun: { completedAt: at(20) } });
92
+ expect(t.visits.slice(1)).toEqual([{ threadId: t.ref.threadId, visitedAt: at(20) }]);
93
+});
94
+
95
+it("does not resend the open a palette pick already sent", () => {
96
+ using t = setup("thread-palette", { updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
97
+ claimThreadOpen(environmentId, t.ref.threadId, Date.UTC(2026, 0, 1));
98
+ t.mount();
99
+ expect(t.visits).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10) }]);
100
+});
101
+
102
+it("keeps a mark-unread on the open thread until new activity lands", () => {
103
+ using t = setup("thread-unread", { updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
104
+ t.mount();
105
+ t.update({ lastVisitedAt: at(10) });
106
+ t.update({ lastVisitedAt: at(5) });
107
+ vi.advanceTimersByTime(VISIT_DISPATCH_THROTTLE_MS);
108
+ expect(t.visits).toHaveLength(1);
109
+
110
+ t.update({ updatedAt: at(30) });
111
+ expect(t.visits.slice(1)).toEqual([{ threadId: t.ref.threadId, visitedAt: at(30) }]);
112
+});
113
+
114
+it("waits for the shell and records local visits for servers without tracking", () => {
115
+ using t = setup("thread-local", null);
116
+ t.mount();
117
+ expect(t.visits).toEqual([]);
118
+ t.update({ updatedAt: at(10), latestRun: null });
119
+ t.update({ updatedAt: at(11) });
120
+ expect(t.visits).toEqual([]);
121
+ expect(t.localVisits).toEqual([at(10), at(11)]);
122
+});
123
+
124
+it("drops a pending visit when the thread is no longer viewed", () => {
125
+ using t = setup("thread-unmount", { updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
126
+ const unmount = t.mount();
127
+ t.update({ updatedAt: at(11) });
128
+ unmount();
129
+ vi.advanceTimersByTime(VISIT_DISPATCH_THROTTLE_MS);
130
+ expect(t.visits).toHaveLength(1);
131
+});
132
+
133
+it("records the open while the thread is shown before its shell arrives", () => {
134
+ using t = setup("thread-shell-missing", null);
135
+ t.mount();
136
+ expect(claimThreadOpen(environmentId, t.ref.threadId, Date.UTC(2026, 0, 1))).toBe(false);
137
+
138
+ t.update({ updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
139
+ expect(t.visits).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10) }]);
140
+});
141
+
142
+it("advances the watermark to a wake without waiting for the throttle", () => {
143
+ using t = setup("thread-wake", { updatedAt: at(10), lastVisitedAt: at(0), latestRun: null });
144
+ t.mount();
145
+ t.update({ wokeAt: at(15) });
146
+ expect(t.visits.slice(1)).toEqual([{ threadId: t.ref.threadId, visitedAt: at(15) }]);
147
+
148
+ vi.advanceTimersByTime(1_000);
149
+ t.update({ updatedAt: at(16) });
150
+ expect(t.visits).toHaveLength(2);
151
+});
packages/client-runtime/src/state/threadVisits.ts
new
+144
@@ -0,0 +1,144 @@
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 { 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 "./threadCommands.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 visit: AtomCommand<
37
+ { readonly environmentId: EnvironmentId; readonly input: VisitThreadInput },
38
+ unknown,
39
+ unknown
40
+ >;
41
+ /**
42
+ * Servers without visit tracking leave `lastVisitedAt` undefined; a client
43
+ * that keeps its own watermark for them records the visit here instead.
44
+ */
45
+ readonly markLocalVisit?: (ref: ScopedThreadRef, visitedAt: string) => void;
46
+}
47
+
48
+/**
49
+ * While mounted, a tracker counts as the user viewing the thread: mounting it
50
+ * records one open (which also feeds search ranking), and every shell update
51
+ * after that advances the visit watermark, throttled while a run streams.
52
+ */
53
+export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) {
54
+ const family = Atom.family((key: string) => {
55
+ const ref = parseThreadKey(key);
56
+ return Atom.make((get) => {
57
+ const registry = get.registry;
58
+ // Showing the thread is the open, whether or not its shell has arrived;
59
+ // the shell only decides whether the server hears about it now.
60
+ // Recorded even when the server cannot take opens, so recents follow
61
+ // it. A palette pick already sent the open with its query.
62
+ let openPending = claimThreadOpen(ref.environmentId, ref.threadId, Date.now());
63
+ // Dedupe per watermark: the shell updates again before the command's echo
64
+ // lands. It also keeps a mark-unread on the open thread sticky, since the
65
+ // rewind leaves updatedAt untouched.
66
+ let lastDispatchedUpdatedAt: string | null = null;
67
+ let lastDispatchAt = 0;
68
+ let timer: ReturnType<typeof setTimeout> | undefined;
69
+ const clearTimer = () => {
70
+ if (timer === undefined) return;
71
+ clearTimeout(timer);
72
+ timer = undefined;
73
+ };
74
+ get.addFinalizer(clearTimer);
75
+
76
+ const dispatch = (shell: VisitedShell, visitedAt: string, opened: boolean) => {
77
+ clearTimer();
78
+ lastDispatchedUpdatedAt = visitedAt;
79
+ lastDispatchAt = Date.now();
80
+ void runAtomCommand(
81
+ registry,
82
+ options.visit,
83
+ {
84
+ environmentId: shell.environmentId,
85
+ input: {
86
+ threadId: shell.id,
87
+ visitedAt,
88
+ ...(opened ? { opened: true } : {}),
89
+ },
90
+ },
91
+ { reportFailure: false },
92
+ );
93
+ };
94
+
95
+ const onShell = (shell: VisitedShell | null) => {
96
+ clearTimer();
97
+ // Only a shell present when the thread is shown carries the open; one
98
+ // that arrives later is an ordinary visit.
99
+ const opened = openPending;
100
+ openPending = false;
101
+ if (shell === null) return;
102
+
103
+ const shellUpdatedAtMs = Date.parse(shell.updatedAt);
104
+ if (Number.isNaN(shellUpdatedAtMs)) return;
105
+ const wokeAtMs = shell.wokeAt ? Date.parse(shell.wokeAt) : NaN;
106
+ const wakeIsLatest = wokeAtMs > shellUpdatedAtMs;
107
+ const visitedAt = wakeIsLatest && shell.wokeAt ? shell.wokeAt : shell.updatedAt;
108
+ const updatedAtMs = wakeIsLatest ? wokeAtMs : shellUpdatedAtMs;
109
+ if (shell.lastVisitedAt === undefined) {
110
+ options.markLocalVisit?.(ref, visitedAt);
111
+ return;
112
+ }
113
+ if (opened) {
114
+ dispatch(shell, visitedAt, true);
115
+ return;
116
+ }
117
+ const lastVisitedAtMs = shell.lastVisitedAt ? Date.parse(shell.lastVisitedAt) : NaN;
118
+ if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= updatedAtMs) return;
119
+ if (lastDispatchedUpdatedAt === visitedAt) return;
120
+
121
+ const completedAtMs = shell.latestRun?.completedAt
122
+ ? Date.parse(shell.latestRun.completedAt)
123
+ : NaN;
124
+ const hasUnseenCompletion =
125
+ !Number.isNaN(completedAtMs) &&
126
+ (Number.isNaN(lastVisitedAtMs) || completedAtMs > lastVisitedAtMs);
127
+ const elapsed = Date.now() - lastDispatchAt;
128
+ if (hasUnseenCompletion || wakeIsLatest || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {
129
+ dispatch(shell, visitedAt, false);
130
+ return;
131
+ }
132
+ timer = setTimeout(
133
+ () => dispatch(shell, visitedAt, false),
134
+ VISIT_DISPATCH_THROTTLE_MS - elapsed,
135
+ );
136
+ };
137
+
138
+ // `subscribe`, not `get`: a rebuild would reset the open and throttle
139
+ // state on every streaming tick.
140
+ get.subscribe(options.threadShellAtom(ref), onShell, { immediate: true });
141
+ }).pipe(Atom.withLabel(`thread-visit-tracker:${key}`));
142
+ });
143
+ return (ref: ScopedThreadRef | null) => (ref === null ? IDLE_TRACKER : family(threadKey(ref)));
144
+}