// LocalWebAgent service worker. // 1. Keeps the app shell available offline (network-first, cache fallback). // 2. Caches the CheerpX runtime the first time the browser loads it from // Leaning Technologies' CDN, so the VM also boots offline. // 3. Serves the Linux disk image to CheerpX as a byte-range-capable virtual file // (__vm__/disk.ext2), backed by the chunks the setup screen stored in Cache Storage. // 4. Adds the cross-origin isolation headers (COOP/COEP) that SharedArrayBuffer, // CheerpX and multi-threaded WASM need, even when a host forgets to send them. const SHELL_VERSION = "lwa-shell-0.10.0"; const CX_ORIGIN = "https://cxrtnc.leaningtech.com"; const CX_CACHE_PREFIX = "lwa-cheerpx-"; const DISK_CACHE = "lwa-disk"; const SCOPE = self.registration.scope; const DISK_URL = SCOPE + "__vm__/disk.ext2"; const MANIFEST_KEY = SCOPE + "__vm__/manifest.json"; const chunkKey = (i) => SCOPE + "__vm__/chunk/" + i; const SHELL_FILES = [ "./", "index.html", "css/app.css", "icon.svg", "manifest.webmanifest", "icons/icon-192.png", "icons/icon-512.png", "icons/maskable-192.png", "icons/maskable-512.png", "icons/apple-touch-icon.png", "js/config.js", "js/config-defaults.js", "js/main.js", "js/setup.js", "js/vm.js", "js/agent.js", "js/llm.js", "js/llm-worker.js", "js/llm-engine.js", "js/lazy-weights.js", "js/remote-llm.js", "js/model-manager.js", "js/fast-download.js", "js/hf-auth.js", "js/oauth-callback.js", "oauth.html", "js/prompts.js", "js/toolcalls.js", "js/markdown.js", "js/files.js", "vendor/transformers.min.js", "vendor/highlight.min.js", "vendor/ort/ort-wasm-simd-threaded.asyncify.mjs", "vendor/ort/ort-wasm-simd-threaded.asyncify.wasm", "vendor/xterm/xterm.mjs", "vendor/xterm/xterm.css", "vendor/xterm/addon-fit.mjs", "vendor/avatars/anthropic.png", "vendor/avatars/cerebras.png", "vendor/avatars/deepseek.png", "vendor/avatars/fireworks.png", "vendor/avatars/google.png", "vendor/avatars/groq.png", "vendor/avatars/huggingface.png", "vendor/avatars/ibm.png", "vendor/avatars/liquidai.png", "vendor/avatars/meta.png", "vendor/avatars/menlo.png", "vendor/avatars/lmstudio.png", "vendor/avatars/mistral.png", "vendor/avatars/ollama.png", "vendor/avatars/openai.png", "vendor/avatars/openrouter.png", "vendor/avatars/qwen.png", "vendor/avatars/together.png", "vendor/avatars/xai.png", "vendor/fonts/inter-latin.woff2", "vendor/fonts/inter-latin-ext.woff2", "vendor/fonts/jetbrains-mono-latin.woff2", ]; self.addEventListener("install", (event) => { event.waitUntil((async () => { const cache = await caches.open(SHELL_VERSION); // Best effort: a missing file must not block installation. await Promise.all(SHELL_FILES.map((f) => cache.add(new Request(new URL(f, SCOPE), { cache: "reload" })).catch(() => {}))); await self.skipWaiting(); })()); }); self.addEventListener("activate", (event) => { event.waitUntil((async () => { for (const k of await caches.keys()) { if (k.startsWith("lwa-shell-") && k !== SHELL_VERSION) await caches.delete(k); } await self.clients.claim(); })()); }); self.addEventListener("message", (event) => { if (event.data?.type === "disk-updated") { manifestPromise = null; lru.clear(); } }); self.addEventListener("fetch", (event) => { const req = event.request; const url = new URL(req.url); if (req.url.split("?")[0] === DISK_URL) return event.respondWith(serveDisk(req)); if (url.origin === CX_ORIGIN) return event.respondWith(cheerpx(req)); if (url.origin === self.location.origin && req.method === "GET") { // Disk chunks are stored decompressed by the setup code; don't double-cache the .gz files. if (url.pathname.includes("/disk/")) return; return event.respondWith(shell(req)); } if (url.hostname === "huggingface.co" || url.hostname.endsWith(".hf.co")) { // Model downloads (byte-range requests from fast-download.js) go straight to the // network: piping hundreds of MB through the service worker only slows them down. if (req.headers.has("range")) return; return event.respondWith(hub(req)); } }); // ---------- app shell ---------- async function shell(req) { const cache = await caches.open(SHELL_VERSION); try { const res = await fetch(req); if (res.ok && res.status === 200 && !req.headers.has("range")) cache.put(req, res.clone()).catch(() => {}); return isolate(res); } catch (err) { const hit = (await cache.match(req, { ignoreSearch: true })) ?? (req.mode === "navigate" ? await cache.match(new URL("index.html", SCOPE)) : undefined); if (hit) return isolate(hit); return new Response("Offline and not cached: " + req.url, { status: 504 }); } } function isolate(res) { if (res.status === 0 || res.type === "opaque") return res; const h = new Headers(res.headers); h.set("Cross-Origin-Opener-Policy", "same-origin"); h.set("Cross-Origin-Embedder-Policy", "require-corp"); h.set("Cross-Origin-Resource-Policy", "cross-origin"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers: h }); } // ---------- CheerpX runtime (cache-first) ---------- async function cheerpx(req) { const version = new URL(req.url).pathname.split("/")[1]; const cache = await caches.open(CX_CACHE_PREFIX + version); const hit = await cache.match(req.url); if (hit) return hit; const res = await fetch(req.url, { mode: "cors", credentials: "omit" }); if (res.ok) await cache.put(req.url, res.clone()); return res; } // ---------- Hugging Face Hub (model files are cached by transformers.js itself) ---------- async function hub(req) { try { return await fetch(req); } catch { // Offline: answer probes for optional files with a clean 404 instead of a network error. return new Response("offline", { status: 404, statusText: "Offline" }); } } // ---------- Disk image ---------- let manifestPromise = null; function manifest() { manifestPromise ??= caches.open(DISK_CACHE) .then((c) => c.match(MANIFEST_KEY)) .then((r) => (r ? r.json() : null)) .catch(() => null); return manifestPromise; } // Small LRU of decompressed 4 MiB chunks. const lru = new Map(); const LRU_MAX = 12; async function getChunk(m, i) { if (!m.chunks[i]) return null; // all-zero chunk let buf = lru.get(i); if (buf) { lru.delete(i); lru.set(i, buf); return buf; } const cache = await caches.open(DISK_CACHE); const res = await cache.match(chunkKey(i)); if (!res) throw new Error("disk chunk " + i + " missing; run setup again"); buf = new Uint8Array(await res.arrayBuffer()); // Chunks are stored gzipped since v0.9 (older installs stored them decompressed). if (buf[0] === 0x1f && buf[1] === 0x8b) { buf = new Uint8Array(await new Response(new Blob([buf]).stream().pipeThrough(new DecompressionStream("gzip"))).arrayBuffer()); } lru.set(i, buf); if (lru.size > LRU_MAX) lru.delete(lru.keys().next().value); return buf; } async function serveDisk(req) { const m = await manifest(); const base = { "Accept-Ranges": "bytes", "Content-Type": "application/octet-stream", "Cross-Origin-Resource-Policy": "same-origin", "Cache-Control": "no-store", }; if (!m) return new Response("Disk image not installed", { status: 503, headers: base }); // CheerpX's HttpBytesDevice requires a validator; the image id changes with the content. base["ETag"] = `"${m.id}"`; base["Last-Modified"] = "Thu, 01 Jan 2026 00:00:00 GMT"; const size = m.size; if (req.method === "HEAD") return new Response(null, { status: 200, headers: { ...base, "Content-Length": String(size) } }); const range = /bytes=(\d*)-(\d*)/.exec(req.headers.get("range") ?? ""); let start = 0, end = size - 1; if (range) { if (range[1] === "") { start = Math.max(0, size - Number(range[2])); } else { start = Number(range[1]); if (range[2] !== "") end = Math.min(Number(range[2]), size - 1); } } if (start > end || start >= size) { return new Response(null, { status: 416, headers: { ...base, "Content-Range": `bytes */${size}` } }); } if (!range) { // Full read: stream every chunk in order. let i = 0; const n = m.chunks.length; const body = new ReadableStream({ async pull(ctrl) { if (i >= n) return ctrl.close(); const len = Math.min(m.chunkSize, size - i * m.chunkSize); const c = await getChunk(m, i++); ctrl.enqueue(c ? c.subarray(0, len) : new Uint8Array(len)); }, }); return new Response(body, { status: 200, headers: { ...base, "Content-Length": String(size) } }); } const out = new Uint8Array(end - start + 1); let pos = start; while (pos <= end) { const i = Math.floor(pos / m.chunkSize); const off = pos - i * m.chunkSize; const take = Math.min(m.chunkSize - off, end - pos + 1); const c = await getChunk(m, i); if (c) out.set(c.subarray(off, off + take), pos - start); pos += take; } return new Response(out, { status: 206, headers: { ...base, "Content-Range": `bytes ${start}-${end}/${size}`, "Content-Length": String(out.length) }, }); }