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

FilePreviewPanel.browser.test.tsx

925 lines35.6 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 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";
177import { ChunkedMarkdown } from "./ChunkedMarkdown";
178import { splitMarkdown } from "@t3tools/shared/markdownChunks";
179​
180const environmentId = EnvironmentId.make("markdown-preview-test");
181const threadRef = { environmentId, threadId: ThreadId.make("thread") };
182function setup() {
183 const keys = ["t3code.fileExplorerOpen", "t3code.renderMarkdown"];
184 const previous = keys.map((key) => localStorage.getItem(key));
185 localStorage.setItem(keys[0]!, "false");
186 localStorage.setItem(keys[1]!, "true");
187 state.file = null;
188 state.optimistic = null;
189 state.assetUrl = { _tag: "Loading" };
190 state.assetResources = [];
191 state.openedBrowserUrls = [];
192 state.diffWorkersReady = true;
193 let mints = 0;
194 state.mintUrl.mockReset().mockImplementation(async () => `/assets/report.docx?mint=${++mints}`);
195 state.writeFile.mockReset().mockResolvedValue(AsyncResult.success(undefined));
196 return {
197 [Symbol.dispose]() {
198 for (const [index, key] of keys.entries()) {
199 const value = previous[index];
200 if (value == null) localStorage.removeItem(key);
201 else localStorage.setItem(key, value);
202 }
203 },
204 };
206​
207function markdownPreview(
208 truncated: boolean,
209 contents = "- [ ] Keep the rest of this file\n",
210 relativePath = "tasks.md",
211) {
212 state.file = {
213 relativePath,
214 contents,
215 byteLength: truncated ? 1_200_000 : contents.length,
216 truncated,
217 };
218 return filePreview(relativePath);
220​
221function filePreview(
222 relativePath: string,
223 workspaceMutationId: string | null = null,
224 reveal: { line: number; requestId: number } | null = null,
225) {
226 return (
227 <FilePreviewPanel
228 environmentId={environmentId}
229 cwd="/workspace"
230 projectName="Project"
231 relativePath={relativePath}
232 threadRef={threadRef}
233 composerDraftTarget={threadRef}
234 keybindings={[]}
235 availableEditors={[]}
236 openInShortcutEnabled={false}
237 revealLine={reveal?.line ?? null}
238 revealRequestId={reveal?.requestId ?? 0}
239 onOpenFile={vi.fn()}
240 onNavigateFolder={vi.fn()}
241 folderTrail={undefined}
242 onPendingChange={vi.fn()}
243 selectedFilePending={false}
244 workspaceMutationId={workspaceMutationId}
245 />
246 );
248​
249function documentPreview(workspaceMutationId: string, fileRevision: string) {
250 state.file = null;
251 state.assetUrl = {
252 _tag: "Success",
253 url: "/assets/report.docx",
254 expiresAt: Number.MAX_SAFE_INTEGER,
255 fileRevision,
256 };
257 return filePreview("report.docx", workspaceMutationId);
259​
260function deepActiveElement() {
261 let active = document.activeElement;
262 while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
263 return active;
265​
266describe("source file focus", () => {
267 it("hands panel focus to the file's editor, which owns mod+f", async () => {
268 using _settings = setup();
269 const style = document.createElement("style");
270 style.textContent = appCss;
271 document.head.append(style);
272 using _style = { [Symbol.dispose]: () => style.remove() };
273 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] });
274 const panel = () => (
275 <div {...workspaceAreaProps("panel", 1, "Workspace panel")}>
276 <div data-right-panel-surface-content>{filePreview("server.ts")}</div>
277 </div>
278 );
279 const editorHasFocus = () => expect(deepActiveElement()?.matches("[data-content]")).toBe(true);
280​
281 await using screen = await render(panel());
282 const focus = createWorkspaceFocusController(document);
283 using _focus = { [Symbol.dispose]: focus.dispose };
284 expect(focus.focus("panel")).toBe(true);
285 state.file = {
286 relativePath: "server.ts",
287 contents: "const server = 1;\n",
288 byteLength: 18,
289 truncated: false,
290 };
291 await screen.rerender(panel());
292 await vi.waitFor(editorHasFocus);
293 await userEvent.keyboard("x");
294 await vi.waitFor(() => expect(deepActiveElement()?.textContent).toContain("xconst server"));
295​
296 (deepActiveElement() as HTMLElement).blur();
297 expect(focus.focus("panel", false)).toBe(true);
298 await vi.waitFor(editorHasFocus);
299 await userEvent.keyboard(
300 isMacPlatform(navigator.platform) ? "{Meta>}f{/Meta}" : "{Control>}f{/Control}",
301 );
302 await vi.waitFor(() => expect(deepActiveElement()).toBeInstanceOf(HTMLInputElement));
303​
304 const findField = deepActiveElement() as HTMLInputElement;
305 await userEvent.keyboard("server");
306 findField.blur();
307 expect(focus.focus("panel", false)).toBe(true);
308 await vi.waitFor(editorHasFocus);
309 const editor = deepActiveElement() as HTMLElement;
310 await userEvent.keyboard("ab");
311 await vi.waitFor(() => expect(editor.textContent).toContain("xabconst server"));
312 expect(findField.value).toBe("server");
313 editorHasFocus();
314 });
315​
316 it("focuses the editor when a file row is clicked or activated with Enter", async () => {
317 using _settings = setup();
318 localStorage.setItem("t3code.fileExplorerOpen", "true");
319 const style = document.createElement("style");
320 style.textContent = appCss;
321 document.head.append(style);
322 using _style = { [Symbol.dispose]: () => style.remove() };
323 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] });
324 state.file = {
325 relativePath: "server.ts",
326 contents: "const server = 1;\n",
327 byteLength: 18,
328 truncated: false,
329 };
330 await using screen = await render(
331 <div {...workspaceAreaProps("panel", 1, "Workspace panel")} style={{ width: 900 }}>
332 <div data-right-panel-surface-content>{filePreview("server.ts")}</div>
333 </div>,
334 );
335 using _focus = {
336 [Symbol.dispose]: startWorkspaceFocus({ subscribe: () => () => {} } as never),
337 };
338 const editorHasFocus = () => expect(deepActiveElement()?.matches("[data-content]")).toBe(true);
339 // The explorer measures its parent row; a wrapper without a box would cap it at the minimum.
340 await expect
341 .element(screen.getByRole("separator", { name: "Resize file explorer" }))
342 .toHaveAttribute("aria-valuemax", "560");
343 const folderRow = screen.getByRole("treeitem", { name: "src" });
344 const fileRow = screen.getByRole("treeitem", { name: "server.ts" });
345​
346 (folderRow.element() as HTMLElement).focus();
347 await userEvent.keyboard("{Enter}");
348 expect(document.activeElement).toBe(folderRow.element());
349​
350 await userEvent.click(fileRow);
351 await vi.waitFor(editorHasFocus);
352​
353 (fileRow.element() as HTMLElement).focus();
354 await userEvent.keyboard("{Enter}");
355 await vi.waitFor(editorHasFocus);
356 });
357});
358​
359describe("source file scroll", () => {
360 it("returns a file tab to where it was scrolled after another file was shown", async () => {
361 using _settings = setup();
362 const style = document.createElement("style");
363 style.textContent = appCss;
364 document.head.append(style);
365 using _style = { [Symbol.dispose]: () => style.remove() };
366 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] });
367 const sourceFile = (relativePath: string, lines: number) => {
368 const contents = Array.from({ length: lines }, (_, i) => `const line${i} = ${i};`).join("\n");
369 state.file = { relativePath, contents, byteLength: contents.length, truncated: false };
370 // The app mounts under StrictMode, whose remount must not wipe the saved offset.
371 return (
372 <StrictMode>
373 <div style={{ height: 400, display: "flex", flexDirection: "column" }}>
374 {filePreview(relativePath)}
375 </div>
376 </StrictMode>
377 );
378 };
379 const scroller = () => document.querySelector<HTMLElement>(".file-preview-virtualizer");
380​
381 await using screen = await render(sourceFile("a.ts", 2000));
382 await vi.waitFor(() => expect(scroller()?.scrollHeight).toBeGreaterThan(5000));
383 scroller()!.scrollTop = 4200;
384 await vi.waitFor(() => expect(scroller()?.scrollTop).toBe(4200));
385​
386 await screen.rerender(sourceFile("b.ts", 1500));
387 await vi.waitFor(() => expect(scroller()?.scrollTop).toBe(0));
388 await screen.rerender(sourceFile("a.ts", 2000));
389​
390 await vi.waitFor(() => expect(scroller()?.scrollTop).toBe(4200));
391 });
392​
393 it("centers a linked line in a scrolled read-only file, and again when the viewer is rebuilt", async () => {
394 using _settings = setup();
395 const style = document.createElement("style");
396 style.textContent = appCss;
397 document.head.append(style);
398 using _style = { [Symbol.dispose]: () => style.remove() };
399 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["text"] });
400 // Wrapped lines of differing lengths, so the viewer estimates heights until it measures them.
401 const contents = Array.from(
402 { length: 140 },
403 (_, i) =>
404 `Line ${i + 1}. ${"Notes that wrap across the preview. ".repeat(2 + ((i * 7) % 9))}`,
405 ).join("\n");
406 // A file outside the workspace is read-only, which CodeView renders.
407 const hostFile = (reveal: { line: number; requestId: number } | null) => {
408 const relativePath = "/outside/notes.txt";
409 state.file = { relativePath, contents, byteLength: contents.length, truncated: false };
410 return (
411 <div style={{ height: 400, width: 500, display: "flex", flexDirection: "column" }}>
412 {filePreview(relativePath, null, reveal)}
413 </div>
414 );
415 };
416 const scroller = () => document.querySelector<HTMLElement>(".file-preview-virtualizer");
417 const row = (line: number) =>
418 document.querySelector("diffs-container")?.shadowRoot?.querySelector(`[data-line="${line}"]`);
419 const middle = (element: Element | null | undefined) => {
420 const rect = element?.getBoundingClientRect();
421 return rect ? (rect.top + rect.bottom) / 2 : Number.NaN;
422 };
423 const lineIsCentered = () =>
424 expect(Math.abs(middle(row(82)) - middle(scroller()))).toBeLessThan(2);
425​
426 await using screen = await render(hostFile(null));
427 await vi.waitFor(() => expect(scroller()?.scrollHeight).toBeGreaterThan(3000));
428 scroller()!.scrollTop = 2500;
429 // The viewer has moved its window of mounted rows to the new offset.
430 await vi.waitFor(() => expect(row(1)).toBeNull());
431​
432 await screen.rerender(hostFile({ line: 82, requestId: 1 }));
433 await vi.waitFor(lineIsCentered);
434​
435 // Starting the worker pool unmounts the viewer and mounts a new one.
436 state.diffWorkersReady = false;
437 await screen.rerender(hostFile({ line: 82, requestId: 1 }));
438 await vi.waitFor(() => expect(scroller()).toBeNull());
439 state.diffWorkersReady = true;
440 await screen.rerender(hostFile({ line: 82, requestId: 1 }));
441 await vi.waitFor(lineIsCentered);
442 });
443​
444 it.each([
445 {
446 label: "keeps a downward drag whose anchor stays mounted across a window shift",
447 startLine: 65,
448 initialScrollLine: 65,
449 direction: "down" as const,
450 targetFirstMounted: 101,
451 expectedIncludedLine: 121,
452 },
453 {
454 label: "keeps a downward drag whose anchor unmounts on a window shift",
455 startLine: 5,
456 initialScrollLine: null,
457 direction: "down" as const,
458 targetFirstMounted: 101,
459 expectedIncludedLine: 121,
460 },
461 {
462 label: "keeps an upward drag whose anchor unmounts on a window shift",
463 startLine: 385,
464 initialScrollLine: 385,
465 direction: "up" as const,
466 targetFirstMounted: 201,
467 expectedIncludedLine: 290,
468 },
469 ])(
470 "$label",
471 async ({
472 startLine,
473 initialScrollLine,
474 direction,
475 targetFirstMounted,
476 expectedIncludedLine,
477 }) => {
478 using _settings = setup();
479 localStorage.setItem("t3code.renderMarkdown", "false");
480 const style = document.createElement("style");
481 style.textContent = appCss;
482 document.head.append(style);
483 using _style = { [Symbol.dispose]: () => style.remove() };
484 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["markdown"] });
485​
486 const lines = Array.from({ length: 400 }, (_, index) => `line ${index + 1} markdown content`);
487 const contents = `${lines.join("\n")}\n`;
488 state.file = {
489 relativePath: "notes.md",
490 contents,
491 byteLength: contents.length,
492 truncated: false,
493 };
494​
495 await using screen = await render(
496 <div style={{ width: 560, height: 400, display: "flex", flexDirection: "column" }}>
497 {filePreview("notes.md")}
498 </div>,
499 );
500​
501 const shadowRoot = () => screen.container.querySelector("diffs-container")?.shadowRoot;
502 const rows = () => shadowRoot()?.querySelectorAll<HTMLElement>("[data-line]") ?? [];
503 await vi.waitFor(() =>
504 expect(
505 shadowRoot()?.querySelector('[data-content][contenteditable="true"]'),
506 ).not.toBeNull(),
507 );
508​
509 const scroller = screen.container.querySelector<HTMLElement>(".file-preview-virtualizer")!;
510 if (initialScrollLine !== null) {
511 if (direction === "up") {
512 await vi.waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(5000));
513 scroller.scrollTop = scroller.scrollHeight;
514 await vi.waitFor(() =>
515 expect(
516 [...rows()].some((row) => row.getAttribute("data-line") === String(startLine)),
517 ).toBe(true),
518 );
519 }
520 const target = [...rows()].find(
521 (row) => row.getAttribute("data-line") === String(initialScrollLine),
522 );
523 expect(target).toBeDefined();
524 target!.scrollIntoView({ block: direction === "up" ? "end" : "start" });
525 await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(0));
526 }
527​
528 const startRow = [...rows()].find(
529 (row) => row.getAttribute("data-line") === String(startLine),
530 );
531 expect(startRow).toBeDefined();
532 const startRect = startRow!.getBoundingClientRect();
533 const scrollerRect = scroller.getBoundingClientRect();
534 const nearEdgeY = direction === "down" ? scrollerRect.bottom - 5 : scrollerRect.top + 5;
535 const outsideEdgeY = direction === "down" ? scrollerRect.bottom + 60 : scrollerRect.top - 60;
536 const frame = window.frameElement?.getBoundingClientRect();
537 const mouse = (type: "mousePressed" | "mouseMoved" | "mouseReleased", x: number, y: number) =>
538 cdp().send("Input.dispatchMouseEvent", {
539 type,
540 x: x + (frame?.left ?? 0),
541 y: y + (frame?.top ?? 0),
542 button: "left",
543 buttons: type === "mouseReleased" ? 0 : 1,
544 clickCount: 1,
545 });
546​
547 const startX = direction === "up" ? startRect.left + 140 : startRect.left + 2;
548 // The editor records the drag anchor on the press's selectionchange; drag only after it.
549 const anchored = new Promise((resolve) =>
550 document.addEventListener("selectionchange", resolve, { once: true }),
551 );
552 await mouse("mousePressed", startX, startRect.top + 5);
553 await anchored;
554 await mouse("mouseMoved", startRect.left + 80, nearEdgeY);
555 await mouse("mouseMoved", startRect.left + 80, outsideEdgeY);
556 await vi.waitFor(() => {
557 const firstMounted = Number(rows()[0]?.getAttribute("data-line"));
558 if (direction === "down") {
559 expect(firstMounted).toBeGreaterThanOrEqual(targetFirstMounted);
560 } else {
561 expect(firstMounted).toBeLessThanOrEqual(targetFirstMounted);
562 }
563 });
564 await mouse("mouseReleased", startRect.left + 80, outsideEdgeY);
565​
566 const overlayRanges = shadowRoot()!.querySelectorAll("[data-selection-range]");
567 expect(overlayRanges.length).toBeGreaterThan(0);
568​
569 const clipboardData = new DataTransfer();
570 const contentEl = shadowRoot()!.querySelector("[data-content]")!;
571 const handled = !contentEl.dispatchEvent(
572 new ClipboardEvent("copy", {
573 clipboardData,
574 bubbles: true,
575 cancelable: true,
576 composed: true,
577 }),
578 );
579 expect(handled).toBe(true);
580 const copied = clipboardData.getData("text/plain");
581 expect(copied).toContain(`line ${startLine} `);
582 expect(copied).toContain(`line ${expectedIncludedLine} markdown content`);
583 },
584 );
585​
586 it("scrolls a find match below many wrapped lines into view", async () => {
587 using _settings = setup();
588 const style = document.createElement("style");
589 style.textContent = appCss;
590 document.head.append(style);
591 using _style = { [Symbol.dispose]: () => style.remove() };
592 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] });
593 const wrapped = "wrap ".repeat(60);
594 const lines = Array.from({ length: 800 }, (_, i) => `const line${i} = "${wrapped}";`);
595 lines.push(
596 "const needle = 1;",
597 ...Array.from({ length: 40 }, (_, i) => `const tail${i} = ${i};`),
598 );
599 const contents = lines.join("\n");
600 state.file = {
601 relativePath: "wrapped.ts",
602 contents,
603 byteLength: contents.length,
604 truncated: false,
605 };
606 const scroller = () => document.querySelector<HTMLElement>(".file-preview-virtualizer");
607​
608 await using _screen = await render(
609 <div style={{ width: 500, height: 400, display: "flex", flexDirection: "column" }}>
610 {filePreview("wrapped.ts")}
611 </div>,
612 );
613 await vi.waitFor(() => expect(scroller()?.scrollHeight).toBeGreaterThan(20_000));
614 const shadowRows = () =>
615 [...document.querySelectorAll("*")].flatMap((host) =>
616 host.shadowRoot ? [...host.shadowRoot.querySelectorAll<HTMLElement>("[data-line]")] : [],
617 );
618 await userEvent.click(shadowRows().find((row) => row.getAttribute("data-line") === "1")!);
619 await vi.waitFor(() => expect(deepActiveElement()?.matches("[data-content]")).toBe(true));
620 await userEvent.keyboard(
621 isMacPlatform(navigator.platform) ? "{Meta>}f{/Meta}" : "{Control>}f{/Control}",
622 );
623 await vi.waitFor(() => expect(deepActiveElement()).toBeInstanceOf(HTMLInputElement));
624 await userEvent.keyboard("needle{Enter}");
625​
626 const visibleLines = () => {
627 const viewport = scroller()!.getBoundingClientRect();
628 return shadowRows()
629 .filter((row) => {
630 const box = row.getBoundingClientRect();
631 return box.height > 0 && box.top >= viewport.top && box.bottom <= viewport.bottom;
632 })
633 .map((row) => Number(row.getAttribute("data-line")));
634 };
635 await vi.waitFor(() => expect(visibleLines()).toContain(801));
636 });
637});
638​
639describe("rendered Markdown task saves", () => {
640 it("renders the whole file of a truncated read, read-only", async () => {
641 using _settings = setup();
642 state.assetUrl = {
643 _tag: "Success",
644 url: "/assets/tasks.md",
645 expiresAt: Number.MAX_SAFE_INTEGER,
646 };
647 const realFetch = globalThis.fetch;
648 using _fetch = vi
649 .spyOn(globalThis, "fetch")
650 .mockImplementation((input, init) =>
651 new URL(String(input), location.href).pathname === "/assets/tasks.md"
652 ? Promise.resolve(
653 new Response("- [ ] Keep the rest of this file\n\nPast the first megabyte\n"),
654 )
655 : realFetch(input, init),
656 );
657 await using screen = await render(markdownPreview(true));
658 await expect.element(screen.getByText("Past the first megabyte")).toBeVisible();
659 const checkbox = screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
660 expect(checkbox.disabled).toBe(true);
661 await act(async () => checkbox.click());
662 expect(state.optimistic).toBeNull();
663 expect(state.writeFile).not.toHaveBeenCalled();
664 });
665​
666 it("still toggles and saves tasks from a complete read", async () => {
667 using _settings = setup();
668 await using screen = await render(markdownPreview(false));
669 // The virtualized list mounts its pieces after measuring the viewport.
670 await expect.element(screen.getByRole("checkbox")).toBeInTheDocument();
671 using _timers = fakeTimers();
672 const checkbox = screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
673 expect(checkbox).not.toBeNull();
674 expect(checkbox.disabled).toBe(false);
675 await act(async () => checkbox.click());
676 await vi.advanceTimersByTimeAsync(500);
677 expect(state.writeFile).toHaveBeenCalledExactlyOnceWith({
678 environmentId,
679 input: {
680 cwd: "/workspace",
681 relativePath: "tasks.md",
682 contents: "- [x] Keep the rest of this file\n",
683 },
684 });
685 });
686});
687​
688describe("workspace document previews", () => {
689 it("keeps an unchanged document loaded when another workspace change lands", async () => {
690 using _settings = setup();
691 await using screen = await render(documentPreview("mutation-1", "revision-1"));
692 const preview = screen.getByTestId("office-preview");
693 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
694 const loaded = preview.element();
695​
696 await screen.rerender(documentPreview("mutation-2", "revision-1"));
697​
698 expect(state.mintUrl, "an unchanged document re-minted its URL").toHaveBeenCalledOnce();
699 expect(screen.container.contains(loaded), "an unchanged document was remounted").toBe(true);
700 });
701​
702 it("keeps an unchanged document mounted while its revision check reloads", async () => {
703 using _settings = setup();
704 await using screen = await render(documentPreview("mutation-1", "revision-1"));
705 const preview = screen.getByTestId("office-preview");
706 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
707 const loaded = preview.element();
708​
709 state.assetUrl = { _tag: "Loading" };
710 await screen.rerender(filePreview("report.docx", "mutation-1"));
711 await screen.rerender(documentPreview("mutation-1", "revision-1"));
712​
713 expect(
714 state.mintUrl,
715 "a reloading revision check re-minted the document URL",
716 ).toHaveBeenCalledOnce();
717 expect(
718 screen.container.contains(loaded),
719 "a reloading revision check remounted the document",
720 ).toBe(true);
721 });
722​
723 it("reloads the document when its URL can no longer be minted", async () => {
724 using _settings = setup();
725 await using screen = await render(documentPreview("mutation-1", "revision-1"));
726 const preview = screen.getByTestId("office-preview");
727 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
728​
729 state.assetUrl = { _tag: "Failure" };
730 await screen.rerender(filePreview("report.docx", "mutation-2"));
731​
732 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=2");
733 });
734​
735 it("loads the new bytes when the document itself changes", async () => {
736 using _settings = setup();
737 await using screen = await render(documentPreview("mutation-1", "revision-1"));
738 const preview = screen.getByTestId("office-preview");
739 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
740​
741 await screen.rerender(documentPreview("mutation-2", "revision-2"));
742​
743 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=2");
744 });
745});
746​
747describe("open file in preview browser", () => {
748 it("mints a fresh asset URL on every click so the browser cannot reuse cached bytes", async () => {
749 using _settings = setup();
750 state.file = {
751 relativePath: "page.html",
752 contents: "<h1>page</h1>",
753 byteLength: 13,
754 truncated: false,
755 };
756 await using screen = await render(filePreview("page.html"));
757 const button = screen.getByRole("button", { name: "Open file in preview browser" });
758​
759 await userEvent.click(button);
760 await vi.waitFor(() => expect(state.openedBrowserUrls).toHaveLength(1));
761 await userEvent.click(button);
762 await vi.waitFor(() => expect(state.openedBrowserUrls).toHaveLength(2));
763​
764 expect(state.openedBrowserUrls[1], "the second click reused the first signed URL").not.toBe(
765 state.openedBrowserUrls[0],
766 );
767 });
768});
769​
770describe("rendered Markdown select all", () => {
771 it("selects only the rendered file, including after a task toggle", async () => {
772 using _settings = setup();
773 await using screen = await render(
774 <>
775 <p>Transcript text from the chat thread.</p>
776 {markdownPreview(false, "- [ ] Task item\n\nRendered file body.\n")}
777 </>,
778 );
779 const expectFileOnlySelection = async () => {
780 await userEvent.keyboard(
781 isMacPlatform(navigator.platform) ? "{Meta>}a{/Meta}" : "{Control>}a{/Control}",
782 );
783 const selection = window.getSelection()?.toString() ?? "";
784 expect(selection).toContain("Rendered file body.");
785 expect(selection).not.toContain("Transcript text from the chat thread.");
786 };
787​
788 await userEvent.click(screen.getByText("Rendered file body."));
789 await expectFileOnlySelection();
790 // A toggled checkbox keeps focus on an input inside the preview.
791 await userEvent.click(screen.getByRole("checkbox"));
792 await expectFileOnlySelection();
793 });
794});
795​
796describe("rendered Markdown relative images", () => {
797 it.each([
798 ["2026-11-23T14:05/README.md", "/workspace/2026-11-23T14:05/diagram.png"],
799 ["/README.md", "/diagram.png"],
800 ])("resolves relative images in %s against its folder", async (relativePath, expectedPath) => {
801 using _settings = setup();
802 await using _screen = await render(
803 markdownPreview(false, "![diagram](diagram.png)\n", relativePath),
804 );
805 await vi.waitFor(() => expect(state.assetResources).not.toHaveLength(0));
806 expect(state.assetResources).toContainEqual(
807 expect.objectContaining({ _tag: "media-file", path: expectedPath }),
808 );
809 });
810});
811​
812describe("rendered Markdown scroll position", () => {
813 const sections = Array.from(
814 { length: 200 },
815 (_, index) => `## Section ${index}\n\nParagraph ${index}.\n`,
816 ).join("\n");
817 const scroller = () =>
818 document.querySelector<HTMLElement>(".scrollbar-gutter-both") ?? expect.unreachable();
819 /** The first heading in view and its offset from the top of the viewport. */
820 const readingPosition = () => {
821 const top = scroller().getBoundingClientRect().top;
822 for (const heading of scroller().querySelectorAll("h2")) {
823 const offset = Math.round(heading.getBoundingClientRect().top - top);
824 if (offset > -100) return { heading: heading.textContent, offset };
825 }
826 return null;
827 };
828 const scrollDown = async () => {
829 scroller().scrollTop = 3000;
830 scroller().dispatchEvent(new Event("scroll"));
831 await vi.waitFor(() => expect(readingPosition()?.heading).not.toBe("Section 0"));
832 return readingPosition();
833 };
834 const expectReadingPosition = (saved: ReturnType<typeof readingPosition>) =>
835 vi.waitFor(() => {
836 const position = readingPosition();
837 expect(position?.heading).toBe(saved?.heading);
838 expect(Math.abs((position?.offset ?? 0) - (saved?.offset ?? 0))).toBeLessThanOrEqual(2);
839 });
840 const withAppCss = () => {
841 const style = document.createElement("style");
842 style.textContent = appCss;
843 document.head.append(style);
844 return { [Symbol.dispose]: () => style.remove() };
845 };
846 const sized = (children: ReactNode) => (
847 <div style={{ width: 500, height: 400, display: "flex", flexDirection: "column" }}>
848 {children}
849 </div>
850 );
851​
852 it("restores each file's reading position after the preview remounts", async () => {
853 using _settings = setup();
854 using _style = withAppCss();
855 const preview = (relativePath: string) => sized(markdownPreview(false, sections, relativePath));
856​
857 let saved: ReturnType<typeof readingPosition>;
858 {
859 await using screen = await render(preview("long.md"));
860 await expect.element(screen.getByText("Section 0", { exact: true })).toBeInTheDocument();
861 saved = await scrollDown();
862 }
863 {
864 await using screen = await render(preview("other.md"));
865 await expect.element(screen.getByText("Section 0", { exact: true })).toBeInTheDocument();
866 expect(scroller().scrollTop, "another file opens at the top").toBe(0);
867 }
868 await using _screen = await render(preview("long.md"));
869 await expectReadingPosition(saved);
870 });
871​
872 it("waits for the saved chunk when a reopened file is still streaming in", async () => {
873 using _settings = setup();
874 using _style = withAppCss();
875 const { chunks, definitions } = splitMarkdown(sections, 200);
876 const preview = (loaded: number, loading: boolean) =>
877 sized(
878 <ChunkedMarkdown
879 chunks={chunks.slice(0, loaded)}
880 definitions={definitions}
881 loading={loading}
882 cwd="/workspace"
883 relativePath="streaming.md"
884 threadRef={threadRef}
885 workspaceMutationId={null}
886 />,
887 );
888​
889 let saved: ReturnType<typeof readingPosition>;
890 {
891 await using screen = await render(preview(chunks.length, false));
892 await expect.element(screen.getByText("Section 0", { exact: true })).toBeInTheDocument();
893 saved = await scrollDown();
894 }
895 await using screen = await render(preview(3, true));
896 expect(document.querySelector(".scrollbar-gutter-both"), "no list before the chunk").toBeNull();
897 await screen.rerender(preview(chunks.length, false));
898 await expectReadingPosition(saved);
899 });
900​
901 it("keeps each thread's position when the same file stays open across threads", async () => {
902 using _settings = setup();
903 using _style = withAppCss();
904 const { chunks, definitions } = splitMarkdown(sections, 200);
905 const preview = (threadId: string) =>
906 sized(
907 <ChunkedMarkdown
908 chunks={chunks}
909 definitions={definitions}
910 cwd="/workspace"
911 relativePath="shared.md"
912 threadRef={{ environmentId, threadId: ThreadId.make(threadId) }}
913 workspaceMutationId={null}
914 />,
915 );
916​
917 await using screen = await render(preview("first"));
918 await expect.element(screen.getByText("Section 0", { exact: true })).toBeInTheDocument();
919 const saved = await scrollDown();
920 await screen.rerender(preview("second"));
921 await vi.waitFor(() => expect(readingPosition()?.heading).toBe("Section 0"));
922 await screen.rerender(preview("first"));
923 await expectReadingPosition(saved);
924 });
925});