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 21, 16:00 UTC
fix(client): retry unread thread visits after reconnect (#36559)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Wout Stiens committed
Nov 14, 2026 at 09:13 UTC
efae4e9da1d09c4cb07c7bc9c1128d4bf9231d74
4 files changed
+191
-6
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+2
@@ -138,6 +138,7 @@ import {
138
type LayoutVariant,
139
} from "../../lib/layout";
140
import { editPendingThreadMessage } from "../../state/edit-pending-thread-message";
141
+import { environmentCatalog } from "../../connection/catalog";
142
import { deviceEnvironment } from "../../state/device";
143
import { useEnvironmentQuery } from "../../state/query";
144
import { threadDevicePreviews } from "../devices/threadDevicePreviews";
@@ -372,6 +373,7 @@ const wakeAwareVisitShell = Atom.family((key: string) => {
373
374
const threadVisitTracker = createThreadVisitTracker({
375
threadShellAtom: (ref) => wakeAwareVisitShell(threadKey(ref)),
376
+ sessionGenerationAtom: environmentCatalog.sessionGenerationAtom,
377
visit: threadEnvironment.visit,
378
});
379
apps/web/src/components/chat/ThreadVisitWatermark.tsx
+2
@@ -3,11 +3,13 @@ import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3
import { createThreadVisitTracker } from "@t3tools/client-runtime/state/thread-visits";
4
import { type ScopedThreadRef } from "@t3tools/contracts";
5
6
+import { environmentCatalog } from "../../connection/catalog";
7
import { useUiStateStore } from "../../uiStateStore";
8
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
9
10
const threadVisitTracker = createThreadVisitTracker({
11
threadShellAtom: environmentThreadShells.threadShellAtom,
12
+ sessionGenerationAtom: environmentCatalog.sessionGenerationAtom,
13
visit: threadEnvironment.visit,
14
markLocalVisit: (ref, visitedAt) =>
15
useUiStateStore.getState().markThreadVisited(scopedThreadKey(ref), visitedAt),
packages/client-runtime/src/state/threadVisits.test.ts
+122
-1
@@ -1,8 +1,10 @@
1
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2
+import * as Cause from "effect/Cause";
3
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
4
import { expect, it, vi } from "vite-plus/test";
5
6
import type { VisitThreadInput } from "../operations/commands.ts";
7
+import type { AtomCommandResult } from "./runtime.ts";
8
import { claimThreadOpen } from "./threadSearch.ts";
9
import { createThreadVisitTracker, VISIT_DISPATCH_THROTTLE_MS } from "./threadVisits.ts";
10
@@ -29,14 +31,25 @@ function setup(threadName: string, initial: Omit<Shell, "environmentId" | "id">
31
const shellAtom = Atom.make<Shell | null>(
32
initial === null ? null : { environmentId, id: threadId, ...initial },
33
);
34
+ // Visits the server accepted; offline ones fail without reaching it.
35
const visits: Array<VisitThreadInput> = [];
36
const localVisits: Array<string> = [];
37
+ let online = true;
38
+ let pendingResult: Promise<AtomCommandResult<void, string>> | undefined;
39
+ const attempts: Array<VisitThreadInput> = [];
40
+ const sessionGenerationAtom = Atom.make(1);
41
const tracker = createThreadVisitTracker({
42
threadShellAtom: () => shellAtom,
43
+ sessionGenerationAtom: () => sessionGenerationAtom,
44
visit: {
45
label: "test-visit",
46
run: async (_registry, value) => {
39
- visits.push(value.input);
47
+ attempts.push(value.input);
48
+ const pending = pendingResult;
49
+ pendingResult = undefined;
50
+ if (online) visits.push(value.input);
51
+ if (pending) return pending;
52
+ if (!online) return AsyncResult.failure(Cause.fail("disconnected"));
53
return AsyncResult.success(undefined);
54
},
55
},
@@ -47,7 +60,17 @@ function setup(threadName: string, initial: Omit<Shell, "environmentId" | "id">
60
ref,
61
visits,
62
localVisits,
63
+ attempts,
64
+ deferNextVisit: () => {
65
+ const deferred = Promise.withResolvers<AtomCommandResult<void, string>>();
66
+ pendingResult = deferred.promise;
67
+ return () => deferred.resolve(AsyncResult.failure(Cause.fail("disconnected")));
68
+ },
69
+ reconnect: () => registry.set(sessionGenerationAtom, registry.get(sessionGenerationAtom) + 1),
70
mount: () => registry.mount(tracker(ref)),
71
+ setOnline: (value: boolean) => {
72
+ online = value;
73
+ },
74
update: (patch: Partial<Shell>) => {
75
const current = registry.get(shellAtom);
76
registry.set(shellAtom, {
@@ -191,3 +214,101 @@ it("advances the watermark to a wake without waiting for the throttle", () => {
214
t.update({ updatedAt: at(16) });
215
expect(t.visits).toHaveLength(2);
216
});
217
+
218
+it("retries a failed visit when the same shell returns after reconnect", async () => {
219
+ using t = setup("thread-retry-failed", {
220
+ updatedAt: at(10),
221
+ lastVisitedAt: at(0),
222
+ latestRun: null,
223
+ });
224
+ t.setOnline(false);
225
+ t.mount();
226
+ await vi.advanceTimersByTimeAsync(0);
227
+ expect(t.visits).toEqual([]);
228
+
229
+ t.setOnline(true);
230
+ t.reconnect();
231
+ await vi.advanceTimersByTimeAsync(VISIT_DISPATCH_THROTTLE_MS);
232
+ expect(t.visits).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10), opened: true }]);
233
+});
234
+
235
+it("does not retry a failed visit the server already shows as seen", async () => {
236
+ using t = setup("thread-failed-seen", {
237
+ updatedAt: at(10),
238
+ lastVisitedAt: at(0),
239
+ latestRun: null,
240
+ });
241
+ t.setOnline(false);
242
+ t.mount();
243
+ t.update({ lastVisitedAt: at(10) });
244
+ await vi.advanceTimersByTimeAsync(0);
245
+
246
+ t.setOnline(true);
247
+ t.reconnect();
248
+ t.update({ lastVisitedAt: at(0) });
249
+ await vi.advanceTimersByTimeAsync(VISIT_DISPATCH_THROTTLE_MS);
250
+ expect(t.visits).toEqual([]);
251
+});
252
+
253
+it("preserves mark unread when an accepted visit fails after the rewind", async () => {
254
+ using t = setup("thread-accepted-rewound-failure", {
255
+ updatedAt: at(10),
256
+ lastVisitedAt: at(0),
257
+ latestRun: null,
258
+ });
259
+ const fail = t.deferNextVisit();
260
+ t.mount();
261
+ t.update({ lastVisitedAt: at(10) });
262
+ t.update({ lastVisitedAt: at(5) });
263
+ fail();
264
+ await vi.advanceTimersByTimeAsync(0);
265
+ t.reconnect();
266
+ t.update({});
267
+ await vi.advanceTimersByTimeAsync(VISIT_DISPATCH_THROTTLE_MS);
268
+ expect(t.attempts).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10), opened: true }]);
269
+});
270
+
271
+it.each(["unchanged shell", "new shell snapshot"] as const)(
272
+ "retries with %s when reconnect arrives before the pending visit fails",
273
+ async (snapshot) => {
274
+ using t = setup(`thread-reconnect-before-failure-${snapshot}`, {
275
+ updatedAt: at(10),
276
+ lastVisitedAt: at(0),
277
+ latestRun: null,
278
+ });
279
+ t.setOnline(false);
280
+ const fail = t.deferNextVisit();
281
+ t.mount();
282
+ t.setOnline(true);
283
+ t.reconnect();
284
+ if (snapshot === "new shell snapshot") t.update({});
285
+ fail();
286
+ await vi.advanceTimersByTimeAsync(VISIT_DISPATCH_THROTTLE_MS);
287
+ expect(t.visits).toEqual([{ threadId: t.ref.threadId, visitedAt: at(10), opened: true }]);
288
+ },
289
+);
290
+
291
+it("retries rejected opens only once per connection generation", async () => {
292
+ using t = setup("thread-rejection-throttle", {
293
+ updatedAt: at(10),
294
+ lastVisitedAt: at(0),
295
+ latestRun: null,
296
+ });
297
+ t.setOnline(false);
298
+ t.mount();
299
+ await vi.advanceTimersByTimeAsync(0);
300
+ for (let second = 1; second < 10; second++) {
301
+ await vi.advanceTimersByTimeAsync(1_000);
302
+ t.update({});
303
+ await vi.advanceTimersByTimeAsync(0);
304
+ }
305
+ expect(t.attempts).toHaveLength(1);
306
+ await vi.advanceTimersByTimeAsync(1_000);
307
+ expect(t.attempts).toHaveLength(1);
308
+ t.reconnect();
309
+ await vi.advanceTimersByTimeAsync(0);
310
+ expect(t.attempts).toHaveLength(2);
311
+ t.update({ updatedAt: at(20), latestRun: { completedAt: at(20) } });
312
+ await vi.advanceTimersByTimeAsync(3 * VISIT_DISPATCH_THROTTLE_MS);
313
+ expect(t.attempts).toHaveLength(2);
314
+});
packages/client-runtime/src/state/threadVisits.ts
+65
-5
@@ -1,6 +1,6 @@
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";
3
+import { AsyncResult, Atom } from "effect/reactivity";
4
5
import { parseThreadKey, threadKey } from "./entities.ts";
6
import { type AtomCommand, runAtomCommand } from "./runtime.ts";
@@ -33,6 +33,7 @@ interface VisitedShell {
33
34
export 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,
@@ -64,6 +65,11 @@ export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) {
65
// lands. It also keeps a mark-unread on the open thread sticky, since the
66
// rewind leaves updatedAt untouched.
67
let lastDispatchedUpdatedAt: string | null = null;
68
+ let lastAcceptedUpdatedAt: string | null = null;
69
+ let retryPending = false;
70
+ const sessionGenerationAtom = options.sessionGenerationAtom(ref.environmentId);
71
+ let lastDispatchGeneration = registry.get(sessionGenerationAtom);
72
+ let active = true;
73
let lastDispatchAt = 0;
74
let timer: ReturnType<typeof setTimeout> | undefined;
75
const clearTimer = () => {
@@ -71,12 +77,24 @@ export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) {
77
clearTimeout(timer);
78
timer = undefined;
79
};
74
- get.addFinalizer(clearTimer);
80
+ get.addFinalizer(() => {
81
+ active = false;
82
+ clearTimer();
83
+ });
84
+
85
+ const accept = (visitedAt: string) => {
86
+ const visitedAtMs = Date.parse(visitedAt);
87
+ if (Number.isNaN(visitedAtMs)) return;
88
+ if (lastAcceptedUpdatedAt === null || visitedAtMs > Date.parse(lastAcceptedUpdatedAt))
89
+ lastAcceptedUpdatedAt = visitedAt;
90
+ };
91
92
const dispatch = (shell: VisitedShell, visitedAt: string, opened: boolean) => {
93
clearTimer();
94
+ retryPending = false;
95
lastDispatchedUpdatedAt = visitedAt;
96
lastDispatchAt = Date.now();
97
+ lastDispatchGeneration = registry.get(sessionGenerationAtom);
98
void runAtomCommand(
99
registry,
100
options.visit,
@@ -89,7 +107,23 @@ export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) {
107
},
108
},
109
{ reportFailure: false },
92
- );
110
+ ).then((result) => {
111
+ if (!active) return;
112
+ if (!AsyncResult.isFailure(result)) {
113
+ accept(visitedAt);
114
+ return;
115
+ }
116
+ // Keep acceptance across a subsequent mark-unread, even if the ack was lost.
117
+ if (
118
+ lastAcceptedUpdatedAt !== null &&
119
+ Date.parse(lastAcceptedUpdatedAt) >= Date.parse(visitedAt)
120
+ )
121
+ return;
122
+ if (lastDispatchedUpdatedAt !== visitedAt) return;
123
+ if (opened) openPending = true;
124
+ retryPending = true;
125
+ onShell(registry.get(options.threadShellAtom(ref)));
126
+ });
127
};
128
129
const onShell = (shell: VisitedShell | null) => {
@@ -106,6 +140,26 @@ export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) {
140
options.markLocalVisit?.(ref, visitedAt);
141
return;
142
}
143
+ if (shell.lastVisitedAt) accept(shell.lastVisitedAt);
144
+ if (
145
+ retryPending &&
146
+ lastAcceptedUpdatedAt !== null &&
147
+ lastDispatchedUpdatedAt !== null &&
148
+ Date.parse(lastAcceptedUpdatedAt) >= Date.parse(lastDispatchedUpdatedAt)
149
+ ) {
150
+ retryPending = false;
151
+ openPending = false;
152
+ }
153
+ // A rejected visit waits for a new session, even if streaming changes the shell.
154
+ if (retryPending && registry.get(sessionGenerationAtom) === lastDispatchGeneration) return;
155
+ const elapsed = Date.now() - lastDispatchAt;
156
+ if (retryPending && elapsed < VISIT_DISPATCH_THROTTLE_MS) {
157
+ timer = setTimeout(
158
+ () => onShell(registry.get(options.threadShellAtom(ref))),
159
+ VISIT_DISPATCH_THROTTLE_MS - elapsed,
160
+ );
161
+ return;
162
+ }
163
// The open rides on the first visit the server hears, however late
164
// the shell arrives, so it still counts toward search ranking.
165
if (openPending) {
@@ -120,7 +174,11 @@ export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) {
174
lastDispatchedUpdatedAt = visitedAt;
175
return;
176
}
123
- if (lastDispatchedUpdatedAt !== null && Date.parse(lastDispatchedUpdatedAt) >= updatedAtMs)
177
+ if (
178
+ !retryPending &&
179
+ lastDispatchedUpdatedAt !== null &&
180
+ Date.parse(lastDispatchedUpdatedAt) >= updatedAtMs
181
+ )
182
return;
183
184
const completedAtMs = shell.latestRun?.completedAt
@@ -129,7 +187,6 @@ export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) {
187
const hasUnseenCompletion =
188
!Number.isNaN(completedAtMs) &&
189
(Number.isNaN(lastVisitedAtMs) || completedAtMs > lastVisitedAtMs);
132
- const elapsed = Date.now() - lastDispatchAt;
190
if (hasUnseenCompletion || wakeIsLatest || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {
191
dispatch(shell, visitedAt, false);
192
return;
@@ -143,6 +200,9 @@ export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) {
200
// `subscribe`, not `get`: a rebuild would reset the open and throttle
201
// state on every streaming tick.
202
get.subscribe(options.threadShellAtom(ref), onShell, { immediate: true });
203
+ get.subscribe(sessionGenerationAtom, () =>
204
+ onShell(registry.get(options.threadShellAtom(ref))),
205
+ );
206
}).pipe(Atom.withLabel(`thread-visit-tracker:${key}`));
207
});
208
return (ref: ScopedThreadRef | null) => (ref === null ? IDLE_TRACKER : family(threadKey(ref)));