Skip to content

Commit c7dee32

Browse files
committed
fix: bound wait stable by the user timeout when a capture stalls
The stable loop only checked the deadline between captures, so a stalled backend capture (observed with macOS AX captures) rode the wait into the 90s daemon request timeout instead of the user-supplied timeoutMs. - Race each settle capture against the remaining wait budget with a real timer (test clocks advance synthetic time and cannot represent a hung backend call) and abandon the capture when the deadline wins, throwing wait_stable_timeout with captureStalled: true and a hint. - Skip the current-surface enrichment on the stalled path: it fires another capture, which is just as slow or hung and pushed the response ~8s further past the timeout on macOS. Verified live against macOS System Settings: cold-runner stall now exits in 10.1s for a 10s timeout (previously ~90s); warm settle unchanged.
1 parent 2d0163a commit c7dee32

3 files changed

Lines changed: 92 additions & 8 deletions

File tree

‎src/commands/interaction/runtime/selector-read.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,39 @@ test('runtime wait stable times out with capture stats when never settling', asy
455455
assert.ok(captures > 1);
456456
});
457457

458+
test('runtime wait stable times out when a backend capture stalls past the wait budget', async () => {
459+
const clock = createFakeClock();
460+
const device = createAgentDevice({
461+
backend: {
462+
platform: 'macos',
463+
// Simulates the stalled macOS AX capture: the promise never settles, so
464+
// only the real-timer deadline can end the wait.
465+
captureSnapshot: () => new Promise<BackendSnapshotResult>(() => {}),
466+
} satisfies AgentDeviceBackend,
467+
artifacts: createLocalArtifactAdapter(),
468+
sessions: createMemorySessionStore([{ name: 'default' }]),
469+
policy: localCommandPolicy(),
470+
clock,
471+
});
472+
473+
await assert.rejects(
474+
() =>
475+
device.selectors.wait({
476+
session: 'default',
477+
target: { kind: 'stable', quietMs: 100, timeoutMs: 250 },
478+
}),
479+
(error: unknown) => {
480+
assert.ok(error instanceof Error);
481+
assert.equal(error.message, 'wait timed out waiting for a stable UI');
482+
const details = (error as { details?: Record<string, unknown> }).details;
483+
assert.equal(details?.reason, 'wait_stable_timeout');
484+
assert.equal(details?.captureStalled, true);
485+
assert.equal(details?.captures, 0);
486+
return true;
487+
},
488+
);
489+
});
490+
458491
test('runtime wait stable uses provided defaults when quietMs/timeoutMs are omitted', async () => {
459492
const snapshot = selectorSnapshot();
460493
const clock = createFakeClock();

‎src/commands/interaction/runtime/selector-read.ts‎

Lines changed: 55 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -530,14 +530,22 @@ async function waitForStable(
530530
let lastNodeCount = 0;
531531
let quietSinceMs = start;
532532
while (now(runtime) - start < timeout) {
533-
// Intentionally do not update the session snapshot: this loop captures an
534-
// interactive-only tree purely as a settle signal, and overwriting the session's
535-
// richer cached snapshot with the filtered tree would degrade subsequent
536-
// ref/get/find lookups against the same session.
537-
const capture = await captureSelectorSnapshot(runtime, options, {
538-
updateSession: false,
539-
interactiveOnly: true,
540-
});
533+
const capture = await captureStableSignalWithinDeadline(
534+
runtime,
535+
options,
536+
timeout - (now(runtime) - start),
537+
);
538+
if (!capture) {
539+
throw new AppError('COMMAND_FAILED', 'wait timed out waiting for a stable UI', {
540+
reason: 'wait_stable_timeout',
541+
captureStalled: true,
542+
quietMs: quiet,
543+
timeoutMs: timeout,
544+
captures,
545+
nodeCount: lastNodeCount,
546+
hint: 'A snapshot capture stalled past the wait timeout, so no settle verdict is available. The UI may still be readable: retry, or use screenshot to inspect the surface.',
547+
});
548+
}
541549
captures += 1;
542550
const digest = digestSnapshotNodes(capture.snapshot.nodes);
543551
const nowMs = now(runtime);
@@ -565,6 +573,45 @@ async function waitForStable(
565573
});
566574
}
567575

576+
// Intentionally does not update the session snapshot: the stable loop captures
577+
// an interactive-only tree purely as a settle signal, and overwriting the
578+
// session's richer cached snapshot with the filtered tree would degrade
579+
// subsequent ref/get/find lookups against the same session.
580+
//
581+
// Resolves undefined when the capture does not return within remainingMs. A
582+
// stalled backend capture (observed with macOS AX captures) must not push the
583+
// stable wait past the user-supplied timeout into the daemon request timeout.
584+
// The deadline uses a real timer even when runtime.clock is injected: test
585+
// clocks advance synthetic time synchronously and cannot represent a hung
586+
// backend call.
587+
async function captureStableSignalWithinDeadline(
588+
runtime: AgentDeviceRuntime,
589+
options: WaitCommandOptions,
590+
remainingMs: number,
591+
): Promise<CapturedSnapshot | undefined> {
592+
const capture = captureSelectorSnapshot(runtime, options, {
593+
updateSession: false,
594+
interactiveOnly: true,
595+
});
596+
let timer: NodeJS.Timeout | undefined;
597+
try {
598+
const result = await Promise.race([
599+
capture,
600+
new Promise<undefined>((resolve) => {
601+
timer = setTimeout(() => resolve(undefined), remainingMs);
602+
}),
603+
]);
604+
if (result === undefined) {
605+
// The abandoned capture settles (or fails) on its own; swallow it so it
606+
// cannot surface as an unhandled rejection after the wait already threw.
607+
capture.catch(() => {});
608+
}
609+
return result;
610+
} finally {
611+
if (timer !== undefined) clearTimeout(timer);
612+
}
613+
}
614+
568615
function digestSnapshotNodes(nodes: SnapshotNode[]): string {
569616
return nodes.map(digestSnapshotNode).join('|');
570617
}

‎src/daemon/wait-current-surface.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ export async function maybeWaitTimeoutSurfaceResponse(
2424
response: DaemonResponse,
2525
): Promise<DaemonResponse> {
2626
if (response.ok || !isWaitTimeoutMessage(response.error.message)) return response;
27+
// A stable wait that just observed a stalled capture must not fire another
28+
// capture for decoration: it would be just as slow (or hung) and push the
29+
// response even further past the user-supplied timeout.
30+
if (response.error.details?.captureStalled === true) return response;
2731
const currentSurface = await inspectCurrentSurface(params).catch(() => null);
2832
if (!currentSurface) return response;
2933
return errorResponse(

0 commit comments

Comments
 (0)