Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

fix(newtab): round-56 review — never force a running send aside; startup cleanup only touches older records

Claudee972f5e70dc2
diff --git a/src/chrome/src/background.js b/src/chrome/src/background.js
index a9f23308b..31bca6a5a 100644
--- a/src/chrome/src/background.js
+++ b/src/chrome/src/background.js
@@ -1646,8 +1646,17 @@ chrome.runtime.onMessage.addListener((msg, sender) => {
// ignored by their age, and closing a tab removes its records.
chrome.runtime.onStartup?.addListener?.(async () => {
try {
+ // Only records written before this moment: a task submitted since the browser started is
+ // never a candidate (the one case left, a stale key rewritten between the read and the
+ // removal below, needs a submission in that few-millisecond gap).
+ const startedAt = Date.now();
const all = await chrome.storage.local.get(null);
- const keys = Object.keys(all).filter((key) => key.startsWith('wbNewtabHandoff:'));
+ const olderThanStart = (record) => Number(record?.createdAt) < startedAt - 10_000;
+ const keys = Object.keys(all).filter((key) => {
+ if (!key.startsWith('wbNewtabHandoff:')) return false;
+ const entries = Array.isArray(all[key]) ? all[key] : [all[key]];
+ return entries.every(olderThanStart);
+ });
if (keys.length) await chrome.storage.local.remove(keys);
} catch {
// best effort
diff --git a/src/chrome/src/ui/newtab-handoff.js b/src/chrome/src/ui/newtab-handoff.js
index a117641a5..8456971a2 100644
--- a/src/chrome/src/ui/newtab-handoff.js
+++ b/src/chrome/src/ui/newtab-handoff.js
@@ -102,8 +102,14 @@ export function createNewtabHandoff({
if (retryTimer) return;
retryTimer = setTimeout(() => {
retryTimer = null;
- // A send that never commits must not hold later hand-offs back forever.
- if (++retries > NEWTAB_HANDOFF_SEND_HOLD_MAX_RETRIES && pendingSend) pendingSend.settled = true;
+ // Stop polling after the budget instead of forcing the send aside: a send that is still
+ // running owns the composer, and putting the next task in beside it would be sent along
+ // with it or duplicated when it settles. The waiting task stays in storage and is picked
+ // up when that send settles (below) or when the panel is next triggered.
+ if (++retries > NEWTAB_HANDOFF_SEND_HOLD_MAX_RETRIES) {
+ retries = 0;
+ return;
+ }
consume();
}, NEWTAB_HANDOFF_SEND_RETRY_MS);
}
@@ -232,6 +238,9 @@ export function createNewtabHandoff({
.then((result) => result !== false, () => false)
.then((sent) => {
send.settled = true;
+ // A task that arrived while this send held the composer is waiting; look for it once
+ // the recovery below (which runs synchronously) is done.
+ queueMicrotask(() => { consume(); });
// Declined or failed: the new tab already showed success and cleared its
// box, so make sure the text is still sitting in the composer.
if (sent) return;
diff --git a/src/firefox/src/background.js b/src/firefox/src/background.js
index 7d6b2b270..e424c7799 100644
--- a/src/firefox/src/background.js
+++ b/src/firefox/src/background.js
@@ -1401,8 +1401,17 @@ browser.runtime.onMessage.addListener((msg, sender) => {
// ignored by their age, and closing a tab removes its records.
browser.runtime.onStartup?.addListener?.(async () => {
try {
+ // Only records written before this moment: a task submitted since the browser started is
+ // never a candidate (the one case left, a stale key rewritten between the read and the
+ // removal below, needs a submission in that few-millisecond gap).
+ const startedAt = Date.now();
const all = await browser.storage.local.get(null);
- const keys = Object.keys(all).filter((key) => key.startsWith('wbNewtabHandoff:'));
+ const olderThanStart = (record) => Number(record?.createdAt) < startedAt - 10_000;
+ const keys = Object.keys(all).filter((key) => {
+ if (!key.startsWith('wbNewtabHandoff:')) return false;
+ const entries = Array.isArray(all[key]) ? all[key] : [all[key]];
+ return entries.every(olderThanStart);
+ });
if (keys.length) await browser.storage.local.remove(keys);
} catch {
// best effort
diff --git a/src/firefox/src/ui/newtab-handoff.js b/src/firefox/src/ui/newtab-handoff.js
index a117641a5..8456971a2 100644
--- a/src/firefox/src/ui/newtab-handoff.js
+++ b/src/firefox/src/ui/newtab-handoff.js
@@ -102,8 +102,14 @@ export function createNewtabHandoff({
if (retryTimer) return;
retryTimer = setTimeout(() => {
retryTimer = null;
- // A send that never commits must not hold later hand-offs back forever.
- if (++retries > NEWTAB_HANDOFF_SEND_HOLD_MAX_RETRIES && pendingSend) pendingSend.settled = true;
+ // Stop polling after the budget instead of forcing the send aside: a send that is still
+ // running owns the composer, and putting the next task in beside it would be sent along
+ // with it or duplicated when it settles. The waiting task stays in storage and is picked
+ // up when that send settles (below) or when the panel is next triggered.
+ if (++retries > NEWTAB_HANDOFF_SEND_HOLD_MAX_RETRIES) {
+ retries = 0;
+ return;
+ }
consume();
}, NEWTAB_HANDOFF_SEND_RETRY_MS);
}
@@ -232,6 +238,9 @@ export function createNewtabHandoff({
.then((result) => result !== false, () => false)
.then((sent) => {
send.settled = true;
+ // A task that arrived while this send held the composer is waiting; look for it once
+ // the recovery below (which runs synchronously) is done.
+ queueMicrotask(() => { consume(); });
// Declined or failed: the new tab already showed success and cleared its
// box, so make sure the text is still sitting in the composer.
if (sent) return;
diff --git a/test/newtab.mjs b/test/newtab.mjs
index 47576653b..2b4501051 100644
--- a/test/newtab.mjs
+++ b/test/newtab.mjs
@@ -643,6 +643,52 @@ for (const browser of ['chrome', 'firefox']) {
assert.equal(input.value, 'task A');
});
+ test(`${browser}: a task waiting behind a long send stays out of the composer and is delivered when the send settles`, async () => {
+ const key3 = newtabHandoffKey(3);
+ const store = { [key3]: { id: 'A', tabId: 3, text: 'task A', mode: 'ask', createdAt: 99_900 } };
+ const input = { value: '', dispatchEvent() {}, focus() {} };
+ let finishA;
+ const gateA = new Promise((r) => { finishA = r; });
+ let calls = 0;
+ const realSetTimeout = globalThis.setTimeout;
+ globalThis.setTimeout = (fn) => { queueMicrotask(fn); return 0; }; // run the 150 ms polls at once
+ try {
+ 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 () => {
+ calls += 1;
+ if (calls === 1) { await gateA; input.value = ''; return true; } // A: slow preflight, then sent
+ input.value = ''; return true;
+ },
+ now: () => 100_000,
+ });
+ await handoff.start(); // A is claimed and its send starts (composer holds A)
+ store[key3] = { id: 'B', tabId: 3, text: 'task B', mode: 'ask', createdAt: 99_950 };
+ await handoff.consume(); // B is waiting behind A
+ for (let i = 0; i < 400; i++) await Promise.resolve(); // polling budget runs out
+ assert.equal(input.value, 'task A', 'B was not merged into the composer beside the running send');
+ assert.equal(store[key3].id, 'B', 'B is still waiting in storage');
+ finishA();
+ for (let i = 0; i < 20; i++) await new Promise((r) => realSetTimeout(r, 0));
+ assert.equal(key3 in store, false, 'B was delivered once A settled');
+ assert.equal(calls, 2);
+ } finally {
+ globalThis.setTimeout = realSetTimeout;
+ }
+ });
+
const rec = (over = {}) => ({ id: 'r1', tabId: 3, text: 'summarise', mode: 'ask', createdAt: 99_000, ...over });
const KEY = newtabHandoffKey(3);
@@ -1768,7 +1814,7 @@ test('round-51: handoff records are cleared at browser start, never swept from a
for (const [file, api] of [['src/chrome/src/background.js', 'chrome'], ['src/firefox/src/background.js', 'browser']]) {
const src = readFileSync(path.join(root, file), 'utf8');
assert.doesNotMatch(src, /sweepStaleNewtabHandoffs/, file);
- assert.match(src, /onStartup\?\.addListener\?\.\(async \(\) => \{\s*try \{[\s\S]*startsWith\('wbNewtabHandoff:'\)/, file);
+ assert.match(src, /onStartup\?\.addListener\?\.\(async \(\) => \{\s*try \{[\s\S]*startedAt - 10_000[\s\S]*startsWith\('wbNewtabHandoff:'\)/, file);
assert.match(src, /wbNewtabHandoff:retry:\$\{closedTabId\}/, file);
}
});