Skip to content

Commit d90ee72

Browse files
committed
fix(web): keep known preview tabs while the session list refreshes
Reopening a thread’s Browser panel after an agent or automation created a tab while the panel was closed can remove that tab when a stale cached session list is replayed during refresh. The stale reconciliation also discards the tab’s desktop overlay state, which the fresh response does not restore. Evaluate the lazy session list on mount, reuse an in-flight request, and reconcile only completed successful responses. Do not restart or reconcile against an in-flight or stale list; keep known tabs and their desktop overlay state until the fresh response arrives. Verification: two cache/refresh regressions fail against main; all 31 focused hook and preview-state tests pass on the branch. Web typecheck and targeted lint/format checks pass. Desktop before/after video is still required before submission: reopen the Browser panel after an agent or automation created a tab while it was closed, and show tab disappearance/reappearance before the fix and retention after it. Upload the videos to the PR. Still screenshots are insufficient for this timing defect. End-to-end desktop behavior remains unverified: the fix assumes real AtomRpc query atoms report waiting with the previous value during refresh, as the transport test harness models them. GPT-6.1 Sol via T3 Code
1 parent 8ed276c commit d90ee72

2 files changed

Lines changed: 199 additions & 2 deletions

File tree

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
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/unstable/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/unstable/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+
readThreadPreviewState,
71+
resetPreviewStateForTests,
72+
} from "~/previewStateStore";
73+
import { AppAtomRegistryProvider, appAtomRegistry } from "~/rpc/atomRegistry";
74+
import { previewEnvironment } from "~/state/preview";
75+
import { usePreviewSession } from "./usePreviewSession";
76+
77+
let renderer: ReactTestRenderer | null = null;
78+
let sequence = 0;
79+
let ref: ScopedThreadRef;
80+
81+
function SessionSync() {
82+
usePreviewSession(ref);
83+
return null;
84+
}
85+
86+
const listAtom = () => {
87+
previewEnvironment.list({ environmentId: ref.environmentId, input: { threadId: ref.threadId } });
88+
return harness.lists.get(ref.threadId)!.atom;
89+
};
90+
const result = (
91+
revision: number,
92+
tabIds: string[],
93+
serverEpoch = "epoch-1",
94+
): PreviewListResult => ({
95+
serverEpoch,
96+
revision,
97+
sessions: tabIds.map((tabId) => ({
98+
threadId: ref.threadId,
99+
tabId,
100+
navStatus: { _tag: "Idle" },
101+
canGoBack: false,
102+
canGoForward: false,
103+
updatedAt: "2026-10-02T00:00:00.000Z",
104+
})),
105+
});
106+
107+
async function mount() {
108+
await act(async () => {
109+
renderer = create(createElement(AppAtomRegistryProvider, null, createElement(SessionSync)));
110+
});
111+
}
112+
113+
beforeEach(() => {
114+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
115+
sequence += 1;
116+
ref = {
117+
environmentId: EnvironmentId.make(`preview-sync-${sequence}`),
118+
threadId: ThreadId.make(`thread-sync-${sequence}`),
119+
};
120+
});
121+
122+
afterEach(async () => {
123+
await act(async () => renderer?.unmount());
124+
renderer = null;
125+
resetPreviewStateForTests();
126+
vi.unstubAllGlobals();
127+
});
128+
129+
describe("native preview session synchronization", () => {
130+
it("evaluates the lazy list once and restores sessions that predate mounting", async () => {
131+
const atom = listAtom();
132+
await mount();
133+
expect(harness.lists.get(ref.threadId)?.box.requests).toBe(1);
134+
appAtomRegistry.set(atom, AsyncResult.success(result(1, ["restored"])));
135+
expect(readThreadPreviewState(ref).activeTabId).toBe("restored");
136+
});
137+
138+
it("preserves a local tab while cached absence is waiting for a fresh response", async () => {
139+
const atom = listAtom();
140+
appAtomRegistry.set(atom, AsyncResult.waiting(AsyncResult.success(result(1, []))));
141+
applyPreviewServerSnapshot(ref, result(1, ["local"]).sessions[0]!);
142+
await mount();
143+
expect(readThreadPreviewState(ref).activeTabId).toBe("local");
144+
expect(harness.lists.get(ref.threadId)?.box.requests).toBe(0);
145+
appAtomRegistry.set(atom, AsyncResult.success(result(2, ["local"])));
146+
expect(readThreadPreviewState(ref).activeTabId).toBe("local");
147+
appAtomRegistry.set(atom, AsyncResult.success(result(3, [])));
148+
expect(readThreadPreviewState(ref).activeTabId).toBeNull();
149+
});
150+
151+
it("refreshes a completed cache without treating its old absence as authoritative", async () => {
152+
const atom = listAtom();
153+
appAtomRegistry.set(atom, AsyncResult.success(result(1, [])));
154+
applyPreviewServerSnapshot(ref, result(1, ["local"]).sessions[0]!);
155+
await mount();
156+
expect(harness.lists.get(ref.threadId)?.box.requests).toBe(1);
157+
expect(readThreadPreviewState(ref).activeTabId).toBe("local");
158+
appAtomRegistry.set(atom, AsyncResult.success(result(2, ["local"])));
159+
expect(readThreadPreviewState(ref).activeTabId).toBe("local");
160+
});
161+
162+
it("retains newer event state when an older list response completes", async () => {
163+
const atom = listAtom();
164+
await mount();
165+
const snapshot = result(2, ["opened"]).sessions[0]!;
166+
previewEnvironment.events({ environmentId: ref.environmentId, input: {} });
167+
appAtomRegistry.set(
168+
harness.events.get(ref.environmentId)!,
169+
AsyncResult.success({
170+
type: "opened",
171+
threadId: ref.threadId,
172+
tabId: snapshot.tabId,
173+
snapshot,
174+
serverEpoch: "epoch-1",
175+
revision: 2,
176+
createdAt: snapshot.updatedAt,
177+
}),
178+
);
179+
appAtomRegistry.set(atom, AsyncResult.success(result(1, [])));
180+
expect(readThreadPreviewState(ref).activeTabId).toBe("opened");
181+
expect(readThreadPreviewState(ref).serverRevision).toBe(2);
182+
});
183+
184+
it("keeps the local snapshot on a completed failure and reconciles a later success", async () => {
185+
const atom = listAtom();
186+
applyPreviewServerSnapshot(ref, result(1, ["local"]).sessions[0]!);
187+
await mount();
188+
appAtomRegistry.set(atom, AsyncResult.failure(Cause.die("offline")));
189+
expect(readThreadPreviewState(ref).activeTabId).toBe("local");
190+
appAtomRegistry.set(atom, AsyncResult.success(result(2, [])));
191+
expect(readThreadPreviewState(ref).activeTabId).toBeNull();
192+
});
193+
});

