Skip to content

Commit 076dcce

Browse files
Bound preview readiness and capture attempts to avoid stale or stuck automation
1 parent 724bf1d commit 076dcce

5 files changed

Lines changed: 260 additions & 66 deletions

File tree

‎apps/desktop/src/preview/Manager.test.ts‎

Lines changed: 96 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2344,7 +2344,7 @@ describe("PreviewManager", () => {
23442344
),
23452345
);
23462346

2347-
effectIt.effect("stops capture retries when the tab swaps to another guest", () =>
2347+
effectIt.effect("stops capture retries when the tab swaps during the retry delay", () =>
23482348
withManager((manager) =>
23492349
Effect.gen(function* () {
23502350
const capturePage = vi.fn(async () => ({
@@ -2356,20 +2356,111 @@ describe("PreviewManager", () => {
23562356
yield* manager.createTab("tab_1");
23572357
yield* manager.registerWebview("tab_1", 42);
23582358

2359-
// Fail persistently, then swap the tab onto a different web contents:
2360-
// retrying against the detached guest would capture the wrong page.
2361-
capturePage.mockClear();
2362-
capturePage.mockRejectedValue(new Error("UnknownVizError"));
2359+
capturePage.mockRejectedValueOnce(new Error("UnknownVizError"));
23632360
const fiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
23642361
Effect.forkChild({ startImmediately: true }),
23652362
);
2363+
// Let the rejection schedule its retry before replacing the guest.
2364+
yield* TestClock.adjust(60);
2365+
expect(capturePage).toHaveBeenCalledTimes(1);
23662366
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 43));
23672367
yield* manager.registerWebview("tab_1", 43);
23682368
yield* TestClock.adjust(1_000);
23692369
const exit = yield* Fiber.join(fiber);
23702370

23712371
expect(Exit.isFailure(exit)).toBe(true);
23722372
expect(capturePage).toHaveBeenCalledTimes(1);
2373+
expect(writeFile).not.toHaveBeenCalled();
2374+
}),
2375+
),
2376+
);
2377+
2378+
effectIt.effect("discards a screenshot that resolves after its guest is replaced", () =>
2379+
withManager((manager) =>
2380+
Effect.gen(function* () {
2381+
const image = {
2382+
toPNG: () => Buffer.from("stale-png"),
2383+
toJPEG: () => Buffer.from("stale-jpeg"),
2384+
getSize: () => ({ width: 100, height: 80 }),
2385+
};
2386+
const pending = Promise.withResolvers<typeof image>();
2387+
const capturePage = vi.fn(() => pending.promise);
2388+
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 42));
2389+
yield* manager.createTab("tab_1");
2390+
yield* manager.registerWebview("tab_1", 42);
2391+
2392+
const fiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
2393+
Effect.forkChild({ startImmediately: true }),
2394+
);
2395+
yield* TestClock.adjust(0);
2396+
expect(capturePage).toHaveBeenCalledOnce();
2397+
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 43));
2398+
yield* manager.registerWebview("tab_1", 43);
2399+
pending.resolve(image);
2400+
const exit = yield* Fiber.join(fiber);
2401+
2402+
expect(Exit.isFailure(exit)).toBe(true);
2403+
expect(capturePage).toHaveBeenCalledOnce();
2404+
expect(writeFile).not.toHaveBeenCalled();
2405+
}),
2406+
),
2407+
);
2408+
2409+
effectIt.effect("releases snapshot control when every capture attempt stalls", () =>
2410+
withManager((manager) =>
2411+
Effect.gen(function* () {
2412+
const capturePage = vi.fn(() => new Promise<TestCapturedPreviewImage>(() => {}));
2413+
const wc = makeTestPreviewWebContents(capturePage);
2414+
Object.assign(wc, { isDevToolsOpened: () => false });
2415+
Object.assign(wc.debugger, {
2416+
sendCommand: vi.fn(async (method: string, params?: Record<string, unknown>) => {
2417+
if (method === "Runtime.evaluate") {
2418+
return {
2419+
result: {
2420+
value:
2421+
params?.["expression"] === "42"
2422+
? 42
2423+
: {
2424+
url: "https://example.com",
2425+
title: "Example",
2426+
loading: false,
2427+
visibleText: "Example",
2428+
interactiveElements: [],
2429+
},
2430+
},
2431+
};
2432+
}
2433+
return method === "Accessibility.getFullAXTree" ? { nodes: [] } : undefined;
2434+
}),
2435+
});
2436+
fromId.mockReturnValue(wc);
2437+
yield* manager.createTab("tab_1");
2438+
yield* manager.registerWebview("tab_1", 42);
2439+
2440+
const snapshot = yield* Effect.exit(manager.automationSnapshot("tab_1")).pipe(
2441+
Effect.forkChild({ startImmediately: true }),
2442+
);
2443+
yield* TestClock.adjust(100);
2444+
expect(capturePage).toHaveBeenCalledOnce();
2445+
const evaluate = yield* manager
2446+
.automationEvaluate("tab_1", { expression: "42" })
2447+
.pipe(Effect.forkChild({ startImmediately: true }));
2448+
expect(evaluate.pollUnsafe()).toBeUndefined();
2449+
2450+
yield* TestClock.adjust(4_000);
2451+
const exit = yield* Fiber.join(snapshot);
2452+
expect(Exit.isFailure(exit)).toBe(true);
2453+
expect(capturePage).toHaveBeenCalledTimes(3);
2454+
if (Exit.isSuccess(exit)) return;
2455+
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
2456+
expect(error).toMatchObject({
2457+
_tag: "PreviewOperationError",
2458+
operation: "automationSnapshot.capturePage",
2459+
tabId: "tab_1",
2460+
webContentsId: 42,
2461+
cause: { _tag: "TimeoutError" },
2462+
});
2463+
expect(yield* Fiber.join(evaluate)).toBe(42);
23732464
}),
23742465
),
23752466
);

