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
+ setup: $("setup"),
9
+ setupTitle: $("setup-title"),
10
+ setupText: $("setup-text"),
11
+ download: $("download"),
12
+ progressWrap: $("progress-wrap"),
13
+ progress: $("progress"),
14
+ progressLabel: $("progress-label"),
15
+ chat: $("chat"),
16
+ transcript: $("transcript"),
17
+ composer: $("composer"),
18
+ input: $("input"),
19
+ send: $("send"),
20
+ stop: $("stop"),
21
+ stats: $("stats"),
22
+ reset: $("reset"),
23
+ clear: $("clear"),
24
+};
25
+
26
+const SYSTEM_PROMPT = "You are Ed, a concise and helpful assistant.";
27
+
28
+// A minimal module that uses a v128 instruction; validate() is false where
29
+// SIMD is missing.
30
+const SIMD_PROBE = new Uint8Array([
31
+ 0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8,
32
+ 0, 65, 0, 253, 15, 253, 98, 11,
33
+]);
34
+
35
+let worker = null;
36
+let modelLabel = "";
37
+let nextId = 0;
38
+let current = null; // { id, bubble }
39
+let ready = false;
40
+let resumeAfterReady = false; // set by Stop: reload the model without the setup card
41
+
42
+const mb = (bytes) => `${(bytes / 1e6).toFixed(0)} MB`;
43
+
44
+function show(section) {
45
+ for (const name of ["unsupported", "setup", "chat"]) {
46
+ els[name].hidden = name !== section;
47
+ }
48
+}
49
+
50
+function unsupported(reason) {
51
+ els.reason.textContent = reason;
52
+ show("unsupported");
53
+}
54
+
55
+function addBubble(role, text = "") {
56
+ const bubble = document.createElement("div");
57
+ bubble.className = `bubble ${role}`;
58
+ bubble.textContent = text;
59
+ els.transcript.append(bubble);
60
+ els.transcript.scrollTop = els.transcript.scrollHeight;
61
+ return bubble;
62
+}
63
+
64
+function setBusy(busy) {
65
+ els.send.hidden = busy;
66
+ els.stop.hidden = !busy;
67
+ els.input.disabled = busy;
68
+ els.reset.disabled = busy;
69
+ els.clear.disabled = busy;
70
+}
71
+
72
+function startWorker() {
73
+ ready = false;
74
+ worker = new Worker(new URL("./worker.js", import.meta.url), {
75
+ type: "module",
76
+ });
77
+ worker.onmessage = ({ data }) => onMessage(data);
78
+ worker.onerror = (e) => unsupported(`The worker failed to start: ${e.message}`);
79
+}
80
+
81
+function post(message) {
82
+ worker.postMessage(message);
83
+}
84
+
85
+function showSetup(cached) {
86
+ show("setup");
87
+ els.progressWrap.hidden = true;
88
+ els.download.disabled = false;
89
+ els.setupTitle.textContent = cached ? "Load the model" : "Download the model";
90
+ els.setupText.textContent = cached
91
+ ? `${modelLabel} is saved in this browser. Loading takes a few seconds.`
92
+ : `${modelLabel}. It downloads once, is saved in this browser, and runs entirely on this device.`;
93
+ els.download.textContent = cached ? "Load" : "Download";
94
+ els.download.dataset.cached = String(cached);
95
+}
96
+
97
+function onMessage(m) {
98
+ switch (m.type) {
99
+ case "ready":
100
+ ready = true;
101
+ modelLabel = m.model;
102
+ if (resumeAfterReady) {
103
+ resumeAfterReady = false;
104
+ post({ type: "load", system: SYSTEM_PROMPT });
105
+ } else {
106
+ showSetup(m.cached);
107
+ }
108
+ break;
109
+ case "progress": {
110
+ els.progressWrap.hidden = false;
111
+ if (m.total) {
112
+ const pct = Math.min(100, (m.received / m.total) * 100);
113
+ els.progress.value = pct;
114
+ els.progressLabel.textContent = `${mb(m.received)} of ${mb(m.total)} (${pct.toFixed(0)}%)`;
115
+ } else {
116
+ els.progress.removeAttribute("value");
117
+ els.progressLabel.textContent = `${mb(m.received)} downloaded`;
118
+ }
119
+ break;
120
+ }
121
+ case "downloaded":
122
+ els.progressLabel.textContent = "Download complete. Loading the model…";
123
+ post({ type: "load", system: SYSTEM_PROMPT });
124
+ break;
125
+ case "loaded":
126
+ show("chat");
127
+ setBusy(false);
128
+ els.stats.textContent = `Model loaded in ${m.seconds.toFixed(1)} s`;
129
+ els.input.focus();
130
+ break;
131
+ case "delta":
132
+ if (current && current.id === m.id) {
133
+ current.bubble.textContent += m.text;
134
+ els.transcript.scrollTop = els.transcript.scrollHeight;
135
+ }
136
+ break;
137
+ case "done":
138
+ if (current && current.id === m.id) {
139
+ current.bubble.classList.remove("pending");
140
+ current = null;
141
+ setBusy(false);
142
+ const rate = m.pieces / Math.max(m.seconds, 0.001);
143
+ els.stats.textContent = `${m.pieces} tokens in ${m.seconds.toFixed(1)} s, ${rate.toFixed(1)} tokens/s`;
144
+ els.input.focus();
145
+ }
146
+ break;
147
+ case "reset":
148
+ els.transcript.replaceChildren();
149
+ els.stats.textContent = "New conversation";
150
+ break;
151
+ case "cleared":
152
+ els.transcript.replaceChildren();
153
+ // The loaded model is still in memory; restart so it is released.
154
+ restart();
155
+ break;
156
+ case "error":
157
+ onError(m);
158
+ break;
159
+ }
160
+}
161
+
162
+function onError(m) {
163
+ if (current) {
164
+ current.bubble.classList.remove("pending");
165
+ current.bubble.classList.add("error");
166
+ current.bubble.textContent ||= `Error: ${m.message}`;
167
+ current = null;
168
+ setBusy(false);
169
+ } else if (m.stage === "boot") {
170
+ unsupported(`Ed could not start: ${m.message}`);
171
+ } else {
172
+ show("setup");
173
+ els.download.disabled = false;
174
+ els.setupTitle.textContent = "Something went wrong";
175
+ els.setupText.textContent = m.message;
176
+ }
177
+}
178
+
179
+function restart() {
180
+ worker.terminate();
181
+ current = null;
182
+ setBusy(false);
183
+ show("setup");
184
+ els.download.disabled = true;
185
+ startWorker();
186
+}
187
+
188
+els.download.addEventListener("click", () => {
189
+ els.download.disabled = true;
190
+ if (els.download.dataset.cached === "true") {
191
+ els.setupTitle.textContent = "Load the model";
192
+ els.setupText.textContent = "Loading the model…";
193
+ post({ type: "load", system: SYSTEM_PROMPT });
194
+ } else {
195
+ els.setupTitle.textContent = "Download the model";
196
+ els.setupText.textContent = `${modelLabel}. Keep this tab open until it finishes.`;
197
+ els.progress.value = 0;
198
+ els.progressLabel.textContent = "Starting…";
199
+ els.progressWrap.hidden = false;
200
+ post({ type: "download" });
201
+ }
202
+});
203
+
204
+els.composer.addEventListener("submit", (event) => {
205
+ event.preventDefault();
206
+ const text = els.input.value.trim();
207
+ if (!text || current || !ready) return;
208
+ els.input.value = "";
209
+ addBubble("user", text);
210
+ const bubble = addBubble("assistant");
211
+ bubble.classList.add("pending");
212
+ const id = nextId++;
213
+ current = { id, bubble };
214
+ setBusy(true);
215
+ els.stats.textContent = "Thinking…";
216
+ post({ type: "send", id, text });
217
+});
218
+
219
+els.input.addEventListener("keydown", (event) => {
220
+ if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
221
+ event.preventDefault();
222
+ els.composer.requestSubmit();
223
+ }
224
+});
225
+
226
+els.input.addEventListener("input", () => {
227
+ els.input.style.height = "auto";
228
+ els.input.style.height = `${els.input.scrollHeight}px`;
229
+});
230
+
231
+// Stop: a forward pass can't be interrupted from outside the worker, so end
232
+// the worker and start another. The model is cached, so reloading is quick,
233
+// but conversation history in the old worker is gone.
234
+els.stop.addEventListener("click", () => {
235
+ if (current) {
236
+ current.bubble.classList.remove("pending");
237
+ current.bubble.append(document.createTextNode(" [stopped]"));
238
+ }
239
+ worker.terminate();
240
+ current = null;
241
+ setBusy(false);
242
+ els.stats.textContent = "Stopped. Reloading the model…";
243
+ els.transcript.append(
244
+ Object.assign(document.createElement("div"), {
245
+ className: "bubble assistant",
246
+ textContent: "Conversation history was reset when generation stopped.",
247
+ }),
248
+ );
249
+ els.input.disabled = true;
250
+ resumeAfterReady = true;
251
+ startWorker();
252
+});
253
+
254
+els.reset.addEventListener("click", () => post({ type: "reset" }));
255
+els.clear.addEventListener("click", () => {
256
+ if (confirm("Remove the downloaded model from this browser?")) {
257
+ post({ type: "clear" });
258
+ }
259
+});
260
+
261
+if (!WebAssembly.validate(SIMD_PROBE)) {
262
+ unsupported("It needs WebAssembly SIMD, which this browser does not support. Try a current Chrome, Edge, Firefox or Safari.");
263
+} else if (!("caches" in self) || !window.isSecureContext) {
264
+ unsupported("It needs Cache Storage, which requires a secure context. Open this page over https or from localhost.");
265
+} else {
266
+ startWorker();
267
+}