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
Show plain-language final answers and render chat blockquotes
Claude103ec5f99d64
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex a660f3871..aa824813b 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -158,6 +158,7 @@ import { GENERATIVE_MEDIA_SETUP_NOTE, isImageGenConfigured, mediaPermissionUrl,import { extractFirstJsonObject } from './json-extract.js';import { repairAssistantDisplayText, repairClarifyText, sanitizeText as sanitizePlannerText } from './text-sanitize.js';import { emptyOutputFailureMessage, modelOutputDiagnostics } from './model-output-diagnostics.js';+import { stepLimitUserMessage, terminalGuardUserMessage } from './terminal-messages.js';import { buildCustomSkillsPrompt, buildSkillLoaderDefinition, buildSkillToolDefinitions, buildSkillToolRegistry, getEligibleCustomSkills, getEligibleSkillCatalog, normalizeCustomSkills } from './skills.js';import { OTP_EMAIL_PROVIDER_IDS, OTP_EMAIL_SKILL_ID, OTP_EMAIL_TOOL_NAME, otpEmailCandidates, otpEmailProviderForUrl, otpEmailUrlLooksLikeMessage, otpOpenMessageRootRef, otpRedactRefs, otpServiceDisplay, otpServiceKey, otpVerificationMessageExcerpt, selectOtpMailboxTab, selectUniqueOtpCandidateByPreview } from './otp-email-tool.js';import { publicMediaUrlNeedsExplicitTarget } from './public-media-url.js';@@ -10663,55 +10664,22 @@ export class Agent extends LoopDetector {}/**- * Synthesize a transparent summary when the agent hits the step limit- * without producing a final answer. Walks the conversation to count- * tool usage and surface the last non-empty assistant message and the- * last tool call, so the user sees WHY the run ended instead of an- * empty `done` event. Pure deterministic β no extra LLM call.+ * Plain-language account of a run that hit the step limit without a final+ * answer. The tool inventory and arguments remain in the trace and verbose+ * rows; the chat explains the limit and quotes the last thing the agent+ * said, if anything. Pure deterministic β no extra LLM call.*/_buildStepLimitSummary(messages, steps) {- const toolCounts = new Map();let lastAssistantText = '';- let lastToolCall = null;const binding = this._activeTaskBinding(messages);// Earlier attempts remain in history, but this handoff describes the// latest authorized revision rather than quoting its superseded answer.const summaryMessages = binding.updates?.some(update => update.kind === 'steering')? messages.slice(binding.index + 1) : messages;for (const m of summaryMessages) {- if (m.role === 'assistant') {- if (Array.isArray(m.tool_calls)) {- for (const tc of m.tool_calls) {- const name = tc?.function?.name || tc?.name;- if (name) {- toolCounts.set(name, (toolCounts.get(name) || 0) + 1);- lastToolCall = { name, args: tc?.function?.arguments || tc?.arguments || '' };- }- }- }- if (typeof m.content === 'string' && m.content.trim()) {- lastAssistantText = m.content;- }- }+ if (m.role === 'assistant' && typeof m.content === 'string' && m.content.trim()) lastAssistantText = m.content;}- const sortedTools = [...toolCounts.entries()]- .sort((a, b) => b[1] - a[1])- .slice(0, 6)- .map(([n, c]) => `${n} Γ${c}`)- .join(', ');- const lastActionLine = lastToolCall- ? `Last tool attempted: ${lastToolCall.name}${lastToolCall.args ? ' (' + String(lastToolCall.args).slice(0, 120) + ')' : ''}`- : '';- const lastTextSnippet = lastAssistantText- ? `Last thing I said: "${lastAssistantText.slice(0, 280).replace(/\s+/g, ' ').trim()}${lastAssistantText.length > 280 ? 'β¦' : ''}"`- : '';- return [- `[Step limit reached after ${steps} steps without completing the task.`,- sortedTools ? `Tools attempted: ${sortedTools}.` : '',- lastActionLine,- lastTextSnippet,- 'This usually means: (a) the task is too complex for the current model β try a stronger one, (b) the step limit is too low β raise it in Settings, or (c) the strategy was wrong β try breaking it into smaller parts.]',- ].filter(Boolean).join('\n\n');+ return stepLimitUserMessage(steps, lastAssistantText);}_stepLimitRecoveryEligible(provider, runOptions = {}) {@@ -15651,12 +15619,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}if (planOnlyDecision?.failure) {await cancelPendingResumes();+ // The tool result keeps the guard's diagnostic for verbose rows,+ // traces and later model turns; the chat shows the plain account.const failedResult = {success: false,done: true,outcome: 'failed',planOnlyTerminal: true,- summary: planOnlyDecision.failure,+ summary: planOnlyDecision.userMessage || planOnlyDecision.failure,error: planOnlyDecision.failure,};onUpdate('tool_result', { name: fnName, result: failedResult });@@ -15671,7 +15641,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d() => ({ success: false, skipped: true, error: 'skipped: plan-only completion failed' }));this._persist(tabId);- return { action: 'return', value: planOnlyDecision.failure, status: 'plan_only_output' };+ return { action: 'return', value: planOnlyDecision.userMessage || planOnlyDecision.failure,+ status: planOnlyDecision.status || 'plan_only_output' };}let rawDoneSummary = toolResult.summary || partialAssistantText || 'Task completed.';if (!scheduledResume && this._looksLikeMetaOnlyDoneSummary(rawDoneSummary)) {@@ -19683,7 +19654,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}_clarificationAuthorizationStopMessage() {- return '[Agent stopped before dispatching another action or accepting a success completion because the latest clarification answer was auto-selected after a timeout and was not user authorization. Please answer the clarification explicitly and retry.]';+ // The block itself (a timeout-selected answer is not authorization) is+ // recorded on the refused tool result; the chat asks for a real answer.+ return terminalGuardUserMessage('clarification_required');}_clarificationAuthorizationPlainFinalDecision(tabId) {@@ -22085,6 +22058,25 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn progress.missing.map(id => social.contract.actions.find(a => a.id === id)?.platform || id);}+ /** Platform names only: which destinations were verified, dispatched but unconfirmed, or never published. */+ _socialPublicationOutcomeFacts(guard) {+ const social = guard?.socialPublication;+ const facts = { verified: [], unconfirmed: [], notStarted: [] };+ if (!social?.contract || social.contract.status !== 'ready') {+ facts.notStarted.push(guard?.siteWorkflow?.adapterName || 'unresolved_intent');+ return facts;+ }+ const missing = new Set(publicationProgress(social.contract, social.outcomes).missing);+ for (const action of social.contract.actions || []) {+ const status = social.outcomes?.[action.id]?.status;+ if (status === 'verified') facts.verified.push(action.platform);+ else if (!missing.has(action.id)) continue;+ else if (status === 'pending') facts.unconfirmed.push(action.platform);+ else facts.notStarted.push(action.platform);+ }+ return facts;+ }+async _adoptLiveSocialPublishWorkflow(tabId, provider, detected = null) {const guard = this._planExecutionGuards.get(tabId);if (!guard?.enabled) return false;@@ -35234,6 +35226,11 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai_planOnlyTerminalDecision(tabId, content, { viaDone = false, outcome = null } = {}) {const state = this._planExecutionGuards.get(tabId);if (!state?.enabled) return null;+ // The bracketed diagnostic stays in tool results and traces; the chat+ // shows a plain-language account of what happened.+ const terminal = (kind, failure, status, facts = {}) => ({ failure, status,+ userMessage: terminalGuardUserMessage(kind, { consequential: state.successfulConsequentialToolCalls > 0,+ readOnly: state.successfulTaskToolCalls > 0, ...facts }) });if (state.taskKey && this._progressTaskKeyHash(tabId) !== state.taskKey) state.taskDrifted = true;const recoveryAnchor = this._executionTaskRecoveryAnchor(state);if (!viaDone && this._isSafetyRefusalTerminal(content)) return null;@@ -35339,91 +35336,76 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai};}if (state.taskDrifted) {- return {- failure: 'The user task changed after this run was authorized, so WebBrain discarded its execution evidence and stopped. Start a fresh run for the current task.',- status: 'task_binding_changed',- };+ return terminal('task_changed',+ 'The user task changed after this run was authorized, so WebBrain discarded its execution evidence and stopped. Start a fresh run for the current task.',+ 'task_binding_changed');}if (missingRequiredSchedulingTool) {- return {- failure: `[Agent stopped because the approved plan required ${state.requiredSchedulingTool}, but no successful matching scheduling call was verified after one recovery nudge. The task may have performed one-time actions, but the requested future work was not scheduled.]`,- status: 'required_tool_missing',- };+ return terminal('schedule_missing',+ `[Agent stopped because the approved plan required ${state.requiredSchedulingTool}, but no successful matching scheduling call was verified after one recovery nudge. The task may have performed one-time actions, but the requested future work was not scheduled.]`,+ 'required_tool_missing');}if (missingRequiredDownload) {- return {- failure: '[Agent stopped because the approved task required a downloaded file, but no successful DOWNLOAD-capability tool result was verified after one recovery nudge. A URL, link, media-resolution result, or unrelated page action does not prove that a file was saved.]',- status: 'required_tool_missing',- };+ return terminal('download_missing',+ '[Agent stopped because the approved task required a downloaded file, but no successful DOWNLOAD-capability tool result was verified after one recovery nudge. A URL, link, media-resolution result, or unrelated page action does not prove that a file was saved.]',+ 'required_tool_missing');}if (missingSocialPublishTargets.length) {- return {- failure: `[Agent stopped because job-bound terminal evidence was still missing for these requested social destinations after one recovery nudge: ${missingSocialPublishTargets.map(name => name === 'twitter' ? 'X' : name === 'bluesky' ? 'Bluesky' : name).join(', ')}. A post may already exist on another destination; inspect each missing destination before retrying to avoid duplicate publication.]`,- status: 'required_evidence_missing',- };+ return terminal('social_missing',+ `[Agent stopped because job-bound terminal evidence was still missing for these requested social destinations after one recovery nudge: ${missingSocialPublishTargets.map(name => name === 'twitter' ? 'X' : name === 'bluesky' ? 'Bluesky' : name).join(', ')}. A post may already exist on another destination; inspect each missing destination before retrying to avoid duplicate publication.]`,+ 'required_evidence_missing', this._socialPublicationOutcomeFacts(state));}if (missingRequiredSubmission) {- return {- failure: this._workflowVerificationKind(state.siteWorkflow) === 'published_resource'+ return terminal('submission_missing', this._workflowVerificationKind(state.siteWorkflow) === 'published_resource'? `[Agent stopped because the selected ${state.siteWorkflow.job.id} job required job-bound terminal evidence after its commit/submit dispatch. ${this._workflowPublicationRecoveryInstruction(state)}]`: state.siteWorkflow?.job?.id? `[Agent stopped because the selected ${state.siteWorkflow.job.id} job required job-bound terminal evidence after its commit/submit dispatch, but that evidence was still missing after one recovery nudge. Some fields or page state may have changed; inspect the current page before retrying to avoid duplicate submission.]`: '[Agent stopped because the approved task required verified terminal evidence after its submit/send/publish dispatch, but no structured site workflow was bound and generic submission evidence was still missing after one recovery nudge. Some fields or page state may have changed; inspect the current page before retrying to avoid duplicate submission.]',- status: 'required_evidence_missing',- };+ 'required_evidence_missing', { submitted: this._completionSubmitStates.get(tabId)?.dispatched === true+ && this._completionSubmitStates.get(tabId)?.taskKey === state.taskKey });}if (forbiddenSubmission) {- return {- failure: `[Agent stopped because the selected ${state.siteWorkflow?.job?.id || 'workflow'} job was authorized to prepare the form and leave it unsubmitted, but a submit action was dispatched. The submission may have gone through; inspect the page before doing anything else.]`,- status: 'required_evidence_missing',- };+ return terminal('forbidden_submission',+ `[Agent stopped because the selected ${state.siteWorkflow?.job?.id || 'workflow'} job was authorized to prepare the form and leave it unsubmitted, but a submit action was dispatched. The submission may have gone through; inspect the page before doing anything else.]`,+ 'required_evidence_missing');}if (missingJobEvidence) {- return {- failure: `[Agent stopped because the selected ${state.siteWorkflow?.job?.id || 'workflow'} job requires its own terminal evidence β a deterministic count for the verified query, or trusted conversation coverage through the terminal page β and that evidence was still missing after one recovery nudge. Any figure or summary produced so far is unverified.]`,- status: 'required_evidence_missing',- };+ return terminal('job_evidence_missing',+ `[Agent stopped because the selected ${state.siteWorkflow?.job?.id || 'workflow'} job requires its own terminal evidence β a deterministic count for the verified query, or trusted conversation coverage through the terminal page β and that evidence was still missing after one recovery nudge. Any figure or summary produced so far is unverified.]`,+ 'required_evidence_missing');}if (missingDraftEvidence) {- return {- failure: `[Agent stopped because the selected ${state.siteWorkflow?.job?.id || 'workflow'} job required a verified saved draft β the intended recipients, the requested subject, the complete body, and the provider's own saved-draft state β but that evidence was still missing after one recovery nudge. The composer may still hold unsaved text; inspect it before retrying.]`,- status: 'required_evidence_missing',- };+ return terminal('draft_missing',+ `[Agent stopped because the selected ${state.siteWorkflow?.job?.id || 'workflow'} job required a verified saved draft β the intended recipients, the requested subject, the complete body, and the provider's own saved-draft state β but that evidence was still missing after one recovery nudge. The composer may still hold unsaved text; inspect it before retrying.]`,+ 'required_evidence_missing');}if (missingRequiredLedger) {- return {- failure: `The selected ${state.siteWorkflow.job.id} site workflow ended without exact reconciliation against a complete app-owned inventory after one recovery nudge, so full item-level completion was not verified.`,- status: 'required_evidence_missing',- };+ return terminal('ledger_incomplete',+ `The selected ${state.siteWorkflow.job.id} site workflow ended without exact reconciliation against a complete app-owned inventory after one recovery nudge, so full item-level completion was not verified.`,+ 'required_evidence_missing');}const hasSuccessfulToolEvidence = state.successfulTaskToolCalls > 0;const hasSuccessfulConsequentialEvidence = state.successfulConsequentialToolCalls > 0;if (staleCancellation && state.staleCancellationRecoveryAttempted) {- return {- failure: hasSuccessfulToolEvidence+ return terminal('stale_cancellation', hasSuccessfulToolEvidence? '[Agent stopped because the model repeated a stale cancellation status after one recovery nudge. No current user stop was received. Some task tools completed, but final completion was not verified. Inspect the current state before retrying to avoid duplicate side effects.]': '[Agent stopped because the model repeated a stale cancellation status after one recovery nudge. No current user stop was received and no successful action was verified.]',- status: 'plan_only_output',- };+ 'plan_only_output', { toolsCompleted: hasSuccessfulToolEvidence });}if (runtimeModeContradiction) {- return {- failure: hasSuccessfulConsequentialEvidence+ return terminal('mode_contradiction', hasSuccessfulConsequentialEvidence? 'The model still claimed Ask mode after a runtime-mode correction even though this was an Act/Dev run. Some consequential tools may already have completed, but final completion was not verified. Inspect the current page before retrying to avoid duplicate side effects.': hasSuccessfulToolEvidence? 'The model still claimed Ask mode after a runtime-mode correction instead of using the available Act/Dev tools. Only read-only task evidence was recorded; no consequential page action was recorded, and nothing was verified as changed, submitted, or sent.': 'The model still claimed Ask mode after a runtime-mode correction instead of using the available Act/Dev tools. No successful page action was verified, and nothing was verified as changed, submitted, or sent.',- status: 'plan_only_output',- };+ 'plan_only_output');}- return {- failure: hasSuccessfulConsequentialEvidence+ return terminal('default', hasSuccessfulConsequentialEvidence? 'Some task tools completed, but I could not verify a valid completion after the recovery attempt. Please inspect the current page before retrying to avoid duplicate side effects.': hasSuccessfulToolEvidence? 'Some read-only task tools completed, but I could not verify the requested action after the recovery attempt. No consequential page action was recorded, and nothing was verified as changed, submitted, or sent.': 'I could not verify any requested page action after the recovery attempt, so I stopped without claiming completion. No successful action was verified, and nothing was verified as submitted or sent.',- status: 'plan_only_output',- };+ 'plan_only_output');}_buildAutoProgressResumeInstruction(tabId) {@@ -48933,8 +48915,10 @@ If the user has already named or confirmed this exact recipient, do NOT ask agaithis._persist(tabId);break;}- finalResponse = '[Agent stopped because the model returned a context-compression placeholder instead of a tool call or real final answer, even after a recovery nudge.]';+ finalResponse = terminalGuardUserMessage('placeholder_output');_traceStatus = 'placeholder_output';+ if (runId) trace.recordNote(runId, steps, 'terminal_guard', { status: _traceStatus,+ detail: '[Agent stopped because the model returned a context-compression placeholder instead of a tool call or real final answer, even after a recovery nudge.]' });messages.push({ role: 'assistant', content: finalResponse });onUpdate('warning', { message: finalResponse });break;@@ -48958,16 +48942,20 @@ If the user has already named or confirmed this exact recipient, do NOT ask agaithis._persist(tabId);break;}- // Second empty in a row: give up with a transparent message.- finalResponse = emptyOutputFailureMessage(modelOutputDiagnostics(result, {+ // Second empty in a row: give up with a plain message. The provider+ // diagnosis stays in the recovery card's technical details and trace.+ const emptyDiagnostics = modelOutputDiagnostics(result, {requestedMaxTokens: mainMaxTokens,recoveryAttempt: 2,- }));+ });+ const emptyDetail = emptyOutputFailureMessage(emptyDiagnostics);+ finalResponse = terminalGuardUserMessage('empty_output', { reason: emptyDiagnostics.emptyReason });_traceStatus = 'empty_output';traceFailureCode = 'EMPTY_RESPONSE';+ if (runId) trace.recordNote(runId, steps, 'terminal_guard', { status: _traceStatus, detail: emptyDetail });this._offerFailureRecovery(tabId, { stage: 'model', code: 'empty_response',message: 'Failed while getting a usable model response. The model returned no answer after a recovery attempt.',- diagnostics: finalResponse }, onUpdate);+ diagnostics: emptyDetail }, onUpdate);messages.push({ role: 'assistant', content: finalResponse });onUpdate('warning', { message: finalResponse });break;@@ -49124,8 +49112,9 @@ If the user has already named or confirmed this exact recipient, do NOT ask agaicontinue;}if (planOnlyDecision?.failure) {- finalResponse = planOnlyDecision.failure;+ finalResponse = planOnlyDecision.userMessage || planOnlyDecision.failure;_traceStatus = planOnlyDecision.status || 'plan_only_output';+ if (runId) trace.recordNote(runId, steps, 'terminal_guard', { status: _traceStatus, detail: planOnlyDecision.failure });messages.push({ role: 'assistant', content: finalResponse });onUpdate('warning', { message: finalResponse });break;@@ -50173,10 +50162,12 @@ If the user has already named or confirmed this exact recipient, do NOT ask agaithis._persist(tabId);return finish(scheduledResume.message, 'scheduled_resume');}- const failMsg = emptyOutputFailureMessage(outputDiagnostics);+ const emptyDetail = emptyOutputFailureMessage(outputDiagnostics);+ const failMsg = terminalGuardUserMessage('empty_output', { reason: outputDiagnostics?.emptyReason });+ if (runId) trace.recordNote(runId, steps, 'terminal_guard', { status: 'empty_output', detail: emptyDetail });this._offerFailureRecovery(tabId, { stage: 'model', code: 'empty_response',message: 'Failed while getting a usable model response. The model returned no answer after a recovery attempt.',- diagnostics: failMsg }, onUpdate);+ diagnostics: emptyDetail }, onUpdate);messages.push({ role: 'assistant', content: failMsg });onUpdate('warning', { message: failMsg });this._persist(tabId);@@ -50202,7 +50193,9 @@ If the user has already named or confirmed this exact recipient, do NOT ask agaithis._persist(tabId);return finish(scheduledResume.message, 'scheduled_resume');}- const failMsg = '[Agent stopped because the model returned a context-compression placeholder instead of a tool call or real final answer, even after a recovery nudge.]';+ const failMsg = terminalGuardUserMessage('placeholder_output');+ if (runId) trace.recordNote(runId, steps, 'terminal_guard', { status: 'placeholder_output',+ detail: '[Agent stopped because the model returned a context-compression placeholder instead of a tool call or real final answer, even after a recovery nudge.]' });messages.push({ role: 'assistant', content: failMsg });onUpdate('warning', { message: failMsg });this._persist(tabId);@@ -50338,13 +50331,16 @@ If the user has already named or confirmed this exact recipient, do NOT ask agaicontinue;}if (planOnlyDecision?.failure) {- messages.push({ role: 'assistant', content: planOnlyDecision.failure });+ const visibleFailure = planOnlyDecision.userMessage || planOnlyDecision.failure;+ if (runId) trace.recordNote(runId, steps, 'terminal_guard', {+ status: planOnlyDecision.status || 'plan_only_output', detail: planOnlyDecision.failure });+ messages.push({ role: 'assistant', content: visibleFailure });// Replace any rejected plan text already emitted as streaming deltas// so the visible terminal content matches the failed run result.- onUpdate('text', { content: planOnlyDecision.failure, replace: true });- onUpdate('warning', { message: planOnlyDecision.failure });+ onUpdate('text', { content: visibleFailure, replace: true });+ onUpdate('warning', { message: visibleFailure });this._persist(tabId);- return finish(planOnlyDecision.failure, planOnlyDecision.status || 'plan_only_output');+ return finish(visibleFailure, planOnlyDecision.status || 'plan_only_output');}if (this._isClearlyIncompleteStandaloneAnswer(fullText, runOptions)) {if (!standaloneIncompleteAnswerRecoveryAttempted) {diff --git a/src/chrome/src/agent/terminal-messages.js b/src/chrome/src/agent/terminal-messages.jsnew file mode 100644index 000000000..a091c9010--- /dev/null+++ b/src/chrome/src/agent/terminal-messages.js@@ -0,0 +1,108 @@+/**+ * Plain-language final answers for runs that a runtime guard ended.+ *+ * The guard's mechanical diagnostic (bracketed, with job ids and recovery+ * instructions) stays in tool results, verbose rows and traces. The person+ * reading the chat gets what happened and what to check next. Messages carry+ * no page content, private values or tool arguments. Keep the Firefox copy+ * byte-identical.+ */++const PLATFORM_LABELS = {+ twitter: 'X', x: 'X', bluesky: 'Bluesky', mastodon: 'Mastodon', linkedin: 'LinkedIn',+ threads: 'Threads', facebook: 'Facebook', instagram: 'Instagram', reddit: 'Reddit',+};++export function socialPlatformLabel(name) {+ const key = String(name || '').trim().toLowerCase();+ if (!key) return 'the requested site';+ if (key === 'unresolved_intent') return 'the requested site';+ return PLATFORM_LABELS[key] || key.charAt(0).toUpperCase() + key.slice(1);+}++function joinLabels(labels) {+ const unique = [...new Set(labels.filter(Boolean))];+ if (unique.length <= 1) return unique[0] || '';+ return `${unique.slice(0, -1).join(', ')} and ${unique.at(-1)}`;+}++function socialMessage({ unconfirmed = [], notStarted = [], verified = [] } = {}) {+ const parts = [];+ const done = joinLabels(verified.map(socialPlatformLabel));+ const pending = joinLabels(unconfirmed.map(socialPlatformLabel));+ const missing = joinLabels(notStarted.map(socialPlatformLabel));+ if (done) parts.push(`I posted to ${done}.`);+ if (pending) {+ parts.push(`I clicked Post on ${pending}, but I couldn't confirm the post afterwards. `+ + 'The page changed, or the post was edited, before I could check it.');+ parts.push(`I didn't post again, so there won't be a duplicate. Please check ${pending} to make sure the post looks right.`);+ }+ if (missing) parts.push(`I couldn't finish posting to ${missing}, so nothing was published there.`);+ if (!parts.length) parts.push("I couldn't confirm that the post was published, so I stopped without posting again.");+ return parts.join(' ');+}++/**+ * kind: the guard branch that ended the run. facts: booleans and platform+ * names only. Unknown kinds fall back to an honest generic message.+ */+export function terminalGuardUserMessage(kind, facts = {}) {+ const consequential = facts.consequential === true;+ const readOnly = !consequential && facts.readOnly === true;+ switch (kind) {+ case 'task_changed':+ return 'Your request changed while I was working, so I stopped before finishing. Send the updated request again and I will start fresh.';+ case 'schedule_missing':+ return "I couldn't set up the scheduled task, so nothing will run later. Some one-time steps may already have happened.";+ case 'download_missing':+ return "I couldn't download the file, so nothing was saved. Finding a link to it is not the same as saving it.";+ case 'social_missing':+ return socialMessage(facts);+ case 'submission_missing':+ // Only a recorded submit dispatch for this task may say "I submitted".+ return facts.submitted === true+ ? "I submitted it, but I couldn't confirm the result on the page afterwards. Please check the page before trying again, so nothing is submitted twice."+ : consequential+ ? "I took some steps on the page, but the final submission didn't go through or couldn't be confirmed. Please check the page before trying again."+ : "I couldn't complete the submission, and I didn't find any sign that it was submitted. Please check the page before trying again.";+ case 'forbidden_submission':+ return 'The form was submitted even though the task was to leave it unsubmitted. Please check the page to see what was sent.';+ case 'job_evidence_missing':+ return "I couldn't verify the result, so anything I found so far may be incomplete. Please don't rely on it without checking.";+ case 'draft_missing':+ return "I couldn't confirm that the draft was saved. The editor may still contain unsaved text, so please check it before trying again.";+ case 'ledger_incomplete':+ return "I couldn't confirm that every item was handled. Some items may still need attention.";+ case 'stale_cancellation':+ return consequential || facts.toolsCompleted === true+ ? "I stopped because I couldn't confirm the task finished. Some steps were completed, so please check the page before trying again."+ : 'I stopped without completing the task. Nothing was changed.';+ case 'clarification_required':+ return 'I need your answer to my question before I continue. The earlier choice was picked automatically after a timeout, so I did not treat it as your decision. Please answer it and try again.';+ case 'placeholder_output':+ return 'The model stopped giving usable answers, so I ended the task. Please try again; a new conversation or a different model may help.';+ case 'empty_output':+ return facts.reason === 'content_filter'+ ? 'The model provider filtered its response, so I could not continue. Please rephrase the request or try another provider.'+ : facts.reason === 'output_limit' || facts.reason === 'reasoning_only'+ ? 'The model used up its response limit without giving an answer. Try lowering its reasoning effort or choosing another model.'+ : 'The model returned empty responses, so I could not continue. Please try again later or choose another model.';+ case 'mode_contradiction':+ default:+ return consequential+ ? "I did part of the work but couldn't confirm the task finished. Please check the page before trying again, so nothing happens twice."+ : readOnly+ ? "I completed some read-only steps but couldn't verify the requested result, so I stopped. Nothing was changed, submitted, or sent."+ : "I couldn't complete the requested action, so I stopped without claiming success. Nothing was changed, submitted, or sent.";+ }+}++/** One plain-language step-limit message; the tool inventory stays in traces. */+export function stepLimitUserMessage(steps, lastAssistantText = '') {+ const count = Number.isSafeInteger(steps) && steps > 0 ? steps : 0;+ const lines = [`I reached the step limit${count ? ` (${count} step${count === 1 ? '' : 's'})` : ''} before finishing the task.`];+ const snippet = String(lastAssistantText || '').replace(/\s+/g, ' ').trim();+ if (snippet) lines.push(`Where I stopped: "${snippet.slice(0, 280)}${snippet.length > 280 ? '...' : ''}"`);+ lines.push('This usually means the task is too complex for the current model, the step limit is too low (you can raise it in Settings), or the task should be split into smaller parts.');+ return lines.join('\n\n');+}diff --git a/src/chrome/src/trace/trajectory.js b/src/chrome/src/trace/trajectory.jsindex 00dd95e8f..19c1d5b11 100644--- a/src/chrome/src/trace/trajectory.js+++ b/src/chrome/src/trace/trajectory.js@@ -79,8 +79,8 @@ function addError(row, data) {const FAILED_END_STATUSES = ['error', 'loop_stopped', 'max_steps', 'cancelled', 'cost_limit','plan_only_output', 'incomplete_output', 'empty_output',- 'placeholder_output', 'required_tool_missing', 'grounding_unavailable',- 'captcha_manual_required',+ 'placeholder_output', 'required_tool_missing', 'required_evidence_missing',+ 'task_binding_changed', 'grounding_unavailable', 'captcha_manual_required',];function markEnd(row, data) {diff --git a/src/chrome/src/ui/markdown-render.js b/src/chrome/src/ui/markdown-render.jsindex 8fb55931d..954ac8c99 100644--- a/src/chrome/src/ui/markdown-render.js+++ b/src/chrome/src/ui/markdown-render.js@@ -819,6 +819,25 @@ export function highlightCode(code, language) {}}+/**+ * Convert escaped Markdown blockquote lines (`> text`) into blockquote+ * elements. Showing the markers literally makes people copy them back into+ * requests as if they were content. Inline formatting and the newline-to-<br>+ * pass stay with the caller; the block swallows its trailing newline so it is+ * not followed by an extra blank line.+ */+export function renderMarkdownBlockquotes(text) {+ return String(text == null ? '' : text).replace(+ /(?:^[ \t]{0,3}>[^\r\n]*(?:\r?\n|$))+/gm,+ block => {+ const inner = block.replace(/\r?\n$/, '').split(/\r?\n/)+ .map(line => line.replace(/^[ \t]{0,3}>[ \t]?/, ''))+ .join('\n');+ return `<blockquote>${inner}</blockquote>`;+ }+ );+}+/** Convert escaped ATX heading lines while leaving inline formatting for the caller. */export function renderMarkdownHeadings(text) {return String(text == null ? '' : text).replace(diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.jsindex 97fcee52e..ca9898361 100644--- a/src/chrome/src/ui/sidepanel.js+++ b/src/chrome/src/ui/sidepanel.js@@ -11,7 +11,7 @@ import { createQuotaController } from './compass-quota.js';import { t, getLocale, setLocale, LANGUAGES, applyDOMTranslations, translationsForKey } from './i18n.js';import { CAPABILITY_LABEL } from '../agent/permission-gate.js';import { sanitizeMarkdownLinks } from './markdown-link.js';-import { codeFenceLanguage, highlightCode, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';+import { codeFenceLanguage, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';import { applyMode, loadMode, watch } from './theme.js';import {UI_SCALE_LEVELS,@@ -10656,6 +10656,14 @@ function handleAgentUpdateMessage(msg) {break;case 'tool_result':+ // A refused completion (blocked done, or a completion skipped for a+ // fresh turn) keeps the run working; do not leave "Finishing up" shown+ // while the next step is decided.+ if (isTerminalDoneTool(data.name) && (data.result?.blockedDone === true+ || (data.result?.success === false && data.result?.done !== true))) {+ clearThinkingActivityTimers();+ beginThinkingActivity();+ }if (currentAssistantEl) {if (data.name === 'generate_image') {void appendGeneratedMedia(currentAssistantEl.querySelector('.message-content'), data.result, t);@@ -13824,6 +13832,7 @@ function formatMarkdown(text, options = {}) {// Code and inline-code placeholders were extracted above, so// Markdown-looking source inside them is not interpreted here.text = renderMarkdownTables(text);+ text = renderMarkdownBlockquotes(text);text = renderMarkdownHeadings(text);text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')diff --git a/src/chrome/styles/sidepanel.css b/src/chrome/styles/sidepanel.cssindex 3c3fa0f10..3223fd35c 100644--- a/src/chrome/styles/sidepanel.css+++ b/src/chrome/styles/sidepanel.css@@ -3617,6 +3617,13 @@ html[data-ui-scale="175"] .conversation-action-label {.message-content h5,.message-content h6 { font-size: 13px; }+.message-content blockquote {+ margin: 6px 0;+ padding: 2px 0 2px 10px;+ border-left: 3px solid var(--border);+ color: inherit;+}+.markdown-table-wrapper {max-width: 100%;margin: 8px 0;diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex 3ae746938..45ca19916 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -151,6 +151,7 @@ import { GENERATIVE_MEDIA_SETUP_NOTE, isImageGenConfigured, mediaPermissionUrl,import { extractFirstJsonObject } from './json-extract.js';import { repairAssistantDisplayText, repairClarifyText, sanitizeText as sanitizePlannerText } from './text-sanitize.js';import { emptyOutputFailureMessage, modelOutputDiagnostics } from './model-output-diagnostics.js';+import { stepLimitUserMessage, terminalGuardUserMessage } from './terminal-messages.js';import { buildCustomSkillsPrompt, buildSkillLoaderDefinition, buildSkillToolDefinitions, buildSkillToolRegistry, getEligibleCustomSkills, getEligibleSkillCatalog, normalizeCustomSkills } from './skills.js';import { OTP_EMAIL_PROVIDER_IDS, OTP_EMAIL_SKILL_ID, OTP_EMAIL_TOOL_NAME, otpEmailCandidates, otpEmailProviderForUrl, otpEmailUrlLooksLikeMessage, otpOpenMessageRootRef, otpRedactRefs, otpServiceDisplay, otpServiceKey, otpVerificationMessageExcerpt, selectOtpMailboxTab, selectUniqueOtpCandidateByPreview } from './otp-email-tool.js';import { publicMediaUrlNeedsExplicitTarget } from './public-media-url.js';@@ -10489,52 +10490,22 @@ export class Agent extends LoopDetector {}/**- * Synthesize a transparent summary when the agent hits the step limit- * without producing a final answer. See chrome's copy for the rationale.+ * Plain-language account of a run that hit the step limit without a final+ * answer. The tool inventory and arguments remain in the trace and verbose+ * rows; the chat explains the limit and quotes the last thing the agent+ * said, if anything. Pure deterministic β no extra LLM call.*/_buildStepLimitSummary(messages, steps) {- const toolCounts = new Map();let lastAssistantText = '';- let lastToolCall = null;const binding = this._activeTaskBinding(messages);// Earlier attempts remain in history, but this handoff describes the// latest authorized revision rather than quoting its superseded answer.const summaryMessages = binding.updates?.some(update => update.kind === 'steering')? messages.slice(binding.index + 1) : messages;for (const m of summaryMessages) {- if (m.role === 'assistant') {- if (Array.isArray(m.tool_calls)) {- for (const tc of m.tool_calls) {- const name = tc?.function?.name || tc?.name;- if (name) {- toolCounts.set(name, (toolCounts.get(name) || 0) + 1);- lastToolCall = { name, args: tc?.function?.arguments || tc?.arguments || '' };- }- }- }- if (typeof m.content === 'string' && m.content.trim()) {- lastAssistantText = m.content;- }- }+ if (m.role === 'assistant' && typeof m.content === 'string' && m.content.trim()) lastAssistantText = m.content;}- const sortedTools = [...toolCounts.entries()]- .sort((a, b) => b[1] - a[1])- .slice(0, 6)- .map(([n, c]) => `${n} Γ${c}`)- .join(', ');- const lastActionLine = lastToolCall- ? `Last tool attempted: ${lastToolCall.name}${lastToolCall.args ? ' (' + String(lastToolCall.args).slice(0, 120) + ')' : ''}`- : '';- const lastTextSnippet = lastAssistantText- ? `Last thing I said: "${lastAssistantText.slice(0, 280).replace(/\s+/g, ' ').trim()}${lastAssistantText.length > 280 ? 'β¦' : ''}"`- : '';- return [- `[Step limit reached after ${steps} steps without completing the task.`,- sortedTools ? `Tools attempted: ${sortedTools}.` : '',- lastActionLine,- lastTextSnippet,- 'This usually means: (a) the task is too complex for the current model β try a stronger one, (b) the step limit is too low β raise it in Settings, or (c) the strategy was wrong β try breaking it into smaller parts.]',- ].filter(Boolean).join('\n\n');+ return stepLimitUserMessage(steps, lastAssistantText);}_stepLimitRecoveryEligible(provider, runOptions = {}) {@@ -14223,12 +14194,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}if (planOnlyDecision?.failure) {await cancelPendingResumes();+ // The tool result keeps the guard's diagnostic for verbose rows,+ // traces and later model turns; the chat shows the plain account.const failedResult = {success: false,done: true,outcome: 'failed',planOnlyTerminal: true,- summary: planOnlyDecision.failure,+ summary: planOnlyDecision.userMessage || planOnlyDecision.failure,error: planOnlyDecision.failure,};onUpdate('tool_result', { name: fnName, result: failedResult });@@ -14243,7 +14216,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d() => ({ success: false, skipped: true, error: 'skipped: plan-only completion failed' }));this._persist(tabId);- return { action: 'return', value: planOnlyDecision.failure, status: 'plan_only_output' };+ return { action: 'return', value: planOnlyDecision.userMessage || planOnlyDecision.failure,+ status: planOnlyDecision.status || 'plan_only_output' };}let rawDoneSummary = toolResult.summary || partialAssistantText || 'Task completed.';if (!scheduledResume && this._looksLikeMetaOnlyDoneSummary(rawDoneSummary)) {@@ -17265,7 +17239,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}_clarificationAuthorizationStopMessage() {- return '[Agent stopped before dispatching another action or accepting a success completion because the latest clarification answer was auto-selected after a timeout and was not user authorization. Please answer the clarification explicitly and retry.]';+ // The block itself (a timeout-selected answer is not authorization) is+ // recorded on the refused tool result; the chat asks for a real answer.+ return terminalGuardUserMessage('clarification_required');}_clarificationAuthorizationPlainFinalDecision(tabId) {@@ -19693,6 +19669,25 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn progress.missing.map(id => social.contract.actions.find(a => a.id === id)?.platform || id);}+ /** Platform names only: which destinations were verified, dispatched but unconfirmed, or never published. */+ _socialPublicationOutcomeFacts(guard) {+ const social = guard?.socialPublication;+ const facts = { verified: [], unconfirmed: [], notStarted: [] };+ if (!social?.contract || social.contract.status !== 'ready') {+ facts.notStarted.push(guard?.siteWorkflow?.adapterName || 'unresolved_intent');+ return facts;+ }+ const missing = new Set(publicationProgress(social.contract, social.outcomes).missing);+ for (const action of social.contract.actions || []) {+ const status = social.outcomes?.[action.id]?.status;+ if (status === 'verified') facts.verified.push(action.platform);+ else if (!missing.has(action.id)) continue;+ else if (status === 'pending') facts.unconfirmed.push(action.platform);+ else facts.notStarted.push(action.platform);+ }+ return facts;+ }+async _adoptLiveSocialPublishWorkflow(tabId, provider, detected = null) {const guard = this._planExecutionGuards.get(tabId);if (!guard?.enabled) return false;@@ -32609,6 +32604,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d_planOnlyTerminalDecision(tabId, content, { viaDone = false, outcome = null } = {}) {const state = this._planExecutionGuards.get(tabId);if (!state?.enabled) return null;+ // The bracketed diagnostic stays in tool results and traces; the chat+ // shows a plain-language account of what happened.+ const terminal = (kind, failure, status, facts = {}) => ({ failure, status,+ userMessage: terminalGuardUserMessage(kind, { consequential: state.successfulConsequentialToolCalls > 0,+ readOnly: state.successfulTaskToolCalls > 0, ...facts }) });if (state.taskKey && this._progressTaskKeyHash(tabId) !== state.taskKey) state.taskDrifted = true;const recoveryAnchor = this._executionTaskRecoveryAnchor(state);if (!viaDone && this._isSafetyRefusalTerminal(content)) return null;@@ -32714,91 +32714,76 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d};}if (state.taskDrifted) {- return {- failure: 'The user task changed after this run was authorized, so WebBrain discarded its execution evidence and stopped. Start a fresh run for the current task.',- status: 'task_binding_changed',- };+ return terminal('task_changed',+ 'The user task changed after this run was authorized, so WebBrain discarded its execution evidence and stopped. Start a fresh run for the current task.',+ 'task_binding_changed');}if (missingRequiredSchedulingTool) {- return {- failure: `[Agent stopped because the approved plan required ${state.requiredSchedulingTool}, but no successful matching scheduling call was verified after one recovery nudge. The task may have performed one-time actions, but the requested future work was not scheduled.]`,- status: 'required_tool_missing',- };+ return terminal('schedule_missing',+ `[Agent stopped because the approved plan required ${state.requiredSchedulingTool}, but no successful matching scheduling call was verified after one recovery nudge. The task may have performed one-time actions, but the requested future work was not scheduled.]`,+ 'required_tool_missing');}if (missingRequiredDownload) {- return {- failure: '[Agent stopped because the approved task required a downloaded file, but no successful DOWNLOAD-capability tool result was verified after one recovery nudge. A URL, link, media-resolution result, or unrelated page action does not prove that a file was saved.]',- status: 'required_tool_missing',- };+ return terminal('download_missing',+ '[Agent stopped because the approved task required a downloaded file, but no successful DOWNLOAD-capability tool result was verified after one recovery nudge. A URL, link, media-resolution result, or unrelated page action does not prove that a file was saved.]',+ 'required_tool_missing');}if (missingSocialPublishTargets.length) {- return {- failure: `[Agent stopped because job-bound terminal evidence was still missing for these requested social destinations after one recovery nudge: ${missingSocialPublishTargets.map(name => name === 'twitter' ? 'X' : name === 'bluesky' ? 'Bluesky' : name).join(', ')}. A post may already exist on another destination; inspect each missing destination before retrying to avoid duplicate publication.]`,- status: 'required_evidence_missing',- };+ return terminal('social_missing',+ `[Agent stopped because job-bound terminal evidence was still missing for these requested social destinations after one recovery nudge: ${missingSocialPublishTargets.map(name => name === 'twitter' ? 'X' : name === 'bluesky' ? 'Bluesky' : name).join(', ')}. A post may already exist on another destination; inspect each missing destination before retrying to avoid duplicate publication.]`,+ 'required_evidence_missing', this._socialPublicationOutcomeFacts(state));}if (missingRequiredSubmission) {- return {- failure: this._workflowVerificationKind(state.siteWorkflow) === 'published_resource'+ return terminal('submission_missing', this._workflowVerificationKind(state.siteWorkflow) === 'published_resource'? `[Agent stopped because the selected ${state.siteWorkflow.job.id} job required job-bound terminal evidence after its commit/submit dispatch. ${this._workflowPublicationRecoveryInstruction(state)}]`: state.siteWorkflow?.job?.id? `[Agent stopped because the selected ${state.siteWorkflow.job.id} job required job-bound terminal evidence after its commit/submit dispatch, but that evidence was still missing after one recovery nudge. Some fields or page state may have changed; inspect the current page before retrying to avoid duplicate submission.]`: '[Agent stopped because the approved task required verified terminal evidence after its submit/send/publish dispatch, but no structured site workflow was bound and generic submission evidence was still missing after one recovery nudge. Some fields or page state may have changed; inspect the current page before retrying to avoid duplicate submission.]',- status: 'required_evidence_missing',- };+ 'required_evidence_missing', { submitted: this._completionSubmitStates.get(tabId)?.dispatched === true+ && this._completionSubmitStates.get(tabId)?.taskKey === state.taskKey });}if (forbiddenSubmission) {- return {- failure: `[Agent stopped because the selected ${state.siteWorkflow?.job?.id || 'workflow'} job was authorized to prepare the form and leave it unsubmitted, but a submit action was dispatched. The submission may have gone through; inspect the page before doing anything else.]`,- status: 'required_evidence_missing',- };+ return terminal('forbidden_submission',+ `[Agent stopped because the selected ${state.siteWorkflow?.job?.id || 'workflow'} job was authorized to prepare the form and leave it unsubmitted, but a submit action was dispatched. The submission may have gone through; inspect the page before doing anything else.]`,+ 'required_evidence_missing');}if (missingJobEvidence) {- return {- failure: `[Agent stopped because the selected ${state.siteWorkflow?.job?.id || 'workflow'} job requires its own terminal evidence β a deterministic count for the verified query, or trusted conversation coverage through the terminal page β and that evidence was still missing after one recovery nudge. Any figure or summary produced so far is unverified.]`,- status: 'required_evidence_missing',- };+ return terminal('job_evidence_missing',+ `[Agent stopped because the selected ${state.siteWorkflow?.job?.id || 'workflow'} job requires its own terminal evidence β a deterministic count for the verified query, or trusted conversation coverage through the terminal page β and that evidence was still missing after one recovery nudge. Any figure or summary produced so far is unverified.]`,+ 'required_evidence_missing');}if (missingDraftEvidence) {- return {- failure: `[Agent stopped because the selected ${state.siteWorkflow?.job?.id || 'workflow'} job required a verified saved draft β the intended recipients, the requested subject, the complete body, and the provider's own saved-draft state β but that evidence was still missing after one recovery nudge. The composer may still hold unsaved text; inspect it before retrying.]`,- status: 'required_evidence_missing',- };+ return terminal('draft_missing',+ `[Agent stopped because the selected ${state.siteWorkflow?.job?.id || 'workflow'} job required a verified saved draft β the intended recipients, the requested subject, the complete body, and the provider's own saved-draft state β but that evidence was still missing after one recovery nudge. The composer may still hold unsaved text; inspect it before retrying.]`,+ 'required_evidence_missing');}if (missingRequiredLedger) {- return {- failure: `The selected ${state.siteWorkflow.job.id} site workflow ended without exact reconciliation against a complete app-owned inventory after one recovery nudge, so full item-level completion was not verified.`,- status: 'required_evidence_missing',- };+ return terminal('ledger_incomplete',+ `The selected ${state.siteWorkflow.job.id} site workflow ended without exact reconciliation against a complete app-owned inventory after one recovery nudge, so full item-level completion was not verified.`,+ 'required_evidence_missing');}const hasSuccessfulToolEvidence = state.successfulTaskToolCalls > 0;const hasSuccessfulConsequentialEvidence = state.successfulConsequentialToolCalls > 0;if (staleCancellation && state.staleCancellationRecoveryAttempted) {- return {- failure: hasSuccessfulToolEvidence+ return terminal('stale_cancellation', hasSuccessfulToolEvidence? '[Agent stopped because the model repeated a stale cancellation status after one recovery nudge. No current user stop was received. Some task tools completed, but final completion was not verified. Inspect the current state before retrying to avoid duplicate side effects.]': '[Agent stopped because the model repeated a stale cancellation status after one recovery nudge. No current user stop was received and no successful action was verified.]',- status: 'plan_only_output',- };+ 'plan_only_output', { toolsCompleted: hasSuccessfulToolEvidence });}if (runtimeModeContradiction) {- return {- failure: hasSuccessfulConsequentialEvidence+ return terminal('mode_contradiction', hasSuccessfulConsequentialEvidence? 'The model still claimed Ask mode after a runtime-mode correction even though this was an Act/Dev run. Some consequential tools may already have completed, but final completion was not verified. Inspect the current page before retrying to avoid duplicate side effects.': hasSuccessfulToolEvidence? 'The model still claimed Ask mode after a runtime-mode correction instead of using the available Act/Dev tools. Only read-only task evidence was recorded; no consequential page action was recorded, and nothing was verified as changed, submitted, or sent.': 'The model still claimed Ask mode after a runtime-mode correction instead of using the available Act/Dev tools. No successful page action was verified, and nothing was verified as changed, submitted, or sent.',- status: 'plan_only_output',- };+ 'plan_only_output');}- return {- failure: hasSuccessfulConsequentialEvidence+ return terminal('default', hasSuccessfulConsequentialEvidence? 'Some task tools completed, but I could not verify a valid completion after the recovery attempt. Please inspect the current page before retrying to avoid duplicate side effects.': hasSuccessfulToolEvidence? 'Some read-only task tools completed, but I could not verify the requested action after the recovery attempt. No consequential page action was recorded, and nothing was verified as changed, submitted, or sent.': 'I could not verify any requested page action after the recovery attempt, so I stopped without claiming completion. No successful action was verified, and nothing was verified as submitted or sent.',- status: 'plan_only_output',- };+ 'plan_only_output');}_buildAutoProgressResumeInstruction(tabId) {@@ -41389,8 +41374,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._persist(tabId);break;}- finalResponse = '[Agent stopped because the model returned a context-compression placeholder instead of a tool call or real final answer, even after a recovery nudge.]';+ finalResponse = terminalGuardUserMessage('placeholder_output');_traceStatus = 'placeholder_output';+ if (runId) trace.recordNote(runId, steps, 'terminal_guard', { status: _traceStatus,+ detail: '[Agent stopped because the model returned a context-compression placeholder instead of a tool call or real final answer, even after a recovery nudge.]' });messages.push({ role: 'assistant', content: finalResponse });onUpdate('warning', { message: finalResponse });break;@@ -41414,15 +41401,20 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._persist(tabId);break;}- finalResponse = emptyOutputFailureMessage(modelOutputDiagnostics(result, {+ // Second empty in a row: give up with a plain message. The provider+ // diagnosis stays in the recovery card's technical details and trace.+ const emptyDiagnostics = modelOutputDiagnostics(result, {requestedMaxTokens: mainMaxTokens,recoveryAttempt: 2,- }));+ });+ const emptyDetail = emptyOutputFailureMessage(emptyDiagnostics);+ finalResponse = terminalGuardUserMessage('empty_output', { reason: emptyDiagnostics.emptyReason });_traceStatus = 'empty_output';traceFailureCode = 'EMPTY_RESPONSE';+ if (runId) trace.recordNote(runId, steps, 'terminal_guard', { status: _traceStatus, detail: emptyDetail });this._offerFailureRecovery(tabId, { stage: 'model', code: 'empty_response',message: 'Failed while getting a usable model response. The model returned no answer after a recovery attempt.',- diagnostics: finalResponse }, onUpdate);+ diagnostics: emptyDetail }, onUpdate);messages.push({ role: 'assistant', content: finalResponse });onUpdate('warning', { message: finalResponse });break;@@ -41579,8 +41571,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dcontinue;}if (planOnlyDecision?.failure) {- finalResponse = planOnlyDecision.failure;+ finalResponse = planOnlyDecision.userMessage || planOnlyDecision.failure;_traceStatus = planOnlyDecision.status || 'plan_only_output';+ if (runId) trace.recordNote(runId, steps, 'terminal_guard', { status: _traceStatus, detail: planOnlyDecision.failure });messages.push({ role: 'assistant', content: finalResponse });onUpdate('warning', { message: finalResponse });break;@@ -42488,10 +42481,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._persist(tabId);return finish(scheduledResume.message, 'scheduled_resume');}- const failMsg = emptyOutputFailureMessage(outputDiagnostics);+ const emptyDetail = emptyOutputFailureMessage(outputDiagnostics);+ const failMsg = terminalGuardUserMessage('empty_output', { reason: outputDiagnostics?.emptyReason });+ if (runId) trace.recordNote(runId, steps, 'terminal_guard', { status: 'empty_output', detail: emptyDetail });this._offerFailureRecovery(tabId, { stage: 'model', code: 'empty_response',message: 'Failed while getting a usable model response. The model returned no answer after a recovery attempt.',- diagnostics: failMsg }, onUpdate);+ diagnostics: emptyDetail }, onUpdate);messages.push({ role: 'assistant', content: failMsg });onUpdate('warning', { message: failMsg });this._persist(tabId);@@ -42517,7 +42512,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._persist(tabId);return finish(scheduledResume.message, 'scheduled_resume');}- const failMsg = '[Agent stopped because the model returned a context-compression placeholder instead of a tool call or real final answer, even after a recovery nudge.]';+ const failMsg = terminalGuardUserMessage('placeholder_output');+ if (runId) trace.recordNote(runId, steps, 'terminal_guard', { status: 'placeholder_output',+ detail: '[Agent stopped because the model returned a context-compression placeholder instead of a tool call or real final answer, even after a recovery nudge.]' });messages.push({ role: 'assistant', content: failMsg });onUpdate('warning', { message: failMsg });return finish(failMsg, 'placeholder_output');@@ -42652,13 +42649,16 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dcontinue;}if (planOnlyDecision?.failure) {- messages.push({ role: 'assistant', content: planOnlyDecision.failure });+ const visibleFailure = planOnlyDecision.userMessage || planOnlyDecision.failure;+ if (runId) trace.recordNote(runId, steps, 'terminal_guard', {+ status: planOnlyDecision.status || 'plan_only_output', detail: planOnlyDecision.failure });+ messages.push({ role: 'assistant', content: visibleFailure });// Replace any rejected plan text already emitted as streaming deltas// so the visible terminal content matches the failed run result.- onUpdate('text', { content: planOnlyDecision.failure, replace: true });- onUpdate('warning', { message: planOnlyDecision.failure });+ onUpdate('text', { content: visibleFailure, replace: true });+ onUpdate('warning', { message: visibleFailure });this._persist(tabId);- return finish(planOnlyDecision.failure, planOnlyDecision.status || 'plan_only_output');+ return finish(visibleFailure, planOnlyDecision.status || 'plan_only_output');}// Streaming text is still the provider's raw completion at this point.shareRawResponse = fullText;diff --git a/src/firefox/src/agent/terminal-messages.js b/src/firefox/src/agent/terminal-messages.jsnew file mode 100644index 000000000..a091c9010--- /dev/null+++ b/src/firefox/src/agent/terminal-messages.js@@ -0,0 +1,108 @@+/**+ * Plain-language final answers for runs that a runtime guard ended.+ *+ * The guard's mechanical diagnostic (bracketed, with job ids and recovery+ * instructions) stays in tool results, verbose rows and traces. The person+ * reading the chat gets what happened and what to check next. Messages carry+ * no page content, private values or tool arguments. Keep the Firefox copy+ * byte-identical.+ */++const PLATFORM_LABELS = {+ twitter: 'X', x: 'X', bluesky: 'Bluesky', mastodon: 'Mastodon', linkedin: 'LinkedIn',+ threads: 'Threads', facebook: 'Facebook', instagram: 'Instagram', reddit: 'Reddit',+};++export function socialPlatformLabel(name) {+ const key = String(name || '').trim().toLowerCase();+ if (!key) return 'the requested site';+ if (key === 'unresolved_intent') return 'the requested site';+ return PLATFORM_LABELS[key] || key.charAt(0).toUpperCase() + key.slice(1);+}++function joinLabels(labels) {+ const unique = [...new Set(labels.filter(Boolean))];+ if (unique.length <= 1) return unique[0] || '';+ return `${unique.slice(0, -1).join(', ')} and ${unique.at(-1)}`;+}++function socialMessage({ unconfirmed = [], notStarted = [], verified = [] } = {}) {+ const parts = [];+ const done = joinLabels(verified.map(socialPlatformLabel));+ const pending = joinLabels(unconfirmed.map(socialPlatformLabel));+ const missing = joinLabels(notStarted.map(socialPlatformLabel));+ if (done) parts.push(`I posted to ${done}.`);+ if (pending) {+ parts.push(`I clicked Post on ${pending}, but I couldn't confirm the post afterwards. `+ + 'The page changed, or the post was edited, before I could check it.');+ parts.push(`I didn't post again, so there won't be a duplicate. Please check ${pending} to make sure the post looks right.`);+ }+ if (missing) parts.push(`I couldn't finish posting to ${missing}, so nothing was published there.`);+ if (!parts.length) parts.push("I couldn't confirm that the post was published, so I stopped without posting again.");+ return parts.join(' ');+}++/**+ * kind: the guard branch that ended the run. facts: booleans and platform+ * names only. Unknown kinds fall back to an honest generic message.+ */+export function terminalGuardUserMessage(kind, facts = {}) {+ const consequential = facts.consequential === true;+ const readOnly = !consequential && facts.readOnly === true;+ switch (kind) {+ case 'task_changed':+ return 'Your request changed while I was working, so I stopped before finishing. Send the updated request again and I will start fresh.';+ case 'schedule_missing':+ return "I couldn't set up the scheduled task, so nothing will run later. Some one-time steps may already have happened.";+ case 'download_missing':+ return "I couldn't download the file, so nothing was saved. Finding a link to it is not the same as saving it.";+ case 'social_missing':+ return socialMessage(facts);+ case 'submission_missing':+ // Only a recorded submit dispatch for this task may say "I submitted".+ return facts.submitted === true+ ? "I submitted it, but I couldn't confirm the result on the page afterwards. Please check the page before trying again, so nothing is submitted twice."+ : consequential+ ? "I took some steps on the page, but the final submission didn't go through or couldn't be confirmed. Please check the page before trying again."+ : "I couldn't complete the submission, and I didn't find any sign that it was submitted. Please check the page before trying again.";+ case 'forbidden_submission':+ return 'The form was submitted even though the task was to leave it unsubmitted. Please check the page to see what was sent.';+ case 'job_evidence_missing':+ return "I couldn't verify the result, so anything I found so far may be incomplete. Please don't rely on it without checking.";+ case 'draft_missing':+ return "I couldn't confirm that the draft was saved. The editor may still contain unsaved text, so please check it before trying again.";+ case 'ledger_incomplete':+ return "I couldn't confirm that every item was handled. Some items may still need attention.";+ case 'stale_cancellation':+ return consequential || facts.toolsCompleted === true+ ? "I stopped because I couldn't confirm the task finished. Some steps were completed, so please check the page before trying again."+ : 'I stopped without completing the task. Nothing was changed.';+ case 'clarification_required':+ return 'I need your answer to my question before I continue. The earlier choice was picked automatically after a timeout, so I did not treat it as your decision. Please answer it and try again.';+ case 'placeholder_output':+ return 'The model stopped giving usable answers, so I ended the task. Please try again; a new conversation or a different model may help.';+ case 'empty_output':+ return facts.reason === 'content_filter'+ ? 'The model provider filtered its response, so I could not continue. Please rephrase the request or try another provider.'+ : facts.reason === 'output_limit' || facts.reason === 'reasoning_only'+ ? 'The model used up its response limit without giving an answer. Try lowering its reasoning effort or choosing another model.'+ : 'The model returned empty responses, so I could not continue. Please try again later or choose another model.';+ case 'mode_contradiction':+ default:+ return consequential+ ? "I did part of the work but couldn't confirm the task finished. Please check the page before trying again, so nothing happens twice."+ : readOnly+ ? "I completed some read-only steps but couldn't verify the requested result, so I stopped. Nothing was changed, submitted, or sent."+ : "I couldn't complete the requested action, so I stopped without claiming success. Nothing was changed, submitted, or sent.";+ }+}++/** One plain-language step-limit message; the tool inventory stays in traces. */+export function stepLimitUserMessage(steps, lastAssistantText = '') {+ const count = Number.isSafeInteger(steps) && steps > 0 ? steps : 0;+ const lines = [`I reached the step limit${count ? ` (${count} step${count === 1 ? '' : 's'})` : ''} before finishing the task.`];+ const snippet = String(lastAssistantText || '').replace(/\s+/g, ' ').trim();+ if (snippet) lines.push(`Where I stopped: "${snippet.slice(0, 280)}${snippet.length > 280 ? '...' : ''}"`);+ lines.push('This usually means the task is too complex for the current model, the step limit is too low (you can raise it in Settings), or the task should be split into smaller parts.');+ return lines.join('\n\n');+}diff --git a/src/firefox/src/trace/trajectory.js b/src/firefox/src/trace/trajectory.jsindex 00dd95e8f..19c1d5b11 100644--- a/src/firefox/src/trace/trajectory.js+++ b/src/firefox/src/trace/trajectory.js@@ -79,8 +79,8 @@ function addError(row, data) {const FAILED_END_STATUSES = ['error', 'loop_stopped', 'max_steps', 'cancelled', 'cost_limit','plan_only_output', 'incomplete_output', 'empty_output',- 'placeholder_output', 'required_tool_missing', 'grounding_unavailable',- 'captcha_manual_required',+ 'placeholder_output', 'required_tool_missing', 'required_evidence_missing',+ 'task_binding_changed', 'grounding_unavailable', 'captcha_manual_required',];function markEnd(row, data) {diff --git a/src/firefox/src/ui/markdown-render.js b/src/firefox/src/ui/markdown-render.jsindex 8fb55931d..954ac8c99 100644--- a/src/firefox/src/ui/markdown-render.js+++ b/src/firefox/src/ui/markdown-render.js@@ -819,6 +819,25 @@ export function highlightCode(code, language) {}}+/**+ * Convert escaped Markdown blockquote lines (`> text`) into blockquote+ * elements. Showing the markers literally makes people copy them back into+ * requests as if they were content. Inline formatting and the newline-to-<br>+ * pass stay with the caller; the block swallows its trailing newline so it is+ * not followed by an extra blank line.+ */+export function renderMarkdownBlockquotes(text) {+ return String(text == null ? '' : text).replace(+ /(?:^[ \t]{0,3}>[^\r\n]*(?:\r?\n|$))+/gm,+ block => {+ const inner = block.replace(/\r?\n$/, '').split(/\r?\n/)+ .map(line => line.replace(/^[ \t]{0,3}>[ \t]?/, ''))+ .join('\n');+ return `<blockquote>${inner}</blockquote>`;+ }+ );+}+/** Convert escaped ATX heading lines while leaving inline formatting for the caller. */export function renderMarkdownHeadings(text) {return String(text == null ? '' : text).replace(diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.jsindex e382f3c97..e5d296bb2 100644--- a/src/firefox/src/ui/sidepanel.js+++ b/src/firefox/src/ui/sidepanel.js@@ -11,7 +11,7 @@ import { createQuotaController } from './compass-quota.js';import { t, getLocale, setLocale, LANGUAGES, applyDOMTranslations, translationsForKey } from './i18n.js';import { CAPABILITY_LABEL } from '../agent/permission-gate.js';import { sanitizeMarkdownLinks } from './markdown-link.js';-import { codeFenceLanguage, highlightCode, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';+import { codeFenceLanguage, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';import { applyMode, loadMode, watch } from './theme.js';import {UI_SCALE_LEVELS,@@ -10168,6 +10168,14 @@ function handleAgentUpdateMessage(msg) {break;case 'tool_result':+ // A refused completion (blocked done, or a completion skipped for a+ // fresh turn) keeps the run working; do not leave "Finishing up" shown+ // while the next step is decided.+ if (isTerminalDoneTool(data.name) && (data.result?.blockedDone === true+ || (data.result?.success === false && data.result?.done !== true))) {+ clearThinkingActivityTimers();+ beginThinkingActivity();+ }if (currentAssistantEl) {if (data.name === 'generate_image') {void appendGeneratedMedia(currentAssistantEl.querySelector('.message-content'), data.result, t);@@ -13457,6 +13465,7 @@ function formatMarkdown(text, options = {}) {// Code and inline-code placeholders were extracted above, so// Markdown-looking source inside them is not interpreted here.text = renderMarkdownTables(text);+ text = renderMarkdownBlockquotes(text);text = renderMarkdownHeadings(text);text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')diff --git a/src/firefox/styles/sidepanel.css b/src/firefox/styles/sidepanel.cssindex cf75ef48e..1ee9a752c 100644--- a/src/firefox/styles/sidepanel.css+++ b/src/firefox/styles/sidepanel.css@@ -3443,6 +3443,13 @@ html[data-ui-scale="175"] .conversation-action-label {.message-content h5,.message-content h6 { font-size: 13px; }+.message-content blockquote {+ margin: 6px 0;+ padding: 2px 0 2px 10px;+ border-left: 3px solid var(--border);+ color: inherit;+}+.markdown-table-wrapper {max-width: 100%;margin: 8px 0;diff --git a/test/chat-steering.mjs b/test/chat-steering.mjsindex e5545e4fb..d7cb18865 100644--- a/test/chat-steering.mjs+++ b/test/chat-steering.mjs@@ -289,7 +289,7 @@ for (const build of ['chrome', 'firefox']) {if (revisedKind === 'respond') assert.equal(result, 'Revised answer');else {// The replacement turn keeps the normal step cap and completion verification.- assert.match(result, /Step limit reached after 1 steps/);+ assert.match(result, /reached the step limit \(1 step\)/);assert.doesNotMatch(result, /Obsolete final-step answer|example\.com\/old/);assert.equal(calls, 2);}diff --git a/test/pure-calculation-reply.mjs b/test/pure-calculation-reply.mjsindex 170f00a39..ed6bdaa82 100644--- a/test/pure-calculation-reply.mjs+++ b/test/pure-calculation-reply.mjs@@ -324,7 +324,9 @@ for (const build of ['chrome', 'firefox']) {assert.deepEqual(updates.filter(e => e.type === 'tool_call').map(e => e.data.name), ['calculate']);assert.equal(updates.some(e => e.type === 'tool_result' && e.data.name === 'done'), false);assert.doesNotMatch(result, /page kept changing/);- assert.match(result, /could not verify the requested action after the recovery attempt/i);+ // The chat answer is plain language; the guard's diagnostic stays in traces.+ assert.match(result, /couldn't verify the requested result, so I stopped\. Nothing was changed, submitted, or sent\./);+ assert.doesNotMatch(result, /\[|\]|recovery attempt|task tools/);} finally { documents.delete(tab); }});}diff --git a/test/run.js b/test/run.jsindex d6b5c8f49..7b1a74f2b 100644--- a/test/run.js+++ b/test/run.js@@ -22441,10 +22441,11 @@ test('sidepanels wire highlighting and heading rendering into fenced Markdown',]) {const panel = fs.readFileSync(path.join(ROOT, panelRel), 'utf8');const css = fs.readFileSync(path.join(ROOT, cssRel), 'utf8');- assert.match(panel, /import \{ codeFenceLanguage, highlightCode, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences \} from '\.\/markdown-render\.js';/, `${label}: renderer helpers should be imported`);+ assert.match(panel, /import \{ codeFenceLanguage, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences \} from '\.\/markdown-render\.js';/, `${label}: renderer helpers should be imported`);assert.match(panel, /const lang = codeFenceLanguage\(info\);/, `${label}: fenced code should tolerate metadata after its language token`);assert.match(panel, /const highlighted = enhance \? highlightCode\(block\.code, block\.lang\) : escapeHtml\(block\.code\);/, `${label}: completed fenced code should be highlighted by its language while live code stays lightweight`);- assert.match(panel, /text = renderMarkdownTables\(text\);\s*text = renderMarkdownHeadings\(text\);/, `${label}: pipe tables must render before headings swallow the following newline`);+ assert.match(panel, /text = renderMarkdownTables\(text\);\s*text = renderMarkdownBlockquotes\(text\);\s*text = renderMarkdownHeadings\(text\);/, `${label}: pipe tables and quotes must render before headings swallow the following newline`);+ assert.match(css, /\.message-content blockquote \{[\s\S]*?border-left: 3px solid var\(--border\);/, `${label}: rendered quotes should be visually distinct`);assert.match(css, /\.message-content table \{[\s\S]*?border-collapse: collapse;/, `${label}: rendered tables should have readable borders`);assert.match(css, /\.syntax-keyword[\s\S]*?var\(--syntax-keyword\)/, `${label}: token colors should be styled`);assert.match(css, /\.syntax-variable \{ color: var\(--syntax-variable\); \}/, `${label}: variables should use their dedicated theme color`);@@ -55978,7 +55979,8 @@ test('schedule_resume pauses unfinished chat work without running success compleassert.equal(premature.action, 'continue');assert.equal(h.jobs()[0].status, 'pending', `${label}: a rejected done cancelled needed work`);const failed = await h.batch([['done', { summary: 'The support answer is complete.', outcome: 'success' }]]);- assert.equal(failed.status, 'plan_only_output');+ // The done path keeps the guard's own status (as the plain-final path does).+ assert.equal(failed.status, 'required_evidence_missing');assert.equal(h.jobs()[0].status, 'cancelled', `${label}: terminal failure left a continuation behind`);}});@@ -89435,7 +89437,8 @@ test('max-step exits clear open completion debt', async () => {agent.executeTool = async () => ({ success: true, verified: true });const final = await agent.processMessage(tabId, 'click the target', () => { }, 'act');- assert.match(final, /Step limit reached/i, `${AgentClass.name}: max-step path did not run`);+ assert.match(final, /reached the step limit/i, `${AgentClass.name}: max-step path did not run`);+ assert.doesNotMatch(final, /\[|\]/, `${AgentClass.name}: the step-limit answer must be plain language`);assert.equal(agent.completionInvariants.has(tabId), false, `${AgentClass.name}: max-step exit leaked completion state`);}});@@ -91637,9 +91640,10 @@ test('Act fails transparently when a stale cancellation echo repeats', async ()const final = await agent.processMessage(tabId, 'Read the open email and draft a reply.', () => { }, 'act');- assert.match(final, /repeated a stale cancellation status/, `${AgentClass.name}: repeated stale cancellation was misreported`);- assert.match(final, /No current user stop was received/, `${AgentClass.name}: failure implied the user cancelled`);- assert.match(final, /no successful action was verified/i, `${AgentClass.name}: failure claimed execution evidence`);+ // The chat answer is plain language; the guard diagnostic stays in traces.+ assert.match(final, /stopped without completing the task/i, `${AgentClass.name}: repeated stale cancellation was misreported`);+ assert.doesNotMatch(final, /stopped by user|you stopped|\[|\]/i, `${AgentClass.name}: failure implied the user cancelled`);+ assert.match(final, /Nothing was changed/, `${AgentClass.name}: failure claimed execution evidence`);}});@@ -91671,10 +91675,10 @@ test('Act preserves successful tool evidence when a stale cancellation echo repeconst final = await agent.processMessage(tabId, 'Read the open email and draft a reply.', () => { }, 'act');- assert.match(final, /repeated a stale cancellation status/, `${AgentClass.name}: repeated stale cancellation was misreported`);- assert.match(final, /Some task tools completed/, `${AgentClass.name}: successful tool evidence was discarded`);- assert.match(final, /Inspect the current state before retrying/, `${AgentClass.name}: retry warning was omitted`);- assert.doesNotMatch(final, /no successful action was verified/i, `${AgentClass.name}: failure contradicted verified tool evidence`);+ assert.match(final, /couldn't confirm the task finished/, `${AgentClass.name}: repeated stale cancellation was misreported`);+ assert.match(final, /Some steps were completed/, `${AgentClass.name}: successful tool evidence was discarded`);+ assert.match(final, /check the page before trying again/, `${AgentClass.name}: retry warning was omitted`);+ assert.doesNotMatch(final, /Nothing was changed|\[|\]/, `${AgentClass.name}: failure contradicted verified tool evidence`);}});@@ -91823,7 +91827,7 @@ test('Act reports failure when plan-only output repeats after its recovery nudgeconst final = await agent.processMessage(tabId, 'Read the current page and summarize it.', () => { }, 'act');- assert.match(final, /No successful action was verified/, `${AgentClass.name}: repeated plan was accepted as success`);+ assert.match(final, /Nothing was changed, submitted, or sent/, `${AgentClass.name}: repeated plan was accepted as success`);assert.equal(ended?.status, 'plan_only_output', `${AgentClass.name}: repeated plan retained a successful trace status`);}});@@ -103800,7 +103804,7 @@ test('streamed repeated plan-only output replaces rejected deltas with the failu);assert.equal(provider.calls, 2, `${AgentClass.name}: repeated plan did not consume the recovery turn`);- assert.match(final, /No successful action was verified/, `${AgentClass.name}: repeated streamed plan was accepted`);+ assert.match(final, /Nothing was changed, submitted, or sent/, `${AgentClass.name}: repeated streamed plan was accepted`);const finalText = updates.filter(update => update.type === 'text').at(-1);assert.equal(finalText?.data?.content, final, `${AgentClass.name}: streamed failure did not replace rejected plan deltas`);assert.equal(finalText?.data?.replace, true, `${AgentClass.name}: streamed failure lacked a forced-replace signal`);diff --git a/test/terminal-user-messages.mjs b/test/terminal-user-messages.mjsnew file mode 100644index 000000000..aae554b03--- /dev/null+++ b/test/terminal-user-messages.mjs@@ -0,0 +1,109 @@+import assert from 'node:assert/strict';+import fs from 'node:fs';+import { test } from 'node:test';++// Unit and Agent-batch checks with mocked browser APIs. The final chat answer+// for a guard-ended run is plain language; the mechanical diagnostic remains+// on the done tool result (verbose rows) and in traces.+const area = { get: async () => ({}), set: async () => {}, remove: async () => {} };+globalThis.chrome = globalThis.browser = {+ storage: { local: area, session: area },+ runtime: { getURL: value => `extension://test/${value}`, sendMessage: async () => ({}) },+ tabs: { get: async id => ({ id, url: 'https://x.com/home', title: 'Home / X' }), sendMessage: async () => ({}) },+ scripting: { executeScript: async () => [{ result: null }] },+};++const jargon = /\[|\]|job-bound|terminal evidence|recovery nudge|PLAN EXECUTION|dispatch|workflow|consequential|tool call/i;++for (const build of ['chrome', 'firefox']) {+ test(`${build}: guard terminal messages are plain language`, async () => {+ const { terminalGuardUserMessage, stepLimitUserMessage, socialPlatformLabel } = await import(`../src/${build}/src/agent/terminal-messages.js`);+ const kinds = ['task_changed', 'schedule_missing', 'download_missing', 'social_missing', 'submission_missing',+ 'forbidden_submission', 'job_evidence_missing', 'draft_missing', 'ledger_incomplete', 'stale_cancellation',+ 'clarification_required', 'placeholder_output', 'empty_output', 'mode_contradiction', 'default'];+ for (const kind of kinds) for (const facts of [{}, { consequential: true }, { readOnly: true },+ { unconfirmed: ['twitter'] }, { notStarted: ['bluesky'], verified: ['twitter'] }, { reason: 'content_filter' }]) {+ const message = terminalGuardUserMessage(kind, facts);+ assert.ok(message.length > 20 && message.length < 600, `${kind}: unexpected length`);+ assert.doesNotMatch(message, jargon, `${kind}: mechanical wording leaked into the chat answer`);+ }+ const social = terminalGuardUserMessage('social_missing', { unconfirmed: ['twitter'], notStarted: ['bluesky'] });+ assert.match(social, /clicked Post on X/);+ assert.match(social, /didn't post again/);+ assert.match(social, /nothing was published there/);+ assert.match(social, /Bluesky/);+ assert.equal(socialPlatformLabel('twitter'), 'X');+ // "I submitted" only when a submit dispatch was recorded for this task.+ assert.match(terminalGuardUserMessage('submission_missing', { submitted: true, consequential: true }), /^I submitted it/);+ assert.doesNotMatch(terminalGuardUserMessage('submission_missing', { consequential: true }), /submitted it/);+ assert.match(terminalGuardUserMessage('submission_missing', { consequential: true }), /final submission didn't go through/);+ const limit = stepLimitUserMessage(130, 'I opened the composer.');+ assert.match(limit, /step limit \(130 steps\)/);+ assert.match(limit, /Where I stopped: "I opened the composer\."/);+ assert.doesNotMatch(limit, /\[|\]|Γ|ref_/);+ });+}++test('terminal message module stays byte-identical across builds', () => {+ assert.equal(fs.readFileSync(new URL('../src/chrome/src/agent/terminal-messages.js', import.meta.url), 'utf8'),+ fs.readFileSync(new URL('../src/firefox/src/agent/terminal-messages.js', import.meta.url), 'utf8'));+});++function batchAgent(Agent, tabId) {+ const agent = new Agent({ getActive: () => ({ model: 'test', supportsTools: true }), getVisionProvider: async () => null });+ agent.conversationIds.set(tabId, 'conv-terminal');+ agent.conversationModes.set(tabId, 'act');+ agent.conversations.set(tabId, [+ { role: 'system', content: 'sys' },+ { role: 'user', content: 'Post "Hello" on X.' },+ ]);+ agent._ensureGateSetting = async () => {};+ agent._skipPermissionGate = true;+ agent._currentUrl = async () => 'https://x.com/home';+ agent._persist = () => {};+ agent._persistNow = async () => true;+ agent.executeTool = async (_tab, name, args) => {+ if (name === 'done') return { done: true, summary: args.summary, outcome: args.outcome };+ throw new Error(`unexpected ${name}`);+ };+ return agent;+}++for (const build of ['chrome', 'firefox']) {+ test(`${build}: a publication that could not be confirmed ends with a plain answer and keeps the diagnostic`, async () => {+ const { Agent } = await import(`../src/${build}/src/agent/agent.js`);+ const { normalizePublicationContract } = await import(`../src/${build}/src/agent/social-publish-contract.js`);+ const tabId = 4401;+ const agent = batchAgent(Agent, tabId);+ const guard = agent._startPlanExecutionGuard(tabId, 'act', {+ requestKind: 'execute', requiresStateChange: true, requiresSubmission: true,+ });+ const contract = normalizePublicationContract({ version: 1, status: 'ready', actions: [{ id: 'p1', platform: 'twitter',+ account: null, posts: [{ body: { kind: 'exact', source: { source: 'request', start: 'Hello', end: 'Hello' } },+ media: { kind: 'count', type: 'any', format: null, min: 0, max: 0 }, context: { kind: 'post', target: null } }] }],+ requirements: 'p1', prohibited: [], reason: 'post' }, { request: 'Post "Hello" on X.' });+ // The Post click was delivered (pending), then the page changed before+ // job-bound evidence could be captured.+ guard.socialPublication = { key: 'contract-key', actionId: 'p1', contract, outcomes: { p1: { status: 'pending' } } };+ guard.successfulConsequentialToolCalls = 1;+ guard.successfulTaskToolCalls = 2;+ guard.evidenceTaskKey = guard.taskKey;+ const updates = [], messages = [];+ const batch = id => agent._executeToolBatch(tabId, [{ id, function: { name: 'done',+ arguments: JSON.stringify({ summary: 'Posted.', outcome: 'success' }) } }], messages,+ (type, data) => updates.push({ type, data }), { supportsVision: false }, null, new Set(['done']), 1, {});+ const first = await batch('done_1');+ assert.equal(first.action, 'continue', 'the first missing-evidence done gets one recovery turn');+ const second = await batch('done_2');+ assert.equal(second.action, 'return');+ assert.equal(second.status, 'required_evidence_missing', 'the guard status is preserved for traces');+ assert.doesNotMatch(second.value, jargon, 'the chat answer must not show guard mechanics');+ assert.match(second.value, /clicked Post on X/);+ assert.match(second.value, /didn't post again/);+ const result = updates.filter(update => update.type === 'tool_result' && update.data.name === 'done').at(-1).data.result;+ assert.match(result.error, /^\[Agent stopped because job-bound terminal evidence was still missing/,+ 'verbose rows and traces keep the exact diagnostic');+ assert.equal(result.outcome, 'failed');+ assert.match(String(messages.at(-1)?.content || ''), /job-bound terminal evidence/, 'later model turns keep the diagnostic');+ });+}