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 /btw window coordination
Codex release-state test9655edbe560a
diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.jsindex 765fcaf4c..8bd5d9ae5 100644--- a/src/chrome/src/ui/sidepanel.js+++ b/src/chrome/src/ui/sidepanel.js@@ -4787,41 +4787,19 @@ async function init() {});if (isBtwWindow) {- // Clean up the btw window tracking when this window is closed- chrome.windows.onRemoved.addListener(async (removedWindowId) => {- const state = await getBtwWindowState();- if (state?.windowId === removedWindowId) {- await chrome.storage.session.remove(BTW_WINDOW_KEY).catch(() => {});- }- });-- // Auto-send the initial prompt if provided+ // Auto-send the initial prompt if provided.if (btwInitialPrompt) {await new Promise(r => setTimeout(r, 300));- inputEl.value = btwInitialPrompt;- inputEl.dispatchEvent(new Event('input', { bubbles: true }));- await sendMessage();+ await sendBtwPrompt(btwInitialPrompt);}+ await consumePendingBtwPrompt();} else {- // When the btw window closes, reload the main panel chat to sync display+ // 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 state = await getBtwWindowState();- if (state?.windowId === removedWindowId) {- await chrome.storage.session.remove(BTW_WINDOW_KEY).catch(() => {});- // Reload the tab chat to pick up any messages the btw window added- const tabId = state?.tabId;- if (tabId != null && tabId === currentTabId) {- try {- const html = await loadTabChat(tabId, { waitForHandoff: true });- if (html && html !== TAB_CHAT_LOAD_FAILED) {- messagesEl.innerHTML = html;- rebindRestoredMessageControls();- refreshRenderedStepLabels();- restoreLatestChatTurnPosition();- }- } catch {}- }- }+ const states = await getBtwWindowStates();+ const state = Object.values(states).find(candidate => candidate?.windowId === removedWindowId);+ if (state && sameTabId(state.tabId, currentTabId)) requestVisibleSidePanelStateRefresh();});}}@@ -14676,27 +14654,52 @@ function btwWindowBounds(display = window.screen) {};}-const BTW_WINDOW_KEY = 'btwWindow';+const BTW_WINDOWS_KEY = 'btwWindows';-async function getBtwWindowState() {+async function getBtwWindowStates() {try {- const stored = await chrome.storage.session.get(BTW_WINDOW_KEY);- return stored[BTW_WINDOW_KEY] || null;+ const stored = await chrome.storage.session.get(BTW_WINDOWS_KEY);+ return stored[BTW_WINDOWS_KEY] || {};} catch {- return null;+ return {};}}+async function getBtwWindowState(tabId) {+ const numericTabId = Number(tabId);+ if (!Number.isFinite(numericTabId)) return null;+ const states = await getBtwWindowStates();+ return states[numericTabId] || null;+}++async function setBtwWindowState(tabId, state) {+ const numericTabId = Number(tabId);+ if (!Number.isFinite(numericTabId)) return;+ const states = await getBtwWindowStates();+ states[numericTabId] = state;+ await chrome.storage.session.set({ [BTW_WINDOWS_KEY]: states }).catch(() => {});+}++async function clearBtwWindowState(tabId, windowId) {+ const numericTabId = Number(tabId);+ if (!Number.isFinite(numericTabId)) return;+ const states = await getBtwWindowStates();+ if (windowId != null && states[numericTabId]?.windowId !== windowId) return;+ delete states[numericTabId];+ await chrome.storage.session.set({ [BTW_WINDOWS_KEY]: states }).catch(() => {});+}+async function openBtwWindow(tabId, prompt = '') {if (tabId == null) return;- const existing = await getBtwWindowState();+ const existing = await getBtwWindowState(tabId);if (existing?.windowId != null) {try {- const win = await chrome.windows.get(existing.windowId);+ const win = await chrome.windows.get(existing.windowId, { populate: true });if (win) {await chrome.windows.update(existing.windowId, { focused: true });- if (prompt && Number(existing.tabId) === Number(tabId)) {+ if (prompt) {+ await setBtwWindowState(tabId, { ...existing, pendingPrompt: prompt });const target = win.tabs?.[0];if (target?.id != null) {await chrome.tabs.sendMessage(target.id, { action: 'btw_prompt', prompt }).catch(() => {});@@ -14705,7 +14708,7 @@ async function openBtwWindow(tabId, prompt = '') {return;}} catch {- await chrome.storage.session.remove(BTW_WINDOW_KEY).catch(() => {});+ await clearBtwWindowState(tabId, existing.windowId);}}@@ -14717,16 +14720,28 @@ async function openBtwWindow(tabId, prompt = '') {...btwWindowBounds(),});- await chrome.storage.session.set({ [BTW_WINDOW_KEY]: { windowId: win.id, tabId } }).catch(() => {});+ await setBtwWindowState(tabId, { windowId: win.id, tabId });}-chrome.runtime.onMessage.addListener((msg) => {- if (!isBtwWindow || msg?.action !== 'btw_prompt') return;- const prompt = String(msg?.prompt || '');+async function sendBtwPrompt(prompt) {if (!prompt || !inputEl) return;inputEl.value = prompt;inputEl.dispatchEvent(new Event('input', { bubbles: true }));- void sendMessage().catch(() => {});+ await sendMessage();+}++async function consumePendingBtwPrompt() {+ if (!isBtwWindow || btwPinnedTabId == null) return;+ const state = await getBtwWindowState(btwPinnedTabId);+ const prompt = String(state?.pendingPrompt || '');+ if (!prompt) return;+ await setBtwWindowState(btwPinnedTabId, { ...state, pendingPrompt: '' });+ await sendBtwPrompt(prompt);+}++chrome.runtime.onMessage.addListener((msg) => {+ if (!isBtwWindow || msg?.action !== 'btw_prompt') return;+ void consumePendingBtwPrompt().catch(() => {});});if (expandBtn) {diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.jsindex ab80a9b6f..fbdff8b7e 100644--- a/src/firefox/src/ui/sidepanel.js+++ b/src/firefox/src/ui/sidepanel.js@@ -4642,41 +4642,19 @@ async function init() {});if (isBtwWindow) {- // Clean up the btw window tracking when this window is closed- browser.windows.onRemoved.addListener(async (removedWindowId) => {- const state = await getBtwWindowState();- if (state?.windowId === removedWindowId) {- await browser.storage.session.remove(BTW_WINDOW_KEY).catch(() => {});- }- });-- // Auto-send the initial prompt if provided+ // Auto-send the initial prompt if provided.if (btwInitialPrompt) {await new Promise(r => setTimeout(r, 300));- inputEl.value = btwInitialPrompt;- inputEl.dispatchEvent(new Event('input', { bubbles: true }));- await sendMessage();+ await sendBtwPrompt(btwInitialPrompt);}+ await consumePendingBtwPrompt();} else {- // When the btw window closes, reload the main panel chat to sync display+ // 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 state = await getBtwWindowState();- if (state?.windowId === removedWindowId) {- await browser.storage.session.remove(BTW_WINDOW_KEY).catch(() => {});- // Reload the tab chat to pick up any messages the btw window added- const tabId = state?.tabId;- if (tabId != null && tabId === currentTabId) {- try {- const html = await loadTabChat(tabId, { waitForHandoff: true });- if (html && html !== TAB_CHAT_LOAD_FAILED) {- messagesEl.innerHTML = html;- rebindRestoredMessageControls();- refreshRenderedStepLabels();- restoreLatestChatTurnPosition();- }- } catch {}- }- }+ const states = await getBtwWindowStates();+ const state = Object.values(states).find(candidate => candidate?.windowId === removedWindowId);+ if (state && sameTabId(state.tabId, currentTabId)) requestVisibleSidePanelStateRefresh();});}}@@ -14175,26 +14153,51 @@ function btwWindowBounds(display = window.screen) {};}-const BTW_WINDOW_KEY = 'btwWindow';+const BTW_WINDOWS_KEY = 'btwWindows';-async function getBtwWindowState() {+async function getBtwWindowStates() {try {- const result = await browser.storage.session.get(BTW_WINDOW_KEY);- return result[BTW_WINDOW_KEY] || null;+ const result = await browser.storage.session.get(BTW_WINDOWS_KEY);+ return result[BTW_WINDOWS_KEY] || {};} catch {- return null;+ return {};}}+async function getBtwWindowState(tabId) {+ const numericTabId = Number(tabId);+ if (!Number.isFinite(numericTabId)) return null;+ const states = await getBtwWindowStates();+ return states[numericTabId] || null;+}++async function setBtwWindowState(tabId, state) {+ const numericTabId = Number(tabId);+ if (!Number.isFinite(numericTabId)) return;+ const states = await getBtwWindowStates();+ states[numericTabId] = state;+ await browser.storage.session.set({ [BTW_WINDOWS_KEY]: states }).catch(() => {});+}++async function clearBtwWindowState(tabId, windowId) {+ const numericTabId = Number(tabId);+ if (!Number.isFinite(numericTabId)) return;+ const states = await getBtwWindowStates();+ if (windowId != null && states[numericTabId]?.windowId !== windowId) return;+ delete states[numericTabId];+ await browser.storage.session.set({ [BTW_WINDOWS_KEY]: states }).catch(() => {});+}+async function openBtwWindow(tabId, prompt = '') {if (tabId == null) return;- const existing = await getBtwWindowState();+ const existing = await getBtwWindowState(tabId);if (existing?.windowId != null) {try {- const win = await browser.windows.get(existing.windowId);+ const win = await browser.windows.get(existing.windowId, { populate: true });if (win) {await browser.windows.update(win.id, { focused: true });- if (prompt && Number(existing.tabId) === Number(tabId)) {+ if (prompt) {+ await setBtwWindowState(tabId, { ...existing, pendingPrompt: prompt });const target = win.tabs?.[0];if (target?.id != null) {await browser.tabs.sendMessage(target.id, { action: 'btw_prompt', prompt }).catch(() => {});@@ -14203,7 +14206,7 @@ async function openBtwWindow(tabId, prompt = '') {return;}} catch {}- await browser.storage.session.remove(BTW_WINDOW_KEY).catch(() => {});+ 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}`);@@ -14212,16 +14215,28 @@ async function openBtwWindow(tabId, prompt = '') {type: 'popup',...btwWindowBounds(),});- await browser.storage.session.set({ [BTW_WINDOW_KEY]: { windowId: win.id, tabId } });+ await setBtwWindowState(tabId, { windowId: win.id, tabId });}-browser.runtime.onMessage.addListener((msg) => {- if (!isBtwWindow || msg?.action !== 'btw_prompt') return;- const prompt = String(msg?.prompt || '');+async function sendBtwPrompt(prompt) {if (!prompt || !inputEl) return;inputEl.value = prompt;inputEl.dispatchEvent(new Event('input', { bubbles: true }));- void sendMessage().catch(() => {});+ await sendMessage();+}++async function consumePendingBtwPrompt() {+ if (!isBtwWindow || btwPinnedTabId == null) return;+ const state = await getBtwWindowState(btwPinnedTabId);+ const prompt = String(state?.pendingPrompt || '');+ if (!prompt) return;+ await setBtwWindowState(btwPinnedTabId, { ...state, pendingPrompt: '' });+ await sendBtwPrompt(prompt);+}++browser.runtime.onMessage.addListener((msg) => {+ if (!isBtwWindow || msg?.action !== 'btw_prompt') return;+ void consumePendingBtwPrompt().catch(() => {});});if (expandBtn) {diff --git a/test/run.js b/test/run.jsindex 73354a633..79436dfd5 100644--- a/test/run.js+++ b/test/run.js@@ -47793,9 +47793,11 @@ 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, /When the btw window closes[\s\S]*?loadTabChat\(tabId, \{ waitForHandoff: true \}\);/, 'chrome: closing a /btw window must reclaim the tab-chat handoff before reloading the main panel');- assert.match(panel, /async function openBtwWindow\(tabId, prompt = ''\) \{[\s\S]*?chrome\.tabs\.sendMessage\(target\.id, \{ action: 'btw_prompt', prompt \}\)\.catch\(\(\) => \{\}\);/, 'chrome: /btw should forward a prompt to an existing /btw window for the same tab');- assert.match(panel, /chrome\.runtime\.onMessage\.addListener\(\(msg\) => \{\s*if \(!isBtwWindow \|\| msg\?\.action !== 'btw_prompt'\) return;/, 'chrome: a /btw window should auto-send forwarded prompts');+ 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, /async function consumePendingBtwPrompt\(\) \{[\s\S]*?pendingPrompt: ''[\s\S]*?await sendBtwPrompt\(prompt\);/, 'chrome: a /btw window should consume retained forwarded prompts');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) {');@@ -47822,9 +47824,11 @@ 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, /When the btw window closes[\s\S]*?loadTabChat\(tabId, \{ waitForHandoff: true \}\);/, 'firefox: closing a /btw window must reclaim the tab-chat handoff before reloading the main panel');- assert.match(panel, /async function openBtwWindow\(tabId, prompt = ''\) \{[\s\S]*?browser\.tabs\.sendMessage\(target\.id, \{ action: 'btw_prompt', prompt \}\)\.catch\(\(\) => \{\}\);/, 'firefox: /btw should forward a prompt to an existing /btw window for the same tab');- assert.match(panel, /browser\.runtime\.onMessage\.addListener\(\(msg\) => \{\s*if \(!isBtwWindow \|\| msg\?\.action !== 'btw_prompt'\) return;/, 'firefox: a /btw window should auto-send forwarded prompts');+ 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, /async function consumePendingBtwPrompt\(\) \{[\s\S]*?pendingPrompt: ''[\s\S]*?await sendBtwPrompt\(prompt\);/, 'firefox: a /btw window should consume retained forwarded prompts');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) {');