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
Fork /btw conversations
Codex release-state test010dae59864d
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex 8ab362cfc..9a96d3130 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -6121,6 +6121,43 @@ export class Agent extends LoopDetector {return (await this.getConversationState(tabId, mode)).conversationId;}+ async forkConversation(sourceTabId, forkTabId) {+ const sourceId = Number(sourceTabId);+ const forkId = Number(forkTabId);+ if (!Number.isFinite(sourceId) || !Number.isFinite(forkId) || sourceId === forkId) {+ throw new Error('Invalid conversation fork');+ }+ if (this._runningTabs.has(forkId)) throw new Error('Fork conversation is already running');++ await this._hydrate(sourceId);+ const sourceMessages = this.conversations.get(sourceId) || [];+ const messages = sourceMessages.length+ ? JSON.parse(JSON.stringify(sourceMessages))+ : [{ role: 'system', content: this._buildSystemPrompt('ask', forkId) }];+ if (messages[0]?.role === 'system') {+ messages[0].content = this._buildSystemPrompt('ask', forkId);+ } else {+ messages.unshift({ role: 'system', content: this._buildSystemPrompt('ask', forkId) });+ }++ // A fork inherits only durable conversation history. Page state, pending+ // plans, workflow drafts, and task progress belong exclusively to its source.+ this.conversations.set(forkId, messages);+ this.conversationModes.set(forkId, 'ask');+ this.conversationIds.set(forkId, `conv_${forkId}_${Date.now()}_${secureRandomBase36Token(12)}`);+ this._latestWorkflowDrafts.delete(forkId);+ this.selectionGroundingScopes.delete(forkId);+ this.selectionGroundingRestorationPendingTabs.delete(forkId);+ this.progressLedgers.delete(forkId);+ this.progressSessions.delete(forkId);+ this.submittedRunRequestIds.delete(forkId);+ this._continuationResponseLanguagePolicies.delete(forkId);+ this._clarificationAuthorizationGuards.delete(forkId);+ this.hydratedTabs.add(forkId);+ await this._persistNow(forkId);+ return { conversationId: this.conversationIds.get(forkId) };+ }+_rememberWorkflowDraftFromCapture(tabId, capture) {if (!capture?.run || capture.run.status !== 'done') return false;const conversationId = this.conversationIds.get(tabId) || null;diff --git a/src/chrome/src/background.js b/src/chrome/src/background.jsindex 9395eaab2..1ea7dd06d 100644--- a/src/chrome/src/background.js+++ b/src/chrome/src/background.js@@ -3228,6 +3228,18 @@ async function handleMessage(msg, sender) {};}+ case 'fork_standalone_conversation': {+ const sourceTabId = Number(msg.sourceTabId);+ const forkTabId = Number(msg.forkTabId || sender.tab?.id);+ if (!Number.isFinite(sourceTabId) || !Number.isFinite(forkTabId)) {+ throw new Error('No source or fork tab ID');+ }+ const fork = await agent.forkConversation(sourceTabId, forkTabId);+ const sourceChat = await tabChatHandoff.load(sourceTabId, { waitForHandoff: true });+ if (sourceChat?.found) await tabChatHandoff.save(forkTabId, sourceChat.html);+ return { ok: true, ...fork };+ }+case 'chat_start': {await standaloneRunProviderId(msg);const claim = msg.contextMenuClaim;diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.jsindex 8bd5d9ae5..2708580d3 100644--- a/src/chrome/src/ui/sidepanel.js+++ b/src/chrome/src/ui/sidepanel.js@@ -87,7 +87,7 @@ import { isTextAttachment } from './attachment-file.js';const isStandaloneWindow = new URLSearchParams(window.location.search).get('standalone') === 'true';const _btwParams = new URLSearchParams(window.location.search);const isBtwWindow = _btwParams.get('btw') === '1';-const btwPinnedTabId = isBtwWindow ? (Number(_btwParams.get('tabId')) || null) : null;+const btwSourceTabId = isBtwWindow ? (Number(_btwParams.get('forkFromTabId')) || null) : null;const btwInitialPrompt = isBtwWindow ? (_btwParams.get('prompt') || '') : '';// Hydrate the theme from chrome.storage.local (the inline <head> bootstrap@@ -4657,8 +4657,11 @@ async function init() {: { active: true, currentWindow: true });let initialTabId = tab?.id;- if (isBtwWindow && btwPinnedTabId != null) {- initialTabId = btwPinnedTabId;+ if (isBtwWindow && btwSourceTabId != null && initialTabId != null) {+ await sendToBackground('fork_standalone_conversation', {+ sourceTabId: btwSourceTabId,+ forkTabId: initialTabId,+ });} else {try {const state = await sendToBackground('agent_run_state', { tabId: initialTabId });@@ -4793,14 +4796,6 @@ async function init() {await sendBtwPrompt(btwInitialPrompt);}await consumePendingBtwPrompt();- } else {- // Keep the stale record until the next open verifies its window ID. Every- // panel must be able to observe this event before that record disappears.- chrome.windows.onRemoved.addListener(async (removedWindowId) => {- const states = await getBtwWindowStates();- const state = Object.values(states).find(candidate => candidate?.windowId === removedWindowId);- if (state && sameTabId(state.tabId, currentTabId)) requestVisibleSidePanelStateRefresh();- });}}@@ -14713,7 +14708,7 @@ async function openBtwWindow(tabId, prompt = '') {}const promptParam = prompt ? `&prompt=${encodeURIComponent(prompt)}` : '';- const url = chrome.runtime.getURL(`src/ui/sidepanel.html?mode=ask&standalone=true&btw=1&tabId=${tabId}${promptParam}`);+ const url = chrome.runtime.getURL(`src/ui/sidepanel.html?mode=ask&standalone=true&btw=1&forkFromTabId=${tabId}${promptParam}`);const win = await chrome.windows.create({url,type: 'popup',@@ -14731,11 +14726,11 @@ async function sendBtwPrompt(prompt) {}async function consumePendingBtwPrompt() {- if (!isBtwWindow || btwPinnedTabId == null) return;- const state = await getBtwWindowState(btwPinnedTabId);+ if (!isBtwWindow || btwSourceTabId == null) return;+ const state = await getBtwWindowState(btwSourceTabId);const prompt = String(state?.pendingPrompt || '');if (!prompt) return;- await setBtwWindowState(btwPinnedTabId, { ...state, pendingPrompt: '' });+ await setBtwWindowState(btwSourceTabId, { ...state, pendingPrompt: '' });await sendBtwPrompt(prompt);}diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex e800a01e9..3c983412f 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -6241,6 +6241,43 @@ export class Agent extends LoopDetector {return (await this.getConversationState(tabId, mode)).conversationId;}+ async forkConversation(sourceTabId, forkTabId) {+ const sourceId = Number(sourceTabId);+ const forkId = Number(forkTabId);+ if (!Number.isFinite(sourceId) || !Number.isFinite(forkId) || sourceId === forkId) {+ throw new Error('Invalid conversation fork');+ }+ if (this._runningTabs.has(forkId)) throw new Error('Fork conversation is already running');++ await this._hydrate(sourceId);+ const sourceMessages = this.conversations.get(sourceId) || [];+ const messages = sourceMessages.length+ ? JSON.parse(JSON.stringify(sourceMessages))+ : [{ role: 'system', content: this._buildSystemPrompt('ask', forkId) }];+ if (messages[0]?.role === 'system') {+ messages[0].content = this._buildSystemPrompt('ask', forkId);+ } else {+ messages.unshift({ role: 'system', content: this._buildSystemPrompt('ask', forkId) });+ }++ // A fork inherits only durable conversation history. Page state, pending+ // plans, workflow drafts, and task progress belong exclusively to its source.+ this.conversations.set(forkId, messages);+ this.conversationModes.set(forkId, 'ask');+ this.conversationIds.set(forkId, `conv_${forkId}_${Date.now()}_${secureRandomBase36Token(12)}`);+ this._latestWorkflowDrafts.delete(forkId);+ this.selectionGroundingScopes.delete(forkId);+ this.selectionGroundingRestorationPendingTabs.delete(forkId);+ this.progressLedgers.delete(forkId);+ this.progressSessions.delete(forkId);+ this.submittedRunRequestIds.delete(forkId);+ this._continuationResponseLanguagePolicies.delete(forkId);+ this._clarificationAuthorizationGuards.delete(forkId);+ this.hydratedTabs.add(forkId);+ await this._persistNow(forkId);+ return { conversationId: this.conversationIds.get(forkId) };+ }+/*** Snapshot the effective runtime settings for a run. Anything we cannot* observe is omitted rather than guessed: an absent field reads as "unknown"diff --git a/src/firefox/src/background.js b/src/firefox/src/background.jsindex e72d8b736..adacbc22f 100644--- a/src/firefox/src/background.js+++ b/src/firefox/src/background.js@@ -2743,6 +2743,18 @@ async function handleMessage(msg, sender) {};}+ case 'fork_standalone_conversation': {+ const sourceTabId = Number(msg.sourceTabId);+ const forkTabId = Number(msg.forkTabId || sender.tab?.id);+ if (!Number.isFinite(sourceTabId) || !Number.isFinite(forkTabId)) {+ throw new Error('No source or fork tab ID');+ }+ const fork = await agent.forkConversation(sourceTabId, forkTabId);+ const sourceChat = await tabChatHandoff.load(sourceTabId, { waitForHandoff: true });+ if (sourceChat?.found) await tabChatHandoff.save(forkTabId, sourceChat.html);+ return { ok: true, ...fork };+ }+case 'chat_start': {const claim = msg.contextMenuClaim;if (!claim?.promptId || !claim?.claimantId) {diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.jsindex fbdff8b7e..78b3a8cb6 100644--- a/src/firefox/src/ui/sidepanel.js+++ b/src/firefox/src/ui/sidepanel.js@@ -93,7 +93,7 @@ const isStandaloneWindow = new URLSearchParams(window.location.search).get('stanconst _btwParams = new URLSearchParams(window.location.search);const isBtwWindow = _btwParams.get('btw') === '1';-const btwPinnedTabId = isBtwWindow ? (Number(_btwParams.get('tabId')) || null) : null;+const btwSourceTabId = isBtwWindow ? (Number(_btwParams.get('forkFromTabId')) || null) : null;const btwInitialPrompt = isBtwWindow ? (_btwParams.get('prompt') || '') : '';// Hydrate the theme from browser.storage.local (the inline <head> bootstrap@@ -4520,8 +4520,11 @@ async function init() {: { active: true, currentWindow: true });let initialTabId = tab?.id;- if (isBtwWindow && btwPinnedTabId != null) {- initialTabId = btwPinnedTabId;+ if (isBtwWindow && btwSourceTabId != null && initialTabId != null) {+ await sendToBackground('fork_standalone_conversation', {+ sourceTabId: btwSourceTabId,+ forkTabId: initialTabId,+ });} else {try {const state = await sendToBackground('agent_run_state', { tabId: initialTabId });@@ -4648,14 +4651,6 @@ async function init() {await sendBtwPrompt(btwInitialPrompt);}await consumePendingBtwPrompt();- } else {- // Keep the stale record until the next open verifies its window ID. Every- // panel must be able to observe this event before that record disappears.- browser.windows.onRemoved.addListener(async (removedWindowId) => {- const states = await getBtwWindowStates();- const state = Object.values(states).find(candidate => candidate?.windowId === removedWindowId);- if (state && sameTabId(state.tabId, currentTabId)) requestVisibleSidePanelStateRefresh();- });}}@@ -14209,7 +14204,7 @@ async function openBtwWindow(tabId, prompt = '') {await clearBtwWindowState(tabId, existing.windowId);}const promptParam = prompt ? `&prompt=${encodeURIComponent(prompt)}` : '';- const url = browser.runtime.getURL(`src/ui/sidepanel.html?mode=ask&standalone=true&btw=1&tabId=${tabId}${promptParam}`);+ const url = browser.runtime.getURL(`src/ui/sidepanel.html?mode=ask&standalone=true&btw=1&forkFromTabId=${tabId}${promptParam}`);const win = await browser.windows.create({url,type: 'popup',@@ -14226,11 +14221,11 @@ async function sendBtwPrompt(prompt) {}async function consumePendingBtwPrompt() {- if (!isBtwWindow || btwPinnedTabId == null) return;- const state = await getBtwWindowState(btwPinnedTabId);+ if (!isBtwWindow || btwSourceTabId == null) return;+ const state = await getBtwWindowState(btwSourceTabId);const prompt = String(state?.pendingPrompt || '');if (!prompt) return;- await setBtwWindowState(btwPinnedTabId, { ...state, pendingPrompt: '' });+ await setBtwWindowState(btwSourceTabId, { ...state, pendingPrompt: '' });await sendBtwPrompt(prompt);}diff --git a/test/run.js b/test/run.jsindex 79436dfd5..f290cb43a 100644--- a/test/run.js+++ b/test/run.js@@ -47793,11 +47793,15 @@ test('chrome sidepanel serializes tab-chat storage writes with clears and reads'assert.match(loadBody, /return await enqueueTabChatOperation\(numericTabId, async \(queuedTabId\) => \{[\s\S]*?sendToBackground\('load_tab_chat', \{[\s\S]*?waitForHandoff,[\s\S]*?\}\);/, 'chrome: tab-chat restore should read through the shared background queue');assert.match(loadBody, /catch \(e\) \{\s*if \(waitForHandoff\) return TAB_CHAT_LOAD_FAILED;\s*\}[\s\S]*?return null;/, 'chrome: coordinated load failures should remain distinct from successful empty restores');assert.match(panel, /const html = await loadTabChat\(tabId, \{ waitForHandoff: true \}\);\s*if \(html === TAB_CHAT_LOAD_FAILED\) return false;[\s\S]*?messagesEl\.innerHTML = '';/, 'chrome: a failed visibility handoff must preserve the current transcript DOM');- assert.match(panel, /const BTW_WINDOWS_KEY = 'btwWindows';[\s\S]*?async function getBtwWindowState\(tabId\)/, 'chrome: /btw windows should be tracked per tab');- assert.match(panel, /chrome\.windows\.onRemoved\.addListener\(async \(removedWindowId\) => \{[\s\S]*?Object\.values\(states\)\.find\(candidate => candidate\?\.windowId === removedWindowId\);[\s\S]*?requestVisibleSidePanelStateRefresh\(\);/, 'chrome: closing a /btw window must use the coordinated visible-state refresh');- assert.doesNotMatch(panel, /chrome\.storage\.session\.remove\(BTW_WINDOW_KEY\)/, 'chrome: closing a /btw window must not race other panels by deleting shared state');- assert.match(panel, /async function openBtwWindow\(tabId, prompt = ''\) \{[\s\S]*?const existing = await getBtwWindowState\(tabId\);[\s\S]*?pendingPrompt: prompt[\s\S]*?chrome\.tabs\.sendMessage\(target\.id, \{ action: 'btw_prompt', prompt \}\)\.catch\(\(\) => \{\}\);/, 'chrome: /btw should retain a prompt until its same-tab window receives it');+ assert.match(panel, /const btwSourceTabId = isBtwWindow \? \(Number\(_btwParams\.get\('forkFromTabId'\)\) \|\| null\) : null;/, 'chrome: /btw should retain its source only as fork metadata');+ assert.match(panel, /if \(isBtwWindow && btwSourceTabId != null && initialTabId != null\) \{[\s\S]*?sendToBackground\('fork_standalone_conversation', \{[\s\S]*?sourceTabId: btwSourceTabId,[\s\S]*?forkTabId: initialTabId,/, 'chrome: /btw must use its popup tab as an independent fork scope');+ assert.match(panel, /async function openBtwWindow\(tabId, prompt = ''\) \{[\s\S]*?const existing = await getBtwWindowState\(tabId\);[\s\S]*?forkFromTabId=\$\{tabId\}/, 'chrome: /btw should only reuse a popup for the same source tab');+ assert.match(panel, /async function openBtwWindow\(tabId, prompt = ''\) \{[\s\S]*?pendingPrompt: prompt[\s\S]*?chrome\.tabs\.sendMessage\(target\.id, \{ action: 'btw_prompt', prompt \}\)\.catch\(\(\) => \{\}\);/, 'chrome: /btw should retain a prompt until its same-tab window receives it');assert.match(panel, /async function consumePendingBtwPrompt\(\) \{[\s\S]*?pendingPrompt: ''[\s\S]*?await sendBtwPrompt\(prompt\);/, 'chrome: a /btw window should consume retained forwarded prompts');+ const chromeBackground = fs.readFileSync(path.join(ROOT, 'src/chrome/src/background.js'), 'utf8');+ const chromeAgent = fs.readFileSync(path.join(ROOT, 'src/chrome/src/agent/agent.js'), 'utf8');+ assert.match(chromeBackground, /case 'fork_standalone_conversation':[\s\S]*?agent\.forkConversation\(sourceTabId, forkTabId\);[\s\S]*?tabChatHandoff\.save\(forkTabId, sourceChat\.html\)/, 'chrome: /btw fork bootstrap must copy history and transcript into the popup scope');+ assert.match(chromeAgent, /async forkConversation\(sourceTabId, forkTabId\) \{[\s\S]*?this\.conversationModes\.set\(forkId, 'ask'\);[\s\S]*?this\.conversationIds\.set\(forkId, `conv_\$\{forkId\}_\$\{Date\.now\(\)\}_\$\{secureRandomBase36Token\(12\)\}`\);/, 'chrome: /btw forks must mint a distinct Ask-only conversation identity');assert.match(panel, /const payload = \{[\s\S]*?handoffOwnerId: tabChatHandoffOwnerId,[\s\S]*?handoffGeneration[\s\S]*?return enqueueTabChatOperation\(tabId, async \(numericTabId\) => \{[\s\S]*?sendToBackground\('persist_tab_chat', payload\);/, 'chrome: visible tab-chat persistence should carry its owner generation through the shared background queue');assert.match(panel, /document\.visibilityState === 'hidden' && allowHidden[\s\S]*?sendToBackground\('persist_tab_chat', payload\);/, 'chrome: hidden handoff must bypass the document-local queue and enter the shared queue immediately');const clearStart = panel.indexOf('function clearCachedTabChat(tabId) {');@@ -47824,11 +47828,15 @@ test('firefox sidepanel serializes tab-chat storage writes with clears and readsassert.match(loadBody, /return await enqueueTabChatOperation\(numericTabId, async \(queuedTabId\) => \{[\s\S]*?sendToBackground\('load_tab_chat', \{[\s\S]*?waitForHandoff,[\s\S]*?\}\);/, 'firefox: tab-chat restore should read through the shared background queue');assert.match(loadBody, /catch \(e\) \{\s*if \(waitForHandoff\) return TAB_CHAT_LOAD_FAILED;\s*\}[\s\S]*?return null;/, 'firefox: coordinated load failures should remain distinct from successful empty restores');assert.match(panel, /const html = await loadTabChat\(tabId, \{ waitForHandoff: true \}\);\s*if \(html === TAB_CHAT_LOAD_FAILED\) return false;[\s\S]*?messagesEl\.innerHTML = '';/, 'firefox: a failed visibility handoff must preserve the current transcript DOM');- assert.match(panel, /const BTW_WINDOWS_KEY = 'btwWindows';[\s\S]*?async function getBtwWindowState\(tabId\)/, 'firefox: /btw windows should be tracked per tab');- assert.match(panel, /browser\.windows\.onRemoved\.addListener\(async \(removedWindowId\) => \{[\s\S]*?Object\.values\(states\)\.find\(candidate => candidate\?\.windowId === removedWindowId\);[\s\S]*?requestVisibleSidePanelStateRefresh\(\);/, 'firefox: closing a /btw window must use the coordinated visible-state refresh');- assert.doesNotMatch(panel, /browser\.storage\.session\.remove\(BTW_WINDOW_KEY\)/, 'firefox: closing a /btw window must not race other panels by deleting shared state');- assert.match(panel, /async function openBtwWindow\(tabId, prompt = ''\) \{[\s\S]*?const existing = await getBtwWindowState\(tabId\);[\s\S]*?pendingPrompt: prompt[\s\S]*?browser\.tabs\.sendMessage\(target\.id, \{ action: 'btw_prompt', prompt \}\)\.catch\(\(\) => \{\}\);/, 'firefox: /btw should retain a prompt until its same-tab window receives it');+ assert.match(panel, /const btwSourceTabId = isBtwWindow \? \(Number\(_btwParams\.get\('forkFromTabId'\)\) \|\| null\) : null;/, 'firefox: /btw should retain its source only as fork metadata');+ assert.match(panel, /if \(isBtwWindow && btwSourceTabId != null && initialTabId != null\) \{[\s\S]*?sendToBackground\('fork_standalone_conversation', \{[\s\S]*?sourceTabId: btwSourceTabId,[\s\S]*?forkTabId: initialTabId,/, 'firefox: /btw must use its popup tab as an independent fork scope');+ assert.match(panel, /async function openBtwWindow\(tabId, prompt = ''\) \{[\s\S]*?const existing = await getBtwWindowState\(tabId\);[\s\S]*?forkFromTabId=\$\{tabId\}/, 'firefox: /btw should only reuse a popup for the same source tab');+ assert.match(panel, /async function openBtwWindow\(tabId, prompt = ''\) \{[\s\S]*?pendingPrompt: prompt[\s\S]*?browser\.tabs\.sendMessage\(target\.id, \{ action: 'btw_prompt', prompt \}\)\.catch\(\(\) => \{\}\);/, 'firefox: /btw should retain a prompt until its same-tab window receives it');assert.match(panel, /async function consumePendingBtwPrompt\(\) \{[\s\S]*?pendingPrompt: ''[\s\S]*?await sendBtwPrompt\(prompt\);/, 'firefox: a /btw window should consume retained forwarded prompts');+ const firefoxBackground = fs.readFileSync(path.join(ROOT, 'src/firefox/src/background.js'), 'utf8');+ const firefoxAgent = fs.readFileSync(path.join(ROOT, 'src/firefox/src/agent/agent.js'), 'utf8');+ assert.match(firefoxBackground, /case 'fork_standalone_conversation':[\s\S]*?agent\.forkConversation\(sourceTabId, forkTabId\);[\s\S]*?tabChatHandoff\.save\(forkTabId, sourceChat\.html\)/, 'firefox: /btw fork bootstrap must copy history and transcript into the popup scope');+ assert.match(firefoxAgent, /async forkConversation\(sourceTabId, forkTabId\) \{[\s\S]*?this\.conversationModes\.set\(forkId, 'ask'\);[\s\S]*?this\.conversationIds\.set\(forkId, `conv_\$\{forkId\}_\$\{Date\.now\(\)\}_\$\{secureRandomBase36Token\(12\)\}`\);/, 'firefox: /btw forks must mint a distinct Ask-only conversation identity');assert.match(panel, /const payload = \{[\s\S]*?handoffOwnerId: tabChatHandoffOwnerId,[\s\S]*?handoffGeneration[\s\S]*?return enqueueTabChatOperation\(tabId, async \(numericTabId\) => \{[\s\S]*?sendToBackground\('persist_tab_chat', payload\);/, 'firefox: visible tab-chat persistence should carry its owner generation through the shared background queue');assert.match(panel, /document\.visibilityState === 'hidden' && allowHidden[\s\S]*?sendToBackground\('persist_tab_chat', payload\);/, 'firefox: hidden handoff must bypass the document-local queue and enter the shared queue immediately');const clearStart = panel.indexOf('function clearCachedTabChat(tabId) {');