diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1ff419b..4deff5a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,6 +48,7 @@ jobs: filters: | rust: - "crates/**" + - "examples/**" - "uniffi-bindgen/**" - "Cargo.toml" - "Cargo.lock" diff --git a/Cargo.toml b/Cargo.toml index 737d364..df66d2e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,8 @@ members = [ "crates/ed-claude", "uniffi-bindgen", ] +# Built only for wasm32 with its own lockfile: see examples/web-chat/README.md. +exclude = ["examples/web-chat"] # Shared across every crate in the workspace so a release moves one number. # `sync-version` tooling (see the Makefile) reads these. diff --git a/README.md b/README.md index 9069b6f..3e33bf5 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,8 @@ Each crate has its own README: [`ed-claude`](crates/ed-claude/README.md), [`ed-mcp`](crates/ed-mcp/README.md), [`ed-onde-account`](crates/ed-onde-account/README.md), -[`ed-acp-testkit`](crates/ed-acp-testkit/README.md). +[`ed-acp-testkit`](crates/ed-acp-testkit/README.md), +[`examples/web-chat`](examples/web-chat/README.md) (Ed in the browser). ## Contributing diff --git a/examples/web-chat/.gitignore b/examples/web-chat/.gitignore new file mode 100644 index 0000000..f748f26 --- /dev/null +++ b/examples/web-chat/.gitignore @@ -0,0 +1,2 @@ +/target +/www/pkg diff --git a/examples/web-chat/.smb/config.toml b/examples/web-chat/.smb/config.toml new file mode 100644 index 0000000..852ccba --- /dev/null +++ b/examples/web-chat/.smb/config.toml @@ -0,0 +1,15 @@ +name = "ondewebdemo" +description = "Ed running in the browser, published at ondewebdemo.5mb.app." + +[project] +id = 50 +# The App the artifact deploy publishes to. The server allocates the target dir. +frontend_app_id = "c0277812-c891-4f4b-a3ee-c8cb371bb629" +name = "ondewebdemo" +# static: nginx serves the directory off disk. No build, no process, no port. +runner = 1 +# `smb deploy --prebuilt` publishes an artifact over HTTPS (see deploy.sh). +deployment_method = 1 +repository = "ondewebdemo" +description = "Ed running in the browser." +source = "." diff --git a/examples/web-chat/Cargo.toml b/examples/web-chat/Cargo.toml new file mode 100644 index 0000000..6099b7b --- /dev/null +++ b/examples/web-chat/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "web-chat" +version = "0.1.0" +edition = "2021" +rust-version = "1.94" +description = "Ed running a model entirely in the browser, in a Web Worker." +license = "MIT OR Apache-2.0" +publish = false + +[lib] +crate-type = ["cdylib"] + +[dependencies] +ed-agent = { path = "../../crates/ed-agent" } +# Used only for web_store::download_model; ed-agent does not re-export it. The +# browser engine and web_store are in ondeinference/onde#50 and not released +# yet, so this does not build from crates.io until a release has them. Raise +# the requirement to that release when it is out. +onde = "1.4.0" +wasm-bindgen = "0.2" +wasm-bindgen-futures = "0.4" +js-sys = "0.3" +serde = { version = "1", features = ["derive"] } +serde-wasm-bindgen = "0.6" +console_error_panic_hook = "0.1" + +[profile.release] +opt-level = 3 +lto = true +codegen-units = 1 + +[package.metadata.wasm-pack.profile.release] +# wasm-opt is downloaded at build time and needs SIMD flags to match the +# +simd128 build; skip it so the build has no network step beyond cargo. +wasm-opt = false diff --git a/examples/web-chat/README.md b/examples/web-chat/README.md new file mode 100644 index 0000000..6cd8956 --- /dev/null +++ b/examples/web-chat/README.md @@ -0,0 +1,61 @@ +# web-chat + +Ed running a model entirely in the browser. The page talks to a Web Worker +that owns one `Ed` instance compiled to `wasm32-unknown-unknown`. Nothing you +type is sent to a server. + +## Build and run + +You need `wasm-pack` and the `wasm32-unknown-unknown` target. + +```bash +./build.sh +python3 -m http.server -d www 8080 +``` + +Open . No bundler, npm or special headers are needed. +Cache Storage needs a secure context, which `localhost` counts as. + +The browser engine lives in `onde` 1.5.0. Until it is released, build against +a local checkout: + +```bash +./build.sh --config 'patch.crates-io.onde.path="../../../onde"' +``` + +## Deploy + +The demo is published at as a static site on +smbCloud (app `ondewebdemo`, in the Onde Inference project). It needs the `smb` +CLI 1.1.0 or newer and a prior `smb login`. + +```bash +./build.sh --config 'patch.crates-io.onde.path="../../../onde"' +./deploy.sh --dry-run # lists the files, uploads nothing +./deploy.sh # publishes, then waits for /version.txt to match +``` + +`deploy.sh` ships only `index.html`, `main.js`, `worker.js`, `style.css` and the +two files in `pkg/` that the page loads. Each deploy is a new release, and +`/version.txt` holds the commit it was built from (`-dirty` if the tree had +uncommitted changes). The site is static and needs no special headers. + +## What it downloads + +Qwen 2.5 0.5B (GGUF, about 380 MB), once, on the first click of Download. It +is stored in the browser's Cache Storage for this origin, so a reload loads it +from disk without downloading again. **Remove model** in the footer deletes it. + +## Speed + +Inference is CPU only, single threaded, using WebAssembly SIMD. Expect one to three +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 +also resets the conversation. + +## Layout + +- `src/lib.rs`: the wasm-bindgen API (`WebChat`) around `Ed`. +- `www/worker.js`: owns the wasm module and the `WebChat`. +- `www/main.js`, `index.html`, `style.css`: the UI. + +This crate is excluded from the root workspace and has its own lockfile. diff --git a/examples/web-chat/build.sh b/examples/web-chat/build.sh new file mode 100755 index 0000000..1f956dd --- /dev/null +++ b/examples/web-chat/build.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Build the wasm package into www/pkg. Serve www/ with any static server: +# python3 -m http.server -d www 8080 +# Extra arguments go to `cargo`, e.g. a local onde while it is unreleased: +# ./build.sh --config 'patch.crates-io.onde.path="../../../onde"' +set -euo pipefail +cd "$(dirname "$0")" + +# simd128 is what makes CPU inference usable in a browser. Every current +# browser supports it, and main.js checks for it before loading anything. +export RUSTFLAGS="${RUSTFLAGS:+$RUSTFLAGS }-C target-feature=+simd128" + +wasm-pack build --target web --release --out-dir www/pkg --no-typescript -- "$@" diff --git a/examples/web-chat/deploy.sh b/examples/web-chat/deploy.sh new file mode 100755 index 0000000..4e1969c --- /dev/null +++ b/examples/web-chat/deploy.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Publish www/ to https://ondewebdemo.5mb.app with the smbCloud CLI (smb >= 1.1.0). +# +# ./deploy.sh --dry-run stage and list the files; uploads nothing +# ./deploy.sh stage, deploy, then check /version.txt +# +# Run ./build.sh first: this ships whatever is in www/pkg. Auth is the token +# from `smb login`, or SMB_TOKEN in CI. +set -euo pipefail +cd "$(dirname "$0")" + +# The App .smb/config.toml must name. A stale config once sent a deploy into +# another app's directory, so a mismatch stops here before anything is written. +EXPECTED_APP_ID="c0277812-c891-4f4b-a3ee-c8cb371bb629" +URL="https://ondewebdemo.5mb.app" + +app_id="$(sed -n 's/^frontend_app_id *= *"\([^"]*\)".*/\1/p' .smb/config.toml | head -n 1)" +if [ "$app_id" != "$EXPECTED_APP_ID" ]; then + echo "refusing to deploy: .smb/config.toml says frontend_app_id ${app_id:-?}, expected $EXPECTED_APP_ID" >&2 + exit 1 +fi + +for f in www/pkg/web_chat.js www/pkg/web_chat_bg.wasm; do + [ -f "$f" ] || { echo "missing $f; run ./build.sh first" >&2; exit 1; } +done + +version="$(git rev-parse --short HEAD)" +git diff --quiet HEAD -- . || version="$version-dirty" + +# Only the servable files. www/pkg also holds a README, package.json and +# .gitignore from wasm-pack that have no place on the site. +stage="$(mktemp -d)" +trap 'rm -rf "$stage"' EXIT +mkdir "$stage/pkg" +cp www/index.html www/main.js www/worker.js www/style.css www/favicon.svg www/apple-touch-icon.png "$stage/" +cp www/pkg/web_chat.js www/pkg/web_chat_bg.wasm "$stage/pkg/" +printf '%s\n' "$version" > "$stage/version.txt" +# Config only: the CLI reads it and leaves it out of the upload. +cp -R .smb "$stage/.smb" + +echo "version: $version" +echo "app: $app_id" +echo "cli: $(smb --version 2>&1)" + +if [ "${1:-}" = "--dry-run" ]; then + (cd "$stage" && smb --ci deploy --prebuilt --dry-run) + exit 0 +fi + +(cd "$stage" && smb --ci deploy --prebuilt) + +echo "waiting for $URL/version.txt to report $version" +for _ in $(seq 15); do + live="$(curl -fsS --max-time 5 -H 'Cache-Control: no-cache' "$URL/version.txt" 2>/dev/null | tr -d '[:space:]' || true)" + if [ "$live" = "$version" ]; then + echo "live: $URL serves $version" + exit 0 + fi + sleep 2 +done +echo "$URL did not report $version within 30s (last saw: ${live:-nothing})" >&2 +exit 1 diff --git a/examples/web-chat/src/lib.rs b/examples/web-chat/src/lib.rs new file mode 100644 index 0000000..1f36faf --- /dev/null +++ b/examples/web-chat/src/lib.rs @@ -0,0 +1,134 @@ +//! Ed in the browser. +//! +//! [`WebChat`] wraps one [`Ed`] and is meant to live in a Web Worker: loading +//! the model and every token's forward pass block the thread they run on. The +//! page talks to it through `www/worker.js`. +//! +//! Each method returns a `Promise` and holds its own `Rc`, because +//! wasm-bindgen would otherwise borrow `&self` across the whole await and a +//! second call (a `reset` while a reply streams) would panic. + +use std::rc::Rc; + +use ed_agent::{Ed, GgufModelConfig}; +use js_sys::{Function, Promise}; +use wasm_bindgen::prelude::*; +use wasm_bindgen_futures::future_to_promise; + +/// The model this example runs: the catalogue's smallest (about 380 MB). The +/// preset comes from onde, so no model name is written here. +fn model() -> GgufModelConfig { + GgufModelConfig::qwen25_0_5b() +} + +fn to_js_error(e: impl std::fmt::Display) -> JsValue { + JsValue::from_str(&e.to_string()) +} + +fn number(n: u64) -> JsValue { + JsValue::from_f64(n as f64) +} + +#[wasm_bindgen] +pub struct WebChat { + ed: Rc, +} + +impl Default for WebChat { + fn default() -> Self { + Self::new() + } +} + +#[wasm_bindgen] +impl WebChat { + #[wasm_bindgen(constructor)] + pub fn new() -> WebChat { + console_error_panic_hook::set_once(); + WebChat { + ed: Rc::new(Ed::new()), + } + } + + /// Display name and size of the model, for the first-run card. + pub fn model_label(&self) -> String { + let config = model(); + format!("{}, {}", config.display_name, config.approx_memory) + } + + /// Resolves to whether the model is already in the browser cache. + pub fn is_cached(&self) -> Promise { + future_to_promise(async move { + Ok(JsValue::from_bool( + onde::web_store::is_cached(&model()).await, + )) + }) + } + + /// Download the model into the browser cache. `on_progress(received, total)` + /// gets byte counts; `total` is `null` when the server hides the length. + pub fn download(&self, on_progress: Function) -> Promise { + future_to_promise(async move { + onde::web_store::download_model(&model(), |received, total| { + let total = total.map_or(JsValue::NULL, number); + let _ = on_progress.call2(&JsValue::NULL, &number(received), &total); + }) + .await + .map_err(to_js_error)?; + Ok(JsValue::UNDEFINED) + }) + } + + /// Remove the downloaded model from the browser cache. + pub fn delete_cached(&self) -> Promise { + future_to_promise(async move { + let removed = onde::web_store::delete_model(&model()) + .await + .map_err(to_js_error)?; + Ok(JsValue::from_bool(removed)) + }) + } + + /// Load the model into memory (downloading it first if it isn't cached). + /// Resolves to the load time in seconds. + pub fn load(&self, system_prompt: Option) -> Promise { + let ed = self.ed.clone(); + future_to_promise(async move { + let took = ed + .load(model(), system_prompt, None) + .await + .map_err(to_js_error)?; + Ok(JsValue::from_f64(took.as_secs_f64())) + }) + } + + /// Send one message. `on_delta(text)` is called for each piece as it is + /// generated; the promise resolves with the whole reply. + pub fn send(&self, message: String, on_delta: Function) -> Promise { + let ed = self.ed.clone(); + future_to_promise(async move { + let mut stream = ed.stream(message).await.map_err(to_js_error)?; + let mut reply = String::new(); + while let Some(piece) = stream.next().await { + let piece = piece.map_err(to_js_error)?; + reply.push_str(&piece); + let _ = on_delta.call1(&JsValue::NULL, &JsValue::from_str(&piece)); + } + Ok(JsValue::from_str(&reply)) + }) + } + + /// Forget the conversation. Resolves to how many messages were dropped. + pub fn reset(&self) -> Promise { + let ed = self.ed.clone(); + future_to_promise(async move { Ok(number(ed.clear_history().await as u64)) }) + } + + /// Engine status, model name and history length. + pub fn info(&self) -> Promise { + let ed = self.ed.clone(); + future_to_promise(async move { + serde_wasm_bindgen::to_value(&ed.info().await).map_err(to_js_error) + }) + } +} diff --git a/examples/web-chat/www/apple-touch-icon.png b/examples/web-chat/www/apple-touch-icon.png new file mode 100644 index 0000000..552c4ed Binary files /dev/null and b/examples/web-chat/www/apple-touch-icon.png differ diff --git a/examples/web-chat/www/favicon.svg b/examples/web-chat/www/favicon.svg new file mode 100644 index 0000000..0ed4d22 --- /dev/null +++ b/examples/web-chat/www/favicon.svg @@ -0,0 +1,5 @@ + + + e + diff --git a/examples/web-chat/www/index.html b/examples/web-chat/www/index.html new file mode 100644 index 0000000..dda243c --- /dev/null +++ b/examples/web-chat/www/index.html @@ -0,0 +1,78 @@ + + + + + + + Ed, in your browser + + + + + + + + + + + + +
+
+

