Open History to see the last commit
1import {
2 BUILT_IN_BROWSER_PROFILES,
3 DEFAULT_BROWSER_PROFILE_ID,
4 DEFAULT_PREVIEW_APPEARANCE,
5 DEFAULT_PREVIEW_ZOOM_FACTOR,
6 EnvironmentId,
7 FILL_PREVIEW_VIEWPORT,
8 ThreadId,
9} from "@t3tools/contracts";
10import { type ComponentProps } from "react";
11import { describe, expect, it, vi } from "vite-plus/test";
12import { page, userEvent } from "vite-plus/test/browser";
13
14import "~/index.css";
15import { act, render } from "../../../test/render";
16
17import type { PreviewableServer } from "./useDiscoveredLocalServers";
18
19const mocks = vi.hoisted(() => ({
20 navigate: vi.fn(async (_tabId: string, _url: string): Promise<void> => undefined),
21 rememberPreviewUrl: vi.fn(),
22 readPreparedConnection: vi.fn(() => ({ httpBaseUrl: "http://172.25.85.75:3773" })),
23 readEnvironmentScope: vi.fn((_environmentId?: unknown, _scope?: unknown) => true),
24 setAnnotationSendEnabled: vi.fn(async (_tabId: string, _enabled: boolean): Promise<void> => {}),
25 cancelPickElement: vi.fn(async (_tabId: string) => undefined),
26 openPictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
27 closePictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
28 pickElement: vi.fn(),
29 addPreviewAnnotation: vi.fn(),
30 addImage: vi.fn(),
31 toast: vi.fn(),
32 pictureInPicture: false,
33 showEmptyState: false,
34 loading: false,
35 nativeServerTab: false,
36 serverEpoch: null as string | null,
37 servers: [] as PreviewableServer[],
38 recordingTabIds: new Set<string>(),
39 recordingRuntimeTabId: null as string | null,
40 recordVisitForThread: vi.fn(),
41}));
42
43const STUB_BROWSER_DEFAULTS = {
44 viewport: FILL_PREVIEW_VIEWPORT,
45 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
46 appearance: DEFAULT_PREVIEW_APPEARANCE,
47 autoShowFloatingPreview: true,
48 profiles: BUILT_IN_BROWSER_PROFILES,
49 profileId: DEFAULT_BROWSER_PROFILE_ID,
50};
51
52// The desktop bridge only exists inside Electron; the view reads it once at import.
53vi.mock(import("./previewBridge"), async (original) => ({
54 ...(await original()),
55 previewBridge: {
56 navigate: mocks.navigate,
57 pickElement: mocks.pickElement,
58 setAnnotationSendEnabled: mocks.setAnnotationSendEnabled,
59 cancelPickElement: mocks.cancelPickElement,
60 refresh: vi.fn(async () => undefined),
61 goBack: vi.fn(async () => undefined),
62 goForward: vi.fn(async () => undefined),
63 hardReload: vi.fn(async () => undefined),
64 openDevTools: vi.fn(async () => undefined),
65 setColorScheme: vi.fn(async () => undefined),
66 zoomIn: vi.fn(async () => undefined),
67 zoomOut: vi.fn(async () => undefined),
68 resetZoom: vi.fn(async () => undefined),
69 clearCookies: vi.fn(async () => undefined),
70 clearCache: vi.fn(async () => undefined),
71 pictureInPicture: {
72 open: mocks.openPictureInPicture,
73 close: mocks.closePictureInPicture,
74 },
75 } as never,
76}));
77vi.mock(import("~/browserHistoryStore"), async (original) => ({
78 ...(await original()),
79 recordVisitForThread: mocks.recordVisitForThread,
80}));
81vi.mock(import("~/state/session"), async (original) => ({
82 ...(await original()),
83 readPreparedConnection: mocks.readPreparedConnection as never,
84 readEnvironmentScope: mocks.readEnvironmentScope,
85 useEnvironmentScope: mocks.readEnvironmentScope,
86}));
87vi.mock(import("~/browser/browserDefaults"), async (original) => ({
88 ...(await original()),
89 useBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
90 getBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
91}));
92vi.mock(import("~/previewStateStore"), async (original) => ({
93 ...(await original()),
94 rememberPreviewUrl: mocks.rememberPreviewUrl,
95 useThreadPreviewState: (() => ({
96 activeTabId: "tab-1",
97 serverEpoch: mocks.serverEpoch,
98 desktopByTabId: {
99 "tab-1": {
100 hasWebContents: true,
101 canGoBack: false,
102 canGoForward: false,
103 loading: mocks.loading,
104 zoomFactor: 1,
105 pictureInPicture: mocks.pictureInPicture,
106 colorScheme: "system",
107 audioMuted: false,
108 audible: false,
109 controller: "none",
110 },
111 },
112 recentlySeenUrls: [],
113 sessions: mocks.showEmptyState
114 ? {}
115 : {
116 "tab-1": {
117 threadId: "thread-1",
118 tabId: "tab-1",
119 runtime: mocks.nativeServerTab ? "server" : "desktop",
120 navStatus: { _tag: "Success", url: "http://example.com/", title: "Example" },
121 canGoBack: false,
122 canGoForward: false,
123 updatedAt: "2026-07-13T00:00:00.000Z",
124 },
125 },
126 })) as never,
127}));
128vi.mock(import("~/state/environments"), async (original) => ({
129 ...(await original()),
130 useEnvironment: (() => ({ label: "WSL" })) as never,
131 useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
132 usePrimaryEnvironmentId: () => null,
133}));
134vi.mock(import("~/browser/browserRecording"), async (original) => ({
135 ...(await original()),
136 findActiveBrowserRecordingRuntimeTabId: () => mocks.recordingRuntimeTabId,
137 useActiveBrowserRecordingTabIds: () => mocks.recordingTabIds,
138}));
139vi.mock(import("~/components/ui/toast"), async (original) => {
140 const actual = await original();
141 return { ...actual, toastManager: { ...actual.toastManager, add: mocks.toast } };
142});
143vi.mock(import("./useDiscoveredLocalServers"), async (original) => ({
144 ...(await original()),
145 useDiscoveredLocalServers: () => mocks.servers,
146}));
147vi.mock(import("./usePreviewSession"), async (original) => ({
148 ...(await original()),
149 usePreviewSession: () => {},
150}));
151
152vi.mock(import("~/browser/previewRuntime"), async (original) => ({
153 ...(await original()),
154 useRendersServerTabNatively: () => mocks.nativeServerTab,
155}));
156
157vi.mock(import("~/browser/browserViewportActions"), { spy: true });
158
159import { useComposerDraftStore } from "~/composerDraftStore";
160import { useBrowserPointerStore } from "~/browser/browserPointerStore";
161import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
162import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
163import { dispatchPreviewAction } from "./previewActionBus";
164import { PreviewView } from "./PreviewView";
165
166const TEST_THREAD_REF = {
167 environmentId: EnvironmentId.make("environment-1"),
168 threadId: ThreadId.make("thread-1"),
169} as const;
170const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
171
172function view(onSendAnnotation?: ComponentProps<typeof PreviewView>["onSendAnnotation"]) {
173 return (
174 <PreviewView
175 threadRef={TEST_THREAD_REF}
176 tabId="tab-1"
177 visible
178 {...(onSendAnnotation ? { onSendAnnotation } : {})}
179 />
180 );
181}
182
183function annotation(id: string, screenshot: unknown = null) {
184 return {
185 id,
186 pageUrl: "https://example.com/dashboard",
187 pageTitle: "Dashboard",
188 comment: "Tighten this spacing",
189 elements: [],
190 regions: [],
191 strokes: [],
192 styleChanges: [],
193 screenshot,
194 createdAt: "2026-07-27T00:00:00.000Z",
195 };
196}
197
198// The mocked modules and stores are shared by the whole file, so every test starts by
199// resetting them.
200function setup() {
201 vi.clearAllMocks();
202 mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
203 mocks.setAnnotationSendEnabled.mockReset().mockResolvedValue(undefined);
204 mocks.pickElement.mockReset();
205 mocks.pictureInPicture = false;
206 mocks.showEmptyState = false;
207 mocks.loading = false;
208 mocks.nativeServerTab = false;
209 mocks.serverEpoch = null;
210 mocks.servers = [];
211 mocks.recordingTabIds = new Set();
212 mocks.recordingRuntimeTabId = null;
213 useComposerDraftStore.setState({
214 addPreviewAnnotation: mocks.addPreviewAnnotation,
215 addImage: mocks.addImage,
216 });
217 usePreviewMiniPlayerStore.setState({ byThreadKey: {} });
218 useBrowserPointerStore.setState({ byTabId: {} });
219}
220
221describe("PreviewView", () => {
222 it("retains the annotation locally when its own environment loses access during capture", async () => {
223 setup();
224 const picked = annotation("annotation-revoked");
225 const onSendAnnotation = vi.fn();
226 let submitPick: (() => void) | undefined;
227 mocks.pickElement.mockImplementationOnce(
228 () =>
229 new Promise((resolve) => {
230 submitPick = () => resolve({ annotation: picked, submission: "send" });
231 }),
232 );
233 await using screen = await render(view(onSendAnnotation));
234 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
235 await vi.waitFor(() => expect(submitPick).toBeDefined());
236 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
237
238 mocks.readEnvironmentScope.mockImplementation(
239 (environmentId?: unknown) => environmentId !== TEST_THREAD_REF.environmentId,
240 );
241 await screen.rerender(view(onSendAnnotation));
242 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, false);
243 await act(async () => submitPick!());
244 await vi.waitFor(() =>
245 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, picked),
246 );
247 expect(onSendAnnotation).not.toHaveBeenCalled();
248
249 mocks.readEnvironmentScope.mockReturnValue(true);
250 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
251 await screen.rerender(view(onSendAnnotation));
252 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
253 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
254 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
255 });
256
257 it("still sends annotation text when the picked element's crop is malformed", async () => {
258 setup();
259 const picked = annotation("annotation-2", {
260 dataUrl: "data:image/png;base64,%%%",
261 width: 10,
262 height: 10,
263 cropRect: { x: 0, y: 0, width: 10, height: 10 },
264 });
265 const onSendAnnotation = vi.fn();
266 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
267 await using _screen = await render(view(onSendAnnotation));
268 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
269
270 const sent = { ...picked, screenshot: null };
271 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
272 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
273 expect(mocks.addImage).not.toHaveBeenCalled();
274 });
275
276 it("focuses the address bar each time the focus-url shortcut fires", async () => {
277 setup();
278 await using _screen = await render(view());
279 const address = page.getByRole("textbox");
280
281 act(() => dispatchPreviewAction("focus-url"));
282 await expect.element(address).toHaveFocus();
283
284 (address.element() as HTMLInputElement).blur();
285 await expect.element(address).not.toHaveFocus();
286 act(() => dispatchPreviewAction("focus-url"));
287 await expect.element(address).toHaveFocus();
288 });
289});