// SPDX-License-Identifier: Apache-2.0
// Decide Live: zero-token decisions with a multimodal embedding model running in the browser.
const $ = (id) => document.getElementById(id);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
const params = new URLSearchParams(location.search);
/* ------------------------------------------------------------------ worker */
const worker = new Worker(new URL("./worker.js?v=5", import.meta.url), { type: "module" });
let reqId = 0;
const pending = new Map();
worker.onmessage = ({ data }) => {
if (data.type === "state") return onState(data);
const p = pending.get(data.id);
if (!p) return;
pending.delete(data.id);
if (data.type === "result") p.resolve(data.result);
else p.reject(new Error(data.message));
};
worker.onerror = (e) => setStatus("error", `Worker error: ${e.message || e}`);
function rpc(op, payload = {}, transfer = []) {
const id = ++reqId;
return new Promise((resolve, reject) => {
pending.set(id, { resolve, reject });
worker.postMessage({ id, op, ...payload }, transfer);
});
}
/* ------------------------------------------------------------------ model */
let model = null; // {device, dtype, audio, loadMs}
let loadPromise = null;
if (params.get("device")) $("device").value = params.get("device");
if (params.get("dtype")) $("dtype").value = params.get("dtype");
function setStatus(phase, text) {
$("status").className = `status ${phase}`;
$("statusText").textContent = text;
}
function onState(s) {
setStatus(s.phase, s.label + (s.totalBytes ? ` (${(s.loadedBytes / 1e6).toFixed(0)} / ${(s.totalBytes / 1e6).toFixed(0)} MB)` : ""));
if (s.phase === "loading" && typeof s.progress === "number") {
$("progressWrap").hidden = false;
$("progressBar").style.width = `${Math.max(2, Math.min(100, s.progress))}%`;
}
if (s.phase === "ready" || s.phase === "error") $("progressWrap").hidden = true;
}
async function ensureModel(audio = false) {
const want = { device: $("device").value, dtype: $("dtype").value, audio: audio || !!model?.audio };
if (model && model.requested === want.dtype && (want.device === "auto" || want.device === model.device) && (!audio || model.audio)) return model;
if (loadPromise) {
await loadPromise.catch(() => {});
return ensureModel(audio);
}
loadPromise = rpc("load", { options: want })
.then((info) => {
if (model && model.dtype !== info.dtype) textCache.clear();
model = info;
if (info.scale) {
trainedScale = info.scale;
if (!tempTouched) setTemp(1 / trainedScale);
}
$("backend").textContent = info.device === "webgpu" ? "WebGPU" : "WASM (CPU)";
$("wasmNote").hidden = info.device !== "wasm";
return info;
})
.catch((e) => { setStatus("error", `Could not load the model: ${e.message}`); throw e; })
.finally(() => (loadPromise = null));
return loadPromise;
}
/* ------------------------------------------------------------------ embeddings and scoring */
const textCache = new Map();
async function embedTexts(texts) {
const missing = [...new Set(texts.filter((t) => !textCache.has(t)))];
let ms = 0;
if (missing.length) {
const r = await rpc("embedTexts", { texts: missing });
r.embeddings.forEach((e, i) => textCache.set(missing[i], e));
ms = r.ms;
}
return { embeddings: texts.map((t) => textCache.get(t)), ms, fresh: missing.length };
}
const dot = (a, b) => { let s = 0; for (let i = 0; i < a.length; i++) s += a[i] * b[i]; return s; };
function softmax(xs, T) {
const z = xs.map((x) => x / T);
const m = Math.max(...z);
const e = z.map((x) => Math.exp(x - m));
const s = e.reduce((a, b) => a + b, 0);
return e.map((x) => x / s);
}
const argmax = (xs) => xs.reduce((bi, x, i) => (x > xs[bi] ? i : bi), 0);
// The model was trained with P(option) = softmax(scale * cos); the learned scale ships with the model
// (decision.json). The default temperature is 1 / scale.
let trainedScale = 19.9607;
let tempTouched = false;
function setTemp(t) {
$("temp").value = t.toFixed(4);
$("tempVal").textContent = `${(+$("temp").value).toFixed(4)}${Math.abs(t - 1 / trainedScale) < 5e-5 ? ` (trained: 1 / ${trainedScale.toFixed(2)})` : ""}`;
}
const temperature = () => parseFloat($("temp").value);
// Image tokens for single inputs and sample tests: model default 280 on WebGPU, 70 on the much slower CPU path.
const imageBudget = () => ($("budgetSingle").value === "auto" ? (model?.device === "wasm" ? 70 : 280) : +$("budgetSingle").value);
/* ------------------------------------------------------------------ prompts */
const DOC = (d) => `title: none | text: ${d}`;
const PH = { image: "<|image|>", rgba: "<|image|>", audio: "<|audio|>", video: "<|video|>" };
// Trained format: media placeholders first, then "task: classification | query: {question}" and
// "\nContext: {context}" when there is one (a context of exactly "See the image." is left out, as in training).
function trainedQuery(kind, question, context, extraText = "") {
const ctx = [context === "See the image." ? "" : context, extraText].filter(Boolean).join("\n");
return (PH[kind] || "") + `task: classification | query: ${question}` + (ctx ? `\nContext: ${ctx}` : "");
}
const PRESETS = {
trained: { label: "Trained decision format (default)", trained: true, opt: DOC },
cls: { label: "Classification query (input + question) and document options", interleave: true, q: "task: classification | query: ", opt: DOC },
qa: { label: "Question answering query (input + question) and document options", interleave: true, q: "task: question answering | query: ", opt: DOC },
sym: { label: "Classification prefix on both sides (symmetric)", interleave: true, q: "task: classification | query: ", opt: (d) => `task: classification | query: ${d}` },
xsearch: { label: "Media alone; question + option as a search query", interleave: false, q: "task: classification | query: ", opt: (d) => `task: search result | query: ${d}` },
xdoc: { label: "Media alone; question + option as a document", interleave: false, q: "task: classification | query: ", opt: DOC },
};
// Live cards: the frame is embedded once with no text (media takes no prefix), options are self-describing.
const LIVE_OPT = (d) => `task: search result | query: ${d}`;
for (const [k, p] of Object.entries(PRESETS)) $("preset").insertAdjacentHTML("beforeend", ``);
$("promptDoc").innerHTML =
`
Single input, sample tests and the egg check (the format is selectable under Single input > Settings):
` +
Object.values(PRESETS)
.map((p) => `
${esc(p.label)}: input ${p.trained ? esc("task: classification | query: {question}") + " " + esc("Context: {context}") : p.interleave ? esc(p.q) + "{context} {question} <media>" : "<media> (no text)"}, option ${esc(p.opt(p.interleave || p.trained ? "{description}" : "{question} {description}"))}${p.trained ? ". Yes / no questions use the options Yes and No." : ""}
`)
.join("") +
`
Live cards: by default each card embeds the frame with its own question in the trained format (one pass per card). The alternative embeds the frame or sound window alone, once for all cards, and each option as ${esc(LIVE_OPT("{description}"))}.
`;
$("eggResult").hidden = false;
}
function eggThumb(i) { return $("eggGrid").querySelector(`.eggthumb[data-i="${i}"]`); }
function stampEgg(i, pred, gold, conf) {
const t = eggThumb(i);
if (!t) return;
t.classList.remove("busy");
t.querySelector(".stamp")?.remove();
t.insertAdjacentHTML("beforeend", `${esc(pred)} ${Math.round(conf * 100)}%`);
}
async function eggBusy(fn) {
const btns = [$("eggRunAll"), ...document.querySelectorAll(".eggthumb")];
btns.forEach((b) => (b.disabled = true));
try { await fn(); } catch (e) { $("eggSummary").innerHTML = `${esc(e.message)}`; }
finally { btns.forEach((b) => (b.disabled = false)); }
}
$("eggGrid").querySelectorAll(".eggthumb").forEach((b) =>
b.addEventListener("click", () => eggBusy(async () => {
const p = EGG_PHOTOS[+b.dataset.i];
$("eggSummary").textContent = model ? "Deciding..." : "Loading the model...";
b.classList.add("busy");
const blob = await fetchBlob(p.file);
const r = await eggDecide(blob).finally(() => b.classList.remove("busy"));
eggShow(blob, r, p.gold);
stampEgg(+b.dataset.i, EGG.options[r.top].key, p.gold, r.probs[r.top]);
$("eggSummary").textContent = "";
}))
);
$("eggFile").addEventListener("change", (e) => eggBusy(async () => {
const f = e.target.files[0];
if (!f) return;
$("eggSummary").textContent = model ? "Deciding..." : "Loading the model...";
const r = await eggDecide(f);
eggShow(f, r, null);
$("eggSummary").textContent = "";
}));
async function eggRunAll() {
const tb = $("eggTable").querySelector("tbody");
tb.innerHTML = "";
$("eggTable").hidden = false;
document.querySelectorAll(".eggthumb .stamp").forEach((x) => x.remove());
let ok = 0, ms = 0;
const rows = [];
for (let i = 0; i < EGG_PHOTOS.length; i++) {
const p = EGG_PHOTOS[i];
$("eggSummary").textContent = model ? `Checking ${i + 1} / ${EGG_PHOTOS.length}...` : "Loading the model...";
eggThumb(i)?.classList.add("busy");
const blob = await fetchBlob(p.file);
const r = await eggDecide(blob);
const pred = EGG.options[r.top].key;
stampEgg(i, pred, p.gold, r.probs[r.top]);
ok += pred === p.gold ? 1 : 0;
ms += r.totalMs;
rows.push({ file: p.file, gold: p.gold, pred, probs: r.probs, cos: r.cos, ms: r.totalMs });
tb.insertAdjacentHTML("beforeend", `
${esc(p.label)}
${esc(p.gold)}
${esc(pred)}
${(r.probs[0] * 100).toFixed(1)}%
${(r.probs[1] * 100).toFixed(1)}%
${pred === p.gold ? "yes" : "no"}
${r.totalMs.toFixed(0)}
`);
}
$("eggSummary").innerHTML = `Accuracy ${ok} / ${EGG_PHOTOS.length}. Mean ${(ms / EGG_PHOTOS.length).toFixed(0)} ms per photo on ${model.device === "webgpu" ? "WebGPU" : "WASM (CPU)"} (${esc(model.dtype)}), ${imageBudget()} image tokens.`;
const res = { ok, n: EGG_PHOTOS.length, meanMs: ms / EGG_PHOTOS.length, device: model.device, dtype: model.dtype, budget: imageBudget(), rows };
window.lastEgg = res;
return res;
}
$("eggRunAll").addEventListener("click", () => eggBusy(eggRunAll));
/* ------------------------------------------------------------------ live decision cards */
const VISION_TEMPLATES = [
{ title: "What kind of scene is this?", options: "animals: wild animals such as giraffes or elephants\nstreet: a city street with vehicles and buildings\npeople: people outdoors, walking or playing\nreceipt: a paper receipt or printed document\napp: a screenshot of a mobile phone app\nchart: a chart or data plot\nshapes: a 3D render of simple geometric objects\negg: an egg lit from behind in the dark" },
{ title: "Is a person in view?", options: "yes: a photo with a person or people in it\nno: a photo with no people, only objects, animals or graphics" },
{ title: "Is this egg good or bad?", context: "Candling photo: a light is shone through the egg in a dark room.", options: "good: Normal, healthy egg\nbad: Defective, spoiled or damaged egg" },
{ title: "What is the person holding?", options: "phone: a person holding a mobile phone\ncup: a person holding a cup or mug\nbook: a person holding a book or paper\nnothing: a person with empty hands" },
{ title: "Which hand gesture is shown?", options: "thumbs_up: a hand giving a thumbs up\nopen_palm: an open palm facing the camera\npeace: a hand making a peace sign\nno_hand: no hand visible" },
{ title: "What is the facial expression?", options: "smiling: a smiling face\nneutral: a neutral, calm face\nsurprised: a surprised face with open mouth" },
{ title: "Is the person wearing a safety helmet?", options: "helmet: a worker wearing a hard hat\nno_helmet: a person without a hard hat on their head" },
{ title: "Indoor or outdoor?", options: "indoor: an indoor scene inside a room\noutdoor: an outdoor scene under the open sky" },
{ title: "How bright is the scene?", options: "bright: a bright, well lit scene\ndim: a dim scene with low light\ndark: a very dark scene" },
];
const AUDIO_TEMPLATES = [
{ title: "What sound is this?", options: "dog: a dog barking\nspeech: a person speaking\nmusic: music playing\nmachine: machine noise, an engine or a motor\nbirds: birds chirping\nwater: running water, rain or waves" },
{ title: "Is someone speaking?", options: "yes: a person speaking words\nno: no speech, only other sounds or silence" },
{ title: "Is there an alarm or siren?", options: "alarm: an alarm, siren or beeping warning sound\nnormal: ordinary background sound" },
{ title: "Are hands clapping or knocking?", options: "clapping: hands clapping\nknocking: knocking on a door or table\nnone: no clapping or knocking" },
];
const MAX_CARDS = 4;
let cardSeq = 0;
const decks = { vision: [], audio: [] };
function makeCard(t, threshold) {
const n = parseOptions(t.options).length;
threshold = threshold ?? (n <= 2 ? 0.6 : 0.5);
return { id: ++cardSeq, title: t.title, context: t.context || "", optionsText: t.options, options: parseOptions(t.options), threshold, probs: null, n: 0, onDevice: 0, escalate: 0, editing: false };
}
decks.vision = [VISION_TEMPLATES[0], VISION_TEMPLATES[1], VISION_TEMPLATES[2]].map((t) => makeCard(t));
decks.audio = [AUDIO_TEMPLATES[0], AUDIO_TEMPLATES[1]].map((t) => makeCard(t));
let primaryId = { vision: decks.vision[0].id, audio: decks.audio[0].id };
const live = { running: false, token: 0, src: "demo", facing: "user", stream: null, fps: 0, lat: 0, lastDone: 0, audioCtx: null, analyser: null, ring: null, ringPos: 0, ringFilled: 0, fileEl: null };
const deckName = () => (live.src === "mic" || live.src === "sound" ? "audio" : "vision");
const deck = () => decks[deckName()];
function renderTemplates() {
const list = deckName() === "audio" ? AUDIO_TEMPLATES : VISION_TEMPLATES;
$("templates").innerHTML = list.map((t, i) => ``).join("");
$("templates").querySelectorAll("button").forEach((b) =>
b.addEventListener("click", () => {
if (deck().length >= MAX_CARDS) return flash(`At most ${MAX_CARDS} decisions at once. Remove one first.`);
deck().push(makeCard(list[+b.dataset.t]));
renderCards();
})
);
$("cardsTitle").textContent = deckName() === "audio" ? "Decisions on every sound window" : "Decisions on every frame";
}
function flash(msg) { $("cardsCount").textContent = msg; setTimeout(updateCount, 2500); }
function updateCount() { $("cardsCount").textContent = `${deck().length} / ${MAX_CARDS}, ${liveTrained() ? "one pass per card" : "one embedding scores all"}`; }
function renderCards() {
const d = deck();
if (!d.find((c) => c.id === primaryId[deckName()]) && d.length) primaryId[deckName()] = d[0].id;
$("cards").innerHTML = d
.map((c) => {
const prim = c.id === primaryId[deckName()];
return `