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
Keep a requested D1 download through Auto; let the guide's button finish D1
Claude0872c01617ff
diff --git a/docs/providers-and-models.md b/docs/providers-and-models.mdindex 0c5990384..5b5ca9c27 100644--- a/docs/providers-and-models.md+++ b/docs/providers-and-models.md@@ -153,11 +153,11 @@ retains the cache; **Remove cached model** requires the model to be unloaded.After **Download and load**, **Load** or the install guide's download, D1stays loaded until it is unloaded, removed or switched off on the Providerspage (decisions Off, or another provider saved under On). Switching to Auto-keeps it loaded while Auto uses it; while Compass is the chat provider, Auto-does not, so the Worker and its GPU memory are released and the Load request-stays for later (`releaseD1OnDecisionChange` in `background.js`). A decision-that finds D1 unloaded (a browser restart, a discarded stalled session, a lost-GPU device, or that release) starts one reload from the verified cache in the+keeps it, loaded or still downloading, while that request stands+(`releaseD1OnDecisionChange` in `background.js`); Auto uses it once it is+downloaded unless Compass is the chat provider, and **Unload** releases it. A+decision that finds D1 unloaded (a browser restart, a discarded stalled+session, a lost GPU device) starts one reload from the verified cache in thebackground and uses the fallback chain meanwhile. A reload never downloads. A decision whose callerstops waiting (a judge timeout, Stop) is cancelled in the Worker, skipped ifit was still queued, and the loaded model stays.diff --git a/docs/webgpu-models.md b/docs/webgpu-models.mdindex 2909abf1d..de9efeba8 100644--- a/docs/webgpu-models.md+++ b/docs/webgpu-models.md@@ -257,7 +257,9 @@ Use the tools in `scripts/models/bonsai/`:Mode, and the first-install page (Chrome), which offers Ternary Bonsai 2 2BVision and D1, the decision model, behind its optional "Download localmodels" button. The two download at once, each in its own worker, and the- page shows D1's progress on a line of its own. The install page checks for+ page shows D1's progress on a line of its own; once the chat model is+ ready, the same button starts, pauses, resumes or retries D1 alone. The+ install page checks forhardware WebGPU before fetching anything (D1 runs its own adapter check, anda GPU it cannot use leaves the Bonsai download going), never changes theactive provider or the decision settings, and only points an idle WebGPUdiff --git a/src/chrome/src/background.js b/src/chrome/src/background.jsindex 7886ae0c0..2c84aede6 100644--- a/src/chrome/src/background.js+++ b/src/chrome/src/background.js@@ -7,8 +7,10 @@ import { D1_CONSENT_KEY, D1_CONSENT_VERSION, D1_KEEP_LOADED_KEY } from './provid// D1's Worker and GPU memory are released when decisions are switched Off,// another decision provider is saved, consent changes or Strict Secret Mode-// starts. Leaving On (for Auto) keeps D1 loaded while Auto uses it: D1 is-// downloaded and Compass is not the chat provider (decision-availability.js).+// starts. Leaving On for Auto keeps D1, loaded or still downloading, while the+// user's Download or Load request stands: Auto uses it once it is downloaded,+// unless Compass is the chat provider (decision-availability.js), and Unload+// on the Providers page releases it.function releaseD1OnDecisionChange(changes, area) {if (area !== 'local') return;const reset = () => { void d1Request('reset').catch(() => {}); };@@ -20,7 +22,7 @@ function releaseD1OnDecisionChange(changes, area) {return;}if (changes.systemOneEnabled?.newValue === false || (changes.decisionMode && changes.decisionMode.newValue !== 'on')) {- void d1UsedForDecisions(chrome).then(used => { if (!used) reset(); }, reset);+ void chrome.storage.local.get(D1_KEEP_LOADED_KEY).then(stored => { if (stored?.[D1_KEEP_LOADED_KEY] !== true) reset(); }, reset);}}chrome.storage.onChanged.addListener(releaseD1OnDecisionChange);diff --git a/src/chrome/src/ui/install.js b/src/chrome/src/ui/install.jsindex ffe2c8a02..7c28a84d2 100644--- a/src/chrome/src/ui/install.js+++ b/src/chrome/src/ui/install.js@@ -261,11 +261,31 @@ export function d1View(state = {}) {}}+/**+ * The shared button: the chat model's, until that model is ready and needs+ * nothing more. Then the same button finishes D1's download, so a D1 that is+ * not downloaded yet, was paused or stopped with an error can still be+ * started, resumed or retried from the guide.+ */+export function localModelButtonView(view, chatStatus, d1State) {+ if (chatStatus !== 'ready' || !d1State) return view;+ switch (d1State.status) {+ case 'idle': return { ...view, labelKey: 'install.local_model.download', action: 'd1-start' };+ case 'paused': return { ...view, labelKey: 'install.local_model.resume', action: 'd1-start' };+ case 'error': return { ...view, labelKey: 'install.local_model.retry', action: 'd1-start' };+ case 'downloading': return { ...view, labelKey: 'install.local_model.pause', action: 'd1-pause' };+ case 'checking': return { ...view, labelKey: 'install.local_model.download', action: null };+ default: return view;+ }+}+export function initializeD1Download({documentLike = globalThis.document,runtime = globalThis.chrome?.runtime,translate = t,pollMs = D1_POLL_MS,+ // Called after each state change, so the shared button can follow D1.+ onChange = null,} = {}) {const line = documentLike?.getElementById?.('local-model-d1');if (!line || !runtime?.sendMessage) return null;@@ -290,6 +310,7 @@ export function initializeD1Download({state = { progress: 0, error: '', usedForDecisions: false, ...next };render();schedule();+ onChange?.();};async function refresh() {@@ -360,19 +381,24 @@ export function initializeLocalModelDownload({const label = documentLike.getElementById('local-model-label');const bar = documentLike.getElementById('local-model-progress');const statusLine = documentLike.getElementById('local-model-status');- const d1 = initializeD1Download({ documentLike, runtime, translate, pollMs });let state = { status: 'checking', progress: 0, error: '' };let inFlight = false;let pollTimer = null;let disposed = false;+ let rendered = false;+ // D1's own changes redraw the button once this controller has drawn it.+ const d1 = initializeD1Download({ documentLike, runtime, translate, pollMs, onChange: () => { if (rendered) render(); } });+ const buttonView = () => localModelButtonView(localModelView(state), state.status, d1?.getState());const render = () => {- const view = localModelView(state);+ rendered = true;+ const view = buttonView();root.dataset.state = state.status;if (label) label.textContent = translate(view.labelKey);if (button) {button.disabled = inFlight || !view.action;- if (inFlight || ['checking', 'downloading', 'stopping'].includes(state.status)) button.setAttribute('aria-busy', 'true');+ const d1Busy = state.status === 'ready' && ['checking', 'downloading'].includes(d1?.getState().status);+ if (inFlight || d1Busy || ['checking', 'downloading', 'stopping'].includes(state.status)) button.setAttribute('aria-busy', 'true');else button.removeAttribute('aria-busy');}if (bar) {@@ -411,9 +437,20 @@ export function initializeLocalModelDownload({}button?.addEventListener('click', async () => {- const view = localModelView(state);+ const view = buttonView();if (!view.action || inFlight) return;inFlight = true;+ if (view.action === 'd1-start' || view.action === 'd1-pause') {+ // The chat model is ready; only D1 is downloaded, paused or resumed.+ render();+ try {+ await (view.action === 'd1-start' ? d1.start() : d1.pause());+ } finally {+ inFlight = false;+ render();+ }+ return;+ }try {if (view.action === 'pause') {render();diff --git a/src/firefox/src/background.js b/src/firefox/src/background.jsindex 354b5d6fa..3a2b9f13c 100644--- a/src/firefox/src/background.js+++ b/src/firefox/src/background.js@@ -7,8 +7,10 @@ import { D1_CONSENT_KEY, D1_CONSENT_VERSION, D1_KEEP_LOADED_KEY } from './provid// D1's Worker and GPU memory are released when decisions are switched Off,// another decision provider is saved, consent changes or Strict Secret Mode-// starts. Leaving On (for Auto) keeps D1 loaded while Auto uses it: D1 is-// downloaded and Compass is not the chat provider (decision-availability.js).+// starts. Leaving On for Auto keeps D1, loaded or still downloading, while the+// user's Download or Load request stands: Auto uses it once it is downloaded,+// unless Compass is the chat provider (decision-availability.js), and Unload+// on the Providers page releases it.function releaseD1OnDecisionChange(changes, area) {if (area !== 'local') return;const reset = () => { void d1Request('reset').catch(() => {}); };@@ -20,7 +22,7 @@ function releaseD1OnDecisionChange(changes, area) {return;}if (changes.systemOneEnabled?.newValue === false || (changes.decisionMode && changes.decisionMode.newValue !== 'on')) {- void d1UsedForDecisions(browser).then(used => { if (!used) reset(); }, reset);+ void browser.storage.local.get(D1_KEEP_LOADED_KEY).then(stored => { if (stored?.[D1_KEEP_LOADED_KEY] !== true) reset(); }, reset);}}browser.storage.onChanged.addListener(releaseD1OnDecisionChange);diff --git a/src/firefox/src/ui/install.js b/src/firefox/src/ui/install.jsindex ffe2c8a02..7c28a84d2 100644--- a/src/firefox/src/ui/install.js+++ b/src/firefox/src/ui/install.js@@ -261,11 +261,31 @@ export function d1View(state = {}) {}}+/**+ * The shared button: the chat model's, until that model is ready and needs+ * nothing more. Then the same button finishes D1's download, so a D1 that is+ * not downloaded yet, was paused or stopped with an error can still be+ * started, resumed or retried from the guide.+ */+export function localModelButtonView(view, chatStatus, d1State) {+ if (chatStatus !== 'ready' || !d1State) return view;+ switch (d1State.status) {+ case 'idle': return { ...view, labelKey: 'install.local_model.download', action: 'd1-start' };+ case 'paused': return { ...view, labelKey: 'install.local_model.resume', action: 'd1-start' };+ case 'error': return { ...view, labelKey: 'install.local_model.retry', action: 'd1-start' };+ case 'downloading': return { ...view, labelKey: 'install.local_model.pause', action: 'd1-pause' };+ case 'checking': return { ...view, labelKey: 'install.local_model.download', action: null };+ default: return view;+ }+}+export function initializeD1Download({documentLike = globalThis.document,runtime = globalThis.chrome?.runtime,translate = t,pollMs = D1_POLL_MS,+ // Called after each state change, so the shared button can follow D1.+ onChange = null,} = {}) {const line = documentLike?.getElementById?.('local-model-d1');if (!line || !runtime?.sendMessage) return null;@@ -290,6 +310,7 @@ export function initializeD1Download({state = { progress: 0, error: '', usedForDecisions: false, ...next };render();schedule();+ onChange?.();};async function refresh() {@@ -360,19 +381,24 @@ export function initializeLocalModelDownload({const label = documentLike.getElementById('local-model-label');const bar = documentLike.getElementById('local-model-progress');const statusLine = documentLike.getElementById('local-model-status');- const d1 = initializeD1Download({ documentLike, runtime, translate, pollMs });let state = { status: 'checking', progress: 0, error: '' };let inFlight = false;let pollTimer = null;let disposed = false;+ let rendered = false;+ // D1's own changes redraw the button once this controller has drawn it.+ const d1 = initializeD1Download({ documentLike, runtime, translate, pollMs, onChange: () => { if (rendered) render(); } });+ const buttonView = () => localModelButtonView(localModelView(state), state.status, d1?.getState());const render = () => {- const view = localModelView(state);+ rendered = true;+ const view = buttonView();root.dataset.state = state.status;if (label) label.textContent = translate(view.labelKey);if (button) {button.disabled = inFlight || !view.action;- if (inFlight || ['checking', 'downloading', 'stopping'].includes(state.status)) button.setAttribute('aria-busy', 'true');+ const d1Busy = state.status === 'ready' && ['checking', 'downloading'].includes(d1?.getState().status);+ if (inFlight || d1Busy || ['checking', 'downloading', 'stopping'].includes(state.status)) button.setAttribute('aria-busy', 'true');else button.removeAttribute('aria-busy');}if (bar) {@@ -411,9 +437,20 @@ export function initializeLocalModelDownload({}button?.addEventListener('click', async () => {- const view = localModelView(state);+ const view = buttonView();if (!view.action || inFlight) return;inFlight = true;+ if (view.action === 'd1-start' || view.action === 'd1-pause') {+ // The chat model is ready; only D1 is downloaded, paused or resumed.+ render();+ try {+ await (view.action === 'd1-start' ? d1.start() : d1.pause());+ } finally {+ inFlight = false;+ render();+ }+ return;+ }try {if (view.action === 'pause') {render();diff --git a/test/d1-decision.mjs b/test/d1-decision.mjsindex 71d4daf24..154689f15 100644--- a/test/d1-decision.mjs+++ b/test/d1-decision.mjs@@ -315,26 +315,28 @@ for (const build of ['chrome', 'firefox']) {});}});- test(`${build}: leaving On for Auto keeps D1 loaded while Auto uses it; Off and other changes release it`, async () => {+ test(`${build}: leaving On for Auto keeps D1 while its Download or Load stands; Off and other changes release it`, async () => {const background = await readFile(new URL(`../src/${build}/src/background.js`, import.meta.url), 'utf8');assert.match(background, new RegExp(`${build === 'chrome' ? 'chrome' : 'browser'}\\.storage\\.onChanged\\.addListener\\(releaseD1OnDecisionChange\\);`));const source = topLevelFunction(background, 'releaseD1OnDecisionChange');const consent = pin.D1_CONSENT_KEY;- for (const [label, changes, used, expected, area = 'local'] of [+ // `loadRequested`: the user's Download or Load still stands (d1KeepLoaded).+ for (const [label, changes, loadRequested, expected, area = 'local'] of [['decisions Off', { decisionMode: { newValue: 'off' }, systemOneEnabled: { newValue: false } }, true, 1],['another provider saved', { decisionProvider: { newValue: 'openrouter' } }, true, 1],['consent removed', { [consent]: { newValue: undefined } }, true, 1],['Strict Secret Mode', { strictSecretMode: { newValue: true } }, true, 1],- ['Auto, which uses D1', { decisionMode: { newValue: 'auto' }, systemOneEnabled: { newValue: false } }, true, 0],- ['Auto while Compass chats', { decisionMode: { newValue: 'auto' }, systemOneEnabled: { newValue: false } }, false, 1],+ ['Auto, with D1 loaded or still downloading', { decisionMode: { newValue: 'auto' }, systemOneEnabled: { newValue: false } }, true, 0],+ ['Auto, after Unload', { decisionMode: { newValue: 'auto' }, systemOneEnabled: { newValue: false } }, false, 1],['On', { decisionMode: { newValue: 'on' }, systemOneEnabled: { newValue: true } }, false, 0],['consent given', { [consent]: { newValue: pin.D1_CONSENT_VERSION } }, false, 0],['an unrelated setting', { theme: { newValue: 'dark' } }, false, 0],['another storage area', { decisionMode: { newValue: 'off' } }, false, 0, 'sync'],]) {const resets = [];- const context = vm.createContext({ D1_CONSENT_KEY: consent, D1_CONSENT_VERSION: pin.D1_CONSENT_VERSION, chrome: {}, browser: {},- d1Request: async command => { resets.push(command); return {}; }, d1UsedForDecisions: async () => used });+ const storage = { storage: { local: { get: async key => (key === pin.D1_KEEP_LOADED_KEY ? { [key]: loadRequested } : {}) } } };+ const context = vm.createContext({ D1_CONSENT_KEY: consent, D1_CONSENT_VERSION: pin.D1_CONSENT_VERSION, D1_KEEP_LOADED_KEY: pin.D1_KEEP_LOADED_KEY,+ chrome: storage, browser: storage, d1Request: async command => { resets.push(command); return {}; } });vm.runInContext(source, context);context.releaseD1OnDecisionChange(changes, area);await new Promise(resolve => setTimeout(resolve, 0));diff --git a/test/run.js b/test/run.jsindex a302f9fd4..62cf93346 100644--- a/test/run.js+++ b/test/run.js@@ -45716,6 +45716,57 @@ test('chrome install page downloads D1 next to the chat model and says what D1 dcontroller.dispose();}+ {+ // The chat model is already downloaded: the same button then starts,+ // pauses, resumes and retries D1, and never touches the chat model.+ const buttonView = install.localModelButtonView;+ const ready = install.localModelView({ status: 'ready' });+ assert.equal(buttonView(ready, 'ready', { status: 'idle' }).action, 'd1-start');+ assert.equal(buttonView(ready, 'ready', { status: 'paused' }).labelKey, 'install.local_model.resume');+ assert.equal(buttonView(ready, 'ready', { status: 'error' }).labelKey, 'install.local_model.retry');+ assert.equal(buttonView(ready, 'ready', { status: 'downloading' }).action, 'd1-pause');+ assert.equal(buttonView(ready, 'ready', { status: 'checking' }).action, null);+ for (const status of ['ready', 'saved', 'unsupported']) assert.deepEqual(buttonView(ready, 'ready', { status }), ready, `${status}: nothing left to do`);+ const downloading = install.localModelView({ status: 'downloading', progress: 10 });+ assert.deepEqual(buttonView(downloading, 'downloading', { status: 'error' }), downloading, 'the chat model keeps the button while it downloads');++ const state = { d1: { status: 'idle' } };+ const runtime = fakeRuntime({+ get_webgpu_download_status: { status: 'ready', ready: true, modelId },+ 'd1_control:status': () => ({ success: true, result: { ...state.d1, usedForDecisions: true } }),+ 'd1_control:probe': { success: true, result: { success: true } },+ 'd1_control:download': () => { state.d1 = { status: 'downloading', progress: 20 }; return { success: true, result: { started: true, ...state.d1 } }; },+ 'd1_control:stop': () => { state.d1 = { status: 'stopped', progress: 40 }; return { success: true, result: { stopped: true } }; },+ });+ const documentLike = fakeDocument();+ const controller = install.initializeLocalModelDownload({ documentLike, runtime, translate, pollMs: 60_000 });+ await settle();+ const { nodes } = documentLike;+ assert.equal(nodes['local-model'].dataset.state, 'ready');+ assert.equal(nodes['local-model-label'].textContent, 'install.local_model.download');+ assert.equal(nodes['local-model-button'].disabled, false, 'D1 can still be downloaded');+ await nodes['local-model-button'].fire('click');+ await settle();+ assert.deepEqual(runtime.sent.filter((message) => message.action === 'd1_control' && message.command !== 'status').map((message) => message.command), ['probe', 'download']);+ assert.ok(!runtime.sent.some((message) => ['test_provider', 'start_webgpu_download'].includes(message.action)), 'the ready chat model is left alone');+ assert.equal(nodes['local-model-label'].textContent, 'install.local_model.pause');+ assert.equal(nodes['local-model-d1'].textContent, 'install.local_model.d1_downloading|20');+ await nodes['local-model-button'].fire('click');+ await settle();+ assert.ok(runtime.sent.some((message) => message.action === 'd1_control' && message.command === 'stop'));+ assert.ok(!runtime.sent.some((message) => message.action === 'pause_webgpu_download'));+ assert.equal(nodes['local-model-label'].textContent, 'install.local_model.resume');+ await nodes['local-model-button'].fire('click');+ await settle();+ assert.equal(runtime.sent.filter((message) => message.action === 'd1_control' && message.command === 'download').length, 2);+ state.d1 = { status: 'ready', loaded: true };+ await controller.d1.refresh();+ assert.equal(nodes['local-model-label'].textContent, 'install.local_model.ready');+ assert.equal(nodes['local-model-button'].disabled, true, 'both models are ready');+ assert.equal(nodes['local-model-d1'].textContent, 'install.local_model.d1_ready');+ controller.dispose();+ }+{// A GPU D1 cannot use: say so, and the chat model still downloads.const state = { bonsai: { status: 'not-downloaded', modelId } };