@ondeinference / ed Mirror · read-only / commits / bfd820c
Fork 0

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

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

Synced Nov 23, 01:00 UTC

examples: add web-chat, Ed running in the browser

A small page that loads Qwen 2.5 0.5B and chats with it entirely on the device. A module worker owns one Ed instance compiled to wasm32-unknown-unknown, and the page talks to it through postMessage. The model downloads once into Cache Storage; a reload loads it without downloading again. Stop terminates the worker and starts a new one, so it also clears the conversation. There is no bundler or npm step: build.sh runs wasm-pack and any static server can host www/. The crate is excluded from the workspace and builds only for wasm32. It needs onde 1.5.0 for web_store, which is not published yet, so CI does not build it and its Cargo.lock is not committed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Co-Authored-By: siGit Code v1.7.10 <noreply@sigit.si> Co-Authored-By: OndeCode v1.1.2 <noreply@ondeinference.com>

Seto Elkahfi committed Nov 16, 2026 at 13:25 UTC bfd820cb984a0c5c8457616efd46608ab51d4d0a
12 files changed +767 -1
.github/workflows/ci.yml
+1
@@ -48,6 +48,7 @@ jobs:
48 filters: |
49 rust:
50 - "crates/**"
51 + - "examples/**"
52 - "uniffi-bindgen/**"
53 - "Cargo.toml"
54 - "Cargo.lock"
Cargo.toml
+2
@@ -13,6 +13,8 @@ members = [
13 "crates/ed-claude",
14 "uniffi-bindgen",
15 ]
16 +# Built only for wasm32 with its own lockfile: see examples/web-chat/README.md.
17 +exclude = ["examples/web-chat"]
18
19 # Shared across every crate in the workspace so a release moves one number.
20 # `sync-version` tooling (see the Makefile) reads these.
README.md
+2 -1
@@ -81,7 +81,8 @@ Each crate has its own README:
81 [`ed-claude`](crates/ed-claude/README.md),
82 [`ed-mcp`](crates/ed-mcp/README.md),
83 [`ed-onde-account`](crates/ed-onde-account/README.md),
84 -[`ed-acp-testkit`](crates/ed-acp-testkit/README.md).
84 +[`ed-acp-testkit`](crates/ed-acp-testkit/README.md),
85 +[`examples/web-chat`](examples/web-chat/README.md) (Ed in the browser).
86
87 ## Contributing
88
examples/web-chat/.gitignore new
+2
@@ -0,0 +1,2 @@
1 +/target
2 +/www/pkg
examples/web-chat/Cargo.toml new
+33
@@ -0,0 +1,33 @@
1 +[package]
2 +name = "web-chat"
3 +version = "0.1.0"
4 +edition = "2021"
5 +rust-version = "1.94"
6 +description = "Ed running a model entirely in the browser, in a Web Worker."
7 +license = "MIT OR Apache-2.0"
8 +publish = false
9 +
10 +[lib]
11 +crate-type = ["cdylib"]
12 +
13 +[dependencies]
14 +ed-agent = { path = "../../crates/ed-agent" }
15 +# Used only for web_store::download_model; ed-agent does not re-export it. The
16 +# browser engine needs an onde release that has it (1.5.0).
17 +onde = "1.4.0"
18 +wasm-bindgen = "0.2"
19 +wasm-bindgen-futures = "0.4"
20 +js-sys = "0.3"
21 +serde = { version = "1", features = ["derive"] }
22 +serde-wasm-bindgen = "0.6"
23 +console_error_panic_hook = "0.1"
24 +
25 +[profile.release]
26 +opt-level = 3
27 +lto = true
28 +codegen-units = 1
29 +
30 +[package.metadata.wasm-pack.profile.release]
31 +# wasm-opt is downloaded at build time and needs SIMD flags to match the
32 +# +simd128 build; skip it so the build has no network step beyond cargo.
33 +wasm-opt = false
examples/web-chat/README.md new
+44
@@ -0,0 +1,44 @@
1 +# web-chat
2 +
3 +Ed running a model entirely in the browser. The page talks to a Web Worker
4 +that owns one `Ed` instance compiled to `wasm32-unknown-unknown`. Nothing you
5 +type is sent to a server.
6 +
7 +## Build and run
8 +
9 +You need `wasm-pack` and the `wasm32-unknown-unknown` target.
10 +
11 +```bash
12 +./build.sh
13 +python3 -m http.server -d www 8080
14 +```
15 +
16 +Open <http://localhost:8080>. No bundler, npm or special headers are needed.
17 +Cache Storage needs a secure context, which `localhost` counts as.
18 +
19 +The browser engine lives in `onde` 1.5.0. Until it is released, build against
20 +a local checkout:
21 +
22 +```bash
23 +./build.sh --config 'patch.crates-io.onde.path="../../../onde"'
24 +```
25 +
26 +## What it downloads
27 +
28 +Qwen 2.5 0.5B (GGUF, about 380 MB), once, on the first click of Download. It
29 +is stored in the browser's Cache Storage for this origin, so a reload loads it
30 +from disk without downloading again. **Remove model** in the footer deletes it.
31 +
32 +## Speed
33 +
34 +Inference is CPU only, single threaded, using WebAssembly SIMD. Expect one to three
35 +tokens per second on a laptop (measured 1.2 to 2.5 on an Apple Silicon Mac). Stop ends the worker and starts a new one, so it
36 +also resets the conversation.
37 +
38 +## Layout
39 +
40 +- `src/lib.rs`: the wasm-bindgen API (`WebChat`) around `Ed`.
41 +- `www/worker.js`: owns the wasm module and the `WebChat`.
42 +- `www/main.js`, `index.html`, `style.css`: the UI.
43 +
44 +This crate is excluded from the root workspace and has its own lockfile.
examples/web-chat/build.sh new
+13
@@ -0,0 +1,13 @@
1 +#!/usr/bin/env bash
2 +# Build the wasm package into www/pkg. Serve www/ with any static server:
3 +# python3 -m http.server -d www 8080
4 +# Extra arguments go to `cargo`, e.g. a local onde while it is unreleased:
5 +# ./build.sh --config 'patch.crates-io.onde.path="../../../onde"'
6 +set -euo pipefail
7 +cd "$(dirname "$0")"
8 +
9 +# simd128 is what makes CPU inference usable in a browser. Every current
10 +# browser supports it, and main.js checks for it before loading anything.
11 +export RUSTFLAGS="${RUSTFLAGS:--C target-feature=+simd128}"
12 +
13 +wasm-pack build --target web --release --out-dir www/pkg --no-typescript -- "$@"
examples/web-chat/src/lib.rs new
+134
@@ -0,0 +1,134 @@
1 +//! Ed in the browser.
2 +//!
3 +//! [`WebChat`] wraps one [`Ed`] and is meant to live in a Web Worker: loading
4 +//! the model and every token's forward pass block the thread they run on. The
5 +//! page talks to it through `www/worker.js`.
6 +//!
7 +//! Each method returns a `Promise` and holds its own `Rc<Ed>`, because
8 +//! wasm-bindgen would otherwise borrow `&self` across the whole await and a
9 +//! second call (a `reset` while a reply streams) would panic.
10 +
11 +use std::rc::Rc;
12 +
13 +use ed_agent::{Ed, GgufModelConfig};
14 +use js_sys::{Function, Promise};
15 +use wasm_bindgen::prelude::*;
16 +use wasm_bindgen_futures::future_to_promise;
17 +
18 +/// The model this example runs: the catalogue's smallest (about 380 MB). The
19 +/// preset comes from onde, so no model name is written here.
20 +fn model() -> GgufModelConfig {
21 + GgufModelConfig::qwen25_0_5b()
22 +}
23 +
24 +fn to_js_error(e: impl std::fmt::Display) -> JsValue {
25 + JsValue::from_str(&e.to_string())
26 +}
27 +
28 +fn number(n: u64) -> JsValue {
29 + JsValue::from_f64(n as f64)
30 +}
31 +
32 +#[wasm_bindgen]
33 +pub struct WebChat {
34 + ed: Rc<Ed>,
35 +}
36 +
37 +impl Default for WebChat {
38 + fn default() -> Self {
39 + Self::new()
40 + }
41 +}
42 +
43 +#[wasm_bindgen]
44 +impl WebChat {
45 + #[wasm_bindgen(constructor)]
46 + pub fn new() -> WebChat {
47 + console_error_panic_hook::set_once();
48 + WebChat {
49 + ed: Rc::new(Ed::new()),
50 + }
51 + }
52 +
53 + /// Display name and size of the model, for the first-run card.
54 + pub fn model_label(&self) -> String {
55 + let config = model();
56 + format!("{}, {}", config.display_name, config.approx_memory)
57 + }
58 +
59 + /// Resolves to whether the model is already in the browser cache.
60 + pub fn is_cached(&self) -> Promise {
61 + future_to_promise(async move {
62 + Ok(JsValue::from_bool(
63 + onde::web_store::is_cached(&model()).await,
64 + ))
65 + })
66 + }
67 +
68 + /// Download the model into the browser cache. `on_progress(received, total)`
69 + /// gets byte counts; `total` is `null` when the server hides the length.
70 + pub fn download(&self, on_progress: Function) -> Promise {
71 + future_to_promise(async move {
72 + onde::web_store::download_model(&model(), |received, total| {
73 + let total = total.map_or(JsValue::NULL, number);
74 + let _ = on_progress.call2(&JsValue::NULL, &number(received), &total);
75 + })
76 + .await
77 + .map_err(to_js_error)?;
78 + Ok(JsValue::UNDEFINED)
79 + })
80 + }
81 +
82 + /// Remove the downloaded model from the browser cache.
83 + pub fn delete_cached(&self) -> Promise {
84 + future_to_promise(async move {
85 + let removed = onde::web_store::delete_model(&model())
86 + .await
87 + .map_err(to_js_error)?;
88 + Ok(JsValue::from_bool(removed))
89 + })
90 + }
91 +
92 + /// Load the model into memory (downloading it first if it isn't cached).
93 + /// Resolves to the load time in seconds.
94 + pub fn load(&self, system_prompt: Option<String>) -> Promise {
95 + let ed = self.ed.clone();
96 + future_to_promise(async move {
97 + let took = ed
98 + .load(model(), system_prompt, None)
99 + .await
100 + .map_err(to_js_error)?;
101 + Ok(JsValue::from_f64(took.as_secs_f64()))
102 + })
103 + }
104 +
105 + /// Send one message. `on_delta(text)` is called for each piece as it is
106 + /// generated; the promise resolves with the whole reply.
107 + pub fn send(&self, message: String, on_delta: Function) -> Promise {
108 + let ed = self.ed.clone();
109 + future_to_promise(async move {
110 + let mut stream = ed.stream(message).await.map_err(to_js_error)?;
111 + let mut reply = String::new();
112 + while let Some(piece) = stream.next().await {
113 + let piece = piece.map_err(to_js_error)?;
114 + reply.push_str(&piece);
115 + let _ = on_delta.call1(&JsValue::NULL, &JsValue::from_str(&piece));
116 + }
117 + Ok(JsValue::from_str(&reply))
118 + })
119 + }
120 +
121 + /// Forget the conversation. Resolves to how many messages were dropped.
122 + pub fn reset(&self) -> Promise {
123 + let ed = self.ed.clone();
124 + future_to_promise(async move { Ok(number(ed.clear_history().await as u64)) })
125 + }
126 +
127 + /// Engine status, model name and history length.
128 + pub fn info(&self) -> Promise {
129 + let ed = self.ed.clone();
130 + future_to_promise(async move {
131 + serde_wasm_bindgen::to_value(&ed.info().await).map_err(to_js_error)
132 + })
133 + }
134 +}
examples/web-chat/www/index.html new
+61
@@ -0,0 +1,61 @@
1 +<!doctype html>
2 +<html lang="en">
3 + <head>
4 + <meta charset="utf-8" />
5 + <meta name="viewport" content="width=device-width, initial-scale=1" />
6 + <meta name="color-scheme" content="light dark" />
7 + <title>Ed, in your browser</title>
8 + <link rel="stylesheet" href="style.css" />
9 + </head>
10 + <body>
11 + <main>
12 + <header>
13 + <h1>Ed</h1>
14 + <p class="tagline">A language model running on this device. Nothing you type leaves it.</p>
15 + </header>
16 +
17 + <section id="unsupported" class="card" hidden>
18 + <h2>This browser can't run Ed</h2>
19 + <p id="unsupported-reason"></p>
20 + </section>
21 +
22 + <section id="setup" class="card" hidden>
23 + <h2 id="setup-title">Download the model</h2>
24 + <p id="setup-text"></p>
25 + <button id="download" type="button" disabled>Download</button>
26 + <div id="progress-wrap" hidden>
27 + <progress id="progress" max="100" value="0" aria-labelledby="progress-label"></progress>
28 + <p id="progress-label" role="status" aria-live="polite"></p>
29 + </div>
30 + </section>
31 +
32 + <section id="chat" hidden>
33 + <div
34 + id="transcript"
35 + role="log"
36 + aria-live="polite"
37 + aria-label="Conversation"
38 + tabindex="0"
39 + ></div>
40 + <form id="composer" autocomplete="off">
41 + <label for="input" class="visually-hidden">Message</label>
42 + <textarea
43 + id="input"
44 + rows="1"
45 + placeholder="Message Ed"
46 +
47 + ></textarea>
48 + <button id="send" type="submit">Send</button>
49 + <button id="stop" type="button" hidden>Stop</button>
50 + </form>
51 + <footer>
52 + <span id="stats" role="status" aria-live="off"></span>
53 + <span class="spacer"></span>
54 + <button id="reset" type="button" class="link">New conversation</button>
55 + <button id="clear" type="button" class="link">Remove model</button>
56 + </footer>
57 + </section>
58 + </main>
59 + <script type="module" src="main.js"></script>
60 + </body>
61 +</html>
examples/web-chat/www/main.js new
+267
@@ -0,0 +1,267 @@
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 +}
examples/web-chat/www/style.css new
+134
@@ -0,0 +1,134 @@
1 +:root {
2 + color-scheme: light dark;
3 + --bg: #f6f4ef;
4 + --surface: #ffffff;
5 + --ink: #1d1d1b;
6 + --muted: #6b6a64;
7 + --line: #e2dfd6;
8 + --accent: #2f5d50;
9 + --accent-ink: #ffffff;
10 + --user: #e9efe9;
11 + --radius: 14px;
12 + font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
13 +}
14 +
15 +@media (prefers-color-scheme: dark) {
16 + :root {
17 + --bg: #161615;
18 + --surface: #1f1f1d;
19 + --ink: #ecebe6;
20 + --muted: #9a998f;
21 + --line: #2f2f2b;
22 + --accent: #7fb3a2;
23 + --accent-ink: #10201b;
24 + --user: #25302b;
25 + }
26 +}
27 +
28 +* { box-sizing: border-box; }
29 +
30 +body {
31 + margin: 0;
32 + min-height: 100dvh;
33 + background: var(--bg);
34 + color: var(--ink);
35 + line-height: 1.5;
36 +}
37 +
38 +main {
39 + max-width: 42rem;
40 + margin: 0 auto;
41 + padding: 2.5rem 1.25rem 1.5rem;
42 + min-height: 100dvh;
43 + display: flex;
44 + flex-direction: column;
45 + gap: 1.5rem;
46 +}
47 +
48 +h1 { margin: 0; font-size: 1.75rem; font-weight: 600; letter-spacing: -0.02em; }
49 +h2 { margin: 0 0 0.5rem; font-size: 1.05rem; font-weight: 600; }
50 +.tagline { margin: 0.25rem 0 0; color: var(--muted); }
51 +
52 +.card {
53 + background: var(--surface);
54 + border: 1px solid var(--line);
55 + border-radius: var(--radius);
56 + padding: 1.25rem;
57 +}
58 +.card p { margin: 0 0 1rem; color: var(--muted); }
59 +
60 +button {
61 + font: inherit;
62 + border: 0;
63 + border-radius: 999px;
64 + padding: 0.55rem 1.1rem;
65 + background: var(--accent);
66 + color: var(--accent-ink);
67 + cursor: pointer;
68 +}
69 +button:disabled { opacity: 0.5; cursor: default; }
70 +button:focus-visible, textarea:focus-visible, #transcript:focus-visible {
71 + outline: 2px solid var(--accent);
72 + outline-offset: 2px;
73 +}
74 +button.link {
75 + background: none;
76 + color: var(--muted);
77 + padding: 0.25rem 0.4rem;
78 + text-decoration: underline;
79 + text-underline-offset: 3px;
80 +}
81 +#stop { background: transparent; color: var(--ink); border: 1px solid var(--line); }
82 +
83 +progress { width: 100%; height: 0.5rem; accent-color: var(--accent); }
84 +#progress-label { margin: 0.5rem 0 0; font-size: 0.875rem; font-variant-numeric: tabular-nums; }
85 +
86 +#chat { flex: 1; display: flex; flex-direction: column; gap: 0.75rem; min-height: 0; }
87 +#transcript {
88 + flex: 1;
89 + overflow-y: auto;
90 + display: flex;
91 + flex-direction: column;
92 + gap: 0.75rem;
93 + padding: 0.25rem 0;
94 +}
95 +.bubble {
96 + max-width: 85%;
97 + padding: 0.65rem 0.95rem;
98 + border-radius: var(--radius);
99 + white-space: pre-wrap;
100 + overflow-wrap: anywhere;
101 +}
102 +.bubble.user { align-self: flex-end; background: var(--user); }
103 +.bubble.assistant { align-self: flex-start; background: var(--surface); border: 1px solid var(--line); }
104 +.bubble.error { color: #b3261e; }
105 +.bubble.pending::after { content: "▍"; margin-left: 1px; opacity: 0.6; }
106 +
107 +#composer { display: flex; gap: 0.5rem; align-items: flex-end; }
108 +textarea {
109 + flex: 1;
110 + font: inherit;
111 + color: inherit;
112 + resize: none;
113 + max-height: 10rem;
114 + padding: 0.65rem 0.9rem;
115 + border-radius: var(--radius);
116 + border: 1px solid var(--line);
117 + background: var(--surface);
118 +}
119 +
120 +footer { display: flex; align-items: center; gap: 0.5rem; color: var(--muted); font-size: 0.8125rem; }
121 +.spacer { flex: 1; }
122 +#stats { font-variant-numeric: tabular-nums; }
123 +
124 +.visually-hidden {
125 + position: absolute; width: 1px; height: 1px; overflow: hidden;
126 + clip: rect(0 0 0 0); white-space: nowrap;
127 +}
128 +
129 +@media (prefers-reduced-motion: no-preference) {
130 + .bubble.pending::after { animation: blink 1s steps(2, start) infinite; }
131 + @keyframes blink { to { visibility: hidden; } }
132 +}
133 +
134 +[hidden] { display: none !important; }
examples/web-chat/www/worker.js new
+74
@@ -0,0 +1,74 @@
1 +// Module worker: owns the wasm module and the one WebChat (Ed) instance.
2 +// The page never touches inference, so a forward pass can't freeze the UI.
3 +// Cancel works by terminating this worker and starting a new one; the model
4 +// stays in Cache Storage, so the restart only re-reads it.
5 +
6 +import init, { WebChat } from "./pkg/web_chat.js";
7 +
8 +let chat = null;
9 +
10 +const reply = (message) => self.postMessage(message);
11 +const fail = (stage, error, id) =>
12 + reply({ type: "error", stage, id, message: String(error?.message ?? error) });
13 +
14 +async function boot() {
15 + await init();
16 + chat = new WebChat();
17 + reply({
18 + type: "ready",
19 + model: chat.model_label(),
20 + cached: await chat.is_cached(),
21 + });
22 +}
23 +
24 +const handlers = {
25 + async download() {
26 + await chat.download((received, total) =>
27 + reply({ type: "progress", received, total }),
28 + );
29 + reply({ type: "downloaded" });
30 + },
31 +
32 + async load({ system }) {
33 + const seconds = await chat.load(system ?? undefined);
34 + reply({ type: "loaded", seconds });
35 + },
36 +
37 + async send({ id, text }) {
38 + const started = performance.now();
39 + let pieces = 0;
40 + const full = await chat.send(text, (delta) => {
41 + pieces += 1;
42 + reply({ type: "delta", id, text: delta });
43 + });
44 + reply({
45 + type: "done",
46 + id,
47 + text: full,
48 + pieces,
49 + seconds: (performance.now() - started) / 1000,
50 + });
51 + },
52 +
53 + async reset() {
54 + await chat.reset();
55 + reply({ type: "reset" });
56 + },
57 +
58 + async clear() {
59 + const removed = await chat.delete_cached();
60 + reply({ type: "cleared", removed });
61 + },
62 +};
63 +
64 +self.onmessage = async ({ data }) => {
65 + const handler = handlers[data.type];
66 + if (!handler || !chat) return;
67 + try {
68 + await handler(data);
69 + } catch (error) {
70 + fail(data.type, error, data.id);
71 + }
72 +};
73 +
74 +boot().catch((error) => fail("boot", error));