Skip to content

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

Fix browser handoff concurrency, persistence and cancellation review findings

Barack Sokullu10c377dfcd82
diff --git a/package.json b/package.json
index 88429458e..e5d61bab5 100644
--- a/package.json
+++ b/package.json
@@ -22,7 +22,7 @@
"test:attachment-drop": "node test/attachment-drop.mjs",
"test:workflow-editor": "node --test test/workflow-editor.mjs",
"test:security": "node test/security/injection-corpus.mjs",
- "test:cloud-bridge-approval": "node --test test/cloud-bridge-approval.mjs test/bot-memory.mjs test/bot-memory-click-guard.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs test/cloud-conversation-isolation.mjs test/cloud-run-outcomes.mjs test/cloud-act-completion.mjs test/cloud-model-recovery.mjs test/private-results.mjs",
+ "test:cloud-bridge-approval": "node --test test/cloud-bridge-approval.mjs test/cloud-handoff.mjs test/bot-memory.mjs test/bot-memory-click-guard.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs test/cloud-conversation-isolation.mjs test/cloud-run-outcomes.mjs test/cloud-act-completion.mjs test/cloud-model-recovery.mjs test/private-results.mjs",
"test:discord": "node --test test/discord-guard.mjs",
"test:toolbar-guard": "node test/rich-text-toolbar-guard.mjs",
"test:pdf-read": "node test/pdf-read.mjs",
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index 0b917e19c..00a126184 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -6870,6 +6870,10 @@ export class Agent extends LoopDetector {
return this._runningTabs.has(tabId);
}
+ hasOtherRunningTabs(tabId) {
+ return [...this._runningTabs].some(other => other !== tabId);
+ }
+
_beginSteeringRun(tabId, onUpdate, runOptions = {}) {
const feedbackRun = this._pageFeedbackRuns?.get(tabId);
if (feedbackRun) feedbackRun.onUpdate = onUpdate;
@@ -19447,6 +19451,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
};
}
+ canPauseAtClarification(tabId, clarifyId) {
+ const entry = this._pendingClarifications.get(tabId)?.get(clarifyId);
+ return entry?.handoffSafe === true && !entry.settled;
+ }
+
/**
* Resolve a pending clarify() tool call with the user's answer. Called by
* background.js when the side panel posts `clarify_response`.
@@ -39267,6 +39276,9 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
restartTimeout: null,
onUpdate,
safeFirst,
+ // Resolving this standalone meta-tool cannot dispatch a page action
+ // before _executeToolBatch reaches the next handoff boundary.
+ handoffSafe: true,
};
// Arm auto-select when Instant (0) or a positive wait; Off (-1) waits forever.
// Instant uses source=auto (user intentionally set auto-approve, e.g. headless).
diff --git a/src/chrome/src/background.js b/src/chrome/src/background.js
index 86eb5cf6e..0c06e9152 100644
--- a/src/chrome/src/background.js
+++ b/src/chrome/src/background.js
@@ -257,8 +257,8 @@ const teacherRunInterlock = createTeacherRunInterlock(teacherSessionStore, {
|| scheduler.isRunning(tabId)
|| cloudRunController.isRunning(tabId),
});
-agent.setRunStartGuard((tabId, context) => {
- cloudRunController.guardRunStart(tabId, context);
+agent.setRunStartGuard(async (tabId, context) => {
+ await cloudRunController.guardRunStart(tabId, context);
return teacherRunInterlock.guardRunStart(tabId);
});
const profileSync = new ProfileSyncManager(chrome.storage.local);
diff --git a/src/chrome/src/cloud-runs.js b/src/chrome/src/cloud-runs.js
index edc51f7ce..5a72f0729 100644
--- a/src/chrome/src/cloud-runs.js
+++ b/src/chrome/src/cloud-runs.js
@@ -693,7 +693,13 @@ export function cloudSafeScheduledJob(job, { strictSecretMode = false } = {}) {
export function buildCloudPersistenceRows(runs) {
const values = Array.isArray(runs) ? [...runs] : [...(runs?.values?.() || [])];
const candidates = values
- .sort((a, b) => String(b?.createdAt || '').localeCompare(String(a?.createdAt || '')))
+ .sort((a, b) => {
+ // Manual control must survive restart even when this task is older than
+ // the retained history or the history fills the storage byte budget.
+ const holdsControl = run => !!run?.handoff && !TERMINAL_STATUSES.has(run.status);
+ return Number(holdsControl(b)) - Number(holdsControl(a))
+ || String(b?.createdAt || '').localeCompare(String(a?.createdAt || ''));
+ })
.slice(0, CLOUD_RUN_LIMIT)
.map(compactCloudRunForPersistence);
const rows = [];
@@ -762,6 +768,7 @@ export function createCloudRunController({
const runs = new Map();
const startingTabs = new Set();
const startingRunIds = new Set();
+ let pendingStarts = 0;
const handoffGates = new Map();
const startingConversations = new Set();
const runAbortControllers = new Map();
@@ -818,7 +825,7 @@ export function createCloudRunController({
if (hydratePromise) return hydratePromise;
hydratePromise = (async () => {
if (!api.storage?.session?.get) return;
- const stored = await api.storage.session.get(CLOUD_RUN_STORAGE_KEY).catch(() => ({}));
+ const stored = await api.storage.session.get(CLOUD_RUN_STORAGE_KEY);
const rows = Array.isArray(stored?.[CLOUD_RUN_STORAGE_KEY]) ? stored[CLOUD_RUN_STORAGE_KEY] : [];
let changed = false;
for (const row of rows) {
@@ -1073,7 +1080,8 @@ export function createCloudRunController({
// survives the rolling 200-update window in exported cloud traces.
run.captchaDiagnostics = { ...scrubbedData, observedAt: run.updatedAt };
}
- if (type === 'clarify' && scrubbedData?.clarifyId && !TERMINAL_STATUSES.has(run.status)) {
+ if (type === 'clarify' && scrubbedData?.clarifyId
+ && ['running', 'needs_user_input', 'pausing', 'paused', 'resuming'].includes(run.status)) {
if (!run.handoff) run.status = 'needs_user_input';
run.pendingInput = scrubbedData;
}
@@ -1129,7 +1137,25 @@ export function createCloudRunController({
return parameters;
}
+ function activeHandoff() {
+ return [...runs.values()].find(run => run.handoff && !TERMINAL_STATUSES.has(run.status));
+ }
+
+ function assertNoHandoff() {
+ if (activeHandoff()) {
+ throw cloudRunError('Browser control belongs to an active handoff. Return control or explicitly reconcile the interrupted run before starting another task.', 409);
+ }
+ }
+
async function startRun(msg = {}) {
+ // Reserve startup before its first await, including model/memory lookup
+ // and helper-tab creation. Handoff cannot grant control during this work.
+ pendingStarts++;
+ try { return await startRunWithReservation(msg); }
+ finally { pendingStarts--; }
+ }
+
+ async function startRunWithReservation(msg = {}) {
const taskMemory = normalizeCloudTaskMemory(msg);
if (taskMemory && msg._workflow) throw cloudRunError('Memory-protected tasks require ordinary guarded browser execution.', 409);
const memoryOwner = await cloudMemoryOwner(taskMemory);
@@ -1161,9 +1187,7 @@ export function createCloudRunController({
async function startRunReserved(msg = {}, startup = null, taskMemory = null, memoryOwner = null) {
await hydrate();
- if ([...runs.values()].some(run => run.handoff && !TERMINAL_STATUSES.has(run.status))) {
- throw cloudRunError('Browser control belongs to an active handoff. Return control or explicitly reconcile the interrupted run before starting another task.', 409);
- }
+ assertNoHandoff();
const recipient = msg.private_result_public_key == null
? null : await importPrivateResultRecipient(msg.private_result_public_key);
const suppliedRunId = msg.runId ?? msg.run_id;
@@ -1268,6 +1292,7 @@ export function createCloudRunController({
if (conversationKey) await agent.clearConversation(tabId);
const targetTab = await api.tabs.get(tabId);
await activateTab(targetTab);
+ assertNoHandoff();
} catch (error) {
startingTabs.delete(tabId);
startingRunIds.delete(runId);
@@ -1758,14 +1783,27 @@ export function createCloudRunController({
const run = runs.get(msg.runId || msg.run_id);
if (!run) throw cloudRunError('Unknown cloud run.', 404);
if (run.workflowId) throw cloudRunError('Saved workflow replay does not support browser handoff.', 409);
- if (run.handoff) return cloudSnapshot(run);
+ if (run.handoff) {
+ // A duplicate pause must not expose a checkpoint still being written.
+ await persistQueue;
+ return cloudSnapshot(run);
+ }
if (!['running', 'needs_user_input'].includes(run.status)) throw cloudRunError('Only a running browser task can be paused.', 409);
+ if (pendingStarts || [...runs.values()].some(other => other !== run && !TERMINAL_STATUSES.has(other.status))
+ || agent.hasOtherRunningTabs?.(run.tabId)) {
+ throw cloudRunError('Another agent is running or starting in this browser. Wait for it to finish before taking control.', 409);
+ }
const waitingClarification = run.status === 'needs_user_input' && !!run.pendingInput;
+ if (waitingClarification && agent.canPauseAtClarification?.(run.tabId,
+ run.pendingInput.clarifyId || run.pendingInput.clarify_id) !== true) {
+ throw cloudRunError('Answer the pending action approval before taking control; its browser action has not settled yet.', 409);
+ }
const gate = handoffGates.get(run.runId);
if (!gate) throw cloudRunError('The active browser run is unavailable for handoff.', 409);
await gate.request();
if (waitingClarification) {
- // clarify() is a known read-only wait: no page action is in flight.
+ // Only standalone clarify() is a safe wait; internal action approvals
+ // may continue a page mutation before the next tool boundary.
// Keep its question pending; handback is not a clarification response.
if (typeof agent._persistNow === 'function') {
const saved = await agent._persistNow(run.tabId);
@@ -1876,8 +1914,14 @@ export function createCloudRunController({
return {
runs,
- guardRunStart(_tabId, { kind } = {}) {
- if (kind !== 'cloud' && [...runs.values()].some(run => run.handoff && !TERMINAL_STATUSES.has(run.status))) {
+ async guardRunStart(tabId, { kind } = {}) {
+ // A scheduled/sidebar run can arrive before any Cloud status request.
+ // Restore the persisted handoff before letting it touch the browser.
+ await hydrate();
+ const owner = activeHandoff();
+ const settlingOwner = kind === 'cloud' && owner?.tabId === tabId
+ && owner.handoff?.state === 'pausing' && !owner.handoff.interrupted;
+ if (owner && !settlingOwner) {
throw cloudRunError('The browser is reserved for manual control. Return control or reconcile the interrupted handoff before starting an agent.', 409);
}
},
diff --git a/src/chrome/src/offscreen/cloud-bridge.js b/src/chrome/src/offscreen/cloud-bridge.js
index c8f9a2060..94ccf6b46 100644
--- a/src/chrome/src/offscreen/cloud-bridge.js
+++ b/src/chrome/src/offscreen/cloud-bridge.js
@@ -21,8 +21,8 @@
'cloud_scheduled_jobs',
'cloud_respond',
'cloud_abort',
- 'cloud_pause',
- 'cloud_resume',
+ 'cloud_pause',
+ 'cloud_resume',
]);
let socket = null;
let bridgeUrl = null;
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index f6227f84a..a79251536 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -6573,6 +6573,10 @@ export class Agent extends LoopDetector {
return this._runningTabs.has(tabId);
}
+ hasOtherRunningTabs(tabId) {
+ return [...this._runningTabs].some(other => other !== tabId);
+ }
+
_beginSteeringRun(tabId, onUpdate, runOptions = {}) {
const feedbackRun = this._pageFeedbackRuns?.get(tabId);
if (feedbackRun) feedbackRun.onUpdate = onUpdate;
@@ -17033,6 +17037,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
};
}
+ canPauseAtClarification(tabId, clarifyId) {
+ const entry = this._pendingClarifications.get(tabId)?.get(clarifyId);
+ return entry?.handoffSafe === true && !entry.settled;
+ }
+
/**
* Resolve a pending clarify() tool call with the user's answer. Called by
* background.js when the side panel posts `clarify_response`.
@@ -35770,6 +35779,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
restartTimeout: null,
onUpdate,
safeFirst,
+ // Resolving this standalone meta-tool cannot dispatch a page action
+ // before _executeToolBatch reaches the next handoff boundary.
+ handoffSafe: true,
};
// Arm auto-select when Instant (0) or a positive wait; Off (-1) waits forever.
// Instant uses source=auto (user intentionally set auto-approve, e.g. headless).
diff --git a/src/firefox/src/background.js b/src/firefox/src/background.js
index 987fd4a52..993feed09 100644
--- a/src/firefox/src/background.js
+++ b/src/firefox/src/background.js
@@ -198,8 +198,8 @@ const teacherRunInterlock = createTeacherRunInterlock(teacherSessionStore, {
|| scheduler.isRunning(tabId)
|| cloudRunController.isRunning(tabId),
});
-agent.setRunStartGuard((tabId, context) => {
- cloudRunController.guardRunStart(tabId, context);
+agent.setRunStartGuard(async (tabId, context) => {
+ await cloudRunController.guardRunStart(tabId, context);
return teacherRunInterlock.guardRunStart(tabId);
});
const profileSync = new ProfileSyncManager(browser.storage.local);
diff --git a/src/firefox/src/cloud-runs.js b/src/firefox/src/cloud-runs.js
index f5572e75c..c2716079d 100644
--- a/src/firefox/src/cloud-runs.js
+++ b/src/firefox/src/cloud-runs.js
@@ -693,7 +693,13 @@ export function cloudSafeScheduledJob(job, { strictSecretMode = false } = {}) {
export function buildCloudPersistenceRows(runs) {
const values = Array.isArray(runs) ? [...runs] : [...(runs?.values?.() || [])];
const candidates = values
- .sort((a, b) => String(b?.createdAt || '').localeCompare(String(a?.createdAt || '')))
+ .sort((a, b) => {
+ // Manual control must survive restart even when this task is older than
+ // the retained history or the history fills the storage byte budget.
+ const holdsControl = run => !!run?.handoff && !TERMINAL_STATUSES.has(run.status);
+ return Number(holdsControl(b)) - Number(holdsControl(a))
+ || String(b?.createdAt || '').localeCompare(String(a?.createdAt || ''));
+ })
.slice(0, CLOUD_RUN_LIMIT)
.map(compactCloudRunForPersistence);
const rows = [];
@@ -764,6 +770,7 @@ export function createCloudRunController({
const runs = new Map();
const startingTabs = new Set();
const startingRunIds = new Set();
+ let pendingStarts = 0;
const handoffGates = new Map();
const startingConversations = new Set();
const runAbortControllers = new Map();
@@ -819,7 +826,7 @@ export function createCloudRunController({
if (hydratePromise) return hydratePromise;
hydratePromise = (async () => {
if (!api.storage?.session?.get) return;
- const stored = await api.storage.session.get(CLOUD_RUN_STORAGE_KEY).catch(() => ({}));
+ const stored = await api.storage.session.get(CLOUD_RUN_STORAGE_KEY);
const rows = Array.isArray(stored?.[CLOUD_RUN_STORAGE_KEY]) ? stored[CLOUD_RUN_STORAGE_KEY] : [];
let changed = false;
for (const row of rows) {
@@ -1074,7 +1081,8 @@ export function createCloudRunController({
// survives the rolling 200-update window in exported cloud traces.
run.captchaDiagnostics = { ...scrubbedData, observedAt: run.updatedAt };
}
- if (type === 'clarify' && scrubbedData?.clarifyId && !TERMINAL_STATUSES.has(run.status)) {
+ if (type === 'clarify' && scrubbedData?.clarifyId
+ && ['running', 'needs_user_input', 'pausing', 'paused', 'resuming'].includes(run.status)) {
if (!run.handoff) run.status = 'needs_user_input';
run.pendingInput = scrubbedData;
}
@@ -1130,7 +1138,25 @@ export function createCloudRunController({
return parameters;
}
+ function activeHandoff() {
+ return [...runs.values()].find(run => run.handoff && !TERMINAL_STATUSES.has(run.status));
+ }
+
+ function assertNoHandoff() {
+ if (activeHandoff()) {
+ throw cloudRunError('Browser control belongs to an active handoff. Return control or explicitly reconcile the interrupted run before starting another task.', 409);
+ }
+ }
+
async function startRun(msg = {}) {
+ // Reserve startup before its first await, including model/memory lookup
+ // and helper-tab creation. Handoff cannot grant control during this work.
+ pendingStarts++;
+ try { return await startRunWithReservation(msg); }
+ finally { pendingStarts--; }
+ }
+
+ async function startRunWithReservation(msg = {}) {
const taskMemory = normalizeCloudTaskMemory(msg);
if (taskMemory && msg._workflow) throw cloudRunError('Memory-protected tasks require ordinary guarded browser execution.', 409);
const memoryOwner = await cloudMemoryOwner(taskMemory);
@@ -1162,9 +1188,7 @@ export function createCloudRunController({
async function startRunReserved(msg = {}, startup = null, taskMemory = null, memoryOwner = null) {
await hydrate();
- if ([...runs.values()].some(run => run.handoff && !TERMINAL_STATUSES.has(run.status))) {
- throw cloudRunError('Browser control belongs to an active handoff. Return control or explicitly reconcile the interrupted run before starting another task.', 409);
- }
+ assertNoHandoff();
const recipient = msg.private_result_public_key == null
? null : await importPrivateResultRecipient(msg.private_result_public_key);
const suppliedRunId = msg.runId ?? msg.run_id;
@@ -1269,6 +1293,7 @@ export function createCloudRunController({
if (conversationKey) await agent.clearConversation(tabId);
const targetTab = await api.tabs.get(tabId);
await activateTab(targetTab);
+ assertNoHandoff();
} catch (error) {
startingTabs.delete(tabId);
startingRunIds.delete(runId);
@@ -1759,14 +1784,27 @@ export function createCloudRunController({
const run = runs.get(msg.runId || msg.run_id);
if (!run) throw cloudRunError('Unknown cloud run.', 404);
if (run.workflowId) throw cloudRunError('Saved workflow replay does not support browser handoff.', 409);
- if (run.handoff) return cloudSnapshot(run);
+ if (run.handoff) {
+ // A duplicate pause must not expose a checkpoint still being written.
+ await persistQueue;
+ return cloudSnapshot(run);
+ }
if (!['running', 'needs_user_input'].includes(run.status)) throw cloudRunError('Only a running browser task can be paused.', 409);
+ if (pendingStarts || [...runs.values()].some(other => other !== run && !TERMINAL_STATUSES.has(other.status))
+ || agent.hasOtherRunningTabs?.(run.tabId)) {
+ throw cloudRunError('Another agent is running or starting in this browser. Wait for it to finish before taking control.', 409);
+ }
const waitingClarification = run.status === 'needs_user_input' && !!run.pendingInput;
+ if (waitingClarification && agent.canPauseAtClarification?.(run.tabId,
+ run.pendingInput.clarifyId || run.pendingInput.clarify_id) !== true) {
+ throw cloudRunError('Answer the pending action approval before taking control; its browser action has not settled yet.', 409);
+ }
const gate = handoffGates.get(run.runId);
if (!gate) throw cloudRunError('The active browser run is unavailable for handoff.', 409);
await gate.request();
if (waitingClarification) {
- // clarify() is a known read-only wait: no page action is in flight.
+ // Only standalone clarify() is a safe wait; internal action approvals
+ // may continue a page mutation before the next tool boundary.
// Keep its question pending; handback is not a clarification response.
if (typeof agent._persistNow === 'function') {
const saved = await agent._persistNow(run.tabId);
@@ -1874,8 +1912,14 @@ export function createCloudRunController({
return {
runs,
- guardRunStart(_tabId, { kind } = {}) {
- if (kind !== 'cloud' && [...runs.values()].some(run => run.handoff && !TERMINAL_STATUSES.has(run.status))) {
+ async guardRunStart(tabId, { kind } = {}) {
+ // A scheduled/sidebar run can arrive before any Cloud status request.
+ // Restore the persisted handoff before letting it touch the browser.
+ await hydrate();
+ const owner = activeHandoff();
+ const settlingOwner = kind === 'cloud' && owner?.tabId === tabId
+ && owner.handoff?.state === 'pausing' && !owner.handoff.interrupted;
+ if (owner && !settlingOwner) {
throw cloudRunError('The browser is reserved for manual control. Return control or reconcile the interrupted handoff before starting an agent.', 409);
}
},
diff --git a/test/cloud-bridge-approval.mjs b/test/cloud-bridge-approval.mjs
index 038ab31d6..35ca8c486 100644
--- a/test/cloud-bridge-approval.mjs
+++ b/test/cloud-bridge-approval.mjs
@@ -224,6 +224,32 @@ function fxHarness({ WebSocketImpl, dispatch } = {}) {
}
for (const build of ['chrome', 'firefox']) {
+ test(`${build}: handoff commands require approval and preserve their run and note payload`, async () => {
+ const h = build === 'chrome' ? harness() : fxHarness();
+ const calls = build === 'chrome' ? h.runtimeCalls : h.calls;
+ if (build === 'chrome') h.start();
+ else h.bridge.start({ url: 'ws://127.0.0.1:17374/extension', ...IDENTITY });
+ const socket = h.sockets[0];
+ socket.emit('open');
+ assert.equal(socket.sent[0].capabilities.includes('run_handoff_v1'), true);
+ try {
+ for (const action of ['cloud_pause', 'cloud_resume']) {
+ await socket.receive({ id: `unapproved-${action}`, action, payload: { runId: 'r1' } });
+ assert.equal(socket.sent.find(reply => reply.id === `unapproved-${action}`).status, 403);
+ }
+ assert.equal(calls.length, 0);
+ await socket.receive({ type: 'connection_approved', browserId: IDENTITY.browserId });
+ await socket.receive({ id: 'pause', action: 'cloud_pause', payload: { runId: 'r1' } });
+ await socket.receive({ id: 'resume', action: 'cloud_resume', payload: { runId: 'r1', note: 'I signed in' } });
+ assert.deepEqual(calls.map(call => ({ ...call })), [
+ { runId: 'r1', target: 'background', action: 'cloud_pause' },
+ { runId: 'r1', note: 'I signed in', target: 'background', action: 'cloud_resume' },
+ ]);
+ assert.equal(socket.sent.find(reply => reply.id === 'pause').ok, true);
+ assert.equal(socket.sent.find(reply => reply.id === 'resume').ok, true);
+ } finally { if (build === 'firefox') h.bridge.stop(); }
+ });
+
test(`${build}: malformed JSON envelopes get a reply and cannot break the approved bridge`, async () => {
const h = build === 'chrome' ? harness() : fxHarness();
if (build === 'chrome') h.start();
diff --git a/test/cloud-handoff.mjs b/test/cloud-handoff.mjs
index f79156c83..a68c49fe2 100644
--- a/test/cloud-handoff.mjs
+++ b/test/cloud-handoff.mjs
@@ -16,7 +16,7 @@ globalThis.chrome = globalThis.browser = {
for (const browser of ['chrome', 'firefox']) {
const { CloudHandoffGate } = await import(`../src/${browser}/src/agent/cloud-handoff.js`);
- const { createCloudRunController } = await import(`../src/${browser}/src/cloud-runs.js`);
+ const { createCloudRunController, buildCloudPersistenceRows } = await import(`../src/${browser}/src/cloud-runs.js`);
const { Agent } = await import(`../src/${browser}/src/agent/agent.js`);
function harness(processMessage) {
@@ -24,7 +24,8 @@ for (const browser of ['chrome', 'firefox']) {
const api = { storage: { session: { get: async key => ({ [key]: structuredClone(stored[key]) }), set: async data => Object.assign(stored, structuredClone(data)) } },
tabs: { get: async id => ({ id, url: 'https://example.com/' }), query: async () => [{ id: 7, url: 'https://example.com/' }], update: async () => {} } };
let clarificationResolve;
- const agent = { isRunning: () => false, strictSecretMode: true, processMessage, abort() {}, _persistNow: async () => ({ ok: true }),
+ const agent = { isRunning: () => false, hasOtherRunningTabs: () => false, canPauseAtClarification: () => true,
+ strictSecretMode: true, processMessage, abort() {}, _persistNow: async () => ({ ok: true }),
submitClarifyResponse(_tab, _id, answer) { clarificationResolve?.(answer); return true; } };
let seq = 0;
const controller = createCloudRunController({ chromeApi: api, agent, makeRunId: () => `run_handoff_${++seq}`, ensureOffscreen: async () => {} });
@@ -77,11 +78,11 @@ for (const browser of ['chrome', 'firefox']) {
await assert.rejects(restarted.resume({ runId: run.runId }), error => error.status === 409);
await assert.rejects(restarted.startRun({ task: 'Another bot' }), error => error.status === 409);
await assert.rejects(restarted.startRun({ task: 'Another bot in another tab', tabId: 8 }), error => error.status === 409);
- for (const kind of ['scheduled', 'interactive']) assert.throws(() => restarted.guardRunStart(8, { kind }), error => error.status === 409);
+ for (const kind of ['scheduled', 'interactive', 'cloud']) await assert.rejects(restarted.guardRunStart(8, { kind }), error => error.status === 409);
assert.equal(calls, 1, 'neither restart nor Hand back replays the old task');
assert.equal((await restarted.abort({ runId: run.runId })).status, 'aborted');
assert.equal(restarted.isRunning(7), false);
- assert.doesNotThrow(() => restarted.guardRunStart(8, { kind: 'scheduled' }));
+ await restarted.guardRunStart(8, { kind: 'scheduled' });
await h.controller.abort({ runId: run.runId });
});
@@ -197,10 +198,119 @@ for (const browser of ['chrome', 'firefox']) {
await h.controller.pause({ runId: run.runId }); ready.resolve(); await writing.promise;
let exposed = false;
const status = h.controller.status({ runId: run.runId }).then(value => { exposed = true; return value; });
+ let pauseExposed = false;
+ const repeatPause = h.controller.pause({ runId: run.runId }).then(value => { pauseExposed = true; return value; });
await tick(); assert.equal(exposed, false, 'the viewer does not get control until the checkpoint is durable');
+ assert.equal(pauseExposed, false, 'repeating Take over also waits for the checkpoint');
written.resolve(); assert.equal((await status).status, 'paused');
+ assert.equal((await repeatPause).status, 'paused');
await h.controller.abort({ runId: run.runId });
await until(() => h.controller.runs.get(run.runId).status === 'aborted');
assert.equal(h.controller.isRunning(7), false);
});
+
+ test(`${browser}: another Cloud startup prevents handoff until it settles`, async () => {
+ const pending = deferred(), entered = deferred(), done = deferred();
+ let started = 0;
+ const h = harness(async (_tab, _task, _update, _mode, _attachments, options) => {
+ started++; await done.promise; options.onRunFinished('done'); return 'Read';
+ });
+ const run = await h.controller.startRun({ task: 'Read', tabId: 7 });
+ const get = h.api.tabs.get;
+ h.api.tabs.get = async id => { if (id === 8) { entered.resolve(); await pending.promise; } return get(id); };
+ const second = h.controller.startRun({ task: 'Read in another tab', tabId: 8 });
+ await entered.promise;
+ try {
+ await assert.rejects(h.controller.pause({ runId: run.runId }), error => error.status === 409);
+ assert.equal(h.controller.runs.get(run.runId).handoff, undefined);
+ } finally { pending.resolve(); await second; done.resolve(); }
+ await until(() => [...h.controller.runs.values()].every(value => value.status === 'completed'));
+ assert.equal(started, 2);
+ });
+
+ test(`${browser}: other active Cloud or native tabs prevent manual control`, async () => {
+ const done = deferred();
+ const h = harness(async (_tab, _task, _update, _mode, _attachments, options) => {
+ await done.promise; options.onRunFinished('done'); return 'Read';
+ });
+ const run = await h.controller.startRun({ task: 'Read', tabId: 7 });
+ const other = await h.controller.startRun({ task: 'Read', tabId: 8 });
+ try {
+ await assert.rejects(h.controller.pause({ runId: run.runId }), error => error.status === 409);
+ h.controller.runs.get(other.runId).status = 'completed';
+ h.agent.hasOtherRunningTabs = id => id === 7;
+ await assert.rejects(h.controller.pause({ runId: run.runId }), error => error.status === 409);
+ assert.equal(h.controller.runs.get(run.runId).handoff, undefined);
+ } finally { done.resolve(); }
+ await until(() => h.controller.runs.get(run.runId).status === 'completed');
+ });
+
+ test(`${browser}: startup guards hydrate interrupted handoffs before permitting any agent`, async () => {
+ const h = harness(async () => assert.fail('No new run should start'));
+ h.stored.webbrainCloudRunSnapshots = [{ runId: 'old', tabId: 7, status: 'paused', createdAt: '2020-01-01',
+ handoff: { state: 'paused', resumable: true, interrupted: false } }];
+ for (const kind of ['cloud', 'scheduled', 'interactive']) {
+ await assert.rejects(h.controller.guardRunStart(8, { kind }), error => error.status === 409);
+ }
+ assert.equal(h.controller.isRunning(7), true);
+ await h.controller.abort({ runId: 'old' });
+ await h.controller.guardRunStart(8, { kind: 'interactive' });
+ });
+
+ test(`${browser}: unavailable persisted state cannot silently authorize a new agent`, async () => {
+ const h = harness(async () => assert.fail('No run should start'));
+ h.api.storage.session.get = async () => { throw new Error('Session storage unavailable'); };
+ await assert.rejects(h.controller.guardRunStart(8, { kind: 'interactive' }), /Session storage unavailable/);
+ await assert.rejects(h.controller.startRun({ task: 'Read' }), /Session storage unavailable/);
+ assert.equal(h.controller.runs.size, 0);
+ });
+
+ test(`${browser}: history limits cannot evict an old active handoff`, () => {
+ const handoff = { runId: 'old-paused', tabId: 7, status: 'paused', createdAt: '2000-01-01',
+ handoff: { state: 'paused', resumable: true, interrupted: false } };
+ const history = Array.from({ length: 60 }, (_, index) => ({ runId: `history-${index}`, status: 'completed',
+ createdAt: `2026-01-01T00:00:${String(index).padStart(2, '0')}Z` }));
+ const rows = buildCloudPersistenceRows([...history, handoff]);
+ assert.equal(rows.length, 50);
+ assert.equal(rows[0].runId, 'old-paused');
+ assert.equal(rows[0].handoff.state, 'paused');
+ });
+
+ test(`${browser}: internal permission waits cannot acknowledge an unsettled action`, async () => {
+ const answer = deferred(); let posted = false;
+ const h = harness(async (_tab, _task, update, _mode, _attachments, options) => {
+ update('clarify', { clarifyId: 'submit-form', promptKind: 'submitConfirmation', question: 'Submit?', options: ['once', 'deny'] });
+ await answer.promise; posted = true; options.onRunFinished('done'); return 'Submitted';
+ });
+ h.agent.canPauseAtClarification = () => false;
+ h.setClarificationResolver(() => answer.resolve());
+ const run = await h.controller.startRun({ task: 'Submit the form' });
+ await until(() => h.controller.runs.get(run.runId).status === 'needs_user_input');
+ await assert.rejects(h.controller.pause({ runId: run.runId }), error => error.status === 409);
+ assert.equal(h.controller.runs.get(run.runId).handoff, undefined);
+ assert.equal(posted, false);
+ await h.controller.respond({ runId: run.runId, clarifyId: 'submit-form', answer: 'once' });
+ await until(() => h.controller.runs.get(run.runId).status === 'completed');
+ assert.equal(posted, true);
+ });
+
+ test(`${browser}: native standalone clarification is safe but native form approval is not`, async () => {
+ const provider = { name: 'test', model: 'test' };
+ const agent = new Agent({ getActive: () => provider });
+ agent.clarifyTimeoutSec = -1;
+ const ready = deferred(); let question, approval;
+ const standalone = agent._executeToolImpl(7, 'clarify', { question: 'Have you signed in?', options: ['Yes', 'Stop'] },
+ (type, data) => { if (type === 'clarify') { question = data; ready.resolve(); } });
+ const form = agent._promptSubmitConfirmation(7, { host: 'example.com', summary: 'Submit this form' },
+ (type, data) => { if (type === 'clarify') approval = data; });
+ try {
+ await ready.promise;
+ assert.equal(agent.canPauseAtClarification(7, question.clarifyId), true);
+ assert.equal(agent.canPauseAtClarification(7, approval.clarifyId), false);
+ } finally { agent._cancelClarifications(7, 'Fixture cleanup'); await Promise.all([standalone, form]); }
+ assert.equal(agent.canPauseAtClarification(7, question.clarifyId), false);
+ agent._runningTabs.add(8);
+ assert.equal(agent.hasOtherRunningTabs(7), true);
+ assert.equal(agent.hasOtherRunningTabs(8), false);
+ });
}