Skip to content

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

Publication prefetch: a call stopped before its cards records its timing

Barack Sokullu1efb99f0695e
diff --git a/docs/trace-format-compatibility.md b/docs/trace-format-compatibility.md
index f9845ec7a..281b0715a 100644
--- a/docs/trace-format-compatibility.md
+++ b/docs/trace-format-compatibility.md
@@ -18,7 +18,7 @@ Planner alignment and publication checks record their auxiliary model requests a
Recoverable failures may include a `failure_recovery_offered` note with the failed stage and retry mode. Chat controls use an opaque runtime recovery ID bound to the exact task and conversation. Starting another run, changing the task, stopping, or choosing Give up expires the offer. Model, response-generation and interaction failures resume through normal continuation checks. For `action_context_unverified`, `action_monitoring_relaxed` identifies one explicitly accepted Retry run on the same task and document; publication Retry remains the separately bound, one-use audit exemption described in the publication contract. Metadata-only `page_action_validation` notes include a finite `certificationFailure` or dispatch `predicate` and a `monitoringRelaxed` boolean. Private grant tokens and target/page content are excluded. Metadata-only `page_traversal_attribution` notes record which attribution a same-document Back/Forward update finally kept (`outcome`: `click_effect`, `page` or `user`) and a finite `reason`; no URL is recorded.
-A consequential tool call may add one `predispatch_timing` note: per-stage milliseconds of its pre-dispatch pipeline (for example `submitProbeMs`, `workflowDispatchMs`, `publicationContractMs`, `publicationAuditMs` or `publicationAuditReusedMs`, `recipientGuardMs`, `checkpointMs`, `executeToolMs`, `totalMs`), the tool name, and an `outcome` of `dispatched`, `not_dispatched` or `blocked`. Stage names vary with the path a call took; readers should treat unknown stages as additional durations. A `publication_prefetch` note records the `status` (`skipped`, `contract_ready`, `authorized`, `denied`, `cached`, `changed` or `failed`) and `durationMs` of a background publication check.
+A consequential tool call may add one `predispatch_timing` note: per-stage milliseconds of its pre-dispatch pipeline (for example `submitProbeMs`, `workflowDispatchMs`, `publicationContractMs`, `publicationAuditMs` or `publicationAuditReusedMs`, `recipientGuardMs`, `checkpointMs`, `executeToolMs`, `totalMs`), the tool name, and an `outcome` of `dispatched`, `not_dispatched` or `blocked`. Stage names vary with the path a call took; readers should treat unknown stages as additional durations. A call stopped before dispatch by a check records `blocked`; one that stopped any other way (a failed preparation, a correction, Stop) records `not_dispatched`, with the rest of its time as `stoppedMs`. A `publication_prefetch` note records the `status` (`skipped`, `contract_ready`, `authorized`, `denied`, `cached`, `changed` or `failed`) and `durationMs` of a background publication check.
Tool events may include an optional `data.outcome` summary containing bounded dispatch, application, provider, error, and CAPTCHA-gate diagnostics. In lossless recordings, this summary survives the content-budget marker, while answer tokens, cookies, provider keys, and form inputs are excluded from the summary. Readers should still honor `_truncated` and `losslessBudgetOmitted`; the summary does not reconstruct discarded content.
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index 514b6202a..5b3e88940 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -9366,6 +9366,7 @@ export class Agent extends LoopDetector {
const stages = {};
const startedAt = Date.now();
let last = startedAt;
+ let emitted = false;
(this._predispatchTimings ||= new Map()).set(tabId, stages);
const add = (stage, ms) => {
if (Number.isFinite(ms) && ms >= 0) stages[stage] = (stages[stage] || 0) + ms;
@@ -9376,9 +9377,12 @@ export class Agent extends LoopDetector {
// The whole pipeline up to this point, e.g. until dispatch begins.
since: stage => add(stage, Date.now() - startedAt),
emit: (step, extra = {}) => {
+ if (emitted) return;
+ emitted = true;
if (this._predispatchTimings?.get(tabId) === stages) this._predispatchTimings.delete(tabId);
this._recordPredispatchTiming(tabId, step, { ...stages, totalMs: Date.now() - startedAt, ...extra });
},
+ get emitted() { return emitted; },
};
}
@@ -9391,6 +9395,24 @@ export class Agent extends LoopDetector {
} catch {}
}
+ // A consequential call that stopped before its dispatch without a note (a
+ // failed preparation, a correction, Stop or any other early stop) gets one
+ // when the next call starts or its batch ends: its stages so far, the rest
+ // of its time as `stoppedMs`.
+ _flushPredispatchTiming(callState) {
+ const pending = callState?.predispatchTiming;
+ if (!pending) return;
+ callState.predispatchTiming = null;
+ const predispatch = pending.timer;
+ if (predispatch.emitted) return;
+ let consequential = false;
+ try { consequential = !!pending.consequential(); } catch {}
+ if (!consequential) return;
+ predispatch.lap('stoppedMs');
+ predispatch.emit(pending.step, { tool: pending.tool,
+ outcome: callState.dispatchState?.started === true ? 'dispatched' : 'not_dispatched' });
+ }
+
_predispatchStage(tabId, stage, ms) {
const stages = this._predispatchTimings?.get(tabId);
if (stages && Number.isFinite(ms) && ms >= 0) stages[stage] = (stages[stage] || 0) + ms;
@@ -15132,6 +15154,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
throw error;
} finally {
this._settleUnverifiedStepScope(tabId);
+ this._flushPredispatchTiming(cancellationState.active);
// Each child owns its nonce boundary and trusted notes. Never re-wrap.
if (parentCalls.length) {
const folded = foldBrowserBatchMessages(messages, { repairPending: true });
@@ -15409,6 +15432,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
const callState = { index: toolIndex, invoked: false, consequential: false, result: null, dispatchState: null,
guardAdvisories: this._trackGuardAdvisories([], tabId) };
+ // The call before this one, if it stopped before dispatch without a timing note.
+ this._flushPredispatchTiming(cancellationState.active);
cancellationState.active = callState;
// The user's 'once' answers this call relies on are spent with it.
this._beginUnverifiedStepScope(tabId);
@@ -15549,6 +15574,20 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// exactly like other tool results.
const predispatch = this._predispatchTimer(tabId);
const protectedPageFailure = await this._chromeProtectedPageFailure(tabId, fnName);
+ // Whether this call can change something: until the permission
+ // capabilities and the submit probe are known, its tool and arguments
+ // decide (reassigned below once they are).
+ let predispatchConsequential = () => !protectedPageFailure && (Agent.STATE_CHANGE_TOOLS.has(fnName)
+ || capabilitiesFor(fnName, fnArgs).length > 0);
+ // A consequential call that a check stops before dispatch still records
+ // where its time went, the wait on a card included. One that stops any
+ // other way gets its note when the next call starts or the batch ends
+ // (_flushPredispatchTiming).
+ const predispatchBlocked = stage => {
+ predispatch.lap(stage);
+ if (predispatchConsequential()) predispatch.emit(step, { tool: fnName, outcome: 'blocked' });
+ };
+ callState.predispatchTiming = { timer: predispatch, step, tool: fnName, consequential: () => predispatchConsequential() };
if (!protectedPageFailure && fnName !== 'done' && !Agent.NAV_TOOLS.has(fnName)) {
try {
await this._adoptLiveSocialPublishWorkflow(tabId, provider);
@@ -15610,6 +15649,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
: this._captchaGateBlockResult(tabId, fnName, fnArgs);
predispatch.lap('captchaGateMs');
if (captchaGateBlock) {
+ if (predispatchConsequential()) predispatch.emit(step, { tool: fnName, outcome: 'blocked' });
// This path returns before normal tool observation. Retain the signup
// checkpoint even when the first detected challenge needs manual help.
const signupRecoveryNote = await this._observeHuggingFaceSignupRecovery(
@@ -15707,6 +15747,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
content: JSON.stringify(mediaTargetGuard),
});
onUpdate('warning', { message: 'Find the visible media permalink before calling download_public_media from a feed.' });
+ predispatchBlocked('preparationMs');
continue;
}
@@ -15751,6 +15792,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
capabilities,
);
if (clarificationAuthorizationBlock) {
+ predispatchBlocked('clarificationMs');
const blockedResult = clarificationAuthorizationBlock.result;
onUpdate('tool_call', { name: fnName, args: fnArgs, outcomeUnknown: false });
onUpdate('tool_result', { name: fnName, result: blockedResult });
@@ -15798,6 +15840,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
await this._ensureGateSetting();
const skillEndpointRedirect = this._skillEndpointToolRedirect(fnName, fnArgs, tabId);
if (skillEndpointRedirect) {
+ predispatchBlocked('clarificationMs');
messages.push({
role: 'tool',
tool_call_id: tc.id,
@@ -15808,6 +15851,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
const mediaDownloadRedirect = await this._downloadPublicMediaRedirectForSocial(tabId, fnName, fnArgs, allowedToolNames, messages);
if (mediaDownloadRedirect) {
+ predispatchBlocked('clarificationMs');
messages.push({
role: 'tool',
tool_call_id: tc.id,
@@ -15820,6 +15864,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
continue;
}
if (isNetworkMutation(fnName, fnArgs) && !apiMutationsAllowedForRun()) {
+ predispatchBlocked('clarificationMs');
const askModeError = apiMutationsDeniedForRun
? `API mutations via ${fnName} are not allowed in Ask mode. Do not retry this mutating API call in this run; continue with read-only tools or return what you can observe.`
: `API mutations via ${fnName} require the user to enable /allow-api for this conversation. Do not retry this mutating API call unless the user enables /allow-api; continue through the visible UI or ask the user to type /allow-api.`;
@@ -15951,15 +15996,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
tabId, fnName, fnArgs, detectedSubmitAction, provider, callState.guardAdvisories,
))
|| this._taskClickLockAsk(tabId, fnName, fnArgs, callState);
- const predispatchConsequential = () => missingResponseOutcomeUnknown
+ // From here the permission capabilities and the submit probe decide.
+ predispatchConsequential = () => missingResponseOutcomeUnknown
|| detectedSubmitAction?.isSubmit === true || detectedSubmitAction?.publicationControl === true;
- // A consequential call that a confirmation card or the permission gate
- // stops still records where its time went, the wait on the card
- // included.
- const predispatchBlocked = stage => {
- predispatch.lap(stage);
- if (predispatchConsequential()) predispatch.emit(step, { tool: fnName, outcome: 'blocked' });
- };
let workflowPreSubmitBlock = await runWorkflowPreSubmitChecks();
if (workflowPreSubmitBlock?.mutationConfirmation
&& this.scheduledRunPolicies.get(tabId)?.requireConsequentialConfirmation !== false) {
diff --git a/src/chrome/src/trace/privacy.js b/src/chrome/src/trace/privacy.js
index 3b24d811a..7be26982e 100644
--- a/src/chrome/src/trace/privacy.js
+++ b/src/chrome/src/trace/privacy.js
@@ -124,7 +124,7 @@ const PREDISPATCH_TIMING_MS_FIELDS = [
'publicationRereadMs', 'submitDetectionMs', 'submitConfirmationMs', 'permissionMs', 'completionChecksMs',
'recipientGuardMs', 'recipientReadingMs', 'checkpointMs', 'pipelineWaitMs', 'toolbarPreflightMs',
'pipelinePublicationMs', 'feedbackRecheckMs', 'genericChatMs', 'attemptCheckpointMs',
- 'dispatchPreparationMs', 'unverifiedStepCardMs', 'preDispatchMs', 'executeToolMs', 'totalMs',
+ 'dispatchPreparationMs', 'unverifiedStepCardMs', 'preDispatchMs', 'executeToolMs', 'stoppedMs', 'totalMs',
];
function projectPredispatchTiming(data) {
const extra = {};
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index ff5faaa0c..602ad7fb3 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -9079,6 +9079,7 @@ export class Agent extends LoopDetector {
const stages = {};
const startedAt = Date.now();
let last = startedAt;
+ let emitted = false;
(this._predispatchTimings ||= new Map()).set(tabId, stages);
const add = (stage, ms) => {
if (Number.isFinite(ms) && ms >= 0) stages[stage] = (stages[stage] || 0) + ms;
@@ -9089,9 +9090,12 @@ export class Agent extends LoopDetector {
// The whole pipeline up to this point, e.g. until dispatch begins.
since: stage => add(stage, Date.now() - startedAt),
emit: (step, extra = {}) => {
+ if (emitted) return;
+ emitted = true;
if (this._predispatchTimings?.get(tabId) === stages) this._predispatchTimings.delete(tabId);
this._recordPredispatchTiming(tabId, step, { ...stages, totalMs: Date.now() - startedAt, ...extra });
},
+ get emitted() { return emitted; },
};
}
@@ -9104,6 +9108,24 @@ export class Agent extends LoopDetector {
} catch {}
}
+ // A consequential call that stopped before its dispatch without a note (a
+ // failed preparation, a correction, Stop or any other early stop) gets one
+ // when the next call starts or its batch ends: its stages so far, the rest
+ // of its time as `stoppedMs`.
+ _flushPredispatchTiming(callState) {
+ const pending = callState?.predispatchTiming;
+ if (!pending) return;
+ callState.predispatchTiming = null;
+ const predispatch = pending.timer;
+ if (predispatch.emitted) return;
+ let consequential = false;
+ try { consequential = !!pending.consequential(); } catch {}
+ if (!consequential) return;
+ predispatch.lap('stoppedMs');
+ predispatch.emit(pending.step, { tool: pending.tool,
+ outcome: callState.dispatchState?.started === true ? 'dispatched' : 'not_dispatched' });
+ }
+
_predispatchStage(tabId, stage, ms) {
const stages = this._predispatchTimings?.get(tabId);
if (stages && Number.isFinite(ms) && ms >= 0) stages[stage] = (stages[stage] || 0) + ms;
@@ -13497,6 +13519,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
throw error;
} finally {
this._settleUnverifiedStepScope(tabId);
+ this._flushPredispatchTiming(cancellationState.active);
// Each child owns its nonce boundary and trusted notes. Never re-wrap.
if (parentCalls.length) {
const folded = foldBrowserBatchMessages(messages, { repairPending: true });
@@ -13770,6 +13793,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
const callState = { index: toolIndex, invoked: false, consequential: false, result: null, dispatchState: null,
guardAdvisories: this._trackGuardAdvisories([], tabId) };
+ // The call before this one, if it stopped before dispatch without a timing note.
+ this._flushPredispatchTiming(cancellationState.active);
cancellationState.active = callState;
// The user's 'once' answers this call relies on are spent with it.
this._beginUnverifiedStepScope(tabId);
@@ -13899,6 +13924,20 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
fnArgs = coordinates.args;
const predispatch = this._predispatchTimer(tabId);
+ // Whether this call can change something: until the permission
+ // capabilities and the submit probe are known, its tool and arguments
+ // decide (reassigned below once they are).
+ let predispatchConsequential = () => (Agent.STATE_CHANGE_TOOLS.has(fnName)
+ || capabilitiesFor(fnName, fnArgs).length > 0);
+ // A consequential call that a check stops before dispatch still records
+ // where its time went, the wait on a card included. One that stops any
+ // other way gets its note when the next call starts or the batch ends
+ // (_flushPredispatchTiming).
+ const predispatchBlocked = stage => {
+ predispatch.lap(stage);
+ if (predispatchConsequential()) predispatch.emit(step, { tool: fnName, outcome: 'blocked' });
+ };
+ callState.predispatchTiming = { timer: predispatch, step, tool: fnName, consequential: () => predispatchConsequential() };
if (fnName !== 'done' && !Agent.NAV_TOOLS.has(fnName)) {
try {
await this._adoptLiveSocialPublishWorkflow(tabId, provider);
@@ -13956,6 +13995,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const captchaGateBlock = this._captchaGateBlockResult(tabId, fnName, fnArgs);
predispatch.lap('captchaGateMs');
if (captchaGateBlock) {
+ if (predispatchConsequential()) predispatch.emit(step, { tool: fnName, outcome: 'blocked' });
// This path returns before normal tool observation. Retain the signup
// checkpoint even when the first detected challenge needs manual help.
const signupRecoveryNote = await this._observeHuggingFaceSignupRecovery(
@@ -14035,6 +14075,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
content: JSON.stringify(mediaTargetGuard),
});
onUpdate('warning', { message: 'Find the visible media permalink before calling download_public_media from a feed.' });
+ predispatchBlocked('preparationMs');
continue;
}
@@ -14074,6 +14115,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
capabilities,
);
if (clarificationAuthorizationBlock) {
+ predispatchBlocked('clarificationMs');
const blockedResult = clarificationAuthorizationBlock.result;
onUpdate('tool_call', { name: fnName, args: fnArgs, outcomeUnknown: false });
onUpdate('tool_result', { name: fnName, result: blockedResult });
@@ -14121,6 +14163,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
await this._ensureGateSetting();
const skillEndpointRedirect = this._skillEndpointToolRedirect(fnName, fnArgs, tabId);
if (skillEndpointRedirect) {
+ predispatchBlocked('clarificationMs');
messages.push({
role: 'tool',
tool_call_id: tc.id,
@@ -14131,6 +14174,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
const mediaDownloadRedirect = await this._downloadPublicMediaRedirectForSocial(tabId, fnName, fnArgs, allowedToolNames, messages);
if (mediaDownloadRedirect) {
+ predispatchBlocked('clarificationMs');
messages.push({
role: 'tool',
tool_call_id: tc.id,
@@ -14143,6 +14187,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
continue;
}
if (isNetworkMutation(fnName, fnArgs) && !apiMutationsAllowedForRun()) {
+ predispatchBlocked('clarificationMs');
const askModeError = apiMutationsDeniedForRun
? `API mutations via ${fnName} are not allowed in Ask mode. Do not retry this mutating API call in this run; continue with read-only tools or return what you can observe.`
: `API mutations via ${fnName} require the user to enable /allow-api for this conversation. Do not retry this mutating API call unless the user enables /allow-api; continue through the visible UI or ask the user to type /allow-api.`;
@@ -14250,15 +14295,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
|| await timedCheck('workflowDispatchMs', () => this._workflowPreSubmitDispatchBlock(
tabId, fnName, fnArgs, detectedSubmitAction, provider, callState.guardAdvisories,
));
- const predispatchConsequential = () => missingResponseOutcomeUnknown
+ // From here the permission capabilities and the submit probe decide.
+ predispatchConsequential = () => missingResponseOutcomeUnknown
|| detectedSubmitAction?.isSubmit === true || detectedSubmitAction?.publicationControl === true;
- // A consequential call that a confirmation card or the permission gate
- // stops still records where its time went, the wait on the card
- // included.
- const predispatchBlocked = stage => {
- predispatch.lap(stage);
- if (predispatchConsequential()) predispatch.emit(step, { tool: fnName, outcome: 'blocked' });
- };
let workflowPreSubmitBlock = await runWorkflowPreSubmitChecks();
if (workflowPreSubmitBlock?.mutationConfirmation
&& this.scheduledRunPolicies.get(tabId)?.requireConsequentialConfirmation !== false) {
diff --git a/src/firefox/src/trace/privacy.js b/src/firefox/src/trace/privacy.js
index 3b24d811a..7be26982e 100644
--- a/src/firefox/src/trace/privacy.js
+++ b/src/firefox/src/trace/privacy.js
@@ -124,7 +124,7 @@ const PREDISPATCH_TIMING_MS_FIELDS = [
'publicationRereadMs', 'submitDetectionMs', 'submitConfirmationMs', 'permissionMs', 'completionChecksMs',
'recipientGuardMs', 'recipientReadingMs', 'checkpointMs', 'pipelineWaitMs', 'toolbarPreflightMs',
'pipelinePublicationMs', 'feedbackRecheckMs', 'genericChatMs', 'attemptCheckpointMs',
- 'dispatchPreparationMs', 'unverifiedStepCardMs', 'preDispatchMs', 'executeToolMs', 'totalMs',
+ 'dispatchPreparationMs', 'unverifiedStepCardMs', 'preDispatchMs', 'executeToolMs', 'stoppedMs', 'totalMs',
];
function projectPredispatchTiming(data) {
const extra = {};
diff --git a/test/publication-prefetch.mjs b/test/publication-prefetch.mjs
index 58c8940b0..63f409961 100644
--- a/test/publication-prefetch.mjs
+++ b/test/publication-prefetch.mjs
@@ -473,6 +473,71 @@ for (const browser of ['chrome', 'firefox']) {
assert.ok(denied.notes[0].timing.permissionMs >= 10, 'the wait on the permission card is recorded');
});
+ test(`${browser}: a consequential call stopped before its cards, or whose preparation fails, still records predispatch_timing`, async () => {
+ const run = async (name, args, stub) => {
+ const f = setup();
+ const { agent, tabId, provider } = f;
+ agent.currentRunId.set(tabId, 'prefetch-run');
+ agent._skipPermissionGate = true;
+ agent._ensureGateSetting = async () => true;
+ agent._persistNow = async () => ({ ok: true });
+ agent.isApiMutationsAllowed = () => false;
+ agent._recordProgressObservation = async () => null;
+ agent._autoRecordProgressAction = () => null;
+ agent._progressWarningForAction = () => '';
+ agent._captureFormValidationState = async () => [];
+ agent._waitForFormValidationFailure = async () => null;
+ agent._readCompletionResult = async () => null;
+ agent._messageRecipientGuardBlock = async () => null;
+ agent._captchaMutationPreflight = async () => null;
+ stub(agent);
+ const dispatched = [];
+ agent.executeTool = async (_tabId, tool) => { dispatched.push(tool); return { success: true, dispatched: true }; };
+ const notes = [];
+ agent._recordPredispatchTiming = (_tabId, step, timing) => notes.push({ step, timing });
+ const messages = [];
+ await agent._executeToolBatch(tabId, [{ id: 'call', function: { name, arguments: JSON.stringify(args) } }],
+ messages, () => {}, provider, '', new Set([name]), 6);
+ return { dispatched, notes, result: String(messages.find(message => message.role === 'tool')?.content || '') };
+ };
+ const click = ['click_ax', { ref_id: 'ref_9' }];
+ // The page did not answer the CAPTCHA safety check in time.
+ const preparationFails = agent => {
+ agent._captchaMutationPreflight = async () => {
+ const error = new Error('The page did not answer in time.');
+ error.code = 'content_action_timeout';
+ throw error;
+ };
+ };
+ for (const [label, [name, args], stub, outcome, stage] of [
+ ['CAPTCHA gate', click, agent => {
+ agent._captchaGateBlockResult = () => ({ success: false, blocked: true, noDispatch: true,
+ error: 'A verification challenge is active.' });
+ agent._observeHuggingFaceSignupRecovery = async () => '';
+ }, 'blocked', 'captchaGateMs'],
+ ['clarification authorization', click, agent => {
+ agent._clarificationAuthorizationBlock = () => ({ result: { success: false, blocked: true,
+ error: 'Answer the clarification first.' } });
+ }, 'blocked', 'clarificationMs'],
+ ['API mutation without /allow-api', ['fetch_url', { url: 'https://api.example.com/items', method: 'POST', body: '{}' }],
+ () => {}, 'blocked', 'clarificationMs'],
+ // Any other stop before dispatch: noted when the batch ends.
+ ['failed preparation', click, preparationFails, 'not_dispatched', 'stoppedMs'],
+ ]) {
+ const stopped = await run(name, args, stub);
+ assert.deepEqual(stopped.dispatched, [], `${label}: nothing was sent`);
+ assert.equal(stopped.notes.length, 1, `${label}: one timing note (${stopped.result.slice(0, 160)})`);
+ const [{ step, timing }] = stopped.notes;
+ assert.equal(step, 6, label);
+ assert.equal(timing.tool, name, label);
+ assert.equal(timing.outcome, outcome, label);
+ assert.equal(typeof timing[stage], 'number', `${label}: ${stage}`);
+ assert.equal(typeof timing.totalMs, 'number', label);
+ }
+ // A read stopped the same way records nothing.
+ assert.equal((await run('get_accessibility_tree', {}, preparationFails)).notes.length, 0);
+ });
+
test(`${browser}: every predispatch stage the agent records survives the trace projection`, async () => {
const fs = await import('node:fs/promises');
const source = await fs.readFile(new URL(`../src/${browser}/src/agent/agent.js`, import.meta.url), 'utf8');