Open-source AI browser agent for Chrome and Firefox (monorepo) ðŸ§
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
Keep Cloud continuations tracked and report actual completion outcomes
Barack Sokullu8e32033ce193
diff --git a/package.json b/package.jsonindex d7ac613dc..f847e7148 100644--- a/package.json+++ b/package.json@@ -16,7 +16,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/cloud-conversation-isolation.mjs",+ "test:cloud-bridge-approval": "node --test test/cloud-bridge-approval.mjs test/cloud-conversation-isolation.mjs test/cloud-run-outcomes.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.jsindex a36ff7e79..c48f0833f 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -30997,7 +30997,8 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai}async _scheduleAutoProgressResume(tabId, onUpdate = () => {}) {- if (!this.scheduler) return null;+ const cloudResume = this.cloudRunContexts.get(tabId)?.deferResume;+ if (!this.scheduler && !cloudResume) return null;const mode = this._effectiveRunMode(tabId);if (!this._isActionMode(mode)) return null;if (!this._shouldBlockDoneForProgress(tabId)) return null;@@ -31005,16 +31006,17 @@ If the user has already named or confirmed this exact recipient, do NOT ask agaiconst { tabUrl, tabTitle } = await this._getTabUrlTitle(tabId);let result;try {- result = await this.scheduler.createResumeJob({+ const args = {+ after_seconds: 90,+ reason: 'The active progress-ledger task hit consecutive stalled model outputs before finishing.',+ resume_instruction: this._buildAutoProgressResumeInstruction(tabId),+ };+ result = cloudResume ? await cloudResume(args) : await this.scheduler.createResumeJob({tabId,conversationId: this.conversationIds.get(tabId) || null,resumeTaskId: this._resumeTaskId(tabId, { create: true }),mode,- args: {- after_seconds: 90,- reason: 'The active progress-ledger task hit consecutive stalled model outputs before finishing.',- resume_instruction: this._buildAutoProgressResumeInstruction(tabId),- },+ args,currentUrl: tabUrl,currentTitle: tabTitle,});@@ -34263,6 +34265,8 @@ If the user has already named or confirmed this exact recipient, do NOT ask agaireturn await this._inspectDevEventListeners(tabId, args || {});}if (name === 'schedule_resume') {+ const cloudResume = this.cloudRunContexts.get(tabId)?.deferResume;+ if (cloudResume) return cloudResume(this._resumeArgsWithProgressGuard(tabId, args || {}));if (!this.scheduler) {return {success: false,@@ -42211,7 +42215,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agaielse this._runProviderOverrides.delete(tabId);const previousCloudContext = this.cloudRunContexts.get(tabId);if (runOptions.cloudRun) {- this.cloudRunContexts.set(tabId, { outputSchema: runOptions.outputSchema ?? null, schemaRepairUsed: false });+ this.cloudRunContexts.set(tabId, { outputSchema: runOptions.outputSchema ?? null, schemaRepairUsed: false, deferResume: runOptions.deferResume });}try {if ((mode === 'act' || mode === 'dev') && !this._isStandaloneChatRun(runOptions)) {@@ -43771,6 +43775,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agaishareRequest = messages;}} catch {}+ runOptions.onRunFinished?.(_traceStatus);await this._endTraceRun(tabId, runId, _traceStatus, finalResponse, { provider, messages, mode, shareRequest, shareResponse: shareRawResponse, hadProviderCompletion: shareHadProviderCompletion });}}@@ -43825,7 +43830,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agaielse this._runProviderOverrides.delete(tabId);const previousCloudContext = this.cloudRunContexts.get(tabId);if (runOptions.cloudRun) {- this.cloudRunContexts.set(tabId, { outputSchema: runOptions.outputSchema ?? null, schemaRepairUsed: false });+ this.cloudRunContexts.set(tabId, { outputSchema: runOptions.outputSchema ?? null, schemaRepairUsed: false, deferResume: runOptions.deferResume });}try {if ((mode === 'act' || mode === 'dev') && !this._isStandaloneChatRun(runOptions)) {@@ -44864,6 +44869,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agaishareRequest = this._pruneOldImages(modelMessagesForRun(), provider);}} catch {}+ runOptions.onRunFinished?.(_traceStatus);await this._endTraceRun(tabId, runId, _traceStatus, finalResponse, { provider, messages, mode, shareRequest, shareResponse: shareRawResponse, hadProviderCompletion: shareHadProviderCompletion });}}diff --git a/src/chrome/src/cloud-runs.js b/src/chrome/src/cloud-runs.jsindex 9f39e1525..afa75a63c 100644--- a/src/chrome/src/cloud-runs.js+++ b/src/chrome/src/cloud-runs.js@@ -4,6 +4,7 @@ import {normalizeSavedWorkflow,} from './agent/workflows.js';import { isCredentialField } from './agent/credential-fields.js';+import { validateResumeArgs } from './agent/scheduler.js';const DEFAULT_CLOUD_BRIDGE_URL = 'ws://127.0.0.1:17374/extension';const CLOUD_RUN_STORAGE_KEY = 'webbrainCloudRunSnapshots';@@ -694,6 +695,7 @@ export function createCloudRunController({workflowTrace = null,now = () => new Date(),makeRunId = () => `run_${globalThis.crypto.randomUUID()}`,+ waitForResume = ms => new Promise(resolve => setTimeout(resolve, ms)),} = {}) {const api = chromeApi;const runs = new Map();@@ -883,12 +885,10 @@ export function createCloudRunController({return redactWorkflowRuntimeValues(withoutSecrets, known, '[redacted strict URL]');}- // Terminal prose reaches the caller by the same two routes as an update row,- // so it takes both secret and trace-only URL redaction. A structured- // `run.result` is handled separately below and takes only credential-value- // redaction so ordinary schema-valid URL components remain usable.+ // Answers retain ordinary article links. Credentials remain value-redacted;+ // trace updates still withhold page URLs and arbitrary tool payloads.function redactStrictTerminal(run, value, strictSecretMode) {- return redactStrictTraceValues(run, value, strictSecretMode);+ return redactStrictSecretValues(run, value, strictSecretMode);}function pushUpdate(run, type, data, runtimeValues = []) {@@ -935,7 +935,7 @@ export function createCloudRunController({// with every string and number replaced by a placeholder, which satisfies// strict mode by making the run useless.const publicSummary = strictSecretMode- ? redactStrictTraceValues(run, result.summary, true)+ ? redactStrictSecretValues(run, result.summary, true): safeResult.summary;if (result.cloudFailed) {run.status = 'failed';@@ -948,6 +948,11 @@ export function createCloudRunController({run.summary = publicSummary || run.summary;}}+ if (type === 'tool_result' && ['done', 'done_json'].includes(data?.name)+ && ['partial', 'failed', 'blocked'].includes(data?.result?.outcome)) {+ run.agentOutcome = data.result.outcome;+ }+ if (type === 'run_status' && data?.status) run.agentOutcome = data.status;if (type === 'captcha_gate') {// Keep the latest sanitized frame/vendor snapshot at run level so it// survives the rolling 200-update window in exported cloud traces.@@ -1066,7 +1071,7 @@ export function createCloudRunController({: String(msg.task || msg.text || '').trim();if (!task) throw new Error('cloud_run requires `task`.');if (startingTabs.has(tabId) || agent.isRunning(tabId)) {- throw new Error(`Tab ${tabId} already has an active WebBrain run.`);+ throw cloudRunError('This browser tab is busy with another run. Wait for it to finish.', 409);}const apiMutationsAllowed = msg.apiMutationsAllowed === true || msg.api_mutations_allowed === true;@@ -1140,7 +1145,7 @@ export function createCloudRunController({// agent's active-run map cannot identify the parent here. The cloud// run record keeps the actual trace id; resolve its session from that// trace instead of attaching the tab's potentially unrelated session.- const parentTraceRunId = parentRun?.traceRunId || null;+ let parentTraceRunId = parentRun?.traceRunId || null;let parentTraceSessionId = null;if (parentTraceRunId && typeof workflowTrace?.getRun === 'function') {try {@@ -1212,18 +1217,62 @@ export function createCloudRunController({);}} else {- content = await agent.processMessage(tabId, task, publishUpdate, mode, [], {- cloudRun: true,- independentRun: true,- apiMutationsDenied: mode === 'ask',- outputSchema,- onTraceStarted(traceRunId) {- run.traceRunId = traceRunId;- schedulePersist();- },- parentRunId: parentTraceRunId,- parentSessionId: parentTraceSessionId,- });+ let prompt = task;+ let continuation = false;+ let resumeCount = 0;+ do {+ let requestedResume = null;+ run.agentOutcome = null;+ content = await agent.processMessage(tabId, prompt, publishUpdate, mode, [], {+ cloudRun: true,+ independentRun: !continuation,+ trustedContinuation: continuation,+ apiMutationsDenied: mode === 'ask',+ outputSchema,+ deferResume(args) {+ if (resumeCount >= 3) return { success: false, dispatched: false, noDispatch: true,+ error: 'Cloud continuation limit reached. Return an honest partial or failed outcome.' };+ const parsed = validateResumeArgs(args, now().getTime());+ if (!parsed.ok) return { success: false, dispatched: false, noDispatch: true, error: parsed.error };+ // No browser-native alarm: it would run outside this Cloud handle,+ // releasing the workspace lock and allowing the profile to pause.+ requestedResume = parsed;+ return { success: true, scheduled: true, done: true, jobId: run.runId,+ scheduledAt: parsed.scheduledAt, summary: `Scheduled a resume for ${parsed.scheduledAt}.` };+ },+ onRunFinished(status) {+ // An explicit failed/partial done outcome overrides generic 'done'.+ if (!['partial', 'failed', 'blocked'].includes(run.agentOutcome)) run.agentOutcome = status;+ },+ onTraceStarted(traceRunId) {+ run.traceRunId = traceRunId;+ schedulePersist();+ },+ parentRunId: parentTraceRunId,+ parentSessionId: parentTraceSessionId,+ });+ if (!requestedResume || ['failed', 'aborting', 'aborted'].includes(run.status)) break;+ resumeCount++;+ pushUpdate(run, 'cloud_resume_wait', { status: 'waiting', scheduledAt: requestedResume.scheduledAt, attempt: resumeCount });+ // Keep the same run, tab reservation, permission scope and secret+ // registries until completion or confirmed cancellation. Polls keep+ // the worker alive; a worker restart fails safely instead of replaying.+ await persist();+ while (run.status !== 'aborting' && now().getTime() < requestedResume.scheduledAtMs) {+ await waitForResume(Math.min(1000, requestedResume.scheduledAtMs - now().getTime()));+ }+ if (run.status === 'aborting') break;+ parentTraceRunId = run.traceRunId;+ parentTraceSessionId = null;+ if (parentTraceRunId && typeof workflowTrace?.getRun === 'function') {+ try {+ parentTraceSessionId = (await workflowTrace.getRun(parentTraceRunId))?.conversationId || null;+ } catch { /* lineage lookup must not fail a continuation */ }+ }+ prompt = requestedResume.resumeInstruction;+ continuation = true;+ pushUpdate(run, 'cloud_resume_wait', { status: 'resuming', attempt: resumeCount });+ } while (true);}run.pendingInput = null;// Terminal fields are published over the bridge and persisted just like@@ -1241,7 +1290,11 @@ export function createCloudRunController({run.status = 'aborted';run.error = run.error || 'Aborted by cloud_abort.';} else if (run.status !== 'failed') {- if (structured && run.result === undefined) {+ if (run.agentOutcome && run.agentOutcome !== 'done') {+ run.status = run.agentOutcome === 'cancelled' ? 'aborted' : 'failed';+ run.error = `Browser task did not finish successfully (${run.agentOutcome}). Review the returned result before retrying.`;+ if (!structured) run.result = run.content;+ } else if (structured && run.result === undefined) {run.status = 'failed';run.error = 'Structured cloud run finished without a valid done_json result.';} else {diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex 668b911b0..35f6ef9fd 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -28616,7 +28616,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}async _scheduleAutoProgressResume(tabId, onUpdate = () => {}) {- if (!this.scheduler) return null;+ const cloudResume = this.cloudRunContexts.get(tabId)?.deferResume;+ if (!this.scheduler && !cloudResume) return null;const mode = this._effectiveRunMode(tabId);if (!this._isActionMode(mode)) return null;if (!this._shouldBlockDoneForProgress(tabId)) return null;@@ -28624,16 +28625,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst { tabUrl, tabTitle } = await this._getTabUrlTitle(tabId);let result;try {- result = await this.scheduler.createResumeJob({+ const args = {+ after_seconds: 90,+ reason: 'The active progress-ledger task hit consecutive stalled model outputs before finishing.',+ resume_instruction: this._buildAutoProgressResumeInstruction(tabId),+ };+ result = cloudResume ? await cloudResume(args) : await this.scheduler.createResumeJob({tabId,conversationId: this.conversationIds.get(tabId) || null,resumeTaskId: this._resumeTaskId(tabId, { create: true }),mode,- args: {- after_seconds: 90,- reason: 'The active progress-ledger task hit consecutive stalled model outputs before finishing.',- resume_instruction: this._buildAutoProgressResumeInstruction(tabId),- },+ args,currentUrl: tabUrl,currentTitle: tabTitle,});@@ -31029,6 +31031,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn await this._resizeWindow(tabId, args || {});}if (name === 'schedule_resume') {+ const cloudResume = this.cloudRunContexts.get(tabId)?.deferResume;+ if (cloudResume) return cloudResume(this._resumeArgsWithProgressGuard(tabId, args || {}));if (!this.scheduler) {return {success: false,@@ -35236,7 +35240,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._runModeOverrides.set(tabId, mode);const previousCloudContext = this.cloudRunContexts.get(tabId);if (runOptions.cloudRun) {- this.cloudRunContexts.set(tabId, { outputSchema: runOptions.outputSchema ?? null, schemaRepairUsed: false });+ this.cloudRunContexts.set(tabId, { outputSchema: runOptions.outputSchema ?? null, schemaRepairUsed: false, deferResume: runOptions.deferResume });}try {if ((mode === 'act' || mode === 'dev') && !this._isStandaloneChatRun(runOptions)) await firefoxBidi.startRun(tabId, this._runAbortSignal(tabId));@@ -36623,6 +36627,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dshareRequest = messages;}} catch {}+ runOptions.onRunFinished?.(_traceStatus);await this._endTraceRun(tabId, runId, _traceStatus, finalResponse, { provider, messages, mode, shareRequest, shareResponse: shareRawResponse, hadProviderCompletion: shareHadProviderCompletion });}}@@ -36668,7 +36673,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._runModeOverrides.set(tabId, mode);const previousCloudContext = this.cloudRunContexts.get(tabId);if (runOptions.cloudRun) {- this.cloudRunContexts.set(tabId, { outputSchema: runOptions.outputSchema ?? null, schemaRepairUsed: false });+ this.cloudRunContexts.set(tabId, { outputSchema: runOptions.outputSchema ?? null, schemaRepairUsed: false, deferResume: runOptions.deferResume });}try {if ((mode === 'act' || mode === 'dev') && !this._isStandaloneChatRun(runOptions)) await firefoxBidi.startRun(tabId, this._runAbortSignal(tabId));@@ -37556,6 +37561,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dshareRequest = this._pruneOldImages(modelMessagesForRun(), provider);}} catch {}+ runOptions.onRunFinished?.(_traceStatus);await this._endTraceRun(tabId, runId, _traceStatus, finalResponse, { provider, messages, mode, shareRequest, shareResponse: shareRawResponse, hadProviderCompletion: shareHadProviderCompletion });}}diff --git a/src/firefox/src/cloud-runs.js b/src/firefox/src/cloud-runs.jsindex a76e48e82..f240e100d 100644--- a/src/firefox/src/cloud-runs.js+++ b/src/firefox/src/cloud-runs.js@@ -4,6 +4,7 @@ import {normalizeSavedWorkflow,} from './agent/workflows.js';import { isCredentialField } from './agent/credential-fields.js';+import { validateResumeArgs } from './agent/scheduler.js';const DEFAULT_CLOUD_BRIDGE_URL = 'ws://127.0.0.1:17374/extension';const CLOUD_RUN_STORAGE_KEY = 'webbrainCloudRunSnapshots';@@ -696,6 +697,7 @@ export function createCloudRunController({workflowTrace = null,now = () => new Date(),makeRunId = () => `run_${globalThis.crypto.randomUUID()}`,+ waitForResume = ms => new Promise(resolve => setTimeout(resolve, ms)),} = {}) {const api = chromeApi;const runs = new Map();@@ -885,12 +887,10 @@ export function createCloudRunController({return redactWorkflowRuntimeValues(withoutSecrets, known, '[redacted strict URL]');}- // Terminal prose reaches the caller by the same two routes as an update row,- // so it takes both secret and trace-only URL redaction. A structured- // `run.result` is handled separately below and takes only credential-value- // redaction so ordinary schema-valid URL components remain usable.+ // Answers retain ordinary article links. Credentials remain value-redacted;+ // trace updates still withhold page URLs and arbitrary tool payloads.function redactStrictTerminal(run, value, strictSecretMode) {- return redactStrictTraceValues(run, value, strictSecretMode);+ return redactStrictSecretValues(run, value, strictSecretMode);}function pushUpdate(run, type, data, runtimeValues = []) {@@ -937,7 +937,7 @@ export function createCloudRunController({// with every string and number replaced by a placeholder, which satisfies// strict mode by making the run useless.const publicSummary = strictSecretMode- ? redactStrictTraceValues(run, result.summary, true)+ ? redactStrictSecretValues(run, result.summary, true): safeResult.summary;if (result.cloudFailed) {run.status = 'failed';@@ -950,6 +950,11 @@ export function createCloudRunController({run.summary = publicSummary || run.summary;}}+ if (type === 'tool_result' && ['done', 'done_json'].includes(data?.name)+ && ['partial', 'failed', 'blocked'].includes(data?.result?.outcome)) {+ run.agentOutcome = data.result.outcome;+ }+ if (type === 'run_status' && data?.status) run.agentOutcome = data.status;if (type === 'captcha_gate') {// Keep the latest sanitized frame/vendor snapshot at run level so it// survives the rolling 200-update window in exported cloud traces.@@ -1068,7 +1073,7 @@ export function createCloudRunController({: String(msg.task || msg.text || '').trim();if (!task) throw new Error('cloud_run requires `task`.');if (startingTabs.has(tabId) || agent.isRunning(tabId)) {- throw new Error(`Tab ${tabId} already has an active WebBrain run.`);+ throw cloudRunError('This browser tab is busy with another run. Wait for it to finish.', 409);}const apiMutationsAllowed = msg.apiMutationsAllowed === true || msg.api_mutations_allowed === true;@@ -1142,7 +1147,7 @@ export function createCloudRunController({// agent's active-run map cannot identify the parent here. The cloud// run record keeps the actual trace id; resolve its session from that// trace instead of attaching the tab's potentially unrelated session.- const parentTraceRunId = parentRun?.traceRunId || null;+ let parentTraceRunId = parentRun?.traceRunId || null;let parentTraceSessionId = null;if (parentTraceRunId && typeof workflowTrace?.getRun === 'function') {try {@@ -1214,18 +1219,62 @@ export function createCloudRunController({);}} else {- content = await agent.processMessage(tabId, task, publishUpdate, mode, [], {- cloudRun: true,- independentRun: true,- apiMutationsDenied: mode === 'ask',- outputSchema,- onTraceStarted(traceRunId) {- run.traceRunId = traceRunId;- schedulePersist();- },- parentRunId: parentTraceRunId,- parentSessionId: parentTraceSessionId,- });+ let prompt = task;+ let continuation = false;+ let resumeCount = 0;+ do {+ let requestedResume = null;+ run.agentOutcome = null;+ content = await agent.processMessage(tabId, prompt, publishUpdate, mode, [], {+ cloudRun: true,+ independentRun: !continuation,+ trustedContinuation: continuation,+ apiMutationsDenied: mode === 'ask',+ outputSchema,+ deferResume(args) {+ if (resumeCount >= 3) return { success: false, dispatched: false, noDispatch: true,+ error: 'Cloud continuation limit reached. Return an honest partial or failed outcome.' };+ const parsed = validateResumeArgs(args, now().getTime());+ if (!parsed.ok) return { success: false, dispatched: false, noDispatch: true, error: parsed.error };+ // No browser-native alarm: it would run outside this Cloud handle,+ // releasing the workspace lock and allowing the profile to pause.+ requestedResume = parsed;+ return { success: true, scheduled: true, done: true, jobId: run.runId,+ scheduledAt: parsed.scheduledAt, summary: `Scheduled a resume for ${parsed.scheduledAt}.` };+ },+ onRunFinished(status) {+ // An explicit failed/partial done outcome overrides generic 'done'.+ if (!['partial', 'failed', 'blocked'].includes(run.agentOutcome)) run.agentOutcome = status;+ },+ onTraceStarted(traceRunId) {+ run.traceRunId = traceRunId;+ schedulePersist();+ },+ parentRunId: parentTraceRunId,+ parentSessionId: parentTraceSessionId,+ });+ if (!requestedResume || ['failed', 'aborting', 'aborted'].includes(run.status)) break;+ resumeCount++;+ pushUpdate(run, 'cloud_resume_wait', { status: 'waiting', scheduledAt: requestedResume.scheduledAt, attempt: resumeCount });+ // Keep the same run, tab reservation, permission scope and secret+ // registries until completion or confirmed cancellation. Polls keep+ // the worker alive; a worker restart fails safely instead of replaying.+ await persist();+ while (run.status !== 'aborting' && now().getTime() < requestedResume.scheduledAtMs) {+ await waitForResume(Math.min(1000, requestedResume.scheduledAtMs - now().getTime()));+ }+ if (run.status === 'aborting') break;+ parentTraceRunId = run.traceRunId;+ parentTraceSessionId = null;+ if (parentTraceRunId && typeof workflowTrace?.getRun === 'function') {+ try {+ parentTraceSessionId = (await workflowTrace.getRun(parentTraceRunId))?.conversationId || null;+ } catch { /* lineage lookup must not fail a continuation */ }+ }+ prompt = requestedResume.resumeInstruction;+ continuation = true;+ pushUpdate(run, 'cloud_resume_wait', { status: 'resuming', attempt: resumeCount });+ } while (true);}run.pendingInput = null;// Terminal fields are published over the bridge and persisted just like@@ -1243,7 +1292,11 @@ export function createCloudRunController({run.status = 'aborted';run.error = run.error || 'Aborted by cloud_abort.';} else if (run.status !== 'failed') {- if (structured && run.result === undefined) {+ if (run.agentOutcome && run.agentOutcome !== 'done') {+ run.status = run.agentOutcome === 'cancelled' ? 'aborted' : 'failed';+ run.error = `Browser task did not finish successfully (${run.agentOutcome}). Review the returned result before retrying.`;+ if (!structured) run.result = run.content;+ } else if (structured && run.result === undefined) {run.status = 'failed';run.error = 'Structured cloud run finished without a valid done_json result.';} else {diff --git a/test/cloud-conversation-isolation.mjs b/test/cloud-conversation-isolation.mjsindex 360c42f34..599623722 100644--- a/test/cloud-conversation-isolation.mjs+++ b/test/cloud-conversation-isolation.mjs@@ -46,7 +46,7 @@ for (const browser of ['chrome', 'firefox']) {const racing = await Promise.allSettled([c.startRun({ conversationKey: key1, task: 'held' }), c.startRun({ conversationKey: key1, task: 'race' })]);assert.equal(racing.filter(r => r.status === 'fulfilled').length, 1);const clearCount = clears.length;- await assert.rejects(c.startRun({ conversationKey: key1, task: 'busy' }), /active|starting/);+ await assert.rejects(c.startRun({ conversationKey: key1, task: 'busy' }), error => error.status === 409 && /busy|starting/.test(error.message));assert.equal(clears.length, clearCount);release(); hold = null; await finished(racing.find(r => r.status === 'fulfilled').value);await assert.rejects(c.startRun({ conversationKey: key1, tabId: 7, task: 'conflict' }), /independent/);diff --git a/test/cloud-run-outcomes.mjs b/test/cloud-run-outcomes.mjsnew file mode 100644index 000000000..6ab466f5b--- /dev/null+++ b/test/cloud-run-outcomes.mjs@@ -0,0 +1,126 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import vm from 'node:vm';++const tick = () => new Promise(resolve => setTimeout(resolve, 5));+for (const browser of ['chrome', 'firefox']) {+ const { createCloudRunController } = await import(`../src/${browser}/src/cloud-runs.js`);+ function harness(processMessage, extra = {}) {+ const stored = {};+ let seq = 0;+ const agent = { isRunning: () => false, processMessage, abort() {}, strictSecretMode: true };+ const api = { storage: { session: { get: async key => ({ [key]: stored[key] }), set: async data => Object.assign(stored, data) } },+ tabs: { get: async () => ({ id: 7, url: 'https://example.com' }), query: async () => [{ id: 7, url: 'https://example.com' }], update: async () => {} } };+ const c = createCloudRunController({ chromeApi: api, agent, makeRunId: () => `run_${++seq}`, ensureOffscreen: async () => {}, ...extra });+ return { c, stored, agent, api };+ }+ async function finished(c, run) {+ for (let i = 0; i < 100 && ['running', 'aborting'].includes(c.runs.get(run.runId).status); i++) await tick();+ return c.status({ runId: run.runId });+ }+ test(`${browser}: tracked continuation keeps its run and tab lock, evidence and secrets`, async () => {+ let clock = Date.parse('2026-10-05T10:00:00Z'), releaseWait;+ const waiting = new Promise(resolve => { releaseWait = resolve; });+ const observed = [];+ const { c } = harness(async (tab, prompt, update, mode, _attachments, options) => {+ observed.push({ tab, prompt, mode, options });+ options.onTraceStarted(`trace_${observed.length}`);+ if (observed.length === 1) {+ update('tool_call', { name: 'set_field', args: { text: 'private-login-secret' } });+ const resume = options.deferResume({ after_seconds: 30, reason: 'Wait for page', resume_instruction: 'Continue the same task' });+ assert.equal(resume.success, true);+ options.onRunFinished('scheduled_resume');+ return resume.summary;+ }+ update('tool_result', { name: 'read_page', result: { url: 'https://news.ycombinator.com/item?id=12345678' } });+ options.onRunFinished('done');+ return 'Article https://news.ycombinator.com/item?id=12345678; private-login-secret';+ }, { now: () => new Date(clock), waitForResume: async () => { await waiting; clock += 30000; }, workflowTrace: { getRun: async () => ({ conversationId: 'same-conversation' }) } });+ const run = await c.startRun({ task: 'Read a public article' });+ await tick();+ assert.equal((await c.status({ runId: run.runId })).status, 'running');+ assert.equal(c.runs.get(run.runId).completedAt, null);+ await assert.rejects(c.startRun({ task: 'Other task' }), e => e.status === 409);+ releaseWait();+ const done = await finished(c, run);+ assert.equal(done.status, 'completed');+ assert.equal(observed.length, 2);+ assert.equal(observed[1].options.trustedContinuation, true);+ assert.equal(observed[1].options.independentRun, false);+ assert.equal(observed[1].options.parentRunId, 'trace_1');+ assert.equal(observed[1].options.parentSessionId, 'same-conversation');+ assert.equal(observed[1].prompt, 'Continue the same task');+ assert.match(done.result, /item\?id=12345678/);+ assert.equal(JSON.stringify(done).includes('private-login-secret'), false);+ assert.equal(JSON.stringify(done.updates).includes('item?id=12345678'), false);+ });+ test(`${browser}: cancellation during a deferred resume never dispatches continuation`, async () => {+ let release, calls = 0;+ const waiting = new Promise(resolve => { release = resolve; });+ const { c } = harness(async (_tab, _task, _update, _mode, _attachments, options) => {+ calls++;+ const r = options.deferResume({ after_seconds: 30, reason: 'Waiting', resume_instruction: 'Continue' });+ options.onRunFinished('scheduled_resume');+ return r.summary;+ }, { waitForResume: () => waiting });+ const run = await c.startRun({ task: 'Read' }); await tick();+ assert.equal((await c.abort({ runId: run.runId })).status, 'aborting');+ release();+ assert.equal((await finished(c, run)).status, 'aborted');+ assert.equal(calls, 1);+ });+ test(`${browser}: failed, partial and recovery-limit outcomes preserve output without reporting success`, async () => {+ for (const outcome of ['partial', 'failed', 'empty_output', 'max_steps', 'required_tool_missing']) {+ const { c } = harness(async (_tab, _task, update, _mode, _attachments, options) => {+ update('tool_result', { name: 'done', result: { outcome: outcome === 'failed' ? 'failed' : undefined } });+ options.onRunFinished(outcome === 'failed' ? 'done' : outcome);+ return 'Only a draft, not posted';+ });+ const run = await c.startRun({ task: 'Comment on an article' });+ const done = await finished(c, run);+ assert.equal(done.status, 'failed');+ assert.match(done.error, /did not finish successfully/);+ assert.equal(done.result, 'Only a draft, not posted');+ }+ });+ test(`${browser}: continuation budget and restart stop safely instead of replaying page actions`, async () => {+ let clock = Date.now(), calls = 0;+ const { c, stored, agent, api } = harness(async (_tab, _task, _update, _mode, _attachments, options) => {+ calls++;+ const resume = options.deferResume({ after_seconds: 30, reason: 'Wait', resume_instruction: 'Continue' });+ options.onRunFinished(resume.success ? 'scheduled_resume' : 'partial');+ return resume.summary || resume.error;+ }, { now: () => new Date(clock), waitForResume: async ms => { clock += ms; } });+ const run = await c.startRun({ task: 'Read' });+ assert.equal((await finished(c, run)).status, 'failed');+ assert.equal(calls, 4);+ const row = structuredClone(stored.webbrainCloudRunSnapshots[0]);+ row.status = 'running'; row.completedAt = null;+ stored.webbrainCloudRunSnapshots = [row];+ const restarted = createCloudRunController({ chromeApi: api, agent, ensureOffscreen: async () => {} });+ assert.equal((await restarted.status({ runId: row.runId })).status, 'failed');+ assert.equal(calls, 4, 'restart never replays a possible consequential action');+ });+ test(`${browser}: real auto-resume helper routes Cloud work to the controller, native scheduling stays unchanged`, async () => {+ const source = fs.readFileSync(new URL(`../src/${browser}/src/agent/agent.js`, import.meta.url), 'utf8');+ const method = source.slice(source.indexOf(' async _scheduleAutoProgressResume('), source.indexOf(' _plainFinalProgressBlock('));+ const helper = vm.runInNewContext(`({${method}})._scheduleAutoProgressResume`);+ let native = 0, cloud = 0;+ const fake = { scheduler: { createResumeJob: async () => { native++; return { success: true }; } },+ cloudRunContexts: new Map([[7, { deferResume: async args => { cloud++; assert.equal(args.after_seconds, 90); return { success: true }; } }]]),+ _effectiveRunMode: () => 'act', _isActionMode: () => true, _shouldBlockDoneForProgress: () => true,+ _getTabUrlTitle: async () => ({}), _buildAutoProgressResumeInstruction: () => 'Continue',+ conversationIds: new Map(), _resumeTaskId: () => 'task' };+ await helper.call(fake, 7);+ assert.equal(cloud, 1); assert.equal(native, 0);+ fake.cloudRunContexts.clear(); await helper.call(fake, 7);+ assert.equal(native, 1);+ const start = source.indexOf(" if (name === 'schedule_resume') {");+ const route = source.slice(start, source.indexOf(' if (!this.scheduler)', start));+ const toolRoute = vm.runInNewContext(`(async function(name,tabId,args){${route}\n}})`);+ fake.cloudRunContexts.set(7, { deferResume: async () => ({ success: true, cloud: true }) });+ fake._resumeArgsWithProgressGuard = (_tab, args) => args;+ assert.equal((await toolRoute.call(fake, 'schedule_resume', 7, {})).cloud, true);+ });+}diff --git a/test/run.js b/test/run.jsindex 055c5e14d..c020c9fb9 100644--- a/test/run.js+++ b/test/run.js@@ -26044,11 +26044,11 @@ test('trace lineage: _startTraceRun and replay plumb parent ids in both builds',assert.match(agentSource, /parentRunId: replayParentRunId,[\s\S]*?parentSessionId: replayParentSessionId,/, `${browser}: replay does not pass captured lineage to tracing`);}const chromeCloudRuns = fs.readFileSync(path.join(ROOT, 'src/chrome/src/cloud-runs.js'), 'utf8');- assert.match(chromeCloudRuns, /const parentTraceRunId = parentRun\?\.traceRunId \|\| null;/, 'cloud-runs does not use the completed parent trace');+ assert.match(chromeCloudRuns, /(?:const|let) parentTraceRunId = parentRun\?\.traceRunId \|\| null;/, 'cloud-runs does not use the completed parent trace');assert.match(chromeCloudRuns, /workflowTrace\.getRun\(parentTraceRunId\)/, 'cloud-runs does not resolve the parent trace session');assert.match(chromeCloudRuns, /parentRunId: parentTraceRunId,[\s\S]*?parentSessionId: parentTraceSessionId,/, 'cloud-runs does not thread resolved parent lineage');const firefoxCloudRuns = fs.readFileSync(path.join(ROOT, 'src/firefox/src/cloud-runs.js'), 'utf8');- assert.match(firefoxCloudRuns, /const parentTraceRunId = parentRun\?\.traceRunId \|\| null;/, 'Firefox cloud-runs does not use the completed parent trace');+ assert.match(firefoxCloudRuns, /(?:const|let) parentTraceRunId = parentRun\?\.traceRunId \|\| null;/, 'Firefox cloud-runs does not use the completed parent trace');assert.match(firefoxCloudRuns, /parentRunId: parentTraceRunId,[\s\S]*?parentSessionId: parentTraceSessionId,/, 'Firefox cloud-runs does not thread resolved parent lineage');});