The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { DEFAULT_THEMES, preloadHighlighter } from "@pierre/diffs"; |
| 2 | import { EnvironmentId, ThreadId, type ProjectReadFileResult } from "@t3tools/contracts"; |
| 3 | import { AsyncResult } from "effect/reactivity"; |
| 4 | import { StrictMode, type ReactNode } from "react"; |
| 5 | import { describe, expect, it, vi } from "vite-plus/test"; |
| 6 | import { cdp, userEvent } from "vite-plus/test/browser"; |
| 7 | import { act, fakeTimers, render } from "../../../test/render"; |
| 8 | import appCss from "~/index.css?inline"; |
| 9 | import { isMacPlatform } from "~/lib/utils"; |
| 10 | import { |
| 11 | createWorkspaceFocusController, |
| 12 | startWorkspaceFocus, |
| 13 | workspaceAreaProps, |
| 14 | } from "~/lib/workspaceFocus"; |
| 15 | |
| 16 | const 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 | |
| 26 | vi.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 | })); |
| 31 | vi.mock(import("~/state/session"), async (original) => ({ |
| 32 | ...(await original()), |
| 33 | readEnvironmentScope: () => true, |
| 34 | useEnvironmentScope: () => true, |
| 35 | })); |
| 36 | vi.mock(import("~/state/filesystem"), async (original) => ({ |
| 37 | ...(await original()), |
| 38 | useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }), |
| 39 | })); |
| 40 | vi.mock(import("~/state/use-atom-command"), async (original) => ({ |
| 41 | ...(await original()), |
| 42 | useAtomCommand: (() => state.writeFile) as never, |
| 43 | })); |
| 44 | vi.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 | }); |
| 53 | vi.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 | })); |
| 58 | vi.mock(import("~/hooks/useTheme"), async (original) => ({ |
| 59 | ...(await original()), |
| 60 | useTheme: () => ({ resolvedTheme: "dark" }) as never, |
| 61 | })); |
| 62 | vi.mock(import("~/hooks/useWorkspaceMutationRefresh"), () => ({ |
| 63 | useWorkspaceMutationRefresh: vi.fn(), |
| 64 | })); |
| 65 | vi.mock(import("~/assets/assetUrls"), async (original) => ({ |
| 66 | ...(await original()), |
| 67 | useAssetUrlRefresh: () => state.mintUrl, |
| 68 | useAssetUrlState: () => state.assetUrl, |
| 69 | })); |
| 70 | vi.mock(import("~/browser/previewRuntime"), async (original) => ({ |
| 71 | ...(await original()), |
| 72 | usePreviewAvailable: () => true, |
| 73 | })); |
| 74 | vi.mock(import("~/state/environments"), async (original) => ({ |
| 75 | ...(await original()), |
| 76 | useEnvironmentHttpBaseUrl: () => "http://environment.test", |
| 77 | })); |
| 78 | vi.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 | }); |
| 100 | vi.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. |
| 121 | vi.mock(import("./OfficeFilePreview"), () => ({ |
| 122 | OfficeFilePreview: ({ src }: { src: string }) => <div data-testid="office-preview">{src}</div>, |
| 123 | })); |
| 124 | vi.mock(import("./FileBreadcrumbs"), () => ({ FileBreadcrumbs: () => <></> })); |
| 125 | vi.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 | })); |
| 137 | vi.mock(import("../DiffWorkerPoolProvider"), () => ({ |
| 138 | DiffWorkerPoolProvider: ({ children }: { children?: ReactNode }) => <>{children}</>, |
| 139 | })); |
| 140 | vi.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 | |
| 164 | import FilePreviewPanel from "./FilePreviewPanel"; |
| 165 | |
| 166 | const environmentId = EnvironmentId.make("markdown-preview-test"); |
| 167 | const threadRef = { environmentId, threadId: ThreadId.make("thread") }; |
| 168 | function 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 | |
| 191 | function 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 | |
| 201 | function 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 | |
| 225 | function 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 | |
| 236 | function deepActiveElement() { |
| 237 | let active = document.activeElement; |
| 238 | while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement; |
| 239 | return active; |
| 240 | } |
| 241 | |
| 242 | describe("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 | |
| 335 | describe("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 | it.each([ |
| 370 | { |
| 371 | label: "keeps a downward drag whose anchor stays mounted across a window shift", |
| 372 | startLine: 65, |
| 373 | initialScrollLine: 65, |
| 374 | direction: "down" as const, |
| 375 | targetFirstMounted: 101, |
| 376 | expectedIncludedLine: 121, |
| 377 | }, |
| 378 | { |
| 379 | label: "keeps a downward drag whose anchor unmounts on a window shift", |
| 380 | startLine: 5, |
| 381 | initialScrollLine: null, |
| 382 | direction: "down" as const, |
| 383 | targetFirstMounted: 101, |
| 384 | expectedIncludedLine: 121, |
| 385 | }, |
| 386 | { |
| 387 | label: "keeps an upward drag whose anchor unmounts on a window shift", |
| 388 | startLine: 385, |
| 389 | initialScrollLine: 385, |
| 390 | direction: "up" as const, |
| 391 | targetFirstMounted: 201, |
| 392 | expectedIncludedLine: 290, |
| 393 | }, |
| 394 | ])( |
| 395 | "$label", |
| 396 | async ({ |
| 397 | startLine, |
| 398 | initialScrollLine, |
| 399 | direction, |
| 400 | targetFirstMounted, |
| 401 | expectedIncludedLine, |
| 402 | }) => { |
| 403 | using _settings = setup(); |
| 404 | localStorage.setItem("t3code.renderMarkdown", "false"); |
| 405 | const style = document.createElement("style"); |
| 406 | style.textContent = appCss; |
| 407 | document.head.append(style); |
| 408 | using _style = { [Symbol.dispose]: () => style.remove() }; |
| 409 | await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["markdown"] }); |
| 410 | |
| 411 | const lines = Array.from({ length: 400 }, (_, index) => `line ${index + 1} markdown content`); |
| 412 | const contents = `${lines.join("\n")}\n`; |
| 413 | state.file = { |
| 414 | relativePath: "notes.md", |
| 415 | contents, |
| 416 | byteLength: contents.length, |
| 417 | truncated: false, |
| 418 | }; |
| 419 | |
| 420 | await using screen = await render( |
| 421 | <div style={{ width: 560, height: 400, display: "flex", flexDirection: "column" }}> |
| 422 | {filePreview("notes.md")} |
| 423 | </div>, |
| 424 | ); |
| 425 | |
| 426 | const shadowRoot = () => screen.container.querySelector("diffs-container")?.shadowRoot; |
| 427 | const rows = () => shadowRoot()?.querySelectorAll<HTMLElement>("[data-line]") ?? []; |
| 428 | await vi.waitFor(() => |
| 429 | expect( |
| 430 | shadowRoot()?.querySelector('[data-content][contenteditable="true"]'), |
| 431 | ).not.toBeNull(), |
| 432 | ); |
| 433 | |
| 434 | const scroller = screen.container.querySelector<HTMLElement>(".file-preview-virtualizer")!; |
| 435 | if (initialScrollLine !== null) { |
| 436 | if (direction === "up") { |
| 437 | await vi.waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(5000)); |
| 438 | scroller.scrollTop = scroller.scrollHeight; |
| 439 | await vi.waitFor(() => |
| 440 | expect( |
| 441 | [...rows()].some((row) => row.getAttribute("data-line") === String(startLine)), |
| 442 | ).toBe(true), |
| 443 | ); |
| 444 | } |
| 445 | const target = [...rows()].find( |
| 446 | (row) => row.getAttribute("data-line") === String(initialScrollLine), |
| 447 | ); |
| 448 | expect(target).toBeDefined(); |
| 449 | target!.scrollIntoView({ block: direction === "up" ? "end" : "start" }); |
| 450 | await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(0)); |
| 451 | } |
| 452 | |
| 453 | const startRow = [...rows()].find( |
| 454 | (row) => row.getAttribute("data-line") === String(startLine), |
| 455 | ); |
| 456 | expect(startRow).toBeDefined(); |
| 457 | const startRect = startRow!.getBoundingClientRect(); |
| 458 | const scrollerRect = scroller.getBoundingClientRect(); |
| 459 | const nearEdgeY = direction === "down" ? scrollerRect.bottom - 5 : scrollerRect.top + 5; |
| 460 | const outsideEdgeY = direction === "down" ? scrollerRect.bottom + 60 : scrollerRect.top - 60; |
| 461 | const frame = window.frameElement?.getBoundingClientRect(); |
| 462 | const mouse = (type: "mousePressed" | "mouseMoved" | "mouseReleased", x: number, y: number) => |
| 463 | cdp().send("Input.dispatchMouseEvent", { |
| 464 | type, |
| 465 | x: x + (frame?.left ?? 0), |
| 466 | y: y + (frame?.top ?? 0), |
| 467 | button: "left", |
| 468 | buttons: type === "mouseReleased" ? 0 : 1, |
| 469 | clickCount: 1, |
| 470 | }); |
| 471 | |
| 472 | const startX = direction === "up" ? startRect.left + 140 : startRect.left + 2; |
| 473 | // The editor records the drag anchor on the press's selectionchange; drag only after it. |
| 474 | const anchored = new Promise((resolve) => |
| 475 | document.addEventListener("selectionchange", resolve, { once: true }), |
| 476 | ); |
| 477 | await mouse("mousePressed", startX, startRect.top + 5); |
| 478 | await anchored; |
| 479 | await mouse("mouseMoved", startRect.left + 80, nearEdgeY); |
| 480 | await mouse("mouseMoved", startRect.left + 80, outsideEdgeY); |
| 481 | await vi.waitFor(() => { |
| 482 | const firstMounted = Number(rows()[0]?.getAttribute("data-line")); |
| 483 | if (direction === "down") { |
| 484 | expect(firstMounted).toBeGreaterThanOrEqual(targetFirstMounted); |
| 485 | } else { |
| 486 | expect(firstMounted).toBeLessThanOrEqual(targetFirstMounted); |
| 487 | } |
| 488 | }); |
| 489 | await mouse("mouseReleased", startRect.left + 80, outsideEdgeY); |
| 490 | |
| 491 | const overlayRanges = shadowRoot()!.querySelectorAll("[data-selection-range]"); |
| 492 | expect(overlayRanges.length).toBeGreaterThan(0); |
| 493 | |
| 494 | const clipboardData = new DataTransfer(); |
| 495 | const contentEl = shadowRoot()!.querySelector("[data-content]")!; |
| 496 | const handled = !contentEl.dispatchEvent( |
| 497 | new ClipboardEvent("copy", { |
| 498 | clipboardData, |
| 499 | bubbles: true, |
| 500 | cancelable: true, |
| 501 | composed: true, |
| 502 | }), |
| 503 | ); |
| 504 | expect(handled).toBe(true); |
| 505 | const copied = clipboardData.getData("text/plain"); |
| 506 | expect(copied).toContain(`line ${startLine} `); |
| 507 | expect(copied).toContain(`line ${expectedIncludedLine} markdown content`); |
| 508 | }, |
| 509 | ); |
| 510 | |
| 511 | it("scrolls a find match below many wrapped lines into view", async () => { |
| 512 | using _settings = setup(); |
| 513 | const style = document.createElement("style"); |
| 514 | style.textContent = appCss; |
| 515 | document.head.append(style); |
| 516 | using _style = { [Symbol.dispose]: () => style.remove() }; |
| 517 | await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] }); |
| 518 | const wrapped = "wrap ".repeat(60); |
| 519 | const lines = Array.from({ length: 800 }, (_, i) => `const line${i} = "${wrapped}";`); |
| 520 | lines.push( |
| 521 | "const needle = 1;", |
| 522 | ...Array.from({ length: 40 }, (_, i) => `const tail${i} = ${i};`), |
| 523 | ); |
| 524 | const contents = lines.join("\n"); |
| 525 | state.file = { |
| 526 | relativePath: "wrapped.ts", |
| 527 | contents, |
| 528 | byteLength: contents.length, |
| 529 | truncated: false, |
| 530 | }; |
| 531 | const scroller = () => document.querySelector<HTMLElement>(".file-preview-virtualizer"); |
| 532 | |
| 533 | await using _screen = await render( |
| 534 | <div style={{ width: 500, height: 400, display: "flex", flexDirection: "column" }}> |
| 535 | {filePreview("wrapped.ts")} |
| 536 | </div>, |
| 537 | ); |
| 538 | await vi.waitFor(() => expect(scroller()?.scrollHeight).toBeGreaterThan(20_000)); |
| 539 | const shadowRows = () => |
| 540 | [...document.querySelectorAll("*")].flatMap((host) => |
| 541 | host.shadowRoot ? [...host.shadowRoot.querySelectorAll<HTMLElement>("[data-line]")] : [], |
| 542 | ); |
| 543 | await userEvent.click(shadowRows().find((row) => row.getAttribute("data-line") === "1")!); |
| 544 | await vi.waitFor(() => expect(deepActiveElement()?.matches("[data-content]")).toBe(true)); |
| 545 | await userEvent.keyboard( |
| 546 | isMacPlatform(navigator.platform) ? "{Meta>}f{/Meta}" : "{Control>}f{/Control}", |
| 547 | ); |
| 548 | await vi.waitFor(() => expect(deepActiveElement()).toBeInstanceOf(HTMLInputElement)); |
| 549 | await userEvent.keyboard("needle{Enter}"); |
| 550 | |
| 551 | const visibleLines = () => { |
| 552 | const viewport = scroller()!.getBoundingClientRect(); |
| 553 | return shadowRows() |
| 554 | .filter((row) => { |
| 555 | const box = row.getBoundingClientRect(); |
| 556 | return box.height > 0 && box.top >= viewport.top && box.bottom <= viewport.bottom; |
| 557 | }) |
| 558 | .map((row) => Number(row.getAttribute("data-line"))); |
| 559 | }; |
| 560 | await vi.waitFor(() => expect(visibleLines()).toContain(801)); |
| 561 | }); |
| 562 | }); |
| 563 | |
| 564 | describe("rendered Markdown task saves", () => { |
| 565 | it("keeps a truncated read read-only without queuing a replacement", async () => { |
| 566 | using _settings = setup(); |
| 567 | await using screen = await render(markdownPreview(true)); |
| 568 | using _timers = fakeTimers(); |
| 569 | const checkbox = screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!; |
| 570 | expect(checkbox).not.toBeNull(); |
| 571 | expect(checkbox.disabled).toBe(true); |
| 572 | expect(checkbox.readOnly).toBe(true); |
| 573 | await act(async () => checkbox.click()); |
| 574 | await vi.advanceTimersByTimeAsync(500); |
| 575 | expect(checkbox.checked).toBe(false); |
| 576 | expect(state.optimistic).toBeNull(); |
| 577 | expect(state.writeFile).not.toHaveBeenCalled(); |
| 578 | }); |
| 579 | |
| 580 | it("still toggles and saves tasks from a complete read", async () => { |
| 581 | using _settings = setup(); |
| 582 | await using screen = await render(markdownPreview(false)); |
| 583 | using _timers = fakeTimers(); |
| 584 | const checkbox = screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!; |
| 585 | expect(checkbox).not.toBeNull(); |
| 586 | expect(checkbox.disabled).toBe(false); |
| 587 | await act(async () => checkbox.click()); |
| 588 | await vi.advanceTimersByTimeAsync(500); |
| 589 | expect(state.writeFile).toHaveBeenCalledExactlyOnceWith({ |
| 590 | environmentId, |
| 591 | input: { |
| 592 | cwd: "/workspace", |
| 593 | relativePath: "tasks.md", |
| 594 | contents: "- [x] Keep the rest of this file\n", |
| 595 | }, |
| 596 | }); |
| 597 | }); |
| 598 | }); |
| 599 | |
| 600 | describe("workspace document previews", () => { |
| 601 | it("keeps an unchanged document loaded when another workspace change lands", async () => { |
| 602 | using _settings = setup(); |
| 603 | await using screen = await render(documentPreview("mutation-1", "revision-1")); |
| 604 | const preview = screen.getByTestId("office-preview"); |
| 605 | await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1"); |
| 606 | const loaded = preview.element(); |
| 607 | |
| 608 | await screen.rerender(documentPreview("mutation-2", "revision-1")); |
| 609 | |
| 610 | expect(state.mintUrl, "an unchanged document re-minted its URL").toHaveBeenCalledOnce(); |
| 611 | expect(screen.container.contains(loaded), "an unchanged document was remounted").toBe(true); |
| 612 | }); |
| 613 | |
| 614 | it("keeps an unchanged document mounted while its revision check reloads", async () => { |
| 615 | using _settings = setup(); |
| 616 | await using screen = await render(documentPreview("mutation-1", "revision-1")); |
| 617 | const preview = screen.getByTestId("office-preview"); |
| 618 | await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1"); |
| 619 | const loaded = preview.element(); |
| 620 | |
| 621 | state.assetUrl = { _tag: "Loading" }; |
| 622 | await screen.rerender(filePreview("report.docx", "mutation-1")); |
| 623 | await screen.rerender(documentPreview("mutation-1", "revision-1")); |
| 624 | |
| 625 | expect( |
| 626 | state.mintUrl, |
| 627 | "a reloading revision check re-minted the document URL", |
| 628 | ).toHaveBeenCalledOnce(); |
| 629 | expect( |
| 630 | screen.container.contains(loaded), |
| 631 | "a reloading revision check remounted the document", |
| 632 | ).toBe(true); |
| 633 | }); |
| 634 | |
| 635 | it("reloads the document when its URL can no longer be minted", async () => { |
| 636 | using _settings = setup(); |
| 637 | await using screen = await render(documentPreview("mutation-1", "revision-1")); |
| 638 | const preview = screen.getByTestId("office-preview"); |
| 639 | await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1"); |
| 640 | |
| 641 | state.assetUrl = { _tag: "Failure" }; |
| 642 | await screen.rerender(filePreview("report.docx", "mutation-2")); |
| 643 | |
| 644 | await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=2"); |
| 645 | }); |
| 646 | |
| 647 | it("loads the new bytes when the document itself changes", async () => { |
| 648 | using _settings = setup(); |
| 649 | await using screen = await render(documentPreview("mutation-1", "revision-1")); |
| 650 | const preview = screen.getByTestId("office-preview"); |
| 651 | await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=1"); |
| 652 | |
| 653 | await screen.rerender(documentPreview("mutation-2", "revision-2")); |
| 654 | |
| 655 | await expect.element(preview).toHaveTextContent("/assets/report.docx?mint=2"); |
| 656 | }); |
| 657 | }); |
| 658 | |
| 659 | describe("open file in preview browser", () => { |
| 660 | it("mints a fresh asset URL on every click so the browser cannot reuse cached bytes", async () => { |
| 661 | using _settings = setup(); |
| 662 | state.file = { |
| 663 | relativePath: "page.html", |
| 664 | contents: "<h1>page</h1>", |
| 665 | byteLength: 13, |
| 666 | truncated: false, |
| 667 | }; |
| 668 | await using screen = await render(filePreview("page.html")); |
| 669 | const button = screen.getByRole("button", { name: "Open file in preview browser" }); |
| 670 | |
| 671 | await userEvent.click(button); |
| 672 | await vi.waitFor(() => expect(state.openedBrowserUrls).toHaveLength(1)); |
| 673 | await userEvent.click(button); |
| 674 | await vi.waitFor(() => expect(state.openedBrowserUrls).toHaveLength(2)); |
| 675 | |
| 676 | expect(state.openedBrowserUrls[1], "the second click reused the first signed URL").not.toBe( |
| 677 | state.openedBrowserUrls[0], |
| 678 | ); |
| 679 | }); |
| 680 | }); |
| 681 | |
| 682 | describe("rendered Markdown select all", () => { |
| 683 | it("selects only the rendered file, including after a task toggle", async () => { |
| 684 | using _settings = setup(); |
| 685 | await using screen = await render( |
| 686 | <> |
| 687 | <p>Transcript text from the chat thread.</p> |
| 688 | {markdownPreview(false, "- [ ] Task item\n\nRendered file body.\n")} |
| 689 | </>, |
| 690 | ); |
| 691 | const expectFileOnlySelection = async () => { |
| 692 | await userEvent.keyboard( |
| 693 | isMacPlatform(navigator.platform) ? "{Meta>}a{/Meta}" : "{Control>}a{/Control}", |
| 694 | ); |
| 695 | const selection = window.getSelection()?.toString() ?? ""; |
| 696 | expect(selection).toContain("Rendered file body."); |
| 697 | expect(selection).not.toContain("Transcript text from the chat thread."); |
| 698 | }; |
| 699 | |
| 700 | await userEvent.click(screen.getByText("Rendered file body.")); |
| 701 | await expectFileOnlySelection(); |
| 702 | // A toggled checkbox keeps focus on an input inside the preview. |
| 703 | await userEvent.click(screen.getByRole("checkbox")); |
| 704 | await expectFileOnlySelection(); |
| 705 | }); |
| 706 | }); |