Skip to content

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

fix: improve recovery and streamed answer handling

Barack Sokulluda8556c3fcf6
diff --git a/docs/social-publication-contract.md b/docs/social-publication-contract.md
index 24c912ef2..8ab438278 100644
--- a/docs/social-publication-contract.md
+++ b/docs/social-publication-contract.md
@@ -12,7 +12,11 @@ Assistant draft references include ordinary assistant text and exact `done(summa
The contract records destinations, accounts, ordered post bodies, media constraints, reply/quote targets, prohibited destinations, and `all`, `any`, or conditional `fallback` requirements. Exact text uses source anchors so the runtime copies the original text instead of accepting a model-reconstructed excerpt. Repeated anchors accept optional `startOccurrence` and `endOccurrence` positive, one-based ordinals, each counted from the beginning of the named source (including overlapping matches). For a short literal with identical start/end anchors, `startOccurrence` alone selects that copy. Omitted ordinals still require unambiguous anchors; invalid or reversed selections are rejected. Unsupported or ambiguous requirements produce `clarify`; read-only or narrative requests produce `none`. Invalid contracts cannot fall back to lexical intent rules.
-A ready contract is not sufficient permission to dispatch. Before a separate publish click, the same selected provider independently checks the authentic request against the concrete composer snapshot. Approval is cached only for that contract, action, payload, account, and page. The runtime rereads the composer after the audit and immediately before execution. A changed snapshot needs a new audit. Rejections retain the checker's reason (or identify invalid/mismatched output) in the tool result so recovery can resolve the actual issue instead of rewriting a matching draft. Arbitrary JavaScript, bundled editing/submission, keyboard submission, and opaque callbacks cannot substitute for the observed publish control.
+A ready contract normally also requires an independent audit by the selected provider against the concrete composer snapshot. Approval is cached only for that contract, action, payload, account, page, and document/frame. The runtime rereads the composer after the audit and immediately before execution. A changed snapshot needs a new audit. Rejections retain the checker's reason; invalid/mismatched output and request failures are separate technical failures. Arbitrary JavaScript, bundled editing/submission, keyboard submission, and opaque callbacks cannot substitute for the observed publish control.
+
+Compilation and audit use 2,048 output tokens initially and 4,096 for one format repair, capped by the selected provider's limit. Supported provider controls reduce reasoning and request structured JSON; an explicit unsupported-control rejection gets a portable prompt-only repair. Repairs keep the original user input and binding frozen and add format instructions to the system message. The audit accepts one JSON object, optionally fenced, with exact key/action identifiers, a boolean verdict, and a string reason; extra metadata is harmless and displayed reasons are limited to 600 characters. Empty, malformed, conflicting, or mismatched results cannot authorize dispatch. Trace exports include each request/reply, output budget, finish/token diagnostics, and the precise validation failure.
+
+An exhausted publication check stops the run with a clear failure message and app-owned Give up / Retry controls. Give up leaves the draft untouched. A direct user Retry grants one audit exemption for this unchanged task, action, account, payload, page, and document/frame. It skips the independent model audit for one dispatch attempt while keeping intent compilation, deterministic preflight, fresh observations, capability permissions, and duplicate-delivery checks. Model-authored arguments, alternate click strategies, and ordinary Continue cannot grant this exemption. Changes or steering invalidate it; it is consumed immediately before the actual guarded tool invocation and cannot be replayed, including after an uncertain or failed invocation. The frozen contract and user grant survive trusted Continue without being counted as successful execution.
## Deterministic enforcement
@@ -34,7 +38,7 @@ A ready contract is not sufficient permission to dispatch. Before a separate pub
- A corrected replacement after an uncertain text write can proceed only after a read-only digest proves the original replacement landed in the same document and field. Changed, incomplete, or unavailable readbacks retain the block; generic page reads never clear it.
- Convert screenshot clicks to CSS coordinates before target/iframe preflight, and use that same point for dispatch.
-Malformed output or failed model calls block publication. Schema validation establishes structure, not correct language understanding; the independent audit is also fallible. Missing site evidence blocks dispatch/completion rather than supplying inferred proof.
+Malformed output or failed model calls block publication until repaired or directly retried by the user through the bound audit exemption. Schema validation establishes structure, not correct language understanding; the independent audit is also fallible. Missing site evidence blocks dispatch/completion rather than supplying inferred proof.
## Validation
diff --git a/docs/trace-format-compatibility.md b/docs/trace-format-compatibility.md
index a52d1fbdb..3d5229d59 100644
--- a/docs/trace-format-compatibility.md
+++ b/docs/trace-format-compatibility.md
@@ -14,6 +14,10 @@ WebBrain's trace data has three independent version layers:
## Reader obligations
+Planner alignment and publication checks record their auxiliary model requests and responses, including `requestedMaxTokens`, `candidateAttempt`, finish/token diagnostics, and a finite `validationFailure` code. Technical repairs keep the candidate binding fixed and are distinct from a replacement plan after a valid semantic rejection. Metadata-only traces retain those diagnostics without prompts, replies, arbitrary JSON property names, or checker explanations; content-enabled traces follow the existing recording policy.
+
+Recoverable failures may include a `failure_recovery_offered` note with the failed stage and retry mode. Chat controls use an opaque runtime recovery ID bound to the exact task and conversation. Starting another run, changing the task, stopping, or choosing Give up expires the offer. Model, response-generation, context, and interaction failures resume through normal continuation checks; publication Retry is the separately bound, one-use audit exemption described in the publication contract.
+
Tool events may include an optional `data.outcome` summary containing bounded dispatch, application, provider, error, and CAPTCHA-gate diagnostics. In lossless recordings, this summary survives the content-budget marker, while answer tokens, cookies, provider keys, and form inputs are excluded from the summary. Readers should still honor `_truncated` and `losslessBudgetOmitted`; the summary does not reconstruct discarded content.
`/export --traces --full` exports the stored conversation through the existing `webbrain-trace/1` session envelope, including stored screenshots. It adds no Markdown preview or turn-count truncation. Recording-time omissions and privacy projections remain explicit. The side panel reads the shared trace database and assembles the download locally; only the session identity crosses runtime messaging, so screenshot-heavy exports do not hit the browser message-size limit.
diff --git a/package.json b/package.json
index a0252b938..e1aed9086 100644
--- a/package.json
+++ b/package.json
@@ -5,7 +5,8 @@
"private": true,
"type": "module",
"scripts": {
- "test": "npm run test:shard:quick && npm run test:shard:runtime-unit && npm run test:shard:browser-a && npm run test:shard:browser-b1 && npm run test:shard:browser-b2 && npm run test:shard:browser-c && npm run test:shard:tail",
+ "test": "npm run test:failure-recovery && npm run test:shard:quick && npm run test:shard:runtime-unit && npm run test:shard:browser-a && npm run test:shard:browser-b1 && npm run test:shard:browser-b2 && npm run test:shard:browser-c && npm run test:shard:tail",
+ "test:failure-recovery": "node --test test/failure-recovery.mjs test/failure-recovery-ui.mjs test/post-submit-model-recovery.mjs test/run-ui-response-retry.mjs test/ask-stream-retry-ui.mjs",
"test:captcha:ui": "node test/captcha-settings-ui.mjs && node test/captcha-application-ui.mjs",
"test:captcha:bridge:ui": "node test/captcha-callback-bridge-ui.mjs",
"test:billing-notice": "node test/billing-payment-notice.mjs",
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index 89ab51c93..6a7625fb6 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -11,17 +11,18 @@ import { installPageFeedback, beforePageAgentDispatch, capturePageAgentInputComp
import { JEV_FAST_KEYS, JEV_CLASSIFIER_THRESHOLD, JEV_BROWSER_THRESHOLD, confidentChoice, buildJevBrowserRequest, decideJevBrowser, jevVisualInputRequiresMainModel, JevFastSession } from './systemone-fast.js';
import { redactSystemOneText, wrapSystemOneData, boundedSystemOneText } from './systemone-evidence.js';
import { createSystemOneJudge, isSystemOneResponseContractError, systemOneFailureReason, SYSTEM_ONE_COST_PROVIDER } from './systemone-judge.js';
-import { SOCIAL_PLATFORMS, socialPublicationApiPlatform, normalizePublicationContract, publicationProgress, exactPublicationText, publicationMediaMatches, publicationContractMessages, publicationAuditMessages, publicationAuditAccepted } from './social-publish-contract.js';
+import { SOCIAL_PLATFORMS, socialPublicationApiPlatform, normalizePublicationContract, publicationProgress, exactPublicationText, publicationMediaMatches, publicationContractMessages, publicationAuditMessages, parsePublicationJson, publicationAuditValidation } from './social-publish-contract.js';
import { mastodonPublicationIntentMessages, normalizeMastodonPublicationIntent, captureNativeMastodonPublication, mastodonPublicationBinding, mastodonPublicationReceipt, mastodonPublicationNavigation } from './mastodon-publication.js';
import { AGENT_TOOLS, AGENT_TOOL_NAMES, RESERVED_AGENT_TOOL_NAMES, getToolsForMode, SYSTEM_PROMPT_ASK, SYSTEM_PROMPT_ACT, SYSTEM_PROMPT_ACT_COMPACT, SYSTEM_PROMPT_ACT_MID, SYSTEM_PROMPT_GENERATIVE_MEDIA, SYSTEM_PROMPT_DEV_APPENDIX, SYSTEM_PROMPT_WEBMCP_ASK, SYSTEM_PROMPT_WEBMCP_ACT } from './tools.js';
import { rejectedCompletionRecovery } from './completion-recovery.js';
+import { FailureRecoveryRegistry, modelFailureRecovery } from './failure-recovery.js';
import { validateToolArguments } from './tool-arguments.js';
import { calculateExpression, calculationResultInText } from './calculator.js';
import { isLiteralCalculationTask, literalCalculationSummaryFormatMatches, isPassivePageFeedback } from './page-feedback-policy.js';
import { chatRecoveryDisplayText, terminalRecoveryFinalText } from './chat-recovery-text.js';
import { isSessionQuotaError, serializeConversationForSession, SESSION_CONVERSATION_BUDGET_BYTES, SESSION_CONVERSATION_RETRY_BUDGET_BYTES } from './conversation-persistence.js';
import { formatErrorMessage } from '../error-format.js';
-import { retryModelCall } from '../providers/model-retry.js';
+import { retryModelCall, retryModelStream } from '../providers/model-retry.js';
import { isQwenConfig } from '../providers/provider-compatibility.js';
import { aggregateMessageCompletion } from '../message-info.js';
import { handleDoneJson } from './cloud-output.js';
@@ -125,7 +126,7 @@ import {
buildPlannerMessages,
buildPlannerAlignmentMessages,
buildPlannerAlignmentRepairMessages,
- parsePlannerAlignmentFromContent,
+ inspectPlannerAlignmentContent,
PLANNER_ALIGNMENT_RESPONSE_JSON_SCHEMA,
buildPlannerIntentMessages,
buildReadScopeMessages,
@@ -1184,6 +1185,7 @@ export class Agent extends LoopDetector {
// abort() and clearConversation() cancel all pending clarifications so
// the agent loop doesn't deadlock.
this._pendingClarifications = new Map();
+ this._failureRecovery = new FailureRecoveryRegistry();
// One-use approvals issued only by an explicit research-escalation
// clarification response. Never persisted; scoped to tab + conversation.
this._researchEscalationAuthorizations = new Map();
@@ -6527,6 +6529,7 @@ export class Agent extends LoopDetector {
// Claim synchronously before awaiting the external guard so teacher-mode
// startup cannot race a run whose persisted teacher-state check is pending.
this._runningTabs.add(tabId);
+ this._failureRecovery.clear(tabId);
this._jevSessions?.delete(tabId);
for (const [id, pending] of this._jevPendingCalls || []) if (pending.tabId === tabId) this._jevPendingCalls.delete(id);
this._systemOneGenerations ??= new Map();
@@ -6930,6 +6933,128 @@ export class Agent extends LoopDetector {
return null;
}
+ _failureRecoveryBinding(tabId) {
+ return { tabId, conversationId: this.conversationIds.get(tabId) || '',
+ taskKey: this._progressTaskKeyHash(tabId), taskSignature: this._sha256TextSync(this._progressTaskAnchorText(tabId)) };
+ }
+
+ _pendingFailureRecoveryForUi(tabId) {
+ return this._failureRecovery.current(this._failureRecoveryBinding(tabId))?.descriptor || null;
+ }
+
+ _offerFailureRecovery(tabId, details, onUpdate) {
+ if (this._checkAbort(tabId) || this._hasPendingSteering(tabId)) return null;
+ const binding = this._failureRecoveryBinding(tabId);
+ const recoveryId = 'recovery_' + secureRandomBase36Token(24);
+ const descriptor = { recoveryId, stage: details.stage || 'model',
+ code: details.code || 'request_failed', message: String(details.message || 'The task could not finish.').slice(0,2000),
+ retryMode: details.stage === 'publication_audit' ? 'publication_without_audit' : 'resume',
+ retryLabel: 'Retry', giveUpLabel: 'Give up',
+ ...(details.diagnostics ? { diagnostics: String(details.diagnostics).slice(0,6000) } : {}) };
+ this._failureRecovery.offer({ ...binding,
+ ...(details.publicationKey ? { publicationKey: details.publicationKey,
+ publicationTaskKey: details.taskKey } : {}) }, descriptor);
+ onUpdate?.('failure_recovery', descriptor);
+ const runId = this.currentRunId.get(tabId);
+ if (runId) trace.recordNote(runId, 0, 'failure_recovery_offered', {
+ stage: descriptor.stage, code: descriptor.code, retryMode: descriptor.retryMode });
+ return descriptor;
+ }
+
+ async _recoverPostActionModelFailure(tabId, messages, onUpdate, provider, step, runOptions = {}) {
+ const submit = this._completionSubmitStates.get(tabId);
+ const invariant = this.completionInvariants.get(tabId);
+ if (submit?.dispatched !== true || !invariant?.lastAction || !this._isActionMode(this._effectiveRunMode(tabId))
+ || this._checkAbort(tabId) || this._hasPendingSteering(tabId)) return null;
+ const binding = this._failureRecoveryBinding(tabId);
+ const actionSequence = invariant.lastAction.sequence;
+ const runToken = invariant.runToken;
+ const current = () => {
+ const latestBinding = this._failureRecoveryBinding(tabId);
+ return this.completionInvariants.get(tabId)?.runToken === runToken
+ && this.completionInvariants.get(tabId)?.lastAction?.sequence === actionSequence
+ && binding.taskKey === latestBinding.taskKey
+ && binding.taskSignature === latestBinding.taskSignature
+ && binding.conversationId === latestBinding.conversationId
+ && !this._checkAbort(tabId) && !this._hasPendingSteering(tabId);
+ };
+ if (!current()) return null;
+ onUpdate?.('warning', { message: 'The model request failed after submission. Inspecting the result without repeating the action.' });
+ const frame = this._completionIframeBinding(tabId);
+ const readName = frame?.currentUrl ? 'verify_form' : 'get_accessibility_tree';
+ const readArgs = frame?.currentUrl ? { urlFilter: frame.currentUrl } : { filter: 'visible', maxChars: 6000 };
+ const runReadOnly = async (name, args) => {
+ const id = 'call_recovery_' + secureRandomBase36Token(24);
+ const call = { id, type: 'function', function: { name, arguments: JSON.stringify(args) } };
+ messages.push({ role: 'assistant', content: null, tool_calls: [call] });
+ return this._executeToolBatch(tabId, [call], messages, onUpdate, provider, null,
+ AGENT_TOOL_NAMES, step, runOptions);
+ };
+ try {
+ await runReadOnly(readName, readArgs);
+ if (!current() || this._completionDoneBlock(tabId, 'done', { outcome: 'success' })) return null;
+ const pageUrl = await this._currentUrl(tabId);
+ if (!current()) return null;
+ const summary = /^https:\/\/addons\.mozilla\.org\//i.test(pageUrl)
+ ? 'The AMO version was submitted for review and the submission confirmation was verified.'
+ : 'The requested submission completed and its result was verified.';
+ const result = await runReadOnly('done', { outcome: 'success', summary });
+ if (current() && result?.action === 'return' && !result.status
+ && this._completionVerdicts.get(tabId)?.outcome === 'succeeded') {
+ if (typeof runOptions.afterVerifiedCompletion === 'function') {
+ await this._settleVerifiedScheduledCompletion(tabId, messages, result, {
+ ...runOptions,
+ afterVerifiedCompletion: proof => runOptions.afterVerifiedCompletion({
+ ...proof,
+ isCurrent: () => current() && proof.isCurrent(),
+ refresh: async () => current() && await proof.refresh() && current(),
+ }),
+ });
+ this._throwIfAborted(this._runAbortSignal(tabId));
+ if (!current()) return null;
+ }
+ return { content: result.value, status: 'done' };
+ }
+ } catch (error) {
+ if (this._checkAbort(tabId) || error?.name === 'AbortError' || this._isCostAllowanceError(error)) throw error;
+ const runId = this.currentRunId.get(tabId);
+ if (runId) trace.recordError(runId, step, 'completion_recovery', formatErrorMessage(error), this._traceErrorCodeFor(error));
+ }
+ return null;
+ }
+
+ async _finalModelFailure(tabId, messages, onUpdate, provider, error, step, runOptions = {}) {
+ const runId = this.currentRunId.get(tabId);
+ if (runId) trace.recordError(runId, step, 'model', formatErrorMessage(error), this._traceErrorCodeFor(error));
+ const recovered = await this._recoverPostActionModelFailure(tabId, messages, onUpdate, provider, step, runOptions);
+ if (recovered) return recovered;
+ const postAction = this._completionSubmitStates.get(tabId)?.dispatched === true;
+ const details = modelFailureRecovery(error, { postAction });
+ this._offerFailureRecovery(tabId, details, onUpdate);
+ onUpdate?.('error', { message: details.message });
+ return { content: details.message, status: postAction ? 'partial' : 'error' };
+ }
+
+ requestFailureRecovery(tabId, recoveryId, choice) {
+ if (!['retry', 'give_up'].includes(choice)) return { ok: false, error: 'Invalid recovery choice.' };
+ if (this.isRunning(tabId)) return { ok: false, error: 'Wait for the current run to finish before choosing recovery.' };
+ const offer = this._failureRecovery.current(this._failureRecoveryBinding(tabId));
+ if (!offer || offer.descriptor.recoveryId !== recoveryId) {
+ return { ok: false, error: 'This retry has expired. Start or continue the current task.' };
+ }
+ if (choice === 'retry' && offer.descriptor.retryMode === 'publication_without_audit') {
+ const granted = this._grantSocialPublicationAuditRetry(tabId, { ...offer.binding,
+ taskKey: offer.binding.publicationTaskKey || offer.binding.taskKey });
+ if (granted !== true && granted?.ok !== true) {
+ this._failureRecovery.clear(tabId);
+ return { ok: false, error: granted?.error || 'The publication changed. Verify the current draft before retrying.' };
+ }
+ }
+ if (choice === 'give_up') this._revokeSocialPublicationAuditRetry(tabId);
+ this._failureRecovery.clear(tabId);
+ return { ok: true, continue: choice === 'retry', retryMode: offer.descriptor.retryMode };
+ }
+
activeRunState(tabId) {
const persistenceState = this.persistenceDegradedTabs.get(tabId) || null;
const state = {
@@ -6937,6 +7062,7 @@ export class Agent extends LoopDetector {
runId: this.currentRunId.get(tabId) || null,
pendingPlan: null,
pendingCurrentClarification: this._pendingCurrentClarificationForUi(tabId),
+ pendingFailureRecovery: this._pendingFailureRecoveryForUi(tabId),
persistenceDegraded: !!persistenceState,
persistenceDegradedReason: persistenceState?.reason || null,
researchEscalationSourceTabId: this.researchEscalationSourceTab(tabId),
@@ -13927,6 +14053,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (runId) trace.recordToolCall(runId, step, {
name: fnName, args: fnArgs, result: workflowPreSubmitBlock, latencyMs: 0,
});
+ if (workflowPreSubmitBlock.failureRecovery?.stage === 'publication_audit') {
+ const offer = this._offerFailureRecovery(tabId, workflowPreSubmitBlock.failureRecovery, onUpdate);
+ this._appendSyntheticToolResults(tabId, toolCalls, toolIndex + 1, messages, onUpdate, step,
+ () => ({ success: false, skipped: true, noDispatch: true, error: 'Paused for a user recovery choice.' }));
+ this._persist(tabId);
+ return { action: 'return', value: offer?.message || workflowPreSubmitBlock.error, status: 'publication_audit_failed' };
+ }
onUpdate('warning', { message: workflowPreSubmitBlock.error });
if (workflowPreSubmitBlock.workflowRearmed || workflowPreSubmitBlock.conditionalMutationBlocked) {
this._appendSyntheticToolResults(tabId, toolCalls, toolIndex + 1, messages, onUpdate, step,
@@ -14554,6 +14687,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
&& (this._hasPendingSteering(tabId) || await this._refreshPageFeedbackForCall(tabId, tc, onUpdate))) return { steered: true };
const calculationDispatchBlock = this._pureCalculationToolBlock(tabId, fnName, fnArgs, calculationRequestScope);
if (!pipelineToolbarPreflight.block && !socialDispatchBlock && !genericChatBlock && !calculationDispatchBlock) {
+ if (detectedSubmitAction?.isSubmit === true && detectedSubmitAction.publicationControl === true) {
+ this._consumeSocialPublicationAuditRetry(tabId);
+ }
if (fnName === 'calculate') this._rememberPureCalculationAttempt(tabId, fnArgs, calculationRequestScope);
callState.invoked = true;
}
@@ -15251,6 +15387,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
await settleConsequentialTool();
this._throwIfAborted(this._runAbortSignal(tabId));
+ if (toolResult?.failureRecovery?.stage === 'publication_audit') {
+ const offer = this._offerFailureRecovery(tabId, toolResult.failureRecovery, onUpdate);
+ this._appendSyntheticToolResults(tabId, toolCalls, toolIndex + 1, messages, onUpdate, step,
+ () => ({ success: false, skipped: true, noDispatch: true, error: 'Paused for a user recovery choice.' }));
+ this._persist(tabId);
+ return { action: 'return', value: offer?.message || toolResult.error, status: 'publication_audit_failed' };
+ }
if ((captchaGateDecision?.status === 'manual_required' || captchaSolveOutcome?.status === 'manual_required')
&& !this._canTryNativeCaptcha(tabId, captchaGateDecision || captchaSolveOutcome)) {
this._appendSyntheticToolResults(
@@ -18715,6 +18858,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
*/
abort(tabId) {
for (const id of this._researchEscalationTabIds(tabId)) {
+ this._failureRecovery.clear(id);
+ this._revokeSocialPublicationAuditRetry(id);
this._ownedNativeChatReadRepairs.delete(id);
this.abortFlags.set(id, true);
cdpClient.stopDialogHandling(id);
@@ -21047,6 +21192,134 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
}
+ _socialPublicationChatOptions(provider, retry = false, portable = false, audit = false) {
+ const options = {
+ temperature: 0,
+ maxTokens: Math.min(retry ? 4096 : 2048, this._providerMaxOutputTokens(provider)),
+ };
+ if (!portable) {
+ const config = { ...(provider?.config || {}),
+ providerName: provider?.config?.providerName || provider?.name || '',
+ model: provider?.config?.model || provider?.model || '' };
+ const schema = audit ? { type: 'object', additionalProperties: false,
+ properties: { key: { type: 'string' }, actionId: { type: 'string' },
+ authorized: { type: 'boolean' }, reason: { type: 'string' } },
+ required: ['key', 'actionId', 'authorized', 'reason'] } : null;
+ const controls = plannerRequestBody(config, {
+ schema, schemaName: 'webbrain_social_publication_authorization', disableThinking: true,
+ });
+ if (['anthropic', 'anthropic-oauth', 'google-vertex-anthropic'].includes(provider?.name)) {
+ controls.thinking = { type: 'disabled' };
+ }
+ if (Object.keys(controls).length) options.extraBody = controls;
+ }
+ return options;
+ }
+
+ _socialPublicationOptionsRejected(error) {
+ const text = String(error?.message || error || '');
+ return /response_format|json_schema|reasoning(?:_effort)?|thinking|chat_template_kwargs/i.test(text)
+ && /unsupported|not supported|unknown|unrecognized|not allowed|unexpected|invalid.*(?:parameter|argument)/i.test(text);
+ }
+
+ _socialPublicationRepairMessages(messages) {
+ return this._plannerProtocolRepairMessages(messages,
+ '/no_think\nThe publication checker response was empty, truncated, or invalid. '
+ + 'Recheck the same unchanged authentic task and supplied binding. Return exactly one complete JSON object '
+ + 'matching the documented schema, with the supplied key and actionId when auditing. '
+ + 'No prose, tool calls, Markdown, or reasoning text. This is format repair, not new user permission.');
+ }
+
+ _socialPublicationResponseObject(response, options) {
+ const diagnostics = modelOutputDiagnostics(response, { requestedMaxTokens: options.maxTokens });
+ if (diagnostics.empty) throw new Error(diagnostics.emptyReason || 'empty_response');
+ if (/^(?:length|max_tokens|max_output_tokens|output_limit)$/i.test(diagnostics.finishReason || '')) {
+ throw new Error('truncated_response');
+ }
+ return parsePublicationJson(response?.content);
+ }
+
+ async _socialPublicationCheckerFailure(tabId, phase, attempt, error, validation = false) {
+ const runId = this.currentRunId.get(tabId);
+ if (!runId) return;
+ if (!validation) {
+ await this._tracePlannerAttemptFailure(runId, phase, attempt, error, 'publication_checker_failed');
+ return;
+ }
+ try {
+ await trace.recordNote(runId, 0, 'publication_checker_validation_failed', {
+ phase, attempt, validationFailure: String(error?.message || error).slice(0, 600),
+ });
+ await trace.recordError(runId, 0, 'publication_checker_invalid_response', String(error?.message || error).slice(0, 600));
+ } catch {}
+ }
+
+ _grantSocialPublicationAuditRetry(tabId, binding) {
+ const liveGuard = this._planExecutionGuards.get(tabId);
+ const carried = this._continuationExecutionEvidence.get(tabId);
+ // Settled runs release the live guard. The app-owned continuation snapshot
+ // retains the publication binding for the user's later recovery choice.
+ const guard = liveGuard || (carried?.requestKind === 'execute'
+ && carried.conversationId === (this.conversationIds.get(tabId) || null) ? carried : null);
+ const social = guard?.socialPublication;
+ const action = this._socialPublicationAction(guard);
+ if (!(liveGuard ? guard?.enabled : guard?.requestKind === 'execute') || guard.taskKey !== binding?.taskKey
+ || this._hasPendingSteering(tabId)
+ || !social || social.needsRecompile || !action || !binding?.publicationKey
+ || social.deniedAuditKey !== binding.publicationKey
+ || !publicationProgress(social.contract, social.outcomes).eligible.includes(action.id)
+ || social.retryBypassUsed?.[binding.publicationKey] || social.retryBypass) return false;
+ social.retryBypass = { key: binding.publicationKey, taskKey: guard.taskKey,
+ contractKey: social.key, actionId: action.id, consumed: false };
+ social.retryAuthorizationTaskKey = this._progressTaskKeyHash(tabId);
+ social.retryAuthorizationTaskSignature = this._sha256TextSync(this._progressTaskAnchorText(tabId));
+ if (liveGuard) this._storeContinuationExecutionEvidence(tabId);
+ return true;
+ }
+
+ _revokeSocialPublicationAuditRetry(tabId) {
+ let revoked = false;
+ const states = new Set([
+ this._planExecutionGuards.get(tabId)?.socialPublication,
+ this._continuationExecutionEvidence.get(tabId)?.socialPublication,
+ ]);
+ for (const social of states) {
+ if (!social?.retryBypass || social.retryBypass.consumed) continue;
+ const key = social.retryBypass.key;
+ social.retryBypass = null;
+ delete social.retryAuthorizationTaskKey;
+ delete social.retryAuthorizationTaskSignature;
+ if (social.dispatch?.auditBypassed && social.dispatch.key === key
+ && !social.outcomes?.[social.dispatch.actionId]) social.dispatch = null;
+ revoked = true;
+ }
+ return revoked;
+ }
+
+ _consumeSocialPublicationAuditRetry(tabId) {
+ const social = this._planExecutionGuards.get(tabId)?.socialPublication;
+ if (!social?.dispatch?.auditBypassed || !social.retryBypass
+ || social.retryBypass.key !== social.dispatch.key || social.retryBypass.consumed) return;
+ social.retryBypass.consumed = true;
+ (social.retryBypassUsed ||= {})[social.retryBypass.key] = true;
+ }
+
+ _continuedSocialPublicationState(social, retryTaskKey = null) {
+ if (!social) return null;
+ const next = structuredClone(social);
+ if (retryTaskKey && next.retryBypass && !next.retryBypass.consumed) {
+ next.retryBypass.taskKey = retryTaskKey;
+ }
+ // Ordinary trusted Continue can repair a technical outage on a new run.
+ // A semantic denial and an explicit one-use Retry grant keep their binding.
+ if (!next.retryBypass && !next.dispatch
+ && ['invalid_response', 'unavailable'].includes(next.deniedAudit?.status)) {
+ delete next.deniedAudit;
+ delete next.deniedAuditKey;
+ }
+ return next;
+ }
+
async _ensureSocialPublicationContract(tabId, provider = this._activeProvider(tabId)) {
const guard = this._planExecutionGuards.get(tabId);
if (!guard?.enabled) return null;
@@ -21069,14 +21342,25 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return state;
}
const messages = publicationContractMessages(sources, context);
+ let portable = false;
for (let attempt = 0; attempt < 2; attempt++) {
+ const requestMessages = attempt ? this._socialPublicationRepairMessages(messages) : messages;
+ const options = this._socialPublicationChatOptions(provider, attempt > 0, portable);
+ const runId = this.currentRunId.get(tabId);
+ const startedAt = Date.now();
+ let received = false;
try {
- const response = await this._chatWithCostAllowance(provider, messages, {
- temperature: 0, maxTokens: Math.min(4096, this._providerMaxOutputTokens(provider)),
- }, this.currentCostState.get(tabId) || null, { tabId, generationName: 'social_publication_contract' });
+ await this._tracePlannerAttemptRequest(runId, 0, provider, requestMessages,
+ 'social_publication_contract', attempt + 1, this._effectiveRunMode(tabId), options);
+ const response = await this._chatWithCostAllowance(provider, requestMessages, options,
+ this.currentCostState.get(tabId) || null, { tabId, generationName: 'social_publication_contract' });
+ received = true;
+ await this._tracePlannerAttemptResponse(runId, 0, provider, response,
+ 'social_publication_contract', attempt + 1, startedAt, options);
if (this._planExecutionGuards.get(tabId) !== guard || this._checkAbort(tabId)) return null;
if (guard.socialPublication !== state || state.needsRecompile) return this._ensureSocialPublicationContract(tabId, provider);
- state.contract = normalizePublicationContract(Agent._extractFirstJsonObject(response?.content || ''), sources);
+ if (this._hasPendingSteering(tabId)) return null;
+ state.contract = normalizePublicationContract(this._socialPublicationResponseObject(response, options), sources);
// A clarification invalidates authorization, not the uploads already
// bound to an unchanged, unattempted action. Preserve its binding only
// when all normalized action constraints match (IDs may be regenerated).
@@ -21090,8 +21374,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return state;
} catch (error) {
if (this._isCostAllowanceError(error) || this._checkAbort(tabId)) throw error;
- state.error = 'Publication intent is incomplete or ambiguous. Clarify the request before publishing.';
- if (attempt === 0) messages.push({ role: 'user', content: 'The contract failed strict validation. Return a complete valid object using only the documented schema and exact unique source anchors. If any requirement cannot be represented, return status=clarify with no actions. Do not guess.' });
+ await this._socialPublicationCheckerFailure(tabId, 'social_publication_contract', attempt + 1, error, received);
+ if (this._planExecutionGuards.get(tabId) !== guard || guard.socialPublication !== state
+ || state.needsRecompile || this._hasPendingSteering(tabId)) return null;
+ state.error = 'Failed while reading the publication request. The checker could not return a complete result; the draft was not published.';
+ state.errorKind = 'technical';
+ if (this._socialPublicationOptionsRejected(error)) portable = true;
}
}
return state;
@@ -21308,41 +21596,102 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
+ '. Resolve publicationValidation before retrying. For body_mismatch, use the exact contract body; preserve every space and line break. A pending text write must first be verified or restored.'),
publicationValidation: { issues } };
}
- const key = this._sha256TextSync(JSON.stringify({ contract: social.key, action, snapshot, pageUrl }));
- if (social.deniedAuditKey === key) return blocked('This unchanged publication did not pass authorization. Use publicationAudit to resolve the stated issue through clarify; do not rewrite a matching draft or retry another click target.');
+ const documentIdentity = detected.frameDocumentIdentity || '';
+ const frameId = Number.isInteger(detected.frameId) ? detected.frameId : 0;
+ const taskKey = guard.taskKey;
+ const key = this._sha256TextSync(JSON.stringify({ contract: social.key, action, snapshot, pageUrl, documentIdentity, frameId }));
+ const auditBlocked = () => {
+ const denied = social.deniedAudit?.status === 'denied';
+ const message = denied
+ ? 'Failed during the publication check: ' + (social.deniedAudit.reason || 'The checker could not confirm this post matches your request.') + ' Your draft was not published.'
+ : 'Failed during the publication check. The checker could not return a valid result, so your draft was not published.';
+ return { ...blocked(message), failureRecovery: {
+ stage: 'publication_audit', code: denied ? 'publication_audit_denied' : 'publication_audit_unavailable',
+ taskKey: guard.taskKey, publicationKey: key, message,
+ retryMode: 'publication_audit_bypass', retryDescription: 'Retry this unchanged draft without the publication audit.',
+ diagnostics: social.deniedAudit?.validationFailure || social.deniedAudit?.reason || '',
+ } };
+ };
+ const bypass = social.retryBypass;
+ const bypassMatches = bypass?.key === key && bypass.taskKey === guard.taskKey
+ && bypass.contractKey === social.key && bypass.actionId === action.id;
+ if (bypass && !bypassMatches) {
+ social.retryBypass = null;
+ return blocked('The draft, account, or page changed after Retry. Read the current draft and run a new publication check.');
+ }
+ if (bypassMatches && (bypass.consumed || social.retryBypassUsed?.[key])) {
+ return blocked('This publication Retry was already used. Verify the previous attempt before trying to publish again.');
+ }
+ if (social.deniedAuditKey === key && !bypassMatches) return auditBlocked();
if (social.dispatch?.key !== key) {
- try {
- const response = await this._chatWithCostAllowance(provider || this._activeProvider(tabId),
- publicationAuditMessages(social.sources, social.contract, action, snapshot, key, social.context), {
- temperature: 0, maxTokens: 800,
- }, this.currentCostState.get(tabId) || null, { tabId, generationName: 'social_publication_authorization' });
- if (this._planExecutionGuards.get(tabId) !== guard || guard.socialPublication !== social
- || social.needsRecompile || this._checkAbort(tabId)) {
- return blocked('Publication context changed during authorization.');
- }
- const audit = Agent._extractFirstJsonObject(response?.content || '');
- if (!publicationAuditAccepted(audit, key, action.id)) {
- social.deniedAuditKey = key;
- const validDenial = audit?.authorized === false && publicationAuditAccepted({ ...audit, authorized: true }, key, action.id);
- social.deniedAudit = validDenial
- ? { status: 'denied', reason: audit.reason }
- : { status: 'invalid_response', reason: 'The publication checker returned an invalid or mismatched authorization response.' };
- return blocked('The selected provider could not confirm this publication. Use publicationAudit to resolve the stated issue through clarify; do not rewrite a matching draft or retry another click target.');
+ if (!bypassMatches) {
+ const auditProvider = provider || this._activeProvider(tabId);
+ const messages = publicationAuditMessages(social.sources, social.contract, action, snapshot, key, social.context);
+ let portable = false;
+ let authorized = false;
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const requestMessages = attempt ? this._socialPublicationRepairMessages(messages) : messages;
+ const options = this._socialPublicationChatOptions(auditProvider, attempt > 0, portable, true);
+ const runId = this.currentRunId.get(tabId);
+ const startedAt = Date.now();
+ let received = false;
+ try {
+ await this._tracePlannerAttemptRequest(runId, 0, auditProvider, requestMessages,
+ 'social_publication_authorization', attempt + 1, this._effectiveRunMode(tabId), options);
+ const response = await this._chatWithCostAllowance(auditProvider, requestMessages, options,
+ this.currentCostState.get(tabId) || null, { tabId, generationName: 'social_publication_authorization' });
+ received = true;
+ await this._tracePlannerAttemptResponse(runId, 0, auditProvider, response,
+ 'social_publication_authorization', attempt + 1, startedAt, options);
+ if (this._planExecutionGuards.get(tabId) !== guard || guard.socialPublication !== social
+ || social.needsRecompile || this._checkAbort(tabId) || this._hasPendingSteering(tabId)
+ || guard.taskKey !== taskKey) {
+ return blocked('Publication context changed during authorization.');
+ }
+ const verdict = publicationAuditValidation(this._socialPublicationResponseObject(response, options), key, action.id);
+ if (!verdict.valid) throw new Error(verdict.failure);
+ if (!verdict.authorized) {
+ social.deniedAuditKey = key;
+ social.deniedAudit = { status: 'denied', reason: verdict.reason };
+ return auditBlocked();
+ }
+ authorized = true;
+ delete social.deniedAudit;
+ delete social.deniedAuditKey;
+ break;
+ } catch (error) {
+ if (this._isCostAllowanceError(error) || this._checkAbort(tabId)) throw error;
+ await this._socialPublicationCheckerFailure(tabId, 'social_publication_authorization', attempt + 1, error, received);
+ if (this._planExecutionGuards.get(tabId) !== guard || guard.socialPublication !== social
+ || social.needsRecompile || this._hasPendingSteering(tabId)
+ || guard.taskKey !== taskKey) {
+ return blocked('Publication context changed during authorization.');
+ }
+ social.deniedAuditKey = key;
+ social.deniedAudit = { status: received ? 'invalid_response' : 'unavailable',
+ reason: received ? 'The publication checker returned an invalid or mismatched authorization response.'
+ : 'The selected provider could not complete the publication check.',
+ validationFailure: String(error?.message || error).slice(0, 600) };
+ if (this._socialPublicationOptionsRejected(error)) portable = true;
+ }
}
- } catch (error) {
- if (this._isCostAllowanceError(error) || this._checkAbort(tabId)) throw error;
- return blocked('Publication authorization could not be verified with the selected provider.');
+ if (!authorized) return auditBlocked();
}
- social.dispatch = { key, actionId: action.id, snapshot: JSON.parse(JSON.stringify(snapshot)), pageUrl };
+ social.dispatch = { key, actionId: action.id, snapshot: JSON.parse(JSON.stringify(snapshot)), pageUrl,
+ documentIdentity, frameId, ...(bypassMatches ? { auditBypassed: true } : {}) };
}
// The semantic check can take time. Re-read the same target afterward;
// neither a changed draft/account nor a navigated document inherits it.
const fresh = await this._detectLikelySubmitAction(tabId, name, args);
if (this._planExecutionGuards.get(tabId) !== guard || guard.socialPublication !== social || social.needsRecompile
+ || this._checkAbort(tabId) || this._hasPendingSteering(tabId) || guard.taskKey !== taskKey
|| fresh?.isSubmit !== true || fresh.publicationControl !== true || fresh.publicationResourceUrlsComplete !== true
+ || (fresh.frameDocumentIdentity || '') !== documentIdentity
+ || (Number.isInteger(fresh.frameId) ? fresh.frameId : 0) !== frameId
|| JSON.stringify(this._socialPublicationSnapshot(guard, fresh.publicationSnapshot)) !== JSON.stringify(snapshot)
|| this._normalizeUrl(await this._currentUrl(tabId)) !== this._normalizeUrl(pageUrl)) {
social.dispatch = null;
+ if (bypassMatches) social.retryBypass = null;
return blocked('The composer or publication target changed during verification. Read the current draft before trying again.');
}
Object.assign(detected, fresh);
@@ -22381,6 +22730,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
}
if (!gate.proceed) {
+ if (gate.failureRecovery || gate.requestKind === 'failed') {
+ this._offerFailureRecovery(tabId, gate.failureRecovery || {
+ stage: 'plan_alignment', code: gate.reason || 'planning_failed',
+ message: gate.message || 'Failed during planning. No actions were started.',
+ }, onUpdate);
+ }
messages.push(this._plannerTerminalAssistantMessage(
gate, tabInfo, this._progressTaskAnchorText(tabId), this._progressTaskKeyHash(tabId),
));
@@ -22467,13 +22822,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
_plannerChatOptions(provider, retry = false, intentOnly = false, schemaKind = null, portable = false) {
- const plannerBudget = intentOnly ? 2048 : 4096;
+ const kind = schemaKind || (intentOnly ? 'intent' : 'planner');
+ const plannerBudget = kind === 'alignment' ? (retry ? 4096 : 2048) : (intentOnly ? 2048 : 4096);
const opts = {
temperature: retry ? 0.1 : 0.3,
maxTokens: Math.min(this._providerMaxOutputTokens(provider), plannerBudget),
};
if (!portable) {
- const kind = schemaKind || (intentOnly ? 'intent' : 'planner');
const schema = kind === 'alignment'
? PLANNER_ALIGNMENT_RESPONSE_JSON_SCHEMA
: kind === 'read_scope'
@@ -22489,7 +22844,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const extraBody = plannerRequestBody(plannerConfig, {
schema,
schemaName: `webbrain_${kind}`,
- includeResponseFormat: !retry,
+ includeResponseFormat: kind === 'alignment' || !retry,
disableThinking: true,
});
if (Object.keys(extraBody).length) opts.extraBody = extraBody;
@@ -22504,7 +22859,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return resolveMaxOutputTokens(config, fallback);
}
- async _tracePlannerAttemptRequest(runId, step, provider, messages, phase, attempt, runtimeMode) {
+ async _tracePlannerAttemptRequest(runId, step, provider, messages, phase, attempt, runtimeMode, chatOptions = {}) {
if (!runId) return;
try {
await trace.recordLLMRequest(runId, step, {
@@ -22515,6 +22870,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
...Agent._traceMediaCounts(messages),
phase,
attempt,
+ ...(Number.isFinite(chatOptions.maxTokens) ? { requestedMaxTokens: chatOptions.maxTokens } : {}),
+ ...(chatOptions.extraBody ? { requestControls: Object.keys(chatOptions.extraBody) } : {}),
...(attempt > 1 ? { repair: true } : {}),
}, {
messages,
@@ -22524,7 +22881,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
} catch {}
}
- async _tracePlannerAttemptResponse(runId, step, provider, result, phase, attempt, startedAt) {
+ async _tracePlannerAttemptResponse(runId, step, provider, result, phase, attempt, startedAt, chatOptions = {}) {
if (!runId) return;
try {
await trace.recordLLMResponse(runId, step, {
@@ -22535,12 +22892,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
model: provider?.model,
phase,
attempt,
+ ...modelOutputDiagnostics(result, { requestedMaxTokens: chatOptions.maxTokens, recoveryAttempt: attempt - 1 }),
...(attempt > 1 ? { repair: true } : {}),
});
} catch {}
}
- async _tracePlannerAttemptFailure(runId, phase, attempt, error) {
+ async _tracePlannerAttemptFailure(runId, phase, attempt, error, code = 'planner_request_failed') {
if (!runId) return;
try {
const detail = sanitizePlannerText(
@@ -22552,7 +22910,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
phase,
attempt,
failureKind: plannerRequestFailureKind(detail),
+ detail,
+ code,
});
+ await trace.recordError(runId, 0, phase, detail, code);
} catch {}
}
@@ -23637,12 +23998,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
let alignmentReplanned = false;
if (historyDigest || followUpContext.priorUserTask || followUpContext.scratchpadFacts) {
let aligned = false;
+ let alignmentFailure = null;
+ let alignmentDenialReason = '';
+ let alignmentRequestAttempt = 0;
try {
- for (let alignmentAttempt = 1; alignmentAttempt <= 2; alignmentAttempt += 1) {
+ for (let candidateAttempt = 1; candidateAttempt <= 2; candidateAttempt += 1) {
if (this._checkAbort(tabId)) return { proceed: false, message: '[Stopped by user]' };
if (this._hasPendingSteering(tabId) || this._steeringGateSuperseded(tabId, runOptions)) {
return { proceed: false, steeringSuperseded: true };
}
+ // Freeze this candidate and its authority for format recovery. A
+ // checker protocol error never requests a different execution plan.
const taskBinding = `plan_alignment_${secureRandomBase36Token(24)}`;
const alignmentMessages = buildPlannerAlignmentMessages(followUpContext.authenticTaskText || this._plannerUserAuthoredText(enriched), plan, {
taskBinding, historyDigest,
@@ -23650,42 +24016,97 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
scratchpadFacts: followUpContext.scratchpadFacts,
independentTask: runOptions?.independentRun === true,
});
- await this._tracePlannerAttemptRequest(
- runId, plannerStep, provider, alignmentMessages, 'planner_alignment', alignmentAttempt, runtimeMode,
- );
- const alignmentStartedAt = Date.now();
- plannerRequestInFlight = true;
- const alignmentResult = await this._chatWithCostAllowance(
- provider, alignmentMessages,
- { ...this._plannerChatOptions(provider, false, false, 'alignment'), temperature: 0,
- maxTokens: Math.min(this._providerMaxOutputTokens(provider), 256) },
- costState, { tabId, generationName: 'planner_alignment' },
- );
- plannerRequestInFlight = false;
- await this._tracePlannerAttemptResponse(
- runId, plannerStep, provider, alignmentResult, 'planner_alignment', alignmentAttempt, alignmentStartedAt,
- );
- if (this._checkAbort(tabId)) return { proceed: false, message: '[Stopped by user]' };
- if (this._hasPendingSteering(tabId) || this._steeringGateSuperseded(tabId, runOptions)) {
- return { proceed: false, steeringSuperseded: true };
+ let verdict = null;
+ let portable = false;
+ for (let checkerAttempt = 1; checkerAttempt <= 2; checkerAttempt += 1) {
+ if (this._checkAbort(tabId)) return { proceed: false, message: '[Stopped by user]' };
+ if (this._hasPendingSteering(tabId) || this._steeringGateSuperseded(tabId, runOptions)) {
+ return { proceed: false, steeringSuperseded: true };
+ }
+ const requestMessages = checkerAttempt === 1 ? alignmentMessages
+ : this._plannerProtocolRepairMessages(alignmentMessages,
+ 'Format recovery: the previous checker response did not contain a complete valid verdict. ' +
+ 'Check the unchanged current_request and proposed_plan below. Copy task_binding exactly. ' +
+ 'Return only one JSON object with task_binding, boolean aligned, and a brief nonempty reason. ' +
+ 'Do not output prose, tool calls, or reasoning text.');
+ const chatOptions = { ...this._plannerChatOptions(provider, checkerAttempt > 1, false, 'alignment', portable),
+ temperature: 0 };
+ alignmentRequestAttempt += 1;
+ await this._tracePlannerAttemptRequest(
+ runId, plannerStep, provider, requestMessages, 'planner_alignment', alignmentRequestAttempt, runtimeMode, chatOptions,
+ );
+ const alignmentStartedAt = Date.now();
+ let alignmentResult;
+ try {
+ plannerRequestInFlight = true;
+ alignmentResult = await this._chatWithCostAllowance(
+ provider, requestMessages, chatOptions,
+ costState, { tabId, generationName: 'planner_alignment' },
+ );
+ } catch (error) {
+ if (this._isCostAllowanceError(error)) throw error;
+ if (this._checkAbort(tabId)) return { proceed: false, message: '[Stopped by user]' };
+ if (this._hasPendingSteering(tabId) || this._steeringGateSuperseded(tabId, runOptions)) {
+ return { proceed: false, steeringSuperseded: true };
+ }
+ await this._tracePlannerAttemptFailure(runId, 'planner_alignment', alignmentRequestAttempt, error);
+ alignmentFailure = 'request_failed';
+ const detail = formatErrorMessage(error, { fallback: '' });
+ const controlsRejected = chatOptions.extraBody && Object.keys(chatOptions.extraBody).length > 0
+ && /unsupported|not supported|unrecognized|unknown|not allowed|invalid (?:parameter|argument)/i.test(detail)
+ && /response_format|json_schema|reasoning|thinking|chat_template_kwargs/i.test(detail);
+ if (checkerAttempt === 1 && controlsRejected) {
+ portable = true;
+ continue;
+ }
+ break;
+ } finally {
+ plannerRequestInFlight = false;
+ }
+ await this._tracePlannerAttemptResponse(
+ runId, plannerStep, provider, alignmentResult, 'planner_alignment', alignmentRequestAttempt, alignmentStartedAt, chatOptions,
+ );
+ if (this._checkAbort(tabId)) return { proceed: false, message: '[Stopped by user]' };
+ if (this._hasPendingSteering(tabId) || this._steeringGateSuperseded(tabId, runOptions)) {
+ return { proceed: false, steeringSuperseded: true };
+ }
+ const inspection = inspectPlannerAlignmentContent(alignmentResult.content, taskBinding);
+ const diagnostics = modelOutputDiagnostics(alignmentResult, { requestedMaxTokens: chatOptions.maxTokens });
+ const truncated = /^(?:length|max_tokens|max_output_tokens|output_limit)$/i.test(diagnostics.finishReason || '');
+ verdict = truncated ? null : inspection.verdict;
+ alignmentFailure = verdict ? null : (diagnostics.emptyReason || (truncated ? 'truncated_response' : inspection.failure));
+ if (verdict) break;
+ try {
+ if (runId) await trace.recordNote(runId, plannerStep, 'planner_alignment_validation_failed', {
+ attempt: alignmentRequestAttempt, candidateAttempt, validationFailure: alignmentFailure,
+ });
+ } catch {}
+ await this._tracePlannerAttemptFailure(runId, 'planner_alignment', alignmentRequestAttempt,
+ new Error(`Plan alignment checker returned an invalid verdict (${alignmentFailure}).`),
+ 'planner_alignment_invalid_response');
+ if (checkerAttempt === 1) {
+ onUpdate('thinking', { step: plannerStep, note: 'Planning… retrying the plan check' });
+ }
}
- const verdict = parsePlannerAlignmentFromContent(alignmentResult.content, taskBinding);
+ if (!verdict) break;
if (verdict?.aligned === true) { aligned = true; break; }
- if (alignmentAttempt === 2) break;
+ alignmentDenialReason = verdict.reason;
+ if (candidateAttempt === 2) break;
const alignmentRepairMessages = buildPlannerAlignmentRepairMessages(plannerMessages);
onUpdate('thinking', { step: plannerStep, note: 'Planning… rechecking the current task' });
+ const repairOptions = this._plannerChatOptions(provider, true);
await this._tracePlannerAttemptRequest(
- runId, plannerStep, provider, alignmentRepairMessages, 'planner_alignment_repair', 1, runtimeMode,
+ runId, plannerStep, provider, alignmentRepairMessages, 'planner_alignment_repair', 1, runtimeMode, repairOptions,
);
const alignmentRepairStartedAt = Date.now();
plannerRequestInFlight = true;
const repaired = await this._chatWithCostAllowance(
- provider, alignmentRepairMessages, this._plannerChatOptions(provider, true),
+ provider, alignmentRepairMessages, repairOptions,
costState, { tabId, generationName: 'planner' },
);
plannerRequestInFlight = false;
await this._tracePlannerAttemptResponse(
- runId, plannerStep, provider, repaired, 'planner_alignment_repair', 1, alignmentRepairStartedAt,
+ runId, plannerStep, provider, repaired, 'planner_alignment_repair', 1, alignmentRepairStartedAt, repairOptions,
);
if (this._checkAbort(tabId)) return { proceed: false, message: '[Stopped by user]' };
if (this._hasPendingSteering(tabId) || this._steeringGateSuperseded(tabId, runOptions)) {
@@ -23693,7 +24114,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
plan = parsePlanFromContent(repaired.content, plannerParseOptions);
if (!plan
- || this._plannerIntentUnresolvedConsistencyIssue(plan, consistencyRepairKind, followUpContext)) break;
+ || this._plannerIntentUnresolvedConsistencyIssue(plan, consistencyRepairKind, followUpContext)) {
+ alignmentFailure = 'invalid_replacement_plan';
+ break;
+ }
alignmentReplanned = true;
// A validated correction can remove execution entirely. Preserve
// its normal terminal route without pinning or approving a plan.
@@ -23704,15 +24128,31 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
plannerRequestInFlight = false;
if (this._isCostAllowanceError(alignmentError)) throw alignmentError;
if (this._checkAbort(tabId)) return { proceed: false, message: '[Stopped by user]' };
- await this._tracePlannerAttemptFailure(runId, 'planner_alignment', 1, alignmentError);
+ alignmentFailure = 'request_failed';
+ await this._tracePlannerAttemptFailure(runId, 'planner_alignment', alignmentRequestAttempt || 1, alignmentError);
}
if (!aligned) {
if (this._hasPendingSteering(tabId) || this._steeringGateSuperseded(tabId, runOptions)) {
return { proceed: false, steeringSuperseded: true };
}
- const message = 'The proposed plan failed alignment with your current task. No actions were started; please retry the task.';
+ const failureDescription = alignmentFailure === 'reasoning_only'
+ ? 'the checker returned reasoning without a verdict.'
+ : (alignmentFailure === 'provider_empty' || alignmentFailure === 'empty_response')
+ ? 'the checker returned no verdict.'
+ : (alignmentFailure === 'output_limit' || alignmentFailure === 'truncated_response')
+ ? 'the checker ran out of response space before returning a verdict.'
+ : alignmentFailure === 'binding_mismatch'
+ ? 'the checker returned a verdict for a different plan.'
+ : alignmentFailure === 'request_failed'
+ ? 'the checker could not complete its request to the model provider.'
+ : 'the checker returned an unreadable verdict.';
+ const reason = alignmentFailure ? 'task_alignment_unverified' : 'task_alignment_rejected';
+ const message = alignmentFailure
+ ? `Failed while checking the plan against your task: ${failureDescription} No actions were started.`
+ : `Failed while checking the plan against your task: the proposed plan did not match your request. ${alignmentDenialReason} No actions were started.`;
onUpdate('warning', { message });
- return { proceed: false, message, reason: 'task_alignment_unverified', requestKind: 'failed' };
+ return { proceed: false, message, reason, requestKind: 'failed',
+ failureRecovery: { stage: 'plan_alignment', code: reason, message } };
}
}
if (alignmentReplanned) {
@@ -24348,6 +24788,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
let finalResponse = '';
let status = 'done';
let quotaFailure = false;
+ let recoveryDetails = null;
try {
finalResponse = await this._generateContextOnlyResponse(
tabId, messages, provider, costState, runId,
@@ -24361,7 +24802,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
status = this._isCostAllowanceError(error) ? 'cost_limit' : 'error';
finalResponse = this._isCostAllowanceError(error)
? error.message
- : `I could not generate the requested response: ${formatErrorMessage(error)}`;
+ : (recoveryDetails = modelFailureRecovery(error, { phase: 'response_generation' })).message;
}
const stopped = this._consumeContextOnlyAbort(tabId, messages, onUpdate);
if (stopped) return stopped;
@@ -24370,8 +24811,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
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.';
+ finalResponse = 'Failed while generating the response. The model returned no usable text. You can retry from the current state.';
+ recoveryDetails = { stage: 'response_generation', code: 'empty_response', message: finalResponse };
}
+ if (recoveryDetails && !quotaFailure) this._offerFailureRecovery(tabId, recoveryDetails, onUpdate);
messages.push({ role: 'assistant', content: finalResponse });
onUpdate('text', { content: finalResponse, replace: true });
if (status !== 'done' && !quotaFailure) onUpdate('error', { message: finalResponse });
@@ -24422,6 +24865,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
: stopMessage;
messages.push({ role: 'assistant', content: finalResponse });
onUpdate('text', { content: finalResponse, replace: true });
+ if (runOptions?.cloudRun !== true) this._offerFailureRecovery(tabId, {
+ stage: 'browser_interaction', code: 'interaction_loop',
+ message: 'Failed during browser interaction because the same step kept repeating. Retry will continue from the current page.' }, onUpdate);
onUpdate('error', {
message: recovered
? 'Browser interaction stopped before completion; a recoverable partial result is shown above.'
@@ -26906,6 +27352,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
tool: name,
reason: String(detected.reason || 'likely form submission').slice(0, 200),
validationSubmitEvidence: detected.validationSubmitEvidence === 'strong' ? 'strong' : 'heuristic',
+ frameDocumentIdentity: String(detected.frameDocumentIdentity || '').slice(0, 8192),
...(name === 'iframe_click' ? { frameId: detected.frameId,
frameUrl: String(detected.url || '').slice(0, 8192),
frameDocumentIdentity: sameFrameDocument ? frameBaseline.identity : '',
@@ -30349,6 +30796,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
}
clearConversation(tabId) {
+ this._failureRecovery.clear(tabId);
this._cancelClarifications(tabId, 'conversation cleared');
this._cancelPendingPlans(tabId, 'conversation cleared');
this.conversations.delete(tabId);
@@ -32885,7 +33333,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
? this._continuationExecutionEvidence.get(tabId)
: null;
this._continuationExecutionEvidence.delete(tabId);
- const carryScopeMatches = enabled
+ const carryScopeCompatible = enabled
&& carried?.requestKind === 'execute'
&& carried.requiresStateChange === requiresStateChange
&& carried.requiresSubmission === requiresSubmission
@@ -32897,8 +33345,14 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
&& carried.requiredSchedulingTool === requiredSchedulingTool
&& JSON.stringify(carried.siteWorkflow || null) === JSON.stringify(siteWorkflow || null)
&& JSON.stringify(carried.conditionalSiteWorkflow || null) === JSON.stringify(gateOutcome.conditionalSiteWorkflow || null)
- && carried.taskKey === taskKey
&& carried.conversationId === (this.conversationIds.get(tabId) || null);
+ const carryScopeMatches = carryScopeCompatible && carried.taskKey === taskKey;
+ const carrySocialRetryAuthorization = carryScopeCompatible
+ && requiresSubmission === true && requiresStateChange === true
+ && carried.socialPublication?.retryAuthorizationTaskKey === taskKey
+ && carried.socialPublication.retryAuthorizationTaskSignature === this._sha256TextSync(this._progressTaskAnchorText(tabId))
+ && carried.socialPublication.retryBypass?.consumed === false
+ && !Object.keys(carried.socialPublication.outcomes || {}).length;
const carryMatches = carryScopeMatches && carried.evidenceTaskKey === taskKey;
// Human recipient grants are task authorization, not execution evidence.
// They can survive Continue even when the last step only approved a send.
@@ -32957,10 +33411,13 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
? (carried.successfulRequiredSchedulingToolCalls || 0)
: 0,
verifiedSubmissionEvidence: carryMatches && carried.verifiedSubmissionEvidence === true,
- socialPublication: carryMatches && carried.socialPublication ? structuredClone(carried.socialPublication) : null,
- socialPublicationClarifications: carryMatches && carried.socialPublicationClarifications
+ // Frozen publication intent and human Retry grants are authorization,
+ // independent of whether this run produced successful execution evidence.
+ socialPublication: carryScopeMatches || carrySocialRetryAuthorization
+ ? this._continuedSocialPublicationState(carried.socialPublication, carrySocialRetryAuthorization ? taskKey : null) : null,
+ socialPublicationClarifications: (carryScopeMatches || carrySocialRetryAuthorization) && carried.socialPublicationClarifications
? structuredClone(carried.socialPublicationClarifications) : [],
- socialPublicationSteering: carryMatches && carried.socialPublicationSteering
+ socialPublicationSteering: (carryScopeMatches || carrySocialRetryAuthorization) && carried.socialPublicationSteering
? structuredClone(carried.socialPublicationSteering) : null,
socialPublishSatisfiedTargets: carryMatches && Array.isArray(carried.socialPublishSatisfiedTargets)
? [...carried.socialPublishSatisfiedTargets]
@@ -33406,6 +33863,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
&& (guard.messageRecipientApprovedAll === true || (guard.approvedRecipients || []).length > 0);
if (guard?.enabled && !guard.taskDrifted && (
hasRecipientAuthorization
+ || guard.socialPublication?.contract?.status === 'ready'
|| guard.successfulTaskToolCalls > 0
|| guard.successfulConsequentialToolCalls > 0
|| guard.pendingDownloadIds.length > 0
@@ -46568,9 +47026,15 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
...this._interactiveAskStreamingFailure(error),
});
if (this._isCostAllowanceError(error)) throw error;
- if (emittedText) onUpdate('text', { content: '', replace: true });
- if (!fallbackSafe) throw error;
+ if (!fallbackSafe) {
+ if (emittedText) onUpdate('text', { content: '', replace: true });
+ throw error;
+ }
askStreamingDisabledForRun = true;
+ // A transport interruption does not invalidate already delivered
+ // prose. Keep it visibly incomplete while regenerating this same
+ // source-grounded turn; explicit invalid-response resets still clear.
+ onUpdate('response_retry', { reason: 'stream_interrupted', retainPartial: emittedText });
onUpdate('warning', {
code: 'ask_stream_fallback',
message: 'Response streaming was interrupted; retrying this Ask turn without streaming.',
@@ -46885,8 +47349,11 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
traceFailureCode = retryCode;
_traceStatus = 'error';
if (runId) trace.recordStepEnd(runId, steps, { ok: false, code: retryCode });
- onUpdate('error', { message: `Context still too large after trimming: ${e2.message}` });
finalResponse = 'The conversation got too long. Please start a new conversation (click the + button).';
+ this._offerFailureRecovery(tabId, { stage: 'model', code: 'context_window_exceeded',
+ message: 'Failed while preparing the model context. The conversation is too large. Retry will use the current trimmed context.',
+ diagnostics: e2.message }, onUpdate);
+ onUpdate('error', { message: finalResponse });
messages.push({ role: 'assistant', content: finalResponse });
break;
}
@@ -46909,8 +47376,9 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
traceFailureCode = this._traceErrorCodeFor(e);
_traceStatus = 'error';
if (runId) trace.recordStepEnd(runId, steps, { ok: false, code: traceFailureCode });
- onUpdate('error', { message: e.message });
- finalResponse = `Error communicating with LLM: ${e.message}`;
+ const recovery = await this._finalModelFailure(tabId, messages, onUpdate, provider, e, steps, runOptions);
+ _traceStatus = recovery.status;
+ finalResponse = recovery.content;
messages.push({ role: 'assistant', content: finalResponse });
break;
}
@@ -46949,8 +47417,9 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
traceFailureCode = this._traceErrorCodeFor(e2);
_traceStatus = 'error';
if (runId) trace.recordStepEnd(runId, steps, { ok: false, code: traceFailureCode });
- onUpdate('error', { message: e2.message });
- finalResponse = `Error communicating with LLM: ${e2.message}`;
+ const recovery = await this._finalModelFailure(tabId, messages, onUpdate, provider, e2, steps, runOptions);
+ _traceStatus = recovery.status;
+ finalResponse = recovery.content;
messages.push({ role: 'assistant', content: finalResponse });
break;
}
@@ -47234,6 +47703,9 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
}));
_traceStatus = 'empty_output';
traceFailureCode = 'EMPTY_RESPONSE';
+ 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);
messages.push({ role: 'assistant', content: finalResponse });
onUpdate('warning', { message: finalResponse });
break;
@@ -48110,7 +48582,24 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
let costStopMessage = '';
this._throwIfAborted(streamOpts.signal);
- for await (const chunk of (fastResult ? this._jevToolStream(fastResult) : provider.chatStream(prunedMessages, streamOpts))) {
+ let streamAttempt = 0;
+ const modelStream = fastResult ? this._jevToolStream(fastResult) : retryModelStream(async () => {
+ streamAttempt++;
+ if (streamAttempt > 1 && runId) await trace.recordLLMRequest(runId, steps, {
+ providerClass: provider.constructor.name, model: provider.model,
+ messageCount: prunedMessages.length, toolsCount: (streamOpts.tools || []).length,
+ requestedMaxTokens: streamOpts.maxTokens, recoveryAttempt: streamAttempt - 1,
+ ...Agent._traceMediaCounts(prunedMessages),
+ }, { messages: prunedMessages, tools: streamOpts.tools || [], runtimeMode: mode });
+ return provider.chatStream(prunedMessages, streamOpts);
+ }, {
+ isAborted: () => this._checkAbort(tabId),
+ onRetry: async ({ error, delayMs, attempt }) => {
+ onUpdate('thinking', { step: steps, note: `The model service could not start the response. Retrying (${attempt})…` });
+ if (runId) await trace.recordLLMRetry(runId, steps, { delayMs, code: this._traceErrorCodeFor(error) });
+ },
+ });
+ for await (const chunk of modelStream) {
this._throwIfAborted(streamOpts.signal);
if (chunk.type === 'text') {
streamEmittedOutput = true;
@@ -48403,6 +48892,9 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
return finish(scheduledResume.message, 'scheduled_resume');
}
const failMsg = emptyOutputFailureMessage(outputDiagnostics);
+ 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);
messages.push({ role: 'assistant', content: failMsg });
onUpdate('warning', { message: failMsg });
this._persist(tabId);
@@ -48670,12 +49162,12 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
if (runId) await trace.recordLLMRetry(runId, steps, { delayMs: 0, code: 'CONTEXT_WINDOW_EXCEEDED' });
continue; // retry the loop with trimmed context
}
- onUpdate('error', { message: caughtMessage });
- const errMsg = `Error: ${caughtMessage}`;
+ const recovery = await this._finalModelFailure(tabId, messages, onUpdate, provider, e, steps, runOptions);
+ const errMsg = recovery.content;
messages.push({ role: 'assistant', content: errMsg });
this._persist(tabId);
traceFailureCode = stepErrorCode;
- return finish(errMsg, 'error');
+ return finish(errMsg, recovery.status);
}
}
diff --git a/src/chrome/src/agent/failure-recovery.js b/src/chrome/src/agent/failure-recovery.js
new file mode 100644
index 000000000..820a6f479
--- /dev/null
+++ b/src/chrome/src/agent/failure-recovery.js
@@ -0,0 +1,34 @@
+// Recovery choices come from the extension UI, never from a model tool call.
+export class FailureRecoveryRegistry {
+ constructor() { this.offers = new Map(); }
+
+ offer(binding, descriptor) {
+ const offer = { binding: { ...binding }, descriptor: { ...descriptor } };
+ this.offers.set(binding.tabId, offer);
+ return { ...offer.descriptor };
+ }
+
+ current(binding) {
+ const offer = this.offers.get(binding.tabId);
+ if (!offer) return null;
+ if (offer.binding.conversationId !== binding.conversationId || offer.binding.taskKey !== binding.taskKey
+ || offer.binding.taskSignature !== binding.taskSignature) {
+ this.offers.delete(binding.tabId);
+ return null;
+ }
+ return offer;
+ }
+
+ clear(tabId) { this.offers.delete(tabId); }
+}
+
+export function modelFailureRecovery(error, { postAction = false, phase = 'model' } = {}) {
+ const code = String(error?.code || 'model_request_failed');
+ const stage = postAction ? 'completion_verification' : phase;
+ const message = postAction
+ ? 'Failed during final verification. The action may have completed. Review the current result before choosing Retry.'
+ : code === 'webbrain_cloud_upstream_error'
+ ? 'Failed while contacting WebBrain Cloud. The model service could not finish this request. You can retry from the current state.'
+ : 'Failed while requesting the model response. You can retry from the current state.';
+ return { stage, code, message, retryMode: 'resume', diagnostics: String(error?.message || error || '').slice(0,6000) };
+}
diff --git a/src/chrome/src/agent/planner.js b/src/chrome/src/agent/planner.js
index 71c5db249..e21a2a099 100644
--- a/src/chrome/src/agent/planner.js
+++ b/src/chrome/src/agent/planner.js
@@ -890,18 +890,27 @@ export function buildPlannerAlignmentMessages(authenticTaskText, plan, opts = {}
}
export function parsePlannerAlignmentFromContent(content, expectedTaskBinding) {
+ return inspectPlannerAlignmentContent(content, expectedTaskBinding).verdict;
+}
+
+export function inspectPlannerAlignmentContent(content, expectedTaskBinding) {
+ if (typeof content !== 'string' || !content.trim()) return { verdict: null, failure: 'empty_response' };
const verdict = extractFirstJsonObject(content);
- if (!verdict || typeof verdict !== 'object' || Array.isArray(verdict)
- || typeof expectedTaskBinding !== 'string' || !expectedTaskBinding
- || verdict.task_binding !== expectedTaskBinding
- || typeof verdict.aligned !== 'boolean'
- || typeof verdict.reason !== 'string' || !verdict.reason.trim()
- || Object.keys(verdict).some(key => !['task_binding', 'aligned', 'reason'].includes(key))) return null;
- return {
+ if (!verdict || typeof verdict !== 'object' || Array.isArray(verdict)) {
+ return { verdict: null, failure: 'invalid_json' };
+ }
+ if (typeof expectedTaskBinding !== 'string' || !expectedTaskBinding
+ || verdict.task_binding !== expectedTaskBinding) return { verdict: null, failure: 'binding_mismatch' };
+ if (typeof verdict.aligned !== 'boolean') return { verdict: null, failure: 'invalid_aligned' };
+ if (typeof verdict.reason !== 'string' || !verdict.reason.trim()) return { verdict: null, failure: 'invalid_reason' };
+ if (Object.keys(verdict).some(key => !['task_binding', 'aligned', 'reason'].includes(key))) {
+ return { verdict: null, failure: 'unexpected_fields' };
+ }
+ return { verdict: {
task_binding: verdict.task_binding,
aligned: verdict.aligned,
reason: sanitizeText(verdict.reason, 500),
- };
+ }, failure: null };
}
export function buildPlannerAlignmentRepairMessages(messages) {
diff --git a/src/chrome/src/agent/social-publish-contract.js b/src/chrome/src/agent/social-publish-contract.js
index c20aacbf0..77ff4e665 100644
--- a/src/chrome/src/agent/social-publish-contract.js
+++ b/src/chrome/src/agent/social-publish-contract.js
@@ -258,7 +258,45 @@ export function publicationAuditMessages(sources, contract, action, snapshot, ke
{ role: 'user', content: JSON.stringify({ sources, contract, action, snapshot, key, context }) }];
}
+// Parse the complete response, rather than taking the first object out of
+// prose. A second/conflicting verdict must never be silently discarded.
+export function parsePublicationJson(content) {
+ if (typeof content !== 'string' || !content.trim()) throw new Error('empty_response');
+ const text = content.trim().replace(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/i, '$1').trim();
+ let raw;
+ try { raw = JSON.parse(text); } catch { throw new Error('malformed_or_multiple_json_objects'); }
+ if (!object(raw)) throw new Error('response_not_object');
+ const tokens = text.match(/"(?:\\.|[^"\\])*"|[{}\[\]:,]/g) || [];
+ const fields = new Set();
+ let depth = 0;
+ for (let i = 0; i < tokens.length; i++) {
+ const token = tokens[i];
+ if (token === '{' || token === '[') depth++;
+ else if (token === '}' || token === ']') depth--;
+ else if (depth === 1 && token.startsWith('"') && tokens[i + 1] === ':') {
+ const field = JSON.parse(token);
+ if (fields.has(field)) throw new Error(['key', 'actionId', 'authorized', 'reason'].includes(field)
+ ? 'duplicate_' + field : 'duplicate_extra_field');
+ fields.add(field);
+ }
+ }
+ return raw;
+}
+
+export function publicationAuditValidation(raw, key, actionId) {
+ if (!object(raw)) return { valid: false, failure: 'response_not_object' };
+ for (const field of ['key', 'actionId', 'authorized', 'reason']) {
+ if (!Object.hasOwn(raw, field)) return { valid: false, failure: 'missing_' + field };
+ }
+ if (raw.key !== key) return { valid: false, failure: 'key_mismatch' };
+ if (raw.actionId !== actionId) return { valid: false, failure: 'action_mismatch' };
+ if (typeof raw.authorized !== 'boolean') return { valid: false, failure: 'authorized_not_boolean' };
+ if (typeof raw.reason !== 'string') return { valid: false, failure: 'reason_not_string' };
+ // Extra metadata and long explanations do not invalidate a bound verdict.
+ return { valid: true, authorized: raw.authorized, reason: raw.reason.slice(0, 600) };
+}
+
export function publicationAuditAccepted(raw, key, actionId) {
- return object(raw) && Object.keys(raw).length === 4 && raw.key === key && raw.actionId === actionId
- && raw.authorized === true && typeof raw.reason === 'string' && raw.reason.length <= 600;
+ const verdict = publicationAuditValidation(raw, key, actionId);
+ return verdict.valid && verdict.authorized;
}
diff --git a/src/chrome/src/background.js b/src/chrome/src/background.js
index 68c319ea9..28c4fab27 100644
--- a/src/chrome/src/background.js
+++ b/src/chrome/src/background.js
@@ -1981,11 +1981,17 @@ function isPersistenceDegradedRunUpdate(update) {
&& update?.data?.status === 'persistence_degraded';
}
+function isPublicationAuditFailureUpdate(update) {
+ return (update?.type === 'run_status' && update?.data?.status === 'publication_audit_failed')
+ || (update?.type === 'failure_recovery' && update?.data?.stage === 'publication_audit');
+}
+
function runUpdatesSucceeded(updates = []) {
return !updates.some(update => (
update?.type === 'error' || update?.type === 'quota'
|| isClarificationRequiredRunUpdate(update)
|| isPersistenceDegradedRunUpdate(update)
+ || isPublicationAuditFailureUpdate(update)
|| isPlannerRequestFailureUpdate(update)
));
}
@@ -1998,6 +2004,7 @@ function terminalRunUiStatus(content, updates = [], error = null) {
if (/before executing requested tool calls/i.test(text)) return 'cancelled';
if (updates.some(update => update?.type === 'error'
|| isPlannerRequestFailureUpdate(update) || isPersistenceDegradedRunUpdate(update)
+ || isPublicationAuditFailureUpdate(update)
|| update?.type === 'quota')) return 'failed';
if (updates.some(isClarificationRequiredRunUpdate)) return 'clarification_required';
return 'completed';
@@ -2020,6 +2027,7 @@ function askCompletionSucceededForBadge(result, updates = [], error = null) {
if (updates.some(update => (
update?.type === 'error' || update?.type === 'quota'
|| isPersistenceDegradedRunUpdate(update)
+ || isPublicationAuditFailureUpdate(update)
|| update?.type === 'attachment_rejected'
|| update?.type === 'max_steps_reached'
|| update?.error
@@ -2929,7 +2937,35 @@ function assertChatRequestInput(msg) {
throw error;
}
+async function handleFailureRecoveryResponse(msg, sender) {
+ if (sender?.url?.split(/[?#]/)[0] !== chrome.runtime.getURL('src/ui/sidepanel.html')) {
+ return { ok: false, error: 'Recovery choices are available from the chat panel only.' };
+ }
+ const tabId = Number(msg.tabId);
+ const recoveryId = typeof msg.recoveryId === 'string' ? msg.recoveryId : '';
+ const choice = msg.choice;
+ if (!Number.isSafeInteger(tabId) || tabId <= 0 || !recoveryId || !['retry', 'give_up'].includes(choice)) {
+ return { ok: false, error: 'Invalid recovery choice.' };
+ }
+ if (choice === 'retry' && typeof msg.requestId === 'string' && msg.requestId) {
+ // An acknowledgement may be lost while its run already started. Repeated
+ // delivery follows that same request rather than consuming a second offer.
+ if (detachedRunStarts.get(tabId)?.requestId === msg.requestId) {
+ return { ok: true, accepted: true, requestId: msg.requestId };
+ }
+ const snapshot = await getRunUiSnapshot(tabId);
+ if (snapshot?.requestId === msg.requestId && snapshot.kind === 'continue') {
+ return { ok: true, accepted: true, requestId: msg.requestId };
+ }
+ }
+ assertNoActiveTabRun(tabId);
+ const result = agent.requestFailureRecovery(tabId, recoveryId, choice);
+ if (!result?.ok || choice === 'give_up' || result.continue !== true) return result;
+ return launchDetachedRun('continue', msg, sender);
+}
+
async function handleMessage(msg, sender) {
+ if (msg.action === 'failure_recovery_response') return handleFailureRecoveryResponse(msg, sender);
if (['chat_start', 'chat', 'chat_stream'].includes(msg.action)) assertChatRequestInput(msg);
if (msg.action === 'get_page_monitor_state') return agent.pageMonitorState(sender, msg.documentToken, msg.frameName);
if (msg.action === 'page_feedback') return agent.observePageFeedback(sender, msg.feedback);
@@ -3821,6 +3857,7 @@ async function handleMessage(msg, sender) {
: false);
const conversationState = await agent.getConversationState(tabId);
const activeState = agent.activeRunState(tabId);
+ const pendingFailureRecovery = agent._pendingFailureRecoveryForUi?.(tabId) || null;
const pendingClarification = activeState.pendingCurrentClarification;
const currentRunUi = runUiJournal.get(tabId);
if (pendingClarification && (!activeState.running || currentRunUi !== runUiSnapshot
@@ -3836,6 +3873,7 @@ async function handleMessage(msg, sender) {
ok: true,
...conversationState,
...activeState,
+ pendingFailureRecovery,
starting: !!starting,
startingRequestId: starting?.requestId || null,
submittedTurnDurable,
diff --git a/src/chrome/src/providers/model-retry.js b/src/chrome/src/providers/model-retry.js
index fbfc68053..1e13cd515 100644
--- a/src/chrome/src/providers/model-retry.js
+++ b/src/chrome/src/providers/model-retry.js
@@ -23,7 +23,8 @@ export async function retryModelCall(initialError, call, {
},
} = {}) {
const rateLimited = initialError?.httpStatus === 429;
- const delays = rateLimited ? [5000, 15000, 30000] : [2000];
+ const cloudUpstream = initialError?.code === 'webbrain_cloud_upstream_error';
+ const delays = rateLimited ? [5000, 15000, 30000] : cloudUpstream ? [2000, 5000] : [2000];
let error = initialError, waited = 0;
for (let i = 0; i < delays.length; i++) {
cancelled(isAborted);
@@ -38,8 +39,52 @@ export async function retryModelCall(initialError, call, {
try { return await call(); }
catch (next) {
error = next;
- if (!rateLimited || error?.httpStatus !== 429) throw error;
+ if (rateLimited ? error?.httpStatus !== 429
+ : !cloudUpstream || error?.code !== 'webbrain_cloud_upstream_error') throw error;
}
}
throw error;
}
+
+/** Retry stream startup only; emitted text/tool events must never be replayed. */
+export async function* retryModelStream(createStream, options = {}) {
+ const isAborted = options.isAborted || (() => false);
+ let iterator = null;
+ const close = async () => {
+ const abandoned = iterator;
+ iterator = null;
+ try { await abandoned?.return?.(); } catch {}
+ };
+ const start = async () => {
+ try {
+ cancelled(isAborted);
+ const stream = await createStream();
+ iterator = stream[Symbol.asyncIterator]();
+ const first = await iterator.next();
+ cancelled(isAborted);
+ return first;
+ } catch (error) {
+ await close();
+ throw error;
+ }
+ };
+ try {
+ let first;
+ try { first = await start(); }
+ catch (error) {
+ if (error?.code !== 'webbrain_cloud_upstream_error' && error?.httpStatus !== 429) throw error;
+ first = await retryModelCall(error, start, options);
+ }
+ if (first.done) return;
+ yield first.value;
+ while (true) {
+ cancelled(isAborted);
+ const next = await iterator.next();
+ cancelled(isAborted);
+ if (next.done) return;
+ yield next.value;
+ }
+ } finally {
+ await close();
+ }
+}
diff --git a/src/chrome/src/run-ui-journal.js b/src/chrome/src/run-ui-journal.js
index a9152b801..0fbb47708 100644
--- a/src/chrome/src/run-ui-journal.js
+++ b/src/chrome/src/run-ui-journal.js
@@ -272,6 +272,10 @@ export class RunUiJournal {
streamedTextStartSeq: 0,
streamedTextSeq: 0,
streamedTextTruncated: false,
+ // Display-only state survives acknowledged events; incomplete prose
+ // never contributes to completion evidence or success classification.
+ responseRetry: null,
+ responseIncomplete: false,
startedAt: Date.now(),
endedAt: null,
};
@@ -300,6 +304,8 @@ export class RunUiJournal {
snapshot.successfulDone = false;
snapshot.runSucceeded = false;
snapshot.endedAt = null;
+ snapshot.responseRetry = null;
+ snapshot.responseIncomplete = false;
return this._changed(tabId, snapshot);
}
@@ -316,6 +322,11 @@ export class RunUiJournal {
snapshot.events.push(event);
if (data?.quota) snapshot.quota = structuredClone(data.quota);
if (type === 'text_delta') {
+ if (snapshot.responseRetry || snapshot.responseIncomplete) {
+ snapshot.streamedText = '';
+ snapshot.streamedTextStartSeq = 0;
+ snapshot.streamedTextTruncated = false;
+ }
const chunk = String(event.data?.content || '');
if (!snapshot.streamedText && !snapshot.streamedTextTruncated) {
snapshot.streamedTextStartSeq = event.seq;
@@ -337,6 +348,23 @@ export class RunUiJournal {
snapshot.streamedTextSeq = 0;
snapshot.streamedTextTruncated = false;
}
+ if (type === 'response_retry') {
+ snapshot.responseRetry = {
+ reason: 'stream_interrupted',
+ retainPartial: data?.retainPartial === true,
+ seq: event.seq,
+ };
+ snapshot.responseIncomplete = snapshot.responseRetry.retainPartial && !!snapshot.streamedText;
+ if (!snapshot.responseRetry.retainPartial) {
+ snapshot.streamedText = '';
+ snapshot.streamedTextStartSeq = 0;
+ snapshot.streamedTextSeq = 0;
+ snapshot.streamedTextTruncated = false;
+ }
+ } else if (['text', 'text_delta', 'tool_call', 'error', 'failure_recovery', 'run_complete', 'steering_applied'].includes(type)) {
+ snapshot.responseRetry = null;
+ }
+ if (['text', 'text_delta', 'tool_call', 'steering_applied'].includes(type)) snapshot.responseIncomplete = false;
while (snapshot.events.length > this.eventLimit) {
const removed = snapshot.events.shift();
const removedSeq = Number(removed?.seq || 0);
@@ -409,6 +437,8 @@ export class RunUiJournal {
snapshot.pendingPlanId = null;
snapshot.pendingToolCall = null;
snapshot.finalContent = String(finalContent || '').slice(0, 30000);
+ snapshot.responseRetry = null;
+ if (status === 'completed' && snapshot.finalContent) snapshot.responseIncomplete = false;
snapshot.endedAt = Date.now();
const event = {
seq: ++snapshot.seq,
@@ -483,6 +513,15 @@ export class RunUiJournal {
const restoredStreamSeq = Number(snapshot.streamedTextSeq || 0);
snapshot.streamedTextStartSeq = Number.isFinite(restoredStreamStartSeq) ? Math.max(0, restoredStreamStartSeq) : 0;
snapshot.streamedTextSeq = Number.isFinite(restoredStreamSeq) ? Math.max(0, restoredStreamSeq) : 0;
+ const restoredRetrySeq = Number(snapshot.responseRetry?.seq);
+ snapshot.responseRetry = snapshot.status === 'running'
+ && snapshot.responseRetry?.reason === 'stream_interrupted'
+ && Number.isSafeInteger(restoredRetrySeq) && restoredRetrySeq > 0
+ && restoredRetrySeq <= Number(snapshot.seq || 0)
+ ? { reason: 'stream_interrupted', retainPartial: snapshot.responseRetry.retainPartial === true, seq: restoredRetrySeq }
+ : null;
+ snapshot.responseIncomplete = snapshot.responseIncomplete === true && !!snapshot.streamedText
+ && !(snapshot.status === 'completed' && snapshot.finalContent);
if (!snapshot.lastPlanResolution || typeof snapshot.lastPlanResolution !== 'object') {
snapshot.lastPlanResolution = null;
}
diff --git a/src/chrome/src/trace/privacy.js b/src/chrome/src/trace/privacy.js
index f8719219d..a5c3fdcb8 100644
--- a/src/chrome/src/trace/privacy.js
+++ b/src/chrome/src/trace/privacy.js
@@ -17,13 +17,13 @@ const RESPONSE_METADATA_FIELDS = [
'step', 'usage', 'latencyMs', 'model', 'phase', 'attempt', 'repair', 'empty',
'finishReason', 'contentChars', 'toolCallCount', 'reasoningPresent',
'reasoningChars', 'reasoningTokens', 'outputTokens', 'requestedMaxTokens',
- 'recoveryAttempt',
+ 'recoveryAttempt', 'emptyReason', 'validationFailure', 'candidateAttempt',
];
const REQUEST_METADATA_FIELDS = [
'step', 'providerClass', 'providerId', 'model', 'phase', 'attempt', 'repair',
'messageCount', 'toolsCount', 'imageBlockCount', 'documentBlockCount',
- 'runtimeMode',
+ 'runtimeMode', 'requestedMaxTokens',
];
const STREAMING_METADATA_FIELDS = [
@@ -39,8 +39,51 @@ const NOTE_METADATA_FIELDS = [
'matchCount', 'multiSource', 'attempted', 'archiveDates', 'durationMs',
'success', 'approved', 'outcome', 'verification', 'count',
'adapter', 'revision', 'notesInjected', 'workflowSchema', 'job', 'template',
+ 'validationFailure', 'candidateAttempt', 'stage', 'retryMode',
];
+// Checker diagnostics are finite protocol labels, never arbitrary model text
+// or JSON property names. A malformed reply can contain private source text in
+// a duplicate field name, so metadata-only traces must normalize it here.
+const VALIDATION_FAILURE_CODES = new Set([
+ 'empty_response', 'invalid_json', 'binding_mismatch', 'invalid_aligned',
+ 'invalid_reason', 'unexpected_fields', 'reasoning_only', 'output_limit',
+ 'provider_empty', 'content_filter', 'truncated_response', 'request_failed',
+ 'invalid_replacement_plan', 'malformed_or_multiple_json_objects',
+ 'response_not_object', 'key_mismatch', 'action_mismatch',
+ 'authorized_not_boolean', 'reason_not_string', 'invalid_response',
+ ...['key', 'actionId', 'authorized', 'reason'].map(field => 'missing_' + field),
+ ...['key', 'actionId', 'authorized', 'reason', 'version', 'status', 'actions',
+ 'requirements', 'prohibited', 'extra_field'].map(field => 'duplicate_' + field),
+]);
+const PUBLICATION_CONTRACT_FAILURES = new Set([
+ 'object fields', 'list bounds', 'enum', 'source reference', 'anchor occurrence',
+ 'missing start occurrence', 'missing end occurrence', 'ambiguous start anchor',
+ 'ambiguous end anchor', 'anchor order', 'text exceeds supported payload size',
+ 'media nesting', 'media count', 'media constraint', 'version/reason',
+ 'duplicate prohibition', 'action id', 'prohibited destination',
+ 'empty body source', 'post context', 'duplicate action id',
+ 'requirement nesting', 'unknown or repeated action reference', 'incomplete requirements',
+]);
+const PUBLICATION_CONTRACT_CODES = new Set([...PUBLICATION_CONTRACT_FAILURES]
+ .map(detail => 'contract_' + detail.replace(/[^a-z0-9]+/g, '_')));
+const EMPTY_OUTPUT_REASONS = new Set(['output_limit', 'reasoning_only', 'content_filter', 'provider_empty']);
+const RECOVERY_STAGES = new Set([
+ 'model', 'inference', 'planning', 'plan_alignment', 'publication_audit',
+ 'completion_verification', 'verification',
+ 'response_generation', 'browser_interaction',
+]);
+const RECOVERY_RETRY_MODES = new Set(['resume', 'publication_without_audit', 'publication_audit_bypass']);
+
+function validationFailureMetadata(value) {
+ if (VALIDATION_FAILURE_CODES.has(value) || PUBLICATION_CONTRACT_CODES.has(value)) return value;
+ const prefix = 'Invalid publication contract: ';
+ const detail = typeof value === 'string' && value.startsWith(prefix) ? value.slice(prefix.length) : '';
+ return PUBLICATION_CONTRACT_FAILURES.has(detail)
+ ? 'contract_' + detail.replace(/[^a-z0-9]+/g, '_')
+ : 'invalid_response';
+}
+
const CLICK_AX_TIMING_MS_FIELDS = [
'preflightMs', 'syntheticDispatchMs', 'syntheticResponseMs',
'postClickObservationMs', 'fallbackPreparationMs', 'fallbackDispatchMs',
@@ -100,6 +143,16 @@ function projectPromptProvenance(value) {
function projectNoteExtra(value) {
const output = pick(value, NOTE_METADATA_FIELDS);
+ if (Object.hasOwn(output, 'validationFailure')) {
+ output.validationFailure = validationFailureMetadata(output.validationFailure);
+ }
+ if (Object.hasOwn(output, 'stage')) output.stage = RECOVERY_STAGES.has(output.stage) ? output.stage : 'model';
+ if (Object.hasOwn(output, 'retryMode')) {
+ output.retryMode = RECOVERY_RETRY_MODES.has(output.retryMode) ? output.retryMode : 'resume';
+ }
+ if (Object.hasOwn(output, 'candidateAttempt') && !Number.isSafeInteger(output.candidateAttempt)) {
+ delete output.candidateAttempt;
+ }
if (Array.isArray(output.archiveDates)) {
output.archiveDates = output.archiveDates.slice(0, 3).map(item => String(item).slice(0, 20));
}
@@ -158,6 +211,10 @@ export function projectTraceEventData(kind, data, { includeContent = false } = {
if (kind === 'llm_request') {
const projected = pick(source, REQUEST_METADATA_FIELDS);
+ if (Object.hasOwn(projected, 'requestedMaxTokens')
+ && (!Number.isSafeInteger(projected.requestedMaxTokens) || projected.requestedMaxTokens < 1)) {
+ delete projected.requestedMaxTokens;
+ }
if (source.promptProvenance && typeof source.promptProvenance === 'object') {
projected.promptProvenance = projectPromptProvenance(source.promptProvenance);
}
@@ -171,6 +228,19 @@ export function projectTraceEventData(kind, data, { includeContent = false } = {
if (kind === 'llm_response') {
const projected = pick(source, RESPONSE_METADATA_FIELDS);
+ if (Object.hasOwn(projected, 'requestedMaxTokens')
+ && (!Number.isSafeInteger(projected.requestedMaxTokens) || projected.requestedMaxTokens < 1)) {
+ delete projected.requestedMaxTokens;
+ }
+ if (Object.hasOwn(projected, 'emptyReason') && !EMPTY_OUTPUT_REASONS.has(projected.emptyReason)) {
+ delete projected.emptyReason;
+ }
+ if (Object.hasOwn(projected, 'validationFailure')) {
+ projected.validationFailure = validationFailureMetadata(projected.validationFailure);
+ }
+ if (Object.hasOwn(projected, 'candidateAttempt') && !Number.isSafeInteger(projected.candidateAttempt)) {
+ delete projected.candidateAttempt;
+ }
if (source.rejectedToolResponse) projected.rejectedToolResponse = source.rejectedToolResponse;
if (source.usage && typeof source.usage === 'object') projected.usage = projectUsage(source.usage);
return projected;
diff --git a/src/chrome/src/ui/failure-recovery.js b/src/chrome/src/ui/failure-recovery.js
new file mode 100644
index 000000000..cfc8567f3
--- /dev/null
+++ b/src/chrome/src/ui/failure-recovery.js
@@ -0,0 +1,64 @@
+const STAGE_MESSAGES = {
+ publication_audit: 'Failed while checking permission to publish. Your draft is still ready.',
+ plan_alignment: 'Failed while checking the plan against your task. No actions were started.',
+ inference: 'Failed while communicating with the AI service. Your completed steps were saved.',
+ verification: 'Failed while checking the result. The action may already be complete.',
+ planning: 'Failed while preparing the plan. No actions were started.',
+};
+
+export function failureRecoveryMessage(data = {}) {
+ const message = typeof data.message === 'string' ? data.message.trim() : '';
+ // Provider JSON belongs in diagnostics, rather than the main recovery copy.
+ if (message && !/webbrain-cloud error|\{"error"|Error communicating with LLM/i.test(message)) {
+ return message.slice(0, 2000);
+ }
+ return STAGE_MESSAGES[data.stage] || 'The task stopped before it could finish. You can retry from the saved progress.';
+}
+
+export function createFailureRecoveryCard(data, { document = globalThis.document, retryLabel = 'Retry' } = {}) {
+ if (!data?.recoveryId) return null;
+ const card = document.createElement('div');
+ card.className = 'failure-recovery-card';
+ card.dataset.recoveryId = String(data.recoveryId);
+ card.dataset.recoveryStage = String(data.stage || 'inference');
+ card.dataset.retryMode = data.retryMode === 'publication_without_audit' ? 'publication_without_audit' : 'resume';
+ card.setAttribute('role', 'alert');
+
+ const message = document.createElement('div');
+ message.className = 'failure-recovery-message';
+ message.textContent = failureRecoveryMessage(data);
+ card.appendChild(message);
+
+ if (card.dataset.retryMode === 'publication_without_audit') {
+ const note = document.createElement('div');
+ note.className = 'failure-recovery-note';
+ note.textContent = 'Retry skips the publication audit once for this unchanged draft.';
+ card.appendChild(note);
+ }
+ if (typeof data.diagnostics === 'string' && data.diagnostics.trim()) {
+ const details = document.createElement('details');
+ details.className = 'failure-recovery-details';
+ const summary = document.createElement('summary');
+ summary.textContent = 'Technical details';
+ const body = document.createElement('pre');
+ body.textContent = data.diagnostics.slice(0, 10000);
+ details.append(summary, body);
+ card.appendChild(details);
+ }
+
+ const actions = document.createElement('div');
+ actions.className = 'failure-recovery-actions';
+ for (const [choice, label] of [['give_up', 'Give up'], ['retry', retryLabel]]) {
+ const button = document.createElement('button');
+ button.type = 'button';
+ button.className = `failure-recovery-action${choice === 'retry' ? ' primary' : ''}`;
+ button.dataset.recoveryChoice = choice;
+ button.textContent = label;
+ actions.appendChild(button);
+ }
+ const status = document.createElement('div');
+ status.className = 'failure-recovery-status';
+ status.setAttribute('role', 'status');
+ card.append(actions, status);
+ return card;
+}
diff --git a/src/chrome/src/ui/locales/ar.js b/src/chrome/src/ui/locales/ar.js
index 616a04347..93e366a93 100644
--- a/src/chrome/src/ui/locales/ar.js
+++ b/src/chrome/src/ui/locales/ar.js
@@ -1217,4 +1217,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "تغيّرت الصفحة أثناء تنفيذ المهمة ({before} → {after}). جارٍ متابعة المهمة.",
+ 'sp.activity.generating_answer': "جارٍ إنشاء الإجابة…",
+ 'sp.activity.retrying_response': "جارٍ إعادة محاولة الإجابة…",
+ 'sp.response.incomplete_retrying': "إجابة غير مكتملة · جارٍ إعادة المحاولة…",
+ 'sp.response.incomplete': "إجابة غير مكتملة",
};
diff --git a/src/chrome/src/ui/locales/bn.js b/src/chrome/src/ui/locales/bn.js
index df95700b3..a694b6212 100644
--- a/src/chrome/src/ui/locales/bn.js
+++ b/src/chrome/src/ui/locales/bn.js
@@ -1216,4 +1216,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "কাজ চলার সময় পৃষ্ঠা বদলেছে ({before} → {after})। কাজ চলতে থাকবে।",
+ 'sp.activity.generating_answer': "উত্তর তৈরি হচ্ছে…",
+ 'sp.activity.retrying_response': "উত্তর আবার চেষ্টা করা হচ্ছে…",
+ 'sp.response.incomplete_retrying': "অসম্পূর্ণ উত্তর · আবার চেষ্টা করা হচ্ছে…",
+ 'sp.response.incomplete': "অসম্পূর্ণ উত্তর",
};
diff --git a/src/chrome/src/ui/locales/de.js b/src/chrome/src/ui/locales/de.js
index 9384f99e9..2610ed4aa 100644
--- a/src/chrome/src/ui/locales/de.js
+++ b/src/chrome/src/ui/locales/de.js
@@ -1189,4 +1189,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "Die Seite hat sich während der Aufgabe geändert ({before} → {after}). Die Aufgabe wird fortgesetzt.",
+ 'sp.activity.generating_answer': "Antwort wird erstellt…",
+ 'sp.activity.retrying_response': "Antwort wird erneut versucht…",
+ 'sp.response.incomplete_retrying': "Unvollständige Antwort · erneuter Versuch…",
+ 'sp.response.incomplete': "Unvollständige Antwort",
};
diff --git a/src/chrome/src/ui/locales/en.js b/src/chrome/src/ui/locales/en.js
index 9ea237abc..345a81495 100644
--- a/src/chrome/src/ui/locales/en.js
+++ b/src/chrome/src/ui/locales/en.js
@@ -260,6 +260,10 @@ export default {
'sp.activity.toggle_history': 'Toggle activity history',
'sp.activity.continuing': 'Continuing...',
'sp.activity.stopping': 'Stopping...',
+ 'sp.activity.generating_answer': 'Generating answer…',
+ 'sp.activity.retrying_response': 'Retrying response…',
+ 'sp.response.incomplete_retrying': 'Incomplete response · retrying…',
+ 'sp.response.incomplete': 'Incomplete response',
'sp.context_compacted': 'Context automatically compacted',
'sp.context_compacted_manual': 'Context compacted',
'sp.context_compacted_detail': '{summarized} earlier messages summarized · {remaining} kept',
diff --git a/src/chrome/src/ui/locales/es.js b/src/chrome/src/ui/locales/es.js
index 684e44d2f..13a9c268f 100644
--- a/src/chrome/src/ui/locales/es.js
+++ b/src/chrome/src/ui/locales/es.js
@@ -1217,4 +1217,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "La página cambió mientras se ejecutaba la tarea ({before} → {after}). La tarea continúa.",
+ 'sp.activity.generating_answer': "Generando respuesta…",
+ 'sp.activity.retrying_response': "Reintentando respuesta…",
+ 'sp.response.incomplete_retrying': "Respuesta incompleta · reintentando…",
+ 'sp.response.incomplete': "Respuesta incompleta",
};
diff --git a/src/chrome/src/ui/locales/fa.js b/src/chrome/src/ui/locales/fa.js
index 297a893f2..fcb24ab54 100644
--- a/src/chrome/src/ui/locales/fa.js
+++ b/src/chrome/src/ui/locales/fa.js
@@ -1216,4 +1216,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "صفحه هنگام اجرای کار تغییر کرد ({before} → {after}). کار ادامه می‌یابد.",
+ 'sp.activity.generating_answer': "در حال تولید پاسخ…",
+ 'sp.activity.retrying_response': "در حال تلاش دوباره برای پاسخ…",
+ 'sp.response.incomplete_retrying': "پاسخ ناقص · تلاش دوباره…",
+ 'sp.response.incomplete': "پاسخ ناقص",
};
diff --git a/src/chrome/src/ui/locales/fr.js b/src/chrome/src/ui/locales/fr.js
index aaca9887e..d91df3490 100644
--- a/src/chrome/src/ui/locales/fr.js
+++ b/src/chrome/src/ui/locales/fr.js
@@ -1217,4 +1217,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "La page a changé pendant la tâche ({before} → {after}). La tâche continue.",
+ 'sp.activity.generating_answer': "Génération de la réponse…",
+ 'sp.activity.retrying_response': "Nouvelle tentative de réponse…",
+ 'sp.response.incomplete_retrying': "Réponse incomplète · nouvelle tentative…",
+ 'sp.response.incomplete': "Réponse incomplète",
};
diff --git a/src/chrome/src/ui/locales/he.js b/src/chrome/src/ui/locales/he.js
index 5b5cbd551..1613c0b9f 100644
--- a/src/chrome/src/ui/locales/he.js
+++ b/src/chrome/src/ui/locales/he.js
@@ -1176,4 +1176,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "הדף השתנה בזמן שהמשימה פעלה ({before} → {after}). ממשיכים במשימה.",
+ 'sp.activity.generating_answer': "יוצר תשובה…",
+ 'sp.activity.retrying_response': "מנסה שוב להשיב…",
+ 'sp.response.incomplete_retrying': "תשובה חלקית · מנסה שוב…",
+ 'sp.response.incomplete': "תשובה חלקית",
};
diff --git a/src/chrome/src/ui/locales/hi.js b/src/chrome/src/ui/locales/hi.js
index 3d741d467..95d3b53e0 100644
--- a/src/chrome/src/ui/locales/hi.js
+++ b/src/chrome/src/ui/locales/hi.js
@@ -1216,4 +1216,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "काम चलने के दौरान पेज बदल गया ({before} → {after})। काम जारी है।",
+ 'sp.activity.generating_answer': "उत्तर तैयार हो रहा है…",
+ 'sp.activity.retrying_response': "उत्तर के लिए फिर प्रयास हो रहा है…",
+ 'sp.response.incomplete_retrying': "अधूरा उत्तर · फिर प्रयास हो रहा है…",
+ 'sp.response.incomplete': "अधूरा उत्तर",
};
diff --git a/src/chrome/src/ui/locales/id.js b/src/chrome/src/ui/locales/id.js
index 3b560eba7..e6088cfdd 100644
--- a/src/chrome/src/ui/locales/id.js
+++ b/src/chrome/src/ui/locales/id.js
@@ -1217,4 +1217,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "Halaman berubah saat tugas berjalan ({before} → {after}). Tugas dilanjutkan.",
+ 'sp.activity.generating_answer': "Membuat jawaban…",
+ 'sp.activity.retrying_response': "Mencoba ulang jawaban…",
+ 'sp.response.incomplete_retrying': "Jawaban belum lengkap · mencoba ulang…",
+ 'sp.response.incomplete': "Jawaban belum lengkap",
};
diff --git a/src/chrome/src/ui/locales/ja.js b/src/chrome/src/ui/locales/ja.js
index 6b2df95e6..efeb941c0 100644
--- a/src/chrome/src/ui/locales/ja.js
+++ b/src/chrome/src/ui/locales/ja.js
@@ -1217,4 +1217,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "タスク実行中にページが変わりました({before} → {after})。タスクを続行します。",
+ 'sp.activity.generating_answer': "回答を生成中…",
+ 'sp.activity.retrying_response': "回答を再試行中…",
+ 'sp.response.incomplete_retrying': "未完の回答 · 再試行中…",
+ 'sp.response.incomplete': "未完の回答",
};
diff --git a/src/chrome/src/ui/locales/ko.js b/src/chrome/src/ui/locales/ko.js
index 5e780f55c..824fd0939 100644
--- a/src/chrome/src/ui/locales/ko.js
+++ b/src/chrome/src/ui/locales/ko.js
@@ -1217,4 +1217,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "작업 실행 중 페이지가 변경되었습니다({before} → {after}). 작업을 계속합니다.",
+ 'sp.activity.generating_answer': "답변 생성 중…",
+ 'sp.activity.retrying_response': "답변 다시 시도 중…",
+ 'sp.response.incomplete_retrying': "미완성 답변 · 다시 시도 중…",
+ 'sp.response.incomplete': "미완성 답변",
};
diff --git a/src/chrome/src/ui/locales/ms.js b/src/chrome/src/ui/locales/ms.js
index ac92952ad..e1520d86a 100644
--- a/src/chrome/src/ui/locales/ms.js
+++ b/src/chrome/src/ui/locales/ms.js
@@ -1217,4 +1217,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "Halaman berubah semasa tugas berjalan ({before} → {after}). Tugas diteruskan.",
+ 'sp.activity.generating_answer': "Menjana jawapan…",
+ 'sp.activity.retrying_response': "Mencuba semula jawapan…",
+ 'sp.response.incomplete_retrying': "Jawapan tidak lengkap · mencuba semula…",
+ 'sp.response.incomplete': "Jawapan tidak lengkap",
};
diff --git a/src/chrome/src/ui/locales/nl.js b/src/chrome/src/ui/locales/nl.js
index fa57bc55b..fc4854b77 100644
--- a/src/chrome/src/ui/locales/nl.js
+++ b/src/chrome/src/ui/locales/nl.js
@@ -1169,4 +1169,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "De pagina is gewijzigd terwijl de taak actief was ({before} → {after}). De taak wordt voortgezet.",
+ 'sp.activity.generating_answer': "Antwoord wordt gegenereerd…",
+ 'sp.activity.retrying_response': "Antwoord opnieuw proberen…",
+ 'sp.response.incomplete_retrying': "Onvolledig antwoord · opnieuw proberen…",
+ 'sp.response.incomplete': "Onvolledig antwoord",
};
diff --git a/src/chrome/src/ui/locales/pl.js b/src/chrome/src/ui/locales/pl.js
index 664e61805..db9803042 100644
--- a/src/chrome/src/ui/locales/pl.js
+++ b/src/chrome/src/ui/locales/pl.js
@@ -1178,4 +1178,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "Strona zmieniła się podczas wykonywania zadania ({before} → {after}). Zadanie jest kontynuowane.",
+ 'sp.activity.generating_answer': "Generowanie odpowiedzi…",
+ 'sp.activity.retrying_response': "Ponawianie odpowiedzi…",
+ 'sp.response.incomplete_retrying': "Niepełna odpowiedź · ponawianie…",
+ 'sp.response.incomplete': "Niepełna odpowiedź",
};
diff --git a/src/chrome/src/ui/locales/pt.js b/src/chrome/src/ui/locales/pt.js
index c4b3e5c36..7463357be 100644
--- a/src/chrome/src/ui/locales/pt.js
+++ b/src/chrome/src/ui/locales/pt.js
@@ -1216,4 +1216,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "A página mudou enquanto a tarefa estava em execução ({before} → {after}). A tarefa continua.",
+ 'sp.activity.generating_answer': "Gerando resposta…",
+ 'sp.activity.retrying_response': "Tentando novamente a resposta…",
+ 'sp.response.incomplete_retrying': "Resposta incompleta · tentando novamente…",
+ 'sp.response.incomplete': "Resposta incompleta",
};
diff --git a/src/chrome/src/ui/locales/ru.js b/src/chrome/src/ui/locales/ru.js
index d25e28415..87e90b521 100644
--- a/src/chrome/src/ui/locales/ru.js
+++ b/src/chrome/src/ui/locales/ru.js
@@ -1217,4 +1217,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "Страница изменилась во время выполнения задачи ({before} → {after}). Задача продолжается.",
+ 'sp.activity.generating_answer': "Формирование ответа…",
+ 'sp.activity.retrying_response': "Повторная попытка ответа…",
+ 'sp.response.incomplete_retrying': "Неполный ответ · повторная попытка…",
+ 'sp.response.incomplete': "Неполный ответ",
};
diff --git a/src/chrome/src/ui/locales/th.js b/src/chrome/src/ui/locales/th.js
index cc1612010..c1f6f54ab 100644
--- a/src/chrome/src/ui/locales/th.js
+++ b/src/chrome/src/ui/locales/th.js
@@ -1217,4 +1217,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "หน้าเว็บเปลี่ยนระหว่างที่งานกำลังทำงาน ({before} → {after}) งานจะดำเนินต่อ",
+ 'sp.activity.generating_answer': "กำลังสร้างคำตอบ…",
+ 'sp.activity.retrying_response': "กำลังลองตอบอีกครั้ง…",
+ 'sp.response.incomplete_retrying': "คำตอบยังไม่สมบูรณ์ · กำลังลองอีกครั้ง…",
+ 'sp.response.incomplete': "คำตอบยังไม่สมบูรณ์",
};
diff --git a/src/chrome/src/ui/locales/tl.js b/src/chrome/src/ui/locales/tl.js
index fd7ce9189..2d59ff5c0 100644
--- a/src/chrome/src/ui/locales/tl.js
+++ b/src/chrome/src/ui/locales/tl.js
@@ -1217,4 +1217,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "Nagbago ang pahina habang tumatakbo ang gawain ({before} → {after}). Nagpapatuloy ang gawain.",
+ 'sp.activity.generating_answer': "Bumubuo ng sagot…",
+ 'sp.activity.retrying_response': "Sinusubukang muli ang sagot…",
+ 'sp.response.incomplete_retrying': "Hindi kumpletong sagot · sinusubukang muli…",
+ 'sp.response.incomplete': "Hindi kumpletong sagot",
};
diff --git a/src/chrome/src/ui/locales/tr.js b/src/chrome/src/ui/locales/tr.js
index 7604cc127..a915828cb 100644
--- a/src/chrome/src/ui/locales/tr.js
+++ b/src/chrome/src/ui/locales/tr.js
@@ -257,6 +257,10 @@ export default {
'sp.activity.toggle_history': 'İşlem geçmişini göster veya gizle',
'sp.activity.continuing': 'Devam ediyor...',
'sp.activity.stopping': 'Durduruluyor...',
+ 'sp.activity.generating_answer': 'Yanıt oluşturuluyor…',
+ 'sp.activity.retrying_response': 'Yanıt yeniden deneniyor…',
+ 'sp.response.incomplete_retrying': 'Tamamlanmamış yanıt · yeniden deneniyor…',
+ 'sp.response.incomplete': 'Tamamlanmamış yanıt',
'sp.copy': 'Kopyala',
'sp.copied': 'Kopyalandı!',
diff --git a/src/chrome/src/ui/locales/uk.js b/src/chrome/src/ui/locales/uk.js
index 4aa7a5e25..ba2f853e8 100644
--- a/src/chrome/src/ui/locales/uk.js
+++ b/src/chrome/src/ui/locales/uk.js
@@ -1217,4 +1217,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "Сторінка змінилася під час виконання завдання ({before} → {after}). Завдання продовжується.",
+ 'sp.activity.generating_answer': "Формування відповіді…",
+ 'sp.activity.retrying_response': "Повторна спроба відповіді…",
+ 'sp.response.incomplete_retrying': "Неповна відповідь · повторна спроба…",
+ 'sp.response.incomplete': "Неповна відповідь",
};
diff --git a/src/chrome/src/ui/locales/vi.js b/src/chrome/src/ui/locales/vi.js
index 247313250..d0f9c4cf2 100644
--- a/src/chrome/src/ui/locales/vi.js
+++ b/src/chrome/src/ui/locales/vi.js
@@ -1216,4 +1216,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "Trang đã thay đổi khi tác vụ đang chạy ({before} → {after}). Tiếp tục tác vụ.",
+ 'sp.activity.generating_answer': "Đang tạo câu trả lời…",
+ 'sp.activity.retrying_response': "Đang thử lại câu trả lời…",
+ 'sp.response.incomplete_retrying': "Câu trả lời chưa hoàn chỉnh · đang thử lại…",
+ 'sp.response.incomplete': "Câu trả lời chưa hoàn chỉnh",
};
diff --git a/src/chrome/src/ui/locales/zh.js b/src/chrome/src/ui/locales/zh.js
index 4d8693690..8dfd30c5d 100644
--- a/src/chrome/src/ui/locales/zh.js
+++ b/src/chrome/src/ui/locales/zh.js
@@ -1217,4 +1217,8 @@ export default {
'st.providers.webgpu_download.stop': 'Stop & remove',
'st.providers.webgpu_download.activate_blocked': 'Download the selected model before choosing WebGPU for chat.',
'sp.monitor.navigation': "任务运行期间页面发生了变化({before} → {after})。正在继续任务。",
+ 'sp.activity.generating_answer': "正在生成回答…",
+ 'sp.activity.retrying_response': "正在重试回答…",
+ 'sp.response.incomplete_retrying': "回答未完成 · 正在重试…",
+ 'sp.response.incomplete': "回答未完成",
};
diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.js
index c5920af5b..6e1266f17 100644
--- a/src/chrome/src/ui/sidepanel.js
+++ b/src/chrome/src/ui/sidepanel.js
@@ -39,6 +39,7 @@ import {
} from './chat-history-store.js';
import { historyTextFromElement } from './history-text.js';
import { claimRunError } from './run-error-dedupe.js';
+import { createFailureRecoveryCard } from './failure-recovery.js';
import { RUN_CAPTURE_START_ERROR_PREFIX } from '../run-capture.js';
import { runUiUnavailableBeforeSeq, runUiUpdatesForCurrentTask } from '../run-ui-journal.js';
import { formatErrorMessage } from '../error-format.js';
@@ -1352,6 +1353,7 @@ function setTabProcessing(tabId, processing) {
if (sameTabId(currentTabId, numericTabId)) {
isProcessing = effectiveProcessing;
syncSelectionScopeRestoreAvailability();
+ if (typeof syncFailureRecoveryButtons === 'function') syncFailureRecoveryButtons();
}
}
@@ -3042,7 +3044,9 @@ function roleFromMessageElement(el) {
function extractChatHistoryMessages(root = messagesEl) {
if (!root) return [];
- return Array.from(root.querySelectorAll(':scope > .message')).map((msgEl, index) => {
+ return Array.from(root.querySelectorAll(':scope > .message')).filter((msgEl) => (
+ msgEl.querySelector('.message-text')?.dataset.responseIncomplete !== 'true'
+ )).map((msgEl, index) => {
const clone = msgEl.cloneNode(true);
clone.querySelectorAll('button, input, textarea, select, .msg-copy-btn, .code-copy-btn, .error-retry-btn')
.forEach((el) => el.remove());
@@ -5682,6 +5686,13 @@ async function applyActiveRunState(numericTabId, state, { shouldContinue = () =>
!isTerminalRunUiStatus(runUi.status)
|| lastRenderedSeq < Number(runUi.seq || 0)
);
+ if (shouldRestoreStreamedText
+ && Object.prototype.hasOwnProperty.call(runUi, 'responseRetry')
+ && !runUi.responseRetry
+ && runUi.responseIncomplete !== true
+ && runAssistantEl.querySelector('.message-text')?.dataset.responseIncomplete === 'true') {
+ finishResponseRetry(runAssistantEl, { completed: true });
+ }
const hasReplayableStreamStart = shouldRestoreStreamedText
&& streamedTextStartSeq > lastRenderedSeq
&& replayEvents.some((event) => (
@@ -5696,6 +5707,13 @@ async function applyActiveRunState(numericTabId, state, { shouldContinue = () =>
streamedAssistantTextByEl.set(textEl, snapshotStreamedText);
textEl.dataset.streamedAssistantActive = 'true';
renderStreamedAssistantMarkdownNow(textEl);
+ if (!isTerminalRunUiStatus(runUi.status)) {
+ showActivity(t(runUi.responseRetry ? 'sp.activity.retrying_response' : 'sp.activity.generating_answer'));
+ }
+ if (runUi.responseIncomplete === true) {
+ markResponseIncomplete(runAssistantEl, { retrying: !!runUi.responseRetry && !isTerminalRunUiStatus(runUi.status) });
+ if (!runUi.responseRetry || isTerminalRunUiStatus(runUi.status)) finishResponseRetry(runAssistantEl);
+ }
restoredSnapshotStream = true;
};
if (!hasReplayableStreamStart) restoreSnapshotStream();
@@ -5741,6 +5759,14 @@ async function applyActiveRunState(numericTabId, state, { shouldContinue = () =>
: event.data,
});
}
+ const canApplyResponseRetrySnapshot = Number(runUi.seq || 0) >= Number(runAssistantEl.dataset.lastRenderedSeq || 0);
+ if (canApplyResponseRetrySnapshot && !isTerminalRunUiStatus(runUi.status)
+ && runUi.responseRetry) {
+ beginResponseRetry(runAssistantEl, runUi.responseRetry);
+ } else if (canApplyResponseRetrySnapshot && (runAssistantEl.dataset.responseRetrying === 'true'
+ || (shouldRestoreStreamedText && runUi.responseIncomplete === true))) {
+ finishResponseRetry(runAssistantEl);
+ }
reconcileRunMessageAttachmentState(
numericTabId,
runAssistantEl,
@@ -5845,6 +5871,9 @@ async function applyActiveRunState(numericTabId, state, { shouldContinue = () =>
hideActivity();
syncSendButtonState();
}
+ if (Object.prototype.hasOwnProperty.call(state || {}, 'pendingFailureRecovery')) {
+ reconcileFailureRecoveryCards(numericTabId, state.pendingFailureRecovery, currentAssistantEl, requestId);
+ }
return true;
}
@@ -7364,6 +7393,25 @@ function bindPlannerProviderSettingsButton(btn) {
function rebindPlannerRequestFailureControls() {
document.querySelectorAll('.planner-request-failure-provider-btn')
.forEach(bindPlannerProviderSettingsButton);
+ document.querySelectorAll('.planner-request-failure-giveup-btn')
+ .forEach(bindPlannerGiveUpButton);
+}
+
+function bindPlannerGiveUpButton(button) {
+ if (!button || button.dataset.bound) return;
+ button.dataset.bound = 'true';
+ button.addEventListener('click', () => {
+ const actions = button.closest('.planner-request-failure-actions');
+ if (!actions || actions.dataset.recoveryChosen === 'true') return;
+ actions.dataset.recoveryChosen = 'true';
+ actions.querySelectorAll('button').forEach(item => { item.disabled = true; });
+ const status = document.createElement('div');
+ status.className = 'failure-recovery-status';
+ status.setAttribute('role', 'status');
+ status.textContent = 'Stopped. No actions were started.';
+ actions.after(status);
+ schedulePersist();
+ });
}
function renderPlannerRequestFailure(assistantEl, data, retryPayload = null) {
@@ -7419,6 +7467,12 @@ function renderPlannerRequestFailure(assistantEl, data, retryPayload = null) {
const visibleActions = orderedActions.filter(Boolean);
visibleActions[0]?.classList.add('primary');
visibleActions.forEach(btn => actions.appendChild(btn));
+ const giveUpButton = document.createElement('button');
+ giveUpButton.type = 'button';
+ giveUpButton.className = 'planner-request-failure-action planner-request-failure-giveup-btn';
+ giveUpButton.textContent = 'Give up';
+ bindPlannerGiveUpButton(giveUpButton);
+ actions.appendChild(giveUpButton);
textEl.append(message, actions);
addMessageCopyButton(assistantEl);
@@ -7458,6 +7512,10 @@ function scheduleActiveChatPayloadCleanup(tabId, state) {
}
function renderAgentErrorUpdate(data, tabId = currentTabId, requestId = '', options = {}) {
+ const recoveryOwner = requestId && messagesEl.querySelector(`.message.assistant[data-run-request-id="${CSS.escape(String(requestId))}"]`);
+ const responseOwner = recoveryOwner || currentAssistantEl;
+ if (responseOwner?.dataset.responseRetrying === 'true') finishResponseRetry(responseOwner);
+ if (recoveryOwner?.querySelector('.failure-recovery-card')) return;
const message = formatErrorMessage(data?.message ?? data?.error ?? data);
// Allowance routing depends on terminal durable-turn proof. Live error
// updates arrive before that proof, so the run_complete/direct response
@@ -7481,6 +7539,114 @@ function renderAgentErrorUpdate(data, tabId = currentTabId, requestId = '', opti
}
}
+function syncFailureRecoveryButtons() {
+ for (const card of messagesEl?.querySelectorAll?.('.failure-recovery-card') || []) {
+ const disabled = card.dataset.recoveryCurrent !== 'true'
+ || card.dataset.recoveryChosen === 'true'
+ || card.dataset.recoveryBusy === 'true'
+ || processingTabs.has(Number(card.dataset.tabId))
+ || isConversationClearInProgress(Number(card.dataset.tabId));
+ card.querySelectorAll('.failure-recovery-action').forEach(button => { button.disabled = disabled; });
+ }
+}
+
+function bindFailureRecoveryCard(card) {
+ for (const button of card.querySelectorAll('.failure-recovery-action')) {
+ if (button.dataset.bound) continue;
+ button.dataset.bound = 'true';
+ button.addEventListener('click', async () => {
+ if (button.disabled || card.dataset.recoveryBusy === 'true') return;
+ const tabId = Number(card.dataset.tabId);
+ if (!sameTabId(currentTabId, tabId) || !sameTabId(renderedTabId, tabId) || isProcessing) return;
+ const choice = button.dataset.recoveryChoice;
+ const recoveryId = String(card.dataset.recoveryId || '');
+ if (!recoveryId || !['retry', 'give_up'].includes(choice)) return;
+ card.dataset.recoveryBusy = 'true';
+ card.setAttribute('aria-busy', 'true');
+ const status = card.querySelector('.failure-recovery-status');
+ status.textContent = choice === 'retry' ? 'Retrying…' : 'Stopping…';
+ syncFailureRecoveryButtons();
+ try {
+ if (choice === 'retry') {
+ const accepted = await continueAgent({
+ failureRecoveryId: recoveryId,
+ mode: card.dataset.runMode,
+ foreground: card.dataset.foreground === 'true',
+ onFailureRecoveryAccepted: () => {
+ card.dataset.recoveryChosen = 'true';
+ card.removeAttribute('aria-busy');
+ status.textContent = 'Retry requested.';
+ schedulePersist();
+ },
+ });
+ if (!accepted) throw new Error('Retry could not start. Try again when the current task has stopped.');
+ } else {
+ const result = await sendToBackground('failure_recovery_response', { tabId, recoveryId, choice });
+ if (!result?.ok) throw new Error(result?.error || 'This recovery option is no longer available.');
+ }
+ card.dataset.recoveryChosen = 'true';
+ status.textContent = choice === 'retry' ? 'Retry requested.' : 'Stopped. Your prepared work was kept.';
+ } catch (error) {
+ status.textContent = formatErrorMessage(error);
+ } finally {
+ delete card.dataset.recoveryBusy;
+ card.removeAttribute('aria-busy');
+ syncFailureRecoveryButtons();
+ schedulePersist();
+ }
+ });
+ }
+}
+
+function renderFailureRecoveryCard(assistantEl, data, { tabId = currentTabId, requestId = '' } = {}) {
+ if (!assistantEl || !data?.recoveryId) return false;
+ const recoveryId = String(data.recoveryId);
+ const existing = assistantEl.querySelector(`.failure-recovery-card[data-recovery-id="${CSS.escape(recoveryId)}"]`);
+ if (existing) {
+ if (existing.dataset.recoveryChosen !== 'true') existing.dataset.recoveryCurrent = 'true';
+ bindFailureRecoveryCard(existing);
+ syncFailureRecoveryButtons();
+ return true;
+ }
+ const card = createFailureRecoveryCard(data, { retryLabel: t('sp.retry') });
+ if (!card) return false;
+ card.dataset.tabId = String(tabId);
+ card.dataset.runRequestId = String(requestId);
+ card.dataset.runMode = assistantEl.dataset.runMode || agentMode;
+ card.dataset.foreground = assistantEl.dataset.retryForeground || 'false';
+ card.dataset.recoveryCurrent = 'true';
+ assistantEl.querySelector('.message-content')?.appendChild(card);
+ bindFailureRecoveryCard(card);
+ syncFailureRecoveryButtons();
+ scrollToBottom();
+ schedulePersist();
+ return true;
+}
+
+function reconcileFailureRecoveryCards(tabId, pending, assistantEl = currentAssistantEl, requestId = '') {
+ const currentId = String(pending?.recoveryId || '');
+ for (const card of messagesEl?.querySelectorAll?.('.failure-recovery-card') || []) {
+ if (!sameTabId(card.dataset.tabId, tabId) || card.dataset.recoveryChosen === 'true') continue;
+ card.dataset.recoveryCurrent = card.dataset.recoveryId === currentId ? 'true' : 'false';
+ if (card.dataset.recoveryCurrent === 'false') {
+ card.querySelector('.failure-recovery-status').textContent = 'This recovery option is no longer available.';
+ }
+ }
+ if (currentId) renderFailureRecoveryCard(assistantEl, pending, { tabId, requestId });
+ syncFailureRecoveryButtons();
+}
+
+function rebindFailureRecoveryCards() {
+ for (const card of document.querySelectorAll('.failure-recovery-card')) {
+ // A restored offer is display data until the background validates it.
+ card.dataset.recoveryCurrent = 'unknown';
+ delete card.dataset.recoveryBusy;
+ card.removeAttribute('aria-busy');
+ bindFailureRecoveryCard(card);
+ }
+ syncFailureRecoveryButtons();
+}
+
function rebindRestoredMessageControls() {
void restoreGeneratedMedia(messagesEl, t);
restoreStagedScreenshotAttachments();
@@ -7491,6 +7657,7 @@ function rebindRestoredMessageControls() {
rebindRetryButtons();
rebindPlanReviewRetryButtons();
rebindPlannerRequestFailureControls();
+ rebindFailureRecoveryCards();
rebindContinueButtons();
rebindClarifyCards();
rebindPlanReviewCards();
@@ -9770,7 +9937,8 @@ async function sendMessage(extraChatParams = {}) {
});
}
addMessageCopyButton(assistantEl);
- } else if (textEl && getStreamedAssistantText(textEl) === String(res.content)) {
+ } else if (textEl && (getStreamedAssistantText(textEl) === String(res.content)
+ || (textEl.dataset.responseIncomplete === 'true' && isSuccessfulAskCompletion(modeForSend, res)))) {
renderAssistantTextUpdate(assistantEl, res.content);
} else if (textEl && !textEl.textContent.trim()) {
if (!renderCostAllowanceError(textEl, res.content, modeForSend, {
@@ -10378,6 +10546,9 @@ function handleAgentUpdateMessage(msg) {
}
case 'steering_applied': {
+ if ((eventAssistantEl || currentAssistantEl)?.dataset.responseRetrying === 'true') {
+ finishResponseRetry(eventAssistantEl || currentAssistantEl);
+ }
const id = String(data?.id || '');
if (id && !messagesEl.querySelector(`[data-steering-message-id="${CSS.escape(id)}"]`)) {
const userEl = addMessage('user', data.text, { beforeCurrentAssistant: true });
@@ -10401,16 +10572,24 @@ function handleAgentUpdateMessage(msg) {
// Empty content usually means "nothing new" — keep prior prose. Exception:
// replace:true with empty content clears a rejected streamed terminal
// (e.g. plan-only recovery) so the bubble is free for the real summary.
- if (data?.content) showActivity(t('tool.done'));
+ if (data?.content) showActivity(t('sp.activity.generating_answer'));
if (currentAssistantEl && (data.content || data.replace === true)) {
renderAssistantTextUpdate(currentAssistantEl, data.content || '', { replace: data.replace === true });
}
break;
case 'text_delta':
- if (data?.content) showActivity(t('tool.done'));
+ if (data?.content) showActivity(t('sp.activity.generating_answer'));
if (currentAssistantEl) {
const textEl = currentAssistantEl.querySelector('.message-text');
+ if (data?.content && (textEl?.dataset.responseIncomplete === 'true'
+ || currentAssistantEl.dataset.responseRetrying === 'true')) {
+ // A replacement stream starts a fresh answer, never appending to
+ // the interrupted attempt retained for the user.
+ finishResponseRetry(currentAssistantEl, { completed: true });
+ textEl.textContent = '';
+ clearStreamedAssistantText(textEl);
+ }
if (textEl && textEl.dataset.suppressToolCallStream !== 'true') {
// Keep the raw Markdown separate from the rendered DOM. Reading back
// textContent would discard markers such as ** and backticks after
@@ -10436,6 +10615,10 @@ function handleAgentUpdateMessage(msg) {
}
break;
+ case 'response_retry':
+ beginResponseRetry(eventAssistantEl || currentAssistantEl, data);
+ break;
+
case 'tool_call':
showActivity(friendlyToolLabel(data.name, data.args));
showInspectionBanner(data.name);
@@ -10510,6 +10693,17 @@ function handleAgentUpdateMessage(msg) {
renderAgentErrorUpdate(data, currentTabId, msg.requestId);
break;
+ case 'failure_recovery':
+ hideActivity();
+ if ((eventAssistantEl || currentAssistantEl)?.dataset.responseRetrying === 'true') {
+ finishResponseRetry(eventAssistantEl || currentAssistantEl);
+ }
+ if (currentAssistantEl) markLastStepFailed();
+ renderFailureRecoveryCard(eventAssistantEl || currentAssistantEl, data, {
+ tabId: eventTabId, requestId: msg.requestId,
+ });
+ break;
+
case 'max_steps_reached':
hideActivity();
// Don't gate on currentAssistantEl — this event sometimes arrives
@@ -10544,6 +10738,7 @@ function handleAgentUpdateMessage(msg) {
addPlannerFallbackNote(message, scheduledAssistantEl || eventAssistantEl || currentAssistantEl);
}
} else if (data?.code === 'ask_stream_fallback') {
+ showActivity(t('sp.activity.retrying_response'));
showComposerToast(t('sp.streaming.fallback'), { duration: 6000 });
} else if (data?.code === 'persistence_degraded') {
showComposerToast(t('sp.persistence.unavailable'), { duration: 10000 });
@@ -10564,6 +10759,10 @@ function handleAgentUpdateMessage(msg) {
break;
case 'run_complete':
+ if ((eventAssistantEl || currentAssistantEl)?.dataset.responseRetrying === 'true'
+ && (data?.status !== 'completed' || !data?.finalContent)) {
+ finishResponseRetry(eventAssistantEl || currentAssistantEl);
+ }
if (data?.quota) {
const target = eventAssistantEl || currentAssistantEl;
const text = target?.querySelector('.message-text');
@@ -10607,7 +10806,8 @@ function handleAgentUpdateMessage(msg) {
});
}
addMessageCopyButton(currentAssistantEl);
- } else if (textEl && hasStreamedText) {
+ } else if (textEl && (hasStreamedText
+ || (data.status === 'completed' && textEl.dataset.responseIncomplete === 'true'))) {
// Background/restored runs do not necessarily reach the local
// sendRunWithReconnect response handler. Finalize their lightweight
// live Markdown here, cancelling any queued frame and enabling the
@@ -11857,7 +12057,55 @@ function flushPendingStreamedAssistantMarkdownRenders(root = messagesEl) {
});
}
+function markResponseIncomplete(assistantEl, { retrying = false } = {}) {
+ const textEl = assistantEl.querySelector('.message-text');
+ if (!textEl) return;
+ renderStreamedAssistantMarkdownNow(textEl);
+ const partialText = getStreamedAssistantText(textEl);
+ if (partialText || textEl.textContent.trim()) {
+ textEl.dataset.responseIncomplete = 'true';
+ // Only retained retries need raw text in persisted markup. The journal
+ // remains authoritative; this also keeps a restored partial readable
+ // when its original deltas have already been acknowledged.
+ if (partialText) textEl.dataset.streamedAssistantText = partialText;
+ let note = assistantEl.querySelector('.response-incomplete-note');
+ if (!note) {
+ note = document.createElement('div');
+ note.className = 'response-incomplete-note';
+ note.setAttribute('role', 'status');
+ textEl.after(note);
+ }
+ note.textContent = t(retrying ? 'sp.response.incomplete_retrying' : 'sp.response.incomplete');
+ }
+}
+
+function beginResponseRetry(assistantEl, data = {}) {
+ if (!assistantEl || data.reason !== 'stream_interrupted') return;
+ assistantEl.dataset.responseRetrying = 'true';
+ if (data.retainPartial === true) markResponseIncomplete(assistantEl, { retrying: true });
+ showActivity(t('sp.activity.retrying_response'));
+ schedulePersist();
+}
+
+function finishResponseRetry(assistantEl, { completed = false } = {}) {
+ if (!assistantEl) return;
+ delete assistantEl.dataset.responseRetrying;
+ const textEl = assistantEl.querySelector('.message-text');
+ const note = assistantEl.querySelector('.response-incomplete-note');
+ if (completed) {
+ if (textEl) delete textEl.dataset.responseIncomplete;
+ note?.remove();
+ } else {
+ // Failed/cancelled retries may retain useful prose, but it remains
+ // explicitly incomplete and excluded from saved conversation messages.
+ if (note) note.textContent = t('sp.response.incomplete');
+ if (textEl?.dataset.responseIncomplete === 'true') clearStreamedAssistantText(textEl);
+ }
+ schedulePersist();
+}
+
function clearAssistantTextStreamState(assistantEl) {
+ if (assistantEl?.dataset.responseRetrying === 'true') finishResponseRetry(assistantEl);
const textEl = assistantEl?.querySelector('.message-text');
if (!textEl) return;
clearStreamedAssistantText(textEl);
@@ -11867,8 +12115,13 @@ function clearAssistantTextStreamState(assistantEl) {
function renderAssistantTextUpdate(assistantEl, content, options = {}) {
const textEl = assistantEl.querySelector('.message-text');
if (!textEl) return;
+ const replacesIncompleteResponse = textEl.dataset.responseIncomplete === 'true';
if (isStoppedByUserStatus(content)) {
+ if (replacesIncompleteResponse) {
+ finishResponseRetry(assistantEl);
+ return;
+ }
textEl.innerHTML = t('sp.stopped_by_user_html');
clearStreamedAssistantText(textEl);
delete textEl.dataset.suppressToolCallStream;
@@ -11876,6 +12129,10 @@ function renderAssistantTextUpdate(assistantEl, content, options = {}) {
return;
}
+ if (replacesIncompleteResponse || assistantEl.dataset.responseRetrying === 'true') {
+ finishResponseRetry(assistantEl, { completed: true });
+ }
+
// Cost-limit text can stream before the terminal snapshot tells us whether
// Retry or Continue is safe. Keep the bubble empty so the terminal renderer
// can build the card with authoritative resume context.
@@ -11899,7 +12156,7 @@ function renderAssistantTextUpdate(assistantEl, content, options = {}) {
// Final text must keep the same Markdown fence structure shown during streaming.
const renderedContent = formatMarkdown(content, { recoverNestedMarkdown: true });
- if (options.replace === true || restoredStreamNeedsReplacement) {
+ if (options.replace === true || restoredStreamNeedsReplacement || replacesIncompleteResponse) {
// A rejected streamed terminal must replace its already-rendered deltas
// even in Verbose mode; appending would leave the invalid plan visible.
// Empty content clears the bubble (plan-only retry before recovery tools).
@@ -11943,6 +12200,10 @@ function isStoppedByUserStatus(content) {
function clearTransientAssistantTextForToolCall() {
if (!currentAssistantEl) return;
+ if (currentAssistantEl.dataset.responseRetrying === 'true'
+ || currentAssistantEl.querySelector('.message-text')?.dataset.responseIncomplete === 'true') {
+ finishResponseRetry(currentAssistantEl, { completed: true });
+ }
const textEl = currentAssistantEl.querySelector('.message-text');
if (!textEl) return;
const text = textEl.textContent || '';
@@ -12923,18 +13184,21 @@ function showContinueButton(options = {}) {
async function continueAgent(options = {}) {
if (isStandaloneWindow) options = { ...options, mode: 'ask' };
+ if (isProcessing) return false;
const tabId = currentTabId;
const modeForSend = ['ask', 'act', 'dev'].includes(options?.mode) ? options.mode : agentMode;
if (rejectSelectionScopedMode(modeForSend, tabId)) return false;
const requestId = createRunRequestId(tabId);
const foregroundForSend = options?.foreground === true;
clearActiveChatPayloadForTab(tabId);
+ localRunRequestIds.set(tabId, requestId);
setTabProcessing(tabId, true);
setTabAbortRequested(tabId, false);
syncSendButtonState();
let assistantEl = null;
+ let runAccepted = false;
try {
await prepareChatHistoryForTurn(tabId, modeForSend);
@@ -12956,16 +13220,24 @@ async function continueAgent(options = {}) {
scrollChatToQuestion({ smooth: false });
}
showActivity(t('sp.activity.continuing'));
- localRunRequestIds.set(tabId, requestId);
- const res = await sendRunWithReconnect('continue_start', {
+ const res = await sendRunWithReconnect(options.failureRecoveryId ? 'failure_recovery_response' : 'continue_start', {
tabId,
requestId,
mode: modeForSend,
foreground: foregroundForSend,
+ ...(options.failureRecoveryId ? { recoveryId: options.failureRecoveryId, choice: 'retry' } : {}),
...(isStandaloneWindow ? { standaloneChat: true } : {}),
...standaloneWebgpuRunPayload(),
+ }, {
+ onStateObserved: state => {
+ if (!runAccepted && (state?.runUi?.requestId === requestId || state?.startingRequestId === requestId)) {
+ runAccepted = true;
+ options.onFailureRecoveryAccepted?.();
+ }
+ },
});
+ runAccepted = true;
if (sameTabId(currentTabId, tabId)) renderReturnedQuota(assistantEl, res);
applyConversationScopeState(tabId, res);
if (res?.conversationId) {
@@ -12995,12 +13267,13 @@ async function continueAgent(options = {}) {
}
}
} catch (e) {
+ if (options.failureRecoveryId && !runAccepted) throw e;
if (currentTabId === tabId
&& assistantEl
&& !isTabAbortRequested(tabId)
&& !clearedConversationRunRequestIds.has(requestId)
&& !conversationClearFollowerCancellationRequestIds.has(requestId)) {
- addMessage('error', t('sp.error_prefix', { msg: e.message }));
+ renderAgentErrorUpdate({ message: e.message, quota: e.quota }, tabId, requestId);
}
} finally {
const ownsRunState = localRunRequestIds.get(tabId) === requestId;
@@ -13022,6 +13295,7 @@ async function continueAgent(options = {}) {
if (currentTabId === tabId && renderedTabId === tabId) await flushChatHistorySnapshot(tabId, { refreshTabInfo: true });
await drainQueuedPromptsAfterRunSettles(tabId);
}
+ return runAccepted;
}
// Track max steps for display in continue bar
@@ -13752,6 +14026,7 @@ async function sendRunWithReconnect(initialAction, payload, recoveryOptions = {}
isConnectionError: isBackgroundConnectionError,
onState: state => {
if (!shouldContinueRunRecovery()) return;
+ recoveryOptions.onStateObserved?.(state);
applyConversationScopeState(tabId, state);
return applyActiveRunState(tabId, state, { shouldContinue: shouldContinueRunRecovery });
},
diff --git a/src/chrome/styles/sidepanel.css b/src/chrome/styles/sidepanel.css
index b5963e0a7..3c3fa0f10 100644
--- a/src/chrome/styles/sidepanel.css
+++ b/src/chrome/styles/sidepanel.css
@@ -1561,6 +1561,12 @@ html[data-ui-scale-ready="false"] body { visibility: hidden; }
display: none;
}
+.response-incomplete-note {
+ margin-top: 8px;
+ color: var(--text-muted);
+ font-size: 12px;
+}
+
.message-content {
padding: 10px 14px;
border-radius: var(--radius);
@@ -4058,6 +4064,40 @@ html[data-ui-scale="175"] .conversation-action-label {
display: none;
}
+.failure-recovery-card {
+ margin: 10px 0;
+ padding: 12px;
+ border: 1px solid var(--border);
+ border-radius: var(--radius, 6px);
+ background: var(--bg-secondary);
+ font-size: 13px;
+ line-height: 1.5;
+}
+
+.failure-recovery-message { color: var(--text-primary); }
+.failure-recovery-note, .failure-recovery-status {
+ margin-top: 6px;
+ color: var(--text-secondary);
+ font-size: 12px;
+}
+.failure-recovery-status:empty { display: none; }
+.failure-recovery-actions { display: flex; gap: 8px; margin-top: 12px; }
+.failure-recovery-action {
+ padding: 6px 12px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--bg-primary);
+ color: var(--text-primary);
+ cursor: pointer;
+ font: inherit;
+}
+.failure-recovery-action.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
+.failure-recovery-action:disabled { cursor: default; opacity: .55; }
+.failure-recovery-action:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.failure-recovery-details { margin-top: 8px; color: var(--text-secondary); font-size: 11px; }
+.failure-recovery-details summary { cursor: pointer; }
+.failure-recovery-details pre { max-height: 180px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; }
+
/* Clarify card — agent paused to ask user a question */
.clarify-card {
margin: 8px 0;
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index f3432826c..a8b2cbd03 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -11,17 +11,18 @@ import { JEV_FAST_KEYS, JEV_CLASSIFIER_THRESHOLD, JEV_BROWSER_THRESHOLD, confide
import { redactSystemOneText, wrapSystemOneData, boundedSystemOneText } from './systemone-evidence.js';
import { createSystemOneJudge, isSystemOneResponseContractError, systemOneFailureReason, SYSTEM_ONE_COST_PROVIDER } from './systemone-judge.js';
import { firefoxBidi } from '../bidi/client.js';
-import { SOCIAL_PLATFORMS, socialPublicationApiPlatform, normalizePublicationContract, publicationProgress, exactPublicationText, publicationMediaMatches, publicationContractMessages, publicationAuditMessages, publicationAuditAccepted } from './social-publish-contract.js';
+import { SOCIAL_PLATFORMS, socialPublicationApiPlatform, normalizePublicationContract, publicationProgress, exactPublicationText, publicationMediaMatches, publicationContractMessages, publicationAuditMessages, parsePublicationJson, publicationAuditValidation } from './social-publish-contract.js';
import { mastodonPublicationIntentMessages, normalizeMastodonPublicationIntent, captureNativeMastodonPublication, mastodonPublicationBinding, mastodonPublicationReceipt, mastodonPublicationNavigation } from './mastodon-publication.js';
import { AGENT_TOOLS, AGENT_TOOL_NAMES, RESERVED_AGENT_TOOL_NAMES, getToolsForMode, SYSTEM_PROMPT_ASK, SYSTEM_PROMPT_ACT, SYSTEM_PROMPT_ACT_COMPACT, SYSTEM_PROMPT_ACT_MID, SYSTEM_PROMPT_GENERATIVE_MEDIA, SYSTEM_PROMPT_DEV_APPENDIX } from './tools.js';
import { rejectedCompletionRecovery } from './completion-recovery.js';
+import { FailureRecoveryRegistry, modelFailureRecovery } from './failure-recovery.js';
import { validateToolArguments } from './tool-arguments.js';
import { calculateExpression, calculationResultInText } from './calculator.js';
import { isLiteralCalculationTask, literalCalculationSummaryFormatMatches } from './page-feedback-policy.js';
import { chatRecoveryDisplayText, terminalRecoveryFinalText } from './chat-recovery-text.js';
import { isSessionQuotaError, serializeConversationForSession, SESSION_CONVERSATION_BUDGET_BYTES, SESSION_CONVERSATION_RETRY_BUDGET_BYTES } from './conversation-persistence.js';
import { formatErrorMessage } from '../error-format.js';
-import { retryModelCall } from '../providers/model-retry.js';
+import { retryModelCall, retryModelStream } from '../providers/model-retry.js';
import { isQwenConfig } from '../providers/provider-compatibility.js';
import { aggregateMessageCompletion } from '../message-info.js';
import { handleDoneJson } from './cloud-output.js';
@@ -118,7 +119,7 @@ import {
buildPlannerMessages,
buildPlannerAlignmentMessages,
buildPlannerAlignmentRepairMessages,
- parsePlannerAlignmentFromContent,
+ inspectPlannerAlignmentContent,
PLANNER_ALIGNMENT_RESPONSE_JSON_SCHEMA,
buildPlannerIntentMessages,
buildReadScopeMessages,
@@ -994,6 +995,7 @@ export class Agent extends LoopDetector {
// Pending clarify() tool calls awaiting user input — see Chrome
// agent.js. Keyed by tabId → (clarifyId → {resolve, ts}).
this._pendingClarifications = new Map();
+ this._failureRecovery = new FailureRecoveryRegistry();
// Explicit, one-use, in-memory approvals for sharing one exact research
// prompt with the configured engine.
this._researchEscalationAuthorizations = new Map();
@@ -6234,6 +6236,7 @@ export class Agent extends LoopDetector {
// Claim synchronously before awaiting the external guard so teacher-mode
// startup cannot race a run whose persisted teacher-state check is pending.
this._runningTabs.add(tabId);
+ this._failureRecovery.clear(tabId);
this._jevSessions?.delete(tabId);
for (const [id, pending] of this._jevPendingCalls || []) if (pending.tabId === tabId) this._jevPendingCalls.delete(id);
this._systemOneGenerations ??= new Map();
@@ -6637,6 +6640,128 @@ export class Agent extends LoopDetector {
return null;
}
+ _failureRecoveryBinding(tabId) {
+ return { tabId, conversationId: this.conversationIds.get(tabId) || '',
+ taskKey: this._progressTaskKeyHash(tabId), taskSignature: this._sha256TextSync(this._progressTaskAnchorText(tabId)) };
+ }
+
+ _pendingFailureRecoveryForUi(tabId) {
+ return this._failureRecovery.current(this._failureRecoveryBinding(tabId))?.descriptor || null;
+ }
+
+ _offerFailureRecovery(tabId, details, onUpdate) {
+ if (this._checkAbort(tabId) || this._hasPendingSteering(tabId)) return null;
+ const binding = this._failureRecoveryBinding(tabId);
+ const recoveryId = 'recovery_' + secureRandomBase36Token(24);
+ const descriptor = { recoveryId, stage: details.stage || 'model',
+ code: details.code || 'request_failed', message: String(details.message || 'The task could not finish.').slice(0,2000),
+ retryMode: details.stage === 'publication_audit' ? 'publication_without_audit' : 'resume',
+ retryLabel: 'Retry', giveUpLabel: 'Give up',
+ ...(details.diagnostics ? { diagnostics: String(details.diagnostics).slice(0,6000) } : {}) };
+ this._failureRecovery.offer({ ...binding,
+ ...(details.publicationKey ? { publicationKey: details.publicationKey,
+ publicationTaskKey: details.taskKey } : {}) }, descriptor);
+ onUpdate?.('failure_recovery', descriptor);
+ const runId = this.currentRunId.get(tabId);
+ if (runId) trace.recordNote(runId, 0, 'failure_recovery_offered', {
+ stage: descriptor.stage, code: descriptor.code, retryMode: descriptor.retryMode });
+ return descriptor;
+ }
+
+ async _recoverPostActionModelFailure(tabId, messages, onUpdate, provider, step, runOptions = {}) {
+ const submit = this._completionSubmitStates.get(tabId);
+ const invariant = this.completionInvariants.get(tabId);
+ if (submit?.dispatched !== true || !invariant?.lastAction || !this._isActionMode(this._effectiveRunMode(tabId))
+ || this._checkAbort(tabId) || this._hasPendingSteering(tabId)) return null;
+ const binding = this._failureRecoveryBinding(tabId);
+ const actionSequence = invariant.lastAction.sequence;
+ const runToken = invariant.runToken;
+ const current = () => {
+ const latestBinding = this._failureRecoveryBinding(tabId);
+ return this.completionInvariants.get(tabId)?.runToken === runToken
+ && this.completionInvariants.get(tabId)?.lastAction?.sequence === actionSequence
+ && binding.taskKey === latestBinding.taskKey
+ && binding.taskSignature === latestBinding.taskSignature
+ && binding.conversationId === latestBinding.conversationId
+ && !this._checkAbort(tabId) && !this._hasPendingSteering(tabId);
+ };
+ if (!current()) return null;
+ onUpdate?.('warning', { message: 'The model request failed after submission. Inspecting the result without repeating the action.' });
+ const frame = this._completionIframeBinding(tabId);
+ const readName = frame?.currentUrl ? 'verify_form' : 'get_accessibility_tree';
+ const readArgs = frame?.currentUrl ? { urlFilter: frame.currentUrl } : { filter: 'visible', maxChars: 6000 };
+ const runReadOnly = async (name, args) => {
+ const id = 'call_recovery_' + secureRandomBase36Token(24);
+ const call = { id, type: 'function', function: { name, arguments: JSON.stringify(args) } };
+ messages.push({ role: 'assistant', content: null, tool_calls: [call] });
+ return this._executeToolBatch(tabId, [call], messages, onUpdate, provider, null,
+ AGENT_TOOL_NAMES, step, runOptions);
+ };
+ try {
+ await runReadOnly(readName, readArgs);
+ if (!current() || this._completionDoneBlock(tabId, 'done', { outcome: 'success' })) return null;
+ const pageUrl = await this._currentUrl(tabId);
+ if (!current()) return null;
+ const summary = /^https:\/\/addons\.mozilla\.org\//i.test(pageUrl)
+ ? 'The AMO version was submitted for review and the submission confirmation was verified.'
+ : 'The requested submission completed and its result was verified.';
+ const result = await runReadOnly('done', { outcome: 'success', summary });
+ if (current() && result?.action === 'return' && !result.status
+ && this._completionVerdicts.get(tabId)?.outcome === 'succeeded') {
+ if (typeof runOptions.afterVerifiedCompletion === 'function') {
+ await this._settleVerifiedScheduledCompletion(tabId, messages, result, {
+ ...runOptions,
+ afterVerifiedCompletion: proof => runOptions.afterVerifiedCompletion({
+ ...proof,
+ isCurrent: () => current() && proof.isCurrent(),
+ refresh: async () => current() && await proof.refresh() && current(),
+ }),
+ });
+ this._throwIfAborted(this._runAbortSignal(tabId));
+ if (!current()) return null;
+ }
+ return { content: result.value, status: 'done' };
+ }
+ } catch (error) {
+ if (this._checkAbort(tabId) || error?.name === 'AbortError' || this._isCostAllowanceError(error)) throw error;
+ const runId = this.currentRunId.get(tabId);
+ if (runId) trace.recordError(runId, step, 'completion_recovery', formatErrorMessage(error), this._traceErrorCodeFor(error));
+ }
+ return null;
+ }
+
+ async _finalModelFailure(tabId, messages, onUpdate, provider, error, step, runOptions = {}) {
+ const runId = this.currentRunId.get(tabId);
+ if (runId) trace.recordError(runId, step, 'model', formatErrorMessage(error), this._traceErrorCodeFor(error));
+ const recovered = await this._recoverPostActionModelFailure(tabId, messages, onUpdate, provider, step, runOptions);
+ if (recovered) return recovered;
+ const postAction = this._completionSubmitStates.get(tabId)?.dispatched === true;
+ const details = modelFailureRecovery(error, { postAction });
+ this._offerFailureRecovery(tabId, details, onUpdate);
+ onUpdate?.('error', { message: details.message });
+ return { content: details.message, status: postAction ? 'partial' : 'error' };
+ }
+
+ requestFailureRecovery(tabId, recoveryId, choice) {
+ if (!['retry', 'give_up'].includes(choice)) return { ok: false, error: 'Invalid recovery choice.' };
+ if (this.isRunning(tabId)) return { ok: false, error: 'Wait for the current run to finish before choosing recovery.' };
+ const offer = this._failureRecovery.current(this._failureRecoveryBinding(tabId));
+ if (!offer || offer.descriptor.recoveryId !== recoveryId) {
+ return { ok: false, error: 'This retry has expired. Start or continue the current task.' };
+ }
+ if (choice === 'retry' && offer.descriptor.retryMode === 'publication_without_audit') {
+ const granted = this._grantSocialPublicationAuditRetry(tabId, { ...offer.binding,
+ taskKey: offer.binding.publicationTaskKey || offer.binding.taskKey });
+ if (granted !== true && granted?.ok !== true) {
+ this._failureRecovery.clear(tabId);
+ return { ok: false, error: granted?.error || 'The publication changed. Verify the current draft before retrying.' };
+ }
+ }
+ if (choice === 'give_up') this._revokeSocialPublicationAuditRetry(tabId);
+ this._failureRecovery.clear(tabId);
+ return { ok: true, continue: choice === 'retry', retryMode: offer.descriptor.retryMode };
+ }
+
activeRunState(tabId) {
const persistenceState = this.persistenceDegradedTabs.get(tabId) || null;
const state = {
@@ -6644,6 +6769,7 @@ export class Agent extends LoopDetector {
runId: this.currentRunId.get(tabId) || null,
pendingPlan: null,
pendingCurrentClarification: this._pendingCurrentClarificationForUi(tabId),
+ pendingFailureRecovery: this._pendingFailureRecoveryForUi(tabId),
persistenceDegraded: !!persistenceState,
persistenceDegradedReason: persistenceState?.reason || null,
researchEscalationSourceTabId: this.researchEscalationSourceTab(tabId),
@@ -12534,6 +12660,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (runId) trace.recordToolCall(runId, step, {
name: fnName, args: fnArgs, result: workflowPreSubmitBlock, latencyMs: 0,
});
+ if (workflowPreSubmitBlock.failureRecovery?.stage === 'publication_audit') {
+ const offer = this._offerFailureRecovery(tabId, workflowPreSubmitBlock.failureRecovery, onUpdate);
+ this._appendSyntheticToolResults(tabId, toolCalls, toolIndex + 1, messages, onUpdate, step,
+ () => ({ success: false, skipped: true, noDispatch: true, error: 'Paused for a user recovery choice.' }));
+ this._persist(tabId);
+ return { action: 'return', value: offer?.message || workflowPreSubmitBlock.error, status: 'publication_audit_failed' };
+ }
onUpdate('warning', { message: workflowPreSubmitBlock.error });
if (workflowPreSubmitBlock.workflowRearmed || workflowPreSubmitBlock.conditionalMutationBlocked) {
this._appendSyntheticToolResults(tabId, toolCalls, toolIndex + 1, messages, onUpdate, step,
@@ -13142,6 +13275,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
&& (this._hasPendingSteering(tabId) || await this._refreshPageFeedbackForCall(tabId, tc, onUpdate))) return { steered: true };
const calculationDispatchBlock = this._pureCalculationToolBlock(tabId, fnName, fnArgs, calculationRequestScope);
if (!pipelineToolbarPreflight.block && !socialDispatchBlock && !genericChatBlock && !calculationDispatchBlock) {
+ if (detectedSubmitAction?.isSubmit === true && detectedSubmitAction.publicationControl === true) {
+ this._consumeSocialPublicationAuditRetry(tabId);
+ }
if (fnName === 'calculate') this._rememberPureCalculationAttempt(tabId, fnArgs, calculationRequestScope);
callState.invoked = true;
}
@@ -13805,6 +13941,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
});
await settleConsequentialTool();
this._throwIfAborted(this._runAbortSignal(tabId));
+ if (toolResult?.failureRecovery?.stage === 'publication_audit') {
+ const offer = this._offerFailureRecovery(tabId, toolResult.failureRecovery, onUpdate);
+ this._appendSyntheticToolResults(tabId, toolCalls, toolIndex + 1, messages, onUpdate, step,
+ () => ({ success: false, skipped: true, noDispatch: true, error: 'Paused for a user recovery choice.' }));
+ this._persist(tabId);
+ return { action: 'return', value: offer?.message || toolResult.error, status: 'publication_audit_failed' };
+ }
if ((captchaGateDecision?.status === 'manual_required' || captchaSolveOutcome?.status === 'manual_required')
&& !this._canTryNativeCaptcha(tabId, captchaGateDecision || captchaSolveOutcome)) {
this._appendSyntheticToolResults(
@@ -16335,6 +16478,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
*/
abort(tabId) {
for (const id of this._researchEscalationTabIds(tabId)) {
+ this._failureRecovery.clear(id);
+ this._revokeSocialPublicationAuditRetry(id);
this._ownedNativeChatReadRepairs.delete(id);
this.abortFlags.set(id, true);
const controller = this._runAbortStates.get(id)?.controller;
@@ -18693,6 +18838,134 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
}
+ _socialPublicationChatOptions(provider, retry = false, portable = false, audit = false) {
+ const options = {
+ temperature: 0,
+ maxTokens: Math.min(retry ? 4096 : 2048, this._providerMaxOutputTokens(provider)),
+ };
+ if (!portable) {
+ const config = { ...(provider?.config || {}),
+ providerName: provider?.config?.providerName || provider?.name || '',
+ model: provider?.config?.model || provider?.model || '' };
+ const schema = audit ? { type: 'object', additionalProperties: false,
+ properties: { key: { type: 'string' }, actionId: { type: 'string' },
+ authorized: { type: 'boolean' }, reason: { type: 'string' } },
+ required: ['key', 'actionId', 'authorized', 'reason'] } : null;
+ const controls = plannerRequestBody(config, {
+ schema, schemaName: 'webbrain_social_publication_authorization', disableThinking: true,
+ });
+ if (['anthropic', 'anthropic-oauth', 'google-vertex-anthropic'].includes(provider?.name)) {
+ controls.thinking = { type: 'disabled' };
+ }
+ if (Object.keys(controls).length) options.extraBody = controls;
+ }
+ return options;
+ }
+
+ _socialPublicationOptionsRejected(error) {
+ const text = String(error?.message || error || '');
+ return /response_format|json_schema|reasoning(?:_effort)?|thinking|chat_template_kwargs/i.test(text)
+ && /unsupported|not supported|unknown|unrecognized|not allowed|unexpected|invalid.*(?:parameter|argument)/i.test(text);
+ }
+
+ _socialPublicationRepairMessages(messages) {
+ return this._plannerProtocolRepairMessages(messages,
+ '/no_think\nThe publication checker response was empty, truncated, or invalid. '
+ + 'Recheck the same unchanged authentic task and supplied binding. Return exactly one complete JSON object '
+ + 'matching the documented schema, with the supplied key and actionId when auditing. '
+ + 'No prose, tool calls, Markdown, or reasoning text. This is format repair, not new user permission.');
+ }
+
+ _socialPublicationResponseObject(response, options) {
+ const diagnostics = modelOutputDiagnostics(response, { requestedMaxTokens: options.maxTokens });
+ if (diagnostics.empty) throw new Error(diagnostics.emptyReason || 'empty_response');
+ if (/^(?:length|max_tokens|max_output_tokens|output_limit)$/i.test(diagnostics.finishReason || '')) {
+ throw new Error('truncated_response');
+ }
+ return parsePublicationJson(response?.content);
+ }
+
+ async _socialPublicationCheckerFailure(tabId, phase, attempt, error, validation = false) {
+ const runId = this.currentRunId.get(tabId);
+ if (!runId) return;
+ if (!validation) {
+ await this._tracePlannerAttemptFailure(runId, phase, attempt, error, 'publication_checker_failed');
+ return;
+ }
+ try {
+ await trace.recordNote(runId, 0, 'publication_checker_validation_failed', {
+ phase, attempt, validationFailure: String(error?.message || error).slice(0, 600),
+ });
+ await trace.recordError(runId, 0, 'publication_checker_invalid_response', String(error?.message || error).slice(0, 600));
+ } catch {}
+ }
+
+ _grantSocialPublicationAuditRetry(tabId, binding) {
+ const liveGuard = this._planExecutionGuards.get(tabId);
+ const carried = this._continuationExecutionEvidence.get(tabId);
+ // Settled runs release the live guard. The app-owned continuation snapshot
+ // retains the publication binding for the user's later recovery choice.
+ const guard = liveGuard || (carried?.requestKind === 'execute'
+ && carried.conversationId === (this.conversationIds.get(tabId) || null) ? carried : null);
+ const social = guard?.socialPublication;
+ const action = this._socialPublicationAction(guard);
+ if (!(liveGuard ? guard?.enabled : guard?.requestKind === 'execute') || guard.taskKey !== binding?.taskKey
+ || this._hasPendingSteering(tabId)
+ || !social || social.needsRecompile || !action || !binding?.publicationKey
+ || social.deniedAuditKey !== binding.publicationKey
+ || !publicationProgress(social.contract, social.outcomes).eligible.includes(action.id)
+ || social.retryBypassUsed?.[binding.publicationKey] || social.retryBypass) return false;
+ social.retryBypass = { key: binding.publicationKey, taskKey: guard.taskKey,
+ contractKey: social.key, actionId: action.id, consumed: false };
+ social.retryAuthorizationTaskKey = this._progressTaskKeyHash(tabId);
+ social.retryAuthorizationTaskSignature = this._sha256TextSync(this._progressTaskAnchorText(tabId));
+ if (liveGuard) this._storeContinuationExecutionEvidence(tabId);
+ return true;
+ }
+
+ _revokeSocialPublicationAuditRetry(tabId) {
+ let revoked = false;
+ const states = new Set([
+ this._planExecutionGuards.get(tabId)?.socialPublication,
+ this._continuationExecutionEvidence.get(tabId)?.socialPublication,
+ ]);
+ for (const social of states) {
+ if (!social?.retryBypass || social.retryBypass.consumed) continue;
+ const key = social.retryBypass.key;
+ social.retryBypass = null;
+ delete social.retryAuthorizationTaskKey;
+ delete social.retryAuthorizationTaskSignature;
+ if (social.dispatch?.auditBypassed && social.dispatch.key === key
+ && !social.outcomes?.[social.dispatch.actionId]) social.dispatch = null;
+ revoked = true;
+ }
+ return revoked;
+ }
+
+ _consumeSocialPublicationAuditRetry(tabId) {
+ const social = this._planExecutionGuards.get(tabId)?.socialPublication;
+ if (!social?.dispatch?.auditBypassed || !social.retryBypass
+ || social.retryBypass.key !== social.dispatch.key || social.retryBypass.consumed) return;
+ social.retryBypass.consumed = true;
+ (social.retryBypassUsed ||= {})[social.retryBypass.key] = true;
+ }
+
+ _continuedSocialPublicationState(social, retryTaskKey = null) {
+ if (!social) return null;
+ const next = structuredClone(social);
+ if (retryTaskKey && next.retryBypass && !next.retryBypass.consumed) {
+ next.retryBypass.taskKey = retryTaskKey;
+ }
+ // Ordinary trusted Continue can repair a technical outage on a new run.
+ // A semantic denial and an explicit one-use Retry grant keep their binding.
+ if (!next.retryBypass && !next.dispatch
+ && ['invalid_response', 'unavailable'].includes(next.deniedAudit?.status)) {
+ delete next.deniedAudit;
+ delete next.deniedAuditKey;
+ }
+ return next;
+ }
+
async _ensureSocialPublicationContract(tabId, provider = this._activeProvider(tabId)) {
const guard = this._planExecutionGuards.get(tabId);
if (!guard?.enabled) return null;
@@ -18715,14 +18988,25 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return state;
}
const messages = publicationContractMessages(sources, context);
+ let portable = false;
for (let attempt = 0; attempt < 2; attempt++) {
+ const requestMessages = attempt ? this._socialPublicationRepairMessages(messages) : messages;
+ const options = this._socialPublicationChatOptions(provider, attempt > 0, portable);
+ const runId = this.currentRunId.get(tabId);
+ const startedAt = Date.now();
+ let received = false;
try {
- const response = await this._chatWithCostAllowance(provider, messages, {
- temperature: 0, maxTokens: Math.min(4096, this._providerMaxOutputTokens(provider)),
- }, this.currentCostState.get(tabId) || null, { tabId, generationName: 'social_publication_contract' });
+ await this._tracePlannerAttemptRequest(runId, 0, provider, requestMessages,
+ 'social_publication_contract', attempt + 1, this._effectiveRunMode(tabId), options);
+ const response = await this._chatWithCostAllowance(provider, requestMessages, options,
+ this.currentCostState.get(tabId) || null, { tabId, generationName: 'social_publication_contract' });
+ received = true;
+ await this._tracePlannerAttemptResponse(runId, 0, provider, response,
+ 'social_publication_contract', attempt + 1, startedAt, options);
if (this._planExecutionGuards.get(tabId) !== guard || this._checkAbort(tabId)) return null;
if (guard.socialPublication !== state || state.needsRecompile) return this._ensureSocialPublicationContract(tabId, provider);
- state.contract = normalizePublicationContract(Agent._extractFirstJsonObject(response?.content || ''), sources);
+ if (this._hasPendingSteering(tabId)) return null;
+ state.contract = normalizePublicationContract(this._socialPublicationResponseObject(response, options), sources);
// A clarification invalidates authorization, not the uploads already
// bound to an unchanged, unattempted action. Preserve its binding only
// when all normalized action constraints match (IDs may be regenerated).
@@ -18736,8 +19020,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return state;
} catch (error) {
if (this._isCostAllowanceError(error) || this._checkAbort(tabId)) throw error;
- state.error = 'Publication intent is incomplete or ambiguous. Clarify the request before publishing.';
- if (attempt === 0) messages.push({ role: 'user', content: 'The contract failed strict validation. Return a complete valid object using only the documented schema and exact unique source anchors. If any requirement cannot be represented, return status=clarify with no actions. Do not guess.' });
+ await this._socialPublicationCheckerFailure(tabId, 'social_publication_contract', attempt + 1, error, received);
+ if (this._planExecutionGuards.get(tabId) !== guard || guard.socialPublication !== state
+ || state.needsRecompile || this._hasPendingSteering(tabId)) return null;
+ state.error = 'Failed while reading the publication request. The checker could not return a complete result; the draft was not published.';
+ state.errorKind = 'technical';
+ if (this._socialPublicationOptionsRejected(error)) portable = true;
}
}
return state;
@@ -18954,41 +19242,102 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
+ '. Resolve publicationValidation before retrying. For body_mismatch, use the exact contract body; preserve every space and line break. A pending text write must first be verified or restored.'),
publicationValidation: { issues } };
}
- const key = this._sha256TextSync(JSON.stringify({ contract: social.key, action, snapshot, pageUrl }));
- if (social.deniedAuditKey === key) return blocked('This unchanged publication did not pass authorization. Use publicationAudit to resolve the stated issue through clarify; do not rewrite a matching draft or retry another click target.');
+ const documentIdentity = detected.frameDocumentIdentity || '';
+ const frameId = Number.isInteger(detected.frameId) ? detected.frameId : 0;
+ const taskKey = guard.taskKey;
+ const key = this._sha256TextSync(JSON.stringify({ contract: social.key, action, snapshot, pageUrl, documentIdentity, frameId }));
+ const auditBlocked = () => {
+ const denied = social.deniedAudit?.status === 'denied';
+ const message = denied
+ ? 'Failed during the publication check: ' + (social.deniedAudit.reason || 'The checker could not confirm this post matches your request.') + ' Your draft was not published.'
+ : 'Failed during the publication check. The checker could not return a valid result, so your draft was not published.';
+ return { ...blocked(message), failureRecovery: {
+ stage: 'publication_audit', code: denied ? 'publication_audit_denied' : 'publication_audit_unavailable',
+ taskKey: guard.taskKey, publicationKey: key, message,
+ retryMode: 'publication_audit_bypass', retryDescription: 'Retry this unchanged draft without the publication audit.',
+ diagnostics: social.deniedAudit?.validationFailure || social.deniedAudit?.reason || '',
+ } };
+ };
+ const bypass = social.retryBypass;
+ const bypassMatches = bypass?.key === key && bypass.taskKey === guard.taskKey
+ && bypass.contractKey === social.key && bypass.actionId === action.id;
+ if (bypass && !bypassMatches) {
+ social.retryBypass = null;
+ return blocked('The draft, account, or page changed after Retry. Read the current draft and run a new publication check.');
+ }
+ if (bypassMatches && (bypass.consumed || social.retryBypassUsed?.[key])) {
+ return blocked('This publication Retry was already used. Verify the previous attempt before trying to publish again.');
+ }
+ if (social.deniedAuditKey === key && !bypassMatches) return auditBlocked();
if (social.dispatch?.key !== key) {
- try {
- const response = await this._chatWithCostAllowance(provider || this._activeProvider(tabId),
- publicationAuditMessages(social.sources, social.contract, action, snapshot, key, social.context), {
- temperature: 0, maxTokens: 800,
- }, this.currentCostState.get(tabId) || null, { tabId, generationName: 'social_publication_authorization' });
- if (this._planExecutionGuards.get(tabId) !== guard || guard.socialPublication !== social
- || social.needsRecompile || this._checkAbort(tabId)) {
- return blocked('Publication context changed during authorization.');
- }
- const audit = Agent._extractFirstJsonObject(response?.content || '');
- if (!publicationAuditAccepted(audit, key, action.id)) {
- social.deniedAuditKey = key;
- const validDenial = audit?.authorized === false && publicationAuditAccepted({ ...audit, authorized: true }, key, action.id);
- social.deniedAudit = validDenial
- ? { status: 'denied', reason: audit.reason }
- : { status: 'invalid_response', reason: 'The publication checker returned an invalid or mismatched authorization response.' };
- return blocked('The selected provider could not confirm this publication. Use publicationAudit to resolve the stated issue through clarify; do not rewrite a matching draft or retry another click target.');
+ if (!bypassMatches) {
+ const auditProvider = provider || this._activeProvider(tabId);
+ const messages = publicationAuditMessages(social.sources, social.contract, action, snapshot, key, social.context);
+ let portable = false;
+ let authorized = false;
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const requestMessages = attempt ? this._socialPublicationRepairMessages(messages) : messages;
+ const options = this._socialPublicationChatOptions(auditProvider, attempt > 0, portable, true);
+ const runId = this.currentRunId.get(tabId);
+ const startedAt = Date.now();
+ let received = false;
+ try {
+ await this._tracePlannerAttemptRequest(runId, 0, auditProvider, requestMessages,
+ 'social_publication_authorization', attempt + 1, this._effectiveRunMode(tabId), options);
+ const response = await this._chatWithCostAllowance(auditProvider, requestMessages, options,
+ this.currentCostState.get(tabId) || null, { tabId, generationName: 'social_publication_authorization' });
+ received = true;
+ await this._tracePlannerAttemptResponse(runId, 0, auditProvider, response,
+ 'social_publication_authorization', attempt + 1, startedAt, options);
+ if (this._planExecutionGuards.get(tabId) !== guard || guard.socialPublication !== social
+ || social.needsRecompile || this._checkAbort(tabId) || this._hasPendingSteering(tabId)
+ || guard.taskKey !== taskKey) {
+ return blocked('Publication context changed during authorization.');
+ }
+ const verdict = publicationAuditValidation(this._socialPublicationResponseObject(response, options), key, action.id);
+ if (!verdict.valid) throw new Error(verdict.failure);
+ if (!verdict.authorized) {
+ social.deniedAuditKey = key;
+ social.deniedAudit = { status: 'denied', reason: verdict.reason };
+ return auditBlocked();
+ }
+ authorized = true;
+ delete social.deniedAudit;
+ delete social.deniedAuditKey;
+ break;
+ } catch (error) {
+ if (this._isCostAllowanceError(error) || this._checkAbort(tabId)) throw error;
+ await this._socialPublicationCheckerFailure(tabId, 'social_publication_authorization', attempt + 1, error, received);
+ if (this._planExecutionGuards.get(tabId) !== guard || guard.socialPublication !== social
+ || social.needsRecompile || this._hasPendingSteering(tabId)
+ || guard.taskKey !== taskKey) {
+ return blocked('Publication context changed during authorization.');
+ }
+ social.deniedAuditKey = key;
+ social.deniedAudit = { status: received ? 'invalid_response' : 'unavailable',
+ reason: received ? 'The publication checker returned an invalid or mismatched authorization response.'
+ : 'The selected provider could not complete the publication check.',
+ validationFailure: String(error?.message || error).slice(0, 600) };
+ if (this._socialPublicationOptionsRejected(error)) portable = true;
+ }
}
- } catch (error) {
- if (this._isCostAllowanceError(error) || this._checkAbort(tabId)) throw error;
- return blocked('Publication authorization could not be verified with the selected provider.');
+ if (!authorized) return auditBlocked();
}
- social.dispatch = { key, actionId: action.id, snapshot: JSON.parse(JSON.stringify(snapshot)), pageUrl };
+ social.dispatch = { key, actionId: action.id, snapshot: JSON.parse(JSON.stringify(snapshot)), pageUrl,
+ documentIdentity, frameId, ...(bypassMatches ? { auditBypassed: true } : {}) };
}
// The semantic check can take time. Re-read the same target afterward;
// neither a changed draft/account nor a navigated document inherits it.
const fresh = await this._detectLikelySubmitAction(tabId, name, args);
if (this._planExecutionGuards.get(tabId) !== guard || guard.socialPublication !== social || social.needsRecompile
+ || this._checkAbort(tabId) || this._hasPendingSteering(tabId) || guard.taskKey !== taskKey
|| fresh?.isSubmit !== true || fresh.publicationControl !== true || fresh.publicationResourceUrlsComplete !== true
+ || (fresh.frameDocumentIdentity || '') !== documentIdentity
+ || (Number.isInteger(fresh.frameId) ? fresh.frameId : 0) !== frameId
|| JSON.stringify(this._socialPublicationSnapshot(guard, fresh.publicationSnapshot)) !== JSON.stringify(snapshot)
|| this._normalizeUrl(await this._currentUrl(tabId)) !== this._normalizeUrl(pageUrl)) {
social.dispatch = null;
+ if (bypassMatches) social.retryBypass = null;
return blocked('The composer or publication target changed during verification. Read the current draft before trying again.');
}
Object.assign(detected, fresh);
@@ -20013,6 +20362,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
}
if (!gate.proceed) {
+ if (gate.failureRecovery || gate.requestKind === 'failed') {
+ this._offerFailureRecovery(tabId, gate.failureRecovery || {
+ stage: 'plan_alignment', code: gate.reason || 'planning_failed',
+ message: gate.message || 'Failed during planning. No actions were started.',
+ }, onUpdate);
+ }
messages.push(this._plannerTerminalAssistantMessage(
gate, tabInfo, this._progressTaskAnchorText(tabId), this._progressTaskKeyHash(tabId),
));
@@ -20098,13 +20453,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
_plannerChatOptions(provider, retry = false, intentOnly = false, schemaKind = null, portable = false) {
- const plannerBudget = intentOnly ? 2048 : 4096;
+ const kind = schemaKind || (intentOnly ? 'intent' : 'planner');
+ const plannerBudget = kind === 'alignment' ? (retry ? 4096 : 2048) : (intentOnly ? 2048 : 4096);
const opts = {
temperature: retry ? 0.1 : 0.3,
maxTokens: Math.min(this._providerMaxOutputTokens(provider), plannerBudget),
};
if (!portable) {
- const kind = schemaKind || (intentOnly ? 'intent' : 'planner');
const schema = kind === 'alignment'
? PLANNER_ALIGNMENT_RESPONSE_JSON_SCHEMA
: kind === 'read_scope'
@@ -20120,7 +20475,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const extraBody = plannerRequestBody(plannerConfig, {
schema,
schemaName: `webbrain_${kind}`,
- includeResponseFormat: !retry,
+ includeResponseFormat: kind === 'alignment' || !retry,
disableThinking: true,
});
if (Object.keys(extraBody).length) opts.extraBody = extraBody;
@@ -20135,7 +20490,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return resolveMaxOutputTokens(config, fallback);
}
- async _tracePlannerAttemptRequest(runId, step, provider, messages, phase, attempt, runtimeMode) {
+ async _tracePlannerAttemptRequest(runId, step, provider, messages, phase, attempt, runtimeMode, chatOptions = {}) {
if (!runId) return;
try {
await trace.recordLLMRequest(runId, step, {
@@ -20146,6 +20501,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
...Agent._traceMediaCounts(messages),
phase,
attempt,
+ ...(Number.isFinite(chatOptions.maxTokens) ? { requestedMaxTokens: chatOptions.maxTokens } : {}),
+ ...(chatOptions.extraBody ? { requestControls: Object.keys(chatOptions.extraBody) } : {}),
...(attempt > 1 ? { repair: true } : {}),
}, {
messages,
@@ -20155,7 +20512,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
} catch {}
}
- async _tracePlannerAttemptResponse(runId, step, provider, result, phase, attempt, startedAt) {
+ async _tracePlannerAttemptResponse(runId, step, provider, result, phase, attempt, startedAt, chatOptions = {}) {
if (!runId) return;
try {
await trace.recordLLMResponse(runId, step, {
@@ -20166,12 +20523,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
model: provider?.model,
phase,
attempt,
+ ...modelOutputDiagnostics(result, { requestedMaxTokens: chatOptions.maxTokens, recoveryAttempt: attempt - 1 }),
...(attempt > 1 ? { repair: true } : {}),
});
} catch {}
}
- async _tracePlannerAttemptFailure(runId, phase, attempt, error) {
+ async _tracePlannerAttemptFailure(runId, phase, attempt, error, code = 'planner_request_failed') {
if (!runId) return;
try {
const detail = sanitizePlannerText(
@@ -20183,7 +20541,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
phase,
attempt,
failureKind: plannerRequestFailureKind(detail),
+ detail,
+ code,
});
+ await trace.recordError(runId, 0, phase, detail, code);
} catch {}
}
@@ -21264,12 +21625,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
let alignmentReplanned = false;
if (historyDigest || followUpContext.priorUserTask || followUpContext.scratchpadFacts) {
let aligned = false;
+ let alignmentFailure = null;
+ let alignmentDenialReason = '';
+ let alignmentRequestAttempt = 0;
try {
- for (let alignmentAttempt = 1; alignmentAttempt <= 2; alignmentAttempt += 1) {
+ for (let candidateAttempt = 1; candidateAttempt <= 2; candidateAttempt += 1) {
if (this._checkAbort(tabId)) return { proceed: false, message: '[Stopped by user]' };
if (this._hasPendingSteering(tabId) || this._steeringGateSuperseded(tabId, runOptions)) {
return { proceed: false, steeringSuperseded: true };
}
+ // Freeze this candidate and its authority for format recovery. A
+ // checker protocol error never requests a different execution plan.
const taskBinding = `plan_alignment_${secureRandomBase36Token(24)}`;
const alignmentMessages = buildPlannerAlignmentMessages(followUpContext.authenticTaskText || this._plannerUserAuthoredText(enriched), plan, {
taskBinding, historyDigest,
@@ -21277,42 +21643,97 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
scratchpadFacts: followUpContext.scratchpadFacts,
independentTask: runOptions?.independentRun === true,
});
- await this._tracePlannerAttemptRequest(
- runId, plannerStep, provider, alignmentMessages, 'planner_alignment', alignmentAttempt, runtimeMode,
- );
- const alignmentStartedAt = Date.now();
- plannerRequestInFlight = true;
- const alignmentResult = await this._chatWithCostAllowance(
- provider, alignmentMessages,
- { ...this._plannerChatOptions(provider, false, false, 'alignment'), temperature: 0,
- maxTokens: Math.min(this._providerMaxOutputTokens(provider), 256) },
- costState, { tabId, generationName: 'planner_alignment' },
- );
- plannerRequestInFlight = false;
- await this._tracePlannerAttemptResponse(
- runId, plannerStep, provider, alignmentResult, 'planner_alignment', alignmentAttempt, alignmentStartedAt,
- );
- if (this._checkAbort(tabId)) return { proceed: false, message: '[Stopped by user]' };
- if (this._hasPendingSteering(tabId) || this._steeringGateSuperseded(tabId, runOptions)) {
- return { proceed: false, steeringSuperseded: true };
+ let verdict = null;
+ let portable = false;
+ for (let checkerAttempt = 1; checkerAttempt <= 2; checkerAttempt += 1) {
+ if (this._checkAbort(tabId)) return { proceed: false, message: '[Stopped by user]' };
+ if (this._hasPendingSteering(tabId) || this._steeringGateSuperseded(tabId, runOptions)) {
+ return { proceed: false, steeringSuperseded: true };
+ }
+ const requestMessages = checkerAttempt === 1 ? alignmentMessages
+ : this._plannerProtocolRepairMessages(alignmentMessages,
+ 'Format recovery: the previous checker response did not contain a complete valid verdict. ' +
+ 'Check the unchanged current_request and proposed_plan below. Copy task_binding exactly. ' +
+ 'Return only one JSON object with task_binding, boolean aligned, and a brief nonempty reason. ' +
+ 'Do not output prose, tool calls, or reasoning text.');
+ const chatOptions = { ...this._plannerChatOptions(provider, checkerAttempt > 1, false, 'alignment', portable),
+ temperature: 0 };
+ alignmentRequestAttempt += 1;
+ await this._tracePlannerAttemptRequest(
+ runId, plannerStep, provider, requestMessages, 'planner_alignment', alignmentRequestAttempt, runtimeMode, chatOptions,
+ );
+ const alignmentStartedAt = Date.now();
+ let alignmentResult;
+ try {
+ plannerRequestInFlight = true;
+ alignmentResult = await this._chatWithCostAllowance(
+ provider, requestMessages, chatOptions,
+ costState, { tabId, generationName: 'planner_alignment' },
+ );
+ } catch (error) {
+ if (this._isCostAllowanceError(error)) throw error;
+ if (this._checkAbort(tabId)) return { proceed: false, message: '[Stopped by user]' };
+ if (this._hasPendingSteering(tabId) || this._steeringGateSuperseded(tabId, runOptions)) {
+ return { proceed: false, steeringSuperseded: true };
+ }
+ await this._tracePlannerAttemptFailure(runId, 'planner_alignment', alignmentRequestAttempt, error);
+ alignmentFailure = 'request_failed';
+ const detail = formatErrorMessage(error, { fallback: '' });
+ const controlsRejected = chatOptions.extraBody && Object.keys(chatOptions.extraBody).length > 0
+ && /unsupported|not supported|unrecognized|unknown|not allowed|invalid (?:parameter|argument)/i.test(detail)
+ && /response_format|json_schema|reasoning|thinking|chat_template_kwargs/i.test(detail);
+ if (checkerAttempt === 1 && controlsRejected) {
+ portable = true;
+ continue;
+ }
+ break;
+ } finally {
+ plannerRequestInFlight = false;
+ }
+ await this._tracePlannerAttemptResponse(
+ runId, plannerStep, provider, alignmentResult, 'planner_alignment', alignmentRequestAttempt, alignmentStartedAt, chatOptions,
+ );
+ if (this._checkAbort(tabId)) return { proceed: false, message: '[Stopped by user]' };
+ if (this._hasPendingSteering(tabId) || this._steeringGateSuperseded(tabId, runOptions)) {
+ return { proceed: false, steeringSuperseded: true };
+ }
+ const inspection = inspectPlannerAlignmentContent(alignmentResult.content, taskBinding);
+ const diagnostics = modelOutputDiagnostics(alignmentResult, { requestedMaxTokens: chatOptions.maxTokens });
+ const truncated = /^(?:length|max_tokens|max_output_tokens|output_limit)$/i.test(diagnostics.finishReason || '');
+ verdict = truncated ? null : inspection.verdict;
+ alignmentFailure = verdict ? null : (diagnostics.emptyReason || (truncated ? 'truncated_response' : inspection.failure));
+ if (verdict) break;
+ try {
+ if (runId) await trace.recordNote(runId, plannerStep, 'planner_alignment_validation_failed', {
+ attempt: alignmentRequestAttempt, candidateAttempt, validationFailure: alignmentFailure,
+ });
+ } catch {}
+ await this._tracePlannerAttemptFailure(runId, 'planner_alignment', alignmentRequestAttempt,
+ new Error(`Plan alignment checker returned an invalid verdict (${alignmentFailure}).`),
+ 'planner_alignment_invalid_response');
+ if (checkerAttempt === 1) {
+ onUpdate('thinking', { step: plannerStep, note: 'Planning… retrying the plan check' });
+ }
}
- const verdict = parsePlannerAlignmentFromContent(alignmentResult.content, taskBinding);
+ if (!verdict) break;
if (verdict?.aligned === true) { aligned = true; break; }
- if (alignmentAttempt === 2) break;
+ alignmentDenialReason = verdict.reason;
+ if (candidateAttempt === 2) break;
const alignmentRepairMessages = buildPlannerAlignmentRepairMessages(plannerMessages);
onUpdate('thinking', { step: plannerStep, note: 'Planning… rechecking the current task' });
+ const repairOptions = this._plannerChatOptions(provider, true);
await this._tracePlannerAttemptRequest(
- runId, plannerStep, provider, alignmentRepairMessages, 'planner_alignment_repair', 1, runtimeMode,
+ runId, plannerStep, provider, alignmentRepairMessages, 'planner_alignment_repair', 1, runtimeMode, repairOptions,
);
const alignmentRepairStartedAt = Date.now();
plannerRequestInFlight = true;
const repaired = await this._chatWithCostAllowance(
- provider, alignmentRepairMessages, this._plannerChatOptions(provider, true),
+ provider, alignmentRepairMessages, repairOptions,
costState, { tabId, generationName: 'planner' },
);
plannerRequestInFlight = false;
await this._tracePlannerAttemptResponse(
- runId, plannerStep, provider, repaired, 'planner_alignment_repair', 1, alignmentRepairStartedAt,
+ runId, plannerStep, provider, repaired, 'planner_alignment_repair', 1, alignmentRepairStartedAt, repairOptions,
);
if (this._checkAbort(tabId)) return { proceed: false, message: '[Stopped by user]' };
if (this._hasPendingSteering(tabId) || this._steeringGateSuperseded(tabId, runOptions)) {
@@ -21320,7 +21741,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
plan = parsePlanFromContent(repaired.content, plannerParseOptions);
if (!plan
- || this._plannerIntentUnresolvedConsistencyIssue(plan, consistencyRepairKind, followUpContext)) break;
+ || this._plannerIntentUnresolvedConsistencyIssue(plan, consistencyRepairKind, followUpContext)) {
+ alignmentFailure = 'invalid_replacement_plan';
+ break;
+ }
alignmentReplanned = true;
// A validated correction can remove execution entirely. Preserve
// its normal terminal route without pinning or approving a plan.
@@ -21331,15 +21755,31 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
plannerRequestInFlight = false;
if (this._isCostAllowanceError(alignmentError)) throw alignmentError;
if (this._checkAbort(tabId)) return { proceed: false, message: '[Stopped by user]' };
- await this._tracePlannerAttemptFailure(runId, 'planner_alignment', 1, alignmentError);
+ alignmentFailure = 'request_failed';
+ await this._tracePlannerAttemptFailure(runId, 'planner_alignment', alignmentRequestAttempt || 1, alignmentError);
}
if (!aligned) {
if (this._hasPendingSteering(tabId) || this._steeringGateSuperseded(tabId, runOptions)) {
return { proceed: false, steeringSuperseded: true };
}
- const message = 'The proposed plan failed alignment with your current task. No actions were started; please retry the task.';
+ const failureDescription = alignmentFailure === 'reasoning_only'
+ ? 'the checker returned reasoning without a verdict.'
+ : (alignmentFailure === 'provider_empty' || alignmentFailure === 'empty_response')
+ ? 'the checker returned no verdict.'
+ : (alignmentFailure === 'output_limit' || alignmentFailure === 'truncated_response')
+ ? 'the checker ran out of response space before returning a verdict.'
+ : alignmentFailure === 'binding_mismatch'
+ ? 'the checker returned a verdict for a different plan.'
+ : alignmentFailure === 'request_failed'
+ ? 'the checker could not complete its request to the model provider.'
+ : 'the checker returned an unreadable verdict.';
+ const reason = alignmentFailure ? 'task_alignment_unverified' : 'task_alignment_rejected';
+ const message = alignmentFailure
+ ? `Failed while checking the plan against your task: ${failureDescription} No actions were started.`
+ : `Failed while checking the plan against your task: the proposed plan did not match your request. ${alignmentDenialReason} No actions were started.`;
onUpdate('warning', { message });
- return { proceed: false, message, reason: 'task_alignment_unverified', requestKind: 'failed' };
+ return { proceed: false, message, reason, requestKind: 'failed',
+ failureRecovery: { stage: 'plan_alignment', code: reason, message } };
}
}
if (alignmentReplanned) {
@@ -21939,6 +22379,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
let finalResponse = '';
let status = 'done';
let quotaFailure = false;
+ let recoveryDetails = null;
try {
finalResponse = await this._generateContextOnlyResponse(
tabId, messages, provider, costState, runId,
@@ -21952,7 +22393,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
status = this._isCostAllowanceError(error) ? 'cost_limit' : 'error';
finalResponse = this._isCostAllowanceError(error)
? error.message
- : `I could not generate the requested response: ${formatErrorMessage(error)}`;
+ : (recoveryDetails = modelFailureRecovery(error, { phase: 'response_generation' })).message;
}
const stopped = this._consumeContextOnlyAbort(tabId, messages, onUpdate);
if (stopped) return stopped;
@@ -21961,8 +22402,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
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.';
+ finalResponse = 'Failed while generating the response. The model returned no usable text. You can retry from the current state.';
+ recoveryDetails = { stage: 'response_generation', code: 'empty_response', message: finalResponse };
}
+ if (recoveryDetails && !quotaFailure) this._offerFailureRecovery(tabId, recoveryDetails, onUpdate);
messages.push({ role: 'assistant', content: finalResponse });
onUpdate('text', { content: finalResponse, replace: true });
if (status !== 'done' && !quotaFailure) onUpdate('error', { message: finalResponse });
@@ -22013,6 +22456,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
: stopMessage;
messages.push({ role: 'assistant', content: finalResponse });
onUpdate('text', { content: finalResponse, replace: true });
+ if (runOptions?.cloudRun !== true) this._offerFailureRecovery(tabId, {
+ stage: 'browser_interaction', code: 'interaction_loop',
+ message: 'Failed during browser interaction because the same step kept repeating. Retry will continue from the current page.' }, onUpdate);
onUpdate('error', {
message: recovered
? 'Browser interaction stopped before completion; a recoverable partial result is shown above.'
@@ -24466,6 +24912,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
tool: name,
reason: String(detected.reason || 'likely form submission').slice(0, 200),
validationSubmitEvidence: detected.validationSubmitEvidence === 'strong' ? 'strong' : 'heuristic',
+ frameDocumentIdentity: String(detected.frameDocumentIdentity || '').slice(0, 8192),
...(name === 'iframe_click' ? { frameId: detected.frameId,
frameUrl: String(detected.url || '').slice(0, 8192),
frameDocumentIdentity: sameFrameDocument ? frameBaseline.identity : '',
@@ -26726,6 +27173,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
* Clear conversation for a tab.
*/
clearConversation(tabId) {
+ this._failureRecovery.clear(tabId);
this._cancelClarifications(tabId, 'conversation cleared');
this._cancelUploadPickers(tabId, 'conversation cleared');
this._cancelPendingPlans(tabId, 'conversation cleared');
@@ -30298,7 +30746,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
? this._continuationExecutionEvidence.get(tabId)
: null;
this._continuationExecutionEvidence.delete(tabId);
- const carryScopeMatches = enabled
+ const carryScopeCompatible = enabled
&& carried?.requestKind === 'execute'
&& carried.requiresStateChange === requiresStateChange
&& carried.requiresSubmission === requiresSubmission
@@ -30310,8 +30758,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
&& carried.requiredSchedulingTool === requiredSchedulingTool
&& JSON.stringify(carried.siteWorkflow || null) === JSON.stringify(siteWorkflow || null)
&& JSON.stringify(carried.conditionalSiteWorkflow || null) === JSON.stringify(gateOutcome.conditionalSiteWorkflow || null)
- && carried.taskKey === taskKey
&& carried.conversationId === (this.conversationIds.get(tabId) || null);
+ const carryScopeMatches = carryScopeCompatible && carried.taskKey === taskKey;
+ const carrySocialRetryAuthorization = carryScopeCompatible
+ && requiresSubmission === true && requiresStateChange === true
+ && carried.socialPublication?.retryAuthorizationTaskKey === taskKey
+ && carried.socialPublication.retryAuthorizationTaskSignature === this._sha256TextSync(this._progressTaskAnchorText(tabId))
+ && carried.socialPublication.retryBypass?.consumed === false
+ && !Object.keys(carried.socialPublication.outcomes || {}).length;
const carryMatches = carryScopeMatches && carried.evidenceTaskKey === taskKey;
// Human recipient grants are task authorization, not execution evidence.
// They can survive Continue even when the last step only approved a send.
@@ -30370,10 +30824,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
? (carried.successfulRequiredSchedulingToolCalls || 0)
: 0,
verifiedSubmissionEvidence: carryMatches && carried.verifiedSubmissionEvidence === true,
- socialPublication: carryMatches && carried.socialPublication ? structuredClone(carried.socialPublication) : null,
- socialPublicationClarifications: carryMatches && carried.socialPublicationClarifications
+ // Frozen publication intent and human Retry grants are authorization,
+ // independent of whether this run produced successful execution evidence.
+ socialPublication: carryScopeMatches || carrySocialRetryAuthorization
+ ? this._continuedSocialPublicationState(carried.socialPublication, carrySocialRetryAuthorization ? taskKey : null) : null,
+ socialPublicationClarifications: (carryScopeMatches || carrySocialRetryAuthorization) && carried.socialPublicationClarifications
? structuredClone(carried.socialPublicationClarifications) : [],
- socialPublicationSteering: carryMatches && carried.socialPublicationSteering
+ socialPublicationSteering: (carryScopeMatches || carrySocialRetryAuthorization) && carried.socialPublicationSteering
? structuredClone(carried.socialPublicationSteering) : null,
socialPublishSatisfiedTargets: carryMatches && Array.isArray(carried.socialPublishSatisfiedTargets)
? [...carried.socialPublishSatisfiedTargets]
@@ -30819,6 +31276,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
&& (guard.messageRecipientApprovedAll === true || (guard.approvedRecipients || []).length > 0);
if (guard?.enabled && !guard.taskDrifted && (
hasRecipientAuthorization
+ || guard.socialPublication?.contract?.status === 'ready'
|| guard.successfulTaskToolCalls > 0
|| guard.successfulConsequentialToolCalls > 0
|| guard.pendingDownloadIds.length > 0
@@ -39271,9 +39729,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
...this._interactiveAskStreamingFailure(error),
});
if (this._isCostAllowanceError(error)) throw error;
- if (emittedText) onUpdate('text', { content: '', replace: true });
- if (!fallbackSafe) throw error;
+ if (!fallbackSafe) {
+ if (emittedText) onUpdate('text', { content: '', replace: true });
+ throw error;
+ }
askStreamingDisabledForRun = true;
+ // A transport interruption does not invalidate already delivered
+ // prose. Keep it visibly incomplete while regenerating this same
+ // source-grounded turn; explicit invalid-response resets still clear.
+ onUpdate('response_retry', { reason: 'stream_interrupted', retainPartial: emittedText });
onUpdate('warning', {
code: 'ask_stream_fallback',
message: 'Response streaming was interrupted; retrying this Ask turn without streaming.',
@@ -39569,8 +40033,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
traceFailureCode = retryCode;
_traceStatus = 'error';
if (runId) trace.recordStepEnd(runId, steps, { ok: false, code: retryCode });
- onUpdate('error', { message: `Context still too large after trimming: ${e2.message}` });
finalResponse = 'The conversation got too long. Please start a new conversation (click the + button).';
+ this._offerFailureRecovery(tabId, { stage: 'model', code: 'context_window_exceeded',
+ message: 'Failed while preparing the model context. The conversation is too large. Retry will use the current trimmed context.',
+ diagnostics: e2.message }, onUpdate);
+ onUpdate('error', { message: finalResponse });
messages.push({ role: 'assistant', content: finalResponse });
break;
}
@@ -39579,8 +40046,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
traceFailureCode = this._traceErrorCodeFor(e);
_traceStatus = 'error';
if (runId) trace.recordStepEnd(runId, steps, { ok: false, code: traceFailureCode });
- onUpdate('error', { message: e.message });
- finalResponse = `Error communicating with LLM: ${e.message}`;
+ const recovery = await this._finalModelFailure(tabId, messages, onUpdate, provider, e, steps, runOptions);
+ _traceStatus = recovery.status;
+ finalResponse = recovery.content;
messages.push({ role: 'assistant', content: finalResponse });
break;
}
@@ -39619,8 +40087,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
traceFailureCode = this._traceErrorCodeFor(e2);
_traceStatus = 'error';
if (runId) trace.recordStepEnd(runId, steps, { ok: false, code: traceFailureCode });
- onUpdate('error', { message: e2.message });
- finalResponse = `Error communicating with LLM: ${e2.message}`;
+ const recovery = await this._finalModelFailure(tabId, messages, onUpdate, provider, e2, steps, runOptions);
+ _traceStatus = recovery.status;
+ finalResponse = recovery.content;
messages.push({ role: 'assistant', content: finalResponse });
break;
}
@@ -39847,6 +40316,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}));
_traceStatus = 'empty_output';
traceFailureCode = 'EMPTY_RESPONSE';
+ 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);
messages.push({ role: 'assistant', content: finalResponse });
onUpdate('warning', { message: finalResponse });
break;
@@ -40633,7 +41105,24 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
let costStopMessage = '';
this._throwIfAborted(streamOpts.signal);
- for await (const chunk of (fastResult ? this._jevToolStream(fastResult) : provider.chatStream(prunedMessages, streamOpts))) {
+ let streamAttempt = 0;
+ const modelStream = fastResult ? this._jevToolStream(fastResult) : retryModelStream(async () => {
+ streamAttempt++;
+ if (streamAttempt > 1 && runId) await trace.recordLLMRequest(runId, steps, {
+ providerClass: provider.constructor.name, model: provider.model,
+ messageCount: prunedMessages.length, toolsCount: (streamOpts.tools || []).length,
+ requestedMaxTokens: streamOpts.maxTokens, recoveryAttempt: streamAttempt - 1,
+ ...Agent._traceMediaCounts(prunedMessages),
+ }, { messages: prunedMessages, tools: streamOpts.tools || [], runtimeMode: mode });
+ return provider.chatStream(prunedMessages, streamOpts);
+ }, {
+ isAborted: () => this._checkAbort(tabId),
+ onRetry: async ({ error, delayMs, attempt }) => {
+ onUpdate('thinking', { step: steps, note: `The model service could not start the response. Retrying (${attempt})…` });
+ if (runId) await trace.recordLLMRetry(runId, steps, { delayMs, code: this._traceErrorCodeFor(error) });
+ },
+ });
+ for await (const chunk of modelStream) {
this._throwIfAborted(streamOpts.signal);
if (chunk.type === 'text') {
streamEmittedOutput = true;
@@ -40876,6 +41365,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return finish(scheduledResume.message, 'scheduled_resume');
}
const failMsg = emptyOutputFailureMessage(outputDiagnostics);
+ 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);
messages.push({ role: 'assistant', content: failMsg });
onUpdate('warning', { message: failMsg });
this._persist(tabId);
@@ -41098,12 +41590,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (runId) await trace.recordLLMRetry(runId, steps, { delayMs: 0, code: 'CONTEXT_WINDOW_EXCEEDED' });
continue; // retry the loop with trimmed context
}
- onUpdate('error', { message: caughtMessage });
- const errMsg = `Error: ${caughtMessage}`;
+ const recovery = await this._finalModelFailure(tabId, messages, onUpdate, provider, e, steps, runOptions);
+ const errMsg = recovery.content;
messages.push({ role: 'assistant', content: errMsg });
this._persist(tabId);
traceFailureCode = stepErrorCode;
- return finish(errMsg, 'error');
+ return finish(errMsg, recovery.status);
}
}
diff --git a/src/firefox/src/agent/failure-recovery.js b/src/firefox/src/agent/failure-recovery.js
new file mode 100644
index 000000000..820a6f479
--- /dev/null
+++ b/src/firefox/src/agent/failure-recovery.js
@@ -0,0 +1,34 @@
+// Recovery choices come from the extension UI, never from a model tool call.
+export class FailureRecoveryRegistry {
+ constructor() { this.offers = new Map(); }
+
+ offer(binding, descriptor) {
+ const offer = { binding: { ...binding }, descriptor: { ...descriptor } };
+ this.offers.set(binding.tabId, offer);
+ return { ...offer.descriptor };
+ }
+
+ current(binding) {
+ const offer = this.offers.get(binding.tabId);
+ if (!offer) return null;
+ if (offer.binding.conversationId !== binding.conversationId || offer.binding.taskKey !== binding.taskKey
+ || offer.binding.taskSignature !== binding.taskSignature) {
+ this.offers.delete(binding.tabId);
+ return null;
+ }
+ return offer;
+ }
+
+ clear(tabId) { this.offers.delete(tabId); }
+}
+
+export function modelFailureRecovery(error, { postAction = false, phase = 'model' } = {}) {
+ const code = String(error?.code || 'model_request_failed');
+ const stage = postAction ? 'completion_verification' : phase;
+ const message = postAction
+ ? 'Failed during final verification. The action may have completed. Review the current result before choosing Retry.'
+ : code === 'webbrain_cloud_upstream_error'
+ ? 'Failed while contacting WebBrain Cloud. The model service could not finish this request. You can retry from the current state.'
+ : 'Failed while requesting the model response. You can retry from the current state.';
+ return { stage, code, message, retryMode: 'resume', diagnostics: String(error?.message || error || '').slice(0,6000) };
+}
diff --git a/src/firefox/src/agent/planner.js b/src/firefox/src/agent/planner.js
index 71c5db249..e21a2a099 100644
--- a/src/firefox/src/agent/planner.js
+++ b/src/firefox/src/agent/planner.js
@@ -890,18 +890,27 @@ export function buildPlannerAlignmentMessages(authenticTaskText, plan, opts = {}
}
export function parsePlannerAlignmentFromContent(content, expectedTaskBinding) {
+ return inspectPlannerAlignmentContent(content, expectedTaskBinding).verdict;
+}
+
+export function inspectPlannerAlignmentContent(content, expectedTaskBinding) {
+ if (typeof content !== 'string' || !content.trim()) return { verdict: null, failure: 'empty_response' };
const verdict = extractFirstJsonObject(content);
- if (!verdict || typeof verdict !== 'object' || Array.isArray(verdict)
- || typeof expectedTaskBinding !== 'string' || !expectedTaskBinding
- || verdict.task_binding !== expectedTaskBinding
- || typeof verdict.aligned !== 'boolean'
- || typeof verdict.reason !== 'string' || !verdict.reason.trim()
- || Object.keys(verdict).some(key => !['task_binding', 'aligned', 'reason'].includes(key))) return null;
- return {
+ if (!verdict || typeof verdict !== 'object' || Array.isArray(verdict)) {
+ return { verdict: null, failure: 'invalid_json' };
+ }
+ if (typeof expectedTaskBinding !== 'string' || !expectedTaskBinding
+ || verdict.task_binding !== expectedTaskBinding) return { verdict: null, failure: 'binding_mismatch' };
+ if (typeof verdict.aligned !== 'boolean') return { verdict: null, failure: 'invalid_aligned' };
+ if (typeof verdict.reason !== 'string' || !verdict.reason.trim()) return { verdict: null, failure: 'invalid_reason' };
+ if (Object.keys(verdict).some(key => !['task_binding', 'aligned', 'reason'].includes(key))) {
+ return { verdict: null, failure: 'unexpected_fields' };
+ }
+ return { verdict: {
task_binding: verdict.task_binding,
aligned: verdict.aligned,
reason: sanitizeText(verdict.reason, 500),
- };
+ }, failure: null };
}
export function buildPlannerAlignmentRepairMessages(messages) {
diff --git a/src/firefox/src/agent/social-publish-contract.js b/src/firefox/src/agent/social-publish-contract.js
index c20aacbf0..77ff4e665 100644
--- a/src/firefox/src/agent/social-publish-contract.js
+++ b/src/firefox/src/agent/social-publish-contract.js
@@ -258,7 +258,45 @@ export function publicationAuditMessages(sources, contract, action, snapshot, ke
{ role: 'user', content: JSON.stringify({ sources, contract, action, snapshot, key, context }) }];
}
+// Parse the complete response, rather than taking the first object out of
+// prose. A second/conflicting verdict must never be silently discarded.
+export function parsePublicationJson(content) {
+ if (typeof content !== 'string' || !content.trim()) throw new Error('empty_response');
+ const text = content.trim().replace(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/i, '$1').trim();
+ let raw;
+ try { raw = JSON.parse(text); } catch { throw new Error('malformed_or_multiple_json_objects'); }
+ if (!object(raw)) throw new Error('response_not_object');
+ const tokens = text.match(/"(?:\\.|[^"\\])*"|[{}\[\]:,]/g) || [];
+ const fields = new Set();
+ let depth = 0;
+ for (let i = 0; i < tokens.length; i++) {
+ const token = tokens[i];
+ if (token === '{' || token === '[') depth++;
+ else if (token === '}' || token === ']') depth--;
+ else if (depth === 1 && token.startsWith('"') && tokens[i + 1] === ':') {
+ const field = JSON.parse(token);
+ if (fields.has(field)) throw new Error(['key', 'actionId', 'authorized', 'reason'].includes(field)
+ ? 'duplicate_' + field : 'duplicate_extra_field');
+ fields.add(field);
+ }
+ }
+ return raw;
+}
+
+export function publicationAuditValidation(raw, key, actionId) {
+ if (!object(raw)) return { valid: false, failure: 'response_not_object' };
+ for (const field of ['key', 'actionId', 'authorized', 'reason']) {
+ if (!Object.hasOwn(raw, field)) return { valid: false, failure: 'missing_' + field };
+ }
+ if (raw.key !== key) return { valid: false, failure: 'key_mismatch' };
+ if (raw.actionId !== actionId) return { valid: false, failure: 'action_mismatch' };
+ if (typeof raw.authorized !== 'boolean') return { valid: false, failure: 'authorized_not_boolean' };
+ if (typeof raw.reason !== 'string') return { valid: false, failure: 'reason_not_string' };
+ // Extra metadata and long explanations do not invalidate a bound verdict.
+ return { valid: true, authorized: raw.authorized, reason: raw.reason.slice(0, 600) };
+}
+
export function publicationAuditAccepted(raw, key, actionId) {
- return object(raw) && Object.keys(raw).length === 4 && raw.key === key && raw.actionId === actionId
- && raw.authorized === true && typeof raw.reason === 'string' && raw.reason.length <= 600;
+ const verdict = publicationAuditValidation(raw, key, actionId);
+ return verdict.valid && verdict.authorized;
}
diff --git a/src/firefox/src/background.js b/src/firefox/src/background.js
index efffdd802..259409ecd 100644
--- a/src/firefox/src/background.js
+++ b/src/firefox/src/background.js
@@ -2178,11 +2178,17 @@ function isPersistenceDegradedRunUpdate(update) {
&& update?.data?.status === 'persistence_degraded';
}
+function isPublicationAuditFailureUpdate(update) {
+ return (update?.type === 'run_status' && update?.data?.status === 'publication_audit_failed')
+ || (update?.type === 'failure_recovery' && update?.data?.stage === 'publication_audit');
+}
+
function runUpdatesSucceeded(updates = []) {
return !updates.some(update => (
update?.type === 'error' || update?.type === 'quota'
|| isClarificationRequiredRunUpdate(update)
|| isPersistenceDegradedRunUpdate(update)
+ || isPublicationAuditFailureUpdate(update)
|| isPlannerRequestFailureUpdate(update)
));
}
@@ -2195,6 +2201,7 @@ function terminalRunUiStatus(content, updates = [], error = null) {
if (/before executing requested tool calls/i.test(text)) return 'cancelled';
if (updates.some(update => update?.type === 'error'
|| isPlannerRequestFailureUpdate(update) || isPersistenceDegradedRunUpdate(update)
+ || isPublicationAuditFailureUpdate(update)
|| update?.type === 'quota')) return 'failed';
if (updates.some(isClarificationRequiredRunUpdate)) return 'clarification_required';
return 'completed';
@@ -2217,6 +2224,7 @@ function askCompletionSucceededForBadge(result, updates = [], error = null) {
if (updates.some(update => (
update?.type === 'error' || update?.type === 'quota'
|| isPersistenceDegradedRunUpdate(update)
+ || isPublicationAuditFailureUpdate(update)
|| update?.type === 'attachment_rejected'
|| update?.type === 'max_steps_reached'
|| update?.error
@@ -2574,7 +2582,35 @@ function assertChatRequestInput(msg) {
throw error;
}
+async function handleFailureRecoveryResponse(msg, sender) {
+ if (sender?.url?.split(/[?#]/)[0] !== browser.runtime.getURL('src/ui/sidepanel.html')) {
+ return { ok: false, error: 'Recovery choices are available from the chat panel only.' };
+ }
+ const tabId = Number(msg.tabId);
+ const recoveryId = typeof msg.recoveryId === 'string' ? msg.recoveryId : '';
+ const choice = msg.choice;
+ if (!Number.isSafeInteger(tabId) || tabId <= 0 || !recoveryId || !['retry', 'give_up'].includes(choice)) {
+ return { ok: false, error: 'Invalid recovery choice.' };
+ }
+ if (choice === 'retry' && typeof msg.requestId === 'string' && msg.requestId) {
+ // An acknowledgement may be lost while its run already started. Repeated
+ // delivery follows that same request rather than consuming a second offer.
+ if (detachedRunStarts.get(tabId)?.requestId === msg.requestId) {
+ return { ok: true, accepted: true, requestId: msg.requestId };
+ }
+ const snapshot = await getRunUiSnapshot(tabId);
+ if (snapshot?.requestId === msg.requestId && snapshot.kind === 'continue') {
+ return { ok: true, accepted: true, requestId: msg.requestId };
+ }
+ }
+ assertNoActiveTabRun(tabId);
+ const result = agent.requestFailureRecovery(tabId, recoveryId, choice);
+ if (!result?.ok || choice === 'give_up' || result.continue !== true) return result;
+ return launchDetachedRun('continue', msg, sender);
+}
+
async function handleMessage(msg, sender) {
+ if (msg.action === 'failure_recovery_response') return handleFailureRecoveryResponse(msg, sender);
if (['chat_start', 'chat', 'chat_stream'].includes(msg.action)) assertChatRequestInput(msg);
if (msg.action === 'get_page_monitor_state') return agent.pageMonitorState(sender, msg.documentToken, msg.frameName);
if (msg.action === 'page_feedback') return agent.observePageFeedback(sender, msg.feedback);
@@ -3288,6 +3324,7 @@ async function handleMessage(msg, sender) {
: false);
const conversationState = await agent.getConversationState(tabId);
const activeState = agent.activeRunState(tabId);
+ const pendingFailureRecovery = agent._pendingFailureRecoveryForUi?.(tabId) || null;
const pendingClarification = activeState.pendingCurrentClarification;
const currentRunUi = runUiJournal.get(tabId);
if (pendingClarification && (!activeState.running || currentRunUi !== runUiSnapshot
@@ -3303,6 +3340,7 @@ async function handleMessage(msg, sender) {
ok: true,
...conversationState,
...activeState,
+ pendingFailureRecovery,
starting: !!starting,
startingRequestId: starting?.requestId || null,
submittedTurnDurable,
diff --git a/src/firefox/src/providers/model-retry.js b/src/firefox/src/providers/model-retry.js
index fbfc68053..1e13cd515 100644
--- a/src/firefox/src/providers/model-retry.js
+++ b/src/firefox/src/providers/model-retry.js
@@ -23,7 +23,8 @@ export async function retryModelCall(initialError, call, {
},
} = {}) {
const rateLimited = initialError?.httpStatus === 429;
- const delays = rateLimited ? [5000, 15000, 30000] : [2000];
+ const cloudUpstream = initialError?.code === 'webbrain_cloud_upstream_error';
+ const delays = rateLimited ? [5000, 15000, 30000] : cloudUpstream ? [2000, 5000] : [2000];
let error = initialError, waited = 0;
for (let i = 0; i < delays.length; i++) {
cancelled(isAborted);
@@ -38,8 +39,52 @@ export async function retryModelCall(initialError, call, {
try { return await call(); }
catch (next) {
error = next;
- if (!rateLimited || error?.httpStatus !== 429) throw error;
+ if (rateLimited ? error?.httpStatus !== 429
+ : !cloudUpstream || error?.code !== 'webbrain_cloud_upstream_error') throw error;
}
}
throw error;
}
+
+/** Retry stream startup only; emitted text/tool events must never be replayed. */
+export async function* retryModelStream(createStream, options = {}) {
+ const isAborted = options.isAborted || (() => false);
+ let iterator = null;
+ const close = async () => {
+ const abandoned = iterator;
+ iterator = null;
+ try { await abandoned?.return?.(); } catch {}
+ };
+ const start = async () => {
+ try {
+ cancelled(isAborted);
+ const stream = await createStream();
+ iterator = stream[Symbol.asyncIterator]();
+ const first = await iterator.next();
+ cancelled(isAborted);
+ return first;
+ } catch (error) {
+ await close();
+ throw error;
+ }
+ };
+ try {
+ let first;
+ try { first = await start(); }
+ catch (error) {
+ if (error?.code !== 'webbrain_cloud_upstream_error' && error?.httpStatus !== 429) throw error;
+ first = await retryModelCall(error, start, options);
+ }
+ if (first.done) return;
+ yield first.value;
+ while (true) {
+ cancelled(isAborted);
+ const next = await iterator.next();
+ cancelled(isAborted);
+ if (next.done) return;
+ yield next.value;
+ }
+ } finally {
+ await close();
+ }
+}
diff --git a/src/firefox/src/run-ui-journal.js b/src/firefox/src/run-ui-journal.js
index a9152b801..0fbb47708 100644
--- a/src/firefox/src/run-ui-journal.js
+++ b/src/firefox/src/run-ui-journal.js
@@ -272,6 +272,10 @@ export class RunUiJournal {
streamedTextStartSeq: 0,
streamedTextSeq: 0,
streamedTextTruncated: false,
+ // Display-only state survives acknowledged events; incomplete prose
+ // never contributes to completion evidence or success classification.
+ responseRetry: null,
+ responseIncomplete: false,
startedAt: Date.now(),
endedAt: null,
};
@@ -300,6 +304,8 @@ export class RunUiJournal {
snapshot.successfulDone = false;
snapshot.runSucceeded = false;
snapshot.endedAt = null;
+ snapshot.responseRetry = null;
+ snapshot.responseIncomplete = false;
return this._changed(tabId, snapshot);
}
@@ -316,6 +322,11 @@ export class RunUiJournal {
snapshot.events.push(event);
if (data?.quota) snapshot.quota = structuredClone(data.quota);
if (type === 'text_delta') {
+ if (snapshot.responseRetry || snapshot.responseIncomplete) {
+ snapshot.streamedText = '';
+ snapshot.streamedTextStartSeq = 0;
+ snapshot.streamedTextTruncated = false;
+ }
const chunk = String(event.data?.content || '');
if (!snapshot.streamedText && !snapshot.streamedTextTruncated) {
snapshot.streamedTextStartSeq = event.seq;
@@ -337,6 +348,23 @@ export class RunUiJournal {
snapshot.streamedTextSeq = 0;
snapshot.streamedTextTruncated = false;
}
+ if (type === 'response_retry') {
+ snapshot.responseRetry = {
+ reason: 'stream_interrupted',
+ retainPartial: data?.retainPartial === true,
+ seq: event.seq,
+ };
+ snapshot.responseIncomplete = snapshot.responseRetry.retainPartial && !!snapshot.streamedText;
+ if (!snapshot.responseRetry.retainPartial) {
+ snapshot.streamedText = '';
+ snapshot.streamedTextStartSeq = 0;
+ snapshot.streamedTextSeq = 0;
+ snapshot.streamedTextTruncated = false;
+ }
+ } else if (['text', 'text_delta', 'tool_call', 'error', 'failure_recovery', 'run_complete', 'steering_applied'].includes(type)) {
+ snapshot.responseRetry = null;
+ }
+ if (['text', 'text_delta', 'tool_call', 'steering_applied'].includes(type)) snapshot.responseIncomplete = false;
while (snapshot.events.length > this.eventLimit) {
const removed = snapshot.events.shift();
const removedSeq = Number(removed?.seq || 0);
@@ -409,6 +437,8 @@ export class RunUiJournal {
snapshot.pendingPlanId = null;
snapshot.pendingToolCall = null;
snapshot.finalContent = String(finalContent || '').slice(0, 30000);
+ snapshot.responseRetry = null;
+ if (status === 'completed' && snapshot.finalContent) snapshot.responseIncomplete = false;
snapshot.endedAt = Date.now();
const event = {
seq: ++snapshot.seq,
@@ -483,6 +513,15 @@ export class RunUiJournal {
const restoredStreamSeq = Number(snapshot.streamedTextSeq || 0);
snapshot.streamedTextStartSeq = Number.isFinite(restoredStreamStartSeq) ? Math.max(0, restoredStreamStartSeq) : 0;
snapshot.streamedTextSeq = Number.isFinite(restoredStreamSeq) ? Math.max(0, restoredStreamSeq) : 0;
+ const restoredRetrySeq = Number(snapshot.responseRetry?.seq);
+ snapshot.responseRetry = snapshot.status === 'running'
+ && snapshot.responseRetry?.reason === 'stream_interrupted'
+ && Number.isSafeInteger(restoredRetrySeq) && restoredRetrySeq > 0
+ && restoredRetrySeq <= Number(snapshot.seq || 0)
+ ? { reason: 'stream_interrupted', retainPartial: snapshot.responseRetry.retainPartial === true, seq: restoredRetrySeq }
+ : null;
+ snapshot.responseIncomplete = snapshot.responseIncomplete === true && !!snapshot.streamedText
+ && !(snapshot.status === 'completed' && snapshot.finalContent);
if (!snapshot.lastPlanResolution || typeof snapshot.lastPlanResolution !== 'object') {
snapshot.lastPlanResolution = null;
}
diff --git a/src/firefox/src/trace/privacy.js b/src/firefox/src/trace/privacy.js
index f8719219d..a5c3fdcb8 100644
--- a/src/firefox/src/trace/privacy.js
+++ b/src/firefox/src/trace/privacy.js
@@ -17,13 +17,13 @@ const RESPONSE_METADATA_FIELDS = [
'step', 'usage', 'latencyMs', 'model', 'phase', 'attempt', 'repair', 'empty',
'finishReason', 'contentChars', 'toolCallCount', 'reasoningPresent',
'reasoningChars', 'reasoningTokens', 'outputTokens', 'requestedMaxTokens',
- 'recoveryAttempt',
+ 'recoveryAttempt', 'emptyReason', 'validationFailure', 'candidateAttempt',
];
const REQUEST_METADATA_FIELDS = [
'step', 'providerClass', 'providerId', 'model', 'phase', 'attempt', 'repair',
'messageCount', 'toolsCount', 'imageBlockCount', 'documentBlockCount',
- 'runtimeMode',
+ 'runtimeMode', 'requestedMaxTokens',
];
const STREAMING_METADATA_FIELDS = [
@@ -39,8 +39,51 @@ const NOTE_METADATA_FIELDS = [
'matchCount', 'multiSource', 'attempted', 'archiveDates', 'durationMs',
'success', 'approved', 'outcome', 'verification', 'count',
'adapter', 'revision', 'notesInjected', 'workflowSchema', 'job', 'template',
+ 'validationFailure', 'candidateAttempt', 'stage', 'retryMode',
];
+// Checker diagnostics are finite protocol labels, never arbitrary model text
+// or JSON property names. A malformed reply can contain private source text in
+// a duplicate field name, so metadata-only traces must normalize it here.
+const VALIDATION_FAILURE_CODES = new Set([
+ 'empty_response', 'invalid_json', 'binding_mismatch', 'invalid_aligned',
+ 'invalid_reason', 'unexpected_fields', 'reasoning_only', 'output_limit',
+ 'provider_empty', 'content_filter', 'truncated_response', 'request_failed',
+ 'invalid_replacement_plan', 'malformed_or_multiple_json_objects',
+ 'response_not_object', 'key_mismatch', 'action_mismatch',
+ 'authorized_not_boolean', 'reason_not_string', 'invalid_response',
+ ...['key', 'actionId', 'authorized', 'reason'].map(field => 'missing_' + field),
+ ...['key', 'actionId', 'authorized', 'reason', 'version', 'status', 'actions',
+ 'requirements', 'prohibited', 'extra_field'].map(field => 'duplicate_' + field),
+]);
+const PUBLICATION_CONTRACT_FAILURES = new Set([
+ 'object fields', 'list bounds', 'enum', 'source reference', 'anchor occurrence',
+ 'missing start occurrence', 'missing end occurrence', 'ambiguous start anchor',
+ 'ambiguous end anchor', 'anchor order', 'text exceeds supported payload size',
+ 'media nesting', 'media count', 'media constraint', 'version/reason',
+ 'duplicate prohibition', 'action id', 'prohibited destination',
+ 'empty body source', 'post context', 'duplicate action id',
+ 'requirement nesting', 'unknown or repeated action reference', 'incomplete requirements',
+]);
+const PUBLICATION_CONTRACT_CODES = new Set([...PUBLICATION_CONTRACT_FAILURES]
+ .map(detail => 'contract_' + detail.replace(/[^a-z0-9]+/g, '_')));
+const EMPTY_OUTPUT_REASONS = new Set(['output_limit', 'reasoning_only', 'content_filter', 'provider_empty']);
+const RECOVERY_STAGES = new Set([
+ 'model', 'inference', 'planning', 'plan_alignment', 'publication_audit',
+ 'completion_verification', 'verification',
+ 'response_generation', 'browser_interaction',
+]);
+const RECOVERY_RETRY_MODES = new Set(['resume', 'publication_without_audit', 'publication_audit_bypass']);
+
+function validationFailureMetadata(value) {
+ if (VALIDATION_FAILURE_CODES.has(value) || PUBLICATION_CONTRACT_CODES.has(value)) return value;
+ const prefix = 'Invalid publication contract: ';
+ const detail = typeof value === 'string' && value.startsWith(prefix) ? value.slice(prefix.length) : '';
+ return PUBLICATION_CONTRACT_FAILURES.has(detail)
+ ? 'contract_' + detail.replace(/[^a-z0-9]+/g, '_')
+ : 'invalid_response';
+}
+
const CLICK_AX_TIMING_MS_FIELDS = [
'preflightMs', 'syntheticDispatchMs', 'syntheticResponseMs',
'postClickObservationMs', 'fallbackPreparationMs', 'fallbackDispatchMs',
@@ -100,6 +143,16 @@ function projectPromptProvenance(value) {
function projectNoteExtra(value) {
const output = pick(value, NOTE_METADATA_FIELDS);
+ if (Object.hasOwn(output, 'validationFailure')) {
+ output.validationFailure = validationFailureMetadata(output.validationFailure);
+ }
+ if (Object.hasOwn(output, 'stage')) output.stage = RECOVERY_STAGES.has(output.stage) ? output.stage : 'model';
+ if (Object.hasOwn(output, 'retryMode')) {
+ output.retryMode = RECOVERY_RETRY_MODES.has(output.retryMode) ? output.retryMode : 'resume';
+ }
+ if (Object.hasOwn(output, 'candidateAttempt') && !Number.isSafeInteger(output.candidateAttempt)) {
+ delete output.candidateAttempt;
+ }
if (Array.isArray(output.archiveDates)) {
output.archiveDates = output.archiveDates.slice(0, 3).map(item => String(item).slice(0, 20));
}
@@ -158,6 +211,10 @@ export function projectTraceEventData(kind, data, { includeContent = false } = {
if (kind === 'llm_request') {
const projected = pick(source, REQUEST_METADATA_FIELDS);
+ if (Object.hasOwn(projected, 'requestedMaxTokens')
+ && (!Number.isSafeInteger(projected.requestedMaxTokens) || projected.requestedMaxTokens < 1)) {
+ delete projected.requestedMaxTokens;
+ }
if (source.promptProvenance && typeof source.promptProvenance === 'object') {
projected.promptProvenance = projectPromptProvenance(source.promptProvenance);
}
@@ -171,6 +228,19 @@ export function projectTraceEventData(kind, data, { includeContent = false } = {
if (kind === 'llm_response') {
const projected = pick(source, RESPONSE_METADATA_FIELDS);
+ if (Object.hasOwn(projected, 'requestedMaxTokens')
+ && (!Number.isSafeInteger(projected.requestedMaxTokens) || projected.requestedMaxTokens < 1)) {
+ delete projected.requestedMaxTokens;
+ }
+ if (Object.hasOwn(projected, 'emptyReason') && !EMPTY_OUTPUT_REASONS.has(projected.emptyReason)) {
+ delete projected.emptyReason;
+ }
+ if (Object.hasOwn(projected, 'validationFailure')) {
+ projected.validationFailure = validationFailureMetadata(projected.validationFailure);
+ }
+ if (Object.hasOwn(projected, 'candidateAttempt') && !Number.isSafeInteger(projected.candidateAttempt)) {
+ delete projected.candidateAttempt;
+ }
if (source.rejectedToolResponse) projected.rejectedToolResponse = source.rejectedToolResponse;
if (source.usage && typeof source.usage === 'object') projected.usage = projectUsage(source.usage);
return projected;
diff --git a/src/firefox/src/ui/failure-recovery.js b/src/firefox/src/ui/failure-recovery.js
new file mode 100644
index 000000000..cfc8567f3
--- /dev/null
+++ b/src/firefox/src/ui/failure-recovery.js
@@ -0,0 +1,64 @@
+const STAGE_MESSAGES = {
+ publication_audit: 'Failed while checking permission to publish. Your draft is still ready.',
+ plan_alignment: 'Failed while checking the plan against your task. No actions were started.',
+ inference: 'Failed while communicating with the AI service. Your completed steps were saved.',
+ verification: 'Failed while checking the result. The action may already be complete.',
+ planning: 'Failed while preparing the plan. No actions were started.',
+};
+
+export function failureRecoveryMessage(data = {}) {
+ const message = typeof data.message === 'string' ? data.message.trim() : '';
+ // Provider JSON belongs in diagnostics, rather than the main recovery copy.
+ if (message && !/webbrain-cloud error|\{"error"|Error communicating with LLM/i.test(message)) {
+ return message.slice(0, 2000);
+ }
+ return STAGE_MESSAGES[data.stage] || 'The task stopped before it could finish. You can retry from the saved progress.';
+}
+
+export function createFailureRecoveryCard(data, { document = globalThis.document, retryLabel = 'Retry' } = {}) {
+ if (!data?.recoveryId) return null;
+ const card = document.createElement('div');
+ card.className = 'failure-recovery-card';
+ card.dataset.recoveryId = String(data.recoveryId);
+ card.dataset.recoveryStage = String(data.stage || 'inference');
+ card.dataset.retryMode = data.retryMode === 'publication_without_audit' ? 'publication_without_audit' : 'resume';
+ card.setAttribute('role', 'alert');
+
+ const message = document.createElement('div');
+ message.className = 'failure-recovery-message';
+ message.textContent = failureRecoveryMessage(data);
+ card.appendChild(message);
+
+ if (card.dataset.retryMode === 'publication_without_audit') {
+ const note = document.createElement('div');
+ note.className = 'failure-recovery-note';
+ note.textContent = 'Retry skips the publication audit once for this unchanged draft.';
+ card.appendChild(note);
+ }
+ if (typeof data.diagnostics === 'string' && data.diagnostics.trim()) {
+ const details = document.createElement('details');
+ details.className = 'failure-recovery-details';
+ const summary = document.createElement('summary');
+ summary.textContent = 'Technical details';
+ const body = document.createElement('pre');
+ body.textContent = data.diagnostics.slice(0, 10000);
+ details.append(summary, body);
+ card.appendChild(details);
+ }
+
+ const actions = document.createElement('div');
+ actions.className = 'failure-recovery-actions';
+ for (const [choice, label] of [['give_up', 'Give up'], ['retry', retryLabel]]) {
+ const button = document.createElement('button');
+ button.type = 'button';
+ button.className = `failure-recovery-action${choice === 'retry' ? ' primary' : ''}`;
+ button.dataset.recoveryChoice = choice;
+ button.textContent = label;
+ actions.appendChild(button);
+ }
+ const status = document.createElement('div');
+ status.className = 'failure-recovery-status';
+ status.setAttribute('role', 'status');
+ card.append(actions, status);
+ return card;
+}
diff --git a/src/firefox/src/ui/locales/ar.js b/src/firefox/src/ui/locales/ar.js
index 85365b10b..938e4e101 100644
--- a/src/firefox/src/ui/locales/ar.js
+++ b/src/firefox/src/ui/locales/ar.js
@@ -1165,4 +1165,8 @@ export default {
"st.sync.consent.denied": "لم يتم منح إذن المزامنة المشفرة.",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "تغيّرت الصفحة أثناء تنفيذ المهمة ({before} → {after}). جارٍ متابعة المهمة.",
+ 'sp.activity.generating_answer': "جارٍ إنشاء الإجابة…",
+ 'sp.activity.retrying_response': "جارٍ إعادة محاولة الإجابة…",
+ 'sp.response.incomplete_retrying': "إجابة غير مكتملة · جارٍ إعادة المحاولة…",
+ 'sp.response.incomplete': "إجابة غير مكتملة",
};
diff --git a/src/firefox/src/ui/locales/bn.js b/src/firefox/src/ui/locales/bn.js
index 2086ff6de..e2ff665b5 100644
--- a/src/firefox/src/ui/locales/bn.js
+++ b/src/firefox/src/ui/locales/bn.js
@@ -1186,4 +1186,8 @@ export default {
"st.sync.consent.denied": "এনক্রিপ্ট করা সিঙ্ক অনুমতি দেওয়া হয়নি।",
'st.providers.webgpu_note.body': '{modelLink} কোনো API এন্ডপয়েন্ট ছাড়াই সম্পূর্ণভাবে Chrome-এ চলে। এটি Settings > Providers > WebGPU বা Apocalypse Mode থেকে ডাউনলোড করুন, তারপর standalone chat-এ nuclear control ব্যবহার করুন।',
'sp.monitor.navigation': "কাজ চলার সময় পৃষ্ঠা বদলেছে ({before} → {after})। কাজ চলতে থাকবে।",
+ 'sp.activity.generating_answer': "উত্তর তৈরি হচ্ছে…",
+ 'sp.activity.retrying_response': "উত্তর আবার চেষ্টা করা হচ্ছে…",
+ 'sp.response.incomplete_retrying': "অসম্পূর্ণ উত্তর · আবার চেষ্টা করা হচ্ছে…",
+ 'sp.response.incomplete': "অসম্পূর্ণ উত্তর",
};
diff --git a/src/firefox/src/ui/locales/de.js b/src/firefox/src/ui/locales/de.js
index dc0433e3a..eef96ea86 100644
--- a/src/firefox/src/ui/locales/de.js
+++ b/src/firefox/src/ui/locales/de.js
@@ -1159,4 +1159,8 @@ export default {
"st.sync.consent.denied": "Die Berechtigung zur verschlüsselten Synchronisierung wurde nicht erteilt.",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "Die Seite hat sich während der Aufgabe geändert ({before} → {after}). Die Aufgabe wird fortgesetzt.",
+ 'sp.activity.generating_answer': "Antwort wird erstellt…",
+ 'sp.activity.retrying_response': "Antwort wird erneut versucht…",
+ 'sp.response.incomplete_retrying': "Unvollständige Antwort · erneuter Versuch…",
+ 'sp.response.incomplete': "Unvollständige Antwort",
};
diff --git a/src/firefox/src/ui/locales/en.js b/src/firefox/src/ui/locales/en.js
index b2cff1db0..0ffdd3783 100644
--- a/src/firefox/src/ui/locales/en.js
+++ b/src/firefox/src/ui/locales/en.js
@@ -259,6 +259,10 @@ export default {
'sp.activity.toggle_history': 'Toggle activity history',
'sp.activity.continuing': 'Continuing...',
'sp.activity.stopping': 'Stopping...',
+ 'sp.activity.generating_answer': 'Generating answer…',
+ 'sp.activity.retrying_response': 'Retrying response…',
+ 'sp.response.incomplete_retrying': 'Incomplete response · retrying…',
+ 'sp.response.incomplete': 'Incomplete response',
'sp.context_compacted': 'Context automatically compacted',
'sp.context_compacted_manual': 'Context compacted',
'sp.context_compacted_detail': '{summarized} earlier messages summarized · {remaining} kept',
diff --git a/src/firefox/src/ui/locales/es.js b/src/firefox/src/ui/locales/es.js
index c240e07db..d6b9e4752 100644
--- a/src/firefox/src/ui/locales/es.js
+++ b/src/firefox/src/ui/locales/es.js
@@ -1165,4 +1165,8 @@ export default {
"st.sync.consent.denied": "No se concedió el permiso de sincronización cifrada.",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "La página cambió mientras se ejecutaba la tarea ({before} → {after}). La tarea continúa.",
+ 'sp.activity.generating_answer': "Generando respuesta…",
+ 'sp.activity.retrying_response': "Reintentando respuesta…",
+ 'sp.response.incomplete_retrying': "Respuesta incompleta · reintentando…",
+ 'sp.response.incomplete': "Respuesta incompleta",
};
diff --git a/src/firefox/src/ui/locales/fa.js b/src/firefox/src/ui/locales/fa.js
index c40e56d81..f31b689bb 100644
--- a/src/firefox/src/ui/locales/fa.js
+++ b/src/firefox/src/ui/locales/fa.js
@@ -1186,4 +1186,8 @@ export default {
"st.sync.consent.denied": "مجوز همگام‌سازی رمزگذاری شده داده نشد.",
'st.providers.webgpu_note.body': '{modelLink} بدون هیچ نقطهٔ پایانی API کاملاً در Chrome اجرا می‌شود. آن را در Settings > Providers > WebGPU یا حالت Apocalypse دانلود کنید، سپس از کنترل nuclear در standalone chat استفاده کنید.',
'sp.monitor.navigation': "صفحه هنگام اجرای کار تغییر کرد ({before} → {after}). کار ادامه می‌یابد.",
+ 'sp.activity.generating_answer': "در حال تولید پاسخ…",
+ 'sp.activity.retrying_response': "در حال تلاش دوباره برای پاسخ…",
+ 'sp.response.incomplete_retrying': "پاسخ ناقص · تلاش دوباره…",
+ 'sp.response.incomplete': "پاسخ ناقص",
};
diff --git a/src/firefox/src/ui/locales/fr.js b/src/firefox/src/ui/locales/fr.js
index 4e58a5e37..27dd38e11 100644
--- a/src/firefox/src/ui/locales/fr.js
+++ b/src/firefox/src/ui/locales/fr.js
@@ -1165,4 +1165,8 @@ export default {
"st.sync.consent.denied": "L'autorisation de synchronisation chiffrée n'a pas été accordée.",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "La page a changé pendant la tâche ({before} → {after}). La tâche continue.",
+ 'sp.activity.generating_answer': "Génération de la réponse…",
+ 'sp.activity.retrying_response': "Nouvelle tentative de réponse…",
+ 'sp.response.incomplete_retrying': "Réponse incomplète · nouvelle tentative…",
+ 'sp.response.incomplete': "Réponse incomplète",
};
diff --git a/src/firefox/src/ui/locales/he.js b/src/firefox/src/ui/locales/he.js
index 44d334bf9..f77a9064c 100644
--- a/src/firefox/src/ui/locales/he.js
+++ b/src/firefox/src/ui/locales/he.js
@@ -1118,4 +1118,8 @@ export default {
"st.sync.consent.denied": "הרשאת סנכרון מוצפן לא ניתנה.",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "הדף השתנה בזמן שהמשימה פעלה ({before} → {after}). ממשיכים במשימה.",
+ 'sp.activity.generating_answer': "יוצר תשובה…",
+ 'sp.activity.retrying_response': "מנסה שוב להשיב…",
+ 'sp.response.incomplete_retrying': "תשובה חלקית · מנסה שוב…",
+ 'sp.response.incomplete': "תשובה חלקית",
};
diff --git a/src/firefox/src/ui/locales/hi.js b/src/firefox/src/ui/locales/hi.js
index 745276ee1..88c5f49a6 100644
--- a/src/firefox/src/ui/locales/hi.js
+++ b/src/firefox/src/ui/locales/hi.js
@@ -1186,4 +1186,8 @@ export default {
"st.sync.consent.denied": "एन्क्रिप्टेड सिंक अनुमति नहीं दी गई थी.",
'st.providers.webgpu_note.body': '{modelLink} बिना किसी API एंडपॉइंट के पूरी तरह Chrome में चलता है। इसे Settings > Providers > WebGPU या Apocalypse Mode में डाउनलोड करें, फिर standalone chat में nuclear control का उपयोग करें।',
'sp.monitor.navigation': "काम चलने के दौरान पेज बदल गया ({before} → {after})। काम जारी है।",
+ 'sp.activity.generating_answer': "उत्तर तैयार हो रहा है…",
+ 'sp.activity.retrying_response': "उत्तर के लिए फिर प्रयास हो रहा है…",
+ 'sp.response.incomplete_retrying': "अधूरा उत्तर · फिर प्रयास हो रहा है…",
+ 'sp.response.incomplete': "अधूरा उत्तर",
};
diff --git a/src/firefox/src/ui/locales/id.js b/src/firefox/src/ui/locales/id.js
index b7cfd22f8..4d30d1e91 100644
--- a/src/firefox/src/ui/locales/id.js
+++ b/src/firefox/src/ui/locales/id.js
@@ -1165,4 +1165,8 @@ export default {
"st.sync.consent.denied": "Izin sinkronisasi terenkripsi tidak diberikan.",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "Halaman berubah saat tugas berjalan ({before} → {after}). Tugas dilanjutkan.",
+ 'sp.activity.generating_answer': "Membuat jawaban…",
+ 'sp.activity.retrying_response': "Mencoba ulang jawaban…",
+ 'sp.response.incomplete_retrying': "Jawaban belum lengkap · mencoba ulang…",
+ 'sp.response.incomplete': "Jawaban belum lengkap",
};
diff --git a/src/firefox/src/ui/locales/ja.js b/src/firefox/src/ui/locales/ja.js
index aa32a1f4e..b751f1beb 100644
--- a/src/firefox/src/ui/locales/ja.js
+++ b/src/firefox/src/ui/locales/ja.js
@@ -1165,4 +1165,8 @@ export default {
"st.sync.consent.denied": "暗号化された同期権限が付与されませんでした。",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "タスク実行中にページが変わりました({before} → {after})。タスクを続行します。",
+ 'sp.activity.generating_answer': "回答を生成中…",
+ 'sp.activity.retrying_response': "回答を再試行中…",
+ 'sp.response.incomplete_retrying': "未完の回答 · 再試行中…",
+ 'sp.response.incomplete': "未完の回答",
};
diff --git a/src/firefox/src/ui/locales/ko.js b/src/firefox/src/ui/locales/ko.js
index 15b6124e5..db12fe2e4 100644
--- a/src/firefox/src/ui/locales/ko.js
+++ b/src/firefox/src/ui/locales/ko.js
@@ -1165,4 +1165,8 @@ export default {
"st.sync.consent.denied": "암호화된 동기화 권한이 부여되지 않았습니다.",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "작업 실행 중 페이지가 변경되었습니다({before} → {after}). 작업을 계속합니다.",
+ 'sp.activity.generating_answer': "답변 생성 중…",
+ 'sp.activity.retrying_response': "답변 다시 시도 중…",
+ 'sp.response.incomplete_retrying': "미완성 답변 · 다시 시도 중…",
+ 'sp.response.incomplete': "미완성 답변",
};
diff --git a/src/firefox/src/ui/locales/ms.js b/src/firefox/src/ui/locales/ms.js
index 748e0dc05..dba169c92 100644
--- a/src/firefox/src/ui/locales/ms.js
+++ b/src/firefox/src/ui/locales/ms.js
@@ -1165,4 +1165,8 @@ export default {
"st.sync.consent.denied": "Kebenaran penyegerakan yang disulitkan tidak diberikan.",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "Halaman berubah semasa tugas berjalan ({before} → {after}). Tugas diteruskan.",
+ 'sp.activity.generating_answer': "Menjana jawapan…",
+ 'sp.activity.retrying_response': "Mencuba semula jawapan…",
+ 'sp.response.incomplete_retrying': "Jawapan tidak lengkap · mencuba semula…",
+ 'sp.response.incomplete': "Jawapan tidak lengkap",
};
diff --git a/src/firefox/src/ui/locales/nl.js b/src/firefox/src/ui/locales/nl.js
index c95c64671..b3701fe26 100644
--- a/src/firefox/src/ui/locales/nl.js
+++ b/src/firefox/src/ui/locales/nl.js
@@ -1139,4 +1139,8 @@ export default {
"st.sync.consent.denied": "Er is geen versleutelde synchronisatietoestemming verleend.",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "De pagina is gewijzigd terwijl de taak actief was ({before} → {after}). De taak wordt voortgezet.",
+ 'sp.activity.generating_answer': "Antwoord wordt gegenereerd…",
+ 'sp.activity.retrying_response': "Antwoord opnieuw proberen…",
+ 'sp.response.incomplete_retrying': "Onvolledig antwoord · opnieuw proberen…",
+ 'sp.response.incomplete': "Onvolledig antwoord",
};
diff --git a/src/firefox/src/ui/locales/pl.js b/src/firefox/src/ui/locales/pl.js
index 11c89f841..ecc9fd8c9 100644
--- a/src/firefox/src/ui/locales/pl.js
+++ b/src/firefox/src/ui/locales/pl.js
@@ -1126,4 +1126,8 @@ export default {
"st.sync.consent.denied": "Nie przyznano zezwolenia na szyfrowaną synchronizację.",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "Strona zmieniła się podczas wykonywania zadania ({before} → {after}). Zadanie jest kontynuowane.",
+ 'sp.activity.generating_answer': "Generowanie odpowiedzi…",
+ 'sp.activity.retrying_response': "Ponawianie odpowiedzi…",
+ 'sp.response.incomplete_retrying': "Niepełna odpowiedź · ponawianie…",
+ 'sp.response.incomplete': "Niepełna odpowiedź",
};
diff --git a/src/firefox/src/ui/locales/pt.js b/src/firefox/src/ui/locales/pt.js
index 2346b4fba..beda26b87 100644
--- a/src/firefox/src/ui/locales/pt.js
+++ b/src/firefox/src/ui/locales/pt.js
@@ -1186,4 +1186,8 @@ export default {
"st.sync.consent.denied": "A permissão de sincronização criptografada não foi concedida.",
'st.providers.webgpu_note.body': '{modelLink} é executado inteiramente no Chrome, sem endpoint de API. Baixe-o em Settings > Providers > WebGPU ou no Modo Apocalipse e use o controle nuclear no standalone chat.',
'sp.monitor.navigation': "A página mudou enquanto a tarefa estava em execução ({before} → {after}). A tarefa continua.",
+ 'sp.activity.generating_answer': "Gerando resposta…",
+ 'sp.activity.retrying_response': "Tentando novamente a resposta…",
+ 'sp.response.incomplete_retrying': "Resposta incompleta · tentando novamente…",
+ 'sp.response.incomplete': "Resposta incompleta",
};
diff --git a/src/firefox/src/ui/locales/ru.js b/src/firefox/src/ui/locales/ru.js
index c002e53c2..631074698 100644
--- a/src/firefox/src/ui/locales/ru.js
+++ b/src/firefox/src/ui/locales/ru.js
@@ -1165,4 +1165,8 @@ export default {
"st.sync.consent.denied": "Разрешение на зашифрованную синхронизацию не предоставлено.",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "Страница изменилась во время выполнения задачи ({before} → {after}). Задача продолжается.",
+ 'sp.activity.generating_answer': "Формирование ответа…",
+ 'sp.activity.retrying_response': "Повторная попытка ответа…",
+ 'sp.response.incomplete_retrying': "Неполный ответ · повторная попытка…",
+ 'sp.response.incomplete': "Неполный ответ",
};
diff --git a/src/firefox/src/ui/locales/th.js b/src/firefox/src/ui/locales/th.js
index 9494af239..31a544b11 100644
--- a/src/firefox/src/ui/locales/th.js
+++ b/src/firefox/src/ui/locales/th.js
@@ -1165,4 +1165,8 @@ export default {
"st.sync.consent.denied": "ไม่ได้รับสิทธิ์การซิงค์ที่เข้ารหัส",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "หน้าเว็บเปลี่ยนระหว่างที่งานกำลังทำงาน ({before} → {after}) งานจะดำเนินต่อ",
+ 'sp.activity.generating_answer': "กำลังสร้างคำตอบ…",
+ 'sp.activity.retrying_response': "กำลังลองตอบอีกครั้ง…",
+ 'sp.response.incomplete_retrying': "คำตอบยังไม่สมบูรณ์ · กำลังลองอีกครั้ง…",
+ 'sp.response.incomplete': "คำตอบยังไม่สมบูรณ์",
};
diff --git a/src/firefox/src/ui/locales/tl.js b/src/firefox/src/ui/locales/tl.js
index 4b881da99..8cad6c30a 100644
--- a/src/firefox/src/ui/locales/tl.js
+++ b/src/firefox/src/ui/locales/tl.js
@@ -1165,4 +1165,8 @@ export default {
"st.sync.consent.denied": "Hindi ibinigay ang naka-encrypt na pahintulot sa pag-sync.",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "Nagbago ang pahina habang tumatakbo ang gawain ({before} → {after}). Nagpapatuloy ang gawain.",
+ 'sp.activity.generating_answer': "Bumubuo ng sagot…",
+ 'sp.activity.retrying_response': "Sinusubukang muli ang sagot…",
+ 'sp.response.incomplete_retrying': "Hindi kumpletong sagot · sinusubukang muli…",
+ 'sp.response.incomplete': "Hindi kumpletong sagot",
};
diff --git a/src/firefox/src/ui/locales/tr.js b/src/firefox/src/ui/locales/tr.js
index 6d8563fd5..252629853 100644
--- a/src/firefox/src/ui/locales/tr.js
+++ b/src/firefox/src/ui/locales/tr.js
@@ -257,6 +257,10 @@ export default {
'sp.activity.toggle_history': 'İşlem geçmişini göster veya gizle',
'sp.activity.continuing': 'Devam ediyor...',
'sp.activity.stopping': 'Durduruluyor...',
+ 'sp.activity.generating_answer': 'Yanıt oluşturuluyor…',
+ 'sp.activity.retrying_response': 'Yanıt yeniden deneniyor…',
+ 'sp.response.incomplete_retrying': 'Tamamlanmamış yanıt · yeniden deneniyor…',
+ 'sp.response.incomplete': 'Tamamlanmamış yanıt',
'sp.copy': 'Kopyala',
'sp.copied': 'Kopyalandı!',
diff --git a/src/firefox/src/ui/locales/uk.js b/src/firefox/src/ui/locales/uk.js
index ebeab8233..ef083c95a 100644
--- a/src/firefox/src/ui/locales/uk.js
+++ b/src/firefox/src/ui/locales/uk.js
@@ -1165,4 +1165,8 @@ export default {
"st.sync.consent.denied": "Дозвіл на зашифровану синхронізацію не надано.",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "Сторінка змінилася під час виконання завдання ({before} → {after}). Завдання продовжується.",
+ 'sp.activity.generating_answer': "Формування відповіді…",
+ 'sp.activity.retrying_response': "Повторна спроба відповіді…",
+ 'sp.response.incomplete_retrying': "Неповна відповідь · повторна спроба…",
+ 'sp.response.incomplete': "Неповна відповідь",
};
diff --git a/src/firefox/src/ui/locales/vi.js b/src/firefox/src/ui/locales/vi.js
index 4cadc9d18..baa7299bf 100644
--- a/src/firefox/src/ui/locales/vi.js
+++ b/src/firefox/src/ui/locales/vi.js
@@ -1186,4 +1186,8 @@ export default {
"st.sync.consent.denied": "Quyền đồng bộ hóa được mã hóa không được cấp.",
'st.providers.webgpu_note.body': '{modelLink} chạy hoàn toàn trong Chrome mà không cần điểm cuối API. Tải mô hình trong Settings > Providers > WebGPU hoặc Chế độ Apocalypse, rồi dùng nút nuclear trong standalone chat.',
'sp.monitor.navigation': "Trang đã thay đổi khi tác vụ đang chạy ({before} → {after}). Tiếp tục tác vụ.",
+ 'sp.activity.generating_answer': "Đang tạo câu trả lời…",
+ 'sp.activity.retrying_response': "Đang thử lại câu trả lời…",
+ 'sp.response.incomplete_retrying': "Câu trả lời chưa hoàn chỉnh · đang thử lại…",
+ 'sp.response.incomplete': "Câu trả lời chưa hoàn chỉnh",
};
diff --git a/src/firefox/src/ui/locales/zh.js b/src/firefox/src/ui/locales/zh.js
index 0699241f6..32606a39f 100644
--- a/src/firefox/src/ui/locales/zh.js
+++ b/src/firefox/src/ui/locales/zh.js
@@ -1165,4 +1165,8 @@ export default {
"st.sync.consent.denied": "未授予加密同步权限。",
'st.providers.webgpu_note.body': '{modelLink} runs entirely in Chrome with no API endpoint. Download it in Settings > Providers > WebGPU or Apocalypse Mode, then use the nuclear control in standalone chat.',
'sp.monitor.navigation': "任务运行期间页面发生了变化({before} → {after})。正在继续任务。",
+ 'sp.activity.generating_answer': "正在生成回答…",
+ 'sp.activity.retrying_response': "正在重试回答…",
+ 'sp.response.incomplete_retrying': "回答未完成 · 正在重试…",
+ 'sp.response.incomplete': "回答未完成",
};
diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.js
index a572b026f..da99b396b 100644
--- a/src/firefox/src/ui/sidepanel.js
+++ b/src/firefox/src/ui/sidepanel.js
@@ -39,6 +39,7 @@ import {
} from './chat-history-store.js';
import { historyTextFromElement } from './history-text.js';
import { claimRunError } from './run-error-dedupe.js';
+import { createFailureRecoveryCard } from './failure-recovery.js';
import { RUN_CAPTURE_START_ERROR_PREFIX } from '../run-capture.js';
import { runUiUnavailableBeforeSeq, runUiUpdatesForCurrentTask } from '../run-ui-journal.js';
import { formatErrorMessage } from '../error-format.js';
@@ -1220,6 +1221,7 @@ function setTabProcessing(tabId, processing) {
if (sameTabId(currentTabId, numericTabId)) {
isProcessing = effectiveProcessing;
syncSelectionScopeRestoreAvailability();
+ if (typeof syncFailureRecoveryButtons === 'function') syncFailureRecoveryButtons();
}
}
@@ -2311,7 +2313,9 @@ function roleFromMessageElement(el) {
function extractChatHistoryMessages(root = messagesEl) {
if (!root) return [];
- return Array.from(root.querySelectorAll(':scope > .message')).map((msgEl, index) => {
+ return Array.from(root.querySelectorAll(':scope > .message')).filter((msgEl) => (
+ msgEl.querySelector('.message-text')?.dataset.responseIncomplete !== 'true'
+ )).map((msgEl, index) => {
const clone = msgEl.cloneNode(true);
clone.querySelectorAll('button, input, textarea, select, .msg-copy-btn, .code-copy-btn, .error-retry-btn')
.forEach((el) => el.remove());
@@ -5540,6 +5544,13 @@ async function applyActiveRunState(numericTabId, state, { shouldContinue = () =>
!isTerminalRunUiStatus(runUi.status)
|| lastRenderedSeq < Number(runUi.seq || 0)
);
+ if (shouldRestoreStreamedText
+ && Object.prototype.hasOwnProperty.call(runUi, 'responseRetry')
+ && !runUi.responseRetry
+ && runUi.responseIncomplete !== true
+ && runAssistantEl.querySelector('.message-text')?.dataset.responseIncomplete === 'true') {
+ finishResponseRetry(runAssistantEl, { completed: true });
+ }
const hasReplayableStreamStart = shouldRestoreStreamedText
&& streamedTextStartSeq > lastRenderedSeq
&& replayEvents.some((event) => (
@@ -5554,6 +5565,13 @@ async function applyActiveRunState(numericTabId, state, { shouldContinue = () =>
streamedAssistantTextByEl.set(textEl, snapshotStreamedText);
textEl.dataset.streamedAssistantActive = 'true';
renderStreamedAssistantMarkdownNow(textEl);
+ if (!isTerminalRunUiStatus(runUi.status)) {
+ showActivity(t(runUi.responseRetry ? 'sp.activity.retrying_response' : 'sp.activity.generating_answer'));
+ }
+ if (runUi.responseIncomplete === true) {
+ markResponseIncomplete(runAssistantEl, { retrying: !!runUi.responseRetry && !isTerminalRunUiStatus(runUi.status) });
+ if (!runUi.responseRetry || isTerminalRunUiStatus(runUi.status)) finishResponseRetry(runAssistantEl);
+ }
restoredSnapshotStream = true;
};
if (!hasReplayableStreamStart) restoreSnapshotStream();
@@ -5595,6 +5613,14 @@ async function applyActiveRunState(numericTabId, state, { shouldContinue = () =>
: event.data,
});
}
+ const canApplyResponseRetrySnapshot = Number(runUi.seq || 0) >= Number(runAssistantEl.dataset.lastRenderedSeq || 0);
+ if (canApplyResponseRetrySnapshot && !isTerminalRunUiStatus(runUi.status)
+ && runUi.responseRetry) {
+ beginResponseRetry(runAssistantEl, runUi.responseRetry);
+ } else if (canApplyResponseRetrySnapshot && (runAssistantEl.dataset.responseRetrying === 'true'
+ || (shouldRestoreStreamedText && runUi.responseIncomplete === true))) {
+ finishResponseRetry(runAssistantEl);
+ }
reconcileRunMessageAttachmentState(
numericTabId,
runAssistantEl,
@@ -5691,6 +5717,9 @@ async function applyActiveRunState(numericTabId, state, { shouldContinue = () =>
hideActivity();
syncSendButtonState();
}
+ if (Object.prototype.hasOwnProperty.call(state || {}, 'pendingFailureRecovery')) {
+ reconcileFailureRecoveryCards(numericTabId, state.pendingFailureRecovery, currentAssistantEl, requestId);
+ }
return true;
}
@@ -7210,6 +7239,25 @@ function bindPlannerProviderSettingsButton(btn) {
function rebindPlannerRequestFailureControls() {
document.querySelectorAll('.planner-request-failure-provider-btn')
.forEach(bindPlannerProviderSettingsButton);
+ document.querySelectorAll('.planner-request-failure-giveup-btn')
+ .forEach(bindPlannerGiveUpButton);
+}
+
+function bindPlannerGiveUpButton(button) {
+ if (!button || button.dataset.bound) return;
+ button.dataset.bound = 'true';
+ button.addEventListener('click', () => {
+ const actions = button.closest('.planner-request-failure-actions');
+ if (!actions || actions.dataset.recoveryChosen === 'true') return;
+ actions.dataset.recoveryChosen = 'true';
+ actions.querySelectorAll('button').forEach(item => { item.disabled = true; });
+ const status = document.createElement('div');
+ status.className = 'failure-recovery-status';
+ status.setAttribute('role', 'status');
+ status.textContent = 'Stopped. No actions were started.';
+ actions.after(status);
+ schedulePersist();
+ });
}
function renderPlannerRequestFailure(assistantEl, data, retryPayload = null) {
@@ -7265,6 +7313,12 @@ function renderPlannerRequestFailure(assistantEl, data, retryPayload = null) {
const visibleActions = orderedActions.filter(Boolean);
visibleActions[0]?.classList.add('primary');
visibleActions.forEach(btn => actions.appendChild(btn));
+ const giveUpButton = document.createElement('button');
+ giveUpButton.type = 'button';
+ giveUpButton.className = 'planner-request-failure-action planner-request-failure-giveup-btn';
+ giveUpButton.textContent = 'Give up';
+ bindPlannerGiveUpButton(giveUpButton);
+ actions.appendChild(giveUpButton);
textEl.append(message, actions);
addMessageCopyButton(assistantEl);
@@ -7304,6 +7358,10 @@ function scheduleActiveChatPayloadCleanup(tabId, state) {
}
function renderAgentErrorUpdate(data, tabId = currentTabId, requestId = '', options = {}) {
+ const recoveryOwner = requestId && messagesEl.querySelector(`.message.assistant[data-run-request-id="${CSS.escape(String(requestId))}"]`);
+ const responseOwner = recoveryOwner || currentAssistantEl;
+ if (responseOwner?.dataset.responseRetrying === 'true') finishResponseRetry(responseOwner);
+ if (recoveryOwner?.querySelector('.failure-recovery-card')) return;
const message = formatErrorMessage(data?.message ?? data?.error ?? data);
// Allowance routing depends on terminal durable-turn proof. Live error
// updates arrive before that proof, so the run_complete/direct response
@@ -7327,6 +7385,114 @@ function renderAgentErrorUpdate(data, tabId = currentTabId, requestId = '', opti
}
}
+function syncFailureRecoveryButtons() {
+ for (const card of messagesEl?.querySelectorAll?.('.failure-recovery-card') || []) {
+ const disabled = card.dataset.recoveryCurrent !== 'true'
+ || card.dataset.recoveryChosen === 'true'
+ || card.dataset.recoveryBusy === 'true'
+ || processingTabs.has(Number(card.dataset.tabId))
+ || isConversationClearInProgress(Number(card.dataset.tabId));
+ card.querySelectorAll('.failure-recovery-action').forEach(button => { button.disabled = disabled; });
+ }
+}
+
+function bindFailureRecoveryCard(card) {
+ for (const button of card.querySelectorAll('.failure-recovery-action')) {
+ if (button.dataset.bound) continue;
+ button.dataset.bound = 'true';
+ button.addEventListener('click', async () => {
+ if (button.disabled || card.dataset.recoveryBusy === 'true') return;
+ const tabId = Number(card.dataset.tabId);
+ if (!sameTabId(currentTabId, tabId) || !sameTabId(renderedTabId, tabId) || isProcessing) return;
+ const choice = button.dataset.recoveryChoice;
+ const recoveryId = String(card.dataset.recoveryId || '');
+ if (!recoveryId || !['retry', 'give_up'].includes(choice)) return;
+ card.dataset.recoveryBusy = 'true';
+ card.setAttribute('aria-busy', 'true');
+ const status = card.querySelector('.failure-recovery-status');
+ status.textContent = choice === 'retry' ? 'Retrying…' : 'Stopping…';
+ syncFailureRecoveryButtons();
+ try {
+ if (choice === 'retry') {
+ const accepted = await continueAgent({
+ failureRecoveryId: recoveryId,
+ mode: card.dataset.runMode,
+ foreground: card.dataset.foreground === 'true',
+ onFailureRecoveryAccepted: () => {
+ card.dataset.recoveryChosen = 'true';
+ card.removeAttribute('aria-busy');
+ status.textContent = 'Retry requested.';
+ schedulePersist();
+ },
+ });
+ if (!accepted) throw new Error('Retry could not start. Try again when the current task has stopped.');
+ } else {
+ const result = await sendToBackground('failure_recovery_response', { tabId, recoveryId, choice });
+ if (!result?.ok) throw new Error(result?.error || 'This recovery option is no longer available.');
+ }
+ card.dataset.recoveryChosen = 'true';
+ status.textContent = choice === 'retry' ? 'Retry requested.' : 'Stopped. Your prepared work was kept.';
+ } catch (error) {
+ status.textContent = formatErrorMessage(error);
+ } finally {
+ delete card.dataset.recoveryBusy;
+ card.removeAttribute('aria-busy');
+ syncFailureRecoveryButtons();
+ schedulePersist();
+ }
+ });
+ }
+}
+
+function renderFailureRecoveryCard(assistantEl, data, { tabId = currentTabId, requestId = '' } = {}) {
+ if (!assistantEl || !data?.recoveryId) return false;
+ const recoveryId = String(data.recoveryId);
+ const existing = assistantEl.querySelector(`.failure-recovery-card[data-recovery-id="${CSS.escape(recoveryId)}"]`);
+ if (existing) {
+ if (existing.dataset.recoveryChosen !== 'true') existing.dataset.recoveryCurrent = 'true';
+ bindFailureRecoveryCard(existing);
+ syncFailureRecoveryButtons();
+ return true;
+ }
+ const card = createFailureRecoveryCard(data, { retryLabel: t('sp.retry') });
+ if (!card) return false;
+ card.dataset.tabId = String(tabId);
+ card.dataset.runRequestId = String(requestId);
+ card.dataset.runMode = assistantEl.dataset.runMode || agentMode;
+ card.dataset.foreground = assistantEl.dataset.retryForeground || 'false';
+ card.dataset.recoveryCurrent = 'true';
+ assistantEl.querySelector('.message-content')?.appendChild(card);
+ bindFailureRecoveryCard(card);
+ syncFailureRecoveryButtons();
+ scrollToBottom();
+ schedulePersist();
+ return true;
+}
+
+function reconcileFailureRecoveryCards(tabId, pending, assistantEl = currentAssistantEl, requestId = '') {
+ const currentId = String(pending?.recoveryId || '');
+ for (const card of messagesEl?.querySelectorAll?.('.failure-recovery-card') || []) {
+ if (!sameTabId(card.dataset.tabId, tabId) || card.dataset.recoveryChosen === 'true') continue;
+ card.dataset.recoveryCurrent = card.dataset.recoveryId === currentId ? 'true' : 'false';
+ if (card.dataset.recoveryCurrent === 'false') {
+ card.querySelector('.failure-recovery-status').textContent = 'This recovery option is no longer available.';
+ }
+ }
+ if (currentId) renderFailureRecoveryCard(assistantEl, pending, { tabId, requestId });
+ syncFailureRecoveryButtons();
+}
+
+function rebindFailureRecoveryCards() {
+ for (const card of document.querySelectorAll('.failure-recovery-card')) {
+ // A restored offer is display data until the background validates it.
+ card.dataset.recoveryCurrent = 'unknown';
+ delete card.dataset.recoveryBusy;
+ card.removeAttribute('aria-busy');
+ bindFailureRecoveryCard(card);
+ }
+ syncFailureRecoveryButtons();
+}
+
function rebindRestoredMessageControls() {
void restoreGeneratedMedia(messagesEl, t);
restoreStagedScreenshotAttachments();
@@ -7337,6 +7503,7 @@ function rebindRestoredMessageControls() {
rebindRetryButtons();
rebindPlanReviewRetryButtons();
rebindPlannerRequestFailureControls();
+ rebindFailureRecoveryCards();
rebindContinueButtons();
rebindClarifyCards();
rebindPlanReviewCards();
@@ -9466,7 +9633,8 @@ async function sendMessage(extraChatParams = {}) {
});
}
addMessageCopyButton(assistantEl);
- } else if (textEl && getStreamedAssistantText(textEl) === String(res.content)) {
+ } else if (textEl && (getStreamedAssistantText(textEl) === String(res.content)
+ || (textEl.dataset.responseIncomplete === 'true' && isSuccessfulAskCompletion(modeForSend, res)))) {
renderAssistantTextUpdate(assistantEl, res.content);
} else if (textEl && !textEl.textContent.trim()) {
if (!renderCostAllowanceError(textEl, res.content, modeForSend, {
@@ -9890,6 +10058,9 @@ function handleAgentUpdateMessage(msg) {
}
case 'steering_applied': {
+ if ((eventAssistantEl || currentAssistantEl)?.dataset.responseRetrying === 'true') {
+ finishResponseRetry(eventAssistantEl || currentAssistantEl);
+ }
const id = String(data?.id || '');
if (id && !messagesEl.querySelector(`[data-steering-message-id="${CSS.escape(id)}"]`)) {
const userEl = addMessage('user', data.text, { beforeCurrentAssistant: true });
@@ -9913,16 +10084,24 @@ function handleAgentUpdateMessage(msg) {
// Empty content usually means "nothing new" — keep prior prose. Exception:
// replace:true with empty content clears a rejected streamed terminal
// (e.g. plan-only recovery) so the bubble is free for the real summary.
- if (data?.content) showActivity(t('tool.done'));
+ if (data?.content) showActivity(t('sp.activity.generating_answer'));
if (currentAssistantEl && (data.content || data.replace === true)) {
renderAssistantTextUpdate(currentAssistantEl, data.content || '', { replace: data.replace === true });
}
break;
case 'text_delta':
- if (data?.content) showActivity(t('tool.done'));
+ if (data?.content) showActivity(t('sp.activity.generating_answer'));
if (currentAssistantEl) {
const textEl = currentAssistantEl.querySelector('.message-text');
+ if (data?.content && (textEl?.dataset.responseIncomplete === 'true'
+ || currentAssistantEl.dataset.responseRetrying === 'true')) {
+ // A replacement stream starts a fresh answer, never appending to
+ // the interrupted attempt retained for the user.
+ finishResponseRetry(currentAssistantEl, { completed: true });
+ textEl.textContent = '';
+ clearStreamedAssistantText(textEl);
+ }
if (textEl && textEl.dataset.suppressToolCallStream !== 'true') {
// Keep the raw Markdown separate from the rendered DOM. Reading back
// textContent would discard markers such as ** and backticks after
@@ -9948,6 +10127,10 @@ function handleAgentUpdateMessage(msg) {
}
break;
+ case 'response_retry':
+ beginResponseRetry(eventAssistantEl || currentAssistantEl, data);
+ break;
+
case 'tool_call':
showActivity(friendlyToolLabel(data.name, data.args));
showInspectionBanner(data.name);
@@ -10022,6 +10205,17 @@ function handleAgentUpdateMessage(msg) {
renderAgentErrorUpdate(data, currentTabId, msg.requestId);
break;
+ case 'failure_recovery':
+ hideActivity();
+ if ((eventAssistantEl || currentAssistantEl)?.dataset.responseRetrying === 'true') {
+ finishResponseRetry(eventAssistantEl || currentAssistantEl);
+ }
+ if (currentAssistantEl) markLastStepFailed();
+ renderFailureRecoveryCard(eventAssistantEl || currentAssistantEl, data, {
+ tabId: eventTabId, requestId: msg.requestId,
+ });
+ break;
+
case 'max_steps_reached':
hideActivity();
// Don't gate on currentAssistantEl — race with sendResponse means it
@@ -10053,6 +10247,7 @@ function handleAgentUpdateMessage(msg) {
addPlannerFallbackNote(message, scheduledAssistantEl || eventAssistantEl || currentAssistantEl);
}
} else if (data?.code === 'ask_stream_fallback') {
+ showActivity(t('sp.activity.retrying_response'));
showComposerToast(t('sp.streaming.fallback'), { duration: 6000 });
} else if (data?.code === 'persistence_degraded') {
showComposerToast(t('sp.persistence.unavailable'), { duration: 10000 });
@@ -10073,6 +10268,10 @@ function handleAgentUpdateMessage(msg) {
break;
case 'run_complete':
+ if ((eventAssistantEl || currentAssistantEl)?.dataset.responseRetrying === 'true'
+ && (data?.status !== 'completed' || !data?.finalContent)) {
+ finishResponseRetry(eventAssistantEl || currentAssistantEl);
+ }
if (data?.quota) {
const target = eventAssistantEl || currentAssistantEl;
const text = target?.querySelector('.message-text');
@@ -10112,7 +10311,8 @@ function handleAgentUpdateMessage(msg) {
});
}
addMessageCopyButton(currentAssistantEl);
- } else if (textEl && hasStreamedText) {
+ } else if (textEl && (hasStreamedText
+ || (data.status === 'completed' && textEl.dataset.responseIncomplete === 'true'))) {
// Background/restored runs do not necessarily reach the local
// sendRunWithReconnect response handler. Finalize their lightweight
// live Markdown here, cancelling any queued frame and enabling the
@@ -11501,7 +11701,55 @@ function flushPendingStreamedAssistantMarkdownRenders(root = messagesEl) {
});
}
+function markResponseIncomplete(assistantEl, { retrying = false } = {}) {
+ const textEl = assistantEl.querySelector('.message-text');
+ if (!textEl) return;
+ renderStreamedAssistantMarkdownNow(textEl);
+ const partialText = getStreamedAssistantText(textEl);
+ if (partialText || textEl.textContent.trim()) {
+ textEl.dataset.responseIncomplete = 'true';
+ // Only retained retries need raw text in persisted markup. The journal
+ // remains authoritative; this also keeps a restored partial readable
+ // when its original deltas have already been acknowledged.
+ if (partialText) textEl.dataset.streamedAssistantText = partialText;
+ let note = assistantEl.querySelector('.response-incomplete-note');
+ if (!note) {
+ note = document.createElement('div');
+ note.className = 'response-incomplete-note';
+ note.setAttribute('role', 'status');
+ textEl.after(note);
+ }
+ note.textContent = t(retrying ? 'sp.response.incomplete_retrying' : 'sp.response.incomplete');
+ }
+}
+
+function beginResponseRetry(assistantEl, data = {}) {
+ if (!assistantEl || data.reason !== 'stream_interrupted') return;
+ assistantEl.dataset.responseRetrying = 'true';
+ if (data.retainPartial === true) markResponseIncomplete(assistantEl, { retrying: true });
+ showActivity(t('sp.activity.retrying_response'));
+ schedulePersist();
+}
+
+function finishResponseRetry(assistantEl, { completed = false } = {}) {
+ if (!assistantEl) return;
+ delete assistantEl.dataset.responseRetrying;
+ const textEl = assistantEl.querySelector('.message-text');
+ const note = assistantEl.querySelector('.response-incomplete-note');
+ if (completed) {
+ if (textEl) delete textEl.dataset.responseIncomplete;
+ note?.remove();
+ } else {
+ // Failed/cancelled retries may retain useful prose, but it remains
+ // explicitly incomplete and excluded from saved conversation messages.
+ if (note) note.textContent = t('sp.response.incomplete');
+ if (textEl?.dataset.responseIncomplete === 'true') clearStreamedAssistantText(textEl);
+ }
+ schedulePersist();
+}
+
function clearAssistantTextStreamState(assistantEl) {
+ if (assistantEl?.dataset.responseRetrying === 'true') finishResponseRetry(assistantEl);
const textEl = assistantEl?.querySelector('.message-text');
if (!textEl) return;
clearStreamedAssistantText(textEl);
@@ -11511,8 +11759,13 @@ function clearAssistantTextStreamState(assistantEl) {
function renderAssistantTextUpdate(assistantEl, content, options = {}) {
const textEl = assistantEl.querySelector('.message-text');
if (!textEl) return;
+ const replacesIncompleteResponse = textEl.dataset.responseIncomplete === 'true';
if (isStoppedByUserStatus(content)) {
+ if (replacesIncompleteResponse) {
+ finishResponseRetry(assistantEl);
+ return;
+ }
textEl.innerHTML = t('sp.stopped_by_user_html');
clearStreamedAssistantText(textEl);
delete textEl.dataset.suppressToolCallStream;
@@ -11520,6 +11773,10 @@ function renderAssistantTextUpdate(assistantEl, content, options = {}) {
return;
}
+ if (replacesIncompleteResponse || assistantEl.dataset.responseRetrying === 'true') {
+ finishResponseRetry(assistantEl, { completed: true });
+ }
+
// Cost-limit text can stream before the terminal snapshot tells us whether
// Retry or Continue is safe. Keep the bubble empty so the terminal renderer
// can build the card with authoritative resume context.
@@ -11543,7 +11800,7 @@ function renderAssistantTextUpdate(assistantEl, content, options = {}) {
// Final text must keep the same Markdown fence structure shown during streaming.
const renderedContent = formatMarkdown(content, { recoverNestedMarkdown: true });
- if (options.replace === true || restoredStreamNeedsReplacement) {
+ if (options.replace === true || restoredStreamNeedsReplacement || replacesIncompleteResponse) {
// A rejected streamed terminal must replace its already-rendered deltas
// even in Verbose mode; appending would leave the invalid plan visible.
// Empty content clears the bubble (plan-only retry before recovery tools).
@@ -11587,6 +11844,10 @@ function isStoppedByUserStatus(content) {
function clearTransientAssistantTextForToolCall() {
if (!currentAssistantEl) return;
+ if (currentAssistantEl.dataset.responseRetrying === 'true'
+ || currentAssistantEl.querySelector('.message-text')?.dataset.responseIncomplete === 'true') {
+ finishResponseRetry(currentAssistantEl, { completed: true });
+ }
const textEl = currentAssistantEl.querySelector('.message-text');
if (!textEl) return;
const text = textEl.textContent || '';
@@ -12567,24 +12828,28 @@ function showContinueButton(options = {}) {
async function continueAgent(options = {}) {
if (isStandaloneWindow) options = { ...options, mode: 'ask' };
+ if (isProcessing) return false;
const tabId = currentTabId;
const modeForSend = ['ask', 'act', 'dev'].includes(options?.mode) ? options.mode : agentMode;
if (rejectSelectionScopedMode(modeForSend, tabId)) return false;
const requestId = createRunRequestId(tabId);
const foregroundForSend = options?.foreground === true;
clearActiveChatPayloadForTab(tabId);
+ localRunRequestIds.set(tabId, requestId);
setTabProcessing(tabId, true);
setTabAbortRequested(tabId, false);
syncSendButtonState();
let assistantEl = null;
+ let runAccepted = false;
try {
await prepareChatHistoryForTurn(tabId, modeForSend);
if (isTabAbortRequested(tabId)) return false;
if (!sameTabId(currentTabId, tabId) || !sameTabId(renderedTabId, tabId)) return false;
+ // Remove the continue bar only after the durable history id is hydrated.
document.querySelectorAll('.continue-bar').forEach(el => el.remove());
resetChatNavigation();
@@ -12599,14 +12864,22 @@ async function continueAgent(options = {}) {
scrollChatToQuestion({ smooth: false });
}
showActivity(t('sp.activity.continuing'));
- localRunRequestIds.set(tabId, requestId);
- const res = await sendRunWithReconnect('continue_start', {
+ const res = await sendRunWithReconnect(options.failureRecoveryId ? 'failure_recovery_response' : 'continue_start', {
tabId,
requestId,
mode: modeForSend,
foreground: foregroundForSend,
+ ...(options.failureRecoveryId ? { recoveryId: options.failureRecoveryId, choice: 'retry' } : {}),
+ }, {
+ onStateObserved: state => {
+ if (!runAccepted && (state?.runUi?.requestId === requestId || state?.startingRequestId === requestId)) {
+ runAccepted = true;
+ options.onFailureRecoveryAccepted?.();
+ }
+ },
});
+ runAccepted = true;
if (sameTabId(currentTabId, tabId)) renderReturnedQuota(assistantEl, res);
applyConversationScopeState(tabId, res);
if (res?.conversationId) {
@@ -12636,12 +12909,13 @@ async function continueAgent(options = {}) {
}
}
} catch (e) {
+ if (options.failureRecoveryId && !runAccepted) throw e;
if (currentTabId === tabId
&& assistantEl
&& !isTabAbortRequested(tabId)
&& !clearedConversationRunRequestIds.has(requestId)
&& !conversationClearFollowerCancellationRequestIds.has(requestId)) {
- addMessage('error', t('sp.error_prefix', { msg: e.message }));
+ renderAgentErrorUpdate({ message: e.message, quota: e.quota }, tabId, requestId);
}
} finally {
const ownsRunState = localRunRequestIds.get(tabId) === requestId;
@@ -12663,6 +12937,7 @@ async function continueAgent(options = {}) {
if (currentTabId === tabId && renderedTabId === tabId) await flushChatHistorySnapshot(tabId, { refreshTabInfo: true });
await drainQueuedPromptsAfterRunSettles(tabId);
}
+ return runAccepted;
}
let agent_maxSteps = 130;
@@ -13377,6 +13652,7 @@ async function sendRunWithReconnect(initialAction, payload, recoveryOptions = {}
isConnectionError: isBackgroundConnectionError,
onState: state => {
if (!shouldContinueRunRecovery()) return;
+ recoveryOptions.onStateObserved?.(state);
applyConversationScopeState(tabId, state);
return applyActiveRunState(tabId, state, { shouldContinue: shouldContinueRunRecovery });
},
diff --git a/src/firefox/styles/sidepanel.css b/src/firefox/styles/sidepanel.css
index 1949223c1..cf75ef48e 100644
--- a/src/firefox/styles/sidepanel.css
+++ b/src/firefox/styles/sidepanel.css
@@ -1393,6 +1393,12 @@ html[data-ui-scale-ready="false"] body { visibility: hidden; }
display: none;
}
+.response-incomplete-note {
+ margin-top: 8px;
+ color: var(--text-muted);
+ font-size: 12px;
+}
+
.message-content {
padding: 10px 14px;
border-radius: var(--radius);
@@ -3897,6 +3903,40 @@ html[data-ui-scale="175"] .conversation-action-label {
display: none;
}
+.failure-recovery-card {
+ margin: 10px 0;
+ padding: 12px;
+ border: 1px solid var(--border);
+ border-radius: var(--radius, 6px);
+ background: var(--bg-secondary);
+ font-size: 13px;
+ line-height: 1.5;
+}
+
+.failure-recovery-message { color: var(--text-primary); }
+.failure-recovery-note, .failure-recovery-status {
+ margin-top: 6px;
+ color: var(--text-secondary);
+ font-size: 12px;
+}
+.failure-recovery-status:empty { display: none; }
+.failure-recovery-actions { display: flex; gap: 8px; margin-top: 12px; }
+.failure-recovery-action {
+ padding: 6px 12px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--bg-primary);
+ color: var(--text-primary);
+ cursor: pointer;
+ font: inherit;
+}
+.failure-recovery-action.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
+.failure-recovery-action:disabled { cursor: default; opacity: .55; }
+.failure-recovery-action:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.failure-recovery-details { margin-top: 8px; color: var(--text-secondary); font-size: 11px; }
+.failure-recovery-details summary { cursor: pointer; }
+.failure-recovery-details pre { max-height: 180px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; }
+
/* Clarify card — agent paused to ask user a question */
.clarify-card {
margin: 8px 0;
diff --git a/test/ask-stream-retry-ui.mjs b/test/ask-stream-retry-ui.mjs
new file mode 100644
index 000000000..1718117f6
--- /dev/null
+++ b/test/ask-stream-retry-ui.mjs
@@ -0,0 +1,308 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import vm from 'node:vm';
+import { test } from 'node:test';
+import { chromium, firefox } from 'playwright';
+
+const read = (build, file) => fs.readFileSync(new URL(`../src/${build}/${file}`, import.meta.url), 'utf8').replace(/\r\n/g, '\n');
+function extract(source, name) {
+ const start = source.search(new RegExp(`^(?:async )?function ${name}\\(`, 'm'));
+ assert.ok(start >= 0, `Missing function ${name}`);
+ return source.slice(start, source.indexOf('\n}', start) + 2);
+}
+const unexport = source => source.replace(/^export /gm, '');
+
+for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {
+ test(`${build}: only fallback-safe Ask interruptions retain the partial and retry the same grounded request`, async () => {
+ const source = read(build, 'src/agent/agent.js');
+ const start = source.indexOf(' const chatMainTurnRaw = async (');
+ const end = source.indexOf('\n const chatMainTurn = async (', start);
+ assert.ok(start >= 0 && end > start);
+ const turn = source.slice(start, end);
+ for (const [safe, code, emittedText] of [
+ [true, 'transport_error', true],
+ [true, 'missing_response_completed', true],
+ [true, 'transport_error', false],
+ [false, 'content_policy', true],
+ [false, 'invalid_response', true],
+ ]) {
+ const updates = [], calls = [];
+ const error = Object.assign(new Error(code), { code, isAskStreamFallbackSafe: safe });
+ const messages = [{ role: 'system', content: 'Use only this selected text: selected source.' }, { role: 'user', content: 'Explain it.' }];
+ const options = { tools: [], signal: { selectedTextOnly: true } };
+ const requestContext = { tabId: 7, sourceGrounding: { kind: 'selected_text' } };
+ const agent = {
+ _interactiveAskStreamingDecision: () => ({ eligible: true, reason: 'eligible' }),
+ _interactiveAskStreamingProtocol: () => 'responses',
+ _interactiveAskStreamingFailure: () => ({ errorCode: code }),
+ _isCostAllowanceError: () => false,
+ _shouldFallbackAskStream: value => value.isAskStreamFallbackSafe === true,
+ async _chatStreamWithCostAllowance(_provider, passedMessages, passedOptions, _cost, passedContext, delta) {
+ calls.push({ kind: 'stream', messages: passedMessages, options: passedOptions, context: passedContext });
+ if (emittedText) delta('The selected text means');
+ throw error;
+ },
+ async _chatWithCostAllowance(_provider, passedMessages, passedOptions, _cost, passedContext) {
+ calls.push({ kind: 'retry', messages: passedMessages, options: passedOptions, context: passedContext });
+ return { content: 'A complete explanation.', toolCalls: [] };
+ },
+ _logDebug() {},
+ };
+ const run = vm.runInNewContext(`(function () { let askStreamingDisabledForRun = false; ${turn}; return chatMainTurnRaw; }).call(agent)`, {
+ agent, provider: {}, mode: 'ask', runOptions: { interactiveChat: true }, costState: {},
+ recordAskStreaming() {}, onUpdate: (type, data) => updates.push({ type, data }),
+ });
+ if (safe) {
+ assert.equal((await run(messages, options, requestContext)).content, 'A complete explanation.');
+ assert.equal(updates.some(update => update.type === 'text' && update.data.replace), false);
+ const retry = updates.find(update => update.type === 'response_retry');
+ assert.equal(retry.data.reason, 'stream_interrupted');
+ assert.equal(retry.data.retainPartial, emittedText);
+ assert.equal(calls.length, 2);
+ for (const call of calls) {
+ assert.equal(call.messages, messages, 'Retry preserves the selected-text source boundary');
+ assert.equal(call.options, options);
+ assert.equal(call.context, requestContext);
+ }
+ } else {
+ await assert.rejects(run(messages, options, requestContext), value => value === error);
+ assert.equal(updates.some(update => update.type === 'response_retry'), false);
+ assert.equal(updates.at(-1).type, 'text');
+ assert.equal(updates.at(-1).data.content, '');
+ assert.equal(updates.at(-1).data.replace, true);
+ assert.equal(calls.length, 1);
+ }
+ }
+ });
+
+ test(`${build}: real message DOM preserves interrupted streams and replaces them cleanly`, async t => {
+ const source = read(build, 'src/ui/sidepanel.js');
+ const helperStart = source.indexOf('const ASSISTANT_RENDERABLE_ELEMENT_SELECTOR =');
+ const observerStart = source.indexOf('const persistObserver =', helperStart);
+ const observerEnd = source.indexOf('\n});', observerStart) + '\n});'.length;
+ const observeCall = source.match(/persistObserver\.observe\(messagesEl, \{[^\n]+\}\);/)?.[0];
+ assert.ok(observeCall);
+ const functions = [
+ 'getStreamedAssistantText', 'hasStreamedAssistantText', 'clearStreamedAssistantText',
+ 'renderStreamedAssistantMarkdownNow', 'scheduleStreamedAssistantMarkdownRender',
+ 'flushPendingStreamedAssistantMarkdownRenders', 'markResponseIncomplete', 'beginResponseRetry',
+ 'finishResponseRetry', 'clearAssistantTextStreamState', 'renderAssistantTextUpdate',
+ 'isStoppedByUserStatus', 'looksLikeRawToolCallText', 'clearTransientAssistantTextForToolCall',
+ 'clearThinkingActivityTimers', 'setActivityText', 'showActivity', 'hideActivity',
+ 'startThinkingActivity', 'renderAgentErrorUpdate', 'handleAgentUpdateMessage',
+ 'roleFromMessageElement', 'normalizeHistoryText', 'extractChatHistoryMessages', 'formatMarkdown', 'isSuccessfulAskCompletion',
+ ].map(name => extract(source, name)).join('\n');
+ const hydration = extract(source, 'applyActiveRunState');
+ const snapshotStart = hydration.indexOf(' let lastRenderedSeq =');
+ const snapshotEnd = hydration.indexOf(' reconcileRunMessageAttachmentState(', snapshotStart);
+ assert.ok(snapshotStart >= 0 && snapshotEnd > snapshotStart);
+ const send = extract(source, 'sendMessage');
+ const responseStart = send.indexOf(' if (renderToCurrentTab && currentTabId === tabId && isTabAbortRequested(tabId))');
+ const responseEnd = send.indexOf('\n } catch (e) {', responseStart);
+ assert.ok(responseStart >= 0 && responseEnd > responseStart);
+ const english = (await import(`../src/${build}/src/ui/locales/en.js`)).default;
+ const browser = await engine.launch({ headless: true });
+ try {
+ async function withPage(run) {
+ const page = await browser.newPage({ viewport: { width: 460, height: 600 } });
+ try {
+ await page.setContent(`<style>${read(build, 'styles/sidepanel.css')}</style><div id="activity"><span id="activity-text"></span></div><div id="live"></div><main id="messages"><div class="message user"><div class="message-content"><div class="message-text">Explain selected text.</div></div></div><div class="message assistant" data-run-request-id="request"><div class="message-content"><div class="message-text"></div></div></div></main>`);
+ await page.addScriptTag({ content: `
+ var messagesEl = document.querySelector('#messages');
+ var currentAssistantEl = document.querySelector('.assistant'), currentTabId = 7, renderedTabId = 7;
+ var localRunRequestIds = new Map([[7, 'request']]), clearedConversationRunRequestIds = new Set();
+ var verboseMode = false, compactProgressVisible = true;
+ var agentActivity = document.querySelector('#activity'), activityText = document.querySelector('#activity-text');
+ var activityLiveStatus = document.querySelector('#live'), activityDisplayMode = 'idle', thinkingActivityTimer = null;
+ var streamedAssistantTextByEl = new WeakMap(), streamedAssistantRenderFrameByEl = new WeakMap();
+ var translations = ${JSON.stringify(english)}, errorMessages = [];
+ function t(key) { return translations[key] || key; }
+ function schedulePersist() {}
+ function scrollToBottom() {}
+ function scheduleMathRender() {}
+ function parseCostAllowanceError() { return null; }
+ function parseSubscribeError() { return null; }
+ function updatesContainStoreReviewFailure(updates) { return (updates || []).some(update => update.type === 'error'); }
+ function renderSubscribeError() { return false; }
+ function renderCostAllowanceError() { return false; }
+ function addMessageCopyButton() {}
+ function ensureCurrentRunAssistant() { return currentAssistantEl; }
+ function beginThinkingActivity() { showActivity('Thinking…'); }
+ function hideInspectionBanner() {}
+ function setCompactProgressVisible(value) { compactProgressVisible = value; }
+ function markLastStepFailed() {}
+ function setMessageCreatedAt() {}
+ function finalizeSteps() {}
+ function reconcileRunMessageAttachmentState() {}
+ async function reconcilePersistedStagedScreenshots() {}
+ function invalidatePlanReviewCards() {}
+ function setPlanReviewAwaiting() {}
+ function clearPlanReviewActiveRun() { hideActivity(); }
+ function isPlanReviewTimeoutTerminal() { return false; }
+ function isTabAbortRequested() { return false; }
+ function formatErrorMessage(value) { return String(value); }
+ function takeActiveRetryPayloadForError() { return {}; }
+ function activeRetryPayloadForRequest() { return null; }
+ function retryPayloadForRunAssistant() { return null; }
+ function addMessage(role, value) {
+ const node = document.createElement('div'); node.className = 'message ' + role;
+ node.textContent = value; messagesEl.appendChild(node); errorMessages.push(value); return node;
+ }
+ function showComposerToast() {}
+ function renderFailureRecoveryCard() {}
+ function runUiUnavailableBeforeSeq() { return 0; }
+ function addRunProgressReplayGapNote() {}
+ function isTerminalRunUiStatus(status) { return ['completed', 'stopped', 'cancelled', 'failed'].includes(status); }
+ function messageAttachmentMetadata() { return []; }
+ function messageCreatedAt() { return 1; }
+ ${unexport(read(build, 'src/ui/utils.js'))}
+ ${unexport(read(build, 'src/ui/markdown-render.js'))}
+ ${unexport(read(build, 'src/ui/markdown-link.js'))}
+ ${unexport(read(build, 'src/ui/history-text.js'))}
+ ${source.slice(helperStart, observerEnd)}
+ ${functions}
+ ${observeCall}
+ function update(type, data = {}, seq) { handleAgentUpdateMessage({ tabId: 7, requestId: 'request', type, data, ...(seq ? { seq } : {}) }); }
+ function hydrateSnapshot(runUi) {
+ const runAssistantEl = currentAssistantEl, numericTabId = 7, requestId = 'request', state = {};
+ ${hydration.slice(snapshotStart, snapshotEnd)}
+ }
+ function applyReturnedResponse(res) {
+ const renderToCurrentTab = true, tabId = currentTabId, assistantEl = currentAssistantEl, modeForSend = 'ask', retryPayload = null;
+ ${send.slice(responseStart, responseEnd)}
+ }
+ ` });
+ await run(page);
+ } finally { await page.close(); }
+ }
+
+ await t.test('partial stays visible during retry and the regenerated answer replaces it even in verbose mode', () => withPage(async page => {
+ await page.evaluate(() => update('text_delta', { content: '**The selected text** means' }, 1));
+ await page.waitForFunction(() => document.querySelector('.message-text strong'));
+ assert.equal(await page.locator('#activity-text').textContent(), 'Generating answer…');
+ await page.evaluate(() => {
+ update('response_retry', { reason: 'stream_interrupted', retainPartial: true }, 2);
+ update('warning', { code: 'ask_stream_fallback' }, 3);
+ update('thinking', {}, 4);
+ });
+ assert.equal(await page.locator('.assistant .message-text').textContent(), 'The selected text means');
+ assert.equal(await page.locator('.response-incomplete-note').textContent(), 'Incomplete response · retrying…');
+ assert.equal(await page.locator('#activity-text').textContent(), 'Retrying response…');
+ assert.notEqual(await page.locator('.assistant').evaluate(node => getComputedStyle(node).display), 'none');
+ assert.deepEqual(await page.evaluate(() => extractChatHistoryMessages().map(message => message.role)), ['user']);
+ await page.evaluate(() => { verboseMode = true; update('text', { content: 'A **complete explanation**.' }, 5); });
+ assert.equal(await page.locator('.assistant .message-text').textContent(), 'A complete explanation.');
+ assert.equal(await page.locator('.response-incomplete-note').count(), 0);
+ assert.equal(await page.locator('.reasoning-step').count(), 0);
+ assert.equal(await page.locator('.assistant').getAttribute('data-response-retrying'), null);
+ assert.deepEqual(await page.evaluate(() => extractChatHistoryMessages().map(message => message.role)), ['user', 'assistant']);
+ }));
+
+ await t.test('cancel and errors settle the retry while retaining clearly incomplete prose', () => withPage(async page => {
+ for (const status of ['stopped', 'failed']) {
+ await page.evaluate(status => {
+ currentAssistantEl.querySelector('.message-text').textContent = '';
+ finishResponseRetry(currentAssistantEl, { completed: true });
+ update('text_delta', { content: 'A useful partial explanation.' });
+ update('response_retry', { reason: 'stream_interrupted', retainPartial: true });
+ if (status === 'failed') update('error', { message: 'The response service is unavailable.' });
+ else update('text', { content: '[Stopped by user]', replace: true });
+ update('run_complete', { status, finalContent: status === 'stopped' ? '[Stopped by user]' : 'The response service is unavailable.' });
+ }, status);
+ assert.equal(await page.locator('.assistant .message-text').textContent(), 'A useful partial explanation.');
+ assert.equal(await page.locator('.response-incomplete-note').textContent(), 'Incomplete response');
+ assert.equal(await page.locator('.assistant').getAttribute('data-response-retrying'), null);
+ assert.equal(await page.locator('.assistant .message-text').getAttribute('data-response-incomplete'), 'true');
+ assert.equal(await page.evaluate(() => extractChatHistoryMessages().some(message => message.role === 'assistant')), false);
+ }
+ }));
+
+ await t.test('explicit invalid-response resets still clear and a new streamed answer cannot concatenate retained text', () => withPage(async page => {
+ await page.evaluate(() => {
+ update('text_delta', { content: 'Interrupted attempt.' });
+ update('response_retry', { reason: 'stream_interrupted', retainPartial: true });
+ update('text', { content: '', replace: true });
+ });
+ assert.equal(await page.locator('.assistant .message-text').textContent(), '');
+ assert.equal(await page.locator('.response-incomplete-note').count(), 0);
+ await page.evaluate(() => {
+ update('text_delta', { content: 'Another partial.' });
+ update('response_retry', { reason: 'stream_interrupted', retainPartial: true });
+ update('text_delta', { content: 'Fresh ' });
+ update('text_delta', { content: 'answer.' });
+ });
+ await page.waitForFunction(() => currentAssistantEl.querySelector('.message-text').textContent === 'Fresh answer.');
+ assert.equal(await page.locator('.response-incomplete-note').count(), 0);
+ assert.equal(await page.locator('#activity-text').textContent(), 'Generating answer…');
+ }));
+
+ await t.test('the resolved sender response preserves failed partials and only successful regeneration replaces them', () => withPage(async page => {
+ for (const status of ['failed', 'cancelled']) {
+ await page.evaluate(status => {
+ clearAssistantTextStreamState(currentAssistantEl);
+ finishResponseRetry(currentAssistantEl, { completed: true });
+ currentAssistantEl.querySelector('.message-text').textContent = '';
+ update('text_delta', { content: 'Useful retained explanation.' });
+ update('response_retry', { reason: 'stream_interrupted', retainPartial: true });
+ const content = status === 'cancelled' ? '[Stopped by user]' : 'Response generation failed.';
+ update('run_complete', { status, finalContent: content });
+ applyReturnedResponse({ content, runSucceeded: false, updates: [{ type: 'error' }] });
+ }, status);
+ assert.equal(await page.locator('.assistant .message-text').textContent(), 'Useful retained explanation.', status);
+ assert.equal(await page.locator('.response-incomplete-note').textContent(), 'Incomplete response', status);
+ assert.equal(await page.evaluate(() => extractChatHistoryMessages().some(message => message.role === 'assistant')), false, status);
+ }
+ await page.evaluate(() => applyReturnedResponse({ content: 'Successfully regenerated answer.', runSucceeded: true, updates: [] }));
+ assert.equal(await page.locator('.assistant .message-text').textContent(), 'Successfully regenerated answer.');
+ assert.equal(await page.locator('.response-incomplete-note').count(), 0);
+ }));
+
+ await t.test('retry before the first token clears its state on new deltas, success, cancellation, or error', () => withPage(async page => {
+ for (const outcome of ['delta', 'success', 'stopped', 'error']) {
+ await page.evaluate(outcome => {
+ clearAssistantTextStreamState(currentAssistantEl);
+ currentAssistantEl.querySelector('.message-text').textContent = '';
+ update('response_retry', { reason: 'stream_interrupted', retainPartial: false });
+ if (outcome === 'delta') update('text_delta', { content: 'First token.' });
+ if (outcome === 'success') update('run_complete', { status: 'completed', finalContent: 'Complete answer.' });
+ if (outcome === 'stopped') update('run_complete', { status: 'stopped', finalContent: '[Stopped by user]' });
+ if (outcome === 'error') update('error', { message: 'Temporary service error.' });
+ }, outcome);
+ assert.equal(await page.locator('.assistant').getAttribute('data-response-retrying'), null, outcome);
+ assert.equal(await page.locator('.response-incomplete-note').count(), 0, outcome);
+ }
+ }));
+
+ await t.test('acknowledged snapshots restore both retrying and settled partials, and normal streams use the generating label', () => withPage(async page => {
+ for (const status of ['running', 'failed', 'stopped']) for (const replayable of [false, true]) {
+ await page.evaluate(({ status, replayable }) => {
+ messagesEl.querySelector('.assistant').remove();
+ currentAssistantEl = document.createElement('div');
+ currentAssistantEl.className = 'message assistant';
+ currentAssistantEl.dataset.runRequestId = 'request';
+ currentAssistantEl.innerHTML = '<div class="message-content"><div class="message-text"></div></div>';
+ messagesEl.appendChild(currentAssistantEl);
+ const events = replayable ? [
+ { seq: 1, type: 'text_delta', data: { content: 'Restored partial.' } },
+ { seq: 4, type: 'response_retry', data: { reason: 'stream_interrupted', retainPartial: true } },
+ ...(status === 'failed' ? [{ seq: 7, type: 'error', data: { message: 'Retry failed.' } }] : []),
+ ...(status !== 'running' ? [{ seq: 8, type: 'run_complete', data: { status, finalContent: status === 'stopped' ? '[Stopped by user]' : 'Retry failed.' } }] : []),
+ ] : [];
+ hydrateSnapshot({ requestId: 'request', status, seq: 8, events, streamedText: 'Restored partial.', streamedTextStartSeq: 1, streamedTextSeq: 3, responseIncomplete: true,
+ responseRetry: status === 'running' ? { reason: 'stream_interrupted', retainPartial: true, seq: 4 } : null });
+ if (status !== 'running') update('run_complete', { status, finalContent: 'Retry failed.' }, 8);
+ }, { status, replayable });
+ assert.equal(await page.locator('.assistant .message-text').textContent(), 'Restored partial.', status);
+ assert.equal(await page.locator('.response-incomplete-note').textContent(), status === 'running' ? 'Incomplete response · retrying…' : 'Incomplete response', status);
+ assert.equal(await page.evaluate(() => extractChatHistoryMessages().some(message => message.role === 'assistant')), false, status);
+ }
+ await page.evaluate(() => {
+ hydrateSnapshot({ requestId: 'request', status: 'running', seq: 9, events: [], streamedText: 'Fresh restored answer.', streamedTextStartSeq: 9, streamedTextSeq: 9, responseRetry: null, responseIncomplete: false });
+ });
+ assert.equal(await page.locator('.assistant .message-text').textContent(), 'Fresh restored answer.');
+ assert.equal(await page.locator('.response-incomplete-note').count(), 0);
+ assert.equal(await page.locator('#activity-text').textContent(), 'Generating answer…');
+ }));
+ } finally { await browser.close(); }
+ });
+}
diff --git a/test/failure-recovery-ui.mjs b/test/failure-recovery-ui.mjs
new file mode 100644
index 000000000..3d2622a09
--- /dev/null
+++ b/test/failure-recovery-ui.mjs
@@ -0,0 +1,179 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import { test } from 'node:test';
+import vm from 'node:vm';
+import { chromium, firefox } from 'playwright';
+
+const read = (build, file) => fs.readFileSync(new URL(`../src/${build}/${file}`, import.meta.url), 'utf8').replace(/\r\n/g, '\n');
+function extract(source, name) {
+ const start = source.search(new RegExp(`^(?:async )?function ${name}\\(`, 'm'));
+ assert.ok(start >= 0, `Missing function: ${name}`);
+ return source.slice(start, source.indexOf('\n}', start) + 2);
+}
+
+for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {
+ test(`${build}: recovery choices preserve stage details, require a click, and lock duplicate retries`, async () => {
+ const browser = await engine.launch({ headless: true });
+ try {
+ const page = await browser.newPage();
+ await page.setContent(`<style>${read(build, 'styles/sidepanel.css')}</style><main id="messages"><div class="message assistant" data-run-mode="act" data-run-request-id="failed-request"><div class="message-content"><div class="message-text"></div></div></div></main>`);
+ const source = read(build, 'src/ui/sidepanel.js');
+ const functions = ['syncFailureRecoveryButtons', 'bindFailureRecoveryCard', 'renderFailureRecoveryCard', 'reconcileFailureRecoveryCards', 'rebindFailureRecoveryCards'].map(name => extract(source, name)).join('\n');
+ await page.addScriptTag({ content: `
+ ${read(build, 'src/ui/failure-recovery.js').replaceAll('export function ', 'function ')}
+ var messagesEl = document.querySelector('#messages');
+ var currentAssistantEl = document.querySelector('.assistant');
+ var currentTabId = 7, renderedTabId = 7, agentMode = 'act', isProcessing = false;
+ var processingTabs = new Set(), calls = [], settleRetry;
+ function sameTabId(a, b) { return Number(a) === Number(b); }
+ function isConversationClearInProgress() { return false; }
+ function t() { return 'Retry'; }
+ function scrollToBottom() {}
+ function schedulePersist() {}
+ function formatErrorMessage(error) { return error.message || String(error); }
+ function continueAgent(options) {
+ const { onFailureRecoveryAccepted, ...payload } = options;
+ calls.push({ type: 'retry', options: payload });
+ return new Promise(resolve => {
+ settleRetry = value => { if (value) onFailureRecoveryAccepted?.(); resolve(value); };
+ });
+ }
+ async function sendToBackground(action, payload) { calls.push({ action, payload }); return { ok: true }; }
+ ${functions}
+ renderFailureRecoveryCard(currentAssistantEl, {
+ recoveryId: 'opaque-draft-offer', stage: 'publication_audit',
+ retryMode: 'publication_without_audit',
+ message: 'webbrain-cloud error 400: {"error":{"message":"upstream error"}}',
+ diagnostics: '<img src=x onerror="window.unsafe=true">'
+ }, { tabId: 7, requestId: 'failed-request' });
+ ` });
+ assert.equal(await page.locator('.failure-recovery-message').textContent(), 'Failed while checking permission to publish. Your draft is still ready.');
+ assert.match(await page.locator('.failure-recovery-note').textContent(), /skips the publication audit once/);
+ assert.deepEqual(await page.locator('.failure-recovery-action').allTextContents(), ['Give up', 'Retry']);
+ assert.equal(await page.locator('.failure-recovery-card img').count(), 0);
+ assert.equal(await page.evaluate(() => calls.length), 0);
+ await page.locator('[data-recovery-choice="retry"]').click();
+ assert.equal(await page.locator('.failure-recovery-action:disabled').count(), 2);
+ await page.evaluate(() => document.querySelector('[data-recovery-choice="retry"]').click());
+ assert.deepEqual(await page.evaluate(() => calls), [{ type: 'retry', options: { failureRecoveryId: 'opaque-draft-offer', mode: 'act', foreground: false } }]);
+ await page.evaluate(() => settleRetry(true));
+ await page.waitForFunction(() => document.querySelector('.failure-recovery-card').dataset.recoveryChosen === 'true');
+ assert.equal(await page.locator('.failure-recovery-status').textContent(), 'Retry requested.');
+ assert.equal(await page.locator('.failure-recovery-action:disabled').count(), 2);
+
+ await page.evaluate(() => {
+ renderFailureRecoveryCard(currentAssistantEl, { recoveryId: 'verification-offer', stage: 'verification', retryMode: 'resume' }, { tabId: 7 });
+ });
+ await page.locator('[data-recovery-id="verification-offer"] [data-recovery-choice="give_up"]').focus();
+ await page.keyboard.press('Enter');
+ await page.waitForFunction(() => calls.length === 2);
+ assert.deepEqual(await page.evaluate(() => calls[1]), { action: 'failure_recovery_response', payload: { tabId: 7, recoveryId: 'verification-offer', choice: 'give_up' } });
+ assert.equal(await page.locator('[data-recovery-id="verification-offer"] .failure-recovery-note').count(), 0);
+ } finally { await browser.close(); }
+ });
+
+ test(`${build}: restored recovery buttons require the current background offer and wait for the run to stop`, async () => {
+ const browser = await engine.launch({ headless: true });
+ try {
+ const page = await browser.newPage();
+ await page.setContent('<main id="messages"><div class="message assistant"><div class="message-content"></div></div></main>');
+ const source = read(build, 'src/ui/sidepanel.js');
+ const functions = ['syncFailureRecoveryButtons', 'bindFailureRecoveryCard', 'renderFailureRecoveryCard', 'reconcileFailureRecoveryCards', 'rebindFailureRecoveryCards'].map(name => extract(source, name)).join('\n');
+ await page.addScriptTag({ content: `
+ ${read(build, 'src/ui/failure-recovery.js').replaceAll('export function ', 'function ')}
+ var messagesEl = document.querySelector('#messages'), currentAssistantEl = document.querySelector('.assistant');
+ var currentTabId = 7, renderedTabId = 7, agentMode = 'act', isProcessing = true, calls = [];
+ var processingTabs = new Set([7]);
+ function sameTabId(a, b) { return Number(a) === Number(b); }
+ function isConversationClearInProgress() { return false; }
+ function t() { return 'Retry'; }
+ function scrollToBottom() {}
+ function schedulePersist() {}
+ function formatErrorMessage(error) { return error.message; }
+ async function sendToBackground(action, payload) { calls.push({ action, payload }); return { ok: true }; }
+ async function continueAgent() { calls.push('retry'); return true; }
+ ${functions}
+ renderFailureRecoveryCard(currentAssistantEl, { recoveryId: 'current-offer', stage: 'plan_alignment' }, { tabId: 7 });
+ ` });
+ assert.equal(await page.locator('.failure-recovery-action:disabled').count(), 2);
+ await page.evaluate(() => {
+ processingTabs.clear(); isProcessing = false;
+ messagesEl.innerHTML = messagesEl.innerHTML;
+ currentAssistantEl = document.querySelector('.assistant');
+ messagesEl.querySelectorAll('[data-bound]').forEach(node => delete node.dataset.bound);
+ rebindFailureRecoveryCards();
+ });
+ assert.equal(await page.locator('.failure-recovery-action:disabled').count(), 2);
+ await page.evaluate(() => reconcileFailureRecoveryCards(7, { recoveryId: 'current-offer', stage: 'plan_alignment' }, currentAssistantEl));
+ assert.equal(await page.locator('.failure-recovery-action:disabled').count(), 0);
+ await page.evaluate(() => reconcileFailureRecoveryCards(7, null, currentAssistantEl));
+ assert.equal(await page.locator('.failure-recovery-action:disabled').count(), 2);
+ assert.equal(await page.locator('.failure-recovery-status').textContent(), 'This recovery option is no longer available.');
+ assert.equal(await page.evaluate(() => calls.length), 0);
+ } finally { await browser.close(); }
+ });
+
+ test(`${build}: recovery transport only accepts the panel and resolves opaque offers before continuing`, async () => {
+ const source = extract(read(build, 'src/background.js'), 'handleFailureRecoveryResponse');
+ const api = { runtime: { getURL: path => `extension://test/${path}` } };
+ const calls = [], detached = new Map();
+ let active = false, available = true, snapshot = null;
+ const agent = { requestFailureRecovery(tabId, recoveryId, choice) {
+ calls.push({ tabId, recoveryId, choice });
+ return available ? { ok: true, continue: choice === 'retry' } : { ok: false, error: 'Stale recovery option.' };
+ } };
+ const handler = new Function('chrome', 'browser', 'agent', 'detachedRunStarts', 'getRunUiSnapshot', 'assertNoActiveTabRun', 'launchDetachedRun', `${source}; return handleFailureRecoveryResponse;`)(
+ api, api, agent, detached, async () => snapshot,
+ () => { if (active) throw new Error('A run is already active for this tab.'); },
+ (action, msg) => { calls.push({ action, requestId: msg.requestId }); detached.set(msg.tabId, { requestId: msg.requestId }); return { ok: true, accepted: true, requestId: msg.requestId }; },
+ );
+ const msg = { tabId: 7, recoveryId: 'bound-id', choice: 'retry', requestId: 'new-recovery-run' };
+ const panel = { url: api.runtime.getURL('src/ui/sidepanel.html') + '?standalone=true' };
+ assert.equal((await handler(msg, { url: 'https://site.example/' })).ok, false);
+ assert.equal((await handler({ ...msg, choice: 'anything' }, panel)).ok, false);
+ assert.equal(calls.length, 0);
+ active = true;
+ await assert.rejects(handler(msg, panel), /already active/);
+ assert.equal(calls.length, 0);
+ active = false; available = false;
+ assert.equal((await handler(msg, panel)).ok, false);
+ assert.deepEqual(calls.pop(), { tabId: 7, recoveryId: 'bound-id', choice: 'retry' });
+ available = true;
+ assert.equal((await handler(msg, panel)).accepted, true);
+ assert.deepEqual(calls, [{ tabId: 7, recoveryId: 'bound-id', choice: 'retry' }, { action: 'continue', requestId: 'new-recovery-run' }]);
+ assert.equal((await handler(msg, panel)).accepted, true);
+ assert.equal(calls.length, 2, 'Lost acknowledgements must follow the same run');
+ detached.clear(); snapshot = { requestId: msg.requestId, kind: 'continue' };
+ assert.equal((await handler(msg, panel)).accepted, true);
+ assert.equal(calls.length, 2);
+ snapshot = null;
+ const stopped = await handler({ ...msg, choice: 'give_up' }, panel);
+ assert.equal(stopped.continue, false);
+ assert.deepEqual(calls.at(-1), { tabId: 7, recoveryId: 'bound-id', choice: 'give_up' });
+ assert.equal(calls.filter(call => call.action === 'continue').length, 1);
+ });
+
+ test(`${build}: retry preflight failure clears its busy state without granting or starting recovery`, async () => {
+ const context = vm.createContext({
+ isStandaloneWindow: false, isProcessing: false, currentTabId: 7, renderedTabId: 7, agentMode: 'act',
+ localRunRequestIds: new Map(), cancelledRunRecoveryRequestIds: new Set(),
+ conversationClearFollowerCancellationRequestIds: new Set(), currentAssistantEl: null,
+ rejectSelectionScopedMode: () => false, createRunRequestId: () => 'retry-preflight',
+ clearActiveChatPayloadForTab: () => {},
+ setTabProcessing: (_tab, value) => { context.isProcessing = value; },
+ setTabAbortRequested: () => {}, syncSendButtonState: () => {},
+ prepareChatHistoryForTurn: async () => { throw new Error('History is unavailable.'); },
+ clearAssistantTextStreamState: () => {}, hideActivity: () => {}, scrollToBottom: () => {},
+ flushRenderedTabChat: async () => {}, flushChatHistorySnapshot: async () => {},
+ drainQueuedPromptsAfterRunSettles: async () => {},
+ sendRunWithReconnect: () => assert.fail('Failed preflight must never grant or start recovery.'),
+ });
+ vm.runInContext(extract(read(build, 'src/ui/sidepanel.js'), 'continueAgent'), context);
+ await assert.rejects(context.continueAgent({ failureRecoveryId: 'opaque-offer' }), /History is unavailable/);
+ assert.equal(context.isProcessing, false);
+ assert.equal(context.localRunRequestIds.size, 0);
+ context.isProcessing = true;
+ assert.equal(await context.continueAgent({ failureRecoveryId: 'opaque-offer' }), false);
+ assert.equal(context.localRunRequestIds.size, 0);
+ });
+}
diff --git a/test/failure-recovery.mjs b/test/failure-recovery.mjs
new file mode 100644
index 000000000..c79a7b86e
--- /dev/null
+++ b/test/failure-recovery.mjs
@@ -0,0 +1,390 @@
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { readFileSync } from 'node:fs';
+import vm from 'node:vm';
+
+const area = { get: async () => ({}), set: async () => {}, remove: async () => {} };
+const extensionApi = {
+ storage: { local: area, session: area },
+ runtime: { getURL: path => `extension://owned/${path}`, sendMessage: async () => ({}) },
+ tabs: { get: async id => ({ id, url: 'https://owned.example.test/' }), sendMessage: async () => ({}) },
+ scripting: { executeScript: async () => [{ result: null }] },
+};
+globalThis.chrome = globalThis.browser = extensionApi;
+
+for (const browser of ['chrome', 'firefox']) {
+ const { FailureRecoveryRegistry, modelFailureRecovery } = await import(`../src/${browser}/src/agent/failure-recovery.js`);
+ const { Agent } = await import(`../src/${browser}/src/agent/agent.js`);
+ const { projectTraceEventData } = await import(`../src/${browser}/src/trace/privacy.js`);
+ const tabId = 42;
+ const task = 'Publish exactly Hello to the owned account.';
+ const generic = { stage: 'inference', code: 'request_failed', message: 'Failed while contacting the model.' };
+
+ function setup() {
+ const agent = new Agent({ getActive: () => ({ name: 'fixture', model: 'fixture', config: {} }) });
+ agent._persist = () => {};
+ agent.conversationIds.set(tabId, 'private-conversation');
+ agent.conversations.set(tabId, [{ role: 'system', content: 'Follow the current user task.' },
+ { role: 'user', content: task, webbrainUserAuthoredText: task }]);
+ return agent;
+ }
+
+ function publicationFixture(agent, guardTaskKey = agent._progressTaskKeyHash(tabId)) {
+ const social = { key: 'private-contract', actionId: 'p1', deniedAuditKey: 'private-publication',
+ contract: { status: 'ready', requirements: { kind: 'all', items: ['p1'] }, actions: [{ id: 'p1' }] },
+ outcomes: {} };
+ agent._planExecutionGuards.set(tabId, { enabled: true, taskKey: guardTaskKey, pendingDownloadIds: [],
+ socialPublication: social });
+ return social;
+ }
+
+ test(`${browser}: recovery registry expires private task signatures even when normalized task keys match`, () => {
+ const registry = new FailureRecoveryRegistry();
+ const binding = { tabId, conversationId: 'c', taskKey: 'tk_same', taskSignature: 'exact-first' };
+ const descriptor = { recoveryId: 'r', stage: 'inference' };
+ registry.offer(binding, descriptor);
+ binding.conversationId = 'mutated';
+ descriptor.recoveryId = 'mutated';
+ assert.equal(registry.current({ tabId, conversationId: 'c', taskKey: 'tk_same', taskSignature: 'exact-first' }).descriptor.recoveryId, 'r');
+ assert.equal(registry.current({ tabId: 99, conversationId: 'c', taskKey: 'tk_same', taskSignature: 'exact-first' }), null);
+ assert.equal(registry.current({ tabId, conversationId: 'c', taskKey: 'tk_same', taskSignature: 'exact-second' }), null);
+ assert.equal(registry.current({ tabId, conversationId: 'c', taskKey: 'tk_same', taskSignature: 'exact-first' }), null);
+ });
+
+ test(`${browser}: model recovery keeps raw provider details outside the friendly message`, () => {
+ const error = Object.assign(new Error('webbrain-cloud error 400: {"error":{"code":"webbrain_cloud_upstream_error"}}'),
+ { code: 'webbrain_cloud_upstream_error' });
+ const model = modelFailureRecovery(error);
+ assert.match(model.message, /WebBrain Cloud/);
+ assert.doesNotMatch(model.message, /400|\{"error"/);
+ assert.equal(model.diagnostics, error.message);
+ const after = modelFailureRecovery(error, { postAction: true });
+ assert.match(after.message, /action may have completed/);
+ assert.match(after.message, /Review the current result before choosing Retry/);
+ });
+
+ test(`${browser}: checker trace budgets survive metadata projection while raw validation content stays private`, () => {
+ const request = projectTraceEventData('llm_request', { phase: 'planner_alignment', requestedMaxTokens: 2048,
+ messages: [{ role: 'user', content: 'private-task-body' }] });
+ assert.equal(request.requestedMaxTokens, 2048);
+ assert.doesNotMatch(JSON.stringify(request), /private-task-body/);
+ const response = projectTraceEventData('llm_response', { requestedMaxTokens: 4096, finishReason: 'length',
+ emptyReason: 'output_limit', content: 'private-checker-body' });
+ assert.equal(response.requestedMaxTokens, 4096);
+ assert.equal(response.emptyReason, 'output_limit');
+ assert.doesNotMatch(JSON.stringify(response), /private-checker-body/);
+ const known = projectTraceEventData('note', { note: 'publication_checker_validation_failed',
+ extra: { validationFailure: 'missing_authorized', attempt: 2, privateText: 'private-task-body' } });
+ assert.equal(known.extra.validationFailure, 'missing_authorized');
+ assert.doesNotMatch(JSON.stringify(known), /private-task-body/);
+ const unknown = projectTraceEventData('note', { note: 'publication_checker_validation_failed',
+ extra: { validationFailure: 'duplicate_private-user-authored-field', stage: 'private-stage',
+ retryMode: 'private-mode', candidateAttempt: 'private-attempt' } });
+ assert.doesNotMatch(JSON.stringify(unknown), /private-user-authored-field/);
+ assert.doesNotMatch(JSON.stringify(unknown), /private-stage|private-mode|private-attempt/);
+ const contract = projectTraceEventData('note', { note: 'publication_checker_validation_failed',
+ extra: { validationFailure: 'Invalid publication contract: ambiguous start anchor' } });
+ assert.equal(contract.extra.validationFailure, 'contract_ambiguous_start_anchor');
+ assert.deepEqual(projectTraceEventData('note', contract), contract, 'Repeated exports preserve canonical diagnostics.');
+ for (const kind of ['llm_request', 'llm_response']) {
+ const invalid = projectTraceEventData(kind, { requestedMaxTokens: 'private-token-budget', emptyReason: 'private-reason' });
+ assert.doesNotMatch(JSON.stringify(invalid), /private-token-budget|private-reason/);
+ }
+ });
+
+ test(`${browser}: explicit generic Retry consumes its opaque offer without granting an audit bypass`, () => {
+ const agent = setup(), events = [];
+ let grants = 0;
+ agent._grantSocialPublicationAuditRetry = () => { grants++; return true; };
+ const offer = agent._offerFailureRecovery(tabId, { ...generic, retryMode: 'publication_without_audit',
+ taskKey: 'private-task', publicationKey: 'private-publication' }, (type, data) => events.push({ type, data }));
+ assert.ok(/^recovery_[a-z0-9]{24}$/.test(offer.recoveryId));
+ assert.equal(offer.retryMode, 'resume');
+ assert.equal(events[0].type, 'failure_recovery');
+ const payload = JSON.stringify(offer);
+ assert.doesNotMatch(payload, /private-conversation|private-task|private-publication|taskSignature|taskKey|conversationId/);
+ assert.deepEqual(agent.requestFailureRecovery(tabId, offer.recoveryId, 'retry'),
+ { ok: true, continue: true, retryMode: 'resume' });
+ assert.equal(grants, 0);
+ assert.equal(agent._pendingFailureRecoveryForUi(tabId), null);
+ assert.equal(agent.requestFailureRecovery(tabId, offer.recoveryId, 'retry').ok, false);
+ });
+
+ test(`${browser}: Give up consumes the offer without continuing or granting publication permission`, () => {
+ const agent = setup();
+ let grants = 0;
+ agent._grantSocialPublicationAuditRetry = () => { grants++; return true; };
+ const offer = agent._offerFailureRecovery(tabId, { stage: 'publication_audit', taskKey: 't',
+ publicationKey: 'private-publication', message: 'Failed during the publication check.' });
+ const answer = agent.requestFailureRecovery(tabId, offer.recoveryId, 'give_up');
+ assert.equal(answer.ok, true);
+ assert.equal(answer.continue, false);
+ assert.equal(grants, 0);
+ assert.equal(agent._pendingFailureRecoveryForUi(tabId), null);
+ assert.equal(agent.requestFailureRecovery(tabId, offer.recoveryId, 'retry').ok, false);
+ });
+
+ test(`${browser}: Give up or Stop revokes an unused publication grant from live and carried state`, () => {
+ for (const choice of ['give_up', 'stop']) {
+ const agent = setup(), social = publicationFixture(agent);
+ assert.equal(agent._grantSocialPublicationAuditRetry(tabId, {
+ taskKey: agent._progressTaskKeyHash(tabId), publicationKey: social.deniedAuditKey }), true);
+ const carried = agent._continuationExecutionEvidence.get(tabId).socialPublication;
+ assert.ok(social.retryBypass);
+ assert.ok(carried.retryBypass);
+ const offer = agent._offerFailureRecovery(tabId, generic);
+ if (choice === 'give_up') assert.equal(agent.requestFailureRecovery(tabId, offer.recoveryId, choice).continue, false);
+ else agent.abort(tabId);
+ assert.equal(social.retryBypass, null);
+ assert.equal(carried.retryBypass, null);
+ assert.equal(social.contract.status, 'ready');
+ assert.equal(carried.contract.status, 'ready');
+ assert.equal(agent._pendingFailureRecoveryForUi(tabId), null);
+ }
+ });
+
+ test(`${browser}: invalid choices, wrong opaque IDs and other tabs cannot consume a valid offer`, () => {
+ const agent = setup();
+ const offer = agent._offerFailureRecovery(tabId, generic);
+ for (const [id, choice] of [[offer.recoveryId, 'approve'], ['unknown', 'retry'], ['', 'give_up']]) {
+ assert.equal(agent.requestFailureRecovery(tabId, id, choice).ok, false);
+ }
+ agent.conversationIds.set(99, 'private-conversation');
+ agent.conversations.set(99, structuredClone(agent.conversations.get(tabId)));
+ assert.equal(agent.requestFailureRecovery(99, offer.recoveryId, 'retry').ok, false);
+ assert.equal(agent._pendingFailureRecoveryForUi(tabId).recoveryId, offer.recoveryId);
+ });
+
+ for (const revision of ['conversation', 'new task', 'case-only task', 'whitespace-only task']) {
+ test(`${browser}: ${revision} invalidates the old recovery offer`, () => {
+ const agent = setup(), offer = agent._offerFailureRecovery(tabId, generic);
+ if (revision === 'conversation') agent.conversationIds.set(tabId, 'replacement-conversation');
+ else {
+ const revised = revision === 'case-only task' ? task.replace('Hello', 'hello')
+ : revision === 'whitespace-only task' ? task.replace('Hello', 'Hello ')
+ : 'Read the owned page without publishing.';
+ agent.conversations.get(tabId).push({ role: 'user', content: revised, webbrainUserAuthoredText: revised });
+ }
+ assert.equal(agent.requestFailureRecovery(tabId, offer.recoveryId, 'retry').ok, false);
+ assert.equal(agent._pendingFailureRecoveryForUi(tabId), null);
+ });
+ }
+
+ test(`${browser}: recovery choices wait for an active run and retain the offer until it finishes`, () => {
+ const agent = setup();
+ agent._runningTabs.add(tabId);
+ const offer = agent._offerFailureRecovery(tabId, generic);
+ assert.ok(offer, 'A winding-down failed run can display its terminal recovery.');
+ assert.equal(agent.requestFailureRecovery(tabId, offer.recoveryId, 'retry').ok, false);
+ assert.equal(agent._pendingFailureRecoveryForUi(tabId).recoveryId, offer.recoveryId);
+ agent._runningTabs.delete(tabId);
+ assert.equal(agent.requestFailureRecovery(tabId, offer.recoveryId, 'retry').continue, true);
+ });
+
+ test(`${browser}: claiming a later run invalidates an old offer for the same task`, async () => {
+ const agent = setup(), offer = agent._offerFailureRecovery(tabId, generic);
+ agent.assertRunStartAllowed = async () => {};
+ agent._beginPageFeedbackRun = async () => {};
+ await agent._claimRunEntry(tabId, 'interactive');
+ agent._releaseRunEntry(tabId);
+ assert.equal(agent.requestFailureRecovery(tabId, offer.recoveryId, 'retry').ok, false);
+ assert.equal(agent._pendingFailureRecoveryForUi(tabId), null);
+ });
+
+ test(`${browser}: cancellation and pending steering do not create a new recovery offer`, () => {
+ const agent = setup();
+ agent.abortFlags.set(tabId, true);
+ assert.equal(agent._offerFailureRecovery(tabId, generic), null);
+ agent.abortFlags.delete(tabId);
+ agent._beginSteeringRun(tabId, () => {}, {});
+ agent._steeringRuns.get(tabId).messages.push({ id: 's', text: 'Change the task.' });
+ assert.equal(agent._offerFailureRecovery(tabId, generic), null);
+ });
+
+ test(`${browser}: a failed publication grant expires recovery without allowing continuation`, () => {
+ const agent = setup();
+ const social = publicationFixture(agent);
+ const offer = agent._offerFailureRecovery(tabId, { stage: 'publication_audit', taskKey: agent._progressTaskKeyHash(tabId),
+ publicationKey: social.deniedAuditKey, message: 'Failed during publication.' });
+ social.needsRecompile = true;
+ const answer = agent.requestFailureRecovery(tabId, offer.recoveryId, 'retry');
+ assert.equal(answer.ok, false);
+ assert.notEqual(answer.continue, true);
+ assert.equal(social.retryBypass, undefined);
+ assert.equal(agent._pendingFailureRecoveryForUi(tabId), null);
+ });
+
+ test(`${browser}: publication Retry binds current steering authority separately from the initiating guard`, () => {
+ const agent = setup(), initiatingKey = agent._progressTaskKeyHash(tabId);
+ const correction = 'Use the same exact body with the corrected account.';
+ agent.conversations.get(tabId).push({ role: 'user', content: correction, webbrainUserAuthoredText: correction,
+ webbrainSteering: { requestId: 'owned-run', messageId: 'owned-steering', revision: 1, parentTaskKey: initiatingKey } });
+ assert.notEqual(agent._progressTaskKeyHash(tabId), initiatingKey);
+ const social = publicationFixture(agent, initiatingKey);
+ const offer = agent._offerFailureRecovery(tabId, { stage: 'publication_audit', taskKey: initiatingKey,
+ publicationKey: social.deniedAuditKey, message: 'Failed during publication.' });
+ assert.doesNotMatch(JSON.stringify(offer), /private-publication|taskKey|publicationTaskKey/);
+ const answer = agent.requestFailureRecovery(tabId, offer.recoveryId, 'retry');
+ assert.equal(answer.ok, true);
+ assert.equal(answer.continue, true);
+ assert.equal(social.retryBypass.taskKey, initiatingKey);
+ assert.equal(social.retryBypass.key, social.deniedAuditKey);
+ assert.equal(agent._continuationExecutionEvidence.get(tabId).socialPublication.retryBypass.taskKey, initiatingKey);
+ assert.equal(agent.requestFailureRecovery(tabId, offer.recoveryId, 'retry').ok, false);
+ });
+
+ test(`${browser}: post-submit recovery uses the real tool batch and observation recorder without replaying Submit`, async () => {
+ const agent = setup(), messages = agent.conversations.get(tabId), dispatched = [], errors = [];
+ const url = 'https://addons.mozilla.org/developers/addon/owned/finish';
+ const provider = { name: 'fixture', model: 'fixture', promptTier: 'full', supportsTools: true, config: {} };
+ agent.conversationModes.set(tabId, 'act');
+ agent._completionVerdicts = new Map();
+ agent._currentUrl = async () => url;
+ agent._skipPermissionGate = true;
+ agent._ensureGateSetting = async () => true;
+ agent._chromeProtectedPageFailure = async () => null;
+ agent._captchaMutationPreflight = async () => null;
+ agent._adoptLiveSocialPublishWorkflow = async () => false;
+ agent._workflowPreSubmitDispatchBlock = async () => null;
+ agent._messageRecipientGuardBlock = async () => null;
+ agent._detectLikelySubmitAction = async () => null;
+ agent._isFormValidationCandidate = () => false;
+ agent._preflightRichTextToolbarTarget = async () => ({ block: null });
+ agent._socialPublicationPreSubmitBlock = async () => null;
+ agent._auditRichTextToolbarTarget = async () => {};
+ agent._shouldAutoScreenshot = () => false;
+ agent._observeCaptchaChallenge = async () => ({ gate: null, loopCheck: { kind: 'none' } });
+ agent._observeHuggingFaceSignupRecovery = async () => null;
+ agent._planExecutionGuards.set(tabId, { requiresSubmission: true, requiresStateChange: true });
+ agent._beginCompletionInvariant(tabId);
+ agent._recordCompletionToolResult(tabId, 'click_ax', { ref_id: 'ref_submit' },
+ { success: true, dispatched: true, verified: true });
+ agent._recordCompletionSubmitAttempt(tabId, { isSubmit: true }, 'click_ax', { ref_id: 'ref_submit' },
+ url, url, { success: true, dispatched: true, verified: true }, 'document-1', 'document-1');
+ const before = agent.completionInvariants.get(tabId);
+ agent._lastAxScopes.set(tabId, { pageUrl: url, documentToken: 'document-1' });
+ agent.executeTool = async (_tab, name, args) => {
+ dispatched.push(name);
+ if (name === 'get_accessibility_tree') {
+ return { success: true, pageUrl: url, pageContent: 'status "Your submission was recorded" [ref_receipt]' };
+ }
+ assert.equal(name, 'done', 'Recovery may only observe and pass through the existing terminal pipeline.');
+ assert.equal(agent._completionSubmitStates.get(tabId).observedAfterSubmit, true);
+ assert.equal(agent._completionDoneBlock(tabId, 'done', args), null);
+ agent._completionVerdicts.set(tabId, { outcome: 'succeeded' });
+ return { success: true, done: true, outcome: 'success', summary: args.summary };
+ };
+ const executeBatch = agent._executeToolBatch.bind(agent);
+ agent._executeToolBatch = async (...args) => {
+ try { return await executeBatch(...args); } catch (error) { errors.push(String(error.stack || error)); throw error; }
+ };
+ const recovered = await agent._recoverPostActionModelFailure(tabId, messages, () => {}, provider, 4);
+ assert.equal(recovered?.status, 'done', JSON.stringify({ recovered, dispatched, errors }));
+ assert.match(recovered.content, /submitted for review/);
+ assert.deepEqual(dispatched, ['get_accessibility_tree', 'done']);
+ assert.notEqual(agent.completionInvariants.get(tabId), before);
+ assert.equal(agent.completionInvariants.get(tabId).lastAction.sequence, before.lastAction.sequence);
+ const recoveryCalls = messages.flatMap(message => message.tool_calls || []);
+ assert.equal(recoveryCalls.length, 2);
+ for (const call of recoveryCalls) {
+ assert.equal(messages.filter(message => message.role === 'tool' && message.tool_call_id === call.id).length, 1);
+ }
+ });
+
+ test(`${browser}: reconciliation stops on exact-task, conversation or in-place run-token changes during its read`, async () => {
+ for (const change of ['exact-task', 'conversation', 'run-token']) {
+ const agent = setup(), operations = [];
+ agent.conversationModes.set(tabId, 'act');
+ agent._beginCompletionInvariant(tabId);
+ agent._recordCompletionToolResult(tabId, 'click_ax', { ref_id: 'submit' }, { success: true, dispatched: true });
+ agent._completionSubmitStates.set(tabId, { dispatched: true });
+ agent._completionDoneBlock = () => null;
+ agent._executeToolBatch = async (_tab, calls) => {
+ const name = calls[0].function.name;
+ operations.push(name);
+ if (name === 'get_accessibility_tree') {
+ if (change === 'exact-task') agent.conversations.get(tabId).push({ role: 'user',
+ content: task.replace('Hello', 'hello'), webbrainUserAuthoredText: task.replace('Hello', 'hello') });
+ if (change === 'conversation') agent.conversationIds.set(tabId, 'replacement-conversation');
+ if (change === 'run-token') agent.completionInvariants.get(tabId).runToken = 'replacement-run';
+ }
+ return { action: 'continue' };
+ };
+ agent._currentUrl = async () => 'https://owned.example.test/result';
+ assert.equal(await agent._recoverPostActionModelFailure(tabId, agent.conversations.get(tabId), () => {}, {}, 4), null);
+ assert.deepEqual(operations, ['get_accessibility_tree'], change);
+ }
+ });
+
+ function messageBoundary(agent) {
+ const source = readFileSync(new URL(`../src/${browser}/src/background.js`, import.meta.url), 'utf8');
+ const start = source.indexOf('async function handleFailureRecoveryResponse(');
+ const end = source.indexOf('\nasync function handleMessage(', start);
+ assert.ok(start >= 0 && end > start);
+ const launches = [], starts = new Map();
+ let snapshot = null;
+ const context = vm.createContext({
+ chrome: extensionApi, browser: extensionApi, agent, detachedRunStarts: starts,
+ getRunUiSnapshot: async () => snapshot,
+ assertNoActiveTabRun: () => {
+ if (agent.isRunning(tabId) || starts.has(tabId)) throw new Error('An agent run is already active.');
+ },
+ launchDetachedRun: async (kind, message, sender) => {
+ launches.push({ kind, message, sender });
+ return { ok: true, accepted: true, requestId: message.requestId };
+ },
+ });
+ vm.runInContext(source.slice(start, end), context);
+ return { send: (message, sender = { url: extensionApi.runtime.getURL('src/ui/sidepanel.html') }) =>
+ context.handleFailureRecoveryResponse(message, sender), launches, starts, setSnapshot: value => { snapshot = value; } };
+ }
+
+ test(`${browser}: only the extension sidepanel can consume a recovery and launch its continuation`, async () => {
+ const agent = setup(), offer = agent._offerFailureRecovery(tabId, generic), boundary = messageBoundary(agent);
+ const message = { action: 'failure_recovery_response', tabId, recoveryId: offer.recoveryId,
+ choice: 'retry', requestId: 'owned-retry' };
+ for (const url of ['https://owned.example.test/', extensionApi.runtime.getURL('src/ui/settings.html')]) {
+ assert.equal((await boundary.send(message, { url })).ok, false);
+ }
+ assert.equal(boundary.launches.length, 0);
+ assert.equal(agent._pendingFailureRecoveryForUi(tabId).recoveryId, offer.recoveryId);
+ assert.equal((await boundary.send(message)).accepted, true);
+ assert.equal(boundary.launches.length, 1);
+ assert.equal(boundary.launches[0].kind, 'continue');
+ assert.equal((await boundary.send(message)).ok, false);
+ assert.equal(boundary.launches.length, 1);
+ });
+
+ test(`${browser}: background Give up and failed audit grants never launch a continuation`, async () => {
+ const agent = setup(), boundary = messageBoundary(agent);
+ const first = agent._offerFailureRecovery(tabId, generic);
+ assert.equal((await boundary.send({ tabId, recoveryId: first.recoveryId, choice: 'give_up' })).continue, false);
+ const publication = agent._offerFailureRecovery(tabId, { stage: 'publication_audit',
+ publicationKey: 'missing', taskKey: 'missing', message: 'Failed during publication.' });
+ assert.equal((await boundary.send({ tabId, recoveryId: publication.recoveryId, choice: 'retry', requestId: 'audit-retry' })).ok, false);
+ assert.equal(boundary.launches.length, 0);
+ });
+
+ test(`${browser}: the background rejects malformed recovery messages before consuming a valid offer`, async () => {
+ const agent = setup(), offer = agent._offerFailureRecovery(tabId, generic), boundary = messageBoundary(agent);
+ const good = { tabId, recoveryId: offer.recoveryId, choice: 'retry', requestId: 'owned-request' };
+ for (const changes of [{ tabId: 0 }, { tabId: -1 }, { tabId: 42.5 }, { tabId: 'invalid' },
+ { recoveryId: null }, { recoveryId: {} }, { choice: 'approve' }]) {
+ assert.equal((await boundary.send({ ...good, ...changes })).ok, false);
+ }
+ assert.equal(boundary.launches.length, 0);
+ assert.equal(agent._pendingFailureRecoveryForUi(tabId).recoveryId, offer.recoveryId);
+ });
+
+ test(`${browser}: duplicate delivery acknowledges an existing continuation without consuming another offer`, async () => {
+ const agent = setup(), offer = agent._offerFailureRecovery(tabId, generic), boundary = messageBoundary(agent);
+ const message = { tabId, recoveryId: offer.recoveryId, choice: 'retry', requestId: 'same-ui-request' };
+ boundary.starts.set(tabId, { requestId: message.requestId });
+ assert.equal((await boundary.send(message)).accepted, true);
+ boundary.starts.clear();
+ boundary.setSnapshot({ kind: 'continue', requestId: message.requestId });
+ assert.equal((await boundary.send(message)).accepted, true);
+ assert.equal(boundary.launches.length, 0);
+ assert.equal(agent._pendingFailureRecoveryForUi(tabId).recoveryId, offer.recoveryId);
+ });
+}
diff --git a/test/llm/lib/social-publication-score.test.mjs b/test/llm/lib/social-publication-score.test.mjs
index b4b9afa13..2fa6f6d34 100644
--- a/test/llm/lib/social-publication-score.test.mjs
+++ b/test/llm/lib/social-publication-score.test.mjs
@@ -75,6 +75,6 @@ test('runner exercises actual provider transport, repair loop and audits against
assert.equal(summary.compiler.firstValid, 2); assert.equal(summary.compiler.repairs, 1);
assert.equal(summary.audit.positive, 2); assert.equal(summary.audit.negative, 1); assert.equal(summary.audit.falseAllows, 0);
assert.equal(requests.length, 7); assert(requests.every(r => r.model === 'fixture-model' && !r.tools));
- assert(requests.every(r => [4096, 800].includes(r.max_tokens)));
+ assert(requests.every(r => [2048, 4096].includes(r.max_tokens)));
} finally { await new Promise(resolve => server.close(resolve)); fs.rmSync(output, { recursive: true, force: true }); }
});
diff --git a/test/llm/run-social-publication.mjs b/test/llm/run-social-publication.mjs
index 4c3597bb8..a7aacc262 100644
--- a/test/llm/run-social-publication.mjs
+++ b/test/llm/run-social-publication.mjs
@@ -7,7 +7,7 @@ import { execFileSync } from 'node:child_process';
import { parseArgs } from 'node:util';
import { Agent } from '../../src/chrome/src/agent/agent.js';
import { OpenAICompatibleProvider } from '../../src/chrome/src/providers/openai.js';
-import { normalizePublicationContract, publicationProgress, publicationAuditMessages, publicationAuditAccepted } from '../../src/chrome/src/agent/social-publish-contract.js';
+import { normalizePublicationContract, publicationProgress, publicationAuditMessages, publicationAuditValidation, parsePublicationJson } from '../../src/chrome/src/agent/social-publish-contract.js';
import { curated, auditChallenges } from './social-publication-cases.mjs';
import { scoreContract, snapshotFor, distribution } from './lib/social-publication-score.mjs';
@@ -61,7 +61,8 @@ const manifest = { startedAt: new Date().toISOString(), commit: execFileSync('gi
suite: args.suite, repeat, timeoutMs: timeout, concurrency: 1,
promptSha256: hash(fs.readFileSync('src/chrome/src/agent/social-publish-contract.js')),
fixtureSha256: hash(fs.readFileSync('test/llm/social-publication-cases.mjs')),
- limits: { compilerMaxTokens: 4096, compilerAttempts: 2, auditMaxTokens: 800, auditAttempts: 1 },
+ limits: { compilerMaxTokens: 2048, compilerRepairMaxTokens: 4096, compilerAttempts: 2,
+ auditMaxTokens: 2048, auditRepairMaxTokens: 4096, auditAttempts: 2 },
notes: ['Sequential calls measure client-observed latency; provider cold-start/cache state is unknown.', 'No browser actions or live publication. Provider credentials and hidden reasoning are not stored.', 'Media grading uses a finite witness set; legacy destination labels are exploratory, not accuracy ground truth.'] };
fs.writeFileSync(path.join(output, 'manifest.json'), JSON.stringify(manifest, null, 2));
const rows = [];
@@ -101,7 +102,7 @@ async function compile(fixture, run, suite = 'curated') {
try { result = await agent._ensureSocialPublicationContract(tabId, provider); } catch (e) { error = redact(e.message); }
const actual = result?.contract || null;
let firstValid = false;
- try { firstValid = !!normalizePublicationContract(Agent._extractFirstJsonObject(calls[0]?.output || ''), fixture.sources); } catch {}
+ try { firstValid = !!normalizePublicationContract(parsePublicationJson(calls[0]?.output), fixture.sources); } catch {}
const score = suite === 'curated' ? scoreContract(actual, golden.get(fixture.id)) : {};
const row = { suite, id: fixture.id, category: fixture.category, run, ms: Math.round(performance.now() - started), firstValid,
valid: !!actual, repaired: calls.length > 1, status: actual?.status || 'invalid', expectedStatus: golden.get(fixture.id)?.status || null, ...score,
@@ -117,13 +118,20 @@ async function compile(fixture, run, suite = 'curated') {
async function audit({ id, sources, proposed, action, snapshot, expected, category, run }) {
const key = hash(JSON.stringify({ id, sources, proposed, action, snapshot }));
const calls = [], started = performance.now();
- let accepted = false, valid = false, raw = null;
- try {
- const response = await chat(publicationAuditMessages(sources, proposed, action, snapshot, key), { temperature: 0, maxTokens: 800 }, 'social_publication_authorization', calls);
- raw = Agent._extractFirstJsonObject(response.content || '');
- valid = !!raw && Object.keys(raw).length === 4 && raw.key === key && raw.actionId === action.id && typeof raw.authorized === 'boolean' && typeof raw.reason === 'string' && raw.reason.length <= 600;
- accepted = publicationAuditAccepted(raw, key, action.id);
- } catch {}
+ let accepted = false, valid = false, portable = false;
+ const agent = new Agent({ getActive: () => provider });
+ const messages = publicationAuditMessages(sources, proposed, action, snapshot, key);
+ for (let attempt = 0; attempt < 2; attempt++) {
+ try {
+ const options = agent._socialPublicationChatOptions(provider, attempt > 0, portable, true);
+ const response = await chat(attempt ? agent._socialPublicationRepairMessages(messages) : messages,
+ options, 'social_publication_authorization', calls);
+ const verdict = publicationAuditValidation(agent._socialPublicationResponseObject(response, options), key, action.id);
+ if (!verdict.valid) throw new Error(verdict.failure);
+ valid = true; accepted = verdict.authorized;
+ break;
+ } catch (error) { if (agent._socialPublicationOptionsRejected(error)) portable = true; }
+ }
const row = { suite: 'audit', id, category, run, expected, accepted, valid, pass: valid && accepted === expected,
ms: Math.round(performance.now() - started), sources, proposed, actionId: action.id, snapshot, calls };
save(row); return row;
diff --git a/test/model-retry.mjs b/test/model-retry.mjs
index 5deac7ee0..09ff6302b 100644
--- a/test/model-retry.mjs
+++ b/test/model-retry.mjs
@@ -1,7 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
for (const browser of ['chrome','firefox']) {
- const {retryModelCall,retryAfterMs}=await import(`../src/${browser}/src/providers/model-retry.js`);
+ const {retryModelCall,retryAfterMs,retryModelStream}=await import(`../src/${browser}/src/providers/model-retry.js`);
const {OpenAICompatibleProvider}=await import(`../src/${browser}/src/providers/openai.js`);
const limited=(hint=null)=>Object.assign(new Error('HTTP 429'),{httpStatus:429,retryAfterMs:hint});
test(`${browser}: retry inference with growing cooldowns without replaying tools`,async()=>{
@@ -16,6 +16,21 @@ for (const browser of ['chrome','firefox']) {
await assert.rejects(retryModelCall(limited(),async()=>{calls++;throw limited();},{sleep:async ms=>waits.push(ms)}),/HTTP 429/);
assert.equal(calls,3);assert.deepEqual(waits,[5000,15000,30000]);
});
+ test(`${browser}: cloud upstream HTTP 400 retries inference twice and preserves its code`,async()=>{
+ const failure=Object.assign(new Error('Compass upstream unavailable'),{httpStatus:400,code:'webbrain_cloud_upstream_error'});
+ let calls=0;const waits=[];
+ const result=await retryModelCall(failure,async()=>{if(++calls===1)throw failure;return 'recovered';},{sleep:async ms=>waits.push(ms)});
+ assert.equal(result,'recovered');assert.equal(calls,2);assert.deepEqual(waits,[2000,5000]);
+ calls=0;waits.length=0;
+ await assert.rejects(retryModelCall(failure,async()=>{calls++;throw failure;},{sleep:async ms=>waits.push(ms)}),e=>e===failure);
+ assert.equal(calls,2);assert.deepEqual(waits,[2000,5000]);
+ });
+ test(`${browser}: a permanent error ends cloud upstream recovery immediately`,async()=>{
+ let calls=0;const failure=Object.assign(new Error('upstream'),{httpStatus:400,code:'webbrain_cloud_upstream_error'});
+ const permanent=Object.assign(new Error('invalid credentials'),{httpStatus:401});
+ await assert.rejects(retryModelCall(failure,async()=>{calls++;throw permanent;},{sleep:async()=>{}}),e=>e===permanent);
+ assert.equal(calls,1);
+ });
test(`${browser}: honor Retry-After and reject cooldowns beyond the recovery budget`,async()=>{
const now=Date.parse('2026-10-06T18:00:00Z');
assert.equal(retryAfterMs('10',now),10000);assert.equal(retryAfterMs('Tue, 06 Oct 2026 18:00:20 GMT',now),20000);
@@ -49,4 +64,57 @@ for (const browser of ['chrome','firefox']) {
assert.equal(result.content,'OK');assert.equal(requests.length,2);assert.deepEqual(requests[0],requests[1]);assert.equal(requests[1].tool_choice,'required');
}finally{globalThis.fetch=native;}
});
+ test(`${browser}: typed cloud startup failures retry the async stream before any event is emitted`,async()=>{
+ const failure=Object.assign(new Error('upstream'),{httpStatus:400,code:'webbrain_cloud_upstream_error'});
+ let starts=0,closed=0;const waits=[],notes=[],events=[];
+ const stream=retryModelStream(async()=>{await Promise.resolve();const attempt=++starts;return(async function*(){
+ try{if(attempt<3)throw failure;yield{type:'text',content:'Recovered'};yield{type:'done'};}finally{closed++;}
+ })();},{sleep:async ms=>waits.push(ms),onRetry:async note=>notes.push(note)});
+ for await(const event of stream)events.push(event);
+ assert.equal(starts,3);assert.equal(closed,3);assert.deepEqual(waits,[2000,5000]);
+ assert.deepEqual(notes.map(n=>n.attempt),[1,2]);
+ assert.deepEqual(events,[{type:'text',content:'Recovered'},{type:'done'}]);
+ });
+ test(`${browser}: a permanent or generic stream startup error is never retried`,async()=>{
+ for(const failure of [Object.assign(new Error('unauthorized'),{httpStatus:401}),new Error('network failed')]){
+ let starts=0,closed=0;
+ const stream=retryModelStream(()=>{starts++;return(async function*(){try{throw failure;}finally{closed++;}})();},
+ {sleep:async()=>assert.fail('No recovery delay for this startup error')});
+ await assert.rejects(async()=>{for await(const _event of stream)assert.fail('No events expected');},e=>e===failure);
+ assert.equal(starts,1);assert.equal(closed,1);
+ }
+ });
+ test(`${browser}: stream errors after the first event never restart or duplicate emitted output`,async()=>{
+ const failure=Object.assign(new Error('upstream'),{httpStatus:400,code:'webbrain_cloud_upstream_error'});
+ let starts=0,closed=0;const events=[];
+ const stream=retryModelStream(()=>{starts++;return(async function*(){
+ try{yield{type:'text',content:'Already emitted'};throw failure;}finally{closed++;}
+ })();},{sleep:async()=>assert.fail('Do not retry after stream output')});
+ await assert.rejects(async()=>{for await(const event of stream)events.push(event);},e=>e===failure);
+ assert.equal(starts,1);assert.equal(closed,1);assert.deepEqual(events,[{type:'text',content:'Already emitted'}]);
+ });
+ test(`${browser}: cancellation during stream startup cooldown prevents another iterator`,async()=>{
+ let aborted=false,starts=0,closed=0;
+ const failure=Object.assign(new Error('upstream'),{httpStatus:400,code:'webbrain_cloud_upstream_error'});
+ const stream=retryModelStream(()=>{starts++;return(async function*(){try{throw failure;}finally{closed++;}})();},
+ {isAborted:()=>aborted,sleep:async()=>{aborted=true;}});
+ await assert.rejects(async()=>{for await(const _event of stream)assert.fail('Cancelled startup emitted an event');},
+ e=>e.name==='AbortError');
+ assert.equal(starts,1);assert.equal(closed,1);
+ });
+ test(`${browser}: cancellation before the first stream event closes the live iterator`,async()=>{
+ let aborted=false,closed=0;const events=[];
+ const stream=retryModelStream(()=>(async function*(){
+ try{aborted=true;yield{type:'text',content:'Must not escape'};}finally{closed++;}
+ })(),{isAborted:()=>aborted,sleep:async()=>assert.fail('Do not retry cancellation')});
+ await assert.rejects(async()=>{for await(const event of stream)events.push(event);},e=>e.name==='AbortError');
+ assert.deepEqual(events,[]);assert.equal(closed,1);
+ });
+ test(`${browser}: breaking stream consumption closes its provider iterator`,async()=>{
+ let closed=0;
+ for await(const event of retryModelStream(()=>(async function*(){
+ try{yield{type:'text',content:'One'};yield{type:'text',content:'Two'};}finally{closed++;}
+ })())){assert.equal(event.content,'One');break;}
+ assert.equal(closed,1);
+ });
}
diff --git a/test/pending-clarification-hydration.mjs b/test/pending-clarification-hydration.mjs
index f2d6fff37..e8310e724 100644
--- a/test/pending-clarification-hydration.mjs
+++ b/test/pending-clarification-hydration.mjs
@@ -11,6 +11,7 @@ const builds = await Promise.all(['chrome', 'firefox'].map(async build => ({
journalModule: await import(`../src/${build}/src/run-ui-journal.js`),
source: await fs.readFile(new URL(`../src/${build}/src/ui/sidepanel.js`, import.meta.url), 'utf8'),
background: await fs.readFile(new URL(`../src/${build}/src/background.js`, import.meta.url), 'utf8'),
+ recoveryUi: await fs.readFile(new URL(`../src/${build}/src/ui/failure-recovery.js`, import.meta.url), 'utf8'),
})));
function extract(source, name) {
source = source.replace(/\r\n/g, '\n');
@@ -85,14 +86,16 @@ async function panel(f, options = {}) {
});
const names = ['applyActiveRunState', 'handleAgentUpdateMessage', 'ensureCurrentRunAssistant', 'isTerminalRunUiStatus',
'renderClarifyCard', 'addRunProgressReplayGapNote', 'clarificationSubmissionKey', 'invalidateUnresolvedClarifyCards',
- 'restorePendingCurrentClarification', 'submitClarify', 'restoreActiveRunState', 'placeAnsweredClarifyCardInTimeline', 'workflowHealingTargetLabel'];
+ 'restorePendingCurrentClarification', 'submitClarify', 'restoreActiveRunState', 'placeAnsweredClarifyCardInTimeline', 'workflowHealingTargetLabel',
+ 'syncFailureRecoveryButtons', 'bindFailureRecoveryCard', 'renderFailureRecoveryCard', 'reconcileFailureRecoveryCards'];
const functions = names.map(name => extract(f.source, name)).join('\n');
- const helpers = `${f.journalModule.runUiDiscardedBeforeSeq.toString()}\n${f.journalModule.runUiUnavailableBeforeSeq.toString()}`;
+ const helpers = `${f.journalModule.runUiDiscardedBeforeSeq.toString()}\n${f.journalModule.runUiUnavailableBeforeSeq.toString()}\n${f.recoveryUi.replaceAll('export function ', 'function ')}`;
await page.evaluate(({ functions, helpers, tab, options }) => {
document.body.innerHTML = '<div id="messages"><div class="message assistant"><div class="message-content"><div class="message-text"></div></div></div></div>';
const noop = () => {};
Object.assign(window, { messagesEl: document.querySelector('#messages'), currentTabId: tab, renderedTabId: tab,
currentAssistantEl: document.querySelector('.assistant'), localRunRequestIds: new Map(options.staleLocalOwner ? [[tab, 'newer-local-request']] : []),
+ processingTabs: new Set(), agentMode: 'act', isProcessing: false,
submittedClarificationIds: new Set(), clearedConversationRunRequestIds: new Set(), cancelledRunRecoveryRequestIds: new Set(),
streamedAssistantTextByEl: new WeakMap(), failedConversationClearRecoveryTabs: new Set(), soundCount: 0,
CAPABILITY_LABEL: { click: 'click' }, t: x => x, sameTabId: (a,b) => Number(a) === Number(b), normalizePlanReviewTabId: Number,
diff --git a/test/planner-repair-authority.mjs b/test/planner-repair-authority.mjs
index e25020919..462c2ed52 100644
--- a/test/planner-repair-authority.mjs
+++ b/test/planner-repair-authority.mjs
@@ -257,8 +257,8 @@ for (const browser of ['chrome', 'firefox']) {
async function run({ task = newTask, candidates = [plan(true), plan()], verdicts = [false, true],
history = 'User: ' + oldTask + '\nAssistant: The result is 323.', priorTask = oldTask,
mode = 'confidence', options = {}, staleBinding = false, messages: transcript = null, enriched = null,
- alignmentEffect = null } = {}) {
- const provider = { model: 'neutral-task-alignment-fixture', name: 'neutral-task-alignment-fixture', config: {} };
+ alignmentEffect = null, alignmentResponse = null, providerConfig = {} } = {}) {
+ const provider = { model: 'neutral-task-alignment-fixture', name: 'neutral-task-alignment-fixture', config: providerConfig };
const agent = new Agent({ getActive: () => provider, getVisionProvider: async () => null });
agent.setPlanReviewSettings({ mode, confidenceThreshold: 0.8 });
agent.useSiteAdapters = false;
@@ -272,7 +272,7 @@ for (const browser of ['chrome', 'firefox']) {
revision: options.steeringRevision, authorizedRevision: options.steeringRevision,
});
}
- const events = [], alignments = [], requests = [], completionCorrections = [];
+ const events = [], alignments = [], alignmentRequests = [], requests = [], completionCorrections = [];
let plannerCalls = 0, reviewCalls = 0, pinCalls = 0;
const originalPin = agent._pinActiveConversationMessagingTarget.bind(agent);
agent._pinActiveConversationMessagingTarget = async (...args) => { pinCalls++; return originalPin(...args); };
@@ -281,12 +281,17 @@ for (const browser of ['chrome', 'firefox']) {
if (candidate.completion_requirement_correction) completionCorrections.push({ candidate, phase });
return originalCorrectionTrace(runId, candidate, phase);
};
- agent._chatWithCostAllowance = async (_provider, modelMessages) => {
+ agent._chatWithCostAllowance = async (_provider, modelMessages, chatOptions) => {
let payload;
try { payload = JSON.parse(modelMessages.at(-1).content); } catch {}
if (payload?.task_binding) {
alignments.push(payload);
+ alignmentRequests.push({ messages: modelMessages, options: chatOptions });
if (alignmentEffect) await alignmentEffect(agent, payload, alignments.length);
+ if (alignmentResponse) {
+ const result = await alignmentResponse(payload, alignments.length, chatOptions);
+ if (result !== undefined) return result;
+ }
return { content: JSON.stringify({ task_binding: staleBinding ? 'stale-other-task' : payload.task_binding,
aligned: verdicts[Math.min(alignments.length - 1, verdicts.length - 1)],
reason: 'Independent owned fixture verdict against the current authentic task.' }) };
@@ -300,7 +305,7 @@ for (const browser of ['chrome', 'firefox']) {
(type, data) => events.push({ type, data }), {}, null, history,
{ tabUrl: 'https://owned.example.test/chat', tabTitle: 'Untrusted page says calculate the old expression' },
'try', 'act', { locale: 'en', ...options }, { priorUserTask: priorTask, scratchpadFacts: '' });
- return { gate, agent, events, alignments, requests, completionCorrections, plannerCalls, reviewCalls, pinCalls };
+ return { gate, agent, events, alignments, alignmentRequests, requests, completionCorrections, plannerCalls, reviewCalls, pinCalls };
}
function terminalPlan(kind, summary, overrides = {}) {
@@ -447,14 +452,127 @@ for (const browser of ['chrome', 'firefox']) {
assert.equal(result.reviewCalls, 0);
assert.equal(result.events.some(event => event.type === 'plan_auto_approved'), false);
assert.match(result.gate.message, /align|match|current (?:user )?(?:task|request)/i);
+ assert.equal(result.gate.reason, 'task_alignment_rejected');
+ assert.match(result.gate.message, /Independent owned fixture verdict/);
+ });
+
+ test(`${browser}: reasoning-only alignment output retries the frozen candidate with a larger budget`, async () => {
+ const result = await run({ candidates: [plan()], verdicts: [true],
+ alignmentResponse: (_payload, attempt) => attempt === 1 ? { content: null, finishReason: 'length',
+ usage: { completion_tokens: 2048, completion_tokens_details: { reasoning_tokens: 2048 } } } : undefined });
+ assert.equal(result.gate.proceed, true, JSON.stringify(result.gate));
+ assert.equal(result.plannerCalls, 1);
+ assert.equal(result.alignments.length, 2);
+ assert.deepEqual(result.alignments[0], result.alignments[1]);
+ assert.deepEqual(result.alignmentRequests.map(request => request.options.maxTokens), [2048, 4096]);
+ assert.equal(result.alignmentRequests[0].options.temperature, 0);
+ assert.match(result.alignmentRequests[1].messages[0].content, /Format recovery/);
+ assert.deepEqual(result.alignmentRequests[0].messages.filter(message => message.role === 'user'),
+ result.alignmentRequests[1].messages.filter(message => message.role === 'user'));
+ });
+
+ test(`${browser}: repeated malformed alignment stops checking without replanning or approval`, async () => {
+ const result = await run({ candidates: [plan()], alignmentResponse: () => ({ content: '{"aligned":' }) });
+ assert.equal(result.gate.proceed, false);
+ assert.equal(result.gate.reason, 'task_alignment_unverified');
+ assert.equal(result.gate.failureRecovery.stage, 'plan_alignment');
+ assert.match(result.gate.message, /unreadable verdict/);
+ assert.equal(result.plannerCalls, 1);
+ assert.equal(result.alignments.length, 2);
+ assert.equal(result.pinCalls, 0);
+ assert.equal(result.reviewCalls, 0);
+ assert.equal(result.events.some(event => event.type === 'plan_auto_approved'), false);
});
+ test(`${browser}: valid-looking truncated alignment must recover before approving`, async () => {
+ const result = await run({ candidates: [plan()], verdicts: [true], alignmentResponse: (payload, attempt) =>
+ attempt === 1 ? { content: JSON.stringify({ task_binding: payload.task_binding, aligned: true, reason: 'Matches.' }),
+ raw: { choices: [{ finish_reason: 'length' }] } } : undefined });
+ assert.equal(result.gate.proceed, true);
+ assert.equal(result.plannerCalls, 1);
+ assert.equal(result.alignments.length, 2);
+ });
+
+ test(`${browser}: format recovery can reject a candidate then audit its replacement with a new binding`, async () => {
+ const result = await run({ verdicts: [false, false, true],
+ alignmentResponse: (_payload, attempt) => attempt === 1 ? { content: null, reasoningContent: 'Checking...' } : undefined });
+ assert.equal(result.gate.proceed, true, JSON.stringify(result.gate));
+ assert.equal(result.plannerCalls, 2);
+ assert.equal(result.alignments.length, 3);
+ assert.equal(result.alignments[0].task_binding, result.alignments[1].task_binding);
+ assert.notEqual(result.alignments[1].task_binding, result.alignments[2].task_binding);
+ assert.deepEqual(result.alignmentRequests.map(request => request.options.maxTokens), [2048, 4096, 2048]);
+ });
+
+ test(`${browser}: alignment controls fall back only after an explicit provider rejection`, async () => {
+ const result = await run({ candidates: [plan()], verdicts: [true], providerConfig: { providerName: 'openrouter' },
+ alignmentResponse: (_payload, attempt) => {
+ if (attempt === 1) throw new Error('HTTP 400: unsupported parameter response_format');
+ } });
+ assert.equal(result.gate.proceed, true, JSON.stringify(result.gate));
+ assert.equal(result.plannerCalls, 1);
+ assert.equal(result.alignments.length, 2);
+ assert.ok(result.alignmentRequests[0].options.extraBody.response_format);
+ assert.equal(result.alignmentRequests[1].options.extraBody, undefined);
+ assert.equal(result.alignments[0].task_binding, result.alignments[1].task_binding);
+ });
+
+ test(`${browser}: generic provider failure never triggers speculative plan repair or control fallback`, async () => {
+ const result = await run({ candidates: [plan()], providerConfig: { providerName: 'openrouter' },
+ alignmentResponse: () => { throw new Error('HTTP 400: webbrain_cloud_upstream_error'); } });
+ assert.equal(result.gate.proceed, false);
+ assert.equal(result.gate.reason, 'task_alignment_unverified');
+ assert.match(result.gate.message, /model provider/);
+ assert.equal(result.plannerCalls, 1);
+ assert.equal(result.alignments.length, 1);
+ assert.equal(result.pinCalls, 0);
+ });
+
+ test(`${browser}: both alignment attempts honor the provider output ceiling`, async () => {
+ const result = await run({ candidates: [plan()], verdicts: [true], providerConfig: { maxOutputTokens: 1024 },
+ alignmentResponse: (_payload, attempt) => attempt === 1 ? { content: '' } : undefined });
+ assert.equal(result.gate.proceed, true);
+ assert.deepEqual(result.alignmentRequests.map(request => request.options.maxTokens), [1024, 1024]);
+ });
+
+ for (const interruption of ['stop', 'steering', 'cost']) {
+ test(`${browser}: ${interruption} during alignment format recovery prevents execution`, async () => {
+ const result = await run({ candidates: [plan()], verdicts: [true],
+ alignmentResponse: (_payload, attempt) => attempt === 1 ? { content: null } : undefined,
+ alignmentEffect: (agent, _payload, attempt) => {
+ if (attempt !== 2) return;
+ if (interruption === 'stop') agent.abortFlags.set(42, true);
+ if (interruption === 'steering') {
+ agent._beginSteeringRun(42, () => {}, {});
+ agent._steeringRuns.get(42).messages.push({ id: 'format-correction', text: 'Pause for a correction.' });
+ }
+ if (interruption === 'cost') {
+ const error = new Error('Checker exceeded its cost allowance.');
+ error.code = 'WB_COST_ALLOWANCE';
+ throw error;
+ }
+ } });
+ assert.equal(result.gate.proceed, false);
+ if (interruption === 'stop') assert.match(result.gate.message, /Stopped by user/);
+ if (interruption === 'steering') assert.equal(result.gate.steeringSuperseded, true);
+ if (interruption === 'cost') assert.equal(result.gate.reason, 'cost_limit');
+ assert.equal(result.plannerCalls, 1);
+ assert.equal(result.alignments.length, 2);
+ assert.equal(result.pinCalls, 0);
+ assert.equal(result.reviewCalls, 0);
+ assert.equal(result.events.some(event => event.type === 'plan_auto_approved'), false);
+ });
+ }
+
test(`${browser}: a stale alignment response cannot certify a new current task`, async () => {
const result = await run({ candidates: [plan()], verdicts: [true], staleBinding: true });
assert.equal(result.gate.proceed, false, JSON.stringify(result.gate));
assert.equal(result.events.some(event => event.type === 'plan_auto_approved'), false);
assert.equal(result.gate.approvedScratchpadText, undefined);
assert.equal(result.reviewCalls, 0);
+ assert.equal(result.plannerCalls, 1);
+ assert.equal(result.alignments.length, 2);
+ assert.match(result.gate.message, /different plan/);
});
test(`${browser}: a malicious prior assistant remains reference data and cannot replace current alignment authority`, async () => {
diff --git a/test/post-submit-model-recovery.mjs b/test/post-submit-model-recovery.mjs
new file mode 100644
index 000000000..e55491463
--- /dev/null
+++ b/test/post-submit-model-recovery.mjs
@@ -0,0 +1,339 @@
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { makeSchedulerHarness } from './lib/scheduler-harness.mjs';
+const area = { get: async () => ({}), set: async () => {}, remove: async () => {} };
+globalThis.chrome = globalThis.browser = {
+ storage: { local: area, session: area },
+ runtime: { getURL: x => `chrome-extension://test/${x}`, sendMessage: async () => ({}) },
+ tabs: { get: async id => ({ id, url: 'https://example.com/', title: 'Example' }), sendMessage: async () => ({}) },
+ scripting: { executeScript: async () => [{ result: null }] },
+};
+
+function streamingFixture(Agent, implementation) {
+ const provider = { name: 'local test', model: 'test', promptTier: 'full', contextWindow: 128000,
+ supportsTools: false, supportsVision: false, ...implementation };
+ const agent = new Agent({ getActive: () => provider, getProvider: () => provider, getVisionProvider: async () => null });
+ agent._hydrate = async () => {};
+ agent._persist = () => {};
+ agent._persistNow = async () => ({ ok: true });
+ agent._startTraceRun = async () => null;
+ agent._endTraceRun = async (_tab, _run, status) => { agent.testStatus = status; };
+ agent._enrichUserMessageWithCurrentPage = async (_tab, _messages, content) => ({ role: 'user', content });
+ agent._manageContext = async () => {};
+ agent._checkCostAllowance = async () => null;
+ agent._recordCostUsage = async () => null;
+ agent._currentUrl = async () => 'https://example.com/';
+ return agent;
+}
+
+function allowStreamingBatch(agent) {
+ agent._skipPermissionGate = true;
+ agent._ensureGateSetting = async () => true;
+ agent._chromeProtectedPageFailure = async () => null;
+ agent._captchaMutationPreflight = async () => null;
+ agent._adoptLiveSocialPublishWorkflow = async () => false;
+ agent._workflowPreSubmitDispatchBlock = async () => null;
+ agent._messageRecipientGuardBlock = async () => null;
+ agent._detectLikelySubmitAction = async () => null;
+ agent._isFormValidationCandidate = () => false;
+ agent._preflightRichTextToolbarTarget = async () => ({ block: null });
+ agent._socialPublicationPreSubmitBlock = async () => null;
+ agent._auditRichTextToolbarTarget = async () => {};
+ agent._shouldAutoScreenshot = () => false;
+ agent._resolveVisionRoute = async () => ({ provider: null });
+ agent._beginReadCompleteness = async () => null;
+ agent._maybeRunPlannerGate = async () => ({ proceed: true, requiresStateChange: false });
+ agent._observeCaptchaChallenge = async () => ({ gate: null, loopCheck: { kind: 'none' } });
+}
+
+for (const browser of ['chrome', 'firefox']) {
+ const { Agent } = await import(`../src/${browser}/src/agent/agent.js`);
+ const scheduler = await import(`../src/${browser}/src/agent/scheduler.js`);
+ const { verifyBrowserCompletion } = await import(`../src/${browser}/src/agent/completion-runtime.js`);
+ function fixture({ verdict = 'succeeded', mutate = () => {}, iframe = false } = {}) {
+ const agent = new Agent({}), tab = 790, operations = [], messages = [], updates = [];
+ agent.conversationModes.set(tab, 'act');
+ agent._completionVerdicts = new Map();
+ agent.conversations.set(tab, messages);
+ agent.conversationIds.set(tab, 'owned-conversation');
+ agent._progressTaskKeyHash = () => 'owned-task';
+ agent._progressTaskAnchorText = () => 'Submit this AMO version for review.';
+ agent._currentUrl = async () => 'https://addons.mozilla.org/developers/addon/owned/finish';
+ agent._completionIframeBinding = () => iframe ? { currentUrl: 'https://owned.example/frame' } : null;
+ agent._completionDoneBlock = () => agent.completionInvariants.get(tab)?.verificationDebt ? { reason: 'verification_required' } : null;
+ agent.completionInvariants.set(tab, { runToken: 'owned-run', sequence: 3, verificationDebt: true,
+ lastAction: { name: 'click_ax', sequence: 3, uncertain: true } });
+ agent._completionSubmitStates.set(tab, { dispatched: true });
+ agent._executeToolBatch = async (_tab, calls, transcript) => {
+ const call = calls[0], name = call.function.name, args = JSON.parse(call.function.arguments);
+ operations.push({ name, args });
+ if (name !== 'done') {
+ const previous = agent.completionInvariants.get(tab);
+ // Real observation recording replaces the invariant object.
+ agent.completionInvariants.set(tab, { ...previous, sequence: previous.sequence + 1, verificationDebt: false });
+ transcript.push({ role: 'tool', tool_call_id: call.id, content: '{"success":true}' });
+ mutate(agent);
+ return { action: 'continue' };
+ }
+ agent._completionVerdicts.set(tab, { outcome: verdict });
+ transcript.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify({ done: verdict === 'succeeded' }) });
+ return { action: 'return', value: args.summary };
+ };
+ return { agent, tab, messages, operations, updates, update: (type, data) => updates.push({ type, data }) };
+ }
+
+ test(`${browser}: post-submit cloud failure observes and verifies without repeating Submit`, async () => {
+ const f = fixture();
+ const result = await f.agent._recoverPostActionModelFailure(f.tab, f.messages, f.update, {}, 4);
+ assert.equal(result.status, 'done');
+ assert.match(result.content, /submitted for review/);
+ assert.deepEqual(f.operations.map(x => x.name), ['get_accessibility_tree', 'done']);
+ assert.equal(f.messages.filter(x => x.role === 'assistant').length, 2);
+ });
+ test(`${browser}: uncertain verdict leaves a partial result and a user recovery choice`, async () => {
+ const f = fixture({ verdict: 'uncertain' });
+ const error = Object.assign(new Error('raw private provider error'), { code: 'webbrain_cloud_upstream_error' });
+ const result = await f.agent._finalModelFailure(f.tab, f.messages, f.update, {}, error, 4);
+ assert.equal(result.status, 'partial');
+ assert.match(result.content, /final verification/);
+ assert.doesNotMatch(result.content, /raw private/);
+ assert.deepEqual(f.operations.map(x => x.name), ['get_accessibility_tree', 'done']);
+ assert.equal(f.updates.find(x => x.type === 'failure_recovery').data.retryMode, 'resume');
+ assert.equal(f.updates.at(-1).type, 'error');
+ });
+ test(`${browser}: recovery uses the submitted frame when present`, async () => {
+ const f = fixture({ iframe: true });
+ await f.agent._recoverPostActionModelFailure(f.tab, f.messages, f.update, {}, 4);
+ assert.deepEqual(f.operations[0], { name: 'verify_form', args: { urlFilter: 'https://owned.example/frame' } });
+ });
+ test(`${browser}: changed run or task after observation cannot be certified`, async () => {
+ for (const mutate of [a => { a.completionInvariants.get(790).runToken = 'changed'; },
+ a => { a._progressTaskKeyHash = () => 'changed'; }]) {
+ const f = fixture({ mutate });
+ assert.equal(await f.agent._recoverPostActionModelFailure(f.tab, f.messages, f.update, {}, 4), null);
+ assert.deepEqual(f.operations.map(x => x.name), ['get_accessibility_tree']);
+ }
+ });
+ test(`${browser}: errors before submission do not invent action evidence`, async () => {
+ const f = fixture(); f.agent._completionSubmitStates.delete(f.tab);
+ assert.equal(await f.agent._recoverPostActionModelFailure(f.tab, f.messages, f.update, {}, 4), null);
+ assert.deepEqual(f.operations, []);
+ });
+
+ test(`${browser}: response generation failures and empty output offer a bound generic Retry`, async () => {
+ for (const result of ['failure', 'empty']) {
+ const f = fixture(); f.agent.conversationModes.set(f.tab, 'ask');
+ f.agent._persist = () => {};
+ f.agent._generateContextOnlyResponse = async () => {
+ if (result === 'failure') throw new Error('private provider diagnostics');
+ return '';
+ };
+ const answer = await f.agent._completeResponseOnlyTurn(f.tab, f.messages, f.update, {}, {}, null);
+ assert.equal(answer.status, result === 'failure' ? 'error' : 'empty_output');
+ assert.doesNotMatch(answer.content, /private provider/);
+ const offer = f.updates.find(x => x.type === 'failure_recovery').data;
+ assert.equal(offer.stage, 'response_generation');
+ assert.equal(offer.retryMode, 'resume');
+ assert.equal(f.agent.requestFailureRecovery(f.tab, offer.recoveryId, 'retry').continue, true);
+ assert.deepEqual(f.operations, []);
+ }
+ });
+
+ test(`${browser}: quota or superseded response failures do not offer generic recovery`, async () => {
+ for (const reason of ['quota', 'steering']) {
+ const f = fixture(); f.agent._persist = () => {};
+ f.agent._generateContextOnlyResponse = async () => {
+ throw Object.assign(new Error('provider failure'), reason === 'quota' ? { quota: { remaining: 0 } } : {});
+ };
+ f.agent._hasPendingSteering = () => reason === 'steering';
+ const answer = await f.agent._completeResponseOnlyTurn(f.tab, f.messages, f.update, {}, {}, null);
+ assert.equal(answer.status, reason === 'steering' ? 'steering_superseded' : 'error');
+ assert.equal(f.updates.some(x => x.type === 'failure_recovery'), false);
+ assert.equal(f.agent._pendingFailureRecoveryForUi(f.tab), null);
+ }
+ });
+
+ test(`${browser}: a stopped interaction offers Retry without replaying tools or overriding publication audit`, async () => {
+ const f = fixture(); f.agent._persist = () => {};
+ f.agent._generateContextOnlyResponse = async () => '';
+ const answer = await f.agent._recoverLoopStoppedTurn(f.tab, f.messages, f.update, {}, {}, null, 4,
+ 'The interaction could not complete.');
+ assert.equal(answer.status, 'loop_stopped');
+ const offer = f.updates.find(x => x.type === 'failure_recovery').data;
+ assert.equal(offer.stage, 'browser_interaction');
+ assert.equal(offer.retryMode, 'resume');
+ assert.deepEqual(f.operations, []);
+ });
+
+ test(`${browser}: real streaming loop retries startup cloud400 without replaying completed browser tools`, async () => {
+ let starts = 0;
+ const summary = 'Verified Example Domain.';
+ const read = { id: 'startup-read', type: 'function', function: { name: 'read_page', arguments: '{}' } };
+ const done = { id: 'startup-done', type: 'function', function: { name: 'done', arguments: JSON.stringify({ summary, outcome: 'success' }) } };
+ const agent = streamingFixture(Agent, { supportsTools: true, async *chatStream() {
+ starts++;
+ if (starts === 2) throw Object.assign(new Error('upstream'), { httpStatus: 400, code: 'webbrain_cloud_upstream_error' });
+ assert.ok(starts <= 3, 'The stream retry must remain bounded');
+ yield { type: 'tool_call', content: [{ ...(starts === 1 ? read : done), index: 0 }] };
+ yield { type: 'done', finishReason: 'tool_calls' };
+ } });
+ allowStreamingBatch(agent); agent.maxSteps = 4;
+ const dispatched = [], updates = [];
+ agent.executeTool = async (_tab, name, args) => {
+ dispatched.push(name);
+ return name === 'done' ? { done: true, summary: args.summary, outcome: args.outcome } : { success: true, text: 'Example Domain' };
+ };
+ const answer = await agent.processMessageStream(791, 'Read the current page title. Read only.',
+ (type, data) => updates.push({ type, data }), 'act', { askStreamingEnabled: false });
+ assert.equal(answer, summary);
+ assert.equal(agent.testStatus, 'done');
+ assert.equal(starts, 3);
+ assert.deepEqual(dispatched, ['read_page', 'done']);
+ assert.equal(updates.filter(x => x.type === 'thinking' && /could not start.*Retrying/.test(x.data.note || '')).length, 1);
+ const history = agent.getConversation(791, 'act');
+ assert.equal(history.flatMap(x => x.tool_calls || []).filter(x => x.id === done.id).length, 1);
+ assert.equal(history.filter(x => x.role === 'tool' && x.tool_call_id === done.id).length, 1);
+ const pending = new Set();
+ for (const message of history) {
+ if (message.role === 'tool') assert.equal(pending.delete(message.tool_call_id), true, 'Each tool result pairs once');
+ else {
+ assert.equal(pending.size, 0, 'Each tool batch completes before another message');
+ for (const call of message.tool_calls || []) pending.add(call.id);
+ }
+ }
+ assert.equal(pending.size, 0);
+ });
+
+ test(`${browser}: real streaming loop does not automatically retry permanent startup errors`, async () => {
+ let starts = 0, toolDispatches = 0;
+ const agent = streamingFixture(Agent, { async *chatStream() {
+ starts++;
+ throw Object.assign(new Error('private authentication diagnostics'), { httpStatus: 401 });
+ } });
+ agent.maxSteps = 1;
+ agent.executeTool = async () => { toolDispatches++; throw new Error('Unexpected browser tool'); };
+ const updates = [];
+ const answer = await agent.processMessageStream(792, 'Hello', (type, data) => updates.push({ type, data }),
+ 'ask', { standaloneChat: true });
+ assert.equal(starts, 1);
+ assert.equal(toolDispatches, 0);
+ assert.equal(agent.testStatus, 'error');
+ assert.equal(updates.some(x => x.type === 'thinking' && /Retrying/.test(x.data.note || '')), false);
+ assert.equal(updates.filter(x => x.type === 'failure_recovery').length, 1);
+ assert.doesNotMatch(answer, /private authentication/);
+ });
+
+ for (const scenario of ['current', 'exact-task', 'conversation', 'run', 'action', 'stop']) {
+ test(`${browser}: post-submit recovery settles the actual scheduled checkpoint only while ${scenario} authority remains current`, async () => {
+ let enter, release;
+ const entered = new Promise(resolve => { enter = resolve; });
+ const resumed = new Promise(resolve => { release = resolve; });
+ const state = { task: 'Acknowledge the new release once.', tree: 'status "Acknowledgement recorded for release-11"',
+ sourceId: '', tabId: null, callbacks: 0, judgments: 0, operations: [], recovered: null, recoveryError: null };
+ const controller = new AbortController();
+ const provider = { name: 'owned test', model: 'owned-model', supportsVision: false, config: { category: 'local' }, chat() {} };
+ const agent = new Agent({ getActive: () => provider });
+ const harness = makeSchedulerHarness(scheduler, { requireConfirmation: false });
+ harness.manager.agent = agent;
+ agent._checkAbort = () => controller.signal.aborted;
+ agent._runAbortSignal = () => controller.signal;
+ agent.abort = () => controller.abort();
+ agent._hasPendingSteering = agent._hasUnvalidatedSteering = () => false;
+ agent._progressTaskKeyHash = () => 'owned-scheduled-task';
+ agent._progressTaskAnchorText = () => state.task;
+ agent._currentUrl = async () => 'https://example.com/';
+ agent._completionDocumentStamp = async () => 'owned-scheduled-document';
+ agent._completionLiveStatusMessages = async () => [state.tree];
+ agent.executeTool = async () => ({ success: true, pageContent: state.tree });
+ agent.recordSystemOneVerdict = () => {};
+ agent._persistNow = async () => ({ ok: true });
+ agent._chatWithCostAllowance = async () => {
+ state.judgments++;
+ return { content: '{"outcome":"succeeded","reason":"Fresh owned release acknowledgement."}' };
+ };
+ agent._executeToolBatch = async (tabId, calls, messages) => {
+ const call = calls[0], name = call.function.name, args = JSON.parse(call.function.arguments);
+ state.operations.push(name);
+ if (name === 'get_accessibility_tree') {
+ const result = { success: true, pageContent: state.tree };
+ messages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
+ agent._recordCompletionToolResult(tabId, name, args, result);
+ return { action: 'continue' };
+ }
+ assert.equal(name, 'done', 'Recovery can only inspect and complete the submission');
+ const pageUrl = 'https://example.com/';
+ const verdict = await verifyBrowserCompletion(agent, tabId, { pageUrl, pageState: {}, summary: args.summary });
+ assert.equal(verdict.outcome, 'succeeded');
+ const result = { done: true, outcome: 'success', summary: args.summary,
+ verification: { pageUrl, pageState: {}, completionWarning: null,
+ decision: { outcome: verdict.outcome, engine: verdict.engine } } };
+ messages.push({ role: 'tool', tool_call_id: call.id, content: agent._wrapUntrusted('done', JSON.stringify(result)) });
+ agent._recordCompletionToolResult(tabId, name, args, result);
+ return { action: 'return', value: args.summary, rawSummary: args.summary };
+ };
+ agent.processMessage = async (tabId, text, onUpdate, _mode, _attachments, runOptions) => {
+ state.tabId = tabId;
+ const messages = [{ role: 'system', content: 'Owned scheduled recovery.' }, { role: 'user', content: text }];
+ agent.conversations.set(tabId, messages);
+ agent.conversationModes.set(tabId, 'act');
+ agent.conversationIds.set(tabId, 'owned-scheduled-conversation');
+ agent._beginCompletionInvariant(tabId);
+ assert.equal(await runOptions.beforeConsequentialTool({ name: 'click_ax' }), true);
+ state.pending = structuredClone(harness.jobs().find(job => job.id === state.sourceId).pendingToolCall);
+ const click = { success: true, dispatched: true, verified: false, inconclusive: true, observedEffects: ['network_request'] };
+ agent._recordCompletionToolResult(tabId, 'click_ax', {}, click);
+ agent._completionSubmitStates.set(tabId, { dispatched: true });
+ assert.equal(await runOptions.afterConsequentialTool({ name: 'click_ax', result: click, outcomeUnknown: true }), false);
+ try {
+ state.recovered = await agent._recoverPostActionModelFailure(tabId, messages, onUpdate, provider, 3, {
+ ...runOptions,
+ afterVerifiedCompletion: async proof => {
+ state.callbacks++;
+ enter();
+ await resumed;
+ state.settled = await runOptions.afterVerifiedCompletion(proof);
+ return state.settled;
+ },
+ });
+ } catch (error) { state.recoveryError = error; }
+ return state.recovered?.content || 'The scheduled submission requires final verification.';
+ };
+ const created = await harness.manager.createWatchJob({ args: { prompt: 'When a new release appears, acknowledge it once.',
+ keep: true, interval_seconds: 30, beep: false }, currentUrl: 'https://example.com/' });
+ state.sourceId = created.jobId;
+ const pendingRun = harness.manager.handleAlarm(harness.alarmName(created.jobId));
+ await Promise.race([entered, pendingRun.then(() => assert.fail('Recovery skipped the scheduled completion callback'))]);
+ assert.ok(harness.jobs().find(job => job.id === created.jobId).pendingToolCall, 'Unknown input remains pending until settlement');
+ if (scenario === 'exact-task') state.task = state.task.toUpperCase();
+ if (scenario === 'conversation') agent.conversationIds.set(state.tabId, 'superseding-conversation');
+ if (scenario === 'run') agent.completionInvariants.get(state.tabId).runToken = 'superseding-run';
+ if (scenario === 'action') agent._recordCompletionToolResult(state.tabId, 'click_ax', {}, { success: true, dispatched: true });
+ if (scenario === 'stop') await harness.manager.cancelJob(created.jobId, 'Owned Stop');
+ release();
+ await pendingRun;
+ const finished = harness.jobs().find(job => job.id === created.jobId);
+ assert.equal(state.callbacks, 1);
+ assert.equal(state.judgments, 1, 'Settlement refreshes the accepted verdict without another model judgment');
+ assert.deepEqual(state.operations, ['get_accessibility_tree', 'done']);
+ if (scenario === 'current') {
+ assert.equal(state.settled, true);
+ assert.equal(state.recovered.status, 'done');
+ assert.equal(finished.pendingToolCall, null);
+ assert.equal(finished.completedConsequentialAction.verification, 'independent_completion');
+ assert.equal(finished.runCount, 1);
+ } else {
+ assert.equal(state.settled, false);
+ assert.equal(state.recovered, null, 'Stale callback authority cannot produce recovery success');
+ if (scenario === 'stop') {
+ assert.equal(state.recoveryError?.name, 'AbortError');
+ assert.equal(finished.status, 'cancelled');
+ } else {
+ assert.equal(state.recoveryError, null);
+ assert.equal(finished.status, 'needs_user_input');
+ assert.deepEqual(finished.pendingToolCall, state.pending, 'Preserve the original uncertain checkpoint');
+ assert.equal(finished.runCount, 0);
+ }
+ }
+ });
+ }
+}
diff --git a/test/run-ui-response-retry.mjs b/test/run-ui-response-retry.mjs
new file mode 100644
index 000000000..9f35f25be
--- /dev/null
+++ b/test/run-ui-response-retry.mjs
@@ -0,0 +1,110 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+
+for (const build of ['chrome', 'firefox']) {
+ const { RunUiJournal, compactRunUiSnapshotForPersist } = await import(`../src/${build}/src/run-ui-journal.js`);
+ const interrupted = () => {
+ const journal = new RunUiJournal({ eventLimit: 2 });
+ journal.begin(7, 'ask', { mode: 'ask' });
+ journal.record(7, 'ask', 'text_delta', { content: 'An unfinished explanation' });
+ journal.record(7, 'ask', 'response_retry', { reason: 'stream_interrupted', retainPartial: true });
+ return journal;
+ };
+
+ test(`${build}: an acknowledged interrupted answer survives cold replay with its retry status`, () => {
+ const journal = interrupted();
+ journal.record(7, 'ask', 'warning', { code: 'ask_stream_fallback' });
+ journal.acknowledge(7, 'ask', journal.get(7).seq);
+ const persisted = JSON.parse(JSON.stringify(compactRunUiSnapshotForPersist(journal.get(7), { tight: true })));
+ const restored = new RunUiJournal();
+ restored.restore(7, persisted);
+ assert.deepEqual(restored.get(7).events, []);
+ assert.equal(restored.get(7).streamedText, 'An unfinished explanation');
+ assert.equal(restored.get(7).responseIncomplete, true);
+ assert.deepEqual(restored.get(7).responseRetry, { reason: 'stream_interrupted', retainPartial: true, seq: 2 });
+ assert.equal(restored.get(7).successfulDone, false);
+ assert.equal(restored.get(7).runSucceeded, false);
+ assert.equal(restored.get(7).finalContent, '');
+ });
+
+ test(`${build}: a regenerated stream replaces the incomplete snapshot rather than appending to it`, () => {
+ const journal = interrupted();
+ journal.record(7, 'ask', 'text_delta', { content: 'A replacement' });
+ journal.record(7, 'ask', 'text_delta', { content: ' explanation.' });
+ assert.equal(journal.get(7).streamedText, 'A replacement explanation.');
+ assert.equal(journal.get(7).streamedTextStartSeq, 3);
+ assert.equal(journal.get(7).streamedTextSeq, 4);
+ assert.equal(journal.get(7).responseRetry, null);
+ assert.equal(journal.get(7).responseIncomplete, false);
+ });
+
+ test(`${build}: a full replacement or an explicit safety clear ends the provisional display`, () => {
+ for (const content of ['The complete explanation.', '']) {
+ const journal = interrupted();
+ journal.record(7, 'ask', 'text', { content, replace: true });
+ assert.equal(journal.get(7).streamedText, '');
+ assert.equal(journal.get(7).responseRetry, null);
+ assert.equal(journal.get(7).responseIncomplete, false);
+ assert.equal(journal.get(7).events.at(-1).data.content, content);
+ }
+ });
+
+ test(`${build}: retry status survives reconnect even before the first token`, () => {
+ const journal = new RunUiJournal();
+ journal.begin(7, 'ask', { mode: 'ask' });
+ journal.record(7, 'ask', 'response_retry', { reason: 'stream_interrupted', retainPartial: false });
+ journal.acknowledge(7, 'ask', 1);
+ const restored = new RunUiJournal();
+ restored.restore(7, compactRunUiSnapshotForPersist(journal.get(7)));
+ assert.equal(restored.get(7).responseRetry.retainPartial, false);
+ assert.equal(restored.get(7).streamedText, '');
+ });
+
+ test(`${build}: terminal outcomes and new execution boundaries clear the retry status`, () => {
+ for (const type of ['tool_call', 'error', 'failure_recovery', 'steering_applied', 'run_complete']) {
+ const journal = interrupted();
+ journal.record(7, 'ask', type, {});
+ assert.equal(journal.get(7).responseRetry, null, type);
+ }
+ const resumed = interrupted();
+ resumed.resume(7, 'ask');
+ assert.equal(resumed.get(7).responseRetry, null);
+ for (const status of ['completed', 'stopped', 'failed']) {
+ const journal = interrupted();
+ journal.finish(7, 'ask', status);
+ assert.equal(journal.get(7).responseRetry, null, status);
+ assert.equal(journal.get(7).runSucceeded, false, 'partial text alone never proves completion');
+ }
+ });
+
+ test(`${build}: restoration rejects stale, malformed, and terminal retry markers`, () => {
+ for (const responseRetry of [undefined, {}, { reason: 'stream_interrupted', seq: 100 },
+ { reason: 'stream_interrupted', seq: -1 }, { reason: 'other', seq: 2 }]) {
+ const snapshot = structuredClone(interrupted().get(7));
+ snapshot.responseRetry = responseRetry;
+ const restored = new RunUiJournal();
+ assert.equal(restored.restore(7, snapshot).responseRetry, null);
+ }
+ const terminal = structuredClone(interrupted().get(7));
+ terminal.status = 'failed';
+ assert.equal(new RunUiJournal().restore(7, terminal).responseRetry, null);
+ });
+
+ test(`${build}: failed or stopped retries remain incomplete after terminal events are acknowledged`, () => {
+ for (const status of ['failed', 'stopped', 'cancelled']) {
+ const journal = interrupted();
+ journal.record(7, 'ask', 'error', { message: 'The replacement could not finish.' });
+ journal.finish(7, 'ask', status, status === 'stopped' ? '[Stopped by user]' : 'The replacement could not finish.');
+ journal.acknowledge(7, 'ask', journal.get(7).seq);
+ const snapshot = JSON.parse(JSON.stringify(compactRunUiSnapshotForPersist(journal.get(7))));
+ const restored = new RunUiJournal().restore(7, snapshot);
+ assert.equal(restored.responseRetry, null);
+ assert.equal(restored.responseIncomplete, true);
+ assert.equal(restored.runSucceeded, false);
+ assert.equal(restored.streamedText, 'An unfinished explanation');
+ }
+ const completed = interrupted();
+ completed.finish(7, 'ask', 'completed', 'The full replacement.', null, { askSucceeded: true });
+ assert.equal(completed.get(7).responseIncomplete, false);
+ });
+}
diff --git a/test/run-ui-scheduled-lifecycle.mjs b/test/run-ui-scheduled-lifecycle.mjs
index a8a23bd36..4de6db3a9 100644
--- a/test/run-ui-scheduled-lifecycle.mjs
+++ b/test/run-ui-scheduled-lifecycle.mjs
@@ -10,6 +10,7 @@ const builds = await Promise.all(['chrome', 'firefox'].map(async build => ({
compactRunUiSnapshotForPersist: (await import(`../src/${build}/src/run-ui-journal.js`)).compactRunUiSnapshotForPersist,
persistRetryBudget: (await import(`../src/${build}/src/run-ui-journal.js`)).RUN_UI_PERSIST_RETRY_BUDGET,
runUiUpdatesForCurrentTask: (await import(`../src/${build}/src/run-ui-journal.js`)).runUiUpdatesForCurrentTask,
+ runDetachedWithReconnect: (await import(`../src/${build}/src/run-reconnect.js`)).runDetachedWithReconnect,
scheduler: await import(`../src/${build}/src/agent/scheduler.js`),
source: fs.readFileSync(new URL(`../src/${build}/src/background.js`, import.meta.url), 'utf8'),
panelSource: fs.readFileSync(new URL(`../src/${build}/src/ui/sidepanel.js`, import.meta.url), 'utf8'),
@@ -557,6 +558,56 @@ for (const item of builds) {
'an explicit current server false overrides the legacy fallback');
});
+ test(`${item.build}: publication denials and checker exhaustion stay failed through memory classification and reconnect`, async () => {
+ for (const code of ['publication_audit_denied', 'publication_audit_unavailable']) {
+ const events = [
+ { type: 'failure_recovery', data: { stage: 'publication_audit', code,
+ recoveryId: 'owned-recovery', message: 'Failed during the publication check. The draft was not published.' } },
+ { type: 'run_status', data: { status: 'publication_audit_failed' } },
+ ];
+ for (const updates of [events, [events[0]], [events[1]]]) {
+ const h = backgroundHarness(item);
+ h.context.beginRunUiSnapshot(77, 'audit-failed', { mode: 'act', kind: 'continue' });
+ for (const event of updates) h.context.recordRunUiEvent(77, 'audit-failed', event.type, event.data);
+ const message = events[0].data.message;
+ const status = h.context.terminalRunUiStatus(message, updates);
+ assert.equal(status, 'failed', code);
+ assert.equal(h.context.runUpdatesSucceeded(updates), false, 'all three user-memory extraction call sites use this classifier');
+ assert.equal(h.context.askCompletionSucceededForBadge(message, updates), false);
+ const terminal = h.context.finishRunUiSnapshot(77, 'audit-failed', status, message);
+ assert.equal(terminal.runSucceeded, false);
+ await h.context.sendAgentRunComplete(77, terminal);
+ assert.equal(h.messages.at(-1).data.status, 'failed');
+ assert.equal(h.attention.at(-1).success, false);
+ const cold = backgroundHarness(item);
+ const restored = cold.journal.restore(77, JSON.parse(JSON.stringify(item.compactRunUiSnapshotForPersist(h.stored.get(77)))));
+ const replay = await item.runDetachedWithReconnect({
+ initialAction: 'continue_start', payload: { requestId: 'audit-failed' },
+ start: async () => ({ accepted: true, requestId: 'audit-failed' }),
+ probe: async () => ({ submittedTurnDurable: true, runUi: restored }),
+ wait: async () => {}, pollIntervalMs: 0,
+ });
+ assert.equal(replay.success, false);
+ assert.equal(replay.successfulDone, false);
+ assert.equal(restored.status, 'failed');
+ assert.equal(restored.runSucceeded, false);
+ }
+ }
+ });
+
+ test(`${item.build}: publication failure classification preserves fresh successful recovery and explicit Stop`, () => {
+ const h = backgroundHarness(item);
+ const failed = { type: 'failure_recovery', data: { stage: 'publication_audit', code: 'publication_audit_denied' } };
+ const successfulRetry = [{ type: 'tool_result', data: done }];
+ assert.equal(h.context.terminalRunUiStatus('Owned task completed.', successfulRetry), 'completed');
+ assert.equal(h.context.runUpdatesSucceeded(successfulRetry), true);
+ assert.equal(h.context.terminalRunUiStatus('Stopped by user.', [failed]), 'stopped');
+ assert.equal(h.context.terminalRunUiStatus('Stopped before executing requested tool calls.', [failed]), 'cancelled');
+ assert.equal(h.context.terminalRunUiStatus('Details unresolved.', [{ type: 'run_status', data: { status: 'clarification_required' } }]), 'clarification_required');
+ const revised = [failed, { type: 'steering_applied', data: { id: 'corrected-task' } }, ...successfulRetry];
+ assert.equal(h.context.terminalRunUiStatus('Owned task completed.', revised), 'completed');
+ });
+
test(`${item.build}: actual sidebar corrected Ask succeeds only without a current error, limit or Stop`, () => {
const panel = panelCompletionHarness(item);
const error = { type: 'error', data: { message: 'Previous task failed.' } };
diff --git a/test/run.js b/test/run.js
index 3659782c4..9f28062b9 100644
--- a/test/run.js
+++ b/test/run.js
@@ -43769,7 +43769,7 @@ test('selected-text scope is a durable visible sidepanel state with a New conver
assert.match(panel, /function resumeAfterSubscription\(btn\) \{[\s\S]*?if \(rejectSelectionScopedMode\(mode\)\) return;[\s\S]*?setMode\(mode\);[\s\S]*?continueAgent\(/, `${label}: subscription resume should reject restored Act or Dev mode before continuing`);
assert.match(panel, /function bindErrorRetryButton\(btn\) \{[\s\S]*?rejectSelectionScopedMode\(payload\.mode, currentTabId, payload\.sourceGrounding\)[\s\S]*?setMode\(payload\.mode\);[\s\S]*?sendMessage\(/, `${label}: error retry should reject restored Act or Dev mode before resubmitting`);
assert.match(panel, /const modeForSend = retryOptions\?\.mode \|\| modeOverride \|\| modeForMessageText\(text\);\s*if \(rejectSelectionScopedMode\(modeForSend, tabId, sourceGrounding\)\) return false;/, `${label}: chat start should enforce the selected-scope mode boundary centrally`);
- assert.match(panel, /async function continueAgent\(options = \{\}\) \{[\s\S]*?const modeForSend =[\s\S]*?if \(rejectSelectionScopedMode\(modeForSend, tabId\)\) return false;[\s\S]*?sendRunWithReconnect\('continue_start'/, `${label}: Continue should enforce the selected-scope mode boundary centrally`);
+ assert.match(panel, /async function continueAgent\(options = \{\}\) \{[\s\S]*?const modeForSend =[\s\S]*?if \(rejectSelectionScopedMode\(modeForSend, tabId\)\) return false;[\s\S]*?sendRunWithReconnect\(options\.failureRecoveryId \? 'failure_recovery_response' : 'continue_start'/, `${label}: Continue should enforce the selected-scope mode boundary centrally`);
assert.match(panel, /async function startSavedWorkflowRun\(workflow, parameters, tabId = currentTabId\) \{[\s\S]*?if \(!\(await ensureActMode\(\)\)\) return false;[\s\S]*?return sendMessage\(/, `${label}: saved workflows should stop when selected-text scope rejects Act mode`);
assert.match(panel, /command\.value === '\/screenshot'[\s\S]*?command\.value === '\/record' && action !== 'stop'[\s\S]*?command\.value === '\/print'[\s\S]*?isSelectionGroundedForTab\(tabId\)[\s\S]*?sp\.selection_scope\.description[\s\S]*?return '';[\s\S]*?command\.value === '\/screenshot' && action === 'viewport'/, `${label}: page and screen slash commands should stop before dispatch while /record --stop remains available`);
assert.match(panel, /if \(!retryOptions\) \{[\s\S]*?sourceGrounding[\s\S]*?!\/\^\\s\*\\\/record\\s\+--stop[\s\S]*?\/\^\\s\*\\\/\(\?:screenshot\|record\|print\)[\s\S]*?sp\.selection_scope\.description[\s\S]*?return false;[\s\S]*?parseTrailingRunCaptureDirective\(text\);/, `${label}: newly selected-text sends should reject page commands without blocking /record --stop`);
@@ -44838,7 +44838,7 @@ test('/foreground is a run-scoped compatibility override in both local builds',
`${label}: max-step continuations should inherit foreground mode`);
assert.match(panel, /function showContinueButton\(options = \{\}\)[\s\S]*?continueBtn\.dataset\.foreground[\s\S]*?continueAgent\(\{[\s\S]*?foreground:/,
`${label}: persisted Continue buttons should retain foreground mode`);
- assert.match(panel, /async function continueAgent\(options = \{\}\)[\s\S]*?const foregroundForSend = options\?\.foreground === true;[\s\S]*?dataset\.retryForeground = foregroundForSend[\s\S]*?sendRunWithReconnect\('continue_start',[\s\S]*?foreground: foregroundForSend,/,
+ assert.match(panel, /async function continueAgent\(options = \{\}\)[\s\S]*?const foregroundForSend = options\?\.foreground === true;[\s\S]*?dataset\.retryForeground = foregroundForSend[\s\S]*?sendRunWithReconnect\(options\.failureRecoveryId \? 'failure_recovery_response' : 'continue_start',[\s\S]*?foreground: foregroundForSend,/,
`${label}: continuation runs should forward and retain foreground mode`);
assert.match(panel, /async function adoptRestoredRunState\([\s\S]*?sendRunWithReconnect\('continue_start', \{[\s\S]*?foreground: runUi\.foreground === true,/,
`${label}: remounted runs should recover foreground mode from the durable journal`);
@@ -46594,12 +46594,15 @@ test('sidepanel suppresses streamed raw tool-call text before rendering tool ste
assert.match(panel, /async function flushRenderedTabChat\(\{ allowHidden = false \} = \{\}\)[\s\S]*?flushPendingStreamedAssistantMarkdownRenders\(\);[\s\S]*?const html = messagesEl\.innerHTML;[\s\S]*?await persistTabChat\(tabId, html, \{ allowHidden \}\);/, `${label}: tab switches and visibility handoffs should render a queued frame before serializing its last acknowledged stream chunk`);
assert.doesNotMatch(panel, /const nextText = textEl\.textContent \+ data\.content;/, `${label}: rendered Markdown must never become the source for later deltas`);
assert.match(panel, /function formatMarkdown\(text, options = \{\}\)[\s\S]*?const enhance = options\.enhance !== false;[\s\S]*?const highlighted = enhance \? highlightCode\(block\.code, block\.lang\) : escapeHtml\(block\.code\);[\s\S]*?if \(enhance\) scheduleMathRender\(\);[\s\S]*?if \(enhance && codeBlocks\.length > 0\)/, `${label}: syntax highlighting and interactive Markdown enhancements should wait for the terminal render`);
- assert.match(panel, /case 'run_complete':[\s\S]*?const streamedText = getStreamedAssistantText\(textEl\);[\s\S]*?const hasStreamedText = hasStreamedAssistantText\(textEl\);[\s\S]*?const visibleStreamedText = streamedText[\s\S]*?\|\| \(hasStreamedText \? textEl\?\.innerText \|\| textEl\?\.textContent \|\| '' : ''\);[\s\S]*?else if \(textEl && hasStreamedText\)[\s\S]*?const terminalContent = data\.status === 'stopped' \|\| data\.status === 'cancelled'[\s\S]*?\? visibleStreamedText[\s\S]*?renderAssistantTextUpdate\(currentAssistantEl, terminalContent, \{[\s\S]*?replace: terminalContent !== streamedText,[\s\S]*?else if \(textEl && !textEl\.textContent\.trim\(\)\)/, `${label}: restored/background streams should receive one enhanced authoritative terminal render while stopped runs preserve visible partial text`);
- assert.doesNotMatch(panel, /dataset\.streamedAssistantText\s*=/, `${label}: streamed text must not be serialized as a data attribute`);
+ assert.match(panel, /case 'run_complete':[\s\S]*?const streamedText = getStreamedAssistantText\(textEl\);[\s\S]*?const hasStreamedText = hasStreamedAssistantText\(textEl\);[\s\S]*?const visibleStreamedText = streamedText[\s\S]*?\|\| \(hasStreamedText \? textEl\?\.innerText \|\| textEl\?\.textContent \|\| '' : ''\);[\s\S]*?else if \(textEl && \(hasStreamedText\s*\|\| \(data\.status === 'completed' && textEl\.dataset\.responseIncomplete === 'true'\)\)\)[\s\S]*?const terminalContent = data\.status === 'stopped' \|\| data\.status === 'cancelled'[\s\S]*?\? visibleStreamedText[\s\S]*?renderAssistantTextUpdate\(currentAssistantEl, terminalContent, \{[\s\S]*?replace: terminalContent !== streamedText,[\s\S]*?else if \(textEl && !textEl\.textContent\.trim\(\)\)/, `${label}: restored/background streams and incomplete completed replies should receive one enhanced authoritative terminal render while stopped runs preserve visible partial text`);
+ const liveStreamBody = panel.slice(panel.indexOf("case 'text_delta':"), panel.indexOf("case 'response_retry':"));
+ assert.doesNotMatch(liveStreamBody, /dataset\.streamedAssistantText\s*=/, `${label}: active stream chunks must not duplicate raw text into serialized attributes`);
+ assert.match(panel, /function markResponseIncomplete\(assistantEl, \{ retrying = false \} = \{\}\)[\s\S]*?textEl\.dataset\.responseIncomplete = 'true';[\s\S]*?if \(partialText\) textEl\.dataset\.streamedAssistantText = partialText;/, `${label}: only an explicitly incomplete retained response should persist its raw partial text for restoration`);
+ assert.match(panel, /function clearStreamedAssistantText\(textEl\)[\s\S]*?delete textEl\.dataset\.streamedAssistantText;/, `${label}: finalization must clear persisted partial stream text`);
assert.match(panel, /getStreamedAssistantText\(textEl\) === String\(res\.content\)[\s\S]*?renderAssistantTextUpdate\(assistantEl, res\.content\);/, `${label}: completed streams should format the visible final text in place`);
assert.match(panel, /clearAssistantTextStreamState\(assistantEl\);/, `${label}: run completion should clear transient streamed-text state before persistence`);
assert.match(panel, /case 'text':[\s\S]*?\(data\.content \|\| data\.replace === true\)[\s\S]*?renderAssistantTextUpdate\(currentAssistantEl, data\.content \|\| '', \{ replace: data\.replace === true \}\);/, `${label}: text updates should forward explicit replacement requests, including empty clears`);
- assert.match(panel, /function renderAssistantTextUpdate\(assistantEl, content, options = \{\}\) \{[\s\S]*?const hasStreamedText = hasStreamedAssistantText\(textEl\);[\s\S]*?const restoredStreamNeedsReplacement = hasStreamedText && !streamedText;[\s\S]*?const renderedContent = formatMarkdown\(content, \{ recoverNestedMarkdown: true \}\);[\s\S]*?if \(options\.replace === true \|\| restoredStreamNeedsReplacement\) \{[\s\S]*?if \(content\) \{[\s\S]*?textEl\.innerHTML = renderedContent;[\s\S]*?streamedAssistantTextByEl\.set\(textEl, String\(content\)\);[\s\S]*?\} else \{[\s\S]*?textEl\.textContent = '';[\s\S]*?clearStreamedAssistantText\(textEl\);[\s\S]*?\} else if \(verboseMode && !hasStreamedText\)/, `${label}: explicit and restored-stream replacements should preserve nested fences while overwriting or clearing verbose streamed text`);
+ assert.match(panel, /function renderAssistantTextUpdate\(assistantEl, content, options = \{\}\) \{[\s\S]*?const hasStreamedText = hasStreamedAssistantText\(textEl\);[\s\S]*?const restoredStreamNeedsReplacement = hasStreamedText && !streamedText;[\s\S]*?const renderedContent = formatMarkdown\(content, \{ recoverNestedMarkdown: true \}\);[\s\S]*?if \(options\.replace === true \|\| restoredStreamNeedsReplacement \|\| replacesIncompleteResponse\) \{[\s\S]*?if \(content\) \{[\s\S]*?textEl\.innerHTML = renderedContent;[\s\S]*?streamedAssistantTextByEl\.set\(textEl, String\(content\)\);[\s\S]*?\} else \{[\s\S]*?textEl\.textContent = '';[\s\S]*?clearStreamedAssistantText\(textEl\);[\s\S]*?\} else if \(verboseMode && !hasStreamedText\)/, `${label}: explicit, restored-stream, and incomplete-response replacements should preserve nested fences while overwriting or clearing verbose streamed text`);
assert.match(panel, /function renderAssistantTextUpdate\(assistantEl, content, options = \{\}\) \{[\s\S]*?const hasStreamedText = hasStreamedAssistantText\(textEl\);[\s\S]*?const renderedContent = formatMarkdown\(content, \{ recoverNestedMarkdown: true \}\);[\s\S]*?else if \(verboseMode && !hasStreamedText\)[\s\S]*?para\.innerHTML = renderedContent;[\s\S]*?else \{[\s\S]*?textEl\.innerHTML = renderedContent;/, `${label}: every streamed final should preserve nested fences in place even when terminal cleanup changed the raw text`);
const start = panel.indexOf("case 'tool_call':");
const end = panel.indexOf("case 'tool_result':", start);
@@ -46674,6 +46677,7 @@ test('verbose terminal rendering does not append a normalized streamed answer tw
streamedTextEl.dataset.streamedAssistantActive = 'true';
streamedTextByEl.set(streamedTextEl, rawStream);
const streamedAssistantEl = {
+ dataset: {},
querySelector: selector => selector === '.message-text' ? streamedTextEl : null,
};
@@ -46685,6 +46689,7 @@ test('verbose terminal rendering does not append a normalized streamed answer tw
const nonStreamedTextEl = makeTextEl('Prior verbose turn.');
const nonStreamedAssistantEl = {
+ dataset: {},
querySelector: selector => selector === '.message-text' ? nonStreamedTextEl : null,
};
renderAssistantTextUpdate(nonStreamedAssistantEl, 'New non-streamed turn.');
@@ -47905,7 +47910,7 @@ test('sidepanel flushes run chat before queue settlement after immediate tab swi
assert.notEqual(sendDrainIdx, -1, `${label}: send completion should drain queued prompts`);
assert.equal(sendFlushIdx < sendDrainIdx, true, `${label}: send completion must flush before draining queued prompts`);
- const continueMatch = panel.match(/async function continueAgent\(options = \{\}\) \{[\s\S]*?finally \{([\s\S]*?)\n \}\n\}/);
+ const continueMatch = panel.match(/async function continueAgent\(options = \{\}\) \{[\s\S]*?finally \{([\s\S]*?)\n \}\n return runAccepted;\n\}/);
assert.ok(continueMatch, `${label}: continueAgent finally block missing`);
const continueFinally = continueMatch[1];
const continueFlushIdx = continueFinally.indexOf('flushRenderedTabChat()');
@@ -51450,9 +51455,9 @@ test('sidepanel continue runs use the initiating tab state', () => {
const match = panel.match(/async function continueAgent\(options = \{\}\) \{[\s\S]*?\n\}/);
assert.ok(match, `${label}: continueAgent missing`);
const body = match[0];
- assert.match(body, /const tabId = currentTabId;[\s\S]*?const modeForSend = \['ask', 'act', 'dev'\]\.includes\(options\?\.mode\) \? options\.mode : agentMode;[\s\S]*?sendRunWithReconnect\('continue_start', \{[\s\S]*?tabId,[\s\S]*?mode: modeForSend,/, `${label}: Continue should send with the tab and requested-or-current mode captured before awaiting`);
- assert.doesNotMatch(body, /sendRunWithReconnect\('continue_start', \{[\s\S]*?tabId: currentTabId/, `${label}: Continue should not read currentTabId inside the async send payload`);
- assert.doesNotMatch(body, /sendRunWithReconnect\('continue_start', \{[\s\S]*?mode: agentMode/, `${label}: Continue should not read agentMode inside the async send payload`);
+ assert.match(body, /const tabId = currentTabId;[\s\S]*?const modeForSend = \['ask', 'act', 'dev'\]\.includes\(options\?\.mode\) \? options\.mode : agentMode;[\s\S]*?sendRunWithReconnect\(options\.failureRecoveryId \? 'failure_recovery_response' : 'continue_start', \{[\s\S]*?tabId,[\s\S]*?mode: modeForSend,/, `${label}: Continue should send with the tab and requested-or-current mode captured before awaiting`);
+ assert.doesNotMatch(body, /sendRunWithReconnect\([^,]+, \{[\s\S]*?tabId: currentTabId/, `${label}: Continue should not read currentTabId inside the async send payload`);
+ assert.doesNotMatch(body, /sendRunWithReconnect\([^,]+, \{[\s\S]*?mode: agentMode/, `${label}: Continue should not read agentMode inside the async send payload`);
assert.match(body, /await prepareChatHistoryForTurn\(tabId, modeForSend\);[\s\S]*?if \(isTabAbortRequested\(tabId\)\) return false;[\s\S]*?if \(!sameTabId\(currentTabId, tabId\) \|\| !sameTabId\(renderedTabId, tabId\)\) return false;[\s\S]*?assistantEl = addMessage\('assistant', ''\);/, `${label}: Continue should hydrate history, honor aborts, and re-check the initiating tab before rendering`);
assert.match(body, /let assistantEl = null;[\s\S]*?assistantEl = addMessage\('assistant', ''\);[\s\S]*?currentAssistantEl = assistantEl;[\s\S]*?if \(currentTabId === tabId && res\?\.content && assistantEl\) \{[\s\S]*?addMessageCopyButton\(assistantEl\);/, `${label}: Continue should render only into its captured assistant bubble for the initiating tab`);
assert.match(body, /if \(currentTabId === tabId && assistantEl\) finalizeSteps\(assistantEl\);[\s\S]*?if \(currentAssistantEl === assistantEl\) currentAssistantEl = null;/, `${label}: Continue should finalize and clear only its captured assistant bubble`);
@@ -51467,7 +51472,7 @@ test('sidepanel drains queued context-menu prompts on run completion', () => {
const panel = fs.readFileSync(path.join(ROOT, panelRel), 'utf8');
const completions = [
['sendMessage', /async function sendMessage\([^)]*\) \{[\s\S]*?finally \{([\s\S]*?)\n \}\n return accepted;/],
- ['continueAgent', /async function continueAgent\(options = \{\}\) \{[\s\S]*?finally \{([\s\S]*?)\n \}\n\}/],
+ ['continueAgent', /async function continueAgent\(options = \{\}\) \{[\s\S]*?finally \{([\s\S]*?)\n \}\n return runAccepted;\n\}/],
];
for (const [fnName, pattern] of completions) {
const match = panel.match(pattern);
@@ -54717,7 +54722,7 @@ test('status-strip clicks hide default compact history while verbose restores fu
assert.match(css, /@media \(prefers-reduced-motion: reduce\) \{[\s\S]*?#activity-text[\s\S]*?animation: none;/, `${label}: activity shimmer should respect reduced motion`);
assert.match(
panel,
- /case 'text':[\s\S]*?showActivity\(t\('tool\.done'\)\)[\s\S]*?case 'text_delta':[\s\S]*?showActivity\(t\('tool\.done'\)\)[\s\S]*?case 'tool_call':[\s\S]*?showActivity\(friendlyToolLabel\(data\.name, data\.args\)\)/,
+ /case 'text':[\s\S]*?showActivity\(t\('sp\.activity\.generating_answer'\)\)[\s\S]*?case 'text_delta':[\s\S]*?showActivity\(t\('sp\.activity\.generating_answer'\)\)[\s\S]*?case 'tool_call':[\s\S]*?showActivity\(friendlyToolLabel\(data\.name, data\.args\)\)/,
`${label}: response rendering and tool calls should replace the generic thinking state with concrete activity`,
);
assert.match(
@@ -74787,7 +74792,7 @@ test('interactive Ask streaming preserves attachments and persists only the comp
}
});
-test('Ask stream failure clears partial text and falls back once for the rest of the run', async () => {
+test('Ask stream failure retains partial text while falling back once for the rest of the run', async () => {
for (const [index, [label, AgentClass]] of [['chrome', AgentCh], ['firefox', AgentFx]].entries()) {
let streamCalls = 0;
let chatCalls = 0;
@@ -74857,7 +74862,12 @@ test('Ask stream failure clears partial text and falls back once for the rest of
assert.equal(streamCalls, 1, `${label}: stream circuit breaker should stay open for later model turns in the run`);
assert.equal(chatCalls, 2, `${label}: failed generation and its tool follow-up should use provider.chat()`);
assert.deepEqual(executed, ['read_page'], `${label}: pre-completion streamed tool call must never execute`);
- assert.ok(updates.some(update => update.type === 'text' && update.data?.replace === true && update.data?.content === ''), `${label}: partial streamed text should be cleared`);
+ const retryIndex = updates.findIndex(update => update.type === 'response_retry');
+ const retryUpdate = updates[retryIndex];
+ assert.equal(retryUpdate?.data?.reason, 'stream_interrupted', `${label}: fallback should identify the interrupted response`);
+ assert.equal(retryUpdate?.data?.retainPartial, true, `${label}: fallback should retain useful partial text while regenerating`);
+ assert.ok(retryIndex > updates.findIndex(update => update.type === 'text_delta'), `${label}: retry notice should follow the partial response`);
+ assert.equal(updates.slice(0, retryIndex + 1).some(update => update.type === 'text' && update.data?.replace === true && update.data?.content === ''), false, `${label}: fallback must not erase useful partial text before a replacement is available`);
assert.equal(
updates.filter(update => update.type === 'warning' && update.data?.code === 'ask_stream_fallback').length,
1,
@@ -74917,7 +74927,10 @@ test('Ask terminal stream errors clear partial text without retrying the generat
{ interactiveChat: true, askStreamingEnabled: true },
);
- assert.equal(final, 'Error communicating with LLM: policy blocked', `${label}: terminal error should be surfaced`);
+ assert.equal(final, 'Failed while requesting the model response. You can retry from the current state.', `${label}: terminal error should use friendly recovery copy`);
+ const recovery = updates.find(update => update.type === 'failure_recovery')?.data;
+ assert.equal(recovery?.retryMode, 'resume', `${label}: explicit Retry should use ordinary continuation checks`);
+ assert.equal(recovery?.diagnostics, 'policy blocked', `${label}: the original failure should remain in technical details`);
assert.equal(streamCalls, 1, `${label}: terminal stream errors must not retry the generation`);
assert.equal(chatCalls, 0, `${label}: terminal stream errors must not fall back to provider.chat()`);
assert.ok(updates.some(update => update.type === 'text' && update.data?.replace === true && update.data?.content === ''), `${label}: partial streamed text should be cleared`);
diff --git a/test/social-publish-contract.mjs b/test/social-publish-contract.mjs
index 0a48482ba..8457f68bc 100644
--- a/test/social-publish-contract.mjs
+++ b/test/social-publish-contract.mjs
@@ -144,6 +144,7 @@ for (const browser of ['chrome', 'firefox']) {
return {content:JSON.stringify(raw)};
};
const detected = {isSubmit:true,publicationControl:true,publicationResourceUrls:[],publicationResourceUrlsComplete:true,
+ frameDocumentIdentity:'https://x.com/compose/post|fixture-document-1',
publicationAccountIdentity:'twitter:alice',publicationAccountIdentityComplete:true,publicationSnapshot:snapshot()};
agent._detectLikelySubmitAction = async () => structuredClone(detected);
return {agent,tabId,guard,provider,calls,detected};
@@ -625,14 +626,13 @@ for (const browser of ['chrome', 'firefox']) {
});
test(`${browser}: malformed audit replies are distinguished from semantic denials`, async () => {
- for (const mode of ['wrong_key', 'extra_field', 'missing_reason']) {
+ for (const mode of ['wrong_key', 'missing_reason']) {
const f = setup();
await f.agent._adoptLiveSocialPublishWorkflow(f.tabId, f.provider, f.detected);
f.agent._chatWithCostAllowance = async (_provider, messages) => {
const input = JSON.parse(messages[1].content);
const response = { key: input.key, actionId: input.action.id, authorized: false, reason: 'Unvalidated reason' };
if (mode === 'wrong_key') response.key = 'wrong';
- if (mode === 'extra_field') response.extra = true;
if (mode === 'missing_reason') delete response.reason;
return { content: JSON.stringify(response) };
};
@@ -659,6 +659,323 @@ for (const browser of ['chrome', 'firefox']) {
assert.deepEqual(api.publicationProgress(state.contract).eligible, []);
});
+ test(`${browser}: audit parsing tolerates fences and metadata but rejects conflicting verdicts`, () => {
+ const verdict = { key: 'bound', actionId: 'p1', authorized: true, reason: 'x'.repeat(900), metadata: { model: 'chosen' } };
+ const raw = api.parsePublicationJson(' ```json\n' + JSON.stringify(verdict) + '\n``` ');
+ assert.equal(api.publicationAuditAccepted(raw, 'bound', 'p1'), true);
+ assert.equal(api.publicationAuditValidation(raw, 'bound', 'p1').reason.length, 600);
+ for (const content of [null, '', '{}\n{}', 'Verdict: {}', '[]',
+ '{"key":"bound","actionId":"p1","authorized":false,"authorized":true,"reason":"Matches."}',
+ JSON.stringify(verdict) + JSON.stringify({ ...verdict, authorized: false })]) {
+ assert.throws(() => api.parsePublicationJson(content));
+ }
+ for (const mutation of [x => { x.key = 'stale'; }, x => { x.actionId = 'p2'; },
+ x => { x.authorized = 'true'; }, x => { delete x.reason; }, x => { x.reason = null; }]) {
+ const copy = structuredClone(verdict); mutation(copy);
+ assert.equal(api.publicationAuditValidation(copy, 'bound', 'p1').valid, false);
+ }
+ assert.throws(() => api.parsePublicationJson('{"private metadata":1,"private metadata":2}'),
+ error => error.message === 'duplicate_extra_field');
+ });
+
+ test(`${browser}: empty or malformed audits repair once with the same frozen request and larger output budget`, async () => {
+ for (const first of [null, '{}', '{"authorized":true', '{}\n{}']) {
+ const f = setup();
+ await f.agent._adoptLiveSocialPublishWorkflow(f.tabId, f.provider, f.detected);
+ const attempts = [];
+ f.agent._chatWithCostAllowance = async (_provider, messages, options) => {
+ attempts.push({ messages, options });
+ const input = JSON.parse(messages[1].content);
+ if (attempts.length === 1) return { content: first, finishReason: 'length', usage: { outputTokens: 2048, reasoningTokens: 2048 } };
+ return { content: JSON.stringify({ key: input.key, actionId: input.action.id, authorized: true, reason: 'Matches.', providerMetadata: true }) };
+ };
+ assert.equal(await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider), null);
+ assert.deepEqual(attempts.map(a => a.options.maxTokens), [2048, 4096]);
+ assert.equal(attempts[0].messages[1].content, attempts[1].messages[1].content);
+ assert.match(attempts[1].messages[0].content, /format repair/);
+ assert.equal(attempts[1].messages.length, 2, 'repair cannot become a new user instruction');
+ }
+ });
+
+ test(`${browser}: publication controls fall back to portable requests only after explicit option rejection`, async () => {
+ const f = setup();
+ f.provider.name = 'openai';
+ await f.agent._adoptLiveSocialPublishWorkflow(f.tabId, f.provider, f.detected);
+ const attempts = [];
+ f.agent._chatWithCostAllowance = async (_provider, messages, options) => {
+ attempts.push(options);
+ if (attempts.length === 1) throw new Error('HTTP 400: unsupported parameter response_format');
+ const input = JSON.parse(messages[1].content);
+ return { content: JSON.stringify({ key: input.key, actionId: input.action.id, authorized: true, reason: 'Matches.' }) };
+ };
+ assert.equal(await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider), null);
+ assert.equal(attempts[0].extraBody.response_format.type, 'json_schema');
+ assert.equal(attempts[1].extraBody, undefined);
+ assert.equal(f.agent._socialPublicationOptionsRejected(new Error('HTTP 500: request failed')), false);
+ });
+
+ test(`${browser}: truncated audit objects retry before approval and respect the provider output ceiling`, async () => {
+ const f = setup();
+ await f.agent._adoptLiveSocialPublishWorkflow(f.tabId, f.provider, f.detected);
+ f.agent._providerMaxOutputTokens = () => 512;
+ const budgets = [];
+ f.agent._chatWithCostAllowance = async (_provider, messages, options) => {
+ budgets.push(options.maxTokens);
+ const input = JSON.parse(messages[1].content);
+ return { content: JSON.stringify({ key: input.key, actionId: input.action.id, authorized: true, reason: 'Matches.' }),
+ finishReason: budgets.length === 1 ? 'length' : 'stop' };
+ };
+ assert.equal(await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider), null);
+ assert.deepEqual(budgets, [512, 512]);
+ });
+
+ async function failedAuditFixture(mode = 'malformed') {
+ const f = setup();
+ await f.agent._adoptLiveSocialPublishWorkflow(f.tabId, f.provider, f.detected);
+ f.auditCalls = 0;
+ f.agent._chatWithCostAllowance = async (_provider, messages) => {
+ f.auditCalls++;
+ const input = JSON.parse(messages[1].content);
+ if (mode === 'transport') throw new Error('Connection reset');
+ return { content: mode === 'denied' ? JSON.stringify({
+ key: input.key, actionId: input.action.id, authorized: false, reason: 'Cannot confirm the intended account.',
+ }) : '{"authorized":true}' };
+ };
+ f.failure = await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider);
+ return f;
+ }
+
+ test(`${browser}: persistent checker failure offers recovery without asking for permission or retrying click strategies`, async () => {
+ for (const mode of ['malformed', 'denied', 'transport']) {
+ const f = await failedAuditFixture(mode);
+ assert.equal(f.failure.noDispatch, true);
+ assert.equal(f.failure.failureRecovery.stage, 'publication_audit');
+ assert.equal(f.failure.failureRecovery.retryMode, 'publication_audit_bypass');
+ assert.match(f.failure.error, /Failed during the publication check/);
+ assert(!/clarify|permission|another click/i.test(f.failure.error));
+ assert.equal(f.auditCalls, mode === 'denied' ? 1 : 2);
+ const repeated = await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click', { skipPublicationAudit: true }, f.detected, f.provider);
+ assert.equal(repeated.failureRecovery.publicationKey, f.failure.failureRecovery.publicationKey);
+ assert.equal(f.auditCalls, mode === 'denied' ? 1 : 2);
+ assert.equal(f.guard.socialPublication.retryBypass, undefined, 'model tool arguments cannot grant Retry');
+ }
+ });
+
+ test(`${browser}: a trusted publication Retry skips one audit and cannot be replayed after its dispatch attempt`, async () => {
+ for (const mode of ['malformed', 'denied', 'transport']) {
+ const f = await failedAuditFixture(mode);
+ const binding = f.failure.failureRecovery;
+ assert.equal(f.agent._grantSocialPublicationAuditRetry(f.tabId, { ...binding, publicationKey: 'forged' }), false);
+ assert.equal(f.agent._grantSocialPublicationAuditRetry(f.tabId, binding), true);
+ assert.equal(f.agent._grantSocialPublicationAuditRetry(f.tabId, binding), false);
+ for (const name of ['click_ax', 'click']) {
+ assert.equal(await f.agent._workflowPreSubmitDispatchBlock(f.tabId, name, {}, f.detected, f.provider), null);
+ }
+ assert.equal(f.guard.socialPublication.dispatch.auditBypassed, true);
+ assert.equal(f.auditCalls, mode === 'denied' ? 1 : 2, 'all guarded preflights of one attempt reuse the user grant');
+ f.agent._consumeSocialPublicationAuditRetry(f.tabId);
+ const blocked = await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider);
+ assert.equal(blocked.noDispatch, true);
+ assert.match(blocked.error, /Retry was already used/);
+ assert.equal(f.agent._grantSocialPublicationAuditRetry(f.tabId, binding), false);
+ assert.equal(f.auditCalls, mode === 'denied' ? 1 : 2);
+ }
+ });
+
+ test(`${browser}: publication Retry cannot inherit a changed draft, account, page, or document`, async () => {
+ for (const change of ['body', 'account', 'page', 'document', 'frame', 'baseline']) {
+ const f = await failedAuditFixture();
+ assert.equal(f.agent._grantSocialPublicationAuditRetry(f.tabId, f.failure.failureRecovery), true);
+ if (change === 'body') f.detected.publicationSnapshot.posts[0].bodyText = 'Changed';
+ if (change === 'account') f.detected.publicationSnapshot.account = 'twitter:bob';
+ if (change === 'page') f.agent._currentUrl = async () => 'https://x.com/home';
+ if (change === 'document') f.detected.frameDocumentIdentity = 'https://x.com/compose/post|new-document';
+ if (change === 'frame') f.detected.frameId = 7;
+ if (change === 'baseline') f.detected.publicationResourceUrlsComplete = false;
+ const blocked = await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider);
+ assert.equal(blocked.noDispatch, true, change);
+ assert.equal(f.guard.socialPublication.dispatch, null, change);
+ assert.equal(f.auditCalls, 2, 'changed state cannot silently skip or replay the audit');
+ }
+ });
+
+ test(`${browser}: the final publication Retry recheck catches changes after preflight`, async () => {
+ const f = await failedAuditFixture();
+ assert.equal(f.agent._grantSocialPublicationAuditRetry(f.tabId, f.failure.failureRecovery), true);
+ f.agent._detectLikelySubmitAction = async () => {
+ const fresh = structuredClone(f.detected);
+ fresh.publicationSnapshot.account = 'twitter:bob';
+ return fresh;
+ };
+ const blocked = await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider);
+ assert.equal(blocked.noDispatch, true);
+ assert.equal(f.guard.socialPublication.dispatch, null);
+ assert.equal(f.guard.socialPublication.retryBypass, null);
+ });
+
+ test(`${browser}: pending outcomes and steering invalidate publication recovery grants`, async () => {
+ for (const change of ['pending', 'verified', 'steering', 'replacement_guard']) {
+ const f = await failedAuditFixture();
+ if (change === 'pending' || change === 'verified') f.guard.socialPublication.outcomes.p1 = { status: change };
+ if (change === 'steering') applySteering(f, 'Do not publish');
+ if (change === 'replacement_guard') f.agent._startPlanExecutionGuard(f.tabId, 'act', { requestKind: 'execute' });
+ assert.equal(f.agent._grantSocialPublicationAuditRetry(f.tabId, f.failure.failureRecovery), false, change);
+ }
+ });
+
+ test(`${browser}: Retry granted after run completion survives Continue without fabricating execution evidence`, async () => {
+ const f = await failedAuditFixture();
+ assert.equal(f.guard.successfulTaskToolCalls, 0);
+ f.agent._storeContinuationExecutionEvidence(f.tabId);
+ const before = f.agent._continuationExecutionEvidence.get(f.tabId);
+ assert.equal(before.socialPublication.retryBypass, undefined);
+ assert.equal(f.agent._grantSocialPublicationAuditRetry(f.tabId, f.failure.failureRecovery), true);
+ assert.equal(f.agent._continuationExecutionEvidence.get(f.tabId).socialPublication.retryBypass.key,
+ f.failure.failureRecovery.publicationKey, 'the trusted click refreshes the already-stored run snapshot');
+ const next = f.agent._startPlanExecutionGuard(f.tabId, 'act', {
+ requestKind: 'execute', requiresStateChange: true, requiresSubmission: true, siteWorkflow: f.guard.siteWorkflow,
+ }, { trustedContinuation: true });
+ assert.equal(next.socialPublication.deniedAuditKey, f.failure.failureRecovery.publicationKey);
+ assert.equal(next.socialPublication.retryBypass.key, f.failure.failureRecovery.publicationKey);
+ assert.equal(next.successfulTaskToolCalls, 0);
+ assert.equal(next.successfulConsequentialToolCalls, 0);
+ assert.equal(next.verifiedSubmissionEvidence, false);
+ assert.equal(await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider), null);
+ assert.equal(f.auditCalls, 2);
+ });
+
+ test(`${browser}: a settled run's stored publication binding accepts Retry after releasing its live guard`, async () => {
+ const f = await failedAuditFixture();
+ f.agent._storeContinuationExecutionEvidence(f.tabId);
+ f.agent._planExecutionGuards.delete(f.tabId);
+ assert.equal(f.agent._grantSocialPublicationAuditRetry(f.tabId, f.failure.failureRecovery), true);
+ assert(f.agent._continuationExecutionEvidence.get(f.tabId).socialPublication.retryBypass);
+ const next = f.agent._startPlanExecutionGuard(f.tabId, 'act', {
+ requestKind: 'execute', requiresStateChange: true, requiresSubmission: true, siteWorkflow: f.guard.siteWorkflow,
+ }, { trustedContinuation: true });
+ assert(next.socialPublication.retryBypass);
+ assert.equal(await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider), null);
+ assert.equal(f.auditCalls, 2);
+ });
+
+ test(`${browser}: Give up revokes unconsumed audit grants in live and stored state without erasing delivery evidence`, async () => {
+ const f = await failedAuditFixture();
+ assert.equal(f.agent._grantSocialPublicationAuditRetry(f.tabId, f.failure.failureRecovery), true);
+ assert.equal(await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider), null);
+ f.agent._storeContinuationExecutionEvidence(f.tabId);
+ const contractKey = f.guard.socialPublication.key;
+ const deniedKey = f.guard.socialPublication.deniedAuditKey;
+ assert.equal(f.agent._revokeSocialPublicationAuditRetry(f.tabId), true);
+ for (const social of [f.guard.socialPublication, f.agent._continuationExecutionEvidence.get(f.tabId).socialPublication]) {
+ assert.equal(social.retryBypass, null);
+ assert.equal(social.retryAuthorizationTaskKey, undefined);
+ assert.equal(social.retryAuthorizationTaskSignature, undefined);
+ assert.equal(social.dispatch, null);
+ assert.equal(social.key, contractKey);
+ assert.equal(social.deniedAuditKey, deniedKey);
+ assert.deepEqual(social.outcomes, {});
+ }
+ const next = f.agent._startPlanExecutionGuard(f.tabId, 'act', {
+ requestKind: 'execute', requiresStateChange: true, requiresSubmission: true, siteWorkflow: f.guard.siteWorkflow,
+ }, { trustedContinuation: true });
+ assert.equal(next.socialPublication.retryBypass, null);
+ const repeated = await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider);
+ assert.equal(repeated.noDispatch, true);
+ assert.equal(f.auditCalls, 4, 'Continue runs a fresh check after the user revoked the exemption');
+ next.socialPublication.retryBypass = { key: 'used', consumed: true };
+ next.socialPublication.retryBypassUsed = { used: true };
+ next.socialPublication.outcomes.p1 = { status: 'pending' };
+ const before = structuredClone(next.socialPublication);
+ assert.equal(f.agent._revokeSocialPublicationAuditRetry(f.tabId), false);
+ assert.deepEqual(next.socialPublication, before, 'consumed attempts and delivery uncertainty are preserved');
+ });
+
+ test(`${browser}: ordinary Continue can recheck a technical outage but retains semantic denials`, async () => {
+ for (const mode of ['malformed', 'denied']) {
+ const f = await failedAuditFixture(mode);
+ f.agent._storeContinuationExecutionEvidence(f.tabId);
+ const next = f.agent._startPlanExecutionGuard(f.tabId, 'act', {
+ requestKind: 'execute', requiresStateChange: true, requiresSubmission: true, siteWorkflow: f.guard.siteWorkflow,
+ }, { trustedContinuation: true });
+ assert.equal(next.socialPublication.retryBypass, undefined);
+ if (mode === 'malformed') {
+ assert.equal(next.socialPublication.deniedAuditKey, undefined);
+ f.agent._chatWithCostAllowance = async (_provider, messages) => {
+ f.auditCalls++;
+ const input = JSON.parse(messages[1].content);
+ return { content: JSON.stringify({ key: input.key, actionId: input.action.id, authorized: true, reason: 'Matches.' }) };
+ };
+ assert.equal(await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider), null);
+ assert.equal(f.auditCalls, 3);
+ } else {
+ assert.equal(next.socialPublication.deniedAuditKey, f.failure.failureRecovery.publicationKey);
+ assert((await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider)).noDispatch);
+ assert.equal(f.auditCalls, 1);
+ }
+ }
+ });
+
+ test(`${browser}: steering then explicit Retry carries the corrected authorization through Continue`, async () => {
+ const f = setup('Post Monday on X', rawContract([rawAction('p1', 'twitter', 'Monday')]));
+ const initiatingTaskKey = f.guard.taskKey;
+ await f.agent._adoptLiveSocialPublishWorkflow(f.tabId, f.provider, f.detected);
+ applySteering(f, 'Use Tuesday instead');
+ f.detected.publicationSnapshot = snapshot('Tuesday');
+ let audits = 0;
+ f.agent._chatWithCostAllowance = async (_provider, messages, _options, _cost, meta) => {
+ if (meta.generationName === 'social_publication_authorization') {
+ audits++;
+ return { content: '{}' };
+ }
+ const raw = rawContract([rawAction('revised', 'twitter', 'Tuesday')], 'revised');
+ raw.actions[0].posts[0].body.source = ref('Tuesday', 'steering_message0');
+ return { content: JSON.stringify(raw) };
+ };
+ const failed = await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider);
+ assert.equal(failed.failureRecovery.stage, 'publication_audit');
+ const correctedTaskKey = f.agent._progressTaskKeyHash(f.tabId);
+ assert.notEqual(correctedTaskKey, initiatingTaskKey);
+ assert.equal(f.agent._grantSocialPublicationAuditRetry(f.tabId, failed.failureRecovery), true);
+ const next = f.agent._startPlanExecutionGuard(f.tabId, 'act', {
+ requestKind: 'execute', requiresStateChange: true, requiresSubmission: true, siteWorkflow: f.guard.siteWorkflow,
+ }, { trustedContinuation: true });
+ assert.equal(next.taskKey, correctedTaskKey);
+ assert.equal(next.socialPublication.retryBypass.taskKey, correctedTaskKey);
+ assert.equal(next.socialPublication.deniedAuditKey, failed.failureRecovery.publicationKey);
+ assert.equal(next.socialPublication.contract.actions[0].posts[0].body.value, 'Tuesday');
+ assert.equal(next.successfulTaskToolCalls, 0);
+ assert.equal(next.successfulConsequentialToolCalls, 0);
+ assert.equal(next.verifiedSubmissionEvidence, false);
+ assert.equal(await f.agent._workflowPreSubmitDispatchBlock(f.tabId, 'click_ax', {}, f.detected, f.provider), null);
+ assert.equal(audits, 2);
+ });
+
+ test(`${browser}: corrected Retry authorization cannot carry across a changed signature or delivery outcome`, () => {
+ for (const change of ['signature', 'outcome', 'conversation', 'scope']) {
+ const f = setup();
+ const currentTaskKey = f.agent._progressTaskKeyHash(f.tabId);
+ const contract = normalize(rawContract());
+ const social = { key: 'contract', contract, actionId: 'p1', outcomes: {},
+ deniedAuditKey: 'publication', retryAuthorizationTaskKey: currentTaskKey,
+ retryAuthorizationTaskSignature: f.agent._sha256TextSync(f.agent._progressTaskAnchorText(f.tabId)),
+ retryBypass: { key: 'publication', taskKey: 'initiating-task', contractKey: 'contract', actionId: 'p1', consumed: false } };
+ f.guard.taskKey = 'initiating-task';
+ f.guard.socialPublication = social;
+ f.agent._storeContinuationExecutionEvidence(f.tabId);
+ const carried = f.agent._continuationExecutionEvidence.get(f.tabId);
+ if (change === 'signature') carried.socialPublication.retryAuthorizationTaskSignature = 'changed-exact-task';
+ if (change === 'outcome') carried.socialPublication.outcomes.p1 = { status: 'pending' };
+ if (change === 'conversation') carried.conversationId = 'changed-conversation';
+ const next = f.agent._startPlanExecutionGuard(f.tabId, 'act', {
+ requestKind: 'execute', requiresStateChange: true, requiresSubmission: change !== 'scope',
+ }, { trustedContinuation: true });
+ assert.equal(next.socialPublication, null, change);
+ assert.equal(next.successfulTaskToolCalls, 0);
+ assert.equal(next.successfulConsequentialToolCalls, 0);
+ assert.equal(next.verifiedSubmissionEvidence, false);
+ }
+ });
+
test(`${browser}: clarification during an in-flight audit invalidates the older approval`, async () => {
const f = setup();
await f.agent._adoptLiveSocialPublishWorkflow(f.tabId, f.provider, f.detected);