‎apps/desktop/src/preview/Manager.ts‎

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -115,13 +115,12 @@ const RECORDING_ARM_GRACE_MS = 10_000;
115115
const PICTURE_IN_PICTURE_FRAME_INTERVAL_MS = Math.ceil(1_000 / 12);
116116
const PICTURE_IN_PICTURE_JPEG_QUALITY = 80;
117117
/**
118-
* Chromium reports UnknownVizError while a hidden or freshly attached guest is
119-
* warming its first compositor frame. Background frame capture already rides
120-
* this out via its scheduled loop; one-shot captures need their own retry or a
121-
* snapshot taken against a backgrounded preview fails outright.
118+
* Cold guests can reject capturePage with UnknownVizError or never settle it.
119+
* Bound each attempt so snapshots release control even when Chromium stalls.
122120
*/
123121
const CAPTURE_PAGE_RETRY_ATTEMPTS = 3;
124122
const CAPTURE_PAGE_RETRY_DELAY_MS = 120;
123+
const CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS = 1_000;
125124
const PICTURE_IN_PICTURE_INITIAL_WIDTH = 480;
126125
const PICTURE_IN_PICTURE_INITIAL_HEIGHT = 320;
127126
const PICTURE_IN_PICTURE_MIN_WIDTH = 240;
@@ -664,32 +663,41 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
664663
try: evaluate,
665664
catch: (cause) => new PreviewOperationError({ ...errorContext, cause }),
666665
});
667-
/**
668-
* capturePage for one-shot captures (snapshots, screenshots), retrying the
669-
* transient compositor warm-up failure instead of surfacing it to callers.
670-
*
671-
* Retries stop as soon as the tab no longer points at this guest, so a
672-
* webview swap during the retry window surfaces the original failure instead
673-
* of capturing from a detached web contents.
674-
*/
675-
const capturePageWithRetry = (
666+
const capturePageWithRetry = Effect.fn("PreviewManager.capturePageWithRetry")(function* (
676667
errorContext: PreviewOperationContext,
677668
tabId: string,
678669
wc: Electron.WebContents,
679-
) => {
680-
const guestIsCurrent = Effect.gen(function* () {
681-
if (wc.isDestroyed()) return false;
670+
) {
671+
const requireCurrentGuest = Effect.gen(function* () {
682672
const tabs = yield* SynchronizedRef.get(tabsRef);
683-
return tabs.get(tabId)?.webContentsId === wc.id;
673+
if (wc.isDestroyed() || tabs.get(tabId)?.webContentsId !== wc.id) {
674+
return yield* new PreviewWebContentsNotFoundError({ tabId, webContentsId: wc.id });
675+
}
684676
});
685-
return attemptPromise(errorContext, () => wc.capturePage()).pipe(
677+
const capture = Effect.gen(function* () {
678+
// Check after the retry delay, and again before accepting its result.
679+
yield* requireCurrentGuest;
680+
const image = yield* Effect.tryPromise({
681+
// An abort-signal parameter makes a stalled promise interruptible.
682+
try: (_signal) => wc.capturePage(),
683+
catch: (cause) => new PreviewOperationError({ ...errorContext, cause }),
684+
}).pipe(
685+
Effect.timeout(CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS),
686+
Effect.catchTag("TimeoutError", (cause) =>
687+
Effect.fail(new PreviewOperationError({ ...errorContext, cause })),
688+
),
689+
);
690+
yield* requireCurrentGuest;
691+
return image;
692+
});
693+
return yield* capture.pipe(
686694
Effect.retry({
687695
times: CAPTURE_PAGE_RETRY_ATTEMPTS - 1,
688696
schedule: Schedule.spaced(CAPTURE_PAGE_RETRY_DELAY_MS),
689-
while: () => guestIsCurrent,
697+
while: isPreviewOperationError,
690698
}),
691699
);
692-
};
700+
});
693701
const currentIso = DateTime.now.pipe(Effect.map(DateTime.formatIso));
694702
const currentMillis = Clock.currentTimeMillis;
695703
const encodeJson = (errorContext: PreviewOperationContext, value: unknown) =>

‎apps/web/src/components/preview/PreviewAutomationHosts.tsx‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ import {
7676
resolvePreviewAutomationOpenTab,
7777
resolvePreviewAutomationTarget,
7878
} from "./previewAutomationTarget";
79-
import { resolveHostWaitBudgetMs } from "./previewAutomationHostBudget";
79+
import { resolveHostWaitBudgetMs, waitForHostReadiness } from "./previewAutomationHostBudget";
8080
import { isPreviewViewportReady } from "./previewViewportReadiness";
8181
import { shouldRollbackPreviewViewport } from "./previewViewportRollback";
8282

@@ -96,23 +96,21 @@ const waitForDesktopOverlay = async (
9696
tabId: string,
9797
runtimeTabId: string,
9898
operation: PreviewAutomationRequest["operation"],
99-
timeoutMs: number,
99+
deadlineMs: number,
100100
): Promise<void> => {
101-
// Expire before the broker does, so an unavailable overlay surfaces as
102-
// PreviewAutomationOverlayTimeoutError rather than a bare broker timeout.
103-
const waitBudgetMs = resolveHostWaitBudgetMs(timeoutMs);
104-
const deadline = Date.now() + waitBudgetMs;
105-
while (Date.now() <= deadline) {
101+
const waitBudgetMs = Math.max(0, deadlineMs - Date.now());
102+
const ready = await waitForHostReadiness(deadlineMs, async () => {
106103
const state = assertPreviewRuntimeCurrent(threadRef, tabId, runtimeTabId, {
107104
operation,
108105
requestId,
109106
});
110107
if (state.desktopByTabId[tabId] && previewBridge && isPreviewWebviewRendering(runtimeTabId)) {
111108
const status = await previewBridge.automation.status(runtimeTabId);
112-
if (status.available) return;
109+
return status.available;
113110
}
114-
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
115-
}
111+
return false;
112+
});
113+
if (ready) return;
116114
throw new PreviewAutomationOverlayTimeoutError({
117115
requestId,
118116
environmentId: threadRef.environmentId,
@@ -321,6 +319,8 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
321319

322320
const handleRequest = useCallback(
323321
async (request: PreviewAutomationRequest): Promise<unknown> => {
322+
// Session sync and tab creation consume the same budget as overlay registration.
323+
const hostDeadlineMs = Date.now() + resolveHostWaitBudgetMs(request.timeoutMs);
324324
const threadRef: ScopedThreadRef = {
325325
environmentId,
326326
threadId: request.threadId,
@@ -382,7 +382,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
382382
readyTabId,
383383
runtimeTabId,
384384
request.operation,
385-
request.timeoutMs,
385+
hostDeadlineMs,
386386
);
387387
return {
388388
bridge,
Lines changed: 97 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,12 @@
1-
import { describe, expect, it } from "vite-plus/test";
1+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
22

33
import {
44
PREVIEW_HOST_RESPONSE_MARGIN_MS,
55
resolveHostWaitBudgetMs,
6+
waitForHostReadiness,
67
} from "./previewAutomationHostBudget";
78

89
describe("resolveHostWaitBudgetMs", () => {
9-
it("always expires before the broker deadline, at every request budget", () => {
10-
// The whole point of the helper: the host must lose no race, at any scale.
11-
for (const requestTimeoutMs of [1, 2, 10, 100, 249, 250, 999, 1_500, 3_000, 15_000, 60_000]) {
12-
expect(resolveHostWaitBudgetMs(requestTimeoutMs)).toBeLessThan(requestTimeoutMs);
13-
}
14-
});
15-
1610
it("reserves the full response margin once the request budget allows it", () => {
1711
expect(resolveHostWaitBudgetMs(15_000)).toBe(15_000 - PREVIEW_HOST_RESPONSE_MARGIN_MS);
1812
expect(resolveHostWaitBudgetMs(60_000)).toBe(60_000 - PREVIEW_HOST_RESPONSE_MARGIN_MS);
@@ -23,16 +17,104 @@ describe("resolveHostWaitBudgetMs", () => {
2317
expect(resolveHostWaitBudgetMs(100)).toBe(80);
2418
});
2519

26-
it("grows monotonically with the request budget", () => {
27-
const budgets = [1, 10, 100, 1_000, 3_000, 15_000].map(resolveHostWaitBudgetMs);
28-
for (let index = 1; index < budgets.length; index += 1) {
29-
expect(budgets[index]!).toBeGreaterThanOrEqual(budgets[index - 1]!);
30-
}
31-
});
32-
3320
it("returns a non-negative budget for invalid input", () => {
3421
for (const invalid of [0, -5, Number.NaN, Number.POSITIVE_INFINITY]) {
3522
expect(resolveHostWaitBudgetMs(invalid)).toBeGreaterThanOrEqual(0);
3623
}
3724
});
3825
});
26+
27+
describe("waitForHostReadiness", () => {
28+
beforeEach(() => {
29+
vi.useFakeTimers();
30+
vi.setSystemTime(0);
31+
});
32+
33+
afterEach(() => {
34+
vi.useRealTimers();
35+
});
36+
37+
it.each([1, 10, 100, 250, 1_000, 15_000])(
38+
"stops unavailable-overlay polling before a %ims broker timeout",
39+
async (requestTimeoutMs) => {
40+
const deadlineMs = Date.now() + resolveHostWaitBudgetMs(requestTimeoutMs);
41+
let finishedAt: number | undefined;
42+
const result = waitForHostReadiness(deadlineMs, async () => false).then((ready) => {
43+
finishedAt = Date.now();
44+
return ready;
45+
});
46+
47+
await vi.advanceTimersByTimeAsync(requestTimeoutMs);
48+
49+
expect(await result).toBe(false);
50+
expect(finishedAt).toBeLessThan(requestTimeoutMs);
51+
expect(vi.getTimerCount()).toBe(0);
52+
},
53+
);
54+
55+
it("includes session setup in the deadline instead of starting a fresh wait budget", async () => {
56+
const deadlineMs = Date.now() + resolveHostWaitBudgetMs(15_000);
57+
await vi.advanceTimersByTimeAsync(2_000);
58+
let finished = false;
59+
const result = waitForHostReadiness(deadlineMs, async () => false).then((ready) => {
60+
finished = true;
61+
return ready;
62+
});
63+
64+
await vi.advanceTimersByTimeAsync(11_499);
65+
expect(finished).toBe(false);
66+
await vi.advanceTimersByTimeAsync(1);
67+
expect(await result).toBe(false);
68+
expect(Date.now()).toBe(deadlineMs);
69+
expect(vi.getTimerCount()).toBe(0);
70+
});
71+
72+
it("skips readiness probes when setup has already exhausted the deadline", async () => {
73+
const deadlineMs = Date.now() + resolveHostWaitBudgetMs(100);
74+
await vi.advanceTimersByTimeAsync(100);
75+
const isReady = vi.fn(async () => false);
76+
77+
expect(await waitForHostReadiness(deadlineMs, isReady)).toBe(false);
78+
expect(isReady).not.toHaveBeenCalled();
79+
expect(vi.getTimerCount()).toBe(0);
80+
});
81+
82+
it("returns as soon as the overlay is ready and clears its timeout", async () => {
83+
const isReady = vi.fn().mockResolvedValueOnce(false).mockResolvedValueOnce(true);
84+
const result = waitForHostReadiness(800, isReady);
85+
86+
await vi.advanceTimersByTimeAsync(50);
87+
88+
expect(await result).toBe(true);
89+
expect(isReady).toHaveBeenCalledTimes(2);
90+
expect(vi.getTimerCount()).toBe(0);
91+
});
92+
93+
it("bounds a stalled status probe and does not poll again if it completes late", async () => {
94+
let completeProbe!: (ready: boolean) => void;
95+
const isReady = vi.fn(
96+
() =>
97+
new Promise<boolean>((resolve) => {
98+
completeProbe = resolve;
99+
}),
100+
);
101+
const result = waitForHostReadiness(80, isReady);
102+
103+
await vi.advanceTimersByTimeAsync(80);
104+
expect(await result).toBe(false);
105+
expect(vi.getTimerCount()).toBe(0);
106+
107+
completeProbe(false);
108+
await vi.runAllTimersAsync();
109+
expect(isReady).toHaveBeenCalledTimes(1);
110+
expect(vi.getTimerCount()).toBe(0);
111+
});
112+
113+
it("preserves probe failures and clears the pending timeout", async () => {
114+
const error = new Error("Preview target was replaced");
115+
const isReady = vi.fn().mockRejectedValue(error);
116+
117+
await expect(waitForHostReadiness(800, isReady)).rejects.toBe(error);
118+
expect(vi.getTimerCount()).toBe(0);
119+
});
120+
});

0 commit comments

Comments
 (0)