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
Budget card prompts conservatively, keep the whole partial answer, report presence earlier
Claude0f25d8f78c7f
diff --git a/docs/architecture.md b/docs/architecture.mdindex b000f70ec..dd72be73b 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -521,16 +521,19 @@ behind a short fixed system message, then makes a single tool-less model call thcost allowance (90 s timeout) and returns the text. The output budget is sized to theselection (at least 2,000 tokens; Translate and Proofread grow to about two tokens percharacter, up to 8,000) and never exceeds the provider's own output ceiling or the room its-context window leaves after the prompt (counted at half a token per character, with a floor of-256 tokens), so a small local window is not sent a request it would reject. If the reply+context window leaves after the prompt (estimated on the high side, since the provider's tokenizer+is not available: half a token per Latin-range character, two per other character such as CJK,+plus a reserve), so a small local window is not sent a request it would reject. When the prompt+leaves less than 256 tokens for the answer, the background makes no call and answers with the+cut-off shape, so the card hands the selection to the side panel. If the replystill stopped at the cap (finish reason, Anthropic `stop_reason` or Responses`incomplete_details`, or token usage at the budget when no reason is reported; OpenAIResponses reports the limit as an error, which the background treats the same way andanswers with whatever text the provider returned) the responseis flagged `truncated`, and the card says so and offers **Continue in side panel** insteadof passing a cut-off translation off as complete. Continue sends the unfinished text as-`continueFrom`; the background wraps it inside the selection's untrusted block (keeping its-end) with a trusted request to resume from where it stops, because running the action again+`continueFrom`; the background wraps it inside the selection's untrusted block (whole, up to the+most a card can produce, because the side panel shows that block to the user) with a trusted request to resume from where it stops, because running the action againwould meet the same output limit. A side-panel reply that is cut off again says so (theresponse-only path appends a notice when the provider reports a length finish, WebGPUreports `outputTruncated`, or OpenAI Responses raises the limit as an error carrying@@ -554,6 +557,8 @@ open panel closes it, so each panel reports its visibility over a long-lived porgesture can lapse, then hands an already-open panel the prompt by message. A panel whose portwas dropped by a background restart reconnects at once (only a port that is refused straightaway backs off), so the restarted worker is not left unaware of a panel that is still showing.+A new panel reports as soon as it knows its window, ahead of its other start-up awaits, so an+action arriving while it is still opening does not open it a second time.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/background.js b/src/chrome/src/background.jsindex 326108226..8f7e2a487 100644--- a/src/chrome/src/background.js+++ b/src/chrome/src/background.js@@ -74,6 +74,7 @@ import {SELECTION_TRANSLATION_LANGUAGES,buildContextMenuPrompt,buildContinuationSelectionPrompt,+ INLINE_CONTINUE_PARTIAL_MAX_CHARS,buildFollowUpSelectionText,buildFullContextSelectionPrompt,buildInlineSelectionMessages,@@ -1789,6 +1790,11 @@ async function answerInlineSelection(msg) {contextWindow: provider?.contextWindow,messages,});+ // The prompt alone fills the model's context window: no call could answer, so the+ // card offers the side panel, which manages its own context, instead.+ if (maxTokens === 0) {+ return { ok: false, truncated: true, error: 'This selection is too long for the model\'s context window.' };+ }const result = await agent._chatWithCostAllowance(provider,messages,@@ -1847,7 +1853,7 @@ function queueSelectionShortcutPrompt(msg, tab, sendResponse, { panelOpened = faconst resumesCutOffAnswer = selectionAction !== 'custom'&& typeof msg.continueFrom === 'string' && msg.continueFrom.trim() !== '';const text = resumesCutOffAnswer- ? buildContinuationSelectionPrompt(msg.selectionText, selectionAction, msg.continueFrom.slice(-20000), msg.language)+ ? buildContinuationSelectionPrompt(msg.selectionText, selectionAction, msg.continueFrom.slice(-INLINE_CONTINUE_PARTIAL_MAX_CHARS), msg.language): includePageContext? buildFullContextSelectionPrompt(selectionText, msg.question): buildSelectionPrompt(diff --git a/src/chrome/src/context-menu-storage.js b/src/chrome/src/context-menu-storage.jsindex daeed4050..ec734ce5e 100644--- a/src/chrome/src/context-menu-storage.js+++ b/src/chrome/src/context-menu-storage.js@@ -280,14 +280,33 @@ export const INLINE_ANSWER_MAX_TOKENS = 8000;const INLINE_FALLBACK_OUTPUT_CEILING = 4096;// Room kept for the prompt in a small context window: backends that enforce// input + max_tokens <= window reject a request whose output budget ignores it. The-// prompt is counted at half a token per character, which holds for CJK and Indic-// text and over-counts Latin text, so a tight window is more likely to cut an answer-// off (the card then offers the side panel) than to refuse it. Chat-template tokens-// are covered by the reserve, and the answer keeps a floor so it is never starved.-const INLINE_PROMPT_TOKENS_PER_CHAR = 0.5;+// provider's tokenizer is not available here, so the prompt is estimated per+// character on the high side: Latin-range text at half a token, everything else+// (CJK, Indic, Arabic, Cyrillic, emoji) at two, which covers the worst tokenizers.+// Over-counting only makes a tight window end in a flagged cut-off or a hand-off to+// the side panel instead of a refused request. Chat-template tokens are covered by+// the reserve.+const INLINE_LATIN_TOKENS_PER_CHAR = 0.5;+const INLINE_OTHER_TOKENS_PER_CHAR = 2;+const INLINE_LATIN_RANGE_END = 0x250;const INLINE_PROMPT_TOKEN_RESERVE = 128;const INLINE_MIN_ANSWER_TOKENS = 256;+function estimateInlinePromptTokens(messages) {+ let tokens = INLINE_PROMPT_TOKEN_RESERVE;+ for (const message of Array.isArray(messages) ? messages : []) {+ if (typeof message?.content !== 'string') continue;+ for (const char of message.content) {+ tokens += char.codePointAt(0) < INLINE_LATIN_RANGE_END+ ? INLINE_LATIN_TOKENS_PER_CHAR+ : INLINE_OTHER_TOKENS_PER_CHAR;+ }+ }+ return Math.ceil(tokens);+}++// 0 means the prompt alone leaves the answer less than its floor in the provider's+// context window, so the card should hand the selection to the side panel.export function inlineSelectionMaxTokens(selectionText, action, providerCeiling, { contextWindow, messages } = {}) {const chars = String(selectionText || '').trim().length;const wanted = String(action || '').trim() === 'explain'@@ -297,10 +316,9 @@ export function inlineSelectionMaxTokens(selectionText, action, providerCeiling,const budget = Math.min(wanted, limit > 0 ? limit : INLINE_FALLBACK_OUTPUT_CEILING);const window = Math.floor(Number(contextWindow));if (!(window > 0)) return budget;- const promptChars = (Array.isArray(messages) ? messages : [])- .reduce((total, message) => total + (typeof message?.content === 'string' ? message.content.length : 0), 0);- const promptTokens = Math.ceil(promptChars * INLINE_PROMPT_TOKENS_PER_CHAR) + INLINE_PROMPT_TOKEN_RESERVE;- return Math.min(budget, Math.max(INLINE_MIN_ANSWER_TOKENS, window - promptTokens));+ const room = window - estimateInlinePromptTokens(messages);+ if (room < Math.min(INLINE_MIN_ANSWER_TOKENS, budget)) return 0;+ return Math.min(budget, room);}// Whether the model stopped because it ran out of output budget. Providers report@@ -357,9 +375,10 @@ export function buildFollowUpSelectionText(selectionText, priorAction, priorAnsw// A card answer that hit the output limit is finished in the side panel by// resuming it, not by running the whole action again: a second full run meets the// same limit. The unfinished text is model output derived from untrusted page-// text, so it travels inside the selection's untrusted block, and only its end is-// kept because that is where the answer has to pick up.-export const INLINE_CONTINUE_PARTIAL_MAX_CHARS = 6000;+// text, so it travels inside the selection's untrusted block. The side panel shows that+// block to the user, so the whole unfinished text is kept (the cap is the most a card+// can produce, 8,000 tokens at four characters each) and only a longer one loses its start.+export const INLINE_CONTINUE_PARTIAL_MAX_CHARS = 32000;const INLINE_CONTINUE_NOTE = ' An earlier attempt at this stopped partway; the text it produced is included after the selection. Continue it from exactly where it stops and give only the missing remainder, without repeating anything already written.';export function buildContinuationSelectionPrompt(selectionText, action, partialAnswer, language = '') {diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.jsindex c1242234c..fcea26243 100644--- a/src/chrome/src/ui/sidepanel.js+++ b/src/chrome/src/ui/sidepanel.js@@ -5028,6 +5028,13 @@ function clearScratchpad(tabId = currentTabId) {async function init() {const initialWindow = await chrome.windows.getCurrent().catch(() => null);const initialWindowId = initialWindow?.id ?? null;+ // Lets the background reuse this panel instead of re-opening it (which closes it). It+ // is reported as soon as the window is known, ahead of the awaits below, so an action+ // that arrives while the panel is still starting up does not open it a second time.+ const presenceReportedEarly = !isBtwWindow && initialWindowId != null;+ if (presenceReportedEarly) {+ reportSidePanelPresence({ runtime: chrome.runtime, doc: document, windowId: initialWindowId });+ }const [tab] = await chrome.tabs.query(initialWindowId != null? { active: true, windowId: initialWindowId }: { active: true, currentWindow: true });@@ -5064,13 +5071,9 @@ async function init() {switchToTab,});- // Lets the background reuse this panel instead of re-opening it (which closes it).- if (!isBtwWindow) {- reportSidePanelPresence({- runtime: chrome.runtime,- doc: document,- windowId: initialWindowId ?? tab?.windowId ?? null,- });+ // The window could not be read up front; fall back to the active tab's.+ if (!isBtwWindow && !presenceReportedEarly) {+ reportSidePanelPresence({ runtime: chrome.runtime, doc: document, windowId: tab?.windowId ?? null });}if (windowScope) {diff --git a/src/firefox/src/background.js b/src/firefox/src/background.jsindex 491c2585a..0ce08cd1c 100644--- a/src/firefox/src/background.js+++ b/src/firefox/src/background.js@@ -67,6 +67,7 @@ import {SELECTION_TRANSLATION_LANGUAGES,buildContextMenuPrompt,buildContinuationSelectionPrompt,+ INLINE_CONTINUE_PARTIAL_MAX_CHARS,buildFollowUpSelectionText,buildFullContextSelectionPrompt,buildInlineSelectionMessages,@@ -1540,6 +1541,11 @@ async function answerInlineSelection(msg) {contextWindow: provider?.contextWindow,messages,});+ // The prompt alone fills the model's context window: no call could answer, so the+ // card offers the side panel, which manages its own context, instead.+ if (maxTokens === 0) {+ return { ok: false, truncated: true, error: 'This selection is too long for the model\'s context window.' };+ }const result = await agent._chatWithCostAllowance(provider,messages,@@ -1599,7 +1605,7 @@ function queueFirefoxSelectionShortcutPrompt(msg, tab, sendResponse) {const resumesCutOffAnswer = selectionAction !== 'custom'&& typeof msg.continueFrom === 'string' && msg.continueFrom.trim() !== '';const text = resumesCutOffAnswer- ? buildContinuationSelectionPrompt(msg.selectionText, selectionAction, msg.continueFrom.slice(-20000), msg.language)+ ? buildContinuationSelectionPrompt(msg.selectionText, selectionAction, msg.continueFrom.slice(-INLINE_CONTINUE_PARTIAL_MAX_CHARS), msg.language): includePageContext? buildFullContextSelectionPrompt(selectionText, msg.question): buildSelectionPrompt(diff --git a/src/firefox/src/context-menu-storage.js b/src/firefox/src/context-menu-storage.jsindex 39d86d4cf..ddff71922 100644--- a/src/firefox/src/context-menu-storage.js+++ b/src/firefox/src/context-menu-storage.js@@ -280,14 +280,33 @@ export const INLINE_ANSWER_MAX_TOKENS = 8000;const INLINE_FALLBACK_OUTPUT_CEILING = 4096;// Room kept for the prompt in a small context window: backends that enforce// input + max_tokens <= window reject a request whose output budget ignores it. The-// prompt is counted at half a token per character, which holds for CJK and Indic-// text and over-counts Latin text, so a tight window is more likely to cut an answer-// off (the card then offers the side panel) than to refuse it. Chat-template tokens-// are covered by the reserve, and the answer keeps a floor so it is never starved.-const INLINE_PROMPT_TOKENS_PER_CHAR = 0.5;+// provider's tokenizer is not available here, so the prompt is estimated per+// character on the high side: Latin-range text at half a token, everything else+// (CJK, Indic, Arabic, Cyrillic, emoji) at two, which covers the worst tokenizers.+// Over-counting only makes a tight window end in a flagged cut-off or a hand-off to+// the side panel instead of a refused request. Chat-template tokens are covered by+// the reserve.+const INLINE_LATIN_TOKENS_PER_CHAR = 0.5;+const INLINE_OTHER_TOKENS_PER_CHAR = 2;+const INLINE_LATIN_RANGE_END = 0x250;const INLINE_PROMPT_TOKEN_RESERVE = 128;const INLINE_MIN_ANSWER_TOKENS = 256;+function estimateInlinePromptTokens(messages) {+ let tokens = INLINE_PROMPT_TOKEN_RESERVE;+ for (const message of Array.isArray(messages) ? messages : []) {+ if (typeof message?.content !== 'string') continue;+ for (const char of message.content) {+ tokens += char.codePointAt(0) < INLINE_LATIN_RANGE_END+ ? INLINE_LATIN_TOKENS_PER_CHAR+ : INLINE_OTHER_TOKENS_PER_CHAR;+ }+ }+ return Math.ceil(tokens);+}++// 0 means the prompt alone leaves the answer less than its floor in the provider's+// context window, so the card should hand the selection to the side panel.export function inlineSelectionMaxTokens(selectionText, action, providerCeiling, { contextWindow, messages } = {}) {const chars = String(selectionText || '').trim().length;const wanted = String(action || '').trim() === 'explain'@@ -297,10 +316,9 @@ export function inlineSelectionMaxTokens(selectionText, action, providerCeiling,const budget = Math.min(wanted, limit > 0 ? limit : INLINE_FALLBACK_OUTPUT_CEILING);const window = Math.floor(Number(contextWindow));if (!(window > 0)) return budget;- const promptChars = (Array.isArray(messages) ? messages : [])- .reduce((total, message) => total + (typeof message?.content === 'string' ? message.content.length : 0), 0);- const promptTokens = Math.ceil(promptChars * INLINE_PROMPT_TOKENS_PER_CHAR) + INLINE_PROMPT_TOKEN_RESERVE;- return Math.min(budget, Math.max(INLINE_MIN_ANSWER_TOKENS, window - promptTokens));+ const room = window - estimateInlinePromptTokens(messages);+ if (room < Math.min(INLINE_MIN_ANSWER_TOKENS, budget)) return 0;+ return Math.min(budget, room);}// Whether the model stopped because it ran out of output budget. Providers report@@ -357,9 +375,10 @@ export function buildFollowUpSelectionText(selectionText, priorAction, priorAnsw// A card answer that hit the output limit is finished in the side panel by// resuming it, not by running the whole action again: a second full run meets the// same limit. The unfinished text is model output derived from untrusted page-// text, so it travels inside the selection's untrusted block, and only its end is-// kept because that is where the answer has to pick up.-export const INLINE_CONTINUE_PARTIAL_MAX_CHARS = 6000;+// text, so it travels inside the selection's untrusted block. The side panel shows that+// block to the user, so the whole unfinished text is kept (the cap is the most a card+// can produce, 8,000 tokens at four characters each) and only a longer one loses its start.+export const INLINE_CONTINUE_PARTIAL_MAX_CHARS = 32000;const INLINE_CONTINUE_NOTE = ' An earlier attempt at this stopped partway; the text it produced is included after the selection. Continue it from exactly where it stops and give only the missing remainder, without repeating anything already written.';export function buildContinuationSelectionPrompt(selectionText, action, partialAnswer, language = '') {diff --git a/test/run.js b/test/run.jsindex 4af3f2610..c4b218d4f 100644--- a/test/run.js+++ b/test/run.js@@ -52151,6 +52151,13 @@ test('a cut-off card answer is resumed in the side panel, not run again', () =>assert.match(block, /Fuchs springt über \[markup stripped\] den faulen/, `${label}: a forged closing tag in the unfinished text is neutralised`);assert.equal((block.match(/<\/untrusted_page_content>/g) || []).length, 1, `${label}: the boundary closes exactly once`);+ // The side panel shows this block, so a partial answer is kept whole up to the most a card can produce.+ assert.equal(maxChars, 32000, `${label}: the cap is the largest card answer (8,000 tokens at four characters)`);+ const wholePartial = `FIRST-${'y'.repeat(11_000)}-LAST`;+ const wholePrompt = buildContinuation('Some text.', 'translate', wholePartial, 'de');+ assert.ok(wholePrompt.includes(wholePartial), `${label}: an unfinished answer well past the old 6,000-character cap is kept in full`);+ assert.doesNotMatch(wholePrompt, /…/, `${label}: nothing was trimmed, so no ellipsis`);+// An answer longer than the budget keeps its end, which is where it has to pick up.const long = `START-${'x'.repeat(maxChars + 500)}-END`;const longPrompt = buildContinuation('Some text.', 'proofread', long, 'en');@@ -52181,7 +52188,7 @@ test('a cut-off card answer is resumed in the side panel, not run again', () =>['firefox', 'src/firefox/src/background.js'],]) {const background = fs.readFileSync(path.join(ROOT, bgPath), 'utf8');- assert.match(background, /const resumesCutOffAnswer = selectionAction !== 'custom'\s*&& typeof msg\.continueFrom === 'string' && msg\.continueFrom\.trim\(\) !== '';\s*const text = resumesCutOffAnswer\s*\? buildContinuationSelectionPrompt\(msg\.selectionText, selectionAction, msg\.continueFrom\.slice\(-20000\), msg\.language\)/,+ assert.match(background, /const resumesCutOffAnswer = selectionAction !== 'custom'\s*&& typeof msg\.continueFrom === 'string' && msg\.continueFrom\.trim\(\) !== '';\s*const text = resumesCutOffAnswer\s*\? buildContinuationSelectionPrompt\(msg\.selectionText, selectionAction, msg\.continueFrom\.slice\(-INLINE_CONTINUE_PARTIAL_MAX_CHARS\), msg\.language\)/,`${prefix}: the background resumes a cut-off answer for the card actions and bounds what it accepts`);const content = fs.readFileSync(path.join(ROOT, `src/${prefix}/src/content/selection-shortcut.js`), 'utf8');assert.match(content, /\.\.\.\(action !== 'custom' && extra\.continueFrom \? \{ continueFrom: extra\.continueFrom \} : \{\}\)/,@@ -52276,6 +52283,7 @@ test('inline card answers are one tool-less, bounded model call behind validatedassert.match(body, /if \(!messages\) return \{ ok: false/, `${prefix}: invalid requests are refused before any model call`);assert.match(body, /agent\._chatWithCostAllowance\(\s*provider,\s*messages,\s*\{ maxTokens, temperature: 0, signal: controller\.signal \},\s*agent\._newCostRunState\(\),/, `${prefix}: the call is bounded, abortable and goes through the cost allowance`);assert.match(body, /const maxTokens = inlineSelectionMaxTokens\(msg\.selectionText, msg\.action, provider\?\.maxOutputTokens, \{\s*contextWindow: provider\?\.contextWindow,\s*messages,\s*\}\);/, `${prefix}: the budget is sized to the selection, the provider's ceiling and the room its context window leaves after the prompt`);+ assert.match(body, /if \(maxTokens === 0\) \{\s*return \{ ok: false, truncated: true, error: [^}]*context window[^}]*\};\s*\}\s*const result = await agent\._chatWithCostAllowance/, `${prefix}: a prompt that fills the context window is handed to the side panel without a model call`);assert.match(body, /inlineAnswerWasCut\(result, maxTokens\) \? \{ ok: true, text, truncated: true \}/, `${prefix}: a capped answer is flagged instead of passing as complete`);assert.match(body, /catch \(error\) \{\s*if \(inlineErrorWasCut\(error\)\) \{[\s\S]*?\{ ok: true, text: partial, truncated: true \}[\s\S]*?\{ ok: false, truncated: true, error:/, `${prefix}: a provider that reports the output limit as an error still ends in the cut-off state`);@@ -52316,10 +52324,32 @@ test('inline card token budget follows the selection and never exceeds the provi`${label}: a large window changes nothing`);assert.equal(budget(longText, 'translate', 16_000, { contextWindow: 16_384, messages: prompt(3500) }), 6000,`${label}: an ordinary local window changes nothing for a card-sized selection`);- assert.equal(budget(longText, 'translate', 16_000, { contextWindow: 2048, messages: prompt(3500) }), 256,- `${label}: the answer keeps a floor when the prompt alone nearly fills the window`);+ // Prompt estimate: 128 reserved + half a token per Latin character; two per other character.+ assert.equal(budget(longText, 'translate', 16_000, { contextWindow: 2048, messages: prompt(2500) }), 2048 - 128 - 1500,+ `${label}: the answer gets what is left once the prompt is counted`);+ assert.equal(budget(longText, 'translate', 16_000, { contextWindow: 2048, messages: prompt(3500) }), 0,+ `${label}: a prompt that leaves less than the answer floor is handed to the side panel`);+ assert.equal(budget(longText, 'translate', 16_000, { contextWindow: 1900, messages: prompt(2500) }), 272,+ `${label}: an answer at or above the floor is still attempted`);+ assert.equal(budget(longText, 'translate', 16_000, { contextWindow: 1800, messages: prompt(2500) }), 0,+ `${label}: just under the floor is handed off`);assert.equal(budget('short', 'translate', 100, { contextWindow: 2048, messages: prompt(10) }), 100,`${label}: a ceiling lower than the floor still wins`);+ assert.equal(budget('short', 'translate', 100, { contextWindow: 2048, messages: prompt(3500) }), 0,+ `${label}: but not when the prompt itself cannot fit`);++ // CJK text costs about a token per character or more, not half of one.+ const cjk = (chars) => [{ role: 'system', content: 'x'.repeat(500) }, { role: 'user', content: '漢'.repeat(chars) }];+ assert.equal(budget('漢'.repeat(4000), 'translate', 16_000, { contextWindow: 4096, messages: cjk(4000) }), 0,+ `${label}: a 4,000-character CJK selection does not fit a 4k window and is handed off`);+ assert.equal(budget('漢'.repeat(1000), 'translate', 16_000, { contextWindow: 4096, messages: cjk(1000) }), 4096 - 128 - 250 - 2000,+ `${label}: a shorter one gets the window minus a two-token-per-character prompt`);+ assert.equal(budget('漢'.repeat(4000), 'translate', 16_000, { contextWindow: 131_072, messages: cjk(4000) }), 8000,+ `${label}: a large window still allows the full answer`);+ assert.equal(budget('Привет'.repeat(300), 'translate', 16_000, { contextWindow: 4096, messages: [{ role: 'user', content: 'Привет'.repeat(300) }] }), 4096 - 128 - 3600,+ `${label}: Cyrillic is counted as non-Latin text too`);+ assert.equal(budget('😀'.repeat(10), 'translate', 16_000, { contextWindow: 500, messages: [{ role: 'user', content: '😀'.repeat(10) }] }), 500 - 128 - 20,+ `${label}: an astral character counts once, not as two UTF-16 units`);assert.equal(budget(longText, 'translate', 16_000, { contextWindow: undefined, messages: prompt(3500) }), 6000,`${label}: an unknown window is not guessed at`);assert.equal(budget(longText, 'translate', 16_000, { contextWindow: 0 }), 6000, `${label}: a zero window is ignored`);@@ -52799,8 +52829,10 @@ test('background does not re-open a side panel that is already showing, and stilassert.match(background, /chrome\.runtime\.onConnect\.addListener\(\(port\) => \{ sidePanelPresence\.attach\(port\); \}\);/,'the presence port must be accepted at the top level of the worker');const panel = fs.readFileSync(path.join(ROOT, 'src/chrome/src/ui/sidepanel.js'), 'utf8');- assert.match(panel, /if \(!isBtwWindow\) \{\s*reportSidePanelPresence\(\{[\s\S]*?runtime: chrome\.runtime,[\s\S]*?windowId: initialWindowId \?\? tab\?\.windowId \?\? null,/,- 'the side panel must tell the background when it is on screen');+ assert.match(panel, /const initialWindowId = initialWindow\?\.id \?\? null;[\s\S]*?const presenceReportedEarly = !isBtwWindow && initialWindowId != null;\s*if \(presenceReportedEarly\) \{\s*reportSidePanelPresence\(\{ runtime: chrome\.runtime, doc: document, windowId: initialWindowId \}\);\s*\}\s*const \[tab\] = await chrome\.tabs\.query/,+ 'the side panel must tell the background it is on screen as soon as its window is known, before its other awaits');+ assert.match(panel, /if \(!isBtwWindow && !presenceReportedEarly\) \{\s*reportSidePanelPresence\(\{ runtime: chrome\.runtime, doc: document, windowId: tab\?\.windowId \?\? null \}\);/,+ 'and still report when the window could only be learned from the active tab');});test('a PDF viewer selection leaves a side panel that is already showing in its window alone', async () => {