The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 15:45 UTC
test(web): attachment preview Word and large-text tests no longer flake on CI (#25664)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 26, 2026 at 16:29 UTC
d73fd1279a9cbf3ef4677b88b4ad82f0a55583c7
1 file changed
+82
-221
apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
+82
-221
@@ -21,6 +21,26 @@ vi.mock(import("./ReadOnlySourcePreview"), () => ({
21
default: ({ text }: { text: string }) => <pre>{text}</pre>,
22
}));
23
24
+// The Word engine compiles about 30 MB of WebAssembly in a fresh worker per document, which took
25
+// 10-17 s per test on loaded CI runners. These tests cover fetching, preparation and remounts, so
26
+// the stand-in shows the prepared body's text instead of laying it out.
27
+vi.mock(import("./office/WordDocument"), async () => {
28
+ const { use } = await import("react");
29
+ const { default: Zip } = await import("jszip");
30
+ const texts = new WeakMap<ArrayBuffer, Promise<string>>();
31
+ const read = (bytes: ArrayBuffer) =>
32
+ Zip.loadAsync(bytes)
33
+ .then((zip) => zip.file("word/document.xml")!.async("string"))
34
+ .then((xml) => xml.replace(/<[^>]+>/g, " "));
35
+ return {
36
+ default: ({ bytes }: { bytes: ArrayBuffer }) => {
37
+ let text = texts.get(bytes);
38
+ if (!text) texts.set(bytes, (text = read(bytes)));
39
+ return <pre>{use(text)}</pre>;
40
+ },
41
+ };
42
+});
43
+
44
import { AttachmentFilePreview } from "./AttachmentFilePreview";
45
import LargeTextViewer from "./LargeTextViewer";
46
import VirtualTablePreview from "./VirtualTablePreview";
@@ -495,15 +515,16 @@ describe("large text preview recovery", () => {
515
expect(workers).toHaveLength(1);
516
state(`${changed}#updated`, "two");
517
await screen.rerender(preview("file-edit"));
518
+ // The prefetched first screen paints before the worker starts, so wait for the worker itself.
519
+ await vi.waitFor(() => expect(workers).toHaveLength(2));
520
await vi.waitFor(() => expect(screen.container.textContent).toContain("changed"));
499
- expect(workers).toHaveLength(2);
521
await screen.rerender(preview("file-edit", 1));
522
await vi.waitFor(() => expect(workers).toHaveLength(3));
523
await vi.waitFor(() => expect(screen.container.textContent).toContain("changed"));
524
state(`${original}#legacy`);
525
await screen.rerender(preview("legacy-edit", 1));
526
+ await vi.waitFor(() => expect(workers).toHaveLength(4));
527
await vi.waitFor(() => expect(screen.container.textContent).toContain("original"));
506
- expect(workers).toHaveLength(4);
528
assetUrlState.mockReturnValue({ _tag: "Failure" });
529
await screen.rerender(preview("legacy-edit", 1));
530
expect(screen.container.textContent).toContain("Unable to load file preview.");
@@ -1323,8 +1344,9 @@ async function expandedWordFixture(role: (typeof EXPANDED_WORD_ROLES)[number]) {
1344
return archive.generateAsync({ type: "blob", compression: "DEFLATE" });
1345
}
1346
1326
-// Rendering starts a layout engine per case, which dominated this file on loaded CI
1327
-// runners. The omission decision lives in prepareOffice, so every role is checked there.
1347
+// Rendering starts a Word engine worker per case, which compiles about 30 MB of WebAssembly and
1348
+// took 10-17 s per test on loaded CI runners. Omission and retention are prepareOffice decisions,
1349
+// so they are checked there.
1350
it.each(EXPANDED_WORD_ROLES)(
1351
"keeps the body and omits expanded %s from the prepared document",
1352
async (role) => {
@@ -1356,38 +1378,6 @@ it.each(EXPANDED_WORD_ROLES)(
1378
},
1379
);
1380
1359
-// Two full renders prove the engine accepts a prepared body whose parts were removed
1360
-// (body references for notes, section references for headers and footers) and show the warning.
1361
-it.each(["footnotes", "footer"] as const)(
1362
- "renders the body and warns when omitting expanded %s",
1363
- async (role) => {
1364
- const file = await expandedWordFixture(role);
1365
- const src = URL.createObjectURL(file);
1366
- try {
1367
- const container = document.createElement("div");
1368
- container.style.cssText = "display:flex;flex-direction:column;width:640px;height:700px";
1369
- await using screen = await render(
1370
- <OfficeFilePreview src={src} name="expanded.docx" kind="docx" sizeBytes={file.size} />,
1371
- { container },
1372
- );
1373
- await vi.waitFor(
1374
- () => {
1375
- expect(screen.container.querySelector('[role="alert"]')?.textContent ?? "").toBe("");
1376
- expect(screen.container.textContent).toContain("body retained");
1377
- },
1378
- { timeout: 30_000 },
1379
- );
1380
- expect(screen.container.textContent).toContain("Preview limited");
1381
- expect(screen.container.textContent).not.toContain("omitted payload");
1382
- await vi.waitFor(() =>
1383
- expect(screen.container.querySelector("canvas")!.width).toBeGreaterThan(0),
1384
- );
1385
- } finally {
1386
- URL.revokeObjectURL(src);
1387
- }
1388
- },
1389
-);
1390
-
1381
it.each([
1382
"ordinary parts",
1383
"unused parts",
@@ -1506,35 +1496,31 @@ it.each([
1496
),
1497
);
1498
}
1509
- const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
1510
- const src = URL.createObjectURL(file);
1511
- try {
1512
- const container = document.createElement("div");
1513
- container.style.cssText = "display:flex;flex-direction:column;width:640px;height:700px";
1514
- await using screen = await render(
1515
- <OfficeFilePreview src={src} name="ordinary.docx" kind="docx" />,
1516
- { container },
1517
- );
1518
- await vi.waitFor(() => expect(screen.container.textContent).toContain("ordinary body"), {
1519
- timeout: 30_000,
1520
- });
1521
- expect(screen.container.textContent).not.toContain("Preview limited");
1522
- await vi.waitFor(() =>
1523
- expect(screen.container.querySelector("canvas")!.width).toBeGreaterThan(0),
1524
- );
1525
- if (scenario === "default template styles")
1526
- expect(screen.container.textContent).toContain("styled cell");
1527
- if (ordinary) {
1528
- expect(screen.container.textContent).toContain("header retained");
1529
- expect(screen.container.textContent).toContain("footer retained");
1530
- }
1531
- } finally {
1532
- URL.revokeObjectURL(src);
1499
+ const { prepareOffice } = await import("./officeArchive");
1500
+ const prepared = await prepareOffice(
1501
+ await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" }),
1502
+ "docx",
1503
+ );
1504
+ expect(prepared.truncated).toBe(false);
1505
+ const bounded = await JSZip.loadAsync(prepared.bytes);
1506
+ const markup = await bounded.file("word/document.xml")!.async("string");
1507
+ expect(markup).toContain("ordinary body");
1508
+ expect(markup).toContain("styled body");
1509
+ expect(bounded.file("word/styles.xml")).not.toBeNull();
1510
+ if (scenario === "default template styles") {
1511
+ expect(markup).toContain("styled cell");
1512
+ expect(await bounded.file("word/styles.xml")!.async("string")).toContain('w:styleId="Table99"');
1513
+ }
1514
+ if (ordinary) {
1515
+ expect(markup).toMatch(/<w:headerReference/);
1516
+ expect(markup).toMatch(/<w:footerReference/);
1517
+ for (const role of ["header", "footer", "footnotes", "endnotes", "comments"])
1518
+ expect(await bounded.file(`word/${role}.xml`)!.async("string")).toContain(`${role} retained`);
1519
}
1520
});
1521
1522
it.each([false, true])(
1537
- "bounds shared-string text including CDATA %s per cell and across sheets in the worker and viewer",
1523
+ "bounds shared-string text including CDATA %s per cell and across sheets in the worker",
1524
async (cdata) => {
1525
const { default: JSZip } = await import("jszip");
1526
const archive = new JSZip();
@@ -1595,34 +1581,6 @@ it.each([false, true])(
1581
} finally {
1582
worker.terminate();
1583
}
1598
- const src = URL.createObjectURL(file);
1599
- try {
1600
- const container = document.createElement("div");
1601
- container.style.cssText = "display:flex;flex-direction:column;width:640px;height:480px";
1602
- await using screen = await render(
1603
- <OfficeFilePreview src={src} name="shared.xlsx" kind="xlsx" />,
1604
- { container },
1605
- );
1606
- await vi.waitFor(
1607
- () =>
1608
- expect(screen.container.querySelector('[role="gridcell"]')?.textContent).toHaveLength(
1609
- 4096,
1610
- ),
1611
- { timeout: 30_000 },
1612
- );
1613
- expect(screen.container.textContent).toContain("Preview limited");
1614
- const canvas = screen.container.querySelector("canvas")!;
1615
- await vi.waitFor(() => expect(canvas.width).toBeGreaterThan(0));
1616
- const scroll = screen.container.querySelector<HTMLElement>('[role="grid"]')!;
1617
- await act(() => {
1618
- scroll.scrollTop = 200;
1619
- scroll.scrollLeft = 200;
1620
- });
1621
- await vi.waitFor(() => expect(scroll.scrollTop).toBe(200));
1622
- expect(canvas.getBoundingClientRect().top).toBeCloseTo(scroll.getBoundingClientRect().top, 0);
1623
- } finally {
1624
- URL.revokeObjectURL(src);
1625
- }
1584
},
1585
);
1586
@@ -1841,7 +1799,7 @@ it("keeps spreadsheet dates on their calendar day west of UTC", async () => {
1799
}
1800
});
1801
1844
-it.each([60, 100])("renders all %i pages of a table-heavy Word report", async (pages) => {
1802
+it.each([60, 100])("prepares all %i pages of a table-heavy Word report", async (pages) => {
1803
const { default: JSZip } = await import("jszip");
1804
const archive = new JSZip();
1805
const paragraph = (text: string) =>
@@ -1869,16 +1827,12 @@ it.each([60, 100])("renders all %i pages of a table-heavy Word report", async (p
1827
sizeBytes={file.size}
1828
/>,
1829
);
1872
- await vi.waitFor(() => expect(screen.container.textContent).toMatch(/\d+ pages/), {
1873
- timeout: 30_000,
1830
+ // The first Office preview in the file loads the lazy viewer chain and the preparation worker.
1831
+ await vi.waitFor(() => expect(screen.container.textContent).toContain("page " + pages), {
1832
+ timeout: 10_000,
1833
});
1834
expect(screen.container.textContent).not.toContain("Preview limited");
1835
expect(screen.container.querySelector('[role="alert"]')).toBeNull();
1877
- const scroll = screen.container.querySelector<HTMLElement>("[data-office-pages]")!;
1878
- await act(() => scroll.scrollTo({ top: scroll.scrollHeight }));
1879
- await vi.waitFor(() => expect(screen.container.textContent).toContain("page " + pages), {
1880
- timeout: 30_000,
1881
- });
1836
});
1837
1838
describe("standalone Mermaid previews", () => {
@@ -2012,6 +1966,13 @@ describe("attachment HTML preview recovery", () => {
1966
await act(async () => button!.click());
1967
};
1968
const alert = (screen: Screen) => screen.container.querySelector('[role="alert"]');
1969
+ // The app's connection runtime keeps polling environment discovery through the same global
1970
+ // fetch while these tests run, so only the attachment's own requests are counted.
1971
+ const attachmentFetches = () =>
1972
+ vi
1973
+ .mocked(fetch)
1974
+ .mock.calls.map(([url]) => url)
1975
+ .filter((url) => typeof url === "string" && url.startsWith("data:text/html"));
1976
1977
it("keeps a renewed URL for subsequent rendered and source views", async () => {
1978
setup();
@@ -2028,7 +1989,7 @@ describe("attachment HTML preview recovery", () => {
1989
await act(async () => {
1990
await import("./ReadOnlySourcePreview");
1991
});
2031
- expect(fetch).toHaveBeenCalledExactlyOnceWith(renewedUrl, expect.any(Object));
1992
+ expect(attachmentFetches()).toEqual([renewedUrl]);
1993
await vi.waitFor(() =>
1994
expect(screen.container.querySelector("pre")?.textContent).toBe("<p>Captured HTML</p>"),
1995
);
@@ -2037,7 +1998,7 @@ describe("attachment HTML preview recovery", () => {
1998
expect(screen.container.querySelector("iframe")?.getAttribute("src")).toBe(renewedUrl);
1999
await toggleMode(screen, "Show HTML source");
2000
expect(refresh).toHaveBeenCalledTimes(2);
2040
- expect(vi.mocked(fetch).mock.calls.map(([url]) => url)).toEqual([renewedUrl, renewedUrl]);
2001
+ expect(attachmentFetches()).toEqual([renewedUrl, renewedUrl]);
2002
});
2003
2004
it("does not fetch or mark an expired URL fresh when reauthorization is unavailable", async () => {
@@ -2052,13 +2013,13 @@ describe("attachment HTML preview recovery", () => {
2013
now = 61 * 60_000;
2014
refresh.mockResolvedValue(null);
2015
await toggleMode(screen, "Show HTML source");
2055
- expect(fetch).not.toHaveBeenCalled();
2016
+ expect(attachmentFetches()).toEqual([]);
2017
expect(alert(screen)?.textContent).toContain("Reconnect to the environment and try again.");
2018
2019
await toggleMode(screen, "Show rendered page");
2020
await toggleMode(screen, "Show HTML source");
2021
expect(refresh).toHaveBeenCalledTimes(3);
2061
- expect(fetch).not.toHaveBeenCalled();
2022
+ expect(attachmentFetches()).toEqual([]);
2023
});
2024
2025
it("can return to rendered HTML after local source decoding fails", async () => {
@@ -2360,112 +2321,6 @@ it("toggles a Mermaid attachment between diagram and source through the lazy pre
2321
expect(screen.container.querySelector('[role="alert"]')).toBeNull();
2322
});
2323
2363
-it("navigates, searches, zooms, and selects mixed-height PDF pages", async () => {
2364
- const objects = [
2365
- "<< /Type /Catalog /Pages 2 0 R >>",
2366
- "<< /Type /Pages /Count 3 /Kids [3 0 R 5 0 R 7 0 R] >>",
2367
- ];
2368
- for (const [index, title] of [
2369
- "Quarterly outlook",
2370
- "Delivery milestones",
2371
- "Budget and risks",
2372
- ].entries()) {
2373
- 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`;
2374
- objects.push(
2375
- `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 ${index === 0 ? 140 : 792}] /Rotate ${index === 2 ? 90 : 0} /Resources << /Font << /F1 9 0 R /F2 10 0 R >> /ExtGState << /GS1 << /TR << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 2 >> >> >> >> /Contents ${4 + index * 2} 0 R >>`,
2376
- `<< /Length ${text.length} >>\nstream\n${text}\nendstream`,
2377
- );
2378
- }
2379
- objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");
2380
- objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>");
2381
- let source = "%PDF-1.4\n";
2382
- const offsets = [0];
2383
- for (const [index, object] of objects.entries()) {
2384
- offsets.push(source.length);
2385
- source += `${index + 1} 0 obj\n${object}\nendobj\n`;
2386
- }
2387
- const xref = source.length;
2388
- source += `xref\n0 11\n0000000000 65535 f \n${offsets
2389
- .slice(1)
2390
- .map((offset) => `${String(offset).padStart(10, "0")} 00000 n \n`)
2391
- .join("")}trailer\n<< /Size 11 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`;
2392
- const file = new Blob([source], { type: "application/pdf" });
2393
- const { default: PdfViewer } = await import("./PdfViewer");
2394
- const url = URL.createObjectURL(file);
2395
- try {
2396
- await using screen = await render(
2397
- <div style={{ display: "flex", height: 600, width: 320 }}>
2398
- <PdfViewer src={url} title="Planning PDF" />
2399
- </div>,
2400
- );
2401
- await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 3 pages"), {
2402
- timeout: 15_000,
2403
- });
2404
- const region = screen.container.querySelector<HTMLElement>('[role="region"]')!;
2405
- await vi.waitFor(() => {
2406
- expect(region.scrollWidth).toBe(region.clientWidth);
2407
- expect(region.querySelector("canvas")!.getBoundingClientRect().width).toBeLessThan(
2408
- region.clientWidth,
2409
- );
2410
- expect(screen.container.textContent).toContain("Fit width");
2411
- });
2412
- await act(() => {
2413
- (screen.container.firstElementChild as HTMLElement).style.width = "500px";
2414
- });
2415
- await vi.waitFor(() =>
2416
- expect(region.querySelector("canvas")!.getBoundingClientRect().width).toBe(468),
2417
- );
2418
- await screen.getByRole("button", { name: "Next page", exact: true }).click();
2419
- await vi.waitFor(() => expect(screen.container.textContent).toContain("2 / 3 pages"));
2420
- await screen.getByRole("button", { name: "Previous page", exact: true }).click();
2421
- await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 3 pages"));
2422
- await screen.getByRole("button", { name: "Zoom in", exact: true }).click();
2423
- await vi.waitFor(() => expect(region.scrollWidth).toBeGreaterThan(region.clientWidth));
2424
- await screen.getByRole("button", { name: "Fit width", exact: true }).click();
2425
- await vi.waitFor(() => expect(region.scrollWidth).toBe(region.clientWidth));
2426
- await screen.getByRole("searchbox", { name: "Find in PDF" }).fill("Quarterly outlook");
2427
- await vi.waitFor(() => {
2428
- expect(screen.container.querySelector('[role="status"]')?.textContent).toBe("1/1");
2429
- expect(
2430
- Array.from(region.querySelectorAll(".pdf-find-match")).map((span) => span.textContent),
2431
- ).toEqual(["Quarter", "ly outlook"]);
2432
- });
2433
- await screen.getByRole("searchbox", { name: "Find in PDF" }).fill("Budget");
2434
- await vi.waitFor(() => expect(screen.container.textContent).toContain("3 / 3 pages"));
2435
- await screen.getByRole("button", { name: "Zoom in", exact: true }).click();
2436
- await vi.waitFor(() => expect(screen.container.textContent).toContain("3 / 3 pages"));
2437
- await vi.waitFor(() => {
2438
- const span = Array.from(screen.container.querySelectorAll("[data-pdf-text-layer] span")).find(
2439
- (node) => node.textContent === "Budget and risks",
2440
- );
2441
- expect(span).toBeDefined();
2442
- const textBounds = span!.getBoundingClientRect();
2443
- const pageBounds = span!.parentElement!.getBoundingClientRect();
2444
- expect(textBounds.width).toBeGreaterThan(0);
2445
- expect(textBounds.height).toBeGreaterThan(0);
2446
- expect(textBounds.left).toBeGreaterThanOrEqual(pageBounds.left - 1);
2447
- expect(textBounds.top).toBeGreaterThanOrEqual(pageBounds.top - 1);
2448
- expect(textBounds.right).toBeLessThanOrEqual(pageBounds.right + 1);
2449
- expect(textBounds.bottom).toBeLessThanOrEqual(pageBounds.bottom + 1);
2450
- const range = document.createRange();
2451
- range.selectNodeContents(span!);
2452
- const selection = window.getSelection()!;
2453
- selection.removeAllRanges();
2454
- selection.addRange(range);
2455
- expect(selection.toString()).toBe("Budget and risks");
2456
- expect(getComputedStyle(span!).userSelect).toBe("text");
2457
- selection.removeAllRanges();
2458
- });
2459
- await screen.getByRole("button", { name: "Fit width", exact: true }).click();
2460
- await vi.waitFor(() => expect(screen.container.textContent).toContain("3 / 3 pages"));
2461
- await screen.getByRole("searchbox", { name: "Find in PDF" }).fill(" ");
2462
- await vi.waitFor(() =>
2463
- expect(screen.container.querySelector('[role="status"]')?.textContent).toBe("0/0"),
2464
- );
2465
- } finally {
2466
- URL.revokeObjectURL(url);
2467
- }
2468
-});
2324
it("mounts a bounded set of saved notebook outputs as the reader scrolls", async () => {
2325
const notebook = {
2326
nbformat: 4,
@@ -2491,8 +2346,10 @@ it("mounts a bounded set of saved notebook outputs as the reader scrolls", async
2346
/>
2347
</div>,
2348
);
2494
- await vi.waitFor(() =>
2495
- expect(screen.container.querySelectorAll("iframe").length).toBeGreaterThan(0),
2349
+ // The first outputs wait on the lazy notebook viewer and the conversion worker, not on a frame.
2350
+ await vi.waitFor(
2351
+ () => expect(screen.container.querySelectorAll("iframe").length).toBeGreaterThan(0),
2352
+ { timeout: 10_000 },
2353
);
2354
expect(screen.container.querySelectorAll("iframe").length).toBeLessThanOrEqual(16);
2355
const first = screen.container.querySelector("iframe")!;
@@ -2646,18 +2503,22 @@ it.each(["rtf", "epub", "ods"] as const)(
2503
/>
2504
</div>,
2505
);
2649
- await vi.waitFor(() => {
2650
- if (kind === "ods") {
2651
- expect(screen.container.textContent).toContain("North");
2652
- expect(screen.container.textContent).toContain("150");
2653
- expect(screen.container.textContent).not.toContain("private note");
2654
- expect(screen.container.textContent).toContain("1 rows · 2 columns");
2655
- expect(screen.container.textContent).not.toContain("Limited to 500");
2656
- } else {
2657
- const frame = screen.container.querySelector("iframe");
2658
- expect(frame?.srcdoc).toContain(kind === "rtf" ? "10–20" : "first<br>second<br>third");
2659
- }
2660
- });
2506
+ await vi.waitFor(
2507
+ () => {
2508
+ if (kind === "ods") {
2509
+ expect(screen.container.textContent).toContain("North");
2510
+ expect(screen.container.textContent).toContain("150");
2511
+ expect(screen.container.textContent).not.toContain("private note");
2512
+ expect(screen.container.textContent).toContain("1 rows · 2 columns");
2513
+ expect(screen.container.textContent).not.toContain("Limited to 500");
2514
+ } else {
2515
+ const frame = screen.container.querySelector("iframe");
2516
+ expect(frame?.srcdoc).toContain(kind === "rtf" ? "10–20" : "first<br>second<br>third");
2517
+ }
2518
+ // The viewer runs its own conversion worker behind lazy chunks.
2519
+ },
2520
+ { timeout: 10_000 },
2521
+ );
2522
expect(screen.container.querySelector('[role="alert"]')).toBeNull();
2523
},
2524
);