Open History to see the last commit
1import type {
2 PreviewCloseInput,
3 PreviewSessionSnapshot,
4 ScopedThreadRef,
5} from "@t3tools/contracts";
6import { AsyncResult } from "effect/reactivity";
7import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
8
9import {
10 applyPreviewServerSnapshot,
11 readThreadPreviewState,
12 resetPreviewStateForTests,
13} from "~/previewStateStore";
14
15import { useClosedViewStore } from "~/closedViewStore";
16
17import { closePreviewSession } from "./closePreviewSession";
18
19const threadRef = {
20 environmentId: "local" as ScopedThreadRef["environmentId"],
21 threadId: "thread-1" as ScopedThreadRef["threadId"],
22};
23
24const snapshot: PreviewSessionSnapshot = {
25 threadId: threadRef.threadId,
26 tabId: "tab-1",
27 navStatus: {
28 _tag: "Success",
29 url: "http://localhost:3000/",
30 title: "Local app",
31 },
32 canGoBack: false,
33 canGoForward: false,
34 updatedAt: "2026-06-18T19:00:00.000Z",
35};
36
37beforeEach(() => {
38 resetPreviewStateForTests();
39 useClosedViewStore.setState({ entries: [] });
40});
41
42describe("closePreviewSession", () => {
43 it("suppresses stale server snapshots while the close is in flight", async () => {
44 applyPreviewServerSnapshot(threadRef, snapshot);
45 let finishClose: (() => void) | undefined;
46 const closePreview = vi.fn(
47 (_input: PreviewCloseInput) =>
48 new Promise<ReturnType<typeof AsyncResult.success<void>>>((resolve) => {
49 finishClose = () => resolve(AsyncResult.success(undefined));
50 }),
51 );
52
53 const closing = closePreviewSession({
54 closePreview: ({ input }) => closePreview(input),
55 snapshot,
56 tabId: snapshot.tabId,
57 threadRef,
58 });
59
60 expect(useClosedViewStore.getState().entries).toEqual([]);
61 expect(readThreadPreviewState(threadRef).sessions).toEqual({});
62 applyPreviewServerSnapshot(threadRef, snapshot);
63 expect(readThreadPreviewState(threadRef).sessions).toEqual({});
64
65 finishClose?.();
66 await closing;
67 expect(useClosedViewStore.getState().entries).toMatchObject([
68 { kind: "browser", threadRef, snapshot },
69 ]);
70 expect(closePreview).toHaveBeenCalledWith({ threadId: "thread-1", tabId: "tab-1" });
71 });
72});