fix(preview): bound automation waits and screenshot captures (#4685)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 authored and GitHub committed 2026-09-04 19:41:58 -07:00
1 parent 7f8cf30ca4
commit de1b798c6e
5 files changed
+383 -14

No files matched your search

+143 -2
View File
@@ -2060,10 +2060,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({
@@ -2397,6 +2417,127 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("stops capture retries when the tab swaps during the retry delay", () =>
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);
capturePage.mockRejectedValueOnce(new Error("UnknownVizError"));
const fiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
Effect.forkChild({ startImmediately: true }),
);
// Let the rejection schedule its retry before replacing the guest.
yield* TestClock.adjust(60);
expect(capturePage).toHaveBeenCalledTimes(1);
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);
expect(writeFile).not.toHaveBeenCalled();
}),
),
);
effectIt.effect("discards a screenshot that resolves after its guest is replaced", () =>
withManager((manager) =>
Effect.gen(function* () {
const image = {
toPNG: () => Buffer.from("stale-png"),
toJPEG: () => Buffer.from("stale-jpeg"),
getSize: () => ({ width: 100, height: 80 }),
};
const pending = Promise.withResolvers<typeof image>();
const capturePage = vi.fn(() => pending.promise);
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 42));
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
const fiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
Effect.forkChild({ startImmediately: true }),
);
yield* TestClock.adjust(0);
expect(capturePage).toHaveBeenCalledOnce();
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 43));
yield* manager.registerWebview("tab_1", 43);
pending.resolve(image);
const exit = yield* Fiber.join(fiber);
expect(Exit.isFailure(exit)).toBe(true);
expect(capturePage).toHaveBeenCalledOnce();
expect(writeFile).not.toHaveBeenCalled();
}),
),
);
effectIt.effect("releases snapshot control when every capture attempt stalls", () =>
withManager((manager) =>
Effect.gen(function* () {
const capturePage = vi.fn(() => new Promise<TestCapturedPreviewImage>(() => {}));
const wc = makeTestPreviewWebContents(capturePage);
Object.assign(wc, { isDevToolsOpened: () => false });
Object.assign(wc.debugger, {
sendCommand: vi.fn(async (method: string, params?: Record<string, unknown>) => {
if (method === "Runtime.evaluate") {
return {
result: {
value:
params?.["expression"] === "42"
? 42
: {
url: "https://example.com",
title: "Example",
loading: false,
visibleText: "Example",
interactiveElements: [],
},
},
};
}
return method === "Accessibility.getFullAXTree" ? { nodes: [] } : undefined;
}),
});
fromId.mockReturnValue(wc);
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
const snapshot = yield* Effect.exit(manager.automationSnapshot("tab_1")).pipe(
Effect.forkChild({ startImmediately: true }),
);
yield* TestClock.adjust(100);
expect(capturePage).toHaveBeenCalledOnce();
const evaluate = yield* manager
.automationEvaluate("tab_1", { expression: "42" })
.pipe(Effect.forkChild({ startImmediately: true }));
expect(evaluate.pollUnsafe()).toBeUndefined();
yield* TestClock.adjust(4_000);
const exit = yield* Fiber.join(snapshot);
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({
_tag: "PreviewOperationError",
operation: "automationSnapshot.capturePage",
tabId: "tab_1",
webContentsId: 42,
cause: { _tag: "TimeoutError" },
});
expect(yield* Fiber.join(evaluate)).toBe(42);
}),
),
);
effectIt.effect("grants each concurrent preview recording its own tab frame", () =>
withManager((manager) =>
Effect.gen(function* () {
+50 -4
View File
@@ -48,6 +48,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";
@@ -113,6 +114,13 @@ const MAX_SCREENSHOT_WIDTH = 1280;
const RECORDING_ARM_GRACE_MS = 10_000;
const PICTURE_IN_PICTURE_FRAME_INTERVAL_MS = Math.ceil(1_000 / 12);
const PICTURE_IN_PICTURE_JPEG_QUALITY = 80;
/**
* Cold guests can reject capturePage with UnknownVizError or never settle it.
* Bound each attempt so snapshots release control even when Chromium stalls.
*/
const CAPTURE_PAGE_RETRY_ATTEMPTS = 3;
const CAPTURE_PAGE_RETRY_DELAY_MS = 120;
const CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS = 1_000;
const PICTURE_IN_PICTURE_INITIAL_WIDTH = 480;
const PICTURE_IN_PICTURE_INITIAL_HEIGHT = 320;
const PICTURE_IN_PICTURE_MIN_WIDTH = 240;
@@ -639,6 +647,42 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
try: evaluate,
catch: (cause) => new PreviewOperationError({ ...errorContext, cause }),
});
const capturePageWithRetry = Effect.fn("PreviewManager.capturePageWithRetry")(function* (
errorContext: PreviewOperationContext,
tabId: string,
wc: Electron.WebContents,
) {
const requireCurrentGuest = Effect.gen(function* () {
const tabs = yield* SynchronizedRef.get(tabsRef);
if (wc.isDestroyed() || tabs.get(tabId)?.webContentsId !== wc.id) {
return yield* new PreviewWebContentsNotFoundError({ tabId, webContentsId: wc.id });
}
});
const capture = Effect.gen(function* () {
// Check after the retry delay, and again before accepting its result.
yield* requireCurrentGuest;
const image = yield* Effect.tryPromise({
// An abort-signal parameter makes a stalled promise interruptible.
try: (_signal) => wc.capturePage(),
catch: (cause) => new PreviewOperationError({ ...errorContext, cause }),
}).pipe(
Effect.timeout(CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS),
Effect.catchTags({
TimeoutError: (cause) =>
Effect.fail(new PreviewOperationError({ ...errorContext, cause })),
}),
);
yield* requireCurrentGuest;
return image;
});
return yield* capture.pipe(
Effect.retry({
times: CAPTURE_PAGE_RETRY_ATTEMPTS - 1,
schedule: Schedule.spaced(CAPTURE_PAGE_RETRY_DELAY_MS),
while: isPreviewOperationError,
}),
);
});
const currentIso = DateTime.now.pipe(Effect.map(DateTime.formatIso));
const currentMillis = Clock.currentTimeMillis;
const encodeJson = (errorContext: PreviewOperationContext, value: unknown) =>
@@ -2648,13 +2692,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)}`;
@@ -3513,13 +3558,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),
@@ -76,6 +76,7 @@ import {
resolvePreviewAutomationOpenTab,
resolvePreviewAutomationTarget,
} from "./previewAutomationTarget";
import { resolveHostWaitBudgetMs, waitForHostReadiness } from "./previewAutomationHostBudget";
import { isPreviewViewportReady } from "./previewViewportReadiness";
import { shouldRollbackPreviewViewport } from "./previewViewportRollback";
@@ -95,25 +96,26 @@ const waitForDesktopOverlay = async (
tabId: string,
runtimeTabId: string,
operation: PreviewAutomationRequest["operation"],
timeoutMs: number,
deadlineMs: number,
): Promise<void> => {
const deadline = Date.now() + timeoutMs;
while (Date.now() <= deadline) {
const waitBudgetMs = Math.max(0, deadlineMs - Date.now());
const ready = await waitForHostReadiness(deadlineMs, async () => {
const state = assertPreviewRuntimeCurrent(threadRef, tabId, runtimeTabId, {
operation,
requestId,
});
if (state.desktopByTabId[tabId] && previewBridge && isPreviewWebviewRendering(runtimeTabId)) {
const status = await previewBridge.automation.status(runtimeTabId);
if (status.available) return;
return status.available;
}
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
}
return false;
});
if (ready) return;
throw new PreviewAutomationOverlayTimeoutError({
requestId,
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
timeoutMs,
timeoutMs: waitBudgetMs,
});
};
@@ -317,6 +319,8 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
const handleRequest = useCallback(
async (request: PreviewAutomationRequest): Promise<unknown> => {
// Session sync and tab creation consume the same budget as overlay registration.
const hostDeadlineMs = Date.now() + resolveHostWaitBudgetMs(request.timeoutMs);
const threadRef: ScopedThreadRef = {
environmentId,
threadId: request.threadId,
@@ -378,7 +382,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
readyTabId,
runtimeTabId,
request.operation,
request.timeoutMs,
hostDeadlineMs,
);
return {
bridge,
@@ -0,0 +1,136 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import {
PREVIEW_HOST_RESPONSE_MARGIN_MS,
resolveHostWaitBudgetMs,
waitForHostReadiness,
} from "./previewAutomationHostBudget";
describe("resolveHostWaitBudgetMs", () => {
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("returns a non-negative budget for invalid input", () => {
for (const invalid of [0, -5, Number.NaN, Number.POSITIVE_INFINITY]) {
expect(resolveHostWaitBudgetMs(invalid)).toBeGreaterThanOrEqual(0);
}
});
});
describe("waitForHostReadiness", () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(0);
});
afterEach(() => {
vi.useRealTimers();
});
it.each([1, 10, 100, 250, 1_000, 15_000])(
"stops unavailable-overlay polling before a %ims broker timeout",
async (requestTimeoutMs) => {
const deadlineMs = Date.now() + resolveHostWaitBudgetMs(requestTimeoutMs);
let finishedAt: number | undefined;
const result = waitForHostReadiness(deadlineMs, async () => false).then((ready) => {
finishedAt = Date.now();
return ready;
});
await vi.advanceTimersByTimeAsync(requestTimeoutMs);
expect(await result).toBe(false);
expect(finishedAt).toBeLessThan(requestTimeoutMs);
expect(vi.getTimerCount()).toBe(0);
},
);
it("includes session setup in the deadline instead of starting a fresh wait budget", async () => {
const deadlineMs = Date.now() + resolveHostWaitBudgetMs(15_000);
await vi.advanceTimersByTimeAsync(2_000);
let finished = false;
const result = waitForHostReadiness(deadlineMs, async () => false).then((ready) => {
finished = true;
return ready;
});
await vi.advanceTimersByTimeAsync(11_499);
expect(finished).toBe(false);
await vi.advanceTimersByTimeAsync(1);
expect(await result).toBe(false);
expect(Date.now()).toBe(deadlineMs);
expect(vi.getTimerCount()).toBe(0);
});
it("skips readiness probes when setup has already exhausted the deadline", async () => {
const deadlineMs = Date.now() + resolveHostWaitBudgetMs(100);
await vi.advanceTimersByTimeAsync(100);
const isReady = vi.fn(async () => false);
expect(await waitForHostReadiness(deadlineMs, isReady)).toBe(false);
expect(isReady).not.toHaveBeenCalled();
expect(vi.getTimerCount()).toBe(0);
});
it("returns as soon as the overlay is ready and clears its timeout", async () => {
const isReady = vi.fn().mockResolvedValueOnce(false).mockResolvedValueOnce(true);
const result = waitForHostReadiness(800, isReady);
await vi.advanceTimersByTimeAsync(50);
expect(await result).toBe(true);
expect(isReady).toHaveBeenCalledTimes(2);
expect(vi.getTimerCount()).toBe(0);
});
it.each([false, true])(
"keeps a probe result of %s that wins the deadline race",
async (ready) => {
const isReady = vi.fn(
() => new Promise<boolean>((resolve) => setTimeout(() => resolve(ready), 80)),
);
const result = waitForHostReadiness(80, isReady);
await vi.advanceTimersByTimeAsync(80);
expect(await result).toBe(ready);
expect(isReady).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
},
);
it("bounds a stalled status probe and ignores a late ready result", async () => {
let completeProbe!: (ready: boolean) => void;
const isReady = vi.fn(
() =>
new Promise<boolean>((resolve) => {
completeProbe = resolve;
}),
);
const result = waitForHostReadiness(80, isReady);
await vi.advanceTimersByTimeAsync(80);
expect(await result).toBe(false);
expect(vi.getTimerCount()).toBe(0);
completeProbe(true);
await vi.runAllTimersAsync();
expect(isReady).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
});
it("preserves probe failures and clears the pending timeout", async () => {
const error = new Error("Preview target was replaced");
const isReady = vi.fn().mockRejectedValue(error);
await expect(waitForHostReadiness(800, isReady)).rejects.toBe(error);
expect(vi.getTimerCount()).toBe(0);
});
});
@@ -0,0 +1,42 @@
/** Allow time to deliver an overlay failure before the broker times out. */
export const PREVIEW_HOST_RESPONSE_MARGIN_MS = 1_500;
const HOST_RESPONSE_MARGIN_FRACTION = 0.2;
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);
}
/** Both readiness probes and polling delays share the request's host deadline. */
export async function waitForHostReadiness(
deadlineMs: number,
isReady: () => Promise<boolean>,
): Promise<boolean> {
while (Date.now() < deadlineMs) {
let timeout: ReturnType<typeof setTimeout> | undefined;
let ready: boolean | null;
try {
ready = await Promise.race([
isReady(),
new Promise<null>((resolve) => {
timeout = setTimeout(() => resolve(null), Math.max(0, deadlineMs - Date.now()));
}),
]);
} finally {
clearTimeout(timeout);
}
if (ready) return true;
if (ready === null || Date.now() >= deadlineMs) return false;
await new Promise<void>((resolve) =>
setTimeout(resolve, Math.min(50, deadlineMs - Date.now())),
);
}
return false;
}