Open-source AI browser agent for Chrome and Firefox (monorepo) ðŸ§
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
fix: make history recovery durable and interlock scheduled runs
Emre Sokullu0ee63806a37a
diff --git a/package.json b/package.jsonindex 87ceb347c..6fb0a8368 100644--- a/package.json+++ b/package.json@@ -59,9 +59,9 @@"benchmark:relevance": "node scripts/benchmark-offline-relevance.mjs --verbose","test:social-contract": "node --test test/social-publish-contract.mjs test/publication-quote-markup.mjs","test:social-contract:dom": "node test/social-publish-contract-dom.mjs",- "test:runtime-lifecycle": "node test/bot-memory-dom.mjs && node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/bot-memory.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs test/cdp-clear-receipt.mjs test/cdp-field-submit-recovery.mjs test/conversation-persistence.mjs test/history-recovery-state.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/chat-steering.mjs test/resource-mutation-guards.mjs test/completion-steering-receipt-authority.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/release-publication-completion.mjs test/workflow-implicit-metadata.mjs test/completion-current-execution-evidence.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/lifecycle-terminal-done.mjs test/lifecycle-planner-digest.mjs test/lifecycle-vision-fallback.mjs test/guards-control-classification.mjs test/guards-steering-receipts.mjs && node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/native-chat-trusted-clear.mjs test/chat-steering-ui.mjs test/history-recovery.mjs test/history-recovery-ui.mjs test/assistant-message-visibility-ui.mjs test/page-monitor-ui.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/native-resource-deletion-binding.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs && node test/message-recipient-upload.mjs && node --test test/message-recipient-whatsapp.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/ask-completion-churn-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs && node test/quality/cloud-bot-memory-mv3.mjs && node test/quality/whatsapp-contact-matrix.mjs && node test/quality/pdf-detection-mv3.mjs && node test/quality/download-upload-mv3.mjs && node test/quality/upload-release-binding-mv3.mjs && node test/quality/release-review-world-mv3.mjs && node test/quality/downloaded-file-saved-bytes-mv3.mjs && node test/quality/file-upload-accept-mv3.mjs && node test/quality/bulk-resume-mv3.mjs && node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs",+ "test:runtime-lifecycle": "node test/bot-memory-dom.mjs && node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/bot-memory.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs test/cdp-clear-receipt.mjs test/cdp-field-submit-recovery.mjs test/conversation-persistence.mjs test/history-recovery-state.mjs test/history-recovery-scheduler.mjs test/history-recovery-atomic.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/chat-steering.mjs test/resource-mutation-guards.mjs test/completion-steering-receipt-authority.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/release-publication-completion.mjs test/workflow-implicit-metadata.mjs test/completion-current-execution-evidence.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/lifecycle-terminal-done.mjs test/lifecycle-planner-digest.mjs test/lifecycle-vision-fallback.mjs test/guards-control-classification.mjs test/guards-steering-receipts.mjs && node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/native-chat-trusted-clear.mjs test/chat-steering-ui.mjs test/history-recovery.mjs test/history-recovery-ui.mjs test/assistant-message-visibility-ui.mjs test/page-monitor-ui.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/native-resource-deletion-binding.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs && node test/message-recipient-upload.mjs && node --test test/message-recipient-whatsapp.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/ask-completion-churn-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs && node test/quality/cloud-bot-memory-mv3.mjs && node test/quality/whatsapp-contact-matrix.mjs && node test/quality/pdf-detection-mv3.mjs && node test/quality/download-upload-mv3.mjs && node test/quality/upload-release-binding-mv3.mjs && node test/quality/release-review-world-mv3.mjs && node test/quality/downloaded-file-saved-bytes-mv3.mjs && node test/quality/file-upload-accept-mv3.mjs && node test/quality/bulk-resume-mv3.mjs && node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs","test:page-feedback": "node --test test/trusted-field-preparation.mjs test/draftjs-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/page-monitor-ui.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-passive-progress.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/delivery-click-ax-response-loss.mjs test/delivery-stop-compound.mjs test/delivery-cdp-input.mjs test/delivery-click-locks.mjs test/delivery-native-button-geometry.mjs && node test/message-recipient-upload.mjs && node --test test/message-recipient-whatsapp.mjs",- "test:history-recovery": "node --test test/history-recovery.mjs test/history-recovery-ui.mjs test/history-recovery-state.mjs test/conversation-persistence.mjs",+ "test:history-recovery": "node --test test/history-recovery.mjs test/history-recovery-ui.mjs test/history-recovery-state.mjs test/history-recovery-scheduler.mjs test/history-recovery-atomic.mjs test/conversation-persistence.mjs","test:chat-steering": "node --test test/chat-steering.mjs test/chat-steering-ui.mjs test/lifecycle-steering-latency.mjs test/lifecycle-run-ui.mjs","test:rich-text-dom": "node test/ui-content-lifecycle.mjs --dom","test:firefox-bidi": "node --test test/firefox-bidi.mjs test/firefox-full-page-screenshot.mjs",diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex 8a35a48b3..05caa7b36 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -7850,7 +7850,7 @@ export class Agent extends LoopDetector {return (await this.getConversationState(tabId, mode)).conversationId;}- async recoverChatHistory(tabId, record) {+ async recoverChatHistory(tabId, record, { storageEntries = {} } = {}) {await this._hydrate(tabId);if (this._runningTabs.has(tabId)) throw new Error('Wait for the current response to finish.');if (this._botMemorySessions.has(tabId)) throw new Error('Managed bot conversations cannot recover chat history.');@@ -7873,7 +7873,7 @@ export class Agent extends LoopDetector {};};const hadPendingPersist = this.persistTimers.has(tabId);- const persisted = await this._persistNow(tabId, { snapshotForBudget, preserveStateOnFailure: true });+ const persisted = await this._persistNow(tabId, { snapshotForBudget, preserveStateOnFailure: true, storageEntries });if (!persisted?.ok) {if (hadPendingPersist) this._persist(tabId);throw new Error('Unable to persist the recovered conversation.');@@ -19632,7 +19632,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d};}- async _persistNow(tabId, { snapshotForBudget = null, preserveStateOnFailure = false } = {}) {+ async _persistNow(tabId, { snapshotForBudget = null, preserveStateOnFailure = false, storageEntries = {} } = {}) {if (tabId == null) return { ok: false, degraded: false, reason: 'invalid_tab' };const existing = this.persistTimers.get(tabId);if (existing) {@@ -19646,13 +19646,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d: this._markPersistenceDegraded(tabId, isSessionQuotaError(error) ? 'quota' : 'unavailable', error);if (!entry) return { ok: false, degraded: false, reason: 'no_conversation' };try {- await chrome.storage.session.set({ [this._convKey(tabId)]: entry });+ await chrome.storage.session.set({ ...storageEntries, [this._convKey(tabId)]: entry });return { ok: true, degraded: entry.sessionSnapshotCompacted === true, reason: entry.sessionSnapshotCompacted ? 'sanitized' : null };} catch (error) {if (isSessionQuotaError(error)) {const compactEntry = snapshot(SESSION_CONVERSATION_RETRY_BUDGET_BYTES);try {- await chrome.storage.session.set({ [this._convKey(tabId)]: compactEntry });+ await chrome.storage.session.set({ ...storageEntries, [this._convKey(tabId)]: compactEntry });return { ok: true, degraded: true, reason: 'quota_compacted' };} catch (retryError) {return failed(retryError);diff --git a/src/chrome/src/background.js b/src/chrome/src/background.jsindex aec99a20a..b445f7e0c 100644--- a/src/chrome/src/background.js+++ b/src/chrome/src/background.js@@ -259,6 +259,11 @@ const teacherRunInterlock = createTeacherRunInterlock(teacherSessionStore, {|| cloudRunController.isRunning(tabId),});agent.setRunStartGuard(async (tabId, context) => {+ if (recoveringHistoryTabs.has(tabId)) {+ // The scheduler checks this guard after reserving the tab and again when+ // the agent starts; report contention so its pending job is requeued.+ throw new Error('An agent run is already in progress for this tab: conversation recovery is in progress.');+ }await cloudRunController.guardRunStart(tabId, context);return teacherRunInterlock.guardRunStart(tabId);});@@ -2147,7 +2152,7 @@ const recoveringHistoryTabs = new Set();function assertNoActiveTabRun(tabId) {if (recoveringHistoryTabs.has(tabId)) throw new Error('Conversation recovery is in progress.');- if (agent.activeRunState(tabId)?.running || detachedRunStarts.has(tabId)) {+ if (agent.activeRunState(tabId)?.running || detachedRunStarts.has(tabId) || scheduler.isRunning(tabId)) {throw new Error('A run is already active for this tab.');}}@@ -3839,8 +3844,13 @@ async function handleMessage(msg, sender) {const record = await getChatHistoryRecord(msg.recordId);const tab = await chrome.tabs.get(tabId);if (!record || !record.url || record.url !== tab.url) throw new Error('This history belongs to a different URL.');+ if (record.updatedAt !== msg.recordUpdatedAt) throw new Error('This history changed before recovery. Try again.');const conversationId = await agent.getConversationId(tabId);- const state = await agent.recoverChatHistory(tabId, record);+ const state = await tabChatHandoff.replace(tabId, msg.html, {+ ownerId: msg.handoffOwnerId,+ handoffGeneration: msg.handoffGeneration,+ commit: storageEntries => agent.recoverChatHistory(tabId, record, { storageEntries }),+ });// A failed recovery must retain the old conversation's scheduled work.// Recovery is already committed here, so scheduler cleanup cannot turn// it into a failure response with a mismatched transcript.diff --git a/src/chrome/src/ui/chat-history-store.js b/src/chrome/src/ui/chat-history-store.jsindex eabd27f33..79fafe021 100644--- a/src/chrome/src/ui/chat-history-store.js+++ b/src/chrome/src/ui/chat-history-store.js@@ -141,7 +141,13 @@ export async function saveChatHistoryRecord(input) {const existing = await promisifyReq(tx(db).objectStore(STORE_NAME).get(String(input.id))).catch(() => null);const record = normalizeRecord(input, existing);if (!record.id || record.userMessageCount < 1) return null;- await promisifyReq(tx(db, 'readwrite').objectStore(STORE_NAME).put(record));+ const transaction = tx(db, 'readwrite');+ await new Promise((resolve, reject) => {+ transaction.oncomplete = () => resolve();+ transaction.onerror = () => reject(transaction.error || new Error('History save transaction failed'));+ transaction.onabort = () => reject(transaction.error || new Error('History save transaction aborted'));+ transaction.objectStore(STORE_NAME).put(record);+ });return record;}diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.jsindex f170c07af..24eca9eca 100644--- a/src/chrome/src/ui/sidepanel.js+++ b/src/chrome/src/ui/sidepanel.js@@ -35,6 +35,7 @@ import {} from '../context-menu-storage.js';import {listChatHistoryRecords,+ getChatHistoryRecord,deleteChatHistoryRecord,repairChatHistoryRecordMessages,saveChatHistoryRecord,@@ -3173,19 +3174,19 @@ async function persistChatHistorySnapshot(tabId, { refreshTabInfo = false, allowconst numericTabId = Number(tabId);if ((document.visibilityState === 'hidden' && !allowHidden)|| !Number.isFinite(numericTabId)- || renderedTabId !== numericTabId) return;+ || renderedTabId !== numericTabId) return { ok: false, reason: 'not-rendered' };const messages = extractChatHistoryMessages(messagesEl);- if (!messages.some((message) => message.role === 'user')) return;+ if (!messages.some((message) => message.role === 'user')) return { ok: true, empty: true };const saveSeq = nextChatHistorySaveSeqForTab(numericTabId);if (!chatHistoryCreatedAtByTab.has(numericTabId)) {chatHistoryCreatedAtByTab.set(numericTabId, Date.now());}await hydrateChatHistoryIdentity(numericTabId, agentMode, { refreshTabInfo });- if (chatHistorySaveSeqByTab.get(numericTabId) !== saveSeq) return;+ if (chatHistorySaveSeqByTab.get(numericTabId) !== saveSeq) return { ok: false, reason: 'superseded' };const tabInfo = chatHistoryTabInfoByTab.get(numericTabId) || {};const recordId = chatHistoryRecordIdsByTab.get(numericTabId) || fallbackHistoryRecordId(numericTabId);const conversationId = chatHistoryConversationIdsByTab.get(numericTabId) || null;- await saveChatHistoryRecord({+ const record = await saveChatHistoryRecord({id: recordId,conversationId,tabId: numericTabId,@@ -3199,7 +3200,9 @@ async function persistChatHistorySnapshot(tabId, { refreshTabInfo = false, allowmessages,}).catch((error) => {console.warn('[WebBrain] failed to save chat history:', error);+ return null;});+ return record ? { ok: true, record } : { ok: false, reason: 'archive-failed' };}async function repairRestoredChatHistorySnapshot(tabId) {@@ -3233,7 +3236,7 @@ async function flushChatHistorySnapshot(tabId, options = {}) {historyPersistTimer = null;historyPersistTimerTabId = null;}- await persistChatHistorySnapshot(tabId, options);+ return persistChatHistorySnapshot(tabId, options);}async function resetChatHistoryStateForTab(tabId) {@@ -5377,6 +5380,7 @@ function requestVisibleSidePanelStateRefresh() {if (!refreshed || refreshPromise !== visibleStateRefreshPromise) return;consumePendingContextMenuPrompt().then(() => drainQueuedContextMenuPrompts()).catch(() => {});}).catch(() => {});+ return refreshPromise;}async function refreshConversationScopeState(tabId = currentTabId, { apply = true } = {}) {@@ -10244,7 +10248,11 @@ chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {|| String(msg.ownerId || '') !== tabChatHandoffOwnerId) return;const respond = () => {const snapshot = lastVisibleTabChatSnapshot;- if (!snapshot || !sameTabId(snapshot.tabId, msg.tabId)) { sendResponse({ ok: false }); return; }+ if (!snapshot || !sameTabId(snapshot.tabId, msg.tabId)+ || tabChatHandoffGenerations.get(Number(msg.tabId)) !== Number(msg.generation)) {+ sendResponse({ ok: false });+ return;+ }sendResponse({ok: true,tabId: Number(snapshot.tabId),@@ -13107,6 +13115,7 @@ function askAboutSelectedAnswer() {}function addMessage(role, content, options = {}) {+ const messageRoot = options.root || messagesEl;const msgEl = document.createElement('div');msgEl.className = `message ${role}`;@@ -13151,10 +13160,10 @@ function addMessage(role, content, options = {}) {if (role === 'user' && Array.isArray(options.attachments) && options.attachments.length) {renderMessageAttachments(msgEl, options.attachments, options.attachmentState || 'included');}- if (options.beforeCurrentAssistant && currentAssistantEl?.parentNode === messagesEl) {- messagesEl.insertBefore(msgEl, currentAssistantEl);+ if (options.beforeCurrentAssistant && currentAssistantEl?.parentNode === messageRoot) {+ messageRoot.insertBefore(msgEl, currentAssistantEl);} else {- messagesEl.appendChild(msgEl);+ messageRoot.appendChild(msgEl);}if (role === 'user' && options.sourceGrounding) {addSelectionScopeDivider(msgEl, options.sourceGrounding);@@ -13174,7 +13183,7 @@ function addMessage(role, content, options = {}) {addMessageCopyButton(msgEl);}- scrollToBottom();+ if (!options.detached) scrollToBottom();return msgEl;}@@ -15611,15 +15620,41 @@ async function openChatHistoryPage() {const historyPopover = document.getElementById('history-popover');let historyPopoverRequest = 0;+function createHistoryRecoveryTranscript(record) {+ const root = document.createElement('div');+ for (const message of record.messages || []) {+ if (!['user', 'assistant'].includes(message.role)) continue;+ const restored = addMessage(message.role, message.text, { root, detached: true, createdAt: message.createdAt,+ attachments: message.attachments, attachmentState: 'included' });+ if (message.role === 'user') {+ delete restored.dataset.composerHistoryVerbatim;+ delete restored.dataset.composerHistoryText;+ const provenance = historyRecoveryMetadata(message);+ if (provenance.userTextSource === 'verbatim') restored.dataset.composerHistoryVerbatim = 'true';+ if (provenance.modelText) restored.dataset.composerHistoryText = provenance.modelText;+ }+ }+ return root.innerHTML;+}+async function recoverHistoryRecord(recordId, tabId, pageUrl) {if (tabSwitchTransitionId != null || isTabProcessing(tabId) || isConversationClearInProgress(tabId)|| !sameTabId(currentTabId, tabId) || !sameTabId(renderedTabId, tabId)) return;historyRecoveryTabs.add(tabId);setConversationClearInProgress(tabId, true);+ let recoveryRequested = false;try {if ((await getTabInfoForHistory(tabId)).url !== pageUrl) throw new Error(t('sp.history.changed'));- await flushChatHistorySnapshot(tabId, { refreshTabInfo: true });- const result = await sendToBackground('recover_chat_history', { tabId, recordId });+ const archived = await flushChatHistorySnapshot(tabId, { refreshTabInfo: true, allowHidden: true });+ if (!archived?.ok) throw new Error(t('sp.history.failed'));+ const source = await getChatHistoryRecord(recordId);+ if (!source) throw new Error(t('sp.history.failed'));+ const html = createHistoryRecoveryTranscript(source);+ recoveryRequested = true;+ const result = await sendToBackground('recover_chat_history', {+ tabId, recordId, html, recordUpdatedAt: source.updatedAt, handoffOwnerId: tabChatHandoffOwnerId,+ handoffGeneration: tabChatHandoffGenerations.get(Number(tabId)),+ });if (!result?.ok) throw new Error(result?.error || t('sp.history.failed'));if (!sameTabId(currentTabId, tabId) || !sameTabId(renderedTabId, tabId)) return;if (historyPersistTimer) clearTimeout(historyPersistTimer);@@ -15638,24 +15673,32 @@ async function recoverHistoryRecord(recordId, tabId, pageUrl) {chatHistoryCreatedAtByTab.set(tabId, Date.now());applyConversationScopeState(tabId, result);setMode('ask');- for (const message of result.record.messages || []) {- if (!['user', 'assistant'].includes(message.role)) continue;- const restored = addMessage(message.role, message.text, { createdAt: message.createdAt,- attachments: message.attachments, attachmentState: 'included' });- if (message.role === 'user') {- delete restored.dataset.composerHistoryVerbatim;- delete restored.dataset.composerHistoryText;- const provenance = historyRecoveryMetadata(message);- if (provenance.userTextSource === 'verbatim') restored.dataset.composerHistoryVerbatim = 'true';- if (provenance.modelText) restored.dataset.composerHistoryText = provenance.modelText;- }- }- const saved = await flushRenderedTabChat({ allowHidden: true });- if (!saved?.ok || saved.skipped) throw new Error(t('sp.history.failed'));+ // The background already durably committed this HTML with the model state.+ tabChatHandoffGenerations.set(Number(tabId), result.handoffGeneration);+ messagesEl.innerHTML = result.html;+ tabChats.set(Number(tabId), result.html);+ lastVisibleTabChatSnapshot = { tabId: Number(tabId), html: result.html };+ rebindRestoredMessageControls();await flushChatHistorySnapshot(tabId, { refreshTabInfo: true, allowHidden: true });historyPopover.hidePopover();} catch (error) {- showComposerToast(error?.message || t('sp.history.failed'), { duration: 7000 });+ if (recoveryRequested) {+ // A lost response may follow a successful commit. Drop every cached old+ // identity/snapshot before the handoff reload so it cannot overwrite the+ // new transcript or enable sends against a different model conversation.+ console.warn('[WebBrain] Reconciling history recovery:', error);+ tabChats.delete(Number(tabId));+ chatHistoryRecordIdsByTab.delete(tabId);+ chatHistoryConversationIdsByTab.delete(tabId);+ chatHistoryCreatedAtByTab.delete(tabId);+ tabChatHandoffGenerations.delete(Number(tabId));+ if (lastVisibleTabChatSnapshot && sameTabId(lastVisibleTabChatSnapshot.tabId, tabId)) lastVisibleTabChatSnapshot = null;+ if (persistTimer && sameTabId(persistTimerTabId, tabId)) { clearTimeout(persistTimer); persistTimer = null; persistTimerTabId = null; }+ // Visibility restoration performs this same refresh when the panel is hidden.+ requestVisibleSidePanelStateRefresh();+ } else {+ showComposerToast(error?.message || t('sp.history.failed'), { duration: 7000 });+ }} finally {historyRecoveryTabs.delete(tabId);setConversationClearInProgress(tabId, false);diff --git a/src/chrome/src/ui/tab-chat-persistence.js b/src/chrome/src/ui/tab-chat-persistence.jsindex 5b8397448..aea0446aa 100644--- a/src/chrome/src/ui/tab-chat-persistence.js+++ b/src/chrome/src/ui/tab-chat-persistence.js@@ -407,6 +407,26 @@ export function createTabChatHandoffCoordinator(storageArea, {});}+ function replace(tabId, html, { ownerId, handoffGeneration, commit } = {}) {+ return enqueue(tabId, async queuedTabId => {+ const current = await readHandoffState(queuedTabId);+ if (!current || current.ownerId !== ownerId || current.generation !== Number(handoffGeneration)) {+ throw new Error('The conversation panel changed before recovery. Try again in the active panel.');+ }+ if (typeof html !== 'string' || typeof commit !== 'function') throw new Error('No recovered transcript.');+ const generation = current.generation + 1;+ const persistedHtml = compactTabChatForPersist(html);+ // The model snapshot, transcript, and ownership generation are one storage+ // transaction. A failed write leaves the previous conversation intact.+ const state = await commit({+ [TAB_CHAT_PREFIX + queuedTabId]: persistedHtml,+ [TAB_CHAT_HANDOFF_PREFIX + queuedTabId]: { ownerId, generation },+ });+ latestHtml.set(queuedTabId, html);+ return { ...state, html, handoffOwnerId: ownerId, handoffGeneration: generation };+ });+ }+async function load(tabId, { waitForHandoff = false, claimantId = '' } = {}) {const numericTabId = normalizeTabId(tabId);if (numericTabId == null) return { ok: false, found: false, error: 'No tab ID' };@@ -530,5 +550,5 @@ export function createTabChatHandoffCoordinator(storageArea, {});}- return { save, load, clear };+ return { save, load, clear, replace };}diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex d34fc6cc3..57c2cd504 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -7825,7 +7825,7 @@ export class Agent extends LoopDetector {};}- async _persistNow(tabId, { snapshotForBudget = null, preserveStateOnFailure = false } = {}) {+ async _persistNow(tabId, { snapshotForBudget = null, preserveStateOnFailure = false, storageEntries = {} } = {}) {if (tabId == null) return { ok: false, degraded: false, reason: 'invalid_tab' };const existing = this.persistTimers.get(tabId);if (existing) {@@ -7839,13 +7839,13 @@ export class Agent extends LoopDetector {: this._markPersistenceDegraded(tabId, isSessionQuotaError(error) ? 'quota' : 'unavailable', error);if (!entry) return { ok: false, degraded: false, reason: 'no_conversation' };try {- await browser.storage.session.set({ [this._convKey(tabId)]: entry });+ await browser.storage.session.set({ ...storageEntries, [this._convKey(tabId)]: entry });return { ok: true, degraded: entry.sessionSnapshotCompacted === true, reason: entry.sessionSnapshotCompacted ? 'sanitized' : null };} catch (error) {if (isSessionQuotaError(error)) {const compactEntry = snapshot(SESSION_CONVERSATION_RETRY_BUDGET_BYTES);try {- await browser.storage.session.set({ [this._convKey(tabId)]: compactEntry });+ await browser.storage.session.set({ ...storageEntries, [this._convKey(tabId)]: compactEntry });return { ok: true, degraded: true, reason: 'quota_compacted' };} catch (retryError) {return failed(retryError);@@ -7942,7 +7942,7 @@ export class Agent extends LoopDetector {return (await this.getConversationState(tabId, mode)).conversationId;}- async recoverChatHistory(tabId, record) {+ async recoverChatHistory(tabId, record, { storageEntries = {} } = {}) {await this._hydrate(tabId);if (this._runningTabs.has(tabId)) throw new Error('Wait for the current response to finish.');if (this._botMemorySessions.has(tabId)) throw new Error('Managed bot conversations cannot recover chat history.');@@ -7965,7 +7965,7 @@ export class Agent extends LoopDetector {};};const hadPendingPersist = this.persistTimers.has(tabId);- const persisted = await this._persistNow(tabId, { snapshotForBudget, preserveStateOnFailure: true });+ const persisted = await this._persistNow(tabId, { snapshotForBudget, preserveStateOnFailure: true, storageEntries });if (!persisted?.ok) {if (hadPendingPersist) this._persist(tabId);throw new Error('Unable to persist the recovered conversation.');diff --git a/src/firefox/src/background.js b/src/firefox/src/background.jsindex 5b9c26ec7..45f6c31ee 100644--- a/src/firefox/src/background.js+++ b/src/firefox/src/background.js@@ -200,6 +200,11 @@ const teacherRunInterlock = createTeacherRunInterlock(teacherSessionStore, {|| cloudRunController.isRunning(tabId),});agent.setRunStartGuard(async (tabId, context) => {+ if (recoveringHistoryTabs.has(tabId)) {+ // The scheduler checks this guard after reserving the tab and again when+ // the agent starts; report contention so its pending job is requeued.+ throw new Error('An agent run is already in progress for this tab: conversation recovery is in progress.');+ }await cloudRunController.guardRunStart(tabId, context);return teacherRunInterlock.guardRunStart(tabId);});@@ -2339,7 +2344,7 @@ const recoveringHistoryTabs = new Set();function assertNoActiveTabRun(tabId) {if (recoveringHistoryTabs.has(tabId)) throw new Error('Conversation recovery is in progress.');- if (agent.activeRunState(tabId)?.running || detachedRunStarts.has(tabId)) {+ if (agent.activeRunState(tabId)?.running || detachedRunStarts.has(tabId) || scheduler.isRunning(tabId)) {throw new Error('A run is already active for this tab.');}}@@ -3311,8 +3316,13 @@ async function handleMessage(msg, sender) {const record = await getChatHistoryRecord(msg.recordId);const tab = await chrome.tabs.get(tabId);if (!record || !record.url || record.url !== tab.url) throw new Error('This history belongs to a different URL.');+ if (record.updatedAt !== msg.recordUpdatedAt) throw new Error('This history changed before recovery. Try again.');const conversationId = await agent.getConversationId(tabId);- const state = await agent.recoverChatHistory(tabId, record);+ const state = await tabChatHandoff.replace(tabId, msg.html, {+ ownerId: msg.handoffOwnerId,+ handoffGeneration: msg.handoffGeneration,+ commit: storageEntries => agent.recoverChatHistory(tabId, record, { storageEntries }),+ });// A failed recovery must retain the old conversation's scheduled work.// Recovery is already committed here, so scheduler cleanup cannot turn// it into a failure response with a mismatched transcript.diff --git a/src/firefox/src/ui/chat-history-store.js b/src/firefox/src/ui/chat-history-store.jsindex eabd27f33..79fafe021 100644--- a/src/firefox/src/ui/chat-history-store.js+++ b/src/firefox/src/ui/chat-history-store.js@@ -141,7 +141,13 @@ export async function saveChatHistoryRecord(input) {const existing = await promisifyReq(tx(db).objectStore(STORE_NAME).get(String(input.id))).catch(() => null);const record = normalizeRecord(input, existing);if (!record.id || record.userMessageCount < 1) return null;- await promisifyReq(tx(db, 'readwrite').objectStore(STORE_NAME).put(record));+ const transaction = tx(db, 'readwrite');+ await new Promise((resolve, reject) => {+ transaction.oncomplete = () => resolve();+ transaction.onerror = () => reject(transaction.error || new Error('History save transaction failed'));+ transaction.onabort = () => reject(transaction.error || new Error('History save transaction aborted'));+ transaction.objectStore(STORE_NAME).put(record);+ });return record;}diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.jsindex 5a242f2dd..5a115be6c 100644--- a/src/firefox/src/ui/sidepanel.js+++ b/src/firefox/src/ui/sidepanel.js@@ -35,6 +35,7 @@ import {} from '../context-menu-storage.js';import {listChatHistoryRecords,+ getChatHistoryRecord,deleteChatHistoryRecord,repairChatHistoryRecordMessages,saveChatHistoryRecord,@@ -2427,19 +2428,19 @@ async function persistChatHistorySnapshot(tabId, { refreshTabInfo = false, allowconst numericTabId = Number(tabId);if ((document.visibilityState === 'hidden' && !allowHidden)|| !Number.isFinite(numericTabId)- || renderedTabId !== numericTabId) return;+ || renderedTabId !== numericTabId) return { ok: false, reason: 'not-rendered' };const messages = extractChatHistoryMessages(messagesEl);- if (!messages.some((message) => message.role === 'user')) return;+ if (!messages.some((message) => message.role === 'user')) return { ok: true, empty: true };const saveSeq = nextChatHistorySaveSeqForTab(numericTabId);if (!chatHistoryCreatedAtByTab.has(numericTabId)) {chatHistoryCreatedAtByTab.set(numericTabId, Date.now());}await hydrateChatHistoryIdentity(numericTabId, agentMode, { refreshTabInfo });- if (chatHistorySaveSeqByTab.get(numericTabId) !== saveSeq) return;+ if (chatHistorySaveSeqByTab.get(numericTabId) !== saveSeq) return { ok: false, reason: 'superseded' };const tabInfo = chatHistoryTabInfoByTab.get(numericTabId) || {};const recordId = chatHistoryRecordIdsByTab.get(numericTabId) || fallbackHistoryRecordId(numericTabId);const conversationId = chatHistoryConversationIdsByTab.get(numericTabId) || null;- await saveChatHistoryRecord({+ const record = await saveChatHistoryRecord({id: recordId,conversationId,tabId: numericTabId,@@ -2453,7 +2454,9 @@ async function persistChatHistorySnapshot(tabId, { refreshTabInfo = false, allowmessages,}).catch((error) => {console.warn('[WebBrain] failed to save chat history:', error);+ return null;});+ return record ? { ok: true, record } : { ok: false, reason: 'archive-failed' };}async function repairRestoredChatHistorySnapshot(tabId) {@@ -2487,7 +2490,7 @@ async function flushChatHistorySnapshot(tabId, options = {}) {historyPersistTimer = null;historyPersistTimerTabId = null;}- await persistChatHistorySnapshot(tabId, options);+ return persistChatHistorySnapshot(tabId, options);}async function resetChatHistoryStateForTab(tabId) {@@ -5237,6 +5240,7 @@ function requestVisibleSidePanelStateRefresh() {if (!refreshed || refreshPromise !== visibleStateRefreshPromise) return;consumePendingContextMenuPrompt().then(() => drainQueuedContextMenuPrompts()).catch(() => {});}).catch(() => {});+ return refreshPromise;}async function refreshConversationScopeState(tabId = currentTabId, { apply = true } = {}) {@@ -9860,7 +9864,11 @@ browser.runtime.onMessage.addListener((msg, _sender, sendResponse) => {|| String(msg.ownerId || '') !== tabChatHandoffOwnerId) return;const respond = () => {const snapshot = lastVisibleTabChatSnapshot;- if (!snapshot || !sameTabId(snapshot.tabId, msg.tabId)) { sendResponse({ ok: false }); return; }+ if (!snapshot || !sameTabId(snapshot.tabId, msg.tabId)+ || tabChatHandoffGenerations.get(Number(msg.tabId)) !== Number(msg.generation)) {+ sendResponse({ ok: false });+ return;+ }sendResponse({ok: true,tabId: Number(snapshot.tabId),@@ -12751,6 +12759,7 @@ function askAboutSelectedAnswer() {}function addMessage(role, content, options = {}) {+ const messageRoot = options.root || messagesEl;const msgEl = document.createElement('div');msgEl.className = `message ${role}`;@@ -12795,10 +12804,10 @@ function addMessage(role, content, options = {}) {if (role === 'user' && Array.isArray(options.attachments) && options.attachments.length) {renderMessageAttachments(msgEl, options.attachments, options.attachmentState || 'included');}- if (options.beforeCurrentAssistant && currentAssistantEl?.parentNode === messagesEl) {- messagesEl.insertBefore(msgEl, currentAssistantEl);+ if (options.beforeCurrentAssistant && currentAssistantEl?.parentNode === messageRoot) {+ messageRoot.insertBefore(msgEl, currentAssistantEl);} else {- messagesEl.appendChild(msgEl);+ messageRoot.appendChild(msgEl);}if (role === 'user' && options.sourceGrounding) {addSelectionScopeDivider(msgEl, options.sourceGrounding);@@ -12819,7 +12828,7 @@ function addMessage(role, content, options = {}) {addMessageCopyButton(msgEl);}- scrollToBottom();+ if (!options.detached) scrollToBottom();return msgEl;}@@ -15109,15 +15118,41 @@ async function openChatHistoryPage() {const historyPopover = document.getElementById('history-popover');let historyPopoverRequest = 0;+function createHistoryRecoveryTranscript(record) {+ const root = document.createElement('div');+ for (const message of record.messages || []) {+ if (!['user', 'assistant'].includes(message.role)) continue;+ const restored = addMessage(message.role, message.text, { root, detached: true, createdAt: message.createdAt,+ attachments: message.attachments, attachmentState: 'included' });+ if (message.role === 'user') {+ delete restored.dataset.composerHistoryVerbatim;+ delete restored.dataset.composerHistoryText;+ const provenance = historyRecoveryMetadata(message);+ if (provenance.userTextSource === 'verbatim') restored.dataset.composerHistoryVerbatim = 'true';+ if (provenance.modelText) restored.dataset.composerHistoryText = provenance.modelText;+ }+ }+ return root.innerHTML;+}+async function recoverHistoryRecord(recordId, tabId, pageUrl) {if (tabSwitchTransitionId != null || isTabProcessing(tabId) || isConversationClearInProgress(tabId)|| !sameTabId(currentTabId, tabId) || !sameTabId(renderedTabId, tabId)) return;historyRecoveryTabs.add(tabId);setConversationClearInProgress(tabId, true);+ let recoveryRequested = false;try {if ((await getTabInfoForHistory(tabId)).url !== pageUrl) throw new Error(t('sp.history.changed'));- await flushChatHistorySnapshot(tabId, { refreshTabInfo: true });- const result = await sendToBackground('recover_chat_history', { tabId, recordId });+ const archived = await flushChatHistorySnapshot(tabId, { refreshTabInfo: true, allowHidden: true });+ if (!archived?.ok) throw new Error(t('sp.history.failed'));+ const source = await getChatHistoryRecord(recordId);+ if (!source) throw new Error(t('sp.history.failed'));+ const html = createHistoryRecoveryTranscript(source);+ recoveryRequested = true;+ const result = await sendToBackground('recover_chat_history', {+ tabId, recordId, html, recordUpdatedAt: source.updatedAt, handoffOwnerId: tabChatHandoffOwnerId,+ handoffGeneration: tabChatHandoffGenerations.get(Number(tabId)),+ });if (!result?.ok) throw new Error(result?.error || t('sp.history.failed'));if (!sameTabId(currentTabId, tabId) || !sameTabId(renderedTabId, tabId)) return;if (historyPersistTimer) clearTimeout(historyPersistTimer);@@ -15136,24 +15171,32 @@ async function recoverHistoryRecord(recordId, tabId, pageUrl) {chatHistoryCreatedAtByTab.set(tabId, Date.now());applyConversationScopeState(tabId, result);setMode('ask');- for (const message of result.record.messages || []) {- if (!['user', 'assistant'].includes(message.role)) continue;- const restored = addMessage(message.role, message.text, { createdAt: message.createdAt,- attachments: message.attachments, attachmentState: 'included' });- if (message.role === 'user') {- delete restored.dataset.composerHistoryVerbatim;- delete restored.dataset.composerHistoryText;- const provenance = historyRecoveryMetadata(message);- if (provenance.userTextSource === 'verbatim') restored.dataset.composerHistoryVerbatim = 'true';- if (provenance.modelText) restored.dataset.composerHistoryText = provenance.modelText;- }- }- const saved = await flushRenderedTabChat({ allowHidden: true });- if (!saved?.ok || saved.skipped) throw new Error(t('sp.history.failed'));+ // The background already durably committed this HTML with the model state.+ tabChatHandoffGenerations.set(Number(tabId), result.handoffGeneration);+ messagesEl.innerHTML = result.html;+ tabChats.set(Number(tabId), result.html);+ lastVisibleTabChatSnapshot = { tabId: Number(tabId), html: result.html };+ rebindRestoredMessageControls();await flushChatHistorySnapshot(tabId, { refreshTabInfo: true, allowHidden: true });historyPopover.hidePopover();} catch (error) {- showComposerToast(error?.message || t('sp.history.failed'), { duration: 7000 });+ if (recoveryRequested) {+ // A lost response may follow a successful commit. Drop every cached old+ // identity/snapshot before the handoff reload so it cannot overwrite the+ // new transcript or enable sends against a different model conversation.+ console.warn('[WebBrain] Reconciling history recovery:', error);+ tabChats.delete(Number(tabId));+ chatHistoryRecordIdsByTab.delete(tabId);+ chatHistoryConversationIdsByTab.delete(tabId);+ chatHistoryCreatedAtByTab.delete(tabId);+ tabChatHandoffGenerations.delete(Number(tabId));+ if (lastVisibleTabChatSnapshot && sameTabId(lastVisibleTabChatSnapshot.tabId, tabId)) lastVisibleTabChatSnapshot = null;+ if (persistTimer && sameTabId(persistTimerTabId, tabId)) { clearTimeout(persistTimer); persistTimer = null; persistTimerTabId = null; }+ // Visibility restoration performs this same refresh when the panel is hidden.+ requestVisibleSidePanelStateRefresh();+ } else {+ showComposerToast(error?.message || t('sp.history.failed'), { duration: 7000 });+ }} finally {historyRecoveryTabs.delete(tabId);setConversationClearInProgress(tabId, false);diff --git a/src/firefox/src/ui/tab-chat-persistence.js b/src/firefox/src/ui/tab-chat-persistence.jsindex eae3d143f..a7c87c0f1 100644--- a/src/firefox/src/ui/tab-chat-persistence.js+++ b/src/firefox/src/ui/tab-chat-persistence.js@@ -407,6 +407,26 @@ export function createTabChatHandoffCoordinator(storageArea, {});}+ function replace(tabId, html, { ownerId, handoffGeneration, commit } = {}) {+ return enqueue(tabId, async queuedTabId => {+ const current = await readHandoffState(queuedTabId);+ if (!current || current.ownerId !== ownerId || current.generation !== Number(handoffGeneration)) {+ throw new Error('The conversation panel changed before recovery. Try again in the active panel.');+ }+ if (typeof html !== 'string' || typeof commit !== 'function') throw new Error('No recovered transcript.');+ const generation = current.generation + 1;+ const persistedHtml = compactTabChatForPersist(html);+ // The model snapshot, transcript, and ownership generation are one storage+ // transaction. A failed write leaves the previous conversation intact.+ const state = await commit({+ [TAB_CHAT_PREFIX + queuedTabId]: persistedHtml,+ [TAB_CHAT_HANDOFF_PREFIX + queuedTabId]: { ownerId, generation },+ });+ latestHtml.set(queuedTabId, html);+ return { ...state, html, handoffOwnerId: ownerId, handoffGeneration: generation };+ });+ }+async function load(tabId, { waitForHandoff = false, claimantId = '' } = {}) {const numericTabId = normalizeTabId(tabId);if (numericTabId == null) return { ok: false, found: false, error: 'No tab ID' };@@ -530,5 +550,5 @@ export function createTabChatHandoffCoordinator(storageArea, {});}- return { save, load, clear };+ return { save, load, clear, replace };}diff --git a/test/ask-stream-retry-ui.mjs b/test/ask-stream-retry-ui.mjsindex 516841539..ccd8c3a08 100644--- a/test/ask-stream-retry-ui.mjs+++ b/test/ask-stream-retry-ui.mjs@@ -160,6 +160,8 @@ for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {${unexport(read(build, 'src/ui/markdown-render.js'))}${unexport(read(build, 'src/ui/markdown-link.js'))}${unexport(read(build, 'src/ui/history-text.js'))}+ ${unexport(read(build, 'src/context-menu-storage.js'))}+ ${unexport(read(build, 'src/chat-history-recovery.js').replace(/^import .*;\n/gm, ''))}${source.slice(helperStart, observerEnd)}${functions}${observeCall}diff --git a/test/history-recovery-atomic.mjs b/test/history-recovery-atomic.mjsnew file mode 100644index 000000000..ea48133e7--- /dev/null+++ b/test/history-recovery-atomic.mjs@@ -0,0 +1,64 @@+import assert from 'node:assert/strict';+import { test } from 'node:test';++let session = {}, failWrite = false, writes = [];+const area = {+ get: async key => key === null ? structuredClone(session) : { [key]: structuredClone(session[key]) },+ set: async values => { writes.push(structuredClone(values)); if (failWrite) throw new Error('Storage unavailable'); Object.assign(session, structuredClone(values)); },+ remove: async key => { delete session[key]; },+};+globalThis.chrome = globalThis.browser = { alarms:{}, runtime:{ getURL:x=>x }, storage:{ session:area, local:{ get:async()=>({}), set:async()=>{} } } };++for (const build of ['chrome','firefox']) {+ const { Agent } = await import(`../src/${build}/src/agent/agent.js`);+ const { createTabChatHandoffCoordinator } = await import(`../src/${build}/src/ui/tab-chat-persistence.js`);+ const archive = { id:'source', messages:[{role:'user',text:'recovered conversation',userTextSource:'verbatim'}] };+ async function fixture() {+ session = { 'tabChat:42':'previous transcript', 'tabChatHandoff:42':{ownerId:'panel',generation:1} };+ failWrite = false; writes=[];+ const agent = new Agent({getActive:()=>({supportsVision:false})});+ agent.hydratedTabs.add(42);+ agent.getConversation(42,'ask').push({role:'user',content:'previous conversation'});+ await agent._persistNow(42);+ const handoff = createTabChatHandoffCoordinator(area);+ const recover = (generation=1) => handoff.replace(42,'recovered transcript',{+ ownerId:'panel', handoffGeneration:generation,+ commit:storageEntries=>agent.recoverChatHistory(42,archive,{storageEntries}),+ });+ return {agent,handoff,recover};+ }+ test(`${build}: recovery commits model context, transcript, and handoff together`,async()=>{+ const f=await fixture(); writes=[];+ const result=await f.recover();+ assert.equal(writes.length,1);+ assert.equal(writes[0]['tabChat:42'],'recovered transcript');+ assert.equal(writes[0]['tabChatHandoff:42'].generation,2);+ assert.equal(writes[0]['agentConv:42'].conversationId,result.conversationId);+ assert.equal((await f.handoff.save(42,'stale old transcript',{ownerId:'panel',handoffGeneration:1})).skipped,true);+ assert.equal((await f.handoff.load(42)).html,'recovered transcript');+ // Reopening after losing the response does not depend on the initiating panel.+ const reopened=createTabChatHandoffCoordinator(area);+ assert.equal((await reopened.load(42)).html,'recovered transcript');+ const restarted=new Agent({getActive:()=>({supportsVision:false})});+ await restarted._hydrate(42);+ assert.equal(restarted.conversationIds.get(42),result.conversationId);+ assert.equal(restarted.conversations.get(42)[1].content,'recovered conversation');+ });+ test(`${build}: failed atomic recovery preserves both old model and old UI`,async()=>{+ const f=await fixture(), old=structuredClone(session), oldId=f.agent.conversationIds.get(42);+ await f.handoff.load(42);+ failWrite=true;+ await assert.rejects(f.recover(),/Unable to persist/);+ failWrite=false;+ assert.deepEqual(session,old);+ assert.equal(f.agent.conversationIds.get(42),oldId);+ assert.equal(f.agent.conversations.get(42)[1].content,'previous conversation');+ assert.equal((await f.handoff.load(42)).html,'previous transcript');+ });+ test(`${build}: stale recovery owner is rejected before changing model context`,async()=>{+ const f=await fixture(), old=structuredClone(session);+ await assert.rejects(f.recover(99),/panel changed/);+ assert.deepEqual(session,old);+ assert.equal(f.agent.conversations.get(42)[1].content,'previous conversation');+ });+}diff --git a/test/history-recovery-scheduler.mjs b/test/history-recovery-scheduler.mjsnew file mode 100644index 000000000..a3ba68e85--- /dev/null+++ b/test/history-recovery-scheduler.mjs@@ -0,0 +1,119 @@+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+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: value => value, sendMessage: async () => ({}) },+ tabs: { get: async id => ({ id, url: 'https://example.com/' }), sendMessage: async () => ({}) },+};+const deferred = () => {+ let resolve;+ const promise = new Promise(done => { resolve = done; });+ return { promise, resolve };+};++function backgroundGuards(source, agent, scheduler, locks, cloudGuard = async () => {}) {+ const start = source.indexOf('agent.setRunStartGuard(async (tabId, context) => {');+ const end = source.indexOf('\nconst profileSync', start);+ assert.ok(start >= 0 && end > start, 'The production run-start guard must be exercised');+ let runStartGuard;+ new Function('agent', 'recoveringHistoryTabs', 'cloudRunController', 'teacherRunInterlock', source.slice(start, end))(+ { setRunStartGuard: guard => { runStartGuard = guard; } }, locks,+ { guardRunStart: cloudGuard }, { guardRunStart: async () => {} },+ );+ const assertStart = source.indexOf('function assertNoActiveTabRun(tabId) {');+ const assertEnd = source.indexOf('\nasync function activateForegroundCompatibilityTab', assertStart);+ assert.ok(assertStart >= 0 && assertEnd > assertStart, 'The production recovery guard must be exercised');+ const assertNoActiveTabRun = new Function('agent', 'scheduler', 'recoveringHistoryTabs', 'detachedRunStarts',+ `${source.slice(assertStart, assertEnd)}\nreturn assertNoActiveTabRun;`)(agent, scheduler, locks, new Map());+ return { runStartGuard, assertNoActiveTabRun };+}++async function createTask(h) {+ const result = await h.manager.createTaskJob({+ tabId: 77, conversationId: 'conv-1', source: 'sidepanel', currentUrl: 'https://example.com/',+ args: { title: 'Read later', prompt: 'Read this page', mode: 'ask', schedule: { after_seconds: 60 },+ target: { type: 'current_tab' } },+ });+ assert.equal(result.success, true);+ return result.jobId;+}++for (const build of ['chrome', 'firefox']) {+ const source = await readFile(`src/${build}/src/background.js`, 'utf8');+ const scheduler = await import(`../src/${build}/src/agent/scheduler.js`);+ const { Agent } = await import(`../src/${build}/src/agent/agent.js`);++ test(`${build}: history recovery blocks scheduler reservation and defers the job without losing it`, async () => {+ let dispatches = 0, cloudChecks = 0;+ const locks = new Set([77]);+ const h = makeSchedulerHarness(scheduler, { processMessage: async () => { dispatches++; return 'Finished'; } });+ h.manager.agent.activeRunState = () => ({ running: false });+ const guards = backgroundGuards(source, h.manager.agent, h.manager, locks, async () => { cloudChecks++; });+ h.manager.agent.assertRunStartAllowed = (tabId, kind) => guards.runStartGuard(tabId, { kind });+ const jobId = await createTask(h);+ await h.manager.handleAlarm(h.alarmName(jobId));+ assert.equal(dispatches, 0);+ assert.equal(cloudChecks, 0, 'A recovery-owned tab must be rejected before asynchronous startup checks');+ assert.equal(h.manager.isRunning(77), false, 'Rejected startup must release the scheduler reservation');+ assert.equal(h.jobs()[0].status, 'queued', 'Recovery is transient contention, not a permanent scheduled failure');+ assert.equal(h.alarms.has(h.alarmName(jobId)), true);+ assert.deepEqual([...locks], [77], 'Scheduler rejection must retain the recovery owner');+ locks.delete(77);+ await h.manager.handleAlarm(h.alarmName(jobId));+ assert.equal(dispatches, 1);+ assert.equal(h.jobs()[0].status, 'completed');+ assert.doesNotThrow(() => guards.assertNoActiveTabRun(77));+ });++ test(`${build}: scheduler reservation blocks recovery throughout guard and provider startup`, async () => {+ const guarded = deferred(), releaseGuard = deferred(), loading = deferred(), releaseLoading = deferred();+ let dispatches = 0;+ const locks = new Set();+ const h = makeSchedulerHarness(scheduler, { processMessage: async () => { dispatches++; return 'Finished'; } });+ h.manager.agent.activeRunState = () => ({ running: false });+ const guards = backgroundGuards(source, h.manager.agent, h.manager, locks, async () => {+ guarded.resolve(); await releaseGuard.promise;+ });+ h.manager.agent.assertRunStartAllowed = (tabId, kind) => guards.runStartGuard(tabId, { kind });+ h.manager.loadProviders = async () => { loading.resolve(); await releaseLoading.promise; };+ const jobId = await createTask(h);+ const run = h.manager.handleAlarm(h.alarmName(jobId));+ try {+ await guarded.promise;+ assert.equal(h.manager.isRunning(77), true);+ assert.equal(dispatches, 0);+ assert.throws(() => guards.assertNoActiveTabRun(77), /already active/);+ releaseGuard.resolve();+ await loading.promise;+ assert.equal(h.manager.isRunning(77), true);+ assert.equal(dispatches, 0, 'The scheduled agent has not started during provider loading');+ assert.throws(() => guards.assertNoActiveTabRun(77), /already active/);+ } finally {+ releaseGuard.resolve(); releaseLoading.resolve(); await run;+ }+ assert.equal(dispatches, 1);+ assert.equal(h.manager.isRunning(77), false);+ assert.doesNotThrow(() => guards.assertNoActiveTabRun(77));+ });++ test(`${build}: actual scheduled agent startup rechecks history ownership before processing`, async () => {+ const agent = new Agent({ getActive: () => ({ supportsVision: false }) });+ const locks = new Set();+ const guards = backgroundGuards(source, agent, { isRunning: () => false }, locks);+ agent.setRunStartGuard(guards.runStartGuard);+ let hydrations = 0, dispatches = 0;+ agent._hydrate = async () => { hydrations++; };+ agent._processMessageInner = async () => { dispatches++; return 'Finished'; };+ await agent.assertRunStartAllowed(77, 'scheduled', { scheduledRun: true });+ locks.add(77);+ await assert.rejects(agent.processMessage(77, 'Read this page', () => {}, 'ask', [], { scheduledRun: true }), /recovery is in progress/);+ assert.equal(hydrations, 0);+ assert.equal(dispatches, 0);+ assert.equal(agent.isRunning(77), false);+ assert.deepEqual([...locks], [77]);+ });+}diff --git a/test/history-recovery-state.mjs b/test/history-recovery-state.mjsindex e7c4bd753..c87079266 100644--- a/test/history-recovery-state.mjs+++ b/test/history-recovery-state.mjs@@ -114,7 +114,7 @@ for (const build of ['chrome', 'firefox']) {source.indexOf(" case 'restore_selection_scope':"));const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;const handle = new AsyncFunction('msg', 'sender', 'agent', 'scheduler', 'recoveringHistoryTabs',- 'assertNoActiveTabRun', 'getChatHistoryRecord', 'chrome', 'browser', 'clearRunUiSnapshot', 'console', body);+ 'assertNoActiveTabRun', 'getChatHistoryRecord', 'chrome', 'browser', 'clearRunUiSnapshot', 'console', 'tabChatHandoff', body);let recoverFails = true, cancelFails = false;const events = [], locks = new Set();const agent = { getConversationId: async () => 'old', recoverChatHistory: async () => {@@ -129,7 +129,8 @@ for (const build of ['chrome', 'firefox']) {const api = { tabs: { get: async () => ({ url: 'https://example.com/' }) } };const invoke = () => handle({ tabId: 1, recordId: 'archive' }, {}, agent, scheduler, locks,() => {}, async () => ({ ...archive, url: 'https://example.com/' }), api, api,- () => events.push('clear-ui'), { warn: () => events.push('warning') });+ () => events.push('clear-ui'), { warn: () => events.push('warning') },+ { replace: async (id, html, { commit }) => commit({}) });await assert.rejects(invoke(), /Unable to persist/);assert.deepEqual(events, ['recover']);assert.equal(locks.size, 0);diff --git a/test/history-recovery-ui.mjs b/test/history-recovery-ui.mjsindex 04911fb67..2cd2e6261 100644--- a/test/history-recovery-ui.mjs+++ b/test/history-recovery-ui.mjs@@ -60,7 +60,11 @@ for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {const hydrateChatHistoryIdentity = async () => {};const fallbackHistoryRecordId = () => 'previous';const extractChatHistoryMessages = () => [{ role: 'user', text: messagesEl.textContent }];- const saveChatHistoryRecord = async record => { window.archive = record; window.archivedHidden = hidden; };+ const saveChatHistoryRecord = async record => {+ if (window.archiveFails) throw new Error('IndexedDB quota exceeded');+ window.archive = record; window.archivedHidden = hidden; return record;+ };+ const getChatHistoryRecord = async () => ({ messages: [{role:'user', text:'recovered dialog'}] });let persistTimer = null, persistTimerTabId = null, historyPersistTimer = null, currentAssistantEl = null;let lastVisibleTabChatSnapshot = { tabId: 42, html: 'old dialog' };const historyPopover = { hidePopover() {} };@@ -77,12 +81,14 @@ for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {const t = value => value;const showComposerToast = message => { window.failure = message; };const enqueueTabChatOperation = (tabId, fn) => fn(tabId);- const addMessage = (role,text) => { const el = document.createElement('div'); el.textContent = text; messagesEl.append(el); return el; };+ const addMessage = (role,text,options={}) => { const el = document.createElement('div'); el.textContent = text; (options.root || messagesEl).append(el); return el; };+ const rebindRestoredMessageControls = () => {};+ const requestVisibleSidePanelStateRefresh = () => { window.refreshRequested = true; };${extract(source, 'persistChatHistorySnapshot')}${extract(source, 'flushChatHistorySnapshot')}let completeRecovery;const sendToBackground = async (action, payload) => {- if (action === 'recover_chat_history') return new Promise(resolve => completeRecovery = resolve);+ if (action === 'recover_chat_history') { window.recoveryCalls = (window.recoveryCalls || 0) + 1; window.candidateHtml = payload.html; if (window.loseResponse) { window.persisted = payload.html; throw new Error('Response channel lost after commit'); } return new Promise(resolve => completeRecovery = resolve); }if (action === 'persist_tab_chat') { window.persisted = payload.html; return { ok: true }; }throw new Error(action);};@@ -91,9 +97,10 @@ for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {${extract(source, 'waitForHistoryRecovery')}${extract(source, 'persistTabChat')}${extract(source, 'flushRenderedTabChat')}+ ${extract(source, 'createHistoryRecoveryTranscript')}${extract(source, 'recoverHistoryRecord')}${listener}- window.finish = () => completeRecovery({ ok: true, conversationId: 'new-id', record: { messages: [{role: 'user', text:'recovered dialog'}] } });+ window.finish = () => { window.persisted = window.candidateHtml; completeRecovery({ ok: true, conversationId: 'new-id', handoffGeneration: 2, html: window.candidateHtml }); };window.hide = () => { hidden = true; };window.recovery = recoverHistoryRecord('archive', 42, 'https://example.com/');` });@@ -107,11 +114,34 @@ for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {await page.evaluate(async () => { window.finish(); await window.recovery; });await page.waitForFunction(() => window.ack);assert.match(await page.evaluate(() => window.persisted), /recovered dialog/);- assert.equal(await page.evaluate(() => window.ack.html), await page.evaluate(() => window.persisted));+ assert.equal(await page.evaluate(() => window.ack.ok), false, 'An acknowledgement from the old generation cannot overwrite the committed transcript');+ await page.evaluate(() => window.handoff({target:'sidepanel', action:'tab_chat_handoff_request', ownerId:'owner', tabId:42, generation:2}, {}, value => {window.freshAck = value;}));+ assert.equal(await page.evaluate(() => window.freshAck.html), await page.evaluate(() => window.persisted));assert.equal(await page.evaluate(() => window.archivedHidden), true);assert.equal(await page.evaluate(() => window.archive.id), 'new-id');assert.equal(await page.evaluate(() => window.archive.messages[0].text), 'recovered dialog');assert.equal(await page.evaluate(() => window.failure), undefined);+ await page.evaluate(async () => {+ document.querySelector('#messages').textContent = 'unsaved current changes';+ window.archiveFails = true;+ await recoverHistoryRecord('archive', 42, 'https://example.com/');+ });+ assert.equal(await page.evaluate(() => window.recoveryCalls), 1, 'Archive failure must not call background recovery');+ assert.equal(await page.locator('#messages').textContent(), 'unsaved current changes');+ assert.equal(await page.evaluate(() => window.failure), 'sp.history.failed');+ await page.evaluate(async () => {+ delete window.failure;+ window.archiveFails = false;+ window.loseResponse = true;+ await recoverHistoryRecord('archive', 42, 'https://example.com/');+ window.cacheAfterLostResponse = { snapshot:lastVisibleTabChatSnapshot,+ id:chatHistoryConversationIdsByTab.get(42), html:tabChats.get(42), generation:tabChatHandoffGenerations.get(42) };+ window.handoff({target:'sidepanel', action:'tab_chat_handoff_request', ownerId:'owner', tabId:42, generation:3}, {}, value => window.lostResponseAck = value);+ });+ assert.equal(await page.evaluate(() => window.refreshRequested), true, 'Lost response reconciles from authoritative background state');+ assert.deepEqual(await page.evaluate(() => window.cacheAfterLostResponse), {snapshot:null, id:undefined, html:undefined, generation:undefined});+ assert.equal(await page.evaluate(() => window.lostResponseAck.ok), false);+ assert.equal(await page.evaluate(() => window.failure), undefined, 'An ambiguous response cannot report the committed recovery as failed');} finally { await browser.close(); }});}diff --git a/test/history-recovery.mjs b/test/history-recovery.mjsindex 3950bfce6..4329fa35e 100644--- a/test/history-recovery.mjs+++ b/test/history-recovery.mjs@@ -63,6 +63,23 @@ for (const build of ['chrome', 'firefox']) {await page.addStyleTag({ content: '#btn-history { position: fixed; bottom: 100px; right: 30px; }' });await page.addScriptTag({ type: 'module', content: `import * as store from '/src/ui/chat-history-store.js'; window.store = store;` });await page.waitForFunction(() => window.store);+ const abortResult = await page.evaluate(async () => {+ const original = IDBObjectStore.prototype.put;+ IDBObjectStore.prototype.put = function(value, ...args) {+ const request = original.call(this, value, ...args);+ if (value.id === 'abort-after-request') request.addEventListener('success', () => this.transaction.abort());+ return request;+ };+ let rejected = false;+ try {+ await window.store.saveChatHistoryRecord({id:'abort-after-request', messages:[{role:'user',text:'must remain unsaved'}]});+ } catch { rejected = true; }+ finally { IDBObjectStore.prototype.put = original; }+ return {rejected, record:await window.store.getChatHistoryRecord('abort-after-request')};+ });+ assert.equal(abortResult.rejected, true, 'Request success is insufficient if the transaction aborts');+ assert.equal(abortResult.record, undefined);+await page.addScriptTag({ type: 'module', content: `import { buildSelectionPrompt, formatSelectionPromptForDisplay } from '/src/context-menu-storage.js';import { historyRecoveryMetadata } from '/src/chat-history-recovery.js';diff --git a/test/run.js b/test/run.jsindex cf78cea3f..767d7533a 100644--- a/test/run.js+++ b/test/run.js@@ -47846,10 +47846,10 @@ test('sidepanel ignores stale async history snapshot saves', () => {const persistStart = panel.indexOf('async function persistChatHistorySnapshot(');assert.notEqual(persistStart, -1, `${label}: persistChatHistorySnapshot missing`);const persistBody = panel.slice(persistStart, panel.indexOf('\n}\n\nfunction scheduleHistoryPersist', persistStart) + 2);- const userCheckIdx = persistBody.indexOf("if (!messages.some((message) => message.role === 'user')) return;");+ const userCheckIdx = persistBody.indexOf("if (!messages.some((message) => message.role === 'user')) return");const stampIdx = persistBody.indexOf('const saveSeq = nextChatHistorySaveSeqForTab(numericTabId);');const hydrateIdx = persistBody.indexOf('await hydrateChatHistoryIdentity(numericTabId, agentMode, { refreshTabInfo });');- const staleGuardIdx = persistBody.indexOf('if (chatHistorySaveSeqByTab.get(numericTabId) !== saveSeq) return;');+ const staleGuardIdx = persistBody.indexOf('if (chatHistorySaveSeqByTab.get(numericTabId) !== saveSeq) return');const saveIdx = persistBody.indexOf('await saveChatHistoryRecord({');assert.notEqual(userCheckIdx, -1, `${label}: snapshots should skip conversations without user messages`);assert.notEqual(stampIdx, -1, `${label}: snapshots should stamp async saves`);