Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PreviewView.browser.test.tsx

274 lines10.0 KB

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 { PreviewView } from "./PreviewView";
164​
165const TEST_THREAD_REF = {
166 environmentId: EnvironmentId.make("environment-1"),
167 threadId: ThreadId.make("thread-1"),
168} as const;
169const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
170​
171function view(onSendAnnotation?: ComponentProps<typeof PreviewView>["onSendAnnotation"]) {
172 return (
173 <PreviewView
174 threadRef={TEST_THREAD_REF}
175 tabId="tab-1"
176 visible
177 {...(onSendAnnotation ? { onSendAnnotation } : {})}
178 />
179 );
181​
182function annotation(id: string, screenshot: unknown = null) {
183 return {
184 id,
185 pageUrl: "https://example.com/dashboard",
186 pageTitle: "Dashboard",
187 comment: "Tighten this spacing",
188 elements: [],
189 regions: [],
190 strokes: [],
191 styleChanges: [],
192 screenshot,
193 createdAt: "2026-07-27T00:00:00.000Z",
194 };
196​
197// The mocked modules and stores are shared by the whole file, so every test starts by
198// resetting them.
199function setup() {
200 vi.clearAllMocks();
201 mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
202 mocks.setAnnotationSendEnabled.mockReset().mockResolvedValue(undefined);
203 mocks.pickElement.mockReset();
204 mocks.pictureInPicture = false;
205 mocks.showEmptyState = false;
206 mocks.loading = false;
207 mocks.nativeServerTab = false;
208 mocks.serverEpoch = null;
209 mocks.servers = [];
210 mocks.recordingTabIds = new Set();
211 mocks.recordingRuntimeTabId = null;
212 useComposerDraftStore.setState({
213 addPreviewAnnotation: mocks.addPreviewAnnotation,
214 addImage: mocks.addImage,
215 });
216 usePreviewMiniPlayerStore.setState({ byThreadKey: {} });
217 useBrowserPointerStore.setState({ byTabId: {} });
219​
220describe("PreviewView", () => {
221 it("retains the annotation locally when its own environment loses access during capture", async () => {
222 setup();
223 const picked = annotation("annotation-revoked");
224 const onSendAnnotation = vi.fn();
225 let submitPick: (() => void) | undefined;
226 mocks.pickElement.mockImplementationOnce(
227 () =>
228 new Promise((resolve) => {
229 submitPick = () => resolve({ annotation: picked, submission: "send" });
230 }),
231 );
232 await using screen = await render(view(onSendAnnotation));
233 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
234 await vi.waitFor(() => expect(submitPick).toBeDefined());
235 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
236​
237 mocks.readEnvironmentScope.mockImplementation(
238 (environmentId?: unknown) => environmentId !== TEST_THREAD_REF.environmentId,
239 );
240 await screen.rerender(view(onSendAnnotation));
241 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, false);
242 await act(async () => submitPick!());
243 await vi.waitFor(() =>
244 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, picked),
245 );
246 expect(onSendAnnotation).not.toHaveBeenCalled();
247​
248 mocks.readEnvironmentScope.mockReturnValue(true);
249 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
250 await screen.rerender(view(onSendAnnotation));
251 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
252 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
253 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
254 });
255​
256 it("still sends annotation text when the picked element's crop is malformed", async () => {
257 setup();
258 const picked = annotation("annotation-2", {
259 dataUrl: "data:image/png;base64,%%%",
260 width: 10,
261 height: 10,
262 cropRect: { x: 0, y: 0, width: 10, height: 10 },
263 });
264 const onSendAnnotation = vi.fn();
265 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
266 await using _screen = await render(view(onSendAnnotation));
267 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
268​
269 const sent = { ...picked, screenshot: null };
270 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
271 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
272 expect(mocks.addImage).not.toHaveBeenCalled();
273 });
274});