Open History to see the last commit
1import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import {
3 type DeviceServiceState,
4 type EnvironmentId,
5 type PreviewSessionSnapshot,
6 ThreadId,
7} from "@t3tools/contracts";
8import { describe, expect, it, vi } from "vite-plus/test";
9
10import { browserMiniPlayerSource, usePreviewMiniPlayerStore } from "../../previewMiniPlayerStore";
11import {
12 __testing as previewStateTesting,
13 applyPreviewServerEvent,
14 applyPreviewServerSnapshot,
15 beginPreviewSessionClose,
16 cancelPreviewSessionClose,
17 reconcilePreviewServerSessions,
18 resetPreviewStateForTests,
19} from "../../previewStateStore";
20import { useRightPanelStore } from "../../rightPanelStore";
21import {
22 applyDeviceSnapshot,
23 floatDeviceSurface,
24 followPreviewSessions,
25 resetDeviceSessionBaselinesForTests,
26 revealServerTabs,
27 startAgentOpenedPreviews,
28} from "./agentOpenedPreviews";
29
30vi.mock("../../state/entities", () => ({
31 readEnvironmentSupportsServerBrowser: () => true,
32}));
33
34const ref = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-1"));
35const threadKey = scopedThreadKey(ref);
36
37const device = {
38 hostId: "local",
39 id: "pixel",
40 platform: "android",
41 name: "Pixel 8",
42 version: "15",
43 booted: true,
44 physical: false,
45} as const;
46
47const session = {
48 threadId: ref.threadId,
49 hostId: "local",
50 deviceId: "pixel",
51 platform: "android",
52 openedAt: "2026-01-01T00:00:00.000Z",
53} as const;
54
55const deviceState = (input: {
56 readonly sessions?: ReadonlyArray<
57 Omit<typeof session, "openedAt"> & { readonly openedAt: string }
58 >;
59 readonly devices?: ReadonlyArray<typeof device>;
60}) =>
61 ({
62 hosts: [],
63 hostStatus: "ready",
64 hostStatuses: {},
65 devices: input.devices ?? [device],
66 sessions: input.sessions ?? [],
67 onboardingCompleted: true,
68 agentAccessEnabled: true,
69 hubBasePath: "/api/device-hub",
70 revision: 0,
71 }) as unknown as DeviceServiceState;
72
73const floating = { sheetLayout: false, autoShowFloatingPreview: true };
74
75function setup() {
76 resetPreviewStateForTests();
77 resetDeviceSessionBaselinesForTests();
78 usePreviewMiniPlayerStore.setState({ byThreadKey: {} });
79 useRightPanelStore.setState({ byThreadKey: {} });
80}
81
82const miniPlayerSource = () => usePreviewMiniPlayerStore.getState().byThreadKey[threadKey]?.source;
83
84describe("applyDeviceSnapshot", () => {
85 it("treats the first snapshot as a baseline and floats sessions that start later", () => {
86 setup();
87 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), floating);
88 expect(miniPlayerSource()).toBeUndefined();
89
90 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [] }), floating);
91 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), floating);
92 expect(miniPlayerSource()).toMatchObject({ kind: "device", deviceId: "pixel" });
93 });
94
95 it("opens a session once its device summary arrives", () => {
96 setup();
97 applyDeviceSnapshot(ref.environmentId, deviceState({}), floating);
98 applyDeviceSnapshot(
99 ref.environmentId,
100 deviceState({ sessions: [session], devices: [] }),
101 floating,
102 );
103 expect(miniPlayerSource()).toBeUndefined();
104
105 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), floating);
106 expect(miniPlayerSource()).toMatchObject({ kind: "device", name: "Pixel 8" });
107 });
108
109 it("opens a panel tab once when floating previews are off, and nothing in sheet layouts", () => {
110 setup();
111 const panel = { sheetLayout: false, autoShowFloatingPreview: false };
112 applyDeviceSnapshot(ref.environmentId, deviceState({}), { ...panel, sheetLayout: true });
113 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), {
114 ...panel,
115 sheetLayout: true,
116 });
117 expect(useRightPanelStore.getState().byThreadKey[threadKey]).toBeUndefined();
118
119 applyDeviceSnapshot(ref.environmentId, deviceState({}), panel);
120 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), panel);
121 applyDeviceSnapshot(ref.environmentId, deviceState({}), panel);
122 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), panel);
123 const devices = useRightPanelStore
124 .getState()
125 .byThreadKey[threadKey]?.surfaces.filter((surface) => surface.kind === "device");
126 expect(devices).toHaveLength(1);
127 expect(miniPlayerSource()).toBeUndefined();
128 });
129
130 it("closes a floating device when its session ends, even before a baseline", () => {
131 setup();
132 usePreviewMiniPlayerStore.getState().open(ref, {
133 kind: "device",
134 hostId: "local",
135 deviceId: "pixel",
136 platform: "android",
137 name: "Pixel 8",
138 });
139 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), floating);
140 expect(miniPlayerSource()).toMatchObject({ kind: "device" });
141
142 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [] }), floating);
143 expect(miniPlayerSource()).toBeUndefined();
144 });
145
146 it("opens a session that ended and reopened between two snapshots", () => {
147 setup();
148 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), floating);
149 expect(miniPlayerSource()).toBeUndefined();
150
151 const reopened = { ...session, openedAt: "2026-01-01T00:05:00.000Z" };
152 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [reopened] }), floating);
153 expect(miniPlayerSource()).toMatchObject({ kind: "device", deviceId: "pixel" });
154 });
155
156 it("opens a device for a thread that had no sessions when the baseline was taken", () => {
157 setup();
158 const otherRef = scopeThreadRef(ref.environmentId, ThreadId.make("thread-2"));
159 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), floating);
160 applyDeviceSnapshot(
161 ref.environmentId,
162 deviceState({ sessions: [session, { ...session, threadId: otherRef.threadId }] }),
163 floating,
164 );
165 expect(miniPlayerSource()).toBeUndefined();
166 expect(
167 usePreviewMiniPlayerStore.getState().byThreadKey[scopedThreadKey(otherRef)]?.source,
168 ).toMatchObject({ kind: "device", deviceId: "pixel" });
169 });
170});
171
172describe("floatDeviceSurface", () => {
173 const source = {
174 kind: "device",
175 hostId: "local",
176 deviceId: "pixel",
177 platform: "android",
178 name: "Pixel 8",
179 } as const;
180
181 it("floats a device with a live session, or before device state loads", () => {
182 setup();
183 floatDeviceSurface(ref, source, deviceState({ sessions: [session] }));
184 expect(miniPlayerSource()).toMatchObject({ kind: "device", deviceId: "pixel" });
185
186 setup();
187 floatDeviceSurface(ref, source, null);
188 expect(miniPlayerSource()).toMatchObject({ kind: "device", deviceId: "pixel" });
189 });
190
191 it("does not float a device whose session ended", () => {
192 setup();
193 floatDeviceSurface(ref, source, deviceState({ sessions: [] }));
194 expect(miniPlayerSource()).toBeUndefined();
195 });
196});
197
198describe("revealServerTabs", () => {
199 const tab = (tabId: string, force?: boolean): PreviewSessionSnapshot => ({
200 threadId: "thread-1",
201 tabId,
202 navStatus: { _tag: "Loading", url: "http://localhost:5173/", title: "" },
203 canGoBack: false,
204 canGoForward: false,
205 updatedAt: "2026-01-01T00:00:00.000Z",
206 runtime: "server",
207 reveal: true,
208 ...(force === undefined ? {} : { revealRequest: { id: "r1", force } }),
209 });
210 const floatingTabId = () => {
211 const source = miniPlayerSource();
212 return source?.kind === "browser" ? source.tabId : null;
213 };
214
215 it("floats revealed tabs, and only forced ones when floating previews are off", () => {
216 setup();
217 revealServerTabs(ref, [tab("tab_plain")], { autoShowFloatingPreview: false });
218 expect(floatingTabId()).toBeNull();
219 revealServerTabs(ref, [tab("tab_forced", true)], { autoShowFloatingPreview: false });
220 expect(floatingTabId()).toBe("tab_forced");
221 });
222
223 it("focuses a tab already in the panel instead of floating it when forced", () => {
224 setup();
225 useRightPanelStore.getState().openBrowser(ref, "tab_a");
226 const browserSurfaceId = useRightPanelStore.getState().byThreadKey[threadKey]?.activeSurfaceId;
227 useRightPanelStore.getState().open(ref, "diff");
228
229 revealServerTabs(ref, [tab("tab_a", false)], { autoShowFloatingPreview: true });
230 expect(useRightPanelStore.getState().byThreadKey[threadKey]?.activeSurfaceId).not.toBe(
231 browserSurfaceId,
232 );
233 revealServerTabs(ref, [tab("tab_a", true)], { autoShowFloatingPreview: true });
234 expect(useRightPanelStore.getState().byThreadKey[threadKey]?.activeSurfaceId).toBe(
235 browserSurfaceId,
236 );
237 expect(floatingTabId()).toBeNull();
238 });
239});
240
241describe("followPreviewSessions", () => {
242 const snapshot = (tabId: string, reveal = true): PreviewSessionSnapshot => ({
243 threadId: "thread-1",
244 tabId,
245 navStatus: { _tag: "Loading", url: "http://localhost:5173/", title: "" },
246 canGoBack: false,
247 canGoForward: false,
248 updatedAt: "2026-01-01T00:00:00.000Z",
249 runtime: "server",
250 reveal,
251 });
252 const previewState = (sessions: ReadonlyArray<PreviewSessionSnapshot>, listLoaded = true) => ({
253 ...previewStateTesting.EMPTY_THREAD_PREVIEW_STATE,
254 listLoaded,
255 sessions: Object.fromEntries(sessions.map((entry) => [entry.tabId, entry])),
256 });
257 const browserTabs = () =>
258 useRightPanelStore
259 .getState()
260 .byThreadKey[threadKey]?.surfaces.filter((surface) => surface.kind === "preview")
261 .map((surface) => surface.id) ?? [];
262
263 it("adds visible sessions as tabs and drops tabs whose session ended", () => {
264 setup();
265 useRightPanelStore.getState().openBrowser(ref, "tab_gone");
266 followPreviewSessions(ref, previewState([snapshot("tab_a"), snapshot("tab_hidden", false)]));
267 expect(browserTabs()).toEqual(["browser:tab_a"]);
268 });
269
270 it("waits for the first server list before treating missing sessions as closed", () => {
271 setup();
272 useRightPanelStore.getState().openBrowser(ref, "tab_a");
273 usePreviewMiniPlayerStore.getState().open(ref, browserMiniPlayerSource("tab_a"));
274 followPreviewSessions(ref, previewState([], false));
275 expect(browserTabs()).toEqual(["browser:tab_a"]);
276 expect(miniPlayerSource()).toMatchObject({ kind: "browser", tabId: "tab_a" });
277
278 followPreviewSessions(ref, previewState([]));
279 expect(browserTabs()).toEqual([]);
280 expect(miniPlayerSource()).toBeUndefined();
281 });
282});
283
284describe("startAgentOpenedPreviews", () => {
285 const serverEpoch = "server-a";
286 const serverTab = (overrides: Partial<PreviewSessionSnapshot> = {}): PreviewSessionSnapshot => ({
287 threadId: "thread-1",
288 tabId: "tab_a",
289 navStatus: { _tag: "Loading", url: "http://localhost:5173/", title: "" },
290 canGoBack: false,
291 canGoForward: false,
292 updatedAt: "2026-01-01T00:00:00.000Z",
293 runtime: "server",
294 reveal: true,
295 ...overrides,
296 });
297 const following = () => {
298 setup();
299 return { [Symbol.dispose]: startAgentOpenedPreviews() };
300 };
301 const navigated = (revision: number, snapshot: PreviewSessionSnapshot) =>
302 applyPreviewServerEvent(ref, {
303 type: "navigated",
304 threadId: "thread-1",
305 tabId: snapshot.tabId,
306 createdAt: snapshot.updatedAt,
307 snapshot,
308 serverEpoch,
309 revision,
310 });
311 const floatingTabId = () => {
312 const source = miniPlayerSource();
313 return source?.kind === "browser" ? source.tabId : null;
314 };
315 const browserTabs = (threadKeyToRead = threadKey) =>
316 useRightPanelStore
317 .getState()
318 .byThreadKey[threadKeyToRead]?.surfaces.filter((surface) => surface.kind === "preview")
319 .map((surface) => surface.id);
320
321 it("treats the first list as a baseline and floats tabs opened later", () => {
322 using _following = following();
323 reconcilePreviewServerSessions(ref, {
324 sessions: [serverTab({ tabId: "tab_restored" })],
325 serverEpoch,
326 revision: 1,
327 });
328 expect(floatingTabId()).toBeNull();
329 expect(browserTabs()).toEqual(["browser:tab_restored"]);
330
331 const opened = serverTab({ tabId: "tab_agent" });
332 applyPreviewServerEvent(ref, {
333 type: "opened",
334 threadId: "thread-1",
335 tabId: opened.tabId,
336 createdAt: opened.updatedAt,
337 snapshot: opened,
338 serverEpoch,
339 revision: 2,
340 });
341 expect(floatingTabId()).toBe("tab_agent");
342 });
343
344 it("reveals an existing tab only for a new reveal request", () => {
345 using _following = following();
346 const tab = serverTab({ revealRequest: { id: "r1", force: false } });
347 reconcilePreviewServerSessions(ref, { sessions: [tab], serverEpoch, revision: 1 });
348
349 navigated(2, { ...tab, updatedAt: "2026-01-01T00:00:01.000Z" });
350 expect(floatingTabId()).toBeNull();
351
352 navigated(3, {
353 ...tab,
354 revealRequest: { id: "r2", force: true },
355 updatedAt: "2026-01-01T00:00:02.000Z",
356 });
357 expect(useRightPanelStore.getState().byThreadKey[threadKey]?.activeSurfaceId).toBe(
358 "browser:tab_a",
359 );
360 });
361
362 it("never reveals tabs this client opened, desktop tabs, or a tab whose close failed", () => {
363 using _following = following();
364 const tab = serverTab({ tabId: "tab_closing" });
365 reconcilePreviewServerSessions(ref, { sessions: [tab], serverEpoch, revision: 1 });
366 applyPreviewServerSnapshot(ref, serverTab({ tabId: "tab_own", reveal: undefined }));
367 applyPreviewServerSnapshot(ref, { ...serverTab({ tabId: "tab_desktop" }), runtime: "desktop" });
368 beginPreviewSessionClose(ref, tab.tabId);
369 cancelPreviewSessionClose(ref, tab, tab.tabId);
370 expect(floatingTabId()).toBeNull();
371 });
372
373 it("follows background threads and closes the floating browser when its session ends", () => {
374 using _following = following();
375 const other = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-2"));
376 reconcilePreviewServerSessions(other, {
377 sessions: [serverTab({ threadId: "thread-2", tabId: "tab_b" })],
378 serverEpoch,
379 revision: 1,
380 });
381 expect(browserTabs(scopedThreadKey(other))).toEqual(["browser:tab_b"]);
382
383 reconcilePreviewServerSessions(ref, { sessions: [], serverEpoch, revision: 1 });
384 const opened = serverTab();
385 applyPreviewServerEvent(ref, {
386 type: "opened",
387 threadId: "thread-1",
388 tabId: opened.tabId,
389 createdAt: opened.updatedAt,
390 snapshot: opened,
391 serverEpoch,
392 revision: 2,
393 });
394 expect(floatingTabId()).toBe("tab_a");
395 applyPreviewServerEvent(ref, {
396 type: "closed",
397 threadId: "thread-1",
398 tabId: opened.tabId,
399 createdAt: opened.updatedAt,
400 serverEpoch,
401 revision: 3,
402 });
403 expect(floatingTabId()).toBeNull();
404 });
405});