Open History to see the last commit
1import { DEFAULT_THEMES, preloadHighlighter } from "@pierre/diffs";
2import { EnvironmentId, ThreadId, type ProjectReadFileResult } from "@t3tools/contracts";
3import { AsyncResult } from "effect/reactivity";
4import { StrictMode, type ReactNode } from "react";
5import { describe, expect, it, vi } from "vite-plus/test";
6import { cdp, userEvent } from "vite-plus/test/browser";
7import { act, fakeTimers, render } from "../../../test/render";
8import appCss from "~/index.css?inline";
9import { isMacPlatform } from "~/lib/utils";
10import {
11 createWorkspaceFocusController,
12 startWorkspaceFocus,
13 workspaceAreaProps,
14} from "~/lib/workspaceFocus";
15
16const state = vi.hoisted(() => ({
17 file: null as ProjectReadFileResult | null,
18 optimistic: null as ProjectReadFileResult | null,
19 writeFile: vi.fn(),
20 assetUrl: { _tag: "Loading" } as import("~/assets/assetUrls").AssetUrlState,
21 assetResources: [] as Array<import("@t3tools/contracts").AssetResource>,
22 mintUrl: vi.fn<() => Promise<string | null>>(),
23 browserAssetMints: 0,
24 openedBrowserUrls: [] as string[],
25 diffWorkersReady: true,
26}));
27
28vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => ({
29 ...(await original()),
30 runAtomCommand: ((_registry: unknown, _command: unknown, request: unknown) =>
31 state.writeFile(request)) as never,
32}));
33vi.mock(import("~/state/session"), async (original) => ({
34 ...(await original()),
35 readEnvironmentScope: () => true,
36 useEnvironmentScope: () => true,
37}));
38vi.mock(import("~/state/filesystem"), async (original) => ({
39 ...(await original()),
40 useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }),
41}));
42vi.mock(import("~/state/use-atom-command"), async (original) => ({
43 ...(await original()),
44 useAtomCommand: (() => state.writeFile) as never,
45}));
46vi.mock(import("~/state/server"), async (original) => {
47 const actual = await original();
48 const { Atom } = await import("effect/reactivity");
49 const noConfig = Atom.make(null);
50 return {
51 ...actual,
52 serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => noConfig) as never },
53 };
54});
55vi.mock(import("~/remoteOpen"), async (original) => ({
56 ...(await original()),
57 useRemoteOpenState: () => ({ mode: "local-exec" }) as never,
58 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
59}));
60vi.mock(import("~/hooks/useTheme"), async (original) => ({
61 ...(await original()),
62 useTheme: () => ({ resolvedTheme: "dark" }) as never,
63 useRenderedAppearance: () => "dark",
64}));
65vi.mock(import("~/hooks/useWorkspaceMutationRefresh"), () => ({
66 useWorkspaceMutationRefresh: vi.fn(),
67}));
68vi.mock(import("~/assets/assetUrls"), async (original) => ({
69 ...(await original()),
70 useAssetUrlRefresh: () => state.mintUrl,
71 useAssetUrlState: (
72 _environmentId: unknown,
73 resource: import("@t3tools/contracts").AssetResource | null,
74 ) => {
75 if (resource) state.assetResources.push(resource);
76 return state.assetUrl;
77 },
78}));
79vi.mock(import("~/browser/previewRuntime"), async (original) => ({
80 ...(await original()),
81 usePreviewAvailable: () => true,
82}));
83vi.mock(import("~/state/environments"), async (original) => ({
84 ...(await original()),
85 useEnvironmentHttpBaseUrl: () => "http://environment.test",
86}));
87vi.mock(import("~/state/assets"), async (original) => {
88 const actual = await original();
89 const { Atom } = await import("effect/reactivity");
90 const Effect = await import("effect/Effect");
91 // Like the real query family, a minted URL stays cached until the atom is refreshed.
92 const createUrl = Atom.family((_key: string) =>
93 Atom.make(
94 Effect.sync(() => ({
95 relativeUrl: `/api/assets/mint-${++state.browserAssetMints}/page.html`,
96 expiresAt: Number.MAX_SAFE_INTEGER,
97 })),
98 ).pipe(Atom.keepAlive),
99 );
100 return {
101 ...actual,
102 assetEnvironment: {
103 ...actual.assetEnvironment,
104 createUrl: ((target: { input: { resource: { path: string } } }) =>
105 createUrl(target.input.resource.path)) as never,
106 },
107 };
108});
109vi.mock(import("~/browser/openFileInPreview"), async (original) => {
110 const actual = await original();
111 return {
112 ...actual,
113 openFileInPreview: (async (input: Parameters<typeof actual.openFileInPreview>[0]) => {
114 const result = await input.createAssetUrl({
115 environmentId: input.threadRef.environmentId,
116 input: {
117 resource: {
118 _tag: "workspace-file",
119 threadId: input.threadRef.threadId,
120 path: input.filePath,
121 },
122 },
123 });
124 if (result._tag === "Success") state.openedBrowserUrls.push(result.value.relativeUrl);
125 return AsyncResult.success(undefined);
126 }) as never,
127 };
128});
129// The Word engine compiles a large WebAssembly bundle; these tests only need the URL it loads.
130vi.mock(import("./OfficeFilePreview"), () => ({
131 OfficeFilePreview: ({ src }: { src: string }) => <div data-testid="office-preview">{src}</div>,
132}));
133vi.mock(import("./FileBreadcrumbs"), () => ({ FileBreadcrumbs: () => <></> }));
134vi.mock(import("./FileBrowserPanel"), () => ({
135 default: () => (
136 <div role="tree">
137 <button type="button" role="treeitem" data-item-path="src/">
138 src
139 </button>
140 <button type="button" role="treeitem" data-item-path="server.ts">
141 server.ts
142 </button>
143 </div>
144 ),
145}));
146vi.mock(import("../DiffWorkerPoolProvider"), () => ({
147 // Like the real provider, a pool that is still starting unmounts the viewer it wraps.
148 DiffWorkerPoolProvider: ({ children }: { children?: ReactNode }) => (
149 <>{state.diffWorkersReady ? children : null}</>
150 ),
151}));
152vi.mock(import("./projectFilesQueryState"), async (original) => ({
153 ...(await original()),
154 useProjectFileQuery: () => ({
155 data: state.file,
156 error: null,
157 isPending: false,
158 readError: null,
159 isNotFile: false,
160 isFile: true,
161 refresh: vi.fn(),
162 }),
163 getOptimisticProjectFileQueryData: () => state.optimistic,
164 getUnsavedProjectFileQueryData: () => null,
165 setProjectFileQueryData: (
166 _environmentId: EnvironmentId,
167 _cwd: string,
168 relativePath: string,
169 contents: string,
170 ) => {
171 state.optimistic = { relativePath, contents, truncated: false, byteLength: contents.length };
172 },
173 confirmProjectFileQueryData: () => true,
174}));
175
176import FilePreviewPanel from "./FilePreviewPanel";
177
178const environmentId = EnvironmentId.make("markdown-preview-test");
179const threadRef = { environmentId, threadId: ThreadId.make("thread") };
180function setup() {
181 const keys = ["t3code.fileExplorerOpen", "t3code.renderMarkdown"];
182 const previous = keys.map((key) => localStorage.getItem(key));
183 localStorage.setItem(keys[0]!, "false");
184 localStorage.setItem(keys[1]!, "true");
185 state.file = null;
186 state.optimistic = null;
187 state.assetUrl = { _tag: "Loading" };
188 state.assetResources = [];
189 state.openedBrowserUrls = [];
190 state.diffWorkersReady = true;
191 let mints = 0;
192 state.mintUrl.mockReset().mockImplementation(async () => `/assets/report.docx?mint=${++mints}`);
193 state.writeFile.mockReset().mockResolvedValue(AsyncResult.success(undefined));
194 return {
195 [Symbol.dispose]() {
196 for (const [index, key] of keys.entries()) {
197 const value = previous[index];
198 if (value == null) localStorage.removeItem(key);
199 else localStorage.setItem(key, value);
200 }
201 },
202 };
203}
204
205function markdownPreview(
206 truncated: boolean,
207 contents = "- [ ] Keep the rest of this file\n",
208 relativePath = "tasks.md",
209) {
210 state.file = {
211 relativePath,
212 contents,
213 byteLength: truncated ? 1_200_000 : contents.length,
214 truncated,
215 };
216 return filePreview(relativePath);
217}
218
219function filePreview(
220 relativePath: string,
221 workspaceMutationId: string | null = null,
222 reveal: { line: number; requestId: number } | null = null,
223) {
224 return (
225 <FilePreviewPanel
226 environmentId={environmentId}
227 cwd="/workspace"
228 projectName="Project"
229 relativePath={relativePath}
230 threadRef={threadRef}
231 composerDraftTarget={threadRef}
232 keybindings={[]}
233 availableEditors={[]}
234 openInShortcutEnabled={false}
235 revealLine={reveal?.line ?? null}
236 revealRequestId={reveal?.requestId ?? 0}
237 onOpenFile={vi.fn()}
238 onNavigateFolder={vi.fn()}
239 folderTrail={undefined}
240 onPendingChange={vi.fn()}
241 selectedFilePending={false}
242 workspaceMutationId={workspaceMutationId}
243 />
244 );
245}
246
247function documentPreview(workspaceMutationId: string, fileRevision: string) {
248 state.file = null;
249 state.assetUrl = {
250 _tag: "Success",
251 url: "/assets/report.docx",
252 expiresAt: Number.MAX_SAFE_INTEGER,
253 fileRevision,
254 };
255 return filePreview("report.docx", workspaceMutationId);
256}
257
258function deepActiveElement() {
259 let active = document.activeElement;
260 while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
261 return active;
262}
263
264describe("source file focus", () => {
265 it("hands panel focus to the file's editor, which owns mod+f", async () => {
266 using _settings = setup();
267 const style = document.createElement("style");
268 style.textContent = appCss;
269 document.head.append(style);
270 using _style = { [Symbol.dispose]: () => style.remove() };
271 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] });
272 const panel = () => (
273 <div {...workspaceAreaProps("panel", 1, "Workspace panel")}>
274 <div data-right-panel-surface-content>{filePreview("server.ts")}</div>
275 </div>
276 );
277 const editorHasFocus = () => expect(deepActiveElement()?.matches("[data-content]")).toBe(true);
278
279 await using screen = await render(panel());
280 const focus = createWorkspaceFocusController(document);
281 using _focus = { [Symbol.dispose]: focus.dispose };
282 expect(focus.focus("panel")).toBe(true);
283 state.file = {
284 relativePath: "server.ts",
285 contents: "const server = 1;\n",
286 byteLength: 18,
287 truncated: false,
288 };
289 await screen.rerender(panel());
290 await vi.waitFor(editorHasFocus);
291 await userEvent.keyboard("x");
292 await vi.waitFor(() => expect(deepActiveElement()?.textContent).toContain("xconst server"));
293
294 (deepActiveElement() as HTMLElement).blur();
295 expect(focus.focus("panel", false)).toBe(true);
296 await vi.waitFor(editorHasFocus);
297 await userEvent.keyboard(
298 isMacPlatform(navigator.platform) ? "{Meta>}f{/Meta}" : "{Control>}f{/Control}",
299 );
300 await vi.waitFor(() => expect(deepActiveElement()).toBeInstanceOf(HTMLInputElement));
301
302 const findField = deepActiveElement() as HTMLInputElement;
303 await userEvent.keyboard("server");
304 findField.blur();
305 expect(focus.focus("panel", false)).toBe(true);
306 await vi.waitFor(editorHasFocus);
307 const editor = deepActiveElement() as HTMLElement;
308 await userEvent.keyboard("ab");
309 await vi.waitFor(() => expect(editor.textContent).toContain("xabconst server"));
310 expect(findField.value).toBe("server");
311 editorHasFocus();
312 });
313
314 it("focuses the editor when a file row is clicked or activated with Enter", async () => {
315 using _settings = setup();
316 localStorage.setItem("t3code.fileExplorerOpen", "true");
317 const style = document.createElement("style");
318 style.textContent = appCss;
319 document.head.append(style);
320 using _style = { [Symbol.dispose]: () => style.remove() };
321 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] });
322 state.file = {
323 relativePath: "server.ts",
324 contents: "const server = 1;\n",
325 byteLength: 18,
326 truncated: false,
327 };
328 await using screen = await render(
329 <div {...workspaceAreaProps("panel", 1, "Workspace panel")} style={{ width: 900 }}>
330 <div data-right-panel-surface-content>{filePreview("server.ts")}</div>
331 </div>,
332 );
333 using _focus = {
334 [Symbol.dispose]: startWorkspaceFocus({ subscribe: () => () => {} } as never),
335 };
336 const editorHasFocus = () => expect(deepActiveElement()?.matches("[data-content]")).toBe(true);
337 // The explorer measures its parent row; a wrapper without a box would cap it at the minimum.
338 await expect
339 .element(screen.getByRole("separator", { name: "Resize file explorer" }))
340 .toHaveAttribute("aria-valuemax", "560");
341 const folderRow = screen.getByRole("treeitem", { name: "src" });
342 const fileRow = screen.getByRole("treeitem", { name: "server.ts" });
343
344 (folderRow.element() as HTMLElement).focus();
345 await userEvent.keyboard("{Enter}");
346 expect(document.activeElement).toBe(folderRow.element());
347
348 await userEvent.click(fileRow);
349 await vi.waitFor(editorHasFocus);
350
351 (fileRow.element() as HTMLElement).focus();
352 await userEvent.keyboard("{Enter}");
353 await vi.waitFor(editorHasFocus);
354 });
355});
356
357describe("source file scroll", () => {
358 it("returns a file tab to where it was scrolled after another file was shown", async () => {
359 using _settings = setup();
360 const style = document.createElement("style");
361 style.textContent = appCss;
362 document.head.append(style);
363 using _style = { [Symbol.dispose]: () => style.remove() };
364 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] });
365 const sourceFile = (relativePath: string, lines: number) => {
366 const contents = Array.from({ length: lines }, (_, i) => `const line${i} = ${i};`).join("\n");
367 state.file = { relativePath, contents, byteLength: contents.length, truncated: false };
368 // The app mounts under StrictMode, whose remount must not wipe the saved offset.
369 return (
370 <StrictMode>
371 <div style={{ height: 400, display: "flex", flexDirection: "column" }}>
372 {filePreview(relativePath)}
373 </div>
374 </StrictMode>
375 );
376 };
377 const scroller = () => document.querySelector<HTMLElement>(".file-preview-virtualizer");
378
379 await using screen = await render(sourceFile("a.ts", 2000));
380 await vi.waitFor(() => expect(scroller()?.scrollHeight).toBeGreaterThan(5000));
381 scroller()!.scrollTop = 4200;
382 await vi.waitFor(() => expect(scroller()?.scrollTop).toBe(4200));
383
384 await screen.rerender(sourceFile("b.ts", 1500));
385 await vi.waitFor(() => expect(scroller()?.scrollTop).toBe(0));
386 await screen.rerender(sourceFile("a.ts", 2000));
387
388 await vi.waitFor(() => expect(scroller()?.scrollTop).toBe(4200));
389 });
390
391 it("centers a linked line in a scrolled read-only file, and again when the viewer is rebuilt", async () => {
392 using _settings = setup();
393 const style = document.createElement("style");
394 style.textContent = appCss;
395 document.head.append(style);
396 using _style = { [Symbol.dispose]: () => style.remove() };
397 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["text"] });
398 // Wrapped lines of differing lengths, so the viewer estimates heights until it measures them.
399 const contents = Array.from(
400 { length: 140 },
401 (_, i) =>
402 `Line ${i + 1}. ${"Notes that wrap across the preview. ".repeat(2 + ((i * 7) % 9))}`,
403 ).join("\n");
404 // A file outside the workspace is read-only, which CodeView renders.
405 const hostFile = (reveal: { line: number; requestId: number } | null) => {
406 const relativePath = "/outside/notes.txt";
407 state.file = { relativePath, contents, byteLength: contents.length, truncated: false };
408 return (
409 <div style={{ height: 400, width: 500, display: "flex", flexDirection: "column" }}>
410 {filePreview(relativePath, null, reveal)}
411 </div>
412 );
413 };
414 const scroller = () => document.querySelector<HTMLElement>(".file-preview-virtualizer");
415 const row = (line: number) =>
416 document.querySelector("diffs-container")?.shadowRoot?.querySelector(`[data-line="${line}"]`);
417 const middle = (element: Element | null | undefined) => {
418 const rect = element?.getBoundingClientRect();
419 return rect ? (rect.top + rect.bottom) / 2 : Number.NaN;
420 };
421 const lineIsCentered = () =>
422 expect(Math.abs(middle(row(82)) - middle(scroller()))).toBeLessThan(2);
423
424 await using screen = await render(hostFile(null));
425 await vi.waitFor(() => expect(scroller()?.scrollHeight).toBeGreaterThan(3000));
426 scroller()!.scrollTop = 2500;
427 // The viewer has moved its window of mounted rows to the new offset.
428 await vi.waitFor(() => expect(row(1)).toBeNull());
429
430 await screen.rerender(hostFile({ line: 82, requestId: 1 }));
431 await vi.waitFor(lineIsCentered);
432
433 // Starting the worker pool unmounts the viewer and mounts a new one.
434 state.diffWorkersReady = false;
435 await screen.rerender(hostFile({ line: 82, requestId: 1 }));
436 await vi.waitFor(() => expect(scroller()).toBeNull());
437 state.diffWorkersReady = true;
438 await screen.rerender(hostFile({ line: 82, requestId: 1 }));
439 await vi.waitFor(lineIsCentered);
440 });
441
442 it.each([
443 {
444 label: "keeps a downward drag whose anchor stays mounted across a window shift",
445 startLine: 65,
446 initialScrollLine: 65,
447 direction: "down" as const,
448 targetFirstMounted: 101,
449 expectedIncludedLine: 121,
450 },
451 {
452 label: "keeps a downward drag whose anchor unmounts on a window shift",
453 startLine: 5,
454 initialScrollLine: null,
455 direction: "down" as const,
456 targetFirstMounted: 101,
457 expectedIncludedLine: 121,
458 },
459 {
460 label: "keeps an upward drag whose anchor unmounts on a window shift",
461 startLine: 385,
462 initialScrollLine: 385,
463 direction: "up" as const,
464 targetFirstMounted: 201,
465 expectedIncludedLine: 290,
466 },
467 ])(
468 "$label",
469 async ({
470 startLine,
471 initialScrollLine,
472 direction,
473 targetFirstMounted,
474 expectedIncludedLine,
475 }) => {
476 using _settings = setup();
477 localStorage.setItem("t3code.renderMarkdown", "false");
478 const style = document.createElement("style");
479 style.textContent = appCss;
480 document.head.append(style);
481 using _style = { [Symbol.dispose]: () => style.remove() };
482 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["markdown"] });
483
484 const lines = Array.from({ length: 400 }, (_, index) => `line ${index + 1} markdown content`);
485 const contents = `${lines.join("\n")}\n`;
486 state.file = {
487 relativePath: "notes.md",
488 contents,
489 byteLength: contents.length,
490 truncated: false,
491 };
492
493 await using screen = await render(
494 <div style={{ width: 560, height: 400, display: "flex", flexDirection: "column" }}>
495 {filePreview("notes.md")}
496 </div>,
497 );
498
499 const shadowRoot = () => screen.container.querySelector("diffs-container")?.shadowRoot;
500 const rows = () => shadowRoot()?.querySelectorAll<HTMLElement>("[data-line]") ?? [];
501 await vi.waitFor(() =>
502 expect(
503 shadowRoot()?.querySelector('[data-content][contenteditable="true"]'),
504 ).not.toBeNull(),
505 );
506
507 const scroller = screen.container.querySelector<HTMLElement>(".file-preview-virtualizer")!;
508 if (initialScrollLine !== null) {
509 if (direction === "up") {
510 await vi.waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(5000));
511 scroller.scrollTop = scroller.scrollHeight;
512 await vi.waitFor(() =>
513 expect(
514 [...rows()].some((row) => row.getAttribute("data-line") === String(startLine)),
515 ).toBe(true),
516 );
517 }
518 const target = [...rows()].find(
519 (row) => row.getAttribute("data-line") === String(initialScrollLine),
520 );
521 expect(target).toBeDefined();
522 target!.scrollIntoView({ block: direction === "up" ? "end" : "start" });
523 await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(0));
524 }
525
526 const startRow = [...rows()].find(
527 (row) => row.getAttribute("data-line") === String(startLine),
528 );
529 expect(startRow).toBeDefined();
530 const startRect = startRow!.getBoundingClientRect();
531 const scrollerRect = scroller.getBoundingClientRect();
532 const nearEdgeY = direction === "down" ? scrollerRect.bottom - 5 : scrollerRect.top + 5;
533 const outsideEdgeY = direction === "down" ? scrollerRect.bottom + 60 : scrollerRect.top - 60;
534 const frame = window.frameElement?.getBoundingClientRect();
535 const mouse = (type: "mousePressed" | "mouseMoved" | "mouseReleased", x: number, y: number) =>
536 cdp().send("Input.dispatchMouseEvent", {
537 type,
538 x: x + (frame?.left ?? 0),
539 y: y + (frame?.top ?? 0),
540 button: "left",
541 buttons: type === "mouseReleased" ? 0 : 1,
542 clickCount: 1,
543 });
544
545 const startX = direction === "up" ? startRect.left + 140 : startRect.left + 2;
546 // The editor records the drag anchor on the press's selectionchange; drag only after it.
547 const anchored = new Promise((resolve) =>
548 document.addEventListener("selectionchange", resolve, { once: true }),
549 );
550 await mouse("mousePressed", startX, startRect.top + 5);
551 await anchored;
552 await mouse("mouseMoved", startRect.left + 80, nearEdgeY);
553 await mouse("mouseMoved", startRect.left + 80, outsideEdgeY);
554 await vi.waitFor(() => {
555 const firstMounted = Number(rows()[0]?.getAttribute("data-line"));
556 if (direction === "down") {
557 expect(firstMounted).toBeGreaterThanOrEqual(targetFirstMounted);
558 } else {
559 expect(firstMounted).toBeLessThanOrEqual(targetFirstMounted);
560 }
561 });
562 await mouse("mouseReleased", startRect.left + 80, outsideEdgeY);
563
564 const overlayRanges = shadowRoot()!.querySelectorAll("[data-selection-range]");
565 expect(overlayRanges.length).toBeGreaterThan(0);
566
567 const clipboardData = new DataTransfer();
568 const contentEl = shadowRoot()!.querySelector("[data-content]")!;
569 const handled = !contentEl.dispatchEvent(
570 new ClipboardEvent("copy", {
571 clipboardData,
572 bubbles: true,
573 cancelable: true,
574 composed: true,
575 }),
576 );
577 expect(handled).toBe(true);
578 const copied = clipboardData.getData("text/plain");
579 expect(copied).toContain(`line ${startLine} `);
580 expect(copied).toContain(`line ${expectedIncludedLine} markdown content`);
581 },
582 );
583
584 it("scrolls a find match below many wrapped lines into view", async () => {
585 using _settings = setup();
586 const style = document.createElement("style");
587 style.textContent = appCss;
588 document.head.append(style);
589 using _style = { [Symbol.dispose]: () => style.remove() };
590 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] });
591 const wrapped = "wrap ".repeat(60);
592 const lines = Array.from({ length: 800 }, (_, i) => `const line${i} = "${wrapped}";`);
593 lines.push(
594 "const needle = 1;",
595 ...Array.from({ length: 40 }, (_, i) => `const tail${i} = ${i};`),
596 );
597 const contents = lines.join("\n");
598 state.file = {
599 relativePath: "wrapped.ts",
600 contents,
601 byteLength: contents.length,
602 truncated: false,
603 };
604 const scroller = () => document.querySelector<HTMLElement>(".file-preview-virtualizer");
605
606 await using _screen = await render(
607 <div style={{ width: 500, height: 400, display: "flex", flexDirection: "column" }}>
608 {filePreview("wrapped.ts")}
609 </div>,
610 );
611 await vi.waitFor(() => expect(scroller()?.scrollHeight).toBeGreaterThan(20_000));
612 const shadowRows = () =>
613 [...document.querySelectorAll("*")].flatMap((host) =>
614 host.shadowRoot ? [...host.shadowRoot.querySelectorAll<HTMLElement>("[data-line]")] : [],
615 );
616 await userEvent.click(shadowRows().find((row) => row.getAttribute("data-line") === "1")!);
617 await vi.waitFor(() => expect(deepActiveElement()?.matches("[data-content]")).toBe(true));
618 await userEvent.keyboard(
619 isMacPlatform(navigator.platform) ? "{Meta>}f{/Meta}" : "{Control>}f{/Control}",
620 );
621 await vi.waitFor(() => expect(deepActiveElement()).toBeInstanceOf(HTMLInputElement));
622 await userEvent.keyboard("needle{Enter}");
623
624 const visibleLines = () => {
625 const viewport = scroller()!.getBoundingClientRect();
626 return shadowRows()
627 .filter((row) => {
628 const box = row.getBoundingClientRect();
629 return box.height > 0 && box.top >= viewport.top && box.bottom <= viewport.bottom;
630 })
631 .map((row) => Number(row.getAttribute("data-line")));
632 };
633 await vi.waitFor(() => expect(visibleLines()).toContain(801));
634 });
635});
636
637describe("rendered Markdown task saves", () => {
638 it("renders the whole file of a truncated read, read-only", async () => {
639 using _settings = setup();
640 state.assetUrl = {
641 _tag: "Success",
642 url: "/assets/tasks.md",
643 expiresAt: Number.MAX_SAFE_INTEGER,
644 };
645 const realFetch = globalThis.fetch;
646 using _fetch = vi
647 .spyOn(globalThis, "fetch")
648 .mockImplementation((input, init) =>
649 new URL(String(input), location.href).pathname === "/assets/tasks.md"
650 ? Promise.resolve(
651 new Response("- [ ] Keep the rest of this file\n\nPast the first megabyte\n"),
652 )
653 : realFetch(input, init),
654 );
655 await using screen = await render(markdownPreview(true));
656 await expect.element(screen.getByText("Past the first megabyte")).toBeVisible();
657 const checkbox = screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
658 expect(checkbox.disabled).toBe(true);
659 await act(async () => checkbox.click());
660 expect(state.optimistic).toBeNull();
661 expect(state.writeFile).not.toHaveBeenCalled();
662 });
663
664 it("still toggles and saves tasks from a complete read", async () => {
665 using _settings = setup();
666 await using screen = await render(markdownPreview(false));
667 // The virtualized list mounts its pieces after measuring the viewport.
668 await expect.element(screen.getByRole("checkbox")).toBeInTheDocument();
669 using _timers = fakeTimers();
670 const checkbox = screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
671 expect(checkbox).not.toBeNull();
672 expect(checkbox.disabled).toBe(false);
673 await act(async () => checkbox.click());
674 await vi.advanceTimersByTimeAsync(500);
675 expect(state.writeFile).toHaveBeenCalledExactlyOnceWith({
676 environmentId,
677 input: {
678 cwd: "/workspace",
679 relativePath: "tasks.md",
680 contents: "- [x] Keep the rest of this file\n",
681 },
682 });
683 });
684});
685
686describe("workspace document previews", () => {
687 it("keeps an unchanged document loaded when another workspace change lands", async () => {
688 using _settings = setup();
689 await using screen = await render(documentPreview("mutation-1", "revision-1"));
690 const preview = screen.getByTestId("office-preview");
691 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
692 const loaded = preview.element();
693
694 await screen.rerender(documentPreview("mutation-2", "revision-1"));
695
696 expect(state.mintUrl, "an unchanged document re-minted its URL").toHaveBeenCalledOnce();
697 expect(screen.container.contains(loaded), "an unchanged document was remounted").toBe(true);
698 });
699
700 it("keeps an unchanged document mounted while its revision check reloads", async () => {
701 using _settings = setup();
702 await using screen = await render(documentPreview("mutation-1", "revision-1"));
703 const preview = screen.getByTestId("office-preview");
704 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
705 const loaded = preview.element();
706
707 state.assetUrl = { _tag: "Loading" };
708 await screen.rerender(filePreview("report.docx", "mutation-1"));
709 await screen.rerender(documentPreview("mutation-1", "revision-1"));
710
711 expect(
712 state.mintUrl,
713 "a reloading revision check re-minted the document URL",
714 ).toHaveBeenCalledOnce();
715 expect(
716 screen.container.contains(loaded),
717 "a reloading revision check remounted the document",
718 ).toBe(true);
719 });
720
721 it("reloads the document when its URL can no longer be minted", async () => {
722 using _settings = setup();
723 await using screen = await render(documentPreview("mutation-1", "revision-1"));
724 const preview = screen.getByTestId("office-preview");
725 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
726
727 state.assetUrl = { _tag: "Failure" };
728 await screen.rerender(filePreview("report.docx", "mutation-2"));
729
730 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=2");
731 });
732
733 it("loads the new bytes when the document itself changes", async () => {
734 using _settings = setup();
735 await using screen = await render(documentPreview("mutation-1", "revision-1"));
736 const preview = screen.getByTestId("office-preview");
737 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
738
739 await screen.rerender(documentPreview("mutation-2", "revision-2"));
740
741 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=2");
742 });
743});
744
745describe("open file in preview browser", () => {
746 it("mints a fresh asset URL on every click so the browser cannot reuse cached bytes", async () => {
747 using _settings = setup();
748 state.file = {
749 relativePath: "page.html",
750 contents: "<h1>page</h1>",
751 byteLength: 13,
752 truncated: false,
753 };
754 await using screen = await render(filePreview("page.html"));
755 const button = screen.getByRole("button", { name: "Open file in preview browser" });
756
757 await userEvent.click(button);
758 await vi.waitFor(() => expect(state.openedBrowserUrls).toHaveLength(1));
759 await userEvent.click(button);
760 await vi.waitFor(() => expect(state.openedBrowserUrls).toHaveLength(2));
761
762 expect(state.openedBrowserUrls[1], "the second click reused the first signed URL").not.toBe(
763 state.openedBrowserUrls[0],
764 );
765 });
766});
767
768describe("rendered Markdown select all", () => {
769 it("selects only the rendered file, including after a task toggle", async () => {
770 using _settings = setup();
771 await using screen = await render(
772 <>
773 <p>Transcript text from the chat thread.</p>
774 {markdownPreview(false, "- [ ] Task item\n\nRendered file body.\n")}
775 </>,
776 );
777 const expectFileOnlySelection = async () => {
778 await userEvent.keyboard(
779 isMacPlatform(navigator.platform) ? "{Meta>}a{/Meta}" : "{Control>}a{/Control}",
780 );
781 const selection = window.getSelection()?.toString() ?? "";
782 expect(selection).toContain("Rendered file body.");
783 expect(selection).not.toContain("Transcript text from the chat thread.");
784 };
785
786 await userEvent.click(screen.getByText("Rendered file body."));
787 await expectFileOnlySelection();
788 // A toggled checkbox keeps focus on an input inside the preview.
789 await userEvent.click(screen.getByRole("checkbox"));
790 await expectFileOnlySelection();
791 });
792});
793
794describe("rendered Markdown relative images", () => {
795 it.each([
796 ["2026-11-23T14:05/README.md", "/workspace/2026-11-23T14:05/diagram.png"],
797 ["/README.md", "/diagram.png"],
798 ])("resolves relative images in %s against its folder", async (relativePath, expectedPath) => {
799 using _settings = setup();
800 await using _screen = await render(
801 markdownPreview(false, "\n", relativePath),
802 );
803 await vi.waitFor(() => expect(state.assetResources).not.toHaveLength(0));
804 expect(state.assetResources).toContainEqual(
805 expect.objectContaining({ _tag: "media-file", path: expectedPath }),
806 );
807 });
808});