Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(test): rearm early DevTools timeout [C7]
Corey Olson922bb0074b78
diff --git a/test/chrome-fixture.js b/test/chrome-fixture.jsindex 82fd2379..17297704 100644--- a/test/chrome-fixture.js+++ b/test/chrome-fixture.js@@ -11,11 +11,6 @@ const CLEANUP_TIMEOUT_MS = 5_000;const GROUP_POLL_MS = 20;const STDERR_LIMIT = 128 * 1024;-/** Treat only a one-millisecond CDP timer rounding difference as the exact operation-budget boundary. */-export function isRoundedBudgetBoundary(reportedMs, elapsedMs, budgetMs) {- return reportedMs === budgetMs - 1 && elapsedMs === budgetMs;-}-/** Find an installed Chrome without making browser availability a product-test failure. */export function findChromeExecutable() {return [process.env.PULLBOARD_CHROME, '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',@@ -152,21 +147,14 @@ export async function startChrome({}/** Wait until a page expression becomes truthy, treating document-transition evaluation errors as pending. */async function waitFor(expression, timeoutMs = commandTimeoutMs, label = 'wait for page condition') {- const waitStartedAt = Date.now();- const waitDeadline = waitStartedAt + timeoutMs;+ const waitDeadline = Date.now() + timeoutMs;let lastEvaluationError = null;while (Date.now() < waitDeadline) {try {if (await evaluate(expression, label, waitDeadline - Date.now())) return;} catch (error) {if (error instanceof Error && error.message.startsWith('Browser evaluation failed:')) lastEvaluationError = error;- else {- const cdpTimeout = error.code === 'CDP_TIMEOUT'- && /timed out after (\d+)ms/u.exec(error.message);- const roundedBoundary = cdpTimeout- && isRoundedBudgetBoundary(Number(cdpTimeout[1]), Date.now() - waitStartedAt, timeoutMs);- if (error.code !== 'CDP_TIMEOUT' || (Date.now() < waitDeadline && !roundedBoundary)) throw error;- }+ else if (error.code !== 'CDP_TIMEOUT' || Date.now() < waitDeadline) throw error;}await pause(Math.max(0, Math.min(50, waitDeadline - Date.now())));}@@ -290,8 +278,11 @@ async function connectDevTools(debuggerUrl, deadline) {return socket;}-/** Create a CDP command sender that correlates responses and bounds every request. */-function createSender(socket, pending, nextId, timeoutMs, loopDelay, relayRequests) {+/** Create a CDP sender with a deadline checked on the same clock used by timeout diagnostics. */+export function createSender(socket, pending, nextId, timeoutMs, loopDelay, relayRequests, timers = {}) {+ const now = timers.now ?? Date.now;+ const schedule = timers.setTimeout ?? setTimeout;+ const cancel = timers.clearTimeout ?? clearTimeout;/** Resolve or reject the request matching one CDP response without logging its payload. */function onMessage(event) {let message;@@ -310,29 +301,44 @@ function createSender(socket, pending, nextId, timeoutMs, loopDelay, relayRequesconst waiter = pending.get(message.id);if (!waiter) return;pending.delete(message.id);- clearTimeout(waiter.timer);+ cancel(waiter.timer);if (message.error) waiter.reject(new Error(`DevTools command failed: ${waiter.method}.`));else waiter.resolve(message.result);}socket.addEventListener('message', onMessage);return (method, params = {}, label = method, remainingMs = timeoutMs) => new Promise((resolveResult, rejectResult) => {const requestId = nextId();- const startedAt = Date.now();+ const startedAt = now();+ const durationMs = Math.max(1, Math.min(timeoutMs, remainingMs));+ const deadline = startedAt + durationMs;const maxDelayAtSend = loopDelay.max;- const timeoutMessage = () => {+ /** Format the timeout using the elapsed value already checked against this command deadline. */+ const timeoutMessage = elapsedMs => {const maxDelayRise = Math.max(0, loopDelay.max - maxDelayAtSend);- return `DevTools ${method} "${label}" timed out after ${Date.now() - startedAt}ms; maximum event-loop delay ${Math.round(maxDelayRise / 1e6)}ms; relay request pending: ${relayRequests.size > 0}.`;+ return `DevTools ${method} "${label}" timed out after ${elapsedMs}ms; maximum event-loop delay ${Math.round(maxDelayRise / 1e6)}ms; relay request pending: ${relayRequests.size > 0}.`;};- const timer = setTimeout(() => {+ let timer;+ /** Re-arm an early callback so timeout reporting cannot precede the armed deadline. */+ const expire = () => {+ if (!pending.has(requestId)) return;+ const currentTime = now();+ const elapsedMs = currentTime - startedAt;+ const remaining = deadline - currentTime;+ if (remaining > 0) {+ timer = schedule(expire, remaining);+ pending.get(requestId).timer = timer;+ return;+ }pending.delete(requestId);- const error = new Error(timeoutMessage());+ const error = new Error(timeoutMessage(elapsedMs));error.code = 'CDP_TIMEOUT';rejectResult(error);- }, Math.max(1, Math.min(timeoutMs, remainingMs)));+ };+ timer = schedule(expire, durationMs);pending.set(requestId, { resolve: resolveResult, reject: rejectResult, timer, method, label });try { socket.send(JSON.stringify({ id: requestId, method, params })); }catch {- clearTimeout(timer);+ cancel(timer);pending.delete(requestId);rejectResult(new Error(`DevTools command could not be sent: ${method}.`));}diff --git a/test/chrome-fixture.test.js b/test/chrome-fixture.test.jsindex fc983ccd..7aa583f9 100644--- a/test/chrome-fixture.test.js+++ b/test/chrome-fixture.test.js@@ -7,7 +7,7 @@ import { loadavg, tmpdir } from 'node:os';import { join } from 'node:path';import { monitorEventLoopDelay } from 'node:perf_hooks';import { test } from 'node:test';-import { findChromeExecutable, isRoundedBudgetBoundary, launchChromeProcess, startChrome } from './chrome-fixture.js';+import { createSender, findChromeExecutable, launchChromeProcess, startChrome } from './chrome-fixture.js';/** Pause between checks while waiting for a fixture helper's readiness marker. */function pause(ms) {@@ -192,24 +192,49 @@ test('a stalled condition uses its remaining operation budget [C7]', {scheduler.disable();const schedulerSlackMs = Math.ceil(scheduler.max / 1e6);const details = `budget=${budgetMs}ms elapsed=${Math.round(elapsedMs)}ms schedulerSlack=${schedulerSlackMs}ms loadavg=${JSON.stringify(loadavg())}`;- const cdpTimeout = failure instanceof Error- && /DevTools Runtime\.evaluate "bounded condition" timed out after (\d+)ms/u.exec(failure.message);const conditionTimeout = failure instanceof Error&& /Browser condition "bounded condition" did not arrive within 250ms/u.test(failure.message);- assert.ok(conditionTimeout || (cdpTimeout && isRoundedBudgetBoundary(Number(cdpTimeout[1]), elapsedMs, budgetMs)),+ assert.ok(conditionTimeout,`the stalled page condition should time out at its operation budget; ${details}; failure=${failure?.message ?? 'none'}`);assert.ok(elapsedMs <= budgetMs + schedulerSlackMs,`the 250ms condition stayed within its measured budget plus scheduler delay; ${details}`);assert.equal(await chrome.evaluate('1 + 1'), 2, 'timing out one command leaves the real DevTools connection usable');});-test('a timeout at the budget boundary passes [C7]', () => {- assert.equal(isRoundedBudgetBoundary(249, 250, 250), true,- 'a 249ms CDP report rounded to 250ms by the shared wall clock is at the budget boundary');- assert.equal(isRoundedBudgetBoundary(248, 250, 250), false,- 'a two-millisecond early CDP timeout is outside the rounding boundary');- assert.equal(isRoundedBudgetBoundary(249, 251, 250), false,- 'elapsed time beyond the budget is not accepted as a rounding boundary');+test('a DevTools timer that fires early still times out at its budget [C7]', async () => {+ let now = 10_000;+ const scheduled = [];+ const timers = {+ /** Read the simulated clock used by both timer arming and diagnostics. */+ now() { return now; },+ /** Capture each timer so the test can fire the first one exactly 1ms early. */+ setTimeout(callback, delay) {+ const timer = { callback, delay };+ scheduled.push(timer);+ return timer;+ },+ /** Mark cancellation without advancing simulated time. */+ clearTimeout(timer) {+ timer.cleared = true;+ },+ };+ const socket = { addEventListener() {}, send() {} };+ const pending = new Map();+ const send = createSender(socket, pending, () => 1, 250, { max: 0 }, new Set(), timers);+ const result = send('Runtime.evaluate', {}, 'early timer').catch(error => error);+ assert.equal(scheduled[0].delay, 250, 'the first timer receives the full command budget');++ now += 249;+ scheduled.shift().callback();+ assert.equal(scheduled.length, 1, 'a timer firing 1ms early is re-armed');+ assert.equal(scheduled[0].delay, 1, 'the re-armed timer uses only the remaining budget');++ now += 1;+ scheduled.shift().callback();+ const error = await result;+ assert.equal(error.code, 'CDP_TIMEOUT');+ assert.match(error.message, /timed out after 250ms/u, 'the reported duration reaches its budget');+ assert.equal(pending.size, 0, 'the timed-out command is removed from the pending set');});test('a wait that throws while the page changes keeps waiting [C7]', async (t) => {