// Demo UI: pick a scenario (or build a custom tool list), speak / upload a // command, see the tool call the model produces -- live.py, in the browser. import { SentencePieceBPE, pyJsonDumps } from "./tokenizer.js"; import { MicRecorder, decodeFile, wavBlob, SAMPLE_RATE } from "./audio.js"; const params = new URLSearchParams(location.search); const MODEL_URL = new URL(params.get("model") || "model/", location.href).href.replace(/\/?$/, "/"); const VARIANT = "q4"; // int4 weights and kernels: the only variant the model ships const STORAGE_KEY = "neudecide-demo/tools-v2"; // v2: the 4-app Mac control set const SAMPLES = [ { label: "“Clean the kitchen”", file: "samples/vaccumkitchen.wav", scenario: "robot_vacuum" }, { label: "“How full is the bin?”", file: "samples/binfullness.wav", scenario: "robot_vacuum" }, { label: "“Return to base”", file: "samples/returntobase.wav", scenario: "robot_vacuum" }, ]; const $ = (id) => document.getElementById(id); function el(tag, attrs = {}, ...children) { const node = document.createElement(tag); for (const [k, v] of Object.entries(attrs)) { if (k === "class") node.className = v; else if (k.startsWith("on")) node.addEventListener(k.slice(2), v); else if (v !== false && v != null) node.setAttribute(k, v === true ? "" : v); } node.append(...children.flat().filter((c) => c != null && c !== false)); return node; } // ---------------------------------------------------------------- state const state = { builtin: {}, // scenario key -> {label, examples, tools} as shipped scenarios: {}, // scenario key -> {label, examples, tools} as edited current: null, tokenizer: null, maxToolsLen: null, ready: false, busy: false, lastCalls: null, }; const storage = { load() { try { return JSON.parse(localStorage.getItem(STORAGE_KEY)) || {}; } catch { return {}; } }, save() { const edited = {}; for (const [k, s] of Object.entries(state.scenarios)) { if (k === "custom" || pyJsonDumps(s.tools) !== pyJsonDumps(state.builtin[k].tools)) edited[k] = s.tools; } try { localStorage.setItem(STORAGE_KEY, JSON.stringify({ edited, current: state.current })); } catch {} }, }; const clone = (x) => JSON.parse(JSON.stringify(x)); const tools = () => state.scenarios[state.current].tools; function setTools(next) { state.scenarios[state.current].tools = next; state.lastCalls = null; storage.save(); renderTools(); } // ---------------------------------------------------------------- tools panel // Scenarios can nest: "mac_control/granola/meeting" is a context inside // "mac_control/granola" (its "parent"). Only top-level scenarios get a tab; // the page moves into a sub-context when an action says so (or via the breadcrumb). const rootOf = (key) => key.split("/")[0]; function contextPath(key) { const path = []; for (let k = key; k; k = state.scenarios[k]?.parent) path.unshift(k); return path; } function renderTabs() { const tabs = $("scenario-tabs"); tabs.replaceChildren(...Object.entries(state.scenarios).filter(([, s]) => !s.parent).map(([key, s]) => el("button", { role: "tab", "aria-selected": String(key === rootOf(state.current)), onclick: () => selectScenario(key) }, s.label))); } function renderBreadcrumb() { const path = contextPath(state.current); const crumb = $("context-path"); crumb.hidden = path.length < 2; crumb.replaceChildren(...path.flatMap((k, i) => [ ...(i ? [el("span", { class: "sep" }, "›")] : []), i === path.length - 1 ? el("strong", {}, state.scenarios[k].label) : el("button", { class: "ghost crumb", onclick: () => selectScenario(k) }, state.scenarios[k].label), ])); } function selectScenario(key) { state.current = key; state.lastCalls = null; storage.save(); renderTabs(); renderBreadcrumb(); renderTools(); closeJsonEditor(); const s = state.scenarios[key]; $("examples").textContent = s.examples?.length ? `Try saying: ${s.examples.map((e) => `“${e}”`).join(" · ")}` : ""; $("scenario-hint").textContent = key === "custom" ? "Your own tool list -- add tools below or paste a JSON list." : s.execute === "mac" ? "Tool calls here really run on this Mac (needs serve.py --mac). Only the actions in mac_actions.py can run." : "Edit, remove or add tools; changes are kept in this browser."; } function paramChip(name, p, required) { let detail = p.type ?? "any"; if (p.enum) detail = p.enum.join(" | "); else if (p.minimum !== undefined || p.maximum !== undefined) detail += ` ${p.minimum ?? ""}–${p.maximum ?? ""}`; return el("span", { class: "param", title: p.description || "" }, name, required ? el("span", { class: "req", title: "required" }, "*") : null, `: ${detail}`); } function renderTools() { const list = $("tool-list"); const ts = tools(); const called = new Set((state.lastCalls || []).map((c) => c.name)); if (!ts.length) { list.replaceChildren(el("li", { class: "empty" }, "No tools yet. Add one, or paste a list with “Edit as JSON”.")); } else { list.replaceChildren(...ts.map((t, i) => { const props = t.parameters?.properties || {}; const required = new Set(t.parameters?.required || []); return el("li", { class: `tool${called.has(t.name) ? " called" : ""}` }, el("span", { class: "tool-name" }, t.name), el("span", { class: "tool-buttons" }, el("button", { class: "ghost", title: "Edit", onclick: () => openToolDialog(i) }, "Edit"), el("button", { class: "ghost", title: "Remove", "aria-label": `Remove ${t.name}`, onclick: () => setTools(ts.filter((_, j) => j !== i)) }, "×")), el("span", { class: "tool-desc" }, t.description || ""), Object.keys(props).length ? el("span", { class: "params" }, Object.entries(props).map(([n, p]) => paramChip(n, p, required.has(n)))) : el("span", { class: "params muted" }, "no parameters")); })); } const base = state.builtin[state.current]; $("reset-tools").hidden = !base || state.current === "custom" || pyJsonDumps(ts) === pyJsonDumps(base.tools); renderTokenCount(); } function renderTokenCount() { const node = $("tool-tokens"); if (!state.tokenizer) { node.textContent = ""; return; } const n = 1 + state.tokenizer.encode(pyJsonDumps(tools())).length; const max = state.maxToolsLen; node.textContent = `${tools().length} tools · ${n}${max ? ` / ${max}` : ""} tokens`; node.style.color = max && n > max ? "var(--error)" : ""; node.title = max && n > max ? "Over the length the model was trained on: the list will be truncated." : ""; } // ---------------------------------------------------------------- JSON editor function openJsonEditor() { $("json-text").value = JSON.stringify(tools(), null, 2); $("json-error").textContent = ""; $("json-editor").hidden = false; $("json-text").focus(); } function closeJsonEditor() { $("json-editor").hidden = true; } function validateTools(ts) { if (!Array.isArray(ts)) throw new Error("Expected a JSON list of tools."); const names = new Set(); ts.forEach((t, i) => { if (!t || typeof t !== "object" || typeof t.name !== "string" || !t.name) throw new Error(`Tool ${i + 1} needs a "name".`); if (names.has(t.name)) throw new Error(`Duplicate tool name "${t.name}".`); names.add(t.name); const p = t.parameters; if (p !== undefined && (typeof p !== "object" || (p.properties && typeof p.properties !== "object"))) throw new Error(`"${t.name}": "parameters" must be a JSON-Schema object.`); }); return ts; } function applyJson() { try { setTools(validateTools(JSON.parse($("json-text").value))); closeJsonEditor(); } catch (e) { $("json-error").textContent = e.message; } } // ---------------------------------------------------------------- tool dialog let editingIndex = null; const MANAGED = new Set(["type", "enum", "minimum", "maximum", "description"]); function addParamRow(name = "", p = { type: "string" }, required = true) { const row = $("param-row").content.firstElementChild.cloneNode(true); row.querySelector(".p-name").value = name; row.querySelector(".p-type").value = ["string", "number", "integer", "boolean"].includes(p.type) ? p.type : "string"; row.querySelector(".p-enum").value = (p.enum || []).join(", "); row.querySelector(".p-min").value = p.minimum ?? ""; row.querySelector(".p-max").value = p.maximum ?? ""; row.querySelector(".p-desc").value = p.description || ""; row.querySelector(".p-req input").checked = required; row.extras = Object.fromEntries(Object.entries(p).filter(([k]) => !MANAGED.has(k))); // e.g. "default", kept as-is const sync = () => { const t = row.querySelector(".p-type").value; row.querySelector(".p-enum").disabled = t !== "string"; row.querySelector(".p-min").disabled = row.querySelector(".p-max").disabled = !(t === "number" || t === "integer"); }; row.querySelector(".p-type").addEventListener("change", sync); row.querySelector(".p-remove").addEventListener("click", () => row.remove()); sync(); $("param-rows").append(row); } function openToolDialog(index = null) { editingIndex = index; const t = index === null ? null : tools()[index]; const form = $("tool-form"); form.reset(); $("tool-dialog-title").textContent = t ? `Edit ${t.name}` : "Add tool"; form.elements.name.value = t?.name || ""; form.elements.description.value = t?.description || ""; $("param-rows").replaceChildren(); const required = new Set(t?.parameters?.required || []); for (const [n, p] of Object.entries(t?.parameters?.properties || {})) addParamRow(n, p, required.has(n)); $("tool-error").textContent = ""; $("tool-dialog").showModal(); } // Builds the tool in the training data's key order: name, description, // parameters{type, properties{type, enum | minimum, maximum, description}, required}. function toolFromForm() { const form = $("tool-form"); const name = form.elements.name.value.trim(); const properties = {}; const required = []; for (const row of $("param-rows").children) { const pname = row.querySelector(".p-name").value.trim(); if (!pname) throw new Error("Every parameter needs a name."); if (pname in properties) throw new Error(`Duplicate parameter "${pname}".`); const type = row.querySelector(".p-type").value; const prop = { type }; const values = row.querySelector(".p-enum").value.split(",").map((s) => s.trim()).filter(Boolean); if (type === "string" && values.length) prop.enum = values; for (const key of ["minimum", "maximum"]) { const raw = row.querySelector(key === "minimum" ? ".p-min" : ".p-max").value.trim(); if ((type === "number" || type === "integer") && raw) { const v = Number(raw); if (!Number.isFinite(v)) throw new Error(`"${pname}": ${key} must be a number.`); prop[key] = v; } } const desc = row.querySelector(".p-desc").value.trim(); if (desc) prop.description = desc; properties[pname] = { ...prop, ...row.extras }; if (row.querySelector(".p-req input").checked) required.push(pname); } const t = { name, description: form.elements.description.value.trim(), parameters: { type: "object", properties, required } }; const others = tools().filter((_, i) => i !== editingIndex); if (others.some((o) => o.name === name)) throw new Error(`A tool named "${name}" already exists.`); return t; } // ---------------------------------------------------------------- model worker // Started through a blob: URL that imports worker.js, not from worker.js // directly: under COEP a worker's own script must carry the COEP header too, // and hosts like HF Spaces only send custom_headers on the page -- the worker // would be blocked (ERR_BLOCKED_BY_RESPONSE) and the page would wait forever. // A blob worker inherits the page's policy; module imports need no header. function startWorker() { const src = `import ${JSON.stringify(new URL("./worker.js", import.meta.url).href)};`; const url = URL.createObjectURL(new Blob([src], { type: "text/javascript" })); const w = new Worker(url, { type: "module" }); setTimeout(() => URL.revokeObjectURL(url), 60_000); return w; } const worker = startWorker(); setStatus("Starting model worker…"); worker.addEventListener("error", (e) => { e.preventDefault(); setStatus(`Model worker failed to start: ${e.message || "see the browser console"}`, "failed"); }); let runId = 0; function setStatus(text, cls = "") { $("model-status").className = `model-status ${cls}`; $("model-status-text").textContent = text; } function setInputsEnabled(on) { $("record").disabled = !on && !recorder.recording; $("upload").disabled = !on; $("upload-label").classList.toggle("disabled", !on); for (const b of $("samples").querySelectorAll("button")) b.disabled = !on; } const fileProgress = {}; worker.onmessage = ({ data }) => { if (data.type === "progress" && data.stage) { setStatus(data.stage); } else if (data.type === "progress") { fileProgress[data.file] = data; const files = Object.values(fileProgress); const loaded = files.reduce((a, f) => a + f.loaded, 0); const total = files.reduce((a, f) => a + (f.total || f.loaded), 0); $("model-progress").hidden = false; $("model-progress").firstElementChild.style.width = `${total ? (100 * loaded) / total : 0}%`; setStatus(data.initializing ? `Initializing ${data.file}…` : `Downloading model… ${(loaded / 2 ** 20).toFixed(0)} MiB`); } else if (data.type === "ready") { state.ready = true; state.maxToolsLen = data.config.max_tools_len; $("model-progress").hidden = true; setStatus(`Model ready · ${data.variant}`, "ready"); renderTokenCount(); setInputsEnabled(true); } else if (data.type === "token" && data.id === runId) { $("raw").textContent = data.text; } else if (data.type === "result" && data.id === runId) { state.busy = false; renderResult(data); setInputsEnabled(true); } else if (data.type === "error") { state.busy = false; if (!state.ready) setStatus(`Failed to load model: ${data.message}`, "failed"); else $("run-error").textContent = data.message; setInputsEnabled(state.ready); } }; function run(waveform) { if (!state.ready || state.busy || !waveform.length) return; if (!tools().length) { $("run-error").textContent = "Add at least one tool first."; return; } state.busy = true; setInputsEnabled(false); $("run-error").textContent = ""; $("result").hidden = false; $("playback").src = URL.createObjectURL(wavBlob(waveform)); $("calls").replaceChildren(el("p", { class: "status-line muted" }, "Thinking…")); $("raw").textContent = ""; $("timings").textContent = ""; runId += 1; const copy = waveform.slice(); worker.postMessage({ type: "run", id: runId, waveform: copy, tools: tools() }, [copy.buffer]); } // ---------------------------------------------------------------- results function checkArgs(call, tool) { const notes = []; const props = tool.parameters?.properties || {}; const args = call.arguments && typeof call.arguments === "object" ? call.arguments : {}; for (const r of tool.parameters?.required || []) { if (!(r in args)) notes.push({ cls: "missing", text: `required argument missing: ${r}` }); } for (const [k, v] of Object.entries(args)) { const p = props[k]; if (!p) { notes.push({ cls: "unknown", text: `${k} isn't a parameter of ${tool.name}` }); continue; } if (p.enum && !p.enum.includes(v)) notes.push({ cls: "unknown", text: `${k} = ${pyJsonDumps(v)} isn't one of ${p.enum.join(", ")}` }); else if (typeof v === "number" && ((p.minimum !== undefined && v < p.minimum) || (p.maximum !== undefined && v > p.maximum))) notes.push({ cls: "unknown", text: `${k} = ${v} is outside ${p.minimum ?? ""}–${p.maximum ?? ""}` }); else notes.push({ cls: "ok", text: `${k} = ${pyJsonDumps(v)}` }); } return notes; } function renderResult(r) { $("result").dataset.run = String(r.id); // lets tests wait for a fresh result $("raw").textContent = r.text; const t = r.timings; $("timings").textContent = `${t.audioSeconds.toFixed(1)}s audio · audio encoder ${t.audioEncoder.toFixed(0)} ms · ` + `encoder ${t.toolEncoder.toFixed(0)} ms (${t.encoderLen} positions) · decode ${t.decode.toFixed(0)} ms ` + `(${t.tokens} tokens)${t.toolsTruncated ? " · tool list truncated!" : ""}`; state.lastCalls = r.calls; renderTools(); const box = $("calls"); if (r.calls === null) { box.replaceChildren(el("p", { class: "status-line error" }, "Couldn't parse the output as a tool call.")); notifyIfAway("NeuDecide", "Didn't catch that -- try again"); } else if (!r.calls.length) { box.replaceChildren(el("p", { class: "status-line muted" }, "No tool call: the model chose not to act.")); notifyIfAway(state.scenarios[state.current].label, "No action for that here"); } else { box.replaceChildren(...r.calls.map((call) => { const tool = tools().find((x) => x.name === call.name); const args = call.arguments && typeof call.arguments === "object" ? call.arguments : {}; const argText = Object.entries(args).map(([k, v]) => `${k}=${pyJsonDumps(v)}`).join(", "); const notes = tool ? checkArgs(call, tool) : [{ cls: "unknown", text: "not in the current tool list" }]; const list = el("ul", { class: "slots" }, notes.map((n) => el("li", { class: n.cls }, n.text))); const valid = tool && notes.every((n) => n.cls === "ok"); if (state.scenarios[state.current].execute === "mac") executeOnMac(call, valid, list); return el("div", { class: "call" }, el("span", { class: "fn" }, call.name), `(${argText})`, list); })); } } // Mac control scenario: run the call through serve.py --mac (mac_actions.py). async function executeOnMac(call, valid, list) { const line = el("li", { class: "muted" }, "▶ running on your Mac…"); list.append(line); if (!valid) { line.className = "unknown"; line.textContent = "▶ not run: fix the arguments above first"; return; } if (call.name === "goBack") { // navigation is the page's job, not the Mac's const parent = state.scenarios[state.current].parent || rootOf(state.current); line.className = "ok"; line.textContent = `✓ back to ${state.scenarios[parent].label}`; notifyIfAway("NeuDecide", `Back to ${state.scenarios[parent].label}`); selectScenario(parent); return; } try { const res = await fetch("api/execute", { method: "POST", headers: { "Content-Type": "application/json" }, // which app's functions to use (Chrome and Notion both have navigate / summarizePage) body: JSON.stringify({ name: call.name, arguments: call.arguments || {}, context: state.current.split("/")[1] || "home" }), }); if (res.status === 404) throw new Error("start the server with --mac to enable this"); if (!res.ok) throw new Error(`HTTP ${res.status}`); const r = await res.json(); line.className = r.ok ? "ok" : "unknown"; line.textContent = `${r.ok ? "✓" : "✗"} ${r.message}`; if (r.detail) list.after(el("pre", { class: "detail" }, r.detail)); let where = ""; if (r.ok && typeof r.enter === "string") { // the action moved us into (or out of) a context const root = rootOf(state.current); const target = r.enter ? `${root}/${r.enter}` : root; if (target && state.scenarios[target]) { if (target !== state.current) selectScenario(target); where = contextPath(target).map((k) => state.scenarios[k].label).join(" › "); list.append(el("li", { class: "ok" }, `→ ${where} · ${tools().length} tools`)); } } notifyIfAway(where || state.scenarios[state.current].label, `${r.ok ? "" : "✗ "}${r.message}${r.detail ? "\n" + r.detail : ""}`); } catch (e) { line.className = "unknown"; line.textContent = `✗ ${e.message}`; notifyIfAway("NeuDecide", `✗ ${e.message}`); } } // ---------------------------------------------------------------- app contexts // The hotkey says which app is in front: move to its tools (unless we're already inside it). // Granola, Slack, Chrome or Notion get their own tools; any other app, the home list. async function syncContext(front) { const root = "mac_control"; if (!front || !state.scenarios[root]) return; const target = front.key && state.scenarios[`${root}/${front.key}`] ? `${root}/${front.key}` : root; if (state.current !== target) selectScenario(target); } // ---------------------------------------------------------------- hotkey // // serve.py --hotkey records the mic itself when you hold the keys (no arming // here) and streams events to the newest open page: "start" (which app is in // front), then "audio" (what you said) or "cancel". This page just needs to // stay open; it can be in the background. const away = () => !document.hasFocus(); const hotkey = { combo: null, sync: null, tab: crypto.randomUUID(), listening: false }; const KEY_GLYPHS = { ctrl: "⌃", alt: "⌥", cmd: "⌘", shift: "⇧" }; function notifyIfAway(title, text) { if (!away() || !hotkey.combo) return; fetch("api/notify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title, text }) }).catch(() => {}); } function claimHotkey() { // the page you last looked at runs hotkey commands fetch("api/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ tab: hotkey.tab }) }).catch(() => {}); } function renderHotkey() { $("hotkey").hidden = !hotkey.combo; if (!hotkey.combo) return; const keys = hotkey.combo.split("+").map((k) => KEY_GLYPHS[k]).join(""); $("hotkey-status").textContent = hotkey.listening ? `Listening… release ${keys} when you're done.` : `Hold ${keys} in any app to talk (tap for hands-free). Keep this tab open; it can be in the background.`; $("hotkey").classList.toggle("armed", true); } function setListening(on) { hotkey.listening = on; $("record").classList.toggle("recording", on); $("record-label").textContent = on ? "Listening" : "Record"; renderHotkey(); } function pcmFromBase64(b64) { const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0)); const i16 = new Int16Array(bytes.buffer); const out = new Float32Array(i16.length); for (let i = 0; i < i16.length; i++) out[i] = i16[i] / 32768; return out; } async function onHotkey(ev) { if (ev.type === "hello") { hotkey.combo = ev.hotkey; renderHotkey(); return; } if (ev.tab && ev.tab !== hotkey.tab) return; // another open tab handles it console.log("[hotkey]", ev.type, ev.frontmost?.name ?? ""); if (ev.type === "start") { if (!state.ready || state.busy || recorder.recording) { notifyIfAway("NeuDecide", !state.ready ? "Model still loading" : "Still working on the last command"); return; } setListening(true); // switch to the frontmost app's tools while you talk -- unless you're using this page if (away()) { if (!state.scenarios[state.current].execute) selectScenario("mac_control"); hotkey.sync = syncContext(ev.frontmost); } } else if (ev.type === "audio") { if (!hotkey.listening) return; setListening(false); await hotkey.sync; hotkey.sync = null; const pcm = pcmFromBase64(ev.pcm16); $("record-time").textContent = `${(pcm.length / SAMPLE_RATE).toFixed(1)}s`; run(pcm); } else if (ev.type === "cancel") { if (hotkey.listening) { setListening(false); $("record-time").textContent = "cancelled"; } } } function connectHotkey() { const es = new EventSource(`api/events?tab=${hotkey.tab}`); es.onmessage = (m) => { try { onHotkey(JSON.parse(m.data)); } catch (e) { console.error(e); } }; es.onerror = () => { if (es.readyState === EventSource.CLOSED) { hotkey.combo = null; renderHotkey(); } }; window.addEventListener("focus", claimHotkey); } // ---------------------------------------------------------------- audio inputs const recorder = new MicRecorder({ onLevel: (rms, seconds) => { $("meter").firstElementChild.style.width = `${Math.min(100, rms * 400)}%`; $("record-time").textContent = `${seconds.toFixed(1)}s`; }, onAutoStop: () => toggleRecording(), }); async function toggleRecording() { const button = $("record"); if (!recorder.recording) { try { await recorder.start(); } catch (e) { $("run-error").textContent = `Microphone unavailable: ${e.message}`; return; } button.classList.add("recording"); $("record-label").textContent = "Stop"; $("run-error").textContent = ""; setInputsEnabled(false); button.disabled = false; } else { button.classList.remove("recording"); $("record-label").textContent = "Record"; $("meter").firstElementChild.style.width = "0"; const pcm = await recorder.stop(); $("record-time").textContent = pcm.length ? `${(pcm.length / SAMPLE_RATE).toFixed(1)}s` : ""; setInputsEnabled(true); run(pcm); } } async function runFile(file) { try { run(await decodeFile(await file.arrayBuffer())); } catch (e) { $("run-error").textContent = `Couldn't decode ${file.name}: ${e.message}`; } } async function runSample(sample) { if (state.scenarios[sample.scenario] && state.current !== sample.scenario) selectScenario(sample.scenario); const res = await fetch(sample.file); run(await decodeFile(await res.arrayBuffer())); } // ---------------------------------------------------------------- wiring async function init() { const shipped = await (await fetch("scenarios.json")).json(); const saved = storage.load(); for (const [key, s] of Object.entries(shipped)) { state.builtin[key] = s; state.scenarios[key] = { ...clone(s), tools: clone(saved.edited?.[key] || s.tools) }; } state.builtin.custom = { label: "Custom", tools: [] }; state.scenarios.custom = { label: "Custom", examples: [], tools: clone(saved.edited?.custom || []) }; selectScenario(state.scenarios[saved.current] ? saved.current : Object.keys(shipped)[0]); $("samples").replaceChildren(...SAMPLES.map((s) => el("button", { class: "secondary", disabled: true, onclick: () => runSample(s) }, s.label))); $("record").addEventListener("click", toggleRecording); $("upload").addEventListener("change", (e) => { if (e.target.files[0]) runFile(e.target.files[0]); e.target.value = ""; }); connectHotkey(); $("add-tool").addEventListener("click", () => openToolDialog()); $("edit-json").addEventListener("click", openJsonEditor); $("json-apply").addEventListener("click", applyJson); $("json-cancel").addEventListener("click", closeJsonEditor); $("reset-tools").addEventListener("click", () => setTools(clone(state.builtin[state.current].tools))); $("add-param").addEventListener("click", () => addParamRow()); $("tool-cancel").addEventListener("click", () => $("tool-dialog").close()); $("tool-form").addEventListener("submit", (e) => { e.preventDefault(); try { const t = toolFromForm(); const next = tools().slice(); if (editingIndex === null) next.push(t); else next[editingIndex] = t; setTools(next); $("tool-dialog").close(); } catch (err) { $("tool-error").textContent = err.message; } }); const panel = document.querySelector(".run-panel"); panel.addEventListener("dragover", (e) => { e.preventDefault(); panel.classList.add("dragging"); }); panel.addEventListener("dragleave", () => panel.classList.remove("dragging")); panel.addEventListener("drop", (e) => { e.preventDefault(); panel.classList.remove("dragging"); const file = e.dataTransfer.files[0]; if (file && state.ready && !state.busy) runFile(file); }); worker.postMessage({ type: "load", baseUrl: MODEL_URL, variant: VARIANT }); try { state.tokenizer = await SentencePieceBPE.load(MODEL_URL + "tokenizer.json"); renderTokenCount(); } catch {} // counts are a nicety; the worker reports real load failures } init().catch((e) => setStatus(`Failed to start: ${e.message}`, "failed"));