Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ jobs:
filters: |
rust:
- "crates/**"
- "examples/**"
- "uniffi-bindgen/**"
- "Cargo.toml"
- "Cargo.lock"
Expand Down
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions examples/web-chat/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/target
/www/pkg
15 changes: 15 additions & 0 deletions examples/web-chat/.smb/config.toml
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 = "."
35 changes: 35 additions & 0 deletions examples/web-chat/Cargo.toml
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"
Comment thread
setoelkahfi marked this conversation as resolved.
Resolved
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
61 changes: 61 additions & 0 deletions examples/web-chat/README.md
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.
13 changes: 13 additions & 0 deletions examples/web-chat/build.sh
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 -- "$@"
62 changes: 62 additions & 0 deletions examples/web-chat/deploy.sh
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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
134 changes: 134 additions & 0 deletions examples/web-chat/src/lib.rs
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)
Comment thread
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)
})
}
}
Binary file added examples/web-chat/www/apple-touch-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 5 additions & 0 deletions examples/web-chat/www/favicon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading