Spaces:
Running
Running
Download js/main.js from ereniko/LocalWebAgent: direct link, hf CLI and curl.
- Browser
- Download file 45.2 kB
-
https://huggingface.co/spaces/ereniko/LocalWebAgent/resolve/main/js/main.js
- Command line
-
hf download hf://spaces/ereniko/LocalWebAgent/js/main.js
-
curl -L -o main.js https://huggingface.co/spaces/ereniko/LocalWebAgent/resolve/main/js/main.js
45.2 kB
| import { DEFAULTS, MODEL_DEVICE, APP_VERSION, LOCAL_MODELS, findModel, setShaderF16, effectiveModel, modelRunsHere } from "./config.js"; | |
| import * as setup from "./setup.js"; | |
| import { LLM } from "./llm.js"; | |
| import { RemoteLLM, findPreset, loadApiKey, migrateLegacyKey } from "./remote-llm.js"; | |
| import { createModelManager, avatarTile } from "./model-manager.js"; | |
| import { freshAccessToken, embedded, standaloneUrl } from "./hf-auth.js"; | |
| import { VM } from "./vm.js"; | |
| import { Agent } from "./agent.js"; | |
| import { renderMarkdown } from "./markdown.js"; | |
| import { FileBrowser } from "./files.js"; | |
| // ---------- helpers ---------- | |
| const $ = (s, el = document) => el.querySelector(s); | |
| const h = (tag, attrs = {}, ...kids) => { | |
| const el = document.createElement(tag); | |
| for (const [k, v] of Object.entries(attrs)) { | |
| if (k === "class") el.className = v; | |
| else if (k.startsWith("on")) el.addEventListener(k.slice(2), v); | |
| else if (v !== false && v != null) el.setAttribute(k, v === true ? "" : v); | |
| } | |
| for (const kid of kids.flat()) if (kid != null) el.append(kid); | |
| return el; | |
| }; | |
| const SVG_NS = "http://www.w3.org/2000/svg"; | |
| const icon = (name, cls) => { | |
| const s = document.createElementNS(SVG_NS, "svg"); | |
| if (cls) s.setAttribute("class", cls); | |
| const u = document.createElementNS(SVG_NS, "use"); | |
| u.setAttribute("href", "#i-" + name); | |
| s.append(u); | |
| return s; | |
| }; | |
| const fmtBytes = (n) => (n >= 1e9 ? (n / 1e9).toFixed(2) + " GB" : n >= 1e6 ? Math.round(n / 1e6) + " MB" : Math.round(n / 1e3) + " KB"); | |
| const fmtSecs = (ms) => (ms < 1000 ? `${Math.max(0.1, ms / 1000).toFixed(1)}s` : ms < 60000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.floor(ms / 60000)}m ${Math.round((ms % 60000) / 1000)}s`); | |
| const plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`; | |
| // ---------- settings ---------- | |
| const settings = { ...DEFAULTS }; | |
| try { Object.assign(settings, JSON.parse(localStorage.getItem("lwa-settings") || "{}")); } catch {} | |
| // Older versions saved the active budget (14000) with everything else; the per-backend | |
| // values replace it, so drop it to let the new defaults apply. | |
| delete settings.contextBudgetTokens; | |
| const saveSettings = () => { | |
| const { contextBudgetTokens, ...persist } = settings; // derived, never stored | |
| try { localStorage.setItem("lwa-settings", JSON.stringify(persist)); } catch {} | |
| }; | |
| // ---------- status ---------- | |
| function status(name, state, text) { | |
| const el = $(`[data-status="${name}"]`); | |
| el.dataset.state = state; | |
| $(".status-text", el).textContent = text; | |
| el.title = text; | |
| } | |
| // ---------- language model: none, local (WebGPU) or one of the saved API models ---------- | |
| const isMobile = () => !!navigator.userAgentData?.mobile || /Android|iPhone|iPad|Mobile/i.test(navigator.userAgent); | |
| // Before the Model Manager (v0.5 and older) there was one API model and one local choice. | |
| (function migrateModelSettings() { | |
| if (Array.isArray(settings.apiModels) && "activeModel" in settings) return; | |
| let hadSettings = false; | |
| try { hadSettings = localStorage.getItem("lwa-settings") != null; } catch {} | |
| settings.apiModels = Array.isArray(settings.apiModels) ? settings.apiModels : []; | |
| if (settings.api?.baseUrl && settings.api?.model && !settings.apiModels.length) { | |
| settings.apiModels.push({ id: "api-1", name: settings.api.model, preset: settings.api.preset ?? "custom", baseUrl: settings.api.baseUrl, model: settings.api.model }); | |
| migrateLegacyKey("api-1"); | |
| } | |
| if (!("activeModel" in settings)) { | |
| settings.activeModel = settings.backend === "api" && settings.apiModels.length ? { kind: "api", id: settings.apiModels[0].id } | |
| : hadSettings ? { kind: "local", id: findModel(settings.localModel).id } // they had a local model installed | |
| : null; | |
| } | |
| delete settings.backend; delete settings.api; delete settings.localModel; | |
| saveSettings(); | |
| })(); | |
| const activeKind = () => settings.activeModel?.kind ?? null; | |
| const activeLocal = () => (activeKind() === "local" ? LOCAL_MODELS.find((m) => m.id === settings.activeModel.id) ?? null : null); | |
| const activeApi = () => (activeKind() === "api" ? settings.apiModels.find((a) => a.id === settings.activeModel.id) ?? null : null); | |
| const usingApi = () => !!activeApi(); | |
| const isActive = (sel) => !!sel && settings.activeModel?.kind === sel.kind && settings.activeModel?.id === sel.id; | |
| const apiConfigFor = (a) => a.auth === "hf-oauth" | |
| // Signed in with Hugging Face: the session's token, refreshed when it is about to expire. | |
| ? { baseUrl: a.baseUrl, model: a.model, headers: findPreset(a.preset).headers, getKey: () => freshAccessToken(a.id) } | |
| : { baseUrl: a.baseUrl, model: a.model, key: loadApiKey(a.id), headers: findPreset(a.preset).headers }; | |
| const apiHost = () => { try { return new URL(activeApi().baseUrl).host; } catch { return activeApi()?.baseUrl ?? ""; } }; | |
| const activeLabel = () => activeApi()?.name ?? activeLocal()?.label ?? "No model"; | |
| const smallestModel = () => LOCAL_MODELS.reduce((a, b) => (b.bytes < a.bytes ? b : a)); | |
| if (settings.activeModel && !activeLocal() && !activeApi()) settings.activeModel = null; // points at something deleted | |
| // The active context budget follows the model. | |
| const syncContextBudget = () => { | |
| settings.contextBudgetTokens = usingApi() ? settings.contextApiTokens | |
| : Math.min(settings.contextLocalTokens, (activeLocal() ?? LOCAL_MODELS[0]).contextMax); | |
| }; | |
| syncContextBudget(); | |
| // Stand-in while no model is chosen. | |
| const noModel = () => ({ | |
| none: true, ready: false, async load() {}, stop() {}, resetCache() {}, dispose() {}, | |
| generate() { return Promise.reject(new Error("No model selected. Open the Model Manager to choose one.")); }, | |
| }); | |
| function createLlm() { | |
| const a = activeApi(); | |
| if (a) return new RemoteLLM(apiConfigFor(a)); | |
| const m = activeLocal(); | |
| return m ? new LLM(m) : noModel(); | |
| } | |
| let llm = createLlm(); | |
| let modelError = null; // why the local model failed to load, if it did | |
| let gpuCheck = null; // result of the WebGPU check, for the Model Manager | |
| let started = false; | |
| const vm = new VM(); | |
| let agent = null; | |
| let diskManifest = null; | |
| let vmReady = false; | |
| let files = null; | |
| // ---------- boot ---------- | |
| async function init() { | |
| // Inside the Space page on huggingface.co (an iframe) the app gets separate, partitioned | |
| // storage and sign-in can't work, so send people to its own page instead of starting. | |
| if (embedded()) { | |
| $("#embed-gate-link").href = standaloneUrl(); | |
| $("#embed-gate").hidden = false; | |
| wipeEmbeddedStorage(); | |
| return; | |
| } | |
| // Mark this browser's first-party storage, so an embedded copy can tell whether it sees | |
| // the same storage (and must not wipe it) or its own partitioned copy. | |
| try { localStorage.setItem(FIRST_PARTY_MARK, "1"); } catch {} | |
| $("#version").textContent = "v" + APP_VERSION; | |
| setBackendLabels(); | |
| syncToggles(); | |
| const checks = await environmentChecks(); | |
| renderChecks(checks); | |
| if (!checks.isolated.ok || !checks.sw.ok) return showSetup(false); | |
| try { await setup.ensureServiceWorker(); } | |
| catch (err) { checks.sw = { ok: false, text: err.message }; renderChecks(checks); return showSetup(false); } | |
| // Free the space of models that were dropped from the catalog (e.g. Qwen3 4B in v0.7). | |
| setup.removeOrphanedModels(LOCAL_MODELS.map((m) => m.repo)) | |
| .then((freed) => { if (freed > 1e6) console.info(`Removed ${fmtBytes(freed)} of files from models no longer in the list.`); }) | |
| .catch((err) => console.warn("cleanup:", err)); | |
| // Setup installs only Linux; models are added later in the Model Manager. | |
| const [cx, disk] = await Promise.all([setup.cheerpxStatus(), setup.installedDisk()]); | |
| diskManifest = disk; | |
| const installed = { cx: cx.ready, disk: !!disk }; | |
| for (const k of Object.keys(installed)) if (installed[k]) setRow(k, 1, "Installed"); | |
| // "Update now" on the new-Linux callout reloads into this: setup screen, download the | |
| // new image, drop the old machine's storage, boot. | |
| const updating = sessionStorage.getItem(UPDATE_FLAG); | |
| if (updating) { | |
| sessionStorage.removeItem(UPDATE_FLAG); | |
| setRow("disk", 0, "Update available"); | |
| showSetup(true); | |
| $("#install").textContent = "Update Linux"; | |
| $("#setup-note").textContent = "Downloading the new Linux machine. Keep this tab open."; | |
| return install({ replacing: disk?.id }); | |
| } | |
| const openModels = new URLSearchParams(location.search).get("open") === "models"; | |
| if (installed.cx && installed.disk) { | |
| updateOfflineStatus(); | |
| if (openModels) models.open(); | |
| start().then(checkForNewImage); | |
| } | |
| else { status("offline", "warn", "Not installed"); showSetup(true); } | |
| } | |
| const UPDATE_FLAG = "lwa-update-linux"; | |
| const FIRST_PARTY_MARK = "lwa-first-party"; | |
| /** | |
| * In the Space embed, deletes everything this app stored there (models, Linux disk and | |
| * files, settings, keys, service worker) so it only lives on the dedicated page. Browsers | |
| * partition an iframe's storage by the top-level site, so this is the embed's own copy; | |
| * if the dedicated page's marker is visible, storage is shared and nothing is deleted. | |
| */ | |
| async function wipeEmbeddedStorage() { | |
| const note = $("#embed-gate-clean"); | |
| let shared = false; | |
| try { shared = localStorage.getItem(FIRST_PARTY_MARK) === "1"; } catch {} | |
| if (shared) { note.textContent = ""; return; } // not partitioned: this is the real app's data | |
| const before = (await navigator.storage?.estimate?.().catch(() => null))?.usage ?? 0; | |
| note.textContent = "Clearing data stored by this embedded view…"; | |
| const tasks = []; | |
| tasks.push((async () => { | |
| for (const r of (await navigator.serviceWorker?.getRegistrations?.()) ?? []) await r.unregister(); | |
| })()); | |
| tasks.push((async () => { for (const k of await caches.keys()) await caches.delete(k); })()); | |
| tasks.push((async () => { | |
| for (const db of (await indexedDB.databases?.()) ?? []) { | |
| if (!db.name) continue; | |
| await new Promise((resolve) => { | |
| const req = indexedDB.deleteDatabase(db.name); | |
| req.onsuccess = req.onerror = req.onblocked = () => resolve(); | |
| }); | |
| } | |
| })()); | |
| tasks.push((async () => { | |
| const root = await navigator.storage?.getDirectory?.(); | |
| if (root) for await (const name of root.keys()) await root.removeEntry(name, { recursive: true }); | |
| })()); | |
| await Promise.allSettled(tasks); | |
| try { localStorage.clear(); sessionStorage.clear(); } catch {} | |
| // An unregistered service worker keeps controlling open pages until they close and can | |
| // re-cache files they load, so sweep the caches once more shortly after. | |
| setTimeout(async () => { try { for (const k of await caches.keys()) await caches.delete(k); } catch {} }, 3000); | |
| const after = (await navigator.storage?.estimate?.().catch(() => null))?.usage ?? 0; | |
| const freed = Math.max(0, before - after); | |
| note.textContent = freed > 1e6 ? `Cleared ${fmtBytes(freed)} this embedded view had stored. Your data on LocalWebAgent's own page is untouched.` : ""; | |
| } | |
| /** After boot: if the server has a newer Linux image than the installed one, offer it. */ | |
| async function checkForNewImage() { | |
| if (!navigator.onLine || !diskManifest) return; | |
| let remote; | |
| try { remote = await setup.fetchRemoteManifest(); } catch { return; } | |
| if (!remote?.id || remote.id === diskManifest.id) return; | |
| const el = callout("info", "A new Linux machine is available", | |
| `Debian 12 with Python 3.11 (numpy, pandas, matplotlib, scipy), Node 18 and TypeScript, PHP, Lua, CMake, ImageMagick and more than 450 packages. Updating downloads ${fmtBytes(remote.downloadBytes)} and starts a fresh machine: files you created in the current one will be gone, so download anything you want to keep from the Files view first.`, | |
| [ | |
| h("button", { class: "btn primary small", type: "button", onclick: () => { | |
| if (agent?.running) return alert("Stop the agent before updating."); | |
| if (!confirm("Replace the Linux machine with the new version? Files you created in the current machine will be deleted.")) return; | |
| sessionStorage.setItem(UPDATE_FLAG, "1"); | |
| location.reload(); | |
| } }, "Update now"), | |
| h("button", { class: "btn small", type: "button", onclick: () => el.remove() }, "Not now"), | |
| ], null, "update"); | |
| } | |
| async function environmentChecks() { | |
| const c = {}; | |
| c.isolated = crossOriginIsolated | |
| ? { ok: true, text: "Cross-origin isolation" } | |
| : { ok: false, text: window.top !== window ? "The embedded view can't run the VM. Open the app in its own tab." : "Cross-origin isolation is off (COOP/COEP headers missing)" }; | |
| c.sw = "serviceWorker" in navigator ? { ok: true, text: "Offline storage" } : { ok: false, text: "Offline storage unavailable (private window?)" }; | |
| if (MODEL_DEVICE !== "webgpu") c.gpu = { ok: true, warn: true, text: `Model runs on ${MODEL_DEVICE} (slow; for testing)` }; | |
| else if (!navigator.gpu) c.gpu = { ok: false, text: "WebGPU unavailable. Use desktop Chrome or Edge." }; | |
| else { | |
| try { | |
| const a = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" }); | |
| if (!a) c.gpu = { ok: false, text: /Linux/.test(navigator.userAgent) ? "No WebGPU adapter found (on Linux, Chrome may need chrome://flags/#enable-vulkan and #enable-unsafe-webgpu)" : "No WebGPU adapter found" }; | |
| else if (!a.features.has("shader-f16")) { | |
| // Common with Chrome on Linux (Vulkan), even on GPUs that have f16 on Windows. | |
| // Local models then use their q4 builds (4-bit weights, fp32 math). | |
| setShaderF16(false); | |
| c.gpu = { ok: true, noF16: true, text: "WebGPU without f16 shaders" + (a.info?.vendor ? ` · ${a.info.vendor}` : "") }; | |
| } | |
| else c.gpu = { ok: true, text: "WebGPU with f16 shaders" + (a.info?.vendor ? ` · ${a.info.vendor}` : "") }; | |
| } catch (e) { c.gpu = { ok: false, text: "WebGPU error: " + e.message }; } | |
| } | |
| // WebGPU only matters for local models, which are optional: report it, don't block setup. | |
| gpuCheck = c.gpu; | |
| c.gpu = c.gpu.noF16 ? { ok: true, warn: true, text: c.gpu.text + ": local models use their larger q4 builds" } | |
| : c.gpu.ok ? { ok: true, text: c.gpu.text + ": local models can run" } | |
| : { ok: true, warn: true, text: `${c.gpu.text}. Local models won't run here; API models will.` }; | |
| const est = await setup.storageEstimate(); | |
| const free = est ? est.quota - est.usage : null; | |
| c.storage = free == null ? { ok: true, text: "Storage space unknown" } | |
| : free > 3e9 ? { ok: true, text: `${fmtBytes(free)} of browser storage available` } | |
| : free > 0.8e9 ? { ok: true, warn: true, text: `${fmtBytes(free)} of browser storage available: enough for Linux, maybe not for local models (0.5 to 3 GB each)` } | |
| : { ok: false, text: `Only ${fmtBytes(free)} of browser storage available; Linux needs about 700 MB` }; | |
| return c; | |
| } | |
| function renderChecks(c) { | |
| $("#checks").replaceChildren(...Object.values(c).map((x) => { | |
| const cls = !x.ok ? "bad" : x.warn ? "warn" : "ok"; | |
| return h("li", { class: cls }, icon(cls === "ok" ? "check" : "x"), h("span", {}, x.text)); | |
| })); | |
| if (!c.isolated.ok && window.top !== window) { | |
| $("#checks").append(h("li", {}, h("a", { href: location.href, target: "_blank", rel: "noopener", class: "btn small" }, "Open in a new tab"))); | |
| } | |
| } | |
| function setRow(k, frac, text) { | |
| const row = $(`[data-row="${k}"]`); | |
| row.dataset.state = frac >= 1 ? "done" : frac > 0 ? "busy" : "todo"; | |
| $("progress", row).value = frac; | |
| $(".row-state", row).textContent = text; | |
| } | |
| function showSetup(canInstall) { | |
| $("#setup").hidden = false; | |
| $("#mobile-banner").hidden = !isMobile(); | |
| const btn = $("#install"); | |
| btn.disabled = !canInstall || !navigator.onLine; | |
| if (!navigator.onLine) $("#setup-note").textContent = "You're offline. Connect once to install; after that it works without internet."; | |
| btn.onclick = install; | |
| } | |
| async function install({ replacing } = {}) { | |
| const btn = $("#install"); | |
| const note = $("#setup-note"); | |
| btn.disabled = true; | |
| btn.textContent = "Installing"; | |
| note.className = "note"; | |
| note.textContent = "Keep this tab open. Interrupted downloads resume where they left off."; | |
| await setup.requestPersistence(); | |
| try { | |
| const cxTask = setup.cheerpxStatus() | |
| .then((s) => s.ready || setup.downloadCheerpX((f) => setRow("cx", f, Math.round(f * 100) + "%"))) | |
| .then(() => setRow("cx", 1, "Installed")); | |
| const diskTask = (async () => { | |
| const remote = await setup.fetchRemoteManifest(); | |
| if (diskManifest?.id === remote.id) return setRow("disk", 1, "Installed"); | |
| $("#disk-size").textContent = fmtBytes(remote.downloadBytes); | |
| diskManifest = await setup.downloadDisk((d, t) => setRow("disk", d / t, `${Math.round((d / t) * 100)}%`)); | |
| setRow("disk", 1, "Installed"); | |
| })(); | |
| await Promise.all([cxTask, diskTask]); | |
| // An update replaces the machine: its writable layer belongs to the old image. | |
| if (replacing && replacing !== diskManifest.id) await setup.resetVmStorage("lwa-overlay-" + replacing).catch(() => {}); | |
| updateOfflineStatus(); | |
| await start(); | |
| if (!settings.activeModel) models.open(); // next step: pick a model | |
| } catch (err) { | |
| console.error(err); | |
| note.className = "note error"; | |
| note.textContent = "Installation failed: " + err.message; | |
| btn.disabled = false; | |
| btn.textContent = "Retry"; | |
| } | |
| } | |
| // Aggregates transformers.js per-file progress into one number. | |
| function loadModel(onProgress) { | |
| if (llm.remote) { | |
| return llm.load().then(() => status("model", "ok", "API ready"), (err) => { status("model", "bad", "API not set up"); throw err; }); | |
| } | |
| const files = new Map(); | |
| llm.onProgress = (p) => { | |
| if (!p.file) return; | |
| const prev = files.get(p.file); | |
| files.set(p.file, { loaded: p.status === "done" ? (prev?.total ?? p.loaded) : p.loaded, total: p.total || prev?.total || 0 }); | |
| let loaded = 0, total = 0; | |
| for (const f of files.values()) { loaded += f.loaded; total += f.total; } | |
| total = Math.max(total, activeLocal() ? effectiveModel(activeLocal()).bytes : 0); | |
| const frac = Math.min(0.99, loaded / total); | |
| onProgress?.(frac, `${fmtBytes(loaded)} of ${fmtBytes(total)}`); | |
| status("model", "busy", `Loading ${Math.round(frac * 100)}%`); | |
| }; | |
| llm.onStatus = (t) => { | |
| const warm = t.includes("Warming"); | |
| status("model", "busy", warm ? "Compiling GPU kernels" : "Loading"); | |
| onProgress?.(0.99, warm ? "Compiling GPU kernels" : "Loading"); | |
| }; | |
| llm.onGpu = (g) => { if (g.vendor) $("#gpu-name").title = [g.vendor, g.architecture, g.description].filter(Boolean).join(" · "); }; | |
| status("model", "busy", "Loading"); | |
| return llm.load().then( | |
| () => status("model", "ok", "Model ready"), | |
| (err) => { status("model", "bad", "Model failed"); throw err; }, | |
| ); | |
| } | |
| // Only one tab may run the VM: two VMs writing the same saved disk corrupt it. | |
| function acquireVmLock() { | |
| if (!navigator.locks) return Promise.resolve(true); | |
| return new Promise((resolve) => { | |
| navigator.locks.request("lwa-vm", { ifAvailable: true }, (lock) => { | |
| resolve(!!lock); | |
| return lock ? new Promise(() => {}) : null; // held for the page's lifetime | |
| }); | |
| }); | |
| } | |
| async function start() { | |
| started = true; | |
| $("#setup").hidden = true; | |
| if (!(await acquireVmLock())) { | |
| status("vm", "bad", "Open in another tab"); | |
| addNotice("LocalWebAgent is already running in another tab. Close it and reload this one; two copies at once would damage the machine's files.", "warn"); | |
| return; | |
| } | |
| vm.mountTerminal($("#terminal")); | |
| vm.onActivity = (busy) => { $("#cpu-led").dataset.on = busy ? "1" : "0"; }; | |
| agent = new Agent({ llm, vm, settings, ui: chatUI }); | |
| setComposerEnabled(); | |
| const bootVm = async () => { | |
| status("vm", "busy", "Booting"); | |
| try { | |
| diskManifest ??= await setup.installedDisk(); | |
| await vm.boot({ diskId: diskManifest.id, onStatus: (t) => t !== "Ready" && status("vm", "busy", t) }); | |
| vmReady = true; | |
| status("vm", "ok", "Linux running"); | |
| files = new FileBrowser({ vm, root: $("#files") }); | |
| if (sideView === "files") files.navigate("/home/user"); | |
| } catch (err) { | |
| console.error(err); | |
| status("vm", "bad", "Linux failed"); | |
| vm.term?.writeln("\r\n\x1b[31mFailed to start Linux: " + err.message + "\x1b[0m"); | |
| } | |
| setComposerEnabled(); | |
| }; | |
| if (isMobile() && activeLocal() && !llm.ready && !modelError) showMobileWarning(); | |
| if (memoryConstrained() && activeLocal()) { | |
| // Upload the weights to the GPU before Linux takes its share of memory: on phones | |
| // the two together at peak are what makes the browser kill the GPU process. | |
| status("vm", "busy", "Waiting for the model"); | |
| await loadModelOnce(); | |
| await bootVm(); | |
| } else { | |
| await Promise.all([bootVm(), loadModelOnce()]); | |
| } | |
| setComposerEnabled(); | |
| } | |
| // Phones, tablets and machines reporting under 8 GB of RAM (Chrome caps deviceMemory at 8). | |
| function memoryConstrained() { | |
| return isMobile() || (navigator.deviceMemory ?? 8) < 8; | |
| } | |
| // Loads the current backend unless it is ready or already failed. Never rejects: a | |
| // local-model failure is shown as a callout with the API option. | |
| async function loadModelOnce() { | |
| if (llm.ready) return; | |
| if (llm.none) { status("model", "warn", "No model"); showNoModel(); setComposerEnabled(); return; } | |
| if (modelError) { showModelFailure(modelError); return; } | |
| const mine = llm; | |
| const m = activeLocal(); | |
| // Downloads happen only in the Model Manager, never implicitly here. | |
| if (m && !(await setup.modelStatus(m)).ready) { | |
| if (mine !== llm) return; | |
| status("model", "warn", "Not downloaded"); | |
| showNoModel(`${m.label} isn't downloaded in this browser. `); | |
| setComposerEnabled(); | |
| return; | |
| } | |
| return loadModel().catch((err) => { | |
| if (mine !== llm) return; // replaced (e.g. switched to an API model) while loading | |
| console.error(err); | |
| if (mine.remote) addNotice("The API model isn't set up: " + err.message, "error"); | |
| else { modelError = err; showModelFailure(err); } | |
| }).finally(setComposerEnabled); | |
| } | |
| function friendlyModelError(err) { | |
| const m = String(err?.message ?? err); | |
| if (/Instance reference|device (was |is )?lost|DeviceLost|out of memory|OOM|allocat|Failed to create a WebGPU|OrtRun|createBuffer|mapAsync|Array buffer/i.test(m)) { | |
| return "Your device ran out of graphics memory while loading the model. This is common on phones and on computers with little RAM."; | |
| } | |
| if (/WebGPU is not available|shader-f16|No WebGPU|WebGPU/i.test(m)) return "This browser can't run the local model because it lacks the WebGPU support the model needs."; | |
| if (/fetch|network|download|Failed to load|Incomplete/i.test(m)) return "The model files couldn't be downloaded. Check your internet connection."; | |
| return "The local model hit an error while loading."; | |
| } | |
| function callout(kind, title, text, actions, details, tag = "model") { | |
| $("#empty")?.remove(); | |
| const el = h("div", { class: `callout ${kind}`, "data-callout": tag }, | |
| h("div", { class: "callout-title" }, icon("alert"), h("span", {}, title)), | |
| h("p", {}, text), | |
| h("div", { class: "callout-actions" }, actions), | |
| details ? h("details", { class: "callout-details" }, h("summary", {}, "Technical details"), h("pre", {}, details)) : null); | |
| thread().append(el); | |
| scrollChat(true); | |
| return el; | |
| } | |
| const clearModelCallouts = () => document.querySelectorAll('[data-callout="model"]').forEach((el) => el.remove()); | |
| function showModelFailure(err) { | |
| status("model", "bad", "Model failed"); | |
| clearModelCallouts(); | |
| const el = callout("error", "The model couldn't load", | |
| `${friendlyModelError(err)} Linux is still running on this device. In the Model Manager you can pick a smaller model${activeLocal() !== smallestModel() ? ` (${smallestModel().label} is the smallest)` : ""} or add an API model, and the agent will keep using this machine.`, | |
| [ | |
| h("button", { class: "btn primary small", type: "button", onclick: () => models.open() }, "Open Model Manager"), | |
| h("button", { class: "btn small", type: "button", onclick: () => { el.remove(); retryLocalModel(); } }, "Try again"), | |
| ], | |
| String(err?.message ?? err)); | |
| setComposerEnabled(); | |
| } | |
| function showMobileWarning() { | |
| const m = activeLocal(); | |
| callout("warn", "You're on a phone or tablet", | |
| `${m.label} needs about ${fmtBytes(effectiveModel(m).bytes)} of graphics memory, which most phones can't give a browser tab, so it may fail to load. Trying anyway. In the Model Manager you can switch to an API model (only the model moves to the provider, Linux keeps running here)${m !== smallestModel() ? ` or the smaller ${smallestModel().label}` : ""}.`, | |
| [h("button", { class: "btn primary small", type: "button", onclick: () => models.open() }, "Open Model Manager")]); | |
| } | |
| function showNoModel(prefix = "") { | |
| clearModelCallouts(); | |
| callout("info", "Choose a language model", | |
| `${prefix}Linux is ready. Open the Model Manager to download a model that runs on your GPU, or to add an API model (OpenAI, Anthropic, Gemini, OpenRouter, Hugging Face and more).`, | |
| [h("button", { class: "btn primary small", type: "button", onclick: () => models.open() }, "Open Model Manager")]); | |
| } | |
| function updateOfflineStatus() { | |
| if (usingApi()) status("offline", "warn", "Model via API"); | |
| else status("offline", "ok", "Available offline"); | |
| } | |
| /** Switches the language model (null = none), unloading the previous one. */ | |
| async function activateModel(sel) { | |
| if (agent?.running) throw new Error("Stop the agent before switching models."); | |
| const old = llm; | |
| settings.activeModel = sel; | |
| saveSettings(); | |
| llm = createLlm(); | |
| old.dispose?.(); // frees a local model's GPU memory | |
| modelError = null; | |
| if (agent) agent.llm = llm; | |
| clearModelCallouts(); | |
| syncContextBudget(); | |
| setBackendLabels(); | |
| syncToggles(); | |
| updateOfflineStatus(); | |
| setComposerEnabled(); | |
| if (!started) return; | |
| await loadModelOnce(); | |
| if (llm.ready) addNotice(usingApi() ? `Now using ${activeLabel()} through ${apiHost()}. Linux still runs on this device.` : `Now using ${activeLabel()} on this device.`); | |
| } | |
| function retryLocalModel() { | |
| modelError = null; | |
| llm.dispose?.(); | |
| llm = createLlm(); | |
| if (agent) agent.llm = llm; | |
| setComposerEnabled(); | |
| loadModelOnce(); | |
| } | |
| function setBackendLabels() { | |
| const av = activeApi() ? findPreset(activeApi().preset).avatar : activeLocal()?.avatar; | |
| $("#model-name").replaceChildren(...(settings.activeModel ? [avatarTile(av, "xs", icon("plus"))] : []), h("span", {}, activeLabel())); | |
| $("#gpu-name").textContent = usingApi() ? "API" : activeLocal() ? (MODEL_DEVICE === "webgpu" ? "WebGPU" : MODEL_DEVICE) : ""; | |
| $("#gpu-name").hidden = !settings.activeModel; | |
| } | |
| // ---------- conversation rendering ---------- | |
| const thread = () => $("#messages"); | |
| const scroller = () => $("#scroller"); | |
| function scrollChat(force) { | |
| const el = scroller(); | |
| if (force || el.scrollHeight - el.scrollTop - el.clientHeight < 140) el.scrollTop = el.scrollHeight; | |
| } | |
| function addNotice(text, kind = "") { | |
| $("#empty")?.remove(); | |
| thread().append(h("div", { class: `notice center ${kind}` }, text)); | |
| scrollChat(true); | |
| } | |
| let currentRun = null; // { el, t0, steps, genTokens, genMs } | |
| const chatUI = { | |
| startTurn(step) { | |
| const stepEl = h("div", { class: "step" }); | |
| const rTime = h("span", { class: "r-time" }); | |
| const rLabel = h("span", { class: "r-label" }, "Reasoning"); | |
| const reasoning = h("details", { class: "reasoning", hidden: true }, | |
| h("summary", {}, icon("chevron"), rLabel, rTime), h("div", { class: "r-body" })); | |
| const body = h("div", { class: "md" }); | |
| const statusText = h("span", {}, step === 1 ? "Reading the task" : "Reading the result"); | |
| const live = h("div", { class: "run-status" }, h("span", { class: "spinner" }), statusText); | |
| stepEl.append(reasoning, body, live); | |
| currentRun.el.append(stepEl); | |
| scrollChat(true); | |
| let thinkStart = 0, thinkMs = 0, timer = null; | |
| const tick = () => { rTime.textContent = ` · ${fmtSecs(performance.now() - thinkStart)}`; }; | |
| return { | |
| prefill(done, total) { statusText.textContent = `Reading ${total.toLocaleString()} tokens · ${Math.round((done / total) * 100)}%`; }, | |
| update(p, final) { | |
| if (p.thinking) { | |
| if (!thinkStart) { thinkStart = performance.now(); timer = setInterval(tick, 200); } | |
| reasoning.hidden = false; | |
| $(".r-body", reasoning).textContent = p.thinking; | |
| if (p.thinkingDone && !thinkMs) { | |
| thinkMs = performance.now() - thinkStart; | |
| clearInterval(timer); | |
| rLabel.textContent = "Reasoned"; | |
| rTime.textContent = ` for ${fmtSecs(thinkMs)}`; | |
| } | |
| } | |
| body.innerHTML = p.content ? renderMarkdown(p.content) : ""; | |
| const preparing = p.calls.find((c) => !c.complete); | |
| statusText.textContent = p.thinking && !p.thinkingDone ? "Reasoning" | |
| : preparing ? `Preparing ${TOOL_VERB[preparing.name]?.toLowerCase() ?? preparing.name}` | |
| : p.calls.length ? "Running" : "Writing"; | |
| if (final) { | |
| clearInterval(timer); | |
| if (thinkStart && !thinkMs) { rLabel.textContent = "Reasoned"; rTime.textContent = ` for ${fmtSecs(performance.now() - thinkStart)}`; } | |
| live.remove(); | |
| } | |
| scrollChat(); | |
| }, | |
| note(text) { stepEl.append(h("div", { class: "notice" }, text)); scrollChat(); }, | |
| }; | |
| }, | |
| onToolStart(call) { | |
| const a = call.arguments; | |
| const verb = TOOL_VERB[call.name] ?? call.name; | |
| const target = call.name === "run_command" ? firstLine(a.command ?? "") : a.path ?? ""; | |
| const t0 = performance.now(); | |
| const statusEl = h("span", { class: "t-status" }, "running"); | |
| const timeEl = h("span", {}); | |
| const head = h("button", { class: "tool-head", type: "button" }, | |
| icon("chevron", "chev"), icon(TOOL_ICON[call.name] ?? "terminal"), | |
| h("span", { class: "tool-label" }, call.name === "run_command" ? null : h("span", { class: "verb" }, verb), target), | |
| h("span", { class: "tool-meta" }, timeEl, statusEl, h("span", { class: "dot" }))); | |
| const bodyEl = h("div", { class: "tool-body" }); | |
| if (call.name === "run_command" && (a.command ?? "").includes("\n")) bodyEl.append(h("pre", {}, a.command)); | |
| if (call.name === "write_file") { | |
| const content = a.content ?? ""; | |
| bodyEl.append(h("div", { class: "sub" }, `${plural(content.replace(/\n$/, "").split("\n").length, "line")}`), h("pre", {}, content)); | |
| } | |
| const card = h("div", { class: "tool", "data-state": "running" }, head, bodyEl); | |
| head.addEventListener("click", () => card.classList.toggle("open")); | |
| card._t0 = t0; card._status = statusEl; card._time = timeEl; card._body = bodyEl; card._name = call.name; | |
| currentRun.el.lastElementChild.append(card); | |
| scrollChat(); | |
| return card; | |
| }, | |
| onToolEnd(card, r) { | |
| const state = r.declined ? "declined" : r.error ? "error" : r.timedOut ? "timeout" : r.exitCode === 0 ? "ok" : r.exitCode === null ? "unknown" : "fail"; | |
| card.dataset.state = state; | |
| card._status.textContent = r.declined ? "skipped" : r.error ? "error" : r.timedOut ? "timed out" : r.exitCode === null ? "done" : `exit ${r.exitCode}`; | |
| card._time.textContent = fmtSecs(performance.now() - card._t0); | |
| const out = (r.error ? r.text : r.output ?? "").trim(); | |
| if (card._name !== "write_file" && !r.declined) { | |
| const lines = out ? out.split("\n").length : 0; | |
| card._body.append(h("div", { class: "sub" }, out ? plural(lines, "line") + " of output" : "No output")); | |
| if (out) card._body.append(h("pre", {}, out.length > 20000 ? out.slice(0, 20000) + "\n…" : out)); | |
| if (out && lines <= 10 && card._name === "run_command") card.classList.add("open"); | |
| } | |
| if (state === "fail" || state === "error" || state === "timeout") card.classList.add("open"); | |
| const written = card._name === "write_file" && state === "ok" ? / to (\/.*)$/m.exec(r.output ?? "")?.[1] : null; | |
| if (written) { | |
| const openBtn = h("button", { class: "tool-open", type: "button", title: "Open in the file viewer" }, icon("open"), "Open"); | |
| openBtn.addEventListener("click", (e) => { e.stopPropagation(); openFile(written); }); | |
| $(".tool-meta", card).prepend(openBtn); | |
| files?.noteChanged(written); | |
| if (sideView !== "files") $("#files-badge").hidden = false; | |
| } else if (card._name === "run_command" && sideView === "files") files?.refresh(); | |
| scrollChat(); | |
| }, | |
| confirmTool(call, card) { | |
| card.classList.add("open"); | |
| return new Promise((resolve) => { | |
| const bar = h("div", { class: "confirm" }, | |
| h("span", {}, call.name === "write_file" ? "Write this file?" : "Run this command?"), | |
| h("button", { class: "btn small", type: "button", onclick: () => { bar.remove(); resolve(false); } }, "Skip"), | |
| h("button", { class: "btn small primary", type: "button", onclick: () => { bar.remove(); resolve(true); } }, "Run")); | |
| card.append(bar); | |
| scrollChat(true); | |
| }); | |
| }, | |
| onStats(s) { | |
| currentRun.steps++; | |
| currentRun.genTokens += s.genTokens; | |
| currentRun.genMs += s.genMs; | |
| const tps = s.genTokens / Math.max(0.001, s.genMs / 1000); | |
| status("model", "ok", `${tps.toFixed(0)} tok/s`); | |
| const used = s.promptTokens + s.genTokens; | |
| $("#ctx").textContent = `${used.toLocaleString()} / ${settings.contextBudgetTokens.toLocaleString()} tokens`; | |
| }, | |
| }; | |
| const TOOL_VERB = { run_command: "Run", write_file: "Write", read_file: "Read" }; | |
| const TOOL_ICON = { run_command: "terminal", write_file: "file-pen", read_file: "file" }; | |
| const firstLine = (s) => { const l = s.trim().split("\n"); return l[0] + (l.length > 1 ? " …" : ""); }; | |
| function setComposerEnabled() { | |
| const ready = llm.ready && vmReady; | |
| const running = !!agent?.running; | |
| $("#prompt").disabled = !ready; | |
| $("#send").hidden = running; | |
| $("#stop").hidden = !running; | |
| $("#send").disabled = !ready; | |
| $("#prompt").placeholder = ready ? "Describe a task for the agent" | |
| : llm.none ? "Choose a model in the Model Manager to start" | |
| : !llm.ready ? (modelError ? "No model loaded. Open the Model Manager or try again." : "Loading the model…") | |
| : "Starting Linux…"; | |
| } | |
| async function send(text) { | |
| text = text.trim(); | |
| if (!text || !agent || agent.running) return; | |
| $("#empty")?.remove(); | |
| thread().append(h("div", { class: "msg user" }, text)); | |
| currentRun = { el: h("div", { class: "msg agent" }), t0: performance.now(), steps: 0, genTokens: 0, genMs: 0 }; | |
| thread().append(currentRun.el); | |
| scrollChat(true); | |
| $("#prompt").value = ""; | |
| autoGrow(); | |
| const run = currentRun; | |
| const p = agent.run(text); | |
| setComposerEnabled(); | |
| try { | |
| await p; | |
| } catch (err) { | |
| console.error(err); | |
| run.el.querySelectorAll(".run-status").forEach((el) => el.remove()); | |
| run.el.append(h("div", { class: "notice error" }, "Error: " + err.message)); | |
| } finally { | |
| const tps = run.genTokens / Math.max(0.001, run.genMs / 1000); | |
| run.el.append(h("div", { class: "run-foot" }, | |
| [plural(run.steps, "step"), fmtSecs(performance.now() - run.t0), run.genTokens ? `${tps.toFixed(0)} tok/s` : null].filter(Boolean).join(" · "))); | |
| setComposerEnabled(); | |
| scrollChat(); | |
| $("#prompt").focus(); | |
| } | |
| } | |
| function autoGrow() { | |
| const t = $("#prompt"); | |
| t.style.height = "auto"; | |
| t.style.height = Math.min(220, t.scrollHeight) + "px"; | |
| } | |
| function newConversation() { | |
| if (agent?.running) return; | |
| agent?.clear(); | |
| $("#ctx").textContent = ""; | |
| thread().replaceChildren(); | |
| $("#prompt").focus(); | |
| } | |
| // ---------- composer toggles ---------- | |
| function syncToggles() { | |
| const canThink = activeLocal()?.thinking ?? true; | |
| $("#tog-thinking").disabled = !canThink; | |
| $("#tog-thinking").title = canThink ? "Let the model reason before each step" : `${activeLocal().label} has no reasoning mode`; | |
| $("#tog-thinking").setAttribute("aria-pressed", String(!!settings.thinking && canThink)); | |
| $("#tog-confirm").setAttribute("aria-pressed", String(!!settings.confirmCommands)); | |
| } | |
| $("#tog-thinking").addEventListener("click", () => { settings.thinking = !settings.thinking; saveSettings(); syncToggles(); }); | |
| $("#tog-confirm").addEventListener("click", () => { settings.confirmCommands = !settings.confirmCommands; saveSettings(); syncToggles(); }); | |
| // ---------- side pane: terminal / files ---------- | |
| let sideView = "term"; | |
| function setSideView(view) { | |
| sideView = view; | |
| const side = $(".side"); | |
| side.dataset.view = view; | |
| $(".view-term").hidden = view !== "term"; | |
| $(".view-files").hidden = view !== "files"; | |
| for (const b of document.querySelectorAll("[data-view]")) b.setAttribute("aria-selected", String(b.dataset.view === view)); | |
| if (view === "files") { | |
| $("#files-badge").hidden = true; | |
| if (files && !files.entries.length) files.navigate(files.dir); | |
| } else setTimeout(() => { try { vm.fit?.fit(); } catch {} }, 30); | |
| } | |
| function openFile(path) { | |
| if (!files) return; | |
| if (window.matchMedia("(max-width: 900px)").matches) selectTab("files"); | |
| setSideView("files"); | |
| files.open(path); | |
| } | |
| for (const b of document.querySelectorAll("[data-view]")) b.addEventListener("click", () => setSideView(b.dataset.view)); | |
| $("#side-max").addEventListener("click", () => { | |
| const on = document.body.classList.toggle("side-max"); | |
| $("#side-max").setAttribute("aria-pressed", String(on)); | |
| $("#side-max").title = on ? "Restore" : "Maximize"; | |
| $("#side-max use").setAttribute("href", on ? "#i-minimize" : "#i-maximize"); | |
| setTimeout(() => { try { vm.fit?.fit(); } catch {} }, 30); | |
| }); | |
| document.addEventListener("keydown", (e) => { if (e.key === "Escape" && document.body.classList.contains("side-max") && !$("#settings").open) $("#side-max").click(); }); | |
| // ---------- resizable split ---------- | |
| (() => { | |
| const ws = $("#workspace"); | |
| const sp = $("#splitter"); | |
| try { const w = localStorage.getItem("lwa-split"); if (w) ws.style.setProperty("--left", w); } catch {} | |
| const setFrac = (frac) => { | |
| const v = `${(Math.min(0.75, Math.max(0.25, frac)) * 100).toFixed(1)}%`; | |
| ws.style.setProperty("--left", v); | |
| try { localStorage.setItem("lwa-split", v); } catch {} | |
| }; | |
| sp.addEventListener("pointerdown", (e) => { | |
| sp.setPointerCapture(e.pointerId); | |
| sp.classList.add("dragging"); | |
| document.body.classList.add("resizing"); | |
| const rect = ws.getBoundingClientRect(); | |
| const move = (ev) => setFrac((ev.clientX - rect.left) / rect.width); | |
| const up = () => { | |
| sp.classList.remove("dragging"); | |
| document.body.classList.remove("resizing"); | |
| sp.removeEventListener("pointermove", move); | |
| try { vm.fit?.fit(); } catch {} | |
| }; | |
| sp.addEventListener("pointermove", move); | |
| sp.addEventListener("pointerup", up, { once: true }); | |
| }); | |
| sp.addEventListener("keydown", (e) => { | |
| if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return; | |
| const cur = parseFloat(getComputedStyle(ws).getPropertyValue("--left")) / 100 || 0.46; | |
| setFrac(cur + (e.key === "ArrowLeft" ? -0.02 : 0.02)); | |
| }); | |
| })(); | |
| // ---------- wiring ---------- | |
| $("#composer").addEventListener("submit", (e) => { e.preventDefault(); send($("#prompt").value); }); | |
| $("#prompt").addEventListener("keydown", (e) => { | |
| if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); send($("#prompt").value); } | |
| }); | |
| $("#prompt").addEventListener("input", autoGrow); | |
| $("#stop").addEventListener("click", () => agent?.stop()); | |
| for (const b of document.querySelectorAll("[data-suggest]")) b.addEventListener("click", () => send(b.textContent)); | |
| $("#ctrl-c").addEventListener("click", () => { vm.interrupt(); vm.term?.focus(); }); | |
| $("#term-clear").addEventListener("click", () => { vm.term?.clear(); vm.term?.focus(); }); | |
| $("#new-chat").addEventListener("click", newConversation); | |
| function selectTab(name) { | |
| document.body.dataset.tab = name; | |
| for (const t of document.querySelectorAll("[data-tab]")) t.setAttribute("aria-selected", String(t.dataset.tab === name)); | |
| if (name === "term" || name === "files") setSideView(name); | |
| if (name === "term") setTimeout(() => { try { vm.term?.focus(); } catch {} }, 50); | |
| } | |
| for (const tab of document.querySelectorAll("[data-tab]")) tab.addEventListener("click", () => selectTab(tab.dataset.tab)); | |
| const dlg = $("#settings"); | |
| $("#open-settings").addEventListener("click", () => { | |
| $("#set-model-desc").textContent = usingApi() ? `${activeLabel()} via ${apiHost()}` : activeLocal() ? `${activeLabel()} on this device (WebGPU)` : "None chosen yet"; | |
| $("#set-thinking").checked = settings.thinking; | |
| $("#set-confirm").checked = settings.confirmCommands; | |
| $("#set-steps").value = settings.maxSteps; | |
| $("#set-timeout").value = settings.commandTimeoutSec; | |
| $("#set-context").value = Math.round(settings.contextBudgetTokens / 1000); | |
| $("#set-context").max = usingApi() ? 2000 : 256; | |
| $("#set-context-desc").textContent = usingApi() | |
| ? "How much of the conversation the API model sees, in thousands of tokens. Set it to your model's context window." | |
| : "How much of the conversation the local model sees, in thousands of tokens. Larger is slower and uses more GPU memory."; | |
| dlg.showModal(); | |
| }); | |
| dlg.addEventListener("close", () => { | |
| settings.thinking = $("#set-thinking").checked; | |
| settings.confirmCommands = $("#set-confirm").checked; | |
| settings.maxSteps = Math.min(50, Math.max(1, Number($("#set-steps").value) || DEFAULTS.maxSteps)); | |
| settings.commandTimeoutSec = Math.min(600, Math.max(5, Number($("#set-timeout").value) || DEFAULTS.commandTimeoutSec)); | |
| const k = Number($("#set-context").value); | |
| if (k && k !== Math.round(settings.contextBudgetTokens / 1000)) { | |
| const key = usingApi() ? "contextApiTokens" : "contextLocalTokens"; | |
| settings[key] = Math.round(Math.min(usingApi() ? 2000 : 256, Math.max(4, k)) * 1000); | |
| syncContextBudget(); | |
| $("#ctx").textContent = $("#ctx").textContent.replace(/\/ [\d,.\s]+ tokens/, `/ ${settings.contextBudgetTokens.toLocaleString()} tokens`); | |
| } | |
| saveSettings(); | |
| syncToggles(); | |
| }); | |
| dlg.addEventListener("click", (e) => { if (e.target === dlg) dlg.close(); }); // click on backdrop | |
| $("#set-model").addEventListener("click", () => { dlg.close(); models.open(); }); | |
| // ---------- Model Manager ---------- | |
| const models = createModelManager({ | |
| settings, saveSettings, h, icon, fmtBytes, setup, | |
| activate: activateModel, | |
| isActive, | |
| isMobile, | |
| gpuNote: () => !gpuCheck ? null | |
| : !gpuCheck.ok ? { ok: false, text: `${gpuCheck.text}, so local models can't run in this browser. API models work.` } | |
| : gpuCheck.noF16 ? { ok: true, text: "This browser's WebGPU has no f16 shaders (common with Chrome on Linux, even on GPUs that have them on Windows). Local models use their q4 builds instead: 4-bit weights with full-precision math, so downloads are 15 to 40% larger and generation a bit slower. Models marked \"Needs f16\" can't run here." } | |
| : null, | |
| }); | |
| $("#open-models").addEventListener("click", () => models.open()); | |
| $("#model-name").addEventListener("click", () => models.open()); | |
| $("#reset-vm").addEventListener("click", async () => { | |
| if (!confirm("Erase all files and changes made inside the Linux machine? The page will reload.")) return; | |
| if (vm.overlayName) await setup.resetVmStorage(vm.overlayName); | |
| location.reload(); | |
| }); | |
| $("#uninstall").addEventListener("click", async () => { | |
| if (!confirm("Remove the downloaded models, the Linux disk and all saved files from this browser? Reinstalling needs an internet connection.")) return; | |
| await setup.uninstallAll(); | |
| location.reload(); | |
| }); | |
| window.addEventListener("online", () => { if (!$("#setup").hidden) showSetup(true); }); | |
| // ---------- install as an app (PWA) ---------- | |
| let installPrompt = null; | |
| const runningAsApp = () => matchMedia("(display-mode: standalone)").matches || navigator.standalone === true; | |
| function syncInstallUi() { | |
| const canPrompt = !!installPrompt && !runningAsApp(); | |
| $("#install-app").hidden = !canPrompt; | |
| $("#setup-install-app").hidden = !canPrompt; | |
| $("#set-install").hidden = runningAsApp(); | |
| $("#set-install-desc").textContent = runningAsApp() | |
| ? "Installed: you're using the app now." | |
| : canPrompt ? "Opens in its own window, with an icon in your launcher, and works offline." | |
| : /iPhone|iPad/.test(navigator.userAgent) ? "In Safari: Share, then Add to Home Screen." | |
| : "Use your browser's menu: Install app (or Add to Home Screen)."; | |
| $("#set-install").disabled = !canPrompt; | |
| } | |
| async function promptInstall() { | |
| if (!installPrompt) return; | |
| installPrompt.prompt(); | |
| await installPrompt.userChoice.catch(() => null); | |
| installPrompt = null; // a prompt can only be used once | |
| syncInstallUi(); | |
| } | |
| window.addEventListener("beforeinstallprompt", (e) => { | |
| e.preventDefault(); // show our own button instead of the browser's mini-infobar | |
| installPrompt = e; | |
| syncInstallUi(); | |
| }); | |
| window.addEventListener("appinstalled", () => { installPrompt = null; syncInstallUi(); }); | |
| $("#install-app").addEventListener("click", promptInstall); | |
| $("#setup-install-app").addEventListener("click", promptInstall); | |
| $("#set-install").addEventListener("click", promptInstall); | |
| syncInstallUi(); | |
| document.body.dataset.tab = "chat"; | |
| $(".side").dataset.view = "term"; | |
| init().catch((err) => { | |
| console.error(err); | |
| addNotice("Startup error: " + err.message, "error"); | |
| }); | |