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 inline card review findings: single model call per card, sized output budget, cut-off fallback
Claude21754c1b8f3e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ed710baa1..53639e5e2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,7 +7,7 @@ This changelog was generated from the repository Git history and release tags. V## [Unreleased]### Changed-- 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 continues in the side panel with the card's answer as context. **More…** opens the same popup the `?` button opened (Summarize, Explain, Quiz me, Proofread, Humanize, Translate, a question box and Hide this). 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. Chrome and Firefox.+- 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 continues in the side panel with the card's answer as context. **More…** opens the same popup the `?` button opened (Summarize, Explain, Quiz me, Proofread, Humanize, Translate, a question box and Hide this). 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, and closing or redoing a card cancels the request it no longer needs. Chrome and Firefox.### Fixed- 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.diff --git a/docs/architecture.md b/docs/architecture.mdindex 657331577..b05e27c59 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -517,8 +517,17 @@ described above. Translate, Explain and Proofread answer in place instead: the sone `WB_SELECTION_SHORTCUT_INLINE` message and the background builds the same allowlistedselection prompt (the selection inside its untrusted boundary, `selection_only` grounding)behind a short fixed system message, then makes a single tool-less model call through the-cost allowance (2,000 output tokens, 90 s timeout) and returns the text. Selections over-4,000 characters skip the card and use the side-panel flow. The card draws the answer as DOM+cost allowance (90 s timeout) and returns the text. The output budget is sized to the+selection (at least 2,000 tokens; Translate and Proofread grow to about two tokens per+character, up to 8,000) and never exceeds the provider's own output ceiling. If the reply+still stopped at the cap (finish reason, Anthropic `stop_reason` or Responses+`incomplete_details`, or token usage at the budget when no reason is reported) the response+is flagged `truncated`, and the card says so and offers **Continue in side panel** instead+of passing a cut-off translation off as complete. Each call carries a job id, and a card+that is closed, retried or retargeted sends `WB_SELECTION_SHORTCUT_INLINE_CANCEL` so the+background aborts the paid request it no longer needs; the card also claims its request id+before it waits for the language bundle, so a double click starts only one call. Selections+over 4,000 characters skip the card and use the side-panel flow. The card draws the answer as DOMnodes (paragraphs, lists, bold, italic and code), never as HTML, and takes the sourcelanguage from the browser's own detector, with no network call. A follow-up typed in a cardcontinues in the side panel as a custom question. The card's answer travels inside thediff --git a/src/chrome/src/background.js b/src/chrome/src/background.jsindex 165a16202..959e48be7 100644--- a/src/chrome/src/background.js+++ b/src/chrome/src/background.js@@ -72,6 +72,8 @@ import {buildFollowUpSelectionText,buildFullContextSelectionPrompt,buildInlineSelectionMessages,+ inlineAnswerWasCut,+ inlineSelectionMaxTokens,buildSelectionPrompt,normalizeSelectionAction,normalizeSelectionSourceGrounding,@@ -1748,11 +1750,17 @@ chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {// prompt builder keeps the selection inside the untrusted boundary and caps its// length, and the call goes through the normal cost allowance.const INLINE_SELECTION_TIMEOUT_MS = 90_000;+// Calls still in flight, keyed by the card's job id, so a card that is closed,+// retried or retargeted can cancel the paid request it no longer needs.+const inlineSelectionJobs = new Map();+const INLINE_JOB_ID_PATTERN = /^[a-z0-9]{8,64}$/;async function answerInlineSelection(msg) {const messages = buildInlineSelectionMessages(msg.selectionText, msg.action, msg.language);if (!messages) return { ok: false, error: 'Invalid selection request.' };const controller = new AbortController();+ const jobId = typeof msg.jobId === 'string' && INLINE_JOB_ID_PATTERN.test(msg.jobId) ? msg.jobId : '';+ if (jobId) inlineSelectionJobs.set(jobId, controller);const timer = setTimeout(() => controller.abort(new Error('The model took too long to answer.')),INLINE_SELECTION_TIMEOUT_MS,@@ -1760,18 +1768,24 @@ async function answerInlineSelection(msg) {try {if (providerManager.providers.size === 0) await providerManager.load();const provider = providerManager.getActive();+ // Sized to the selection and never above what the provider accepts; an answer+ // that still hits the ceiling is flagged so the card can offer the side panel+ // instead of presenting a cut-off translation as complete.+ const maxTokens = inlineSelectionMaxTokens(msg.selectionText, msg.action, provider?.maxOutputTokens);const result = await agent._chatWithCostAllowance(provider,messages,- { maxTokens: 2000, temperature: 0, signal: controller.signal },+ { maxTokens, temperature: 0, signal: controller.signal },agent._newCostRunState(),);const text = String(result?.content || '').trim();- return text ? { ok: true, text } : { ok: false, error: 'The model returned an empty answer.' };+ if (!text) return { ok: false, error: 'The model returned an empty answer.' };+ return inlineAnswerWasCut(result, maxTokens) ? { ok: true, text, truncated: true } : { ok: true, text };} catch (error) {return { ok: false, error: String(error?.message || error).slice(0, 300) };} finally {clearTimeout(timer);+ if (jobId && inlineSelectionJobs.get(jobId) === controller) inlineSelectionJobs.delete(jobId);}}@@ -1781,6 +1795,13 @@ chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {return true;});+chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {+ if (msg?.type !== 'WB_SELECTION_SHORTCUT_INLINE_CANCEL') return;+ const jobId = typeof msg.jobId === 'string' ? msg.jobId : '';+ inlineSelectionJobs.get(jobId)?.abort(new Error('The card was closed.'));+ sendResponse({ ok: true });+});+// Selection-shortcut clicks originate in a content script. Keep this listener// synchronous until sidePanel.open() so Chrome preserves the originating user// gesture; prompt recovery storage can finish afterward.diff --git a/src/chrome/src/content/selection-shortcut.js b/src/chrome/src/content/selection-shortcut.jsindex 43eb8d2b1..232b018d8 100644--- a/src/chrome/src/content/selection-shortcut.js+++ b/src/chrome/src/content/selection-shortcut.js@@ -31,6 +31,7 @@: {};const LOCALIZATION_MESSAGE = 'WB_SELECTION_SHORTCUT_LOCALIZATION';const INLINE_MESSAGE = 'WB_SELECTION_SHORTCUT_INLINE';+ const INLINE_CANCEL_MESSAGE = 'WB_SELECTION_SHORTCUT_INLINE_CANCEL';const GAP = 8;const TOOLBAR_HEIGHT = 38;const POPUP_WIDTH = 316;@@ -53,6 +54,7 @@'proofread', 'humanize', 'translate', 'translateTo', 'askAbout','askQuestion', 'sendQuestion', 'includePageContext', 'hideShortcut', 'sentManual', 'sendFailed','more', 'askFollowUp', 'sendFollowUp', 'working', 'autoDetect', 'inlineFailed', 'retry',+ 'cutOff', 'continueInPanel',]);// English copy for strings the card shows before the localization bundle// arrives (or when the background cannot be reached).@@ -60,6 +62,8 @@translateTo: 'Translate to',autoDetect: 'Auto-detect',inlineFailed: 'Could not get an answer.',+ cutOff: 'This answer was cut off.',+ continueInPanel: 'Continue in side panel',});// Language codes the browser's detector reports that differ from ours.const DETECTED_LANGUAGE_ALIASES = Object.freeze({ iw: 'he', fil: 'tl', in: 'id' });@@ -84,6 +88,8 @@let cardSide = 'above';let cardOpener = null;let cardRequestId = 0;+ // Id of the model call the card is waiting on, so closing or redoing the card can cancel it.+ let cardJobId = '';let toolbarLeft = 0;let interfaceLanguage = resolveInterfaceLanguage('');let localization = null;@@ -223,6 +229,8 @@cardParts.target.setAttribute('aria-label', strings.translateTo);cardParts.skeleton.setAttribute('aria-label', strings.working);cardParts.retry.textContent = strings.retry;+ cardParts.cutText.textContent = strings.cutOff;+ cardParts.continueButton.textContent = strings.continueInPanel;populateTargetLanguages();renderCard();// Label widths change with the language, and the bar is centered on the selection.@@ -416,6 +424,15 @@color:var(--text); font-size:14px; font-weight:550; cursor:pointer;}.card-retry:hover { background:var(--hover); }+ .card-cut {+ display:flex; flex:none; flex-wrap:wrap; align-items:center; gap:6px 10px; margin-top:10px;+ color:var(--muted); font-size:13px; line-height:1.4;+ }+ .card-continue {+ padding:5px 11px; border:1px solid var(--border); border-radius:10px; background:transparent;+ color:var(--text); font-size:13px; font-weight:550; cursor:pointer;+ }+ .card-continue:hover { background:var(--hover); }.followup {display:flex; flex:none; align-items:center; gap:8px; margin-top:12px;padding:5px 5px 5px 14px; border-radius:16px; background:var(--field);@@ -542,6 +559,10 @@<button class="card-retry" type="button">Try again</button></div></div>+ <div class="card-cut" hidden>+ <span class="card-cut-text">This answer was cut off.</span>+ <button class="card-continue" type="button">Continue in side panel</button>+ </div><div class="followup"><input class="followup-input" type="text" maxlength="2000" aria-label="Ask a follow-up" placeholder="Ask a follow-up"><button class="followup-send" type="button" aria-label="Send follow-up" disabled>@@ -572,6 +593,9 @@errorText: shadow.querySelector('.card-error-text'),errorDetail: shadow.querySelector('.card-error-detail'),retry: shadow.querySelector('.card-retry'),+ cut: shadow.querySelector('.card-cut'),+ cutText: shadow.querySelector('.card-cut-text'),+ continueButton: shadow.querySelector('.card-continue'),followUp: shadow.querySelector('.followup-input'),send: shadow.querySelector('.followup-send'),};@@ -609,6 +633,9 @@cardParts.retry.addEventListener('click', (event) => {if (event.isTrusted) runInline();});+ cardParts.continueButton.addEventListener('click', (event) => {+ if (event.isTrusted) continueInPanel();+ });cardParts.followUp.addEventListener('input', () => {cardParts.send.disabled = !cardParts.followUp.value.trim();});@@ -896,6 +923,7 @@parts.skeleton.hidden = status !== 'loading';parts.text.hidden = status !== 'ready';parts.error.hidden = status !== 'error';+ parts.cut.hidden = !(status === 'ready' && cardState.truncated);if (status === 'ready') renderAnswer(parts.text, cardState.text, kind !== 'translate');if (status === 'error') {parts.errorText.textContent = str('inlineFailed');@@ -908,8 +936,12 @@async function openCard(kind, opener) {if (!snapshot || submitting || !INLINE_ACTIONS.includes(kind)) return;+ // Claim the card before anything is awaited: a second click while the+ // localization loads takes a newer id, so this call stops instead of opening+ // a second card and starting a second paid request.+ const requestId = ++cardRequestId;if (!localization) await refreshLocalization(interfaceLanguage);- if (!snapshot || submitting) return;+ if (requestId !== cardRequestId || !snapshot || submitting) return;if (snapshot.text.length > INLINE_MAX_CHARS) {// Too long for a card: the side panel is the better place to read it.submitSelection(kind, '', interfaceLanguage);@@ -918,7 +950,6 @@ensureSurface();applyLocalization();closePopup(false);- const requestId = ++cardRequestId;cardOpener = opener || null;cardState = {kind,@@ -927,6 +958,7 @@sourceLabel: '',quote: kind === 'translate' ? snapshot.text : '',text: '',+ truncated: false,error: '',};cardParts.followUp.value = '';@@ -956,29 +988,54 @@runInline();}+ function newInlineJobId() {+ const bytes = new Uint8Array(12);+ crypto.getRandomValues(bytes);+ return Array.from(bytes, (byte) => (byte % 36).toString(36)).join('');+ }++ // Tell the background to stop the model call the card no longer needs.+ function cancelInline() {+ const jobId = cardJobId;+ cardJobId = '';+ if (!jobId) return;+ try {+ Promise.resolve(api.runtime.sendMessage({ type: INLINE_CANCEL_MESSAGE, jobId })).catch(() => {});+ } catch { /* The call ends on its own timeout if the background is unreachable. */ }+ }+async function runInline() {if (!cardState || !snapshot) return;+ // Retrying or retargeting replaces the call that is still running.+ cancelInline();const requestId = ++cardRequestId;+ const jobId = newInlineJobId();+ cardJobId = jobId;const { kind, target } = cardState;const selectionText = snapshot.text;cardState.status = 'loading';cardState.text = '';+ cardState.truncated = false;cardState.error = '';renderCard();try {const response = await api.runtime.sendMessage({type: INLINE_MESSAGE,+ jobId,action: kind,selectionText,language: kind === 'translate' ? target : interfaceLanguage,});if (requestId !== cardRequestId || !cardState) return;+ cardJobId = '';const answer = typeof response?.text === 'string' ? response.text.trim() : '';if (!response?.ok || !answer) throw new Error(typeof response?.error === 'string' ? response.error : '');cardState.status = 'ready';cardState.text = answer;+ cardState.truncated = response.truncated === true;} catch (error) {if (requestId !== cardRequestId || !cardState) return;+ cardJobId = '';cardState.status = 'error';cardState.error = String(error?.message || '').slice(0, 300);}@@ -997,8 +1054,16 @@});}- // Forget the card without touching the bar; a request still in flight is ignored.+ // A cut-off answer is finished in the side panel, where the reply is not capped.+ function continueInPanel() {+ if (!cardState || cardState.status !== 'ready') return;+ const { kind, target } = cardState;+ submitSelection(kind, '', kind === 'translate' ? target : interfaceLanguage);+ }++ // Forget the card without touching the bar; a request still in flight is cancelled and ignored.function resetCard() {+ cancelInline();cardRequestId += 1;cardState = null;cardOpener = null;@@ -1034,6 +1099,7 @@function destroySurface() {hideToast();+ cancelInline();cardRequestId += 1;host?.remove();host = shadow = highlightLayer = shortcut = moreButton = popup = question = includePageContext = sendButton = toast = null;@@ -1230,6 +1296,10 @@followUpRect: card && !card.hidden ? rectOf('.followup') : null,followUpSendRect: card && !card.hidden ? rectOf('.followup-send') : null,retryRect: cardParts && !cardParts.error.hidden ? rectOf('.card-retry') : null,+ cardTruncated: cardState?.truncated === true,+ cutNoticeText: cardParts && !cardParts.cut.hidden ? cardParts.cutText.textContent : '',+ continueRect: cardParts && !cardParts.cut.hidden ? rectOf('.card-continue') : null,+ continueLabel: cardParts && !cardParts.cut.hidden ? cardParts.continueButton.textContent : '',followUpPlaceholder: cardParts?.followUp.placeholder || '',followUpValue: cardParts?.followUp.value || '',followUpSendDisabled: cardParts ? cardParts.send.disabled : true,diff --git a/src/chrome/src/context-menu-storage.js b/src/chrome/src/context-menu-storage.jsindex 809d2a372..50ec61fe1 100644--- a/src/chrome/src/context-menu-storage.js+++ b/src/chrome/src/context-menu-storage.js@@ -263,6 +263,47 @@ export function buildInlineSelectionMessages(selectionText, action, language = '];}+// How many output tokens a card answer may need. Translate and Proofread hand the+// whole text back, so they scale with the selection (CJK and Indic scripts can take+// one to two tokens per character on either side of a translation); Explain stays+// short. The request never exceeds what the provider says it will accept.+export const INLINE_ANSWER_MIN_TOKENS = 2000;+export const INLINE_ANSWER_MAX_TOKENS = 8000;+const INLINE_FALLBACK_OUTPUT_CEILING = 4096;++export function inlineSelectionMaxTokens(selectionText, action, providerCeiling) {+ const chars = String(selectionText || '').trim().length;+ const wanted = String(action || '').trim() === 'explain'+ ? INLINE_ANSWER_MIN_TOKENS+ : Math.max(INLINE_ANSWER_MIN_TOKENS, Math.min(INLINE_ANSWER_MAX_TOKENS, chars * 2));+ const limit = Math.floor(Number(providerCeiling));+ return Math.min(wanted, limit > 0 ? limit : INLINE_FALLBACK_OUTPUT_CEILING);+}++// Whether the model stopped because it ran out of output budget. Providers report+// this in different places (a normalized finishReason, Anthropic's raw stop_reason,+// OpenAI's choices[0].finish_reason, a Responses-API incomplete status). A reported+// reason is trusted either way; the token count is only a fallback for providers+// that report none.+const INLINE_CUT_REASONS = new Set(['length', 'max_tokens', 'max_output_tokens', 'max_completion_tokens']);++export function inlineAnswerWasCut(result, maxTokens) {+ const raw = result?.raw;+ const reason = [+ result?.finishReason,+ result?.stopReason,+ raw?.stop_reason,+ raw?.stopReason,+ raw?.choices?.[0]?.finish_reason,+ raw?.candidates?.[0]?.finishReason,+ raw?.incomplete_details?.reason,+ ].map((value) => String(value ?? '').trim().toLowerCase()).find(Boolean);+ if (reason) return INLINE_CUT_REASONS.has(reason);+ const used = Number(result?.usage?.completion_tokens ?? result?.usage?.output_tokens);+ return Number.isFinite(used) && Number.isFinite(maxTokens) && maxTokens > 0+ && used >= Math.floor(maxTokens * 0.98);+}+const INLINE_FOLLOW_UP_LABELS = Object.freeze({translate: 'translation',explain: 'explanation',diff --git a/src/chrome/src/selection-shortcut-i18n.js b/src/chrome/src/selection-shortcut-i18n.jsindex ef1306e8a..43f154fbd 100644--- a/src/chrome/src/selection-shortcut-i18n.js+++ b/src/chrome/src/selection-shortcut-i18n.js@@ -30,6 +30,8 @@ const STRINGS = Object.freeze({autoDetect: 'Auto-detect',inlineFailed: 'Could not get an answer.',retry: 'Try again',+ cutOff: 'This answer was cut off.',+ continueInPanel: 'Continue in side panel',},zh: {askSelection: '添加到聊天',@@ -57,6 +59,8 @@ const STRINGS = Object.freeze({autoDetect: '自动检测',inlineFailed: '无法获取回答。',retry: '重试',+ cutOff: '此回答被截断了。',+ continueInPanel: '在侧边栏继续',},ar: {askSelection: 'إضافة إلى الدردشة',@@ -84,6 +88,8 @@ const STRINGS = Object.freeze({autoDetect: 'اكتشاف تلقائي',inlineFailed: 'تعذر الحصول على إجابة.',retry: 'حاول مرة أخرى',+ cutOff: 'تم اقتطاع هذه الإجابة.',+ continueInPanel: 'المتابعة في اللوحة الجانبية',},bn: {askSelection: 'চ্যাটে যোগ করুন',@@ -111,6 +117,8 @@ const STRINGS = Object.freeze({autoDetect: 'স্বয়ংক্রিয় শনাক্তকরণ',inlineFailed: 'উত্তর পাওয়া যায়নি।',retry: 'আবার চেষ্টা করুন',+ cutOff: 'এই উত্তরটি কেটে গেছে।',+ continueInPanel: 'সাইড প্যানেলে চালিয়ে যান',},de: {askSelection: 'Zum Chat hinzufügen',@@ -138,6 +146,8 @@ const STRINGS = Object.freeze({autoDetect: 'Automatisch erkennen',inlineFailed: 'Es konnte keine Antwort abgerufen werden.',retry: 'Erneut versuchen',+ cutOff: 'Diese Antwort wurde abgeschnitten.',+ continueInPanel: 'In der Seitenleiste fortsetzen',},es: {askSelection: 'Añadir al chat',@@ -165,6 +175,8 @@ const STRINGS = Object.freeze({autoDetect: 'Detectar automáticamente',inlineFailed: 'No se pudo obtener una respuesta.',retry: 'Reintentar',+ cutOff: 'Esta respuesta se cortó.',+ continueInPanel: 'Continuar en el panel lateral',},fa: {askSelection: 'افزودن به چت',@@ -192,6 +204,8 @@ const STRINGS = Object.freeze({autoDetect: 'تشخیص خودکار',inlineFailed: 'دریافت پاسخ ممکن نشد.',retry: 'تلاش دوباره',+ cutOff: 'این پاسخ ناقص مانده است.',+ continueInPanel: 'ادامه در پنل کناری',},fr: {askSelection: 'Ajouter au chat',@@ -219,6 +233,8 @@ const STRINGS = Object.freeze({autoDetect: 'Détection automatique',inlineFailed: 'Impossible d’obtenir une réponse.',retry: 'Réessayer',+ cutOff: 'Cette réponse a été tronquée.',+ continueInPanel: 'Continuer dans le panneau latéral',},he: {askSelection: 'הוספה לצ׳אט',@@ -246,6 +262,8 @@ const STRINGS = Object.freeze({autoDetect: 'זיהוי אוטומטי',inlineFailed: 'לא ניתן היה לקבל תשובה.',retry: 'נסה שוב',+ cutOff: 'התשובה נקטעה.',+ continueInPanel: 'המשך בחלונית הצד',},hi: {askSelection: 'चैट में जोड़ें',@@ -273,6 +291,8 @@ const STRINGS = Object.freeze({autoDetect: 'स्वतः पहचानें',inlineFailed: 'उत्तर नहीं मिल सका।',retry: 'फिर से प्रयास करें',+ cutOff: 'यह उत्तर अधूरा रह गया।',+ continueInPanel: 'साइड पैनल में जारी रखें',},id: {askSelection: 'Tambahkan ke chat',@@ -300,6 +320,8 @@ const STRINGS = Object.freeze({autoDetect: 'Deteksi otomatis',inlineFailed: 'Tidak dapat memperoleh jawaban.',retry: 'Coba lagi',+ cutOff: 'Jawaban ini terpotong.',+ continueInPanel: 'Lanjutkan di panel samping',},ja: {askSelection: 'チャットに追加',@@ -327,6 +349,8 @@ const STRINGS = Object.freeze({autoDetect: '自動検出',inlineFailed: '回答を取得できませんでした。',retry: '再試行',+ cutOff: 'この回答は途中で切れています。',+ continueInPanel: 'サイドパネルで続ける',},ko: {askSelection: '채팅에 추가',@@ -354,6 +378,8 @@ const STRINGS = Object.freeze({autoDetect: '자동 감지',inlineFailed: '답변을 가져오지 못했습니다.',retry: '다시 시도',+ cutOff: '답변이 잘렸습니다.',+ continueInPanel: '사이드 패널에서 계속',},ms: {askSelection: 'Tambahkan pada sembang',@@ -381,6 +407,8 @@ const STRINGS = Object.freeze({autoDetect: 'Kesan automatik',inlineFailed: 'Tidak dapat mendapatkan jawapan.',retry: 'Cuba lagi',+ cutOff: 'Jawapan ini terpotong.',+ continueInPanel: 'Teruskan di panel sisi',},nl: {askSelection: 'Toevoegen aan chat',@@ -408,6 +436,8 @@ const STRINGS = Object.freeze({autoDetect: 'Automatisch detecteren',inlineFailed: 'Er kon geen antwoord worden opgehaald.',retry: 'Opnieuw proberen',+ cutOff: 'Dit antwoord is afgekapt.',+ continueInPanel: 'Verder in het zijpaneel',},pl: {askSelection: 'Dodaj do czatu',@@ -435,6 +465,8 @@ const STRINGS = Object.freeze({autoDetect: 'Wykryj automatycznie',inlineFailed: 'Nie udało się uzyskać odpowiedzi.',retry: 'Spróbuj ponownie',+ cutOff: 'Ta odpowiedź została ucięta.',+ continueInPanel: 'Kontynuuj w panelu bocznym',},pt: {askSelection: 'Adicionar ao chat',@@ -462,6 +494,8 @@ const STRINGS = Object.freeze({autoDetect: 'Detectar automaticamente',inlineFailed: 'Não foi possível obter uma resposta.',retry: 'Tentar novamente',+ cutOff: 'Esta resposta foi cortada.',+ continueInPanel: 'Continuar no painel lateral',},ru: {askSelection: 'Добавить в чат',@@ -489,6 +523,8 @@ const STRINGS = Object.freeze({autoDetect: 'Определить автоматически',inlineFailed: 'Не удалось получить ответ.',retry: 'Повторить',+ cutOff: 'Ответ обрезан.',+ continueInPanel: 'Продолжить в боковой панели',},th: {askSelection: 'เพิ่มไปยังแชท',@@ -516,6 +552,8 @@ const STRINGS = Object.freeze({autoDetect: 'ตรวจหาอัตโนมัติ',inlineFailed: 'ไม่สามารถรับคำตอบได้',retry: 'ลองอีกครั้ง',+ cutOff: 'คำตอบนี้ถูกตัดทอน',+ continueInPanel: 'ดำเนินการต่อในแผงด้านข้าง',},tl: {askSelection: 'Idagdag sa chat',@@ -543,6 +581,8 @@ const STRINGS = Object.freeze({autoDetect: 'Awtomatikong tukuyin',inlineFailed: 'Hindi makakuha ng sagot.',retry: 'Subukan muli',+ cutOff: 'Naputol ang sagot na ito.',+ continueInPanel: 'Ipagpatuloy sa side panel',},tr: {askSelection: 'Sohbete ekle',@@ -570,6 +610,8 @@ const STRINGS = Object.freeze({autoDetect: 'Otomatik algıla',inlineFailed: 'Yanıt alınamadı.',retry: 'Tekrar dene',+ cutOff: 'Bu yanıt yarıda kesildi.',+ continueInPanel: 'Yan panelde devam et',},uk: {askSelection: 'Додати до чату',@@ -597,6 +639,8 @@ const STRINGS = Object.freeze({autoDetect: 'Визначити автоматично',inlineFailed: 'Не вдалося отримати відповідь.',retry: 'Спробувати ще раз',+ cutOff: 'Відповідь обрізано.',+ continueInPanel: 'Продовжити в бічній панелі',},vi: {askSelection: 'Thêm vào cuộc trò chuyện',@@ -624,6 +668,8 @@ const STRINGS = Object.freeze({autoDetect: 'Tự động phát hiện',inlineFailed: 'Không thể nhận được câu trả lời.',retry: 'Thử lại',+ cutOff: 'Câu trả lời này bị cắt ngắn.',+ continueInPanel: 'Tiếp tục trong bảng bên',},});diff --git a/src/firefox/src/background.js b/src/firefox/src/background.jsindex b90742feb..a71f346ab 100644--- a/src/firefox/src/background.js+++ b/src/firefox/src/background.js@@ -69,6 +69,8 @@ import {buildFollowUpSelectionText,buildFullContextSelectionPrompt,buildInlineSelectionMessages,+ inlineAnswerWasCut,+ inlineSelectionMaxTokens,buildSelectionPrompt,normalizeSelectionAction,normalizeSelectionSourceGrounding,@@ -1511,11 +1513,17 @@ browser.runtime.onMessage.addListener((msg, _sender, sendResponse) => {// prompt builder keeps the selection inside the untrusted boundary and caps its// length, and the call goes through the normal cost allowance.const INLINE_SELECTION_TIMEOUT_MS = 90_000;+// Calls still in flight, keyed by the card's job id, so a card that is closed,+// retried or retargeted can cancel the paid request it no longer needs.+const inlineSelectionJobs = new Map();+const INLINE_JOB_ID_PATTERN = /^[a-z0-9]{8,64}$/;async function answerInlineSelection(msg) {const messages = buildInlineSelectionMessages(msg.selectionText, msg.action, msg.language);if (!messages) return { ok: false, error: 'Invalid selection request.' };const controller = new AbortController();+ const jobId = typeof msg.jobId === 'string' && INLINE_JOB_ID_PATTERN.test(msg.jobId) ? msg.jobId : '';+ if (jobId) inlineSelectionJobs.set(jobId, controller);const timer = setTimeout(() => controller.abort(new Error('The model took too long to answer.')),INLINE_SELECTION_TIMEOUT_MS,@@ -1523,18 +1531,24 @@ async function answerInlineSelection(msg) {try {if (providerManager.providers.size === 0) await providerManager.load();const provider = providerManager.getActive();+ // Sized to the selection and never above what the provider accepts; an answer+ // that still hits the ceiling is flagged so the card can offer the side panel+ // instead of presenting a cut-off translation as complete.+ const maxTokens = inlineSelectionMaxTokens(msg.selectionText, msg.action, provider?.maxOutputTokens);const result = await agent._chatWithCostAllowance(provider,messages,- { maxTokens: 2000, temperature: 0, signal: controller.signal },+ { maxTokens, temperature: 0, signal: controller.signal },agent._newCostRunState(),);const text = String(result?.content || '').trim();- return text ? { ok: true, text } : { ok: false, error: 'The model returned an empty answer.' };+ if (!text) return { ok: false, error: 'The model returned an empty answer.' };+ return inlineAnswerWasCut(result, maxTokens) ? { ok: true, text, truncated: true } : { ok: true, text };} catch (error) {return { ok: false, error: String(error?.message || error).slice(0, 300) };} finally {clearTimeout(timer);+ if (jobId && inlineSelectionJobs.get(jobId) === controller) inlineSelectionJobs.delete(jobId);}}@@ -1544,6 +1558,13 @@ browser.runtime.onMessage.addListener((msg, _sender, sendResponse) => {return true;});+browser.runtime.onMessage.addListener((msg, _sender, sendResponse) => {+ if (msg?.type !== 'WB_SELECTION_SHORTCUT_INLINE_CANCEL') return;+ const jobId = typeof msg.jobId === 'string' ? msg.jobId : '';+ inlineSelectionJobs.get(jobId)?.abort(new Error('The card was closed.'));+ sendResponse({ ok: true });+});+// Firefox does not treat a click in an injected page UI as an authorized// sidebarAction.open() gesture. Persist and notify the existing sidebar when// it is open; otherwise startup recovery will consume the prompt after thediff --git a/src/firefox/src/content/selection-shortcut.js b/src/firefox/src/content/selection-shortcut.jsindex 43eb8d2b1..232b018d8 100644--- a/src/firefox/src/content/selection-shortcut.js+++ b/src/firefox/src/content/selection-shortcut.js@@ -31,6 +31,7 @@: {};const LOCALIZATION_MESSAGE = 'WB_SELECTION_SHORTCUT_LOCALIZATION';const INLINE_MESSAGE = 'WB_SELECTION_SHORTCUT_INLINE';+ const INLINE_CANCEL_MESSAGE = 'WB_SELECTION_SHORTCUT_INLINE_CANCEL';const GAP = 8;const TOOLBAR_HEIGHT = 38;const POPUP_WIDTH = 316;@@ -53,6 +54,7 @@'proofread', 'humanize', 'translate', 'translateTo', 'askAbout','askQuestion', 'sendQuestion', 'includePageContext', 'hideShortcut', 'sentManual', 'sendFailed','more', 'askFollowUp', 'sendFollowUp', 'working', 'autoDetect', 'inlineFailed', 'retry',+ 'cutOff', 'continueInPanel',]);// English copy for strings the card shows before the localization bundle// arrives (or when the background cannot be reached).@@ -60,6 +62,8 @@translateTo: 'Translate to',autoDetect: 'Auto-detect',inlineFailed: 'Could not get an answer.',+ cutOff: 'This answer was cut off.',+ continueInPanel: 'Continue in side panel',});// Language codes the browser's detector reports that differ from ours.const DETECTED_LANGUAGE_ALIASES = Object.freeze({ iw: 'he', fil: 'tl', in: 'id' });@@ -84,6 +88,8 @@let cardSide = 'above';let cardOpener = null;let cardRequestId = 0;+ // Id of the model call the card is waiting on, so closing or redoing the card can cancel it.+ let cardJobId = '';let toolbarLeft = 0;let interfaceLanguage = resolveInterfaceLanguage('');let localization = null;@@ -223,6 +229,8 @@cardParts.target.setAttribute('aria-label', strings.translateTo);cardParts.skeleton.setAttribute('aria-label', strings.working);cardParts.retry.textContent = strings.retry;+ cardParts.cutText.textContent = strings.cutOff;+ cardParts.continueButton.textContent = strings.continueInPanel;populateTargetLanguages();renderCard();// Label widths change with the language, and the bar is centered on the selection.@@ -416,6 +424,15 @@color:var(--text); font-size:14px; font-weight:550; cursor:pointer;}.card-retry:hover { background:var(--hover); }+ .card-cut {+ display:flex; flex:none; flex-wrap:wrap; align-items:center; gap:6px 10px; margin-top:10px;+ color:var(--muted); font-size:13px; line-height:1.4;+ }+ .card-continue {+ padding:5px 11px; border:1px solid var(--border); border-radius:10px; background:transparent;+ color:var(--text); font-size:13px; font-weight:550; cursor:pointer;+ }+ .card-continue:hover { background:var(--hover); }.followup {display:flex; flex:none; align-items:center; gap:8px; margin-top:12px;padding:5px 5px 5px 14px; border-radius:16px; background:var(--field);@@ -542,6 +559,10 @@<button class="card-retry" type="button">Try again</button></div></div>+ <div class="card-cut" hidden>+ <span class="card-cut-text">This answer was cut off.</span>+ <button class="card-continue" type="button">Continue in side panel</button>+ </div><div class="followup"><input class="followup-input" type="text" maxlength="2000" aria-label="Ask a follow-up" placeholder="Ask a follow-up"><button class="followup-send" type="button" aria-label="Send follow-up" disabled>@@ -572,6 +593,9 @@errorText: shadow.querySelector('.card-error-text'),errorDetail: shadow.querySelector('.card-error-detail'),retry: shadow.querySelector('.card-retry'),+ cut: shadow.querySelector('.card-cut'),+ cutText: shadow.querySelector('.card-cut-text'),+ continueButton: shadow.querySelector('.card-continue'),followUp: shadow.querySelector('.followup-input'),send: shadow.querySelector('.followup-send'),};@@ -609,6 +633,9 @@cardParts.retry.addEventListener('click', (event) => {if (event.isTrusted) runInline();});+ cardParts.continueButton.addEventListener('click', (event) => {+ if (event.isTrusted) continueInPanel();+ });cardParts.followUp.addEventListener('input', () => {cardParts.send.disabled = !cardParts.followUp.value.trim();});@@ -896,6 +923,7 @@parts.skeleton.hidden = status !== 'loading';parts.text.hidden = status !== 'ready';parts.error.hidden = status !== 'error';+ parts.cut.hidden = !(status === 'ready' && cardState.truncated);if (status === 'ready') renderAnswer(parts.text, cardState.text, kind !== 'translate');if (status === 'error') {parts.errorText.textContent = str('inlineFailed');@@ -908,8 +936,12 @@async function openCard(kind, opener) {if (!snapshot || submitting || !INLINE_ACTIONS.includes(kind)) return;+ // Claim the card before anything is awaited: a second click while the+ // localization loads takes a newer id, so this call stops instead of opening+ // a second card and starting a second paid request.+ const requestId = ++cardRequestId;if (!localization) await refreshLocalization(interfaceLanguage);- if (!snapshot || submitting) return;+ if (requestId !== cardRequestId || !snapshot || submitting) return;if (snapshot.text.length > INLINE_MAX_CHARS) {// Too long for a card: the side panel is the better place to read it.submitSelection(kind, '', interfaceLanguage);@@ -918,7 +950,6 @@ensureSurface();applyLocalization();closePopup(false);- const requestId = ++cardRequestId;cardOpener = opener || null;cardState = {kind,@@ -927,6 +958,7 @@sourceLabel: '',quote: kind === 'translate' ? snapshot.text : '',text: '',+ truncated: false,error: '',};cardParts.followUp.value = '';@@ -956,29 +988,54 @@runInline();}+ function newInlineJobId() {+ const bytes = new Uint8Array(12);+ crypto.getRandomValues(bytes);+ return Array.from(bytes, (byte) => (byte % 36).toString(36)).join('');+ }++ // Tell the background to stop the model call the card no longer needs.+ function cancelInline() {+ const jobId = cardJobId;+ cardJobId = '';+ if (!jobId) return;+ try {+ Promise.resolve(api.runtime.sendMessage({ type: INLINE_CANCEL_MESSAGE, jobId })).catch(() => {});+ } catch { /* The call ends on its own timeout if the background is unreachable. */ }+ }+async function runInline() {if (!cardState || !snapshot) return;+ // Retrying or retargeting replaces the call that is still running.+ cancelInline();const requestId = ++cardRequestId;+ const jobId = newInlineJobId();+ cardJobId = jobId;const { kind, target } = cardState;const selectionText = snapshot.text;cardState.status = 'loading';cardState.text = '';+ cardState.truncated = false;cardState.error = '';renderCard();try {const response = await api.runtime.sendMessage({type: INLINE_MESSAGE,+ jobId,action: kind,selectionText,language: kind === 'translate' ? target : interfaceLanguage,});if (requestId !== cardRequestId || !cardState) return;+ cardJobId = '';const answer = typeof response?.text === 'string' ? response.text.trim() : '';if (!response?.ok || !answer) throw new Error(typeof response?.error === 'string' ? response.error : '');cardState.status = 'ready';cardState.text = answer;+ cardState.truncated = response.truncated === true;} catch (error) {if (requestId !== cardRequestId || !cardState) return;+ cardJobId = '';cardState.status = 'error';cardState.error = String(error?.message || '').slice(0, 300);}@@ -997,8 +1054,16 @@});}- // Forget the card without touching the bar; a request still in flight is ignored.+ // A cut-off answer is finished in the side panel, where the reply is not capped.+ function continueInPanel() {+ if (!cardState || cardState.status !== 'ready') return;+ const { kind, target } = cardState;+ submitSelection(kind, '', kind === 'translate' ? target : interfaceLanguage);+ }++ // Forget the card without touching the bar; a request still in flight is cancelled and ignored.function resetCard() {+ cancelInline();cardRequestId += 1;cardState = null;cardOpener = null;@@ -1034,6 +1099,7 @@function destroySurface() {hideToast();+ cancelInline();cardRequestId += 1;host?.remove();host = shadow = highlightLayer = shortcut = moreButton = popup = question = includePageContext = sendButton = toast = null;@@ -1230,6 +1296,10 @@followUpRect: card && !card.hidden ? rectOf('.followup') : null,followUpSendRect: card && !card.hidden ? rectOf('.followup-send') : null,retryRect: cardParts && !cardParts.error.hidden ? rectOf('.card-retry') : null,+ cardTruncated: cardState?.truncated === true,+ cutNoticeText: cardParts && !cardParts.cut.hidden ? cardParts.cutText.textContent : '',+ continueRect: cardParts && !cardParts.cut.hidden ? rectOf('.card-continue') : null,+ continueLabel: cardParts && !cardParts.cut.hidden ? cardParts.continueButton.textContent : '',followUpPlaceholder: cardParts?.followUp.placeholder || '',followUpValue: cardParts?.followUp.value || '',followUpSendDisabled: cardParts ? cardParts.send.disabled : true,diff --git a/src/firefox/src/context-menu-storage.js b/src/firefox/src/context-menu-storage.jsindex b09464e15..3bb0408be 100644--- a/src/firefox/src/context-menu-storage.js+++ b/src/firefox/src/context-menu-storage.js@@ -263,6 +263,47 @@ export function buildInlineSelectionMessages(selectionText, action, language = '];}+// How many output tokens a card answer may need. Translate and Proofread hand the+// whole text back, so they scale with the selection (CJK and Indic scripts can take+// one to two tokens per character on either side of a translation); Explain stays+// short. The request never exceeds what the provider says it will accept.+export const INLINE_ANSWER_MIN_TOKENS = 2000;+export const INLINE_ANSWER_MAX_TOKENS = 8000;+const INLINE_FALLBACK_OUTPUT_CEILING = 4096;++export function inlineSelectionMaxTokens(selectionText, action, providerCeiling) {+ const chars = String(selectionText || '').trim().length;+ const wanted = String(action || '').trim() === 'explain'+ ? INLINE_ANSWER_MIN_TOKENS+ : Math.max(INLINE_ANSWER_MIN_TOKENS, Math.min(INLINE_ANSWER_MAX_TOKENS, chars * 2));+ const limit = Math.floor(Number(providerCeiling));+ return Math.min(wanted, limit > 0 ? limit : INLINE_FALLBACK_OUTPUT_CEILING);+}++// Whether the model stopped because it ran out of output budget. Providers report+// this in different places (a normalized finishReason, Anthropic's raw stop_reason,+// OpenAI's choices[0].finish_reason, a Responses-API incomplete status). A reported+// reason is trusted either way; the token count is only a fallback for providers+// that report none.+const INLINE_CUT_REASONS = new Set(['length', 'max_tokens', 'max_output_tokens', 'max_completion_tokens']);++export function inlineAnswerWasCut(result, maxTokens) {+ const raw = result?.raw;+ const reason = [+ result?.finishReason,+ result?.stopReason,+ raw?.stop_reason,+ raw?.stopReason,+ raw?.choices?.[0]?.finish_reason,+ raw?.candidates?.[0]?.finishReason,+ raw?.incomplete_details?.reason,+ ].map((value) => String(value ?? '').trim().toLowerCase()).find(Boolean);+ if (reason) return INLINE_CUT_REASONS.has(reason);+ const used = Number(result?.usage?.completion_tokens ?? result?.usage?.output_tokens);+ return Number.isFinite(used) && Number.isFinite(maxTokens) && maxTokens > 0+ && used >= Math.floor(maxTokens * 0.98);+}+const INLINE_FOLLOW_UP_LABELS = Object.freeze({translate: 'translation',explain: 'explanation',diff --git a/src/firefox/src/selection-shortcut-i18n.js b/src/firefox/src/selection-shortcut-i18n.jsindex ef1306e8a..43f154fbd 100644--- a/src/firefox/src/selection-shortcut-i18n.js+++ b/src/firefox/src/selection-shortcut-i18n.js@@ -30,6 +30,8 @@ const STRINGS = Object.freeze({autoDetect: 'Auto-detect',inlineFailed: 'Could not get an answer.',retry: 'Try again',+ cutOff: 'This answer was cut off.',+ continueInPanel: 'Continue in side panel',},zh: {askSelection: '添加到聊天',@@ -57,6 +59,8 @@ const STRINGS = Object.freeze({autoDetect: '自动检测',inlineFailed: '无法获取回答。',retry: '重试',+ cutOff: '此回答被截断了。',+ continueInPanel: '在侧边栏继续',},ar: {askSelection: 'إضافة إلى الدردشة',@@ -84,6 +88,8 @@ const STRINGS = Object.freeze({autoDetect: 'اكتشاف تلقائي',inlineFailed: 'تعذر الحصول على إجابة.',retry: 'حاول مرة أخرى',+ cutOff: 'تم اقتطاع هذه الإجابة.',+ continueInPanel: 'المتابعة في اللوحة الجانبية',},bn: {askSelection: 'চ্যাটে যোগ করুন',@@ -111,6 +117,8 @@ const STRINGS = Object.freeze({autoDetect: 'স্বয়ংক্রিয় শনাক্তকরণ',inlineFailed: 'উত্তর পাওয়া যায়নি।',retry: 'আবার চেষ্টা করুন',+ cutOff: 'এই উত্তরটি কেটে গেছে।',+ continueInPanel: 'সাইড প্যানেলে চালিয়ে যান',},de: {askSelection: 'Zum Chat hinzufügen',@@ -138,6 +146,8 @@ const STRINGS = Object.freeze({autoDetect: 'Automatisch erkennen',inlineFailed: 'Es konnte keine Antwort abgerufen werden.',retry: 'Erneut versuchen',+ cutOff: 'Diese Antwort wurde abgeschnitten.',+ continueInPanel: 'In der Seitenleiste fortsetzen',},es: {askSelection: 'Añadir al chat',@@ -165,6 +175,8 @@ const STRINGS = Object.freeze({autoDetect: 'Detectar automáticamente',inlineFailed: 'No se pudo obtener una respuesta.',retry: 'Reintentar',+ cutOff: 'Esta respuesta se cortó.',+ continueInPanel: 'Continuar en el panel lateral',},fa: {askSelection: 'افزودن به چت',@@ -192,6 +204,8 @@ const STRINGS = Object.freeze({autoDetect: 'تشخیص خودکار',inlineFailed: 'دریافت پاسخ ممکن نشد.',retry: 'تلاش دوباره',+ cutOff: 'این پاسخ ناقص مانده است.',+ continueInPanel: 'ادامه در پنل کناری',},fr: {askSelection: 'Ajouter au chat',@@ -219,6 +233,8 @@ const STRINGS = Object.freeze({autoDetect: 'Détection automatique',inlineFailed: 'Impossible d’obtenir une réponse.',retry: 'Réessayer',+ cutOff: 'Cette réponse a été tronquée.',+ continueInPanel: 'Continuer dans le panneau latéral',},he: {askSelection: 'הוספה לצ׳אט',@@ -246,6 +262,8 @@ const STRINGS = Object.freeze({autoDetect: 'זיהוי אוטומטי',inlineFailed: 'לא ניתן היה לקבל תשובה.',retry: 'נסה שוב',+ cutOff: 'התשובה נקטעה.',+ continueInPanel: 'המשך בחלונית הצד',},hi: {askSelection: 'चैट में जोड़ें',@@ -273,6 +291,8 @@ const STRINGS = Object.freeze({autoDetect: 'स्वतः पहचानें',inlineFailed: 'उत्तर नहीं मिल सका।',retry: 'फिर से प्रयास करें',+ cutOff: 'यह उत्तर अधूरा रह गया।',+ continueInPanel: 'साइड पैनल में जारी रखें',},id: {askSelection: 'Tambahkan ke chat',@@ -300,6 +320,8 @@ const STRINGS = Object.freeze({autoDetect: 'Deteksi otomatis',inlineFailed: 'Tidak dapat memperoleh jawaban.',retry: 'Coba lagi',+ cutOff: 'Jawaban ini terpotong.',+ continueInPanel: 'Lanjutkan di panel samping',},ja: {askSelection: 'チャットに追加',@@ -327,6 +349,8 @@ const STRINGS = Object.freeze({autoDetect: '自動検出',inlineFailed: '回答を取得できませんでした。',retry: '再試行',+ cutOff: 'この回答は途中で切れています。',+ continueInPanel: 'サイドパネルで続ける',},ko: {askSelection: '채팅에 추가',@@ -354,6 +378,8 @@ const STRINGS = Object.freeze({autoDetect: '자동 감지',inlineFailed: '답변을 가져오지 못했습니다.',retry: '다시 시도',+ cutOff: '답변이 잘렸습니다.',+ continueInPanel: '사이드 패널에서 계속',},ms: {askSelection: 'Tambahkan pada sembang',@@ -381,6 +407,8 @@ const STRINGS = Object.freeze({autoDetect: 'Kesan automatik',inlineFailed: 'Tidak dapat mendapatkan jawapan.',retry: 'Cuba lagi',+ cutOff: 'Jawapan ini terpotong.',+ continueInPanel: 'Teruskan di panel sisi',},nl: {askSelection: 'Toevoegen aan chat',@@ -408,6 +436,8 @@ const STRINGS = Object.freeze({autoDetect: 'Automatisch detecteren',inlineFailed: 'Er kon geen antwoord worden opgehaald.',retry: 'Opnieuw proberen',+ cutOff: 'Dit antwoord is afgekapt.',+ continueInPanel: 'Verder in het zijpaneel',},pl: {askSelection: 'Dodaj do czatu',@@ -435,6 +465,8 @@ const STRINGS = Object.freeze({autoDetect: 'Wykryj automatycznie',inlineFailed: 'Nie udało się uzyskać odpowiedzi.',retry: 'Spróbuj ponownie',+ cutOff: 'Ta odpowiedź została ucięta.',+ continueInPanel: 'Kontynuuj w panelu bocznym',},pt: {askSelection: 'Adicionar ao chat',@@ -462,6 +494,8 @@ const STRINGS = Object.freeze({autoDetect: 'Detectar automaticamente',inlineFailed: 'Não foi possível obter uma resposta.',retry: 'Tentar novamente',+ cutOff: 'Esta resposta foi cortada.',+ continueInPanel: 'Continuar no painel lateral',},ru: {askSelection: 'Добавить в чат',@@ -489,6 +523,8 @@ const STRINGS = Object.freeze({autoDetect: 'Определить автоматически',inlineFailed: 'Не удалось получить ответ.',retry: 'Повторить',+ cutOff: 'Ответ обрезан.',+ continueInPanel: 'Продолжить в боковой панели',},th: {askSelection: 'เพิ่มไปยังแชท',@@ -516,6 +552,8 @@ const STRINGS = Object.freeze({autoDetect: 'ตรวจหาอัตโนมัติ',inlineFailed: 'ไม่สามารถรับคำตอบได้',retry: 'ลองอีกครั้ง',+ cutOff: 'คำตอบนี้ถูกตัดทอน',+ continueInPanel: 'ดำเนินการต่อในแผงด้านข้าง',},tl: {askSelection: 'Idagdag sa chat',@@ -543,6 +581,8 @@ const STRINGS = Object.freeze({autoDetect: 'Awtomatikong tukuyin',inlineFailed: 'Hindi makakuha ng sagot.',retry: 'Subukan muli',+ cutOff: 'Naputol ang sagot na ito.',+ continueInPanel: 'Ipagpatuloy sa side panel',},tr: {askSelection: 'Sohbete ekle',@@ -570,6 +610,8 @@ const STRINGS = Object.freeze({autoDetect: 'Otomatik algıla',inlineFailed: 'Yanıt alınamadı.',retry: 'Tekrar dene',+ cutOff: 'Bu yanıt yarıda kesildi.',+ continueInPanel: 'Yan panelde devam et',},uk: {askSelection: 'Додати до чату',@@ -597,6 +639,8 @@ const STRINGS = Object.freeze({autoDetect: 'Визначити автоматично',inlineFailed: 'Не вдалося отримати відповідь.',retry: 'Спробувати ще раз',+ cutOff: 'Відповідь обрізано.',+ continueInPanel: 'Продовжити в бічній панелі',},vi: {askSelection: 'Thêm vào cuộc trò chuyện',@@ -624,6 +668,8 @@ const STRINGS = Object.freeze({autoDetect: 'Tự động phát hiện',inlineFailed: 'Không thể nhận được câu trả lời.',retry: 'Thử lại',+ cutOff: 'Câu trả lời này bị cắt ngắn.',+ continueInPanel: 'Tiếp tục trong bảng bên',},});diff --git a/test/fixtures/run.mjs b/test/fixtures/run.mjsindex 4c844960b..74da3b824 100644--- a/test/fixtures/run.mjs+++ b/test/fixtures/run.mjs@@ -363,7 +363,7 @@ async function collectSmd(page, mode = 'auto') {}, mode);}-async function setupSelectionShortcut(page, sourcePath, { enabled = true, requiresManualOpen = false, locale = 'en', promiseDetect = false } = {}) {+async function setupSelectionShortcut(page, sourcePath, { enabled = true, requiresManualOpen = false, locale = 'en', promiseDetect = false, holdLocalization = false } = {}) {await page.setViewportSize({ width: 360, height: 280 });await page.setContent(`<!doctype html><style>body{margin:0;font:18px/1.5 sans-serif} #copy{position:absolute;right:2px;bottom:2px;width:210px}</style>@@ -372,6 +372,9 @@ async function setupSelectionShortcut(page, sourcePath, { enabled = true, requirawait page.addScriptTag({ content: `window.__selectionMessages = [];window.__selectionInlineMessages = [];+ window.__selectionCancelMessages = [];+ window.__selectionLocalizationRequests = 0;+ window.__selectionLocalizationGate = ${holdLocalization ? 'new Promise((resolve) => { window.__releaseLocalization = resolve; })' : 'null'};window.__selectionDetectedLanguage = '';window.__selectionInlineHandler = async (message) => ({ok: true,@@ -385,6 +388,8 @@ async function setupSelectionShortcut(page, sourcePath, { enabled = true, requirruntime: {sendMessage: async (message) => {if (message.type === 'WB_SELECTION_SHORTCUT_LOCALIZATION') {+ window.__selectionLocalizationRequests += 1;+ if (window.__selectionLocalizationGate) await window.__selectionLocalizationGate;const locale = String(message.locale || 'en').toLowerCase().split('-')[0];return { ok: true, ...(window.__selectionLocalizations[locale] || window.__selectionLocalizations.en) };}@@ -392,6 +397,10 @@ async function setupSelectionShortcut(page, sourcePath, { enabled = true, requirwindow.__selectionInlineMessages.push(message);return window.__selectionInlineHandler(message);}+ if (message.type === 'WB_SELECTION_SHORTCUT_INLINE_CANCEL') {+ window.__selectionCancelMessages.push(message);+ return { ok: true };+ }window.__selectionMessages.push(message);return { ok: true, queued: true, requiresManualOpen: ${requiresManualOpen ? 'true' : 'false'} };},@@ -2239,6 +2248,116 @@ for (const [label, sourcePath, manualOpen] of [}});+ test(`${label}: a double click while the language bundle loads starts one card and one model call`, async (page) => {+ await setupSelectionShortcut(page, sourcePath, { requiresManualOpen: manualOpen, holdLocalization: true });+ const selected = await selectFixtureText(page);+ await clickRectCenter(page, selected.inlineRects.explain);+ await clickRectCenter(page, selected.inlineRects.explain);+ // The start-up request plus one per click are now waiting on the held bundle.+ await page.waitForFunction(() => window.__selectionLocalizationRequests >= 3);+ await page.evaluate(() => window.__releaseLocalization());+ await waitForCardStatus(page, 'ready');+ await page.waitForTimeout(60);+ const result = await page.evaluate(() => ({+ inline: window.__selectionInlineMessages.length,+ cancels: window.__selectionCancelMessages.length,+ state: window.__webbrainSelectionShortcut.getState(),+ }));+ if (result.inline !== 1 || result.cancels !== 0 || !result.state.cardVisible || result.state.cardText !== 'Mock explain answer for en') {+ throw new Error(`a double click opened more than one paid request: ${JSON.stringify(result)}`);+ }+ });++ test(`${label}: closing, retargeting or retrying a card cancels the call it abandons`, async (page) => {+ await setupSelectionShortcut(page, sourcePath, { requiresManualOpen: manualOpen });+ await page.evaluate(() => {+ window.__selectionInlineHandler = () => new Promise(() => {});+ });+ await openInlineCard(page, 'explain');+ await page.waitForFunction(() => window.__selectionInlineMessages.length === 1);+ let result = await page.evaluate(() => ({+ inline: window.__selectionInlineMessages, cancels: window.__selectionCancelMessages,+ }));+ const firstId = result.inline[0].jobId;+ if (!/^[a-z0-9]{8,64}$/.test(firstId) || result.cancels.length !== 0) {+ throw new Error(`a running card should carry a well-formed job id and nothing to cancel yet: ${JSON.stringify(result)}`);+ }+ await page.keyboard.press('Escape');+ await page.waitForFunction(() => window.__selectionCancelMessages.length === 1);+ result = await page.evaluate(() => window.__selectionCancelMessages);+ if (result[0].jobId !== firstId) {+ throw new Error(`closing the card should cancel its own call: ${JSON.stringify({ firstId, result })}`);+ }++ // Retargeting a Translate card replaces the running call with a new one.+ await openInlineCard(page, 'translate');+ await page.waitForFunction(() => window.__selectionInlineMessages.length === 2);+ await page.evaluate(() => window.__webbrainSelectionShortcut.chooseTarget('de'));+ await page.waitForFunction(() => window.__selectionInlineMessages.length === 3);+ result = await page.evaluate(() => ({+ ids: window.__selectionInlineMessages.map((message) => message.jobId),+ cancels: window.__selectionCancelMessages.map((message) => message.jobId),+ }));+ if (new Set(result.ids).size !== 3 || result.cancels.length !== 2 || result.cancels[1] !== result.ids[1]) {+ throw new Error(`a new target should cancel the call it replaces and use a fresh id: ${JSON.stringify(result)}`);+ }++ // Closing mid-flight cancels the third call too, but a call that already finished has nothing to cancel.+ await page.evaluate(() => {+ window.__selectionInlineHandler = async () => ({ ok: true, text: 'Done' });+ });+ await page.keyboard.press('Escape');+ await page.waitForFunction(() => window.__selectionCancelMessages.length === 3);+ await openInlineCard(page, 'proofread');+ await waitForCardStatus(page, 'ready');+ await page.keyboard.press('Escape');+ await page.waitForTimeout(60);+ const cancels = await page.evaluate(() => window.__selectionCancelMessages.length);+ if (cancels !== 3) throw new Error(`closing a finished card should not send a cancel: ${cancels}`);+ });++ test(`${label}: a cut-off card answer says so and continues in the side panel`, async (page) => {+ await setupSelectionShortcut(page, sourcePath, { requiresManualOpen: manualOpen, locale: 'zh' });+ await page.evaluate(() => {+ window.__selectionInlineHandler = async (message) => ({+ ok: true,+ text: 'Partial ' + message.action + ' answer',+ truncated: message.action === 'translate',+ });+ });+ const zh = await page.evaluate(() => window.__selectionLocalizations.zh.strings);+ await openInlineCard(page, 'translate');+ await page.evaluate(() => window.__webbrainSelectionShortcut.chooseTarget('de'));+ let state = await waitForCardStatus(page, 'ready');+ await page.waitForFunction(() => window.__webbrainSelectionShortcut.getState().cardTruncated);+ state = await page.evaluate(() => window.__webbrainSelectionShortcut.getState());+ if (state.cutNoticeText !== zh.cutOff || !state.continueRect || state.cardText !== 'Partial translate answer') {+ throw new Error(`a capped answer should be flagged in the interface language: ${JSON.stringify({ state, zh: zh.cutOff })}`);+ }+ if (state.continueLabel !== zh.continueInPanel) {+ throw new Error(`the continue button should be localized: ${state.continueLabel}`);+ }+ await clickRectCenter(page, state.continueRect);+ await page.waitForFunction(() => window.__selectionMessages.length === 1);+ const handoff = await page.evaluate(() => ({+ message: window.__selectionMessages[0],+ cancels: window.__selectionCancelMessages.length,+ state: window.__webbrainSelectionShortcut.getState(),+ }));+ if (handoff.message.action !== 'translate' || handoff.message.language !== 'de'+ || !/Selected words near the viewport edge/.test(handoff.message.selectionText)+ || handoff.state.cardVisible || handoff.cancels > 1) {+ throw new Error(`continuing should hand the same translation to the side panel: ${JSON.stringify(handoff)}`);+ }++ // A complete answer shows no notice.+ await openInlineCard(page, 'explain');+ state = await waitForCardStatus(page, 'ready');+ if (state.cardTruncated || state.continueRect || state.cutNoticeText) {+ throw new Error(`a complete answer must not look cut off: ${JSON.stringify(state)}`);+ }+ });+test(`${label}: an older Translate answer never replaces a newer one`, async (page) => {await setupSelectionShortcut(page, sourcePath, { requiresManualOpen: manualOpen });await page.evaluate(() => {diff --git a/test/run.js b/test/run.jsindex 110bba4cd..dec5e01e9 100644--- a/test/run.js+++ b/test/run.js@@ -689,8 +689,12 @@ const { historyTextFromElement: historyTextFromElementFx } = await import();const {CONTEXT_MENU_CLAIM_LEASE_MS: CONTEXT_MENU_CLAIM_LEASE_MS_CH,+ INLINE_ANSWER_MAX_TOKENS: INLINE_ANSWER_MAX_TOKENS_CH,+ INLINE_ANSWER_MIN_TOKENS: INLINE_ANSWER_MIN_TOKENS_CH,INLINE_SELECTION_ACTIONS: INLINE_SELECTION_ACTIONS_CH,INLINE_SELECTION_MAX_CHARS: INLINE_SELECTION_MAX_CHARS_CH,+ inlineAnswerWasCut: inlineAnswerWasCutCh,+ inlineSelectionMaxTokens: inlineSelectionMaxTokensCh,buildFollowUpSelectionText: buildFollowUpSelectionTextCh,buildInlineSelectionMessages: buildInlineSelectionMessagesCh,SELECTION_CONTEXT_SOURCE_GROUNDING: SELECTION_CONTEXT_SOURCE_GROUNDING_CH,@@ -706,8 +710,12 @@ const {);const {CONTEXT_MENU_CLAIM_LEASE_MS: CONTEXT_MENU_CLAIM_LEASE_MS_FX,+ INLINE_ANSWER_MAX_TOKENS: INLINE_ANSWER_MAX_TOKENS_FX,+ INLINE_ANSWER_MIN_TOKENS: INLINE_ANSWER_MIN_TOKENS_FX,INLINE_SELECTION_ACTIONS: INLINE_SELECTION_ACTIONS_FX,INLINE_SELECTION_MAX_CHARS: INLINE_SELECTION_MAX_CHARS_FX,+ inlineAnswerWasCut: inlineAnswerWasCutFx,+ inlineSelectionMaxTokens: inlineSelectionMaxTokensFx,buildFollowUpSelectionText: buildFollowUpSelectionTextFx,buildInlineSelectionMessages: buildInlineSelectionMessagesFx,SELECTION_CONTEXT_SOURCE_GROUNDING: SELECTION_CONTEXT_SOURCE_GROUNDING_FX,@@ -51620,9 +51628,9 @@ test('selection shortcut localizations cover every interface locale with browser];const expectedKeys = ['addSelectionToChat', 'askAbout', 'askFollowUp', 'askHighlightedText', 'askQuestion', 'askSelection', 'autoDetect',- 'explain', 'hideShortcut', 'humanize', 'includePageContext', 'inlineFailed', 'more', 'openChat', 'proofread',- 'quiz', 'retry', 'sendFailed', 'sendFollowUp', 'sendQuestion', 'sentManual', 'summarize', 'translate',- 'translateTo', 'working',+ 'continueInPanel', 'cutOff', 'explain', 'hideShortcut', 'humanize', 'includePageContext', 'inlineFailed', 'more',+ 'openChat', 'proofread', 'quiz', 'retry', 'sendFailed', 'sendFollowUp', 'sendQuestion', 'sentManual', 'summarize',+ 'translate', 'translateTo', 'working',].sort();for (const [label, locales, getLocalization, normalizeLocale] of [@@ -51740,13 +51748,87 @@ test('inline card answers are one tool-less, bounded model call behind validatedconst body = background.slice(start, background.indexOf('\n}\n', start));assert.match(body, /buildInlineSelectionMessages\(msg\.selectionText, msg\.action, msg\.language\)/, `${prefix}: the prompt comes from the validated builder`);assert.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: 2000, temperature: 0, signal: controller\.signal \},\s*agent\._newCostRunState\(\),/, `${prefix}: the call is bounded, abortable and goes through the cost allowance`);+ 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\);/, `${prefix}: the budget is sized to the selection and the provider's ceiling`);+ assert.match(body, /inlineAnswerWasCut\(result, maxTokens\) \? \{ ok: true, text, truncated: true \}/, `${prefix}: a capped answer is flagged instead of passing as complete`);++ // A card that is closed, retried or retargeted cancels the paid call it no longer needs.+ assert.match(body, /const jobId = typeof msg\.jobId === 'string' && INLINE_JOB_ID_PATTERN\.test\(msg\.jobId\) \? msg\.jobId : '';\s*if \(jobId\) inlineSelectionJobs\.set\(jobId, controller\);/, `${prefix}: only well-formed job ids are tracked`);+ assert.match(body, /finally \{[^}]*inlineSelectionJobs\.get\(jobId\) === controller\) inlineSelectionJobs\.delete\(jobId\);/, `${prefix}: a finished job leaves the table`);+ assert.match(background, /if \(msg\?\.type !== 'WB_SELECTION_SHORTCUT_INLINE_CANCEL'\) return;[^}]*inlineSelectionJobs\.get\(jobId\)\?\.abort\(/, `${prefix}: a cancel message aborts the tracked call`);+ assert.match(content, /const INLINE_CANCEL_MESSAGE = 'WB_SELECTION_SHORTCUT_INLINE_CANCEL';/, `${prefix}: the card uses the cancel message the background listens for`);assert.doesNotMatch(body, /\btools\b|toolDefs|tool_choice/, `${prefix}: an in-page answer must not have tools`);assert.match(body, /controller\.abort\(/, `${prefix}: a hung provider must time out`);assert.match(body, /finally \{\s*clearTimeout\(timer\);/, `${prefix}: the timeout timer is always cleared`);}});+test('inline card token budget follows the selection and never exceeds the provider ceiling', () => {+ for (const [label, min, max, budget] of [+ ['chrome', INLINE_ANSWER_MIN_TOKENS_CH, INLINE_ANSWER_MAX_TOKENS_CH, inlineSelectionMaxTokensCh],+ ['firefox', INLINE_ANSWER_MIN_TOKENS_FX, INLINE_ANSWER_MAX_TOKENS_FX, inlineSelectionMaxTokensFx],+ ]) {+ assert.equal(min, 2000, `${label}: short answers keep the original budget`);+ assert.equal(max, 8000, `${label}: the budget has a hard upper bound`);+ assert.equal(budget('a short phrase', 'translate', 16_000), min, `${label}: a short translation uses the floor`);+ assert.equal(budget('x'.repeat(1500), 'translate', 16_000), 3000, `${label}: a long translation gets room for roughly two tokens per character`);+ assert.equal(budget('x'.repeat(1500), 'proofread', 16_000), 3000, `${label}: proofreading rewrites the whole selection too`);+ assert.equal(budget('x'.repeat(6000), 'translate', 64_000), max, `${label}: the budget never passes the upper bound`);+ assert.equal(budget('x'.repeat(6000), 'explain', 64_000), min, `${label}: an explanation does not grow with the selection`);+ assert.equal(budget('x'.repeat(6000), 'translate', 2048), 2048, `${label}: a small-output model caps the request, which it would otherwise reject`);+ assert.equal(budget('x'.repeat(1500), 'translate', undefined), 3000, `${label}: an unknown ceiling falls back to a safe default`);+ assert.equal(budget('x'.repeat(6000), 'translate', undefined), 4096, `${label}: the fallback ceiling stays conservative`);+ assert.equal(budget('x'.repeat(6000), 'translate', 'junk'), 4096, `${label}: a non-numeric ceiling is ignored`);+ }+});++test('inline card detects an answer that stopped at the output cap on every provider shape', () => {+ for (const [label, wasCut] of [['chrome', inlineAnswerWasCutCh], ['firefox', inlineAnswerWasCutFx]]) {+ assert.equal(wasCut({ content: 'x', finishReason: 'length' }, 2000), true, `${label}: OpenAI-style length stop`);+ assert.equal(wasCut({ content: 'x', raw: { stop_reason: 'max_tokens' } }, 2000), true, `${label}: Anthropic max_tokens stop`);+ assert.equal(wasCut({ content: 'x', raw: { choices: [{ finish_reason: 'length' }] } }, 2000), true, `${label}: raw chat completion`);+ assert.equal(wasCut({ content: 'x', raw: { candidates: [{ finishReason: 'MAX_TOKENS' }] } }, 2000), true, `${label}: Gemini stop is case-insensitive`);+ assert.equal(wasCut({ content: 'x', raw: { incomplete_details: { reason: 'max_output_tokens' } } }, 2000), true, `${label}: Responses API incomplete`);+ assert.equal(wasCut({ content: 'x', finishReason: 'stop', usage: { completion_tokens: 2000 } }, 2000), false, `${label}: an explicit natural stop wins over a coincidental token count`);+ assert.equal(wasCut({ content: 'x', raw: { stop_reason: 'end_turn' } }, 2000), false, `${label}: Anthropic natural stop`);+ assert.equal(wasCut({ content: 'x', usage: { completion_tokens: 1990 } }, 2000), true, `${label}: no stop reason but the usage sits at the cap`);+ assert.equal(wasCut({ content: 'x', usage: { output_tokens: 2000 } }, 2000), true, `${label}: output_tokens is read too`);+ assert.equal(wasCut({ content: 'x', usage: { completion_tokens: 400 } }, 2000), false, `${label}: a short answer is complete`);+ assert.equal(wasCut({ content: 'x' }, 2000), false, `${label}: no signal at all is treated as complete`);+ assert.equal(wasCut(null, 2000), false, `${label}: a missing result is not a cut-off`);+ }+});++test('inline card claims its request before waiting, cancels what it abandons and finishes cut-off answers in the panel', () => {+ for (const prefix of ['src/chrome', 'src/firefox']) {+ const content = fs.readFileSync(path.join(ROOT, prefix, 'src/content/selection-shortcut.js'), 'utf8');+ const body = (name, next) => content.slice(content.indexOf(name), content.indexOf(next, content.indexOf(name)));++ // Double click while the localization bundle loads: the later click owns the card.+ const open = body('async function openCard(kind, opener) {', 'async function runInline()');+ assert.ok(+ open.indexOf('const requestId = ++cardRequestId;') < open.indexOf('await refreshLocalization('),+ `${prefix}: the card must claim its request id before the first await`,+ );+ assert.match(open, /await refreshLocalization\(interfaceLanguage\);\s*if \(requestId !== cardRequestId \|\| !snapshot \|\| submitting\) return;/, `${prefix}: a superseded open must stop after the localization wait`);+ assert.equal((open.match(/\+\+cardRequestId/g) || []).length, 1, `${prefix}: opening a card takes exactly one request id`);++ // Every path that abandons a running call tells the background.+ const run = body('async function runInline()', 'function submitFollowUp()');+ assert.match(run, /cancelInline\(\);\s*const requestId = \+\+cardRequestId;/, `${prefix}: a retry or new target cancels the call it replaces`);+ assert.match(run, /type: INLINE_MESSAGE,\s*jobId,/, `${prefix}: the call carries its job id`);+ assert.match(content, /function newInlineJobId\(\) \{[^}]*crypto\.getRandomValues/, `${prefix}: job ids are unguessable`);+ assert.match(body('function resetCard()', 'function closeCard('), /cancelInline\(\);\s*cardRequestId \+= 1;/, `${prefix}: closing or dismissing the card cancels the call`);+ assert.match(body('function destroySurface()', 'function hideToast()'), /cancelInline\(\);\s*cardRequestId \+= 1;/, `${prefix}: tearing the surface down cancels the call`);+ assert.match(body('function cancelInline()', 'async function runInline()'), /type: INLINE_CANCEL_MESSAGE, jobId/, `${prefix}: cancellation names the job`);++ // A capped answer is never shown as complete.+ assert.match(run, /cardState\.truncated = response\.truncated === true;/, `${prefix}: the card records the cut-off flag`);+ assert.match(content, /parts\.cut\.hidden = !\(status === 'ready' && cardState\.truncated\);/, `${prefix}: the notice shows for a cut-off answer only`);+ assert.match(body('function continueInPanel()', 'function resetCard()'), /submitSelection\(kind, '', kind === 'translate' \? target : interfaceLanguage\)/, `${prefix}: continuing hands the same action to the side panel`);+ }+});+test('selection shortcut grounding metadata suppresses competing page images', async () => {for (const [label, AgentClass, buildSelectionPrompt, sourceGrounding] of [['chrome', AgentCh, buildSelectionPromptCh, SELECTION_ONLY_SOURCE_GROUNDING_CH],