@ondeinference / ed Mirror · read-only
Fork 0

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

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

Synced Nov 23, 01:00 UTC

main
js 75 lines 1.84 KB
Raw
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) return;
67 if (!chat) return fail(data.type, "Ed is still starting", data.id);
68 try {
69 await handler(data);
70 } catch (error) {
71 fail(data.type, error, data.id);
72 }
73 };
74
75 boot().catch((error) => fail("boot", error));