`;
}).join("");
}
// ------------------------------------------------------------------ Model settings (GET / POST /config, #564)
// A few documented keys of the run config (strata-.json), for every client, from the next start on. The
// server lists them, checks every value and keeps every other key of the file as it is.
let cfgKeys = [];
async function loadConfig() {
let r;
try { r = await fetch("config", {headers: headers()}); } catch (e) { return; }
if (!r.ok) { $("cfg-card").hidden = true; return; } // no run config, an older server, or no key yet
const c = await r.json();
cfgKeys = c.keys || [];
$("cfg-file").textContent = c.file || "";
$("cfg-form").innerHTML = cfgKeys.map((k, i) => {
const id = `cfg-${i}`, v = k.value;
let input;
if (k.kind === "bool" || k.kind === "enum") {
const opts = k.kind === "bool" ? [["true", "on"], ["false", "off"]] : k.choices.map((x) => [x, x]);
const cur = v == null ? "" : String(v);
input = ``;
} else {
const text = v == null ? "" : Array.isArray(v) ? v.join(", ") : String(v);
input = ``;
}
return `${input}`;
}).join("");
$("cfg-card").hidden = false;
}
function configValue(k, el) {
const s = el.value.trim();
if (s === "") return null;
if (k.kind === "bool") return s === "true";
if (k.kind === "number") return Number(s);
return s; // enum, or names (the server splits them at commas)
}
$("cfg-save").addEventListener("click", async () => {
const set = {};
cfgKeys.forEach((k, i) => {
const v = configValue(k, $(`cfg-${i}`));
const old = Array.isArray(k.value) ? k.value.join(", ") : k.value;
if (JSON.stringify(v) !== JSON.stringify(old ?? null)) set[k.key] = v;
});
if (!Object.keys(set).length) { $("cfg-msg").textContent = "Nothing changed."; return; }
try {
const r = await fetch("config", {method: "POST", headers: headers(true), body: JSON.stringify({set})});
const b = await r.json();
if (!r.ok) throw new Error((b.error || {}).message || `HTTP ${r.status}`);
$("cfg-msg").textContent = b.changed.length
? `Saved (${b.changed.join(", ")}); the earlier file is ${b.file}.bak. Start the model again to use it.` : "Nothing changed.";
loadConfig();
} catch (e) {
$("cfg-msg").textContent = "";
toast("error", "Not saved", String(e.message || e), 6000);
}
});
// ------------------------------------------------------------------ Markdown (escaped first, then formatted)
function inline(s) {
const codes = [];
s = s.replace(/`([^`\n]+)`/g, (_, c) => { codes.push(c); return `\u0000${codes.length - 1}\u0000`; });
s = esc(s)
.replace(/\*\*([^*\n]+)\*\*/g, "$1")
.replace(/(^|[^*\w])\*([^*\n]+)\*(?![*\w])/g, "$1$2")
.replace(/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g, '$1');
return s.replace(/\u0000(\d+)\u0000/g, (_, i) => `${esc(codes[+i])}`);
}
// An ```svg or ```html block that is complete gets a Preview button (serve/web/preview.js): the block's own code in a sandboxed
// frame, built when it is first opened and again when the theme changes. The state lives on the box (data-preview), so it
// resets if the answer is rebuilt. A page (html) can also be run WITH scripts, after a warning, one block at a time.
function pageTheme() {
const root = document.documentElement;
return {dark: root.dataset.theme === "dark", ink: getComputedStyle(root).getPropertyValue("--st-ink").trim()};
}
function fillPreview(fr, scripts, blank) {
const box = fr.closest(".st-code");
const doc = blank ? null : StrataPreview.previewDoc(fr.dataset.lang, box.querySelector("pre").textContent, scripts, pageTheme(), window);
const nf = StrataPreview.makeFrame(doc, {scripts, title: fr.title, lang: fr.dataset.lang});
fr.replaceWith(nf);
box.classList.toggle("st-code--run", !!(doc && scripts));
const rb = box.querySelector("[data-preview-scripts]");
if (rb) {
rb.setAttribute("aria-pressed", String(!!(doc && scripts)));
rb.setAttribute("aria-label", doc && scripts ? tr("preview.stopScripts", "Stop scripts") : tr("preview.runScripts", "Run scripts"));
}
}
function refreshPreviews() { for (const fr of document.querySelectorAll("iframe[data-opened]")) fillPreview(fr, fr.dataset.scripts === "1"); }
function codeBlock(lang, code, complete) {
const ok = complete && StrataPreview.canPreview(lang || "", code);
const kind = ok ? StrataPreview.kindOf(lang) : null;
const label = kind === "svg" ? tr("preview.showSvg", "Preview the picture") : tr("preview.showPage", "Preview the page");
const head = `
`;
}
function blocks(text) {
const out = [], lines = text.split("\n");
let para = [], list = null;
const flushPara = () => { if (para.length) out.push(`
${para.map(inline).join(" ")}
`); para = []; };
const flushList = () => { if (list) out.push(`<${list.tag}>${list.items.map((i) => `
${inline(i)}
`).join("")}${list.tag}>`); list = null; };
for (let i = 0; i < lines.length; i++) {
const l = lines[i];
let m;
if (!l.trim()) { flushPara(); flushList(); continue; }
if ((m = l.match(/^(#{1,6})\s+(.*)$/))) { flushPara(); flushList(); out.push(`<${m[1].length <= 2 ? "h3" : "h4"}>${inline(m[2])}${m[1].length <= 2 ? "h3" : "h4"}>`); continue; }
if (/^\s*([-*_])\s*\1\s*\1[\s\1]*$/.test(l)) { flushPara(); flushList(); out.push(""); continue; }
if ((m = l.match(/^>\s?(.*)$/))) { flushPara(); flushList(); out.push(`
${inline(m[1])}
`); continue; }
if (/^\s*\|.*\|\s*$/.test(l) && i + 1 < lines.length && /^\s*\|?[\s:-]+\|[\s|:-]*$/.test(lines[i + 1])) {
flushPara(); flushList();
const cells = (row) => row.trim().replace(/^\||\|$/g, "").split("|").map((c) => inline(c.trim()));
let html = `
${cells(l).map((c) => `
${c}
`).join("")}
`;
i += 2;
while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) html += `
${cells(lines[i++]).map((c) => `
${c}
`).join("")}
`;
i--;
out.push(html + "
");
continue;
}
if ((m = l.match(/^\s*(?:[-*+]|(\d+)[.)])\s+(.*)$/))) {
flushPara();
const tag = m[1] ? "ol" : "ul";
if (!list || list.tag !== tag) { flushList(); list = {tag, items: []}; }
list.items.push(m[2]);
continue;
}
if (list && /^\s{2,}\S/.test(l)) { list.items[list.items.length - 1] += " " + l.trim(); continue; }
flushList();
para.push(l);
}
flushPara(); flushList();
return out.join("");
}
function markdown(text) {
let html = "", rest = text;
for (;;) {
const m = rest.match(/(^|\n)```([^\n`]*)\n/);
if (!m) { html += blocks(rest); break; }
html += blocks(rest.slice(0, m.index));
rest = rest.slice(m.index + m[0].length);
const end = rest.match(/(^|\n)```[ \t]*(\n|$)/);
if (!end) { html += codeBlock(m[2].trim(), rest, false); break; } // still streaming: no preview of a half-written block
html += codeBlock(m[2].trim(), rest.slice(0, end.index), true);
rest = rest.slice(end.index + end[0].length);
}
return html;
}
// ------------------------------------------------------------------ Chat
// The sampling shown until the user changes it is the model card's thinking set. Untouched, the page sends NO sampling
// fields: the server picks the card's set for the request's thinking state (thinking 1.0 / 0.95 / 20, not thinking
// 0.7 / 0.8 / 20 with a presence penalty). Before 0.1.45 the page sent 0.6 itself; a stored 0.6 with the other two
// values untouched counts as "not set" too.
const DEFAULTS = {thinking: "high", temperature: 1.0, top_p: 0.95, top_k: 20, max: "", seed: "", show: true, esp: true, mcp: true, math: false,
chatList: false, chatEdit: false, whileBusy: "wait"};
const OLD_DEFAULT_TEMPERATURE = 0.6;
function samplingUntouched(s) {
const t = +s.temperature;
return (t === DEFAULTS.temperature || t === OLD_DEFAULT_TEMPERATURE) && +s.top_p === DEFAULTS.top_p && +s.top_k === DEFAULTS.top_k;
}
let settings = {...DEFAULTS, ...store.get("sampling", {})};
if (samplingUntouched(settings)) settings.temperature = DEFAULTS.temperature;
let messages = store.get("chat", []); // the open chat's messages (chats-ui.js: with the saved-chats list on, also that chat's own)
let attachments = []; // {name, url}
let busy = null; // {controller, msg, cut, cutAfterTool}
let pending = null; // a message parked while an answer is written: {text, images, files, mode}
function timeStr(t) { return new Date(t).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit"}); }
function msgEl(m, i) {
const el = document.createElement("div");
el.className = `st-msg st-msg--${m.role}`;
el.dataset.i = i;
if (m.role === "user") {
if (m.files && m.files.length) {
const wrap = document.createElement("div");
wrap.className = "msg-images";
for (const f of m.files) {
const c = document.createElement("span");
c.className = "chip";
c.innerHTML = icon("attach", "st-icon st-icon--sm");
c.append(f.name);
wrap.appendChild(c);
}
el.appendChild(wrap);
}
if (m.images && m.images.length) {
const wrap = document.createElement("div");
wrap.className = "msg-images";
for (const im of m.images) {
if (im.url) { const img = document.createElement("img"); img.src = im.url; img.alt = im.name || tr("chat.image", "image"); wrap.appendChild(img); }
else { const c = document.createElement("span"); c.className = "chip"; c.innerHTML = icon("image", "st-icon st-icon--sm"); c.append(im.name || tr("chat.image", "image")); wrap.appendChild(c); }
}
el.appendChild(wrap);
}
const b = document.createElement("div");
b.className = "st-bubble";
b.textContent = m.text;
el.appendChild(b);
const meta = document.createElement("div");
meta.className = "st-msg__meta";
meta.textContent = `${tr("chat.you", "You")} · ${timeStr(m.time)}`;
el.appendChild(meta);
} else {
el.innerHTML = `${icon("thinking", "st-icon st-icon--sm")}` +
`${icon("chevron", "st-icon st-icon--sm st-chev")}` +
`
` +
`
`;
updateAssistant(el, m, false);
}
const actions = msgActions(m, i); // edit / regenerate / rewind (chats-ui.js), when switched on
if (actions) el.appendChild(actions);
return el;
}
// One MCP tool call in the answer: a compact block (name, state, a one-line preview) that opens to the arguments and
// the result as the model read it. Its body is built only while open: a result can be 20,000 characters.
const TOOL_STATE = {writing: ["st-badge--reading", () => tr("tool.writing", "Writing")], running: ["st-badge--generating", () => tr("tool.running", "Running")],
done: ["", () => tr("tool.done", "Done")], error: ["st-badge--error", () => tr("tool.error", "Error")],
skipped: ["st-badge--queued", () => tr("tool.skipped", "Not run")]};
function toolHtml(t, k) {
const [cls, labelOf] = TOOL_STATE[t.state] || ["", () => t.state];
const label = labelOf();
const args = t.arguments == null ? "" : JSON.stringify(t.arguments, null, 2);
const preview = t.result != null ? t.result : args.replace(/\s+/g, " ");
let body = "";
if (t.open) {
body = `
`;
}
// Raster tool results are same-origin cached files; credentials stay in request headers.
const mediaBlobs = new Map();
let mediaEpoch = 0;
function clearToolMedia() {
mediaEpoch++;
for (const pending of mediaBlobs.values()) pending.then((url) => URL.revokeObjectURL(url), () => {});
mediaBlobs.clear();
}
window.addEventListener("pagehide", clearToolMedia);
window.addEventListener("pageshow", (event) => { if (event.persisted) hydrateToolImages(document); });
function safeToolMedia(url) { return typeof url === "string" && /^tool-media\/[0-9a-f]{64}\.(png|jpg|webp)$/.test(url); }
function toolImages(t) {
return (t.images || []).filter((im) => safeToolMedia(im.url)).map((im) =>
`` +
`Download image`).join("");
}
function hydrateToolImages(root) {
root.querySelectorAll("[data-tool-image]").forEach((img) => {
const url = img.dataset.toolImage, epoch = mediaEpoch;
if (!safeToolMedia(url)) return;
if (!mediaBlobs.has(url)) mediaBlobs.set(url, fetch(url, {headers: headers()}).then((r) => {
if (!r.ok) throw new Error("Image unavailable");
return r.blob();
}).then((b) => URL.createObjectURL(b)).catch((e) => {if (epoch === mediaEpoch) mediaBlobs.delete(url); throw e;}));
mediaBlobs.get(url).then((blob) => {
if (epoch !== mediaEpoch || !img.isConnected) return;
img.src = blob;
const a = img.closest("figure").querySelector("[data-tool-download]");
a.href = blob;
}).catch(() => { img.alt = "Image unavailable; try refreshing"; });
});
}
// the answer's text with the tool blocks where the model called them
// math (opt-in, serve/web/math.js): formulas become placeholders before the Markdown runs and are drawn after it
function answerMarkdown(text) {
return settings.math ? StrataMath.markdown(text, markdown) : markdown(text);
}
function answerHtml(m) {
if (!m.tools || !m.tools.length) return answerMarkdown(m.text || "");
let html = "", pos = 0;
m.tools.forEach((t, k) => {
const at = Math.min(Math.max(t.at || 0, pos), m.text.length);
if (at > pos) html += answerMarkdown(m.text.slice(pos, at));
pos = at;
html += toolHtml(t, k) + toolImages(t);
});
return html + answerMarkdown(m.text.slice(pos));
}
// a tool event from the stream (the `strata_mcp` field of a chunk)
function onTool(m, x) {
if (x.event === "limit") { m.limit = x.max_rounds; return; }
m.tools = m.tools || [];
let t = m.tools.find((y) => y.id === x.id);
if (!t) { t = {id: x.id, name: x.name, at: m.text.length, rat: m.reasoning.length, state: "writing"}; m.tools.push(t); }
if (x.event === "call") {
Object.assign(t, {name: x.name, server: x.server, tool: x.tool, arguments: x.arguments, round: x.round, state: "running"});
} else if (x.event === "result") {
Object.assign(t, {result: x.text, ok: x.ok, chars: x.chars, truncated: x.truncated, ms: x.ms, images: x.images || [], vision: x.vision === true,
state: x.skipped ? "skipped" : x.ok ? "done" : "error"});
}
}
function updateAssistant(el, m, streaming) {
const det = el.querySelector("details.think");
if (m.reasoning) {
det.hidden = false;
const thinkingNow = streaming && !m.text;
el.querySelector(".think-title").textContent = thinkingNow ? tr("think.now", "Thinking…") :
m.thinkSecs != null ? tr("think.for", "Thought for {s} s", {s: fmt(m.thinkSecs, 1)}) : tr("think.done", "Thoughts");
const body = el.querySelector(".thinking");
if (det.open || thinkingNow) body.textContent = m.reasoning;
else body.dataset.pending = "1";
// open while it streams (if wanted), closed once the answer starts - unless the user toggled it themselves
if (thinkingNow && settings.show && !det.dataset.touched && !det.open) { det._auto = true; det.open = true; }
if (!thinkingNow && det.open && !det.dataset.touched) { det._auto = true; det.open = false; }
}
const bubble = el.querySelector(".st-bubble");
if (m.error) {
bubble.innerHTML = ``;
bubble.firstChild.textContent = m.error;
} else if (!m.text && streaming && !(m.tools && m.tools.length)) {
bubble.innerHTML = m.reasoning ? `Writing` : ``;
} else {
bubble.innerHTML = answerHtml(m);
hydrateToolImages(bubble);
if (settings.math) StrataMath.hydrate(bubble);
if (streaming) bubble.classList.add("cursor"); else bubble.classList.remove("cursor");
}
el.querySelector(".meta-text").textContent = m.meta || (streaming ? "" : m.stopped ? tr("chat.stopped", "Stopped") : "");
el.querySelector("[data-msg-copy]").hidden = streaming || !m.text;
}
function renderChat() {
const chat = $("chat");
chat.querySelectorAll(".st-msg").forEach((e) => e.remove());
$("chat-empty").hidden = messages.length > 0;
messages.forEach((m, i) => chat.appendChild(msgEl(m, i)));
renderSidebar();
renderParent();
renderUndoBar();
scrollDown(true);
}
// Follow the answer while the reader has not left (#4014). Asking "am I within 120 px of the bottom?" on every frame pulled
// the view back after every wheel notch (a notch is about 100 px), so scrolling up during a long answer only worked by
// dragging the scrollbar. Now the reader's own input lets go (wheel up, a finger or a key moving up, the scrollbar), and a
// scroll back to the bottom follows again.
let stickToBottom = true, lastReaderInput = 0;
const FOLLOW_SLACK = 24, FAR_AWAY = 400, INPUT_WINDOW_MS = 400;
function followAfterScroll(distance, wasFollowing, msSinceInput) {
if (distance <= FOLLOW_SLACK) return true;
if (msSinceInput <= INPUT_WINDOW_MS || distance > FAR_AWAY) return false;
return wasFollowing;
}
function scrollDown(force) {
const s = $("chat-scroll");
if (force) stickToBottom = true;
if (stickToBottom) s.scrollTop = s.scrollHeight;
}
(function watchReader() {
const s = $("chat-scroll");
const touch = () => { lastReaderInput = Date.now(); };
s.addEventListener("wheel", (e) => { touch(); if (e.deltaY < 0 && s.scrollTop > 0) stickToBottom = false; }, {passive: true});
s.addEventListener("touchmove", touch, {passive: true});
s.addEventListener("pointerdown", touch, {passive: true});
s.addEventListener("keydown", (e) => {
touch();
if (["PageUp", "ArrowUp", "Home"].includes(e.key) && e.target === s && s.scrollTop > 0) stickToBottom = false;
});
s.addEventListener("scroll", () => {
stickToBottom = followAfterScroll(s.scrollHeight - s.scrollTop - s.clientHeight, stickToBottom, Date.now() - lastReaderInput);
}, {passive: true});
})();
$("chat").addEventListener("click", (e) => {
const cc = e.target.closest("[data-code-copy]");
if (cc) { copyText(cc.closest(".st-code").querySelector("pre").textContent, cc); return; }
// an svg/html block: flip between its code and its sandboxed preview. Closing the preview also turns scripts off.
const pv = e.target.closest("[data-preview-toggle]");
if (pv) {
const box = pv.closest(".st-code");
const on = box.dataset.preview === "true";
if (on) delete box.dataset.preview; else box.dataset.preview = "true";
pv.setAttribute("aria-pressed", String(!on));
pv.setAttribute("aria-label", on ? pv.dataset.previewLabel : tr("preview.showCode", "Show the code"));
const fr = box.querySelector("iframe");
if (on) fillPreview(fr, false, true);
else if (!fr.dataset.opened) fillPreview(fr, false);
return;
}
const rs = e.target.closest("[data-preview-scripts]");
if (rs) {
const fr = rs.closest(".st-code").querySelector("iframe");
const run = fr.dataset.scripts !== "1";
if (run && !confirm(tr("preview.confirm", "Run this code with scripts?\n\nIt runs in your browser, cut off from this chat and from the network, but it can still freeze the tab, and it is code the model wrote.\n\nOnly this block, and only until you close the preview."))) return;
fillPreview(fr, run);
return;
}
const mc = e.target.closest("[data-msg-copy]");
if (mc) { const i = +mc.closest(".st-msg").dataset.i; copyText(messages[i].text, mc); return; }
// a tool block: its open state lives in the message (the answer is rebuilt while it streams), so the click sets it
const sum = e.target.closest(".tool-call > summary");
if (sum) {
e.preventDefault();
const el = sum.closest(".st-msg"), m = messages[+el.dataset.i], t = m && m.tools && m.tools[+sum.parentElement.dataset.tool];
if (!t) return;
t.open = !t.open;
updateAssistant(el, m, !!busy && busy.msg === m);
}
});
$("chat").addEventListener("toggle", (e) => {
const d = e.target;
if (d.tagName !== "DETAILS" || !d.classList.contains("think")) return;
if (d._auto) { d._auto = false; return; } // our own open/close, not the user's
d.dataset.touched = "1";
const body = d.querySelector(".thinking");
if (d.open && body.dataset.pending) { body.textContent = messages[+d.closest(".st-msg").dataset.i].reasoning; delete body.dataset.pending; }
}, true);
function apiMessages() {
const out = [];
for (const m of messages) {
if (m.role === "user") {
const imgs = (m.images || []).filter((i) => i.url);
const text = userText(m);
out.push({role: "user", content: imgs.length ? [{type: "text", text},
...imgs.map((i) => ({type: "image_url", image_url: {url: i.url}}))] : text});
} else if (!(busy && busy.msg === m)) { // the answer being asked for now is not history yet
out.push(...assistantMessages(m));
}
}
return out;
}
// An answer that used MCP tools goes back as the model wrote it: per round the text before the calls, the calls and
// their results (as the model read them), then the rest - so the next question can build on what the tools found.
function assistantMessages(m) {
const ran = (m.tools || []).filter((t) => t.round != null && t.result != null && t.state !== "skipped");
// #1392: a turn with no answer text (only reasoning, a stop before the first content token, or an error) still goes
// back as an assistant turn, so the history keeps alternating and a reasoning model sees that it already answered.
// The server leaves such a turn out of the prompt itself (serve/frontend.py, #843); reasoning_content rides along.
if (!ran.length) {
const msg = {role: "assistant", content: m.text || ""};
if (!m.text && m.reasoning) msg.reasoning_content = m.reasoning;
return [msg];
}
const out = [];
let pos = 0;
for (const r of [...new Set(ran.map((t) => t.round))]) {
const calls = ran.filter((t) => t.round === r);
const at = Math.min(Math.max(pos, calls[0].at || 0), m.text.length);
out.push({role: "assistant", content: m.text.slice(pos, at).trim(),
tool_calls: calls.map((t) => ({id: t.id, type: "function", function: {name: t.name, arguments: JSON.stringify(t.arguments || {})}}))});
for (const t of calls) {
const pictures = t.vision ? (t.images || []).filter((im) => safeToolMedia(im.url)) : [];
const content = pictures.length ? [{type: "text", text: t.result}, ...pictures.map((im) =>
({type: "image_url", image_url: {url: "strata-tool-media:" + im.url.split("/").pop()}}))] : t.result;
out.push({role: "tool", tool_call_id: t.id, content});
}
pos = at;
}
const rest = m.text.slice(pos).trim();
if (rest) out.push({role: "assistant", content: rest});
return out;
}
function busyHint() {
const mode = settings.whileBusy;
return mode === "queue" ? tr("composer.hintQueue", "Enter sends when the answer is done")
: mode === "interject" ? tr("composer.hintInterject", "Enter stops the answer here and sends now") : "";
}
// While an answer is written, Send is off ("wait", as always) or parks the message ("queue", "interject": Chat settings)
const parksWhileBusy = () => settings.whileBusy === "queue" || settings.whileBusy === "interject";
function setBusy(on) {
$("stop-btn").hidden = !on;
$("send-btn").disabled = (on && !parksWhileBusy()) || !!panel;
$("input").disabled = !!panel;
$("composer-hint").textContent = panel ? tr("composer.finishOpen", "Save or cancel what is open above to continue")
: on ? busyHint() : tr("composer.newline", "Shift+Enter: new line");
if (settings.chatEdit) syncActions(); // the buttons follow the state: none under the answer being written
$("s-list").disabled = $("s-edit").disabled = !!busy || !!panel; // they change the messages on the screen
renderUndoBar();
renderPending();
}
// A message sent while an answer is being written (#4004). "queue": it waits and goes when the answer is done. "interject": the
// answer stops where it is (what is written stays, marked interrupted) and the message goes at once; if a tool is running, the
// tool finishes first. Only one message waits. Off by default: with "wait" the page does nothing, as before.
function park(p, own) {
if (!parksWhileBusy()) return;
if (pending) { toast("warn", tr("pending.one", "A message is already waiting"), tr("pending.oneText", "Take it back or wait until it is sent.")); return; }
pending = {...p, mode: settings.whileBusy};
if (own) { attachments = []; renderAttachments(); $("input").value = ""; autosize(); }
if (pending.mode === "interject") requestCut();
setBusy(!!busy);
}
function requestCut() {
if (!busy || busy.cut) return;
if ((busy.msg.tools || []).some((t) => t.state === "running")) { busy.cutAfterTool = true; return; } // let the tool finish
busy.cut = true;
busy.controller.abort();
}
function renderPending() {
let el = $("pending");
if (!pending) { if (el) el.remove(); return; }
if (!el) {
el = node("div", "pending");
el.id = "pending";
el.setAttribute("role", "status");
el.innerHTML = "" +
"";
el.querySelector("[data-pending-now]").onclick = pendingNow;
el.querySelector("[data-pending-back]").onclick = releasePending;
$("composer").before(el);
}
const quote = (pending.text || (pending.files[0] || pending.images[0] || {}).name || "").replace(/\s+/g, " ").slice(0, 70);
const text = !busy ? tr("pending.ready", "Not sent yet: “{text}”", {text: quote})
: pending.mode === "queue" ? tr("pending.queued", "Sends when this answer is done: “{text}”", {text: quote})
: busy.cutAfterTool ? tr("pending.afterTool", "Waiting for the tool to finish, then sending: “{text}”", {text: quote})
: tr("pending.cutting", "Stopping the answer, then sending: “{text}”", {text: quote});
el.querySelector(".pending__text").textContent = text;
const now = el.querySelector("[data-pending-now]");
now.textContent = busy ? tr("pending.sendNow", "Send now") : tr("pending.send", "Send");
now.hidden = !!busy && pending.mode === "interject"; // already on its way
el.querySelector("[data-pending-back]").textContent = tr("pending.takeBack", "Take back");
}
function pendingNow() {
if (!pending) return;
if (busy) { pending.mode = "interject"; requestCut(); setBusy(true); return; }
const p = pending;
pending = null;
setBusy(false);
send(p);
}
// the waiting message goes back into the message box (a chat switch or a new chat must not lose it)
function releasePending() {
if (!pending) return;
const p = pending;
pending = null;
if (!$("input").value.trim()) $("input").value = p.text;
else $("input").value = `${p.text}\n\n${$("input").value}`;
attachments = [...p.images, ...p.files, ...attachments];
renderAttachments(); autosize();
setBusy(!!busy);
}
// after an answer: an interrupted one sends an interjection, a finished one sends a queued message
function settlePending(cut, finished) {
if (!pending) return;
if ((pending.mode === "interject" && cut) || (pending.mode === "queue" && finished)) {
const p = pending;
pending = null;
setBusy(false);
send(p);
}
}
// the message box (or a parked message, `payload`) becomes a user turn and a reply is asked for
async function send(payload) {
const own = !payload;
const p = payload || {text: $("input").value.trim(), images: attachments.filter((a) => a.kind !== "file"),
files: attachments.filter((a) => a.kind === "file")};
if (!p.text && !p.images.length && !p.files.length) return;
if (panel) return; // something is open above (an edit): finish it first
if (busy) { park(p, own); return; }
clearUndo();
messages.push({role: "user", text: p.text, images: p.images, files: p.files, time: Date.now()});
if (own) {
attachments = [];
renderAttachments();
$("input").value = "";
autosize();
}
return generateReply();
}
// an answer for the messages as they are: the last one is a user turn
async function generateReply() {
const m = {role: "assistant", text: "", reasoning: "", time: Date.now()};
messages.push(m);
renderChat();
const el = $("chat").lastElementChild;
const controller = new AbortController();
busy = {controller, msg: m, cut: false, cutAfterTool: false};
setBusy(true);
paintLive();
const body = {model: health.model, messages: apiMessages(), stream: true,
reasoning_effort: settings.thinking};
if (!(settings.temperature > 0)) {
body.temperature = 0;
} else if (!samplingUntouched(settings)) {
Object.assign(body, {temperature: +settings.temperature, top_p: +settings.top_p, top_k: +settings.top_k});
}
if (settings.seed) body.seed = +settings.seed;
if (settings.max) body.max_tokens = +settings.max;
if (projectionLoaded()) body.experimental_speed_projection = !!settings.esp;
if (settings.mcp !== false && mcpInfo.tools > 0) body.strata_mcp = true; // this server may run MCP tools for it
let firstAt = null, thinkStart = null, usage = null, frame = 0;
const paint = () => { frame = 0; updateAssistant(el, m, true); scrollDown(); };
try {
const r = await fetch("v1/chat/completions", {method: "POST", headers: headers(true), body: JSON.stringify(body),
signal: controller.signal});
if (!r.ok) {
let msg = `HTTP ${r.status}`;
try { msg = (await r.json()).error.message || msg; } catch (e) { /* not json */ }
if (r.status === 401) msg = tr("toast.keyNeeded", "This server needs an API key: add it under About > Settings.");
throw new Error(msg);
}
const reader = r.body.getReader(), dec = new TextDecoder();
let buf = "";
for (;;) {
const {value, done} = await reader.read();
if (done) break;
buf += dec.decode(value, {stream: true});
let nl;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (!line.startsWith("data:")) continue; // ": keep-alive" comments while a long prompt is read
const data = line.slice(5).trim();
if (data === "[DONE]") continue;
let j;
try { j = JSON.parse(data); } catch (e) { continue; }
if (j.error) throw new Error(j.error.message || tr("toast.engineError", "the engine reported an error"));
if (j.usage) usage = j.usage;
if (j.strata_mcp) {
onTool(m, j.strata_mcp);
// an interjection waited for a running tool: it has its result now, so the answer can stop
if (busy.cutAfterTool && !busy.cut && !(m.tools || []).some((t) => t.state === "running")) { busy.cut = true; controller.abort(); }
}
const d = (j.choices && j.choices[0] && j.choices[0].delta) || {};
const lastTool = m.tools && m.tools.length ? m.tools[m.tools.length - 1] : null; // a new round after a tool
if (d.reasoning_content) {
if (!firstAt) firstAt = performance.now();
if (!thinkStart) thinkStart = performance.now();
if (lastTool && m.reasoning && lastTool.rat === m.reasoning.length) m.reasoning += "\n\n";
m.reasoning += d.reasoning_content;
}
if (d.content) {
if (!firstAt) firstAt = performance.now();
if (thinkStart && m.thinkSecs == null) m.thinkSecs = (performance.now() - thinkStart) / 1000;
if (lastTool && m.text && lastTool.at === m.text.length) m.text += "\n\n";
m.text += d.content;
}
if (!frame) frame = requestAnimationFrame(paint);
}
}
} catch (e) {
if (e.name === "AbortError") m.stopped = true;
else { m.error = e.message || String(e); toast("error", tr("toast.requestFailed", "The request failed"), m.error, 6000); }
}
const cut = busy.cut; // an interjection ended it: kept as written, marked interrupted
if (cut) m.interrupted = true;
if (thinkStart && m.thinkSecs == null) m.thinkSecs = (performance.now() - thinkStart) / 1000;
const n = usage ? usage.completion_tokens : null;
const ended = cut ? tr("chat.interruptedLower", "interrupted") : tr("chat.stoppedLower", "stopped");
if (n && firstAt) {
const secs = (performance.now() - firstAt) / 1000;
m.meta = tr("chat.tokens", "{n} tokens", {n: fmt(n)}) + (secs > 0.25 ? ` · ${fmt(n / secs, 1)} tok/s` : "") + (m.stopped ? ` · ${ended}` : "") +
(projectionLoaded() ? (settings.esp ? ` · ${tr("chat.projectionOn", "projection on")}` : ` · ${tr("chat.projectionOff", "projection off")}`) : "");
} else if (m.stopped) {
m.meta = cut ? tr("chat.interrupted", "Interrupted") : tr("chat.stopped", "Stopped");
}
for (const t of m.tools || []) if (t.state === "writing" || t.state === "running") { t.state = "skipped"; t.ms = null; }
const ran = (m.tools || []).filter((t) => t.state === "done" || t.state === "error").length;
if (ran) m.meta = `${m.meta ? `${m.meta} · ` : ""}${tr("chat.toolCalls", {one: "{n} tool call", other: "{n} tool calls"}, {n: ran})}`;
if (m.limit) m.meta = `${m.meta || ""} · ${tr("chat.toolLimit", "stopped at the limit of {n} tool rounds (mcp.max_rounds)", {n: m.limit})}`;
busy = null;
setBusy(false);
paintLive();
if (frame) cancelAnimationFrame(frame);
updateAssistant(el, m, false);
saveChat();
scrollDown();
settlePending(cut, !m.stopped && !m.error);
}
$("composer").onsubmit = (e) => { e.preventDefault(); send(); };
$("stop-btn").onclick = () => { if (busy) busy.controller.abort(); };
$("input").addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); send(); }
});
function autosize() { const t = $("input"); t.style.height = "auto"; t.style.height = `${Math.min(t.scrollHeight, innerHeight * 0.4)}px`; }
$("input").addEventListener("input", autosize);
// one chat, as before: New chat clears it, with an Undo (with the saved-chats list on, its own New chat button does this job)
$("new-btn").onclick = () => {
if (busy) { stillWriting(); return; }
if (panel) { closePanel(); }
clearUndo();
releasePending();
if (!messages.length) return;
const backup = messages;
clearToolMedia();
messages = [];
saveChat();
renderChat();
toast("info", tr("chat.newToast", "New chat"), tr("chat.clearedToast", "The last one was cleared."), 6000, {label: tr("undo", "Undo"), run: () => {
if (busy || messages.length) return; // a new question since: the cleared chat is not put back over it
messages = backup; saveChat(); renderChat();
}});
};
$("export-btn").onclick = () => {
if (!messages.length) { toast("info", tr("export.nothing", "Nothing to save yet")); return; }
const tools = (m) => (m.tools || []).filter((t) => t.result != null).map((t) =>
`Tool ${t.server ? `${t.server} / ` : ""}${t.tool || t.name}${t.ok ? "" : " (error)"}\n\n` +
`\`\`\`json\n${JSON.stringify(t.arguments || {}, null, 2)}\n\`\`\`\n\n\`\`\`\n${t.result}\n\`\`\`\n\n\n\n`).join("");
const md = messages.map((m) => m.role === "user" ? `## You\n\n${m.text}\n` :
`## ${health.model}\n\n${m.reasoning ? `Thinking\n\n${m.reasoning}\n\n\n\n` : ""}${tools(m)}${m.text || m.error || ""}\n`).join("\n");
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([md], {type: "text/markdown"}));
a.download = `strata-chat-${new Date().toISOString().slice(0, 16).replace(/[:T]/g, "-")}.md`;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 5000);
};
// pictures and text files: the attach button, dropping them on the chat, or pasting a picture (issue #30)
const TEXT_EXT = /\.(txt|md|markdown|rst|tex|py|pyi|ipynb|js|mjs|cjs|ts|tsx|jsx|vue|svelte|json|jsonl|csv|tsv|log|ya?ml|toml|ini|cfg|conf|env|xml|html?|css|scss|less|c|cc|cpp|cxx|h|hh|hpp|cu|cuh|rs|go|java|kt|kts|swift|rb|php|pl|lua|r|jl|scala|sql|sh|bash|zsh|fish|ps1|psm1|bat|cmd|diff|patch|gradle|cmake|mk|dockerfile|gitignore|proto|graphql)$/i;
const MAX_TEXT_FILE = 512 * 1024;
function isTextFile(f) {
return f.type.startsWith("text/") || /json|xml|javascript|yaml|toml|x-sh|x-python/.test(f.type) ||
TEXT_EXT.test(f.name) || /(^|[\\/])(makefile|dockerfile|readme|license)$/i.test(f.name);
}
function addFiles(files) {
for (const f of files) {
if (f.type.startsWith("image/")) {
if (!health.images) { toast("warn", tr("file.picturesOff", "Pictures are off"), tr("file.picturesOffText", "This model was set up for text only.")); continue; }
if (f.size > 20e6) { toast("warn", tr("file.pictureBig", "Picture too large"), tr("file.pictureBigText", "{name} is over 20 MB.", {name: f.name})); continue; }
const r = new FileReader();
r.onload = () => { attachments.push({kind: "image", name: f.name || tr("file.pasted", "pasted image"), url: r.result}); renderAttachments(); };
r.readAsDataURL(f);
continue;
}
if (!isTextFile(f)) { toast("warn", tr("file.notText", "Not a text file"), health.images ? tr("file.notTextPictures", "{name}: attach text files (code, notes, logs, data) or pictures.", {name: f.name})
: tr("file.notTextOnly", "{name}: attach text files (code, notes, logs, data).", {name: f.name})); continue; }
if (f.size > MAX_TEXT_FILE) { toast("warn", tr("file.big", "File too large"), tr("file.bigText", "{name} is over 512 KB.", {name: f.name})); continue; }
const r = new FileReader();
r.onload = () => {
const text = String(r.result);
if (text.includes("\u0000")) { toast("warn", tr("file.notText", "Not a text file"), tr("file.binaryText", "{name} looks like a binary file.", {name: f.name})); return; }
attachments.push({kind: "file", name: f.name, text});
renderAttachments();
};
r.readAsText(f);
}
}
// a file's text in the message, fenced with more backticks than it contains itself
function fileBlock(f) {
const longest = Math.max(2, ...(f.text.match(/`+/g) || []).map((s) => s.length));
const fence = "`".repeat(longest + 1);
return `File: ${f.name}\n${fence}\n${f.text}\n${fence}`;
}
function userText(m) {
const files = (m.files || []).filter((f) => f.text != null);
return [m.text, ...files.map(fileBlock)].filter((s) => s).join("\n\n");
}
function renderAttachments() {
const box = $("attachments");
box.hidden = !attachments.length;
box.innerHTML = "";
attachments.forEach((a, i) => {
const c = document.createElement("span");
c.className = "chip";
c.innerHTML = icon(a.kind === "file" ? "attach" : "image", "st-icon st-icon--sm");
c.append(a.name);
const x = document.createElement("button");
x.type = "button"; x.className = "st-btn st-btn--icon"; x.setAttribute("aria-label", tr("file.remove", "Remove"));
x.innerHTML = icon("trash");
x.onclick = () => { attachments.splice(i, 1); renderAttachments(); };
c.appendChild(x);
box.appendChild(c);
});
}
$("attach-btn").onclick = () => $("file").click();
// drop files on the chat or the message box
for (const id of ["chat", "composer"]) {
const el = $(id);
el.addEventListener("dragover", (e) => {
if (![...(e.dataTransfer || {}).types || []].includes("Files")) return;
e.preventDefault();
$("composer").classList.add("dragging");
});
el.addEventListener("dragleave", () => $("composer").classList.remove("dragging"));
el.addEventListener("drop", (e) => {
$("composer").classList.remove("dragging");
if (!e.dataTransfer || !e.dataTransfer.files.length) return;
e.preventDefault();
addFiles(e.dataTransfer.files);
$("input").focus();
});
}
$("file").onchange = () => { addFiles($("file").files); $("file").value = ""; };
$("input").addEventListener("paste", (e) => {
if (!health.images) return;
const files = [...(e.clipboardData || {}).files || []].filter((f) => f.type.startsWith("image/"));
if (files.length) { e.preventDefault(); addFiles(files); }
});
// ------------------------------------------------------------------ the chat settings drawer
function openDrawer(open) {
$("drawer").dataset.open = String(open);
$("drawer").setAttribute("aria-hidden", String(!open));
$("scrim").hidden = !open;
if (open) { loadDrawer(); loadShared(); loadMcp(); }
}
const checked = (id) => $(id).getAttribute("aria-checked") === "true";
const segValue = (id) => { const b = [...$(id).children].find((x) => x.getAttribute("aria-checked") === "true"); return b ? b.dataset.v : null; };
function loadDrawer(s = settings) {
for (const b of $("s-thinking").children) b.setAttribute("aria-checked", String(b.dataset.v === s.thinking));
$("s-temp").value = s.temperature; $("s-topp").value = s.top_p; $("s-topk").value = s.top_k;
$("s-max").value = s.max; $("s-seed").value = s.seed;
$("s-math").setAttribute("aria-checked", String(!!s.math));
$("s-show").setAttribute("aria-checked", String(!!s.show));
$("s-esp").setAttribute("aria-checked", String(s.esp !== false));
$("esp-row").hidden = !projectionLoaded();
$("s-mcp").setAttribute("aria-checked", String(s.mcp !== false));
$("s-share").setAttribute("aria-checked", String(sharedOn));
$("s-list").setAttribute("aria-checked", String(!!s.chatList));
$("s-edit").setAttribute("aria-checked", String(!!s.chatEdit));
for (const b of $("s-busy").children) b.setAttribute("aria-checked", String(b.dataset.v === (s.whileBusy || "wait")));
outputs();
}
// "Use for other apps too": the server keeps these settings as every client's defaults (GET/POST /settings)
let sharedOn = false;
async function loadShared() {
try {
const r = await fetch("settings", {headers: headers()});
if (r.ok) sharedOn = !!(await r.json()).shared;
} catch (e) { /* an older server: the switch just stays off */ }
$("s-share").setAttribute("aria-checked", String(sharedOn));
}
function sharedDefaults(s) {
const d = {reasoning_effort: s.thinking};
if (!(+s.temperature > 0)) d.temperature = 0;
else if (!samplingUntouched(s)) Object.assign(d, {temperature: +s.temperature, top_p: +s.top_p, top_k: +s.top_k});
if (s.seed) d.seed = +s.seed;
if (s.max) d.max_tokens = +s.max;
if (projectionLoaded()) d.experimental_speed_projection = s.esp !== false;
return d;
}
async function saveShared(on, s) {
const r = await fetch("settings", {method: "POST", headers: headers(true),
body: JSON.stringify({defaults: on ? sharedDefaults(s) : null})});
if (!r.ok) {
let msg = `HTTP ${r.status}`;
try { msg = (await r.json()).error.message || msg; } catch (e) { /* not json */ }
throw new Error(msg);
}
sharedOn = !!(await r.json()).shared;
}
// the engine was started with the experimental-speed-projection control vector (INFO cvec=...)
function projectionLoaded() {
const c = lastMetrics && lastMetrics.engine ? lastMetrics.engine.cvec : 0;
return !!c && c !== "0";
}
function outputs() {
const t = +$("s-temp").value;
$("o-temp").textContent = t === 0 ? tr("drawer.greedy", "0 · greedy") : t.toFixed(2);
$("o-topp").textContent = (+$("s-topp").value).toFixed(2);
$("o-topk").textContent = $("s-topk").value;
const sel = segValue("s-thinking");
$("o-thinking").textContent = sel ? {none: tr("drawer.thinkNone", "answers right away"), low: tr("drawer.thinkLow", "short"),
medium: tr("drawer.thinkMedium", "medium"), high: tr("drawer.thinkHigh", "thorough (default)")}[sel] : "";
const busyMode = segValue("s-busy");
$("o-busy").textContent = {wait: tr("drawer.busyWaitNote", "Send is off until the answer is done, as before."),
queue: tr("drawer.busyQueueNote", "Your message waits and goes as soon as the answer is done."),
interject: tr("drawer.busyInterjectNote", "The answer stops where it is (what is written stays) and your message goes at once. A tool that is running finishes first.")}[busyMode] || "";
for (const id of ["s-topp", "s-topk"]) $(id).disabled = t === 0;
}
for (const b of $("s-thinking").children) b.onclick = () => { for (const x of $("s-thinking").children) x.setAttribute("aria-checked", String(x === b)); outputs(); };
for (const b of $("s-busy").children) b.onclick = () => { for (const x of $("s-busy").children) x.setAttribute("aria-checked", String(x === b)); outputs(); };
for (const id of ["s-temp", "s-topp", "s-topk"]) $(id).oninput = outputs;
for (const id of ["s-math", "s-show", "s-esp", "s-mcp", "s-share", "s-list", "s-edit"]) {
$(id).onclick = () => $(id).setAttribute("aria-checked", String($(id).getAttribute("aria-checked") !== "true"));
}
$("s-reset").onclick = () => loadDrawer(DEFAULTS);
$("s-apply").onclick = async () => {
const prev = settings;
// the list and the edit controls change the messages on the screen: not while an answer is written or something is open
const locked = !!busy || !!panel;
settings = {thinking: segValue("s-thinking") || "high", temperature: +$("s-temp").value, top_p: +$("s-topp").value,
top_k: +$("s-topk").value, max: $("s-max").value.trim(), seed: $("s-seed").value.trim(),
math: checked("s-math"), show: checked("s-show"), esp: checked("s-esp"), mcp: checked("s-mcp"),
chatList: locked ? !!prev.chatList : checked("s-list"), chatEdit: locked ? !!prev.chatEdit : checked("s-edit"),
whileBusy: segValue("s-busy") || "wait"};
store.set("sampling", settings);
StrataMath.reset(); // math on or off: every answer is drawn again
if (settings.chatList !== !!prev.chatList) await setChatList(settings.chatList, true);
if (settings.chatEdit !== !!prev.chatEdit) { clearUndo(); syncActions(); }
if (settings.whileBusy === "wait" && pending) releasePending(); // "wait" parks nothing: a waiting message goes back to the box
setBusy(!!busy);
for (const el of $("chat").querySelectorAll(".st-msg--assistant")) {
const m = messages[+el.dataset.i];
updateAssistant(el, m, !!busy && busy.msg === m); // the element send() holds stays the same while an answer streams
}
const share = checked("s-share");
openDrawer(false);
if (share || sharedOn) {
try {
await saveShared(share, settings);
toast("success", tr("drawer.saved", "Chat settings saved"), share ? tr("drawer.savedShared", "Other apps (omp, API clients) use these settings from their next request.")
: tr("drawer.savedOwn", "Other apps use their own settings again."));
} catch (e) {
toast("error", tr("drawer.savedHere", "Saved here, but not for other apps"), e.message, 6000);
}
return;
}
toast("success", tr("drawer.saved", "Chat settings saved"), settings.temperature === 0 ? tr("drawer.savedGreedy", "Greedy: the same question gives the same answer.") : "");
};
$("sampling-btn").onclick = () => openDrawer(true);
$("drawer-close").onclick = () => openDrawer(false);
$("scrim").onclick = () => openDrawer(false);
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && $("drawer").dataset.open === "true") openDrawer(false); });
// ------------------------------------------------------------------ language (serve/web/i18n.js)
// The user's own choice, kept in this browser: English until they pick another. /?lang=de shows one for this visit only.
const urlLang = new URLSearchParams(location.search).get("lang");
$("lang").innerHTML = StrataI18n.LANGUAGES.map(([code, name]) => ``).join("");
function showLanguage() {
$("lang").value = StrataI18n.lang;
renderEmptyChat();
setSidebar(sidebarOpen, false);
outputs();
renderChat();
setBusy(!!busy);
if (lastMetrics) render(lastMetrics);
}
$("lang").onchange = async () => {
store.set("lang", $("lang").value);
await StrataI18n.setLanguage($("lang").value);
showLanguage();
};
// ------------------------------------------------------------------ start
async function start() {
await StrataI18n.setLanguage(urlLang || store.get("lang", "en"));
$("lang").value = StrataI18n.lang;
renderEmptyChat();
initChats();
if (settings.chatList) await setChatList(true, false); // the saved-chats list is read before the first draw
setBusy(false);
renderChat();
// /?q=... fills the question in and focuses the box; it is never sent from the address (#4221): any page can link here,
// and a send would go out with the API key and the MCP tools saved in this browser. The person presses Send.
const startQuestion = new URLSearchParams(location.search).get("q");
if (startQuestion) {
history.replaceState(null, "", location.pathname + location.hash);
$("input").value = startQuestion;
autosize();
}
loadHealth().then(loadMcp);
showTab(location.hash.slice(1) || "chat");
if (startQuestion && tab === "chat") $("input").focus();
poll();
requestAnimationFrame(fitHeader);
}
start();
// ------------------------------------------------------------------ images (POST /v1/images/generations)
$("img-form").onsubmit = async (ev) => {
ev.preventDefault();
const prompt = $("img-prompt").value.trim();
if (!prompt) return;
const body = {prompt, size: $("img-size").value, response_format: "b64_json"};
if ($("img-seed").value !== "") body.seed = Number($("img-seed").value);
imageBusy = true;
$("img-go").disabled = true;
paintLive();
const t0 = performance.now();
$("img-hint").textContent = "Generating\u2026 (a minute or more on a small GPU)";
try {
const r = await fetch("v1/images/generations", {method: "POST", headers: headers(true), body: JSON.stringify(body)});
const j = await r.json();
if (!r.ok) throw new Error((j.error && j.error.message) || r.statusText);
for (const d of j.data) {
const fig = document.createElement("figure");
const img = document.createElement("img");
img.src = "data:image/png;base64," + d.b64_json;
img.alt = prompt;
const cap = document.createElement("figcaption");
cap.textContent = `${j.size}, seed ${d.seed}, ${((performance.now() - t0) / 1000).toFixed(0)} s: ${prompt}`;
fig.append(img, cap);
$("img-results").prepend(fig);
}
$("img-hint").textContent = "Done. Right-click an image to save it.";
} catch (e) {
$("img-hint").textContent = "";
toast("error", "No image", String(e.message || e), 8000);
} finally {
imageBusy = false;
$("img-go").disabled = false;
paintLive();
}
};