Skip to content

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

Preserve steering through emergency trims and initial responses

Emre Sokullub07e6828adb6
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index bf3eb083c..d40e567de 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -6264,6 +6264,27 @@ export class Agent extends LoopDetector {
}
}
+ async _completeInitialResponseOnlyTurn(tabId, messages, onUpdate, mode, provider, costState, runId, runOptions, gate, enriched, priorMessages) {
+ let revalidated = false;
+ while (gate.proceed && gate.responseOnly) {
+ const capture = {};
+ const response = await this._completeResponseOnlyTurn(
+ tabId, messages, onUpdate, provider, costState, runId, runOptions, enriched, priorMessages, capture,
+ );
+ if (!this._hasPendingSteering(tabId)) return { gate, response, capture, revalidated };
+ onUpdate('text', { content: '', replace: true });
+ const refresh = await this._revalidatePendingSteering(
+ tabId, messages, onUpdate, mode, costState, runId, runOptions,
+ );
+ if (refresh?.gate) {
+ gate = refresh.gate;
+ revalidated = true;
+ }
+ enriched = refresh?.enriched || { role: 'user', content: this._activeTaskBinding(messages).text };
+ }
+ return { gate, revalidated };
+ }
+
activeRunState(tabId) {
const persistenceState = this.persistenceDegradedTabs.get(tabId) || null;
const state = {
@@ -22837,6 +22858,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
const stopped = this._consumeContextOnlyAbort(tabId, messages, onUpdate);
if (stopped) return stopped;
+ // An accepted correction supersedes this answer before it reaches the
+ // transcript, UI, persistence, or voluntary generation sharing.
+ if (this._hasPendingSteering(tabId)) return { content: '', status: 'steering_superseded' };
if (!finalResponse) {
status = 'empty_output';
finalResponse = 'I could not generate a usable response from the existing conversation context.';
@@ -32671,6 +32695,19 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
_emergencyTrimModelCopy(messages) {
const modelCopy = messages.map(message => ({ ...message }));
this._emergencyTrim(modelCopy);
+ // Linked corrections hash their parent task, so even wrapped source in
+ // that authority must stay verbatim across further overflow retries.
+ if (this._activeTaskBinding(messages).pinnedIndices.length > 1) return modelCopy;
+ // A selected-text request can itself contain the oversized source.
+ // Trim only wrapped page data in this disposable model view, retaining
+ // the surrounding user instructions and the complete saved transcript.
+ for (const message of modelCopy) {
+ if (message.role !== 'user' || typeof message.content !== 'string') continue;
+ message.content = message.content.replace(
+ /<untrusted_page_content\b[^>]*>[\s\S]*?<\/untrusted_page_content\b[^>]*>/g,
+ wrapper => wrapper.length > 5000 ? this._truncatePreservingUntrustedWrapper(wrapper, 5000) : wrapper,
+ );
+ }
return modelCopy;
}
@@ -32961,6 +32998,12 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
originalTask = m;
break;
}
+ const taskBinding = this._activeTaskBinding(messages);
+ // Authorized corrections must survive even outside the recent window,
+ // without the truncation applied to intermediate tool results.
+ const pinnedTasks = taskBinding.pinnedIndices.map(index => messages[index]).filter(Boolean);
+ if (originalTask && !pinnedTasks.includes(originalTask)) pinnedTasks.unshift(originalTask);
+ const pinnedTaskSet = new Set(pinnedTasks);
const scheduledResumeIdx = this._findLatestScheduledResumeIndex(messages);
const scheduledResumeMsg = scheduledResumeIdx >= 0 && messages[scheduledResumeIdx] !== originalTask
? messages[scheduledResumeIdx]
@@ -32974,7 +33017,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
const progressIdx = this._findProgressLedgerIndex(messages);
const progressMsg = progressIdx >= 0 ? messages[progressIdx] : null;
const keepLast = 6; // keep only 6 most recent messages
- const recent = messages.slice(-keepLast).filter(m => m !== scheduledResumeMsg && !this._isScheduledResumeTurn(m.content) && !this._isPinnedAgentStateMessage(m));
+ const recent = messages.slice(-keepLast).filter(m => !pinnedTaskSet.has(m) && m !== scheduledResumeMsg && !this._isScheduledResumeTurn(m.content) && !this._isPinnedAgentStateMessage(m));
// Drop any leading `tool` messages whose requesting assistant turn fell
// outside the kept window. Both OpenAI-compatible and Anthropic APIs reject
@@ -33001,16 +33044,16 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
const notice = {
role: 'user',
- content: '[Context was too large for the model. Older intermediate steps were removed, but your ORIGINAL TASK is pinned above — keep working on it based on the most recent state you can see.]',
+ content: '[Context was too large for the model. Older intermediate steps were removed, but the active request and ordered genuine user corrections are pinned above. Apply the latest corrections and keep working from the most recent state.]',
};
const ack = {
role: 'assistant',
- content: 'Understood. I\'ll continue the original task with the recent state.',
+ content: 'Understood. I\'ll continue the active request with its latest corrections and recent state.',
};
messages.length = 0;
messages.push(systemMsg);
- if (originalTask) messages.push(originalTask);
+ messages.push(...pinnedTasks);
if (scheduledResumeMsg) messages.push(scheduledResumeMsg);
if (scratchpadMsg) messages.push(scratchpadMsg);
if (memoryMsg) messages.push(memoryMsg);
@@ -43233,7 +43276,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
);
}
- const gateOutcome = await this._maybeRunPlannerGate(
+ let gateOutcome = await this._maybeRunPlannerGate(
tabId, messages, enriched, onUpdate, mode, costState, runId, plannerTabInfo, runOptions,
);
if (!gateOutcome.proceed) {
@@ -43250,28 +43293,37 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
|| gateOutcome.responseLanguageApprovedPlanOverride === true,
trustedContinuation: runOptions?.trustedContinuation === true,
});
+ let initialResponseRevalidated = false;
if (gateOutcome.responseOnly === true) {
- const responseOnlyShareCapture = {};
- const responseOnly = await this._completeResponseOnlyTurn(
- tabId, messages, onUpdate, provider, costState, runId,
- runOptions, enriched, sourceBoundPriorMessages, responseOnlyShareCapture,
+ const responseOutcome = await this._completeInitialResponseOnlyTurn(
+ tabId, messages, onUpdate, mode, provider, costState, runId,
+ runOptions, gateOutcome, enriched, sourceBoundPriorMessages,
);
- finalResponse = responseOnly.content;
- _traceStatus = responseOnly.status;
- // Response-only turns do call the model (source-grounded + pruned
- // inside _generateContextOnlyResponse). Only mark shareable on success,
- // keeping the exact request (with the context-only system prompt).
- if (responseOnly.status === 'done') {
- shareHadProviderCompletion = true;
- shareRawResponse = responseOnlyShareCapture.response;
- if (Array.isArray(responseOnlyShareCapture.request) && responseOnlyShareCapture.request.length) {
- currentNonStreamRequestMessages = responseOnlyShareCapture.request;
+ gateOutcome = responseOutcome.gate;
+ initialResponseRevalidated = responseOutcome.revalidated;
+ if (!gateOutcome.proceed) {
+ _traceStatus = gateOutcome.reason === 'plan_only' ? 'plan_only_output' : gateOutcome.reason || 'cancelled';
+ return (finalResponse = gateOutcome.message || 'More information is required.');
+ }
+ const { response: responseOnly, capture: responseOnlyShareCapture } = responseOutcome;
+ if (responseOnly) {
+ finalResponse = responseOnly.content;
+ _traceStatus = responseOnly.status;
+ // Response-only turns do call the model (source-grounded + pruned
+ // inside _generateContextOnlyResponse). Only mark shareable on success,
+ // keeping the exact request (with the context-only system prompt).
+ if (responseOnly.status === 'done') {
+ shareHadProviderCompletion = true;
+ shareRawResponse = responseOnlyShareCapture.response;
+ if (Array.isArray(responseOnlyShareCapture.request) && responseOnlyShareCapture.request.length) {
+ currentNonStreamRequestMessages = responseOnlyShareCapture.request;
+ }
}
+ return finalResponse;
}
- return finalResponse;
}
if (this._consumeSelectionGroundingRestoration(tabId, enriched)) this._persist(tabId);
- this._startPlanExecutionGuard(tabId, mode, gateOutcome, runOptions);
+ if (!initialResponseRevalidated) this._startPlanExecutionGuard(tabId, mode, gateOutcome, runOptions);
if (this._isActionMode(mode) && !selectionOnly && !standaloneChatRun) {
await this._ensureProgressSessionForCurrentTask(tabId, {
@@ -43477,7 +43529,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
this._appendStandaloneUngroundedPolicy(enriched, standaloneGroundingGap);
}
- const recommendedFirstTool = await this._maybeExecuteRecommendedActionFirstTool(
+ const recommendedFirstTool = initialResponseRevalidated ? null : await this._maybeExecuteRecommendedActionFirstTool(
tabId, runOptions, messages, onUpdate, provider, allowedToolNames, toolSchemas,
);
if (recommendedFirstTool?.action === 'return') {
@@ -44581,7 +44633,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
);
}
- const gateOutcome = await this._maybeRunPlannerGate(
+ let gateOutcome = await this._maybeRunPlannerGate(
tabId, messages, enriched, onUpdate, mode, costState, runId, plannerTabInfo, runOptions,
);
if (!gateOutcome.proceed) {
@@ -44598,23 +44650,32 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
|| gateOutcome.responseLanguageApprovedPlanOverride === true,
trustedContinuation: runOptions?.trustedContinuation === true,
});
+ let initialResponseRevalidated = false;
if (gateOutcome.responseOnly === true) {
- const responseOnlyShareCapture = {};
- const responseOnly = await this._completeResponseOnlyTurn(
- tabId, messages, onUpdate, provider, costState, runId,
- runOptions, enriched, sourceBoundPriorMessages, responseOnlyShareCapture,
+ const responseOutcome = await this._completeInitialResponseOnlyTurn(
+ tabId, messages, onUpdate, mode, provider, costState, runId,
+ runOptions, gateOutcome, enriched, sourceBoundPriorMessages,
);
- if (responseOnly.status === 'done') {
- shareHadProviderCompletion = true;
- shareRawResponse = responseOnlyShareCapture.response;
- if (Array.isArray(responseOnlyShareCapture.request) && responseOnlyShareCapture.request.length) {
- currentStreamRequestMessages = responseOnlyShareCapture.request;
+ gateOutcome = responseOutcome.gate;
+ initialResponseRevalidated = responseOutcome.revalidated;
+ if (!gateOutcome.proceed) {
+ const status = gateOutcome.reason === 'plan_only' ? 'plan_only_output' : gateOutcome.reason || 'cancelled';
+ return finish(gateOutcome.message || 'More information is required.', status);
+ }
+ const { response: responseOnly, capture: responseOnlyShareCapture } = responseOutcome;
+ if (responseOnly) {
+ if (responseOnly.status === 'done') {
+ shareHadProviderCompletion = true;
+ shareRawResponse = responseOnlyShareCapture.response;
+ if (Array.isArray(responseOnlyShareCapture.request) && responseOnlyShareCapture.request.length) {
+ currentStreamRequestMessages = responseOnlyShareCapture.request;
+ }
}
+ return finish(responseOnly.content, responseOnly.status);
}
- return finish(responseOnly.content, responseOnly.status);
}
if (this._consumeSelectionGroundingRestoration(tabId, enriched)) this._persist(tabId);
- this._startPlanExecutionGuard(tabId, mode, gateOutcome, runOptions);
+ if (!initialResponseRevalidated) this._startPlanExecutionGuard(tabId, mode, gateOutcome, runOptions);
let standaloneGroundingGap = this._standaloneOfflineGroundingGap(localWikipediaRag, runOptions);
if (standaloneGroundingGap) {
@@ -44678,7 +44739,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
// currentStreamRequestMessages is declared at the top of this function so
// pre-loop exits (e.g. response-only turns) can capture their request.
- const recommendedFirstTool = await this._maybeExecuteRecommendedActionFirstTool(
+ const recommendedFirstTool = initialResponseRevalidated ? null : await this._maybeExecuteRecommendedActionFirstTool(
tabId, runOptions, messages, onUpdate, provider, allowedToolNames, toolSchemas,
);
if (recommendedFirstTool?.action === 'return') {
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index 460176a96..9704135f8 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -5978,6 +5978,27 @@ export class Agent extends LoopDetector {
}
}
+ async _completeInitialResponseOnlyTurn(tabId, messages, onUpdate, mode, provider, costState, runId, runOptions, gate, enriched, priorMessages) {
+ let revalidated = false;
+ while (gate.proceed && gate.responseOnly) {
+ const capture = {};
+ const response = await this._completeResponseOnlyTurn(
+ tabId, messages, onUpdate, provider, costState, runId, runOptions, enriched, priorMessages, capture,
+ );
+ if (!this._hasPendingSteering(tabId)) return { gate, response, capture, revalidated };
+ onUpdate('text', { content: '', replace: true });
+ const refresh = await this._revalidatePendingSteering(
+ tabId, messages, onUpdate, mode, costState, runId, runOptions,
+ );
+ if (refresh?.gate) {
+ gate = refresh.gate;
+ revalidated = true;
+ }
+ enriched = refresh?.enriched || { role: 'user', content: this._activeTaskBinding(messages).text };
+ }
+ return { gate, revalidated };
+ }
+
activeRunState(tabId) {
const persistenceState = this.persistenceDegradedTabs.get(tabId) || null;
const state = {
@@ -20633,6 +20654,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
const stopped = this._consumeContextOnlyAbort(tabId, messages, onUpdate);
if (stopped) return stopped;
+ // An accepted correction supersedes this answer before it reaches the
+ // transcript, UI, persistence, or voluntary generation sharing.
+ if (this._hasPendingSteering(tabId)) return { content: '', status: 'steering_superseded' };
if (!finalResponse) {
status = 'empty_output';
finalResponse = 'I could not generate a usable response from the existing conversation context.';
@@ -30269,6 +30293,19 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
_emergencyTrimModelCopy(messages) {
const modelCopy = messages.map(message => ({ ...message }));
this._emergencyTrim(modelCopy);
+ // Linked corrections hash their parent task, so even wrapped source in
+ // that authority must stay verbatim across further overflow retries.
+ if (this._activeTaskBinding(messages).pinnedIndices.length > 1) return modelCopy;
+ // A selected-text request can itself contain the oversized source.
+ // Trim only wrapped page data in this disposable model view, retaining
+ // the surrounding user instructions and the complete saved transcript.
+ for (const message of modelCopy) {
+ if (message.role !== 'user' || typeof message.content !== 'string') continue;
+ message.content = message.content.replace(
+ /<untrusted_page_content\b[^>]*>[\s\S]*?<\/untrusted_page_content\b[^>]*>/g,
+ wrapper => wrapper.length > 5000 ? this._truncatePreservingUntrustedWrapper(wrapper, 5000) : wrapper,
+ );
+ }
return modelCopy;
}
@@ -30558,6 +30595,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
originalTask = m;
break;
}
+ const taskBinding = this._activeTaskBinding(messages);
+ // Authorized corrections must survive even outside the recent window,
+ // without the truncation applied to intermediate tool results.
+ const pinnedTasks = taskBinding.pinnedIndices.map(index => messages[index]).filter(Boolean);
+ if (originalTask && !pinnedTasks.includes(originalTask)) pinnedTasks.unshift(originalTask);
+ const pinnedTaskSet = new Set(pinnedTasks);
const scheduledResumeIdx = this._findLatestScheduledResumeIndex(messages);
const scheduledResumeMsg = scheduledResumeIdx >= 0 && messages[scheduledResumeIdx] !== originalTask
? messages[scheduledResumeIdx]
@@ -30571,7 +30614,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const progressIdx = this._findProgressLedgerIndex(messages);
const progressMsg = progressIdx >= 0 ? messages[progressIdx] : null;
const keepLast = 6; // keep only 6 most recent messages
- const recent = messages.slice(-keepLast).filter(m => m !== scheduledResumeMsg && !this._isScheduledResumeTurn(m.content) && !this._isPinnedAgentStateMessage(m));
+ const recent = messages.slice(-keepLast).filter(m => !pinnedTaskSet.has(m) && m !== scheduledResumeMsg && !this._isScheduledResumeTurn(m.content) && !this._isPinnedAgentStateMessage(m));
// Drop any leading `tool` messages whose requesting assistant turn fell
// outside the kept window. Both OpenAI-compatible and Anthropic APIs reject
@@ -30598,16 +30641,16 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const notice = {
role: 'user',
- content: '[Context was too large for the model. Older intermediate steps were removed, but your ORIGINAL TASK is pinned above — keep working on it based on the most recent state you can see.]',
+ content: '[Context was too large for the model. Older intermediate steps were removed, but the active request and ordered genuine user corrections are pinned above. Apply the latest corrections and keep working from the most recent state.]',
};
const ack = {
role: 'assistant',
- content: 'Understood, some earlier context was trimmed. I\'ll continue with what I have.',
+ content: 'Understood. I\'ll continue the active request with its latest corrections and recent state.',
};
messages.length = 0;
messages.push(systemMsg);
- if (originalTask) messages.push(originalTask);
+ messages.push(...pinnedTasks);
if (scheduledResumeMsg) messages.push(scheduledResumeMsg);
if (scratchpadMsg) messages.push(scratchpadMsg);
if (memoryMsg) messages.push(memoryMsg);
@@ -36197,7 +36240,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
);
}
- const gateOutcome = await this._maybeRunPlannerGate(
+ let gateOutcome = await this._maybeRunPlannerGate(
tabId, messages, enriched, onUpdate, mode, costState, runId, plannerTabInfo, runOptions,
);
if (!gateOutcome.proceed) {
@@ -36214,28 +36257,37 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
|| gateOutcome.responseLanguageApprovedPlanOverride === true,
trustedContinuation: runOptions?.trustedContinuation === true,
});
+ let initialResponseRevalidated = false;
if (gateOutcome.responseOnly === true) {
- const responseOnlyShareCapture = {};
- const responseOnly = await this._completeResponseOnlyTurn(
- tabId, messages, onUpdate, provider, costState, runId,
- runOptions, enriched, sourceBoundPriorMessages, responseOnlyShareCapture,
+ const responseOutcome = await this._completeInitialResponseOnlyTurn(
+ tabId, messages, onUpdate, mode, provider, costState, runId,
+ runOptions, gateOutcome, enriched, sourceBoundPriorMessages,
);
- finalResponse = responseOnly.content;
- _traceStatus = responseOnly.status;
- // Response-only turns do call the model (source-grounded + pruned
- // inside _generateContextOnlyResponse). Only mark shareable on success,
- // keeping the exact request (with the context-only system prompt).
- if (responseOnly.status === 'done') {
- shareHadProviderCompletion = true;
- shareRawResponse = responseOnlyShareCapture.response;
- if (Array.isArray(responseOnlyShareCapture.request) && responseOnlyShareCapture.request.length) {
- currentNonStreamRequestMessages = responseOnlyShareCapture.request;
+ gateOutcome = responseOutcome.gate;
+ initialResponseRevalidated = responseOutcome.revalidated;
+ if (!gateOutcome.proceed) {
+ _traceStatus = gateOutcome.reason === 'plan_only' ? 'plan_only_output' : gateOutcome.reason || 'cancelled';
+ return (finalResponse = gateOutcome.message || 'More information is required.');
+ }
+ const { response: responseOnly, capture: responseOnlyShareCapture } = responseOutcome;
+ if (responseOnly) {
+ finalResponse = responseOnly.content;
+ _traceStatus = responseOnly.status;
+ // Response-only turns do call the model (source-grounded + pruned
+ // inside _generateContextOnlyResponse). Only mark shareable on success,
+ // keeping the exact request (with the context-only system prompt).
+ if (responseOnly.status === 'done') {
+ shareHadProviderCompletion = true;
+ shareRawResponse = responseOnlyShareCapture.response;
+ if (Array.isArray(responseOnlyShareCapture.request) && responseOnlyShareCapture.request.length) {
+ currentNonStreamRequestMessages = responseOnlyShareCapture.request;
+ }
}
+ return finalResponse;
}
- return finalResponse;
}
if (this._consumeSelectionGroundingRestoration(tabId, enriched)) this._persist(tabId);
- this._startPlanExecutionGuard(tabId, mode, gateOutcome, runOptions);
+ if (!initialResponseRevalidated) this._startPlanExecutionGuard(tabId, mode, gateOutcome, runOptions);
if (this._isActionMode(mode) && !selectionOnly && !standaloneChatRun) {
await this._ensureProgressSessionForCurrentTask(tabId, {
@@ -36430,7 +36482,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
);
}
- const recommendedFirstTool = await this._maybeExecuteRecommendedActionFirstTool(
+ const recommendedFirstTool = initialResponseRevalidated ? null : await this._maybeExecuteRecommendedActionFirstTool(
tabId, runOptions, messages, onUpdate, provider, allowedToolNames, toolSchemas,
);
if (recommendedFirstTool?.action === 'return') {
@@ -37376,7 +37428,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
);
}
- const gateOutcome = await this._maybeRunPlannerGate(
+ let gateOutcome = await this._maybeRunPlannerGate(
tabId, messages, enriched, onUpdate, mode, costState, runId, plannerTabInfo, runOptions,
);
if (!gateOutcome.proceed) {
@@ -37393,23 +37445,32 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
|| gateOutcome.responseLanguageApprovedPlanOverride === true,
trustedContinuation: runOptions?.trustedContinuation === true,
});
+ let initialResponseRevalidated = false;
if (gateOutcome.responseOnly === true) {
- const responseOnlyShareCapture = {};
- const responseOnly = await this._completeResponseOnlyTurn(
- tabId, messages, onUpdate, provider, costState, runId,
- runOptions, enriched, sourceBoundPriorMessages, responseOnlyShareCapture,
+ const responseOutcome = await this._completeInitialResponseOnlyTurn(
+ tabId, messages, onUpdate, mode, provider, costState, runId,
+ runOptions, gateOutcome, enriched, sourceBoundPriorMessages,
);
- if (responseOnly.status === 'done') {
- shareHadProviderCompletion = true;
- shareRawResponse = responseOnlyShareCapture.response;
- if (Array.isArray(responseOnlyShareCapture.request) && responseOnlyShareCapture.request.length) {
- currentStreamRequestMessages = responseOnlyShareCapture.request;
+ gateOutcome = responseOutcome.gate;
+ initialResponseRevalidated = responseOutcome.revalidated;
+ if (!gateOutcome.proceed) {
+ const status = gateOutcome.reason === 'plan_only' ? 'plan_only_output' : gateOutcome.reason || 'cancelled';
+ return finish(gateOutcome.message || 'More information is required.', status);
+ }
+ const { response: responseOnly, capture: responseOnlyShareCapture } = responseOutcome;
+ if (responseOnly) {
+ if (responseOnly.status === 'done') {
+ shareHadProviderCompletion = true;
+ shareRawResponse = responseOnlyShareCapture.response;
+ if (Array.isArray(responseOnlyShareCapture.request) && responseOnlyShareCapture.request.length) {
+ currentStreamRequestMessages = responseOnlyShareCapture.request;
+ }
}
+ return finish(responseOnly.content, responseOnly.status);
}
- return finish(responseOnly.content, responseOnly.status);
}
if (this._consumeSelectionGroundingRestoration(tabId, enriched)) this._persist(tabId);
- this._startPlanExecutionGuard(tabId, mode, gateOutcome, runOptions);
+ if (!initialResponseRevalidated) this._startPlanExecutionGuard(tabId, mode, gateOutcome, runOptions);
if (this._isActionMode(mode) && !selectionOnly && !standaloneChatRun) {
await this._ensureProgressSessionForCurrentTask(tabId, {
@@ -37460,7 +37521,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// currentStreamRequestMessages is declared at the top of this function so
// pre-loop exits (e.g. response-only turns) can capture their request.
- const recommendedFirstTool = await this._maybeExecuteRecommendedActionFirstTool(
+ const recommendedFirstTool = initialResponseRevalidated ? null : await this._maybeExecuteRecommendedActionFirstTool(
tabId, runOptions, messages, onUpdate, provider, allowedToolNames, toolSchemas,
);
if (recommendedFirstTool?.action === 'return') {
diff --git a/test/chat-steering.mjs b/test/chat-steering.mjs
index 7cfe9f8a6..cb376a124 100644
--- a/test/chat-steering.mjs
+++ b/test/chat-steering.mjs
@@ -116,6 +116,60 @@ for (const build of ['chrome', 'firefox']) {
});
for (const streaming of [false, true]) {
+ for (const mode of ['act', 'dev']) {
+ for (const revisedKind of ['respond', 'execute']) {
+ test(`${build}: ${mode} ${streaming ? 'stream' : 'chat'} initial response-only steering switches to ${revisedKind}`, async () => {
+ const entered = deferred(), release = deferred(), updates = [], persisted = [], dispatched = [];
+ let modelCalls = 0, plannerCalls = 0;
+ const next = async () => {
+ if (++modelCalls === 1) {
+ entered.resolve(); await release.promise;
+ return { content: 'Obsolete initial answer' };
+ }
+ if (revisedKind === 'respond') return { content: 'Revised answer' };
+ if (modelCalls === 2) return { toolCalls: [{ id: 'dashboard', function: { name: 'navigate', arguments: '{"url":"https://example.com/dashboard"}' } }] };
+ return { toolCalls: [{ id: 'finished', function: { name: 'done', arguments: '{"summary":"Dashboard opened","outcome":"success"}' } }] };
+ };
+ const agent = actSetup(Agent, {
+ chat: next,
+ async *chatStream() {
+ const result = await next();
+ if (result.content) yield { type: 'text', content: result.content };
+ if (result.toolCalls) yield { type: 'tool_call', content: result.toolCalls };
+ yield { type: 'done' };
+ },
+ }, async (_tab, enriched) => {
+ if (++plannerCalls > 1) assert.match(enriched.content, /Use the revised request/);
+ return plannerCalls > 1 && revisedKind === 'execute'
+ ? { proceed: true, requestKind: 'execute', requiresStateChange: true, requiresSubmission: false }
+ : { proceed: true, responseOnly: true, requestKind: 'respond', requiresStateChange: false, requiresSubmission: false };
+ });
+ agent._persist = () => persisted.push(structuredClone(agent.conversations.get(tabId) || []));
+ if (revisedKind === 'execute') agent._maybeExecuteRecommendedActionFirstTool = async () => assert.fail('Superseded initial recommendations must not run');
+ agent.executeTool = async (_tab, name, args) => {
+ if (name === 'done') {
+ assert.equal(agent._planOnlyTerminalDecision(tabId, args.summary, { viaDone: true, outcome: args.outcome }), null);
+ return { done: true, summary: args.summary, outcome: args.outcome };
+ }
+ dispatched.push(args.url); return { success: true, url: args.url };
+ };
+ const update = (type, data) => updates.push({ type, data });
+ const run = streaming
+ ? agent.processMessageStream(tabId, 'Explain the event', update, mode, options)
+ : agent.processMessage(tabId, 'Explain the event', update, mode, [], options);
+ await Promise.race([entered.promise, run.then(result => assert.fail(`Early completion: ${result}`))]);
+ assert.equal(steer(agent, 'Use the revised request').accepted, true);
+ release.resolve();
+ assert.equal(await run, revisedKind === 'respond' ? 'Revised answer' : 'Dashboard opened');
+ assert.equal(plannerCalls, 2);
+ assert.equal(updates.some(update => update.type === 'steering_queued'), false);
+ assert.equal(updates.some(update => update.type === 'text' && update.data.content === 'Obsolete initial answer'), false);
+ assert.equal(persisted.some(messages => messages.some(message => message.role === 'assistant' && message.content === 'Obsolete initial answer')), false);
+ assert.deepEqual(dispatched, revisedKind === 'execute' ? ['https://example.com/dashboard'] : []);
+ });
+ }
+ }
+
test(`${build}: ${streaming ? 'stream' : 'chat'} reauthorizes Ipek steering with the real Act guard`, async () => {
const entered = deferred(), release = deferred();
const plans = [], dispatched = [], requests = [];
@@ -472,6 +526,50 @@ for (const build of ['chrome', 'firefox']) {
agent._finishSteeringRun(tabId); agent._releaseRunEntry(tabId);
});
+ test(`${build}: emergency trims preserve authorized steering and attempt receipts verbatim`, async () => {
+ const agent = actSetup(Agent);
+ await agent._claimRunEntry(tabId, 'interactive', options); agent._beginSteeringRun(tabId, () => {}, options);
+ const task = `Add the event to my calendar.\n${agent._wrapUntrusted('read_page', 'Invitation source '.repeat(500))}`;
+ const messages = [{ role: 'system', content: 'sys' }, { role: 'user', content: task }];
+ agent.conversations.set(tabId, messages);
+ const guard = agent._startPlanExecutionGuard(tabId, 'act', { requiresStateChange: true });
+ guard.steeringPriorSubmission = { dispatched: true, observedAfterSubmit: false };
+ steer(agent, 'Use Ipek’s corrected details '.repeat(400), 'early');
+ await agent._revalidatePendingSteering(tabId, messages, () => {}, 'act', null, null, options);
+ for (let i = 0; i < 8; i++) {
+ messages.push({ role: 'assistant', tool_calls: [{ id: `read-${i}`, function: { name: 'read_page', arguments: '{}' } }] },
+ { role: 'tool', tool_call_id: `read-${i}`, content: agent._wrapUntrusted('read_page', 'Earlier page observation '.repeat(300)) });
+ }
+ steer(agent, 'Use the work calendar '.repeat(400), 'recent');
+ await agent._revalidatePendingSteering(tabId, messages, () => {}, 'act', null, null, options);
+ const binding = agent._activeTaskBinding(messages);
+ const pinned = binding.pinnedIndices.map(index => structuredClone(messages[index]));
+ const before = structuredClone(messages);
+ const modelCopy = agent._emergencyTrimModelCopy(messages);
+ assert.deepEqual(messages, before, 'Model-copy trim does not mutate the transcript');
+ agent._emergencyTrim(messages);
+ for (const trimmed of [messages, modelCopy]) {
+ assert.equal(agent._activeTaskBinding(trimmed).text, binding.text);
+ assert.equal(agent._activeTaskBinding(trimmed).priorSubmission.dispatched, true);
+ for (const message of pinned) assert.equal(trimmed.filter(candidate => JSON.stringify(candidate) === JSON.stringify(message)).length, 1);
+ assertPairedTools(trimmed);
+ }
+ agent._finishSteeringRun(tabId); agent._releaseRunEntry(tabId);
+ });
+
+ test(`${build}: emergency model copies trim source data while preserving surrounding instructions`, () => {
+ const agent = setup(Agent);
+ const source = agent._wrapUntrusted('read_page', `${'Selected source '.repeat(600)}SOURCE_TAIL`);
+ const messages = [{ role: 'system', content: 'sys' }, { role: 'user', content: `Summarize only this source.\n${source}\nUse the specified output format.` }];
+ const copy = agent._emergencyTrimModelCopy(messages);
+ const request = copy.find(message => message.role === 'user' && message.content.startsWith('Summarize only this source.'));
+ assert.ok(request);
+ assert.equal(agent._hasUntrustedWrapper(request.content), true);
+ assert.doesNotMatch(request.content, /SOURCE_TAIL/);
+ assert.ok(request.content.endsWith('Use the specified output format.'));
+ assert.match(messages[1].content, /SOURCE_TAIL/);
+ });
+
test(`${build}: steering invalidates a real plan review and requires review of the latest revision`, async () => {
const agent = actSetup(Agent);
agent._plannerMode = () => 'try'; agent.setPlanReviewSettings({ mode: 'always' });