@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 484 lines 18.1 KB
Raw
1 import {
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";
10 import { type ComponentProps } from "react";
11 import { describe, expect, it, vi } from "vite-plus/test";
12 import { page, userEvent } from "vite-plus/test/browser";
13
14 import "~/index.css";
15 import { act, render } from "../../../test/render";
16
17 import type { PreviewableServer } from "./useDiscoveredLocalServers";
18
19 const 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 pictureInPicture: false,
32 showEmptyState: false,
33 idleServerTab: false,
34 idleDesktopTab: false,
35 idleDesktopOverlay: false,
36 loading: false,
37 nativeServerTab: false,
38 streamedServerTab: false,
39 serverEpoch: null as string | null,
40 servers: [] as PreviewableServer[],
41 recordingTabIds: new Set<string>(),
42 recordingRuntimeTabId: null as string | null,
43 recordVisitForThread: vi.fn(),
44 }));
45
46 const STUB_BROWSER_DEFAULTS = {
47 viewport: FILL_PREVIEW_VIEWPORT,
48 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
49 appearance: DEFAULT_PREVIEW_APPEARANCE,
50 autoShowFloatingPreview: true,
51 profiles: BUILT_IN_BROWSER_PROFILES,
52 profileId: DEFAULT_BROWSER_PROFILE_ID,
53 };
54
55 // The desktop bridge only exists inside Electron; the view reads it once at import.
56 vi.mock(import("./previewBridge"), async (original) => ({
57 ...(await original()),
58 previewBridge: {
59 navigate: mocks.navigate,
60 pickElement: mocks.pickElement,
61 annotationVoice: { onEvent: () => () => {}, update: async () => {} },
62 setAnnotationSendEnabled: mocks.setAnnotationSendEnabled,
63 cancelPickElement: mocks.cancelPickElement,
64 refresh: vi.fn(async () => undefined),
65 goBack: vi.fn(async () => undefined),
66 goForward: vi.fn(async () => undefined),
67 hardReload: vi.fn(async () => undefined),
68 openDevTools: vi.fn(async () => undefined),
69 setColorScheme: vi.fn(async () => undefined),
70 zoomIn: vi.fn(async () => undefined),
71 zoomOut: vi.fn(async () => undefined),
72 resetZoom: vi.fn(async () => undefined),
73 clearCookies: vi.fn(async () => undefined),
74 clearCache: vi.fn(async () => undefined),
75 pictureInPicture: {
76 open: mocks.openPictureInPicture,
77 close: mocks.closePictureInPicture,
78 },
79 findInPage: vi.fn(async () => undefined),
80 stopFindInPage: vi.fn(async () => undefined),
81 onFindResult: vi.fn(() => () => undefined),
82 } as never,
83 }));
84 vi.mock(import("~/browserHistoryStore"), async (original) => ({
85 ...(await original()),
86 recordVisitForThread: mocks.recordVisitForThread,
87 }));
88 vi.mock(import("~/state/session"), async (original) => ({
89 ...(await original()),
90 readPreparedConnection: mocks.readPreparedConnection as never,
91 readEnvironmentScope: mocks.readEnvironmentScope,
92 useEnvironmentScope: mocks.readEnvironmentScope,
93 }));
94 vi.mock(import("~/browser/browserDefaults"), async (original) => ({
95 ...(await original()),
96 useBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
97 getBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
98 }));
99 vi.mock(import("~/previewStateStore"), async (original) => ({
100 ...(await original()),
101 rememberPreviewUrl: mocks.rememberPreviewUrl,
102 useThreadPreviewState: (() => ({
103 activeTabId: "tab-1",
104 serverEpoch: mocks.serverEpoch,
105 desktopByTabId: {
106 "tab-1": {
107 hasWebContents: true,
108 navStatus: mocks.idleDesktopOverlay
109 ? { _tag: "Idle" }
110 : { _tag: "Success", url: "http://example.com/", title: "Example" },
111 canGoBack: false,
112 canGoForward: false,
113 loading: mocks.loading,
114 zoomFactor: 1,
115 pictureInPicture: mocks.pictureInPicture,
116 colorScheme: "system",
117 audioMuted: false,
118 audible: false,
119 controller: "none",
120 },
121 },
122 recentlySeenUrls: [],
123 sessions: mocks.showEmptyState
124 ? {}
125 : mocks.idleServerTab || mocks.idleDesktopTab
126 ? {
127 "tab-1": {
128 threadId: "thread-1",
129 tabId: "tab-1",
130 runtime: mocks.idleDesktopTab ? "desktop" : "server",
131 navStatus: { _tag: "Idle" },
132 canGoBack: false,
133 canGoForward: false,
134 updatedAt: "2026-07-13T00:00:00.000Z",
135 },
136 }
137 : {
138 "tab-1": {
139 threadId: "thread-1",
140 tabId: "tab-1",
141 runtime: mocks.nativeServerTab || mocks.streamedServerTab ? "server" : "desktop",
142 navStatus: { _tag: "Success", url: "http://example.com/", title: "Example" },
143 canGoBack: false,
144 canGoForward: false,
145 updatedAt: "2026-07-13T00:00:00.000Z",
146 },
147 },
148 })) as never,
149 }));
150 vi.mock(import("~/state/environments"), async (original) => ({
151 ...(await original()),
152 useEnvironment: (() => ({ label: "WSL" })) as never,
153 useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
154 usePrimaryEnvironmentId: () => null,
155 }));
156 vi.mock(import("~/browser/browserRecording"), async (original) => ({
157 ...(await original()),
158 findActiveBrowserRecordingRuntimeTabId: () => mocks.recordingRuntimeTabId,
159 useActiveBrowserRecordingTabIds: () => mocks.recordingTabIds,
160 }));
161 vi.mock(import("./useDiscoveredLocalServers"), async (original) => ({
162 ...(await original()),
163 useDiscoveredLocalServers: () => mocks.servers,
164 }));
165 vi.mock(import("./usePreviewSession"), async (original) => ({
166 ...(await original()),
167 usePreviewSession: () => {},
168 }));
169
170 vi.mock(import("~/browser/previewRuntime"), async (original) => ({
171 ...(await original()),
172 useRendersServerTabNatively: () => mocks.nativeServerTab,
173 }));
174
175 vi.mock(import("~/browser/browserViewportActions"), { spy: true });
176 // The real surface opens a preview stream to the server; only its box matters here.
177 vi.mock(import("~/browser/ServerBrowserSurface"), async (original) => ({
178 ...(await original()),
179 ServerBrowserSurface: ((props: { className?: string }) => (
180 <div data-testid="server-browser-surface" className={props.className} />
181 )) as never,
182 }));
183
184 import { useComposerDraftStore } from "~/composerDraftStore";
185 import { commitBrowserViewportChange } from "~/browser/browserViewportActions";
186 import { resolveResponsiveBrowserViewportSize } from "~/browser/browserViewportLayout";
187 import { useBrowserPointerStore } from "~/browser/browserPointerStore";
188 import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
189 import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
190 import { dispatchPreviewAction } from "./previewActionBus";
191 import { PreviewView } from "./PreviewView";
192 import { ToastProvider } from "~/components/ui/toast";
193
194 const TEST_THREAD_REF = {
195 environmentId: EnvironmentId.make("environment-1"),
196 threadId: ThreadId.make("thread-1"),
197 } as const;
198 const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
199
200 function view(onSendAnnotation?: ComponentProps<typeof PreviewView>["onSendAnnotation"]) {
201 return (
202 <PreviewView
203 threadRef={TEST_THREAD_REF}
204 tabId="tab-1"
205 visible
206 {...(onSendAnnotation ? { onSendAnnotation } : {})}
207 />
208 );
209 }
210
211 function annotation(id: string, screenshot: unknown = null) {
212 return {
213 id,
214 pageUrl: "https://example.com/dashboard",
215 pageTitle: "Dashboard",
216 comment: "Tighten this spacing",
217 elements: [],
218 regions: [],
219 strokes: [],
220 styleChanges: [],
221 screenshot,
222 createdAt: "2026-07-27T00:00:00.000Z",
223 };
224 }
225
226 // The mocked modules and stores are shared by the whole file, so every test starts by
227 // resetting them.
228 function setup() {
229 vi.clearAllMocks();
230 mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
231 mocks.setAnnotationSendEnabled.mockReset().mockResolvedValue(undefined);
232 mocks.pickElement.mockReset();
233 mocks.pictureInPicture = false;
234 mocks.showEmptyState = false;
235 mocks.idleServerTab = false;
236 mocks.idleDesktopTab = false;
237 mocks.idleDesktopOverlay = false;
238 mocks.loading = false;
239 mocks.nativeServerTab = false;
240 mocks.streamedServerTab = false;
241 mocks.serverEpoch = null;
242 mocks.servers = [];
243 mocks.recordingTabIds = new Set();
244 mocks.recordingRuntimeTabId = null;
245 useComposerDraftStore.setState({
246 addPreviewAnnotation: mocks.addPreviewAnnotation,
247 addImage: mocks.addImage,
248 });
249 usePreviewMiniPlayerStore.setState({ byThreadKey: {} });
250 useBrowserPointerStore.setState({ byTabId: {} });
251 }
252
253 describe("PreviewView", () => {
254 it.each(["mailto:alice@example.com", "http://"])(
255 "reports rejected address %s without navigating or recording it",
256 async (address) => {
257 setup();
258 await using _screen = await render(<ToastProvider timeout={0}>{view()}</ToastProvider>);
259 const input = page.getByPlaceholder("Search or enter URL");
260 await input.fill(address);
261 await userEvent.keyboard("{Enter}");
262
263 await expect.element(page.getByText("Could not open this address")).toBeVisible();
264 await expect.element(page.getByText("Enter an http or https URL.")).toBeVisible();
265 expect(mocks.navigate).not.toHaveBeenCalled();
266 expect(mocks.recordVisitForThread).not.toHaveBeenCalled();
267 await userEvent.click(page.getByRole("button", { name: "Dismiss notification" }));
268 },
269 );
270
271 it("shows a desktop navigation before its backend status echo arrives", async () => {
272 setup();
273 mocks.idleDesktopTab = true;
274 await using _screen = await render(view());
275 await expect
276 .element(page.getByPlaceholder("Search or enter URL"))
277 .toHaveValue("http://example.com/");
278 await expect.element(page.getByText("No preview yet")).not.toBeInTheDocument();
279 await expect.element(page.getByRole("button", { name: "Annotate preview" })).toBeVisible();
280 });
281
282 it("keeps the server navigation while the new desktop tab is still idle", async () => {
283 setup();
284 mocks.idleDesktopOverlay = true;
285 await using _screen = await render(view());
286 await expect
287 .element(page.getByPlaceholder("Search or enter URL"))
288 .toHaveValue("http://example.com/");
289 await expect.element(page.getByText("No preview yet")).not.toBeInTheDocument();
290 });
291
292 it("keeps the address in the bar when Enter commits an IME composition", async () => {
293 setup();
294 await using _screen = await render(view());
295 const input = page.getByPlaceholder("Search or enter URL");
296 await input.fill("https://example.com/pinyin");
297
298 const enter = new KeyboardEvent("keydown", {
299 key: "Enter",
300 code: "Enter",
301 isComposing: true,
302 bubbles: true,
303 cancelable: true,
304 });
305 Object.defineProperty(enter, "keyCode", { value: 229 });
306 act(() => {
307 input.element().dispatchEvent(enter);
308 });
309
310 await expect.element(input).toHaveFocus();
311 await expect.element(input).toHaveValue("https://example.com/pinyin");
312 expect(mocks.navigate).not.toHaveBeenCalled();
313 expect(enter.defaultPrevented).toBe(true);
314 });
315
316 it("retains the annotation locally when its own environment loses access during capture", async () => {
317 setup();
318 const picked = annotation("annotation-revoked");
319 const onSendAnnotation = vi.fn();
320 let submitPick: (() => void) | undefined;
321 mocks.pickElement.mockImplementationOnce(
322 () =>
323 new Promise((resolve) => {
324 submitPick = () => resolve({ annotation: picked, submission: "send" });
325 }),
326 );
327 await using screen = await render(view(onSendAnnotation));
328 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
329 await vi.waitFor(() => expect(submitPick).toBeDefined());
330 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
331
332 mocks.readEnvironmentScope.mockImplementation(
333 (environmentId?: unknown) => environmentId !== TEST_THREAD_REF.environmentId,
334 );
335 await screen.rerender(view(onSendAnnotation));
336 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, false);
337 await act(async () => submitPick!());
338 await vi.waitFor(() =>
339 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, picked),
340 );
341 expect(onSendAnnotation).not.toHaveBeenCalled();
342
343 mocks.readEnvironmentScope.mockReturnValue(true);
344 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
345 await screen.rerender(view(onSendAnnotation));
346 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
347 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
348 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
349 });
350
351 it("still sends annotation text when the picked element's crop is malformed", async () => {
352 setup();
353 const picked = annotation("annotation-2", {
354 dataUrl: "data:image/png;base64,%%%",
355 width: 10,
356 height: 10,
357 cropRect: { x: 0, y: 0, width: 10, height: 10 },
358 });
359 const onSendAnnotation = vi.fn();
360 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
361 await using _screen = await render(view(onSendAnnotation));
362 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
363
364 const sent = { ...picked, screenshot: null };
365 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
366 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
367 expect(mocks.addImage).not.toHaveBeenCalled();
368 });
369
370 it("lets the pointer reach a local server card above an idle server-rendered tab", async () => {
371 setup();
372 mocks.idleServerTab = true;
373 mocks.servers = [
374 {
375 host: "localhost",
376 port: 8081,
377 url: "http://localhost:8081/",
378 requestedUrl: "http://localhost:8081/",
379 processName: "python3",
380 pid: 4242,
381 terminal: null,
382 source: "scanner",
383 },
384 ];
385 await using _screen = await render(<ToastProvider timeout={0}>{view()}</ToastProvider>);
386 const card = page.getByRole("button", { name: /localhost:8081/ });
387 await expect.element(card).toBeVisible();
388
389 const rect = card.element().getBoundingClientRect();
390 const hit = document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2);
391 expect(card.element().contains(hit)).toBe(true);
392 });
393
394 it("sizes the first device viewport of a streamed tab to its panel", async () => {
395 setup();
396 mocks.streamedServerTab = true;
397 await using _screen = await render(<ToastProvider timeout={0}>{view()}</ToastProvider>);
398 const surface = page.getByTestId("server-browser-surface");
399 await expect.element(surface).toBeInTheDocument();
400 const rect = surface.element().getBoundingClientRect();
401
402 await userEvent.click(page.getByRole("button", { name: "Preview menu" }));
403 await userEvent.click(page.getByRole("menuitem", { name: "Show device toolbar" }));
404
405 expect(commitBrowserViewportChange).toHaveBeenCalledWith(expect.anything(), {
406 _tag: "freeform",
407 ...resolveResponsiveBrowserViewportSize(rect, 1),
408 });
409 });
410
411 it("focuses and selects the address from forwarded desktop actions only while visible", async () => {
412 setup();
413 using stack = new DisposableStack();
414 const previousBridge = window.desktopBridge;
415 stack.defer(() => {
416 if (previousBridge) window.desktopBridge = previousBridge;
417 else delete window.desktopBridge;
418 });
419 const listeners = new Set<(action: string) => void>();
420 window.desktopBridge = {
421 getWindowZoomFactor: () => 1,
422 onMenuAction: (listener: (action: string) => void) => {
423 listeners.add(listener);
424 return () => {
425 listeners.delete(listener);
426 };
427 },
428 } as NonNullable<typeof window.desktopBridge>;
429 await using screen = await render(view());
430 const address = page.getByRole("textbox");
431 const input = address.element() as HTMLInputElement;
432 const forward = () =>
433 act(() => {
434 listeners.forEach((listener) => listener("preview.focusUrl"));
435 });
436
437 await forward();
438 await expect.element(address).toHaveFocus();
439 expect(input.selectionStart).toBe(0);
440 expect(input.selectionEnd).toBe(input.value.length);
441 await act(() => input.blur());
442 await forward();
443 await expect.element(address).toHaveFocus();
444
445 await act(() => input.blur());
446 await screen.rerender(
447 <PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible={false} />,
448 );
449 await forward();
450 await expect.element(address).not.toHaveFocus();
451 expect(listeners.size).toBe(0);
452 });
453
454 it("focuses the address bar each time the focus-url shortcut fires", async () => {
455 setup();
456 await using _screen = await render(view());
457 const address = page.getByRole("textbox");
458
459 act(() => dispatchPreviewAction("focus-url"));
460 await expect.element(address).toHaveFocus();
461
462 (address.element() as HTMLInputElement).blur();
463 await expect.element(address).not.toHaveFocus();
464 act(() => dispatchPreviewAction("focus-url"));
465 await expect.element(address).toHaveFocus();
466 });
467
468 it("does not reopen find when the user returns to a tab they left with find open", async () => {
469 setup();
470 const tabView = (tabId: string) => (
471 <PreviewView threadRef={TEST_THREAD_REF} tabId={tabId} visible />
472 );
473 await using screen = await render(tabView("tab-1"));
474 const findBar = page.getByRole("search", { name: "Find in page" });
475
476 act(() => dispatchPreviewAction("find"));
477 await expect.element(findBar).toBeInTheDocument();
478
479 await screen.rerender(tabView("tab-2"));
480 await expect.element(findBar).not.toBeInTheDocument();
481 await screen.rerender(tabView("tab-1"));
482 await expect.element(findBar).not.toBeInTheDocument();
483 });
484 });