Compare commits

...
Author SHA1 Message Date
Julius MarmingeandClaude Fable 5 57ae612f0e Clamp host wait below every broker budget and pin capture retries to the guest
- Reserve a proportional margin for short request budgets so the host wait
  never exceeds the broker deadline it is meant to beat
- Stop capture retries once the tab points at a different web contents

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-28 00:06:30 +02:00
Julius MarmingeandClaude Fable 5 afdc17c415 Make preview automation fail with the real cause, not a timeout
Host-side waits used the broker's own request budget, so an unavailable
overlay always lost the race to the broker deadline and agents saw an
opaque timeout instead of the overlay error. Reserve a response margin so
the host reports first.

One-shot capturePage calls also failed outright on the transient
UnknownVizError Chromium raises while a hidden guest warms its first
compositor frame; background frame capture already tolerated it. Retry
snapshot and screenshot captures the same way.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-27 23:56:01 +02:00
5 changed files with 166 additions and 8 deletions

No files matched your search

+52 -2
View File
@@ -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({
@@ -766,6 +786,36 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("stops capture retries when the tab swaps to another guest", () =>
withManager((manager) =>
Effect.gen(function* () {
const capturePage = vi.fn(async () => ({
toPNG: () => Buffer.from("png"),
toJPEG: () => Buffer.from("jpeg"),
getSize: () => ({ width: 100, height: 80 }),
}));
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 42));
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
// Fail persistently, then swap the tab onto a different web contents:
// retrying against the detached guest would capture the wrong page.
capturePage.mockClear();
capturePage.mockRejectedValue(new Error("UnknownVizError"));
const fiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
Effect.forkChild({ startImmediately: true }),
);
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 43));
yield* manager.registerWebview("tab_1", 43);
yield* TestClock.adjust(1_000);
const exit = yield* Fiber.join(fiber);
expect(Exit.isFailure(exit)).toBe(true);
expect(capturePage).toHaveBeenCalledTimes(1);
}),
),
);
effectIt.effect("captures hidden preview recordings independently for concurrent tabs", () =>
withManager((manager) =>
Effect.gen(function* () {
+41 -4
View File
@@ -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,32 @@ 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.
*
* Retries stop as soon as the tab no longer points at this guest, so a
* webview swap during the retry window surfaces the original failure instead
* of capturing from a detached web contents.
*/
const capturePageWithRetry = (
errorContext: PreviewOperationContext,
tabId: string,
wc: Electron.WebContents,
) => {
const guestIsCurrent = Effect.gen(function* () {
if (wc.isDestroyed()) return false;
const tabs = yield* SynchronizedRef.get(tabsRef);
return tabs.get(tabId)?.webContentsId === wc.id;
});
return attemptPromise(errorContext, () => wc.capturePage()).pipe(
Effect.retry({
times: CAPTURE_PAGE_RETRY_ATTEMPTS - 1,
schedule: Schedule.spaced(CAPTURE_PAGE_RETRY_DELAY_MS),
while: () => guestIsCurrent,
}),
);
};
const currentIso = DateTime.now.pipe(Effect.map(DateTime.formatIso));
const currentMillis = Clock.currentTimeMillis;
const encodeJson = (errorContext: PreviewOperationContext, value: unknown) =>
@@ -1947,13 +1982,14 @@ 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(),
tabId,
wc,
),
]);
const id = `browser-screenshot-${artifactSiteSlug(wc.getURL())}-${millis.toString(36)}`;
@@ -2621,13 +2657,14 @@ 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(),
tabId,
wc,
),
Ref.get(diagnosticsRef),
Ref.get(actionTimelineRef),
@@ -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<void> => {
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,
});
};
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vite-plus/test";
import {
PREVIEW_HOST_RESPONSE_MARGIN_MS,
resolveHostWaitBudgetMs,
} from "./previewAutomationHostBudget";
describe("resolveHostWaitBudgetMs", () => {
it("always expires before the broker deadline, at every request budget", () => {
// The whole point of the helper: the host must lose no race, at any scale.
for (const requestTimeoutMs of [1, 2, 10, 100, 249, 250, 999, 1_500, 3_000, 15_000, 60_000]) {
expect(resolveHostWaitBudgetMs(requestTimeoutMs)).toBeLessThan(requestTimeoutMs);
}
});
it("reserves the full response margin once the request budget allows it", () => {
expect(resolveHostWaitBudgetMs(15_000)).toBe(15_000 - PREVIEW_HOST_RESPONSE_MARGIN_MS);
expect(resolveHostWaitBudgetMs(60_000)).toBe(60_000 - PREVIEW_HOST_RESPONSE_MARGIN_MS);
});
it("keeps most of a short request budget instead of collapsing it", () => {
expect(resolveHostWaitBudgetMs(1_000)).toBe(800);
expect(resolveHostWaitBudgetMs(100)).toBe(80);
});
it("grows monotonically with the request budget", () => {
const budgets = [1, 10, 100, 1_000, 3_000, 15_000].map(resolveHostWaitBudgetMs);
for (let index = 1; index < budgets.length; index += 1) {
expect(budgets[index]!).toBeGreaterThanOrEqual(budgets[index - 1]!);
}
});
it("returns a non-negative budget for invalid input", () => {
for (const invalid of [0, -5, Number.NaN, Number.POSITIVE_INFINITY]) {
expect(resolveHostWaitBudgetMs(invalid)).toBeGreaterThanOrEqual(0);
}
});
});
@@ -0,0 +1,29 @@
/**
* 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;
/**
* Share of the request budget reserved when the request is too short for the
* full margin, so the host still expires first rather than being clamped past
* the broker's deadline.
*/
const HOST_RESPONSE_MARGIN_FRACTION = 0.2;
/**
* Budget a host-side wait so it always expires before the broker's deadline
* for the same request.
*/
export function resolveHostWaitBudgetMs(requestTimeoutMs: number): number {
if (!Number.isFinite(requestTimeoutMs) || requestTimeoutMs <= 0) {
return 0;
}
const reservedMs = Math.min(
PREVIEW_HOST_RESPONSE_MARGIN_MS,
Math.ceil(requestTimeoutMs * HOST_RESPONSE_MARGIN_FRACTION),
);
return Math.max(0, requestTimeoutMs - reservedMs);
}