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
Merge origin/main into feat/newtab-page
Claude7e862fcaa586
diff --cc CHANGELOG.mdindex 4014ba891,c027cc2f4..78ac6619a--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -7,7 -7,10 +7,11 @@@ This changelog was generated from the r## [Unreleased]### Added- - New tab page: WebBrain now provides a new tab with a clock, quick links, bundled backgrounds and a WebBrain box (Ask, Act or Search). Ask runs in the side panel straight away; Act opens the panel with your task filled in and waits for you to press Enter. Based on Mue (BSD-3-Clause), with all of Mue's network calls and telemetry removed. Adds the `search` permission. See `docs/newtab.md`.+ - Automatic mode selection: WebBrain now picks Ask, Act or Dev for each message, and the Ask, Act and Dev buttons are gone. It stays read-only unless your message asks it to do something in the browser. With a decision model configured (WebBrain Cloud includes one), the choice is made while the page is being read, so a message waits at most a quarter of a second longer. Without one, or when the decision model is unsure, the message starts in Ask; if it needs clicking, typing or opening pages, the model hands it over to Act, quoting your words. That hand-off counts only when your words, read again without the page, also ask for an action; the same message then restarts in Act with the usual plan review and permission prompts. Page content can never switch a message into Act, and right-click and selection prompts stay in Ask. Start a message with /ask, /act or /dev, or press Ctrl+Shift+A, X or D, to choose the mode for that message yourself. Text you selected on the page and the standalone window always stay in Ask.++- New tab page: WebBrain now provides a new tab with a clock, quick links, bundled backgrounds and a WebBrain box (Ask, Act or Search). Ask and Act both run in the side panel straight away (Act shows a warning that it starts working immediately; Plan before Act still applies). Based on Mue (BSD-3-Clause), with all of Mue's network calls and telemetry removed. Adds the `search` permission. See `docs/newtab.md`.++ ### Changed+ - The side panel layout is rearranged. The language, text size, Settings and pop-out buttons moved to the top left, and History and New chat to the top right, where History opens its list downward. The model picker moved into the message box, next to the attach button below your text, and its list opens upward.### 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 --cc src/chrome/src/ui/newtab-handoff.jsindex 48eb68818,000000000..77a5e4dd7mode 100644,000000..100644--- a/src/chrome/src/ui/newtab-handoff.js+++ b/src/chrome/src/ui/newtab-handoff.js@@@ -1,371 -1,0 +1,376 @@@+/**+ * Receives a task typed into the WebBrain new tab (newtab/src/features/agent).+ *+ * The new tab stores { id, tabId, text, mode, createdAt } under a per-tab key+ * (`wbNewtabHandoff:<tabId>`, so two submissions can never overwrite each other)+ * and opens this panel from its own click handler. The panel claims the record+ * only if it is fresh and addressed to the tab it is showing:+ * - Ask: the task is filled in and sent (Ask is read-only). If a run is already+ * active in that tab it is queued behind it, exactly like pressing Send then.+ * If the panel declines to send (plan review pending, state refresh, ...) the+ * text stays in the composer for the user to send.+ * If the composer already holds a different draft (the user's own, or an+ * unconfirmed Act task) nothing is overwritten, the mode is left as it is, and+ * nothing is sent: the task is added below the draft for the user to review+ * and send.+ * - Act: the task is filled in and the panel switches to Act, but nothing is+ * sent. Act always needs the user's own Enter in the panel.+ *+ * A second hand-off is held back while an earlier Ask is still being sent (its text+ * is still sitting in the composer): filling the composer again would make that+ * send see a changed draft and drop it.+ *+ * Nothing is claimed until start() is called, after the panel has finished+ * restoring its chat: sending earlier would be overwritten by the restore. The+ * freshness window is extended by however long that startup took.+ *+ * The Chrome and Firefox copies of this file are identical — edit both together.+ */++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;+export const NEWTAB_HANDOFF_SEND_RETRY_MS = 150;+// Give up holding a later hand-off back after this many retries (~15 s). It has to stay well+// under NEWTAB_HANDOFF_MAX_AGE_MS: a record held longer than it is accepted would come out+// stale, unclaimed, after the new tab had already reported success.+export const NEWTAB_HANDOFF_SEND_HOLD_MAX_RETRIES = 100;++/** Returns a clean record, or null when it is malformed, stale or from the future. */+export function normalizeNewtabHandoff(raw, now = Date.now(), maxAgeMs = NEWTAB_HANDOFF_MAX_AGE_MS) {+ if (!raw || typeof raw !== 'object') return null;+ const text = String(raw.text ?? '').replace(/\r\n/g, '\n').trim();+ if (!text || text.length > NEWTAB_HANDOFF_MAX_TEXT) return null;+ const mode = raw.mode === 'act' ? 'act' : raw.mode === 'ask' ? 'ask' : null;+ if (!mode) return null;+ const tabId = Number(raw.tabId);+ if (!Number.isInteger(tabId) || tabId < 0) return null;+ const createdAt = Number(raw.createdAt);+ if (!Number.isFinite(createdAt)) return null;+ if (now - createdAt > maxAgeMs || createdAt - now > 5_000) return null;+ const id = String(raw.id ?? '');+ if (!id) return null;+ return { id, tabId, text, mode, createdAt };+}++export function createNewtabHandoff({+ storage,+ onChanged,+ getCurrentTabId,+ getIsProcessing,+ getIsBlocked = () => false,+ getIsDocumentVisible = () => true,+ doc = globalThis.document,+ setMode,+ getInputEl,+ autoResizeInput,+ sendMessage,+ now = Date.now,+}) {+ const handled = new Set();+ const startedAt = now();+ let ready = false;+ let startupAllowanceMs = 0;+ let startedUpAt = -Infinity; // when start() ran; tasks created before it were delayed by the startup+ let consuming = false;+ let rerun = false;+ let retryTimer = null;+ const retries = new Map(); // tabId -> polls spent waiting for that tab's send+ // The Ask most recently handed to sendMessage, while its text may still be in+ // the composer waiting for the send's own checks to finish.+ // One per tab: a send in preflight on one tab must stay known while another tab is shown.+ const pendingSends = new Map();+ // When a look at storage was first put off because a send still held the composer. A task that+ // sat waiting behind that send is not stale for the time the panel itself kept it waiting.+ const heldSince = new Map(); // tabId -> when+ // The waiting time of tasks put off by that hold, kept until every task it delayed has been+ // looked at (a fresher one may be considered first).+ const heldAllowanceMs = new Map(); // tabId -> ms+ // Writes to the retry slot (a list, written only by this panel) run one after another, so+ // two hand-backs or a hand-back and a claim never overwrite each other.+ let retrySlotWrites = Promise.resolve();+ const serialRetryWrite = (fn) => {+ retrySlotWrites = retrySlotWrites.then(fn, fn);+ return retrySlotWrites;+ };+ const asList = (raw) => (Array.isArray(raw) ? raw : raw == null ? [] : [raw]);+ // Tasks that could not be written back to storage (it was refusing writes). They exist only in+ // memory, so every look at storage first tries to save them again; the retry slot stays the+ // one place they are picked up from.+ const unsaved = [];+ const stashRecord = (record) => serialRetryWrite(async () => {+ const retryKey = newtabHandoffRetryKey(Number(record.tabId));+ try {+ const queue = asList((await storage.get(retryKey))?.[retryKey]);+ if (!queue.some((entry) => entry?.id === record.id)) {+ await storage.set?.({ [retryKey]: [...queue, record] });+ }+ const at = unsaved.findIndex((entry) => entry.id === record.id);+ if (at >= 0) unsaved.splice(at, 1);+ return true;+ } catch {+ if (!unsaved.some((entry) => entry.id === record.id)) unsaved.push(record);+ return false;+ }+ });++ const sendStillHoldsComposer = (tabId) => {+ const pendingSend = pendingSends.get(Number(tabId));+ if (!pendingSend || pendingSend.settled) return false;+ const value = String(getInputEl()?.value ?? '');+ if (value === pendingSend.text) return true;+ // A slash command empties the composer before its (asynchronous) preflight finishes, so an+ // empty box does not yet mean the send has committed. It has once the run is under way, and a+ // send that was queued behind a run settles by itself.+ return pendingSend.text.startsWith('/') && value === '' && (pendingSend.queued || !getIsProcessing());+ };++ function retrySoon(tabId) {+ // 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. The budget belongs+ // to the tab whose send is being waited for, so another tab's polling does not use it up.+ const polls = (retries.get(Number(tabId)) ?? 0) + 1;+ if (polls > NEWTAB_HANDOFF_SEND_HOLD_MAX_RETRIES) {+ retries.delete(Number(tabId));+ return;+ }+ retries.set(Number(tabId), polls);+ if (retryTimer) return;+ retryTimer = setTimeout(() => {+ retryTimer = null;+ consume();+ }, NEWTAB_HANDOFF_SEND_RETRY_MS);+ }++ async function consume() {+ if (!ready || !getIsDocumentVisible()) return false;+ // A record can arrive while another is being claimed (the new tab unlocks as+ // soon as the first is removed). Remember it and look again when this ends.+ if (consuming) {+ rerun = true;+ return false;+ }+ const tabId = getCurrentTabId();+ if (tabId == null) return false;+ if (sendStillHoldsComposer(tabId)) {+ if (!heldSince.has(Number(tabId))) heldSince.set(Number(tabId), now());+ retrySoon(tabId);+ return false;+ }+ retries.delete(Number(tabId));+ if (heldSince.has(Number(tabId))) {+ heldAllowanceMs.set(+ Number(tabId),+ Math.max(+ heldAllowanceMs.get(Number(tabId)) ?? 0,+ Math.min(now() - heldSince.get(Number(tabId)), NEWTAB_HANDOFF_MAX_STARTUP_ALLOWANCE_MS),+ ),+ );+ heldSince.delete(Number(tabId));+ }+ const primaryKey = newtabHandoffKey(Number(tabId));+ const retryKey = newtabHandoffRetryKey(Number(tabId));+ let key = primaryKey;+ let claimedOne = false;+ consuming = true;+ // Anything that could not be saved earlier gets another try before storage is read.+ for (const record of unsaved.slice()) await stashRecord(record);+ const heldAllowance = heldAllowanceMs.get(Number(tabId)) ?? 0;+ // The shared composer belongs to whichever tab is active now. If the user switches+ // 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);+ // 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 = stashRecord;+ const retryWaiting = async () => {+ try {+ return asList((await storage.get(retryKey))?.[retryKey]).length > 0;+ } catch {+ return false;+ }+ };+ // Takes the record just read out of storage: the primary key is simply removed, the retry+ // slot drops that one entry and keeps the others.+ const removeClaimed = (record) => {+ if (key !== retryKey) return storage.remove(key);+ return serialRetryWrite(async () => {+ const rest = asList((await storage.get(retryKey))?.[retryKey]).filter((entry) => entry?.id !== record?.id);+ if (rest.length) await storage.set?.({ [retryKey]: rest });+ else await storage.remove(retryKey);+ });+ };+ try {+ // Every task typed before the panel finished starting was delayed by that startup, whichever+ // tab it belongs to and whichever tab is looked at first.+ const accept = (record) => {+ const delayedByStartup = Number(record?.createdAt) <= startedUpAt ? startupAllowanceMs : 0;+ return normalizeNewtabHandoff(record, now(), NEWTAB_HANDOFF_MAX_AGE_MS + delayedByStartup + heldAllowance);+ };+ let stored = (await storage.get(primaryKey))?.[primaryKey];+ let handoff = stored == null ? null : accept(stored);+ // A stale or malformed primary record is left where it is: the new tab replaces it once+ // its own lock has run out, and deleting the key from an earlier read could take a task+ // written in between (storage has no compare-and-delete). Look in the retry slot instead.+ if (!handoff && sameTab()) {+ stored = asList((await storage.get(retryKey))?.[retryKey])[0];+ key = retryKey;+ handoff = stored == null ? null : accept(stored);+ }+ if (stored == null) {+ heldAllowanceMs.delete(Number(tabId)); // nothing left that the hold could have delayed+ return false;+ }+ if (!sameTab()) return false;+ if (!handoff) {+ // Only the panel writes the retry slot, so dropping an expired entry is safe.+ if (key === retryKey) {+ await removeClaimed(stored);+ claimedOne = true; // others may be waiting behind it+ }+ return false;+ }+ if (handoff.tabId !== Number(tabId) || handled.has(handoff.id)) return false;++ handled.add(handoff.id);+ try {+ await removeClaimed(stored);+ } catch (error) {+ // Not claimed after all (storage refused): the record is still there, so it must stay claimable.+ handled.delete(handoff.id);+ throw error;+ }+ if (!sameTab()) {+ // Switched during the removal: put the record back for when this tab is shown again.+ handled.delete(handoff.id);+ // The new tab already showed this task as handed over, so it must outlive the freshness+ // window that has been running since it was typed.+ await stashForLater({ ...stored, createdAt: now() });+ return false;+ }++ const input = getInputEl();+ // Never overwrite what is already in the composer. The task goes below it,+ // and the panel keeps the mode that draft was written in: switching it would+ // change what confirming the combined draft does (an Ask draft would become+ // an Act, or the reverse).+ // `existing` is only for the emptiness / equality checks; the draft itself is kept as typed.+ const draft = String(input.value || '');+ const existing = draft.trim();+ const keepsDraft = Boolean(existing) && existing !== handoff.text;+ if (!keepsDraft) setMode(handoff.mode);+ const composerText = keepsDraft ? `${draft}\n\n${handoff.text}` : handoff.text;+ const fill = () => {+ input.value = composerText;+ input.dispatchEvent(new Event('input', { bubbles: true }));+ autoResizeInput();+ };+ fill();+ input.focus?.();+ if (!getIsBlocked() && !keepsDraft) {+ // sendMessage reads the composer synchronously when called, so starting it+ // here captures this task. It is not awaited: a send can last a whole run,+ // and that must not hold up later hand-offs or the panel's own startup.+ const send = { text: handoff.text, settled: false, queued: Boolean(getIsProcessing()) };+ pendingSends.set(Number(tabId), send);+ let sending;+ try {- sending = Promise.resolve(sendMessage(getIsProcessing() ? { __deliveryMode: 'queue' } : undefined));++ // __mode pins the mode the user chose in the box: with automatic mode selection the++ // panel would otherwise pick one itself, and Ask must stay read-only while Act acts.++ sending = Promise.resolve(sendMessage({++ ...(getIsProcessing() ? { __deliveryMode: 'queue' } : {}),++ __mode: handoff.mode,++ }));+ } catch (error) {+ sending = Promise.reject(error);+ }+ sending+ .then((result) => result !== false, () => false)+ .then((sent) => {+ send.settled = true;+ if (pendingSends.get(Number(tabId)) === send) pendingSends.delete(Number(tabId));+ // 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;+ if (sameTab()) {+ const current = String(input.value || '');+ if (!current.trim()) {+ fill();+ } else if (current.trim() !== handoff.text && !current.endsWith(`\n\n${handoff.text}`)) {+ // The user typed something else while the send was pending: keep their draft and+ // put the task below it (the record is gone, so this is the only copy left).+ input.value = `${current}\n\n${handoff.text}`;+ input.dispatchEvent(new Event('input', { bubbles: true }));+ autoResizeInput();+ }+ } 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.+ stashForLater({ ...stored, id: `${handoff.id}-retry`, createdAt: now() });+ }+ });+ }+ // A task handed back earlier may be waiting behind the one just claimed (removing a+ // primary record raises no change event this panel acts on), so look again if so.+ if (key === primaryKey) {+ claimedOne = await retryWaiting();+ // Nothing else was delayed by the hold: whatever arrives next is judged on its own age.+ if (!claimedOne) heldAllowanceMs.delete(Number(tabId));+ } else {+ // A hand-back was claimed; look again, which finds the next one or clears the allowance.+ claimedOne = true;+ }+ return true;+ } catch {+ return false;+ } finally {+ consuming = false;+ if (rerun || claimedOne) {+ rerun = false;+ queueMicrotask(() => { consume(); });+ }+ }+ }++ /** Call once the panel has finished restoring its chat. */+ function start() {+ startupAllowanceMs = Math.min(+ Math.max(0, now() - startedAt),+ NEWTAB_HANDOFF_MAX_STARTUP_ALLOWANCE_MS,+ );+ startedUpAt = now();+ ready = true;+ return consume();+ }++ function watch() {+ onChanged?.addListener((changes, area) => {+ if (area && area !== 'local') return;+ const tabId = getCurrentTabId();+ 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 hidden+ // panels, so try again the moment this one is shown.+ doc?.addEventListener?.('visibilitychange', () => {+ if (getIsDocumentVisible()) consume();+ });+ }++ return { consume, start, watch };+}diff --cc src/firefox/src/ui/newtab-handoff.jsindex 48eb68818,000000000..77a5e4dd7mode 100644,000000..100644--- a/src/firefox/src/ui/newtab-handoff.js+++ b/src/firefox/src/ui/newtab-handoff.js@@@ -1,371 -1,0 +1,376 @@@+/**+ * Receives a task typed into the WebBrain new tab (newtab/src/features/agent).+ *+ * The new tab stores { id, tabId, text, mode, createdAt } under a per-tab key+ * (`wbNewtabHandoff:<tabId>`, so two submissions can never overwrite each other)+ * and opens this panel from its own click handler. The panel claims the record+ * only if it is fresh and addressed to the tab it is showing:+ * - Ask: the task is filled in and sent (Ask is read-only). If a run is already+ * active in that tab it is queued behind it, exactly like pressing Send then.+ * If the panel declines to send (plan review pending, state refresh, ...) the+ * text stays in the composer for the user to send.+ * If the composer already holds a different draft (the user's own, or an+ * unconfirmed Act task) nothing is overwritten, the mode is left as it is, and+ * nothing is sent: the task is added below the draft for the user to review+ * and send.+ * - Act: the task is filled in and the panel switches to Act, but nothing is+ * sent. Act always needs the user's own Enter in the panel.+ *+ * A second hand-off is held back while an earlier Ask is still being sent (its text+ * is still sitting in the composer): filling the composer again would make that+ * send see a changed draft and drop it.+ *+ * Nothing is claimed until start() is called, after the panel has finished+ * restoring its chat: sending earlier would be overwritten by the restore. The+ * freshness window is extended by however long that startup took.+ *+ * The Chrome and Firefox copies of this file are identical — edit both together.+ */++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;+export const NEWTAB_HANDOFF_SEND_RETRY_MS = 150;+// Give up holding a later hand-off back after this many retries (~15 s). It has to stay well+// under NEWTAB_HANDOFF_MAX_AGE_MS: a record held longer than it is accepted would come out+// stale, unclaimed, after the new tab had already reported success.+export const NEWTAB_HANDOFF_SEND_HOLD_MAX_RETRIES = 100;++/** Returns a clean record, or null when it is malformed, stale or from the future. */+export function normalizeNewtabHandoff(raw, now = Date.now(), maxAgeMs = NEWTAB_HANDOFF_MAX_AGE_MS) {+ if (!raw || typeof raw !== 'object') return null;+ const text = String(raw.text ?? '').replace(/\r\n/g, '\n').trim();+ if (!text || text.length > NEWTAB_HANDOFF_MAX_TEXT) return null;+ const mode = raw.mode === 'act' ? 'act' : raw.mode === 'ask' ? 'ask' : null;+ if (!mode) return null;+ const tabId = Number(raw.tabId);+ if (!Number.isInteger(tabId) || tabId < 0) return null;+ const createdAt = Number(raw.createdAt);+ if (!Number.isFinite(createdAt)) return null;+ if (now - createdAt > maxAgeMs || createdAt - now > 5_000) return null;+ const id = String(raw.id ?? '');+ if (!id) return null;+ return { id, tabId, text, mode, createdAt };+}++export function createNewtabHandoff({+ storage,+ onChanged,+ getCurrentTabId,+ getIsProcessing,+ getIsBlocked = () => false,+ getIsDocumentVisible = () => true,+ doc = globalThis.document,+ setMode,+ getInputEl,+ autoResizeInput,+ sendMessage,+ now = Date.now,+}) {+ const handled = new Set();+ const startedAt = now();+ let ready = false;+ let startupAllowanceMs = 0;+ let startedUpAt = -Infinity; // when start() ran; tasks created before it were delayed by the startup+ let consuming = false;+ let rerun = false;+ let retryTimer = null;+ const retries = new Map(); // tabId -> polls spent waiting for that tab's send+ // The Ask most recently handed to sendMessage, while its text may still be in+ // the composer waiting for the send's own checks to finish.+ // One per tab: a send in preflight on one tab must stay known while another tab is shown.+ const pendingSends = new Map();+ // When a look at storage was first put off because a send still held the composer. A task that+ // sat waiting behind that send is not stale for the time the panel itself kept it waiting.+ const heldSince = new Map(); // tabId -> when+ // The waiting time of tasks put off by that hold, kept until every task it delayed has been+ // looked at (a fresher one may be considered first).+ const heldAllowanceMs = new Map(); // tabId -> ms+ // Writes to the retry slot (a list, written only by this panel) run one after another, so+ // two hand-backs or a hand-back and a claim never overwrite each other.+ let retrySlotWrites = Promise.resolve();+ const serialRetryWrite = (fn) => {+ retrySlotWrites = retrySlotWrites.then(fn, fn);+ return retrySlotWrites;+ };+ const asList = (raw) => (Array.isArray(raw) ? raw : raw == null ? [] : [raw]);+ // Tasks that could not be written back to storage (it was refusing writes). They exist only in+ // memory, so every look at storage first tries to save them again; the retry slot stays the+ // one place they are picked up from.+ const unsaved = [];+ const stashRecord = (record) => serialRetryWrite(async () => {+ const retryKey = newtabHandoffRetryKey(Number(record.tabId));+ try {+ const queue = asList((await storage.get(retryKey))?.[retryKey]);+ if (!queue.some((entry) => entry?.id === record.id)) {+ await storage.set?.({ [retryKey]: [...queue, record] });+ }+ const at = unsaved.findIndex((entry) => entry.id === record.id);+ if (at >= 0) unsaved.splice(at, 1);+ return true;+ } catch {+ if (!unsaved.some((entry) => entry.id === record.id)) unsaved.push(record);+ return false;+ }+ });++ const sendStillHoldsComposer = (tabId) => {+ const pendingSend = pendingSends.get(Number(tabId));+ if (!pendingSend || pendingSend.settled) return false;+ const value = String(getInputEl()?.value ?? '');+ if (value === pendingSend.text) return true;+ // A slash command empties the composer before its (asynchronous) preflight finishes, so an+ // empty box does not yet mean the send has committed. It has once the run is under way, and a+ // send that was queued behind a run settles by itself.+ return pendingSend.text.startsWith('/') && value === '' && (pendingSend.queued || !getIsProcessing());+ };++ function retrySoon(tabId) {+ // 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. The budget belongs+ // to the tab whose send is being waited for, so another tab's polling does not use it up.+ const polls = (retries.get(Number(tabId)) ?? 0) + 1;+ if (polls > NEWTAB_HANDOFF_SEND_HOLD_MAX_RETRIES) {+ retries.delete(Number(tabId));+ return;+ }+ retries.set(Number(tabId), polls);+ if (retryTimer) return;+ retryTimer = setTimeout(() => {+ retryTimer = null;+ consume();+ }, NEWTAB_HANDOFF_SEND_RETRY_MS);+ }++ async function consume() {+ if (!ready || !getIsDocumentVisible()) return false;+ // A record can arrive while another is being claimed (the new tab unlocks as+ // soon as the first is removed). Remember it and look again when this ends.+ if (consuming) {+ rerun = true;+ return false;+ }+ const tabId = getCurrentTabId();+ if (tabId == null) return false;+ if (sendStillHoldsComposer(tabId)) {+ if (!heldSince.has(Number(tabId))) heldSince.set(Number(tabId), now());+ retrySoon(tabId);+ return false;+ }+ retries.delete(Number(tabId));+ if (heldSince.has(Number(tabId))) {+ heldAllowanceMs.set(+ Number(tabId),+ Math.max(+ heldAllowanceMs.get(Number(tabId)) ?? 0,+ Math.min(now() - heldSince.get(Number(tabId)), NEWTAB_HANDOFF_MAX_STARTUP_ALLOWANCE_MS),+ ),+ );+ heldSince.delete(Number(tabId));+ }+ const primaryKey = newtabHandoffKey(Number(tabId));+ const retryKey = newtabHandoffRetryKey(Number(tabId));+ let key = primaryKey;+ let claimedOne = false;+ consuming = true;+ // Anything that could not be saved earlier gets another try before storage is read.+ for (const record of unsaved.slice()) await stashRecord(record);+ const heldAllowance = heldAllowanceMs.get(Number(tabId)) ?? 0;+ // The shared composer belongs to whichever tab is active now. If the user switches+ // 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);+ // 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 = stashRecord;+ const retryWaiting = async () => {+ try {+ return asList((await storage.get(retryKey))?.[retryKey]).length > 0;+ } catch {+ return false;+ }+ };+ // Takes the record just read out of storage: the primary key is simply removed, the retry+ // slot drops that one entry and keeps the others.+ const removeClaimed = (record) => {+ if (key !== retryKey) return storage.remove(key);+ return serialRetryWrite(async () => {+ const rest = asList((await storage.get(retryKey))?.[retryKey]).filter((entry) => entry?.id !== record?.id);+ if (rest.length) await storage.set?.({ [retryKey]: rest });+ else await storage.remove(retryKey);+ });+ };+ try {+ // Every task typed before the panel finished starting was delayed by that startup, whichever+ // tab it belongs to and whichever tab is looked at first.+ const accept = (record) => {+ const delayedByStartup = Number(record?.createdAt) <= startedUpAt ? startupAllowanceMs : 0;+ return normalizeNewtabHandoff(record, now(), NEWTAB_HANDOFF_MAX_AGE_MS + delayedByStartup + heldAllowance);+ };+ let stored = (await storage.get(primaryKey))?.[primaryKey];+ let handoff = stored == null ? null : accept(stored);+ // A stale or malformed primary record is left where it is: the new tab replaces it once+ // its own lock has run out, and deleting the key from an earlier read could take a task+ // written in between (storage has no compare-and-delete). Look in the retry slot instead.+ if (!handoff && sameTab()) {+ stored = asList((await storage.get(retryKey))?.[retryKey])[0];+ key = retryKey;+ handoff = stored == null ? null : accept(stored);+ }+ if (stored == null) {+ heldAllowanceMs.delete(Number(tabId)); // nothing left that the hold could have delayed+ return false;+ }+ if (!sameTab()) return false;+ if (!handoff) {+ // Only the panel writes the retry slot, so dropping an expired entry is safe.+ if (key === retryKey) {+ await removeClaimed(stored);+ claimedOne = true; // others may be waiting behind it+ }+ return false;+ }+ if (handoff.tabId !== Number(tabId) || handled.has(handoff.id)) return false;++ handled.add(handoff.id);+ try {+ await removeClaimed(stored);+ } catch (error) {+ // Not claimed after all (storage refused): the record is still there, so it must stay claimable.+ handled.delete(handoff.id);+ throw error;+ }+ if (!sameTab()) {+ // Switched during the removal: put the record back for when this tab is shown again.+ handled.delete(handoff.id);+ // The new tab already showed this task as handed over, so it must outlive the freshness+ // window that has been running since it was typed.+ await stashForLater({ ...stored, createdAt: now() });+ return false;+ }++ const input = getInputEl();+ // Never overwrite what is already in the composer. The task goes below it,+ // and the panel keeps the mode that draft was written in: switching it would+ // change what confirming the combined draft does (an Ask draft would become+ // an Act, or the reverse).+ // `existing` is only for the emptiness / equality checks; the draft itself is kept as typed.+ const draft = String(input.value || '');+ const existing = draft.trim();+ const keepsDraft = Boolean(existing) && existing !== handoff.text;+ if (!keepsDraft) setMode(handoff.mode);+ const composerText = keepsDraft ? `${draft}\n\n${handoff.text}` : handoff.text;+ const fill = () => {+ input.value = composerText;+ input.dispatchEvent(new Event('input', { bubbles: true }));+ autoResizeInput();+ };+ fill();+ input.focus?.();+ if (!getIsBlocked() && !keepsDraft) {+ // sendMessage reads the composer synchronously when called, so starting it+ // here captures this task. It is not awaited: a send can last a whole run,+ // and that must not hold up later hand-offs or the panel's own startup.+ const send = { text: handoff.text, settled: false, queued: Boolean(getIsProcessing()) };+ pendingSends.set(Number(tabId), send);+ let sending;+ try {- sending = Promise.resolve(sendMessage(getIsProcessing() ? { __deliveryMode: 'queue' } : undefined));++ // __mode pins the mode the user chose in the box: with automatic mode selection the++ // panel would otherwise pick one itself, and Ask must stay read-only while Act acts.++ sending = Promise.resolve(sendMessage({++ ...(getIsProcessing() ? { __deliveryMode: 'queue' } : {}),++ __mode: handoff.mode,++ }));+ } catch (error) {+ sending = Promise.reject(error);+ }+ sending+ .then((result) => result !== false, () => false)+ .then((sent) => {+ send.settled = true;+ if (pendingSends.get(Number(tabId)) === send) pendingSends.delete(Number(tabId));+ // 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;+ if (sameTab()) {+ const current = String(input.value || '');+ if (!current.trim()) {+ fill();+ } else if (current.trim() !== handoff.text && !current.endsWith(`\n\n${handoff.text}`)) {+ // The user typed something else while the send was pending: keep their draft and+ // put the task below it (the record is gone, so this is the only copy left).+ input.value = `${current}\n\n${handoff.text}`;+ input.dispatchEvent(new Event('input', { bubbles: true }));+ autoResizeInput();+ }+ } 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.+ stashForLater({ ...stored, id: `${handoff.id}-retry`, createdAt: now() });+ }+ });+ }+ // A task handed back earlier may be waiting behind the one just claimed (removing a+ // primary record raises no change event this panel acts on), so look again if so.+ if (key === primaryKey) {+ claimedOne = await retryWaiting();+ // Nothing else was delayed by the hold: whatever arrives next is judged on its own age.+ if (!claimedOne) heldAllowanceMs.delete(Number(tabId));+ } else {+ // A hand-back was claimed; look again, which finds the next one or clears the allowance.+ claimedOne = true;+ }+ return true;+ } catch {+ return false;+ } finally {+ consuming = false;+ if (rerun || claimedOne) {+ rerun = false;+ queueMicrotask(() => { consume(); });+ }+ }+ }++ /** Call once the panel has finished restoring its chat. */+ function start() {+ startupAllowanceMs = Math.min(+ Math.max(0, now() - startedAt),+ NEWTAB_HANDOFF_MAX_STARTUP_ALLOWANCE_MS,+ );+ startedUpAt = now();+ ready = true;+ return consume();+ }++ function watch() {+ onChanged?.addListener((changes, area) => {+ if (area && area !== 'local') return;+ const tabId = getCurrentTabId();+ 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 hidden+ // panels, so try again the moment this one is shown.+ doc?.addEventListener?.('visibilitychange', () => {+ if (getIsDocumentVisible()) consume();+ });+ }++ return { consume, start, watch };+}diff --cc test/newtab.mjsindex 9e34b99a8,000000000..7897fa917mode 100644,000000..100644--- a/test/newtab.mjs+++ b/test/newtab.mjs@@@ -1,2550 -1,0 +1,2550 @@@+import test from 'node:test';+import assert from 'node:assert/strict';+import { existsSync, readdirSync, readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const nt = (...p) => path.join(root, 'newtab', 'src', ...p);+const load = (file) => import(pathToFileURL(file).href);++const { createNamespacedStorage, NAMESPACE_PREFIX } = await load(nt('lib/storage-namespace.js'));+const { buildHandoff, toNavigableUrl, submitTask, handoffKey, HANDOFF_PREFIX, isHandoffPending, whenClaimed, adoptPendingHandoff } = await load(nt('features/agent/handoff.js'));+const { getTitleFromUrl } = await load(nt('utils/links/getTitleFromUrl.js'));+const { normalizeLinkUrl } = await load(nt('utils/links/normalizeLinkUrl.js'));++const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++function memoryStorage(seed = {}) {+ const map = new Map(Object.entries(seed));+ return {+ get length() { return map.size; },+ key: (i) => [...map.keys()][i] ?? null,+ getItem: (k) => (map.has(k) ? map.get(k) : null),+ setItem: (k, v) => { map.set(k, String(v)); },+ removeItem: (k) => { map.delete(k); },+ clear: () => map.clear(),+ _map: map,+ };+}++test('new tab storage is namespaced and cannot touch WebBrain keys', () => {+ const real = memoryStorage({ wbLocale: 'fr', apiKey: 'secret' });+ const ls = createNamespacedStorage(real);+ ls.setItem('theme', 'dark');+ assert.equal(real.getItem(`${NAMESPACE_PREFIX}theme`), 'dark');+ assert.equal(ls.getItem('wbLocale'), null);+ assert.equal(ls.getItem('theme'), 'dark');+ ls.clear();+ assert.equal(real.getItem('wbLocale'), 'fr');+ assert.equal(real.getItem('apiKey'), 'secret');+ assert.equal(ls.length, 0);+});++test('toNavigableUrl only accepts http(s) and bare hosts', () => {+ assert.equal(toNavigableUrl('https://example.com/a'), 'https://example.com/a');+ assert.equal(toNavigableUrl('example.com'), 'https://example.com/');+ assert.equal(toNavigableUrl('localhost:3000/x'), 'https://localhost:3000/x');+ assert.equal(toNavigableUrl('javascript:alert(1)'), null);+ assert.equal(toNavigableUrl('data:text/html,hi'), null);+ assert.equal(toNavigableUrl('chrome://settings'), null);+ assert.equal(toNavigableUrl('file:///etc/passwd'), null);+ assert.equal(toNavigableUrl('how do i cook rice'), null);+ assert.equal(toNavigableUrl(''), null);+});++test('buildHandoff clamps text and defaults to ask', () => {+ const h = buildHandoff({ text: 'x'.repeat(9000), mode: 'whatever', tabId: 7, now: 1000 });+ assert.equal(h.text.length, 4000);+ assert.equal(h.mode, 'ask');+ assert.equal(h.tabId, 7);+ assert.equal(buildHandoff({ text: 'a', mode: 'act', tabId: 1 }).mode, 'act');+});++test('submitTask stores the task, opens the panel from the same tick, then announces it', async () => {+ const calls = [];+ const api = {+ storage: { local: { set: (v) => { calls.push(['set', v]); return Promise.resolve(); } } },+ sidePanel: {+ setOptions: () => { calls.push(['setOptions']); return Promise.resolve(); },+ open: (o) => { calls.push(['open', o]); return Promise.resolve(); },+ },+ runtime: { sendMessage: (m) => { calls.push(['msg', m]); return Promise.resolve(); } },+ };+ const p = submitTask({ text: 'hello', mode: 'act' }, api, { id: 42 });+ // Everything needed for the user gesture must have happened synchronously.+ assert.deepEqual(calls.map((c) => c[0]), ['set', 'setOptions', 'open']);+ assert.equal(calls[0][1][handoffKey(42)].mode, 'act');+ assert.deepEqual(calls[2][1], { tabId: 42 });+ await p;+ assert.deepEqual(calls.at(-1)[1], { type: 'WB_NEWTAB_PANEL_OPENED', tabId: 42 });+ await assert.rejects(() => submitTask({ text: 'x', mode: 'ask' }, api, null));+});++function failingApi({ open, withSidePanel = true } = {}) {+ const store = new Map();+ const listeners = [];+ const api = {+ storage: {+ local: {+ set: async (v) => { for (const [k, val] of Object.entries(v)) store.set(k, val); },+ get: async (k) => (store.has(k) ? { [k]: store.get(k) } : {}),+ remove: async (k) => { store.delete(k); },+ },+ },+ runtime: { sendMessage: async () => {} },+ _store: store,+ _claim(tabId) {+ const key = handoffKey(tabId);+ const oldValue = store.get(key);+ store.delete(key);+ [...listeners].forEach((fn) => fn({ [key]: { oldValue } }, 'local'));+ },+ };+ api.storage.onChanged = {+ addListener: (fn) => listeners.push(fn),+ removeListener: (fn) => { const i = listeners.indexOf(fn); if (i >= 0) listeners.splice(i, 1); },+ };+ if (withSidePanel) api.sidePanel = { setOptions: async () => {}, open };+ return api;+}++test('a failed panel open removes the stored task so it cannot be sent later', async () => {+ const rejected = failingApi({ open: () => Promise.reject(new Error('no gesture')) });+ await assert.rejects(() => submitTask({ text: 'secret plan', mode: 'ask' }, rejected, { id: 1 }), /no gesture/);+ assert.equal(rejected._store.has(handoffKey(1)), false);++ const threw = failingApi({ open: () => { throw new Error('sync failure'); } });+ await assert.rejects(() => submitTask({ text: 'x', mode: 'ask' }, threw, { id: 1 }), /sync failure/);+ assert.equal(threw._store.has(handoffKey(1)), false);+});++test('an unavailable side panel API never stores the task', async () => {+ const api = failingApi({ withSidePanel: false });+ await assert.rejects(() => submitTask({ text: 'x', mode: 'ask' }, api, { id: 1 }));+ assert.equal(api._store.has(handoffKey(1)), false);+});++test('cleanup never removes a newer task written by another submit', async () => {+ const api = failingApi({+ open: async () => {+ api._store.set(handoffKey(1), { id: 'newer', tabId: 1, text: 'later', mode: 'ask', createdAt: Date.now() });+ throw new Error('late failure');+ },+ });+ await assert.rejects(() => submitTask({ text: 'first', mode: 'ask' }, api, { id: 1 }));+ assert.equal(api._store.get(handoffKey(1))?.id, 'newer');+});++test('two submits in the same tick: the second is refused before anything is written', async () => {+ const writes = [];+ const api = {+ storage: {+ local: {+ set: (v) => { writes.push(v); return new Promise(() => {}); }, // never settles: the first submit is still in flight+ get: async () => ({}),+ remove: async () => {},+ },+ },+ sidePanel: { setOptions: async () => {}, open: () => new Promise(() => {}) },+ runtime: { sendMessage: async () => {} },+ };+ const tab = { id: 88 };+ submitTask({ text: 'first', mode: 'ask' }, api, tab);+ assert.equal(isHandoffPending(88), true, 'locked synchronously');+ await assert.rejects(() => submitTask({ text: 'second', mode: 'ask' }, api, tab), /still being handed over/);+ assert.equal(writes.length, 1, 'only the first task was written');+});++test('a failed submit releases the lock so the next one can go through', async () => {+ const api = failingApi({ open: () => Promise.reject(new Error('blocked')) });+ await assert.rejects(() => submitTask({ text: 'a', mode: 'ask' }, api, { id: 91 }));+ assert.equal(isHandoffPending(91), false);+ api.sidePanel.open = async () => {};+ await submitTask({ text: 'b', mode: 'ask' }, api, { id: 91 });+ assert.equal(api._store.get(handoffKey(91)).text, 'b');+ api._claim(91);+ await whenClaimed({ id: 91 });+ assert.equal(isHandoffPending(91), false);+});++test('a second submit from the same tab waits until the first task has been claimed', async () => {+ const store = new Map();+ const listeners = [];+ const api = {+ storage: {+ local: {+ set: async (v) => { for (const [k, val] of Object.entries(v)) store.set(k, val); },+ get: async (k) => (store.has(k) ? { [k]: store.get(k) } : {}),+ remove: async (k) => { store.delete(k); },+ },+ onChanged: {+ addListener: (fn) => listeners.push(fn),+ removeListener: (fn) => { const i = listeners.indexOf(fn); if (i >= 0) listeners.splice(i, 1); },+ },+ },+ sidePanel: { setOptions: async () => {}, open: async () => {} },+ runtime: { sendMessage: async () => {} },+ };+ const tab = { id: 77 };+ const claim = () => {+ const key = handoffKey(77);+ const oldValue = store.get(key);+ store.delete(key);+ [...listeners].forEach((fn) => fn({ [key]: { oldValue } }, 'local'));+ };++ await submitTask({ text: 'first', mode: 'ask' }, api, tab);+ assert.equal(isHandoffPending(77), true);+ const first = store.get(handoffKey(77));+ await assert.rejects(() => submitTask({ text: 'second', mode: 'ask' }, api, tab), /still being handed over/);+ assert.equal(store.get(handoffKey(77)).id, first.id, 'the first task was not replaced');++ claim();+ await whenClaimed(tab);+ assert.equal(isHandoffPending(77), false);+ assert.equal(listeners.length, 0, 'the storage listener is removed');++ await submitTask({ text: 'second', mode: 'ask' }, api, tab);+ assert.equal(store.get(handoffKey(77)).text, 'second');+ claim();+ await whenClaimed(tab);+});++test('round-66: a wait that times out is reported as unclaimed, a real claim as claimed', async () => {+ const store = new Map();+ const listeners = [];+ const api = {+ storage: {+ local: {+ get: async (k) => (store.has(k) ? { [k]: store.get(k) } : {}),+ set: async (v) => { for (const [k, val] of Object.entries(v)) store.set(k, val); },+ remove: async (k) => { store.delete(k); },+ },+ onChanged: { addListener: (fn) => listeners.push(fn), removeListener() {} },+ },+ };+ // a record written 20 ms before the lock would run out, never claimed by any panel+ const now = Date.now();+ store.set(handoffKey(188), { id: 'x', tabId: 188, text: 't', mode: 'ask', createdAt: now - 160_000 + 20 });+ assert.equal(await adoptPendingHandoff(api, 188, now), true);+ assert.equal(await whenClaimed({ id: 188 }), false, 'timeout is not a claim');+ assert.equal(isHandoffPending(188), false);+ // a record that is removed resolves as claimed+ store.set(handoffKey(189), { id: 'y', tabId: 189, text: 't', mode: 'ask', createdAt: now });+ assert.equal(await adoptPendingHandoff(api, 189, now), true);+ const key = handoffKey(189);+ store.delete(key);+ listeners.forEach((fn) => fn({ [key]: { oldValue: {} } }, 'local'));+ assert.equal(await whenClaimed({ id: 189 }), true);+ const box = readFileSync(nt('features/agent/TaskBox.jsx'), 'utf8');+ assert.match(box, /if \(claimed === false\) \{\s*setText\(\(current\) => current \|\| value\);\s*setError\(/);+});++test('quick link style option values match what the renderer checks', () => {+ const options = readFileSync(nt('features/quicklinks/options/QuickLinksOptions.jsx'), 'utf8');+ const renderer = readFileSync(nt('features/quicklinks/QuickLinks.jsx'), 'utf8');+ const offered = [...options.slice(options.indexOf('name="quickLinksStyle"')).matchAll(/value: '([a-z_]+)'/g)]+ .map((m) => m[1]).slice(0, 3);+ assert.deepEqual(offered, ['icon', 'text', 'metro']);+ for (const style of ['text', 'metro']) {+ assert.match(renderer, new RegExp(`quickLinksStyle'\\)\\s*===\\s*'${style}'`));+ }+});++test('link titles are derived locally and never fetched', async () => {+ const realFetch = globalThis.fetch;+ globalThis.fetch = () => { throw new Error('network call'); };+ try {+ assert.equal(await getTitleFromUrl('https://www.example.com/a/b?q=1'), 'example.com');+ assert.equal(await getTitleFromUrl('docs.example.org/path'), 'docs.example.org');+ assert.equal(await getTitleFromUrl('not a url at all'), 'not a url at all');+ assert.equal(await getTitleFromUrl(''), '');+ } finally {+ globalThis.fetch = realFetch;+ }+});++test('link URLs are normalised the same way for add and edit', () => {+ assert.equal(normalizeLinkUrl('example.com'), 'https://example.com');+ assert.equal(normalizeLinkUrl(' http://example.com/x '), 'http://example.com/x');+ assert.equal(normalizeLinkUrl('HTTPS://Example.com'), 'https://Example.com');+ assert.equal(normalizeLinkUrl('javascript:alert(1)'), null);+ assert.equal(normalizeLinkUrl('javascript:alert(1)//https://a.bc'), null);+ assert.equal(normalizeLinkUrl('data:text/html,hi'), null);+ assert.equal(normalizeLinkUrl('ftp://example.com'), null);+ assert.equal(normalizeLinkUrl('nodots'), null);+ assert.equal(normalizeLinkUrl(''), null);+ assert.equal(normalizeLinkUrl(undefined), null);+});++test('editing a link uses the same normalisation as adding one', () => {+ for (const file of ['features/quicklinks/options/QuickLinksOptions.jsx', 'features/navbar/options/AppsOptions.jsx']) {+ const src = readFileSync(nt(file), 'utf8');+ const start = src.indexOf('const editLink');+ const edit = src.slice(start, start + 1500);+ assert.match(src, /normalizeLinkUrl/, file);+ assert.match(edit, /normalizeLinkUrl\(url\)/, `${file}: editLink must normalise`);+ }+});++test('the only remaining fetch in the new tab source loads the chosen background image', () => {+ const walk = (dir) => readdirSync(dir, { withFileTypes: true }).flatMap((e) =>+ e.isDirectory() ? walk(path.join(dir, e.name)) : [path.join(dir, e.name)]);+ const hits = walk(nt()).filter((f) => /\.(jsx?|mjs)$/.test(f))+ .filter((f) => /\bfetch\(|XMLHttpRequest|sendBeacon|new WebSocket/.test(readFileSync(f, 'utf8')))+ .map((f) => path.relative(nt(), f).split(path.sep).join('/'));+ assert.deepEqual(hits, ['features/background/api/blobUrl.js']);+});++for (const browser of ['chrome', 'firefox']) {+ 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`, () => {+ const now = 1_000_000;+ const ok = { id: 'a', tabId: 3, text: ' hi ', mode: 'ask', createdAt: now - 1000 };+ assert.equal(normalizeNewtabHandoff(ok, now).text, 'hi');+ assert.equal(normalizeNewtabHandoff({ ...ok, createdAt: now - 60_000 }, now), null);+ assert.equal(normalizeNewtabHandoff({ ...ok, createdAt: now + 60_000 }, now), null);+ assert.equal(normalizeNewtabHandoff({ ...ok, mode: 'dev' }, now), null);+ assert.equal(normalizeNewtabHandoff({ ...ok, text: ' ' }, now), null);+ assert.equal(normalizeNewtabHandoff({ ...ok, text: 'x'.repeat(4001) }, now), null);+ assert.equal(normalizeNewtabHandoff({ ...ok, tabId: 'x' }, now), null);+ assert.equal(normalizeNewtabHandoff(null, now), null);+ });++ async function harness({+ tabId = 3, processing = false, blocked = false, records, record, visible = true,+ start = true, sendResult, clock,+ }) {+ const seed = records ?? (record ? { [newtabHandoffKey(record.tabId)]: record } : {});+ const store = start ? {} : { ...seed };+ const log = { mode: null, sent: [], value: '' };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ const listeners = [];+ const state = { visible, tabId, time: clock ?? 100_000 };+ const handoff = createNewtabHandoff({+ storage: {+ get: async (k) => (k in store ? { [k]: store[k] } : {}),+ remove: async (k) => { delete store[k]; },+ },+ getCurrentTabId: () => state.tabId,+ getIsProcessing: () => processing,+ getIsBlocked: () => blocked,+ getIsDocumentVisible: () => state.visible,+ doc: { addEventListener: (type, fn) => { if (type === 'visibilitychange') listeners.push(fn); } },+ setMode: (m) => { log.mode = m; },+ getInputEl: () => input,+ autoResizeInput() {},+ sendMessage: async (params) => {+ log.sent.push(params);+ log.value = input.value;+ if (sendResult === false) return false;+ input.value = '';+ return undefined;+ },+ now: () => state.time,+ });+ // A started panel with nothing waiting; the record then "arrives".+ if (start) {+ await handoff.start();+ Object.assign(store, seed);+ }+ return { handoff, store, log, input, state, listeners };+ }+ for (const switchAt of ['read', 'remove']) {+ test(`${browser}: a tab switch during the ${switchAt} neither applies nor loses the old tab's task`, async () => {+ const key3 = newtabHandoffKey(3);+ const record = { id: 'r1', tabId: 3, text: 'for tab three', mode: 'ask', createdAt: 99_000 };+ const store = { [key3]: record };+ const state = { tabId: 3 };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ const sent = [];+ const handoff = createNewtabHandoff({+ storage: {+ get: async (k) => { const r = k in store ? { [k]: store[k] } : {}; if (switchAt === 'read' && !state.done) { state.tabId = 4; state.done = true; } return r; },+ remove: async (k) => { delete store[k]; if (switchAt === 'remove' && !state.done) { state.tabId = 4; state.done = true; } },+ set: async (o) => Object.assign(store, o),+ },+ getCurrentTabId: () => state.tabId,+ getIsProcessing: () => false,+ getIsBlocked: () => false,+ getIsDocumentVisible: () => true,+ doc: { addEventListener() {} },+ setMode() {},+ getInputEl: () => input,+ autoResizeInput() {},+ sendMessage: async () => { sent.push(input.value); },+ now: () => 100_000,+ });+ 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");+ // a read-time switch leaves the record where it was; a removal-time switch hands it back+ assert.equal((store[key3] ?? store[newtabHandoffRetryKey(3)]?.[0])?.id, 'r1', "the old tab's record is still waiting");+ // back on tab 3 the task is applied+ state.tabId = 3;+ await handoff.consume();+ assert.deepEqual(sent, ['for tab three']);+ });+ }++ test(`${browser}: a slash-command Ask keeps the composer held while its preflight runs`, async () => {+ const key3 = newtabHandoffKey(3);+ const store = { [key3]: { id: 'A', tabId: 3, text: '/compact question', mode: 'ask', createdAt: 99_000 } };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ let processing = false;+ const sent = [];+ let release;+ const gate = new Promise((r) => { release = r; });+ 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: () => processing,+ getIsBlocked: () => false,+ getIsDocumentVisible: () => true,+ doc: { addEventListener() {} },+ setMode() {},+ getInputEl: () => input,+ autoResizeInput() {},+ // like sidepanel.js: a slash command empties the box, then awaits its preflight+ sendMessage: async () => { sent.push(input.value); input.value = ''; await gate; return true; },+ now: () => 100_000,+ });+ await handoff.start();+ assert.equal(input.value, '');+ // a second task arrives while the first is still in preflight (box empty, not yet running)+ store[key3] = { id: 'B', tabId: 3, text: 'task B', mode: 'act', createdAt: 99_500 };+ await handoff.consume();+ assert.equal(input.value, '', 'the second task waits instead of landing in the box');+ assert.equal(store[key3]?.id, 'B', 'and stays in storage');+ release();+ await new Promise((r) => setTimeout(r, 0));+ await new Promise((r) => setTimeout(r, 0));+ await new Promise((r) => setTimeout(r, 0));+ assert.deepEqual(sent, ['/compact question', 'task B'], 'it is sent once the first send has settled');+ assert.equal(processing, false);+ });++ test(`${browser}: a task that could not be written back is kept in memory and saved on the next look`, async () => {+ const key3 = newtabHandoffKey(3);+ const store = { [key3]: { id: 'r1', tabId: 3, text: 'for tab three', mode: 'ask', createdAt: 99_000 } };+ const state = { tabId: 3, failSets: true };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ const sent = [];+ const handoff = createNewtabHandoff({+ storage: {+ get: async (k) => (k in store ? { [k]: store[k] } : {}),+ // the user switches tabs as the claim is removed; the write-back is then refused+ remove: async (k) => { delete store[k]; if (!state.switched) { state.switched = true; state.tabId = 4; } },+ set: async (o) => { if (state.failSets) throw new Error('storage refused'); Object.assign(store, o); },+ },+ getCurrentTabId: () => state.tabId,+ getIsProcessing: () => false,+ getIsBlocked: () => false,+ getIsDocumentVisible: () => true,+ doc: { addEventListener() {} },+ setMode() {},+ getInputEl: () => input,+ autoResizeInput() {},+ sendMessage: async () => { sent.push(input.value); },+ now: () => 100_000,+ });+ await handoff.start();+ assert.equal(newtabHandoffRetryKey(3) in store, false, 'the write-back failed');+ assert.deepEqual(sent, []);+ // storage works again; the next look (on any tab) saves the task for its own tab+ state.failSets = false;+ await handoff.consume();+ assert.equal(store[newtabHandoffRetryKey(3)]?.[0]?.text, 'for tab three');+ // and back on tab 3 it is applied+ state.tabId = 3;+ await handoff.consume();+ assert.deepEqual(sent, ['for tab three']);+ });++ test(`${browser}: a task handed back after a tab switch is still fresh when its tab returns`, async () => {+ const key3 = newtabHandoffKey(3);+ const store = { [key3]: { id: 'r1', tabId: 3, text: 'for tab three', mode: 'ask', createdAt: 80_000 } };+ const state = { tabId: 3, clock: 100_000 };+ 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]; if (!state.switched) { state.switched = true; state.tabId = 4; } },+ set: async (o) => Object.assign(store, o),+ },+ getCurrentTabId: () => state.tabId,+ getIsProcessing: () => false,+ getIsBlocked: () => false,+ getIsDocumentVisible: () => true,+ doc: { addEventListener() {} },+ setMode() {},+ getInputEl: () => input,+ autoResizeInput() {},+ sendMessage: async () => { sent.push(input.value); },+ now: () => state.clock,+ });+ await handoff.start(); // claimed at 100 s when 20 s old, then the user switched away+ assert.equal(store[newtabHandoffRetryKey(3)]?.[0]?.text, 'for tab three');+ state.clock = 125_000; // back after 25 s: older than 30 s counted from the original typing+ state.tabId = 3;+ await handoff.consume();+ assert.deepEqual(sent, ['for tab three'], 'the task the new tab already cleared is not dropped');+ });++ test(`${browser}: a send still in preflight on one tab stays known while another tab is shown`, async () => {+ const store = {+ [newtabHandoffKey(3)]: { id: 'A', tabId: 3, text: 'task A', mode: 'ask', createdAt: 99_000 },+ };+ const state = { tabId: 3 };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ const sends = [];+ let releaseA;+ const gateA = new Promise((r) => { releaseA = r; });+ 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: () => state.tabId,+ getIsProcessing: () => false,+ getIsBlocked: () => false,+ getIsDocumentVisible: () => true,+ doc: { addEventListener() {} },+ setMode() {},+ getInputEl: () => input,+ autoResizeInput() {},+ sendMessage: async () => {+ const text = input.value;+ sends.push(text);+ if (text === 'task A') { await gateA; input.value = ''; } // A stays in preflight, then commits+ return true;+ },+ now: () => 100_000,+ });+ await handoff.start();+ assert.deepEqual(sends, ['task A']);+ // the panel swaps in tab 4's composer; tab 4 gets and sends its own task+ state.tabId = 4;+ input.value = '';+ store[newtabHandoffKey(4)] = { id: 'B', tabId: 4, text: 'task B', mode: 'ask', createdAt: 99_500 };+ await handoff.consume();+ await new Promise((r) => setTimeout(r, 0));+ assert.deepEqual(sends, ['task A', 'task B']);+ // back on tab 3 (its composer shows A again) a new task must not be applied over A+ state.tabId = 3;+ input.value = 'task A';+ store[newtabHandoffKey(3)] = { id: 'A2', tabId: 3, text: 'task A2', mode: 'ask', createdAt: 99_800 };+ await handoff.consume();+ assert.equal(input.value, 'task A', "A's composer is untouched while A is still being sent");+ assert.equal(store[newtabHandoffKey(3)]?.id, 'A2', 'A2 waits in storage');+ releaseA();+ await new Promise((r) => setTimeout(r, 0));+ await new Promise((r) => setTimeout(r, 0));+ await new Promise((r) => setTimeout(r, 0));+ assert.equal(sends.includes('task A2'), true, 'A2 goes out once A has settled');+ });++ test(`${browser}: the time a task waited behind a send is kept for its own tab`, async () => {+ const key3 = newtabHandoffKey(3);+ const store = { [key3]: { id: 'A', tabId: 3, text: 'task A', mode: 'ask', createdAt: 99_000 } };+ const state = { tabId: 3, clock: 100_000 };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ const sends = [];+ let releaseA;+ const gateA = new Promise((r) => { releaseA = r; });+ 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: () => state.tabId,+ getIsProcessing: () => false,+ getIsBlocked: () => false,+ getIsDocumentVisible: () => true,+ doc: { addEventListener() {} },+ setMode() {},+ getInputEl: () => input,+ autoResizeInput() {},+ sendMessage: async () => {+ const text = input.value;+ sends.push(text);+ if (text === 'task A') { await gateA; input.value = ''; }+ return true;+ },+ now: () => state.clock,+ });+ await handoff.start();+ store[key3] = { id: 'A2', tabId: 3, text: 'task A2', mode: 'ask', createdAt: 99_800 };+ await handoff.consume(); // held behind A: the wait starts counting here+ assert.deepEqual(sends, ['task A']);+ state.clock = 135_000; // the send is slow; A2 is now 35 s old+ // the user looks at another tab, which has nothing waiting+ state.tabId = 4;+ input.value = '';+ await handoff.consume();+ releaseA();+ await new Promise((r) => setTimeout(r, 0));+ await new Promise((r) => setTimeout(r, 0));+ // and returns: A2 is older than 30 s only because the panel kept it waiting+ state.tabId = 3;+ input.value = '';+ await handoff.consume();+ await new Promise((r) => setTimeout(r, 0));+ assert.equal(sends.includes('task A2'), true, 'the waiting task is still accepted');+ });++ test(`${browser}: the startup delay is credited to every tab's task, not just the first one looked at`, async () => {+ const store = {+ [newtabHandoffKey(3)]: { id: 'T3', tabId: 3, text: 'task three', mode: 'act', createdAt: 100_500 },+ [newtabHandoffKey(4)]: { id: 'T4', tabId: 4, text: 'task four', mode: 'act', createdAt: 100_600 },+ };+ const state = { tabId: 3, clock: 100_000 };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ const sent = [];+ const settle = async () => { for (let i = 0; i < 5; i++) await new Promise((r) => setTimeout(r, 0)); };+ 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: () => state.tabId,+ getIsProcessing: () => false,+ getIsBlocked: () => false,+ getIsDocumentVisible: () => true,+ doc: { addEventListener() {} },+ setMode() {},+ getInputEl: () => input,+ autoResizeInput() {},+ sendMessage: async () => { sent.push(input.value); input.value = ''; },+ now: () => state.clock,+ });+ state.clock = 150_000; // a cold panel took 50 s to restore its chat; both tasks are ~50 s old+ await handoff.start();+ await settle();+ assert.deepEqual(sent, ['task three']);+ state.tabId = 4;+ await handoff.consume();+ await settle();+ assert.deepEqual(sent, ['task three', 'task four'], "the second tab's equally old task is accepted too");+ // a task typed after startup gets no such credit+ store[newtabHandoffKey(3)] = { id: 'late', tabId: 3, text: 'late', mode: 'act', createdAt: 150_100 };+ state.clock = 190_000; // 40 s old, more than the ordinary 30 s+ state.tabId = 3;+ await handoff.consume();+ await settle();+ assert.deepEqual(sent, ['task three', 'task four'], 'a task created after startup uses the ordinary window');+ });++ test(`${browser}: the hold allowance is dropped once the delayed task has been claimed`, async () => {+ const key3 = newtabHandoffKey(3);+ const store = { [key3]: { id: 'A', tabId: 3, text: 'task A', mode: 'ask', createdAt: 99_000 } };+ const state = { clock: 100_000 };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ const sent = [];+ let releaseA;+ const gateA = new Promise((r) => { releaseA = r; });+ 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); await gateA; input.value = ''; return true; },+ now: () => state.clock,+ });+ await handoff.start();+ // an Act task waits behind A's slow send (nothing is sent for it, so no later look follows)+ store[key3] = { id: 'B', tabId: 3, text: 'task B', mode: 'act', createdAt: 99_800 };+ await handoff.consume();+ state.clock = 135_000; // B is 35 s old because of the hold+ releaseA();+ for (let i = 0; i < 6; i++) await new Promise((r) => setTimeout(r, 0));+ assert.deepEqual(sent, ['task A', 'task B'], 'the delayed task is accepted and sent');+ // a later, unrelated task that is genuinely stale (40 s) must not borrow the allowance+ store[key3] = { id: 'C', tabId: 3, text: 'task C', mode: 'act', createdAt: state.clock - 40_000 };+ await handoff.consume();+ for (let i = 0; i < 5; i++) await new Promise((r) => setTimeout(r, 0));+ assert.deepEqual(sent, ['task A', 'task B'], 'it is judged on its own age');+ });++ test(`${browser}: a declined send never refills another tab's composer; the task goes back to its own tab`, async () => {+ const key3 = newtabHandoffKey(3);+ const store = { [key3]: { id: 'r1', tabId: 3, text: 'for tab three', mode: 'ask', createdAt: 99_000 } };+ const state = { tabId: 3 };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ let release;+ const gate = new Promise((r) => { release = r; });+ 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: () => state.tabId,+ getIsProcessing: () => false,+ getIsBlocked: () => false,+ getIsDocumentVisible: () => true,+ doc: { addEventListener() {} },+ setMode() {},+ getInputEl: () => input,+ autoResizeInput() {},+ sendMessage: async () => { input.value = ''; await gate; return false; },+ now: () => 100_000,+ });+ await handoff.start();+ state.tabId = 4; // user switches while the send is pending...+ release(); // ...and it is then declined+ 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[newtabHandoffRetryKey(3)]?.[0]?.text, 'for tab three', 'the task is waiting for tab 3 again');+ assert.equal(store[newtabHandoffRetryKey(3)][0].id, 'r1-retry');+ });++ test(`${browser}: a declined send keeps a draft typed meanwhile and adds the task below it`, async () => {+ const key3 = newtabHandoffKey(3);+ const store = { [key3]: { id: 'A', tabId: 3, text: 'task A', mode: 'ask', createdAt: 99_000 } };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ let release;+ const gate = new Promise((r) => { release = r; });+ 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 () => { input.value = 'my own draft'; await gate; return false; },+ now: () => 100_000,+ });+ await handoff.start();+ release();+ await new Promise((r) => setTimeout(r, 0));+ await new Promise((r) => setTimeout(r, 0));+ assert.equal(input.value, 'my own draft\n\ntask A');+ });++ test(`${browser}: a declined send does not overwrite a newer task stored for the same tab`, async () => {+ const key3 = newtabHandoffKey(3);+ const store = { [key3]: { id: 'A', tabId: 3, text: 'task A', mode: 'ask', createdAt: 99_000 } };+ const state = { tabId: 3 };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ let release;+ const gate = new Promise((r) => { release = r; });+ 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: () => state.tabId,+ getIsProcessing: () => false,+ getIsBlocked: () => false,+ getIsDocumentVisible: () => true,+ doc: { addEventListener() {} },+ setMode() {},+ getInputEl: () => input,+ autoResizeInput() {},+ sendMessage: async () => { input.value = ''; await gate; return false; },+ now: () => 100_000,+ });+ await handoff.start();+ store[key3] = { id: 'B', tabId: 3, text: 'task B', mode: 'ask', createdAt: 99_500 }; // new tab unlocked+ state.tabId = 4;+ release();+ 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)][0].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);+ });++ test(`${browser}: handing a task back never discards one already waiting in the retry slot`, async () => {+ const key3 = newtabHandoffKey(3);+ const retry3 = newtabHandoffRetryKey(3);+ const store = {+ [key3]: { id: 'B', tabId: 3, text: 'task B', mode: 'ask', createdAt: 99_500 },+ [retry3]: [{ id: 'A-retry', tabId: 3, text: 'task A', mode: 'ask', createdAt: 99_900 }],+ };+ const state = { tabId: 3 };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ let release;+ const gate = new Promise((r) => { release = r; });+ 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: () => state.tabId,+ getIsProcessing: () => false,+ getIsBlocked: () => false,+ getIsDocumentVisible: () => true,+ doc: { addEventListener() {} },+ setMode() {},+ getInputEl: () => input,+ autoResizeInput() {},+ sendMessage: async () => { input.value = ''; await gate; return false; },+ now: () => 100_000,+ });+ await handoff.start(); // B (the primary record) is claimed first and sent+ state.tabId = 4;+ release();+ for (let i = 0; i < 4; i++) await new Promise((r) => setTimeout(r, 0));+ assert.deepEqual(store[retry3].map((r) => r.id), ['A-retry', 'B-retry'], 'both tasks are kept');+ });++ test(`${browser}: a short task is not mistaken for a longer replacement draft that merely contains it`, async () => {+ const key3 = newtabHandoffKey(3);+ const store = { [key3]: { id: 'A', tabId: 3, text: 'yes', mode: 'ask', createdAt: 99_000 } };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ let release;+ const gate = new Promise((r) => { release = r; });+ 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 () => { input.value = 'yesterday'; await gate; return false; },+ now: () => 100_000,+ });+ await handoff.start();+ release();+ await new Promise((r) => setTimeout(r, 0));+ await new Promise((r) => setTimeout(r, 0));+ assert.equal(input.value, 'yesterday\n\nyes');+ });++ test(`${browser}: a task waiting in the retry slot is picked up after a newer primary one`, async () => {+ const key3 = newtabHandoffKey(3);+ const retry3 = newtabHandoffRetryKey(3);+ const store = {+ [key3]: { id: 'B', tabId: 3, text: 'task B', mode: 'act', createdAt: 99_500 },+ [retry3]: [{ id: 'A-retry', tabId: 3, text: 'task A', mode: 'act', createdAt: 99_900 }],+ };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ 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 () => {},+ now: () => 100_000,+ });+ await handoff.start();+ for (let i = 0; i < 6; i++) await new Promise((r) => setTimeout(r, 0));+ assert.equal(input.value, 'task B\n\ntask A');+ assert.deepEqual(Object.keys(store), [], 'both records were claimed');+ });++ test(`${browser}: a live retry behind a stale primary record is still delivered`, async () => {+ const key3 = newtabHandoffKey(3);+ const retry3 = newtabHandoffRetryKey(3);+ const store = {+ [key3]: { id: 'OLD', tabId: 3, text: 'too old', mode: 'act', createdAt: 1_000 },+ [retry3]: [{ id: 'A-retry', tabId: 3, text: 'task A', mode: 'act', createdAt: 99_900 }],+ };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ 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 () => {},+ now: () => 100_000,+ });+ await handoff.start();+ for (let i = 0; i < 6; i++) await new Promise((r) => setTimeout(r, 0));+ assert.equal(input.value, 'task A');+ assert.deepEqual(Object.keys(store), [key3], 'only the stale primary is left behind, untouched');+ });++ test(`${browser}: a failed claim leaves the task deliverable on the next attempt`, async () => {+ const key3 = newtabHandoffKey(3);+ const store = { [key3]: { id: 'A', tabId: 3, text: 'task A', mode: 'act', createdAt: 99_500 } };+ let failRemove = true;+ const input = { value: '', dispatchEvent() {}, focus() {} };+ const handoff = createNewtabHandoff({+ storage: {+ get: async (k) => (k in store ? { [k]: store[k] } : {}),+ remove: async (k) => { if (failRemove) throw new Error('storage unavailable'); 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 () => {},+ now: () => 100_000,+ });+ assert.equal(await handoff.start(), false);+ assert.equal(input.value, '');+ failRemove = false;+ assert.equal(await handoff.consume(), true);+ 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;+ }+ });++ test(`${browser}: the polling budget belongs to the tab being waited for`, async () => {+ const key3 = newtabHandoffKey(3);+ const key4 = newtabHandoffKey(4);+ const store = { [key3]: { id: 'A', tabId: 3, text: 'task A', mode: 'ask', createdAt: 99_900 } };+ const state = { tabId: 3, looks: 0 };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ const timers = [];+ const realSetTimeout = globalThis.setTimeout;+ globalThis.setTimeout = (fn) => { timers.push(fn); return timers.length; };+ const step = async (n) => {+ for (let i = 0; i < n && timers.length; i++) {+ timers.shift()();+ for (let k = 0; k < 30; k++) await Promise.resolve();+ }+ };+ try {+ const never = new Promise(() => {}); // sends stay in preflight for the whole test+ 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: () => state.tabId,+ getIsProcessing: () => false,+ getIsBlocked: () => false,+ getIsDocumentVisible: () => { state.looks += 1; return true; },+ doc: { addEventListener() {} },+ setMode() {},+ getInputEl: () => input,+ autoResizeInput() {},+ sendMessage: async () => { await never; },+ now: () => 100_000,+ });+ await handoff.start(); // A's send holds tab 3's composer+ state.tabId = 4;+ input.value = '';+ store[key4] = { id: 'C', tabId: 4, text: 'task C', mode: 'ask', createdAt: 99_990 };+ await handoff.consume(); // C's send holds tab 4's composer+ state.tabId = 3;+ input.value = 'task A';+ store[key3] = { id: 'B', tabId: 3, text: 'task B', mode: 'ask', createdAt: 99_950 };+ await handoff.consume(); // B waits behind A; polling starts+ await step(97); // most of tab 3's budget is spent+ state.tabId = 4;+ input.value = 'task C';+ store[key4] = { id: 'D', tabId: 4, text: 'task D', mode: 'ask', createdAt: 99_995 };+ await handoff.consume(); // D waits behind C+ const before = state.looks;+ await step(40);+ assert.ok(state.looks - before >= 35, `tab 4 keeps polling on its own budget (${state.looks - before} looks)`);+ } finally {+ globalThis.setTimeout = realSetTimeout;+ }+ });++ test(`${browser}: a task delayed by the panel's own hold is not stale when the send settles`, async () => {+ const key3 = newtabHandoffKey(3);+ const clock = { t: 100_000 };+ 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; };+ 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; },+ now: () => clock.t,+ });+ await handoff.start();+ store[key3] = { id: 'B', tabId: 3, text: 'task B', mode: 'ask', createdAt: clock.t };+ await handoff.consume(); // B waits behind A: the hold starts here+ for (let i = 0; i < 400; i++) await Promise.resolve();+ clock.t += 45_000; // A's preflight takes 45 s: B is older than the 30 s a record is accepted for+ finishA();+ for (let i = 0; i < 20; i++) await new Promise((r) => realSetTimeout(r, 0));+ assert.equal(calls, 2, 'B was still delivered');+ assert.equal(key3 in store, false);+ } finally {+ globalThis.setTimeout = realSetTimeout;+ }+ });++ test(`${browser}: the hold allowance lasts until every task it delayed has been considered`, async () => {+ const key3 = newtabHandoffKey(3);+ const retry3 = newtabHandoffRetryKey(3);+ const clock = { t: 100_000 };+ const store = {+ [key3]: { id: 'C', tabId: 3, text: 'task C', mode: 'ask', createdAt: 99_950 },+ [retry3]: [{ id: 'B-retry', tabId: 3, text: 'task B', mode: 'ask', createdAt: 99_900 }],+ };+ const input = { value: '', dispatchEvent() {}, focus() {} };+ let finishC;+ const gateC = new Promise((r) => { finishC = r; });+ const sentTexts = [];+ const realSetTimeout = globalThis.setTimeout;+ globalThis.setTimeout = (fn) => { queueMicrotask(fn); return 0; };+ 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 () => {+ const text = input.value;+ sentTexts.push(text);+ if (text === 'task C') await gateC;+ input.value = '';+ return true;+ },+ now: () => clock.t,+ });+ await handoff.start(); // C is sent first; B (retry slot) is put off behind it+ for (let i = 0; i < 400; i++) await Promise.resolve();+ clock.t += 45_000; // C's preflight is slow+ store[key3] = { id: 'D', tabId: 3, text: 'task D', mode: 'ask', createdAt: clock.t }; // fresh+ finishC();+ for (let i = 0; i < 40; i++) await new Promise((r) => realSetTimeout(r, 0));+ assert.deepEqual(sentTexts, ['task C', 'task D', 'task B']);+ assert.equal(retry3 in store, false);+ } finally {+ globalThis.setTimeout = realSetTimeout;+ }+ });++ const rec = (over = {}) => ({ id: 'r1', tabId: 3, text: 'summarise', mode: 'ask', createdAt: 99_000, ...over });+ const KEY = newtabHandoffKey(3);++ test(`${browser}: Ask is sent automatically and the record is claimed once`, async () => {+ const h = await harness({ record: rec() });+ assert.equal(await h.handoff.consume(), true);+ assert.equal(h.log.mode, 'ask');- assert.deepEqual(h.log.sent, [undefined]);++ assert.deepEqual(h.log.sent, [{ __mode: 'ask' }]);+ assert.equal(h.log.value, 'summarise');+ assert.equal(KEY in h.store, false);+ assert.equal(await h.handoff.consume(), false);+ assert.equal(h.log.sent.length, 1);+ });++ test(`${browser}: Act is sent immediately, in Act mode, like Ask`, async () => {+ const h = await harness({ record: rec({ mode: 'act', text: 'book a table' }) });+ assert.equal(await h.handoff.consume(), true);+ assert.equal(h.log.mode, 'act');- assert.equal(h.log.sent.length, 1);++ assert.deepEqual(h.log.sent, [{ __mode: 'act' }], 'the mode chosen in the box is pinned, not left to automatic selection');+ assert.equal(h.log.value, 'book a table', 'the composer held the task when it was sent');+ const ask = await harness({ record: rec({ mode: 'ask', text: 'what is this' }) });+ await ask.handoff.consume();+ assert.equal(ask.log.mode, 'ask');- assert.equal(ask.log.sent.length, 1);++ assert.deepEqual(ask.log.sent, [{ __mode: 'ask' }]);+ assert.equal(ask.log.value, 'what is this');+ });++ test(`${browser}: a record for another tab is left alone; a stale one is ignored and left in place`, async () => {+ const other = await harness({ record: rec({ tabId: 99 }) });+ assert.equal(await other.handoff.consume(), false);+ assert.equal(newtabHandoffKey(99) in other.store, true);+ // A record filed under this tab's key but naming another tab is refused too.+ const mismatched = await harness({ records: { [KEY]: rec({ tabId: 99 }) } });+ assert.equal(await mismatched.handoff.consume(), false);+ assert.equal(mismatched.log.sent.length, 0);+ assert.equal(other.log.sent.length, 0);++ const stale = await harness({ record: rec({ createdAt: 1 }), start: false });+ await stale.handoff.start();+ assert.equal(await stale.handoff.consume(), false);+ assert.equal(stale.log.sent.length, 0, 'a stale task is never applied');+ // not deleted from an earlier read: the new tab replaces it once its own lock has run out+ assert.equal(KEY in stale.store, true);+ });++ test(`${browser}: Ask during an active run is queued behind it, not dropped`, async () => {+ const h = await harness({ processing: true, record: rec() });+ assert.equal(await h.handoff.consume(), true);- assert.deepEqual(h.log.sent, [{ __deliveryMode: 'queue' }]);++ assert.deepEqual(h.log.sent, [{ __deliveryMode: 'queue', __mode: 'ask' }]);+ assert.equal(h.log.value, 'summarise');+ assert.equal(KEY in h.store, false);+ });++ test(`${browser}: Ask while the conversation is being cleared is only pre-filled`, async () => {+ const h = await harness({ blocked: true, record: rec() });+ await h.handoff.consume();+ assert.equal(h.log.sent.length, 0);+ assert.equal(h.input.value, 'summarise');+ });++ test(`${browser}: a hidden panel claims the task as soon as it becomes visible`, async () => {+ const h = await harness({ visible: false, record: rec() });+ h.handoff.watch();+ assert.equal(await h.handoff.consume(), false);+ assert.equal(KEY in h.store, true);+ h.state.visible = true;+ h.listeners.forEach((fn) => fn());+ await new Promise((r) => setTimeout(r, 0));+ await new Promise((r) => setTimeout(r, 0));+ assert.equal(h.log.sent.length, 1);+ assert.equal(KEY in h.store, false);+ });++ test(`${browser}: nothing is claimed before start(), and a slow startup does not make the task stale`, async () => {+ const h = await harness({ record: rec({ createdAt: 99_000 }), start: false, clock: 100_000 });+ assert.equal(await h.handoff.consume(), false);+ assert.equal(KEY in h.store, true);+ assert.equal(h.log.sent.length, 0);+ // Startup took 45 s: the record is now 46 s old, beyond the normal 30 s window.+ h.state.time = 145_000;+ assert.equal(await h.handoff.start(), true);- assert.deepEqual(h.log.sent, [undefined]);++ assert.deepEqual(h.log.sent, [{ __mode: 'ask' }]);+ assert.equal(KEY in h.store, false);+ });++ test(`${browser}: the startup allowance applies once and is capped`, async () => {+ const h = await harness({ record: rec({ createdAt: 99_000 }), start: false, clock: 100_000 });+ h.state.time = 100_000 + 10 * 60_000; // ten minutes of startup+ assert.equal(await h.handoff.start(), false); // allowance capped at 2 min, record far older+ assert.equal(h.log.sent.length, 0);+ });++ test(`${browser}: submissions for different tabs never overwrite each other`, async () => {+ const a = rec({ id: 'a', tabId: 3, text: 'first' });+ const b = rec({ id: 'b', tabId: 4, text: 'second' });+ const h = await harness({ records: { [newtabHandoffKey(3)]: a, [newtabHandoffKey(4)]: b } });+ await h.handoff.consume();+ await flush(); // the follow-up look for further tasks settles+ assert.equal(h.log.value, 'first');+ assert.equal(newtabHandoffKey(4) in h.store, true, "tab 4's task is untouched");+ h.state.tabId = 4;+ await h.handoff.consume();+ await flush();+ assert.equal(h.log.value, 'second');+ assert.equal(Object.keys(h.store).length, 0);+ });++ test(`${browser}: a declined send leaves the text in the composer`, async () => {+ const h = await harness({ record: rec(), sendResult: false });+ h.input.value = '';+ assert.equal(await h.handoff.consume(), true);+ assert.equal(h.log.sent.length, 1);+ await flush();+ assert.equal(h.input.value, 'summarise');+ });++ test(`${browser}: a send that lasts a whole run does not block the next hand-off`, async () => {+ const h = await harness({ record: rec() });+ let finishRun;+ const slow = createNewtabHandoff({+ storage: {+ get: async (k) => (k in h.store ? { [k]: h.store[k] } : {}),+ remove: async (k) => { delete h.store[k]; },+ },+ getCurrentTabId: () => 3,+ getIsProcessing: () => false,+ getIsDocumentVisible: () => true,+ doc: null,+ setMode() {},+ getInputEl: () => h.input,+ autoResizeInput() {},+ // Like the real send: commits (clears the composer) quickly, then runs for a long time.+ sendMessage: () => new Promise((resolve) => { h.input.value = ''; finishRun = resolve; }),+ now: () => 100_000,+ });+ await slow.start();+ const result = await Promise.race([slow.consume(), new Promise((r) => setTimeout(() => r('blocked'), 200))]);+ assert.equal(result, false); // record was already claimed by start(); nothing hangs+ h.store[KEY] = rec({ id: 'r2', text: 'next' });+ const second = await Promise.race([slow.consume(), new Promise((r) => setTimeout(() => r('blocked'), 200))]);+ assert.equal(second, true, 'the second task is claimed while the first run is still going');+ finishRun();+ });++ test(`${browser}: a record that arrives while another is being claimed is retried`, async () => {+ const h = await harness({ record: rec({ id: 'r1', text: 'first' }) });+ const sent = [];+ const handoff = createNewtabHandoff({+ storage: {+ get: async (k) => (k in h.store ? { [k]: h.store[k] } : {}),+ remove: async (k) => { delete h.store[k]; },+ },+ getCurrentTabId: () => 3,+ getIsProcessing: () => false,+ getIsDocumentVisible: () => true,+ doc: null,+ setMode: () => {+ // The new tab unlocks once the first record is removed, so the next one+ // lands (and its storage event calls consume) while this claim is running.+ if (!h.store[KEY] && !sent.length) {+ h.store[KEY] = rec({ id: 'r2', text: 'second' });+ handoff.consume();+ }+ },+ getInputEl: () => h.input,+ autoResizeInput() {},+ sendMessage: async () => { sent.push(h.input.value); h.input.value = ''; },+ now: () => 100_000,+ });+ await handoff.start();+ h.store[KEY] = rec({ id: 'r1', text: 'first' });+ await handoff.consume();+ await flush();+ await flush();+ assert.deepEqual(sent, ['first', 'second']);+ assert.equal(KEY in h.store, false);+ });++ test(`${browser}: a second hand-off waits while the first Ask still holds the composer`, async () => {+ const h = await harness({ record: rec({ id: 'r1', text: 'first' }) });+ const sent = [];+ let commitFirst;+ const handoff = createNewtabHandoff({+ storage: {+ get: async (k) => (k in h.store ? { [k]: h.store[k] } : {}),+ remove: async (k) => { delete h.store[k]; },+ },+ getCurrentTabId: () => 3,+ getIsProcessing: () => false,+ getIsDocumentVisible: () => true,+ doc: null,+ setMode() {},+ getInputEl: () => h.input,+ autoResizeInput() {},+ // The send checks the composer, so the draft stays put until it has committed.+ sendMessage: () => new Promise((resolve) => {+ sent.push(h.input.value);+ commitFirst = () => { h.input.value = ''; resolve(undefined); };+ }),+ now: () => 100_000,+ });+ await handoff.start();+ h.store[KEY] = rec({ id: 'r1', text: 'first' });+ await handoff.consume();+ assert.deepEqual(sent, ['first']);++ // The next task lands before the first send has committed.+ h.store[KEY] = rec({ id: 'r2', text: 'second' });+ assert.equal(await handoff.consume(), false);+ assert.equal(h.input.value, 'first', "the first task's text was not replaced");+ assert.equal(KEY in h.store, true, 'the second task is still waiting');++ commitFirst();+ await new Promise((r) => setTimeout(r, 400));+ assert.deepEqual(sent, ['first', 'second']);+ assert.equal(KEY in h.store, false);+ });++ test(`${browser}: Act never replaces what is already in the composer`, async () => {+ const h = await harness({ record: rec({ mode: 'act', text: 'book a table at 8' }) });+ h.input.value = 'book a table';+ assert.equal(await h.handoff.consume(), true);+ assert.equal(h.input.value, 'book a table\n\nbook a table at 8');+ assert.equal(h.log.sent.length, 0);+ assert.equal(h.log.mode, null, 'the draft keeps the mode it was written in');++ // The same text twice is not duplicated; an empty composer is filled and the task is sent.+ const same = await harness({ record: rec({ mode: 'act', text: 'x' }) });+ same.input.value = 'x';+ await same.handoff.consume();+ assert.equal(same.log.value, 'x');+ const empty = await harness({ record: rec({ mode: 'act', text: 'y' }) });+ await empty.handoff.consume();+ assert.equal(empty.log.value, 'y');+ assert.equal(empty.log.sent.length, 1);+ });++ test(`${browser}: Ask never overwrites an existing draft and is not sent over it`, async () => {+ const h = await harness({ record: rec({ text: 'summarise this' }) });+ h.input.value = 'my half-written email to Sam';+ assert.equal(await h.handoff.consume(), true);+ assert.equal(h.input.value, 'my half-written email to Sam\n\nsummarise this');+ assert.equal(h.log.sent.length, 0, 'the combined text is left for the user to review and send');+ assert.equal(h.log.mode, null, 'an Act draft is not turned into an Ask (or the reverse)');+ assert.equal(KEY in h.store, false);+ });++ test(`${browser}: an existing draft keeps its own whitespace when the task is added below it`, async () => {+ const h = await harness({ record: rec({ text: 'summarise this' }) });+ h.input.value = ' indented code\n more ';+ assert.equal(await h.handoff.consume(), true);+ assert.equal(h.input.value, ' indented code\n more \n\nsummarise this');+ const blank = await harness({ record: rec({ mode: 'act', text: 'task' }) });+ blank.input.value = ' \n ';+ await blank.handoff.consume();+ assert.equal(blank.log.value, 'task', 'a whitespace-only composer counts as empty');+ });++ test(`${browser}: manifest and background are wired`, () => {+ const manifest = JSON.parse(readFileSync(path.join(root, 'src', browser, 'manifest.json'), 'utf8'));+ assert.equal(manifest.chrome_url_overrides?.newtab, 'newtab/index.html');+ assert.ok(manifest.permissions.includes('search'));+ assert.ok(existsSync(path.join(root, 'src', browser, 'newtab/index.html')), 'run npm run build:newtab');+ const bg = readFileSync(path.join(root, 'src', browser, 'src/background.js'), 'utf8');+ assert.match(bg, /WB_NEWTAB_PANEL_OPENED/);+ // Unclaimed records are cleaned up without waiting for another submission.+ assert.match(bg, /tabs\.onRemoved\.addListener\(\(closedTabId\)[^]*?wbNewtabHandoff:\$\{closedTabId\}/);+ assert.match(bg, /runtime\.onStartup\?\.addListener\?\.\(async \(\) => \{\s*try \{[\s\S]*startsWith\('wbNewtabHandoff:'\)/);+ });+}++test('new tab and side panel agree on the hand-off key', async () => {+ const { NEWTAB_HANDOFF_PREFIX: panelPrefix, newtabHandoffKey } =+ await load(path.join(root, 'src/chrome/src/ui/newtab-handoff.js'));+ assert.equal(HANDOFF_PREFIX, panelPrefix);+ assert.equal(handoffKey(12), newtabHandoffKey(12));+ for (const b of ['chrome', 'firefox']) {+ const bg = readFileSync(path.join(root, 'src', b, 'src/background.js'), 'utf8');+ assert.ok(bg.includes(`'${panelPrefix}'`), `${b} background sweeps ${panelPrefix}*`);+ }+});++test('both extensions ship an identical handoff module', () => {+ const a = readFileSync(path.join(root, 'src/chrome/src/ui/newtab-handoff.js'), 'utf8');+ const b = readFileSync(path.join(root, 'src/firefox/src/ui/newtab-handoff.js'), 'utf8');+ assert.equal(a, b);+});++test('built new tab is identical in both extensions and calls no external host', () => {+ const dirs = ['chrome', 'firefox'].map((b) => path.join(root, 'src', b, 'newtab'));+ const html = dirs.map((d) => readFileSync(path.join(d, 'index.html'), 'utf8'));+ assert.equal(html[0], html[1]);+ assert.doesNotMatch(html[0], /https?:\/\//);+ assert.doesNotMatch(html[0], /<script(?![^>]*src=)[^>]*>[^<]/, 'no inline script (MV3 CSP)');+});++test('every WebBrain locale has every new tab string', async (t) => {+ let esbuild;+ try {+ esbuild = await import(pathToFileURL(path.join(root, 'newtab/node_modules/esbuild/lib/main.js')).href);+ } catch {+ return t.skip('newtab dependencies are not installed');+ }+ const out = await esbuild.build({+ entryPoints: [nt('lib/wb-strings.js')],+ bundle: true,+ write: false,+ format: 'esm',+ nodePaths: [nt()],+ platform: 'node',+ });+ const code = `data:text/javascript;base64,${Buffer.from(out.outputFiles[0].text).toString('base64')}`;+ const { WB_STRINGS } = await import(code);+ const expected = 'en zh ar bn nl tl fr de he hi id ja ko ms fa pl pt ru es th tr uk vi'.split(' ');+ assert.deepEqual(Object.keys(WB_STRINGS).sort(), [...expected].sort());+ const keys = Object.keys(WB_STRINGS.en);+ assert.equal(keys.length, 18);+ for (const lang of expected) {+ for (const k of keys) {+ assert.ok(String(WB_STRINGS[lang][k] ?? '').trim(), `${lang} is missing ${k}`);+ }+ }+});++test('first run on an empty store writes the defaults instead of throwing', async (t) => {+ let esbuild;+ try {+ esbuild = await import(pathToFileURL(path.join(root, 'newtab/node_modules/esbuild/lib/main.js')).href);+ } catch {+ return t.skip('newtab dependencies are not installed');+ }+ const out = await esbuild.build({+ stdin: {+ contents: "import variables from 'config/variables'; export { moveSettings } from 'utils/settings/move'; export { variables };",+ resolveDir: nt(),+ loader: 'js',+ },+ bundle: true,+ write: false,+ format: 'esm',+ nodePaths: [nt()],+ platform: 'node',+ });+ const mod = await import(`data:text/javascript;base64,${Buffer.from(out.outputFiles[0].text).toString('base64')}`);+ mod.variables.getMessage = () => 'New Tab';++ const real = globalThis.localStorage;+ const store = memoryStorage();+ Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: new Proxy(store, {+ ownKeys: () => [...store._map.keys()],+ getOwnPropertyDescriptor: (_t, k) => (store._map.has(k) ? { value: store._map.get(k), enumerable: true, configurable: true } : undefined),+ }) });+ try {+ assert.doesNotThrow(() => mod.moveSettings());+ assert.equal(store.getItem('firstRun'), 'true');+ assert.equal(store.getItem('taskBox'), 'true');++ // A store that already has values keeps them over the defaults.+ store.clear();+ store.setItem('taskBoxMode', 'act');+ mod.moveSettings();+ assert.equal(store.getItem('taskBoxMode'), 'act');+ assert.equal(store.getItem('firstRun'), 'true');+ } finally {+ if (real === undefined) delete globalThis.localStorage;+ else Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: real });+ }+});++test('recent chats open the clicked conversation by id', () => {+ const recent = readFileSync(nt('features/agent/RecentChats.jsx'), 'utf8');+ assert.match(recent, /\?id=\$\{encodeURIComponent\(chat\.id\)\}/);+ for (const b of ['chrome', 'firefox']) {+ const history = readFileSync(path.join(root, 'src', b, 'src/ui/history.js'), 'utf8');+ assert.match(history, /get\('id'\)/, `${b} history reads ?id=`);+ assert.match(history, /renderRecord\(initialRecordId\)/, `${b} history opens it`);+ }+});++test('EventBus.off removes the listener that was really registered', async () => {+ const doc = new EventTarget();+ const hadDocument = 'document' in globalThis;+ const previous = globalThis.document;+ globalThis.document = doc;+ try {+ const { default: EventBus } = await load(nt('utils/eventbus.js'));+ const calls = [];+ const handler = (detail) => calls.push(detail);++ EventBus.on('refresh', handler);+ EventBus.emit('refresh', 'a');+ EventBus.off('refresh', handler);+ EventBus.emit('refresh', 'b');+ assert.deepEqual(calls, ['a'], 'off() stops further calls (cleanup in React effects works)');+ assert.equal(EventBus.getListeners('refresh').length, 0);++ // Re-subscribing on every render must not pile handlers up.+ for (let i = 0; i < 5; i += 1) {+ EventBus.on('refresh', handler);+ EventBus.off('refresh', handler);+ }+ calls.length = 0;+ EventBus.emit('refresh', 'c');+ assert.deepEqual(calls, []);++ EventBus.once('ping', handler);+ EventBus.emit('ping', 1);+ EventBus.emit('ping', 2);+ assert.deepEqual(calls, [1]);++ calls.length = 0;+ EventBus.prepend('cap', handler);+ EventBus.emit('cap', 'x');+ EventBus.off('cap', handler);+ EventBus.emit('cap', 'y');+ assert.deepEqual(calls, ['x'], 'capture-phase listeners are removed too');+ } finally {+ if (hadDocument) globalThis.document = previous;+ else delete globalThis.document;+ }+});++test('picking a colour refreshes the visible background even though the type is unchanged', () => {+ const hook = readFileSync(nt('features/background/hooks/useBackgroundEvents.js'), 'utf8');+ assert.match(hook, /type === 'colour'/);+});++test('the producer lock outlasts the panel\'s accepted record age', async () => {+ const { NEWTAB_HANDOFF_MAX_AGE_MS, NEWTAB_HANDOFF_MAX_STARTUP_ALLOWANCE_MS } =+ await load(path.join(root, 'src/chrome/src/ui/newtab-handoff.js'));+ const longest = NEWTAB_HANDOFF_MAX_AGE_MS + NEWTAB_HANDOFF_MAX_STARTUP_ALLOWANCE_MS;+ const number = (text, re) => Number(re.exec(text)[1].replace(/_/g, ''));++ const lock = number(readFileSync(nt('features/agent/handoff.js'), 'utf8'), /CLAIM_TIMEOUT_MS = ([\d_]+)/);+ assert.ok(lock > longest, `producer lock ${lock} must exceed ${longest}`);+});++test('the recent-chats switch refreshes the widgets', () => {+ const src = readFileSync(nt('features/agent/TaskBoxOptions.jsx'), 'utf8');+ assert.match(src, /<Switch name="recentChats" category="widgets"/);+ assert.doesNotMatch(src, /element=/, 'a missing .other element made the switch bail out');+});++test('components unsubscribe the handler they registered', () => {+ for (const file of [+ 'features/greeting/Greeting.jsx', 'features/navbar/components/Notes.jsx', 'features/navbar/Navbar.jsx',+ 'features/misc/views/Widgets.jsx', 'features/message/Message.jsx', 'features/time/Clock.jsx', 'features/time/Date.jsx',+ ]) {+ assert.doesNotMatch(readFileSync(nt(file), 'utf8'), /EventBus\.off\('refresh'\)/, file);+ }+});++test('the task box can be hidden from settings', () => {+ const src = readFileSync(nt('features/agent/TaskBoxOptions.jsx'), 'utf8');+ assert.match(src, /setting="taskBox"[^>]*visibilityToggle=\{true\}/);+});++test('deleting a custom background does not also select a card', () => {+ const src = readFileSync(nt('features/background/options/Custom.jsx'), 'utf8');+ assert.match(src, /closest\('\.delete-button'\)/);+ assert.match(src, /e\.stopPropagation\(\);\s*modifyCustomBackground\('remove', originalIndex\)/);+});++test('reset also deletes the uploaded backgrounds', () => {+ const src = readFileSync(nt('components/Elements/ResetModal/ResetModal.jsx'), 'utf8');+ assert.match(src, /import \{ clearAllBackgrounds \} from 'utils\/customBackgroundDB'/);+ assert.ok(src.indexOf('await clearAllBackgrounds()') < src.indexOf("setDefaultSettings('reset')"));+});++test('the gallery has no arrows that emit a URL the event bus drops', () => {+ const src = readFileSync(nt('features/background/options/Custom.jsx'), 'utf8');+ assert.doesNotMatch(src, /image-nav-buttons|nav-prev|nav-next/);+ assert.doesNotMatch(src, /EventBus\.emit\('refresh', 'background', [^)]*\.url\)/);+});++test('the unreachable custom-URL background flow is gone', () => {+ const src = readFileSync(nt('features/background/options/Custom.jsx'), 'utf8');+ assert.doesNotMatch(src, /addCustomURL|CustomURLModal|setCustomURLModal/);+ assert.equal(existsSync(nt('features/background/options/CustomURLModal.jsx')), false);+});++test('a superseded background load is cancelled instead of painting over the newer one', () => {+ const src = readFileSync(nt('features/background/hooks/useBackgroundRenderer.js'), 'utf8');+ assert.match(src, /let cancelled = false/);+ assert.match(src, /cancelled = true;\s*clearTimeout\(swapTimer\)/);+ assert.equal((src.match(/if \(cancelled\)/g) || []).length >= 2, true);+ assert.doesNotMatch(src, /abortControllerRef/);+});++test('the background settings header has a Hide/Show toggle', () => {+ const src = readFileSync(nt('features/background/options/BackgroundOptions.jsx'), 'utf8');+ assert.match(src, /setting="background"[\s\S]{0,120}visibilityToggle=\{true\}/);+});++for (const browserName of ['chrome', 'firefox']) {+ test(`${browserName}: Act can bootstrap navigation away from WebBrain's own new tab page`, async () => {+ const { BotMemorySession } = await import(+ pathToFileURL(path.join(root, 'src', browserName, 'src/agent/bot-memory.js')).href+ );+ const base = browserName === 'chrome' ? 'chrome-extension://abc123/' : 'moz-extension://uuid-1/';+ const api = { runtime: { getURL: (p) => base + p } };+ const prev = { chrome: globalThis.chrome, browser: globalThis.browser };+ globalThis.chrome = api;+ globalThis.browser = api;+ try {+ const check = (url) => {+ const s = Object.create(BotMemorySession.prototype);+ s.getTab = async () => ({ url });+ return s.canBootstrapNavigation(1, 'navigate', { url: 'https://example.com/' });+ };+ assert.equal(await check(`${base}newtab/index.html`), true);+ assert.equal(await check(`${base}newtab/index.html?x=1#y`), true);+ assert.equal(await check(`${base}src/ui/history.html`), false); // other extension pages: no+ assert.equal(await check('chrome-extension://evil/newtab/index.html'), browserName === 'chrome' ? false : false);+ assert.equal(await check('https://example.com/newtab/index.html'), false);+ } finally {+ globalThis.chrome = prev.chrome;+ globalThis.browser = prev.browser;+ if (prev.chrome === undefined) delete globalThis.chrome;+ if (prev.browser === undefined) delete globalThis.browser;+ }+ });+}++test('chrome agent treats the extension new tab page as a browser new tab', () => {+ const src = readFileSync(path.join(root, 'src/chrome/src/agent/agent.js'), 'utf8');+ const fn = src.slice(src.indexOf('function isBrowserNewTabUrl'), src.indexOf('function isBrowserNewTabUrl') + 700);+ assert.match(fn, /runtime\.getURL\('newtab\/index\.html'\)/);+});++test('a background refresh requested mid-load is not dropped (latest request wins)', () => {+ const src = readFileSync(nt('features/background/hooks/useBackgroundLoader.js'), 'utf8');+ assert.doesNotMatch(src, /isLoadingRef/);+ assert.match(src, /requestRef\.current/);+ assert.match(src, /await getBackgroundData\(\);\s*if \(isStale\(\)\) return;/);+});++test('PreferencesWrapper subscribes to toggle in an effect and unsubscribes', () => {+ const src = readFileSync(nt('components/Layout/Settings/PreferencesWrapper/PreferencesWrapper.jsx'), 'utf8');+ assert.match(src, /useEffect\(/);+ assert.match(src, /EventBus\.off\('toggle', handleToggle\)/);+ // the only subscription lives inside the effect body+ assert.equal((src.match(/EventBus\.on\('toggle'/g) || []).length, 1);+ assert.ok(src.indexOf("EventBus.on('toggle'") > src.indexOf('useEffect('));+});++test('enabling quick links refreshes the widget tree so the widget mounts', () => {+ const src = readFileSync(nt('features/quicklinks/options/QuickLinksOptions.jsx'), 'utf8');+ assert.match(src, /setting="quicklinksenabled"\s*category="widgets"/);+ assert.doesNotMatch(src, /element="\.quicklinks-container"/);+});++test('round-14 inherited fixes: clock timer, custom overlay, video flags, colour reset, icon errors', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ const clock = read('features/time/Clock.jsx');+ assert.match(clock, /clearTimeout\(timerRef\.current\);\s*timerRef\.current = null;\s*startTime\(0\)/);+ assert.match(read('features/background/components/BackgroundImage.jsx'), /\[isCustomType, url\]/);+ const video = read('features/background/components/BackgroundVideo.jsx');+ assert.doesNotMatch(video, /useMemo/);+ assert.match(video, /data === 'backgroundvideo'/);+ const custom = read('features/background/options/Custom.jsx');+ assert.equal((custom.match(/category="backgroundvideo"/g) || []).length, 2);+ const colour = read('features/background/options/Colour.jsx');+ assert.match(colour, /setColour\(DEFAULT_COLOUR\);\s*[^\n]*\n?\s*localStorage\.setItem\('customBackgroundColour', DEFAULT_COLOUR\)/);+ assert.match(read('features/navbar/options/AppsOptions.jsx'), /iconError=\{appsModalInfo\.iconError\}/);+ assert.match(read('features/quicklinks/options/QuickLinksOptions.jsx'), /iconError=\{iconError\}/);+});++test('the reload reminder is shown through a null-safe helper (the notice may not be mounted)', () => {+ const helper = readFileSync(nt('utils/reminder.js'), 'utf8');+ assert.match(helper, /const el = document\.querySelector\('\.reminder-info'\);\s*if \(el\)/);+ const offenders = [];+ const walk = (dir) => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) walk(full);+ else if (/\.jsx?$/.test(entry.name) && full !== nt('utils/reminder.js')+ && /querySelector\('\.reminder-info'\)\.style/.test(readFileSync(full, 'utf8'))) offenders.push(full);+ }+ };+ walk(nt('.'));+ assert.deepEqual(offenders, []);+});++test('widget Show buttons remount through the widget tree, not an element probe', () => {+ for (const f of [+ 'features/greeting/options/GreetingOptions.jsx',+ 'features/message/options/MessageOptions.jsx',+ 'features/time/options/DateOptions.jsx',+ 'features/time/options/TimeOptions.jsx',+ ]) {+ const src = readFileSync(nt(f), 'utf8');+ const at = src.indexOf('visibilityToggle', src.indexOf('setting="'));+ const start = src.lastIndexOf('<Header', at);+ const header = src.slice(start, src.indexOf('/>', at));+ assert.match(header, /category="widgets"/, f);+ assert.doesNotMatch(header, /element=/, f);+ }+});++test('the date widget rolls over to a new day and the drag handler ignores a null drop target', () => {+ const date = readFileSync(nt('features/time/Date.jsx'), 'utf8');+ assert.match(date, /setInterval\(getDate, 60_000\)/);+ assert.match(date, /clearInterval\(dayTimer\)/);+ const overview = readFileSync(nt('features/misc/sections/Overview.jsx'), 'utf8');+ assert.match(overview, /if \(over && active\.id !== over\.id\)/);+});++test('after a page reload a still-pending record keeps its lock, so a second submit cannot replace it', async () => {+ const store = new Map();+ const listeners = [];+ const api = {+ storage: {+ local: {+ get: async (k) => (store.has(k) ? { [k]: store.get(k) } : {}),+ set: async (o) => Object.entries(o).forEach(([k, v]) => store.set(k, v)),+ remove: async (k) => store.delete(k),+ },+ onChanged: { addListener: (fn) => listeners.push(fn), removeListener: (fn) => listeners.splice(listeners.indexOf(fn), 1) },+ },+ sidePanel: { setOptions: async () => {}, open: async () => {} },+ runtime: { sendMessage: async () => {} },+ };+ const tabId = 123;+ const now = Date.now();+ // nothing stored: nothing to adopt+ assert.equal(await adoptPendingHandoff(api, tabId, now), false);+ // an expired record is not adopted+ store.set(handoffKey(tabId), { id: 'old', tabId, text: 'x', mode: 'ask', createdAt: now - 200_000 });+ assert.equal(await adoptPendingHandoff(api, tabId, now), false);+ assert.equal(isHandoffPending(tabId), false);+ // a fresh record written by the previous page instance is+ store.set(handoffKey(tabId), { id: 'fresh', tabId, text: 'first', mode: 'ask', createdAt: now - 5_000 });+ assert.equal(await adoptPendingHandoff(api, tabId, now), true);+ assert.equal(isHandoffPending(tabId), true);+ await assert.rejects(() => submitTask({ text: 'second', mode: 'ask' }, api, { id: tabId }), /still being handed over/);+ assert.equal(store.get(handoffKey(tabId)).id, 'fresh');+ // the panel claims it -> released+ const key = handoffKey(tabId);+ store.delete(key);+ listeners.slice().forEach((fn) => fn({ [key]: { oldValue: {} } }, 'local'));+ await whenClaimed({ id: tabId });+ assert.equal(isHandoffPending(tabId), false);+ assert.equal(listeners.length, 0);+});++test('Show on a background that was off at load mounts it without a reload', () => {+ const app = readFileSync(nt('App.jsx'), 'utf8');+ assert.match(app, /data === 'background'[\s\S]{0,120}setShowBackground\(localStorage\.getItem\('background'\) === 'true'\)/);+ assert.match(app, /EventBus\.off\('refresh', handleRefresh\)/);+ const opts = readFileSync(nt('features/background/options/BackgroundOptions.jsx'), 'utf8');+ assert.doesNotMatch(opts, /element="#backgroundImage"/);+});++test('the new tab only publishes its tab after pending-record adoption finished', () => {+ const src = readFileSync(nt('features/agent/handoff.js'), 'utf8');+ const fn = src.slice(src.indexOf('export async function primeCurrentTab'), src.indexOf('export function buildHandoff'));+ assert.ok(fn.indexOf('await adoptPendingHandoff') < fn.indexOf('currentTab = tab'));+});++test('round-17: maximise and effect controls handle video backgrounds; dismissing the modal leaves edit mode', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ const max = read('features/navbar/components/Maximise.jsx');+ assert.match(max, /getElementById\('backgroundVideo'\)/);+ assert.match(max, /if \(widgets\) widgets\.style\.display = 'none'/);+ const fx = read('features/background/options/sections/EffectsSettings.jsx');+ assert.equal((fx.match(/element="#backgroundImage, #backgroundVideo"/g) || []).length, 4);+ assert.doesNotMatch(fx, /element="#backgroundImage"/);+ const ql = read('features/quicklinks/options/QuickLinksOptions.jsx');+ assert.match(ql, /onRequestClose=\{\(\) => \{[^}]*setEdit\(false\);\s*setEditData\(''\);/);+});++test('videoCheck accepts a File MIME type as well as data URLs and extensions', async () => {+ const { default: videoCheck } = await load(nt('features/background/api/videoCheck.js'));+ for (const yes of ['video/mp4', 'video/webm', 'video/ogg', 'data:video/mp4;base64,AAA', 'https://x/a.webm']) {+ assert.equal(videoCheck(yes), true, yes);+ }+ for (const no of ['image/png', 'image/jpeg', 'data:image/png;base64,AAA', '']) {+ assert.equal(videoCheck(no), false, no);+ }+});++test('first run does not reload forever when storage is only in memory', () => {+ const app = readFileSync(nt('App.jsx'), 'utf8');+ assert.match(app, /import \{ rawStorage \} from 'lib\/storage-namespace'/);+ assert.match(app, /if \(rawStorage\) \{\s*window\.location\.reload\(\);\s*\} else \{[\s\S]*onDefaultsApplied/);+ assert.match(app, /key=\{setupKey\}/);+});++test('round-18b: maximise toggles the overlay effects, message list changes refresh the widget, birthday is a local date', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ const max = read('features/navbar/components/Maximise.jsx');+ assert.match(max, /getElementById\('backgroundFilterOverlay'\)/);+ assert.doesNotMatch(max, /setAttribute\(/, 'no longer overwrites the image element style attribute');+ const msg = read('features/message/Message.jsx');+ assert.match(msg, /messages\.includes\(current\)/);+ assert.match(read('features/message/options/MessageOptions.jsx'), /EventBus\.emit\('refresh', 'message'\)/);+ const greet = read('features/greeting/options/GreetingOptions.jsx');+ assert.match(greet, /new Date\(year, month - 1, day\)/);+ assert.doesNotMatch(greet, /toISOString/);+ // the parse really lands on the same calendar day west of UTC+ const parse = (value) => { const [y, m, d] = value.split('-').map(Number); return new Date(y, m - 1, d); };+ const d = parse('2026-10-17');+ assert.deepEqual([d.getFullYear(), d.getMonth(), d.getDate()], [2026, 9, 17]);+});++test('round-19: import applies by reloading; multiline messages split on real newlines; week number clears', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ assert.match(read('utils/settings/import.js'), /setTimeout\(\(\) => window\.location\.reload\(\), 1200\)/);+ const msg = read('features/message/Message.jsx');+ assert.match(msg, /split\(\/\\r\?\\n\/\)/);+ assert.doesNotMatch(msg, /split\('\\\\n'\)/);+ const date = read('features/time/Date.jsx');+ assert.doesNotMatch(date, /weekNumber !== null/);+ assert.equal('a\nb\r\nc'.split(/\r?\n/).length, 3);+});++test('round-20: todo focus handlers, vertical colour resets, padded date reordering, seconds clearing', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ const todo = read('features/navbar/components/Todo.jsx');+ assert.match(todo, /onFocus=\{handleShowTodo\}/);+ assert.doesNotMatch(todo, /onFocus=\{handleHideTodo\}/);+ const time = read('features/time/options/TimeOptions.jsx');+ assert.doesNotMatch(time, /onClick=\{\(\) => localStorage\.setItem\('(hour|minute|second)Colour'/);+ assert.equal((time.match(/updateColour\('(hour|minute|second)Colour', \{ target: \{ value: '#ffffff' \} \}\)/g) || []).length, 6);+ const date = read('features/time/Date.jsx');+ assert.doesNotMatch(date, /day = dateMonth|month = dateDay|year = dateDay/);+ assert.match(read('features/time/Clock.jsx'), /setFinalSeconds\(''\)/);+});++test('round-21: Apps popup closes on blur; Maximise restores the page when it unmounts', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ assert.match(read('features/navbar/components/Apps.jsx'), /onFocus=\{handleShowApps\}/);+ const max = read('features/navbar/components/Maximise.jsx');+ assert.match(max, /useEffect\(\s*\(\) => \(\) => \{\s*if \(!hiddenRef\.current\) return;/);+ assert.match(max, /hiddenRef\.current = true/);+ assert.match(max, /hiddenRef\.current = false/);+});++test('round-22: switch is an accessible control; report link uses ?title=; uploads are not mirrored into localStorage', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ const sw = read('components/Form/Settings/Switch/Switch.jsx');+ assert.match(sw, /role="switch"/);+ assert.match(sw, /aria-label=\{label\}/);+ assert.doesNotMatch(sw, /className="switch-input"[\s\S]{0,80}aria-hidden="true"/);+ assert.match(read('components/Form/Settings/Switch/Switch.scss'), /switch-input:focus-visible/);+ assert.match(read('components/Layout/Settings/Header/Header.jsx'), /BUG_REPORT\}\?title=\$\{encodeURIComponent\(props\.title\)\}/);+ const custom = read('features/background/options/Custom.jsx');+ assert.doesNotMatch(custom, /localStorage\.setItem\('customBackground', JSON/);+ assert.equal((custom.match(/syncBackgroundCount\(backgrounds\)/g) || []).length, 3);+});++test('round-23: popups keep focus inside; reminder mounts via event; backups carry uploaded backgrounds', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ for (const f of ['Notes', 'Todo', 'Apps']) {+ const src = read(`features/navbar/components/${f}.jsx`);+ assert.match(src, /event\.currentTarget\.contains\(event\.relatedTarget\)/, f);+ assert.doesNotMatch(src, /<button[\s\S]{0,200}onBlur=/, `${f}: trigger no longer hides on its own blur`);+ }+ assert.match(read('utils/reminder.js'), /EventBus\.emit\('reminder'\)/);+ assert.match(read('components/Elements/MainModal/backend/Tabs.jsx'), /EventBus\.on\('reminder', handleReminder\)[\s\S]*EventBus\.off\('reminder', handleReminder\)/);+ const exp = read('utils/settings/export.js');+ assert.match(exp, /BACKGROUNDS_BACKUP_KEY = 'wbBackgroundsBackup'/);+ assert.match(exp, /getAllBackgroundsWithMetadata\(\)/);+ assert.match(exp, /could not be read[\s\S]*return false;/);+ const imp = read('utils/settings/import.js');+ assert.match(imp, /export async function importSettings/);+ assert.match(imp, /\[BACKGROUNDS_BACKUP_KEY\]: backgrounds/);+ assert.match(imp, /await clearAllBackgrounds\(\)[\s\S]*await addBackground\(record\)/);+});++test('round-24: filters follow the background, backups record an empty gallery, deletions reload the picture', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ const rend = read('features/background/hooks/useBackgroundRenderer.js');+ assert.match(rend, /useBackgroundFilters\(backgroundData\)[\s\S]*\[backgroundData\]/);+ assert.match(rend, /useBackgroundOverlayFilters\(backgroundData\)/);+ assert.match(rend, /element\.style\.backgroundImage = ''/);+ const bg = read('features/background/Background.jsx');+ assert.match(bg, /useBackgroundFilters\(backgroundData\)/);+ assert.match(bg, /useBackgroundOverlayFilters\(backgroundData\)/);+ const exp = read('utils/settings/export.js');+ assert.match(exp, /await getBackgroundCount\(\)/);+ assert.match(exp, /if \(backgrounds\.length !== count\) throw/);+ assert.doesNotMatch(exp, /if \(backgrounds\.length > 0\)/);+ const custom = read('features/background/options/Custom.jsx');+ assert.equal((custom.match(/EventBus\.emit\('refresh', 'backgroundrefresh'\)/g) || []).length, 2);+});++test('importSettings restores uploaded backgrounds atomically and rolls back on failure', async (t) => {+ let esbuild;+ try {+ esbuild = await import(pathToFileURL(path.join(root, 'newtab/node_modules/esbuild/lib/main.js')).href);+ } catch {+ return t.skip('newtab dependencies are not installed');+ }+ const fakes = {+ 'utils/customBackgroundDB': `+ export const db = { rows: [], nextId: 1, failAddAt: -1, adds: 0, unreadable: false };+ export const getBackgroundCount = async () => { if (db.unreadable) throw new Error('db'); return db.rows.length; };+ export const getAllBackgroundsWithMetadata = async () => db.rows.map((r) => ({ ...r }));+ export const clearAllBackgrounds = async () => { db.rows = []; };+ export const addBackground = async (r) => {+ if (db.adds++ === db.failAddAt) throw new Error('quota');+ db.rows.push({ ...r, id: db.nextId++ });+ };`,+ 'react-toastify': 'export const toast = (m) => { (globalThis.__toasts ||= []).push(m); };',+ 'config/variables': 'export default { getMessage: (k) => k, stats: { postEvent() {} } };',+ };+ const bundleImport = async (persistent) => {+ const all = {+ ...fakes,+ 'lib/storage-namespace': `export const rawStorage = ${persistent ? '{}' : 'null'};`,+ 'utils/eventbus': 'export default class EventBus { static emit(name) { (globalThis.__events ||= []).push(name); } }',+ };+ const plugin = {+ name: 'fakes',+ setup(build) {+ build.onResolve({ filter: /^(utils\/customBackgroundDB|react-toastify|config\/variables|lib\/storage-namespace|utils\/eventbus)$/ }, (a) => ({ path: a.path, namespace: 'fake' }));+ build.onLoad({ filter: /.*/, namespace: 'fake' }, (a) => ({ contents: all[a.path], loader: 'js' }));+ },+ };+ const out = await esbuild.build({+ stdin: {+ contents: "export { importSettings } from 'utils/settings/import'; export { BACKGROUNDS_BACKUP_KEY } from 'utils/settings/export'; export { db } from 'utils/customBackgroundDB';",+ resolveDir: nt(), loader: 'js',+ },+ bundle: true, write: false, format: 'esm', nodePaths: [nt()], platform: 'node', plugins: [plugin],+ });+ return import(`data:text/javascript;base64,${Buffer.from(out.outputFiles[0].text).toString('base64')}`);+ };+ const mod = await bundleImport(true);+ const memoryMod = await bundleImport(false);++ const realLs = globalThis.localStorage;+ const realTimeout = globalThis.setTimeout;+ const realWindow = globalThis.window;+ const store = memoryStorage();+ Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: store });+ globalThis.window = { location: { reload() { globalThis.__reloads = (globalThis.__reloads || 0) + 1; } } };+ globalThis.setTimeout = (fn) => { fn(); return 0; };+ try {+ const K = mod.BACKGROUNDS_BACKUP_KEY;+ const backup = (rows) => JSON.stringify({ theme: 'dark', [K]: rows });+ mod.db.rows = [{ id: 1, url: 'data:old-1' }, { id: 2, url: 'data:old-2' }];+ mod.db.nextId = 3;++ // failure part-way: the old gallery is back, nothing else is imported, no success+ mod.db.adds = 0; mod.db.failAddAt = 1;+ globalThis.__toasts = []; globalThis.__reloads = 0;+ const failed = await mod.importSettings(backup([{ id: 9, url: 'data:image/png;base64,N1==' }, { url: 'data:image/png;base64,N2==' }, { url: 'data:image/png;base64,N3==' }]));+ assert.equal(failed, false);+ assert.deepEqual(mod.db.rows.map((r) => r.url), ['data:old-1', 'data:old-2']);+ assert.equal(store.getItem('theme'), null, 'settings were not applied');+ assert.deepEqual(globalThis.__toasts, ['toasts.error'], 'no success toast');+ assert.equal(globalThis.__reloads, 0);++ // success replaces the gallery and applies settings+ mod.db.adds = 0; mod.db.failAddAt = -1; globalThis.__toasts = [];+ const ok = await mod.importSettings(backup([{ id: 9, url: 'data:image/png;base64,N1==' }, { url: 'data:image/png;base64,N2==' }]));+ assert.equal(ok, true);+ assert.deepEqual(mod.db.rows.map((r) => r.url), ['data:image/png;base64,N1==', 'data:image/png;base64,N2==']);+ // bare hosts in a backup are stored the way the add/edit dialogs would save them+ const reloads0 = globalThis.__reloads, toasts0 = globalThis.__toasts.length;+ assert.equal(await mod.importSettings(JSON.stringify({ quicklinks: JSON.stringify([{ name: 'a', url: 'example.com', key: 'k' }]), applinks: JSON.stringify([{ name: 'b', url: 'HTTP://b.test/x', key: 'j' }]) })), true);+ assert.equal(JSON.parse(store.getItem('quicklinks'))[0].url, 'https://example.com');+ assert.equal(JSON.parse(store.getItem('applinks'))[0].url, 'http://b.test/x');+ globalThis.__reloads = reloads0; globalThis.__toasts.length = toasts0;+ assert.equal(store.getItem('theme'), 'dark');+ assert.ok(globalThis.__toasts.includes('toasts.imported'));+ assert.equal(globalThis.__reloads, 1);++ // an explicit empty list clears the gallery; no list leaves it alone+ await mod.importSettings(backup([]));+ assert.deepEqual(mod.db.rows, []);+ mod.db.rows = [{ id: 5, url: 'data:keep' }];+ await mod.importSettings(JSON.stringify({ theme: 'light' }));+ assert.deepEqual(mod.db.rows.map((r) => r.url), ['data:keep']);++ // the legacy URL list is rendered entry by entry, so every entry has to be a usable address+ assert.equal(await mod.importSettings(JSON.stringify({ customBackground: JSON.stringify([{}]) })), false);+ assert.equal(await mod.importSettings(JSON.stringify({ customBackground: JSON.stringify(['']) })), false);+ assert.equal(await mod.importSettings(JSON.stringify({ customBackground: JSON.stringify(['https://x.test/a.jpg']) })), true);+ store.setItem('theme', 'light');++ // the shipped defaults (what a fresh profile exports) must import+ const defaults = JSON.parse(readFileSync(nt('utils/data/default_settings.json'), 'utf8'));+ const shipped = Object.fromEntries(+ ['applinks', 'backgroundExclude', 'customBackground', 'customEvents', 'quicklinks', 'order']+ .map((k) => [k, defaults.find((d) => d.name === k).value]),+ );+ assert.equal(shipped.customBackground, '');+ assert.equal(await mod.importSettings(JSON.stringify(shipped)), true);+ store.setItem('theme', 'light');++ // a widget listed twice would render twice and break drag-and-drop ordering+ assert.equal(await mod.importSettings(JSON.stringify({ order: JSON.stringify(['time', 'time']) })), false);+ assert.equal(await mod.importSettings(JSON.stringify({ order: JSON.stringify(['time', 'date']) })), true);+ store.setItem('theme', 'light');++ // a truncated / foreign file is reported and changes nothing+ globalThis.__toasts = [];+ for (const bad of ['{"theme": "da', '[1,2]', 'null', '"str"']) {+ assert.equal(await mod.importSettings(bad), false, bad);+ }+ assert.deepEqual(globalThis.__toasts, ['toasts.error', 'toasts.error', 'toasts.error', 'toasts.error']);+ assert.equal(store.getItem('theme'), 'light');++ // structured settings that would crash the page on the next load are refused up front+ globalThis.__toasts = []; globalThis.__reloads = 0;+ mod.db.rows = [{ id: 1, url: 'data:keep' }];+ for (const bad of [+ { customEvents: 'not-json' }, { messages: '{"a":1}' }, { applinks: '' }, { order: 'null' }, { order: '["__proto__"]' }, { order: '["time","nope"]' },+ { timezone: 'Not/AZone' }, { timezone: '' }, { favourite: '[1]' }, { favourite: '{}' }, { favourite: '{"url":" "}' }, { favourite: '{"url":5}' }, { favourite: '{"url":"not-a-url"}' }, { favourite: '{"type":"photo","url":"data:text/plain,x"}' }, { theme: { nested: true } },+ ]) {+ assert.equal(await mod.importSettings(JSON.stringify({ ...bad, [K]: [{ url: 'data:image/png;base64,OTHE' }] })), false, JSON.stringify(bad));+ }+ for (const bad of [+ { customEvents: '[null]' }, { customEvents: '[{"name":"x","month":"1","date":1}]' }, { messages: '[1]' },+ { applinks: '[{"name":"a"}]' }, { order: '[null]' }, { todo: '[{"done":true}]' }, { backgroundExclude: '[{}]' },+ ]) {+ assert.equal(await mod.importSettings(JSON.stringify(bad)), false, JSON.stringify(bad));+ }+ assert.equal(await mod.importSettings(JSON.stringify({ quicklinks: '[null]' })), false);+ // a malformed gallery record is refused as a whole; it must not clear the current gallery+ mod.db.rows = [{ id: 1, url: 'data:keep' }];+ assert.equal(await mod.importSettings(JSON.stringify({ [K]: [null] })), false);+ assert.equal(await mod.importSettings(JSON.stringify({ [K]: [{ url: 'data:image/png;base64,OK==' }, { name: 'no url' }] })), false);+ assert.equal(await mod.importSettings(JSON.stringify({ [K]: 'nope' })), false);+ assert.equal(await mod.importSettings(JSON.stringify({ [K]: [{ url: '' }] })), false);+ assert.equal(await mod.importSettings(JSON.stringify({ [K]: [{ url: ' ' }] })), false);+ for (const bad of [{ name: {} }, { folder: 5 }, { blurHash: [] }, { fileSize: '10' }, { dimensions: { width: 'x', height: 1 } }, { dimensions: 4 }]) {+ assert.equal(await mod.importSettings(JSON.stringify({ [K]: [{ url: 'https://example.com/a.jpg', ...bad }] })), false, JSON.stringify(bad));+ }+ for (const url of ['data:image/png;base64,%%%', 'data:image/png;base64,AAA', 'data:image/png,%E0%A4%A', 'data:image/png;', 'data:video/mp4,', 'data:image/png;base64,', 'not-a-url', 'data:text/plain,x', 'javascript:alert(1)', 'ftp://a.test/x.png']) {+ assert.equal(await mod.importSettings(JSON.stringify({ [K]: [{ url }] })), false, url);+ }+ mod.db.rows = [{ id: 1, url: 'data:keep' }];+ // links follow the add/edit URL policy+ for (const url of ['javascript:alert(1)', '', 'not a url', 'ftp://a.test']) {+ assert.equal(await mod.importSettings(JSON.stringify({ quicklinks: JSON.stringify([{ name: 'a', url, key: 'k' }]) })), false, url);+ assert.equal(await mod.importSettings(JSON.stringify({ applinks: JSON.stringify([{ name: 'a', url, key: 'k' }]) })), false, url);+ }+ assert.equal(await mod.importSettings(JSON.stringify({ quicklinks: '[{"name":"x"}]' })), false);+ // delete / drag-and-drop identify links by key: it must be present and unique+ assert.equal(await mod.importSettings(JSON.stringify({ quicklinks: '[{"name":"a","url":"https://a.test"}]' })), false);+ assert.equal(await mod.importSettings(JSON.stringify({ applinks: '[{"name":"a","url":"u","key":"k"},{"name":"b","url":"u","key":"k"}]' })), false);+ assert.equal(globalThis.__toasts.length, 55);+ assert.equal(globalThis.__reloads, 0);+ assert.deepEqual(mod.db.rows.map((r) => r.url), ['data:keep'], 'nothing was touched');+ assert.equal(await mod.importSettings(JSON.stringify({+ customEvents: '[]', messages: '["hi"]', applinks: '[{"name":"a","url":"https://a.test","key":"k1"}]', order: '["time"]', todo: '[]', favourite: 'null',+ })), true);+ // colour favourites must parse as a CSS background where the browser can tell+ globalThis.CSS = { supports: (_p, v) => /^(#|rgb|linear-gradient)/.test(v) };+ try {+ assert.equal(await mod.importSettings(JSON.stringify({ favourite: '{"type":"random_colour","url":"not-a-colour"}' })), false);+ assert.equal(await mod.importSettings(JSON.stringify({ favourite: '{"url":"https://img.test/a.jpg","credit":{}}' })), false);+ assert.equal(await mod.importSettings(JSON.stringify({ favourite: '{"url":"https://img.test/a.jpg","blur_hash":[],"hidden":"no"}' })), false);+ assert.equal(await mod.importSettings(JSON.stringify({ favourite: '{"url":"https://img.test/a.jpg","credit":"Ada","colour":"#fff"}' })), true);+ assert.equal(await mod.importSettings(JSON.stringify({ favourite: '{"type":"random_gradient","url":"linear-gradient(red, blue)"}' })), true);+ } finally {+ delete globalThis.CSS;+ }+ for (const tz of ['auto', 'Europe/Istanbul', 'UTC']) {+ assert.equal(await mod.importSettings(JSON.stringify({ timezone: tz })), true, tz);+ }+ for (const ok of ['{"type":"random_colour","url":"#ff00aa"}', '{"url":"https://img.test/a.jpg"}', '{"url":"data:image/png;base64,AA=="}']) {+ assert.equal(await mod.importSettings(JSON.stringify({ favourite: ok })), true, ok);+ }++ // a settings write that fails part-way (quota) rolls back both stores+ {+ const failing = memoryStorage({ theme: 'light', keep: 'me' });+ let writes = 0;+ const realSet = failing.setItem.bind(failing);+ failing.setItem = (k, v) => { if (++writes === 3) throw new DOMException('QuotaExceededError'); realSet(k, v); };+ Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: failing });+ mod.db.rows = [{ id: 1, url: 'data:keep' }];+ globalThis.__toasts = []; globalThis.__reloads = 0;+ const res = await mod.importSettings(JSON.stringify({ theme: 'dark', a: '1', b: '2', [K]: [{ url: 'data:replacement' }] }));+ assert.equal(res, false);+ assert.equal(failing.getItem('theme'), 'light', 'earlier writes are undone');+ assert.equal(failing.getItem('a'), null);+ assert.equal(failing.getItem('keep'), 'me');+ assert.deepEqual(mod.db.rows.map((r) => r.url), ['data:keep'], 'the old gallery is back');+ assert.deepEqual(globalThis.__toasts, ['toasts.error']);+ assert.equal(globalThis.__reloads, 0);+ Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: store });+ }++ // with in-memory storage an import remounts instead of reloading (a reload would drop it)+ {+ globalThis.__events = []; globalThis.__reloads = 0;+ memoryMod.db.rows = [];+ assert.equal(await memoryMod.importSettings(JSON.stringify({ theme: 'sepia' })), true);+ assert.equal(store.getItem('theme'), 'sepia');+ assert.equal(globalThis.__reloads, 0);+ assert.deepEqual(globalThis.__events, ['settingsimported']);+ }++ // an unreadable current gallery aborts instead of being wiped+ mod.db.unreadable = true;+ assert.equal(await mod.importSettings(backup([{ url: 'data:x' }])), false);+ mod.db.unreadable = false;+ assert.deepEqual(mod.db.rows.map((r) => r.url), ['data:keep']);+ } finally {+ globalThis.setTimeout = realTimeout;+ if (realWindow === undefined) delete globalThis.window; else globalThis.window = realWindow;+ if (realLs === undefined) delete globalThis.localStorage;+ else Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: realLs });+ }+});++test('round-25: video remounts per url, migration drops the localStorage copy, Navbar tracks background state', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ assert.match(read('features/background/components/BackgroundVideo.jsx'), /key=\{url\}/);+ const db = read('utils/customBackgroundDB.js');+ assert.match(db, /localStorage\.removeItem\('customBackground'\);\s*localStorage\.setItem\('customBackgroundCount'/);+ const nav = read('features/navbar/Navbar.jsx');+ assert.match(nav, /\[backgroundEnabled, setBackgroundEnabled\] = useState/);+ assert.match(nav, /setBackgroundEnabled\(localStorage\.getItem\('background'\) === 'true'\)/);+ assert.doesNotMatch(nav, /const backgroundEnabled = localStorage/);+});++test('a Storage object whose methods throw falls back to in-memory storage', async () => {+ const href = pathToFileURL(nt('lib/storage-namespace.js')).href;+ const realWindow = globalThis.window;+ try {+ const broken = { setItem() { throw new DOMException('QuotaExceededError'); }, getItem() { return null; }, removeItem() {}, key: () => null, length: 0 };+ globalThis.window = { localStorage: broken };+ const mod = await import(`${href}?broken=${Date.now()}`);+ assert.equal(mod.rawStorage, null, 'no persistent storage is claimed');+ const ls = globalThis.window.localStorage;+ ls.setItem('a', 'b');+ assert.equal(ls.getItem('a'), 'b', 'the page still has working (in-memory) settings');++ const working = memoryStorage();+ globalThis.window = { localStorage: working };+ const ok = await import(`${href}?ok=${Date.now()}`);+ assert.equal(ok.rawStorage, working, 'real storage is used when it works');+ assert.equal(working.getItem(`${NAMESPACE_PREFIX}__probe`), null, 'the probe leaves nothing behind');+ } finally {+ if (realWindow === undefined) delete globalThis.window; else globalThis.window = realWindow;+ }+});++test('round-27: document language follows the WebBrain locale; effects wait while maximised; import remount wired', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ assert.match(read('index.jsx'), /applyDocumentLanguage\(\);/);+ assert.doesNotMatch(read('index.jsx'), /documentElement\.lang = languagecode/);+ const ctx = read('contexts/TranslationContext.jsx');+ assert.doesNotMatch(ctx, /documentElement\.lang = /);+ assert.equal((ctx.match(/applyDocumentLanguage\(\)/g) || []).length, 2);+ assert.match(read('lib/document-language.js'), /WB_STRINGS\[resolved\.lang\] \? resolved : \{ lang: 'en', dir: 'ltr' \}/);+ assert.match(read('features/background/hooks/useBackgroundEvents.js'), /dataset\.bgMaximised === 'true'\) return/);+ assert.match(read('features/navbar/components/Maximise.jsx'), /dataset\.bgMaximised = 'true'/);+ assert.match(read('App.jsx'), /EventBus\.on\('settingsimported', importedHandler\)[\s\S]*EventBus\.off\('settingsimported', importedHandler\)/);+});++test('round-28: migration cleans up partial copies; maximised remounts stay unfiltered; in-memory import reapplies globals; single delete clears selection', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ assert.match(read('utils/customBackgroundDB.js'), /await addBackground\(bg\);\s*\}\s*\} catch \(error\) \{\s*try \{\s*await clearAllBackgrounds\(\);/);+ const rend = read('features/background/hooks/useBackgroundRenderer.js');+ assert.match(rend, /isMaximised\(\) \? 'blur\(0px\) brightness\(100%\)'/);+ assert.match(rend, /isMaximised\(\) \? NO_OVERLAY/);+ assert.match(read('App.jsx'), /importedHandler = \(\) => \{\s*loadSettings\(true\);/);+ const custom = read('features/background/options/Custom.jsx');+ assert.match(custom, /syncBackgroundCount\(backgrounds\);\s*\/\/ Selections are array indices[^\n]*\n\s*setSelectedImages\(new Set\(\)\);/);+});++test('round-29: an open dropdown commits the highlighted option on Enter / Space', () => {+ const src = readFileSync(nt('components/Form/Settings/Dropdown/Dropdown.jsx'), 'utf8');+ assert.match(src, /isOpen && focusedIndex >= 0\s*\? props\.items\.filter\(\(i\) => i !== null\)\[focusedIndex\]/);+ assert.match(src, /onChange\(highlighted\.value\)/);+ assert.match(src, /\[isOpen, focusedIndex, onChange, props\.items, props\.disabled\]/);+});++test('round-30: leaving the settings route with Back closes the modal', () => {+ const src = readFileSync(nt('components/Elements/MainModal/Main.jsx'), 'utf8');+ assert.match(src, /else if \(!window\.location\.hash\) \{[^}]*modalClose\?\.\(\);/);+ assert.match(src, /\[modalClose\]\);/);+});++test('round-31: history navigation keeps the breadcrumb in step; breadcrumb click updates the route', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ assert.match(read('components/Elements/MainModal/backend/Tabs.jsx'), /onSectionChange\?\.\(label, section\.name, \{ fromHistory: true \}\)/);+ const main = read('components/Elements/MainModal/Main.jsx');+ assert.match(main, /\{ fromHistory = false \} = \{\}/);+ assert.match(main, /if \(fromHistory\) return;/);+ assert.match(read('components/Elements/MainModal/components/ModalTopBar.jsx'), /onSubSectionChange\(null, currentSectionName\)/);+ assert.match(read('utils/settings/import.js'), /quicklinks: isLinkEntry/);+});++test('round-32: closing or normally opening the settings modal drops stale deep-link data', () => {+ const src = readFileSync(nt('features/misc/modals/Modals.jsx'), 'utf8');+ assert.match(src, /setMainModal\(action\);[^}]*setDeepLinkData\(null\);/);+});++test('round-33: tooltip description sits on the focusable control; initial settings sync keeps the deep-link route', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ const tip = read('components/Elements/Tooltip/Tooltip.jsx');+ assert.match(tip, /cloneElement\(children, \{ 'aria-describedby': tooltipId \}\)/);+ assert.match(tip, /<span id=\{tooltipId\} role="tooltip"/);+ assert.doesNotMatch(tip, /Math\.random/);+ assert.doesNotMatch(tip, /<div[^>]*aria-describedby/);+ const tabs = read('components/Elements/MainModal/backend/Tabs.jsx');+ assert.match(tabs, /onSectionChange\(currentTab, currentName, \{ fromHistory: true \}\)/);+});++test('round-34: keyed import lists, keyboard sections, named navbar buttons, forward-nav reopen, toast time, close button', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ assert.match(read('utils/settings/import.js'), /KEYED_LISTS[\s\S]*share a key/);+ assert.match(read('components/Layout/Settings/Section/Section.jsx'), /role="button"[\s\S]*tabIndex=\{0\}[\s\S]*onKeyDown/);+ assert.match(read('features/navbar/components/Todo.jsx'), /aria-label=\{t\('widgets\.navbar\.todo\.title'\)\}/);+ assert.match(read('features/navbar/components/Apps.jsx'), /aria-label=\{variables\.getMessage\('widgets\.navbar\.apps\.title'\)\}/);+ assert.match(read('features/misc/modals/Modals.jsx'), /addEventListener\('popstate', handlePopState\)/);+ assert.match(read('App.jsx'), /setToastDisplayTime\(parseInt\(localStorage\.getItem\('toastDisplayTime'\)/);+ assert.match(read('components/Elements/MainModal/components/ModalTopBar.jsx'), /<button\s+type="button"\s+className="closeModal"/);+});++test('round-36: reset stops when uploads cannot be cleared', () => {+ const src = readFileSync(nt('components/Elements/ResetModal/ResetModal.jsx'), 'utf8');+ assert.match(src, /catch \(error\) \{[\s\S]*toast\(variables\.getMessage\('toasts\.error'\)\);\s*return;/);+ assert.ok(src.indexOf('return;') < src.indexOf("setDefaultSettings('reset')"));+});++test('round-37: Back to a bare #settings entry shows the default section', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ assert.match(read('components/Elements/MainModal/Main.jsx'), /else if \(linkData\) \{[\s\S]*type: 'settings-default'/);+ assert.match(read('components/Elements/MainModal/backend/Tabs.jsx'), /type === 'settings-default'[\s\S]*children\[0\]\?\.props[\s\S]*fromHistory: true/);+});++test('round-37b: a navigation trigger is acted on once, not on every language change', () => {+ const tabs = readFileSync(nt('components/Elements/MainModal/backend/Tabs.jsx'), 'utf8');+ assert.match(tabs, /handledTriggerRef\.current === navigationTrigger\) return;/);+ assert.equal((tabs.match(/handledTriggerRef\.current = navigationTrigger/g) || []).length, 2);+});++test('round-38: imported links are stored normalised; gallery urls must be loadable', async () => {+ const src = readFileSync(nt('utils/settings/import.js'), 'utf8');+ assert.match(src, /normalizeLinks\(content\);/);+ assert.match(src, /data:\(image\|video\)/);+});++test('round-42: background cards and todo checkboxes work from the keyboard; nested dropdown does not open the card', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ const card = read('features/background/options/sections/NavigationCard.jsx');+ assert.match(card, /role="button"[\s\S]*tabIndex=\{0\}[\s\S]*onKeyDown/);+ assert.match(card, /event\.stopPropagation\(\)/);+ assert.match(read('components/Layout/Settings/Section/Section.jsx'), /event\.stopPropagation\(\)/);+ const todo = read('features/navbar/components/Todo.jsx');+ assert.match(todo, /role="checkbox"[\s\S]*aria-checked[\s\S]*tabIndex=\{0\}[\s\S]*onKeyDown/);+});++test('round-43: todo delete icon is a keyboard control', () => {+ const todo = readFileSync(nt('features/navbar/components/Todo.jsx'), 'utf8');+ assert.match(todo, /<MdDelete\s+role="button"\s+tabIndex=\{0\}/);+});++test('round-51: handoff records are cleared at browser start, never swept from a snapshot', () => {+ 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]*startedAt - 10_000[\s\S]*startsWith\('wbNewtabHandoff:'\)/, file);+ assert.match(src, /wbNewtabHandoff:retry:\$\{closedTabId\}/, file);+ }+});++test('round-48: dialog close controls work from the keyboard', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ for (const f of ['components/Elements/AddModal/AddModal.jsx', 'components/Elements/ResetModal/ResetModal.jsx']) {+ assert.match(read(f), /className="close"\s+role="button"\s+tabIndex=\{0\}[\s\S]*onActivateKey\(/, f);+ }+ assert.match(read('components/Elements/MainModal/components/ReminderInfo.jsx'), /<button\s+type="button"\s+className="closeModal"/);+ assert.match(read('utils/keyboard.js'), /event\.key === 'Enter' \|\| event\.key === ' '/);+});++test('round-52: a video favourite is flagged so it renders as a video', () => {+ const loader = readFileSync(nt('features/background/api/backgroundLoader.js'), 'utf8');+ assert.match(loader, /video: videoCheck\(fav\.url\)/);+});++test('round-53: video detection looks at the lower-cased path of the address', async () => {+ const videoCheck = (await load(nt('features/background/api/videoCheck.js'))).default;+ for (const url of [+ 'https://cdn.example/clip.mp4?token=abc', 'https://cdn.example/CLIP.MP4#t=3', 'data:video/mp4;base64,AA==',+ 'video/webm', 'https://a.test/x.OGG', 'clip.webm?x=1',+ ]) assert.equal(videoCheck(url), true, url);+ for (const url of ['https://cdn.example/pic.jpg?name=a.mp4', 'https://a.test/mp4', 'data:image/png;base64,AA==', '']) {+ assert.equal(videoCheck(url), false, url);+ }+ const privacy = readFileSync(path.join(root, 'docs/privacy-and-data-flow.md'), 'utf8');+ assert.doesNotMatch(readFileSync(path.join(root, "docs/newtab.md"), "utf8"), /swept each time/);+ assert.doesNotMatch(privacy, /unclaimed\s+records are removed after about three minutes/);+});++test('round-54: a remote picture that fails to load is retried as a video; the composer hold stays under the record age', async () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ assert.match(read('features/background/hooks/useBackgroundRenderer.js'), /!loaded && \/\^https\?:\/i\.test\(backgroundData\.url\)/);+ assert.match(read('features/background/Background.jsx'), /updateBackground\(\{ video: true \}\)/);+ for (const b of ['chrome', 'firefox']) {+ const mod = await load(path.join(root, `src/${b}/src/ui/newtab-handoff.js`));+ const hold = mod.NEWTAB_HANDOFF_SEND_HOLD_MAX_RETRIES * mod.NEWTAB_HANDOFF_SEND_RETRY_MS;+ assert.ok(hold <= mod.NEWTAB_HANDOFF_MAX_AGE_MS / 2, `${b}: hold ${hold} ms must be well under ${mod.NEWTAB_HANDOFF_MAX_AGE_MS}`);+ }+});++test('round-55: the video fallback also runs when the fade transition is off', () => {+ const src = readFileSync(nt('features/background/hooks/useBackgroundRenderer.js'), 'utf8');+ const skipBranch = src.slice(src.indexOf('if (!hasTransition || prefersReducedMotion)'), src.indexOf('// Create or get overlay element'));+ assert.match(skipBranch, /onRemoteImageFailedRef\.current\?\.\(backgroundData\.url\)/);+});++test('round-58: CSS url() values are quoted and escaped', () => {+ const src = readFileSync(nt('features/background/hooks/useBackgroundRenderer.js'), 'utf8');+ const match = /export const cssUrl = \(url\) =>\n\s+(`[^\n]*`);/.exec(src);+ assert.ok(match, 'cssUrl helper present');+ const cssUrl = new Function('url', `return ${match[1]};`);+ assert.equal(cssUrl('https://host/a.jpg'), 'url("https://host/a.jpg")');+ assert.equal(cssUrl('https://host/image).jpg'), 'url("https://host/image).jpg")');+ assert.equal(cssUrl('a"b\\c'), 'url("a\\"b\\\\c")');+ assert.equal(cssUrl('a\nb'), 'url("a\\a b")');+ assert.doesNotMatch(src, /`url\(\$\{/, 'no raw url(${...}) left');+});++test('round-59: reset actions are keyboard-operable; Dropdown only writes a paired setting it was given', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ for (const [f, cls] of [+ ['components/Form/Settings/Slider/Slider.jsx', 'slider-reset'],+ ['components/Form/Settings/Dropdown/Dropdown.jsx', 'dropdown-reset'],+ ['components/Form/Settings/Text/Text.jsx', 'text-field-reset'],+ ]) {+ assert.match(read(f), new RegExp(`className="${cls}"\\s+onClick=\\{resetItem\\}\\s+onKeyDown=\\{onActivateKey\\(resetItem\\)\\}\\s+role="button"\\s+tabIndex=\\{0\\}`), f);+ }+ const dd = read('components/Form/Settings/Dropdown/Dropdown.jsx');+ assert.match(dd, /props\.name2 !== undefined && props\.name2 !== null\) \{\s*localStorage\.setItem\(props\.name2, props\.value2\)/);+});++test('round-63: remaining click-only controls are keyboard-operable', () => {+ const read = (f) => readFileSync(nt(f), 'utf8');+ const time = read('features/time/options/TimeOptions.jsx');+ assert.equal((time.match(/onKeyDown=\{onActivateKey\(\(\) => updateColour\(/g) || []).length, 3);+ assert.equal((time.match(/role="button"\s+tabIndex=\{0\}/g) || []).length >= 3, true);+ assert.match(read('features/background/options/Colour.jsx'), /onKeyDown=\{onActivateKey\(\(\) => resetColour\(\)\)\}\s+role="button"\s+tabIndex=\{0\}/);+ const chips = read('components/Form/Settings/ChipSelect/ChipSelect.jsx');+ assert.match(chips, /className="chipSelect-control"[\s\S]*onKeyDown=\{onActivateKey[\s\S]*role="combobox"[\s\S]*tabIndex=\{0\}/);+ assert.match(chips, /className=\{`chipSelect-option[\s\S]*onKeyDown=\{onActivateKey[\s\S]*role="option"[\s\S]*tabIndex=\{0\}/);+});++test('round-64: a failed gallery write reaches the batch uploader instead of counting as stored', () => {+ const src = readFileSync(nt('features/background/options/Custom.jsx'), 'utf8');+ assert.match(src, /console\.error\('Error saving background:', error\);\s*throw error;/);+ assert.match(src, /error\.name === 'QuotaExceededError'/);+ assert.match(src, /errors\.push\(files\[i\]\.name\)/);+});++test('round-69: the documented hold budget matches the constants', async () => {+ const { NEWTAB_HANDOFF_SEND_RETRY_MS: every, NEWTAB_HANDOFF_SEND_HOLD_MAX_RETRIES: max } =+ await import(path.join(root, 'src/chrome/src/ui/newtab-handoff.js'));+ assert.equal((every * max) / 1000, 15);+ assert.match(readFileSync(path.join(root, 'docs/newtab.md'), 'utf8'), /retried every 150 ms, for up to about 15 s/);+});++test('round-73: icon-only buttons have an accessible name', () => {+ const unnamed = [];+ const walk = (dir) => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) walk(full);+ else if (entry.name.endsWith('.jsx')) {+ const src = readFileSync(full, 'utf8');+ for (const m of src.matchAll(/<button\b/g)) {+ let i = m.index + m[0].length;+ let depth = 0;+ for (; i < src.length; i++) {+ const c = src[i];+ if (c === '{') depth++;+ else if (c === '}') depth--;+ else if (c === '>' && depth === 0 && src[i - 1] !== '=') break;+ }+ const tag = src.slice(m.index, i + 1);+ const end = src.indexOf('</button>', i);+ const body = src.slice(i + 1, end).replace(/<Md\w+\s*\/>/g, '').trim();+ if (!body && !/aria-label=/.test(tag)) unnamed.push(`${path.relative(nt(), full)}:${src.slice(0, m.index).split('\n').length}`);+ }+ }+ }+ };+ walk(nt());+ assert.deepEqual(unnamed, [], 'icon-only <button>s need an aria-label');+});++test('round-74: gallery writes resolve only once the IndexedDB transaction has committed', async (t) => {+ let esbuild;+ try {+ esbuild = await import(pathToFileURL(path.join(root, 'newtab/node_modules/esbuild/lib/main.js')).href);+ } catch {+ return t.skip('newtab dependencies are not installed');+ }+ const out = await esbuild.build({+ entryPoints: [nt('utils/customBackgroundDB.js')],+ bundle: true, write: false, format: 'esm', platform: 'node',+ });+ // A tiny IndexedDB: every request "succeeds" a tick after it is made, the transaction settles+ // later, and with failCommit it aborts at that point (storage full) without applying anything.+ const state = { rows: [], next: 1, failCommit: false };+ const later = (fn, ms = 1) => globalThis.setTimeout(fn, ms);+ const makeTx = () => {+ const ops = [];+ const tx = { oncomplete: null, onerror: null, onabort: null, error: null };+ const request = (result, op) => {+ const req = { result: undefined, onsuccess: null, onerror: null };+ if (op) ops.push(op);+ later(() => { req.result = typeof result === 'function' ? result() : result; req.onsuccess?.(); });+ return req;+ };+ const store = {+ add: (data) => { const id = state.next++; return request(id, () => state.rows.push({ ...data, id })); },+ put: (item) => request(item.id, () => { const at = state.rows.findIndex((r) => r.id === item.id); if (at >= 0) state.rows[at] = item; }),+ get: (id) => request(() => { const row = state.rows.find((r) => r.id === id); return row && { ...row }; }),+ getAll: () => request(() => state.rows.map((r) => ({ ...r }))),+ delete: (id) => request(undefined, () => { state.rows = state.rows.filter((r) => r.id !== id); }),+ clear: () => request(undefined, () => { state.rows = []; }),+ count: () => request(() => state.rows.length),+ };+ tx.objectStore = () => store;+ later(() => {+ if (state.failCommit) {+ tx.error = new Error('QuotaExceededError');+ tx.onabort?.();+ } else {+ ops.forEach((op) => op());+ tx.oncomplete?.();+ }+ }, 15);+ return tx;+ };+ const db = { objectStoreNames: { contains: () => true }, transaction: () => makeTx() };+ const realIDB = globalThis.indexedDB;+ Object.defineProperty(globalThis, 'indexedDB', {+ configurable: true,+ value: { open: () => { const req = { result: db, onsuccess: null }; later(() => req.onsuccess?.()); return req; } },+ });+ try {+ const mod = await import(`data:text/javascript;base64,${Buffer.from(out.outputFiles[0].text).toString('base64')}`);+ // committed: the row exists by the time the promise resolves+ const id = await mod.addBackground({ url: 'data:image/png;base64,AAAA', name: 'a' });+ assert.equal(id, 1);+ assert.equal(state.rows.length, 1);+ await mod.updateBackgroundMetadata(1, { name: 'b' });+ assert.equal(state.rows[0].name, 'b');+ // every request succeeds, then the commit aborts: each write reports the failure+ state.failCommit = true;+ await assert.rejects(() => mod.addBackground({ url: 'data:image/png;base64,BBBB', name: 'c' }), /Quota/);+ await assert.rejects(() => mod.deleteBackground(0), /Quota/);+ await assert.rejects(() => mod.deleteMultipleBackgrounds([0]), /Quota/);+ await assert.rejects(() => mod.clearAllBackgrounds(), /Quota/);+ await assert.rejects(() => mod.updateBackgroundMetadata(1, { name: 'z' }), /Quota/);+ await assert.rejects(() => mod.updateBackground(0, { name: 'z' }), /Quota/);+ assert.deepEqual(state.rows.map((r) => r.name), ['b'], 'nothing from the aborted transactions was kept');+ state.failCommit = false;+ await mod.deleteMultipleBackgrounds([0]);+ assert.equal(state.rows.length, 0);+ await assert.rejects(() => mod.updateBackgroundMetadata(99, {}), /not found/);+ } finally {+ if (realIDB === undefined) delete globalThis.indexedDB;+ else Object.defineProperty(globalThis, 'indexedDB', { configurable: true, value: realIDB });+ }+});++test('round-74: gallery selection checkboxes are named', () => {+ const src = readFileSync(nt('features/background/options/Custom.jsx'), 'utf8');+ assert.match(src, /onChange=\{\(\) => toggleImageSelection\(originalIndex\)\}\s+aria-label=\{bg\.name \|\| `\$\{originalIndex \+ 1\}`\}/);+});++test('round-76: Act warns that it starts immediately, in every shipped language', () => {+ const box = readFileSync(nt('features/agent/TaskBox.jsx'), 'utf8');+ assert.match(box, /mode === 'act' && \(\s*<span className="taskBoxHint taskBoxWarning" role="note">\s*\{wbT\('wb\.act_hint'\)\}/);+ const strings = readFileSync(nt('lib/wb-strings.js'), 'utf8');+ assert.doesNotMatch(strings, /Press Enter there to run it|Pulsa Intro allÃ/);+ assert.equal((strings.match(/^ "[^"]*(?:Enter|Intro|Entrée|Eingabetaste)[^"]*",$/gm) || []).length >= 15, true);+ const h = readFileSync(path.join(root, 'src/chrome/src/ui/newtab-handoff.js'), 'utf8');+ assert.doesNotMatch(h, /handoff\.mode === 'ask' && !getIsBlocked/);+});