diff --git a/apps/server/src/preview/ServerBrowserPage.test.ts b/apps/server/src/preview/ServerBrowserPage.test.ts index 79ccc4089aeee..69aab57ecbfd0 100644 --- a/apps/server/src/preview/ServerBrowserPage.test.ts +++ b/apps/server/src/preview/ServerBrowserPage.test.ts @@ -46,6 +46,13 @@ describe("snapshot deadline diagnostics", () => { const stalledSnapshot = async (options: { readonly stalled?: "metrics"; readonly page?: Partial>; + readonly large?: boolean | Promise; + readonly sizeReadIn?: (contextId: number | undefined) => void; + readonly screenshot?: () => Promise<{ readonly data: string }>; + /** Runs once everything the snapshot started without waiting has been asked for. */ + readonly started?: () => void | Promise; + /** Runs after the clock has advanced, while it is still faked. */ + readonly advanced?: () => Promise; readonly advanceMs: number; }) => { vi.useFakeTimers(); @@ -67,9 +74,16 @@ describe("snapshot deadline diagnostics", () => { ...options.page, } as unknown as Page; const cdp = { - send: async (method: string) => { + send: async ( + method: string, + params?: { readonly contextId?: number; readonly expression?: string }, + ) => { if (options.stalled === "metrics") return never(); - if (method === "Page.captureScreenshot") return { data: "" }; + if (method === "Page.captureScreenshot") return options.screenshot?.() ?? { data: "" }; + if (params?.expression === ServerBrowserPage.LARGE_PAGE_SCRIPT) { + options.sizeReadIn?.(params.contextId); + return { result: { value: (await options.large) ?? false } }; + } if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } }; if (method === "Page.createIsolatedWorld") return { executionContextId: 1 }; if (method === "Runtime.evaluate") return { result: { value: [] } }; @@ -84,7 +98,12 @@ describe("snapshot deadline diagnostics", () => { networkEntries: [], actionTimeline: [], }).catch((error: unknown) => error); + if (options.started) { + await vi.advanceTimersByTimeAsync(0); + await options.started(); + } await vi.advanceTimersByTimeAsync(options.advanceMs); + await options.advanced?.(); return await captured; } finally { vi.useRealTimers(); @@ -113,6 +132,53 @@ describe("snapshot deadline diagnostics", () => { }); }); + it("finishes a large page's screenshot before building its tree", async () => { + const png = Buffer.concat([Buffer.alloc(16), Buffer.from([0, 0, 5, 0, 0, 0, 3, 32])]); + const screenshot = Promise.withResolvers<{ readonly data: string }>(); + const ariaSnapshot = vi.fn(async () => "- table"); + const sizeReadIn = vi.fn(); + const captured = await stalledSnapshot({ + large: true, + sizeReadIn, + page: { ariaSnapshot }, + screenshot: () => screenshot.promise, + // Building the tree holds the page's main thread, so a screenshot still pending would starve. + started: async () => { + await vi.advanceTimersByTimeAsync(2_500); + expect(ariaSnapshot).not.toHaveBeenCalled(); + screenshot.resolve({ data: png.toString("base64") }); + }, + advanceMs: 0, + }); + expect(captured).toMatchObject({ + accessibilityTree: "- table", + screenshot: { width: 1280, height: 800 }, + }); + // The isolated world, which page script cannot reach. + expect(sizeReadIn).toHaveBeenCalledWith(1); + // The 2.5 s the screenshot took leaves 7.5 s; 1 s of that is kept back for what follows the tree. + expect(ariaSnapshot).toHaveBeenCalledWith(expect.objectContaining({ timeout: 6_500 })); + }); + + it("starts no tree when the page's size is known only after the deadline", async () => { + const large = Promise.withResolvers(); + const ariaSnapshot = vi.fn(async () => ""); + const captured = await stalledSnapshot({ + large: large.promise, + page: { ariaSnapshot }, + advanceMs: 10_000, + advanced: async () => { + large.resolve(false); + await vi.advanceTimersByTimeAsync(0); + }, + }); + expect(captured).toMatchObject({ + detail: { timeoutMs: 10_000, pendingStages: ["page state"] }, + }); + // The deadline rejects either way; this is what the check before the tree adds. + expect(ariaSnapshot).not.toHaveBeenCalled(); + }); + it("omits a timed-out stage after it succeeds on retry", async () => { let attempts = 0; const timedOut = Object.assign(new Error("Timeout exceeded"), { name: "TimeoutError" }); diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index ac37b9914ef76..8a04ff37b326c 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -253,6 +253,23 @@ const withoutTreeDataPayloads = (tree: string) => // The broker waits 15s for the host; a snapshot, retry included, answers well before. const SNAPSHOT_TIMEOUT_MS = 10_000; const FRAME_ANSWER_MS = 1_000; +// Playwright builds the tree for every element and holds the page's main thread meanwhile, +// which a screenshot with a 3 s limit must not wait behind. A heuristic, chosen conservatively. +const LARGE_PAGE_ELEMENTS = 10_000; + +// Counts open shadow roots, which the tree includes, and stops at the limit. Child frames are +// not counted. +export const LARGE_PAGE_SCRIPT = `(() => { + let left = ${LARGE_PAGE_ELEMENTS}; + const exceeds = (root) => { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT); + for (let element = walker.nextNode(); element; element = walker.nextNode()) { + if (--left < 0 || (element.shadowRoot && exceeds(element.shadowRoot))) return true; + } + return false; + }; + return exceeds(document); +})()`; // Include password and CSS-masked text in open shadow roots, normalized like accessible text. const DOTTED_SCRIPT = `(() => { @@ -395,10 +412,11 @@ const openReaders = async (page: Page, cdp: CDPSession) => { throw cause; } }; - return { frames: owned, read }; + return { frames: owned, read, worlds: () => (contexts ??= open()) }; }; + const main = sessionReader(page.mainFrame(), cdp); const readers = [ - sessionReader(page.mainFrame(), cdp), + main, ...frames.flatMap((frame) => { const owner = owners.get(frame); if (owner) return owner === cdp ? [] : [sessionReader(frame, owner)]; @@ -408,6 +426,7 @@ const openReaders = async (page: Page, cdp: CDPSession) => { ]; return { readers, + mainWorld: async () => (await main.worlds())[0]!, read: async (before?: ReadonlyArray) => { const now = page.frames(); if (now.length !== frames.length || now.some((frame, i) => frame !== frames[i])) { @@ -691,8 +710,18 @@ const capture = async ( const state = refsFor(input.page); invalidateRefs(input.page); const generation = state.generation; - const { readers, read } = await track("frames", () => openReaders(input.page, input.cdp)); + const { readers, read, mainWorld } = await track("frames", () => + openReaders(input.page, input.cdp), + ); const before = await track("frames", () => read()); + // Tracked as page state: it reads the page's document. Its isolated world is the value reads'. + const large = track("page state", async () => + input.cdp.send("Runtime.evaluate", { + contextId: await mainWorld(), + expression: LARGE_PAGE_SCRIPT, + returnByValue: true, + }), + ).catch(constVoid); // Bracket the tree with value reads to detect changes; await tree completion before retrying failed captures. const pageAndScreenshot = Promise.all([ track( @@ -723,12 +752,22 @@ const capture = async ( ), ]); void pageAndScreenshot.catch(constVoid); + // A screenshot still pending when a large page's tree takes the main thread gets no frame + // before its own timeout, so on a large page, or one whose size went unread, it finishes + // first. The page state, asked for before the tree, is ahead of it on that thread either way. + const screenshotFirst = (await large)?.result?.value !== false; + if (screenshotFirst) await pageAndScreenshot; + // A late reply must not begin a tree after the snapshot has timed out or its refs were revoked. + if (Date.now() >= deadline) throw snapshotTimedOut(stages); + if (state.generation !== generation) throw pageChanged(); // Leaves time for the second read; a frame that never loads holds the tree until then. + // The screenshot's time is already spent when it went first, so less is kept back. + const reserveMs = screenshotFirst ? FRAME_ANSWER_MS : 2_000; const tree = await track("accessibility tree", () => input.page.ariaSnapshot({ mode: "ai", boxes: true, - timeout: Math.max(1, deadline - Date.now() - 2_000), + timeout: Math.max(1, deadline - Date.now() - reserveMs), }), ); const after = await track("frames", () => read(before));