feat: sync thread read state across clients #9124
Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 3 commits into
main fromt3code/server-owned-thread-read-stateopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/web/src/hooks/useThreadViewState.ts line 27OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +7,21 @@7+import { useAtomCommand } from "../state/use-atom-command";8+import { useUiStateStore } from "../uiStateStore";9+10+/**11+ * Marks a thread viewed or unread. On servers that persist view state the12+ * change is a command and every client renders the server's `viewedAt`; on13+ * older servers it falls back to this device's local visit store. Like14+ * settlement, there is no optimistic override: the UI flips when the shell15+ * update arrives.16+ */17+export function useThreadViewState() {18+ const viewThread = useAtomCommand(threadEnvironment.view, { reportFailure: false });19+ const markUnreadOnServer = useAtomCommand(threadEnvironment.markUnread, "mark thread unread");20+ const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);21+ const markThreadUnread = useUiStateStore((store) => store.markThreadUnread);22+23+ // viewedThrough is the completion the user looked at, never wall clock, so24+ // a completion that lands while the thread is open still shows as unread.25+ const markViewed = useCallback(26+ (threadRef: ScopedThreadRef, viewedThrough: string) => {27+ if (!readEnvironmentSupportsViewState(threadRef.environmentId)) {packages/contracts/src/orchestration.ts line 801OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -789,3 +792,10 @@789792 reason: Schema.Literal("user"),790793 });791794795+const ThreadViewCommand = Schema.Struct({796+ type: Schema.Literal("thread.view"),797+ commandId: CommandId,798+ threadId: ThreadId,799+ // The completion the user looked at. The server caps it at its own clock800+ // and never moves an existing boundary backward.801+ viewedThrough: IsoDateTime,
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/web/src/components/ChatView.tsx lines 2087 to 2117Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -1830,7 +1837,15 @@1837+ const serverThreadEnvironmentId = serverThread?.environmentId;1838+ const serverThreadId = serverThread?.id;1839+ const serverThreadCompletedAt = serverThread?.latestTurn?.completedAt;1840+ const serverThreadConfigLoaded =1841+ serverThreadEnvironmentId !== undefined && serverConfigs.has(serverThreadEnvironmentId);18301842 useEffect(() => {1831- const completedAt = serverThread?.latestTurn?.completedAt;1832- if (!serverThread?.id || !completedAt) return;1833- markThreadVisited(1834- scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),1835- completedAt,1836- );1843+ if (1844+ !serverThreadEnvironmentId ||1845+ !serverThreadId ||1846+ !serverThreadCompletedAt ||1847+ !serverThreadConfigLoaded1848+ ) {1849+ return;1850+ }1851+ const threadRef = scopeThreadRef(serverThreadEnvironmentId, serverThreadId);
- apps/web/src/components/ChatView.tsx line 1850OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -1829 +1831,20 @@1829- // timestamp backwards).1831+ // lands later still gets its signal (the boundary never moves backwards).1832+ // Only a focused, visible document counts as reading; a completion that1833+ // lands in a background tab stays unread until the user comes back. The1834+ // listeners stay attached for the life of the effect so a later refocus1835+ // re-acks (the hook skips the send when the server already covers it).1836+ // The environment config decides whether the ack is a server command or a1837+ // local write, and the command needs a live connection, so wait for both:1838+ // an ack sent early would be misfiled locally or fail silently. Both are1839+ // deps, so the effect re-runs once config lands or the socket reconnects.1840+ const serverThreadEnvironmentId = serverThread?.environmentId;1841+ const serverThreadId = serverThread?.id;1842+ const serverThreadCompletedAt = serverThread?.latestTurn?.completedAt;1843+ const serverThreadConfigLoaded =1844+ serverThreadEnvironmentId !== undefined && serverConfigs.has(serverThreadEnvironmentId);1845+ const serverThreadEnvironment =1846+ serverThreadEnvironmentId === undefined1847+ ? null1848+ : (environmentById.get(serverThreadEnvironmentId) ?? null);1849+ const serverThreadConnected =1850+ serverThreadEnvironment === null || serverThreadEnvironment.connection.phase === "connected";
- apps/web/src/components/ChatView.tsx lines 1849 to 1850OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1829 +1831,20 @@1829- // timestamp backwards).1831+ // lands later still gets its signal (the boundary never moves backwards).1832+ // Only a focused, visible document counts as reading; a completion that1833+ // lands in a background tab stays unread until the user comes back. The1834+ // listeners stay attached for the life of the effect so a later refocus1835+ // re-acks (the hook skips the send when the server already covers it).1836+ // The environment config decides whether the ack is a server command or a1837+ // local write, and the command needs a live connection, so wait for both:1838+ // an ack sent early would be misfiled locally or fail silently. Both are1839+ // deps, so the effect re-runs once config lands or the socket reconnects.1840+ const serverThreadEnvironmentId = serverThread?.environmentId;1841+ const serverThreadId = serverThread?.id;1842+ const serverThreadCompletedAt = serverThread?.latestTurn?.completedAt;1843+ const serverThreadConfigLoaded =1844+ serverThreadEnvironmentId !== undefined && serverConfigs.has(serverThreadEnvironmentId);1845+ const serverThreadEnvironment =1846+ serverThreadEnvironmentId === undefined1847+ ? null1848+ : (environmentById.get(serverThreadEnvironmentId) ?? null);1849+ const serverThreadConnected =1850+ serverThreadEnvironment === null || serverThreadEnvironment.connection.phase === "connected";
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 334OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -305,0 +314,21 @@314+ return () => subscription.remove();315+ }, []);316+ // Records the server-side visited watermark while this route is focused so317+ // the Done indicator clears on every client. Files, Review, and Terminal318+ // are native pushes that blur this route, so a completion that lands319+ // behind them stays unread until the user comes back. The watermark is the320+ // shell's updatedAt; the completion comes from the loaded detail so a slow321+ // or failed message load cannot mark a completion read before the user322+ // can see it. A cached detail (stream paused while the thread was not in323+ // use) still shows its messages, so it counts as loaded. lastVisitedAt is324+ // read through a ref and kept out of the deps: another client marking the325+ // thread unread must not trigger an immediate re-visit.326+ const selectedThreadEnvironmentId = selectedThread?.environmentId ?? null;327+ const selectedThreadId = selectedThread?.id ?? null;328+ const selectedThreadUpdatedAt = selectedThread?.updatedAt ?? null;329+ const selectedThreadDetailLoaded =330+ selectedThreadDetailState.status === "live" || selectedThreadDetailState.status === "cached";331+ const selectedThreadCompletedAt = selectedThreadDetail?.latestTurn?.completedAt ?? null;332+ const selectedThreadLastVisitedAtRef = useRef(selectedThread?.lastVisitedAt);333+ selectedThreadLastVisitedAtRef.current = selectedThread?.lastVisitedAt;334+ const lastVisitDispatchAtRef = useRef(0);apps/mobile/src/features/threads/ThreadRouteScreen.tsx lines 352 to 381OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -305,0 +361,21 @@361+ // Mid-turn activity bumps arrive several times a second; coalesce them362+ // into a trailing visit so the newest watermark wins without a flood.363+ const elapsed = Date.now() - lastVisitDispatchAtRef.current;364+ if (urgency === "now" || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {365+ dispatch();366+ return;367+ }368+ const timer = setTimeout(dispatch, VISIT_DISPATCH_THROTTLE_MS - elapsed);369+ return () => clearTimeout(timer);370+ }, [371+ appState,372+ routeConnectionState,373+ selectedThreadCompletedAt,374+ selectedThreadDetailLoaded,375+ selectedThreadEnvironmentId,376+ selectedThreadId,377+ selectedThreadUpdatedAt,378+ supportsVisitedTracking,379+ visitThread,380+ ]),381+ );apps/web/src/components/ChatView.tsx lines 2105 to 2138OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -2079,0 +2118,21 @@2118+ const dispatch = () => {2119+ timer = undefined;2120+ lastVisitDispatchAtRef.current = Date.now();2121+ markVisited(threadRef, serverThreadUpdatedAt);2122+ };2123+ const visit = () => {2124+ if (document.visibilityState !== "visible" || !document.hasFocus()) return;2125+ if (timer !== undefined) return;2126+ const lastVisitedAtMs = serverThreadLastVisitedAt2127+ ? Date.parse(serverThreadLastVisitedAt)2128+ : NaN;2129+ const completedAtMs = serverThreadCompletedAt ? Date.parse(serverThreadCompletedAt) : NaN;2130+ const hasUnseenCompletion =2131+ Number.isFinite(completedAtMs) &&2132+ (!Number.isFinite(lastVisitedAtMs) || completedAtMs > lastVisitedAtMs);2133+ const elapsed = Date.now() - lastVisitDispatchAtRef.current;2134+ if (hasUnseenCompletion || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {2135+ dispatch();2136+ return;2137+ }2138+ timer = window.setTimeout(dispatch, VISIT_DISPATCH_THROTTLE_MS - elapsed);apps/web/src/components/ChatView.tsx lines 2118 to 2122OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -2075,5 +2107,16 @@2075- if (!serverThread?.id || !completedAt) return;2076- markThreadVisited(2077- scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),2078- completedAt,2079- );2107+ if (2108+ !serverThreadEnvironmentId ||2109+ !serverThreadId ||2110+ !serverThreadUpdatedAt ||2111+ !serverThreadConfigLoaded ||2112+ !serverThreadConnected2113+ ) {2114+ return;2115+ }2116+ const threadRef = scopeThreadRef(serverThreadEnvironmentId, serverThreadId);2117+ let timer: number | undefined;2118+ const dispatch = () => {2119+ timer = undefined;2120+ lastVisitDispatchAtRef.current = Date.now();2121+ markVisited(threadRef, serverThreadUpdatedAt);2122+ };
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.


macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed