Spaces:
Running
Running
v0.6.2: fast, resumable model downloads
Browse filesSource: github.com/erinoooo/LocalWebAgent@7c48302
- README.md +1 -1
- js/config.js +1 -1
- js/fast-download.js +142 -0
- js/model-manager.js +26 -5
- js/setup.js +31 -33
- sw.js +2 -2
README.md
CHANGED
|
@@ -38,7 +38,7 @@ An AI agent with its own Linux computer, entirely inside one web page.
|
|
| 38 |
|
| 39 |
## Local models
|
| 40 |
|
| 41 |
-
Download, remove and switch them in the Model Manager. Downloads show their progress, can be cancelled, and
|
| 42 |
|
| 43 |
| Model | Download | Context | Reasoning | Notes |
|
| 44 |
|---|---:|---:|:---:|---|
|
|
|
|
| 38 |
|
| 39 |
## Local models
|
| 40 |
|
| 41 |
+
Download, remove and switch them in the Model Manager. Downloads are fast: large files are fetched in 16 MB pieces over several connections at once (8, or 4 on low-memory devices), with automatic retries. They show their progress and speed, can be cancelled, and resume where they stopped, even after closing the tab. Everything is stored in the browser so the model also works offline. Switching models doesn't reload the page. The first model you download is put to use automatically. All are 4-bit (q4f16) ONNX builds loaded straight from their Hugging Face repositories.
|
| 42 |
|
| 43 |
| Model | Download | Context | Reasoning | Notes |
|
| 44 |
|---|---:|---:|:---:|---|
|
js/config.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
// Central configuration. Everything that pins a version or a location lives here.
|
| 2 |
-
export const APP_VERSION = "0.6.
|
| 3 |
|
| 4 |
// --- Local language models (loaded from the Hugging Face Hub, cached in Cache Storage) ---
|
| 5 |
// Each runs on WebGPU through transformers.js. `chunks` is how many external weight files
|
|
|
|
| 1 |
// Central configuration. Everything that pins a version or a location lives here.
|
| 2 |
+
export const APP_VERSION = "0.6.2";
|
| 3 |
|
| 4 |
// --- Local language models (loaded from the Hugging Face Hub, cached in Cache Storage) ---
|
| 5 |
// Each runs on WebGPU through transformers.js. `chunks` is how many external weight files
|
js/fast-download.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Fast, resumable downloads of large files into Cache Storage.
|
| 2 |
+
//
|
| 3 |
+
// A single HTTP stream rarely fills a fast connection (TCP ramp-up, per-connection
|
| 4 |
+
// throughput limits on the CDN side). Hugging Face's CDN supports byte ranges and exposes
|
| 5 |
+
// Content-Range to web pages, so big files are split into pieces fetched over several
|
| 6 |
+
// connections at once. Each finished piece is stored in its own cache entry, so a
|
| 7 |
+
// cancelled or interrupted download continues where it stopped. When every piece is
|
| 8 |
+
// there, they are joined into one Blob (disk-backed in Chromium, never one big
|
| 9 |
+
// ArrayBuffer) and stored as the finished file under its normal URL.
|
| 10 |
+
//
|
| 11 |
+
// Servers that ignore Range get a plain single-stream download.
|
| 12 |
+
|
| 13 |
+
export const PARTIAL_CACHE = "lwa-partial";
|
| 14 |
+
const CHUNK = 16 * 1024 * 1024;
|
| 15 |
+
const RETRIES = 4;
|
| 16 |
+
|
| 17 |
+
/** Connections to use: fewer on low-memory devices, since each in-flight piece is buffered. */
|
| 18 |
+
export function defaultConnections() {
|
| 19 |
+
const mem = typeof navigator !== "undefined" ? navigator.deviceMemory ?? 8 : 8;
|
| 20 |
+
return mem <= 4 ? 4 : 8;
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
| 24 |
+
const t = setTimeout(resolve, ms);
|
| 25 |
+
signal?.addEventListener("abort", () => { clearTimeout(t); reject(signal.reason ?? new DOMException("Aborted", "AbortError")); }, { once: true });
|
| 26 |
+
});
|
| 27 |
+
|
| 28 |
+
/** Reads a response body, reporting each chunk's size; returns the bytes as a Blob. */
|
| 29 |
+
async function readBody(res, onBytes) {
|
| 30 |
+
const reader = res.body.getReader();
|
| 31 |
+
const parts = [];
|
| 32 |
+
let got = 0;
|
| 33 |
+
for (;;) {
|
| 34 |
+
const { done, value } = await reader.read();
|
| 35 |
+
if (done) break;
|
| 36 |
+
parts.push(value);
|
| 37 |
+
got += value.byteLength;
|
| 38 |
+
onBytes(value.byteLength);
|
| 39 |
+
}
|
| 40 |
+
return { blob: new Blob(parts), got };
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
/** Plain single-stream download, streamed straight into the cache. */
|
| 44 |
+
async function streamToCache(cache, url, res, onBytes) {
|
| 45 |
+
const size = Number(res.headers.get("Content-Length")) || 0;
|
| 46 |
+
let got = 0;
|
| 47 |
+
const counted = res.body.pipeThrough(new TransformStream({
|
| 48 |
+
transform(chunk, ctl) { got += chunk.byteLength; onBytes(chunk.byteLength); ctl.enqueue(chunk); },
|
| 49 |
+
}));
|
| 50 |
+
await cache.put(url, new Response(counted, { status: 200, headers: new Headers(res.headers) }));
|
| 51 |
+
if (size && got !== size) {
|
| 52 |
+
await cache.delete(url);
|
| 53 |
+
throw new Error(`Incomplete download (${got} of ${size} bytes)`);
|
| 54 |
+
}
|
| 55 |
+
return got;
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
const partKey = (url, i, n, total) => `${url}${url.includes("?") ? "&" : "?"}lwa-part=${i}&of=${n}&size=${total}`;
|
| 59 |
+
|
| 60 |
+
/**
|
| 61 |
+
* Downloads url into cache (stored under url). onBytes(delta) reports progress, including
|
| 62 |
+
* pieces already present from an earlier attempt; it can be negative when a failed piece
|
| 63 |
+
* is retried. onSize(total) reports the file size once known. Returns the size.
|
| 64 |
+
*/
|
| 65 |
+
export async function fetchToCache(cache, url, { signal, onBytes = () => {}, onSize = () => {}, connections = defaultConnections(), chunkSize = CHUNK } = {}) {
|
| 66 |
+
// Probe: one byte tells us whether ranges work, the total size and the final CDN URL.
|
| 67 |
+
const probe = await fetch(url, { headers: { Range: "bytes=0-0" }, signal });
|
| 68 |
+
const range = probe.status === 206 && /\/(\d+)\s*$/.exec(probe.headers.get("Content-Range") ?? "");
|
| 69 |
+
if (!range) {
|
| 70 |
+
if (!probe.ok || !probe.body) throw new Error(`HTTP ${probe.status}`);
|
| 71 |
+
onSize(Number(probe.headers.get("Content-Length")) || 0);
|
| 72 |
+
return streamToCache(cache, url, probe, onBytes); // no range support: this is the whole file
|
| 73 |
+
}
|
| 74 |
+
await probe.body?.cancel().catch(() => {});
|
| 75 |
+
const total = Number(range[1]);
|
| 76 |
+
onSize(total);
|
| 77 |
+
const contentType = probe.headers.get("Content-Type") || "application/octet-stream";
|
| 78 |
+
if (total <= chunkSize * 2) {
|
| 79 |
+
const res = await fetch(url, { signal });
|
| 80 |
+
if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}`);
|
| 81 |
+
return streamToCache(cache, url, res, onBytes);
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
// Signed CDN URLs skip the redirect hop for every piece; fall back to the original URL
|
| 85 |
+
// if the signature expires mid-download.
|
| 86 |
+
let rangeUrl = probe.redirected ? probe.url : url;
|
| 87 |
+
const n = Math.ceil(total / chunkSize);
|
| 88 |
+
const partial = await caches.open(PARTIAL_CACHE);
|
| 89 |
+
const missing = [];
|
| 90 |
+
for (let i = 0; i < n; i++) {
|
| 91 |
+
const hit = await partial.match(partKey(url, i, n, total));
|
| 92 |
+
if (hit) onBytes(Math.min(chunkSize, total - i * chunkSize)); // resumed piece
|
| 93 |
+
else missing.push(i);
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
async function fetchPiece(i) {
|
| 97 |
+
const start = i * chunkSize;
|
| 98 |
+
const end = Math.min(total, start + chunkSize) - 1;
|
| 99 |
+
const want = end - start + 1;
|
| 100 |
+
for (let attempt = 0; ; attempt++) {
|
| 101 |
+
let counted = 0;
|
| 102 |
+
try {
|
| 103 |
+
const res = await fetch(rangeUrl, { headers: { Range: `bytes=${start}-${end}` }, signal });
|
| 104 |
+
if ((res.status === 403 || res.status === 410) && rangeUrl !== url) { rangeUrl = url; throw new Error(`HTTP ${res.status}`); }
|
| 105 |
+
if (res.status !== 206 || !res.body) throw new Error(`HTTP ${res.status}`);
|
| 106 |
+
const { blob, got } = await readBody(res, (b) => { counted += b; onBytes(b); });
|
| 107 |
+
if (got !== want) throw new Error(`short piece (${got} of ${want} bytes)`);
|
| 108 |
+
await partial.put(partKey(url, i, n, total), new Response(blob, { headers: { "Content-Length": String(got) } }));
|
| 109 |
+
return;
|
| 110 |
+
} catch (err) {
|
| 111 |
+
if (counted) onBytes(-counted); // those bytes will be fetched again
|
| 112 |
+
if (signal?.aborted || err.name === "AbortError") throw err;
|
| 113 |
+
if (attempt >= RETRIES) throw new Error(`Download failed after ${RETRIES + 1} attempts: ${err.message}`);
|
| 114 |
+
await sleep(500 * 2 ** attempt, signal);
|
| 115 |
+
}
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
// A small pool of workers pulls pieces off the queue.
|
| 120 |
+
const queue = missing.slice();
|
| 121 |
+
const worker = async () => { while (queue.length) await fetchPiece(queue.shift()); };
|
| 122 |
+
await Promise.all(Array.from({ length: Math.min(connections, queue.length) }, worker));
|
| 123 |
+
|
| 124 |
+
// Join the pieces (Blobs backed by the cache on disk) and store the finished file.
|
| 125 |
+
const blobs = [];
|
| 126 |
+
for (let i = 0; i < n; i++) {
|
| 127 |
+
const res = await partial.match(partKey(url, i, n, total));
|
| 128 |
+
if (!res) throw new Error(`piece ${i} went missing; try again`);
|
| 129 |
+
blobs.push(await res.blob());
|
| 130 |
+
}
|
| 131 |
+
const file = new Blob(blobs, { type: contentType });
|
| 132 |
+
if (file.size !== total) throw new Error(`assembled ${file.size} of ${total} bytes`);
|
| 133 |
+
await cache.put(url, new Response(file, { status: 200, headers: { "Content-Type": contentType, "Content-Length": String(total) } }));
|
| 134 |
+
for (let i = 0; i < n; i++) await partial.delete(partKey(url, i, n, total));
|
| 135 |
+
return total;
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
/** Deletes leftover pieces of unfinished downloads whose URL starts with prefix. */
|
| 139 |
+
export async function clearPartial(prefix) {
|
| 140 |
+
const partial = await caches.open(PARTIAL_CACHE);
|
| 141 |
+
for (const req of await partial.keys()) if (req.url.startsWith(prefix)) await partial.delete(req);
|
| 142 |
+
}
|
js/model-manager.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
// The Model Manager: one place to download, remove and switch local models, and to add,
|
| 2 |
// edit, test and switch between any number of API models.
|
| 3 |
import { LOCAL_MODELS } from "./config.js";
|
|
|
|
| 4 |
import { API_PRESETS, findPreset, RemoteLLM, loadApiKey, saveApiKey, deleteApiKey, apiKeyRemembered } from "./remote-llm.js";
|
| 5 |
|
| 6 |
const AVATAR_BASE = new URL("../vendor/avatars/", import.meta.url).href;
|
|
@@ -39,6 +40,7 @@ export function createModelManager(deps) {
|
|
| 39 |
const editDlg = document.getElementById("api-edit");
|
| 40 |
const downloads = new Map(); // model id -> { loaded, total, ctrl, error }
|
| 41 |
const cached = new Map(); // model id -> bytes in Cache Storage
|
|
|
|
| 42 |
let busy = null; // id being activated
|
| 43 |
let tab = "local";
|
| 44 |
|
|
@@ -55,6 +57,11 @@ export function createModelManager(deps) {
|
|
| 55 |
}
|
| 56 |
|
| 57 |
async function refreshCached() {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
await Promise.all(LOCAL_MODELS.map(async (m) => {
|
| 59 |
const [st, bytes] = await Promise.all([setup.modelStatus(m).catch(() => ({ ready: false })), setup.modelCachedBytes(m).catch(() => 0)]);
|
| 60 |
cached.set(m.id, st.ready ? bytes || m.bytes : 0);
|
|
@@ -130,7 +137,7 @@ export function createModelManager(deps) {
|
|
| 130 |
h("button", { class: "icon-btn sm", type: "button", title: `Remove ${m.label}`, "aria-label": `Remove ${m.label}`, onclick: () => remove(m) }, icon("trash")),
|
| 131 |
];
|
| 132 |
} else {
|
| 133 |
-
actions = [h("button", { class: "btn small primary", type: "button", onclick: () => download(m) }, icon("download"), "Download")];
|
| 134 |
}
|
| 135 |
|
| 136 |
const pct = d?.total ? Math.round((d.loaded / d.total) * 100) : 0;
|
|
@@ -149,7 +156,7 @@ export function createModelManager(deps) {
|
|
| 149 |
chip(null, m.license, "muted")),
|
| 150 |
downloading ? h("div", { class: "mc-progress" },
|
| 151 |
h("div", { class: "bar" }, h("i", { style: `width:${pct}%` })),
|
| 152 |
-
h("span", { class: "mc-progress-text" }, `${pct}% · ${fmtBytes(d.loaded)} of ${fmtBytes(d.total)}`)) : null,
|
| 153 |
d?.error ? h("div", { class: "mc-error" }, d.error) : null),
|
| 154 |
h("div", { class: "mc-actions" }, actions));
|
| 155 |
}
|
|
@@ -207,6 +214,15 @@ export function createModelManager(deps) {
|
|
| 207 |
downloads.set(m.id, d);
|
| 208 |
render();
|
| 209 |
let lastPaint = 0;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
try {
|
| 211 |
await setup.requestPersistence();
|
| 212 |
await setup.downloadModel(m, {
|
|
@@ -214,6 +230,10 @@ export function createModelManager(deps) {
|
|
| 214 |
onProgress: (loaded, total) => {
|
| 215 |
d.loaded = loaded; d.total = total;
|
| 216 |
const now = performance.now();
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
const card = dlg.querySelector(`[data-local="${m.id}"]`);
|
| 218 |
if (!card || now - lastPaint < 100) return;
|
| 219 |
lastPaint = now;
|
|
@@ -221,16 +241,17 @@ export function createModelManager(deps) {
|
|
| 221 |
const bar = card.querySelector(".mc-progress .bar i");
|
| 222 |
if (bar) bar.style.width = pct + "%";
|
| 223 |
const t = card.querySelector(".mc-progress-text");
|
| 224 |
-
if (t) t.textContent = `${pct}% · ${fmtBytes(loaded)} of ${fmtBytes(total)}`;
|
| 225 |
},
|
| 226 |
});
|
| 227 |
downloads.delete(m.id);
|
|
|
|
| 228 |
await refreshCached();
|
| 229 |
// First model ever: start using it right away.
|
| 230 |
if (!settings.activeModel) await use({ kind: "local", id: m.id });
|
| 231 |
} catch (err) {
|
| 232 |
-
if (err.name === "AbortError") downloads.delete(m.id);
|
| 233 |
-
else d.error =
|
| 234 |
}
|
| 235 |
render();
|
| 236 |
}
|
|
|
|
| 1 |
// The Model Manager: one place to download, remove and switch local models, and to add,
|
| 2 |
// edit, test and switch between any number of API models.
|
| 3 |
import { LOCAL_MODELS } from "./config.js";
|
| 4 |
+
import { PARTIAL_CACHE } from "./fast-download.js";
|
| 5 |
import { API_PRESETS, findPreset, RemoteLLM, loadApiKey, saveApiKey, deleteApiKey, apiKeyRemembered } from "./remote-llm.js";
|
| 6 |
|
| 7 |
const AVATAR_BASE = new URL("../vendor/avatars/", import.meta.url).href;
|
|
|
|
| 40 |
const editDlg = document.getElementById("api-edit");
|
| 41 |
const downloads = new Map(); // model id -> { loaded, total, ctrl, error }
|
| 42 |
const cached = new Map(); // model id -> bytes in Cache Storage
|
| 43 |
+
const partialIds = new Set(); // models with pieces of an unfinished download
|
| 44 |
let busy = null; // id being activated
|
| 45 |
let tab = "local";
|
| 46 |
|
|
|
|
| 57 |
}
|
| 58 |
|
| 59 |
async function refreshCached() {
|
| 60 |
+
const partialUrls = await caches.open(PARTIAL_CACHE).then((c) => c.keys()).then((ks) => ks.map((r) => r.url)).catch(() => []);
|
| 61 |
+
for (const m of LOCAL_MODELS) {
|
| 62 |
+
if (partialUrls.some((u) => u.startsWith(`https://huggingface.co/${m.repo}/`))) partialIds.add(m.id);
|
| 63 |
+
else if (!downloads.has(m.id)) partialIds.delete(m.id);
|
| 64 |
+
}
|
| 65 |
await Promise.all(LOCAL_MODELS.map(async (m) => {
|
| 66 |
const [st, bytes] = await Promise.all([setup.modelStatus(m).catch(() => ({ ready: false })), setup.modelCachedBytes(m).catch(() => 0)]);
|
| 67 |
cached.set(m.id, st.ready ? bytes || m.bytes : 0);
|
|
|
|
| 137 |
h("button", { class: "icon-btn sm", type: "button", title: `Remove ${m.label}`, "aria-label": `Remove ${m.label}`, onclick: () => remove(m) }, icon("trash")),
|
| 138 |
];
|
| 139 |
} else {
|
| 140 |
+
actions = [h("button", { class: "btn small primary", type: "button", onclick: () => download(m) }, icon("download"), partialIds.has(m.id) ? "Resume" : "Download")];
|
| 141 |
}
|
| 142 |
|
| 143 |
const pct = d?.total ? Math.round((d.loaded / d.total) * 100) : 0;
|
|
|
|
| 156 |
chip(null, m.license, "muted")),
|
| 157 |
downloading ? h("div", { class: "mc-progress" },
|
| 158 |
h("div", { class: "bar" }, h("i", { style: `width:${pct}%` })),
|
| 159 |
+
h("span", { class: "mc-progress-text" }, `${pct}% · ${fmtBytes(d.loaded)} of ${fmtBytes(d.total)}${d.speed ?? ""}`)) : null,
|
| 160 |
d?.error ? h("div", { class: "mc-error" }, d.error) : null),
|
| 161 |
h("div", { class: "mc-actions" }, actions));
|
| 162 |
}
|
|
|
|
| 214 |
downloads.set(m.id, d);
|
| 215 |
render();
|
| 216 |
let lastPaint = 0;
|
| 217 |
+
const samples = []; // [time, bytes] for a moving speed average
|
| 218 |
+
const started = performance.now();
|
| 219 |
+
const speedText = () => {
|
| 220 |
+
if (samples.length < 2) return "";
|
| 221 |
+
const [t0, b0] = samples[0];
|
| 222 |
+
const [t1, b1] = samples[samples.length - 1];
|
| 223 |
+
const bps = ((b1 - b0) / (t1 - t0)) * 1000;
|
| 224 |
+
return bps > 0 ? ` · ${fmtBytes(bps)}/s` : "";
|
| 225 |
+
};
|
| 226 |
try {
|
| 227 |
await setup.requestPersistence();
|
| 228 |
await setup.downloadModel(m, {
|
|
|
|
| 230 |
onProgress: (loaded, total) => {
|
| 231 |
d.loaded = loaded; d.total = total;
|
| 232 |
const now = performance.now();
|
| 233 |
+
// Skip the first moment: pieces resumed from an earlier attempt arrive instantly.
|
| 234 |
+
if (now - started > 700) samples.push([now, loaded]);
|
| 235 |
+
while (samples.length > 2 && now - samples[0][0] > 4000) samples.shift();
|
| 236 |
+
d.speed = speedText();
|
| 237 |
const card = dlg.querySelector(`[data-local="${m.id}"]`);
|
| 238 |
if (!card || now - lastPaint < 100) return;
|
| 239 |
lastPaint = now;
|
|
|
|
| 241 |
const bar = card.querySelector(".mc-progress .bar i");
|
| 242 |
if (bar) bar.style.width = pct + "%";
|
| 243 |
const t = card.querySelector(".mc-progress-text");
|
| 244 |
+
if (t) t.textContent = `${pct}% · ${fmtBytes(loaded)} of ${fmtBytes(total)}${d.speed}`;
|
| 245 |
},
|
| 246 |
});
|
| 247 |
downloads.delete(m.id);
|
| 248 |
+
partialIds.delete(m.id);
|
| 249 |
await refreshCached();
|
| 250 |
// First model ever: start using it right away.
|
| 251 |
if (!settings.activeModel) await use({ kind: "local", id: m.id });
|
| 252 |
} catch (err) {
|
| 253 |
+
if (err.name === "AbortError") { downloads.delete(m.id); partialIds.add(m.id); } // pieces kept: next time resumes
|
| 254 |
+
else { d.error = `Download failed: ${err.message}. Finished parts are kept, so Resume continues from there.`; partialIds.add(m.id); }
|
| 255 |
}
|
| 256 |
render();
|
| 257 |
}
|
js/setup.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
| 4 |
import {
|
| 5 |
CX_BASE, CX_FILES, CACHE_CX, CACHE_DISK, CACHE_MODEL, DISK_BASE, modelFiles, hubUrl,
|
| 6 |
} from "./config.js";
|
|
|
|
| 7 |
|
| 8 |
const scopeUrl = (p) => new URL(p, document.baseURI).href;
|
| 9 |
const MANIFEST_KEY = () => scopeUrl("__vm__/manifest.json");
|
|
@@ -69,45 +70,41 @@ export async function modelCachedBytes(model) {
|
|
| 69 |
|
| 70 |
/**
|
| 71 |
* Downloads every file a local model needs into Cache Storage (the cache transformers.js
|
| 72 |
-
* reads)
|
| 73 |
-
*
|
| 74 |
-
*
|
| 75 |
*/
|
| 76 |
export async function downloadModel(model, { onProgress, signal } = {}) {
|
| 77 |
const cache = await caches.open(CACHE_MODEL);
|
| 78 |
const files = modelFiles(model);
|
| 79 |
-
const sizes = new Map();
|
| 80 |
-
let
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
for (const f of files) {
|
| 84 |
-
const
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
const res = await fetch(url, { signal });
|
| 88 |
-
if (!res.ok || !res.body) throw new Error(`Download failed (HTTP ${res.status}) for ${f}`);
|
| 89 |
-
const size = Number(res.headers.get("Content-Length")) || 0;
|
| 90 |
-
sizes.set(f, size);
|
| 91 |
-
total = Math.max(total, done + size);
|
| 92 |
-
let got = 0;
|
| 93 |
-
let last = 0;
|
| 94 |
-
const counted = res.body.pipeThrough(new TransformStream({
|
| 95 |
-
transform(chunk, ctl) {
|
| 96 |
-
got += chunk.byteLength;
|
| 97 |
-
const now = performance.now();
|
| 98 |
-
if (now - last > 150) { last = now; report(got); }
|
| 99 |
-
ctl.enqueue(chunk);
|
| 100 |
-
},
|
| 101 |
-
}));
|
| 102 |
-
await cache.put(url, new Response(counted, { status: 200, headers: new Headers(res.headers) }));
|
| 103 |
-
if (size && got !== size) {
|
| 104 |
-
await cache.delete(url);
|
| 105 |
-
throw new Error(`Incomplete download of ${f} (${got} of ${size} bytes)`);
|
| 106 |
-
}
|
| 107 |
-
done += got;
|
| 108 |
-
report(0);
|
| 109 |
}
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
}
|
| 112 |
|
| 113 |
/** Deletes one model's downloaded files. */
|
|
@@ -115,6 +112,7 @@ export async function removeModel(model) {
|
|
| 115 |
const cache = await caches.open(CACHE_MODEL);
|
| 116 |
const prefix = `https://huggingface.co/${model.repo}/`;
|
| 117 |
for (const req of await cache.keys()) if (req.url.startsWith(prefix)) await cache.delete(req);
|
|
|
|
| 118 |
}
|
| 119 |
|
| 120 |
export async function fetchRemoteManifest() {
|
|
|
|
| 4 |
import {
|
| 5 |
CX_BASE, CX_FILES, CACHE_CX, CACHE_DISK, CACHE_MODEL, DISK_BASE, modelFiles, hubUrl,
|
| 6 |
} from "./config.js";
|
| 7 |
+
import { fetchToCache, clearPartial } from "./fast-download.js";
|
| 8 |
|
| 9 |
const scopeUrl = (p) => new URL(p, document.baseURI).href;
|
| 10 |
const MANIFEST_KEY = () => scopeUrl("__vm__/manifest.json");
|
|
|
|
| 70 |
|
| 71 |
/**
|
| 72 |
* Downloads every file a local model needs into Cache Storage (the cache transformers.js
|
| 73 |
+
* reads). Weight files use parallel, resumable range requests (fast-download.js); the
|
| 74 |
+
* small config/tokenizer files are fetched all at once. Files already cached are skipped.
|
| 75 |
+
* onProgress(loaded, total) in bytes; signal aborts (finished pieces are kept for a resume).
|
| 76 |
*/
|
| 77 |
export async function downloadModel(model, { onProgress, signal } = {}) {
|
| 78 |
const cache = await caches.open(CACHE_MODEL);
|
| 79 |
const files = modelFiles(model);
|
| 80 |
+
const sizes = new Map();
|
| 81 |
+
let loaded = 0;
|
| 82 |
+
const report = () => {
|
| 83 |
+
let known = 0;
|
| 84 |
+
for (const v of sizes.values()) known += v;
|
| 85 |
+
onProgress?.(loaded, Math.max(model.bytes, known, loaded));
|
| 86 |
+
};
|
| 87 |
+
const todo = [];
|
| 88 |
for (const f of files) {
|
| 89 |
+
const hit = await cache.match(hubUrl(model, f));
|
| 90 |
+
if (hit) { const n = Number(hit.headers.get("Content-Length")) || 0; sizes.set(f, n); loaded += n; }
|
| 91 |
+
else todo.push(f);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
}
|
| 93 |
+
report();
|
| 94 |
+
const get = (f) => fetchToCache(cache, hubUrl(model, f), {
|
| 95 |
+
signal,
|
| 96 |
+
onSize: (n) => { sizes.set(f, n); report(); },
|
| 97 |
+
onBytes: (d) => { loaded += d; report(); },
|
| 98 |
+
});
|
| 99 |
+
const big = todo.filter((f) => f.startsWith("onnx/"));
|
| 100 |
+
const small = todo.filter((f) => !f.startsWith("onnx/"));
|
| 101 |
+
// Small files in parallel with the weights; weight files one after another, each
|
| 102 |
+
// using the full pool of connections.
|
| 103 |
+
await Promise.all([
|
| 104 |
+
Promise.all(small.map(get)),
|
| 105 |
+
(async () => { for (const f of big) await get(f); })(),
|
| 106 |
+
]);
|
| 107 |
+
report();
|
| 108 |
}
|
| 109 |
|
| 110 |
/** Deletes one model's downloaded files. */
|
|
|
|
| 112 |
const cache = await caches.open(CACHE_MODEL);
|
| 113 |
const prefix = `https://huggingface.co/${model.repo}/`;
|
| 114 |
for (const req of await cache.keys()) if (req.url.startsWith(prefix)) await cache.delete(req);
|
| 115 |
+
await clearPartial(prefix); // pieces of an unfinished download
|
| 116 |
}
|
| 117 |
|
| 118 |
export async function fetchRemoteManifest() {
|
sw.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
| 6 |
// (__vm__/disk.ext2), backed by the chunks the setup screen stored in Cache Storage.
|
| 7 |
// 4. Adds the cross-origin isolation headers (COOP/COEP) that SharedArrayBuffer,
|
| 8 |
// CheerpX and multi-threaded WASM need, even when a host forgets to send them.
|
| 9 |
-
const SHELL_VERSION = "lwa-shell-0.6.
|
| 10 |
const CX_ORIGIN = "https://cxrtnc.leaningtech.com";
|
| 11 |
const CX_CACHE_PREFIX = "lwa-cheerpx-";
|
| 12 |
const DISK_CACHE = "lwa-disk";
|
|
@@ -18,7 +18,7 @@ const chunkKey = (i) => SCOPE + "__vm__/chunk/" + i;
|
|
| 18 |
const SHELL_FILES = [
|
| 19 |
"./", "index.html", "css/app.css", "icon.svg",
|
| 20 |
"js/config.js", "js/config-defaults.js", "js/main.js", "js/setup.js", "js/vm.js", "js/agent.js", "js/llm.js",
|
| 21 |
-
"js/llm-worker.js", "js/llm-engine.js", "js/lazy-weights.js", "js/remote-llm.js", "js/model-manager.js", "js/prompts.js", "js/toolcalls.js", "js/markdown.js", "js/files.js",
|
| 22 |
"vendor/transformers.min.js", "vendor/highlight.min.js",
|
| 23 |
"vendor/ort/ort-wasm-simd-threaded.asyncify.mjs", "vendor/ort/ort-wasm-simd-threaded.asyncify.wasm",
|
| 24 |
"vendor/xterm/xterm.mjs", "vendor/xterm/xterm.css", "vendor/xterm/addon-fit.mjs",
|
|
|
|
| 6 |
// (__vm__/disk.ext2), backed by the chunks the setup screen stored in Cache Storage.
|
| 7 |
// 4. Adds the cross-origin isolation headers (COOP/COEP) that SharedArrayBuffer,
|
| 8 |
// CheerpX and multi-threaded WASM need, even when a host forgets to send them.
|
| 9 |
+
const SHELL_VERSION = "lwa-shell-0.6.2";
|
| 10 |
const CX_ORIGIN = "https://cxrtnc.leaningtech.com";
|
| 11 |
const CX_CACHE_PREFIX = "lwa-cheerpx-";
|
| 12 |
const DISK_CACHE = "lwa-disk";
|
|
|
|
| 18 |
const SHELL_FILES = [
|
| 19 |
"./", "index.html", "css/app.css", "icon.svg",
|
| 20 |
"js/config.js", "js/config-defaults.js", "js/main.js", "js/setup.js", "js/vm.js", "js/agent.js", "js/llm.js",
|
| 21 |
+
"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/prompts.js", "js/toolcalls.js", "js/markdown.js", "js/files.js",
|
| 22 |
"vendor/transformers.min.js", "vendor/highlight.min.js",
|
| 23 |
"vendor/ort/ort-wasm-simd-threaded.asyncify.mjs", "vendor/ort/ort-wasm-simd-threaded.asyncify.wasm",
|
| 24 |
"vendor/xterm/xterm.mjs", "vendor/xterm/xterm.css", "vendor/xterm/addon-fit.mjs",
|