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
Keep the PDF viewer's window current when its tab moves
Claude36426d637b0e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 58dd8c883..ed2c6c85a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,7 +10,7 @@ This changelog was generated from the repository Git history and release tags. V- Selecting text on a page now shows a small bar, **Translate | Explain | Proofread | More…**, instead of the single `?` button. Translate, Explain and Proofread answer in a card next to the selection: Translate shows the detected source language, the original text and a target-language picker, and every card has an "Ask a follow-up" box that, once the answer is there, continues in the side panel with the card's answer as context. **More…** opens the same popup the `?` button opened (Summarize, Quiz me, Humanize, a question box and Hide this; Translate, Explain and Proofread are on the bar, so they are not repeated there). A card sends the selected text to your configured model provider, like any other selection action; selections over 4,000 characters go to the side panel instead of a card. A card answer that reaches the model's output limit says it was cut off and offers to continue in the side panel, which picks up from the unfinished text instead of starting over (a side-panel reply that is cut off again says so, including when an OpenAI Responses model reports the limit as an error, in which case the text it wrote is kept and the call still counts toward your cloud-cost allowance), and closing or redoing a card, or reloading or leaving the page, cancels the request it no longer needs. Chrome and Firefox.### Fixed-- Chrome: sending a follow-up or a selection action to WebBrain while the side panel is already open no longer closes it. Each side panel now tells the background whether it is on screen, and the background skips re-opening a panel that is already showing and hands it the prompt directly A panel that was open while the background restarted tells the new worker about itself at once instead of after a delay, so a request in that moment does not close it. The same holds for actions chosen on a selection in WebBrain's PDF viewer, where a panel that was closed is opened once rather than twice. A side panel that the browser moves to another window (its tab dragged out) now reports its new window, so an action in that window no longer closes it and an action in the old window opens a panel again.+- Chrome: sending a follow-up or a selection action to WebBrain while the side panel is already open no longer closes it. Each side panel now tells the background whether it is on screen, and the background skips re-opening a panel that is already showing and hands it the prompt directly A panel that was open while the background restarted tells the new worker about itself at once instead of after a delay, so a request in that moment does not close it. The same holds for actions chosen on a selection in WebBrain's PDF viewer, where a panel that was closed is opened once rather than twice. A side panel that the browser moves to another window (its tab dragged out) now reports its new window, so an action in that window no longer closes it and an action in the old window opens a panel again. The PDF viewer keeps its own window up to date the same way, so a viewer tab dragged to another window reports where it is now.- Stopping a task while WebBrain was waiting for page navigation to settle now stops it immediately. The pending settle step previously kept waiting and could let the run continue after you chose Stop.- Mastodon: replying to toots in a narrow window no longer posts the same reply several times and stops before the next toot. There, a toot's Reply button opens the composer at /publish, and after posting Mastodon goes back to the previous column by itself. WebBrain took both page changes for something you did, so it reported each click's outcome as unknown; the agent then concluded its reply had not been posted, wrote it again, and never reached the next toot. In Chrome, a page's own Back is now told apart from your browser's Back button: the page a click opens counts as that click's verified effect, and a click after which the page goes back by itself counts as delivered, to be checked on the page. The Mastodon notes now cover replies (start with the prefilled @mentions once, check the reply under the toot before any retry) and stay active on Favourites, Bookmarks and the other columns. Firefox still treats a page's own Back as yours until its Back button reporting is verified.- Finishing a form you asked WebBrain not to submit no longer takes most of a minute. The completion check removed every line that mentioned a password, so "fill out this form with a random password … don't submit" reached its judge as "[credential omitted]", and so did the approved plan and the agent's summary. Seeing only an unsubmitted signup form, the judge answered "pending" again and again; in the trace it took four attempts and about 50 seconds, ending only when a slow screenshot check ran out of time. The active model's check, which already holds these texts in the conversation, now receives every line of them, with only addresses shortened and bearer tokens and entered passwords hidden, as in all judge evidence. A decision model on this device, or WebBrain Cloud's own while WebBrain Cloud is also your provider, receives that same copy; any other decision model keeps whole-line redaction, and when that leaves it without the task, it is no longer asked while the active model can judge. A password WebBrain typed into a password field during the run is now hidden in the text judges receive, such as the agent's summary or a field a "show password" control revealed, unless the typing tool could not tell what kind of field it was; other entered values stay visible, so a judge can still catch a mistyped one. The judges are told that a task asking not to submit is complete once the staged values match, that a hidden value neither proves nor disproves an entry, and, for each recorded entry, whether its field read back what was entered, whether it is a credential field and which field it targeted; a credential field's line in the page evidence keeps its role and reference. Staged field edits are judged from the accessibility tree first: a screenshot shows passwords only as dots, and the focused field's blinking caret made each one stale before its verdict returned.diff --git a/docs/architecture.md b/docs/architecture.mdindex caa505312..96c15a2ed 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -562,6 +562,9 @@ action arriving while it is still opening does not open it a second time.A panel the browser carries to another window (the tab dragged out) keeps its document; the window scopenotices on its next live `windows.getCurrent()` lookup and the reporter (`setWindowId()`) names the newwindow, so the background does not treat the old window as occupied and the new one as empty.+The PDF viewer does the same for the window id it sends with a selection: `pdf-viewer-window.js`+re-reads `windows.getCurrent()` when its tab is attached, when the window gains focus and at the start+of every pointer gesture, and the selection script reads those fields when it sends, not once at load.A selection made in the bundled PDF viewer, whose message carries only a tab id, brings thewindow too (Chrome's `sender.tab` for that tab, else the window the viewer reported from`windows.getCurrent()`), so the same check applies there; that path opens the panel once in thediff --git a/src/chrome/src/content/selection-shortcut.js b/src/chrome/src/content/selection-shortcut.jsindex 6e4f60a87..14e5f2a15 100644--- a/src/chrome/src/content/selection-shortcut.js+++ b/src/chrome/src/content/selection-shortcut.js@@ -24,7 +24,9 @@&& shortcutConfig.submitMessage.trim()? shortcutConfig.submitMessage.trim(): 'WB_SELECTION_SHORTCUT_SUBMIT';- const SUBMIT_FIELDS = shortcutConfig?.submitFields+ // Read when a request is sent, not once at load: the PDF viewer keeps its window id+ // current while its tab moves between windows.+ const currentSubmitFields = () => shortcutConfig?.submitFields&& typeof shortcutConfig.submitFields === 'object'&& !Array.isArray(shortcutConfig.submitFields)? { ...shortcutConfig.submitFields }@@ -1146,7 +1148,7 @@if (action === 'custom' && !String(customQuestion || '').trim()) return;if (action === 'translate' && !isSupportedTranslationLanguage(language)) return;const request = {- ...SUBMIT_FIELDS,+ ...currentSubmitFields(),type: SUBMIT_MESSAGE,action,selectionText: snapshot.text,diff --git a/src/chrome/src/ui/pdf-handler.js b/src/chrome/src/ui/pdf-handler.jsindex 73657e89b..28649c637 100644--- a/src/chrome/src/ui/pdf-handler.js+++ b/src/chrome/src/ui/pdf-handler.js@@ -1,5 +1,6 @@import { normalizePdfOcrResult, renderPdfOcrTextLayer } from '../agent/pdf-ocr.js';import { readPdfResponseBytes } from '../agent/pdf-stream.js';+import { trackViewerWindow } from './pdf-viewer-window.js';const api = globalThis.browser || globalThis.chrome;const elements = Object.fromEntries([@@ -696,15 +697,15 @@ async function initialize() {elements['pdf-title'].textContent = String(streamInfo.originalUrl || 'WebBrain PDF');// The window this viewer is in. The background needs it before its first await to// tell whether WebBrain's side panel is already showing there (re-opening it closes it).- let windowId = null;- try { windowId = (await api.windows?.getCurrent?.())?.id ?? null; } catch { /* optional */ }+ // The tab can be dragged into another window later, so it is kept up to date.+ const submitFields = {+ tabId: streamInfo.tabId,+ originalUrl: String(streamInfo.originalUrl || ''),+ };+ await trackViewerWindow({ api, target: window, fields: submitFields }).refresh();globalThis.__webbrainSelectionShortcutConfig = {submitMessage: 'WB_PDF_SELECTION_SHORTCUT_SUBMIT',- submitFields: {- tabId: streamInfo.tabId,- originalUrl: String(streamInfo.originalUrl || ''),- ...(Number.isInteger(windowId) ? { windowId } : {}),- },+ submitFields,allowNestedFrame: true,};await import(api.runtime.getURL('src/content/selection-shortcut.js'));diff --git a/src/chrome/src/ui/pdf-viewer-window.js b/src/chrome/src/ui/pdf-viewer-window.jsnew file mode 100644index 000000000..bb976d46e--- /dev/null+++ b/src/chrome/src/ui/pdf-viewer-window.js@@ -0,0 +1,26 @@+/**+ * Keeps the window id the PDF viewer reports with a selection current.+ *+ * The background uses it to tell whether WebBrain's side panel is already showing in+ * the viewer's window (re-opening an open panel closes it). A viewer tab can be+ * dragged into another window after it started, so the id is read again whenever the+ * tab is attached somewhere, the window gains focus, and at the start of each pointer+ * gesture, which is always ahead of the selection it would be sent with.+ */+export function trackViewerWindow({ api, target, fields }) {+ let latest = 0;++ async function refresh() {+ const request = ++latest;+ try {+ const id = (await api.windows?.getCurrent?.())?.id;+ // A slower, older lookup must not overwrite a newer answer.+ if (request === latest && Number.isInteger(id)) fields.windowId = id;+ } catch { /* keep the last id we confirmed */ }+ }++ api.tabs?.onAttached?.addListener?.(refresh);+ target.addEventListener('focus', refresh);+ target.addEventListener('pointerdown', refresh, true);+ return { refresh };+}diff --git a/src/firefox/src/content/selection-shortcut.js b/src/firefox/src/content/selection-shortcut.jsindex 6e4f60a87..14e5f2a15 100644--- a/src/firefox/src/content/selection-shortcut.js+++ b/src/firefox/src/content/selection-shortcut.js@@ -24,7 +24,9 @@&& shortcutConfig.submitMessage.trim()? shortcutConfig.submitMessage.trim(): 'WB_SELECTION_SHORTCUT_SUBMIT';- const SUBMIT_FIELDS = shortcutConfig?.submitFields+ // Read when a request is sent, not once at load: the PDF viewer keeps its window id+ // current while its tab moves between windows.+ const currentSubmitFields = () => shortcutConfig?.submitFields&& typeof shortcutConfig.submitFields === 'object'&& !Array.isArray(shortcutConfig.submitFields)? { ...shortcutConfig.submitFields }@@ -1146,7 +1148,7 @@if (action === 'custom' && !String(customQuestion || '').trim()) return;if (action === 'translate' && !isSupportedTranslationLanguage(language)) return;const request = {- ...SUBMIT_FIELDS,+ ...currentSubmitFields(),type: SUBMIT_MESSAGE,action,selectionText: snapshot.text,diff --git a/test/pdf-selection.mjs b/test/pdf-selection.mjsindex 02b932830..92ca11634 100644--- a/test/pdf-selection.mjs+++ b/test/pdf-selection.mjs@@ -333,13 +333,16 @@ async function testPdfSelectionCarriesItsTabScope() {document.dispatchEvent(new PointerEvent('pointerup', { bubbles: true }));});await page.waitForFunction(() => window.__webbrainSelectionShortcut.getState().shortcutVisible);+ // The viewer's tab is dragged into another window after the page loaded; the viewer+ // keeps its fields current, and the selection must carry the window it is in now.+ await page.evaluate(() => { window.__webbrainSelectionShortcutConfig.submitFields.windowId = 8; });await page.evaluate(() => window.__webbrainSelectionShortcut.submitPreset('summarize'));await page.waitForFunction(() => window.__selectionMessages.length === 1);const message = await page.evaluate(() => window.__selectionMessages[0]);assert.equal(message.type, 'WB_PDF_SELECTION_SHORTCUT_SUBMIT');assert.equal(message.tabId, 73);assert.equal(message.originalUrl, 'https://papers.example.test/reading.pdf');- assert.equal(message.windowId, 5, 'the viewer\'s window travels with the selection');+ assert.equal(message.windowId, 8, 'the window the viewer is in when the selection is sent travels with it');assert.equal(message.action, 'summarize');assert.match(message.selectionText, /Selectable text rendered by the PDF text layer/);} finally {diff --git a/test/run.js b/test/run.jsindex a05c0d298..828944218 100644--- a/test/run.js+++ b/test/run.js@@ -52993,9 +52993,83 @@ test('a PDF viewer selection leaves a side panel that is already showing in itsassert.equal(JSON.stringify(queued[0].options), '{"panelOpened":true}', 'and told the panel was already opened');assert.equal(queued[0].tab.id, 7);const viewer = fs.readFileSync(path.join(ROOT, 'src/chrome/src/ui/pdf-handler.js'), 'utf8');- assert.match(viewer, /windowId = \(await api\.windows\?\.getCurrent\?\.\(\)\)\?\.id \?\? null;[\s\S]*?submitFields: \{[\s\S]*?\.\.\.\(Number\.isInteger\(windowId\) \? \{ windowId \} : \{\}\),/,- 'the PDF viewer must report the window it is in');- }+ assert.match(viewer, /const submitFields = \{\s*tabId: streamInfo\.tabId,\s*originalUrl: String\(streamInfo\.originalUrl \|\| ''\),\s*\};\s*await trackViewerWindow\(\{ api, target: window, fields: submitFields \}\)\.refresh\(\);[\s\S]*?submitFields,\s*allowNestedFrame: true,/,+ 'the PDF viewer must report the window it is in, and keep that current');+ const shortcut = fs.readFileSync(path.join(ROOT, 'src/chrome/src/content/selection-shortcut.js'), 'utf8');+ assert.match(shortcut, /const currentSubmitFields = \(\) => shortcutConfig\?\.submitFields[\s\S]*?\? \{ \.\.\.shortcutConfig\.submitFields \}/,+ 'the selection script must read the viewer\'s fields when it sends, not once at load');+ assert.match(shortcut, /const request = \{\s*\.\.\.currentSubmitFields\(\),\s*type: SUBMIT_MESSAGE,/);+ assert.equal(fs.readFileSync(path.join(ROOT, 'src/firefox/src/content/selection-shortcut.js'), 'utf8'), shortcut,+ 'the selection script stays identical in both builds');+ }+});++test('the PDF viewer follows its tab into another window before a selection is sent', async () => {+ const { trackViewerWindow } = await import(pathToFileURL(path.join(ROOT, 'src/chrome/src/ui/pdf-viewer-window.js')).href);+ let liveWindowId = 5;+ const lookups = [];+ const gates = [];+ const attachListeners = [];+ const domListeners = [];+ const api = {+ windows: {+ getCurrent: () => {+ lookups.push(liveWindowId);+ const answer = liveWindowId;+ const gate = gates.shift();+ return gate ? gate.then(() => ({ id: answer })) : Promise.resolve({ id: answer });+ },+ },+ tabs: { onAttached: { addListener: callback => attachListeners.push(callback) } },+ };+ const target = { addEventListener: (type, callback, capture) => domListeners.push({ type, callback, capture }) };+ const fields = { tabId: 73 };+ const tracker = trackViewerWindow({ api, target, fields });+ await tracker.refresh();+ assert.equal(fields.windowId, 5, 'the window the viewer starts in');++ // A tab dragged into another window is found when it is attached.+ liveWindowId = 9;+ attachListeners[0](73, { newWindowId: 9 });+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(fields.windowId, 9, 'attaching the tab to another window updates the id');++ // Window focus and the start of a pointer gesture refresh it too.+ liveWindowId = 12;+ domListeners.find(item => item.type === 'focus').callback();+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(fields.windowId, 12, 'gaining focus updates the id');+ liveWindowId = 15;+ const pointer = domListeners.find(item => item.type === 'pointerdown');+ assert.equal(pointer.capture, true, 'the pointer refresh runs before anything on the page can stop the event');+ pointer.callback();+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(fields.windowId, 15, 'the start of a selection gesture updates the id');++ // A slow, older answer must not overwrite a newer one.+ let releaseOld;+ gates.push(new Promise(resolve => { releaseOld = resolve; }));+ liveWindowId = 20;+ const older = tracker.refresh();+ liveWindowId = 21;+ await tracker.refresh();+ assert.equal(fields.windowId, 21);+ releaseOld();+ await older;+ assert.equal(fields.windowId, 21, 'an older lookup that finishes late is ignored');++ // A failed or unusable lookup keeps the last confirmed id.+ api.windows.getCurrent = async () => { throw new Error('windows unavailable'); };+ await tracker.refresh();+ assert.equal(fields.windowId, 21);+ api.windows.getCurrent = async () => ({ id: null });+ await tracker.refresh();+ assert.equal(fields.windowId, 21);++ // Nothing to track without the windows API; the viewer still works.+ const bare = { tabId: 1 };+ await trackViewerWindow({ api: {}, target: { addEventListener() {} }, fields: bare }).refresh();+ assert.deepEqual(bare, { tabId: 1 });});test('WebGPU provider drops a request whose caller aborts while the offscreen document is starting', async () => {