@devries-cameron20 / t3code-1 / commits / 0a20d7ea73
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): switching threads no longer delays the next thread's visit by up to 10s (#25368)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 26, 2026 at 01:48 UTC 0a20d7ea73dc1f80b5fec1ccefd77f19f3931832
2 files changed +96 -109
apps/web/src/components/chat/ThreadVisitWatermark.browser.test.tsx new
+82
@@ -0,0 +1,82 @@
1 +import { claimThreadOpen } from "@t3tools/client-runtime/state/thread-search";
2 +import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
3 +import { AsyncResult, Atom } from "effect/reactivity";
4 +import { expect, it, vi } from "vite-plus/test";
5 +
6 +import { fakeTimers, render } from "../../../test/render";
7 +import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
8 +
9 +const mocks = vi.hoisted(() => ({
10 + visitRun: vi.fn(),
11 +}));
12 +
13 +const shellKey = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`;
14 +
15 +vi.mock(import("../../state/threads"), async (original) => {
16 + const actual = await original();
17 + return {
18 + ...actual,
19 + environmentThreadShells: {
20 + ...actual.environmentThreadShells,
21 + threadShellAtom: ((ref: ScopedThreadRef) => shellAtom(shellKey(ref))) as never,
22 + },
23 + threadEnvironment: {
24 + ...actual.threadEnvironment,
25 + visit: { label: "visit", run: mocks.visitRun } as never,
26 + },
27 + };
28 +});
29 +
30 +import { ThreadVisitWatermark } from "./ThreadVisitWatermark";
31 +
32 +// Kept alive so a shell set before its tracker mounts is still there when it does.
33 +const shellAtom = Atom.family((_key: string) => Atom.make<unknown>(null).pipe(Atom.keepAlive));
34 +
35 +const NOW = Date.parse("2026-01-04T00:00:00.000Z");
36 +const ENVIRONMENT = EnvironmentId.make("environment-visit-watermark");
37 +const threadA: ScopedThreadRef = { environmentId: ENVIRONMENT, threadId: ThreadId.make("a") };
38 +const threadB: ScopedThreadRef = { environmentId: ENVIRONMENT, threadId: ThreadId.make("b") };
39 +
40 +function setShell(ref: ScopedThreadRef, updatedAt: string) {
41 + appAtomRegistry.set(shellAtom(shellKey(ref)), {
42 + environmentId: ref.environmentId,
43 + id: ref.threadId,
44 + updatedAt,
45 + lastVisitedAt: "2026-01-01T00:00:00.000Z",
46 + latestRun: null,
47 + });
48 +}
49 +
50 +function visitedThreadIds() {
51 + return mocks.visitRun.mock.calls.map(
52 + ([, input]) => (input as { input: { threadId: string } }).input.threadId,
53 + );
54 +}
55 +
56 +it("records the visit of the next thread at once after switching threads", async () => {
57 + mocks.visitRun.mockReset();
58 + mocks.visitRun.mockResolvedValue(AsyncResult.success(undefined));
59 + setShell(threadA, "2026-01-02T00:00:00.000Z");
60 + setShell(threadB, "2026-01-03T00:00:00.000Z");
61 + using _timers = fakeTimers();
62 + vi.setSystemTime(NOW);
63 + // A palette pick already sent B's open with its query, so B's visit is a plain watermark advance.
64 + claimThreadOpen(threadB.environmentId, threadB.threadId, NOW);
65 +
66 + await using screen = await render(
67 + <AppAtomRegistryProvider>
68 + <ThreadVisitWatermark threadRef={threadA} />
69 + </AppAtomRegistryProvider>,
70 + );
71 + expect(visitedThreadIds()).toEqual(["a"]);
72 +
73 + await screen.rerender(
74 + <AppAtomRegistryProvider>
75 + <ThreadVisitWatermark threadRef={threadB} />
76 + </AppAtomRegistryProvider>,
77 + );
78 +
79 + // Thread A's throttle must not hold back B's first watermark: leaving B
80 + // within the throttle window would otherwise keep it unread.
81 + expect(visitedThreadIds()).toEqual(["a", "b"]);
82 +});
apps/web/src/components/chat/ThreadVisitWatermark.tsx
+14 -109
@@ -1,117 +1,22 @@
1 +import { useAtomMount } from "@effect/atom-react";
2 +import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3 +import { createThreadVisitTracker } from "@t3tools/client-runtime/state/thread-visits";
4 import { type ScopedThreadRef } from "@t3tools/contracts";
2 -import { resolveThreadLastVisitedAt } from "../Sidebar.logic";
3 -import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
4 -import { claimThreadOpen } from "@t3tools/client-runtime/state/thread-search";
5 -import { useEffect, useRef } from "react";
5 +
6 import { useUiStateStore } from "../../uiStateStore";
7 -import { threadEnvironment } from "../../state/threads";
8 -import { useThreadShell } from "../../state/entities";
9 -import { useAtomCommand } from "../../state/use-atom-command";
7 +import { environmentThreadShells, threadEnvironment } from "../../state/threads";
8
11 -// During an active turn the thread's updatedAt advances several times per
12 -// second, and every server-side visit is a full command dispatch plus a
13 -// broadcast to all shell subscribers.
14 -const VISIT_DISPATCH_THROTTLE_MS = 10_000;
9 +const threadVisitTracker = createThreadVisitTracker({
10 + threadShellAtom: environmentThreadShells.threadShellAtom,
11 + visit: threadEnvironment.visit,
12 + markLocalVisit: (ref, visitedAt) =>
13 + useUiStateStore.getState().markThreadVisited(scopedThreadKey(ref), visitedAt),
14 +});
15
16 // The visit watermark is the one part of the chat view that follows the
17 -// shell's updatedAt, which ticks while a run streams. Keeping it in a leaf lets
18 -// ChatView read the quiet shell.
17 +// shell's updatedAt, which ticks while a run streams. The tracker subscribes to
18 +// it outside React, so ChatView keeps reading the quiet shell.
19 export function ThreadVisitWatermark(props: { readonly threadRef: ScopedThreadRef }) {
20 - const serverThread = useThreadShell(props.threadRef);
21 - const threadKey = scopedThreadKey(props.threadRef);
22 - const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
23 - const activeThreadLocalLastVisitedAt = useUiStateStore(
24 - (store) => store.threadLastVisitedAtById[threadKey],
25 - );
26 - const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
27 - const lastDispatchedVisitRef = useRef<string | null>(null);
28 - const lastVisitDispatchAtRef = useRef(0);
29 - const recordedOpenRef = useRef<string | null>(null);
30 -
31 - // Opening a thread is one visit that also counts toward search ranking. A
32 - // palette pick already sent it with the query. It runs before the watermark
33 - // effect, which then sees this watermark as sent.
34 - useEffect(() => {
35 - if (!serverThread?.id) return;
36 - if (recordedOpenRef.current === threadKey) return;
37 - recordedOpenRef.current = threadKey;
38 - // Recorded here even when the server cannot take opens, so recents follow it.
39 - const claimed = claimThreadOpen(serverThread.environmentId, serverThread.id, Date.now());
40 - if (!claimed || serverThread.lastVisitedAt === undefined) return;
41 - lastDispatchedVisitRef.current = `${threadKey}:${serverThread.updatedAt}`;
42 - lastVisitDispatchAtRef.current = Date.now();
43 - void visitThreadMutation({
44 - environmentId: serverThread.environmentId,
45 - input: {
46 - threadId: serverThread.id,
47 - visitedAt: serverThread.updatedAt,
48 - opened: true,
49 - },
50 - });
51 - }, [
52 - threadKey,
53 - serverThread?.environmentId,
54 - serverThread?.id,
55 - serverThread?.lastVisitedAt,
56 - serverThread?.updatedAt,
57 - visitThreadMutation,
58 - ]);
59 -
60 - useEffect(() => {
61 - if (!serverThread?.id) return;
62 - const threadUpdatedAt = Date.parse(serverThread.updatedAt);
63 - if (Number.isNaN(threadUpdatedAt)) return;
64 - const effectiveLastVisitedAt = resolveThreadLastVisitedAt(
65 - serverThread.lastVisitedAt,
66 - activeThreadLocalLastVisitedAt,
67 - );
68 - const lastVisitedAt = effectiveLastVisitedAt ? Date.parse(effectiveLastVisitedAt) : NaN;
69 - if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= threadUpdatedAt) return;
70 -
71 - if (serverThread.lastVisitedAt !== undefined) {
72 - // Dedupe per watermark — the effect re-runs before the command's echo
73 - // lands. The dedupe also keeps a mark-unread on the open thread sticky:
74 - // the rewind leaves updatedAt untouched, so the already-dispatched key
75 - // skips a fresh visit until new activity lands or the thread is reopened.
76 - const dispatchKey = `${threadKey}:${serverThread.updatedAt}`;
77 - if (lastDispatchedVisitRef.current === dispatchKey) return;
78 - const dispatch = () => {
79 - lastDispatchedVisitRef.current = dispatchKey;
80 - lastVisitDispatchAtRef.current = Date.now();
81 - void visitThreadMutation({
82 - environmentId: serverThread.environmentId,
83 - input: { threadId: serverThread.id, visitedAt: serverThread.updatedAt },
84 - });
85 - };
86 - const latestRunCompletedAtMs = serverThread.latestRun?.completedAt
87 - ? Date.parse(serverThread.latestRun.completedAt)
88 - : NaN;
89 - const hasUnseenCompletion =
90 - !Number.isNaN(latestRunCompletedAtMs) &&
91 - (Number.isNaN(lastVisitedAt) || latestRunCompletedAtMs > lastVisitedAt);
92 - const elapsed = Date.now() - lastVisitDispatchAtRef.current;
93 - if (hasUnseenCompletion || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {
94 - dispatch();
95 - return;
96 - }
97 - const timer = setTimeout(dispatch, VISIT_DISPATCH_THROTTLE_MS - elapsed);
98 - return () => clearTimeout(timer);
99 - }
100 -
101 - markThreadVisited(
102 - scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),
103 - serverThread.updatedAt,
104 - );
105 - }, [
106 - activeThreadLocalLastVisitedAt,
107 - markThreadVisited,
108 - threadKey,
109 - serverThread?.environmentId,
110 - serverThread?.id,
111 - serverThread?.lastVisitedAt,
112 - serverThread?.latestRun?.completedAt,
113 - serverThread?.updatedAt,
114 - visitThreadMutation,
115 - ]);
20 + useAtomMount(threadVisitTracker(props.threadRef));
21 return null;
22 }