diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index fa962f58ce..0c8fd50e80 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -749,10 +749,30 @@ describe("PreviewManager", () => { /\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/, ); + // Chromium reports UnknownVizError while a hidden guest warms its + // first compositor frame, so transient failures are retried. + capturePage.mockClear(); + capturePage.mockRejectedValueOnce(new Error("UnknownVizError")); + capturePage.mockRejectedValueOnce(new Error("UnknownVizError")); + const retriedFiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe( + Effect.forkChild({ startImmediately: true }), + ); + yield* TestClock.adjust(1_000); + const retriedExit = yield* Fiber.join(retriedFiber); + expect(Exit.isSuccess(retriedExit)).toBe(true); + expect(capturePage).toHaveBeenCalledTimes(3); + + // A persistent failure still surfaces once the retries are spent. + capturePage.mockClear(); const captureCause = new Error("capture failed"); - capturePage.mockRejectedValueOnce(captureCause); - const exit = yield* Effect.exit(manager.captureScreenshot("tab_1")); + capturePage.mockRejectedValue(captureCause); + const failingFiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe( + Effect.forkChild({ startImmediately: true }), + ); + yield* TestClock.adjust(1_000); + const exit = yield* Fiber.join(failingFiber); expect(Exit.isFailure(exit)).toBe(true); + expect(capturePage).toHaveBeenCalledTimes(3); if (Exit.isSuccess(exit)) return; const error = Option.getOrThrow(Cause.findErrorOption(exit.cause)); expect(error).toMatchObject({ diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 4321cf9dcf..9cc3d4fb2a 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -44,6 +44,7 @@ import * as Path from "effect/Path"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; +import * as Schedule from "effect/Schedule"; import * as Scope from "effect/Scope"; import * as SynchronizedRef from "effect/SynchronizedRef"; @@ -98,6 +99,14 @@ const MAX_EVALUATION_BYTES = 64_000; const MAX_VISIBLE_TEXT_LENGTH = 20_000; const MAX_INTERACTIVE_ELEMENTS = 200; const MAX_SCREENSHOT_WIDTH = 1280; +/** + * Chromium reports UnknownVizError while a hidden or freshly attached guest is + * warming its first compositor frame. Background frame capture already rides + * this out via its scheduled loop; one-shot captures need their own retry or a + * snapshot taken against a backgrounded preview fails outright. + */ +const CAPTURE_PAGE_RETRY_ATTEMPTS = 3; +const CAPTURE_PAGE_RETRY_DELAY_MS = 120; const RECORDING_FRAME_INTERVAL_MS = Math.ceil(1_000 / 12); const RECORDING_JPEG_QUALITY = 80; const PICTURE_IN_PICTURE_INITIAL_WIDTH = 480; @@ -510,6 +519,17 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function try: evaluate, catch: (cause) => new PreviewOperationError({ ...errorContext, cause }), }); + /** + * capturePage for one-shot captures (snapshots, screenshots), retrying the + * transient compositor warm-up failure instead of surfacing it to callers. + */ + const capturePageWithRetry = (errorContext: PreviewOperationContext, wc: Electron.WebContents) => + attemptPromise(errorContext, () => wc.capturePage()).pipe( + Effect.retry({ + times: CAPTURE_PAGE_RETRY_ATTEMPTS - 1, + schedule: Schedule.spaced(CAPTURE_PAGE_RETRY_DELAY_MS), + }), + ); const currentIso = DateTime.now.pipe(Effect.map(DateTime.formatIso)); const currentMillis = Clock.currentTimeMillis; const encodeJson = (errorContext: PreviewOperationContext, value: unknown) => @@ -1947,13 +1967,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const [createdAt, millis, image] = yield* Effect.all([ currentIso, currentMillis, - attemptPromise( + capturePageWithRetry( { operation: "captureScreenshot.capturePage", tabId, webContentsId: wc.id, }, - () => wc.capturePage(), + wc, ), ]); const id = `browser-screenshot-${artifactSiteSlug(wc.getURL())}-${millis.toString(36)}`; @@ -2621,13 +2641,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); const [accessibility, sourceImage, diagnostics, timelines] = yield* Effect.all([ send("Accessibility.getFullAXTree"), - attemptPromise( + capturePageWithRetry( { operation: "automationSnapshot.capturePage", tabId, webContentsId: wc.id, }, - () => wc.capturePage(), + wc, ), Ref.get(diagnosticsRef), Ref.get(actionTimelineRef), diff --git a/apps/web/src/components/preview/PreviewAutomationHosts.tsx b/apps/web/src/components/preview/PreviewAutomationHosts.tsx index 2a007fb4ce..0527017141 100644 --- a/apps/web/src/components/preview/PreviewAutomationHosts.tsx +++ b/apps/web/src/components/preview/PreviewAutomationHosts.tsx @@ -70,6 +70,7 @@ import { resolvePreviewAutomationOpenTab, resolvePreviewAutomationTarget, } from "./previewAutomationTarget"; +import { resolveHostWaitBudgetMs } from "./previewAutomationHostBudget"; import { isPreviewViewportReady } from "./previewViewportReadiness"; import { shouldRollbackPreviewViewport } from "./previewViewportRollback"; @@ -91,7 +92,10 @@ const waitForDesktopOverlay = async ( operation: PreviewAutomationRequest["operation"], timeoutMs: number, ): Promise => { - const deadline = Date.now() + timeoutMs; + // Expire before the broker does, so an unavailable overlay surfaces as + // PreviewAutomationOverlayTimeoutError rather than a bare broker timeout. + const waitBudgetMs = resolveHostWaitBudgetMs(timeoutMs); + const deadline = Date.now() + waitBudgetMs; while (Date.now() <= deadline) { const state = assertPreviewRuntimeCurrent(threadRef, tabId, runtimeTabId, { operation, @@ -107,7 +111,7 @@ const waitForDesktopOverlay = async ( requestId, environmentId: threadRef.environmentId, threadId: threadRef.threadId, - timeoutMs, + timeoutMs: waitBudgetMs, }); }; diff --git a/apps/web/src/components/preview/previewAutomationHostBudget.test.ts b/apps/web/src/components/preview/previewAutomationHostBudget.test.ts new file mode 100644 index 0000000000..bd68954157 --- /dev/null +++ b/apps/web/src/components/preview/previewAutomationHostBudget.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + PREVIEW_HOST_RESPONSE_MARGIN_MS, + resolveHostWaitBudgetMs, +} from "./previewAutomationHostBudget"; + +describe("resolveHostWaitBudgetMs", () => { + it("expires before the broker deadline so the host failure wins the race", () => { + const requestTimeoutMs = 15_000; + const budget = resolveHostWaitBudgetMs(requestTimeoutMs); + + expect(budget).toBeLessThan(requestTimeoutMs); + expect(requestTimeoutMs - budget).toBe(PREVIEW_HOST_RESPONSE_MARGIN_MS); + }); + + it("keeps a usable wait for short request budgets", () => { + expect(resolveHostWaitBudgetMs(1_000)).toBeGreaterThan(0); + expect(resolveHostWaitBudgetMs(1_000)).toBeLessThan(1_000); + expect(resolveHostWaitBudgetMs(10)).toBeGreaterThan(0); + expect(resolveHostWaitBudgetMs(10)).toBeLessThan(PREVIEW_HOST_RESPONSE_MARGIN_MS); + }); + + it("falls back to a positive budget for invalid input", () => { + expect(resolveHostWaitBudgetMs(0)).toBeGreaterThan(0); + expect(resolveHostWaitBudgetMs(-5)).toBeGreaterThan(0); + expect(resolveHostWaitBudgetMs(Number.NaN)).toBeGreaterThan(0); + }); +}); diff --git a/apps/web/src/components/preview/previewAutomationHostBudget.ts b/apps/web/src/components/preview/previewAutomationHostBudget.ts new file mode 100644 index 0000000000..d5e8e301d2 --- /dev/null +++ b/apps/web/src/components/preview/previewAutomationHostBudget.ts @@ -0,0 +1,21 @@ +/** + * Reserve for delivering the host's response back to the broker once a wait + * gives up. Without it a host wait that runs the full request budget always + * loses the race to the broker's own deadline, so the agent sees an opaque + * "timed out" instead of the specific failure the host was about to report. + */ +export const PREVIEW_HOST_RESPONSE_MARGIN_MS = 1_500; + +/** Smallest useful wait; below this a slow first poll would fail instantly. */ +const MIN_HOST_WAIT_MS = 250; + +/** + * Budget a host-side wait so it expires before the broker's deadline for the + * same request. + */ +export function resolveHostWaitBudgetMs(requestTimeoutMs: number): number { + if (!Number.isFinite(requestTimeoutMs) || requestTimeoutMs <= 0) { + return MIN_HOST_WAIT_MS; + } + return Math.max(MIN_HOST_WAIT_MS, requestTimeoutMs - PREVIEW_HOST_RESPONSE_MARGIN_MS); +}