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(newtab): round-44 review — hand declined tasks back through a panel-owned key
Claude2405799f81d0
diff --git a/src/chrome/src/background.js b/src/chrome/src/background.jsindex bf3c73082..2a85dfdbd 100644--- a/src/chrome/src/background.js+++ b/src/chrome/src/background.js@@ -1658,7 +1658,9 @@ async function sweepStaleNewtabHandoffs() {// anything left over from a previous browser session is dropped on every start of// the background (top level runs at browser start and when the worker wakes).chrome.tabs.onRemoved.addListener((closedTabId) => {- chrome.storage.local.remove(`wbNewtabHandoff:${closedTabId}`).catch(() => {});+ chrome.storage.local+ .remove([`wbNewtabHandoff:${closedTabId}`, `wbNewtabHandoff:retry:${closedTabId}`])+ .catch(() => {});});sweepStaleNewtabHandoffs();diff --git a/src/chrome/src/ui/newtab-handoff.js b/src/chrome/src/ui/newtab-handoff.jsindex e4379165f..79f5cf1df 100644--- a/src/chrome/src/ui/newtab-handoff.js+++ b/src/chrome/src/ui/newtab-handoff.js@@ -29,6 +29,10 @@export const NEWTAB_HANDOFF_PREFIX = 'wbNewtabHandoff:';export const newtabHandoffKey = (tabId) => `${NEWTAB_HANDOFF_PREFIX}${tabId}`;+// A task the panel has to hand back (its tab lost focus mid-send, ...) goes to a key only the+// panel writes. Reusing the new tab's key could overwrite a newer task stored there meanwhile,+// and chrome.storage has no compare-and-set to guard that.+export const newtabHandoffRetryKey = (tabId) => `${NEWTAB_HANDOFF_PREFIX}retry:${tabId}`;export const NEWTAB_HANDOFF_MAX_AGE_MS = 30_000;export const NEWTAB_HANDOFF_MAX_STARTUP_ALLOWANCE_MS = 120_000;export const NEWTAB_HANDOFF_MAX_TEXT = 4000;@@ -109,7 +113,9 @@ export function createNewtabHandoff({return false;}retries = 0;- const key = newtabHandoffKey(Number(tabId));+ const primaryKey = newtabHandoffKey(Number(tabId));+ const retryKey = newtabHandoffRetryKey(Number(tabId));+ let key = primaryKey;consuming = true;// Only the first attempt after start() gets the startup allowance.const allowance = startupAllowanceMs;@@ -118,16 +124,20 @@ export function createNewtabHandoff({// tabs while storage is being read or written, this tab's task must not be applied// to the other tab's composer; the switch's own consume() picks up the right one.const sameTab = () => Number(getCurrentTabId()) === Number(tabId);- // Put a record back only if nothing newer took its place: the new tab unlocks as soon as a- // record is removed and may already have stored the next task under the same key.- const restoreIfEmpty = async (record) => {+ // Hand a task back for when this tab is shown again, without touching the key the new tab+ // writes to (it unlocks as soon as a record is removed and may already hold the next task).+ const stashForLater = async (record) => {try {- const current = (await storage.get(key))?.[key];- if (current == null) await storage.set?.({ [key]: record });+ const current = (await storage.get(retryKey))?.[retryKey];+ if (current == null) await storage.set?.({ [retryKey]: record });} catch { /* best effort */ }};try {- const stored = (await storage.get(key))?.[key];+ let stored = (await storage.get(primaryKey))?.[primaryKey];+ if (stored == null && sameTab()) {+ stored = (await storage.get(retryKey))?.[retryKey];+ key = retryKey;+ }if (stored == null || !sameTab()) return false;const handoff = normalizeNewtabHandoff(stored, now(), NEWTAB_HANDOFF_MAX_AGE_MS + allowance);if (!handoff) {@@ -141,7 +151,7 @@ export function createNewtabHandoff({if (!sameTab()) {// Switched during the removal: put the record back for when this tab is shown again.handled.delete(handoff.id);- await restoreIfEmpty(stored);+ await stashForLater(stored);return false;}@@ -194,7 +204,7 @@ export function createNewtabHandoff({} else {// The user moved to another tab while the send was being declined, and the// composer now belongs to that tab. Hand the task back for its own tab instead.- restoreIfEmpty({ ...stored, id: `${handoff.id}-retry`, createdAt: now() });+ stashForLater({ ...stored, id: `${handoff.id}-retry`, createdAt: now() });}});}@@ -224,7 +234,11 @@ export function createNewtabHandoff({onChanged?.addListener((changes, area) => {if (area && area !== 'local') return;const tabId = getCurrentTabId();- if (tabId != null && changes?.[newtabHandoffKey(Number(tabId))]?.newValue) consume();+ if (tabId == null) return;+ if (+ changes?.[newtabHandoffKey(Number(tabId))]?.newValue ||+ changes?.[newtabHandoffRetryKey(Number(tabId))]?.newValue+ ) consume();});// The record can arrive just before an already-loaded panel becomes visible// (the new tab writes it, then opens the panel). consume() skips hiddendiff --git a/src/firefox/src/background.js b/src/firefox/src/background.jsindex b1c8954a0..ee71745f4 100644--- a/src/firefox/src/background.js+++ b/src/firefox/src/background.js@@ -1413,7 +1413,9 @@ async function sweepStaleNewtabHandoffs() {// anything left over from a previous browser session is dropped on every start of// the background (top level runs at browser start and when the worker wakes).browser.tabs.onRemoved.addListener((closedTabId) => {- browser.storage.local.remove(`wbNewtabHandoff:${closedTabId}`).catch(() => {});+ browser.storage.local+ .remove([`wbNewtabHandoff:${closedTabId}`, `wbNewtabHandoff:retry:${closedTabId}`])+ .catch(() => {});});sweepStaleNewtabHandoffs();diff --git a/src/firefox/src/ui/newtab-handoff.js b/src/firefox/src/ui/newtab-handoff.jsindex e4379165f..79f5cf1df 100644--- a/src/firefox/src/ui/newtab-handoff.js+++ b/src/firefox/src/ui/newtab-handoff.js@@ -29,6 +29,10 @@export const NEWTAB_HANDOFF_PREFIX = 'wbNewtabHandoff:';export const newtabHandoffKey = (tabId) => `${NEWTAB_HANDOFF_PREFIX}${tabId}`;+// A task the panel has to hand back (its tab lost focus mid-send, ...) goes to a key only the+// panel writes. Reusing the new tab's key could overwrite a newer task stored there meanwhile,+// and chrome.storage has no compare-and-set to guard that.+export const newtabHandoffRetryKey = (tabId) => `${NEWTAB_HANDOFF_PREFIX}retry:${tabId}`;export const NEWTAB_HANDOFF_MAX_AGE_MS = 30_000;export const NEWTAB_HANDOFF_MAX_STARTUP_ALLOWANCE_MS = 120_000;export const NEWTAB_HANDOFF_MAX_TEXT = 4000;@@ -109,7 +113,9 @@ export function createNewtabHandoff({return false;}retries = 0;- const key = newtabHandoffKey(Number(tabId));+ const primaryKey = newtabHandoffKey(Number(tabId));+ const retryKey = newtabHandoffRetryKey(Number(tabId));+ let key = primaryKey;consuming = true;// Only the first attempt after start() gets the startup allowance.const allowance = startupAllowanceMs;@@ -118,16 +124,20 @@ export function createNewtabHandoff({// tabs while storage is being read or written, this tab's task must not be applied// to the other tab's composer; the switch's own consume() picks up the right one.const sameTab = () => Number(getCurrentTabId()) === Number(tabId);- // Put a record back only if nothing newer took its place: the new tab unlocks as soon as a- // record is removed and may already have stored the next task under the same key.- const restoreIfEmpty = async (record) => {+ // Hand a task back for when this tab is shown again, without touching the key the new tab+ // writes to (it unlocks as soon as a record is removed and may already hold the next task).+ const stashForLater = async (record) => {try {- const current = (await storage.get(key))?.[key];- if (current == null) await storage.set?.({ [key]: record });+ const current = (await storage.get(retryKey))?.[retryKey];+ if (current == null) await storage.set?.({ [retryKey]: record });} catch { /* best effort */ }};try {- const stored = (await storage.get(key))?.[key];+ let stored = (await storage.get(primaryKey))?.[primaryKey];+ if (stored == null && sameTab()) {+ stored = (await storage.get(retryKey))?.[retryKey];+ key = retryKey;+ }if (stored == null || !sameTab()) return false;const handoff = normalizeNewtabHandoff(stored, now(), NEWTAB_HANDOFF_MAX_AGE_MS + allowance);if (!handoff) {@@ -141,7 +151,7 @@ export function createNewtabHandoff({if (!sameTab()) {// Switched during the removal: put the record back for when this tab is shown again.handled.delete(handoff.id);- await restoreIfEmpty(stored);+ await stashForLater(stored);return false;}@@ -194,7 +204,7 @@ export function createNewtabHandoff({} else {// The user moved to another tab while the send was being declined, and the// composer now belongs to that tab. Hand the task back for its own tab instead.- restoreIfEmpty({ ...stored, id: `${handoff.id}-retry`, createdAt: now() });+ stashForLater({ ...stored, id: `${handoff.id}-retry`, createdAt: now() });}});}@@ -224,7 +234,11 @@ export function createNewtabHandoff({onChanged?.addListener((changes, area) => {if (area && area !== 'local') return;const tabId = getCurrentTabId();- if (tabId != null && changes?.[newtabHandoffKey(Number(tabId))]?.newValue) consume();+ if (tabId == null) return;+ if (+ changes?.[newtabHandoffKey(Number(tabId))]?.newValue ||+ changes?.[newtabHandoffRetryKey(Number(tabId))]?.newValue+ ) consume();});// The record can arrive just before an already-loaded panel becomes visible// (the new tab writes it, then opens the panel). consume() skips hiddendiff --git a/test/newtab.mjs b/test/newtab.mjsindex 1b3cccd70..2e0af6004 100644--- a/test/newtab.mjs+++ b/test/newtab.mjs@@ -268,7 +268,7 @@ test('the only remaining fetch in the new tab source loads the chosen background});for (const browser of ['chrome', 'firefox']) {- const { normalizeNewtabHandoff, createNewtabHandoff, newtabHandoffKey, NEWTAB_HANDOFF_PREFIX } =+ const { normalizeNewtabHandoff, createNewtabHandoff, newtabHandoffKey, newtabHandoffRetryKey, NEWTAB_HANDOFF_PREFIX } =await load(path.join(root, 'src', browser, 'src/ui/newtab-handoff.js'));test(`${browser}: handoff normalisation rejects stale, malformed or oversized records`, () => {@@ -351,7 +351,8 @@ for (const browser of ['chrome', 'firefox']) {await handoff.start();assert.deepEqual(sent, [], 'nothing was sent into the other tab');assert.equal(input.value, '', "the other tab's composer was not touched");- assert.equal(store[key3]?.id, 'r1', "the old tab's record is still waiting");+ // a read-time switch leaves the record where it was; a removal-time switch hands it back+ assert.equal((store[key3] ?? store[newtabHandoffRetryKey(3)])?.id, 'r1', "the old tab's record is still waiting");// back on tab 3 the task is appliedstate.tabId = 3;await handoff.consume();@@ -389,8 +390,8 @@ for (const browser of ['chrome', 'firefox']) {await new Promise((r) => setTimeout(r, 0));await new Promise((r) => setTimeout(r, 0));assert.equal(input.value, '', "tab 4's composer stays empty");- assert.equal(store[key3]?.text, 'for tab three', 'the task is waiting for tab 3 again');- assert.equal(store[key3].id, 'r1-retry');+ assert.equal(store[newtabHandoffRetryKey(3)]?.text, 'for tab three', 'the task is waiting for tab 3 again');+ assert.equal(store[newtabHandoffRetryKey(3)].id, 'r1-retry');});test(`${browser}: a declined send keeps a draft typed meanwhile and adds the task below it`, async () => {@@ -454,6 +455,36 @@ for (const browser of ['chrome', 'firefox']) {await new Promise((r) => setTimeout(r, 0));await new Promise((r) => setTimeout(r, 0));assert.equal(store[key3].id, 'B', 'the newer task is kept');+ assert.equal(store[newtabHandoffRetryKey(3)].id, 'A-retry', 'and the declined one is kept beside it');+ });++ test(`${browser}: a task handed back to its tab is applied when that tab is shown again, and the slot is cleared`, async () => {+ const key3 = newtabHandoffKey(3);+ const retry3 = newtabHandoffRetryKey(3);+ const store = { [retry3]: { id: 'A-retry', tabId: 3, text: 'task A', mode: 'ask', createdAt: 99_900 } };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ const sent = [];+ const handoff = createNewtabHandoff({+ storage: {+ get: async (k) => (k in store ? { [k]: store[k] } : {}),+ remove: async (k) => { delete store[k]; },+ set: async (o) => Object.assign(store, o),+ },+ getCurrentTabId: () => 3,+ getIsProcessing: () => false,+ getIsBlocked: () => false,+ getIsDocumentVisible: () => true,+ doc: { addEventListener() {} },+ setMode() {},+ getInputEl: () => input,+ autoResizeInput() {},+ sendMessage: async () => { sent.push(input.value); input.value = ''; },+ now: () => 100_000,+ });+ await handoff.start();+ assert.deepEqual(sent, ['task A']);+ assert.equal(retry3 in store, false);+ assert.equal(key3 in store, false);});const rec = (over = {}) => ({ id: 'r1', tabId: 3, text: 'summarise', mode: 'ask', createdAt: 99_000, ...over });