Repository navigation
Add examples/web-chat: Ed running in the browser #62
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
setoelkahfi
merged 4 commits into
feature/ed-agent-wasm-seams
from
feature/web-chat-example
Nov 18, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
bfd820c
examples: add web-chat, Ed running in the browser
setoelkahfi c196d65
web-chat: keep caller RUSTFLAGS, report early messages, mark failed r…
setoelkahfi a13a5a3
web-chat: publish the demo at ondewebdemo.5mb.app
setoelkahfi 260ce0e
web-chat: add a favicon
setoelkahfi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| /target | ||
| /www/pkg |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 = "." |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 <http://localhost:8080>. 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 <https://ondewebdemo.5mb.app> 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 -- "$@" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit — The final message says the script gave up after 30s, but the loop is 15 attempts with up to 5s of curl timeout plus a 2s sleep each, so it can actually wait about 105s before failing. |
||
| exit 1 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<Ed>`, 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) | ||
|
setoelkahfi marked this conversation as resolved.
Resolved
|
||
| } | ||
|
|
||
| #[wasm_bindgen] | ||
| pub struct WebChat { | ||
| ed: Rc<Ed>, | ||
| } | ||
|
|
||
| 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<String>) -> 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) | ||
| }) | ||
| } | ||
| } | ||
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.