Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

Fix plan approval timeout behavior

Barack Sokullu9d2b87629b67
diff --git a/docs/architecture.md b/docs/architecture.md
index c63a899ef..1b7856491 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -371,7 +371,7 @@ reference identifies the same form; saved HTML readback needs no AX reference.
Failure diagnostics name
the missing verification step and preserve whether submission already occurred.
-If the planner returns valid JSON, the side panel receives `agent_update: plan_review` and renders an editable review card. Approval pins the approved plan into the scratchpad so it survives context compaction. Rejection, timeout, or user abort stops the run before any browser tools execute. In Try mode, invalid JSON after one repair degrades only that turn to the Ask prompt and read-only tool catalog; Strict mode still stops before tools. Scheduled runs can set `autoApprovePlanReview` and pin the plan without showing the card.
+If the planner returns valid JSON and needs review, the side panel receives `agent_update: plan_review` and renders an editable review card. Approval pins the approved plan into the scratchpad so it survives context compaction. If no decision arrives within two minutes, the original plan is automatically approved and execution continues; the runtime emits `plan_resolved` with `decision: 'approve'` and `source: 'timeout'` to clear the pending review and its notifications. Rejection or user abort stops the run before any browser tools execute. A Cancel delayed past approval stops the matching active request and plan; its rejected resolution is journaled so reconnect can recover a lost acknowledgement without stopping a newer request. In Try mode, invalid JSON after one repair degrades only that turn to the Ask prompt and read-only tool catalog; Strict mode still stops before tools. Scheduled runs can set `autoApprovePlanReview` and pin the plan without showing the card.
### Step 5: Main Agent Loop
```
diff --git a/package.json b/package.json
index c479b322a..d3cfa9a3c 100644
--- a/package.json
+++ b/package.json
@@ -13,7 +13,7 @@
"test:quality:relaxed-monitoring-retry": "node test/quality/relaxed-monitoring-retry-mv3.mjs",
"test:captcha:ui": "node test/captcha-settings-ui.mjs && node test/captcha-application-ui.mjs && node --test test/captcha-draft-content.mjs test/captcha-challenge-surfaces.mjs",
"test:captcha:bridge:ui": "node test/captcha-callback-bridge-ui.mjs",
- "test:plan-notifications": "node --test test/plan-review-notifications.mjs test/attention-flash-markers.mjs",
+ "test:plan-notifications": "node --test test/plan-review-notifications.mjs test/attention-flash-markers.mjs test/plan-review-cancellation.mjs",
"test:billing-notice": "node test/billing-payment-notice.mjs",
"test:provider-limits": "node test/provider-model-limits.mjs",
"test:frontier:live": "node scripts/check-frontier-models.mjs",
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index 5c1adb1da..86d6a0e14 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -19845,7 +19845,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
async _waitForPlanReview(tabId, planId, plan, markdown, onUpdate, verboseMarkdown = '') {
- const PLAN_REVIEW_TIMEOUT_MS = 10 * 60 * 1000;
+ const PLAN_REVIEW_TIMEOUT_MS = 2 * 60 * 1000;
const tabPending = this._pendingPlans.get(tabId) || new Map();
this._pendingPlans.set(tabId, tabPending);
const responsePromise = new Promise((resolve) => {
@@ -19854,9 +19854,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
let timeoutId = null;
const timeoutPromise = new Promise((resolve) => {
timeoutId = setTimeout(() => resolve({
- action: 'reject',
- cancelled: true,
- reason: 'plan review timed out',
+ action: 'approve',
+ source: 'timeout',
}), PLAN_REVIEW_TIMEOUT_MS);
});
if (typeof onUpdate === 'function') {
@@ -19866,19 +19865,19 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
try {
const response = await Promise.race([responsePromise, timeoutPromise]);
- if (response?.cancelled && typeof onUpdate === 'function') {
+ if ((response?.cancelled || response?.source === 'timeout') && typeof onUpdate === 'function') {
try {
onUpdate('plan_resolved', {
planId,
- decision: response.reason === 'plan review timed out' ? 'timeout' : 'cancelled',
+ decision: response.cancelled ? 'cancelled' : 'approve',
+ ...(response.source === 'timeout' ? { source: 'timeout' } : {}),
});
} catch {}
}
return response;
} finally {
- // Cancel the 10-minute timer once the race settles so a fast approval
- // doesn't leave an armed timer (and its captured resolve/plan closure)
- // alive for up to 10 minutes.
+ // Clear the auto-approval timer when a manual decision or cancellation
+ // settles first so it cannot resolve a stale review later.
if (timeoutId != null) clearTimeout(timeoutId);
tabPending.delete(planId);
if (!tabPending.size) this._pendingPlans.delete(tabId);
diff --git a/src/chrome/src/background.js b/src/chrome/src/background.js
index 111f2e0a4..2d1cd7193 100644
--- a/src/chrome/src/background.js
+++ b/src/chrome/src/background.js
@@ -4420,8 +4420,32 @@ async function handleMessage(msg, sender) {
const editedText = String(msg.editedText || '');
const markdownMode = msg.markdownMode === 'verbose' ? 'verbose' : 'compact';
if (!planId) return { ok: false, error: 'planId required' };
- const matched = agent.submitPlanResponse(tabId, planId, decision, editedText, markdownMode);
+ const requestId = String(msg.requestId || '');
const snapshot = await getRunUiSnapshot(tabId);
+ if (requestId && (snapshot?.requestId !== requestId || runUiJournal.get(tabId) !== snapshot)) {
+ return { ok: false, matched: false };
+ }
+ const matched = agent.submitPlanResponse(tabId, planId, decision, editedText, markdownMode);
+ if (!matched && decision === 'reject' && requestId
+ && snapshot?.status === 'running'
+ && snapshot.lastPlanResolution?.planId === planId
+ && snapshot.lastPlanResolution.decision === 'approve') {
+ const activeState = agent.activeRunState(tabId);
+ if (activeState.running && (!snapshot.runId || snapshot.runId === activeState.runId)) {
+ // Cancel can cross the timeout while its response is in transit.
+ // Stop only the request that owned this approved plan.
+ const sourceTabId = agent.researchEscalationSourceTab(tabId);
+ const promptHold = holdContextMenuPromptsAfterStop(tabId, sourceTabId);
+ cancelDetachedRunStart(tabId);
+ if (sourceTabId) cancelDetachedRunStart(sourceTabId);
+ agent.abort(sourceTabId || tabId);
+ // Persist the accepted rejection before yielding so a lost reply
+ // can be recovered without confusing it with timeout approval.
+ sendAgentUpdate(tabId, requestId, 'plan_resolved', { planId, decision });
+ await promptHold;
+ return { ok: true, matched: true };
+ }
+ }
if (matched && snapshot?.requestId) {
sendAgentUpdate(tabId, snapshot.requestId, 'plan_resolved', { planId, decision });
}
diff --git a/src/chrome/src/run-reconnect.js b/src/chrome/src/run-reconnect.js
index 448f103fb..4a9c8f172 100644
--- a/src/chrome/src/run-reconnect.js
+++ b/src/chrome/src/run-reconnect.js
@@ -347,13 +347,13 @@ export async function sendPlanResponseWithReconnect({
}
const planId = String(payload?.planId || '');
if (!planId) throw new Error('Plan response recovery requires a planId.');
- const expectedRequestId = String(requestId || '');
+ const expectedRequestId = String(requestId || payload?.requestId || '');
let lastConnectionError = null;
let reconnected = false;
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
try {
- const response = await send(payload);
+ const response = await send({ ...payload, requestId: expectedRequestId });
if (response?.matched) return { ...response, reconnected };
} catch (error) {
if (!isConnectionError?.(error)) throw error;
@@ -379,10 +379,17 @@ export async function sendPlanResponseWithReconnect({
continue;
}
- const resolution = matchingPlanResolution(state, planId);
+ const sameRequest = !expectedRequestId
+ || requestMatches(state?.runUi?.requestId, expectedRequestId);
+ const resolution = sameRequest ? matchingPlanResolution(state, planId) : null;
if (resolution) {
reconnected = true;
onStatus({ phase: 'reconnected', planId, state });
+ // Timeout approval is not an acknowledgement of Cancel. Retry its
+ // request-scoped rejection so the background can stop the active run.
+ if (expectedRequestId && payload?.decision === 'reject'
+ && resolution.decision === 'approve'
+ && state?.running === true && state.runUi.status === 'running') continue;
return {
ok: true,
matched: String(resolution.decision || '') === String(payload?.decision || ''),
@@ -391,8 +398,6 @@ export async function sendPlanResponseWithReconnect({
};
}
- const sameRequest = !expectedRequestId
- || requestMatches(state?.runUi?.requestId, expectedRequestId);
const samePendingPlan = requestMatches(state?.pendingPlan?.planId, planId);
if (samePendingPlan && sameRequest) {
reconnected = true;
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index f20456687..dc9848bfa 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -17331,7 +17331,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
async _waitForPlanReview(tabId, planId, plan, markdown, onUpdate, verboseMarkdown = '') {
- const PLAN_REVIEW_TIMEOUT_MS = 10 * 60 * 1000;
+ const PLAN_REVIEW_TIMEOUT_MS = 2 * 60 * 1000;
const tabPending = this._pendingPlans.get(tabId) || new Map();
this._pendingPlans.set(tabId, tabPending);
const responsePromise = new Promise((resolve) => {
@@ -17340,9 +17340,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
let timeoutId = null;
const timeoutPromise = new Promise((resolve) => {
timeoutId = setTimeout(() => resolve({
- action: 'reject',
- cancelled: true,
- reason: 'plan review timed out',
+ action: 'approve',
+ source: 'timeout',
}), PLAN_REVIEW_TIMEOUT_MS);
});
if (typeof onUpdate === 'function') {
@@ -17352,19 +17351,19 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
try {
const response = await Promise.race([responsePromise, timeoutPromise]);
- if (response?.cancelled && typeof onUpdate === 'function') {
+ if ((response?.cancelled || response?.source === 'timeout') && typeof onUpdate === 'function') {
try {
onUpdate('plan_resolved', {
planId,
- decision: response.reason === 'plan review timed out' ? 'timeout' : 'cancelled',
+ decision: response.cancelled ? 'cancelled' : 'approve',
+ ...(response.source === 'timeout' ? { source: 'timeout' } : {}),
});
} catch {}
}
return response;
} finally {
- // Cancel the 10-minute timer once the race settles so a fast approval
- // doesn't leave an armed timer (and its captured resolve/plan closure)
- // alive for up to 10 minutes.
+ // Clear the auto-approval timer when a manual decision or cancellation
+ // settles first so it cannot resolve a stale review later.
if (timeoutId != null) clearTimeout(timeoutId);
tabPending.delete(planId);
if (!tabPending.size) this._pendingPlans.delete(tabId);
diff --git a/src/firefox/src/background.js b/src/firefox/src/background.js
index 04efbeb6f..a9df7f0ed 100644
--- a/src/firefox/src/background.js
+++ b/src/firefox/src/background.js
@@ -3867,8 +3867,32 @@ async function handleMessage(msg, sender) {
const editedText = String(msg.editedText || '');
const markdownMode = msg.markdownMode === 'verbose' ? 'verbose' : 'compact';
if (!planId) return { ok: false, error: 'planId required' };
- const matched = agent.submitPlanResponse(tabId, planId, decision, editedText, markdownMode);
+ const requestId = String(msg.requestId || '');
const snapshot = await getRunUiSnapshot(tabId);
+ if (requestId && (snapshot?.requestId !== requestId || runUiJournal.get(tabId) !== snapshot)) {
+ return { ok: false, matched: false };
+ }
+ const matched = agent.submitPlanResponse(tabId, planId, decision, editedText, markdownMode);
+ if (!matched && decision === 'reject' && requestId
+ && snapshot?.status === 'running'
+ && snapshot.lastPlanResolution?.planId === planId
+ && snapshot.lastPlanResolution.decision === 'approve') {
+ const activeState = agent.activeRunState(tabId);
+ if (activeState.running && (!snapshot.runId || snapshot.runId === activeState.runId)) {
+ // Cancel can cross the timeout while its response is in transit.
+ // Stop only the request that owned this approved plan.
+ const sourceTabId = agent.researchEscalationSourceTab(tabId);
+ const promptHold = holdContextMenuPromptsAfterStop(tabId, sourceTabId);
+ cancelDetachedRunStart(tabId);
+ if (sourceTabId) cancelDetachedRunStart(sourceTabId);
+ agent.abort(sourceTabId || tabId);
+ // Persist the accepted rejection before yielding so a lost reply
+ // can be recovered without confusing it with timeout approval.
+ sendAgentUpdate(tabId, requestId, 'plan_resolved', { planId, decision });
+ await promptHold;
+ return { ok: true, matched: true };
+ }
+ }
if (matched && snapshot?.requestId) {
sendAgentUpdate(tabId, snapshot.requestId, 'plan_resolved', { planId, decision });
}
diff --git a/src/firefox/src/run-reconnect.js b/src/firefox/src/run-reconnect.js
index 448f103fb..4a9c8f172 100644
--- a/src/firefox/src/run-reconnect.js
+++ b/src/firefox/src/run-reconnect.js
@@ -347,13 +347,13 @@ export async function sendPlanResponseWithReconnect({
}
const planId = String(payload?.planId || '');
if (!planId) throw new Error('Plan response recovery requires a planId.');
- const expectedRequestId = String(requestId || '');
+ const expectedRequestId = String(requestId || payload?.requestId || '');
let lastConnectionError = null;
let reconnected = false;
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
try {
- const response = await send(payload);
+ const response = await send({ ...payload, requestId: expectedRequestId });
if (response?.matched) return { ...response, reconnected };
} catch (error) {
if (!isConnectionError?.(error)) throw error;
@@ -379,10 +379,17 @@ export async function sendPlanResponseWithReconnect({
continue;
}
- const resolution = matchingPlanResolution(state, planId);
+ const sameRequest = !expectedRequestId
+ || requestMatches(state?.runUi?.requestId, expectedRequestId);
+ const resolution = sameRequest ? matchingPlanResolution(state, planId) : null;
if (resolution) {
reconnected = true;
onStatus({ phase: 'reconnected', planId, state });
+ // Timeout approval is not an acknowledgement of Cancel. Retry its
+ // request-scoped rejection so the background can stop the active run.
+ if (expectedRequestId && payload?.decision === 'reject'
+ && resolution.decision === 'approve'
+ && state?.running === true && state.runUi.status === 'running') continue;
return {
ok: true,
matched: String(resolution.decision || '') === String(payload?.decision || ''),
@@ -391,8 +398,6 @@ export async function sendPlanResponseWithReconnect({
};
}
- const sameRequest = !expectedRequestId
- || requestMatches(state?.runUi?.requestId, expectedRequestId);
const samePendingPlan = requestMatches(state?.pendingPlan?.planId, planId);
if (samePendingPlan && sameRequest) {
reconnected = true;
diff --git a/test/plan-review-cancellation.mjs b/test/plan-review-cancellation.mjs
new file mode 100644
index 000000000..4010ab50d
--- /dev/null
+++ b/test/plan-review-cancellation.mjs
@@ -0,0 +1,276 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import test from 'node:test';
+import vm from 'node:vm';
+
+const area = { get: async () => ({}), set: async () => {}, remove: async () => {} };
+globalThis.chrome = globalThis.browser = {
+ storage: { local: area, session: area },
+ runtime: { getURL: value => value, sendMessage: async () => ({}) },
+};
+const builds = await Promise.all(['chrome', 'firefox'].map(async build => ({
+ build,
+ Agent: (await import(`../src/${build}/src/agent/agent.js`)).Agent,
+ journalModule: await import(`../src/${build}/src/run-ui-journal.js`),
+ reconnect: (await import(`../src/${build}/src/run-reconnect.js`)).sendPlanResponseWithReconnect,
+ background: (await fs.readFile(new URL(`../src/${build}/src/background.js`, import.meta.url), 'utf8')).replace(/\r\n/g, '\n'),
+})));
+
+function extract(source, name) {
+ const start = source.search(new RegExp(`^(?:async )?function ${name}\\(`, 'm'));
+ const end = source.indexOf('\n}', start);
+ assert.ok(start >= 0 && end > start, `Missing production function ${name}`);
+ return source.slice(start, end + 2);
+}
+function between(source, from, to) {
+ const start = source.indexOf(from), end = source.indexOf(to, start + from.length);
+ assert.ok(start >= 0 && end > start, `Missing production message route ${from}`);
+ return source.slice(start, end);
+}
+function deferred() {
+ let resolve;
+ const promise = new Promise(done => { resolve = done; });
+ return { promise, resolve };
+}
+const flush = () => new Promise(resolve => setImmediate(resolve));
+const connectionError = () => new Error('Owned runtime message port closed');
+
+// Run the real worker routes without starting unrelated background services.
+// Agent review timers/abort, the UI journal, and reconnect recovery stay real.
+function fixture(build, options = {}) {
+ const tab = 77, request = 'owned-request', planId = 'owned-plan';
+ const runId = options.noTracing ? null : 'owned-runtime';
+ const agent = new build.Agent({ getActive: () => ({ name: 'owned', model: 'owned' }) });
+ agent._persist = () => {};
+ agent._runningTabs.add(tab);
+ if (runId) agent.currentRunId.set(tab, runId);
+ const controller = new AbortController();
+ agent._runAbortStates.set(tab, { controller, dispose() {} });
+ agent.getConversationState = async () => ({ conversationId: 'owned-conversation' });
+ agent.hasDurableSubmittedTurn = async () => true;
+ const journal = new build.journalModule.RunUiJournal();
+ journal.begin(tab, request);
+ const messages = [], holds = [], waits = [], sends = [], statuses = [];
+ const reserved = { requestId: request, cancelled: false };
+ const context = vm.createContext({
+ agent, runUiJournal: journal, console,
+ contextMenuStorage: { hold: async tabId => { holds.push(tabId); await options.hold?.(); } },
+ detachedRunStarts: new Map([[tab, reserved]]), detachedRunFailures: new Map(), runUiPersistenceFailures: new Map(),
+ runUiSnapshotForRequest: build.journalModule.runUiSnapshotForRequest,
+ getRunUiSnapshot: async tabId => journal.get(tabId),
+ notifyPlanReview() {}, clearPlanReviewAttention() {}, planReviewAttentionByTab: new Map(),
+ chrome: { runtime: { sendMessage: async message => { messages.push(structuredClone(message)); } } },
+ });
+ context.browser = context.chrome;
+ vm.runInContext([
+ ...['recordRunUiEvent', 'sendAgentUpdate', 'holdContextMenuPromptsAfterStop', 'cancelDetachedRunStart'].map(name => extract(build.background, name)),
+ `async function route(msg, sender = {}) { switch (msg.action) {
+ ${between(build.background, " case 'agent_run_state': {", " case 'agent_run_ack': {")}
+ ${between(build.background, " case 'plan_response': {", " case 'get_debug_log': {")}
+ } }`,
+ ].join('\n'), context);
+ const f = {
+ ...build, tab, request, planId, runId, agent, journal, controller, messages, holds, waits, sends, statuses, reserved, context,
+ state: () => context.route({ action: 'agent_run_state', tabId: tab, requestId: request }),
+ respond: data => context.route({ action: 'plan_response', tabId: tab, planId, requestId: request, decision: 'reject', ...data }),
+ review(id = planId) {
+ const waiting = agent._waitForPlanReview(tab, id, { steps: [] }, 'Owned test plan',
+ (type, data) => context.sendAgentUpdate(tab, request, type, data));
+ waits.push(waiting);
+ return waiting;
+ },
+ recover(options = {}) {
+ return build.reconnect({
+ payload: { tabId: tab, planId, decision: 'reject', ...options.payload }, requestId: options.requestId ?? request,
+ send: async payload => {
+ sends.push(structuredClone(payload));
+ return options.send ? options.send(payload, sends.length) : f.respond(payload);
+ },
+ probe: options.probe || (() => f.state()),
+ isConnectionError: error => /Owned runtime message port closed/.test(error?.message || ''),
+ wait: options.wait || (async () => {}), onStatus: status => statuses.push(status),
+ });
+ },
+ async close() { agent._cancelPendingPlans(tab, 'Owned fixture cleanup'); await Promise.all(waits); },
+ };
+ return f;
+}
+
+async function autoApprove(t, f) {
+ const waiting = f.review();
+ t.mock.timers.tick(120_000);
+ await flush();
+ assert.deepEqual(await waiting, { action: 'approve', source: 'timeout' });
+ assert.equal(f.agent.activeRunState(f.tab).pendingPlan, null);
+ assert.equal(f.journal.get(f.tab).status, 'running');
+ assert.deepEqual({ ...f.journal.get(f.tab).lastPlanResolution }, { planId: f.planId, decision: 'approve' });
+}
+function assertStopped(f) {
+ assert.equal(f.controller.signal.aborted, true, 'The live execution receives Stop');
+ assert.equal(f.agent.abortFlags.get(f.tab), true);
+ assert.equal(f.reserved.cancelled, true, 'Detached startup is cancelled just like Stop');
+ assert.ok(f.holds.includes(f.tab), 'Queued browser-menu prompts are held just like Stop');
+ assert.deepEqual({ ...f.journal.get(f.tab).lastPlanResolution }, { planId: f.planId, decision: 'reject' });
+}
+
+for (const build of builds) {
+ test(`${build.build}: ordinary pending Cancel remains a review rejection`, async () => {
+ const f = fixture(build), waiting = f.review();
+ try {
+ const response = await f.recover();
+ assert.equal(response.matched, true);
+ assert.equal((await waiting).action, 'reject');
+ assert.equal(f.sends[0].requestId, f.request, 'The reconnect sender binds the worker message to its request');
+ assert.equal(f.controller.signal.aborted, false, 'The pending planning gate handles its own rejection');
+ assert.equal(f.holds.length, 0);
+ assert.equal(f.journal.get(f.tab).lastPlanResolution.decision, 'reject');
+ } finally { await f.close(); }
+ });
+
+ test(`${build.build}: Cancel delivered after the exact two-minute auto-approval stops the same live run`, async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const f = fixture(build), gate = deferred(), started = deferred(), waiting = f.review();
+ try {
+ const cancelling = f.recover({ send: async payload => { started.resolve(); await gate.promise; return f.respond(payload); } });
+ await started.promise;
+ t.mock.timers.tick(119_999);
+ await flush();
+ assert.equal(f.journal.get(f.tab).status, 'awaiting_plan');
+ assert.equal(f.controller.signal.aborted, false);
+ t.mock.timers.tick(1);
+ await flush();
+ assert.deepEqual(await waiting, { action: 'approve', source: 'timeout' });
+ assert.equal(f.journal.get(f.tab).lastPlanResolution.decision, 'approve');
+ gate.resolve();
+ assert.equal((await cancelling).matched, true);
+ assertStopped(f);
+ } finally { gate.resolve(); await f.close(); }
+ });
+
+ test(`${build.build}: lost first Cancel retries after the reconnect probe observes auto-approval`, async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const f = fixture(build), waiting = f.review();
+ try {
+ const response = await f.recover({
+ send: async (payload, attempt) => { if (attempt === 1) throw connectionError(); return f.respond(payload); },
+ wait: async () => { t.mock.timers.tick(120_000); await flush(); },
+ });
+ assert.deepEqual(await waiting, { action: 'approve', source: 'timeout' });
+ assert.equal(response.matched, true);
+ assert.equal(f.sends.length, 2);
+ assert.ok(f.sends.every(payload => payload.requestId === f.request));
+ assertStopped(f);
+ } finally { await f.close(); }
+ });
+
+ test(`${build.build}: a lost Stop reply recovers the rejected decision after journal ACK and run completion`, async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const f = fixture(build);
+ try {
+ await autoApprove(t, f);
+ const response = await f.recover({ send: async payload => {
+ assert.equal((await f.respond(payload)).matched, true);
+ f.journal.acknowledge(f.tab, f.request, f.journal.get(f.tab).seq);
+ f.journal.finish(f.tab, f.request, 'stopped', 'Stopped by user', f.runId);
+ f.agent._runningTabs.delete(f.tab);
+ throw connectionError();
+ } });
+ assert.equal(response.matched, true);
+ assert.equal(response.recovered, true);
+ assert.equal(f.sends.length, 1, 'The durable rejected resolution prevents a second Stop');
+ assert.equal(f.journal.get(f.tab).events.some(event => event.type === 'plan_resolved'), false);
+ assertStopped(f);
+ } finally { await f.close(); }
+ });
+
+ test(`${build.build}: Stop and its durable resolution happen before prompt-hold storage finishes`, async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const gate = deferred(), f = fixture(build, { hold: () => gate.promise });
+ try {
+ await autoApprove(t, f);
+ let settled = false;
+ const response = f.respond().then(value => { settled = true; return value; });
+ await flush();
+ assert.equal(settled, false);
+ assertStopped(f);
+ gate.resolve();
+ assert.equal((await response).matched, true);
+ } finally { gate.resolve(); await f.close(); }
+ });
+
+ test(`${build.build}: auto-approved Cancel still stops when tracing has no runtime ID`, async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const f = fixture(build, { noTracing: true });
+ try {
+ await autoApprove(t, f);
+ assert.equal(f.journal.get(f.tab).runId, null);
+ assert.equal((await f.recover()).matched, true);
+ assertStopped(f);
+ } finally { await f.close(); }
+ });
+
+ for (const change of ['wrong-request', 'missing-request', 'other-plan', 'another-runtime', 'restarted-worker', 'completed', 'stopped', 'failed', 'cancelled', 'clarification_required', 'new-plan']) {
+ test(`${build.build}: late Cancel cannot stop ${change}`, async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const f = fixture(build);
+ try {
+ await autoApprove(t, f);
+ const payload = {};
+ if (change === 'wrong-request') payload.requestId = 'different-request';
+ if (change === 'missing-request') payload.requestId = '';
+ if (change === 'other-plan') payload.planId = 'different-plan';
+ if (change === 'another-runtime') f.agent.currentRunId.set(f.tab, 'new-runtime');
+ if (change === 'restarted-worker') f.agent._runningTabs.delete(f.tab);
+ if (['completed', 'stopped', 'failed', 'cancelled', 'clarification_required'].includes(change)) f.journal.finish(f.tab, f.request, change, '', f.runId);
+ if (change === 'new-plan') f.review('different-pending-plan');
+ assert.equal((await f.respond(payload)).matched, false);
+ assert.equal(f.controller.signal.aborted, false);
+ assert.equal(f.agent.abortFlags.get(f.tab), undefined);
+ assert.equal(f.reserved.cancelled, false);
+ assert.equal(f.holds.length, 0);
+ } finally { await f.close(); }
+ });
+ }
+
+ test(`${build.build}: wrong request cannot settle an ordinary pending review`, async () => {
+ const f = fixture(build), waiting = f.review();
+ try {
+ assert.equal((await f.respond({ requestId: 'different-request' })).matched, false);
+ assert.equal(f.agent.activeRunState(f.tab).pendingPlan.planId, f.planId);
+ assert.equal((await f.respond()).matched, true);
+ assert.equal((await waiting).action, 'reject');
+ } finally { await f.close(); }
+ });
+
+ test(`${build.build}: a replacement journal during snapshot await cannot cancel its new run`, async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const f = fixture(build), gate = deferred(), started = deferred();
+ try {
+ await autoApprove(t, f);
+ const oldSnapshot = f.journal.get(f.tab);
+ f.context.getRunUiSnapshot = async () => { started.resolve(); await gate.promise; return oldSnapshot; };
+ const response = f.respond();
+ await started.promise;
+ f.journal.begin(f.tab, f.request);
+ f.journal.record(f.tab, f.request, 'plan_resolved', { planId: f.planId, decision: 'approve' }, f.runId);
+ gate.resolve();
+ assert.equal((await response).matched, false);
+ assert.equal(f.controller.signal.aborted, false);
+ assert.equal(f.holds.length, 0);
+ } finally { gate.resolve(); await f.close(); }
+ });
+
+ test(`${build.build}: reconnect cannot accept a different request's identical rejected plan ID`, async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const f = fixture(build);
+ try {
+ await autoApprove(t, f);
+ f.journal.begin(f.tab, 'different-request');
+ f.journal.record(f.tab, 'different-request', 'plan_resolved', { planId: f.planId, decision: 'reject' }, f.runId);
+ const response = await f.recover({ probe: async () => ({ ...f.agent.activeRunState(f.tab), runUi: f.journal.get(f.tab) }) });
+ assert.equal(response.matched, false);
+ assert.equal(f.controller.signal.aborted, false);
+ assert.equal(f.sends.length, 1);
+ } finally { await f.close(); }
+ });
+}
diff --git a/test/plan-review-notifications.mjs b/test/plan-review-notifications.mjs
index 8885d20eb..587186dc5 100644
--- a/test/plan-review-notifications.mjs
+++ b/test/plan-review-notifications.mjs
@@ -265,6 +265,53 @@ for (const item of builds) {
assert.equal(h.audio.length, 3, 'Plan ID reuse in another request must not suppress its alert');
});
+ test(`${item.build}: plan timeout resumes the journal and clears review attention`, async t => {
+ const h = deliveryHarness(item);
+ const agent = new item.Agent({ getActive: () => ({}) });
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ let settled = false;
+ const waiting = agent._waitForPlanReview(77, 'plan-1', { steps: [] }, 'Plan',
+ (type, data) => h.context.sendAgentUpdate(77, 'request-1', type, data))
+ .then(response => { settled = true; return response; });
+ await flush();
+
+ assert.equal(h.journal.get(77).status, 'awaiting_plan');
+ assert.equal(h.journal.get(77).pendingPlanId, 'plan-1');
+ assert.equal(h.audio.length, 1);
+ assert.equal(h.attention.length, 1);
+ const currentAudio = h.audio[0].isCurrent;
+ const currentAttention = h.attention[0].isCurrent;
+ assert.equal(currentAudio(), true);
+ assert.equal(currentAttention(), true);
+ assert.equal(vm.runInContext('planReviewAttentionByTab.has(77)', h.context), true);
+
+ t.mock.timers.tick(119_999);
+ await flush();
+ assert.equal(settled, false, 'The plan remains reviewable before the deadline');
+ assert.equal(h.journal.get(77).status, 'awaiting_plan');
+
+ t.mock.timers.tick(1);
+ await flush();
+ assert.equal(settled, true, 'The review settles at two minutes');
+ assert.deepEqual(await waiting, { action: 'approve', source: 'timeout' });
+ assert.equal(h.messages.at(-1).type, 'plan_resolved');
+ assert.deepEqual({ ...h.messages.at(-1).data }, {
+ planId: 'plan-1', decision: 'approve', source: 'timeout',
+ });
+ assert.equal(h.journal.get(77).status, 'running');
+ assert.equal(h.journal.get(77).pendingPlanId, null);
+ assert.deepEqual({ ...h.journal.get(77).lastPlanResolution }, {
+ planId: 'plan-1', decision: 'approve',
+ });
+ assert.equal(agent._pendingPlans.has(77), false);
+ assert.equal(vm.runInContext('planReviewAttentionByTab.has(77)', h.context), false);
+ assert.equal(currentAudio(), false, 'Queued audio loses ownership after auto-approval');
+ assert.equal(currentAttention(), false, 'Queued visual attention loses ownership after auto-approval');
+ assert.equal(h.stopped.at(-1).action, 'attention_flash_stop');
+ assert.equal(h.stopped.at(-1).params.attentionId, h.attention[0].attentionId);
+ assert.equal(h.audio.length, 1, 'Resolving the plan must not replay its alert');
+ });
+
test(`${item.build}: scheduled runs use the same plan alert owner`, async () => {
const h = deliveryHarness(item, { begin: false });
const owner = { jobId: 'job-1', executionId: 'execution-1', mode: 'act', kind: 'resume' };
diff --git a/test/run.js b/test/run.js
index bb690639c..5c021e3b1 100644
--- a/test/run.js
+++ b/test/run.js
@@ -117823,31 +117823,141 @@ test('WebBrain Compass subscription 402 renders as one terminal assistant prompt
}
});
-test('plan review: cancellation emits plan_resolved and timeout has an explicit terminal decision', async () => {
+async function withPlanReviewClock(fn) {
+ const originalSetTimeout = globalThis.setTimeout;
+ const originalClearTimeout = globalThis.clearTimeout;
+ let now = 0;
+ let nextTimerId = 1;
+ const timers = new Map();
+ globalThis.setTimeout = (callback, delay) => {
+ const timerId = nextTimerId++;
+ timers.set(timerId, { callback, delay, deadline: now + delay });
+ return timerId;
+ };
+ globalThis.clearTimeout = timerId => timers.delete(timerId);
+ try {
+ await fn({
+ timers,
+ async advance(ms) {
+ now += ms;
+ for (const [timerId, timer] of [...timers]) {
+ if (timer.deadline > now) continue;
+ timers.delete(timerId);
+ timer.callback();
+ }
+ await Promise.resolve();
+ await Promise.resolve();
+ },
+ });
+ } finally {
+ globalThis.setTimeout = originalSetTimeout;
+ globalThis.clearTimeout = originalClearTimeout;
+ }
+}
+
+test('plan review: unanswered plans auto-approve after two minutes and clear pending state', async () => {
await withPlannerBrowserGlobals(async () => {
- for (const [label, AgentClass, sourceRel] of [
- ['chrome', AgentCh, 'src/chrome/src/agent/agent.js'],
- ['firefox', AgentFx, 'src/firefox/src/agent/agent.js'],
- ]) {
- const tabId = label === 'chrome' ? 9301 : 9302;
- const agent = new AgentClass({ getActive: () => ({}) });
- const updates = [];
- const waiting = agent._waitForPlanReview(
- tabId,
- 'plan-1',
- { steps: [] },
- 'Plan',
- (type, data) => updates.push({ type, data }),
- );
- agent._cancelPendingPlans(tabId, 'Stopped by user');
- const result = await waiting;
- assert.equal(result.cancelled, true, `${label}: abort should cancel the pending plan`);
- assert.deepEqual(updates.map(update => update.type), ['plan_review', 'plan_resolved'], `${label}: abort should invalidate all plan copies`);
- assert.equal(updates.at(-1).data.decision, 'cancelled', `${label}: abort should have an explicit resolution`);
+ await withPlanReviewClock(async clock => {
+ for (const [label, AgentClass] of [['chrome', AgentCh], ['firefox', AgentFx]]) {
+ const tabId = label === 'chrome' ? 9301 : 9302;
+ const agent = new AgentClass({ getActive: () => ({}) });
+ const updates = [];
+ let settled = false;
+ const waiting = agent._waitForPlanReview(
+ tabId, 'plan-1', { steps: [] }, 'Plan',
+ (type, data) => updates.push({ type, data }),
+ ).then(result => { settled = true; return result; });
+
+ assert.equal(clock.timers.size, 1, `${label}: review should arm one timeout`);
+ assert.equal([...clock.timers.values()][0].delay, 120_000, `${label}: review deadline must be two minutes`);
+ await clock.advance(119_999);
+ assert.equal(settled, false, `${label}: review should remain open before the deadline`);
+ assert.equal(agent._pendingPlans.get(tabId)?.has('plan-1'), true, `${label}: unanswered plan should stay pending`);
+
+ await clock.advance(1);
+ const result = await waiting;
+ assert.deepEqual(result, { action: 'approve', source: 'timeout' }, `${label}: timeout should approve the plan`);
+ assert.deepEqual(updates.map(update => update.type), ['plan_review', 'plan_resolved'], `${label}: timeout should resolve all visible plan copies`);
+ assert.deepEqual(updates.at(-1).data, { planId: 'plan-1', decision: 'approve', source: 'timeout' }, `${label}: timeout should resume the run as approved`);
+ assert.equal(clock.timers.size, 0, `${label}: settled timeout should be cleared`);
+ assert.equal(agent._pendingPlans.has(tabId), false, `${label}: timeout should remove the pending tab`);
+ assert.equal(agent.submitPlanResponse(tabId, 'plan-1', 'reject'), false, `${label}: expired plan should reject late responses`);
+ }
+ });
+ });
+});
- const source = fs.readFileSync(path.join(ROOT, sourceRel), 'utf8');
- assert.match(source, /response\.reason === 'plan review timed out' \? 'timeout' : 'cancelled'/, `${label}: timeout should emit an explicit plan resolution`);
- }
+test('plan review: user approval, rejection and cancellation clear the auto-approval timer', async () => {
+ await withPlannerBrowserGlobals(async () => {
+ await withPlanReviewClock(async clock => {
+ for (const [label, AgentClass] of [['chrome', AgentCh], ['firefox', AgentFx]]) {
+ for (const action of ['approve', 'reject', 'cancel']) {
+ const tabId = label === 'chrome' ? 9303 : 9304;
+ const agent = new AgentClass({ getActive: () => ({}) });
+ const updates = [];
+ const waiting = agent._waitForPlanReview(
+ tabId, 'plan-1', { steps: [] }, 'Plan',
+ (type, data) => updates.push({ type, data }),
+ );
+ if (action === 'cancel') agent._cancelPendingPlans(tabId, 'Stopped by user');
+ else assert.equal(agent.submitPlanResponse(tabId, 'plan-1', action, ' Edited plan ', 'verbose'), true);
+
+ const result = await waiting;
+ if (action === 'cancel') {
+ assert.deepEqual(result, { action: 'reject', cancelled: true, reason: 'Stopped by user' }, `${label}: cancellation should remain terminal`);
+ assert.deepEqual(updates.at(-1), { type: 'plan_resolved', data: { planId: 'plan-1', decision: 'cancelled' } }, `${label}: cancellation should invalidate plan cards`);
+ } else {
+ assert.deepEqual(result, { action, editedText: 'Edited plan', markdownMode: 'verbose' }, `${label}: ${action} should retain the user's response`);
+ }
+ assert.equal(clock.timers.size, 0, `${label}: ${action} should clear its timeout`);
+ assert.equal(agent._pendingPlans.has(tabId), false, `${label}: ${action} should remove the pending tab`);
+ assert.equal(agent.submitPlanResponse(tabId, 'plan-1', 'approve'), false, `${label}: ${action} should reject stale responses`);
+ const updateCount = updates.length;
+ await clock.advance(120_000);
+ assert.equal(updates.length, updateCount, `${label}: ${action} must not auto-approve later`);
+ }
+ }
+ });
+ });
+});
+
+test('planner gate: plan timeout proceeds with the approved plan pinned to scratchpad', async () => {
+ await withPlannerBrowserGlobals(async () => {
+ await withPlanReviewClock(async clock => {
+ for (const [label, AgentClass] of [['chrome', AgentCh], ['firefox', AgentFx]]) {
+ const tabId = label === 'chrome' ? 9305 : 9306;
+ const agent = new AgentClass({ getActive: () => ({}) });
+ agent.setPlanBeforeActMode('try');
+ agent.setPlanReviewSettings({ mode: 'always' });
+ agent.conversations.set(tabId, [{ role: 'system', content: 'system' }]);
+ agent._chatWithCostAllowance = async (_provider, messages) => positivePlannerAlignmentFixture(messages)
+ || { content: plannerFixtureJson() };
+ const updates = [];
+ const waiting = agent._maybeRunPlannerGate(
+ tabId, agent.conversations.get(tabId), { role: 'user', content: 'collect account links' },
+ (type, data) => updates.push({ type, data }), 'act', null, null,
+ );
+ for (let i = 0; i < 100 && !updates.some(update => update.type === 'plan_review'); i++) await Promise.resolve();
+ const review = updates.find(update => update.type === 'plan_review')?.data;
+ assert.ok(review?.planId, `${label}: planner should request review`);
+
+ await clock.advance(120_000);
+ const outcome = await waiting;
+ assert.equal(outcome.proceed, true, `${label}: review timeout should continue execution`);
+ assert.equal(outcome.requestKind, 'execute', `${label}: timeout should preserve Act execution`);
+ assert.match(outcome.approvedScratchpadText, /\[Approved plan — pinned by planner\]/, `${label}: timeout should carry the approved handoff`);
+ const messages = agent.conversations.get(tabId);
+ const idx = agent._findScratchpadIndex(messages);
+ assert.ok(idx >= 0, `${label}: timeout should pin the approved plan`);
+ const scratchpad = agent._extractScratchpadBody(messages[idx].content);
+ assert.match(scratchpad, /read_page/, `${label}: timeout should pin verbose tool details`);
+ assert.match(scratchpad, /Scratchpad: yes/, `${label}: timeout should pin the plan's memory strategy`);
+ assert.equal(updates.filter(update => update.type === 'plan_resolved').length, 1, `${label}: timeout should resolve the plan once`);
+ assert.deepEqual(updates.find(update => update.type === 'plan_resolved')?.data, { planId: review.planId, decision: 'approve', source: 'timeout' }, `${label}: timeout should resolve the live review as approved`);
+ assert.equal(agent._pendingPlans.has(tabId), false, `${label}: execution should have no pending review`);
+ assert.equal([...clock.timers.values()].some(timer => timer.delay === 120_000), false, `${label}: execution should have no review timeout`);
+ }
+ });
});
});