Read-only mirror of github.com/ondeinference/ed.
Mirrored from https://github.com/ondeinference/ed.git
Synced Nov 23, 01:00 UTC
| 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 | const note = `Error: ${m.message}`; |
| 167 | current.bubble.textContent = current.bubble.textContent |
| 168 | ? `${current.bubble.textContent}\n\n[${note}]` |
| 169 | : note; |
| 170 | current = null; |
| 171 | setBusy(false); |
| 172 | } else if (m.stage === "boot") { |
| 173 | unsupported(`Ed could not start: ${m.message}`); |
| 174 | } else { |
| 175 | show("setup"); |
| 176 | els.download.disabled = false; |
| 177 | els.setupTitle.textContent = "Something went wrong"; |
| 178 | els.setupText.textContent = m.message; |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | function restart() { |
| 183 | worker.terminate(); |
| 184 | current = null; |
| 185 | setBusy(false); |
| 186 | show("setup"); |
| 187 | els.download.disabled = true; |
| 188 | startWorker(); |
| 189 | } |
| 190 | |
| 191 | els.download.addEventListener("click", () => { |
| 192 | els.download.disabled = true; |
| 193 | if (els.download.dataset.cached === "true") { |
| 194 | els.setupTitle.textContent = "Load the model"; |
| 195 | els.setupText.textContent = "Loading the model…"; |
| 196 | post({ type: "load", system: SYSTEM_PROMPT }); |
| 197 | } else { |
| 198 | els.setupTitle.textContent = "Download the model"; |
| 199 | els.setupText.textContent = `${modelLabel}. Keep this tab open until it finishes.`; |
| 200 | els.progress.value = 0; |
| 201 | els.progressLabel.textContent = "Starting…"; |
| 202 | els.progressWrap.hidden = false; |
| 203 | post({ type: "download" }); |
| 204 | } |
| 205 | }); |
| 206 | |
| 207 | els.composer.addEventListener("submit", (event) => { |
| 208 | event.preventDefault(); |
| 209 | const text = els.input.value.trim(); |
| 210 | if (!text || current || !ready) return; |
| 211 | els.input.value = ""; |
| 212 | addBubble("user", text); |
| 213 | const bubble = addBubble("assistant"); |
| 214 | bubble.classList.add("pending"); |
| 215 | const id = nextId++; |
| 216 | current = { id, bubble }; |
| 217 | setBusy(true); |
| 218 | els.stats.textContent = "Thinking…"; |
| 219 | post({ type: "send", id, text }); |
| 220 | }); |
| 221 | |
| 222 | els.input.addEventListener("keydown", (event) => { |
| 223 | if (event.key === "Enter" && !event.shiftKey && !event.isComposing) { |
| 224 | event.preventDefault(); |
| 225 | els.composer.requestSubmit(); |
| 226 | } |
| 227 | }); |
| 228 | |
| 229 | els.input.addEventListener("input", () => { |
| 230 | els.input.style.height = "auto"; |
| 231 | els.input.style.height = `${els.input.scrollHeight}px`; |
| 232 | }); |
| 233 | |
| 234 | // Stop: a forward pass can't be interrupted from outside the worker, so end |
| 235 | // the worker and start another. The model is cached, so reloading is quick, |
| 236 | // but conversation history in the old worker is gone. |
| 237 | els.stop.addEventListener("click", () => { |
| 238 | if (current) { |
| 239 | current.bubble.classList.remove("pending"); |
| 240 | current.bubble.append(document.createTextNode(" [stopped]")); |
| 241 | } |
| 242 | worker.terminate(); |
| 243 | current = null; |
| 244 | setBusy(false); |
| 245 | els.stats.textContent = "Stopped. Reloading the model…"; |
| 246 | els.transcript.append( |
| 247 | Object.assign(document.createElement("div"), { |
| 248 | className: "bubble assistant", |
| 249 | textContent: "Conversation history was reset when generation stopped.", |
| 250 | }), |
| 251 | ); |
| 252 | els.input.disabled = true; |
| 253 | resumeAfterReady = true; |
| 254 | startWorker(); |
| 255 | }); |
| 256 | |
| 257 | els.reset.addEventListener("click", () => post({ type: "reset" })); |
| 258 | els.clear.addEventListener("click", () => { |
| 259 | if (confirm("Remove the downloaded model from this browser?")) { |
| 260 | post({ type: "clear" }); |
| 261 | } |
| 262 | }); |
| 263 | |
| 264 | if (!WebAssembly.validate(SIMD_PROBE)) { |
| 265 | unsupported("It needs WebAssembly SIMD, which this browser does not support. Try a current Chrome, Edge, Firefox or Safari."); |
| 266 | } else if (!("caches" in self) || !window.isSecureContext) { |
| 267 | unsupported("It needs Cache Storage, which requires a secure context. Open this page over https or from localhost."); |
| 268 | } else { |
| 269 | startWorker(); |
| 270 | } |