Skip to content

Commit a0f74ad

Browse files
committed
feat: sync thread read state across clients
Thread read and unread state lived in each web client's local storage, so opening a thread on one device did not clear its Done indicator anywhere else. The server now owns a lastVisitedAt watermark per thread. Clients send thread.visit with the shell's updatedAt when a focused, visible thread is read, and thread.mark-unread from the existing menus, then render the server value directly with no optimistic override, the same shape as server-side settlement. The decider keeps the maximum watermark and caps it at server time. Streaming activity bumps coalesce into one trailing visit per ten seconds. Servers without the threadVisitedTracking capability keep the previous device-local fallback. Migration 053 backfills existing threads as read. Names match the orchestrator V2 branch (lastVisitedAt, thread.visit, threadVisitedTracking) so V2 can import the column directly. Made with Claude Fable 5.1 through Claude Code.
1 parent 7cafe52 commit a0f74ad

43 files changed

Lines changed: 1185 additions & 51 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/mobile/src/features/threads/ThreadRouteScreen.tsx‎

Lines changed: 77 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ import {
2222
projectScriptRuntimeEnv,
2323
resolveProjectScripts,
2424
} from "@t3tools/shared/projectScripts";
25-
import { Alert, Platform, ScrollView, View } from "react-native";
25+
import { Alert, AppState, Platform, ScrollView, View } from "react-native";
2626
import { useSafeAreaInsets } from "react-native-safe-area-context";
2727
import { useWorkspaceState } from "../../state/workspace";
2828
import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
@@ -88,6 +88,7 @@ import {
8888
ThreadInspectorContentStack,
8989
type ThreadInspectorMode,
9090
} from "./thread-inspector-content-stack";
91+
import { resolveThreadVisit, VISIT_DISPATCH_THROTTLE_MS } from "./threadVisitedState";
9192

