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

FilePreviewPanel.browser.test.tsx

747 lines28.3 KB

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