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 { 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 mintUrl: vi.fn<() => Promise<string | null>>(),
22 browserAssetMints: 0,
23 openedBrowserUrls: [] as string[],
24}));
25
26vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => ({
27 ...(await original()),
28 runAtomCommand: ((_registry: unknown, _command: unknown, request: unknown) =>
29 state.writeFile(request)) as never,
30}));
31vi.mock(import("~/state/session"), async (original) => ({
32 ...(await original()),
33 readEnvironmentScope: () => true,
34 useEnvironmentScope: () => true,
35}));
36vi.mock(import("~/state/filesystem"), async (original) => ({
37 ...(await original()),
38 useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }),
39}));
40vi.mock(import("~/state/use-atom-command"), async (original) => ({
41 ...(await original()),
42 useAtomCommand: (() => state.writeFile) as never,
43}));
44vi.mock(import("~/state/server"), async (original) => {
45 const actual = await original();
46 const { Atom } = await import("effect/reactivity");
47 const noConfig = Atom.make(null);
48 return {
49 ...actual,
50 serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => noConfig) as never },
51 };
52});
53vi.mock(import("~/remoteOpen"), async (original) => ({
54 ...(await original()),
55 useRemoteOpenState: () => ({ mode: "local-exec" }) as never,
56 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
57}));
58vi.mock(import("~/hooks/useTheme"), async (original) => ({
59 ...(await original()),
60 useTheme: () => ({ resolvedTheme: "dark" }) as never,
61}));
62vi.mock(import("~/hooks/useWorkspaceMutationRefresh"), () => ({
63 useWorkspaceMutationRefresh: vi.fn(),
64}));
65vi.mock(import("~/assets/assetUrls"), async (original) => ({
66 ...(await original()),
67 useAssetUrlRefresh: () => state.mintUrl,
68 useAssetUrlState: () => state.assetUrl,
69}));
70vi.mock(import("~/browser/previewRuntime"), async (original) => ({
71 ...(await original()),
72 usePreviewAvailable: () => true,
73}));
74vi.mock(import("~/state/environments"), async (original) => ({
75 ...(await original()),
76 useEnvironmentHttpBaseUrl: () => "http://environment.test",
77}));
78vi.mock(import("~/state/assets"), async (original) => {
79 const actual = await original();
80 const { Atom } = await import("effect/reactivity");
81 const Effect = await import("effect/Effect");
82 // Like the real query family, a minted URL stays cached until the atom is refreshed.
83 const createUrl = Atom.family((_key: string) =>
84 Atom.make(
85 Effect.sync(() => ({
86 relativeUrl: `/api/assets/mint-${++state.browserAssetMints}/page.html`,
87 expiresAt: Number.MAX_SAFE_INTEGER,
88 })),
89 ).pipe(Atom.keepAlive),
90 );
91 return {
92 ...actual,
93 assetEnvironment: {
94 ...actual.assetEnvironment,
95 createUrl: ((target: { input: { resource: { path: string } } }) =>
96 createUrl(target.input.resource.path)) as never,
97 },
98 };
99});
100vi.mock(import("~/browser/openFileInPreview"), async (original) => {
101 const actual = await original();
102 return {
103 ...actual,
104 openFileInPreview: (async (input: Parameters<typeof actual.openFileInPreview>[0]) => {
105 const result = await input.createAssetUrl({
106 environmentId: input.threadRef.environmentId,
107 input: {
108 resource: {
109 _tag: "workspace-file",
110 threadId: input.threadRef.threadId,
111 path: input.filePath,
112 },
113 },
114 });
115 if (result._tag === "Success") state.openedBrowserUrls.push(result.value.relativeUrl);
116 return AsyncResult.success(undefined);
117 }) as never,
118 };
119});
120// The Word engine compiles a large WebAssembly bundle; these tests only need the URL it loads.
121vi.mock(import("./OfficeFilePreview"), () => ({
122 OfficeFilePreview: ({ src }: { src: string }) => <div data-testid="office-preview">{src}</div>,
123}));
124vi.mock(import("./FileBreadcrumbs"), () => ({ FileBreadcrumbs: () => <></> }));
125vi.mock(import("./FileBrowserPanel"), () => ({
126 default: () => (
127 <div role="tree">
128 <button type="button" role="treeitem" data-item-path="src/">
129 src
130 </button>
131 <button type="button" role="treeitem" data-item-path="server.ts">
132 server.ts
133 </button>
134 </div>
135 ),
136}));
137vi.mock(import("../DiffWorkerPoolProvider"), () => ({
138 DiffWorkerPoolProvider: ({ children }: { children?: ReactNode }) => <>{children}</>,
139}));
140vi.mock(import("./projectFilesQueryState"), async (original) => ({
141 ...(await original()),
142 useProjectFileQuery: () => ({
143 data: state.file,
144 error: null,
145 isPending: false,
146 readError: null,
147 isNotFile: false,
148 isFile: true,
149 refresh: vi.fn(),
150 }),
151 getOptimisticProjectFileQueryData: () => state.optimistic,
152 getUnsavedProjectFileQueryData: () => null,
153 setProjectFileQueryData: (
154 _environmentId: EnvironmentId,
155 _cwd: string,
156 relativePath: string,
157 contents: string,
158 ) => {
159 state.optimistic = { relativePath, contents, truncated: false, byteLength: contents.length };
160 },
161 confirmProjectFileQueryData: () => true,
162}));
163
164import FilePreviewPanel from "./FilePreviewPanel";
165
166const environmentId = EnvironmentId.make("markdown-preview-test");
167const threadRef = { environmentId, threadId: ThreadId.make("thread") };
168function setup() {
169 const keys = ["t3code.fileExplorerOpen", "t3code.renderMarkdown"];
170 const previous = keys.map((key) => localStorage.getItem(key));
171 localStorage.setItem(keys[0]!, "false");
172 localStorage.setItem(keys[1]!, "true");
173 state.file = null;
174 state.optimistic = null;
175 state.assetUrl = { _tag: "Loading" };
176 state.openedBrowserUrls = [];
177 let mints = 0;
178 state.mintUrl.mockReset().mockImplementation(async () => `/assets/report.docx?mint=${++mints}`);
179 state.writeFile.mockReset().mockResolvedValue(AsyncResult.success(undefined));
180 return {
181 [Symbol.dispose]() {
182 for (const [index, key] of keys.entries()) {
183 const value = previous[index];
184 if (value == null) localStorage.removeItem(key);
185 else localStorage.setItem(key, value);
186 }
187 },
188 };
189}
190
191function markdownPreview(truncated: boolean, contents = "- [ ] Keep the rest of this file\n") {
192 state.file = {
193 relativePath: "tasks.md",
194 contents,
195 byteLength: truncated ? 1_200_000 : contents.length,
196 truncated,
197 };
198 return filePreview("tasks.md");
199}
200
201function filePreview(relativePath: string, workspaceMutationId: string | null = null) {
202 return (
203 <FilePreviewPanel
204 environmentId={environmentId}
205 cwd="/workspace"
206 projectName="Project"
207 relativePath={relativePath}
208 threadRef={threadRef}
209 composerDraftTarget={threadRef}
210 keybindings={[]}
211 availableEditors={[]}
212 openInShortcutEnabled={false}
213 revealLine={null}
214 revealRequestId={0}
215 onOpenFile={vi.fn()}
216 onNavigateFolder={vi.fn()}
217 folderTrail={undefined}
218 onPendingChange={vi.fn()}
219 selectedFilePending={false}
220 workspaceMutationId={workspaceMutationId}
221 />
222 );
223}
224
225function documentPreview(workspaceMutationId: string, fileRevision: string) {
226 state.file = null;
227 state.assetUrl = {
228 _tag: "Success",
229 url: "/assets/report.docx",
230 expiresAt: Number.MAX_SAFE_INTEGER,
231 fileRevision,
232 };
233 return filePreview("report.docx", workspaceMutationId);
234}
235
236function deepActiveElement() {
237 let active = document.activeElement;
238 while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
239 return active;
240}
241
242describe("source file focus", () => {
243 it("hands panel focus to the file's editor, which owns mod+f", async () => {
244 using _settings = setup();
245 const style = document.createElement("style");
246 style.textContent = appCss;
247 document.head.append(style);
248 using _style = { [Symbol.dispose]: () => style.remove() };
249 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] });
250 const panel = () => (
251 <div {...workspaceAreaProps("panel", 1, "Workspace panel")}>
252 <div data-right-panel-surface-content>{filePreview("server.ts")}</div>
253 </div>
254 );
255 const editorHasFocus = () => expect(deepActiveElement()?.matches("[data-content]")).toBe(true);
256
257 await using screen = await render(panel());
258 const focus = createWorkspaceFocusController(document);
259 using _focus = { [Symbol.dispose]: focus.dispose };
260 expect(focus.focus("panel")).toBe(true);
261 state.file = {
262 relativePath: "server.ts",
263 contents: "const server = 1;\n",
264 byteLength: 18,
265 truncated: false,
266 };
267 await screen.rerender(panel());
268 await vi.waitFor(editorHasFocus);
269 await userEvent.keyboard("x");
270 await vi.waitFor(() => expect(deepActiveElement()?.textContent).toContain("xconst server"));
271
272 (deepActiveElement() as HTMLElement).blur();
273 expect(focus.focus("panel", false)).toBe(true);
274 await vi.waitFor(editorHasFocus);
275 await userEvent.keyboard(
276 isMacPlatform(navigator.platform) ? "{Meta>}f{/Meta}" : "{Control>}f{/Control}",
277 );
278 await vi.waitFor(() => expect(deepActiveElement()).toBeInstanceOf(HTMLInputElement));
279
280 const findField = deepActiveElement() as HTMLInputElement;
281 await userEvent.keyboard("server");
282 findField.blur();
283 expect(focus.focus("panel", false)).toBe(true);
284 await vi.waitFor(editorHasFocus);
285 const editor = deepActiveElement() as HTMLElement;
286 await userEvent.keyboard("ab");
287 await vi.waitFor(() => expect(editor.textContent).toContain("xabconst server"));
288 expect(findField.value).toBe("server");
289 editorHasFocus();
290 });
291
292 it("focuses the editor when a file row is clicked or activated with Enter", async () => {
293 using _settings = setup();
294 localStorage.setItem("t3code.fileExplorerOpen", "true");
295 const style = document.createElement("style");
296 style.textContent = appCss;
297 document.head.append(style);
298 using _style = { [Symbol.dispose]: () => style.remove() };
299 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] });
300 state.file = {
301 relativePath: "server.ts",
302 contents: "const server = 1;\n",
303 byteLength: 18,
304 truncated: false,
305 };
306 await using screen = await render(
307 <div {...workspaceAreaProps("panel", 1, "Workspace panel")} style={{ width: 900 }}>
308 <div data-right-panel-surface-content>{filePreview("server.ts")}</div>
309 </div>,
310 );
311 using _focus = {
312 [Symbol.dispose]: startWorkspaceFocus({ subscribe: () => () => {} } as never),
313 };
314 const editorHasFocus = () => expect(deepActiveElement()?.matches("[data-content]")).toBe(true);
315 // The explorer measures its parent row; a wrapper without a box would cap it at the minimum.
316 await expect
317 .element(screen.getByRole("separator", { name: "Resize file explorer" }))
318 .toHaveAttribute("aria-valuemax", "560");
319 const folderRow = screen.getByRole("treeitem", { name: "src" });
320 const fileRow = screen.getByRole("treeitem", { name: "server.ts" });
321
322 (folderRow.element() as HTMLElement).focus();
323 await userEvent.keyboard("{Enter}");
324 expect(document.activeElement).toBe(folderRow.element());
325
326 await userEvent.click(fileRow);
327 await vi.waitFor(editorHasFocus);
328
329 (fileRow.element() as HTMLElement).focus();
330 await userEvent.keyboard("{Enter}");
331 await vi.waitFor(editorHasFocus);
332 });
333});
334
335describe("source file scroll", () => {
336 it("returns a file tab to where it was scrolled after another file was shown", async () => {
337 using _settings = setup();
338 const style = document.createElement("style");
339 style.textContent = appCss;
340 document.head.append(style);
341 using _style = { [Symbol.dispose]: () => style.remove() };
342 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] });
343 const sourceFile = (relativePath: string, lines: number) => {
344 const contents = Array.from({ length: lines }, (_, i) => `const line${i} = ${i};`).join("\n");
345 state.file = { relativePath, contents, byteLength: contents.length, truncated: false };
346 // The app mounts under StrictMode, whose remount must not wipe the saved offset.
347 return (
348 <StrictMode>
349 <div style={{ height: 400, display: "flex", flexDirection: "column" }}>
350 {filePreview(relativePath)}
351 </div>
352 </StrictMode>
353 );
354 };
355 const scroller = () => document.querySelector<HTMLElement>(".file-preview-virtualizer");
356
357 await using screen = await render(sourceFile("a.ts", 2000));
358 await vi.waitFor(() => expect(scroller()?.scrollHeight).toBeGreaterThan(5000));
359 scroller()!.scrollTop = 4200;
360 await vi.waitFor(() => expect(scroller()?.scrollTop).toBe(4200));
361
362 await screen.rerender(sourceFile("b.ts", 1500));
363 await vi.waitFor(() => expect(scroller()?.scrollTop).toBe(0));
364 await screen.rerender(sourceFile("a.ts", 2000));
365
366 await vi.waitFor(() => expect(scroller()?.scrollTop).toBe(4200));
367 });
368});
369
370describe("rendered Markdown task saves", () => {
371 it("keeps a truncated read read-only without queuing a replacement", async () => {
372 using _settings = setup();
373 await using screen = await render(markdownPreview(true));
374 using _timers = fakeTimers();
375 const checkbox = screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
376 expect(checkbox).not.toBeNull();
377 expect(checkbox.disabled).toBe(true);
378 expect(checkbox.readOnly).toBe(true);
379 await act(async () => checkbox.click());
380 await vi.advanceTimersByTimeAsync(500);
381 expect(checkbox.checked).toBe(false);
382 expect(state.optimistic).toBeNull();
383 expect(state.writeFile).not.toHaveBeenCalled();
384 });
385
386 it("still toggles and saves tasks from a complete read", async () => {
387 using _settings = setup();
388 await using screen = await render(markdownPreview(false));
389 using _timers = fakeTimers();
390 const checkbox = screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
391 expect(checkbox).not.toBeNull();
392 expect(checkbox.disabled).toBe(false);
393 await act(async () => checkbox.click());
394 await vi.advanceTimersByTimeAsync(500);
395 expect(state.writeFile).toHaveBeenCalledExactlyOnceWith({
396 environmentId,
397 input: {
398 cwd: "/workspace",
399 relativePath: "tasks.md",
400 contents: "- [x] Keep the rest of this file\n",
401 },
402 });
403 });
404});
405
406describe("workspace document previews", () => {
407 it("keeps an unchanged document loaded when another workspace change lands", async () => {
408 using _settings = setup();
409 await using screen = await render(documentPreview("mutation-1", "revision-1"));
410 const preview = screen.getByTestId("office-preview");
411 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
412 const loaded = preview.element();
413
414 await screen.rerender(documentPreview("mutation-2", "revision-1"));
415
416 expect(state.mintUrl, "an unchanged document re-minted its URL").toHaveBeenCalledOnce();
417 expect(screen.container.contains(loaded), "an unchanged document was remounted").toBe(true);
418 });
419
420 it("keeps an unchanged document mounted while its revision check reloads", async () => {
421 using _settings = setup();
422 await using screen = await render(documentPreview("mutation-1", "revision-1"));
423 const preview = screen.getByTestId("office-preview");
424 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
425 const loaded = preview.element();
426
427 state.assetUrl = { _tag: "Loading" };
428 await screen.rerender(filePreview("report.docx", "mutation-1"));
429 await screen.rerender(documentPreview("mutation-1", "revision-1"));
430
431 expect(
432 state.mintUrl,
433 "a reloading revision check re-minted the document URL",
434 ).toHaveBeenCalledOnce();
435 expect(
436 screen.container.contains(loaded),
437 "a reloading revision check remounted the document",
438 ).toBe(true);
439 });
440
441 it("reloads the document when its URL can no longer be minted", async () => {
442 using _settings = setup();
443 await using screen = await render(documentPreview("mutation-1", "revision-1"));
444 const preview = screen.getByTestId("office-preview");
445 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
446
447 state.assetUrl = { _tag: "Failure" };
448 await screen.rerender(filePreview("report.docx", "mutation-2"));
449
450 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=2");
451 });
452
453 it("loads the new bytes when the document itself changes", async () => {
454 using _settings = setup();
455 await using screen = await render(documentPreview("mutation-1", "revision-1"));
456 const preview = screen.getByTestId("office-preview");
457 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1");
458
459 await screen.rerender(documentPreview("mutation-2", "revision-2"));
460
461 await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=2");
462 });
463});
464
465describe("open file in preview browser", () => {
466 it("mints a fresh asset URL on every click so the browser cannot reuse cached bytes", async () => {
467 using _settings = setup();
468 state.file = {
469 relativePath: "page.html",
470 contents: "<h1>page</h1>",
471 byteLength: 13,
472 truncated: false,
473 };
474 await using screen = await render(filePreview("page.html"));
475 const button = screen.getByRole("button", { name: "Open file in preview browser" });
476
477 await userEvent.click(button);
478 await vi.waitFor(() => expect(state.openedBrowserUrls).toHaveLength(1));
479 await userEvent.click(button);
480 await vi.waitFor(() => expect(state.openedBrowserUrls).toHaveLength(2));
481
482 expect(state.openedBrowserUrls[1], "the second click reused the first signed URL").not.toBe(
483 state.openedBrowserUrls[0],
484 );
485 });
486});
487
488describe("rendered Markdown select all", () => {
489 it("selects only the rendered file, including after a task toggle", async () => {
490 using _settings = setup();
491 await using screen = await render(
492 <>
493 <p>Transcript text from the chat thread.</p>
494 {markdownPreview(false, "- [ ] Task item\n\nRendered file body.\n")}
495 </>,
496 );
497 const expectFileOnlySelection = async () => {
498 await userEvent.keyboard(
499 isMacPlatform(navigator.platform) ? "{Meta>}a{/Meta}" : "{Control>}a{/Control}",
500 );
501 const selection = window.getSelection()?.toString() ?? "";
502 expect(selection).toContain("Rendered file body.");
503 expect(selection).not.toContain("Transcript text from the chat thread.");
504 };
505
506 await userEvent.click(screen.getByText("Rendered file body."));
507 await expectFileOnlySelection();
508 // A toggled checkbox keeps focus on an input inside the preview.
509 await userEvent.click(screen.getByRole("checkbox"));
510 await expectFileOnlySelection();
511 });
512});