The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import DocumentPages, { sanitizeDocumentHtml } from "./DocumentPages"; |
| 2 | import { act, fakeTimers, render, stubGlobal, type Screen } from "../../../test/render"; |
| 3 | import { EnvironmentId, ThreadId } from "@t3tools/contracts"; |
| 4 | import { describe, expect, it, vi } from "vite-plus/test"; |
| 5 | import { page, userEvent } from "vite-plus/test/browser"; |
| 6 | import "~/index.css"; |
| 7 | |
| 8 | // Prepare the real worker before tests; Vite's worker transform adds a large inline source map. |
| 9 | const { refresh, assetUrlState, pdfOpens, pdfWorkerUrl } = await vi.hoisted(async () => { |
| 10 | const { default: source } = await import("pdfjs-dist/build/pdf.worker.min.mjs?raw"); |
| 11 | return { |
| 12 | refresh: vi.fn<() => Promise<string | null>>(), |
| 13 | assetUrlState: vi.fn<() => import("~/assets/assetUrls").AssetUrlState>(), |
| 14 | pdfOpens: [] as Array<(task: import("pdfjs-dist").PDFDocumentLoadingTask) => void>, |
| 15 | pdfWorkerUrl: URL.createObjectURL(new Blob([source], { type: "text/javascript" })), |
| 16 | }; |
| 17 | }); |
| 18 | |
| 19 | vi.mock(import("pdfjs-dist/build/pdf.worker.min.mjs?url"), () => ({ |
| 20 | default: pdfWorkerUrl, |
| 21 | })); |
| 22 | |
| 23 | // Like the real hook, the callback is a new function whenever its resource object is. |
| 24 | const refreshers = new WeakMap<object, () => Promise<string | null>>(); |
| 25 | vi.mock(import("~/assets/assetUrls"), async (original) => ({ |
| 26 | ...(await original()), |
| 27 | useAssetUrlRefresh: (_environmentId, resource) => { |
| 28 | if (!resource) return refresh; |
| 29 | let callback = refreshers.get(resource); |
| 30 | if (!callback) refreshers.set(resource, (callback = () => refresh())); |
| 31 | return callback; |
| 32 | }, |
| 33 | useAssetUrlState: assetUrlState, |
| 34 | })); |
| 35 | // Hands each document pdf.js opens to the PDF test, which awaits its load instead of a poll window. |
| 36 | vi.mock(import("./pdfDocument"), async (original) => { |
| 37 | const actual = await original(); |
| 38 | return { |
| 39 | ...actual, |
| 40 | openPdf: (bytes) => { |
| 41 | const task = actual.openPdf(bytes); |
| 42 | pdfOpens.shift()?.(task); |
| 43 | return task; |
| 44 | }, |
| 45 | }; |
| 46 | }); |
| 47 | // The real source view highlights through a worker pool; the text it receives is what matters here. |
| 48 | // Never load the original: its highlighter graph can outlast waitFor on a cold CI browser. |
| 49 | vi.mock(import("./ReadOnlySourcePreview"), () => ({ |
| 50 | default: ({ text, wordWrap }: { text: string; wordWrap?: boolean }) => ( |
| 51 | <pre data-word-wrap={String(wordWrap)}>{text}</pre> |
| 52 | ), |
| 53 | })); |
| 54 | |
| 55 | // The Word engine compiles about 30 MB of WebAssembly in a fresh worker per document, which took |
| 56 | // 10-17 s per test on loaded CI runners. These tests cover fetching, preparation and remounts, so |
| 57 | // the stand-in shows the prepared body's text instead of laying it out. |
| 58 | vi.mock(import("./office/WordDocument"), async () => { |
| 59 | const { use } = await import("react"); |
| 60 | const { default: Zip } = await import("jszip"); |
| 61 | const texts = new WeakMap<ArrayBuffer, Promise<string>>(); |
| 62 | const read = (bytes: ArrayBuffer) => |
| 63 | Zip.loadAsync(bytes) |
| 64 | .then((zip) => zip.file("word/document.xml")!.async("string")) |
| 65 | .then((xml) => xml.replace(/<[^>]+>/g, " ")); |
| 66 | return { |
| 67 | default: ({ bytes }: { bytes: ArrayBuffer }) => { |
| 68 | let text = texts.get(bytes); |
| 69 | if (!text) texts.set(bytes, (text = read(bytes))); |
| 70 | return <pre>{use(text)}</pre>; |
| 71 | }, |
| 72 | }; |
| 73 | }); |
| 74 | |
| 75 | import { getClientSettings } from "~/hooks/useSettings"; |
| 76 | import { AttachmentFilePreview } from "./AttachmentFilePreview"; |
| 77 | import LargeTextViewer from "./LargeTextViewer"; |
| 78 | import VirtualTablePreview from "./VirtualTablePreview"; |
| 79 | import { OfficeFilePreview } from "./OfficeFilePreview"; |
| 80 | import { MermaidFilePreview } from "./MermaidFilePreview"; |
| 81 | import JSZip from "jszip"; |
| 82 | import { boundedZip } from "@t3tools/client-runtime/zip/bounded-zip"; |
| 83 | import BinaryViewer from "./BinaryViewer"; |
| 84 | import { decodeImagePreview } from "./decodeImagePreview"; |
| 85 | import type { BinaryWorkerResult } from "./binaryPreviewProtocol"; |
| 86 | import type { TextPreviewResult } from "./largeTextProtocol"; |
| 87 | import type { ReactElement } from "react"; |
| 88 | import type { OfficeWorkerResult } from "./officePreviewProtocol"; |
| 89 | import { previewErrorText } from "./previewFailureMessages"; |
| 90 | |
| 91 | // Real worker imports and WASM initialization can exceed waitFor's default second |
| 92 | // when the full browser project runs concurrently on CI. |
| 93 | describe("bounded binary previews", () => { |
| 94 | it("preserves length-delimited local and global PAX attributes", async () => { |
| 95 | const encode = (value: string) => new TextEncoder().encode(value); |
| 96 | const block = ( |
| 97 | name: string, |
| 98 | content: Uint8Array, |
| 99 | type = "0", |
| 100 | size = content.length, |
| 101 | linkname = "", |
| 102 | ) => { |
| 103 | const bytes = new Uint8Array(512 + Math.ceil(content.length / 512) * 512); |
| 104 | const write = (offset: number, value: string) => bytes.set(encode(value), offset); |
| 105 | write(0, name); |
| 106 | write(124, size.toString(8).padStart(11, "0") + "\0"); |
| 107 | bytes.fill(32, 148, 156); |
| 108 | write(156, type); |
| 109 | write(157, linkname); |
| 110 | write( |
| 111 | 148, |
| 112 | bytes |
| 113 | .subarray(0, 512) |
| 114 | .reduce((sum, byte) => sum + byte, 0) |
| 115 | .toString(8) |
| 116 | .padStart(6, "0") + "\0 ", |
| 117 | ); |
| 118 | bytes.set(content, 512); |
| 119 | return bytes; |
| 120 | }; |
| 121 | const attributes = (values: Record<string, string>) => |
| 122 | encode( |
| 123 | Object.entries(values) |
| 124 | .map(([key, value]) => { |
| 125 | const payload = ` ${key}=${value}\n`; |
| 126 | let record = `${encode(payload).length + 1}${payload}`; |
| 127 | while (encode(record).length !== Number.parseInt(record, 10)) |
| 128 | record = `${encode(record).length}${payload}`; |
| 129 | return record; |
| 130 | }) |
| 131 | .join(""), |
| 132 | ); |
| 133 | const chunks = [ |
| 134 | block("Global", attributes({ size: "5", mtime: "-86400" }), "g"), |
| 135 | block("Local", attributes({ path: "café\n9 size=1\nname.txt" }), "x"), |
| 136 | block("first.txt", encode("hello"), "0", 0), |
| 137 | block("world.txt", encode("world"), "0", 0), |
| 138 | block("Local", attributes({ size: "3", mtime: "-172800" }), "x"), |
| 139 | block("short.txt", encode("bye"), "0", 0), |
| 140 | block("again.txt", encode("again"), "0", 0), |
| 141 | block("Global", attributes({ size: "", mtime: "" }), "g"), |
| 142 | block("original.txt", encode("hello world")), |
| 143 | block("alias.txt", encode(""), "1", 0, "original.txt"), |
| 144 | block("chain.txt", encode(""), "1", 0, "alias.txt"), |
| 145 | block("Local", attributes({ linkpath: "original.txt" }), "x"), |
| 146 | block("pax-link.txt", encode(""), "1", 0, "wrong-target"), |
| 147 | block("LongLink", encode("original.txt\0"), "K"), |
| 148 | block("gnu-link.txt", encode(""), "1", 0, "wrong-target"), |
| 149 | block("original.txt", encode("replacement")), |
| 150 | new Uint8Array(1024), |
| 151 | ]; |
| 152 | const bytes = new Uint8Array(chunks.reduce((size, chunk) => size + chunk.length, 0)); |
| 153 | let offset = 0; |
| 154 | for (const chunk of chunks) { |
| 155 | bytes.set(chunk, offset); |
| 156 | offset += chunk.length; |
| 157 | } |
| 158 | const worker = new Worker(new URL("./binaryPreview.worker.ts", import.meta.url), { |
| 159 | type: "module", |
| 160 | }); |
| 161 | const request = (input: object) => |
| 162 | new Promise<BinaryWorkerResult>((resolve, reject) => { |
| 163 | worker.addEventListener("message", (event) => resolve(event.data), { once: true }); |
| 164 | worker.addEventListener("error", reject, { once: true }); |
| 165 | worker.postMessage(input, []); |
| 166 | }); |
| 167 | try { |
| 168 | const result = await request({ |
| 169 | type: "open", |
| 170 | kind: "archive", |
| 171 | name: "pax.tar", |
| 172 | bytes: bytes.buffer, |
| 173 | }); |
| 174 | expect(result.type).toBe("archive"); |
| 175 | if (result.type !== "archive") throw new Error("Expected archive"); |
| 176 | expect(result.entries.map((entry) => [entry.path, entry.size, entry.modified])).toEqual([ |
| 177 | ["café\n9 size=1\nname.txt", 5, "1969-12-31T00:00:00.000Z"], |
| 178 | ["world.txt", 5, "1969-12-31T00:00:00.000Z"], |
| 179 | ["short.txt", 3, "1969-12-30T00:00:00.000Z"], |
| 180 | ["again.txt", 5, "1969-12-31T00:00:00.000Z"], |
| 181 | ...[ |
| 182 | "original.txt", |
| 183 | "alias.txt", |
| 184 | "chain.txt", |
| 185 | "pax-link.txt", |
| 186 | "gnu-link.txt", |
| 187 | "original.txt", |
| 188 | ].map((path) => [path, 11, "1970-01-01T00:00:00.000Z"]), |
| 189 | ]); |
| 190 | const entry = await request({ type: "entry", path: "café\n9 size=1\nname.txt" }); |
| 191 | if (entry.type !== "entry") throw new Error("Expected entry"); |
| 192 | expect(new TextDecoder().decode(entry.bytes)).toBe("hello"); |
| 193 | expect(entry.bytes.buffer.byteLength).toBe(5); |
| 194 | entry.bytes[0] = 0; |
| 195 | const reopened = await request({ type: "entry", path: entry.path }); |
| 196 | if (reopened.type !== "entry") throw new Error("Expected entry"); |
| 197 | expect(new TextDecoder().decode(reopened.bytes)).toBe("hello"); |
| 198 | expect(reopened.bytes.buffer.byteLength).toBe(5); |
| 199 | for (const path of ["alias.txt", "chain.txt", "pax-link.txt", "gnu-link.txt"]) { |
| 200 | const linked = await request({ type: "entry", path }); |
| 201 | if (linked.type !== "entry") throw new Error("Expected hard link entry"); |
| 202 | expect(new TextDecoder().decode(linked.bytes)).toBe("hello world"); |
| 203 | } |
| 204 | const unresolved = new Uint8Array( |
| 205 | await new Blob([ |
| 206 | block("missing.txt", encode(""), "1", 0, "nowhere.txt"), |
| 207 | block("early.txt", encode(""), "1", 0, "later.txt"), |
| 208 | block("later.txt", encode("hello")), |
| 209 | block("folder/", encode(""), "5"), |
| 210 | block("to-folder.txt", encode(""), "1", 0, "folder/"), |
| 211 | block("replaced.txt", encode("stale")), |
| 212 | block("replaced.txt", encode(""), "2", 0, "elsewhere.txt"), |
| 213 | block("to-replaced.txt", encode(""), "1", 0, "replaced.txt"), |
| 214 | block("Local", attributes({ linkpath: "" }), "x"), |
| 215 | block("emptied.txt", encode(""), "1", 0, "later.txt"), |
| 216 | new Uint8Array(1024), |
| 217 | ]).arrayBuffer(), |
| 218 | ); |
| 219 | const skipped = await request({ |
| 220 | type: "open", |
| 221 | kind: "archive", |
| 222 | name: "links.tar", |
| 223 | bytes: unresolved.buffer, |
| 224 | }); |
| 225 | if (skipped.type !== "archive") throw new Error("Expected archive"); |
| 226 | expect(skipped.entries.map((entry) => entry.path)).toEqual([ |
| 227 | "later.txt", |
| 228 | "folder/", |
| 229 | "replaced.txt", |
| 230 | ]); |
| 231 | expect(await request({ type: "entry", path: "replaced.txt" })).toEqual({ |
| 232 | type: "error", |
| 233 | code: "archive-entry-unavailable", |
| 234 | message: "archive-entry-unavailable", |
| 235 | }); |
| 236 | } finally { |
| 237 | worker.terminate(); |
| 238 | } |
| 239 | }); |
| 240 | |
| 241 | it("can leave an archive folder with a repeated separator", async () => { |
| 242 | const bytes = new Uint8Array(2048); |
| 243 | const write = (offset: number, value: string) => |
| 244 | bytes.set(new TextEncoder().encode(value), offset); |
| 245 | write(0, "a//hello.txt"); |
| 246 | write(124, "00000000014\0"); |
| 247 | bytes.fill(32, 148, 156); |
| 248 | write(156, "0"); |
| 249 | write( |
| 250 | 148, |
| 251 | bytes |
| 252 | .subarray(0, 512) |
| 253 | .reduce((sum, byte) => sum + byte, 0) |
| 254 | .toString(8) |
| 255 | .padStart(6, "0") + "\0 ", |
| 256 | ); |
| 257 | write(512, "nested hello"); |
| 258 | const src = URL.createObjectURL(new Blob([bytes])); |
| 259 | try { |
| 260 | await using screen = await render(<BinaryViewer src={src} name="paths.tar" kind="archive" />); |
| 261 | const child = () => screen.container.querySelector<HTMLButtonElement>("tbody button"); |
| 262 | await vi.waitFor(() => expect(child()?.textContent).toBe("a"), 10_000); |
| 263 | await act(() => child()!.click()); |
| 264 | await act(() => child()!.click()); |
| 265 | await vi.waitFor(() => expect(child()?.textContent).toBe("hello.txt")); |
| 266 | const parent = () => |
| 267 | screen.container.querySelector<HTMLButtonElement>('[aria-label="Parent folder"]')!; |
| 268 | await act(() => parent().click()); |
| 269 | await act(() => parent().click()); |
| 270 | expect(parent().disabled).toBe(true); |
| 271 | expect(child()?.textContent).toBe("a"); |
| 272 | } finally { |
| 273 | URL.revokeObjectURL(src); |
| 274 | } |
| 275 | }); |
| 276 | |
| 277 | it("uses a PAX size override for the following TAR payload and bounds it", async () => { |
| 278 | const archive = (size: string) => { |
| 279 | const header = (name: string, size: number, type: string) => { |
| 280 | const bytes = new Uint8Array(512); |
| 281 | const write = (offset: number, value: string) => |
| 282 | bytes.set(new TextEncoder().encode(value), offset); |
| 283 | write(0, name); |
| 284 | write(124, size.toString(8).padStart(11, "0") + "\0"); |
| 285 | bytes.fill(32, 148, 156); |
| 286 | write(156, type); |
| 287 | write( |
| 288 | 148, |
| 289 | bytes |
| 290 | .reduce((sum, byte) => sum + byte, 0) |
| 291 | .toString(8) |
| 292 | .padStart(6, "0") + "\0 ", |
| 293 | ); |
| 294 | return bytes; |
| 295 | }; |
| 296 | const payload = ` size=${size}\n`; |
| 297 | let record = `${payload.length + 1}${payload}`; |
| 298 | while (record.length !== Number.parseInt(record, 10)) record = `${record.length}${payload}`; |
| 299 | const bytes = new Uint8Array(3072); |
| 300 | bytes.set(header("PaxHeader", record.length, "x")); |
| 301 | bytes.set(new TextEncoder().encode(record), 512); |
| 302 | bytes.set(header("hello.txt", 0, "0"), 1024); |
| 303 | bytes.set(new TextEncoder().encode("hello"), 1536); |
| 304 | return bytes; |
| 305 | }; |
| 306 | for (const size of ["5", "999999999999999999999"]) { |
| 307 | const src = URL.createObjectURL(new Blob([archive(size)])); |
| 308 | try { |
| 309 | await using screen = await render(<BinaryViewer src={src} name="pax.tar" kind="archive" />); |
| 310 | if (size === "5") { |
| 311 | await vi.waitFor( |
| 312 | () => |
| 313 | expect(screen.container.querySelector("tbody button")?.textContent).toBe("hello.txt"), |
| 314 | 10_000, |
| 315 | ); |
| 316 | await act(() => |
| 317 | screen.container.querySelector<HTMLButtonElement>("tbody button")!.click(), |
| 318 | ); |
| 319 | await vi.waitFor( |
| 320 | () => expect(screen.container.querySelector("pre")?.textContent).toBe("hello"), |
| 321 | 10_000, |
| 322 | ); |
| 323 | } else { |
| 324 | await vi.waitFor( |
| 325 | () => |
| 326 | expect(screen.container.querySelector('[role="alert"]')?.textContent).toContain( |
| 327 | "too large or damaged", |
| 328 | ), |
| 329 | 10_000, |
| 330 | ); |
| 331 | } |
| 332 | } finally { |
| 333 | URL.revokeObjectURL(src); |
| 334 | } |
| 335 | } |
| 336 | }); |
| 337 | |
| 338 | it.each([320, 1280])( |
| 339 | "shows generated SQLite columns and retains picker focus at %i px", |
| 340 | async (width) => { |
| 341 | await page.viewport(width, 800); |
| 342 | const [{ default: initSqlJs }, { default: wasmUrl }] = await Promise.all([ |
| 343 | import("sql.js"), |
| 344 | import("sql.js/dist/sql-wasm.wasm?url"), |
| 345 | ]); |
| 346 | const SQL = await initSqlJs({ locateFile: () => wasmUrl }); |
| 347 | const database = new SQL.Database(); |
| 348 | database.run( |
| 349 | "CREATE TABLE sqliteData (price INTEGER, quantity INTEGER, total INTEGER GENERATED ALWAYS AS (price * quantity) STORED, doubled INTEGER GENERATED ALWAYS AS (price * 2) VIRTUAL); INSERT INTO sqliteData(price, quantity) VALUES (7, 3); CREATE TABLE zzInventory (stock INTEGER); INSERT INTO zzInventory VALUES(42)", |
| 350 | ); |
| 351 | const src = URL.createObjectURL(new Blob([new Uint8Array(database.export())])); |
| 352 | database.close(); |
| 353 | try { |
| 354 | await using screen = await render( |
| 355 | <BinaryViewer src={src} name="orders.sqlite" kind="sqlite" />, |
| 356 | ); |
| 357 | await vi.waitFor( |
| 358 | () => |
| 359 | expect([...screen.container.querySelectorAll("th")].map((x) => x.textContent)).toEqual([ |
| 360 | "price", |
| 361 | "quantity", |
| 362 | "total", |
| 363 | "doubled", |
| 364 | ]), |
| 365 | 10_000, |
| 366 | ); |
| 367 | expect([...screen.container.querySelectorAll("td")].map((x) => x.textContent)).toEqual([ |
| 368 | "7", |
| 369 | "3", |
| 370 | "21", |
| 371 | "14", |
| 372 | ]); |
| 373 | const trigger = screen.container.querySelector<HTMLButtonElement>('[aria-label="Table"]')!; |
| 374 | await act(() => trigger.focus()); |
| 375 | await userEvent.keyboard("{Enter}"); |
| 376 | await expect |
| 377 | .element(page.getByRole("option", { name: "zzInventory (1 row)" })) |
| 378 | .toBeVisible(); |
| 379 | await userEvent.keyboard("{ArrowDown}{Enter}"); |
| 380 | await vi.waitFor(() => |
| 381 | expect([...screen.container.querySelectorAll("td")].map((x) => x.textContent)).toEqual([ |
| 382 | "42", |
| 383 | ]), |
| 384 | ); |
| 385 | await vi.waitFor(() => expect(document.activeElement).toBe(trigger)); |
| 386 | await userEvent.keyboard("{Enter}"); |
| 387 | await expect |
| 388 | .element(page.getByRole("option", { name: "zzInventory (1 row)" })) |
| 389 | .toBeVisible(); |
| 390 | await userEvent.keyboard("{Escape}"); |
| 391 | } finally { |
| 392 | URL.revokeObjectURL(src); |
| 393 | await page.viewport(1280, 800); |
| 394 | } |
| 395 | }, |
| 396 | ); |
| 397 | |
| 398 | it("reauthorizes a failed image when retry is clicked", async () => { |
| 399 | const image = |
| 400 | 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="2" height="2"/>'; |
| 401 | refresh |
| 402 | .mockReset() |
| 403 | .mockResolvedValueOnce("data:image/png;base64,broken") |
| 404 | .mockResolvedValue(image); |
| 405 | await using screen = await render( |
| 406 | <AttachmentFilePreview |
| 407 | name="photo.png" |
| 408 | mimeType="image/png" |
| 409 | sizeBytes={100} |
| 410 | asset={{ environmentId: EnvironmentId.make("test-environment"), attachmentId: "image" }} |
| 411 | />, |
| 412 | ); |
| 413 | await vi.waitFor(() => |
| 414 | expect(screen.container.querySelector('[role="alert"]')?.textContent).toContain( |
| 415 | "Unable to load image.", |
| 416 | ), |
| 417 | ); |
| 418 | await act(() => |
| 419 | screen.container.querySelector<HTMLButtonElement>('[role="alert"] button')!.click(), |
| 420 | ); |
| 421 | await vi.waitFor(() => |
| 422 | expect(screen.container.querySelector("img")?.getAttribute("src")).toBe(image), |
| 423 | ); |
| 424 | expect(refresh).toHaveBeenCalledTimes(2); |
| 425 | }); |
| 426 | |
| 427 | it("reads a small ZIP64 archive and rejects understated directory counts", async () => { |
| 428 | const zip = new JSZip().file("readme.txt", "hello"); |
| 429 | const bytes = await zip.generateAsync({ type: "uint8array" }); |
| 430 | const end = bytes.length - 22; |
| 431 | const legacy = new DataView(bytes.buffer); |
| 432 | const extended = new Uint8Array(bytes.length + 76); |
| 433 | extended.set(bytes.subarray(0, end)); |
| 434 | extended.set(bytes.subarray(end), end + 76); |
| 435 | const view = new DataView(extended.buffer); |
| 436 | view.setUint32(end, 0x06064b50, true); |
| 437 | view.setBigUint64(end + 4, 44n, true); |
| 438 | view.setBigUint64(end + 24, 1n, true); |
| 439 | view.setBigUint64(end + 32, 1n, true); |
| 440 | view.setBigUint64(end + 40, BigInt(legacy.getUint32(end + 12, true)), true); |
| 441 | view.setBigUint64(end + 48, BigInt(legacy.getUint32(end + 16, true)), true); |
| 442 | view.setUint32(end + 56, 0x07064b50, true); |
| 443 | view.setBigUint64(end + 64, BigInt(end), true); |
| 444 | view.setUint32(end + 72, 1, true); |
| 445 | view.setUint16(end + 76 + 10, 0xffff, true); |
| 446 | expect( |
| 447 | new TextDecoder().decode((await boundedZip(extended.buffer)).get("readme.txt")?.bytes), |
| 448 | ).toBe("hello"); |
| 449 | |
| 450 | const redirected = new Uint8Array(extended.length + 56); |
| 451 | redirected.set(extended.subarray(0, end + 56)); |
| 452 | redirected.set(extended.subarray(end + 56), end + 112); |
| 453 | const redirect = new DataView(redirected.buffer); |
| 454 | redirect.setUint32(end + 56, 0x06064b50, true); |
| 455 | redirect.setBigUint64(end + 60, 44n, true); |
| 456 | redirect.setBigUint64(end + 104, BigInt(end), true); |
| 457 | await expect(boundedZip(redirected.buffer)).rejects.toThrow("Unsupported ZIP64 directory"); |
| 458 | |
| 459 | const commented = new Uint8Array(extended.length + 20); |
| 460 | commented.set(extended); |
| 461 | const comment = new DataView(commented.buffer); |
| 462 | comment.setUint16(extended.length - 2, 20, true); |
| 463 | comment.setUint32(extended.length, 0x07064b50, true); |
| 464 | comment.setBigUint64(extended.length + 8, BigInt(end), true); |
| 465 | comment.setUint32(extended.length + 16, 1, true); |
| 466 | const load = vi.spyOn(JSZip, "loadAsync"); |
| 467 | try { |
| 468 | await expect(boundedZip(commented.buffer)).rejects.toThrow("Unsupported ZIP64 directory"); |
| 469 | expect(load).not.toHaveBeenCalled(); |
| 470 | } finally { |
| 471 | load.mockRestore(); |
| 472 | } |
| 473 | |
| 474 | const many = new JSZip(); |
| 475 | for (let i = 0; i < 2049; i++) many.file(`file-${i}`, ""); |
| 476 | const crowded = await many.generateAsync({ type: "arraybuffer" }); |
| 477 | new DataView(crowded).setUint16(crowded.byteLength - 12, 1, true); |
| 478 | await expect(boundedZip(crowded)).rejects.toThrow("more than 2,048 entries"); |
| 479 | }); |
| 480 | |
| 481 | it("keeps a file and directory with the same basename accessible", async () => { |
| 482 | const bytes = await new JSZip() |
| 483 | .file("foo.txt", "root file") |
| 484 | .file("foo.txt/bar.txt", "child") |
| 485 | .generateAsync({ type: "arraybuffer" }); |
| 486 | const src = URL.createObjectURL(new Blob([bytes])); |
| 487 | try { |
| 488 | await using screen = await render(<BinaryViewer src={src} name="names.zip" kind="archive" />); |
| 489 | await vi.waitFor( |
| 490 | () => expect(screen.container.querySelectorAll("tbody button")).toHaveLength(2), |
| 491 | 10_000, |
| 492 | ); |
| 493 | const buttons = [...screen.container.querySelectorAll<HTMLButtonElement>("tbody button")]; |
| 494 | expect(buttons.map((button) => button.textContent)).toEqual(["foo.txt", "foo.txt"]); |
| 495 | await act(() => buttons[1]!.click()); |
| 496 | await vi.waitFor(() => expect(screen.container.textContent).toContain("root file"), 10_000); |
| 497 | } finally { |
| 498 | URL.revokeObjectURL(src); |
| 499 | } |
| 500 | }); |
| 501 | |
| 502 | it("keeps WhiteIsZero TIFF brightness and rejects oversized metadata before decoding", async () => { |
| 503 | const tags = [ |
| 504 | [256, 2], |
| 505 | [257, 1], |
| 506 | [258, 8], |
| 507 | [259, 1], |
| 508 | [262, 0], |
| 509 | [273, 134], |
| 510 | [277, 1], |
| 511 | [278, 1], |
| 512 | [279, 2], |
| 513 | [284, 1], |
| 514 | ]; |
| 515 | const bytes = new ArrayBuffer(136); |
| 516 | const view = new DataView(bytes); |
| 517 | view.setUint16(0, 0x4949); |
| 518 | view.setUint16(2, 42, true); |
| 519 | view.setUint32(4, 8, true); |
| 520 | view.setUint16(8, tags.length, true); |
| 521 | tags.forEach(([tag, value], index) => { |
| 522 | const offset = 10 + index * 12; |
| 523 | view.setUint16(offset, tag!, true); |
| 524 | view.setUint16(offset + 2, 4, true); |
| 525 | view.setUint32(offset + 4, 1, true); |
| 526 | view.setUint32(offset + 8, value!, true); |
| 527 | }); |
| 528 | view.setUint8(135, 255); |
| 529 | const src = URL.createObjectURL(new Blob([bytes])); |
| 530 | try { |
| 531 | const blob = await decodeImagePreview(src, false, new AbortController().signal); |
| 532 | const bitmap = await createImageBitmap(blob); |
| 533 | const canvas = new OffscreenCanvas(2, 1); |
| 534 | const context = canvas.getContext("2d")!; |
| 535 | context.drawImage(bitmap, 0, 0); |
| 536 | expect([...context.getImageData(0, 0, 2, 1).data]).toEqual([ |
| 537 | 255, 255, 255, 255, 0, 0, 0, 255, |
| 538 | ]); |
| 539 | bitmap.close(); |
| 540 | } finally { |
| 541 | URL.revokeObjectURL(src); |
| 542 | } |
| 543 | view.setUint32(14, 1_000_000, true); |
| 544 | const invalid = URL.createObjectURL(new Blob([bytes])); |
| 545 | try { |
| 546 | await expect( |
| 547 | decodeImagePreview(invalid, false, new AbortController().signal), |
| 548 | ).rejects.toThrow("metadata"); |
| 549 | } finally { |
| 550 | URL.revokeObjectURL(invalid); |
| 551 | } |
| 552 | }); |
| 553 | }); |
| 554 | |
| 555 | describe("large text preview recovery", () => { |
| 556 | it("retains the workspace viewer across URL renewals and reloads revisions and manual refreshes", async () => { |
| 557 | const { WorkspaceLargeTextPreview } = await import("./FilePreviewPanel"); |
| 558 | const original = URL.createObjectURL(new Blob(["original\n".repeat(1000)])); |
| 559 | const changed = URL.createObjectURL(new Blob(["changed\n".repeat(1000)])); |
| 560 | const workers: Worker[] = []; |
| 561 | const indexed: Promise<void>[] = []; |
| 562 | using _worker = stubGlobal( |
| 563 | "Worker", |
| 564 | class extends Worker { |
| 565 | constructor(...args: ConstructorParameters<typeof Worker>) { |
| 566 | super(...args); |
| 567 | workers.push(this); |
| 568 | indexed.push( |
| 569 | new Promise((resolve) => |
| 570 | this.addEventListener("message", (event: MessageEvent<TextPreviewResult>) => { |
| 571 | if (event.data.type === "meta" && event.data.complete) resolve(); |
| 572 | }), |
| 573 | ), |
| 574 | ); |
| 575 | } |
| 576 | }, |
| 577 | ); |
| 578 | const preview = (mutation: string, key = 0) => ( |
| 579 | <div style={{ display: "flex", flexDirection: "column", height: 400, width: 600 }}> |
| 580 | <WorkspaceLargeTextPreview |
| 581 | key={key} |
| 582 | environmentId={EnvironmentId.make("test")} |
| 583 | threadRef={{ environmentId: EnvironmentId.make("test"), threadId: ThreadId.make("test") }} |
| 584 | absolutePath="/repo/large.txt" |
| 585 | name="large.txt" |
| 586 | delimiter={null} |
| 587 | workspaceMutationId={mutation} |
| 588 | revealLine={null} |
| 589 | revealRequestId={0} |
| 590 | wordWrap |
| 591 | /> |
| 592 | </div> |
| 593 | ); |
| 594 | const state = (url: string, fileRevision?: string) => |
| 595 | assetUrlState.mockReturnValue({ |
| 596 | _tag: "Success", |
| 597 | url, |
| 598 | expiresAt: Date.now() + 3_600_000, |
| 599 | ...(fileRevision === undefined ? {} : { fileRevision }), |
| 600 | }); |
| 601 | refresh.mockResolvedValue(`${original}#renewed`); |
| 602 | try { |
| 603 | state(`${original}#initial`, "one"); |
| 604 | await using screen = await render(preview("first")); |
| 605 | await vi.waitFor(() => expect(workers).toHaveLength(1)); |
| 606 | await vi.waitFor(() => expect(screen.container.textContent).toContain("original")); |
| 607 | // A cold worker can take longer than waitFor allows to load and index on CI. |
| 608 | await indexed[0]; |
| 609 | await vi.waitFor(() => expect(screen.container.textContent).toContain("1,000 lines")); |
| 610 | const viewport = screen.container.querySelector<HTMLElement>('[tabindex="0"]')!; |
| 611 | await act(() => |
| 612 | viewport.dispatchEvent( |
| 613 | new WheelEvent("wheel", { deltaY: 250, bubbles: true, cancelable: true }), |
| 614 | ), |
| 615 | ); |
| 616 | await vi.waitFor(() => expect(viewport.scrollTop).toBeGreaterThan(0)); |
| 617 | const scrollTop = viewport.scrollTop; |
| 618 | state(`${original}#renewed`, "one"); |
| 619 | await screen.rerender(preview("unrelated-command")); |
| 620 | expect(screen.container.querySelector('[tabindex="0"]')).toBe(viewport); |
| 621 | expect(viewport.scrollTop).toBe(scrollTop); |
| 622 | expect(workers).toHaveLength(1); |
| 623 | state(`${changed}#updated`, "two"); |
| 624 | await screen.rerender(preview("file-edit")); |
| 625 | // The prefetched first screen paints before the worker starts, so wait for the worker itself. |
| 626 | await vi.waitFor(() => expect(workers).toHaveLength(2)); |
| 627 | await vi.waitFor(() => expect(screen.container.textContent).toContain("changed")); |
| 628 | await screen.rerender(preview("file-edit", 1)); |
| 629 | await vi.waitFor(() => expect(workers).toHaveLength(3)); |
| 630 | await vi.waitFor(() => expect(screen.container.textContent).toContain("changed")); |
| 631 | state(`${original}#legacy`); |
| 632 | await screen.rerender(preview("legacy-edit", 1)); |
| 633 | await vi.waitFor(() => expect(workers).toHaveLength(4)); |
| 634 | await vi.waitFor(() => expect(screen.container.textContent).toContain("original")); |
| 635 | assetUrlState.mockReturnValue({ _tag: "Failure" }); |
| 636 | await screen.rerender(preview("legacy-edit", 1)); |
| 637 | expect(screen.container.textContent).toContain("Unable to load file preview."); |
| 638 | refresh.mockClear(); |
| 639 | refresh.mockImplementation(async () => { |
| 640 | state(`${changed}#retried`); |
| 641 | return changed; |
| 642 | }); |
| 643 | await screen.getByRole("button", { name: "Try again" }).click(); |
| 644 | expect(refresh).toHaveBeenCalledOnce(); |
| 645 | await screen.rerender(preview("legacy-edit", 1)); |
| 646 | await vi.waitFor(() => expect(screen.container.textContent).toContain("changed")); |
| 647 | expect(screen.container.querySelector('[role="alert"]')).toBeNull(); |
| 648 | } finally { |
| 649 | URL.revokeObjectURL(original); |
| 650 | URL.revokeObjectURL(changed); |
| 651 | } |
| 652 | }); |
| 653 | |
| 654 | it("scrolls within a wrapped row when the row-count track is shorter than the viewport", async () => { |
| 655 | await using screen = await render( |
| 656 | <div style={{ display: "flex", height: 400, width: 600 }}> |
| 657 | <VirtualTablePreview |
| 658 | name="one.txt" |
| 659 | count={1} |
| 660 | columns={1} |
| 661 | source |
| 662 | wrap |
| 663 | getRows={() => [["wrapped source text ".repeat(500)]]} |
| 664 | /> |
| 665 | </div>, |
| 666 | ); |
| 667 | const row = () => screen.container.querySelector<HTMLElement>('[data-preview-row="0"]')!; |
| 668 | const viewport = () => screen.container.querySelector<HTMLElement>('[tabindex="0"]')!; |
| 669 | await vi.waitFor(() => expect(row()?.offsetHeight).toBeGreaterThan(1000)); |
| 670 | await act(() => |
| 671 | viewport().dispatchEvent( |
| 672 | new WheelEvent("wheel", { deltaY: 150, bubbles: true, cancelable: true }), |
| 673 | ), |
| 674 | ); |
| 675 | await vi.waitFor(() => { |
| 676 | const offset = viewport().getBoundingClientRect().top - row().getBoundingClientRect().top; |
| 677 | expect(offset).toBeGreaterThan(50); |
| 678 | expect(offset).toBeLessThan(300); |
| 679 | }); |
| 680 | await act(() => |
| 681 | viewport().dispatchEvent(new KeyboardEvent("keydown", { key: "End", bubbles: true })), |
| 682 | ); |
| 683 | await vi.waitFor(() => |
| 684 | expect( |
| 685 | Math.abs(row().getBoundingClientRect().bottom - viewport().getBoundingClientRect().bottom), |
| 686 | ).toBeLessThan(2), |
| 687 | ); |
| 688 | await act(() => |
| 689 | viewport().dispatchEvent(new KeyboardEvent("keydown", { key: "Home", bubbles: true })), |
| 690 | ); |
| 691 | await vi.waitFor(() => |
| 692 | expect(row().getBoundingClientRect().top).toBe(viewport().getBoundingClientRect().top), |
| 693 | ); |
| 694 | }); |
| 695 | |
| 696 | it("scrolls every tall row in the final virtual viewport", async () => { |
| 697 | const view = (loaded: boolean) => ( |
| 698 | <div style={{ display: "flex", height: 400, width: 600 }}> |
| 699 | <VirtualTablePreview |
| 700 | name="tail.txt" |
| 701 | count={100} |
| 702 | columns={1} |
| 703 | source |
| 704 | wrap |
| 705 | getRows={(page) => |
| 706 | !loaded && page > 0 |
| 707 | ? undefined |
| 708 | : Array.from({ length: 32 }, (_, i) => [ |
| 709 | "line-" + (page * 32 + i + 1) + " wrapped source text".repeat(500), |
| 710 | ]) |
| 711 | } |
| 712 | /> |
| 713 | </div> |
| 714 | ); |
| 715 | await using screen = await render(view(false)); |
| 716 | const viewport = () => screen.container.querySelector<HTMLElement>('[tabindex="0"]')!; |
| 717 | const row = (index: number) => |
| 718 | screen.container.querySelector<HTMLElement>('[data-preview-row="' + index + '"]')!; |
| 719 | await vi.waitFor(() => expect(row(0)?.offsetHeight).toBeGreaterThan(1000)); |
| 720 | await act(() => |
| 721 | viewport().dispatchEvent(new KeyboardEvent("keydown", { key: "End", bubbles: true })), |
| 722 | ); |
| 723 | await vi.waitFor(() => expect(row(99)).not.toBeNull()); |
| 724 | await screen.rerender(view(true)); |
| 725 | await vi.waitFor(() => |
| 726 | expect( |
| 727 | Math.abs( |
| 728 | row(99).getBoundingClientRect().bottom - viewport().getBoundingClientRect().bottom, |
| 729 | ), |
| 730 | ).toBeLessThan(2), |
| 731 | ); |
| 732 | await act(() => |
| 733 | viewport().dispatchEvent(new KeyboardEvent("keydown", { key: "Home", bubbles: true })), |
| 734 | ); |
| 735 | await vi.waitFor(() => expect(row(0)).not.toBeNull()); |
| 736 | await act(() => { |
| 737 | viewport().scrollTop = 100 * 29 - viewport().clientHeight; |
| 738 | viewport().dispatchEvent(new Event("scroll", { bubbles: true })); |
| 739 | }); |
| 740 | const checkTop = (index: number) => |
| 741 | expect( |
| 742 | Math.abs(row(index).getBoundingClientRect().top - viewport().getBoundingClientRect().top), |
| 743 | ).toBeLessThan(2); |
| 744 | await vi.waitFor(() => checkTop(87)); |
| 745 | for (let index = 88; index < 100; index++) { |
| 746 | await act(() => |
| 747 | viewport().dispatchEvent( |
| 748 | new WheelEvent("wheel", { |
| 749 | deltaY: row(index - 1).offsetHeight, |
| 750 | bubbles: true, |
| 751 | cancelable: true, |
| 752 | }), |
| 753 | ), |
| 754 | ); |
| 755 | if (index < 99) await vi.waitFor(() => checkTop(index)); |
| 756 | } |
| 757 | await act(() => |
| 758 | viewport().dispatchEvent(new KeyboardEvent("keydown", { key: "End", bubbles: true })), |
| 759 | ); |
| 760 | await vi.waitFor(() => |
| 761 | expect( |
| 762 | Math.abs( |
| 763 | row(99).getBoundingClientRect().bottom - viewport().getBoundingClientRect().bottom, |
| 764 | ), |
| 765 | ).toBeLessThan(2), |
| 766 | ); |
| 767 | }); |
| 768 | |
| 769 | it("rejects malformed UTF-8 bytes through the real text worker", async () => { |
| 770 | const src = URL.createObjectURL(new Blob([new Uint8Array([0xe9, 10])])); |
| 771 | try { |
| 772 | await using screen = await render( |
| 773 | <LargeTextViewer src={src} name="latin.txt" delimiter={null} />, |
| 774 | ); |
| 775 | await vi.waitFor( |
| 776 | () => expect(screen.container.querySelector('[role="alert"]')).not.toBeNull(), |
| 777 | 10_000, |
| 778 | ); |
| 779 | } finally { |
| 780 | URL.revokeObjectURL(src); |
| 781 | } |
| 782 | }); |
| 783 | |
| 784 | it("replaces both prefetched pages with the worker's current file version", async () => { |
| 785 | const old = Array.from({ length: 64 }, (_, i) => "old-" + i).join("\n") + "\n"; |
| 786 | const current = Array.from({ length: 100 }, (_, i) => "current-" + i).join("\n"); |
| 787 | const src = URL.createObjectURL(new Blob([current])); |
| 788 | using _fetch = stubGlobal( |
| 789 | "fetch", |
| 790 | vi.fn().mockResolvedValue( |
| 791 | new Response(old, { |
| 792 | status: 206, |
| 793 | headers: { |
| 794 | "content-length": String(old.length), |
| 795 | "content-range": "bytes 0-" + (old.length - 1) + "/100000", |
| 796 | }, |
| 797 | }), |
| 798 | ), |
| 799 | ); |
| 800 | try { |
| 801 | await using screen = await render( |
| 802 | <div style={{ display: "flex", height: 2000, width: 600 }}> |
| 803 | <LargeTextViewer src={src} name="log.txt" delimiter={null} /> |
| 804 | </div>, |
| 805 | ); |
| 806 | await vi.waitFor(() => expect(screen.container.textContent).toContain("current-40"), 10_000); |
| 807 | expect(screen.container.textContent).not.toContain("old-"); |
| 808 | } finally { |
| 809 | URL.revokeObjectURL(src); |
| 810 | } |
| 811 | }); |
| 812 | |
| 813 | it("fills the horizontal viewport using measured column widths", async () => { |
| 814 | const header = Array.from({ length: 20 }, (_, i) => "C" + i); |
| 815 | await using screen = await render( |
| 816 | <div style={{ display: "flex", height: 400, width: 400 }}> |
| 817 | <VirtualTablePreview |
| 818 | name="wide.csv" |
| 819 | count={2} |
| 820 | columns={20} |
| 821 | header={header} |
| 822 | getRows={() => [header, header]} |
| 823 | /> |
| 824 | </div>, |
| 825 | ); |
| 826 | const outer = () => screen.container.querySelector('[role="table"]')!.parentElement!; |
| 827 | const check = () => { |
| 828 | const cells = screen.container.querySelectorAll('[role="columnheader"]'); |
| 829 | expect(cells.length).toBeGreaterThan(0); |
| 830 | expect(cells[cells.length - 1]!.getBoundingClientRect().right).toBeGreaterThanOrEqual( |
| 831 | outer().getBoundingClientRect().right - 1, |
| 832 | ); |
| 833 | }; |
| 834 | await vi.waitFor(check); |
| 835 | await act(() => { |
| 836 | outer().scrollLeft = outer().scrollWidth; |
| 837 | outer().dispatchEvent(new Event("scroll", { bubbles: true })); |
| 838 | }); |
| 839 | await vi.waitFor(check); |
| 840 | expect(screen.container.textContent).toContain("C19"); |
| 841 | }); |
| 842 | |
| 843 | it("reveals and highlights requested source lines again for a new request", async () => { |
| 844 | const view = (line: number, request: number, loaded = true) => ( |
| 845 | <div style={{ display: "flex", height: 400, width: 600 }}> |
| 846 | <VirtualTablePreview |
| 847 | name="log.txt" |
| 848 | count={1000} |
| 849 | columns={1} |
| 850 | source |
| 851 | wrap |
| 852 | revealLine={line} |
| 853 | revealRequestId={request} |
| 854 | getRows={(page) => |
| 855 | loaded || page === 0 |
| 856 | ? Array.from({ length: 32 }, (_, i) => [ |
| 857 | "line-" + (page * 32 + i + 1) + " wrapped source text".repeat(20), |
| 858 | ]) |
| 859 | : undefined |
| 860 | } |
| 861 | /> |
| 862 | </div> |
| 863 | ); |
| 864 | await using screen = await render(view(500, 1, false)); |
| 865 | await vi.waitFor(() => |
| 866 | expect(screen.container.querySelector('[data-preview-reveal="true"]')?.textContent).toBe( |
| 867 | "500", |
| 868 | ), |
| 869 | ); |
| 870 | await screen.rerender(view(500, 1)); |
| 871 | await vi.waitFor(() => |
| 872 | expect(screen.container.querySelector('[data-preview-reveal="true"]')?.textContent).toContain( |
| 873 | "line-500", |
| 874 | ), |
| 875 | ); |
| 876 | const checkVisible = () => { |
| 877 | const row = screen.container.querySelector<HTMLElement>('[data-preview-reveal="true"]')!; |
| 878 | const viewport = screen.container.querySelector<HTMLElement>('[tabindex="0"]')!; |
| 879 | expect(row.getBoundingClientRect().top).toBeGreaterThanOrEqual( |
| 880 | viewport.getBoundingClientRect().top - 1, |
| 881 | ); |
| 882 | expect(row.getBoundingClientRect().bottom).toBeLessThanOrEqual( |
| 883 | viewport.getBoundingClientRect().bottom + 1, |
| 884 | ); |
| 885 | }; |
| 886 | await vi.waitFor(checkVisible); |
| 887 | await screen.rerender(view(900, 2)); |
| 888 | await vi.waitFor(() => |
| 889 | expect(screen.container.querySelector('[data-preview-reveal="true"]')?.textContent).toContain( |
| 890 | "line-900", |
| 891 | ), |
| 892 | ); |
| 893 | await vi.waitFor(checkVisible); |
| 894 | await screen.rerender(view(999, 3)); |
| 895 | await vi.waitFor(() => |
| 896 | expect(screen.container.querySelector('[data-preview-reveal="true"]')?.textContent).toContain( |
| 897 | "line-999", |
| 898 | ), |
| 899 | ); |
| 900 | await vi.waitFor(checkVisible); |
| 901 | }); |
| 902 | |
| 903 | it.each( |
| 904 | [5, 100, 10_000].flatMap((count) => [false, true].map((mixed) => [count, mixed] as const)), |
| 905 | )( |
| 906 | "preserves the source row when indexing grows beyond %i lines (mixed heights: %s)", |
| 907 | async (count, mixed) => { |
| 908 | const view = (count: number) => ( |
| 909 | <div style={{ display: "flex", height: 400, width: 600 }}> |
| 910 | <VirtualTablePreview |
| 911 | name="growing.txt" |
| 912 | count={count} |
| 913 | columns={1} |
| 914 | source |
| 915 | wrap |
| 916 | getRows={(page) => |
| 917 | Array.from({ length: 32 }, (_, i) => [ |
| 918 | `line-${page * 32 + i + 1} ` + |
| 919 | "wrapped source text ".repeat(mixed ? 5 + (i % 4) * 20 : 20), |
| 920 | ]) |
| 921 | } |
| 922 | /> |
| 923 | </div> |
| 924 | ); |
| 925 | await using screen = await render(view(count)); |
| 926 | const viewport = () => screen.container.querySelector<HTMLElement>('[tabindex="0"]')!; |
| 927 | await vi.waitFor(() => expect(viewport()?.scrollHeight).toBeGreaterThan(400)); |
| 928 | await act(() => { |
| 929 | viewport().scrollTop = count === 100 ? 100 * 29 - 400 + 1200 : 1200; |
| 930 | viewport().dispatchEvent(new Event("scroll", { bubbles: true })); |
| 931 | }); |
| 932 | const visibleRow = () => |
| 933 | [...screen.container.querySelectorAll<HTMLElement>("[data-preview-row]")].find( |
| 934 | (row) => row.getBoundingClientRect().bottom > viewport().getBoundingClientRect().top + 1, |
| 935 | )!; |
| 936 | await vi.waitFor(() => expect(visibleRow()).toBeDefined()); |
| 937 | const before = visibleRow().dataset.previewRow; |
| 938 | const offset = |
| 939 | visibleRow().getBoundingClientRect().top - viewport().getBoundingClientRect().top; |
| 940 | await screen.rerender(view(1_000_000)); |
| 941 | await vi.waitFor(() => { |
| 942 | expect(visibleRow().dataset.previewRow).toBe(before); |
| 943 | expect( |
| 944 | Math.abs( |
| 945 | visibleRow().getBoundingClientRect().top - |
| 946 | viewport().getBoundingClientRect().top - |
| 947 | offset, |
| 948 | ), |
| 949 | ).toBeLessThan(Math.max(5, visibleRow().offsetHeight / 29 + 1)); |
| 950 | }); |
| 951 | }, |
| 952 | ); |
| 953 | |
| 954 | it("recovers from a failed worker load when its source changes", async () => { |
| 955 | await using screen = await render( |
| 956 | <LargeTextViewer name="log.txt" text={"bad\0text"} delimiter={null} />, |
| 957 | ); |
| 958 | await vi.waitFor( |
| 959 | () => expect(screen.container.textContent).toContain("This file contains binary data."), |
| 960 | 10_000, |
| 961 | ); |
| 962 | await screen.rerender(<LargeTextViewer name="log.txt" text="" delimiter={null} />); |
| 963 | await vi.waitFor( |
| 964 | () => expect(screen.container.textContent).toContain("This file is empty."), |
| 965 | 10_000, |
| 966 | ); |
| 967 | expect(screen.container.querySelector('[role="alert"]')).toBeNull(); |
| 968 | }); |
| 969 | |
| 970 | it("reloads a partial page when the indexed row count grows", async () => { |
| 971 | const load = vi.fn(); |
| 972 | const rows = [["first"]]; |
| 973 | const view = (count: number) => ( |
| 974 | <div style={{ display: "flex", height: 400, width: 600 }}> |
| 975 | <VirtualTablePreview |
| 976 | name="log.txt" |
| 977 | count={count} |
| 978 | columns={1} |
| 979 | source |
| 980 | getRows={() => rows} |
| 981 | loadPage={load} |
| 982 | /> |
| 983 | </div> |
| 984 | ); |
| 985 | await using screen = await render(view(1)); |
| 986 | await vi.waitFor(() => expect(screen.container.textContent).toContain("first")); |
| 987 | expect(load).not.toHaveBeenCalled(); |
| 988 | await screen.rerender(view(2)); |
| 989 | await vi.waitFor(() => expect(load).toHaveBeenCalledWith(0)); |
| 990 | }); |
| 991 | }); |
| 992 | describe("standalone Mermaid previews", () => { |
| 993 | it.each([ |
| 994 | 'A@{ "img": "//attacker.invalid/pixel.png" }', |
| 995 | 'A@{ "im\\u0067": "/pixel.png" }', |
| 996 | "A@{ label: &key img, *key: '/pixel.png' }", |
| 997 | 'A["<img src=//attacker.invalid/pixel.png>"]', |
| 998 | ])("rejects resource syntax before Mermaid lays out %s", async (node) => { |
| 999 | using imageSource = vi |
| 1000 | .spyOn(HTMLImageElement.prototype, "src", "set") |
| 1001 | .mockImplementation(() => {}); |
| 1002 | await using screen = await render(<MermaidFilePreview text={`flowchart LR\n${node}`} />); |
| 1003 | // The first case loads the Mermaid viewer chunk, which can take over a second on a slow runner. |
| 1004 | await vi.waitFor( |
| 1005 | () => |
| 1006 | expect(screen.container.querySelector('[role="alert"]')?.textContent).toContain( |
| 1007 | "Show Mermaid source", |
| 1008 | ), |
| 1009 | { timeout: 10_000 }, |
| 1010 | ); |
| 1011 | expect(imageSource).not.toHaveBeenCalled(); |
| 1012 | expect(screen.container.querySelector("svg")).toBeNull(); |
| 1013 | }); |
| 1014 | |
| 1015 | it.each(["<-->", "<==>", "<-.->", "-->"])("renders the %s arrow", async (arrow) => { |
| 1016 | await using screen = await render(<MermaidFilePreview text={`flowchart LR\nA ${arrow} B`} />); |
| 1017 | await vi.waitFor( |
| 1018 | () => { |
| 1019 | const diagram = screen.container.querySelector("svg"); |
| 1020 | expect(diagram?.querySelector("path")).not.toBeNull(); |
| 1021 | expect(diagram?.textContent).toContain("A"); |
| 1022 | expect(diagram?.textContent).toContain("B"); |
| 1023 | }, |
| 1024 | { timeout: 10_000 }, |
| 1025 | ); |
| 1026 | expect(screen.container.querySelector('[role="alert"]')).toBeNull(); |
| 1027 | }); |
| 1028 | }); |
| 1029 | |
| 1030 | it("reloads a workspace Word file after a preview remount", async () => { |
| 1031 | const { default: JSZip } = await import("jszip"); |
| 1032 | let heading = "Original outlook"; |
| 1033 | using _fetch = stubGlobal( |
| 1034 | "fetch", |
| 1035 | vi.fn(async () => { |
| 1036 | const archive = new JSZip().file( |
| 1037 | "word/document.xml", |
| 1038 | `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>${heading}</w:t></w:r></w:p></w:body></w:document>`, |
| 1039 | ); |
| 1040 | return new Response(await archive.generateAsync({ type: "arraybuffer" })); |
| 1041 | }), |
| 1042 | ); |
| 1043 | refresh.mockReset().mockResolvedValue("https://example.com/workspace.docx"); |
| 1044 | const asset = { environmentId: EnvironmentId.make("test-environment"), attachmentId: "word" }; |
| 1045 | await using screen = await render( |
| 1046 | <AttachmentFilePreview |
| 1047 | key="original" |
| 1048 | name="outlook.docx" |
| 1049 | mimeType="application/octet-stream" |
| 1050 | sizeBytes={0} |
| 1051 | asset={asset} |
| 1052 | />, |
| 1053 | ); |
| 1054 | await vi.waitFor(() => expect(screen.container.textContent).toContain("Original outlook"), { |
| 1055 | timeout: 10_000, |
| 1056 | }); |
| 1057 | heading = "Revised outlook"; |
| 1058 | await screen.rerender( |
| 1059 | <AttachmentFilePreview |
| 1060 | key="refreshed" |
| 1061 | name="outlook.docx" |
| 1062 | mimeType="application/octet-stream" |
| 1063 | sizeBytes={0} |
| 1064 | asset={asset} |
| 1065 | />, |
| 1066 | ); |
| 1067 | await vi.waitFor(() => expect(screen.container.textContent).toContain("Revised outlook"), { |
| 1068 | timeout: 10_000, |
| 1069 | }); |
| 1070 | expect(screen.container.textContent).not.toContain("Original outlook"); |
| 1071 | }); |
| 1072 | |
| 1073 | it("clears an Office metadata error when the same URL becomes previewable", async () => { |
| 1074 | const src = "data:application/octet-stream,invalid-office-file"; |
| 1075 | let resolveBody!: (body: string) => void; |
| 1076 | const body = new Promise<string>((resolve) => { |
| 1077 | resolveBody = resolve; |
| 1078 | }); |
| 1079 | using _fetch = stubGlobal( |
| 1080 | "fetch", |
| 1081 | vi.fn(() => body.then((text) => new Response(text))), |
| 1082 | ); |
| 1083 | await using screen = await render( |
| 1084 | <OfficeFilePreview src={src} name="report.docx" kind="docx" sizeBytes={51 * 1024 * 1024} />, |
| 1085 | ); |
| 1086 | await vi.waitFor(() => expect(screen.container.textContent).toContain("under 50 MB")); |
| 1087 | await screen.rerender( |
| 1088 | <OfficeFilePreview src={src} name="report.docx" kind="docx" sizeBytes={100} />, |
| 1089 | ); |
| 1090 | await vi.waitFor(() => |
| 1091 | expect(screen.container.querySelector('[aria-label="Loading file"]')).not.toBeNull(), |
| 1092 | ); |
| 1093 | expect(screen.container.textContent).not.toContain("under 50 MB"); |
| 1094 | resolveBody("invalid-office-file"); |
| 1095 | await vi.waitFor(() => expect(screen.container.textContent).toContain("not a readable ZIP"), { |
| 1096 | timeout: 10_000, |
| 1097 | }); |
| 1098 | }); |
| 1099 | |
| 1100 | describe("attachment HTML preview recovery", () => { |
| 1101 | const originalUrl = "data:text/html,original"; |
| 1102 | const renewedUrl = "data:text/html,renewed"; |
| 1103 | |
| 1104 | function setup() { |
| 1105 | refresh.mockReset().mockResolvedValueOnce(originalUrl).mockResolvedValue(renewedUrl); |
| 1106 | } |
| 1107 | |
| 1108 | const openRemote = () => |
| 1109 | render( |
| 1110 | <AttachmentFilePreview |
| 1111 | name="document.html" |
| 1112 | mimeType="text/html" |
| 1113 | sizeBytes={100} |
| 1114 | asset={{ environmentId: EnvironmentId.make("test-environment"), attachmentId: "html" }} |
| 1115 | />, |
| 1116 | ); |
| 1117 | |
| 1118 | const toggleMode = async (screen: Screen, label: string) => { |
| 1119 | const button = screen.container.querySelector<HTMLButtonElement>( |
| 1120 | `button[aria-label="${label}"]`, |
| 1121 | ); |
| 1122 | expect(button, label).not.toBeNull(); |
| 1123 | await act(async () => button!.click()); |
| 1124 | }; |
| 1125 | const alert = (screen: Screen) => screen.container.querySelector('[role="alert"]'); |
| 1126 | // The app's connection runtime keeps polling environment discovery through the same global |
| 1127 | // fetch while these tests run, so only the attachment's own requests are counted. |
| 1128 | const attachmentFetches = () => |
| 1129 | vi |
| 1130 | .mocked(fetch) |
| 1131 | .mock.calls.map(([url]) => url) |
| 1132 | .filter((url) => typeof url === "string" && url.startsWith("data:text/html")); |
| 1133 | |
| 1134 | it("keeps a renewed URL for subsequent rendered and source views", async () => { |
| 1135 | setup(); |
| 1136 | let now = 0; |
| 1137 | using _now = vi.spyOn(Date, "now").mockImplementation(() => now); |
| 1138 | using _fetch = stubGlobal( |
| 1139 | "fetch", |
| 1140 | vi.fn(async () => new Response("<p>Captured HTML</p>")), |
| 1141 | ); |
| 1142 | await using screen = await openRemote(); |
| 1143 | expect(screen.container.querySelector("iframe")?.getAttribute("src")).toBe(originalUrl); |
| 1144 | now = 61 * 60_000; |
| 1145 | await toggleMode(screen, "Show HTML source"); |
| 1146 | await act(async () => { |
| 1147 | await import("./ReadOnlySourcePreview"); |
| 1148 | }); |
| 1149 | expect(attachmentFetches()).toEqual([renewedUrl]); |
| 1150 | await vi.waitFor(() => |
| 1151 | expect(screen.container.querySelector("pre")?.textContent).toBe("<p>Captured HTML</p>"), |
| 1152 | ); |
| 1153 | |
| 1154 | await toggleMode(screen, "Show rendered page"); |
| 1155 | expect(screen.container.querySelector("iframe")?.getAttribute("src")).toBe(renewedUrl); |
| 1156 | await toggleMode(screen, "Show HTML source"); |
| 1157 | expect(refresh).toHaveBeenCalledTimes(2); |
| 1158 | expect(attachmentFetches()).toEqual([renewedUrl, renewedUrl]); |
| 1159 | }); |
| 1160 | |
| 1161 | it("does not fetch or mark an expired URL fresh when reauthorization is unavailable", async () => { |
| 1162 | setup(); |
| 1163 | let now = 0; |
| 1164 | using _now = vi.spyOn(Date, "now").mockImplementation(() => now); |
| 1165 | using _fetch = stubGlobal( |
| 1166 | "fetch", |
| 1167 | vi.fn(async () => new Response("<p>Captured HTML</p>")), |
| 1168 | ); |
| 1169 | await using screen = await openRemote(); |
| 1170 | now = 61 * 60_000; |
| 1171 | refresh.mockResolvedValue(null); |
| 1172 | await toggleMode(screen, "Show HTML source"); |
| 1173 | expect(attachmentFetches()).toEqual([]); |
| 1174 | expect(alert(screen)?.textContent).toContain("Reconnect to the environment and try again."); |
| 1175 | |
| 1176 | await toggleMode(screen, "Show rendered page"); |
| 1177 | await toggleMode(screen, "Show HTML source"); |
| 1178 | expect(refresh).toHaveBeenCalledTimes(3); |
| 1179 | expect(attachmentFetches()).toEqual([]); |
| 1180 | }); |
| 1181 | |
| 1182 | it("can return to rendered HTML after local source decoding fails", async () => { |
| 1183 | setup(); |
| 1184 | let now = 0; |
| 1185 | using _now = vi.spyOn(Date, "now").mockImplementation(() => now); |
| 1186 | using _fetch = stubGlobal( |
| 1187 | "fetch", |
| 1188 | vi.fn(async () => new Response("<p>Captured HTML</p>")), |
| 1189 | ); |
| 1190 | const file = new Blob([new Uint8Array([0x3c, 0x70, 0x3e, 0xe9])], { type: "text/html" }); |
| 1191 | await using screen = await render( |
| 1192 | <AttachmentFilePreview |
| 1193 | name="document.html" |
| 1194 | mimeType="text/html" |
| 1195 | sizeBytes={file.size} |
| 1196 | file={file} |
| 1197 | />, |
| 1198 | ); |
| 1199 | await toggleMode(screen, "Show HTML source"); |
| 1200 | await vi.waitFor(() => expect(alert(screen)?.textContent).toContain("not UTF-8")); |
| 1201 | |
| 1202 | await toggleMode(screen, "Show rendered page"); |
| 1203 | expect(alert(screen)).toBeNull(); |
| 1204 | expect(screen.container.querySelector("iframe")?.title).toBe("document.html"); |
| 1205 | }); |
| 1206 | }); |
| 1207 | |
| 1208 | describe("document output sanitization", () => { |
| 1209 | it("fits saved HTML outputs to their content and resizes when the content changes", async () => { |
| 1210 | await using screen = await render( |
| 1211 | <DocumentPages html="<table><tr><td>42</td></tr></table>" name="Output" output />, |
| 1212 | ); |
| 1213 | const frame = screen.container.querySelector("iframe")!; |
| 1214 | await vi.waitFor(() => { |
| 1215 | expect(frame.contentDocument?.querySelector("td")?.textContent).toBe("42"); |
| 1216 | expect(frame.clientHeight).toBeGreaterThan(32); |
| 1217 | expect(frame.clientHeight).toBeLessThan(120); |
| 1218 | }); |
| 1219 | const initialHeight = frame.clientHeight; |
| 1220 | await screen.rerender( |
| 1221 | <DocumentPages html={"<p>More saved output</p>".repeat(10)} name="Output" output />, |
| 1222 | ); |
| 1223 | await vi.waitFor(() => { |
| 1224 | expect(frame.contentDocument?.querySelectorAll("p")).toHaveLength(10); |
| 1225 | expect(frame.clientHeight).toBeGreaterThan(initialHeight); |
| 1226 | expect(frame.contentDocument!.body.scrollHeight).toBeLessThanOrEqual(frame.clientHeight); |
| 1227 | }); |
| 1228 | }); |
| 1229 | |
| 1230 | it("preserves table content and raster data while removing scripts and network resources", () => { |
| 1231 | const html = sanitizeDocumentHtml( |
| 1232 | '<script>alert(1)</script><style>@import "https://example.com/style.css";</style><iframe src="https://example.com"></iframe><img src="https://example.com/tracker.png" onerror="alert(1)"><img src="data:image/png;base64,iVBORw0KGgo="><table><tr><td>Research</td></tr></table><a href="https://example.com">Results</a>', |
| 1233 | ); |
| 1234 | const doc = new DOMParser().parseFromString(html, "text/html"); |
| 1235 | expect(doc.querySelector("td")?.textContent).toBe("Research"); |
| 1236 | expect(doc.images).toHaveLength(1); |
| 1237 | expect(doc.images[0]!.getAttribute("src")).toBe("data:image/png;base64,iVBORw0KGgo="); |
| 1238 | expect(doc.querySelector("script,style,iframe,a,[onerror]")).toBeNull(); |
| 1239 | expect(html).not.toContain("https://"); |
| 1240 | }); |
| 1241 | }); |
| 1242 | it("keeps an attachment URL when the parent passes a fresh asset object for the same attachment", async () => { |
| 1243 | const url = URL.createObjectURL(new Blob(["%PDF-1.4"], { type: "application/pdf" })); |
| 1244 | refresh.mockReset().mockResolvedValue(url); |
| 1245 | const preview = () => ( |
| 1246 | <AttachmentFilePreview |
| 1247 | name="report.pdf" |
| 1248 | mimeType="application/pdf" |
| 1249 | sizeBytes={8} |
| 1250 | asset={{ environmentId: EnvironmentId.make("test"), attachmentId: "report" }} |
| 1251 | /> |
| 1252 | ); |
| 1253 | try { |
| 1254 | await using screen = await render(preview()); |
| 1255 | await vi.waitFor(() => expect(refresh).toHaveBeenCalledTimes(1)); |
| 1256 | // FilePreviewPanel rebuilds `asset` when an agent command completes. |
| 1257 | await screen.rerender(preview()); |
| 1258 | expect(refresh).toHaveBeenCalledTimes(1); |
| 1259 | } finally { |
| 1260 | URL.revokeObjectURL(url); |
| 1261 | } |
| 1262 | }); |
| 1263 | |
| 1264 | it("opens a known empty attachment even when its range response is inaccessible", async () => { |
| 1265 | refresh.mockResolvedValue("https://unreachable.invalid/empty.txt"); |
| 1266 | await using screen = await render( |
| 1267 | <AttachmentFilePreview |
| 1268 | name="empty.txt" |
| 1269 | mimeType="text/plain" |
| 1270 | sizeBytes={0} |
| 1271 | asset={{ environmentId: EnvironmentId.make("test"), attachmentId: "empty" }} |
| 1272 | />, |
| 1273 | ); |
| 1274 | await vi.waitFor( |
| 1275 | () => expect(screen.container.textContent).toContain("This file is empty."), |
| 1276 | 10_000, |
| 1277 | ); |
| 1278 | }); |
| 1279 | |
| 1280 | it.each(["draft", "thread"] as const)( |
| 1281 | "reads an unknown-size %s workspace file instead of treating it as empty", |
| 1282 | async (source) => { |
| 1283 | refresh.mockResolvedValue("https://example.test/binary.txt"); |
| 1284 | using _fetch = stubGlobal( |
| 1285 | "fetch", |
| 1286 | vi.fn(async () => new Response("invalid\0text")), |
| 1287 | ); |
| 1288 | await using screen = await render( |
| 1289 | <AttachmentFilePreview |
| 1290 | name="binary.txt" |
| 1291 | mimeType="application/octet-stream" |
| 1292 | sizeBytes={0} |
| 1293 | asset={{ |
| 1294 | environmentId: EnvironmentId.make("test"), |
| 1295 | resource: |
| 1296 | source === "draft" |
| 1297 | ? { _tag: "draft-workspace-file", cwd: "/repo", path: "/repo/binary.txt" } |
| 1298 | : { _tag: "media-file", threadId: ThreadId.make("test"), path: "/repo/binary.txt" }, |
| 1299 | }} |
| 1300 | />, |
| 1301 | ); |
| 1302 | await vi.waitFor(() => |
| 1303 | expect(screen.container.textContent).toContain( |
| 1304 | "This file contains binary data and cannot be shown as text.", |
| 1305 | ), |
| 1306 | ); |
| 1307 | expect(fetch).toHaveBeenCalled(); |
| 1308 | expect(screen.container.textContent).not.toContain("This file is empty."); |
| 1309 | }, |
| 1310 | ); |
| 1311 | |
| 1312 | it("refreshes authorization and retries a failed streamed attachment", async () => { |
| 1313 | const bad = URL.createObjectURL(new Blob(["invalid\0text"])); |
| 1314 | const good = URL.createObjectURL(new Blob(["recovered text\n"])); |
| 1315 | refresh.mockReset().mockResolvedValueOnce(bad).mockResolvedValue(good); |
| 1316 | try { |
| 1317 | await using screen = await render( |
| 1318 | <AttachmentFilePreview |
| 1319 | name="retry.txt" |
| 1320 | mimeType="text/plain" |
| 1321 | sizeBytes={2_000_000} |
| 1322 | asset={{ environmentId: EnvironmentId.make("test"), attachmentId: "retry" }} |
| 1323 | />, |
| 1324 | ); |
| 1325 | // A cold large-text worker can take longer than waitFor's default to boot on CI. |
| 1326 | await vi.waitFor( |
| 1327 | () => expect(screen.container.textContent).toContain("This file contains binary data."), |
| 1328 | { timeout: 10_000 }, |
| 1329 | ); |
| 1330 | await act(() => |
| 1331 | screen.container.querySelector<HTMLButtonElement>('[role="alert"] button')!.click(), |
| 1332 | ); |
| 1333 | await vi.waitFor(() => expect(screen.container.textContent).toContain("recovered text")); |
| 1334 | expect(refresh).toHaveBeenCalledTimes(2); |
| 1335 | } finally { |
| 1336 | URL.revokeObjectURL(bad); |
| 1337 | URL.revokeObjectURL(good); |
| 1338 | } |
| 1339 | }); |
| 1340 | |
| 1341 | it.each([ |
| 1342 | ["custom/sheet1.xml", 250001], |
| 1343 | ["/xl/custom/sheet1.bin", 250001], |
| 1344 | ["custom/valid.xml", 1], |
| 1345 | ] as const)( |
| 1346 | "bounds the worksheet relationship target %s at row %i before the reader allocates its grid", |
| 1347 | async (target, row) => { |
| 1348 | const { default: JSZip } = await import("jszip"); |
| 1349 | const zip = new JSZip(); |
| 1350 | zip.file( |
| 1351 | "xl/workbook.xml", |
| 1352 | '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet" sheetId="1" r:id="rId1"/></sheets></workbook>', |
| 1353 | ); |
| 1354 | zip.file( |
| 1355 | "xl/_rels/workbook.xml.rels", |
| 1356 | `<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="${target}"/></Relationships>`, |
| 1357 | ); |
| 1358 | zip.file( |
| 1359 | target.startsWith("/") ? target.slice(1) : `xl/${target}`, |
| 1360 | `<worksheet><sheetData><row r="${row}"><c r="A${row}" t="inlineStr"><is><t>worksheet value</t></is></c></row></sheetData></worksheet>`, |
| 1361 | ); |
| 1362 | const bytes = await zip.generateAsync({ type: "arraybuffer", compression: "DEFLATE" }); |
| 1363 | const { prepareOffice } = await import("./officeArchive"); |
| 1364 | if (row > 250000) { |
| 1365 | await expect( |
| 1366 | prepareOffice(bytes, "xlsx").catch((cause: unknown) => previewErrorText(cause, "")), |
| 1367 | ).resolves.toContain("This workbook exceeds the preview limit"); |
| 1368 | return; |
| 1369 | } |
| 1370 | const prepared = await prepareOffice(bytes, "xlsx"); |
| 1371 | const bounded = await JSZip.loadAsync(prepared.bytes); |
| 1372 | expect(await bounded.file(`xl/${target}`)!.async("string")).toContain("worksheet value"); |
| 1373 | }, |
| 1374 | ); |
| 1375 | |
| 1376 | it("copies every indexed line rather than the mounted preview rows", async () => { |
| 1377 | const text = Array.from({ length: 10_000 }, (_, i) => `line-${i}`).join("\n"); |
| 1378 | const copyContents = { current: null as (() => Promise<string>) | null }; |
| 1379 | await using screen = await render( |
| 1380 | <LargeTextViewer name="whole.txt" text={text} delimiter={null} copyContents={copyContents} />, |
| 1381 | ); |
| 1382 | await vi.waitFor(() => expect(screen.container.textContent).toContain("line-0")); |
| 1383 | // Copy rejects until the worker finishes indexing, which a cold worker can delay past waitFor's default on CI. |
| 1384 | await vi.waitFor(async () => expect(await copyContents.current!()).toBe(text), { |
| 1385 | timeout: 10_000, |
| 1386 | }); |
| 1387 | const first = copyContents.current!(); |
| 1388 | await expect(copyContents.current!()).rejects.toThrow("Another copy is in progress."); |
| 1389 | expect(await first).toBe(text); |
| 1390 | expect(await copyContents.current!()).toBe(text); |
| 1391 | expect(screen.container.querySelector('[role="alert"]')).toBeNull(); |
| 1392 | }); |
| 1393 | |
| 1394 | it.each([ |
| 1395 | ["one.csv", "text/csv", "name\nAda\n", "1 row · 1 column ·"], |
| 1396 | ["two.csv", "text/csv", "name,count\nAda,1\nGrace,2\n", "2 rows · 2 columns ·"], |
| 1397 | ["one.tsv", "text/tab-separated-values", "name\nAda\n", "1 row · 1 column ·"], |
| 1398 | ["one.txt", "text/plain", "a".repeat(1024 * 1024) + "\n", "1 line ·"], |
| 1399 | ["two.txt", "text/plain", ("a".repeat(512 * 1024) + "\n").repeat(2), "2 lines ·"], |
| 1400 | ] as const)("labels the counts of %s in the status line", async (name, mimeType, text, label) => { |
| 1401 | const file = new Blob([text], { type: mimeType }); |
| 1402 | await using screen = await render( |
| 1403 | <AttachmentFilePreview name={name} mimeType={mimeType} sizeBytes={file.size} file={file} />, |
| 1404 | ); |
| 1405 | const status = () => screen.container.querySelector('[role="status"]')?.textContent ?? ""; |
| 1406 | // A cold large-text worker can take longer than waitFor's default to boot on CI. |
| 1407 | await vi.waitFor(() => expect(status()).toMatch(/ [KM]?B$/), { timeout: 10_000 }); |
| 1408 | expect(status()).toContain(label); |
| 1409 | }); |
| 1410 | |
| 1411 | it.each(["archive", "sqlite"] as const)( |
| 1412 | "reauthorizes and retries a failed %s attachment", |
| 1413 | async (kind) => { |
| 1414 | const bad = URL.createObjectURL(new Blob(["invalid"])); |
| 1415 | let bytes: Uint8Array<ArrayBuffer>; |
| 1416 | if (kind === "archive") |
| 1417 | bytes = new Uint8Array( |
| 1418 | await new JSZip().file("recovered.txt", "ok").generateAsync({ type: "uint8array" }), |
| 1419 | ); |
| 1420 | else { |
| 1421 | const [{ default: initSqlJs }, { default: wasmUrl }] = await Promise.all([ |
| 1422 | import("sql.js"), |
| 1423 | import("sql.js/dist/sql-wasm.wasm?url"), |
| 1424 | ]); |
| 1425 | const SQL = await initSqlJs({ locateFile: () => wasmUrl }); |
| 1426 | const database = new SQL.Database(); |
| 1427 | database.run( |
| 1428 | "CREATE TABLE recovered (value TEXT); INSERT INTO recovered VALUES('retry succeeded')", |
| 1429 | ); |
| 1430 | bytes = new Uint8Array(database.export()); |
| 1431 | database.close(); |
| 1432 | } |
| 1433 | const good = URL.createObjectURL(new Blob([bytes])); |
| 1434 | refresh.mockReset().mockResolvedValueOnce(bad).mockResolvedValue(good); |
| 1435 | try { |
| 1436 | await using screen = await render( |
| 1437 | <AttachmentFilePreview |
| 1438 | name={kind === "archive" ? "retry.zip" : "retry.sqlite"} |
| 1439 | mimeType="application/octet-stream" |
| 1440 | sizeBytes={bytes.length} |
| 1441 | asset={{ environmentId: EnvironmentId.make("test"), attachmentId: "retry" }} |
| 1442 | />, |
| 1443 | ); |
| 1444 | await vi.waitFor( |
| 1445 | () => expect(screen.container.querySelector('[role="alert"] button')).not.toBeNull(), |
| 1446 | 10_000, |
| 1447 | ); |
| 1448 | await act(() => |
| 1449 | screen.container.querySelector<HTMLButtonElement>('[role="alert"] button')!.click(), |
| 1450 | ); |
| 1451 | await vi.waitFor( |
| 1452 | () => |
| 1453 | expect(screen.container.textContent).toContain( |
| 1454 | kind === "archive" ? "recovered.txt" : "retry succeeded", |
| 1455 | ), |
| 1456 | 10_000, |
| 1457 | ); |
| 1458 | expect(refresh).toHaveBeenCalledTimes(2); |
| 1459 | } finally { |
| 1460 | URL.revokeObjectURL(bad); |
| 1461 | URL.revokeObjectURL(good); |
| 1462 | } |
| 1463 | }, |
| 1464 | ); |
| 1465 | |
| 1466 | it("loads a font attachment through the lazy preview", async () => { |
| 1467 | const { default: fontUrl } = |
| 1468 | await import("../../../node_modules/@betteroffice/fonts/assets/Carlito-Regular.ttf?url"); |
| 1469 | const file = await (await fetch(fontUrl)).blob(); |
| 1470 | await using screen = await render( |
| 1471 | <AttachmentFilePreview |
| 1472 | name="Carlito.ttf" |
| 1473 | mimeType="font/ttf" |
| 1474 | sizeBytes={file.size} |
| 1475 | file={file} |
| 1476 | />, |
| 1477 | ); |
| 1478 | // Two cold lazy chunks plus decoding a 600 KB font can take longer than waitFor's default on CI. |
| 1479 | await vi.waitFor( |
| 1480 | () => { |
| 1481 | const frame = screen.container.querySelector("iframe"); |
| 1482 | expect(frame?.title).toBe("Carlito.ttf"); |
| 1483 | expect(frame?.srcdoc).toContain("@font-face"); |
| 1484 | expect(frame?.srcdoc).toContain("The quick brown fox"); |
| 1485 | }, |
| 1486 | { timeout: 10_000 }, |
| 1487 | ); |
| 1488 | expect(screen.container.querySelector('[role="alert"]')).toBeNull(); |
| 1489 | }); |
| 1490 | |
| 1491 | it("toggles a Mermaid attachment between diagram and source through the lazy preview", async () => { |
| 1492 | const text = "flowchart LR\nA --> B"; |
| 1493 | const file = new Blob([text], { type: "text/vnd.mermaid" }); |
| 1494 | await using screen = await render( |
| 1495 | <AttachmentFilePreview |
| 1496 | name="diagram.mmd" |
| 1497 | mimeType={file.type} |
| 1498 | sizeBytes={file.size} |
| 1499 | file={file} |
| 1500 | />, |
| 1501 | ); |
| 1502 | await vi.waitFor(() => |
| 1503 | expect(screen.container.querySelector("[data-markdown-mermaid] svg path")).not.toBeNull(), |
| 1504 | ); |
| 1505 | await screen.getByRole("button", { name: "Expand diagram" }).click(); |
| 1506 | await vi.waitFor(() => { |
| 1507 | const image = document.querySelector<HTMLImageElement>('[role="dialog"] img'); |
| 1508 | expect(image?.alt).toBe("Mermaid diagram"); |
| 1509 | expect(image?.naturalWidth).toBeGreaterThan(0); |
| 1510 | }); |
| 1511 | await page.getByRole("button", { name: "Back, close image preview" }).click(); |
| 1512 | await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).toBeNull()); |
| 1513 | await screen.getByRole("button", { name: "Show Mermaid source" }).click(); |
| 1514 | await vi.waitFor(() => expect(screen.container.querySelector("pre")?.textContent).toBe(text)); |
| 1515 | await screen.getByRole("button", { name: "Show rendered diagram" }).click(); |
| 1516 | await vi.waitFor(() => |
| 1517 | expect(screen.container.querySelector("[data-markdown-mermaid] svg path")).not.toBeNull(), |
| 1518 | ); |
| 1519 | expect(screen.container.querySelector('[role="alert"]')).toBeNull(); |
| 1520 | }); |
| 1521 | |
| 1522 | it("keeps a workspace PDF open across URL renewals and reloads it when the file changes", async () => { |
| 1523 | const { WorkspaceBrowserPreview } = await import("./FilePreviewPanel"); |
| 1524 | using _native = vi.spyOn(navigator, "pdfViewerEnabled", "get").mockReturnValue(true); |
| 1525 | const original = URL.createObjectURL(new Blob(["%PDF-1.4"], { type: "application/pdf" })); |
| 1526 | const edited = URL.createObjectURL(new Blob(["%PDF-1.4 edited"], { type: "application/pdf" })); |
| 1527 | const preview = (mutation: string) => ( |
| 1528 | <WorkspaceBrowserPreview |
| 1529 | environmentId={EnvironmentId.make("test")} |
| 1530 | threadRef={{ environmentId: EnvironmentId.make("test"), threadId: ThreadId.make("test") }} |
| 1531 | draft={false} |
| 1532 | workspaceRoot="/repo" |
| 1533 | absolutePath="/repo/planning.pdf" |
| 1534 | title="Planning PDF" |
| 1535 | workspaceMutationId={mutation} |
| 1536 | /> |
| 1537 | ); |
| 1538 | assetUrlState.mockReturnValue({ |
| 1539 | _tag: "Success", |
| 1540 | url: `${original}#initial`, |
| 1541 | expiresAt: 0, |
| 1542 | fileRevision: "one", |
| 1543 | }); |
| 1544 | try { |
| 1545 | await using screen = await render(preview("first")); |
| 1546 | const opened = screen.container.querySelector("iframe"); |
| 1547 | expect(opened?.src.startsWith(original)).toBe(true); |
| 1548 | |
| 1549 | // An agent command renews the signed URL but leaves the file alone. |
| 1550 | assetUrlState.mockReturnValue({ |
| 1551 | _tag: "Success", |
| 1552 | url: `${original}#renewed`, |
| 1553 | expiresAt: 0, |
| 1554 | fileRevision: "one", |
| 1555 | }); |
| 1556 | await screen.rerender(preview("second")); |
| 1557 | expect(assetUrlState).toHaveBeenLastCalledWith(expect.anything(), expect.anything(), "second"); |
| 1558 | expect(screen.container.querySelector("iframe")).toBe(opened); |
| 1559 | |
| 1560 | assetUrlState.mockReturnValue({ |
| 1561 | _tag: "Success", |
| 1562 | url: edited, |
| 1563 | expiresAt: 0, |
| 1564 | fileRevision: "two", |
| 1565 | }); |
| 1566 | await screen.rerender(preview("third")); |
| 1567 | const reloaded = screen.container.querySelector("iframe"); |
| 1568 | expect(reloaded).not.toBe(opened); |
| 1569 | expect(reloaded?.src.startsWith(edited)).toBe(true); |
| 1570 | |
| 1571 | // Servers without revisions hold the preview back until a fresh grant arrives. |
| 1572 | assetUrlState.mockReturnValue({ |
| 1573 | _tag: "Success", |
| 1574 | url: `${edited}#stale`, |
| 1575 | expiresAt: 0, |
| 1576 | waiting: true, |
| 1577 | }); |
| 1578 | await screen.rerender(preview("fourth")); |
| 1579 | expect(screen.container.querySelector("iframe")).toBeNull(); |
| 1580 | assetUrlState.mockReturnValue({ _tag: "Success", url: original, expiresAt: 0 }); |
| 1581 | await screen.rerender(preview("fourth")); |
| 1582 | expect(screen.container.querySelector("iframe")?.src.startsWith(original)).toBe(true); |
| 1583 | } finally { |
| 1584 | URL.revokeObjectURL(original); |
| 1585 | URL.revokeObjectURL(edited); |
| 1586 | } |
| 1587 | }); |
| 1588 | |
| 1589 | it("loads an edited HTML file outside the workspace from a renewed URL", async () => { |
| 1590 | const { WorkspaceBrowserPreview } = await import("./FilePreviewPanel"); |
| 1591 | const preview = (mutation: string) => ( |
| 1592 | <WorkspaceBrowserPreview |
| 1593 | environmentId={EnvironmentId.make("test")} |
| 1594 | threadRef={{ environmentId: EnvironmentId.make("test"), threadId: ThreadId.make("test") }} |
| 1595 | draft={false} |
| 1596 | workspaceRoot="/repo" |
| 1597 | absolutePath="/tmp/report.html" |
| 1598 | title="Report" |
| 1599 | workspaceMutationId={mutation} |
| 1600 | /> |
| 1601 | ); |
| 1602 | assetUrlState.mockReturnValue({ _tag: "Success", url: "data:text/html,original", expiresAt: 0 }); |
| 1603 | await using screen = await render(preview("first")); |
| 1604 | const opened = screen.container.querySelector("iframe"); |
| 1605 | expect(opened?.getAttribute("src")).toMatch(/^data:text\/html,original/); |
| 1606 | |
| 1607 | assetUrlState.mockReturnValue({ |
| 1608 | _tag: "Success", |
| 1609 | url: "data:text/html,original", |
| 1610 | expiresAt: 0, |
| 1611 | waiting: true, |
| 1612 | }); |
| 1613 | await screen.rerender(preview("second")); |
| 1614 | expect(assetUrlState).toHaveBeenLastCalledWith(expect.anything(), expect.anything(), "second"); |
| 1615 | expect(screen.container.querySelector("iframe")).toBe(opened); |
| 1616 | |
| 1617 | assetUrlState.mockReturnValue({ _tag: "Success", url: "data:text/html,edited", expiresAt: 0 }); |
| 1618 | await screen.rerender(preview("second")); |
| 1619 | expect(screen.container.querySelector("iframe")?.getAttribute("src")).toMatch( |
| 1620 | /^data:text\/html,edited/, |
| 1621 | ); |
| 1622 | }); |
| 1623 | |
| 1624 | it("keeps an unchanged workspace HTML page loaded across commands and renews its grant", async () => { |
| 1625 | const { WorkspaceBrowserPreview } = await import("./FilePreviewPanel"); |
| 1626 | const preview = (mutation: string) => ( |
| 1627 | <WorkspaceBrowserPreview |
| 1628 | environmentId={EnvironmentId.make("test")} |
| 1629 | threadRef={{ environmentId: EnvironmentId.make("test"), threadId: ThreadId.make("test") }} |
| 1630 | draft={false} |
| 1631 | workspaceRoot="/repo" |
| 1632 | absolutePath="/repo/report.html" |
| 1633 | title="Report" |
| 1634 | workspaceMutationId={mutation} |
| 1635 | /> |
| 1636 | ); |
| 1637 | const minted = (url: string, fileRevision: string, expiresAt: number) => |
| 1638 | assetUrlState.mockReturnValue({ _tag: "Success", url, expiresAt, fileRevision }); |
| 1639 | const shownSrc = (screen: Screen) => |
| 1640 | screen.container.querySelector("iframe")?.getAttribute("src"); |
| 1641 | refresh.mockReset(); |
| 1642 | using _timers = fakeTimers(); |
| 1643 | vi.setSystemTime(0); |
| 1644 | const expiresAt = 60 * 60_000; |
| 1645 | minted("data:text/html,original", "one", expiresAt); |
| 1646 | await using screen = await render(preview("first")); |
| 1647 | const opened = screen.container.querySelector("iframe"); |
| 1648 | expect(shownSrc(screen)).toMatch(/^data:text\/html,original/); |
| 1649 | |
| 1650 | // Agent commands re-mint the URL; the page and everything it loaded are unchanged. |
| 1651 | minted("data:text/html,renewed", "one", expiresAt + 30 * 60_000); |
| 1652 | await screen.rerender(preview("second")); |
| 1653 | await screen.rerender(preview("third")); |
| 1654 | expect(screen.container.querySelector("iframe")).toBe(opened); |
| 1655 | expect(shownSrc(screen)).toMatch(/^data:text\/html,original/); |
| 1656 | expect(refresh).not.toHaveBeenCalled(); |
| 1657 | |
| 1658 | // Its grant is about to expire, so the page moves to the URL minted since. |
| 1659 | await act(() => vi.advanceTimersByTime(59 * 60_000)); |
| 1660 | expect(shownSrc(screen)).toMatch(/^data:text\/html,renewed/); |
| 1661 | expect(refresh).not.toHaveBeenCalled(); |
| 1662 | |
| 1663 | // With no command since, the page asks for a fresh URL itself and moves to it. |
| 1664 | refresh.mockResolvedValue(null); |
| 1665 | await act(() => vi.advanceTimersByTime(30 * 60_000)); |
| 1666 | expect(refresh).toHaveBeenCalledTimes(1); |
| 1667 | minted("data:text/html,renewed-again", "one", expiresAt + 90 * 60_000); |
| 1668 | await screen.rerender(preview("third")); |
| 1669 | expect(shownSrc(screen)).toMatch(/^data:text\/html,renewed-again/); |
| 1670 | |
| 1671 | minted("data:text/html,edited", "two", expiresAt + 90 * 60_000); |
| 1672 | await screen.rerender(preview("fourth")); |
| 1673 | expect(shownSrc(screen)).toMatch(/^data:text\/html,edited/); |
| 1674 | }); |
| 1675 | |
| 1676 | function planningPdf( |
| 1677 | titles = ["Quarterly outlook", "Delivery milestones", "Budget and risks"], |
| 1678 | firstHeight = 140, |
| 1679 | pageHeight = 792, |
| 1680 | ) { |
| 1681 | const objects = [ |
| 1682 | "<< /Type /Catalog /Pages 2 0 R >>", |
| 1683 | `<< /Type /Pages /Count ${titles.length} /Kids [${titles.map((_, index) => `${3 + index * 2} 0 R`).join(" ")}] >>`, |
| 1684 | ]; |
| 1685 | const font = 3 + titles.length * 2; |
| 1686 | for (const [index, title] of titles.entries()) { |
| 1687 | const text = `/GS1 gs BT /F1 24 Tf 30 ${index === 0 ? 70 : 700} Td ${index === 0 ? "(Quarter) Tj /F2 24 Tf (ly outlook) Tj" : `(${title}) Tj`} ET`; |
| 1688 | objects.push( |
| 1689 | `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 ${index === 0 ? firstHeight : pageHeight}] /Rotate ${index === 2 ? 90 : 0} /Resources << /Font << /F1 ${font} 0 R /F2 ${font + 1} 0 R >> /ExtGState << /GS1 << /TR << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 2 >> >> >> >> /Contents ${4 + index * 2} 0 R >>`, |
| 1690 | `<< /Length ${text.length} >>\nstream\n${text}\nendstream`, |
| 1691 | ); |
| 1692 | } |
| 1693 | objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"); |
| 1694 | objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>"); |
| 1695 | let source = "%PDF-1.4\n"; |
| 1696 | const offsets = [0]; |
| 1697 | for (const [index, object] of objects.entries()) { |
| 1698 | offsets.push(source.length); |
| 1699 | source += `${index + 1} 0 obj\n${object}\nendobj\n`; |
| 1700 | } |
| 1701 | const xref = source.length; |
| 1702 | source += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n${offsets |
| 1703 | .slice(1) |
| 1704 | .map((offset) => `${String(offset).padStart(10, "0")} 00000 n \n`) |
| 1705 | .join("")}trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`; |
| 1706 | return new Blob([source], { type: "application/pdf" }); |
| 1707 | } |
| 1708 | |
| 1709 | // Resolves once pdf.js has parsed the next document and every page size the viewer reads. |
| 1710 | function nextPdfLoad() { |
| 1711 | return new Promise<import("pdfjs-dist").PDFDocumentLoadingTask>((resolve) => |
| 1712 | pdfOpens.push(resolve), |
| 1713 | ).then(async (task) => { |
| 1714 | const document = await task.promise; |
| 1715 | await Promise.all( |
| 1716 | Array.from({ length: document.numPages }, (_, index) => document.getPage(index + 1)), |
| 1717 | ); |
| 1718 | }); |
| 1719 | } |
| 1720 | |
| 1721 | it("keeps a workspace PDF's page, offset and zoom when a new revision reloads it", async () => { |
| 1722 | assetUrlState.mockReset(); |
| 1723 | pdfOpens.length = 0; |
| 1724 | const { WorkspaceBrowserPreview } = await import("./FilePreviewPanel"); |
| 1725 | using _native = vi.spyOn(navigator, "pdfViewerEnabled", "get").mockReturnValue(false); |
| 1726 | const original = URL.createObjectURL(planningPdf()); |
| 1727 | // A taller first page moves page 2, so only a page-relative restore lands on the same spot. |
| 1728 | const updated = URL.createObjectURL( |
| 1729 | planningPdf(["Quarterly outlook", "Delivery milestones", "Updated budget"], 500), |
| 1730 | ); |
| 1731 | const preview = (src: string, mutation: string, path = "/repo/planning.pdf") => { |
| 1732 | assetUrlState.mockReturnValue({ |
| 1733 | _tag: "Success", |
| 1734 | url: `${src}#preview`, |
| 1735 | expiresAt: Date.now() + 3_600_000, |
| 1736 | }); |
| 1737 | return ( |
| 1738 | <div className="flex h-[600px] w-[320px]"> |
| 1739 | <WorkspaceBrowserPreview |
| 1740 | environmentId={EnvironmentId.make("test")} |
| 1741 | threadRef={{ |
| 1742 | environmentId: EnvironmentId.make("test"), |
| 1743 | threadId: ThreadId.make(original), |
| 1744 | }} |
| 1745 | draft={false} |
| 1746 | absolutePath={path} |
| 1747 | workspaceRoot="/repo" |
| 1748 | title="Planning PDF" |
| 1749 | workspaceMutationId={mutation} |
| 1750 | /> |
| 1751 | </div> |
| 1752 | ); |
| 1753 | }; |
| 1754 | const reload = async (screen: Screen, element: ReactElement) => { |
| 1755 | const loaded = nextPdfLoad(); |
| 1756 | await screen.rerender(element); |
| 1757 | await loaded; |
| 1758 | }; |
| 1759 | try { |
| 1760 | const loaded = nextPdfLoad(); |
| 1761 | await using screen = await render(preview(original, "one")); |
| 1762 | await loaded; |
| 1763 | await expect.element(screen.getByText("1 / 3 pages", { exact: true })).toBeVisible(); |
| 1764 | using workers = vi.spyOn(window, "Worker"); |
| 1765 | const region = () => screen.getByRole("region", { name: "Planning PDF" }).element(); |
| 1766 | const offset = () => |
| 1767 | region().getBoundingClientRect().top - |
| 1768 | region().querySelector('canvas[aria-label="Page 2"]')!.getBoundingClientRect().top; |
| 1769 | await screen.getByRole("button", { name: "Zoom in", exact: true }).click(); |
| 1770 | await screen.getByRole("button", { name: "Next page", exact: true }).click(); |
| 1771 | await expect.element(screen.getByText("2 / 3 pages", { exact: true })).toBeVisible(); |
| 1772 | const zoom = screen.container.textContent!.match(/\d+%/)![0]; |
| 1773 | const top = region().scrollTop + 100; |
| 1774 | await act(async () => { |
| 1775 | const scrolled = new Promise((resolve) => |
| 1776 | region().addEventListener("scroll", resolve, { once: true }), |
| 1777 | ); |
| 1778 | region().scrollTo({ top, left: 80 }); |
| 1779 | await scrolled; |
| 1780 | }); |
| 1781 | const savedOffset = offset(); |
| 1782 | |
| 1783 | await reload(screen, preview(updated, "two")); |
| 1784 | await expect.element(screen.getByText("2 / 3 pages", { exact: true })).toBeVisible(); |
| 1785 | expect(screen.container.textContent).toContain(zoom); |
| 1786 | expect(region().scrollLeft).toBe(80); |
| 1787 | expect(offset()).toBeCloseTo(savedOffset, 0); |
| 1788 | expect(workers).not.toHaveBeenCalled(); |
| 1789 | |
| 1790 | await reload(screen, preview(updated, "two", "/repo/another.pdf")); |
| 1791 | await expect.element(screen.getByText("1 / 3 pages", { exact: true })).toBeVisible(); |
| 1792 | expect(screen.container.textContent).toContain("Fit width"); |
| 1793 | expect(region().scrollTop).toBe(0); |
| 1794 | } finally { |
| 1795 | URL.revokeObjectURL(original); |
| 1796 | URL.revokeObjectURL(updated); |
| 1797 | } |
| 1798 | }); |
| 1799 | |
| 1800 | it("unwraps one text attachment without turning off the word wrap setting", async () => { |
| 1801 | const file = new Blob(["a long line"], { type: "text/plain" }); |
| 1802 | await using screen = await render( |
| 1803 | <AttachmentFilePreview |
| 1804 | name="notes.txt" |
| 1805 | mimeType={file.type} |
| 1806 | sizeBytes={file.size} |
| 1807 | file={file} |
| 1808 | />, |
| 1809 | ); |
| 1810 | await screen.getByRole("button", { name: "Disable word wrap" }).click(); |
| 1811 | await expect.element(screen.getByRole("button", { name: "Enable word wrap" })).toBeVisible(); |
| 1812 | expect(getClientSettings().wordWrap).toBe(true); |
| 1813 | expect(screen.container.querySelector("pre")?.dataset.wordWrap).toBe("false"); |
| 1814 | }); |
| 1815 | |
| 1816 | it("mounts a bounded set of saved notebook outputs as the reader scrolls", async () => { |
| 1817 | const notebook = { |
| 1818 | nbformat: 4, |
| 1819 | metadata: {}, |
| 1820 | cells: Array.from({ length: 20 }, (_, cell) => ({ |
| 1821 | cell_type: "code", |
| 1822 | source: [], |
| 1823 | metadata: {}, |
| 1824 | outputs: Array.from({ length: 100 }, (_, output) => ({ |
| 1825 | output_type: "display_data", |
| 1826 | data: { "text/html": `<p>saved ${cell}-${output}</p>` }, |
| 1827 | })), |
| 1828 | })), |
| 1829 | }; |
| 1830 | const file = new Blob([JSON.stringify(notebook)]); |
| 1831 | await using screen = await render( |
| 1832 | <div style={{ display: "flex", height: 400, width: 600 }}> |
| 1833 | <AttachmentFilePreview |
| 1834 | name="observations.ipynb" |
| 1835 | mimeType="application/json" |
| 1836 | sizeBytes={file.size} |
| 1837 | file={file} |
| 1838 | /> |
| 1839 | </div>, |
| 1840 | ); |
| 1841 | // The first outputs wait on the lazy notebook viewer and the conversion worker, not on a frame. |
| 1842 | await vi.waitFor( |
| 1843 | () => expect(screen.container.querySelectorAll("iframe").length).toBeGreaterThan(0), |
| 1844 | { timeout: 10_000 }, |
| 1845 | ); |
| 1846 | expect(screen.container.querySelectorAll("iframe").length).toBeLessThanOrEqual(16); |
| 1847 | const first = screen.container.querySelector("iframe")!; |
| 1848 | expect(first.srcdoc).toContain("saved 0-0"); |
| 1849 | const viewport = screen.container.querySelector<HTMLElement>(".scrollbar-gutter-both")!; |
| 1850 | await act(() => { |
| 1851 | viewport.scrollTop = viewport.scrollHeight; |
| 1852 | }); |
| 1853 | await vi.waitFor(() => { |
| 1854 | expect( |
| 1855 | [...screen.container.querySelectorAll("iframe")].some((frame) => |
| 1856 | frame.srcdoc.includes("saved 19-99"), |
| 1857 | ), |
| 1858 | ).toBe(true); |
| 1859 | expect(first.isConnected).toBe(false); |
| 1860 | }); |
| 1861 | expect(screen.container.querySelectorAll("iframe").length).toBeLessThanOrEqual(16); |
| 1862 | await act(() => { |
| 1863 | viewport.scrollTop = 0; |
| 1864 | }); |
| 1865 | await vi.waitFor(() => |
| 1866 | expect(screen.container.querySelector("iframe")?.srcdoc).toContain("saved 0-0"), |
| 1867 | ); |
| 1868 | }); |
| 1869 | |
| 1870 | it.each([ |
| 1871 | [String.raw`{\rtf1\uc1\u945{\b bold}Hello}`, "αboldHello"], |
| 1872 | [String.raw`{\rtf1\uc1{\u945}Hello}`, "αHello"], |
| 1873 | [ |
| 1874 | String.raw`{\rtf1\ansi{\fonttbl{\f0\fcharset204 Cyrillic;}{\f1\fcharset0 Latin;}}\f0\'c0{\f1\'c0}\'c1}`, |
| 1875 | "АÀБ", |
| 1876 | ], |
| 1877 | [String.raw`{\rtf1\ansi\deff1{\fonttbl{\f1\fcharset204 Cyrillic;}}\'c0\plain\'c1}`, "АБ"], |
| 1878 | ])("retains RTF grouped Unicode and font text in %s", async (source, expected) => { |
| 1879 | const { openRtf } = await import("./extendedDocumentPreview"); |
| 1880 | const result = openRtf(new TextEncoder().encode(source).buffer); |
| 1881 | if (result.type !== "document") throw new Error("Expected rich text document"); |
| 1882 | const html = result.pages.map((page) => page.html).join(""); |
| 1883 | expect(new DOMParser().parseFromString(html, "text/html").body.textContent).toBe(expected); |
| 1884 | }); |
| 1885 | |
| 1886 | it.each(["odt", "odp"] as const)("preserves rendered %s spaces and tabs", async (kind) => { |
| 1887 | const archive = new JSZip().file( |
| 1888 | "content.xml", |
| 1889 | `<office:document>${kind === "odt" ? "<office:text>" : "<draw:page>"}<text:p>A<text:s text:c="3"/>B<text:tab/>C</text:p>${kind === "odt" ? "</office:text>" : "</draw:page>"}</office:document>`, |
| 1890 | ); |
| 1891 | const bytes = await archive.generateAsync({ type: "arraybuffer" }); |
| 1892 | const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), { |
| 1893 | type: "module", |
| 1894 | }); |
| 1895 | try { |
| 1896 | const result = await new Promise<OfficeWorkerResult>((resolve) => { |
| 1897 | worker.addEventListener( |
| 1898 | "message", |
| 1899 | (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data), |
| 1900 | { once: true }, |
| 1901 | ); |
| 1902 | worker.postMessage({ type: "open", kind, bytes }, [bytes]); |
| 1903 | }); |
| 1904 | if (result.type !== "document") throw new Error("Expected document"); |
| 1905 | await using screen = await render( |
| 1906 | <DocumentPages html={result.pages[0]!.html} name="spacing" output />, |
| 1907 | ); |
| 1908 | await vi.waitFor(() => { |
| 1909 | const doc = screen.container.querySelector("iframe")?.contentDocument; |
| 1910 | const spans = doc?.querySelectorAll<HTMLElement>("span[data-odf-whitespace]"); |
| 1911 | expect(doc?.querySelector("p")?.textContent).toBe("A B\tC"); |
| 1912 | expect(spans).toHaveLength(2); |
| 1913 | for (const span of spans!) { |
| 1914 | expect(doc!.defaultView!.getComputedStyle(span).whiteSpace).toBe("pre-wrap"); |
| 1915 | expect(span.getBoundingClientRect().width).toBeGreaterThan(0); |
| 1916 | } |
| 1917 | expect(spans![0]!.getBoundingClientRect().width).toBeGreaterThan(10); |
| 1918 | }); |
| 1919 | } finally { |
| 1920 | worker.terminate(); |
| 1921 | } |
| 1922 | }); |
| 1923 | |
| 1924 | it.each(["rtf", "epub", "ods"] as const)( |
| 1925 | "preserves %s document text through the worker and attachment viewer", |
| 1926 | async (kind) => { |
| 1927 | const archive = new JSZip(); |
| 1928 | if (kind === "epub") { |
| 1929 | archive.file( |
| 1930 | "META-INF/container.xml", |
| 1931 | '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>', |
| 1932 | ); |
| 1933 | archive.file( |
| 1934 | "book.opf", |
| 1935 | '<package><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>', |
| 1936 | ); |
| 1937 | archive.file( |
| 1938 | "chapter.xhtml", |
| 1939 | "<html><head><title>Handbook</title></head><body><p>first<br/>second<br/>third</p><hr/></body></html>", |
| 1940 | ); |
| 1941 | } else if (kind === "ods") { |
| 1942 | archive.file( |
| 1943 | "content.xml", |
| 1944 | '<office:document><table:table table:name="Forecast"><table:table-row><table:table-cell><text:p>North<office:annotation><text:p>nested note</text:p></office:annotation></text:p><office:annotation><text:p>private note</text:p></office:annotation></table:table-cell><table:table-cell office:value="150"><office:annotation><text:p>revised from 120</text:p></office:annotation></table:table-cell><table:table-cell table:number-columns-repeated="1024"/></table:table-row><table:table-row table:number-rows-repeated="1048570"><table:table-cell table:number-columns-repeated="1024"/></table:table-row></table:table></office:document>', |
| 1945 | ); |
| 1946 | } |
| 1947 | const file = |
| 1948 | kind === "rtf" |
| 1949 | ? new Blob([ |
| 1950 | String.raw`{\rtf1\ansi 10\endash 20 \emdash \bullet \lquote a\rquote \ldblquote b\rdblquote\par Name\cell Value\cell\row 12\cell 34\cell\row{\*\private hidden\endash\cell\row}Unicode:\u8211\endash end}`, |
| 1951 | ]) |
| 1952 | : await archive.generateAsync({ type: "blob" }); |
| 1953 | const bytes = await file.arrayBuffer(); |
| 1954 | const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), { |
| 1955 | type: "module", |
| 1956 | }); |
| 1957 | try { |
| 1958 | const result = await new Promise<OfficeWorkerResult>((resolve) => { |
| 1959 | worker.addEventListener( |
| 1960 | "message", |
| 1961 | (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data), |
| 1962 | { once: true }, |
| 1963 | ); |
| 1964 | worker.postMessage({ type: "open", kind, bytes }, [bytes]); |
| 1965 | }); |
| 1966 | if (kind === "ods") { |
| 1967 | expect(result.type).toBe("ods"); |
| 1968 | if (result.type !== "ods") throw new Error("Expected spreadsheet"); |
| 1969 | expect(result.sheets[0]!.rows).toEqual([["North", "150"]]); |
| 1970 | } else { |
| 1971 | expect(result.type).toBe("document"); |
| 1972 | if (result.type !== "document") throw new Error("Expected document"); |
| 1973 | const body = new DOMParser().parseFromString(result.pages[0]!.html, "text/html").body; |
| 1974 | if (kind === "epub") { |
| 1975 | expect(body.querySelectorAll("br")).toHaveLength(2); |
| 1976 | expect(body.querySelectorAll("hr")).toHaveLength(1); |
| 1977 | } else { |
| 1978 | expect(body.textContent).toContain("10–20 —•‘a’“b”"); |
| 1979 | expect(body.textContent).toContain("Name\tValue\t12\t34\t"); |
| 1980 | expect(body.textContent).toContain("Unicode:–end"); |
| 1981 | expect(body.textContent).not.toContain("hidden"); |
| 1982 | expect(body.querySelectorAll("br")).toHaveLength(3); |
| 1983 | } |
| 1984 | } |
| 1985 | } finally { |
| 1986 | worker.terminate(); |
| 1987 | } |
| 1988 | await using screen = await render( |
| 1989 | <div style={{ display: "flex", height: 400, width: 600 }}> |
| 1990 | <AttachmentFilePreview |
| 1991 | name={`report.${kind}`} |
| 1992 | mimeType="application/octet-stream" |
| 1993 | sizeBytes={file.size} |
| 1994 | file={file} |
| 1995 | /> |
| 1996 | </div>, |
| 1997 | ); |
| 1998 | await vi.waitFor( |
| 1999 | () => { |
| 2000 | if (kind === "ods") { |
| 2001 | expect(screen.container.textContent).toContain("North"); |
| 2002 | expect(screen.container.textContent).toContain("150"); |
| 2003 | expect(screen.container.textContent).not.toContain("private note"); |
| 2004 | expect(screen.container.textContent).toContain("1 row · 2 columns"); |
| 2005 | expect(screen.container.textContent).not.toContain("Limited to 500"); |
| 2006 | } else { |
| 2007 | const frame = screen.container.querySelector("iframe"); |
| 2008 | expect(frame?.srcdoc).toContain(kind === "rtf" ? "10–20" : "first<br>second<br>third"); |
| 2009 | } |
| 2010 | // The viewer runs its own conversion worker behind lazy chunks. |
| 2011 | }, |
| 2012 | { timeout: 10_000 }, |
| 2013 | ); |
| 2014 | expect(screen.container.querySelector('[role="alert"]')).toBeNull(); |
| 2015 | }, |
| 2016 | ); |
| 2017 | |
| 2018 | it.each(["epub", "odt", "ipynb", "html", "encoded-html"] as const)( |
| 2019 | "bounds %s image pixels before returning browser markup", |
| 2020 | async (kind) => { |
| 2021 | const canvas = new OffscreenCanvas(2, 3); |
| 2022 | canvas.getContext("2d"); |
| 2023 | const blob = await canvas.convertToBlob({ type: "image/png" }); |
| 2024 | for (const width of [2, 12000]) { |
| 2025 | const image = await blob.arrayBuffer(); |
| 2026 | new DataView(image).setUint32(16, width); |
| 2027 | new DataView(image).setUint32(20, width === 2 ? 3 : 12000); |
| 2028 | const archive = new JSZip(); |
| 2029 | archive.file("cover.png", image); |
| 2030 | if (kind === "epub") { |
| 2031 | archive.file( |
| 2032 | "META-INF/container.xml", |
| 2033 | '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>', |
| 2034 | ); |
| 2035 | archive.file( |
| 2036 | "book.opf", |
| 2037 | '<package><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>', |
| 2038 | ); |
| 2039 | archive.file( |
| 2040 | "chapter.xhtml", |
| 2041 | '<html><body><p>retained caption</p><img src="cover.png"/></body></html>', |
| 2042 | ); |
| 2043 | } else |
| 2044 | archive.file( |
| 2045 | "content.xml", |
| 2046 | '<office:document><office:text><text:p>retained caption</text:p><draw:image xlink:href="cover.png"/></office:text></office:document>', |
| 2047 | ); |
| 2048 | const base64 = btoa(String.fromCharCode(...new Uint8Array(image))); |
| 2049 | const bytes = |
| 2050 | kind === "ipynb" || kind === "html" || kind === "encoded-html" |
| 2051 | ? new TextEncoder().encode( |
| 2052 | JSON.stringify({ |
| 2053 | nbformat: 4, |
| 2054 | cells: [ |
| 2055 | { |
| 2056 | cell_type: "code", |
| 2057 | source: "plot()", |
| 2058 | outputs: [ |
| 2059 | { |
| 2060 | data: { |
| 2061 | ...(kind === "html" || kind === "encoded-html" |
| 2062 | ? { |
| 2063 | "text/html": `<table><tr><td>retained caption</td></tr></table><img src="${kind === "encoded-html" ? "data" : "data"}:image/png;base64,${base64}">`, |
| 2064 | } |
| 2065 | : { "image/png": base64 }), |
| 2066 | "text/plain": "retained caption", |
| 2067 | }, |
| 2068 | }, |
| 2069 | ], |
| 2070 | }, |
| 2071 | ], |
| 2072 | }), |
| 2073 | ).buffer |
| 2074 | : await archive.generateAsync({ type: "arraybuffer" }); |
| 2075 | const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), { |
| 2076 | type: "module", |
| 2077 | }); |
| 2078 | try { |
| 2079 | const result = await new Promise<OfficeWorkerResult>((resolve) => { |
| 2080 | worker.addEventListener( |
| 2081 | "message", |
| 2082 | (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data), |
| 2083 | { once: true }, |
| 2084 | ); |
| 2085 | worker.postMessage( |
| 2086 | { |
| 2087 | type: "open", |
| 2088 | kind: kind === "html" || kind === "encoded-html" ? "ipynb" : kind, |
| 2089 | bytes, |
| 2090 | }, |
| 2091 | [bytes], |
| 2092 | ); |
| 2093 | }); |
| 2094 | if (result.type === "notebook") { |
| 2095 | const output = result.cells[0]!.outputs[0]!; |
| 2096 | expect(output.kind).toBe( |
| 2097 | width === 2 ? (kind === "html" || kind === "encoded-html" ? "html" : "image") : "text", |
| 2098 | ); |
| 2099 | if (output.kind === "html") { |
| 2100 | const rendered = new DOMParser().parseFromString( |
| 2101 | sanitizeDocumentHtml(output.text), |
| 2102 | "text/html", |
| 2103 | ); |
| 2104 | expect(rendered.images).toHaveLength(1); |
| 2105 | expect(rendered.querySelector("td")!.textContent).toBe("retained caption"); |
| 2106 | } |
| 2107 | if (width !== 2) expect(result.cells[0]!.outputs[0]!.text).toBe("retained caption"); |
| 2108 | } else { |
| 2109 | expect(result.type).toBe("document"); |
| 2110 | if (result.type !== "document") throw new Error("Expected document"); |
| 2111 | expect(result.pages[0]!.html.includes("<img")).toBe(width === 2); |
| 2112 | expect(result.pages[0]!.html).toContain("retained caption"); |
| 2113 | } |
| 2114 | } finally { |
| 2115 | worker.terminate(); |
| 2116 | } |
| 2117 | } |
| 2118 | }, |
| 2119 | ); |
| 2120 | |
| 2121 | it.each([ |
| 2122 | ["standardFontDataUrl", "FoxitSerif.pfb", "standard_fonts"], |
| 2123 | ["cMapUrl", "78-EUC-H.bcmap", "cmaps"], |
| 2124 | ["wasmUrl", "openjpeg.wasm", "wasm"], |
| 2125 | ])("validates PDF %s assets before decoding", async (kind, filename, directory) => { |
| 2126 | const { BinaryDataFactory } = await import("./pdfDocument"); |
| 2127 | const factory = new BinaryDataFactory(); |
| 2128 | const fetchAsset = vi.fn( |
| 2129 | async () => |
| 2130 | new Response("<html>app</html>", { |
| 2131 | headers: { "content-type": "text/html; charset=utf-8" }, |
| 2132 | }), |
| 2133 | ); |
| 2134 | using _fetch = stubGlobal("fetch", fetchAsset); |
| 2135 | await expect(factory.fetch({ kind, filename })).rejects.toThrow( |
| 2136 | `PDF ${directory} asset unavailable.`, |
| 2137 | ); |
| 2138 | fetchAsset.mockImplementation(async () => new Response(new Uint8Array([1, 2, 3]))); |
| 2139 | await expect(factory.fetch({ kind, filename })).resolves.toEqual(new Uint8Array([1, 2, 3])); |
| 2140 | await expect(factory.fetch({ kind, filename: "missing" })).rejects.toThrow( |
| 2141 | `Unsupported PDF ${directory} asset.`, |
| 2142 | ); |
| 2143 | }); |