okami.mom/strata

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

Niko1221rc1 merge gui-fb3 (6acd50efe)c64702b72

main
8.9 KiB124 linesraw
1"use strict";
2const $ = id => document.getElementById(id);
3let selected = null, detail = null, pane = "input", records = [], state = null, operating = false, stamp = "", actionError = "";
4let apiKey = sessionStorage.getItem("strata.monitor.key") || "";
5document.documentElement.dataset.theme = localStorage.getItem("strata.theme") || "dark";
6const seconds = n => typeof n === "number" ? `${n.toFixed(2)} s` : "—";
7const speed = n => typeof n === "number" ? n.toFixed(1) : "—";
8const active = r => !["completed", "error", "disconnected"].includes(r.state);
9// The run's average decode speed: every token produced over the run divided by the run's decode time, from each
10// finished request's engine timings (predicted_n over predicted_ms). Token-weighted, so a short request does not
11// outweigh a long one - the same figure the engine's DONE lines and the server's totals report. Not the last request.
12function averageDecodeSpeed(rows) {
13  let tokens = 0, ms = 0;
14  for (const r of rows) {
15    const t = r.timings;
16    if (!t) continue;
17    const n = t.predicted_n, d = t.predicted_ms;
18    if (typeof n === "number" && typeof d === "number" && n >= 2 && d > 0) { tokens += n; ms += d; }
19  }
20  return ms > 0 ? tokens / (ms / 1000) : null;
21}
22function text(id, value) { const el = $(id); if (el.textContent !== String(value)) el.textContent = value; }
23async function api(path, body) {
24  const response = await fetch(path, {cache:"no-store", headers:{...(apiKey ? {Authorization:`Bearer ${apiKey}`} : {}), ...(body !== undefined ? {"Content-Type":"application/json"} : {})}, ...(body !== undefined ? {method:"POST", body:JSON.stringify(body)} : {})});
25  const value = await response.json();
26  if (!response.ok) {
27    if (response.status === 401) $("auth").hidden = false;
28    throw new Error(value.error?.message || `HTTP ${response.status}`);
29  }
30  return value;
31}
32function notice(message) { $("error").hidden = !message; text("error", message || ""); }
33function list() {
34  const query = $("search").value.toLowerCase(), filter = $("filter").value;
35  const visible = records.filter(r => `${r.id} ${r.path} ${r.model}`.toLowerCase().includes(query) && (filter === "all" || (filter === "active" ? active(r) : r.state === filter)));
36  const nextStamp = JSON.stringify([visible, selected]);
37  if (stamp === nextStamp) return;
38  stamp = nextStamp;
39  const focusId = document.activeElement?.dataset.request;
40  $("requests").replaceChildren();
41  if (!visible.length) {
42    const empty = document.createElement("div"); empty.className = "empty";
43    empty.textContent = records.length ? "No matching requests." : "No requests yet. API calls will appear here automatically.";
44    $("requests").append(empty);
45  }
46  for (const r of visible) {
47    const button = document.createElement("button"); button.className = `request${selected === r.id ? " selected" : ""}`;
48    button.dataset.request = r.id; button.setAttribute("aria-label", `Request ${r.id}`); button.setAttribute("aria-pressed", String(selected === r.id));
49    const row = document.createElement("div"); row.className = "row";
50    const time = document.createElement("span"); time.textContent = new Date(r.started_at * 1000).toLocaleTimeString();
51    const tag = document.createElement("span"); tag.className = `tag ${r.state}`; tag.textContent = r.state;
52    row.append(time, tag);
53    const endpoint = document.createElement("div"); endpoint.className = "endpoint"; endpoint.textContent = `POST ${r.path}`;
54    const meta = document.createElement("div"); meta.className = "small";
55    meta.textContent = `${r.id} · ${seconds(r.wallclock_s)} · ${r.stream ? "stream" : "JSON response"}${r.http_status ? ` · HTTP ${r.http_status}` : ""}`;
56    button.append(row, endpoint, meta);
57    button.onclick = async () => { selected = r.id; detail = null; list(); await showDetail(); };
58    $("requests").append(button);
59    if (focusId === r.id) button.focus({preventScroll:true});
60  }
61}
62function content() {
63  if (!detail) return;
64  let value = detail[pane] || (pane === "response" && detail.stream ? "Streaming response: see Output and the request error, if any." : "No content.");
65  if (pane === "output") { try { value = JSON.stringify(JSON.parse(value), null, 2); } catch (_) {} }
66  text("content", value);
67  const note = pane === "output" && detail.error ? "Raw model output retained for diagnosis. The API returned an error." : pane === "input" ? "Original request body." : pane === "output" ? "Model answer. JSON is formatted here for readability." : pane === "reasoning" ? "Separate reasoning content, when enabled." : "API response body.";
68  text("content-note", note + (detail[`${pane}_truncated`] ? " Monitor capture truncated at 256K characters; the API response was not shortened." : ""));
69}
70async function showDetail() {
71  if (!selected) return;
72  const id = selected;
73  const value = await api(`/api/requests?id=${encodeURIComponent(id)}`);
74  if (selected !== id) return;
75  detail = value; $("selection").hidden = false; $("no-selection").hidden = true;
76  text("detail-title", `${value.id} · ${value.path}`);
77  text("detail-status", value.state); $("detail-status").className = `tag ${value.state}`;
78  text("detail-time", new Date(value.started_at * 1000).toLocaleString());
79  text("detail-wall", seconds(value.wallclock_s ?? ((Date.now() / 1000) - value.started_at)));
80  text("detail-load", seconds(value.load_s)); text("detail-queue", seconds(value.queue_s)); text("detail-first", seconds(value.first_token_s));
81  text("detail-prompt", value.usage?.prompt_tokens ?? value.usage?.input_tokens ?? "—");
82  text("detail-tokens", value.usage?.completion_tokens ?? value.usage?.output_tokens ?? "—");
83  text("detail-speed", speed(value.timings?.predicted_per_second)); text("detail-format", value.response_format || "text");
84  $("detail-error").hidden = !value.error; text("detail-error", value.error?.message || ""); content();
85}
86async function refresh() {
87  try {
88    const [status, history] = await Promise.all([api("/v1/status"), api("/api/requests")]);
89    state = status; records = history.requests;
90    status.loaded = history.loaded; status.auto_load = history.auto_load;
91    if (selected && !records.some(r => r.id === selected)) {
92      selected = detail = null; $("selection").hidden = true; $("no-selection").hidden = false;
93    }
94    const inflight = Math.max(status.activity.in_flight, records.filter(active).length);
95    const loading = records.some(r => r.state === "loading");
96    text("loaded", loading ? "Loading…" : inflight ? "In use" : status.loaded ? "Loaded" : "Unloaded");
97    $("model-state").className = `value ${inflight || loading ? "busy" : status.loaded ? "loaded" : ""}`;
98    text("model", status.model); text("count", records.length);
99    text("active", inflight ? `${inflight} active / queued` : status.auto_load ? "Loads automatically on the next request" : "No active requests");
100    const last = records.find(r => !active(r));
101    text("wall", last ? seconds(last.wallclock_s) : "—"); text("speed", speed(averageDecodeSpeed(records.filter(r => !active(r)))));
102    $("load").disabled = operating || Boolean(inflight) || status.loaded; $("unload").disabled = operating || Boolean(inflight) || !status.loaded;
103    list(); if (selected) await showDetail();
104    text("updated", `Live · updated ${new Date().toLocaleTimeString()}`);
105    if (!operating) notice(actionError);
106  } catch (error) { notice(error.message); text("updated", "Disconnected · retrying"); $("load").disabled = $("unload").disabled = true; }
107}
108async function control(load) {
109  actionError = "";
110  operating = true; $("load").disabled = $("unload").disabled = true;
111  text("loaded", load ? "Loading…" : "Unloading…");
112  try { await api(load ? "/load" : "/unload", {}); notice(""); }
113  catch (error) { actionError = error.message; notice(actionError); }
114  finally { operating = false; await refresh(); }
115}
116$("load").onclick = () => control(true); $("unload").onclick = () => control(false);
117$("key").onclick = () => { $("auth").hidden = !$("auth").hidden; if (!$("auth").hidden) $("api-key").focus(); };
118$("auth").onsubmit = async event => { event.preventDefault(); apiKey = $("api-key").value.trim(); sessionStorage.setItem("strata.monitor.key", apiKey); $("auth").hidden = true; await refresh(); };
119$("theme").onclick = () => { const theme = document.documentElement.dataset.theme === "dark" ? "light" : "dark"; document.documentElement.dataset.theme = theme; localStorage.setItem("strata.theme", theme); };
120$("search").oninput = list; $("filter").onchange = list;
121document.querySelectorAll("[data-pane]").forEach(button => { button.onclick = () => { pane = button.dataset.pane; document.querySelectorAll("[data-pane]").forEach(b => b.setAttribute("aria-selected", String(b === button))); content(); }; });
122$("copy").onclick = async () => { try { await navigator.clipboard.writeText($("content").textContent); text("copy", "Copied"); setTimeout(() => text("copy", "Copy"), 1500); } catch (_) { notice("Clipboard unavailable; select the text to copy it."); } };
123async function poll() { await refresh(); setTimeout(poll, 2000); }
124poll();