9293
interface ThreadInspectorSelection {
9394
readonly routeThreadIdentity: string | null;
@@ -303,6 +304,81 @@ function ThreadRouteContent(
303304
const routeConnectionState =
304305
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
305306
const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
307+
const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
308+
const supportsVisitedTracking =
309+
serverConfig?.environment.capabilities.threadVisitedTracking === true;
310+
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
311+
const [appState, setAppState] = useState(() => AppState.currentState);
312+
useEffect(() => {
313+
const subscription = AppState.addEventListener("change", setAppState);
314+
return () => subscription.remove();
315+
}, []);
316+
// Records the server-side visited watermark while this route is focused so
317+
// the Done indicator clears on every client. Files, Review, and Terminal
318+
// are native pushes that blur this route, so a completion that lands
319+
// behind them stays unread until the user comes back. The watermark is the
320+
// shell's updatedAt; the completion comes from the loaded detail so a slow
321+
// or failed message load cannot mark a completion read before the user
322+
// can see it. A cached detail (stream paused while the thread was not in
323+
// use) still shows its messages, so it counts as loaded. lastVisitedAt is
324+
// read through a ref and kept out of the deps: another client marking the
325+
// 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);
335+
useFocusEffect(
336+
useCallback(() => {
337+
if (
338+
selectedThreadEnvironmentId === null ||
339+
selectedThreadId === null ||
340+
selectedThreadUpdatedAt === null
341+
) {
342+
return;
343+
}
344+
const urgency = resolveThreadVisit({
345+
appState,
346+
connectionState: routeConnectionState,
347+
supported: supportsVisitedTracking,
348+
detailLoaded: selectedThreadDetailLoaded,
349+
updatedAt: selectedThreadUpdatedAt,
350+
completedAt: selectedThreadCompletedAt,
351+
lastVisitedAt: selectedThreadLastVisitedAtRef.current,
352+
});
353+
if (urgency === "skip") return;
354+
const dispatch = () => {
355+
lastVisitDispatchAtRef.current = Date.now();
356+
void visitThread({
357+
environmentId: selectedThreadEnvironmentId,
358+
input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
359+
});
360+
};
361+
// Mid-turn activity bumps arrive several times a second; coalesce them
362+
// 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+
);
306382
const selectedThreadWithDraftSettings = useMemo(
307383
() =>
308384
selectedThread
@@ -835,7 +911,6 @@ function ThreadRouteContent(
835911
detailDeleted: selectedThreadDetailState.status === "deleted",
836912
connectionState: routeConnectionState,
837913
});
838-
const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
839914
const renderThreadRouteBody = (showActionControls: boolean) => (
840915
<>
841916
<ThreadGitControls {...threadGitControlProps} showActionControls={showActionControls} />
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { resolveThreadVisit } from "./threadVisitedState";
4+
5+
const base = {
6+
appState: "active" as const,
7+
connectionState: "connected" as const,
8+
supported: true,
9+
detailLoaded: true,
10+
updatedAt: "2026-01-01T00:01:00.000Z",
11+
completedAt: "2026-01-01T00:01:00.000Z",
12+
lastVisitedAt: "2026-01-01T00:00:30.000Z",
13+
};
14+
15+
describe("resolveThreadVisit", () => {
16+
it("sends an unseen completion immediately", () => {
17+
expect(resolveThreadVisit(base)).toBe("now");
18+
expect(resolveThreadVisit({ ...base, lastVisitedAt: null })).toBe("now");
19+
});
20+
21+
it("throttles mid-turn activity that has no new completion", () => {
22+
expect(
23+
resolveThreadVisit({ ...base, completedAt: null, updatedAt: "2026-01-01T00:02:00.000Z" }),
24+
).toBe("throttled");
25+
expect(
26+
resolveThreadVisit({
27+
...base,
28+
completedAt: "2026-01-01T00:00:10.000Z",
29+
updatedAt: "2026-01-01T00:02:00.000Z",
30+
}),
31+
).toBe("throttled");
32+
});
33+
34+
it("skips when the watermark already covers the latest update", () => {
35+
expect(resolveThreadVisit({ ...base, lastVisitedAt: base.updatedAt })).toBe("skip");
36+
});
37+
38+
it("skips when backgrounded, disconnected, unsupported, or unloaded", () => {
39+
expect(resolveThreadVisit({ ...base, appState: "background" })).toBe("skip");
40+
expect(resolveThreadVisit({ ...base, connectionState: "reconnecting" })).toBe("skip");
41+
expect(resolveThreadVisit({ ...base, supported: false })).toBe("skip");
42+
expect(resolveThreadVisit({ ...base, detailLoaded: false })).toBe("skip");
43+
});
44+
45+
it("never visits on a malformed update timestamp", () => {
46+
expect(resolveThreadVisit({ ...base, updatedAt: "not-a-date" })).toBe("skip");
47+
});
48+
});
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
2+
import type { AppStateStatus } from "react-native";
3+
4+
/** Trailing coalesce window for visit watermarks while a turn streams. */
5+
export const VISIT_DISPATCH_THROTTLE_MS = 10_000;
6+
7+
/**
8+
* Decides whether the focused thread route should record a visit and how
9+
* urgently. Skipped when the app is not in front, the environment is not
10+
* connected, the server does not track visits, the thread's messages have
11+
* not loaded (the user cannot have read what they cannot see), or the
12+
* server watermark already covers the thread's latest update. An unseen
13+
* completion sends immediately; mid-turn activity bumps coalesce into a
14+
* trailing visit so streaming does not flood the server.
15+
*/
16+
export function resolveThreadVisit(input: {
17+
readonly appState: AppStateStatus;
18+
readonly connectionState: EnvironmentConnectionPhase;
19+
readonly supported: boolean;
20+
readonly detailLoaded: boolean;
21+
readonly updatedAt: string;
22+
readonly completedAt: string | null | undefined;
23+
readonly lastVisitedAt: string | null | undefined;
24+
}): "now" | "throttled" | "skip" {
25+
if (input.appState !== "active" || input.connectionState !== "connected" || !input.supported) {
26+
return "skip";
27+
}
28+
if (!input.detailLoaded) return "skip";
29+
const updatedAtMs = Date.parse(input.updatedAt);
30+
if (!Number.isFinite(updatedAtMs)) return "skip";
31+
const lastVisitedAtMs = input.lastVisitedAt ? Date.parse(input.lastVisitedAt) : NaN;
32+
if (Number.isFinite(lastVisitedAtMs) && lastVisitedAtMs >= updatedAtMs) return "skip";
33+
const completedAtMs = input.completedAt ? Date.parse(input.completedAt) : NaN;
34+
const hasUnseenCompletion =
35+
Number.isFinite(completedAtMs) &&
36+
(!Number.isFinite(lastVisitedAtMs) || completedAtMs > lastVisitedAtMs);
37+
return hasUnseenCompletion ? "now" : "throttled";
38+
}

‎apps/mobile/src/state/use-thread-selection.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ function threadDetailToShell(
7676
activeOrderKey: thread.activeOrderKey,
7777
pinnedAt: thread.pinnedAt,
7878
pinOrderKey: thread.pinOrderKey,
79+
lastVisitedAt: thread.lastVisitedAt,
7980
snoozedUntil: thread.snoozedUntil ?? null,
8081
snoozedAt: thread.snoozedAt ?? null,
8182
session: thread.session,

‎apps/server/src/environment/ServerEnvironment.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
170170
expect(second.capabilities.pullRequests).toBe(true);
171171
expect(second.capabilities.usagePriceOverrides).toBe(true);
172172
expect(second.capabilities.threadActiveReorder).toBe(true);
173+
expect(second.capabilities.threadVisitedTracking).toBe(true);
173174
expect(second.capabilities.threadTitleRegeneration).toBe(true);
174175
expect(second.capabilities.threadPullRequests).toBe(true);
175176
expect(second.capabilities.threadPullRequestLinking).toBe(true);

‎apps/server/src/environment/ServerEnvironment.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,7 @@ export const make = Effect.gen(function* () {
231231
threadPinning: true,
232232
threadPinReorder: true,
233233
threadActiveReorder: true,
234+
threadVisitedTracking: true,
234235
threadTitleRegeneration: true,
235236
threadPullRequests: true,
236237
pullRequestStackActions: true,

‎apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,70 @@ describe("OrchestrationEngine", () => {
331331
}
332332
},
333333
);
334+
it("persists thread visits through backward-compatible metadata events", async () => {
335+
const system = await createOrchestrationSystem();
336+
const { engine } = system;
337+
const createdAt = "2026-01-01T00:00:00.000Z";
338+
const lastVisitedAt = "2026-01-01T00:05:00.000Z";
339+
340+
await system.run(
341+
engine.dispatch({
342+
type: "project.create",
343+
commandId: CommandId.make("cmd-visited-state-project-create"),
344+
projectId: asProjectId("project-visited-state"),
345+
title: "Visited project",
346+
workspaceRoot: "/tmp/project-visited-state",
347+
defaultModelSelection: {
348+
instanceId: ProviderInstanceId.make("codex"),
349+
model: "gpt-5-codex",
350+
},
351+
createdAt,
352+
}),
353+
);
354+
await system.run(
355+
engine.dispatch({
356+
type: "thread.create",
357+
commandId: CommandId.make("cmd-visited-state-thread-create"),
358+
threadId: ThreadId.make("thread-visited-state"),
359+
projectId: asProjectId("project-visited-state"),
360+
title: "Visited thread",
361+
modelSelection: {
362+
instanceId: ProviderInstanceId.make("codex"),
363+
model: "gpt-5-codex",
364+
},
365+
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
366+
runtimeMode: "full-access",
367+
branch: null,
368+
worktreePath: null,
369+
createdAt,
370+
}),
371+
);
372+
373+
expect((await system.readModel()).threads[0]?.lastVisitedAt).toBe(createdAt);
374+
375+
const receipt = await system.run(
376+
engine.dispatch({
377+
type: "thread.visit",
378+
commandId: CommandId.make("cmd-visited-state-view"),
379+
threadId: ThreadId.make("thread-visited-state"),
380+
visitedAt: lastVisitedAt,
381+
}),
382+
);
383+
const snapshot = await system.readModel();
384+
const events = await system.run(
385+
Stream.runCollect(engine.readEvents(receipt.sequence - 1, 1)).pipe(
386+
Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
387+
),
388+
);
389+
390+
expect(snapshot.threads[0]).toMatchObject({ lastVisitedAt, updatedAt: createdAt });
391+
expect(events[0]).toMatchObject({
392+
type: "thread.meta-updated",
393+
payload: { lastVisitedAt, updatedAt: createdAt },
394+
});
395+
396+
await system.dispose();
397+
});
334398

335399
it("bootstraps command handling from persisted projections without reading the full snapshot", async () => {
336400
let nextSequence = 8;

‎apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,66 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
616616
activeOrderKey: null,
617617
},
618618
]);
619+
620+
yield* eventStore.append({
621+
type: "thread.meta-updated",
622+
eventId: EventId.make("evt-viewed-1"),
623+
aggregateKind: "thread",
624+
aggregateId: ThreadId.make("thread-1"),
625+
occurredAt: "2026-01-01T00:00:03.000Z",
626+
commandId: CommandId.make("cmd-viewed-1"),
627+
causationEventId: null,
628+
correlationId: CommandId.make("cmd-viewed-1"),
629+
metadata: {},
630+
payload: {
631+
threadId: ThreadId.make("thread-1"),
632+
lastVisitedAt: "2026-01-01T00:00:03.000Z",
633+
updatedAt: "2026-01-01T00:00:02.000Z",
634+
},
635+
});
636+
yield* projectionPipeline.bootstrap;
637+
638+
const viewedRows = yield* sql<{
639+
readonly lastVisitedAt: string;
640+
readonly updatedAt: string;
641+
}>`
642+
SELECT
643+
last_visited_at AS "lastVisitedAt",
644+
updated_at AS "updatedAt"
645+
FROM projection_threads
646+
WHERE thread_id = 'thread-1'
647+
`;
648+
assert.deepEqual(viewedRows, [
649+
{
650+
lastVisitedAt: "2026-01-01T00:00:03.000Z",
651+
updatedAt: "2026-01-01T00:00:02.000Z",
652+
},
653+
]);
654+
655+
yield* eventStore.append({
656+
type: "thread.meta-updated",
657+
eventId: EventId.make("evt-marked-unread-1"),
658+
aggregateKind: "thread",
659+
aggregateId: ThreadId.make("thread-1"),
660+
occurredAt: "2026-01-01T00:00:04.000Z",
661+
commandId: CommandId.make("cmd-marked-unread-1"),
662+
causationEventId: null,
663+
correlationId: CommandId.make("cmd-marked-unread-1"),
664+
metadata: {},
665+
payload: {
666+
threadId: ThreadId.make("thread-1"),
667+
lastVisitedAt: "2025-12-31T23:59:59.999Z",
668+
updatedAt: "2026-01-01T00:00:02.000Z",
669+
},
670+
});
671+
yield* projectionPipeline.bootstrap;
672+
673+
const markedUnreadRows = yield* sql<{ readonly lastVisitedAt: string }>`
674+
SELECT last_visited_at AS "lastVisitedAt"
675+
FROM projection_threads
676+
WHERE thread_id = 'thread-1'
677+
`;
678+
assert.deepEqual(markedUnreadRows, [{ lastVisitedAt: "2025-12-31T23:59:59.999Z" }]);
619679
}),
620680
);
621681
});

‎apps/server/src/orchestration/Layers/ProjectionPipeline.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
628628
settledOverride: null,
629629
settledAt: null,
630630
unsettledAt: null,
631+
lastVisitedAt: event.payload.createdAt,
631632
snoozedUntil: null,
632633
snoozedAt: null,
633634
pinnedAt: null,
@@ -832,6 +833,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
832833
...(event.payload.branchPullRequest !== undefined
833834
? { branchPullRequest: event.payload.branchPullRequest }
834835
: {}),
836+
...(event.payload.lastVisitedAt !== undefined
837+
? { lastVisitedAt: event.payload.lastVisitedAt }
838+
: {}),
835839
updatedAt: event.payload.updatedAt,
836840
});
837841
// Legacy single-link events replay into the link table. The old

‎apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
480480
settledOverride: null,
481481
settledAt: null,
482482
unsettledAt: null,
483+
lastVisitedAt: "2026-02-24T00:00:02.000Z",
483484
snoozedUntil: null,
484485
snoozedAt: null,
485486
pinnedAt: "2026-02-24T00:00:01.000Z",
@@ -606,6 +607,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
606607
settledOverride: null,
607608
settledAt: null,
608609
unsettledAt: null,
610+
lastVisitedAt: "2026-02-24T00:00:02.000Z",
609611
snoozedUntil: null,
610612
snoozedAt: null,
611613
pinnedAt: "2026-02-24T00:00:01.000Z",

0 commit comments

Comments
 (0)