‎apps/web/src/components/preview/usePreviewSession.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
4242
let eventsVersion = 0;
4343

4444
const reconcileSessions = (result: Atom.Type<typeof sessionsAtom>) => {
45-
if (!AsyncResult.isSuccess(result)) return;
45+
if (result.waiting || !AsyncResult.isSuccess(result)) return;
4646
reconcilePreviewServerSessions(threadRef, result.value);
4747
};
4848

@@ -60,6 +60,9 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
6060
disposed = true;
6161
});
6262
const initialEvent = get.once(eventsAtom);
63+
// Subscribing alone does not evaluate a lazy list. Start it now, but
64+
// reconcile only subsequent responses: a completed cache may be stale.
65+
get.once(sessionsAtom);
6366
get.subscribe(sessionsAtom, (result) => {
6467
reconcileSessions(result);
6568
});
@@ -72,7 +75,8 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
7275
// The cached list can predate an automation-created tab. Keep the local
7376
// snapshot visible until an authoritative refresh arrives instead of
7477
// reconciling against a stale empty result when the panel first mounts.
75-
get.refresh(sessionsAtom);
78+
const current = get.once(sessionsAtom);
79+
if (!AsyncResult.isInitial(current) && !current.waiting) get.refresh(sessionsAtom);
7680
if (eventsVersion === 0) applyLatestEvent(initialEvent);
7781
});
7882
}).pipe(Atom.setIdleTTL(1_000), Atom.withLabel(`preview:session-sync:${threadKey}`));

0 commit comments

Comments
 (0)