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 23, 04:15 UTC
fix(web): keep known preview tabs while the session list refreshes (#14955)
Co-authored-by: SAPHID <saphid@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Alex Southwell committed
Oct 19, 2026 at 06:14 UTC
26c241144a9e8cfeb8b7b19e5d6646aedc9a859f
2 files changed
+226
-3
apps/web/src/components/preview/previewSessionSync.test.ts
new
+219
@@ -0,0 +1,219 @@
1
+import {
2
+ EnvironmentId,
3
+ ThreadId,
4
+ type PreviewEvent,
5
+ type PreviewListResult,
6
+ type ScopedThreadRef,
7
+} from "@t3tools/contracts";
8
+import * as Cause from "effect/Cause";
9
+import { AsyncResult, Atom } from "effect/reactivity";
10
+import { act, createElement } from "react";
11
+import { create, type ReactTestRenderer } from "react-test-renderer";
12
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13
+
14
+// Only the transport is substituted. The hook, atom registry and preview
15
+// store run unchanged, including lazy evaluation and refresh notifications.
16
+type ListResult = AsyncResult.AsyncResult<PreviewListResult, never>;
17
+type EventResult = AsyncResult.AsyncResult<PreviewEvent, never>;
18
+const harness = vi.hoisted(() => ({
19
+ lists: new Map<
20
+ string,
21
+ {
22
+ box: { current: ListResult; requests: number };
23
+ atom: Atom.Writable<ListResult>;
24
+ }
25
+ >(),
26
+ events: new Map<string, Atom.Writable<EventResult>>(),
27
+}));
28
+
29
+vi.mock("~/state/preview", async () => {
30
+ const { AsyncResult, Atom } = await import("effect/reactivity");
31
+ return {
32
+ previewEnvironment: {
33
+ list: (target: { input: { threadId: string } }) => {
34
+ const key = target.input.threadId;
35
+ let entry = harness.lists.get(key);
36
+ if (!entry) {
37
+ const box: { current: ListResult; requests: number } = {
38
+ current: AsyncResult.initial(),
39
+ requests: 0,
40
+ };
41
+ const atom = Atom.writable(
42
+ () => {
43
+ box.requests += 1;
44
+ return AsyncResult.waiting(box.current);
45
+ },
46
+ (ctx, value: ListResult) => {
47
+ box.current = value;
48
+ ctx.setSelf(value);
49
+ },
50
+ );
51
+ entry = { box, atom };
52
+ harness.lists.set(key, entry);
53
+ }
54
+ return entry.atom;
55
+ },
56
+ events: (target: { environmentId: string }) => {
57
+ let atom = harness.events.get(target.environmentId);
58
+ if (!atom) {
59
+ atom = Atom.make<EventResult>(AsyncResult.initial());
60
+ harness.events.set(target.environmentId, atom);
61
+ }
62
+ return atom;
63
+ },
64
+ },
65
+ };
66
+});
67
+
68
+import {
69
+ applyPreviewServerSnapshot,
70
+ applyPreviewDesktopState,
71
+ readThreadPreviewState,
72
+ reconcilePreviewServerSessions,
73
+ resetPreviewStateForTests,
74
+} from "~/previewStateStore";
75
+import { AppAtomRegistryProvider, appAtomRegistry } from "~/rpc/atomRegistry";
76
+import { previewEnvironment } from "~/state/preview";
77
+import { usePreviewSession } from "./usePreviewSession";
78
+
79
+let renderer: ReactTestRenderer | null = null;
80
+let sequence = 0;
81
+let ref: ScopedThreadRef;
82
+
83
+function SessionSync() {
84
+ usePreviewSession(ref);
85
+ return null;
86
+}
87
+
88
+const listAtom = () => {
89
+ previewEnvironment.list({ environmentId: ref.environmentId, input: { threadId: ref.threadId } });
90
+ return harness.lists.get(ref.threadId)!.atom;
91
+};
92
+const result = (
93
+ revision: number,
94
+ tabIds: string[],
95
+ serverEpoch = "epoch-1",
96
+): PreviewListResult => ({
97
+ serverEpoch,
98
+ revision,
99
+ sessions: tabIds.map((tabId) => ({
100
+ threadId: ref.threadId,
101
+ tabId,
102
+ navStatus: { _tag: "Idle" },
103
+ canGoBack: false,
104
+ canGoForward: false,
105
+ updatedAt: "2026-10-02T00:00:00.000Z",
106
+ })),
107
+});
108
+
109
+async function mount() {
110
+ await act(async () => {
111
+ renderer = create(createElement(AppAtomRegistryProvider, null, createElement(SessionSync)));
112
+ });
113
+}
114
+
115
+beforeEach(() => {
116
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
117
+ sequence += 1;
118
+ ref = {
119
+ environmentId: EnvironmentId.make(`preview-sync-${sequence}`),
120
+ threadId: ThreadId.make(`thread-sync-${sequence}`),
121
+ };
122
+});
123
+
124
+afterEach(async () => {
125
+ await act(async () => renderer?.unmount());
126
+ renderer = null;
127
+ resetPreviewStateForTests();
128
+ vi.unstubAllGlobals();
129
+});
130
+
131
+describe("native preview session synchronization", () => {
132
+ it("evaluates the lazy list once and restores sessions that predate mounting", async () => {
133
+ const atom = listAtom();
134
+ await mount();
135
+ expect(harness.lists.get(ref.threadId)?.box.requests).toBe(1);
136
+ appAtomRegistry.set(atom, AsyncResult.success(result(1, ["restored"])));
137
+ expect(readThreadPreviewState(ref).activeTabId).toBe("restored");
138
+ });
139
+
140
+ it("preserves a local tab while cached absence is waiting for a fresh response", async () => {
141
+ const atom = listAtom();
142
+ appAtomRegistry.set(atom, AsyncResult.waiting(AsyncResult.success(result(1, []))));
143
+ applyPreviewServerSnapshot(ref, result(1, ["local"]).sessions[0]!);
144
+ await mount();
145
+ expect(readThreadPreviewState(ref).activeTabId).toBe("local");
146
+ expect(harness.lists.get(ref.threadId)?.box.requests).toBe(0);
147
+ appAtomRegistry.set(atom, AsyncResult.success(result(2, ["local"])));
148
+ expect(readThreadPreviewState(ref).activeTabId).toBe("local");
149
+ appAtomRegistry.set(atom, AsyncResult.success(result(3, [])));
150
+ expect(readThreadPreviewState(ref).activeTabId).toBeNull();
151
+ });
152
+
153
+ it("refreshes a completed cache without treating its old absence as authoritative", async () => {
154
+ const atom = listAtom();
155
+ appAtomRegistry.set(atom, AsyncResult.success(result(1, [])));
156
+ reconcilePreviewServerSessions(ref, result(1, []));
157
+ applyPreviewServerSnapshot(ref, result(1, ["local"]).sessions[0]!);
158
+ applyPreviewDesktopState(ref, "local", {
159
+ hasWebContents: true,
160
+ canGoBack: true,
161
+ canGoForward: false,
162
+ loading: false,
163
+ zoomFactor: 1.5,
164
+ pictureInPicture: false,
165
+ colorScheme: "system",
166
+ audioMuted: false,
167
+ audible: false,
168
+ controller: "human",
169
+ favicon: null,
170
+ });
171
+ await mount();
172
+ expect(harness.lists.get(ref.threadId)?.box.requests).toBe(1);
173
+ expect(readThreadPreviewState(ref).activeTabId).toBe("local");
174
+ expect(readThreadPreviewState(ref).desktopOverlay?.zoomFactor).toBe(1.5);
175
+ appAtomRegistry.set(atom, AsyncResult.success(result(2, ["local"])));
176
+ expect(readThreadPreviewState(ref).activeTabId).toBe("local");
177
+ expect(readThreadPreviewState(ref).desktopOverlay?.canGoBack).toBe(true);
178
+ });
179
+
180
+ it("retains newer event state when an older list response completes, then retries the list", async () => {
181
+ const atom = listAtom();
182
+ await mount();
183
+ const snapshot = result(2, ["opened"]).sessions[0]!;
184
+ previewEnvironment.events({ environmentId: ref.environmentId, input: {} });
185
+ appAtomRegistry.set(
186
+ harness.events.get(ref.environmentId)!,
187
+ AsyncResult.success({
188
+ type: "opened",
189
+ threadId: ref.threadId,
190
+ tabId: snapshot.tabId,
191
+ snapshot,
192
+ serverEpoch: "epoch-1",
193
+ revision: 2,
194
+ createdAt: snapshot.updatedAt,
195
+ }),
196
+ );
197
+ await act(async () => appAtomRegistry.set(atom, AsyncResult.success(result(1, []))));
198
+ expect(readThreadPreviewState(ref).activeTabId).toBe("opened");
199
+ expect(readThreadPreviewState(ref).serverRevision).toBe(2);
200
+ expect(readThreadPreviewState(ref).listLoaded).toBe(false);
201
+ // The overtaken list is not a baseline, so the hook asks again; its
202
+ // waiting state must not reconcile, and the fresh answer completes it.
203
+ expect(harness.lists.get(ref.threadId)?.box.requests).toBe(2);
204
+ expect(readThreadPreviewState(ref).activeTabId).toBe("opened");
205
+ appAtomRegistry.set(atom, AsyncResult.success(result(2, ["opened"])));
206
+ expect(readThreadPreviewState(ref).listLoaded).toBe(true);
207
+ expect(readThreadPreviewState(ref).activeTabId).toBe("opened");
208
+ });
209
+
210
+ it("keeps the local snapshot on a completed failure and reconciles a later success", async () => {
211
+ const atom = listAtom();
212
+ applyPreviewServerSnapshot(ref, result(1, ["local"]).sessions[0]!);
213
+ await mount();
214
+ appAtomRegistry.set(atom, AsyncResult.failure(Cause.die("offline")));
215
+ expect(readThreadPreviewState(ref).activeTabId).toBe("local");
216
+ appAtomRegistry.set(atom, AsyncResult.success(result(2, [])));
217
+ expect(readThreadPreviewState(ref).activeTabId).toBeNull();
218
+ });
219
+});
apps/web/src/components/preview/usePreviewSession.ts
+7
-3
@@ -42,9 +42,9 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
42
let eventsVersion = 0;
43
44
const reconcileSessions = (result: Atom.Type<typeof sessionsAtom>) => {
45
- if (!AsyncResult.isSuccess(result)) return;
45
+ if (result.waiting || !AsyncResult.isSuccess(result)) return;
46
reconcilePreviewServerSessions(threadRef, result.value);
47
- if (!result.waiting && !readThreadPreviewState(threadRef).listLoaded) {
47
+ if (!readThreadPreviewState(threadRef).listLoaded) {
48
// An event overtook the first list. Retry the authoritative baseline;
49
// do not declare a partial event-only index ready for surface cleanup.
50
queueMicrotask(() => {
@@ -67,6 +67,9 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
67
disposed = true;
68
});
69
const initialEvent = get.once(eventsAtom);
70
+ // Subscribing alone does not evaluate a lazy list. Start it now, but
71
+ // reconcile only subsequent responses: a completed cache may be stale.
72
+ get.once(sessionsAtom);
73
get.subscribe(sessionsAtom, (result) => {
74
reconcileSessions(result);
75
});
@@ -81,7 +84,8 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
84
// The cached list can predate an automation-created tab. Keep the local
85
// snapshot visible until an authoritative refresh arrives instead of
86
// reconciling against a stale empty result when the panel first mounts.
84
- get.refresh(sessionsAtom);
87
+ const current = get.once(sessionsAtom);
88
+ if (!AsyncResult.isInitial(current) && !current.waiting) get.refresh(sessionsAtom);
89
if (eventsVersion === 0) applyLatestEvent(initialEvent);
90
});
91
}).pipe(Atom.setIdleTTL(1_000), Atom.withLabel(`preview:session-sync:${threadKey}`));