Ed

+

A language model running on this device. Nothing you type leaves it.

+
+ + + + + + + + +
+ + + diff --git a/examples/web-chat/www/main.js b/examples/web-chat/www/main.js new file mode 100644 index 0000000..a04e95a --- /dev/null +++ b/examples/web-chat/www/main.js @@ -0,0 +1,270 @@ +// UI thread: DOM and worker messaging only. All inference runs in worker.js. +// Messages are inserted with textContent, never as HTML. + +const $ = (id) => document.getElementById(id); +const els = { + unsupported: $("unsupported"), + reason: $("unsupported-reason"), + setup: $("setup"), + setupTitle: $("setup-title"), + setupText: $("setup-text"), + download: $("download"), + progressWrap: $("progress-wrap"), + progress: $("progress"), + progressLabel: $("progress-label"), + chat: $("chat"), + transcript: $("transcript"), + composer: $("composer"), + input: $("input"), + send: $("send"), + stop: $("stop"), + stats: $("stats"), + reset: $("reset"), + clear: $("clear"), +}; + +const SYSTEM_PROMPT = "You are Ed, a concise and helpful assistant."; + +// A minimal module that uses a v128 instruction; validate() is false where +// SIMD is missing. +const SIMD_PROBE = new Uint8Array([ + 0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, + 0, 65, 0, 253, 15, 253, 98, 11, +]); + +let worker = null; +let modelLabel = ""; +let nextId = 0; +let current = null; // { id, bubble } +let ready = false; +let resumeAfterReady = false; // set by Stop: reload the model without the setup card + +const mb = (bytes) => `${(bytes / 1e6).toFixed(0)} MB`; + +function show(section) { + for (const name of ["unsupported", "setup", "chat"]) { + els[name].hidden = name !== section; + } +} + +function unsupported(reason) { + els.reason.textContent = reason; + show("unsupported"); +} + +function addBubble(role, text = "") { + const bubble = document.createElement("div"); + bubble.className = `bubble ${role}`; + bubble.textContent = text; + els.transcript.append(bubble); + els.transcript.scrollTop = els.transcript.scrollHeight; + return bubble; +} + +function setBusy(busy) { + els.send.hidden = busy; + els.stop.hidden = !busy; + els.input.disabled = busy; + els.reset.disabled = busy; + els.clear.disabled = busy; +} + +function startWorker() { + ready = false; + worker = new Worker(new URL("./worker.js", import.meta.url), { + type: "module", + }); + worker.onmessage = ({ data }) => onMessage(data); + worker.onerror = (e) => unsupported(`The worker failed to start: ${e.message}`); +} + +function post(message) { + worker.postMessage(message); +} + +function showSetup(cached) { + show("setup"); + els.progressWrap.hidden = true; + els.download.disabled = false; + els.setupTitle.textContent = cached ? "Load the model" : "Download the model"; + els.setupText.textContent = cached + ? `${modelLabel} is saved in this browser. Loading takes a few seconds.` + : `${modelLabel}. It downloads once, is saved in this browser, and runs entirely on this device.`; + els.download.textContent = cached ? "Load" : "Download"; + els.download.dataset.cached = String(cached); +} + +function onMessage(m) { + switch (m.type) { + case "ready": + ready = true; + modelLabel = m.model; + if (resumeAfterReady) { + resumeAfterReady = false; + post({ type: "load", system: SYSTEM_PROMPT }); + } else { + showSetup(m.cached); + } + break; + case "progress": { + els.progressWrap.hidden = false; + if (m.total) { + const pct = Math.min(100, (m.received / m.total) * 100); + els.progress.value = pct; + els.progressLabel.textContent = `${mb(m.received)} of ${mb(m.total)} (${pct.toFixed(0)}%)`; + } else { + els.progress.removeAttribute("value"); + els.progressLabel.textContent = `${mb(m.received)} downloaded`; + } + break; + } + case "downloaded": + els.progressLabel.textContent = "Download complete. Loading the model…"; + post({ type: "load", system: SYSTEM_PROMPT }); + break; + case "loaded": + show("chat"); + setBusy(false); + els.stats.textContent = `Model loaded in ${m.seconds.toFixed(1)} s`; + els.input.focus(); + break; + case "delta": + if (current && current.id === m.id) { + current.bubble.textContent += m.text; + els.transcript.scrollTop = els.transcript.scrollHeight; + } + break; + case "done": + if (current && current.id === m.id) { + current.bubble.classList.remove("pending"); + current = null; + setBusy(false); + const rate = m.pieces / Math.max(m.seconds, 0.001); + els.stats.textContent = `${m.pieces} tokens in ${m.seconds.toFixed(1)} s, ${rate.toFixed(1)} tokens/s`; + els.input.focus(); + } + break; + case "reset": + els.transcript.replaceChildren(); + els.stats.textContent = "New conversation"; + break; + case "cleared": + els.transcript.replaceChildren(); + // The loaded model is still in memory; restart so it is released. + restart(); + break; + case "error": + onError(m); + break; + } +} + +function onError(m) { + if (current) { + current.bubble.classList.remove("pending"); + current.bubble.classList.add("error"); + const note = `Error: ${m.message}`; + current.bubble.textContent = current.bubble.textContent + ? `${current.bubble.textContent}\n\n[${note}]` + : note; + current = null; + setBusy(false); + } else if (m.stage === "boot") { + unsupported(`Ed could not start: ${m.message}`); + } else { + show("setup"); + els.download.disabled = false; + els.setupTitle.textContent = "Something went wrong"; + els.setupText.textContent = m.message; + } +} + +function restart() { + worker.terminate(); + current = null; + setBusy(false); + show("setup"); + els.download.disabled = true; + startWorker(); +} + +els.download.addEventListener("click", () => { + els.download.disabled = true; + if (els.download.dataset.cached === "true") { + els.setupTitle.textContent = "Load the model"; + els.setupText.textContent = "Loading the model…"; + post({ type: "load", system: SYSTEM_PROMPT }); + } else { + els.setupTitle.textContent = "Download the model"; + els.setupText.textContent = `${modelLabel}. Keep this tab open until it finishes.`; + els.progress.value = 0; + els.progressLabel.textContent = "Starting…"; + els.progressWrap.hidden = false; + post({ type: "download" }); + } +}); + +els.composer.addEventListener("submit", (event) => { + event.preventDefault(); + const text = els.input.value.trim(); + if (!text || current || !ready) return; + els.input.value = ""; + addBubble("user", text); + const bubble = addBubble("assistant"); + bubble.classList.add("pending"); + const id = nextId++; + current = { id, bubble }; + setBusy(true); + els.stats.textContent = "Thinking…"; + post({ type: "send", id, text }); +}); + +els.input.addEventListener("keydown", (event) => { + if (event.key === "Enter" && !event.shiftKey && !event.isComposing) { + event.preventDefault(); + els.composer.requestSubmit(); + } +}); + +els.input.addEventListener("input", () => { + els.input.style.height = "auto"; + els.input.style.height = `${els.input.scrollHeight}px`; +}); + +// Stop: a forward pass can't be interrupted from outside the worker, so end +// the worker and start another. The model is cached, so reloading is quick, +// but conversation history in the old worker is gone. +els.stop.addEventListener("click", () => { + if (current) { + current.bubble.classList.remove("pending"); + current.bubble.append(document.createTextNode(" [stopped]")); + } + worker.terminate(); + current = null; + setBusy(false); + els.stats.textContent = "Stopped. Reloading the model…"; + els.transcript.append( + Object.assign(document.createElement("div"), { + className: "bubble assistant", + textContent: "Conversation history was reset when generation stopped.", + }), + ); + els.input.disabled = true; + resumeAfterReady = true; + startWorker(); +}); + +els.reset.addEventListener("click", () => post({ type: "reset" })); +els.clear.addEventListener("click", () => { + if (confirm("Remove the downloaded model from this browser?")) { + post({ type: "clear" }); + } +}); + +if (!WebAssembly.validate(SIMD_PROBE)) { + unsupported("It needs WebAssembly SIMD, which this browser does not support. Try a current Chrome, Edge, Firefox or Safari."); +} else if (!("caches" in self) || !window.isSecureContext) { + unsupported("It needs Cache Storage, which requires a secure context. Open this page over https or from localhost."); +} else { + startWorker(); +} diff --git a/examples/web-chat/www/style.css b/examples/web-chat/www/style.css new file mode 100644 index 0000000..3aba4e7 --- /dev/null +++ b/examples/web-chat/www/style.css @@ -0,0 +1,136 @@ +:root { + color-scheme: light dark; + --bg: #f6f4ef; + --surface: #ffffff; + --ink: #1d1d1b; + --muted: #6b6a64; + --line: #e2dfd6; + --accent: #2f5d50; + --accent-ink: #ffffff; + --user: #e9efe9; + --radius: 14px; + font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #161615; + --surface: #1f1f1d; + --ink: #ecebe6; + --muted: #9a998f; + --line: #2f2f2b; + --accent: #7fb3a2; + --accent-ink: #10201b; + --user: #25302b; + } +} + +* { box-sizing: border-box; } + +body { + margin: 0; + min-height: 100dvh; + background: var(--bg); + color: var(--ink); + line-height: 1.5; +} + +main { + max-width: 42rem; + margin: 0 auto; + padding: 2.5rem 1.25rem 1.5rem; + min-height: 100dvh; + display: flex; + flex-direction: column; + gap: 1.5rem; +} + +h1 { margin: 0; font-size: 1.75rem; font-weight: 600; letter-spacing: -0.02em; } +h2 { margin: 0 0 0.5rem; font-size: 1.05rem; font-weight: 600; } +.tagline { margin: 0.25rem 0 0; color: var(--muted); } + +.card { + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 1.25rem; +} +.card p { margin: 0 0 1rem; color: var(--muted); } + +button { + font: inherit; + border: 0; + border-radius: 999px; + padding: 0.55rem 1.1rem; + background: var(--accent); + color: var(--accent-ink); + cursor: pointer; +} +button:disabled { opacity: 0.5; cursor: default; } +button:focus-visible, textarea:focus-visible, #transcript:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} +button.link { + background: none; + color: var(--muted); + padding: 0.25rem 0.4rem; + text-decoration: underline; + text-underline-offset: 3px; +} +#stop { background: transparent; color: var(--ink); border: 1px solid var(--line); } + +progress { width: 100%; height: 0.5rem; accent-color: var(--accent); } +#progress-label { margin: 0.5rem 0 0; font-size: 0.875rem; font-variant-numeric: tabular-nums; } + +#chat { flex: 1; display: flex; flex-direction: column; gap: 0.75rem; min-height: 0; } +#transcript { + flex: 1; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 0.75rem; + padding: 0.25rem 0; +} +.bubble { + max-width: 85%; + padding: 0.65rem 0.95rem; + border-radius: var(--radius); + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.bubble.user { align-self: flex-end; background: var(--user); } +.bubble.assistant { align-self: flex-start; background: var(--surface); border: 1px solid var(--line); } +.bubble.error { color: #b3261e; } +.bubble.pending::after { content: "▍"; margin-left: 1px; opacity: 0.6; } + +#composer { display: flex; gap: 0.5rem; align-items: flex-end; } +textarea { + flex: 1; + font: inherit; + color: inherit; + resize: none; + max-height: 10rem; + padding: 0.65rem 0.9rem; + border-radius: var(--radius); + border: 1px solid var(--line); + background: var(--surface); +} + +footer { display: flex; align-items: center; gap: 0.5rem; color: var(--muted); font-size: 0.8125rem; } +.spacer { flex: 1; } +.byline { margin: 0; text-align: center; color: var(--muted); font-size: 0.8125rem; } +.byline a { color: inherit; text-underline-offset: 3px; } +#stats { font-variant-numeric: tabular-nums; } + +.visually-hidden { + position: absolute; width: 1px; height: 1px; overflow: hidden; + clip: rect(0 0 0 0); white-space: nowrap; +} + +@media (prefers-reduced-motion: no-preference) { + .bubble.pending::after { animation: blink 1s steps(2, start) infinite; } + @keyframes blink { to { visibility: hidden; } } +} + +[hidden] { display: none !important; } diff --git a/examples/web-chat/www/worker.js b/examples/web-chat/www/worker.js new file mode 100644 index 0000000..7f7e320 --- /dev/null +++ b/examples/web-chat/www/worker.js @@ -0,0 +1,75 @@ +// Module worker: owns the wasm module and the one WebChat (Ed) instance. +// The page never touches inference, so a forward pass can't freeze the UI. +// Cancel works by terminating this worker and starting a new one; the model +// stays in Cache Storage, so the restart only re-reads it. + +import init, { WebChat } from "./pkg/web_chat.js"; + +let chat = null; + +const reply = (message) => self.postMessage(message); +const fail = (stage, error, id) => + reply({ type: "error", stage, id, message: String(error?.message ?? error) }); + +async function boot() { + await init(); + chat = new WebChat(); + reply({ + type: "ready", + model: chat.model_label(), + cached: await chat.is_cached(), + }); +} + +const handlers = { + async download() { + await chat.download((received, total) => + reply({ type: "progress", received, total }), + ); + reply({ type: "downloaded" }); + }, + + async load({ system }) { + const seconds = await chat.load(system ?? undefined); + reply({ type: "loaded", seconds }); + }, + + async send({ id, text }) { + const started = performance.now(); + let pieces = 0; + const full = await chat.send(text, (delta) => { + pieces += 1; + reply({ type: "delta", id, text: delta }); + }); + reply({ + type: "done", + id, + text: full, + pieces, + seconds: (performance.now() - started) / 1000, + }); + }, + + async reset() { + await chat.reset(); + reply({ type: "reset" }); + }, + + async clear() { + const removed = await chat.delete_cached(); + reply({ type: "cleared", removed }); + }, +}; + +self.onmessage = async ({ data }) => { + const handler = handlers[data.type]; + if (!handler) return; + if (!chat) return fail(data.type, "Ed is still starting", data.id); + try { + await handler(data); + } catch (error) { + fail(data.type, error, data.id); + } +}; + +boot().catch((error) => fail("boot", error));