Skip to content

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

Lean mode: keep the chat receipt check and the ledger override after steering

Barack Sokullu21afe02deb44
diff --git a/docs/lean-mode-comparison.md b/docs/lean-mode-comparison.md
index 52dfa8e2f..7b827688b 100644
--- a/docs/lean-mode-comparison.md
+++ b/docs/lean-mode-comparison.md
@@ -8,12 +8,12 @@ The system prompt and tool schemas a model receives on each Act turn, with produ
| Build | Provider model | Lean mode | System prompt | Tools | Tool schemas | Per turn |
| --- | --- | --- | ---: | ---: | ---: | ---: |
-| Chrome | `claude-sonnet-4-5`, `gpt-5` | Off | 53,163 chars, β‰ˆ13,292 tokens | 58 | 82,870 chars, β‰ˆ20,718 tokens | β‰ˆ34,010 tokens |
-| Chrome | `claude-sonnet-4-5`, `gpt-5` | Auto β†’ lean (strong_cloud_model) | 8,366 chars, β‰ˆ2,092 tokens | 17 | 29,900 chars, β‰ˆ7,475 tokens | β‰ˆ9,567 tokens |
-| Firefox | `claude-sonnet-4-5`, `gpt-5` | Off | 43,578 chars, β‰ˆ10,895 tokens | 57 | 79,799 chars, β‰ˆ19,950 tokens | β‰ˆ30,845 tokens |
-| Firefox | `claude-sonnet-4-5`, `gpt-5` | Auto β†’ lean (strong_cloud_model) | 8,265 chars, β‰ˆ2,067 tokens | 17 | 28,866 chars, β‰ˆ7,217 tokens | β‰ˆ9,284 tokens |
+| Chrome | `claude-sonnet-4-5`, `gpt-5` | Off | 53,276 chars, β‰ˆ13,320 tokens | 58 | 83,121 chars, β‰ˆ20,781 tokens | β‰ˆ34,101 tokens |
+| Chrome | `claude-sonnet-4-5`, `gpt-5` | Auto β†’ lean (strong_cloud_model) | 8,366 chars, β‰ˆ2,092 tokens | 17 | 30,151 chars, β‰ˆ7,538 tokens | β‰ˆ9,630 tokens |
+| Firefox | `claude-sonnet-4-5`, `gpt-5` | Off | 43,691 chars, β‰ˆ10,924 tokens | 57 | 80,050 chars, β‰ˆ20,013 tokens | β‰ˆ30,937 tokens |
+| Firefox | `claude-sonnet-4-5`, `gpt-5` | Auto β†’ lean (strong_cloud_model) | 8,265 chars, β‰ˆ2,067 tokens | 17 | 29,117 chars, β‰ˆ7,280 tokens | β‰ˆ9,347 tokens |
-Lean mode cuts this fixed per-turn input by 72% in the Chrome build (β‰ˆ34,010 β†’ β‰ˆ9,567 tokens) and by 70% in the Firefox build. Tool schemas are unchanged; lean mode offers fewer of them.
+Lean mode cuts this fixed per-turn input by 72% in the Chrome build (β‰ˆ34,101 β†’ β‰ˆ9,630 tokens) and by 70% in the Firefox build. Tool schemas are unchanged; lean mode offers fewer of them.
The lean Act tools (17): `calculate`, `get_accessibility_tree`, `click_ax`, `set_checked`, `type_ax`, `set_field`, `inspect_viewport`, `read_page`, `click`, `type_text`, `press_keys`, `scroll`, `navigate`, `wait_for_stable`, `done`, `clarify`, `upload_file`. `generate_image`, `carousel_navigate`, `gmail_count_results` and enabled skills' tools are added when they apply, as in a full run.
@@ -34,9 +34,9 @@ The model is a fixed script: it reads the page, acts on the targets it names by
| Task | Lean mode | Model turns | Tool calls | Refused | Notes | Caveat | LLM side calls | Cards | Page probes | Input tokens | On the page | Result |
| --- | --- | ---: | ---: | ---: | ---: | --- | ---: | ---: | ---: | ---: | --- | --- |
-| GitHub edit + commit | Off | 8 | 8 | 1 | 0 | yes | 5 | 3 | 229 | β‰ˆ295k | committed once, file text exact | done, answer carries a caveat |
+| GitHub edit + commit | Off | 8 | 8 | 1 | 0 | yes | 5 | 3 | 229 | β‰ˆ296k | committed once, file text exact | done, answer carries a caveat |
| GitHub edit + commit | Auto β†’ lean | 7 | 7 | 0 | 0 | no | 4 | 3 | 174 | β‰ˆ86k | committed once, file text exact | success |
-| Contact form | Off | 7 | 7 | 0 | 0 | no | 3 | 2 | 136 | β‰ˆ249k | sent once with the requested values | success |
+| Contact form | Off | 7 | 7 | 0 | 0 | no | 3 | 2 | 136 | β‰ˆ250k | sent once with the requested values | success |
| Contact form | Auto β†’ lean | 7 | 7 | 0 | 0 | no | 1 | 2 | 102 | β‰ˆ78k | sent once with the requested values | success |
| Read-only lookup | Off | 2 | 2 | 0 | 0 | no | 1 | 0 | 34 | β‰ˆ70k | answered $129.00 | success |
| Read-only lookup | Auto β†’ lean | 2 | 2 | 0 | 0 | no | 0 | 0 | 9 | β‰ˆ21k | answered $129.00 | success |
@@ -49,7 +49,7 @@ The case that motivated lean mode. The task replaces NOTES.md with a three-parag
- **Auto β†’ lean:** `get_accessibility_tree` β†’ `set_field` β†’ `click_ax` β†’ `get_accessibility_tree` β†’ `click_ax` β†’ `get_accessibility_tree` β†’ `done`.
- **LLM side calls** (besides the planner's intent call, 1 in each mode): Off 5 (intent, reading: control_effect Γ—2, reading: page_blocker, completion_verification); lean 4 (intent, reading: control_effect Γ—2, reading: page_blocker).
- **Cards shown to the user:** Off site permission, submit confirmation Γ—2; lean site permission, submit confirmation Γ—2.
-- **Model input:** Off 294,859 tokens over 8 turns (58 tools offered, a 54,593-character system prompt); lean 85,860 tokens over 7 turns (17 tools, 9,796 characters).
+- **Model input:** Off 295,587 tokens over 8 turns (58 tools offered, a 54,706-character system prompt); lean 86,298 tokens over 7 turns (17 tools, 9,796 characters).
### 2. Fill a simple form and submit it
@@ -59,7 +59,7 @@ Three fields and a Send button on a plain page; the page posts with fetch and sh
- **Auto β†’ lean:** `get_accessibility_tree` β†’ `set_field` β†’ `set_field` β†’ `set_field` β†’ `click_ax` β†’ `get_accessibility_tree` β†’ `done`.
- **LLM side calls** (besides the planner's intent call, 1 in each mode): Off 3 (reading: control_effect, reading: status_message, completion_verification); lean 1 (reading: control_effect).
- **Cards shown to the user:** Off site permission, submit confirmation; lean site permission, submit confirmation.
-- **Model input:** Off 249,078 tokens over 7 turns (58 tools offered, a 53,735-character system prompt); lean 77,984 tokens over 7 turns (17 tools, 8,938 characters).
+- **Model input:** Off 249,715 tokens over 7 turns (58 tools offered, a 53,848-character system prompt); lean 78,425 tokens over 7 turns (17 tools, 8,938 characters).
### 3. Read-only lookup on the current page
@@ -69,7 +69,7 @@ A question about the open product page: what does the Trail Runner 2 cost? The a
- **Auto β†’ lean:** `read_page` β†’ `done`.
- **LLM side calls** (besides the planner's intent call, 1 in each mode): Off 1 (completion_verification); lean 0.
- **Cards shown to the user:** Off none; lean none.
-- **Model input:** Off 70,051 tokens over 2 turns (58 tools offered, a 53,735-character system prompt); lean 21,168 tokens over 2 turns (17 tools, 8,938 characters).
+- **Model input:** Off 70,233 tokens over 2 turns (58 tools offered, a 53,848-character system prompt); lean 21,293 tokens over 2 turns (17 tools, 8,938 characters).
## Limits
diff --git a/docs/lean-mode.md b/docs/lean-mode.md
index 19a5be177..84b9253d3 100644
--- a/docs/lean-mode.md
+++ b/docs/lean-mode.md
@@ -81,7 +81,7 @@ Some steps that look like quality work feed the hard checks, so they stay too:
- the social publication contract;
- the rich-text toolbar probe, which pins the typing target (only its classification is skipped);
- automatic screenshots, as set in Settings;
-- a delivered chat message's receipt, which must be saved before `done` reports success, or a resumed run could send it again.
+- a chat message sent in the run: its delivery must be confirmed in the conversation and its receipt saved before `done` reports success, or a resumed run could send it again. A receipt that cannot be saved refuses success every time; a send the conversation cannot confirm refuses it once per send, and `partial` or `failed` always ends the run.
These quality guards keep running, each because a hard check depends on it (`LEAN_KEPT_QUALITY_GUARDS` in `lean-mode.js`):
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index 0adcfd832..d0790b408 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -1493,9 +1493,13 @@ export class Agent extends LoopDetector {
// done in a lean run. The completion is the model's own call: WebBrain
// takes no verification screenshot, runs no completion or incomplete-task
// judge and checks no page warnings or workflow evidence. One hard check
- // stays (native-chat-receipt-not-durable): a chat message delivered in this
- // run must have its receipt saved before success is reported, or a resumed
- // run could send it again.
+ // stays (native-chat-receipt-not-durable): a chat message sent in this run
+ // must be confirmed in the conversation and its receipt saved before
+ // success is reported, or a resumed run could send it again. A receipt
+ // that cannot be saved refuses success every time, as in a full run. A send
+ // the conversation cannot confirm (its read failed, the conversation
+ // changed, a new message arrived) refuses success once per send, as a full
+ // run's submission-evidence check does; partial and failed always end.
async _leanDoneResult(tabId, args = {}) {
const outcome = normalizeDoneOutcome(args?.outcome);
if (outcome === 'success' && (this.completionInvariants.get(tabId)?.lastAction?.chatDeliveryBinding
@@ -1510,11 +1514,34 @@ export class Agent extends LoopDetector {
if (savedNativeReceipt !== true && savedNativeReceipt?.ok !== true) {
return { success: false, blockedDone: true, error: 'The verified chat delivery receipt could not be saved. Retry completion after storage is available; do not send the message again.' };
}
+ } else if (this._leanChatDeliveryUnconfirmedRefuses(tabId)) {
+ return { success: false, blockedDone: true, chatDeliveryUnconfirmed: true,
+ error: 'WebBrain could not confirm in the conversation that your message was delivered: its latest read failed, the conversation changed, or a new message arrived. Do not send the message again. Read the conversation now, then call done again; if the delivery still cannot be confirmed, finish with outcome "partial" and say so.' };
}
}
return { done: true, summary: args.summary, outcome };
}
+ // native-chat-receipt-not-durable in a lean run when the conversation could
+ // not confirm a send: true the first time for this send in this run. Only a
+ // send the plan contract requires is checked; outside one there is no
+ // receipt to confirm (_nativeChatTerminalEvidence).
+ _leanChatDeliveryUnconfirmedRefuses(tabId) {
+ const guard = this._planExecutionGuards.get(tabId);
+ if (!guard?.enabled || guard.siteWorkflow?.job || guard.requiresSubmission !== true
+ || guard.requiresStateChange !== true) return false;
+ const lastAction = this.completionInvariants.get(tabId)?.lastAction;
+ const receipt = this.chatSessions.get(tabId)?.completionReceipt;
+ const key = lastAction?.chatDeliveryBinding
+ ? `send:${lastAction.sequence ?? ''}:${lastAction.chatDeliveryBinding.threadKey || ''}`
+ : `receipt:${receipt?.threadKey || ''}:${receipt?.messageId || ''}`;
+ const state = this._guardRunState(tabId);
+ const refused = (state.leanUnconfirmedChatSends ||= new Set());
+ if (refused.has(key)) return false;
+ refused.add(key);
+ return true;
+ }
+
_readCompletenessNeedsScopeClassification(tabId) {
// Lean mode enforces no read coverage, so it needs no scope reading.
if (this._leanRunActive(tabId)) return false;
@@ -6409,8 +6436,7 @@ export class Agent extends LoopDetector {
});
if (!gate.responseOnly) await this._ensureProgressSessionForCurrentTask(tabId, {
provider: this._activeProvider(tabId), costState,
- progressLedgerPolicy: gate.progressLedgerPolicy, progressAction: gate.progressAction,
- expectedItems: gate.expectedItems,
+ ...this._progressLedgerGateOptions(tabId, gate),
});
// The system prompt is rebuilt by the new guard. Clear the old approved
// plan even when only intent classification is enabled for this revision.
@@ -37882,6 +37908,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
});
}
+ // The progress-ledger options a planner gate hands
+ // _ensureProgressSessionForCurrentTask, at a run's start and after each
+ // steering revision. Lean mode keeps no progress ledger (its tools omit
+ // progress_read and progress_update); the call still prepares the
+ // publication contract and the workflow fields hard checks rely on.
+ _progressLedgerGateOptions(tabId, gate) {
+ if (this._leanRunActive(tabId)) return { progressLedgerPolicy: 'disabled', progressAction: null, expectedItems: null };
+ return { progressLedgerPolicy: gate?.progressLedgerPolicy, progressAction: gate?.progressAction,
+ expectedItems: gate?.expectedItems };
+ }
+
async _ensureProgressSessionForCurrentTask(tabId, opts = {}) {
const publicationGuard = this._planExecutionGuards.get(tabId);
if (publicationGuard?.enabled && publicationGuard.requiresSubmission === true
@@ -53107,15 +53144,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (!initialTaskRevalidated) this._startPlanExecutionGuard(tabId, mode, gateOutcome, runOptions);
if (this._isActionMode(mode) && !selectionOnly && !standaloneChatRun) {
- // Lean mode keeps no progress ledger; the call still prepares the
- // publication contract and workflow fields hard checks rely on.
- const leanRun = this._leanRunActive(tabId);
await this._ensureProgressSessionForCurrentTask(tabId, {
provider,
costState,
- progressLedgerPolicy: leanRun ? 'disabled' : gateOutcome.progressLedgerPolicy,
- progressAction: leanRun ? null : gateOutcome.progressAction,
- expectedItems: leanRun ? null : gateOutcome.expectedItems,
+ ...this._progressLedgerGateOptions(tabId, gateOutcome),
});
}
const tier = provider.promptTier;
@@ -54772,15 +54804,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
if (this._isActionMode(mode) && !selectionOnly && !standaloneChatRun) {
- // Lean mode keeps no progress ledger; the call still prepares the
- // publication contract and workflow fields hard checks rely on.
- const leanRun = this._leanRunActive(tabId);
await this._ensureProgressSessionForCurrentTask(tabId, {
provider,
costState,
- progressLedgerPolicy: leanRun ? 'disabled' : gateOutcome.progressLedgerPolicy,
- progressAction: leanRun ? null : gateOutcome.progressAction,
- expectedItems: leanRun ? null : gateOutcome.expectedItems,
+ ...this._progressLedgerGateOptions(tabId, gateOutcome),
});
}
const tier = provider.promptTier;
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index 9d0e86aae..e26f99b36 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -1125,9 +1125,13 @@ export class Agent extends LoopDetector {
// done in a lean run. The completion is the model's own call: WebBrain
// takes no verification screenshot, runs no completion or incomplete-task
// judge and checks no page warnings or workflow evidence. One hard check
- // stays (native-chat-receipt-not-durable): a chat message delivered in this
- // run must have its receipt saved before success is reported, or a resumed
- // run could send it again.
+ // stays (native-chat-receipt-not-durable): a chat message sent in this run
+ // must be confirmed in the conversation and its receipt saved before
+ // success is reported, or a resumed run could send it again. A receipt
+ // that cannot be saved refuses success every time, as in a full run. A send
+ // the conversation cannot confirm (its read failed, the conversation
+ // changed, a new message arrived) refuses success once per send, as a full
+ // run's submission-evidence check does; partial and failed always end.
async _leanDoneResult(tabId, args = {}) {
const outcome = normalizeDoneOutcome(args?.outcome);
if (outcome === 'success' && (this.completionInvariants.get(tabId)?.lastAction?.chatDeliveryBinding
@@ -1142,11 +1146,34 @@ export class Agent extends LoopDetector {
if (savedNativeReceipt !== true && savedNativeReceipt?.ok !== true) {
return { success: false, blockedDone: true, error: 'The verified chat delivery receipt could not be saved. Retry completion after storage is available; do not send the message again.' };
}
+ } else if (this._leanChatDeliveryUnconfirmedRefuses(tabId)) {
+ return { success: false, blockedDone: true, chatDeliveryUnconfirmed: true,
+ error: 'WebBrain could not confirm in the conversation that your message was delivered: its latest read failed, the conversation changed, or a new message arrived. Do not send the message again. Read the conversation now, then call done again; if the delivery still cannot be confirmed, finish with outcome "partial" and say so.' };
}
}
return { done: true, summary: args.summary, outcome };
}
+ // native-chat-receipt-not-durable in a lean run when the conversation could
+ // not confirm a send: true the first time for this send in this run. Only a
+ // send the plan contract requires is checked; outside one there is no
+ // receipt to confirm (_nativeChatTerminalEvidence).
+ _leanChatDeliveryUnconfirmedRefuses(tabId) {
+ const guard = this._planExecutionGuards.get(tabId);
+ if (!guard?.enabled || guard.siteWorkflow?.job || guard.requiresSubmission !== true
+ || guard.requiresStateChange !== true) return false;
+ const lastAction = this.completionInvariants.get(tabId)?.lastAction;
+ const receipt = this.chatSessions.get(tabId)?.completionReceipt;
+ const key = lastAction?.chatDeliveryBinding
+ ? `send:${lastAction.sequence ?? ''}:${lastAction.chatDeliveryBinding.threadKey || ''}`
+ : `receipt:${receipt?.threadKey || ''}:${receipt?.messageId || ''}`;
+ const state = this._guardRunState(tabId);
+ const refused = (state.leanUnconfirmedChatSends ||= new Set());
+ if (refused.has(key)) return false;
+ refused.add(key);
+ return true;
+ }
+
_readCompletenessNeedsScopeClassification(tabId) {
// Lean mode enforces no read coverage, so it needs no scope reading.
if (this._leanRunActive(tabId)) return false;
@@ -5955,8 +5982,7 @@ export class Agent extends LoopDetector {
});
if (!gate.responseOnly) await this._ensureProgressSessionForCurrentTask(tabId, {
provider: this._activeProvider(tabId), costState,
- progressLedgerPolicy: gate.progressLedgerPolicy, progressAction: gate.progressAction,
- expectedItems: gate.expectedItems,
+ ...this._progressLedgerGateOptions(tabId, gate),
});
// The system prompt is rebuilt by the new guard. Clear the old approved
// plan even when only intent classification is enabled for this revision.
@@ -34745,6 +34771,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
});
}
+ // The progress-ledger options a planner gate hands
+ // _ensureProgressSessionForCurrentTask, at a run's start and after each
+ // steering revision. Lean mode keeps no progress ledger (its tools omit
+ // progress_read and progress_update); the call still prepares the
+ // publication contract and the workflow fields hard checks rely on.
+ _progressLedgerGateOptions(tabId, gate) {
+ if (this._leanRunActive(tabId)) return { progressLedgerPolicy: 'disabled', progressAction: null, expectedItems: null };
+ return { progressLedgerPolicy: gate?.progressLedgerPolicy, progressAction: gate?.progressAction,
+ expectedItems: gate?.expectedItems };
+ }
+
async _ensureProgressSessionForCurrentTask(tabId, opts = {}) {
const publicationGuard = this._planExecutionGuards.get(tabId);
if (publicationGuard?.enabled && publicationGuard.requiresSubmission === true
@@ -44726,15 +44763,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (!initialTaskRevalidated) this._startPlanExecutionGuard(tabId, mode, gateOutcome, runOptions);
if (this._isActionMode(mode) && !selectionOnly && !standaloneChatRun) {
- // Lean mode keeps no progress ledger; the call still prepares the
- // publication contract and workflow fields hard checks rely on.
- const leanRun = this._leanRunActive(tabId);
await this._ensureProgressSessionForCurrentTask(tabId, {
provider,
costState,
- progressLedgerPolicy: leanRun ? 'disabled' : gateOutcome.progressLedgerPolicy,
- progressAction: leanRun ? null : gateOutcome.progressAction,
- expectedItems: leanRun ? null : gateOutcome.expectedItems,
+ ...this._progressLedgerGateOptions(tabId, gateOutcome),
});
}
const tier = provider.promptTier;
@@ -46196,15 +46228,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (!initialTaskRevalidated) this._startPlanExecutionGuard(tabId, mode, gateOutcome, runOptions);
if (this._isActionMode(mode) && !selectionOnly && !standaloneChatRun) {
- // Lean mode keeps no progress ledger; the call still prepares the
- // publication contract and workflow fields hard checks rely on.
- const leanRun = this._leanRunActive(tabId);
await this._ensureProgressSessionForCurrentTask(tabId, {
provider,
costState,
- progressLedgerPolicy: leanRun ? 'disabled' : gateOutcome.progressLedgerPolicy,
- progressAction: leanRun ? null : gateOutcome.progressAction,
- expectedItems: leanRun ? null : gateOutcome.expectedItems,
+ ...this._progressLedgerGateOptions(tabId, gateOutcome),
});
}
const tier = provider.promptTier;
diff --git a/test/guard-policy.mjs b/test/guard-policy.mjs
index 0d6816bb4..a0f0a956b 100644
--- a/test/guard-policy.mjs
+++ b/test/guard-policy.mjs
@@ -75,8 +75,9 @@ const GRANDFATHERED_CEILING = 158;
// Completion refusals (`blockedDone: true`) per build. A new one must be a
// registered guard routed through _guardRefusesOnce (or a hard-class guard);
// raise the ceiling only in the change that registers it. Lean mode's done
-// keeps one hard check (native-chat-receipt-not-durable) in its own path.
-const BLOCKED_DONE_CEILING = { chrome: 19, firefox: 18 };
+// keeps one hard check (native-chat-receipt-not-durable) in its own path:
+// a receipt that cannot be saved, and a send the conversation cannot confirm.
+const BLOCKED_DONE_CEILING = { chrome: 20, firefox: 19 };
function walk(dir) {
return fs.readdirSync(new URL(`../${dir}`, import.meta.url), { withFileTypes: true }).flatMap(entry => {
diff --git a/test/lean-mode.mjs b/test/lean-mode.mjs
index 93973c85c..36ca2df81 100644
--- a/test/lean-mode.mjs
+++ b/test/lean-mode.mjs
@@ -404,13 +404,51 @@ for (const build of ['chrome', 'firefox']) {
const done = await agent.executeTool(tab, 'done', { summary: 'Saved.', outcome: 'success' });
assert.deepEqual(done, { done: true, summary: 'Saved.', outcome: 'success' });
assert.equal(probes + judged, 0, 'no probe, screenshot or judge');
- // recipient class: a delivered chat message must have its receipt saved.
- agent.completionInvariants.set(tab, { lastAction: { name: 'click_ax', chatDeliveryBinding: { token: 'sent' } } });
+ // recipient class: a delivered chat message must have its receipt saved,
+ // every time, as in a full run.
+ agent.completionInvariants.set(tab, { lastAction: { name: 'click_ax', sequence: 3, chatDeliveryBinding: { token: 'sent', threadKey: 'dom:chat:1' } } });
agent._freshNativeChatTerminalEvidence = async () => ({ receipt: 'delivered' });
agent._persistNow = async () => false;
- const refused = await agent.executeTool(tab, 'done', { summary: 'Sent.', outcome: 'success' });
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const refused = await agent.executeTool(tab, 'done', { summary: 'Sent.', outcome: 'success' });
+ assert.equal(refused.blockedDone, true, JSON.stringify(refused));
+ assert.match(refused.error, /delivery receipt could not be saved/);
+ }
+ });
+
+ test(`${build}: a lean done over a send the conversation cannot confirm is refused once, then ends`, async () => {
+ const agent = new Agent({ getActive: () => STRONG });
+ const tab = nextTab++;
+ agent.conversationModes.set(tab, 'act');
+ agent._runModeOverrides.set(tab, 'act');
+ leanState(agent, tab);
+ let reads = 0;
+ agent._freshNativeChatTerminalEvidence = async () => { reads++; return null; };
+ agent._persistNow = async () => assert.fail('nothing to save without confirmed delivery');
+ agent.completionInvariants.set(tab, { lastAction: { name: 'press_keys', sequence: 4, chatDeliveryBinding: { token: 'sent', threadKey: 'dom:chat:1' } } });
+ // Outside a plan contract that requires the send, there is no receipt
+ // to confirm.
+ assert.deepEqual(await agent.executeTool(tab, 'done', { summary: 'Replied.', outcome: 'success' }),
+ { done: true, summary: 'Replied.', outcome: 'success' });
+ agent._planExecutionGuards.set(tab, { enabled: true, requiresSubmission: true, requiresStateChange: true, taskKey: 'tk_reply' });
+ const refused = await agent.executeTool(tab, 'done', { summary: 'Replied.', outcome: 'success' });
assert.equal(refused.blockedDone, true, JSON.stringify(refused));
- assert.match(refused.error, /delivery receipt could not be saved/);
+ assert.equal(refused.chatDeliveryUnconfirmed, true);
+ assert.match(refused.error, /could not confirm in the conversation/);
+ assert.match(refused.error, /Do not send the message again/);
+ assert.match(refused.error, /outcome "partial"/);
+ // An honest ending is never refused.
+ for (const outcome of ['partial', 'failed']) {
+ assert.deepEqual(await agent.executeTool(tab, 'done', { summary: 'Sent; not confirmed.', outcome }),
+ { done: true, summary: 'Sent; not confirmed.', outcome });
+ }
+ // Once per send: the next success ends the run.
+ assert.deepEqual(await agent.executeTool(tab, 'done', { summary: 'Replied.', outcome: 'success' }),
+ { done: true, summary: 'Replied.', outcome: 'success' });
+ // A later send in the same run is checked again.
+ agent.completionInvariants.set(tab, { lastAction: { name: 'press_keys', sequence: 9, chatDeliveryBinding: { token: 'sent-2', threadKey: 'dom:chat:1' } } });
+ assert.equal((await agent.executeTool(tab, 'done', { summary: 'Replied again.', outcome: 'success' })).chatDeliveryUnconfirmed, true);
+ assert.ok(reads >= 3, 'the conversation is read again at every success');
});
test(`${build}: in a lean run an unverified CodeMirror write is a plain success with no note or lock`, async () => {
@@ -479,10 +517,54 @@ for (const build of ['chrome', 'firefox']) {
// The run loop calls these through the lean checks; see agent.js.
const source = read(`src/${build}/src/agent/agent.js`);
assert.equal((source.match(/if \(!this\._leanRunActive\(tabId\)\) await this\._prepareCalculationReading\(tabId\);/g) || []).length, 2);
- assert.equal((source.match(/progressLedgerPolicy: leanRun \? 'disabled' : gateOutcome\.progressLedgerPolicy,/g) || []).length, 2);
+ // Every gate that starts or revises a task (both run loops and steering)
+ // takes its ledger options from the one helper that honours lean mode.
+ const ledgerCalls = source.match(/await this\._ensureProgressSessionForCurrentTask\(tabId, \{[\s\S]*?\n\s*\}\);/g) || [];
+ assert.equal(ledgerCalls.length, 3);
+ for (const site of ledgerCalls) assert.match(site, /\.\.\.this\._progressLedgerGateOptions\(tabId, (?:gateOutcome|gate)\)/);
+ const gate = { progressLedgerPolicy: 'enabled', progressAction: 'process_item', expectedItems: [{ id: 'a' }] };
+ assert.deepEqual(agent._progressLedgerGateOptions(tab, gate), { progressLedgerPolicy: 'disabled', progressAction: null, expectedItems: null });
+ assert.deepEqual(agent._progressLedgerGateOptions(nextTab++, gate), gate, 'a run that is not lean keeps the gate\'s ledger');
assert.equal(calculationReads, 0);
});
+ // A correction mid-run reruns the planner gate; a lean run keeps no ledger
+ // after it either, so no auto-recorded result points at progress tools the
+ // run does not offer.
+ for (const setting of ['on', 'off']) {
+ test(`${build}: a steered ${setting === 'on' ? 'lean' : 'full'} run ${setting === 'on' ? 'keeps the progress ledger off' : 'takes the revised ledger'}`, async () => {
+ const agent = new Agent({ getActive: () => STRONG });
+ const tab = nextTab++;
+ agent.conversationModes.set(tab, 'act');
+ if (setting === 'on') leanState(agent, tab);
+ Object.assign(agent, { _persist: () => {}, _persistNow: async () => ({ ok: true }), _currentUrl: async () => PAGE,
+ _applyPendingSteering: () => {} });
+ agent._steeringRuns.set(tab, { requestId: `lean-${tab}`, messages: [], acceptedIds: new Set(), revision: 2,
+ authorizedRevision: 1, onUpdate: () => {} });
+ const revisedGate = { proceed: true, requestKind: 'execute', requiresStateChange: true, requiresSubmission: false,
+ progressLedgerPolicy: 'enabled', progressAction: 'process_item', expectedItems: [{ id: 'row-1' }, { id: 'row-2' }] };
+ agent._maybeRunPlannerGate = async () => revisedGate;
+ const ledgerCalls = [];
+ const ensure = agent._ensureProgressSessionForCurrentTask.bind(agent);
+ agent._ensureWorkflowMetadataRequirements = async () => {};
+ agent._ensureProgressSessionForCurrentTask = async (tabId, opts) => {
+ ledgerCalls.push({ policy: opts.progressLedgerPolicy, action: opts.progressAction, items: opts.expectedItems });
+ return setting === 'on' ? ensure(tabId, opts) : null;
+ };
+ const messages = [{ role: 'system', content: 'sys' }, { role: 'user', content: 'Process the two rows.' }];
+ agent.conversations.set(tab, messages);
+ const revised = await agent._revalidatePendingSteering(tab, messages, () => {}, 'act', {}, null, {});
+ assert.equal(revised?.changed, true);
+ if (setting === 'on') {
+ assert.deepEqual(ledgerCalls, [{ policy: 'disabled', action: null, items: null }]);
+ assert.equal(agent.progressSessions.get(tab)?.mode, 'inactive', 'the revised task has no active ledger');
+ assert.equal(agent.progressExpectedItems.has(tab), false);
+ } else {
+ assert.deepEqual(ledgerCalls, [{ policy: 'enabled', action: 'process_item', items: revisedGate.expectedItems }]);
+ }
+ });
+ }
+
// ── Hard checks keep their cards ────────────────────────────────────────
test(`${build}: a lean run still sends an unclear deletion to WebBrain's deletion card`, async () => {
const pageUrl = 'https://shop.example/cart';