okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0215-webspec: web page: the About card's "MTP drafts up to N tokens" only when the MTP drafts (#5080)d8124515a

main
91.1 KiB1629 linesraw
1// serve/web/app.js - the Strata web app: Chat, Monitor, About. No framework, no network beyond this server.
2// The Monitor tab rebuilds PR #22's dashboard idea (code-martin) on the server's own /metrics.
3"use strict";
4
5const $ = (id) => document.getElementById(id);
6const SPRITE = "web/sprite.svg";
7const icon = (name, cls = "st-icon") => `<svg class="${cls}" aria-hidden="true"><use href="${SPRITE}#i-${name}"/></svg>`;
8const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}[c]));
9const fmt = (n, d = 0) => (n == null || Number.isNaN(n) ? "–" : Number(n).toLocaleString(undefined, {maximumFractionDigits: d, minimumFractionDigits: d}));
10const kfmt = (n) => (n == null ? "–" : n >= 1000 ? `${fmt(n / 1000, n >= 10000 ? 0 : 1)}k` : fmt(n));
11// a context size: 32768 -> "32K" (powers of two), else like kfmt
12const ctxfmt = (n) => (n && n % 1024 === 0 ? `${fmt(n / 1024)}K` : kfmt(n));
13const gb = (b, d = 1) => (b == null ? "–" : fmt(b / 1073741824, d));   // memory: binary GB, as Windows shows it
14
15const store = {
16  get(k, d) { try { const v = localStorage.getItem("strata." + k); return v === null ? d : JSON.parse(v); } catch (e) { return d; } },
17  set(k, v) { try { localStorage.setItem("strata." + k, JSON.stringify(v)); return true; } catch (e) { return false; } },
18};
19
20// ------------------------------------------------------------------ toasts
21function toast(kind, title, text = "", ms = 3500, action = null) {
22  const names = {info: "info", success: "check", warn: "warning", error: "error"};
23  const el = document.createElement("div");
24  el.className = `st-toast st-toast--${kind}`;
25  el.innerHTML = `${icon(names[kind] || "info")}<div><div class="st-toast__title"></div><div class="t-text"></div></div>`;
26  el.querySelector(".st-toast__title").textContent = title;
27  el.querySelector(".t-text").textContent = text;
28  if (action) {
29    const b = document.createElement("button");
30    b.className = "st-btn st-btn--secondary";
31    b.style.height = "32px";
32    b.style.marginLeft = "auto";
33    b.textContent = action.label;
34    b.onclick = () => { action.run(); el.remove(); };
35    el.appendChild(b);
36  }
37  $("toasts").appendChild(el);
38  setTimeout(() => el.remove(), ms);
39}
40
41async function copyText(text, btn) {
42  try {
43    await navigator.clipboard.writeText(text);
44  } catch (e) {                                   // http on another host: no async clipboard
45    const ta = document.createElement("textarea");
46    ta.value = text; document.body.appendChild(ta); ta.select(); document.execCommand("copy"); ta.remove();
47  }
48  if (btn) {
49    const use = btn.querySelector("use");
50    use.setAttribute("href", `${SPRITE}#i-check`);
51    setTimeout(() => use.setAttribute("href", `${SPRITE}#i-copy`), 1500);
52  }
53  toast("success", tr("toast.copied", "Copied to clipboard"), "", 1800);
54}
55
56// ------------------------------------------------------------------ theme and tabs
57// the system's theme until the user picks one (only a click is saved)
58function setTheme(t, save) {
59  document.documentElement.dataset.theme = t;
60  if (save) try { localStorage.setItem("strata.theme", t); } catch (e) { /* ignore */ }
61  $("theme-icon").setAttribute("href", `${SPRITE}#i-${t === "dark" ? "sun" : "moon"}`);
62  $("dark-toggle").setAttribute("aria-checked", String(t === "dark"));
63  refreshPreviews();                                  // the preview frames carry the page's colours
64}
65const flipTheme = () => setTheme(document.documentElement.dataset.theme === "dark" ? "light" : "dark", true);
66$("theme-btn").onclick = flipTheme;
67$("dark-toggle").onclick = flipTheme;
68setTheme(document.documentElement.dataset.theme || "light", false);
69matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (e) => {
70  let saved = null;
71  try { saved = localStorage.getItem("strata.theme"); } catch (err) { /* ignore */ }
72  if (!saved) setTheme(e.matches ? "dark" : "light", false);
73});
74
75let tab = "chat";
76function showTab(name) {
77  tab = ["chat", "images", "monitor", "about"].includes(name) ? name : "chat";
78  for (const b of document.querySelectorAll(".st-tab")) b.setAttribute("aria-selected", String(b.dataset.tab === tab));
79  for (const v of ["chat", "images", "monitor", "about"]) $(`view-${v}`).hidden = v !== tab;
80  if (tab === "images") $("img-prompt").focus();
81  if (location.hash.slice(1) !== tab) history.replaceState(null, "", tab === "chat" ? location.pathname : `#${tab}`);
82  if (tab === "chat") $("input").focus();
83  if (tab === "monitor") loadMcp();
84  if (tab === "about") loadConfig();
85  if (lastMetrics) render(lastMetrics);
86}
87for (const b of document.querySelectorAll(".st-tab")) b.onclick = () => showTab(b.dataset.tab);
88window.addEventListener("hashchange", () => showTab(location.hash.slice(1)));
89
90// ------------------------------------------------------------------ server access
91let apiKey = store.get("apikey", "");
92function headers(json = false) {
93  const h = {};
94  if (apiKey) h.Authorization = "Bearer " + apiKey;
95  if (json) h["Content-Type"] = "application/json";
96  return h;
97}
98$("api-key").value = apiKey;
99function saveApiKey(notify = false) {
100  apiKey = $("api-key").value.trim();                // usable even when browser storage is blocked or full
101  const saved = store.set("apikey", apiKey);
102  if (notify) {
103    if (saved) toast("success", "API key saved", "Kept in this browser only.");
104    else toast("warn", "API key used for this page only", "Browser storage is unavailable. Enter it again after reloading.");
105  }
106}
107$("api-key").oninput = () => saveApiKey();
108$("api-key").onchange = () => saveApiKey(true);
109
110let health = {model: "strata", images: false, max_context: 0};
111// the texts that depend on what this server offers: the empty chat's line and the attach button's hint
112function renderEmptyChat() {
113  $("attach-btn").title = health.images ? tr("composer.attachPictures", "Attach a text file or a picture (or drop it here)")
114                                        : tr("composer.attach", "Attach a text file (or drop it here)");
115  $("chat-empty-sub").textContent = tr("chat.emptyModel", "{model} runs on this PC. Nothing leaves it.", {model: health.model});
116}
117async function loadHealth() {
118  try {
119    health = await (await fetch("health")).json();
120    renderEmptyChat();
121    $("tab-btn-images").hidden = !health.image_generation;
122    if (location.hash === "#images" && health.image_generation) showTab("images");
123  } catch (e) {
124    setTimeout(loadHealth, 2000);
125  }
126}
127
128// ------------------------------------------------------------------ Monitor
129const METRICS = [
130  {key: "speed", label: "Speed", icon: "gauge", unit: "t/s", series: "tok_s"},
131  {key: "gpu", label: "GPU load", icon: "gpu", unit: "%", series: "gpu_util", max: 100},
132  {key: "vram", label: "VRAM", icon: "layers", unit: "GB", series: "gpu_mem_used"},
133  {key: "temp", label: "GPU temp", icon: "thermometer", unit: "°C", series: "gpu_temp", tone: "warn"},
134  {key: "power", label: "Power", icon: "bolt", unit: "W", series: "gpu_power"},
135  {key: "pcie", label: "PCIe", icon: "link", unit: "", series: "gpu_pcie_rx_mb", tone: "info"},
136  {key: "cpu", label: "CPU", icon: "cpu", unit: "%", series: "cpu", max: 100},
137  {key: "disk", label: "Disk read", icon: "disk", unit: "MB/s", series: "disk_read_mb", tone: "info"},
138];
139$("metrics").innerHTML = METRICS.map((m) => `
140  <div class="st-card metric-card"><div class="st-metric">
141    <span class="st-metric__label">${icon(m.icon, "st-icon st-icon--sm")}${esc(m.label)}</span>
142    ${m.key === "speed" ? `<div class="speed-values">
143      <div><span class="st-metric__value" id="mv-speed">-</span><span class="st-metric__sub" id="ms-speed">Decode</span></div>
144      <div class="speed-prefill"><span class="st-metric__value" id="mv-prefill">-</span><span class="st-metric__sub" id="ms-prefill">Prefill</span></div>
145    </div>` : `<span class="st-metric__value" id="mv-${m.key}">–</span>
146    <span class="st-metric__sub" id="ms-${m.key}"></span>`}
147    <svg class="st-metric__spark" id="sp-${m.key}" viewBox="0 0 100 32" preserveAspectRatio="none"${m.tone ? ` data-tone="${m.tone}"` : ""}>
148      <path class="area" fill="currentColor" opacity=".12"/><path class="line" fill="none" stroke="currentColor"
149      stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round" vector-effect="non-scaling-stroke"/>
150      ${m.key === "speed" ? `<g id="sp-prefill" class="speed-prefill"><path class="area" fill="currentColor" opacity=".12"/>
151        <path class="line" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"
152        stroke-linecap="round" vector-effect="non-scaling-stroke"/></g>` : ""}</svg>
153  </div></div>`).join("");
154
155function spark(id, values, max) {
156  const svg = $(id);
157  const v = (values || []).map((x) => (x == null ? 0 : x));
158  if (v.length < 2) { svg.querySelector(".line").setAttribute("d", ""); svg.querySelector(".area").setAttribute("d", ""); return; }
159  const top = Math.max(max || 0, ...v, 1);
160  const pts = v.map((x, i) => [(i / (v.length - 1)) * 100, 30 - (x / top) * 26]);
161  const line = pts.map((p, i) => `${i ? "L" : "M"}${p[0].toFixed(2)},${p[1].toFixed(2)}`).join("");
162  svg.querySelector(".line").setAttribute("d", line);
163  svg.querySelector(".area").setAttribute("d", `${line}L100,32L0,32Z`);
164}
165function setMetric(key, value, unit, sub) {
166  $(`mv-${key}`).innerHTML = value == null ? "–" : `${esc(value)}${unit ? `<small>${esc(unit)}</small>` : ""}`;
167  $(`ms-${key}`).textContent = sub || "";
168}
169
170let lastMetrics = null, metricsFailures = 0, keyWarned = false, mcpTick = 0;
171let metricsEpoch = 0;
172// After Load or Unload returns, a poll that started earlier can still say the opposite. Hold the POST's state until a later
173// poll agrees, or until the first poll that started after the POST arrives. (PR #3550 by sakuumomo)
174let metricsHold = null;
175let reqShowAll = false;   // the Monitor's request table: the last 12, or every one the server keeps (issue #35)
176function metricsAgree(live, state) {
177  const s = (live && live.state) || "";
178  if (state === "unloaded") return s === "unloaded";
179  return s !== "" && s !== "unloaded";
180}
181async function poll() {
182  const epoch = ++metricsEpoch;
183  try {
184    const r = await fetch(reqShowAll ? "metrics?requests=all" : "metrics", {headers: headers()});
185    if (r.status === 401) {
186      setPill("error", tr("pill.keyNeeded", "API key needed"));
187      if (!keyWarned) { keyWarned = true; toast("warn", tr("pill.keyNeeded", "API key needed"), tr("toast.keyAbout", "This server needs a key: add it under About > Settings."), 6000); }
188    } else if (r.ok) {
189      const m = await r.json();
190      if (metricsHold && epoch <= metricsHold.after && !metricsAgree(m.live, metricsHold.state)) {
191        setTimeout(poll, 1000);
192        return;
193      }
194      if (metricsHold && (metricsAgree(m.live, metricsHold.state) || epoch > metricsHold.after)) metricsHold = null;
195      lastMetrics = m;
196      metricsFailures = 0;
197      render(lastMetrics);
198    } else {
199      throw new Error(`HTTP ${r.status}`);
200    }
201  } catch (e) {
202    if (++metricsFailures === 3) setPill("error", tr("pill.unreachable", "Server not reachable"));
203  }
204  if (tab === "monitor" && ++mcpTick % 10 === 0) loadMcp();       // server states change rarely: every 10 s
205  setTimeout(poll, 1000);
206}
207
208function setPill(state, text) {
209  $("pill").dataset.state = state === "error" ? "queued" : state;
210  $("pill-text").textContent = text;
211  // a poll re-sets the sentence every second; refit only when its text changed
212  if (text !== lastPillText) { lastPillText = text; fitHeader(); }
213}
214let lastPillText = null;
215// The pill's sentence is the first thing the header row can spare when it runs out of room.
216function fitHeader() {
217  const header = document.querySelector(".st-header");
218  if (!header) return;
219  header.classList.remove("st-header--clip");
220  if (header.scrollWidth > header.clientWidth) header.classList.add("st-header--clip");
221}
222window.addEventListener("resize", fitHeader);
223
224// ------------------------------------------------------------------ Load / Unload (POST /load, /unload: the header button)
225// Metrics stay "unloaded" until the engine is READY, so a turn or an image job on this page has to paint Loading itself.
226// modelOp covers the button's own POST, which returns before the next poll can agree.
227let modelOp = null;
228let imageBusy = false;
229function pageBusy() { return busy != null || imageBusy; }
230// "generating an image" is the job a refresh can see. imageBusy is this page's POST before that phase is published. A chat
231// phase already on the metrics wins, because Stop still stops that reply.
232function imageLive(live) {
233  if (live && live.phase === "generating an image") return true;
234  const state = live && live.state;
235  if (state === "reading" || state === "generating") return false;
236  return imageBusy;
237}
238function paintLive() { if (lastMetrics) render(lastMetrics); }
239function turnBlocksUnload(live) {
240  const state = (live && live.state) || "";
241  return pageBusy() || state === "reading" || state === "generating" || (live && live.queued > 0);
242}
243function setModelButton(text, title, disabled) {
244  const btn = $("unload-btn");
245  btn.textContent = text; btn.title = title; btn.disabled = disabled;
246  fitHeader();
247}
248function modelButton(live) {
249  if (modelOp === "load") return setModelButton(tr("model.loading", "Loading…"), tr("model.loadingTitle", "The model is loading"), true);
250  if (modelOp === "unload") return setModelButton(tr("model.unloading", "Unloading…"), tr("model.unloadingTitle", "The model is unloading"), true);
251  const state = (live && live.state) || "";
252  const metricsBusy = state === "reading" || state === "generating" || (live && live.queued > 0);
253  const imageNow = imageLive(live);
254  const unload = tr("model.unload", "Unload");
255  if (state === "unloaded") {
256    if (imageNow) return setModelButton(tr("model.loading", "Loading…"), tr("model.imageLoading", "An image is already loading the model"), true);
257    if (pageBusy()) return setModelButton(tr("model.loading", "Loading…"), tr("model.replyLoading", "A reply is already loading the model"), true);
258    return setModelButton(tr("model.load", "Load"), tr("model.loadTitle", "Load the model now. A message also loads it."), false);
259  }
260  if (imageNow) return setModelButton(unload, tr("model.imageBusy", "An image is generating. It finishes on its own."), true);
261  if (!state) return setModelButton("…", tr("model.waiting", "Waiting for the server"), true);
262  if (metricsBusy || pageBusy()) return setModelButton(unload, tr("model.stopFirst", "Stop the reply, then unload"), true);
263  return setModelButton(unload, tr("model.unloadTitle", "Unload the model and free the GPU"), false);
264}
265$("unload-btn").onclick = async () => {
266  if (modelOp) return;
267  const live = (lastMetrics && lastMetrics.live) || {};
268  const loading = live.state === "unloaded";
269  const busyCopy = (sample, stillLoading) => stillLoading
270    ? (imageLive(sample) ? tr("model.imageLoadingDot", "An image is already loading the model.") : tr("model.replyLoadingDot", "A reply is already loading the model."))
271    : (imageLive(sample) ? tr("model.imageBusy", "An image is generating. It finishes on its own.") : tr("model.stopFirstDot", "Stop the reply, then unload."));
272  if (loading ? pageBusy() : turnBlocksUnload(live)) {
273    toast("warn", tr("model.busy", "Model is busy"), busyCopy(live, loading));
274    return;
275  }
276  if (!loading && !confirm(tr("model.confirmUnload", "Unload the model and free the GPU? Load, or the next message, brings it back."))) return;
277  // confirm() blocks the poll. Yield so a sample that arrived during the dialog is applied. A confirmed Unload stays an unload.
278  if (!loading) {
279    modelOp = "unload";
280    modelButton(live);
281    await new Promise((resolve) => setTimeout(resolve, 0));
282  }
283  const now = (lastMetrics && lastMetrics.live) || {};
284  const loadingNow = loading;
285  if (loadingNow ? pageBusy() : turnBlocksUnload(now)) {
286    modelOp = null;
287    if (lastMetrics) render(lastMetrics); else modelButton(now);
288    toast("warn", tr("model.busy", "Model is busy"), busyCopy(now, loadingNow));
289    return;
290  }
291  modelOp = loadingNow ? "load" : "unload";
292  modelButton(now);
293  if (loadingNow) toast("info", tr("model.loadingToast", "Loading the model"), tr("model.fewMinutes", "This can take a few minutes."));
294  const remember = (state) => {
295    if (!lastMetrics) lastMetrics = {};
296    lastMetrics.live = Object.assign({}, lastMetrics.live, {state, queued: 0});
297    metricsHold = {state, after: metricsEpoch};
298  };
299  try {
300    const r = await fetch(loadingNow ? "load" : "unload", {method: "POST", headers: headers(true), body: "{}"});
301    let body = {};
302    try { body = await r.json(); } catch (e) { /* the connection dropped */ }
303    const status = body.status || "";
304    const msg = (body.error && body.error.message) ||
305                (r.status === 401 ? tr("toast.keyAbout2", "API key needed: add it under About > Settings.") : tr("toast.httpAnswer", "The server answered HTTP {code}.", {code: r.status}));
306    const failTitle = loadingNow ? tr("model.loadFailed", "Load failed") : tr("model.unloadFailed", "Unload failed");
307    if (loadingNow) {
308      if (r.ok && status === "loaded") {
309        remember("idle");
310        toast("success", tr("model.loaded", "Model loaded"), tr("model.gpuInUse", "The GPU is in use."));
311      } else {
312        toast("error", failTitle, msg);
313      }
314    } else if (status === "unloaded" || status === "not loaded") {
315      remember("unloaded");
316      toast(status === "unloaded" ? "success" : "info",
317            status === "unloaded" ? tr("model.unloaded", "Model unloaded") : tr("model.alreadyUnloaded", "Already unloaded"),
318            tr("model.gpuFree", "The GPU is free. Load, or the next message, brings it back."));
319    } else if (r.status === 409 || status === "busy") {
320      let sample = (lastMetrics && lastMetrics.live) || {};
321      try {
322        const mr = await fetch("metrics", {headers: headers()});
323        if (mr.ok) {
324          const m = await mr.json();
325          if (m && m.live) { sample = m.live; lastMetrics = m; }
326        }
327      } catch (e) { /* the 409 body has no phase */ }
328      toast("warn", tr("model.busy", "Model is busy"), imageLive(sample)
329        ? tr("model.imageBusy", "An image is generating. It finishes on its own.") : tr("model.stopFirstDot", "Stop the reply, then unload."));
330    } else if (status === "unsupported") {
331      toast("error", tr("model.unsupported", "Unload is not available"), "");
332    } else {
333      toast("error", failTitle, msg);
334    }
335  } catch (e) {
336    toast("error", loadingNow ? tr("model.loadFailed", "Load failed") : tr("model.unloadFailed", "Unload failed"), tr("model.noAnswer", "The server did not answer."));
337  } finally {
338    modelOp = null;
339    if (lastMetrics) render(lastMetrics); else modelButton({});
340  }
341};
342
343function render(m) {
344  const live = m.live || {}, hw = m.hardware || {}, st = m.hardware_static || {}, eng = m.engine || {}, h = m.history || {};
345  const last = (m.requests || [])[0];
346  // the header pill. modelOp and a local load win over "N queued": with parallel requests, queued stays up through
347  // ensure_loaded(), and metrics stay "unloaded" until the engine is READY. An image POST in that window is still a load.
348  const localLoad = live.state === "unloaded" && (busy != null || imageBusy);
349  if (modelOp === "load") {
350    setPill("idle", tr("model.loading", "Loading…"));
351  } else if (modelOp === "unload") {
352    setPill("idle", tr("model.unloading", "Unloading…"));
353  } else if (localLoad) {
354    setPill("idle", tr("model.loading", "Loading…"));
355  } else if (imageLive(live)) {
356    setPill("reading", tr("pill.image", "Generating image…"));
357  } else if (live.state === "reading") {
358    const pct = live.prompt_total ? Math.round((100 * live.prompt_read) / live.prompt_total) : null;
359    setPill("reading", pct != null ? tr("pill.readingPct", "Reading prompt · {pct}%", {pct}) : tr("pill.reading", "Reading prompt"));
360  } else if (live.state === "generating") {
361    setPill("generating", tr("pill.generating", "Generating · {rate} tok/s", {rate: fmt(live.tok_s, 1)}));
362  } else if (live.state === "unloaded") {
363    setPill("idle", tr("pill.unloaded", "Unloaded"));
364  } else {
365    setPill("idle", tr("pill.idle", "Idle"));
366  }
367  modelButton(live);
368  if (!modelOp && !localLoad && live.queued > 0) setPill("queued", tr("pill.queued", "{n} queued", {n: live.queued}));
369  if (tab === "monitor") renderMonitor(live, hw, st, eng, h, last, m.requests || [], m.totals, m.requests_kept);
370  if (tab === "monitor") renderConvCache(m.conversation_cache);
371  if (tab === "about") renderAbout(eng, hw, st);
372}
373
374// #596: the conversation cache - the prompt's state the engine keeps between requests (always), and the whole
375// conversations it parks in RAM when "--conversation-cache-mib N" is in the run config's args (opt-in)
376function since(t) {
377  if (!t) return "";
378  const s = Math.max(0, Date.now() / 1000 - t);
379  return s < 60 ? "just now" : s < 3600 ? `${fmt(s / 60)} min ago` : `${fmt(s / 3600, 1)} h ago`;
380}
381function renderConvCache(c) {
382  $("cc-card").hidden = !c;
383  if (!c) return;                                  // an older server
384  const pct = (a, b) => (b ? `${Math.min(100, (100 * a) / b)}%` : "0%");
385  $("cc-bars").hidden = !c.enabled;
386  if (c.enabled) {
387    $("cc-slots-text").textContent = `${fmt(c.parked)} / ${fmt(c.slots)}`;
388    $("cc-slots-bar").style.width = pct(c.parked, c.slots);
389    const budget = c.budget_mib * 1048576;
390    $("cc-mem-text").textContent = `${gb(c.bytes)} / ${gb(budget)} GB`;
391    $("cc-mem-bar").style.width = pct(c.bytes, budget);
392  }
393  $("cc-sum").textContent = c.requests ? `${fmt(c.requests_reused)} of ${fmt(c.requests)} requests reused part of their prompt` : "";
394  const share = c.prompt_tokens ? ` (${fmt((100 * c.reused_tokens) / c.prompt_tokens)}% of all prompt tokens)` : "";
395  const event = c.last_event ? `${c.last_event === "parked" ? "Parked" : "Restored"} ${fmt(c.last_tokens)} tokens, ${since(c.last_at)}` : null;
396  facts($("cc-facts"), [
397    ["Last request", c.last_prompt != null ? `${fmt(c.last_reused || 0)} of ${fmt(c.last_prompt)} prompt tokens reused` : null],
398    ["Reused since start", c.requests ? `${fmt(c.reused_tokens)} tokens${share}` : null],
399    ["Parked / restored", c.enabled ? `${fmt(c.parks)} / ${fmt(c.restores)}${c.evictions ? ` · ${fmt(c.evictions)} evicted` : ""}` : null],
400    ["Last switch", c.enabled ? event : null],
401  ]);
402  $("cc-note").textContent = c.enabled
403    ? "A request that continues a parked conversation gets its state back instead of reading it again; the oldest goes when the slots or the memory are full."
404    : "The engine keeps the last conversation's state, so a follow-up reads only what is new. To keep several conversations (agents taking turns), add \"--conversation-cache-mib\", \"8192\" to the run config's args (docs/DETAILS.md).";
405}
406
407function renderTotals(t) {
408  if (!t || !t.requests) return "";
409  const since = new Date(t.since * 1000).toLocaleString([], {weekday: "short", hour: "2-digit", minute: "2-digit"});
410  const read = t.prompt_tokens - t.reused;
411  const pSpeed = t.prompt_ms > 0 && read > 0 ? ` at ${fmt(read / (t.prompt_ms / 1000))} tok/s` : "";
412  const oSpeed = t.decode_ms > 0 && t.output_tokens > 0 ? ` at ${fmt(t.output_tokens / (t.decode_ms / 1000), 1)} tok/s` : "";
413  return `Since ${since}: ${fmt(t.requests)} requests · ${fmt(read)} prompt tokens read${pSpeed} (${fmt(t.reused)} reused) · ` +
414         `${fmt(t.output_tokens)} written${oSpeed}`;
415}
416function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) {
417  // model state
418  // A local turn keeps metrics on "unloaded" for the whole engine start.
419  const imageNow = imageLive(live);
420  const starting = modelOp === "load" || imageNow || (busy != null && live.state === "unloaded");
421  const on = !modelOp && live.queued > 0 ? "queued" : live.state;
422  for (const b of document.querySelectorAll("#state-badges .st-badge")) {
423    const lit = (b.dataset.s === on || b.dataset.s === live.state) && !(starting && b.dataset.s === "unloaded");
424    b.classList.toggle("on", lit);
425  }
426  const prog = $("state-progress");
427  let label = "Waiting for a request", detail = "", pct = 0;
428  if (modelOp === "load" || (busy != null && live.state === "unloaded" && !imageNow)) {
429    label = "Loading";
430    delete prog.dataset.tone;
431    detail = "The model is loading.";
432  } else if (imageNow && (live.state === "unloaded" || live.state === "reading" || live.state === "generating" || live.state === "idle")) {
433    label = live.state === "unloaded" ? "Loading" : "Generating image";
434    delete prog.dataset.tone;
435    detail = live.state === "unloaded" ? "The model is loading." : "An image is generating. It finishes on its own.";
436  } else if (modelOp === "unload") {
437    label = "Unloading";
438    delete prog.dataset.tone;
439    detail = "Freeing the GPU.";
440  } else if (live.state === "reading") {
441    label = "Reading prompt";
442    prog.dataset.tone = "info";
443    if (live.prompt_total) {
444      pct = (100 * live.prompt_read) / live.prompt_total;
445      detail = `${fmt(live.prompt_read)} / ${fmt(live.prompt_total)} tokens · ${fmt(pct)}%`;
446    } else {
447      detail = `${fmt(live.prompt_tokens)} tokens`;
448    }
449  } else if (live.state === "generating") {
450    label = live.phase ? live.phase[0].toUpperCase() + live.phase.slice(1) : "Generating";
451    delete prog.dataset.tone;
452    pct = live.max_tokens ? Math.min(100, (100 * live.generated) / live.max_tokens) : 0;
453    detail = `${fmt(live.generated)} tokens · ${fmt(live.tok_s, 1)} tok/s`;
454  } else if (live.state === "unloaded") {
455    label = "Unloaded";
456    delete prog.dataset.tone;
457    detail = "Load brings it back. A message does too.";
458  } else if (last) {
459    delete prog.dataset.tone;
460    detail = `last: ${fmt(last.output_tokens)} tokens${last.decode_tok_s ? ` at ${fmt(last.decode_tok_s, 1)} tok/s` : ""}`;
461  }
462  $("state-label").textContent = label;
463  $("state-detail").textContent = detail;
464  $("state-bar").style.width = `${pct}%`;
465
466  // the eight cards
467  // Idle: not the last request's speed (one request is noisy) but the run's average from the server's totals
468  // (token-weighted, the same figure the engine's DONE lines and Prometheus report). Live stays live.
469  const avgDecode = totals && totals.decode_ms > 0 && totals.output_tokens > 0 ? totals.output_tokens / (totals.decode_ms / 1000) : null;
470  const readTokens = totals ? totals.prompt_tokens - (totals.reused || 0) : 0;
471  const avgPrefill = totals && totals.prompt_ms > 0 && readTokens > 0 ? readTokens / (totals.prompt_ms / 1000) : null;
472  const speed = live.state === "generating" ? live.tok_s : avgDecode != null ? avgDecode : last ? last.decode_tok_s : null;
473  setMetric("speed", speed == null ? null : fmt(speed, 1), "t/s",
474            live.state === "generating" ? "Decode now" : avgDecode != null ? "Decode · run average" : last ? "Decode last request" : "Decode");
475  const prefill = live.state !== "idle" ? live.prefill_tok_s_mean
476                : avgPrefill != null ? avgPrefill : last && last.prompt_ms > 0 ? Math.max(0, last.prompt_tokens - (last.reused || 0)) / (last.prompt_ms / 1000) : null;
477  setMetric("prefill", prefill == null ? null : fmt(prefill), "t/s",
478            live.state === "reading" ? "Prefill now" : live.state === "generating" ? "Prefill this request" : avgPrefill != null ? "Prefill · run average" : last ? "Prefill last request" : "Prefill");
479  spark("sp-speed", h.tok_s);
480  spark("sp-prefill", h.prefill_tok_s_mean);
481  // a model split across several cards (issue #112): the cards show their total / mean / hottest, and each card's own
482  const per = (f) => (hw.gpus || []).map((g) => `GPU ${g.index} ${f(g)}`).join(" · ");
483  const multi = (hw.gpus || []).length > 1;
484  setMetric("gpu", hw.gpu_util == null ? null : fmt(hw.gpu_util), "%",
485            multi ? per((g) => (g.util == null ? "–" : `${fmt(g.util)}%`)) : st.gpu_name || (st.gpu_note ? "not available" : ""));
486  spark("sp-gpu", h.gpu_util, 100);
487  setMetric("vram", hw.gpu_mem_used == null ? null : gb(hw.gpu_mem_used), hw.gpu_mem_total ? `/ ${gb(hw.gpu_mem_total, 0)} GB` : "GB",
488            multi ? per((g) => (g.mem_used == null ? "–" : `${gb(g.mem_used)} GB`))
489                  : eng.expert_slots ? `${fmt(eng.expert_slots)} experts cached` : (st.gpu_note ? "not available on Windows AMD yet" : ""));
490  spark("sp-vram", h.gpu_mem_used, hw.gpu_mem_total);
491  setMetric("temp", hw.gpu_temp == null ? null : fmt(hw.gpu_temp), "°C",
492            multi ? per((g) => (g.temp == null ? "–" : `${fmt(g.temp)}°`)) : "");
493  spark("sp-temp", h.gpu_temp, 90);
494  setMetric("power", hw.gpu_power == null ? null : fmt(hw.gpu_power), "W", hw.gpu_power_limit ? `of ${fmt(hw.gpu_power_limit)} W limit` : "");
495  spark("sp-power", h.gpu_power, hw.gpu_power_limit);
496  const gen = hw.gpu_pcie_gen_max || hw.gpu_pcie_gen;
497  setMetric("pcie", gen ? `Gen${gen}` : null, hw.gpu_pcie_width ? `x${hw.gpu_pcie_width}` : "",
498            hw.gpu_pcie_rx_mb == null ? "" : `to GPU ${fmt(hw.gpu_pcie_rx_mb, hw.gpu_pcie_rx_mb < 10 ? 1 : 0)} MB/s` +
499            (hw.gpu_pcie_gen && gen && hw.gpu_pcie_gen < gen ? ` · idle Gen${hw.gpu_pcie_gen}` : ""));
500  spark("sp-pcie", h.gpu_pcie_rx_mb);
501  setMetric("cpu", hw.cpu == null ? null : fmt(hw.cpu), "%", st.threads ? `${st.cores ? `${st.cores} cores · ` : ""}${st.threads} threads` : "");
502  spark("sp-cpu", h.cpu, 100);
503  if (hw.disk_read_mb == null) {
504    setMetric("disk", null, "", st.psutil ? "" : "needs psutil (setup installs it)");
505  } else {
506    const big = hw.disk_read_mb >= 1000;
507    setMetric("disk", big ? fmt(hw.disk_read_mb / 1024, 2) : fmt(hw.disk_read_mb, hw.disk_read_mb < 10 ? 1 : 0), big ? "GB/s" : "MB/s",
508              hw.disk_write_mb == null ? "" : `write ${fmt(hw.disk_write_mb, 1)} MB/s`);
509  }
510  spark("sp-disk", h.disk_read_mb);
511
512  // context fill: the running request, else the last one
513  const ctx = eng.max_context || 0;
514  let used = 0;
515  if (live.state !== "idle") used = (live.prompt_tokens || 0) + (live.generated || 0);
516  else if (last) used = (last.prompt_tokens || 0) + (last.output_tokens || 0);
517  const frac = ctx ? Math.min(1, used / ctx) : 0;
518  $("ctx-fill").setAttribute("stroke-dasharray", `${(235.6 * frac).toFixed(1)} 314.2`);
519  $("ctx-fill").style.opacity = 235.6 * frac >= 3 ? "1" : "0";         // a near-zero arc would draw just its round cap
520  $("ctx-pct").textContent = `${Math.round(frac * 100)}%`;
521  $("ctx-sub").textContent = ctx ? `${kfmt(used)} / ${ctxfmt(ctx)}` : "–";
522  const cacheBytes = (eng.expert_cache_mib || 0) * 1048576;
523  $("slots-text").textContent = eng.expert_slots ? `${fmt(eng.expert_slots)} · ${gb(cacheBytes)} GB` : "–";
524  $("slots-bar").style.width = hw.gpu_mem_total ? `${Math.min(100, (100 * cacheBytes) / hw.gpu_mem_total)}%` : "0%";
525  $("ram-text").textContent = hw.ram_total ? `${gb(hw.ram_used)} / ${gb(hw.ram_total, 0)} GB` : "–";
526  const ramPct = hw.ram_total ? (100 * hw.ram_used) / hw.ram_total : 0;
527  $("ram-bar").style.width = `${ramPct}%`;
528  if (ramPct > 92) $("ram-progress").dataset.tone = "danger"; else delete $("ram-progress").dataset.tone;
529  $("temp-text").textContent = hw.gpu_temp == null ? "–" : `${fmt(hw.gpu_temp)} °C`;
530  $("temp-bar").style.width = hw.gpu_temp == null ? "0%" : `${Math.min(100, hw.gpu_temp)}%`;
531
532  // recent requests
533  const body = $("req-body");
534  if (!requests.length) {
535    body.innerHTML = `<tr><td colspan="9" class="muted">No requests yet</td></tr>`;
536  } else {
537    const badge = {stop: ["", "Done"], length: ["", "Max tokens"], cancel: ["st-badge--queued", "Stopped"],
538                   disconnect: ["st-badge--queued", "Closed"], error: ["st-badge--error", "Error"],
539                   timeout: ["st-badge--queued", "Timeout"]};
540    body.innerHTML = requests.slice(0, reqShowAll ? requests.length : 12).map((r) => {
541      const [cls, text] = badge[r.finish] || ["", r.finish || "–"];
542      const t = new Date(r.time * 1000).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit", second: "2-digit"});
543      const proj = r.projection == null ? "" : ` <span class="st-badge${r.projection ? " st-badge--reading" : ""}" title="experimental speed projection ${r.projection ? "on" : "off"}">${r.projection ? "ESP" : "stock"}</span>`;
544      // #588: the VRAM share; the PCIe share (--pcie-frac) beside it when there is one
545      const hit = r.hit_rate == null ? "–" : `${(r.hit_rate * 100).toFixed(1)}%` +
546        (r.pcie_share ? ` <span class="muted" title="routed experts the GPU read over PCIe (--pcie-frac) or another GPU computed">+${(r.pcie_share * 100).toFixed(1)}% PCIe</span>` : "");
547      // Reused tokens are not prefetched again. Match the Monitor's existing Prefill metric.
548      const fresh = r.prompt_tokens == null ? null : Math.max(0, r.prompt_tokens - (r.reused || 0));
549      const prefillRate = fresh > 0 && r.prompt_ms > 0 ? fresh / (r.prompt_ms / 1000) : null;
550      return `<tr><td>${esc(t)}</td><td><span class="st-badge ${cls}">${esc(text)}</span>${proj}</td><td class="num">${fmt(r.prompt_tokens)}</td>
551        <td class="num">${fmt(r.reused)}</td><td class="num">${fmt(r.output_tokens)}</td><td class="num">${fmt(prefillRate)}</td><td class="num">${fmt(r.decode_tok_s, 1)}</td>
552        <td class="num">${hit}</td><td class="num">${fmt(r.duration_s, 1)} s</td></tr>`;
553    }).join("");
554  }
555  const all = $("req-all");
556  kept = kept == null ? requests.length : kept;
557  all.hidden = kept <= 12;
558  all.textContent = reqShowAll ? "Show fewer" : `Show all (${kept})`;
559  $("req-wrap").classList.toggle("all", reqShowAll);
560  $("req-totals").textContent = renderTotals(totals);
561}
562
563function facts(el, rows) {
564  el.innerHTML = rows.filter((r) => r[1] != null && r[1] !== "").map(([k, v, copy]) =>
565    `<dt>${esc(k)}</dt><dd>${copy ? `<code>${esc(v)}</code><button class="st-btn st-btn--icon" data-copy="${esc(v)}" aria-label="Copy">${icon("copy")}</button>` : esc(v)}</dd>`).join("");
566}
567// INFO cvec=project:4-44[:singleL] | add:A-B | 0
568function projectionText(c) {
569  if (!c || c === "0" || c === 0) return null;
570  const [mode, range, single] = String(c).split(":");
571  const [a, b] = (range || "").split("-");
572  return `${mode === "project" ? "Projection" : "Additive"} control vector on layers ${a}–${b}` +
573         `${single ? ` (layer ${single.replace("single", "")}'s direction)` : ""}. Per chat in Sampling. Its package ` +
574         "describes the vector as a refusal-direction projection; measure the speed yourself";
575}
576function renderAbout(eng, hw, st) {
577  const kv = {int8: "8-bit", q4_0: "4-bit (Hadamard-rotated)", fp16: "16-bit"}[eng.kv] || eng.kv;
578  facts($("facts-engine"), [
579    ["Model", eng.model],
580    ["Engine", eng.version ? `v${eng.version}` : "built from source"],
581    ["Context", eng.max_context ? `${fmt(eng.max_context)} tokens` : null],
582    ["KV cache", kv ? `${kv}${eng.kv_resident ? `, streamed: ${fmt(eng.kv_resident)} positions per layer in VRAM, the rest in RAM` : ", all in VRAM"}` : null],
583    ["Experts in VRAM", eng.expert_slots ? `${fmt(eng.expert_slots)} (${gb((eng.expert_cache_mib || 0) * 1048576)} GB)` : null],
584    // #5080: the MTP line only when the MTP is the drafter (eng.drafting, strata_control/drafting.py engine_info; an engine too old to say had only the MTP)
585    ["Speculation", eng.spec && (eng.drafting == null || eng.drafting === "mtp") ? `MTP drafts up to ${Math.max(0, (eng.mtp_max || eng.spec) - 1)} tokens${eng.lookup ? ", prompt lookup on" : ""}` : null],
586    ["Images", eng.images ? "on" : "off"],
587    ["Experimental speed projection", projectionText(eng.cvec)],
588  ]);
589  facts($("facts-hw"), [
590    ["GPU", st.gpu_name ? `${st.gpu_name}${hw.gpu_mem_total ? `, ${gb(hw.gpu_mem_total, 0)} GB` : ""}` : (st.gpu_note || "not readable (NVML)")],
591    ["CPU", st.cpu_name ? `${st.cpu_name}${st.threads ? `, ${st.threads} threads` : ""}` : null],
592    ["RAM", hw.ram_total ? `${gb(hw.ram_total, 0)} GB` : null],
593  ]);
594  const base = location.origin;
595  facts($("facts-api"), [
596    ["OpenAI base URL", `${base}/v1`, true],
597    ["Anthropic base URL", base, true],
598    ["Model name", eng.model, true],
599  ]);
600}
601document.addEventListener("click", (e) => {
602  const b = e.target.closest("[data-copy]");
603  if (b) copyText(b.dataset.copy, b);
604});
605$("req-all").addEventListener("click", () => { reqShowAll = !reqShowAll; if (lastMetrics) render(lastMetrics); });
606
607// ------------------------------------------------------------------ MCP servers (GET /mcp)
608// Tools from the MCP servers in the run config: the chat offers them to the model (opt-in per request,
609// "strata_mcp": true, which only this page sends); the Monitor lists the servers and what they offer.
610let mcpInfo = {servers: [], tools: 0}, mcpRetry = null;
611async function loadMcp() {
612  try {
613    const r = await fetch("mcp", {headers: headers()});
614    if (!r.ok) return;
615    mcpInfo = await r.json();
616  } catch (e) { return; /* an older server: no MCP */ }
617  renderMcp();
618  clearTimeout(mcpRetry);                          // right after the start, servers may still be starting (npx downloads)
619  if ((mcpInfo.servers || []).some((s) => s.status === "starting")) mcpRetry = setTimeout(loadMcp, 3000);
620}
621const MCP_STATE = {ready: ["st-badge--generating", "Connected"], starting: ["st-badge--reading", "Starting"],
622                   failed: ["st-badge--error", "Failed"], stopped: ["st-badge--queued", "Stopped"], idle: ["", "Waiting"]};
623function renderMcp() {
624  const servers = mcpInfo.servers || [];
625  $("mcp-card").hidden = !servers.length;
626  $("mcp-row").hidden = !servers.length;
627  const ready = servers.filter((s) => s.status === "ready" || s.status === "stopped");
628  $("mcp-sum").textContent = servers.length ? `${fmt(mcpInfo.tools)} tools · ${ready.length} of ${servers.length} servers connected` : "";
629  $("mcp-row-sub").textContent = mcpInfo.tools ? `${fmt(mcpInfo.tools)} tools from ${ready.map((s) => s.name).join(", ")}; the model calls them when it decides to`
630                                               : "no server is connected yet (see the Monitor)";
631  $("mcp-list").innerHTML = servers.map((s) => {
632    const [cls, text] = MCP_STATE[s.status] || ["", s.status];
633    const info = s.info && s.info.name ? ` · ${s.info.name}${s.info.version ? ` ${s.info.version}` : ""}` : "";
634    return `<div class="mcp-server"><div class="mcp-server__head"><span class="st-badge ${cls}">${esc(text)}</span>` +
635      `<strong>${esc(s.name)}</strong><span class="muted small">${esc(s.transport)} · ${fmt(s.tools.length)} tools${esc(info)}</span></div>` +
636      (s.error ? `<div class="msg-error">${esc(s.error)}</div>` : "") +
637      (s.tools.length ? `<div class="mcp-server__tools">${s.tools.map((t) => `<span class="chip" title="${esc(t.description || "")}">${esc(t.tool)}</span>`).join("")}</div>` : "") +
638      `</div>`;
639  }).join("");
640}
641
642// ------------------------------------------------------------------ Model settings (GET / POST /config, #564)
643// A few documented keys of the run config (strata-<model>.json), for every client, from the next start on.  The
644// server lists them, checks every value and keeps every other key of the file as it is.
645let cfgKeys = [];
646async function loadConfig() {
647  let r;
648  try { r = await fetch("config", {headers: headers()}); } catch (e) { return; }
649  if (!r.ok) { $("cfg-card").hidden = true; return; }       // no run config, an older server, or no key yet
650  const c = await r.json();
651  cfgKeys = c.keys || [];
652  $("cfg-file").textContent = c.file || "";
653  $("cfg-form").innerHTML = cfgKeys.map((k, i) => {
654    const id = `cfg-${i}`, v = k.value;
655    let input;
656    if (k.kind === "bool" || k.kind === "enum") {
657      const opts = k.kind === "bool" ? [["true", "on"], ["false", "off"]] : k.choices.map((x) => [x, x]);
658      const cur = v == null ? "" : String(v);
659      input = `<select class="st-input" id="${id}"><option value=""${cur === "" ? " selected" : ""}>default</option>` +
660        opts.map(([val, text]) => `<option value="${esc(val)}"${cur === val ? " selected" : ""}>${esc(text)}</option>`).join("") + `</select>`;
661    } else {
662      const text = v == null ? "" : Array.isArray(v) ? v.join(", ") : String(v);
663      input = `<input class="st-input" id="${id}" ${k.kind === "number" ? 'type="number" step="any" min="0"' : 'type="text"'} ` +
664        `value="${esc(text)}" placeholder="default" autocomplete="off">`;
665    }
666    return `<label for="${id}" title="${esc(k.help)}">${esc(k.help)}<code>${esc(k.key)}</code></label>${input}`;
667  }).join("");
668  $("cfg-card").hidden = false;
669}
670function configValue(k, el) {
671  const s = el.value.trim();
672  if (s === "") return null;
673  if (k.kind === "bool") return s === "true";
674  if (k.kind === "number") return Number(s);
675  return s;                                         // enum, or names (the server splits them at commas)
676}
677$("cfg-save").addEventListener("click", async () => {
678  const set = {};
679  cfgKeys.forEach((k, i) => {
680    const v = configValue(k, $(`cfg-${i}`));
681    const old = Array.isArray(k.value) ? k.value.join(", ") : k.value;
682    if (JSON.stringify(v) !== JSON.stringify(old ?? null)) set[k.key] = v;
683  });
684  if (!Object.keys(set).length) { $("cfg-msg").textContent = "Nothing changed."; return; }
685  try {
686    const r = await fetch("config", {method: "POST", headers: headers(true), body: JSON.stringify({set})});
687    const b = await r.json();
688    if (!r.ok) throw new Error((b.error || {}).message || `HTTP ${r.status}`);
689    $("cfg-msg").textContent = b.changed.length
690      ? `Saved (${b.changed.join(", ")}); the earlier file is ${b.file}.bak. Start the model again to use it.` : "Nothing changed.";
691    loadConfig();
692  } catch (e) {
693    $("cfg-msg").textContent = "";
694    toast("error", "Not saved", String(e.message || e), 6000);
695  }
696});
697
698// ------------------------------------------------------------------ Markdown (escaped first, then formatted)
699function inline(s) {
700  const codes = [];
701  s = s.replace(/`([^`\n]+)`/g, (_, c) => { codes.push(c); return `\u0000${codes.length - 1}\u0000`; });
702  s = esc(s)
703    .replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>")
704    .replace(/(^|[^*\w])\*([^*\n]+)\*(?![*\w])/g, "$1<em>$2</em>")
705    .replace(/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
706  return s.replace(/\u0000(\d+)\u0000/g, (_, i) => `<code class="inline">${esc(codes[+i])}</code>`);
707}
708// An ```svg or ```html block that is complete gets a Preview button (serve/web/preview.js): the block's own code in a sandboxed
709// frame, built when it is first opened and again when the theme changes. The state lives on the box (data-preview), so it
710// resets if the answer is rebuilt. A page (html) can also be run WITH scripts, after a warning, one block at a time.
711function pageTheme() {
712  const root = document.documentElement;
713  return {dark: root.dataset.theme === "dark", ink: getComputedStyle(root).getPropertyValue("--st-ink").trim()};
714}
715function fillPreview(fr, scripts, blank) {
716  const box = fr.closest(".st-code");
717  const doc = blank ? null : StrataPreview.previewDoc(fr.dataset.lang, box.querySelector("pre").textContent, scripts, pageTheme(), window);
718  const nf = StrataPreview.makeFrame(doc, {scripts, title: fr.title, lang: fr.dataset.lang});
719  fr.replaceWith(nf);
720  box.classList.toggle("st-code--run", !!(doc && scripts));
721  const rb = box.querySelector("[data-preview-scripts]");
722  if (rb) {
723    rb.setAttribute("aria-pressed", String(!!(doc && scripts)));
724    rb.setAttribute("aria-label", doc && scripts ? tr("preview.stopScripts", "Stop scripts") : tr("preview.runScripts", "Run scripts"));
725  }
726}
727function refreshPreviews() { for (const fr of document.querySelectorAll("iframe[data-opened]")) fillPreview(fr, fr.dataset.scripts === "1"); }
728function codeBlock(lang, code, complete) {
729  const ok = complete && StrataPreview.canPreview(lang || "", code);
730  const kind = ok ? StrataPreview.kindOf(lang) : null;
731  const label = kind === "svg" ? tr("preview.showSvg", "Preview the picture") : tr("preview.showPage", "Preview the page");
732  const head = `<div class="st-code__head"><span>${esc(lang || tr("code.label", "code"))}</span><span class="st-code__btns">` +
733    (kind === "page" ? `<button class="st-btn st-btn--icon" data-preview-scripts aria-label="${esc(tr("preview.runScripts", "Run scripts"))}" aria-pressed="false" title="${esc(tr("preview.runScripts", "Run scripts"))}">${icon("warning")}</button>` : "") +
734    (ok ? `<button class="st-btn st-btn--icon" data-preview-toggle data-preview-label="${esc(label)}" aria-label="${esc(label)}" title="${esc(label)}" aria-pressed="false">${icon("image")}</button>` : "") +
735    `<button class="st-btn st-btn--icon" data-code-copy aria-label="${esc(tr("code.copy", "Copy code"))}">${icon("copy")}</button></span></div>`;
736  const prev = ok ? `<div class="st-code__preview"><iframe sandbox="" title="${esc(kind === "svg" ? tr("preview.titleSvg", "Picture preview") : tr("preview.titlePage", "Page preview"))}" data-lang="${esc(lang)}"></iframe></div>` : "";
737  return `<div class="st-code">${head}<pre><code>${esc(code)}</code></pre>${prev}</div>`;
738}
739function blocks(text) {
740  const out = [], lines = text.split("\n");
741  let para = [], list = null;
742  const flushPara = () => { if (para.length) out.push(`<p>${para.map(inline).join("<br>")}</p>`); para = []; };
743  const flushList = () => { if (list) out.push(`<${list.tag}>${list.items.map((i) => `<li>${inline(i)}</li>`).join("")}</${list.tag}>`); list = null; };
744  for (let i = 0; i < lines.length; i++) {
745    const l = lines[i];
746    let m;
747    if (!l.trim()) { flushPara(); flushList(); continue; }
748    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; }
749    if (/^\s*([-*_])\s*\1\s*\1[\s\1]*$/.test(l)) { flushPara(); flushList(); out.push("<hr>"); continue; }
750    if ((m = l.match(/^>\s?(.*)$/))) { flushPara(); flushList(); out.push(`<blockquote>${inline(m[1])}</blockquote>`); continue; }
751    if (/^\s*\|.*\|\s*$/.test(l) && i + 1 < lines.length && /^\s*\|?[\s:-]+\|[\s|:-]*$/.test(lines[i + 1])) {
752      flushPara(); flushList();
753      const cells = (row) => row.trim().replace(/^\||\|$/g, "").split("|").map((c) => inline(c.trim()));
754      let html = `<table><thead><tr>${cells(l).map((c) => `<th>${c}</th>`).join("")}</tr></thead><tbody>`;
755      i += 2;
756      while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) html += `<tr>${cells(lines[i++]).map((c) => `<td>${c}</td>`).join("")}</tr>`;
757      i--;
758      out.push(html + "</tbody></table>");
759      continue;
760    }
761    if ((m = l.match(/^\s*(?:[-*+]|(\d+)[.)])\s+(.*)$/))) {
762      flushPara();
763      const tag = m[1] ? "ol" : "ul";
764      if (!list || list.tag !== tag) { flushList(); list = {tag, items: []}; }
765      list.items.push(m[2]);
766      continue;
767    }
768    if (list && /^\s{2,}\S/.test(l)) { list.items[list.items.length - 1] += " " + l.trim(); continue; }
769    flushList();
770    para.push(l);
771  }
772  flushPara(); flushList();
773  return out.join("");
774}
775function markdown(text) {
776  let html = "", rest = text;
777  for (;;) {
778    const m = rest.match(/(^|\n)```([^\n`]*)\n/);
779    if (!m) { html += blocks(rest); break; }
780    html += blocks(rest.slice(0, m.index));
781    rest = rest.slice(m.index + m[0].length);
782    const end = rest.match(/(^|\n)```[ \t]*(\n|$)/);
783    if (!end) { html += codeBlock(m[2].trim(), rest, false); break; }  // still streaming: no preview of a half-written block
784    html += codeBlock(m[2].trim(), rest.slice(0, end.index), true);
785    rest = rest.slice(end.index + end[0].length);
786  }
787  return html;
788}
789
790// ------------------------------------------------------------------ Chat
791// The sampling shown until the user changes it is the model card's thinking set. Untouched, the page sends NO sampling
792// fields: the server picks the card's set for the request's thinking state (thinking 1.0 / 0.95 / 20, not thinking
793// 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
794// values untouched counts as "not set" too.
795const DEFAULTS = {thinking: "high", temperature: 1.0, top_p: 0.95, top_k: 20, max: "", seed: "", show: true, esp: true, mcp: true, math: false,
796                  chatList: false, chatEdit: false, whileBusy: "wait"};
797const OLD_DEFAULT_TEMPERATURE = 0.6;
798function samplingUntouched(s) {
799  const t = +s.temperature;
800  return (t === DEFAULTS.temperature || t === OLD_DEFAULT_TEMPERATURE) && +s.top_p === DEFAULTS.top_p && +s.top_k === DEFAULTS.top_k;
801}
802let settings = {...DEFAULTS, ...store.get("sampling", {})};
803if (samplingUntouched(settings)) settings.temperature = DEFAULTS.temperature;
804let messages = store.get("chat", []);   // the open chat's messages (chats-ui.js: with the saved-chats list on, also that chat's own)
805let attachments = [];                 // {name, url}
806let busy = null;                      // {controller, msg, cut, cutAfterTool}
807let pending = null;                   // a message parked while an answer is written: {text, images, files, mode}
808function timeStr(t) { return new Date(t).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit"}); }
809
810function msgEl(m, i) {
811  const el = document.createElement("div");
812  el.className = `st-msg st-msg--${m.role}`;
813  el.dataset.i = i;
814  if (m.role === "user") {
815    if (m.files && m.files.length) {
816      const wrap = document.createElement("div");
817      wrap.className = "msg-images";
818      for (const f of m.files) {
819        const c = document.createElement("span");
820        c.className = "chip";
821        c.innerHTML = icon("attach", "st-icon st-icon--sm");
822        c.append(f.name);
823        wrap.appendChild(c);
824      }
825      el.appendChild(wrap);
826    }
827    if (m.images && m.images.length) {
828      const wrap = document.createElement("div");
829      wrap.className = "msg-images";
830      for (const im of m.images) {
831        if (im.url) { const img = document.createElement("img"); img.src = im.url; img.alt = im.name || tr("chat.image", "image"); wrap.appendChild(img); }
832        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); }
833      }
834      el.appendChild(wrap);
835    }
836    const b = document.createElement("div");
837    b.className = "st-bubble";
838    b.textContent = m.text;
839    el.appendChild(b);
840    const meta = document.createElement("div");
841    meta.className = "st-msg__meta";
842    meta.textContent = `${tr("chat.you", "You")} · ${timeStr(m.time)}`;
843    el.appendChild(meta);
844  } else {
845    el.innerHTML = `<details class="st-collapse think" hidden><summary>${icon("thinking", "st-icon st-icon--sm")}<span class="think-title"></span>` +
846      `${icon("chevron", "st-icon st-icon--sm st-chev")}</summary><div class="st-collapse__body thinking"></div></details>` +
847      `<div class="st-bubble"></div><div class="st-msg__meta"><span class="meta-text"></span>` +
848      `<button class="st-btn st-btn--icon" data-msg-copy aria-label="${esc(tr("chat.copyAnswer", "Copy the answer"))}" title="${esc(tr("chat.copy", "Copy"))}">${icon("copy")}</button></div>`;
849    updateAssistant(el, m, false);
850  }
851  const actions = msgActions(m, i);                 // edit / regenerate / rewind (chats-ui.js), when switched on
852  if (actions) el.appendChild(actions);
853  return el;
854}
855// One MCP tool call in the answer: a compact block (name, state, a one-line preview) that opens to the arguments and
856// the result as the model read it.  Its body is built only while open: a result can be 20,000 characters.
857const TOOL_STATE = {writing: ["st-badge--reading", () => tr("tool.writing", "Writing")], running: ["st-badge--generating", () => tr("tool.running", "Running")],
858                    done: ["", () => tr("tool.done", "Done")], error: ["st-badge--error", () => tr("tool.error", "Error")],
859                    skipped: ["st-badge--queued", () => tr("tool.skipped", "Not run")]};
860function toolHtml(t, k) {
861  const [cls, labelOf] = TOOL_STATE[t.state] || ["", () => t.state];
862  const label = labelOf();
863  const args = t.arguments == null ? "" : JSON.stringify(t.arguments, null, 2);
864  const preview = t.result != null ? t.result : args.replace(/\s+/g, " ");
865  let body = "";
866  if (t.open) {
867    body = `<div class="tool-call__label">${esc(tr("tool.arguments", "Arguments"))}</div><pre class="tool-call__pre">${esc(args || tr("tool.beingWritten", "(being written)"))}</pre>`;
868    if (t.result != null) {
869      body += `<div class="tool-call__label">${esc(t.ok ? tr("tool.result", "Result") : tr("tool.error", "Error"))}${t.chars ? ` · ${esc(tr("tool.chars", "{n} characters", {n: fmt(t.chars)}))}` : ""}` +
870              `${t.truncated ? esc(tr("tool.cut", ", cut for the model")) : ""}</div><pre class="tool-call__pre">${esc(t.result)}</pre>`;
871    }
872  }
873  return `<details class="st-collapse tool-call" data-tool="${k}" data-state="${esc(t.state)}"${t.open ? " open" : ""}>` +
874    `<summary>${icon("tool", "st-icon st-icon--sm")}<span class="tool-call__name" title="${esc(t.name || "")}">${esc(t.tool || t.name || "tool")}</span>` +
875    (t.server ? `<span class="muted small">${esc(t.server)}</span>` : "") +
876    `<span class="tool-call__preview muted">${esc(preview.slice(0, 200))}</span>` +
877    `<span class="st-badge ${cls}">${esc(label)}</span>${t.ms != null && t.state !== "skipped" ? `<span class="muted small">${fmt(t.ms / 1000, 1)} s</span>` : ""}` +
878    `${icon("chevron", "st-icon st-icon--sm st-chev")}</summary><div class="st-collapse__body">${body}</div></details>`;
879}
880// Raster tool results are same-origin cached files; credentials stay in request headers.
881const mediaBlobs = new Map();
882let mediaEpoch = 0;
883function clearToolMedia() {
884  mediaEpoch++;
885  for (const pending of mediaBlobs.values()) pending.then((url) => URL.revokeObjectURL(url), () => {});
886  mediaBlobs.clear();
887}
888window.addEventListener("pagehide", clearToolMedia);
889window.addEventListener("pageshow", (event) => { if (event.persisted) hydrateToolImages(document); });
890function safeToolMedia(url) { return typeof url === "string" && /^tool-media\/[0-9a-f]{64}\.(png|jpg|webp)$/.test(url); }
891function toolImages(t) {
892  return (t.images || []).filter((im) => safeToolMedia(im.url)).map((im) =>
893    `<figure class="tool-image"><img data-tool-image="${esc(im.url)}" alt="Tool image" loading="lazy">` +
894    `<figcaption><a class="st-btn" data-tool-download="${esc(im.url)}" download="${esc(im.name || "generated-image.png")}">Download image</a></figcaption></figure>`).join("");
895}
896function hydrateToolImages(root) {
897  root.querySelectorAll("[data-tool-image]").forEach((img) => {
898    const url = img.dataset.toolImage, epoch = mediaEpoch;
899    if (!safeToolMedia(url)) return;
900    if (!mediaBlobs.has(url)) mediaBlobs.set(url, fetch(url, {headers: headers()}).then((r) => {
901      if (!r.ok) throw new Error("Image unavailable");
902      return r.blob();
903    }).then((b) => URL.createObjectURL(b)).catch((e) => {if (epoch === mediaEpoch) mediaBlobs.delete(url); throw e;}));
904    mediaBlobs.get(url).then((blob) => {
905      if (epoch !== mediaEpoch || !img.isConnected) return;
906      img.src = blob;
907      const a = img.closest("figure").querySelector("[data-tool-download]");
908      a.href = blob;
909    }).catch(() => { img.alt = "Image unavailable; try refreshing"; });
910  });
911}
912// the answer's text with the tool blocks where the model called them
913// math (opt-in, serve/web/math.js): formulas become placeholders before the Markdown runs and are drawn after it
914function answerMarkdown(text) {
915  return settings.math ? StrataMath.markdown(text, markdown) : markdown(text);
916}
917function answerHtml(m) {
918  if (!m.tools || !m.tools.length) return answerMarkdown(m.text || "");
919  let html = "", pos = 0;
920  m.tools.forEach((t, k) => {
921    const at = Math.min(Math.max(t.at || 0, pos), m.text.length);
922    if (at > pos) html += answerMarkdown(m.text.slice(pos, at));
923    pos = at;
924    html += toolHtml(t, k) + toolImages(t);
925  });
926  return html + answerMarkdown(m.text.slice(pos));
927}
928// a tool event from the stream (the `strata_mcp` field of a chunk)
929function onTool(m, x) {
930  if (x.event === "limit") { m.limit = x.max_rounds; return; }
931  m.tools = m.tools || [];
932  let t = m.tools.find((y) => y.id === x.id);
933  if (!t) { t = {id: x.id, name: x.name, at: m.text.length, rat: m.reasoning.length, state: "writing"}; m.tools.push(t); }
934  if (x.event === "call") {
935    Object.assign(t, {name: x.name, server: x.server, tool: x.tool, arguments: x.arguments, round: x.round, state: "running"});
936  } else if (x.event === "result") {
937    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,
938                      state: x.skipped ? "skipped" : x.ok ? "done" : "error"});
939  }
940}
941function updateAssistant(el, m, streaming) {
942  const det = el.querySelector("details.think");
943  if (m.reasoning) {
944    det.hidden = false;
945    const thinkingNow = streaming && !m.text;
946    el.querySelector(".think-title").textContent = thinkingNow ? tr("think.now", "Thinking…") :
947      m.thinkSecs != null ? tr("think.for", "Thought for {s} s", {s: fmt(m.thinkSecs, 1)}) : tr("think.done", "Thoughts");
948    const body = el.querySelector(".thinking");
949    if (det.open || thinkingNow) body.textContent = m.reasoning;
950    else body.dataset.pending = "1";
951    // open while it streams (if wanted), closed once the answer starts - unless the user toggled it themselves
952    if (thinkingNow && settings.show && !det.dataset.touched && !det.open) { det._auto = true; det.open = true; }
953    if (!thinkingNow && det.open && !det.dataset.touched) { det._auto = true; det.open = false; }
954  }
955  const bubble = el.querySelector(".st-bubble");
956  if (m.error) {
957    bubble.innerHTML = `<div class="msg-error"></div>`;
958    bubble.firstChild.textContent = m.error;
959  } else if (!m.text && streaming && !(m.tools && m.tools.length)) {
960    bubble.innerHTML = m.reasoning ? `<span class="muted cursor">Writing</span>` : `<span class="cursor"></span>`;
961  } else {
962    bubble.innerHTML = answerHtml(m);
963    hydrateToolImages(bubble);
964    if (settings.math) StrataMath.hydrate(bubble);
965    if (streaming) bubble.classList.add("cursor"); else bubble.classList.remove("cursor");
966  }
967  el.querySelector(".meta-text").textContent = m.meta || (streaming ? "" : m.stopped ? tr("chat.stopped", "Stopped") : "");
968  el.querySelector("[data-msg-copy]").hidden = streaming || !m.text;
969}
970function renderChat() {
971  const chat = $("chat");
972  chat.querySelectorAll(".st-msg").forEach((e) => e.remove());
973  $("chat-empty").hidden = messages.length > 0;
974  messages.forEach((m, i) => chat.appendChild(msgEl(m, i)));
975  renderSidebar();
976  renderParent();
977  renderUndoBar();
978  scrollDown(true);
979}
980// Follow the answer while the reader has not left (#4014). Asking "am I within 120 px of the bottom?" on every frame pulled
981// the view back after every wheel notch (a notch is about 100 px), so scrolling up during a long answer only worked by
982// dragging the scrollbar. Now the reader's own input lets go (wheel up, a finger or a key moving up, the scrollbar), and a
983// scroll back to the bottom follows again.
984let stickToBottom = true, lastReaderInput = 0;
985const FOLLOW_SLACK = 24, FAR_AWAY = 400, INPUT_WINDOW_MS = 400;
986function followAfterScroll(distance, wasFollowing, msSinceInput) {
987  if (distance <= FOLLOW_SLACK) return true;
988  if (msSinceInput <= INPUT_WINDOW_MS || distance > FAR_AWAY) return false;
989  return wasFollowing;
990}
991function scrollDown(force) {
992  const s = $("chat-scroll");
993  if (force) stickToBottom = true;
994  if (stickToBottom) s.scrollTop = s.scrollHeight;
995}
996(function watchReader() {
997  const s = $("chat-scroll");
998  const touch = () => { lastReaderInput = Date.now(); };
999  s.addEventListener("wheel", (e) => { touch(); if (e.deltaY < 0 && s.scrollTop > 0) stickToBottom = false; }, {passive: true});
1000  s.addEventListener("touchmove", touch, {passive: true});
1001  s.addEventListener("pointerdown", touch, {passive: true});
1002  s.addEventListener("keydown", (e) => {
1003    touch();
1004    if (["PageUp", "ArrowUp", "Home"].includes(e.key) && e.target === s && s.scrollTop > 0) stickToBottom = false;
1005  });
1006  s.addEventListener("scroll", () => {
1007    stickToBottom = followAfterScroll(s.scrollHeight - s.scrollTop - s.clientHeight, stickToBottom, Date.now() - lastReaderInput);
1008  }, {passive: true});
1009})();
1010
1011$("chat").addEventListener("click", (e) => {
1012  const cc = e.target.closest("[data-code-copy]");
1013  if (cc) { copyText(cc.closest(".st-code").querySelector("pre").textContent, cc); return; }
1014  // an svg/html block: flip between its code and its sandboxed preview. Closing the preview also turns scripts off.
1015  const pv = e.target.closest("[data-preview-toggle]");
1016  if (pv) {
1017    const box = pv.closest(".st-code");
1018    const on = box.dataset.preview === "true";
1019    if (on) delete box.dataset.preview; else box.dataset.preview = "true";
1020    pv.setAttribute("aria-pressed", String(!on));
1021    pv.setAttribute("aria-label", on ? pv.dataset.previewLabel : tr("preview.showCode", "Show the code"));
1022    const fr = box.querySelector("iframe");
1023    if (on) fillPreview(fr, false, true);
1024    else if (!fr.dataset.opened) fillPreview(fr, false);
1025    return;
1026  }
1027  const rs = e.target.closest("[data-preview-scripts]");
1028  if (rs) {
1029    const fr = rs.closest(".st-code").querySelector("iframe");
1030    const run = fr.dataset.scripts !== "1";
1031    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;
1032    fillPreview(fr, run);
1033    return;
1034  }
1035  const mc = e.target.closest("[data-msg-copy]");
1036  if (mc) { const i = +mc.closest(".st-msg").dataset.i; copyText(messages[i].text, mc); return; }
1037  // a tool block: its open state lives in the message (the answer is rebuilt while it streams), so the click sets it
1038  const sum = e.target.closest(".tool-call > summary");
1039  if (sum) {
1040    e.preventDefault();
1041    const el = sum.closest(".st-msg"), m = messages[+el.dataset.i], t = m && m.tools && m.tools[+sum.parentElement.dataset.tool];
1042    if (!t) return;
1043    t.open = !t.open;
1044    updateAssistant(el, m, !!busy && busy.msg === m);
1045  }
1046});
1047$("chat").addEventListener("toggle", (e) => {
1048  const d = e.target;
1049  if (d.tagName !== "DETAILS" || !d.classList.contains("think")) return;
1050  if (d._auto) { d._auto = false; return; }          // our own open/close, not the user's
1051  d.dataset.touched = "1";
1052  const body = d.querySelector(".thinking");
1053  if (d.open && body.dataset.pending) { body.textContent = messages[+d.closest(".st-msg").dataset.i].reasoning; delete body.dataset.pending; }
1054}, true);
1055
1056function apiMessages() {
1057  const out = [];
1058  for (const m of messages) {
1059    if (m.role === "user") {
1060      const imgs = (m.images || []).filter((i) => i.url);
1061      const text = userText(m);
1062      out.push({role: "user", content: imgs.length ? [{type: "text", text},
1063        ...imgs.map((i) => ({type: "image_url", image_url: {url: i.url}}))] : text});
1064    } else if (!(busy && busy.msg === m)) {            // the answer being asked for now is not history yet
1065      out.push(...assistantMessages(m));
1066    }
1067  }
1068  return out;
1069}
1070// An answer that used MCP tools goes back as the model wrote it: per round the text before the calls, the calls and
1071// their results (as the model read them), then the rest - so the next question can build on what the tools found.
1072function assistantMessages(m) {
1073  const ran = (m.tools || []).filter((t) => t.round != null && t.result != null && t.state !== "skipped");
1074  // #1392: a turn with no answer text (only reasoning, a stop before the first content token, or an error) still goes
1075  // back as an assistant turn, so the history keeps alternating and a reasoning model sees that it already answered.
1076  // The server leaves such a turn out of the prompt itself (serve/frontend.py, #843); reasoning_content rides along.
1077  if (!ran.length) {
1078    const msg = {role: "assistant", content: m.text || ""};
1079    if (!m.text && m.reasoning) msg.reasoning_content = m.reasoning;
1080    return [msg];
1081  }
1082  const out = [];
1083  let pos = 0;
1084  for (const r of [...new Set(ran.map((t) => t.round))]) {
1085    const calls = ran.filter((t) => t.round === r);
1086    const at = Math.min(Math.max(pos, calls[0].at || 0), m.text.length);
1087    out.push({role: "assistant", content: m.text.slice(pos, at).trim(),
1088              tool_calls: calls.map((t) => ({id: t.id, type: "function", function: {name: t.name, arguments: JSON.stringify(t.arguments || {})}}))});
1089    for (const t of calls) {
1090      const pictures = t.vision ? (t.images || []).filter((im) => safeToolMedia(im.url)) : [];
1091      const content = pictures.length ? [{type: "text", text: t.result}, ...pictures.map((im) =>
1092        ({type: "image_url", image_url: {url: "strata-tool-media:" + im.url.split("/").pop()}}))] : t.result;
1093      out.push({role: "tool", tool_call_id: t.id, content});
1094    }
1095    pos = at;
1096  }
1097  const rest = m.text.slice(pos).trim();
1098  if (rest) out.push({role: "assistant", content: rest});
1099  return out;
1100}
1101
1102function busyHint() {
1103  const mode = settings.whileBusy;
1104  return mode === "queue" ? tr("composer.hintQueue", "Enter sends when the answer is done")
1105       : mode === "interject" ? tr("composer.hintInterject", "Enter stops the answer here and sends now") : "";
1106}
1107// While an answer is written, Send is off ("wait", as always) or parks the message ("queue", "interject": Chat settings)
1108const parksWhileBusy = () => settings.whileBusy === "queue" || settings.whileBusy === "interject";
1109function setBusy(on) {
1110  $("stop-btn").hidden = !on;
1111  $("send-btn").disabled = (on && !parksWhileBusy()) || !!panel;
1112  $("input").disabled = !!panel;
1113  $("composer-hint").textContent = panel ? tr("composer.finishOpen", "Save or cancel what is open above to continue")
1114                                         : on ? busyHint() : tr("composer.newline", "Shift+Enter: new line");
1115  if (settings.chatEdit) syncActions();                 // the buttons follow the state: none under the answer being written
1116  $("s-list").disabled = $("s-edit").disabled = !!busy || !!panel;      // they change the messages on the screen
1117  renderUndoBar();
1118  renderPending();
1119}
1120
1121// A message sent while an answer is being written (#4004). "queue": it waits and goes when the answer is done. "interject": the
1122// answer stops where it is (what is written stays, marked interrupted) and the message goes at once; if a tool is running, the
1123// tool finishes first. Only one message waits. Off by default: with "wait" the page does nothing, as before.
1124function park(p, own) {
1125  if (!parksWhileBusy()) return;
1126  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; }
1127  pending = {...p, mode: settings.whileBusy};
1128  if (own) { attachments = []; renderAttachments(); $("input").value = ""; autosize(); }
1129  if (pending.mode === "interject") requestCut();
1130  setBusy(!!busy);
1131}
1132function requestCut() {
1133  if (!busy || busy.cut) return;
1134  if ((busy.msg.tools || []).some((t) => t.state === "running")) { busy.cutAfterTool = true; return; }   // let the tool finish
1135  busy.cut = true;
1136  busy.controller.abort();
1137}
1138function renderPending() {
1139  let el = $("pending");
1140  if (!pending) { if (el) el.remove(); return; }
1141  if (!el) {
1142    el = node("div", "pending");
1143    el.id = "pending";
1144    el.setAttribute("role", "status");
1145    el.innerHTML = "<span class=\"pending__text\"></span><span class=\"pending__actions\"><button type=\"button\" class=\"st-btn st-btn--secondary\" data-pending-now></button>" +
1146      "<button type=\"button\" class=\"st-btn st-btn--secondary\" data-pending-back></button></span>";
1147    el.querySelector("[data-pending-now]").onclick = pendingNow;
1148    el.querySelector("[data-pending-back]").onclick = releasePending;
1149    $("composer").before(el);
1150  }
1151  const quote = (pending.text || (pending.files[0] || pending.images[0] || {}).name || "").replace(/\s+/g, " ").slice(0, 70);
1152  const text = !busy ? tr("pending.ready", "Not sent yet: “{text}”", {text: quote})
1153    : pending.mode === "queue" ? tr("pending.queued", "Sends when this answer is done: “{text}”", {text: quote})
1154    : busy.cutAfterTool ? tr("pending.afterTool", "Waiting for the tool to finish, then sending: “{text}”", {text: quote})
1155    : tr("pending.cutting", "Stopping the answer, then sending: “{text}”", {text: quote});
1156  el.querySelector(".pending__text").textContent = text;
1157  const now = el.querySelector("[data-pending-now]");
1158  now.textContent = busy ? tr("pending.sendNow", "Send now") : tr("pending.send", "Send");
1159  now.hidden = !!busy && pending.mode === "interject";            // already on its way
1160  el.querySelector("[data-pending-back]").textContent = tr("pending.takeBack", "Take back");
1161}
1162function pendingNow() {
1163  if (!pending) return;
1164  if (busy) { pending.mode = "interject"; requestCut(); setBusy(true); return; }
1165  const p = pending;
1166  pending = null;
1167  setBusy(false);
1168  send(p);
1169}
1170// the waiting message goes back into the message box (a chat switch or a new chat must not lose it)
1171function releasePending() {
1172  if (!pending) return;
1173  const p = pending;
1174  pending = null;
1175  if (!$("input").value.trim()) $("input").value = p.text;
1176  else $("input").value = `${p.text}\n\n${$("input").value}`;
1177  attachments = [...p.images, ...p.files, ...attachments];
1178  renderAttachments(); autosize();
1179  setBusy(!!busy);
1180}
1181// after an answer: an interrupted one sends an interjection, a finished one sends a queued message
1182function settlePending(cut, finished) {
1183  if (!pending) return;
1184  if ((pending.mode === "interject" && cut) || (pending.mode === "queue" && finished)) {
1185    const p = pending;
1186    pending = null;
1187    setBusy(false);
1188    send(p);
1189  }
1190}
1191
1192// the message box (or a parked message, `payload`) becomes a user turn and a reply is asked for
1193async function send(payload) {
1194  const own = !payload;
1195  const p = payload || {text: $("input").value.trim(), images: attachments.filter((a) => a.kind !== "file"),
1196                        files: attachments.filter((a) => a.kind === "file")};
1197  if (!p.text && !p.images.length && !p.files.length) return;
1198  if (panel) return;                                  // something is open above (an edit): finish it first
1199  if (busy) { park(p, own); return; }
1200  clearUndo();
1201  messages.push({role: "user", text: p.text, images: p.images, files: p.files, time: Date.now()});
1202  if (own) {
1203    attachments = [];
1204    renderAttachments();
1205    $("input").value = "";
1206    autosize();
1207  }
1208  return generateReply();
1209}
1210// an answer for the messages as they are: the last one is a user turn
1211async function generateReply() {
1212  const m = {role: "assistant", text: "", reasoning: "", time: Date.now()};
1213  messages.push(m);
1214  renderChat();
1215  const el = $("chat").lastElementChild;
1216  const controller = new AbortController();
1217  busy = {controller, msg: m, cut: false, cutAfterTool: false};
1218  setBusy(true);
1219  paintLive();
1220
1221  const body = {model: health.model, messages: apiMessages(), stream: true,
1222                reasoning_effort: settings.thinking};
1223  if (!(settings.temperature > 0)) {
1224    body.temperature = 0;
1225  } else if (!samplingUntouched(settings)) {
1226    Object.assign(body, {temperature: +settings.temperature, top_p: +settings.top_p, top_k: +settings.top_k});
1227  }
1228  if (settings.seed) body.seed = +settings.seed;
1229  if (settings.max) body.max_tokens = +settings.max;
1230  if (projectionLoaded()) body.experimental_speed_projection = !!settings.esp;
1231  if (settings.mcp !== false && mcpInfo.tools > 0) body.strata_mcp = true;   // this server may run MCP tools for it
1232
1233  let firstAt = null, thinkStart = null, usage = null, frame = 0;
1234  const paint = () => { frame = 0; updateAssistant(el, m, true); scrollDown(); };
1235  try {
1236    const r = await fetch("v1/chat/completions", {method: "POST", headers: headers(true), body: JSON.stringify(body),
1237                                                   signal: controller.signal});
1238    if (!r.ok) {
1239      let msg = `HTTP ${r.status}`;
1240      try { msg = (await r.json()).error.message || msg; } catch (e) { /* not json */ }
1241      if (r.status === 401) msg = tr("toast.keyNeeded", "This server needs an API key: add it under About > Settings.");
1242      throw new Error(msg);
1243    }
1244    const reader = r.body.getReader(), dec = new TextDecoder();
1245    let buf = "";
1246    for (;;) {
1247      const {value, done} = await reader.read();
1248      if (done) break;
1249      buf += dec.decode(value, {stream: true});
1250      let nl;
1251      while ((nl = buf.indexOf("\n")) >= 0) {
1252        const line = buf.slice(0, nl).trim();
1253        buf = buf.slice(nl + 1);
1254        if (!line.startsWith("data:")) continue;              // ": keep-alive" comments while a long prompt is read
1255        const data = line.slice(5).trim();
1256        if (data === "[DONE]") continue;
1257        let j;
1258        try { j = JSON.parse(data); } catch (e) { continue; }
1259        if (j.error) throw new Error(j.error.message || tr("toast.engineError", "the engine reported an error"));
1260        if (j.usage) usage = j.usage;
1261        if (j.strata_mcp) {
1262          onTool(m, j.strata_mcp);
1263          // an interjection waited for a running tool: it has its result now, so the answer can stop
1264          if (busy.cutAfterTool && !busy.cut && !(m.tools || []).some((t) => t.state === "running")) { busy.cut = true; controller.abort(); }
1265        }
1266        const d = (j.choices && j.choices[0] && j.choices[0].delta) || {};
1267        const lastTool = m.tools && m.tools.length ? m.tools[m.tools.length - 1] : null;   // a new round after a tool
1268        if (d.reasoning_content) {
1269          if (!firstAt) firstAt = performance.now();
1270          if (!thinkStart) thinkStart = performance.now();
1271          if (lastTool && m.reasoning && lastTool.rat === m.reasoning.length) m.reasoning += "\n\n";
1272          m.reasoning += d.reasoning_content;
1273        }
1274        if (d.content) {
1275          if (!firstAt) firstAt = performance.now();
1276          if (thinkStart && m.thinkSecs == null) m.thinkSecs = (performance.now() - thinkStart) / 1000;
1277          if (lastTool && m.text && lastTool.at === m.text.length) m.text += "\n\n";
1278          m.text += d.content;
1279        }
1280        if (!frame) frame = requestAnimationFrame(paint);
1281      }
1282    }
1283  } catch (e) {
1284    if (e.name === "AbortError") m.stopped = true;
1285    else { m.error = e.message || String(e); toast("error", tr("toast.requestFailed", "The request failed"), m.error, 6000); }
1286  }
1287  const cut = busy.cut;                                      // an interjection ended it: kept as written, marked interrupted
1288  if (cut) m.interrupted = true;
1289  if (thinkStart && m.thinkSecs == null) m.thinkSecs = (performance.now() - thinkStart) / 1000;
1290  const n = usage ? usage.completion_tokens : null;
1291  const ended = cut ? tr("chat.interruptedLower", "interrupted") : tr("chat.stoppedLower", "stopped");
1292  if (n && firstAt) {
1293    const secs = (performance.now() - firstAt) / 1000;
1294    m.meta = tr("chat.tokens", "{n} tokens", {n: fmt(n)}) + (secs > 0.25 ? ` · ${fmt(n / secs, 1)} tok/s` : "") + (m.stopped ? ` · ${ended}` : "") +
1295             (projectionLoaded() ? (settings.esp ? ` · ${tr("chat.projectionOn", "projection on")}` : ` · ${tr("chat.projectionOff", "projection off")}`) : "");
1296  } else if (m.stopped) {
1297    m.meta = cut ? tr("chat.interrupted", "Interrupted") : tr("chat.stopped", "Stopped");
1298  }
1299  for (const t of m.tools || []) if (t.state === "writing" || t.state === "running") { t.state = "skipped"; t.ms = null; }
1300  const ran = (m.tools || []).filter((t) => t.state === "done" || t.state === "error").length;
1301  if (ran) m.meta = `${m.meta ? `${m.meta} · ` : ""}${tr("chat.toolCalls", {one: "{n} tool call", other: "{n} tool calls"}, {n: ran})}`;
1302  if (m.limit) m.meta = `${m.meta || ""} · ${tr("chat.toolLimit", "stopped at the limit of {n} tool rounds (mcp.max_rounds)", {n: m.limit})}`;
1303  busy = null;
1304  setBusy(false);
1305  paintLive();
1306  if (frame) cancelAnimationFrame(frame);
1307  updateAssistant(el, m, false);
1308  saveChat();
1309  scrollDown();
1310  settlePending(cut, !m.stopped && !m.error);
1311}
1312
1313$("composer").onsubmit = (e) => { e.preventDefault(); send(); };
1314$("stop-btn").onclick = () => { if (busy) busy.controller.abort(); };
1315$("input").addEventListener("keydown", (e) => {
1316  if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); send(); }
1317});
1318function autosize() { const t = $("input"); t.style.height = "auto"; t.style.height = `${Math.min(t.scrollHeight, innerHeight * 0.4)}px`; }
1319$("input").addEventListener("input", autosize);
1320
1321// 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)
1322$("new-btn").onclick = () => {
1323  if (busy) { stillWriting(); return; }
1324  if (panel) { closePanel(); }
1325  clearUndo();
1326  releasePending();
1327  if (!messages.length) return;
1328  const backup = messages;
1329  clearToolMedia();
1330  messages = [];
1331  saveChat();
1332  renderChat();
1333  toast("info", tr("chat.newToast", "New chat"), tr("chat.clearedToast", "The last one was cleared."), 6000, {label: tr("undo", "Undo"), run: () => {
1334    if (busy || messages.length) return;                         // a new question since: the cleared chat is not put back over it
1335    messages = backup; saveChat(); renderChat();
1336  }});
1337};
1338$("export-btn").onclick = () => {
1339  if (!messages.length) { toast("info", tr("export.nothing", "Nothing to save yet")); return; }
1340  const tools = (m) => (m.tools || []).filter((t) => t.result != null).map((t) =>
1341    `<details><summary>Tool ${t.server ? `${t.server} / ` : ""}${t.tool || t.name}${t.ok ? "" : " (error)"}</summary>\n\n` +
1342    `\`\`\`json\n${JSON.stringify(t.arguments || {}, null, 2)}\n\`\`\`\n\n\`\`\`\n${t.result}\n\`\`\`\n\n</details>\n\n`).join("");
1343  const md = messages.map((m) => m.role === "user" ? `## You\n\n${m.text}\n` :
1344    `## ${health.model}\n\n${m.reasoning ? `<details><summary>Thinking</summary>\n\n${m.reasoning}\n\n</details>\n\n` : ""}${tools(m)}${m.text || m.error || ""}\n`).join("\n");
1345  const a = document.createElement("a");
1346  a.href = URL.createObjectURL(new Blob([md], {type: "text/markdown"}));
1347  a.download = `strata-chat-${new Date().toISOString().slice(0, 16).replace(/[:T]/g, "-")}.md`;
1348  a.click();
1349  setTimeout(() => URL.revokeObjectURL(a.href), 5000);
1350};
1351
1352// pictures and text files: the attach button, dropping them on the chat, or pasting a picture (issue #30)
1353const 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;
1354const MAX_TEXT_FILE = 512 * 1024;
1355function isTextFile(f) {
1356  return f.type.startsWith("text/") || /json|xml|javascript|yaml|toml|x-sh|x-python/.test(f.type) ||
1357         TEXT_EXT.test(f.name) || /(^|[\\/])(makefile|dockerfile|readme|license)$/i.test(f.name);
1358}
1359function addFiles(files) {
1360  for (const f of files) {
1361    if (f.type.startsWith("image/")) {
1362      if (!health.images) { toast("warn", tr("file.picturesOff", "Pictures are off"), tr("file.picturesOffText", "This model was set up for text only.")); continue; }
1363      if (f.size > 20e6) { toast("warn", tr("file.pictureBig", "Picture too large"), tr("file.pictureBigText", "{name} is over 20 MB.", {name: f.name})); continue; }
1364      const r = new FileReader();
1365      r.onload = () => { attachments.push({kind: "image", name: f.name || tr("file.pasted", "pasted image"), url: r.result}); renderAttachments(); };
1366      r.readAsDataURL(f);
1367      continue;
1368    }
1369    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})
1370                                                              : tr("file.notTextOnly", "{name}: attach text files (code, notes, logs, data).", {name: f.name})); continue; }
1371    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; }
1372    const r = new FileReader();
1373    r.onload = () => {
1374      const text = String(r.result);
1375      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; }
1376      attachments.push({kind: "file", name: f.name, text});
1377      renderAttachments();
1378    };
1379    r.readAsText(f);
1380  }
1381}
1382// a file's text in the message, fenced with more backticks than it contains itself
1383function fileBlock(f) {
1384  const longest = Math.max(2, ...(f.text.match(/`+/g) || []).map((s) => s.length));
1385  const fence = "`".repeat(longest + 1);
1386  return `File: ${f.name}\n${fence}\n${f.text}\n${fence}`;
1387}
1388function userText(m) {
1389  const files = (m.files || []).filter((f) => f.text != null);
1390  return [m.text, ...files.map(fileBlock)].filter((s) => s).join("\n\n");
1391}
1392function renderAttachments() {
1393  const box = $("attachments");
1394  box.hidden = !attachments.length;
1395  box.innerHTML = "";
1396  attachments.forEach((a, i) => {
1397    const c = document.createElement("span");
1398    c.className = "chip";
1399    c.innerHTML = icon(a.kind === "file" ? "attach" : "image", "st-icon st-icon--sm");
1400    c.append(a.name);
1401    const x = document.createElement("button");
1402    x.type = "button"; x.className = "st-btn st-btn--icon"; x.setAttribute("aria-label", tr("file.remove", "Remove"));
1403    x.innerHTML = icon("trash");
1404    x.onclick = () => { attachments.splice(i, 1); renderAttachments(); };
1405    c.appendChild(x);
1406    box.appendChild(c);
1407  });
1408}
1409$("attach-btn").onclick = () => $("file").click();
1410// drop files on the chat or the message box
1411for (const id of ["chat", "composer"]) {
1412  const el = $(id);
1413  el.addEventListener("dragover", (e) => {
1414    if (![...(e.dataTransfer || {}).types || []].includes("Files")) return;
1415    e.preventDefault();
1416    $("composer").classList.add("dragging");
1417  });
1418  el.addEventListener("dragleave", () => $("composer").classList.remove("dragging"));
1419  el.addEventListener("drop", (e) => {
1420    $("composer").classList.remove("dragging");
1421    if (!e.dataTransfer || !e.dataTransfer.files.length) return;
1422    e.preventDefault();
1423    addFiles(e.dataTransfer.files);
1424    $("input").focus();
1425  });
1426}
1427$("file").onchange = () => { addFiles($("file").files); $("file").value = ""; };
1428$("input").addEventListener("paste", (e) => {
1429  if (!health.images) return;
1430  const files = [...(e.clipboardData || {}).files || []].filter((f) => f.type.startsWith("image/"));
1431  if (files.length) { e.preventDefault(); addFiles(files); }
1432});
1433
1434// ------------------------------------------------------------------ the chat settings drawer
1435function openDrawer(open) {
1436  $("drawer").dataset.open = String(open);
1437  $("drawer").setAttribute("aria-hidden", String(!open));
1438  $("scrim").hidden = !open;
1439  if (open) { loadDrawer(); loadShared(); loadMcp(); }
1440}
1441const checked = (id) => $(id).getAttribute("aria-checked") === "true";
1442const segValue = (id) => { const b = [...$(id).children].find((x) => x.getAttribute("aria-checked") === "true"); return b ? b.dataset.v : null; };
1443function loadDrawer(s = settings) {
1444  for (const b of $("s-thinking").children) b.setAttribute("aria-checked", String(b.dataset.v === s.thinking));
1445  $("s-temp").value = s.temperature; $("s-topp").value = s.top_p; $("s-topk").value = s.top_k;
1446  $("s-max").value = s.max; $("s-seed").value = s.seed;
1447  $("s-math").setAttribute("aria-checked", String(!!s.math));
1448  $("s-show").setAttribute("aria-checked", String(!!s.show));
1449  $("s-esp").setAttribute("aria-checked", String(s.esp !== false));
1450  $("esp-row").hidden = !projectionLoaded();
1451  $("s-mcp").setAttribute("aria-checked", String(s.mcp !== false));
1452  $("s-share").setAttribute("aria-checked", String(sharedOn));
1453  $("s-list").setAttribute("aria-checked", String(!!s.chatList));
1454  $("s-edit").setAttribute("aria-checked", String(!!s.chatEdit));
1455  for (const b of $("s-busy").children) b.setAttribute("aria-checked", String(b.dataset.v === (s.whileBusy || "wait")));
1456  outputs();
1457}
1458// "Use for other apps too": the server keeps these settings as every client's defaults (GET/POST /settings)
1459let sharedOn = false;
1460async function loadShared() {
1461  try {
1462    const r = await fetch("settings", {headers: headers()});
1463    if (r.ok) sharedOn = !!(await r.json()).shared;
1464  } catch (e) { /* an older server: the switch just stays off */ }
1465  $("s-share").setAttribute("aria-checked", String(sharedOn));
1466}
1467function sharedDefaults(s) {
1468  const d = {reasoning_effort: s.thinking};
1469  if (!(+s.temperature > 0)) d.temperature = 0;
1470  else if (!samplingUntouched(s)) Object.assign(d, {temperature: +s.temperature, top_p: +s.top_p, top_k: +s.top_k});
1471  if (s.seed) d.seed = +s.seed;
1472  if (s.max) d.max_tokens = +s.max;
1473  if (projectionLoaded()) d.experimental_speed_projection = s.esp !== false;
1474  return d;
1475}
1476async function saveShared(on, s) {
1477  const r = await fetch("settings", {method: "POST", headers: headers(true),
1478                                      body: JSON.stringify({defaults: on ? sharedDefaults(s) : null})});
1479  if (!r.ok) {
1480    let msg = `HTTP ${r.status}`;
1481    try { msg = (await r.json()).error.message || msg; } catch (e) { /* not json */ }
1482    throw new Error(msg);
1483  }
1484  sharedOn = !!(await r.json()).shared;
1485}
1486// the engine was started with the experimental-speed-projection control vector (INFO cvec=...)
1487function projectionLoaded() {
1488  const c = lastMetrics && lastMetrics.engine ? lastMetrics.engine.cvec : 0;
1489  return !!c && c !== "0";
1490}
1491function outputs() {
1492  const t = +$("s-temp").value;
1493  $("o-temp").textContent = t === 0 ? tr("drawer.greedy", "0 · greedy") : t.toFixed(2);
1494  $("o-topp").textContent = (+$("s-topp").value).toFixed(2);
1495  $("o-topk").textContent = $("s-topk").value;
1496  const sel = segValue("s-thinking");
1497  $("o-thinking").textContent = sel ? {none: tr("drawer.thinkNone", "answers right away"), low: tr("drawer.thinkLow", "short"),
1498    medium: tr("drawer.thinkMedium", "medium"), high: tr("drawer.thinkHigh", "thorough (default)")}[sel] : "";
1499  const busyMode = segValue("s-busy");
1500  $("o-busy").textContent = {wait: tr("drawer.busyWaitNote", "Send is off until the answer is done, as before."),
1501    queue: tr("drawer.busyQueueNote", "Your message waits and goes as soon as the answer is done."),
1502    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] || "";
1503  for (const id of ["s-topp", "s-topk"]) $(id).disabled = t === 0;
1504}
1505for (const b of $("s-thinking").children) b.onclick = () => { for (const x of $("s-thinking").children) x.setAttribute("aria-checked", String(x === b)); outputs(); };
1506for (const b of $("s-busy").children) b.onclick = () => { for (const x of $("s-busy").children) x.setAttribute("aria-checked", String(x === b)); outputs(); };
1507for (const id of ["s-temp", "s-topp", "s-topk"]) $(id).oninput = outputs;
1508for (const id of ["s-math", "s-show", "s-esp", "s-mcp", "s-share", "s-list", "s-edit"]) {
1509  $(id).onclick = () => $(id).setAttribute("aria-checked", String($(id).getAttribute("aria-checked") !== "true"));
1510}
1511$("s-reset").onclick = () => loadDrawer(DEFAULTS);
1512$("s-apply").onclick = async () => {
1513  const prev = settings;
1514  // the list and the edit controls change the messages on the screen: not while an answer is written or something is open
1515  const locked = !!busy || !!panel;
1516  settings = {thinking: segValue("s-thinking") || "high", temperature: +$("s-temp").value, top_p: +$("s-topp").value,
1517              top_k: +$("s-topk").value, max: $("s-max").value.trim(), seed: $("s-seed").value.trim(),
1518              math: checked("s-math"), show: checked("s-show"), esp: checked("s-esp"), mcp: checked("s-mcp"),
1519              chatList: locked ? !!prev.chatList : checked("s-list"), chatEdit: locked ? !!prev.chatEdit : checked("s-edit"),
1520              whileBusy: segValue("s-busy") || "wait"};
1521  store.set("sampling", settings);
1522  StrataMath.reset();                                  // math on or off: every answer is drawn again
1523  if (settings.chatList !== !!prev.chatList) await setChatList(settings.chatList, true);
1524  if (settings.chatEdit !== !!prev.chatEdit) { clearUndo(); syncActions(); }
1525  if (settings.whileBusy === "wait" && pending) releasePending();    // "wait" parks nothing: a waiting message goes back to the box
1526  setBusy(!!busy);
1527  for (const el of $("chat").querySelectorAll(".st-msg--assistant")) {
1528    const m = messages[+el.dataset.i];
1529    updateAssistant(el, m, !!busy && busy.msg === m);  // the element send() holds stays the same while an answer streams
1530  }
1531  const share = checked("s-share");
1532  openDrawer(false);
1533  if (share || sharedOn) {
1534    try {
1535      await saveShared(share, settings);
1536      toast("success", tr("drawer.saved", "Chat settings saved"), share ? tr("drawer.savedShared", "Other apps (omp, API clients) use these settings from their next request.")
1537                                                                         : tr("drawer.savedOwn", "Other apps use their own settings again."));
1538    } catch (e) {
1539      toast("error", tr("drawer.savedHere", "Saved here, but not for other apps"), e.message, 6000);
1540    }
1541    return;
1542  }
1543  toast("success", tr("drawer.saved", "Chat settings saved"), settings.temperature === 0 ? tr("drawer.savedGreedy", "Greedy: the same question gives the same answer.") : "");
1544};
1545$("sampling-btn").onclick = () => openDrawer(true);
1546$("drawer-close").onclick = () => openDrawer(false);
1547$("scrim").onclick = () => openDrawer(false);
1548document.addEventListener("keydown", (e) => { if (e.key === "Escape" && $("drawer").dataset.open === "true") openDrawer(false); });
1549
1550// ------------------------------------------------------------------ language (serve/web/i18n.js)
1551// The user's own choice, kept in this browser: English until they pick another. /?lang=de shows one for this visit only.
1552const urlLang = new URLSearchParams(location.search).get("lang");
1553$("lang").innerHTML = StrataI18n.LANGUAGES.map(([code, name]) => `<option value="${esc(code)}">${esc(name)}</option>`).join("");
1554function showLanguage() {
1555  $("lang").value = StrataI18n.lang;
1556  renderEmptyChat();
1557  setSidebar(sidebarOpen, false);
1558  outputs();
1559  renderChat();
1560  setBusy(!!busy);
1561  if (lastMetrics) render(lastMetrics);
1562}
1563$("lang").onchange = async () => {
1564  store.set("lang", $("lang").value);
1565  await StrataI18n.setLanguage($("lang").value);
1566  showLanguage();
1567};
1568
1569// ------------------------------------------------------------------ start
1570async function start() {
1571  await StrataI18n.setLanguage(urlLang || store.get("lang", "en"));
1572  $("lang").value = StrataI18n.lang;
1573  renderEmptyChat();
1574  initChats();
1575  if (settings.chatList) await setChatList(true, false);       // the saved-chats list is read before the first draw
1576  setBusy(false);
1577  renderChat();
1578  // /?q=... fills the question in and focuses the box; it is never sent from the address (#4221): any page can link here,
1579  // and a send would go out with the API key and the MCP tools saved in this browser. The person presses Send.
1580  const startQuestion = new URLSearchParams(location.search).get("q");
1581  if (startQuestion) {
1582    history.replaceState(null, "", location.pathname + location.hash);
1583    $("input").value = startQuestion;
1584    autosize();
1585  }
1586  loadHealth().then(loadMcp);
1587  showTab(location.hash.slice(1) || "chat");
1588  if (startQuestion && tab === "chat") $("input").focus();
1589  poll();
1590  requestAnimationFrame(fitHeader);
1591}
1592start();
1593
1594// ------------------------------------------------------------------ images (POST /v1/images/generations)
1595$("img-form").onsubmit = async (ev) => {
1596  ev.preventDefault();
1597  const prompt = $("img-prompt").value.trim();
1598  if (!prompt) return;
1599  const body = {prompt, size: $("img-size").value, response_format: "b64_json"};
1600  if ($("img-seed").value !== "") body.seed = Number($("img-seed").value);
1601  imageBusy = true;
1602  $("img-go").disabled = true;
1603  paintLive();
1604  const t0 = performance.now();
1605  $("img-hint").textContent = "Generating\u2026 (a minute or more on a small GPU)";
1606  try {
1607    const r = await fetch("v1/images/generations", {method: "POST", headers: headers(true), body: JSON.stringify(body)});
1608    const j = await r.json();
1609    if (!r.ok) throw new Error((j.error && j.error.message) || r.statusText);
1610    for (const d of j.data) {
1611      const fig = document.createElement("figure");
1612      const img = document.createElement("img");
1613      img.src = "data:image/png;base64," + d.b64_json;
1614      img.alt = prompt;
1615      const cap = document.createElement("figcaption");
1616      cap.textContent = `${j.size}, seed ${d.seed}, ${((performance.now() - t0) / 1000).toFixed(0)} s: ${prompt}`;
1617      fig.append(img, cap);
1618      $("img-results").prepend(fig);
1619    }
1620    $("img-hint").textContent = "Done. Right-click an image to save it.";
1621  } catch (e) {
1622    $("img-hint").textContent = "";
1623    toast("error", "No image", String(e.message || e), 8000);
1624  } finally {
1625    imageBusy = false;
1626    $("img-go").disabled = false;
1627    paintLive();
1628  }
1629};