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 type DesktopPreviewOverlay,
18 reconcilePreviewServerSessions,
19 resetPreviewStateForTests,
20 type ThreadPreviewState,
21} from "../../previewStateStore";
22import { useRightPanelStore } from "../../rightPanelStore";
23import {
24 applyDeviceSnapshot,
25 dockFloatingPreviewInPanel,
26 floatBrowserSurface,
27 floatDeviceSurface,
28 floatPanelSurfaceOnClose,
29 followPreviewSessions,
30 resetDeviceSessionBaselinesForTests,
31 revealServerTabs,
32 startAgentOpenedPreviews,
33} from "./agentOpenedPreviews";
34
35vi.mock("../../state/entities", () => ({
36 readEnvironmentSupportsServerBrowser: () => true,
37}));
38
39const ref = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-1"));
40const threadKey = scopedThreadKey(ref);
41
42const device = {
43 hostId: "local",
44 id: "pixel",
45 platform: "android",
46 name: "Pixel 8",
47 version: "15",
48 booted: true,
49 physical: false,
50} as const;
51
52const session = {
53 threadId: ref.threadId,
54 hostId: "local",
55 deviceId: "pixel",
56 platform: "android",
57 openedAt: "2026-01-01T00:00:00.000Z",
58} as const;
59
60const deviceState = (input: {
61 readonly sessions?: ReadonlyArray<
62 Omit<typeof session, "openedAt"> & { readonly openedAt: string }
63 >;
64 readonly devices?: ReadonlyArray<typeof device>;
65}) =>
66 ({
67 hosts: [],
68 hostStatus: "ready",
69 hostStatuses: {},
70 devices: input.devices ?? [device],
71 sessions: input.sessions ?? [],
72 onboardingCompleted: true,
73 agentAccessEnabled: true,
74 hubBasePath: "/api/device-hub",
75 revision: 0,
76 }) as unknown as DeviceServiceState;
77
78const floating = { sheetLayout: false, autoShowFloatingPreview: true };
79
80function setup() {
81 resetPreviewStateForTests();
82 resetDeviceSessionBaselinesForTests();
83 usePreviewMiniPlayerStore.setState({ byThreadKey: {} });
84 useRightPanelStore.setState({ byThreadKey: {} });
85}
86
87const miniPlayerSource = () => usePreviewMiniPlayerStore.getState().byThreadKey[threadKey]?.source;
88
89describe("applyDeviceSnapshot", () => {
90 it("treats the first snapshot as a baseline and floats sessions that start later", () => {
91 setup();
92 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), floating);
93 expect(miniPlayerSource()).toBeUndefined();
94
95 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [] }), floating);
96 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), floating);
97 expect(miniPlayerSource()).toMatchObject({ kind: "device", deviceId: "pixel" });
98 });
99
100 it("opens a session once its device summary arrives", () => {
101 setup();
102 applyDeviceSnapshot(ref.environmentId, deviceState({}), floating);
103 applyDeviceSnapshot(
104 ref.environmentId,
105 deviceState({ sessions: [session], devices: [] }),
106 floating,
107 );
108 expect(miniPlayerSource()).toBeUndefined();
109
110 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), floating);
111 expect(miniPlayerSource()).toMatchObject({ kind: "device", name: "Pixel 8" });
112 });
113
114 it("opens a panel tab once when floating previews are off, and nothing in sheet layouts", () => {
115 setup();
116 const panel = { sheetLayout: false, autoShowFloatingPreview: false };
117 applyDeviceSnapshot(ref.environmentId, deviceState({}), { ...panel, sheetLayout: true });
118 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), {
119 ...panel,
120 sheetLayout: true,
121 });
122 expect(useRightPanelStore.getState().byThreadKey[threadKey]).toBeUndefined();
123
124 applyDeviceSnapshot(ref.environmentId, deviceState({}), panel);
125 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), panel);
126 applyDeviceSnapshot(ref.environmentId, deviceState({}), panel);
127 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), panel);
128 const devices = useRightPanelStore
129 .getState()
130 .byThreadKey[threadKey]?.surfaces.filter((surface) => surface.kind === "device");
131 expect(devices).toHaveLength(1);
132 expect(miniPlayerSource()).toBeUndefined();
133 });
134
135 it("closes a floating device when its session ends, even before a baseline", () => {
136 setup();
137 usePreviewMiniPlayerStore.getState().open(ref, {
138 kind: "device",
139 hostId: "local",
140 deviceId: "pixel",
141 platform: "android",
142 name: "Pixel 8",
143 });
144 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), floating);
145 expect(miniPlayerSource()).toMatchObject({ kind: "device" });
146
147 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [] }), floating);
148 expect(miniPlayerSource()).toBeUndefined();
149 });
150
151 it("opens a session that ended and reopened between two snapshots", () => {
152 setup();
153 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), floating);
154 expect(miniPlayerSource()).toBeUndefined();
155
156 const reopened = { ...session, openedAt: "2026-01-01T00:05:00.000Z" };
157 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [reopened] }), floating);
158 expect(miniPlayerSource()).toMatchObject({ kind: "device", deviceId: "pixel" });
159 });
160
161 it("opens a device for a thread that had no sessions when the baseline was taken", () => {
162 setup();
163 const otherRef = scopeThreadRef(ref.environmentId, ThreadId.make("thread-2"));
164 applyDeviceSnapshot(ref.environmentId, deviceState({ sessions: [session] }), floating);
165 applyDeviceSnapshot(
166 ref.environmentId,
167 deviceState({ sessions: [session, { ...session, threadId: otherRef.threadId }] }),
168 floating,
169 );
170 expect(miniPlayerSource()).toBeUndefined();
171 expect(
172 usePreviewMiniPlayerStore.getState().byThreadKey[scopedThreadKey(otherRef)]?.source,
173 ).toMatchObject({ kind: "device", deviceId: "pixel" });
174 });
175});
176
177describe("floatDeviceSurface", () => {
178 const source = {
179 kind: "device",
180 hostId: "local",
181 deviceId: "pixel",
182 platform: "android",
183 name: "Pixel 8",
184 } as const;
185
186 it("floats a device with a live session, or before device state loads", () => {
187 setup();
188 floatDeviceSurface(ref, source, deviceState({ sessions: [session] }));
189 expect(miniPlayerSource()).toMatchObject({ kind: "device", deviceId: "pixel" });
190
191 setup();
192 floatDeviceSurface(ref, source, null);
193 expect(miniPlayerSource()).toMatchObject({ kind: "device", deviceId: "pixel" });
194 });
195
196 it("does not float a device whose session ended", () => {
197 setup();
198 floatDeviceSurface(ref, source, deviceState({ sessions: [] }));
199 expect(miniPlayerSource()).toBeUndefined();
200 });
201});
202
203describe("floatBrowserSurface", () => {
204 const tab = (navStatus: PreviewSessionSnapshot["navStatus"]): PreviewSessionSnapshot => ({
205 threadId: "thread-1",
206 tabId: "tab_a",
207 navStatus,
208 canGoBack: false,
209 canGoForward: false,
210 updatedAt: "2026-01-01T00:00:00.000Z",
211 });
212 const state = (
213 snapshot: PreviewSessionSnapshot,
214 desktopNavStatus?: PreviewSessionSnapshot["navStatus"],
215 ) => ({
216 ...previewStateTesting.EMPTY_THREAD_PREVIEW_STATE,
217 sessions: { tab_a: snapshot },
218 desktopByTabId: desktopNavStatus
219 ? { tab_a: { navStatus: desktopNavStatus } as DesktopPreviewOverlay }
220 : {},
221 });
222 const loading = { _tag: "Loading", url: "http://localhost:5173/", title: "" } as const;
223
224 it("floats a navigated tab but not one that never left the empty page", () => {
225 setup();
226 floatBrowserSurface(ref, "tab_a", state(tab({ _tag: "Idle" })));
227 expect(miniPlayerSource()).toBeUndefined();
228
229 floatBrowserSurface(ref, "tab_a", state(tab(loading)));
230 expect(miniPlayerSource()).toEqual(browserMiniPlayerSource("tab_a"));
231 });
232
233 it("follows the desktop page when the server snapshot has not caught up", () => {
234 setup();
235 floatBrowserSurface(ref, "tab_a", state(tab({ _tag: "Idle" }), loading));
236 expect(miniPlayerSource()).toEqual(browserMiniPlayerSource("tab_a"));
237 });
238});
239
240describe("floatPanelSurfaceOnClose", () => {
241 const browser = browserMiniPlayerSource("tab_panel");
242 const previewState = {
243 ...previewStateTesting.EMPTY_THREAD_PREVIEW_STATE,
244 sessions: {
245 tab_panel: {
246 threadId: "thread-1",
247 tabId: "tab_panel",
248 navStatus: { _tag: "Loading", url: "http://localhost:5173/", title: "" },
249 canGoBack: false,
250 canGoForward: false,
251 updatedAt: "2026-01-01T00:00:00.000Z",
252 },
253 },
254 } satisfies ThreadPreviewState;
255
256 it.each([
257 { name: "floats a browser", source: browser, autoShow: true, before: null, after: browser },
258 {
259 name: "floats no browser with Auto-show off",
260 source: browser,
261 autoShow: false,
262 before: null,
263 after: undefined,
264 },
265 {
266 name: "keeps a float the user opened with Auto-show off",
267 source: browser,
268 autoShow: false,
269 before: browser,
270 after: browser,
271 },
272 ])("$name", ({ source, autoShow, before, after }) => {
273 setup();
274 if (before) usePreviewMiniPlayerStore.getState().open(ref, before);
275 floatPanelSurfaceOnClose(ref, source, {
276 autoShowFloatingPreview: autoShow,
277 previewState,
278 deviceState: deviceState({ sessions: [session] }),
279 });
280 expect(miniPlayerSource()).toEqual(after);
281 });
282});
283
284describe("dockFloatingPreviewInPanel", () => {
285 it("ends the float when the reopened panel shows that browser, and keeps other floats", () => {
286 setup();
287 useRightPanelStore.getState().openBrowser(ref, "tab_panel");
288 useRightPanelStore.getState().close(ref);
289 usePreviewMiniPlayerStore.getState().open(ref, browserMiniPlayerSource("tab_panel"));
290 dockFloatingPreviewInPanel(ref);
291 expect(miniPlayerSource()).toEqual(browserMiniPlayerSource("tab_panel"));
292
293 useRightPanelStore.getState().toggleVisibility(ref);
294 dockFloatingPreviewInPanel(ref);
295 expect(miniPlayerSource()).toBeUndefined();
296
297 usePreviewMiniPlayerStore.getState().open(ref, browserMiniPlayerSource("tab_other"));
298 dockFloatingPreviewInPanel(ref);
299 expect(miniPlayerSource()).toEqual(browserMiniPlayerSource("tab_other"));
300 });
301});
302
303describe("revealServerTabs", () => {
304 const tab = (tabId: string, force?: boolean): PreviewSessionSnapshot => ({
305 threadId: "thread-1",
306 tabId,
307 navStatus: { _tag: "Loading", url: "http://localhost:5173/", title: "" },
308 canGoBack: false,
309 canGoForward: false,
310 updatedAt: "2026-01-01T00:00:00.000Z",
311 runtime: "server",
312 reveal: true,
313 ...(force === undefined ? {} : { revealRequest: { id: "r1", force } }),
314 });
315 const floatingTabId = () => {
316 const source = miniPlayerSource();
317 return source?.kind === "browser" ? source.tabId : null;
318 };
319
320 it("floats revealed tabs, and only forced ones when floating previews are off", () => {
321 setup();
322 revealServerTabs(ref, [tab("tab_plain")], { autoShowFloatingPreview: false });
323 expect(floatingTabId()).toBeNull();
324 revealServerTabs(ref, [tab("tab_forced", true)], { autoShowFloatingPreview: false });
325 expect(floatingTabId()).toBe("tab_forced");
326 });
327
328 it("focuses a tab already in the panel instead of floating it when forced", () => {
329 setup();
330 useRightPanelStore.getState().openBrowser(ref, "tab_a");
331 const browserSurfaceId = useRightPanelStore.getState().byThreadKey[threadKey]?.activeSurfaceId;
332 useRightPanelStore.getState().open(ref, "diff");
333
334 revealServerTabs(ref, [tab("tab_a", false)], { autoShowFloatingPreview: true });
335 expect(useRightPanelStore.getState().byThreadKey[threadKey]?.activeSurfaceId).not.toBe(
336 browserSurfaceId,
337 );
338 const userActionRevision = useRightPanelStore.getState().getUserActionRevision(ref);
339 revealServerTabs(ref, [tab("tab_a", true)], { autoShowFloatingPreview: true });
340 expect(useRightPanelStore.getState().byThreadKey[threadKey]?.activeSurfaceId).toBe(
341 browserSurfaceId,
342 );
343 expect(floatingTabId()).toBeNull();
344 // A user action moves keyboard focus into the panel; an agent reveal must not.
345 expect(useRightPanelStore.getState().getUserActionRevision(ref)).toBe(userActionRevision);
346 });
347});
348
349describe("followPreviewSessions", () => {
350 const snapshot = (tabId: string, reveal = true): PreviewSessionSnapshot => ({
351 threadId: "thread-1",
352 tabId,
353 navStatus: { _tag: "Loading", url: "http://localhost:5173/", title: "" },
354 canGoBack: false,
355 canGoForward: false,
356 updatedAt: "2026-01-01T00:00:00.000Z",
357 runtime: "server",
358 reveal,
359 });
360 const previewState = (sessions: ReadonlyArray<PreviewSessionSnapshot>, listLoaded = true) => ({
361 ...previewStateTesting.EMPTY_THREAD_PREVIEW_STATE,
362 listLoaded,
363 sessions: Object.fromEntries(sessions.map((entry) => [entry.tabId, entry])),
364 });
365 const browserTabs = () =>
366 useRightPanelStore
367 .getState()
368 .byThreadKey[threadKey]?.surfaces.filter((surface) => surface.kind === "preview")
369 .map((surface) => surface.id) ?? [];
370
371 it("adds visible sessions as tabs and drops tabs whose session ended", () => {
372 setup();
373 useRightPanelStore.getState().openBrowser(ref, "tab_gone");
374 followPreviewSessions(ref, previewState([snapshot("tab_a"), snapshot("tab_hidden", false)]));
375 expect(browserTabs()).toEqual(["browser:tab_a"]);
376 });
377
378 it("waits for the first server list before treating missing sessions as closed", () => {
379 setup();
380 useRightPanelStore.getState().openBrowser(ref, "tab_a");
381 usePreviewMiniPlayerStore.getState().open(ref, browserMiniPlayerSource("tab_a"));
382 followPreviewSessions(ref, previewState([], false));
383 expect(browserTabs()).toEqual(["browser:tab_a"]);
384 expect(miniPlayerSource()).toMatchObject({ kind: "browser", tabId: "tab_a" });
385
386 followPreviewSessions(ref, previewState([]));
387 expect(browserTabs()).toEqual([]);
388 expect(miniPlayerSource()).toBeUndefined();
389 });
390});
391
392describe("startAgentOpenedPreviews", () => {
393 const serverEpoch = "server-a";
394 const serverTab = (overrides: Partial<PreviewSessionSnapshot> = {}): PreviewSessionSnapshot => ({
395 threadId: "thread-1",
396 tabId: "tab_a",
397 navStatus: { _tag: "Loading", url: "http://localhost:5173/", title: "" },
398 canGoBack: false,
399 canGoForward: false,
400 updatedAt: "2026-01-01T00:00:00.000Z",
401 runtime: "server",
402 reveal: true,
403 ...overrides,
404 });
405 const following = () => {
406 setup();
407 return { [Symbol.dispose]: startAgentOpenedPreviews() };
408 };
409 const navigated = (revision: number, snapshot: PreviewSessionSnapshot) =>
410 applyPreviewServerEvent(ref, {
411 type: "navigated",
412 threadId: "thread-1",
413 tabId: snapshot.tabId,
414 createdAt: snapshot.updatedAt,
415 snapshot,
416 serverEpoch,
417 revision,
418 });
419 const floatingTabId = () => {
420 const source = miniPlayerSource();
421 return source?.kind === "browser" ? source.tabId : null;
422 };
423 const browserTabs = (threadKeyToRead = threadKey) =>
424 useRightPanelStore
425 .getState()
426 .byThreadKey[threadKeyToRead]?.surfaces.filter((surface) => surface.kind === "preview")
427 .map((surface) => surface.id);
428
429 it("treats the first list as a baseline and floats tabs opened later", () => {
430 using _following = following();
431 reconcilePreviewServerSessions(ref, {
432 sessions: [serverTab({ tabId: "tab_restored" })],
433 serverEpoch,
434 revision: 1,
435 });
436 expect(floatingTabId()).toBeNull();
437 expect(browserTabs()).toEqual(["browser:tab_restored"]);
438
439 const opened = serverTab({ tabId: "tab_agent" });
440 applyPreviewServerEvent(ref, {
441 type: "opened",
442 threadId: "thread-1",
443 tabId: opened.tabId,
444 createdAt: opened.updatedAt,
445 snapshot: opened,
446 serverEpoch,
447 revision: 2,
448 });
449 expect(floatingTabId()).toBe("tab_agent");
450 });
451
452 it("reveals an existing tab only for a new reveal request", () => {
453 using _following = following();
454 const tab = serverTab({ revealRequest: { id: "r1", force: false } });
455 reconcilePreviewServerSessions(ref, { sessions: [tab], serverEpoch, revision: 1 });
456
457 navigated(2, { ...tab, updatedAt: "2026-01-01T00:00:01.000Z" });
458 expect(floatingTabId()).toBeNull();
459
460 navigated(3, {
461 ...tab,
462 revealRequest: { id: "r2", force: true },
463 updatedAt: "2026-01-01T00:00:02.000Z",
464 });
465 expect(useRightPanelStore.getState().byThreadKey[threadKey]?.activeSurfaceId).toBe(
466 "browser:tab_a",
467 );
468 });
469
470 it("never reveals tabs this client opened, desktop tabs, or a tab whose close failed", () => {
471 using _following = following();
472 const tab = serverTab({ tabId: "tab_closing" });
473 reconcilePreviewServerSessions(ref, { sessions: [tab], serverEpoch, revision: 1 });
474 applyPreviewServerSnapshot(ref, serverTab({ tabId: "tab_own", reveal: undefined }));
475 applyPreviewServerSnapshot(ref, { ...serverTab({ tabId: "tab_desktop" }), runtime: "desktop" });
476 beginPreviewSessionClose(ref, tab.tabId);
477 cancelPreviewSessionClose(ref, tab, tab.tabId);
478 expect(floatingTabId()).toBeNull();
479 });
480
481 it("follows background threads and closes the floating browser when its session ends", () => {
482 using _following = following();
483 const other = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-2"));
484 reconcilePreviewServerSessions(other, {
485 sessions: [serverTab({ threadId: "thread-2", tabId: "tab_b" })],
486 serverEpoch,
487 revision: 1,
488 });
489 expect(browserTabs(scopedThreadKey(other))).toEqual(["browser:tab_b"]);
490
491 reconcilePreviewServerSessions(ref, { sessions: [], serverEpoch, revision: 1 });
492 const opened = serverTab();
493 applyPreviewServerEvent(ref, {
494 type: "opened",
495 threadId: "thread-1",
496 tabId: opened.tabId,
497 createdAt: opened.updatedAt,
498 snapshot: opened,
499 serverEpoch,
500 revision: 2,
501 });
502 expect(floatingTabId()).toBe("tab_a");
503 applyPreviewServerEvent(ref, {
504 type: "closed",
505 threadId: "thread-1",
506 tabId: opened.tabId,
507 createdAt: opened.updatedAt,
508 serverEpoch,
509 revision: 3,
510 });
511 expect(floatingTabId()).toBeNull();
512 });
513});