@ondeinference / ed Mirror · read-only
Fork 0

Read-only mirror of github.com/ondeinference/ed.

Mirrored from https://github.com/ondeinference/ed.git

Synced Nov 23, 01:00 UTC

development
js 346 lines 11 KB
Raw
1 // UI thread: DOM and worker messaging only. All inference runs in worker.js.
2 // Messages are inserted with textContent, never as HTML.
3
4 const $ = (id) => document.getElementById(id);
5 const els = {
6 unsupported: $("unsupported"),
7 reason: $("unsupported-reason"),
8 mobile: $("mobile"),
9 mobileTitle: $("mobile-title"),
10 mobileReason: $("mobile-reason"),
11 copyLink: $("copy-link"),
12 tryAnyway: $("try-anyway"),
13 badgeAppStore: $("badge-app-store"),
14 badgeGooglePlay: $("badge-google-play"),
15 setup: $("setup"),
16 setupTitle: $("setup-title"),
17 setupText: $("setup-text"),
18 download: $("download"),
19 progressWrap: $("progress-wrap"),
20 progress: $("progress"),
21 progressLabel: $("progress-label"),
22 chat: $("chat"),
23 transcript: $("transcript"),
24 composer: $("composer"),
25 input: $("input"),
26 send: $("send"),
27 stop: $("stop"),
28 stats: $("stats"),
29 reset: $("reset"),
30 clear: $("clear"),
31 };
32
33 const SYSTEM_PROMPT = "You are Ed, a concise and helpful assistant.";
34
35 // A minimal module that uses a v128 instruction; validate() is false where
36 // SIMD is missing.
37 const SIMD_PROBE = new Uint8Array([
38 0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8,
39 0, 65, 0, 253, 15, 253, 98, 11,
40 ]);
41
42 let worker = null;
43 let modelLabel = "";
44 let nextId = 0;
45 let current = null; // { id, bubble }
46 let ready = false;
47 let resumeAfterReady = false; // set by Stop: reload the model without the setup card
48
49 const mb = (bytes) => `${(bytes / 1e6).toFixed(0)} MB`;
50
51 // Set while the model loads into memory (not while it downloads, which streams
52 // to disk), cleared once it is ready or fails. Still set on a visit soon after
53 // means the tab was killed mid-load, almost always for running out of memory.
54 // localStorage can throw (private modes, disabled storage), and this is only a
55 // hint, so failures are ignored.
56 const LOADING_KEY = "web-chat:loading";
57 const CRASH_WINDOW_MS = 10 * 60 * 1000;
58 const storage = {
59 get: () => { try { return localStorage.getItem(LOADING_KEY); } catch { return null; } },
60 set: () => { try { localStorage.setItem(LOADING_KEY, String(Date.now())); } catch {} },
61 clear: () => { try { localStorage.removeItem(LOADING_KEY); } catch {} },
62 };
63
64 function postLoad(message) {
65 storage.set();
66 post(message);
67 }
68
69 const ua = navigator.userAgent;
70 // iPadOS Safari reports a Mac user agent; touch support gives it away.
71 const isApple = /iPhone|iPod|iPad/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1);
72 const isAndroid = /Android/.test(ua);
73
74 // Phones and tablets kill the tab before the model is loaded: loading peaks
75 // at about three times the 380 MB file. deviceMemory is Chromium only.
76 function constrainedDevice() {
77 if (navigator.userAgentData?.mobile) return true;
78 if (isApple || isAndroid || /Mobile/.test(ua)) return true;
79 return typeof navigator.deviceMemory === "number" && navigator.deviceMemory < 4;
80 }
81
82 function showMobileWarning(crashed) {
83 els.mobileTitle.textContent = crashed
84 ? "The model didn't fit last time"
85 : "Ed needs a desktop browser for now";
86 els.mobileReason.textContent = crashed
87 ? "The last attempt to load the model closed this tab, most likely because it ran out of memory. Loading takes over 1 GB, more than many browsers give a tab."
88 : "Loading the model takes over 1 GB of memory, more than phone and tablet browsers give a tab.";
89 // Offer the store for this device; elsewhere, both.
90 els.badgeAppStore.hidden = isAndroid;
91 els.badgeGooglePlay.hidden = isApple;
92 show("mobile");
93 }
94
95 function show(section) {
96 for (const name of ["unsupported", "mobile", "setup", "chat"]) {
97 els[name].hidden = name !== section;
98 }
99 }
100
101 function unsupported(reason) {
102 els.reason.textContent = reason;
103 show("unsupported");
104 }
105
106 function addBubble(role, text = "") {
107 const bubble = document.createElement("div");
108 bubble.className = `bubble ${role}`;
109 bubble.textContent = text;
110 els.transcript.append(bubble);
111 els.transcript.scrollTop = els.transcript.scrollHeight;
112 return bubble;
113 }
114
115 function setBusy(busy) {
116 els.send.hidden = busy;
117 els.stop.hidden = !busy;
118 els.input.disabled = busy;
119 els.reset.disabled = busy;
120 els.clear.disabled = busy;
121 }
122
123 function startWorker() {
124 ready = false;
125 worker = new Worker(new URL("./worker.js", import.meta.url), {
126 type: "module",
127 });
128 worker.onmessage = ({ data }) => onMessage(data);
129 worker.onerror = (e) => unsupported(`The worker failed to start: ${e.message}`);
130 }
131
132 function post(message) {
133 worker.postMessage(message);
134 }
135
136 function showSetup(cached) {
137 show("setup");
138 els.progressWrap.hidden = true;
139 els.download.disabled = false;
140 els.setupTitle.textContent = cached ? "Load the model" : "Download the model";
141 els.setupText.textContent = cached
142 ? `${modelLabel} is saved in this browser. Loading takes a few seconds.`
143 : `${modelLabel}. It downloads once, is saved in this browser, and runs entirely on this device.`;
144 els.download.textContent = cached ? "Load" : "Download";
145 els.download.dataset.cached = String(cached);
146 }
147
148 function onMessage(m) {
149 switch (m.type) {
150 case "ready":
151 ready = true;
152 modelLabel = m.model;
153 if (resumeAfterReady) {
154 resumeAfterReady = false;
155 postLoad({ type: "load", system: SYSTEM_PROMPT });
156 } else {
157 showSetup(m.cached);
158 }
159 break;
160 case "progress": {
161 els.progressWrap.hidden = false;
162 if (m.total) {
163 const pct = Math.min(100, (m.received / m.total) * 100);
164 els.progress.value = pct;
165 els.progressLabel.textContent = `${mb(m.received)} of ${mb(m.total)} (${pct.toFixed(0)}%)`;
166 } else {
167 els.progress.removeAttribute("value");
168 els.progressLabel.textContent = `${mb(m.received)} downloaded`;
169 }
170 break;
171 }
172 case "downloaded":
173 els.progressLabel.textContent = "Download complete. Loading the model…";
174 postLoad({ type: "load", system: SYSTEM_PROMPT });
175 break;
176 case "loaded":
177 storage.clear();
178 show("chat");
179 setBusy(false);
180 els.stats.textContent = `Model loaded in ${m.seconds.toFixed(1)} s`;
181 els.input.focus();
182 break;
183 case "delta":
184 if (current && current.id === m.id) {
185 current.bubble.textContent += m.text;
186 els.transcript.scrollTop = els.transcript.scrollHeight;
187 }
188 break;
189 case "done":
190 if (current && current.id === m.id) {
191 current.bubble.classList.remove("pending");
192 current = null;
193 setBusy(false);
194 const rate = m.pieces / Math.max(m.seconds, 0.001);
195 els.stats.textContent = `${m.pieces} tokens in ${m.seconds.toFixed(1)} s, ${rate.toFixed(1)} tokens/s`;
196 els.input.focus();
197 }
198 break;
199 case "reset":
200 els.transcript.replaceChildren();
201 els.stats.textContent = "New conversation";
202 break;
203 case "cleared":
204 els.transcript.replaceChildren();
205 // The loaded model is still in memory; restart so it is released.
206 restart();
207 break;
208 case "error":
209 onError(m);
210 break;
211 }
212 }
213
214 function onError(m) {
215 storage.clear();
216 if (current) {
217 current.bubble.classList.remove("pending");
218 current.bubble.classList.add("error");
219 const note = `Error: ${m.message}`;
220 current.bubble.textContent = current.bubble.textContent
221 ? `${current.bubble.textContent}\n\n[${note}]`
222 : note;
223 current = null;
224 setBusy(false);
225 } else if (m.stage === "boot") {
226 unsupported(`Ed could not start: ${m.message}`);
227 } else {
228 show("setup");
229 els.download.disabled = false;
230 els.setupTitle.textContent = "Something went wrong";
231 els.setupText.textContent = m.message;
232 }
233 }
234
235 function restart() {
236 worker.terminate();
237 current = null;
238 setBusy(false);
239 show("setup");
240 els.download.disabled = true;
241 startWorker();
242 }
243
244 els.download.addEventListener("click", () => {
245 els.download.disabled = true;
246 if (els.download.dataset.cached === "true") {
247 els.setupTitle.textContent = "Load the model";
248 els.setupText.textContent = "Loading the model…";
249 postLoad({ type: "load", system: SYSTEM_PROMPT });
250 } else {
251 els.setupTitle.textContent = "Download the model";
252 els.setupText.textContent = `${modelLabel}. Keep this tab open until it finishes.`;
253 els.progress.value = 0;
254 els.progressLabel.textContent = "Starting…";
255 els.progressWrap.hidden = false;
256 post({ type: "download" });
257 }
258 });
259
260 els.composer.addEventListener("submit", (event) => {
261 event.preventDefault();
262 const text = els.input.value.trim();
263 if (!text || current || !ready) return;
264 els.input.value = "";
265 addBubble("user", text);
266 const bubble = addBubble("assistant");
267 bubble.classList.add("pending");
268 const id = nextId++;
269 current = { id, bubble };
270 setBusy(true);
271 els.stats.textContent = "Thinking…";
272 post({ type: "send", id, text });
273 });
274
275 els.input.addEventListener("keydown", (event) => {
276 if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
277 event.preventDefault();
278 els.composer.requestSubmit();
279 }
280 });
281
282 els.input.addEventListener("input", () => {
283 els.input.style.height = "auto";
284 els.input.style.height = `${els.input.scrollHeight}px`;
285 });
286
287 // Stop: a forward pass can't be interrupted from outside the worker, so end
288 // the worker and start another. The model is cached, so reloading is quick,
289 // but conversation history in the old worker is gone.
290 els.stop.addEventListener("click", () => {
291 if (current) {
292 current.bubble.classList.remove("pending");
293 current.bubble.append(document.createTextNode(" [stopped]"));
294 }
295 worker.terminate();
296 current = null;
297 setBusy(false);
298 els.stats.textContent = "Stopped. Reloading the model…";
299 els.transcript.append(
300 Object.assign(document.createElement("div"), {
301 className: "bubble assistant",
302 textContent: "Conversation history was reset when generation stopped.",
303 }),
304 );
305 els.input.disabled = true;
306 resumeAfterReady = true;
307 startWorker();
308 });
309
310 els.reset.addEventListener("click", () => post({ type: "reset" }));
311
312 els.copyLink.addEventListener("click", async () => {
313 try {
314 await navigator.clipboard.writeText(location.href);
315 els.copyLink.textContent = "Copied";
316 } catch {
317 els.copyLink.textContent = location.href;
318 }
319 });
320
321 // The worker is started only now, so a phone that stays on the warning never
322 // fetches the 5.6 MB wasm.
323 els.tryAnyway.addEventListener("click", () => {
324 show("setup");
325 startWorker();
326 });
327 els.clear.addEventListener("click", () => {
328 if (confirm("Remove the downloaded model from this browser?")) {
329 post({ type: "clear" });
330 }
331 });
332
333 if (!WebAssembly.validate(SIMD_PROBE)) {
334 unsupported("It needs WebAssembly SIMD, which this browser does not support. Try a current Chrome, Edge, Firefox or Safari.");
335 } else if (!("caches" in self) || !window.isSecureContext) {
336 unsupported("It needs Cache Storage, which requires a secure context. Open this page over https or from localhost.");
337 } else {
338 const since = Date.now() - Number(storage.get());
339 const crashed = storage.get() !== null && since >= 0 && since < CRASH_WINDOW_MS;
340 storage.clear();
341 if (crashed || constrainedDevice()) {
342 showMobileWarning(crashed);
343 } else {
344 startWorker();
345 }
346 }