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 D1's Download and Load buttons; shorten Unload
Claude5cc3a70deb4f
diff --git a/docs/providers-and-models.md b/docs/providers-and-models.mdindex ce3412cc2..7aa8af23c 100644--- a/docs/providers-and-models.md+++ b/docs/providers-and-models.md@@ -107,8 +107,9 @@ into OPFS. The package stores FP16 weights and computes in FP32; it is thewith its weights rounded once, and answers the same on its held-out test. Acached FP32 package from an earlier version is removed on the next download. The repository name is not a production-readiness claim; this providerremains experimental. Executable JS/WASM is packaged in the extension, not-downloaded from the model repository. **Load cached model** verifies the files-again; inference cannot trigger a model download.+downloaded from the model repository. Once the package is in the cache the+same button reads **Load**: it verifies the files again and loads them without+the download pass; inference cannot trigger a model download.This experimental path needs hardware WebGPU, OPFS and substantial GPU/hostmemory. Software adapters are rejected. The encoder's attention is dense, so@@ -123,9 +124,9 @@ document with a dedicated decision Worker; Firefox uses its background-pageWorker when the corresponding browser capabilities are available. Mirroredcode is not evidence that every browser/GPU is supported. CPU/WASM control andshape operators are permitted and explicitly disclosed; it is not a pure-GPU-claim. Unload or disabling outsourcing releases the Worker/GPU resources and+claim. **Unload** or disabling outsourcing releases the Worker/GPU resources andretains the cache; **Remove cached model** requires the model to be unloaded.-After **Download and load** or **Load cached model**, D1 stays loaded until+After **Download and load** or **Load**, D1 stays loaded untilit is unloaded, removed or switched off in Settings: a decision that finds itunloaded (a browser restart, a discarded stalled session, a lost GPU device)starts one reload from the verified cache in the background and uses thediff --git a/package.json b/package.jsonindex ccb36325f..bfe54d6bb 100644--- a/package.json+++ b/package.json@@ -71,8 +71,8 @@"test:rich-text-dom": "node test/ui-content-lifecycle.mjs --dom","test:firefox-bidi": "node --test test/firefox-bidi.mjs test/firefox-full-page-screenshot.mjs","test:firefox-bidi:e2e": "node test/firefox-bidi-e2e.mjs",- "test:systemone": "node --test test/decision-mode.mjs test/systemone.mjs test/completion-verifier.mjs test/completion-result.mjs test/completion-document.mjs test/d1-decision.mjs test/webgpu-decisions.mjs",- "test:d1": "node --test test/d1-decision.mjs",+ "test:systemone": "node --test test/decision-mode.mjs test/systemone.mjs test/completion-verifier.mjs test/completion-result.mjs test/completion-document.mjs test/d1-decision.mjs test/d1-settings-ui.mjs test/webgpu-decisions.mjs",+ "test:d1": "node --test test/d1-decision.mjs test/d1-settings-ui.mjs","test:systemone:ui": "node test/systemone-ui.mjs","test:systemone:fast": "node --test test/systemone-fast.mjs && node test/systemone-fast-dom.mjs && node --test test/jev/fixtures.test.mjs","benchmark:jev": "node test/jev/benchmark.mjs",diff --git a/src/chrome/src/providers/d1-config.js b/src/chrome/src/providers/d1-config.jsindex 788248ae0..e63b7da19 100644--- a/src/chrome/src/providers/d1-config.js+++ b/src/chrome/src/providers/d1-config.js@@ -1,7 +1,7 @@export const D1_MODEL_ID = 'webbrain-one/d1-browser-decision-fp16';export const D1_CONSENT_VERSION = 1;export const D1_CONSENT_KEY = 'd1WebgpuConsentVersion';-// Set by Settings' Download and load / Load cached model, cleared by Unload,+// Set by Settings' Download and load (or Load, once cached), cleared by Unload,// Remove and switching D1 off there. While it is set, a decision that finds// the model unloaded (a browser restart, a discarded stalled session, a lost// GPU device) reloads the verified cache in the background; never downloads.diff --git a/src/chrome/src/ui/d1-settings.js b/src/chrome/src/ui/d1-settings.jsindex 74eb4e039..65420a7aa 100644--- a/src/chrome/src/ui/d1-settings.js+++ b/src/chrome/src/ui/d1-settings.js@@ -12,12 +12,22 @@ export function initD1Settings(send) {if (!selected) { clearInterval(timer); timer = null; return; }await refresh(); if (!timer) timer = setInterval(refresh, 2000);};+ // One button downloads what is missing and loads; once the model is in the+ // cache it only loads, which skips the download pass's second verification.+ const loadButton = document.getElementById('d1-load');+ const showLoadButton = snapshot => {+ const cached = snapshot?.loaded === true || ['cached', 'ready'].includes(snapshot?.status);+ loadButton.dataset.d1Command = cached ? 'load' : 'download';+ loadButton.dataset.i18n = cached ? 'st.d1.load' : 'st.d1.download';+ loadButton.textContent = t(loadButton.dataset.i18n);+ };async function refresh() {if (provider.value !== 'webgpu_d1') return;try {const result = await send('d1_control', { command: 'status' });if (!result.success) throw new Error(result.error);const snapshot = result.result;+ showLoadButton(snapshot);line.textContent = `${snapshot.status || 'idle'}${snapshot.progress ? ` (${Math.round(snapshot.progress)}%)` : ''}${snapshot.error ? ': ' + snapshot.error : ''}${snapshot.adapter ? ' | ' + [snapshot.adapter.vendor, snapshot.adapter.device, snapshot.adapter.description].filter(Boolean).join(' / ') : ''}`;} catch (error) { line.textContent = error.message; }}diff --git a/src/chrome/src/ui/locales/decision-copy.mjs b/src/chrome/src/ui/locales/decision-copy.mjsindex 9c1cc5259..4e52ed5cc 100644--- a/src/chrome/src/ui/locales/decision-copy.mjs+++ b/src/chrome/src/ui/locales/decision-copy.mjs@@ -28,8 +28,8 @@ export const decisionEnglish = {'st.d1.warning': 'Experimental on-device decision model, about 0.95 GB download plus tokenizer. Requires hardware WebGPU and substantial GPU memory. Not a chat model or sole completion authority. CPU/WASM control operators may run. Browser support and model decisions are not universally validated.','st.d1.consent': 'I accept the experimental local model download from Hugging Face and its memory requirements.','st.d1.need_consent': 'Accept the experimental model download consent first.',- 'st.d1.download': 'Download and load', 'st.d1.load': 'Load cached model', 'st.d1.stop': 'Stop download',- 'st.d1.unload': 'Unload model', 'st.d1.remove': 'Remove cached model',+ 'st.d1.download': 'Download and load', 'st.d1.load': 'Load', 'st.d1.stop': 'Stop download',+ 'st.d1.unload': 'Unload', 'st.d1.remove': 'Remove cached model','st.system_one.title': 'Decision models','st.system_one.api_key.label': 'API key (optional for local models)','st.system_one.need_key': 'Enter an API key for the selected provider.',@@ -75,8 +75,8 @@ export const decisionTranslations = {'st.d1.warning': 'Deneysel yerel karar modeli; tokenizer ile birlikte yaklaşık 0,95 GB indirme. Donanım WebGPU ve yüksek GPU belleği gerekir. Sohbet modeli veya tek başına tamamlanma yetkilisi değildir. CPU/WASM kontrol işlemleri çalışabilir. Her tarayıcı, GPU ve model kararı doğrulanmış değildir.','st.d1.consent': 'Hugging Face üzerinden deneysel yerel model indirmesini ve bellek gereksinimlerini kabul ediyorum.','st.d1.need_consent': 'Önce deneysel model indirme onayını kabul edin.',- 'st.d1.download': 'İndir ve yükle', 'st.d1.load': 'Önbellekten yükle', 'st.d1.stop': 'İndirmeyi durdur',- 'st.d1.unload': 'Modeli bellekten kaldır', 'st.d1.remove': 'Önbellekteki modeli sil',+ 'st.d1.download': 'İndir ve yükle', 'st.d1.load': 'Yükle', 'st.d1.stop': 'İndirmeyi durdur',+ 'st.d1.unload': 'Bellekten kaldır', 'st.d1.remove': 'Önbellekteki modeli sil','st.system_one.title': 'Karar modelleri', 'st.system_one.api_key.label': 'API anahtarı (yerel modellerde isteğe bağlı)','st.system_one.need_key': 'Seçilen sağlayıcı için bir API anahtarı girin.','st.system_one.security_html': "Bulut karar modelleri (Açık modda ya da Otomatik modda Compass) sınırlı görev ve sayfa kanıtı alır; Ternary Bonsai 2 2B Vision ve D1 bunları bu cihazda tutar. Anahtarlar yerel olarak saklanır. Bulut kullanımı ücretli olabilir. Kesin Gizlilik Modu karar modellerini kapatır.",@@ -96,9 +96,9 @@ export const decisionTranslations = {"st.d1.consent": "Acepto la descarga experimental del modelo local desde Hugging Face y sus requisitos de memoria.","st.d1.need_consent": "Primero acepta el consentimiento de descarga del modelo experimental.","st.d1.download": "Descargar y cargar",- "st.d1.load": "Cargar modelo en caché",+ "st.d1.load": "Cargar","st.d1.stop": "Detener descarga",- "st.d1.unload": "Descargar de la memoria",+ "st.d1.unload": "Liberar","st.d1.remove": "Eliminar modelo en caché","st.system_one.title": "Modelos de decisión","st.system_one.api_key.label": "Clave de API (opcional para modelos locales)",@@ -150,9 +150,9 @@ export const decisionTranslations = {"st.d1.consent": "J’accepte le téléchargement expérimental du modèle local depuis Hugging Face et ses besoins en mémoire.","st.d1.need_consent": "Acceptez d’abord le consentement au téléchargement du modèle expérimental.","st.d1.download": "Télécharger et charger",- "st.d1.load": "Charger le modèle en cache",+ "st.d1.load": "Charger","st.d1.stop": "Arrêter le téléchargement",- "st.d1.unload": "Décharger le modèle",+ "st.d1.unload": "Décharger","st.d1.remove": "Supprimer le modèle en cache","st.system_one.title": "Modèles de décision","st.system_one.api_key.label": "Clé API (facultative pour les modèles locaux)",@@ -204,9 +204,9 @@ export const decisionTranslations = {"st.d1.consent": "Ich akzeptiere den experimentellen Download des lokalen Modells von Hugging Face und seine Speicheranforderungen.","st.d1.need_consent": "Stimmen Sie zuerst dem Download des experimentellen Modells zu.","st.d1.download": "Herunterladen und laden",- "st.d1.load": "Zwischengespeichertes Modell laden",+ "st.d1.load": "Laden","st.d1.stop": "Download stoppen",- "st.d1.unload": "Modell entladen",+ "st.d1.unload": "Entladen","st.d1.remove": "Zwischengespeichertes Modell entfernen","st.system_one.title": "Entscheidungsmodelle","st.system_one.api_key.label": "API-Schlüssel (für lokale Modelle optional)",@@ -258,9 +258,9 @@ export const decisionTranslations = {"st.d1.consent": "Ik accepteer de experimentele download van het lokale model van Hugging Face en de geheugenvereisten.","st.d1.need_consent": "Geef eerst toestemming voor de download van het experimentele model.","st.d1.download": "Downloaden en laden",- "st.d1.load": "Model uit cache laden",+ "st.d1.load": "Laden","st.d1.stop": "Download stoppen",- "st.d1.unload": "Model uit geheugen halen",+ "st.d1.unload": "Uit geheugen halen","st.d1.remove": "Model uit cache verwijderen","st.system_one.title": "Beslismodellen","st.system_one.api_key.label": "API-sleutel (optioneel voor lokale modellen)",@@ -312,9 +312,9 @@ export const decisionTranslations = {"st.d1.consent": "Aceito o download experimental do modelo local a partir do Hugging Face e seus requisitos de memória.","st.d1.need_consent": "Aceite primeiro o consentimento de download do modelo experimental.","st.d1.download": "Baixar e carregar",- "st.d1.load": "Carregar modelo em cache",+ "st.d1.load": "Carregar","st.d1.stop": "Parar download",- "st.d1.unload": "Descarregar modelo",+ "st.d1.unload": "Descarregar","st.d1.remove": "Remover modelo em cache","st.system_one.title": "Modelos de decisão","st.system_one.api_key.label": "Chave de API (opcional para modelos locais)",@@ -366,9 +366,9 @@ export const decisionTranslations = {"st.d1.consent": "Akceptuję eksperymentalne pobranie lokalnego modelu z Hugging Face i jego wymagania pamięciowe.","st.d1.need_consent": "Najpierw zaakceptuj zgodę na pobranie eksperymentalnego modelu.","st.d1.download": "Pobierz i załaduj",- "st.d1.load": "Załaduj model z pamięci podręcznej",+ "st.d1.load": "Załaduj","st.d1.stop": "Zatrzymaj pobieranie",- "st.d1.unload": "Zwolnij model z pamięci",+ "st.d1.unload": "Zwolnij z pamięci","st.d1.remove": "Usuń model z pamięci podręcznej","st.system_one.title": "Modele decyzyjne","st.system_one.api_key.label": "Klucz API (opcjonalny dla modeli lokalnych)",@@ -420,9 +420,9 @@ export const decisionTranslations = {"st.d1.consent": "Я принимаю экспериментальную загрузку локальной модели с Hugging Face и её требования к памяти.","st.d1.need_consent": "Сначала подтвердите согласие на загрузку экспериментальной модели.","st.d1.download": "Загрузить и запустить",- "st.d1.load": "Запустить из кэша",+ "st.d1.load": "Запустить","st.d1.stop": "Остановить загрузку",- "st.d1.unload": "Выгрузить модель",+ "st.d1.unload": "Выгрузить","st.d1.remove": "Удалить модель из кэша","st.system_one.title": "Модели решений","st.system_one.api_key.label": "Ключ API (необязателен для локальных моделей)",@@ -474,9 +474,9 @@ export const decisionTranslations = {"st.d1.consent": "Я приймаю експериментальне завантаження локальної моделі з Hugging Face та її вимоги до пам’яті.","st.d1.need_consent": "Спершу підтвердьте згоду на завантаження експериментальної моделі.","st.d1.download": "Завантажити й запустити",- "st.d1.load": "Запустити з кешу",+ "st.d1.load": "Запустити","st.d1.stop": "Зупинити завантаження",- "st.d1.unload": "Вивантажити модель",+ "st.d1.unload": "Вивантажити","st.d1.remove": "Видалити модель із кешу","st.system_one.title": "Моделі рішень","st.system_one.api_key.label": "Ключ API (необов’язковий для локальних моделей)",@@ -528,9 +528,9 @@ export const decisionTranslations = {"st.d1.consent": "我接受从 Hugging Face 实验性下载本地模型及其内存要求。","st.d1.need_consent": "请先同意下载实验性模型。","st.d1.download": "下载并加载",- "st.d1.load": "加载缓存的模型",+ "st.d1.load": "加载","st.d1.stop": "停止下载",- "st.d1.unload": "卸载模型",+ "st.d1.unload": "卸载","st.d1.remove": "删除缓存的模型","st.system_one.title": "决策模型","st.system_one.api_key.label": "API 密钥(本地模型可选)",@@ -582,9 +582,9 @@ export const decisionTranslations = {"st.d1.consent": "Hugging Face からの試験的なローカルモデルのダウンロードとメモリ要件に同意します。","st.d1.need_consent": "先に試験的モデルのダウンロードに同意してください。","st.d1.download": "ダウンロードして読み込む",- "st.d1.load": "キャッシュ済みモデルを読み込む",+ "st.d1.load": "読み込む","st.d1.stop": "ダウンロードを停止",- "st.d1.unload": "モデルをアンロード",+ "st.d1.unload": "アンロード","st.d1.remove": "キャッシュ済みモデルを削除","st.system_one.title": "判定モデル","st.system_one.api_key.label": "API キー(ローカルモデルでは任意)",@@ -636,9 +636,9 @@ export const decisionTranslations = {"st.d1.consent": "Hugging Face에서 실험적 로컬 모델을 다운로드하는 것과 메모리 요구 사항에 동의합니다.","st.d1.need_consent": "먼저 실험적 모델 다운로드에 동의하세요.","st.d1.download": "다운로드 후 불러오기",- "st.d1.load": "캐시된 모델 불러오기",+ "st.d1.load": "불러오기","st.d1.stop": "다운로드 중지",- "st.d1.unload": "모델 언로드",+ "st.d1.unload": "언로드","st.d1.remove": "캐시된 모델 삭제","st.system_one.title": "결정 모델","st.system_one.api_key.label": "API 키(로컬 모델은 선택 사항)",@@ -690,9 +690,9 @@ export const decisionTranslations = {"st.d1.consent": "أوافق على التنزيل التجريبي للنموذج المحلي من Hugging Face ومتطلبات الذاكرة الخاصة به.","st.d1.need_consent": "وافق أولًا على تنزيل النموذج التجريبي.","st.d1.download": "تنزيل وتحميل",- "st.d1.load": "تحميل النموذج المخزَّن",+ "st.d1.load": "تحميل","st.d1.stop": "إيقاف التنزيل",- "st.d1.unload": "إلغاء تحميل النموذج",+ "st.d1.unload": "إلغاء التحميل","st.d1.remove": "إزالة النموذج المخزَّن","st.system_one.title": "نماذج القرار","st.system_one.api_key.label": "مفتاح API (اختياري للنماذج المحلية)",@@ -744,9 +744,9 @@ export const decisionTranslations = {"st.d1.consent": "אני מאשר את ההורדה הניסיונית של המודל המקומי מ-Hugging Face ואת דרישות הזיכרון שלו.","st.d1.need_consent": "אשר קודם את ההסכמה להורדת המודל הניסיוני.","st.d1.download": "הורדה וטעינה",- "st.d1.load": "טעינת המודל מהמטמון",+ "st.d1.load": "טעינה","st.d1.stop": "עצירת ההורדה",- "st.d1.unload": "פריקת המודל",+ "st.d1.unload": "פריקה","st.d1.remove": "הסרת המודל מהמטמון","st.system_one.title": "מודלי החלטות","st.system_one.api_key.label": "מפתח API (אופציונלי למודלים מקומיים)",@@ -798,9 +798,9 @@ export const decisionTranslations = {"st.d1.consent": "دانلود آزمایشی مدل محلی از Hugging Face و نیازهای حافظهٔ آن را میپذیرم.","st.d1.need_consent": "ابتدا رضایت دانلود مدل آزمایشی را بپذیرید.","st.d1.download": "دانلود و بارگذاری",- "st.d1.load": "بارگذاری مدل ذخیرهشده",+ "st.d1.load": "بارگذاری","st.d1.stop": "توقف دانلود",- "st.d1.unload": "خارج کردن مدل از حافظه",+ "st.d1.unload": "خارج کردن از حافظه","st.d1.remove": "حذف مدل ذخیرهشده","st.system_one.title": "مدلهای تصمیم","st.system_one.api_key.label": "کلید API (برای مدلهای محلی اختیاری)",@@ -852,9 +852,9 @@ export const decisionTranslations = {"st.d1.consent": "मैं Hugging Face से प्रायोगिक स्थानीय मॉडल डाउनलोड और उसकी मेमोरी आवश्यकताओं को स्वीकार करता/करती हूँ।","st.d1.need_consent": "पहले प्रायोगिक मॉडल डाउनलोड की सहमति दें।","st.d1.download": "डाउनलोड करें और लोड करें",- "st.d1.load": "कैश किया मॉडल लोड करें",+ "st.d1.load": "लोड करें","st.d1.stop": "डाउनलोड रोकें",- "st.d1.unload": "मॉडल अनलोड करें",+ "st.d1.unload": "अनलोड करें","st.d1.remove": "कैश किया मॉडल हटाएँ","st.system_one.title": "निर्णय मॉडल","st.system_one.api_key.label": "API कुंजी (स्थानीय मॉडल के लिए वैकल्पिक)",@@ -906,9 +906,9 @@ export const decisionTranslations = {"st.d1.consent": "আমি Hugging Face থেকে পরীক্ষামূলক লোকাল মডেল ডাউনলোড ও এর মেমরির প্রয়োজনীয়তা মেনে নিচ্ছি।","st.d1.need_consent": "আগে পরীক্ষামূলক মডেল ডাউনলোডের সম্মতি দিন।","st.d1.download": "ডাউনলোড ও লোড করুন",- "st.d1.load": "ক্যাশ করা মডেল লোড করুন",+ "st.d1.load": "লোড করুন","st.d1.stop": "ডাউনলোড থামান",- "st.d1.unload": "মডেল আনলোড করুন",+ "st.d1.unload": "আনলোড করুন","st.d1.remove": "ক্যাশ করা মডেল সরান","st.system_one.title": "ডিসিশন মডেল","st.system_one.api_key.label": "API কী (লোকাল মডেলের জন্য ঐচ্ছিক)",@@ -960,9 +960,9 @@ export const decisionTranslations = {"st.d1.consent": "Saya menyetujui unduhan eksperimental model lokal dari Hugging Face beserta kebutuhan memorinya.","st.d1.need_consent": "Setujui dulu unduhan model eksperimental.","st.d1.download": "Unduh dan muat",- "st.d1.load": "Muat model dari cache",+ "st.d1.load": "Muat","st.d1.stop": "Hentikan unduhan",- "st.d1.unload": "Lepas model dari memori",+ "st.d1.unload": "Lepas dari memori","st.d1.remove": "Hapus model dari cache","st.system_one.title": "Model keputusan","st.system_one.api_key.label": "Kunci API (opsional untuk model lokal)",@@ -1014,9 +1014,9 @@ export const decisionTranslations = {"st.d1.consent": "Saya menerima muat turun eksperimen model setempat daripada Hugging Face dan keperluan memorinya.","st.d1.need_consent": "Terima persetujuan muat turun model eksperimen dahulu.","st.d1.download": "Muat turun dan muatkan",- "st.d1.load": "Muatkan model dalam cache",+ "st.d1.load": "Muatkan","st.d1.stop": "Hentikan muat turun",- "st.d1.unload": "Nyahmuat model",+ "st.d1.unload": "Nyahmuat","st.d1.remove": "Buang model dalam cache","st.system_one.title": "Model keputusan","st.system_one.api_key.label": "Kunci API (pilihan untuk model setempat)",@@ -1068,9 +1068,9 @@ export const decisionTranslations = {"st.d1.consent": "Tinatanggap ko ang eksperimental na pag-download ng lokal na model mula sa Hugging Face at ang mga kailangan nito sa memory.","st.d1.need_consent": "Tanggapin muna ang pahintulot sa pag-download ng eksperimental na model.","st.d1.download": "I-download at i-load",- "st.d1.load": "I-load ang naka-cache na model",+ "st.d1.load": "I-load","st.d1.stop": "Itigil ang download",- "st.d1.unload": "I-unload ang model",+ "st.d1.unload": "I-unload","st.d1.remove": "Alisin ang naka-cache na model","st.system_one.title": "Mga decision model","st.system_one.api_key.label": "API key (opsyonal sa mga lokal na model)",@@ -1122,9 +1122,9 @@ export const decisionTranslations = {"st.d1.consent": "ฉันยอมรับการดาวน์โหลดโมเดลในเครื่องแบบทดลองจาก Hugging Face และความต้องการหน่วยความจำของโมเดล","st.d1.need_consent": "ยอมรับความยินยอมในการดาวน์โหลดโมเดลทดลองก่อน","st.d1.download": "ดาวน์โหลดและโหลด",- "st.d1.load": "โหลดโมเดลที่แคชไว้",+ "st.d1.load": "โหลด","st.d1.stop": "หยุดดาวน์โหลด",- "st.d1.unload": "ยกเลิกการโหลดโมเดล",+ "st.d1.unload": "ยกเลิกการโหลด","st.d1.remove": "ลบโมเดลที่แคชไว้","st.system_one.title": "โมเดลการตัดสินใจ","st.system_one.api_key.label": "คีย์ API (ไม่บังคับสำหรับโมเดลในเครื่อง)",@@ -1176,9 +1176,9 @@ export const decisionTranslations = {"st.d1.consent": "Tôi chấp nhận việc tải thử nghiệm mô hình cục bộ từ Hugging Face và yêu cầu bộ nhớ của nó.","st.d1.need_consent": "Hãy đồng ý tải mô hình thử nghiệm trước.","st.d1.download": "Tải xuống và nạp",- "st.d1.load": "Nạp mô hình đã lưu đệm",+ "st.d1.load": "Nạp","st.d1.stop": "Dừng tải xuống",- "st.d1.unload": "Gỡ mô hình khỏi bộ nhớ",+ "st.d1.unload": "Gỡ khỏi bộ nhớ","st.d1.remove": "Xóa mô hình đã lưu đệm","st.system_one.title": "Mô hình quyết định","st.system_one.api_key.label": "Khóa API (không bắt buộc với mô hình cục bộ)",diff --git a/src/chrome/src/ui/settings.html b/src/chrome/src/ui/settings.htmlindex 6a77d6578..2319d3b9e 100644--- a/src/chrome/src/ui/settings.html+++ b/src/chrome/src/ui/settings.html@@ -2440,8 +2440,7 @@<p class="setting-desc decision-note" data-i18n="st.d1.warning"></p><label><input type="checkbox" id="d1-consent"> <span data-i18n="st.d1.consent"></span></label><div class="btn-row" style="margin-top:10px;flex-wrap:wrap">- <button class="btn-secondary" data-d1-command="download" data-i18n="st.d1.download"></button>- <button class="btn-secondary" data-d1-command="load" data-i18n="st.d1.load"></button>+ <button class="btn-secondary" id="d1-load" data-d1-command="download" data-i18n="st.d1.download"></button><button class="btn-secondary" data-d1-command="stop" data-i18n="st.d1.stop"></button><button class="btn-secondary" data-d1-command="reset" data-i18n="st.d1.unload"></button><button class="btn-secondary" data-d1-command="clear" data-i18n="st.d1.remove"></button>diff --git a/src/firefox/src/providers/d1-config.js b/src/firefox/src/providers/d1-config.jsindex 788248ae0..e63b7da19 100644--- a/src/firefox/src/providers/d1-config.js+++ b/src/firefox/src/providers/d1-config.js@@ -1,7 +1,7 @@export const D1_MODEL_ID = 'webbrain-one/d1-browser-decision-fp16';export const D1_CONSENT_VERSION = 1;export const D1_CONSENT_KEY = 'd1WebgpuConsentVersion';-// Set by Settings' Download and load / Load cached model, cleared by Unload,+// Set by Settings' Download and load (or Load, once cached), cleared by Unload,// Remove and switching D1 off there. While it is set, a decision that finds// the model unloaded (a browser restart, a discarded stalled session, a lost// GPU device) reloads the verified cache in the background; never downloads.diff --git a/src/firefox/src/ui/d1-settings.js b/src/firefox/src/ui/d1-settings.jsindex 74eb4e039..65420a7aa 100644--- a/src/firefox/src/ui/d1-settings.js+++ b/src/firefox/src/ui/d1-settings.js@@ -12,12 +12,22 @@ export function initD1Settings(send) {if (!selected) { clearInterval(timer); timer = null; return; }await refresh(); if (!timer) timer = setInterval(refresh, 2000);};+ // One button downloads what is missing and loads; once the model is in the+ // cache it only loads, which skips the download pass's second verification.+ const loadButton = document.getElementById('d1-load');+ const showLoadButton = snapshot => {+ const cached = snapshot?.loaded === true || ['cached', 'ready'].includes(snapshot?.status);+ loadButton.dataset.d1Command = cached ? 'load' : 'download';+ loadButton.dataset.i18n = cached ? 'st.d1.load' : 'st.d1.download';+ loadButton.textContent = t(loadButton.dataset.i18n);+ };async function refresh() {if (provider.value !== 'webgpu_d1') return;try {const result = await send('d1_control', { command: 'status' });if (!result.success) throw new Error(result.error);const snapshot = result.result;+ showLoadButton(snapshot);line.textContent = `${snapshot.status || 'idle'}${snapshot.progress ? ` (${Math.round(snapshot.progress)}%)` : ''}${snapshot.error ? ': ' + snapshot.error : ''}${snapshot.adapter ? ' | ' + [snapshot.adapter.vendor, snapshot.adapter.device, snapshot.adapter.description].filter(Boolean).join(' / ') : ''}`;} catch (error) { line.textContent = error.message; }}diff --git a/src/firefox/src/ui/locales/decision-copy.mjs b/src/firefox/src/ui/locales/decision-copy.mjsindex 9c1cc5259..4e52ed5cc 100644--- a/src/firefox/src/ui/locales/decision-copy.mjs+++ b/src/firefox/src/ui/locales/decision-copy.mjs@@ -28,8 +28,8 @@ export const decisionEnglish = {'st.d1.warning': 'Experimental on-device decision model, about 0.95 GB download plus tokenizer. Requires hardware WebGPU and substantial GPU memory. Not a chat model or sole completion authority. CPU/WASM control operators may run. Browser support and model decisions are not universally validated.','st.d1.consent': 'I accept the experimental local model download from Hugging Face and its memory requirements.','st.d1.need_consent': 'Accept the experimental model download consent first.',- 'st.d1.download': 'Download and load', 'st.d1.load': 'Load cached model', 'st.d1.stop': 'Stop download',- 'st.d1.unload': 'Unload model', 'st.d1.remove': 'Remove cached model',+ 'st.d1.download': 'Download and load', 'st.d1.load': 'Load', 'st.d1.stop': 'Stop download',+ 'st.d1.unload': 'Unload', 'st.d1.remove': 'Remove cached model','st.system_one.title': 'Decision models','st.system_one.api_key.label': 'API key (optional for local models)','st.system_one.need_key': 'Enter an API key for the selected provider.',@@ -75,8 +75,8 @@ export const decisionTranslations = {'st.d1.warning': 'Deneysel yerel karar modeli; tokenizer ile birlikte yaklaşık 0,95 GB indirme. Donanım WebGPU ve yüksek GPU belleği gerekir. Sohbet modeli veya tek başına tamamlanma yetkilisi değildir. CPU/WASM kontrol işlemleri çalışabilir. Her tarayıcı, GPU ve model kararı doğrulanmış değildir.','st.d1.consent': 'Hugging Face üzerinden deneysel yerel model indirmesini ve bellek gereksinimlerini kabul ediyorum.','st.d1.need_consent': 'Önce deneysel model indirme onayını kabul edin.',- 'st.d1.download': 'İndir ve yükle', 'st.d1.load': 'Önbellekten yükle', 'st.d1.stop': 'İndirmeyi durdur',- 'st.d1.unload': 'Modeli bellekten kaldır', 'st.d1.remove': 'Önbellekteki modeli sil',+ 'st.d1.download': 'İndir ve yükle', 'st.d1.load': 'Yükle', 'st.d1.stop': 'İndirmeyi durdur',+ 'st.d1.unload': 'Bellekten kaldır', 'st.d1.remove': 'Önbellekteki modeli sil','st.system_one.title': 'Karar modelleri', 'st.system_one.api_key.label': 'API anahtarı (yerel modellerde isteğe bağlı)','st.system_one.need_key': 'Seçilen sağlayıcı için bir API anahtarı girin.','st.system_one.security_html': "Bulut karar modelleri (Açık modda ya da Otomatik modda Compass) sınırlı görev ve sayfa kanıtı alır; Ternary Bonsai 2 2B Vision ve D1 bunları bu cihazda tutar. Anahtarlar yerel olarak saklanır. Bulut kullanımı ücretli olabilir. Kesin Gizlilik Modu karar modellerini kapatır.",@@ -96,9 +96,9 @@ export const decisionTranslations = {"st.d1.consent": "Acepto la descarga experimental del modelo local desde Hugging Face y sus requisitos de memoria.","st.d1.need_consent": "Primero acepta el consentimiento de descarga del modelo experimental.","st.d1.download": "Descargar y cargar",- "st.d1.load": "Cargar modelo en caché",+ "st.d1.load": "Cargar","st.d1.stop": "Detener descarga",- "st.d1.unload": "Descargar de la memoria",+ "st.d1.unload": "Liberar","st.d1.remove": "Eliminar modelo en caché","st.system_one.title": "Modelos de decisión","st.system_one.api_key.label": "Clave de API (opcional para modelos locales)",@@ -150,9 +150,9 @@ export const decisionTranslations = {"st.d1.consent": "J’accepte le téléchargement expérimental du modèle local depuis Hugging Face et ses besoins en mémoire.","st.d1.need_consent": "Acceptez d’abord le consentement au téléchargement du modèle expérimental.","st.d1.download": "Télécharger et charger",- "st.d1.load": "Charger le modèle en cache",+ "st.d1.load": "Charger","st.d1.stop": "Arrêter le téléchargement",- "st.d1.unload": "Décharger le modèle",+ "st.d1.unload": "Décharger","st.d1.remove": "Supprimer le modèle en cache","st.system_one.title": "Modèles de décision","st.system_one.api_key.label": "Clé API (facultative pour les modèles locaux)",@@ -204,9 +204,9 @@ export const decisionTranslations = {"st.d1.consent": "Ich akzeptiere den experimentellen Download des lokalen Modells von Hugging Face und seine Speicheranforderungen.","st.d1.need_consent": "Stimmen Sie zuerst dem Download des experimentellen Modells zu.","st.d1.download": "Herunterladen und laden",- "st.d1.load": "Zwischengespeichertes Modell laden",+ "st.d1.load": "Laden","st.d1.stop": "Download stoppen",- "st.d1.unload": "Modell entladen",+ "st.d1.unload": "Entladen","st.d1.remove": "Zwischengespeichertes Modell entfernen","st.system_one.title": "Entscheidungsmodelle","st.system_one.api_key.label": "API-Schlüssel (für lokale Modelle optional)",@@ -258,9 +258,9 @@ export const decisionTranslations = {"st.d1.consent": "Ik accepteer de experimentele download van het lokale model van Hugging Face en de geheugenvereisten.","st.d1.need_consent": "Geef eerst toestemming voor de download van het experimentele model.","st.d1.download": "Downloaden en laden",- "st.d1.load": "Model uit cache laden",+ "st.d1.load": "Laden","st.d1.stop": "Download stoppen",- "st.d1.unload": "Model uit geheugen halen",+ "st.d1.unload": "Uit geheugen halen","st.d1.remove": "Model uit cache verwijderen","st.system_one.title": "Beslismodellen","st.system_one.api_key.label": "API-sleutel (optioneel voor lokale modellen)",@@ -312,9 +312,9 @@ export const decisionTranslations = {"st.d1.consent": "Aceito o download experimental do modelo local a partir do Hugging Face e seus requisitos de memória.","st.d1.need_consent": "Aceite primeiro o consentimento de download do modelo experimental.","st.d1.download": "Baixar e carregar",- "st.d1.load": "Carregar modelo em cache",+ "st.d1.load": "Carregar","st.d1.stop": "Parar download",- "st.d1.unload": "Descarregar modelo",+ "st.d1.unload": "Descarregar","st.d1.remove": "Remover modelo em cache","st.system_one.title": "Modelos de decisão","st.system_one.api_key.label": "Chave de API (opcional para modelos locais)",@@ -366,9 +366,9 @@ export const decisionTranslations = {"st.d1.consent": "Akceptuję eksperymentalne pobranie lokalnego modelu z Hugging Face i jego wymagania pamięciowe.","st.d1.need_consent": "Najpierw zaakceptuj zgodę na pobranie eksperymentalnego modelu.","st.d1.download": "Pobierz i załaduj",- "st.d1.load": "Załaduj model z pamięci podręcznej",+ "st.d1.load": "Załaduj","st.d1.stop": "Zatrzymaj pobieranie",- "st.d1.unload": "Zwolnij model z pamięci",+ "st.d1.unload": "Zwolnij z pamięci","st.d1.remove": "Usuń model z pamięci podręcznej","st.system_one.title": "Modele decyzyjne","st.system_one.api_key.label": "Klucz API (opcjonalny dla modeli lokalnych)",@@ -420,9 +420,9 @@ export const decisionTranslations = {"st.d1.consent": "Я принимаю экспериментальную загрузку локальной модели с Hugging Face и её требования к памяти.","st.d1.need_consent": "Сначала подтвердите согласие на загрузку экспериментальной модели.","st.d1.download": "Загрузить и запустить",- "st.d1.load": "Запустить из кэша",+ "st.d1.load": "Запустить","st.d1.stop": "Остановить загрузку",- "st.d1.unload": "Выгрузить модель",+ "st.d1.unload": "Выгрузить","st.d1.remove": "Удалить модель из кэша","st.system_one.title": "Модели решений","st.system_one.api_key.label": "Ключ API (необязателен для локальных моделей)",@@ -474,9 +474,9 @@ export const decisionTranslations = {"st.d1.consent": "Я приймаю експериментальне завантаження локальної моделі з Hugging Face та її вимоги до пам’яті.","st.d1.need_consent": "Спершу підтвердьте згоду на завантаження експериментальної моделі.","st.d1.download": "Завантажити й запустити",- "st.d1.load": "Запустити з кешу",+ "st.d1.load": "Запустити","st.d1.stop": "Зупинити завантаження",- "st.d1.unload": "Вивантажити модель",+ "st.d1.unload": "Вивантажити","st.d1.remove": "Видалити модель із кешу","st.system_one.title": "Моделі рішень","st.system_one.api_key.label": "Ключ API (необов’язковий для локальних моделей)",@@ -528,9 +528,9 @@ export const decisionTranslations = {"st.d1.consent": "我接受从 Hugging Face 实验性下载本地模型及其内存要求。","st.d1.need_consent": "请先同意下载实验性模型。","st.d1.download": "下载并加载",- "st.d1.load": "加载缓存的模型",+ "st.d1.load": "加载","st.d1.stop": "停止下载",- "st.d1.unload": "卸载模型",+ "st.d1.unload": "卸载","st.d1.remove": "删除缓存的模型","st.system_one.title": "决策模型","st.system_one.api_key.label": "API 密钥(本地模型可选)",@@ -582,9 +582,9 @@ export const decisionTranslations = {"st.d1.consent": "Hugging Face からの試験的なローカルモデルのダウンロードとメモリ要件に同意します。","st.d1.need_consent": "先に試験的モデルのダウンロードに同意してください。","st.d1.download": "ダウンロードして読み込む",- "st.d1.load": "キャッシュ済みモデルを読み込む",+ "st.d1.load": "読み込む","st.d1.stop": "ダウンロードを停止",- "st.d1.unload": "モデルをアンロード",+ "st.d1.unload": "アンロード","st.d1.remove": "キャッシュ済みモデルを削除","st.system_one.title": "判定モデル","st.system_one.api_key.label": "API キー(ローカルモデルでは任意)",@@ -636,9 +636,9 @@ export const decisionTranslations = {"st.d1.consent": "Hugging Face에서 실험적 로컬 모델을 다운로드하는 것과 메모리 요구 사항에 동의합니다.","st.d1.need_consent": "먼저 실험적 모델 다운로드에 동의하세요.","st.d1.download": "다운로드 후 불러오기",- "st.d1.load": "캐시된 모델 불러오기",+ "st.d1.load": "불러오기","st.d1.stop": "다운로드 중지",- "st.d1.unload": "모델 언로드",+ "st.d1.unload": "언로드","st.d1.remove": "캐시된 모델 삭제","st.system_one.title": "결정 모델","st.system_one.api_key.label": "API 키(로컬 모델은 선택 사항)",@@ -690,9 +690,9 @@ export const decisionTranslations = {"st.d1.consent": "أوافق على التنزيل التجريبي للنموذج المحلي من Hugging Face ومتطلبات الذاكرة الخاصة به.","st.d1.need_consent": "وافق أولًا على تنزيل النموذج التجريبي.","st.d1.download": "تنزيل وتحميل",- "st.d1.load": "تحميل النموذج المخزَّن",+ "st.d1.load": "تحميل","st.d1.stop": "إيقاف التنزيل",- "st.d1.unload": "إلغاء تحميل النموذج",+ "st.d1.unload": "إلغاء التحميل","st.d1.remove": "إزالة النموذج المخزَّن","st.system_one.title": "نماذج القرار","st.system_one.api_key.label": "مفتاح API (اختياري للنماذج المحلية)",@@ -744,9 +744,9 @@ export const decisionTranslations = {"st.d1.consent": "אני מאשר את ההורדה הניסיונית של המודל המקומי מ-Hugging Face ואת דרישות הזיכרון שלו.","st.d1.need_consent": "אשר קודם את ההסכמה להורדת המודל הניסיוני.","st.d1.download": "הורדה וטעינה",- "st.d1.load": "טעינת המודל מהמטמון",+ "st.d1.load": "טעינה","st.d1.stop": "עצירת ההורדה",- "st.d1.unload": "פריקת המודל",+ "st.d1.unload": "פריקה","st.d1.remove": "הסרת המודל מהמטמון","st.system_one.title": "מודלי החלטות","st.system_one.api_key.label": "מפתח API (אופציונלי למודלים מקומיים)",@@ -798,9 +798,9 @@ export const decisionTranslations = {"st.d1.consent": "دانلود آزمایشی مدل محلی از Hugging Face و نیازهای حافظهٔ آن را میپذیرم.","st.d1.need_consent": "ابتدا رضایت دانلود مدل آزمایشی را بپذیرید.","st.d1.download": "دانلود و بارگذاری",- "st.d1.load": "بارگذاری مدل ذخیرهشده",+ "st.d1.load": "بارگذاری","st.d1.stop": "توقف دانلود",- "st.d1.unload": "خارج کردن مدل از حافظه",+ "st.d1.unload": "خارج کردن از حافظه","st.d1.remove": "حذف مدل ذخیرهشده","st.system_one.title": "مدلهای تصمیم","st.system_one.api_key.label": "کلید API (برای مدلهای محلی اختیاری)",@@ -852,9 +852,9 @@ export const decisionTranslations = {"st.d1.consent": "मैं Hugging Face से प्रायोगिक स्थानीय मॉडल डाउनलोड और उसकी मेमोरी आवश्यकताओं को स्वीकार करता/करती हूँ।","st.d1.need_consent": "पहले प्रायोगिक मॉडल डाउनलोड की सहमति दें।","st.d1.download": "डाउनलोड करें और लोड करें",- "st.d1.load": "कैश किया मॉडल लोड करें",+ "st.d1.load": "लोड करें","st.d1.stop": "डाउनलोड रोकें",- "st.d1.unload": "मॉडल अनलोड करें",+ "st.d1.unload": "अनलोड करें","st.d1.remove": "कैश किया मॉडल हटाएँ","st.system_one.title": "निर्णय मॉडल","st.system_one.api_key.label": "API कुंजी (स्थानीय मॉडल के लिए वैकल्पिक)",@@ -906,9 +906,9 @@ export const decisionTranslations = {"st.d1.consent": "আমি Hugging Face থেকে পরীক্ষামূলক লোকাল মডেল ডাউনলোড ও এর মেমরির প্রয়োজনীয়তা মেনে নিচ্ছি।","st.d1.need_consent": "আগে পরীক্ষামূলক মডেল ডাউনলোডের সম্মতি দিন।","st.d1.download": "ডাউনলোড ও লোড করুন",- "st.d1.load": "ক্যাশ করা মডেল লোড করুন",+ "st.d1.load": "লোড করুন","st.d1.stop": "ডাউনলোড থামান",- "st.d1.unload": "মডেল আনলোড করুন",+ "st.d1.unload": "আনলোড করুন","st.d1.remove": "ক্যাশ করা মডেল সরান","st.system_one.title": "ডিসিশন মডেল","st.system_one.api_key.label": "API কী (লোকাল মডেলের জন্য ঐচ্ছিক)",@@ -960,9 +960,9 @@ export const decisionTranslations = {"st.d1.consent": "Saya menyetujui unduhan eksperimental model lokal dari Hugging Face beserta kebutuhan memorinya.","st.d1.need_consent": "Setujui dulu unduhan model eksperimental.","st.d1.download": "Unduh dan muat",- "st.d1.load": "Muat model dari cache",+ "st.d1.load": "Muat","st.d1.stop": "Hentikan unduhan",- "st.d1.unload": "Lepas model dari memori",+ "st.d1.unload": "Lepas dari memori","st.d1.remove": "Hapus model dari cache","st.system_one.title": "Model keputusan","st.system_one.api_key.label": "Kunci API (opsional untuk model lokal)",@@ -1014,9 +1014,9 @@ export const decisionTranslations = {"st.d1.consent": "Saya menerima muat turun eksperimen model setempat daripada Hugging Face dan keperluan memorinya.","st.d1.need_consent": "Terima persetujuan muat turun model eksperimen dahulu.","st.d1.download": "Muat turun dan muatkan",- "st.d1.load": "Muatkan model dalam cache",+ "st.d1.load": "Muatkan","st.d1.stop": "Hentikan muat turun",- "st.d1.unload": "Nyahmuat model",+ "st.d1.unload": "Nyahmuat","st.d1.remove": "Buang model dalam cache","st.system_one.title": "Model keputusan","st.system_one.api_key.label": "Kunci API (pilihan untuk model setempat)",@@ -1068,9 +1068,9 @@ export const decisionTranslations = {"st.d1.consent": "Tinatanggap ko ang eksperimental na pag-download ng lokal na model mula sa Hugging Face at ang mga kailangan nito sa memory.","st.d1.need_consent": "Tanggapin muna ang pahintulot sa pag-download ng eksperimental na model.","st.d1.download": "I-download at i-load",- "st.d1.load": "I-load ang naka-cache na model",+ "st.d1.load": "I-load","st.d1.stop": "Itigil ang download",- "st.d1.unload": "I-unload ang model",+ "st.d1.unload": "I-unload","st.d1.remove": "Alisin ang naka-cache na model","st.system_one.title": "Mga decision model","st.system_one.api_key.label": "API key (opsyonal sa mga lokal na model)",@@ -1122,9 +1122,9 @@ export const decisionTranslations = {"st.d1.consent": "ฉันยอมรับการดาวน์โหลดโมเดลในเครื่องแบบทดลองจาก Hugging Face และความต้องการหน่วยความจำของโมเดล","st.d1.need_consent": "ยอมรับความยินยอมในการดาวน์โหลดโมเดลทดลองก่อน","st.d1.download": "ดาวน์โหลดและโหลด",- "st.d1.load": "โหลดโมเดลที่แคชไว้",+ "st.d1.load": "โหลด","st.d1.stop": "หยุดดาวน์โหลด",- "st.d1.unload": "ยกเลิกการโหลดโมเดล",+ "st.d1.unload": "ยกเลิกการโหลด","st.d1.remove": "ลบโมเดลที่แคชไว้","st.system_one.title": "โมเดลการตัดสินใจ","st.system_one.api_key.label": "คีย์ API (ไม่บังคับสำหรับโมเดลในเครื่อง)",@@ -1176,9 +1176,9 @@ export const decisionTranslations = {"st.d1.consent": "Tôi chấp nhận việc tải thử nghiệm mô hình cục bộ từ Hugging Face và yêu cầu bộ nhớ của nó.","st.d1.need_consent": "Hãy đồng ý tải mô hình thử nghiệm trước.","st.d1.download": "Tải xuống và nạp",- "st.d1.load": "Nạp mô hình đã lưu đệm",+ "st.d1.load": "Nạp","st.d1.stop": "Dừng tải xuống",- "st.d1.unload": "Gỡ mô hình khỏi bộ nhớ",+ "st.d1.unload": "Gỡ khỏi bộ nhớ","st.d1.remove": "Xóa mô hình đã lưu đệm","st.system_one.title": "Mô hình quyết định","st.system_one.api_key.label": "Khóa API (không bắt buộc với mô hình cục bộ)",diff --git a/src/firefox/src/ui/settings.html b/src/firefox/src/ui/settings.htmlindex 390332f92..f01650b33 100644--- a/src/firefox/src/ui/settings.html+++ b/src/firefox/src/ui/settings.html@@ -2256,8 +2256,7 @@<p class="setting-desc decision-note" data-i18n="st.d1.warning"></p><label><input type="checkbox" id="d1-consent"> <span data-i18n="st.d1.consent"></span></label><div class="btn-row" style="margin-top:10px;flex-wrap:wrap">- <button class="btn-secondary" data-d1-command="download" data-i18n="st.d1.download"></button>- <button class="btn-secondary" data-d1-command="load" data-i18n="st.d1.load"></button>+ <button class="btn-secondary" id="d1-load" data-d1-command="download" data-i18n="st.d1.download"></button><button class="btn-secondary" data-d1-command="stop" data-i18n="st.d1.stop"></button><button class="btn-secondary" data-d1-command="reset" data-i18n="st.d1.unload"></button><button class="btn-secondary" data-d1-command="clear" data-i18n="st.d1.remove"></button>diff --git a/test/d1-settings-ui.mjs b/test/d1-settings-ui.mjsnew file mode 100644index 000000000..b648d04cc--- /dev/null+++ b/test/d1-settings-ui.mjs@@ -0,0 +1,74 @@+// Settings → Decision models with D1 selected: one button downloads what is+// missing and loads, and reads "Load" once the package is cached; Unload is+// short. Firefox runs only where its Playwright browser is installed.+import { chromium, firefox } from 'playwright';+import { createServer } from 'node:http';+import { readFile } from 'node:fs/promises';+import { resolve, extname, sep } from 'node:path';+import assert from 'node:assert/strict';+import { test } from 'node:test';++const root = resolve('.');+const { version } = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8'));+const server = createServer(async (req, res) => {+ try {+ const file = resolve(root, '.' + new URL(req.url, 'http://localhost').pathname);+ if (!file.startsWith(root + sep)) throw Error();+ res.setHeader('Content-Type', ({ '.js': 'text/javascript', '.mjs': 'text/javascript', '.html': 'text/html', '.css': 'text/css', '.svg': 'image/svg+xml' })[extname(file)] || 'text/plain');+ res.end(await readFile(file));+ } catch { res.statusCode = 404; res.end(); }+});+await new Promise(done => server.listen(0, '127.0.0.1', done));+const origin = `http://127.0.0.1:${server.address().port}`;++for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {+ test(`${build}: D1 has one Download and load button that reads Load once cached`, async t => {+ let browser;+ try { browser = await engine.launch(); } catch (error) { t.skip(`${build} browser unavailable: ${error.message.split('\n')[0]}`); return; }+ try {+ const page = await browser.newPage({ viewport: { width: 1280, height: 1000 } });+ const errors = []; page.on('pageerror', error => errors.push(error.message));+ await page.addInitScript(({ build, version }) => {+ localStorage.setItem('wbLocale', 'en');+ const data = { wbLocale: 'en', decisionMode: 'on', systemOneEnabled: true, decisionProvider: 'webgpu_d1', d1WebgpuConsentVersion: 1 };+ window.testRequests = []; window.d1Status = 'idle';+ const storage = {+ async get(keys) { return keys == null ? { ...data } : Object.fromEntries((Array.isArray(keys) ? keys : typeof keys === 'string' ? [keys] : Object.keys(keys)).map(k => [k, data[k]])); },+ async set(values) { Object.assign(data, values); },+ async remove(keys) { for (const key of Array.isArray(keys) ? keys : [keys]) delete data[key]; },+ };+ window.chrome = window.browser = {+ storage: { local: storage, onChanged: { addListener() {} } },+ runtime: { getURL: path => `${location.origin}/src/${build}/${path}`, getManifest: () => ({ version }), onMessage: { addListener() {} }, sendMessage(msg, callback) {+ window.testRequests.push(msg);+ const result = msg.action === 'd1_control'+ ? { success: true, result: msg.command === 'status' ? { status: window.d1Status, ready: window.d1Status === 'ready', loaded: window.d1Status === 'ready' } : { started: true } }+ : msg.action === 'get_providers' ? { providers: {}, active: '' } : { success: true };+ callback?.(result); return Promise.resolve(result);+ } },+ commands: { getAll: async () => [] }, tabs: { create: async () => ({}) },+ };+ }, { build, version });+ await page.goto(`${origin}/src/${build}/src/ui/settings.html#multimodal`);+ await page.waitForFunction(() => !document.querySelector('#d1-controls')?.hidden);+ const commands = await page.locator('#d1-controls button[data-d1-command]').evaluateAll(buttons => buttons.map(button => button.dataset.d1Command));+ assert.deepEqual(commands, ['download', 'stop', 'reset', 'clear'], 'Download and Load share one button');+ assert.equal(await page.locator('#d1-controls button[data-d1-command="reset"]').textContent(), 'Unload');+ const load = page.locator('#d1-load');+ await page.waitForFunction(() => document.querySelector('#d1-load').textContent === 'Download and load');+ assert.equal(await load.getAttribute('data-d1-command'), 'download');+ // Once the package is cached, the same button only loads it.+ await page.evaluate(() => { window.d1Status = 'cached'; });+ await page.waitForFunction(() => document.querySelector('#d1-load').textContent === 'Load', null, { timeout: 5000 });+ assert.equal(await load.getAttribute('data-d1-command'), 'load');+ await page.locator('#d1-consent').check();+ await load.click();+ await page.waitForFunction(() => window.testRequests.some(msg => msg.action === 'd1_control' && msg.command === 'load'));+ const sent = await page.evaluate(() => window.testRequests.find(msg => msg.action === 'd1_control' && msg.command === 'load'));+ assert.equal(sent.consent, true); assert.equal(sent.consentVersion, 1);+ assert.deepEqual(errors, []);+ } finally { await browser.close(); }+ });+}++test.after(() => server.close());