The Kurgan 1.0.0: one process for the LCD, fans, lighting, local LLM servers and the web UI

This commit is contained in:
paul committed 2026-12-05 16:20:49 +13:00
commit f631386618
71 files changed
+14616

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Web: the control UI and its JSON API, on 127.0.0.1 only."""
+284
View File
@@ -0,0 +1,284 @@
"""The LLM servers' addresses on The Kurgan's web server: /strata/... and /llama/...
http://127.0.0.1:8080/strata/v1 OpenAI-compatible base URL for Strata
http://127.0.0.1:8080/llama/v1 ... for llama.cpp (no API key needed; any key is accepted)
http://127.0.0.1:8080/strata/ each server's own chat page (and everything else it serves)
http://127.0.0.1:8080/llama/
A request starts its server if it isn't running (see AiService.claim, which also stops the other
server once that one is idle) and the reply is streamed back as it is generated. A client that
hangs up (a timeout, or the user cancelling) is noticed within a second, even while it is still
waiting: its place is given up and the connection to the server closed, which stops the work on
it. The log then says how long the client waited and at what stage. GET .../v1/models is
answered here while a server is stopped, so a client listing the models of both doesn't make
them swap.
Security: the web server's Host check applies (DNS rebinding). A request carrying an Origin
header other than this server's comes from another site's page and is refused, as is anything
else a browser marks cross-site except opening a page. Pages of this server (the chat pages) are
let through with the Origin removed, so each server treats them like any local client.
llama-server keeps its API key on its own port, and this proxy supplies it, so neither server
asks clients here for a key.
"""
from __future__ import annotations
import http.client
import json
import logging
import re
import select
import socket
import time
log = logging.getLogger(__name__)
ROUTE = re.compile(r"^/(strata|llama)(/[^?#]*)?(\?.*)?$")
MAX_BODY = 64 * 1024 * 1024 # images and very long prompts are big, but not this big
CONNECT_TIMEOUT = 10.0
READ_TIMEOUT = 1800.0 # between bytes: a model load plus a long prompt can take minutes
REQUEST_SKIP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer",
"transfer-encoding", "upgrade", "host", "content-length", "origin", "expect"}
RESPONSE_SKIP = {"connection", "keep-alive", "proxy-authenticate", "te", "trailer", "transfer-encoding",
"upgrade", "server", "date"}
class BodyError(Exception):
def __init__(self, message: str, status: int):
super().__init__(message)
self.status = status
def match(path: str) -> tuple[str, str | None] | None:
"""("llama", "/v1/models?x") for "/llama/v1/models?x"; ("llama", None) for "/llama"; None otherwise."""
m = ROUTE.match(path)
if m is None:
return None
rest = m[2]
return m[1], None if rest is None else rest + (m[3] or "")
def _error(handler, status: int, message: str) -> None:
body = json.dumps({"error": {"message": message, "type": "kurgan"}}).encode()
handler.send_response(status)
handler.send_header("Content-Type", "application/json")
handler.send_header("Content-Length", str(len(body)))
handler.send_header("Cache-Control", "no-store")
handler.send_header("Connection", "close")
handler.end_headers()
handler.close_connection = True
if handler.command != "HEAD":
handler.wfile.write(body)
def _read_body(handler) -> bytes | None:
"""The request body (Content-Length or chunked), None if there is none."""
if handler.headers.get("Transfer-Encoding", "").lower() == "chunked":
parts, total = [], 0
while True:
line = handler.rfile.readline(1024)
try:
size = int(line.split(b";")[0].strip(), 16)
except ValueError:
raise BodyError("malformed chunked body", 400) from None
if size == 0:
while handler.rfile.readline(1024) not in (b"\r\n", b"\n", b""): # trailers
pass
return b"".join(parts)
total += size
if total > MAX_BODY:
raise BodyError("request body too large", 413)
parts.append(handler.rfile.read(size))
handler.rfile.readline(8)
length = handler.headers.get("Content-Length")
if length is None:
return None
try:
length = int(length)
except ValueError:
raise BodyError("bad Content-Length", 400) from None
if length < 0:
raise BodyError("bad Content-Length", 400)
if length > MAX_BODY:
remaining = min(length, 1024 * 1024) # read a little so the client sees the answer; beyond that, give up
while remaining > 0:
chunk = handler.rfile.read(min(remaining, 65536))
if not chunk:
break
remaining -= len(chunk)
raise BodyError("request body too large", 413)
return handler.rfile.read(length)
def _models(handler, backend, rest: str) -> None:
"""OpenAI's model list, without starting the server."""
path = rest.split("?", 1)[0].rstrip("/")
models = [{"id": m, "object": "model", "created": 0, "owned_by": backend.key} for m in backend.model_ids()]
if path == "/v1/models":
data = {"object": "list", "data": models}
else:
wanted = path[len("/v1/models/"):]
data = next((m for m in models if m["id"] == wanted), None)
if data is None:
_error(handler, 404, f"model {wanted!r} not found")
return
body = json.dumps(data).encode()
handler.send_response(200)
handler.send_header("Content-Type", "application/json")
handler.send_header("Content-Length", str(len(body)))
handler.send_header("Connection", "close")
handler.end_headers()
handler.close_connection = True
handler.wfile.write(body)
def _location(value: str, backend) -> str:
"""Map a redirect from the server's own address onto its path here."""
internal = f"http://127.0.0.1:{backend.port}"
if value.startswith(internal):
value = value[len(internal):] or "/"
if not value.startswith("/"):
return value
if backend.prefix and value.startswith(backend.prefix):
value = value[len(backend.prefix):] or "/"
return f"/{backend.key}{value}"
class ClientGone(Exception):
"""The client closed its connection (it timed out or was cancelled); args[0] says when."""
def client_gone(handler) -> bool:
"""True once the client has closed its connection. The request has been read in full by
then, so a readable socket with nothing to read means the client hung up."""
sock = handler.connection
try:
readable, _, _ = select.select([sock], [], [], 0)
return bool(readable) and sock.recv(1, socket.MSG_PEEK) == b""
except (OSError, ValueError):
return True
def handle(handler, ai, hosts: set[str], origins: set[str]) -> None:
"""Serve one request for /strata/... or /llama/... (handler is a BaseHTTPRequestHandler)."""
started = time.monotonic()
try:
_serve(handler, ai, hosts, origins, started)
except (ClientGone, ConnectionError) as e:
handler.close_connection = True
when = e.args[0] if isinstance(e, ClientGone) else "before its answer was sent"
log.info("%s %s: the client gave up after %.0f s, %s", handler.command, handler.path,
time.monotonic() - started, when)
def _serve(handler, ai, hosts: set[str], origins: set[str], started: float) -> None:
key, rest = match(handler.path)
try:
body = _read_body(handler) # before any answer: unread data would reset the connection on Windows
except BodyError as e:
_error(handler, e.status, str(e))
return
if handler.headers.get("Host") not in hosts:
_error(handler, 403, "forbidden host")
return
origin = handler.headers.get("Origin")
if origin is not None and origin not in origins:
_error(handler, 403, f"web pages of {origin} may not use The Kurgan's AI servers")
return
# An <img> or <script> on another site's page sends no Origin but could still make the servers
# swap; browsers mark it cross-site. Following a link (a top-level page load) is fine.
if handler.headers.get("Sec-Fetch-Site") == "cross-site" and handler.headers.get("Sec-Fetch-Dest") != "document":
_error(handler, 403, "other sites' pages may not use The Kurgan's AI servers")
return
if rest is None: # /llama -> /llama/, so the chat page's relative links resolve under it
handler.send_response(308)
handler.send_header("Location", f"/{key}/")
handler.send_header("Content-Length", "0")
handler.end_headers()
return
if ai is None:
_error(handler, 503, "AI management is off for this run of The Kurgan (--no-ai)")
return
path = rest.split("?", 1)[0].rstrip("/")
if handler.command == "GET" and (path == "/v1/models" or path.startswith("/v1/models/")) and not ai.running(key):
_models(handler, ai.slots[key].backend, rest)
return
from kurgan.ai.service import CLIENT_GONE, RouteError
try:
# A client that leaves while waiting (for the other server to finish, or for this one to
# start) releases its place, so an abandoned request never makes the servers swap.
backend = ai.claim(key, gone=lambda: client_gone(handler))
except RouteError as e:
if e.status == CLIENT_GONE:
raise ClientGone(str(e)) from None
log.warning("%s %s: %s", handler.command, handler.path, e)
_error(handler, e.status, str(e))
return
try:
status = _relay(handler, backend, rest, body)
finally:
ai.release(key)
if handler.command != "GET" or status >= 400:
log.info("%s %s -> %s in %.1f s", handler.command, handler.path, status, time.monotonic() - started)
def _await_reply(handler, upstream: socket.socket, backend) -> None:
"""Wait for the server's reply to start: a request can sit in its queue, or its prompt be read,
for minutes, and a reply that isn't streamed arrives all at once at the end. If the client
hangs up meanwhile, give up: closing the connection tells the server to drop the request."""
deadline = time.monotonic() + READ_TIMEOUT
while not select.select([upstream], [], [], 0.5)[0]:
if client_gone(handler):
raise ClientGone(f"before {backend.label} started its reply")
if time.monotonic() > deadline:
raise TimeoutError(f"no reply within {READ_TIMEOUT:.0f} s")
def _relay(handler, backend, rest: str, body: bytes | None) -> int:
extra = backend.proxy_headers() if hasattr(backend, "proxy_headers") else {}
skip = REQUEST_SKIP | {k.lower() for k in extra}
headers = {k: v for k, v in handler.headers.items() if k.lower() not in skip}
headers.update(extra)
headers["Host"] = f"127.0.0.1:{backend.port}"
if body is not None:
headers["Content-Length"] = str(len(body))
connection = http.client.HTTPConnection("127.0.0.1", backend.port, timeout=CONNECT_TIMEOUT)
try:
try:
connection.connect()
connection.sock.settimeout(READ_TIMEOUT)
connection.request(handler.command, backend.prefix + rest, body=body, headers=headers)
_await_reply(handler, connection.sock, backend)
response = connection.getresponse()
except (OSError, http.client.HTTPException) as e:
_error(handler, 502, f"{backend.label} isn't answering: {e}")
return 502
handler.send_response(response.status, response.reason)
for name, value in response.getheaders():
if name.lower() in RESPONSE_SKIP:
continue
handler.send_header(name, _location(value, backend) if name.lower() == "location" else value)
handler.send_header("Connection", "close") # HTTP/1.0: the end of the stream ends the reply
handler.end_headers()
handler.close_connection = True
if handler.command == "HEAD":
return response.status
sent = 0
while True:
try:
chunk = response.read1(65536)
except (OSError, http.client.HTTPException) as e:
log.warning("%s stopped answering mid-reply: %s", backend.label, e)
break
if not chunk:
break
try:
handler.wfile.write(chunk)
except OSError: # closing our side (finally, below) stops the generation
raise ClientGone(f"mid-reply, after {sent:,} bytes") from None
sent += len(chunk)
return response.status
finally:
connection.close()
+225
View File
@@ -0,0 +1,225 @@
"""The web UI and its JSON API, served on 127.0.0.1 only.
GET / the UI (static/index.html)
GET /api/state everything live, polled by the UI once a second
GET /api/history the last 10 minutes of telemetry (fetched once; the UI appends from /api/state)
GET /api/config fan profiles, lighting zones and AI backends (static)
POST /api/lighting {"zone": "case_fans"|"memory"|"gpu", "mode": "off"|...}
POST /api/cooling/profile {"profile": "quiet"|"balanced"|"performance"|"full"}
POST /api/ai/active {"backend": "strata"|"llama"|null, "variant": "q5"|"iq3" (Strata only, optional)}
POST /api/ai/model {"action": "load"|"unload"}
* /strata/... /llama/... the LLM servers, started on demand (kurgan/web/proxy.py)
The process runs elevated and controls fans, so requests are guarded: the Host header must
name this server (blocks DNS rebinding), and every POST needs JSON plus an X-Kurgan header,
which a page on another site can't send without a CORS preflight that this server never
answers. There is no other authentication: anything already running on this PC as you can
use the API.
"""
from __future__ import annotations
import json
import logging
import mimetypes
import os
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from kurgan.web import proxy
log = logging.getLogger(__name__)
STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
MAX_BODY = 16 * 1024
class ApiError(Exception):
def __init__(self, message: str, status: int = 400):
super().__init__(message)
self.status = status
def make_handler(app, port: int):
hosts = {f"127.0.0.1:{port}", f"localhost:{port}"}
origins = {f"http://{h}" for h in hosts}
posts = {
"/api/lighting": lambda b: app.set_lighting(_text(b, "zone"), _text(b, "mode")),
"/api/cooling/profile": lambda b: app.set_fan_profile(_text(b, "profile")),
"/api/ai/active": lambda b: app.set_ai(_optional_text(b, "backend"), _optional_text(b, "variant")),
"/api/ai/model": lambda b: app.ai_model(_text(b, "action")),
}
class Handler(BaseHTTPRequestHandler):
server_version = "Kurgan"
sys_version = ""
def log_message(self, fmt, *args) -> None:
log.debug("%s %s", self.address_string(), fmt % args)
def _send(self, status: int, body: bytes, content_type: str = "application/json",
cache: str = "no-store") -> None:
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", cache)
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("X-Frame-Options", "DENY")
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
def _json(self, status: int, data) -> None:
self._send(status, json.dumps(data, separators=(",", ":")).encode())
def _guard(self) -> bool:
if self.headers.get("Host") not in hosts:
self._json(403, {"error": "forbidden host"})
return False
return True
def _proxied(self) -> bool:
"""Hand /strata/... and /llama/... to the LLM servers; True if it did."""
if proxy.match(self.path) is None:
return False
try:
proxy.handle(self, getattr(app, "ai", None), hosts, origins)
except Exception:
log.exception("%s %s failed", self.command, self.path)
self.close_connection = True
return True
def _other(self) -> None:
if self._proxied():
return
self._read_body()
if self._guard():
self._json(405, {"error": "method not allowed"})
do_PUT = do_DELETE = do_PATCH = do_OPTIONS = _other
def do_HEAD(self) -> None:
if not self._proxied() and self._guard():
self._json(405, {"error": "method not allowed"})
def do_GET(self) -> None:
if self._proxied() or not self._guard():
return
path = self.path.split("?", 1)[0]
try:
if path == "/api/state":
self._json(200, app.state())
elif path == "/api/history":
self._json(200, app.history())
elif path == "/api/config":
self._json(200, app.config())
elif path in ("/", "/index.html"):
self._static("index.html")
elif path.startswith("/static/"):
self._static(path[len("/static/"):])
else:
self._json(404, {"error": "not found"})
except Exception:
log.exception("GET %s failed", path)
self._json(500, {"error": "internal error; see kurgan.log"})
def _static(self, name: str) -> None:
if name not in os.listdir(STATIC_DIR): # no paths, no traversal: only files in static/
self._json(404, {"error": "not found"})
return
with open(os.path.join(STATIC_DIR, name), "rb") as f:
body = f.read()
kind = mimetypes.guess_type(name)[0] or "application/octet-stream"
if kind.startswith("text/") or kind in ("application/javascript", "image/svg+xml"):
kind += "; charset=utf-8"
self._send(200, body, kind, cache="no-cache")
def _read_body(self) -> bytes | None:
"""The request body, or None if missing or oversized. Read before any answer: closing a
socket with unread data resets the connection on Windows, and the client would see a
dropped connection instead of the error."""
try:
length = int(self.headers.get("Content-Length", "0"))
except ValueError:
self.close_connection = True
return None
if 0 < length <= MAX_BODY:
return self.rfile.read(length)
remaining = min(max(length, 0), 1024 * 1024) # drain a modest oversized body; beyond that, give up
while remaining > 0:
chunk = self.rfile.read(min(remaining, 65536))
if not chunk:
break
remaining -= len(chunk)
self.close_connection = True
return None
def do_POST(self) -> None:
if self._proxied():
return
raw = self._read_body()
if not self._guard():
return
origin = self.headers.get("Origin")
if self.headers.get("X-Kurgan") != "1" or (origin is not None and origin not in origins):
self._json(403, {"error": "forbidden"})
return
if not self.headers.get("Content-Type", "").startswith("application/json"):
self._json(415, {"error": "send application/json"})
return
action = posts.get(self.path)
if action is None:
self._json(404, {"error": "not found"})
return
try:
if raw is None:
raise ApiError("missing or oversized body")
body = json.loads(raw)
if not isinstance(body, dict):
raise ApiError("body must be a JSON object")
action(body)
self._json(200, app.state())
except (ApiError, ValueError) as e:
status = e.status if isinstance(e, ApiError) else 400
self._json(status, {"error": str(e)})
except OSError as e:
log.warning("POST %s failed: %s", self.path, e)
self._json(500, {"error": f"Couldn't save the setting: {e}"})
except Exception:
log.exception("POST %s failed", self.path)
self._json(500, {"error": "internal error; see kurgan.log"})
return Handler
def _text(body: dict, key: str) -> str:
value = body.get(key)
if not isinstance(value, str) or not value:
raise ApiError(f"{key} is required")
return value
def _optional_text(body: dict, key: str) -> str | None:
value = body.get(key)
if value is not None and not isinstance(value, str):
raise ApiError(f"{key} must be a string or null")
return value
class WebServer:
def __init__(self, app, port: int):
self.port = port
self.url = f"http://127.0.0.1:{port}/"
self.httpd = ThreadingHTTPServer(("127.0.0.1", port), make_handler(app, port))
self.httpd.daemon_threads = True
self._thread: threading.Thread | None = None
def start(self) -> None:
self._thread = threading.Thread(target=self.httpd.serve_forever, kwargs={"poll_interval": 0.5},
name="web", daemon=True)
self._thread.start()
log.info("Web UI at %s", self.url)
def close(self) -> None:
self.httpd.shutdown()
self.httpd.server_close()
+802
View File
@@ -0,0 +1,802 @@
/* The Kurgan - control UI. Polls /api/state once a second while the page is visible. */
"use strict";
const SVGNS = "http://www.w3.org/2000/svg";
const WINDOW_S = 600;
const $ = (id) => document.getElementById(id);
/* Elements are built with textContent only: names and messages come from devices and servers. */
function el(tag, attrs = {}, ...children) {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (v == null || v === false) continue;
if (k === "class") node.className = v;
else if (k === "style") node.style.cssText = v;
else if (k.startsWith("on")) node.addEventListener(k.slice(2), v);
else if (k === "text") node.textContent = v;
else node.setAttribute(k, v === true ? "" : v);
}
for (const child of children.flat()) {
if (child == null || child === false) continue;
node.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
return node;
}
function svg(tag, attrs = {}) {
const node = document.createElementNS(SVGNS, tag);
for (const [k, v] of Object.entries(attrs)) if (v != null) node.setAttribute(k, v);
return node;
}
function setText(id, text) {
const node = typeof id === "string" ? $(id) : id;
if (node && node.textContent !== text) node.textContent = text;
}
const fmt = {
n0: (v) => (v == null ? "--" : Math.round(v).toLocaleString()),
n1: (v) => (v == null ? "--" : (Math.round(v * 10) / 10).toLocaleString(undefined, { minimumFractionDigits: 1 })),
gib: (bytes) => (bytes == null ? "--" : (bytes / 2 ** 30).toFixed(1)),
dur(s) {
if (s == null) return "--";
s = Math.round(s);
if (s < 60) return `${s} s`;
if (s < 3600) return `${Math.floor(s / 60)} min ${s % 60} s`;
const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60);
return h >= 24 ? `${Math.floor(h / 24)} d ${h % 24} h` : `${h} h ${m} min`;
},
clock: (t) => new Date(t * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }),
};
const ICON = {
warning: "M8 1.5 15 14H1L8 1.5Zm0 4.2v4m0 2.2v.1",
critical: "M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1Zm0 3.8v4.4m0 2.2v.1",
info: "M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1Zm0 6v4.5m0-6.7v.1",
};
function note(kind, text) {
const icon = svg("svg", { viewBox: "0 0 16 16", "aria-hidden": "true" });
icon.append(svg("path", { d: ICON[kind], fill: "none", stroke: "currentColor", "stroke-width": "1.6",
"stroke-linecap": "round", "stroke-linejoin": "round" }));
const label = { warning: "Warning", critical: "Problem", info: "Note" }[kind];
return el("div", { class: `note ${kind}` }, icon, el("span", {}, el("b", { text: `${label}: ` }), text));
}
/* ------------------------------------------------------------------ API */
async function api(path, body) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), body ? 15000 : 4000);
try {
const response = await fetch(path, body === undefined ? { signal: controller.signal } : {
method: "POST", signal: controller.signal,
headers: { "Content-Type": "application/json", "X-Kurgan": "1" }, body: JSON.stringify(body),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
return data;
} finally {
clearTimeout(timer);
}
}
let bannerTimer = null;
function banner(kind, text, sticky = false) {
const node = $("banner");
clearTimeout(bannerTimer);
if (!text) { node.hidden = true; node.dataset.kind = ""; return; }
node.replaceChildren(note(kind, text));
node.dataset.kind = kind;
node.hidden = false;
if (!sticky) bannerTimer = setTimeout(() => { node.hidden = true; }, 9000);
}
/* Send a change; the group is disabled until the answer arrives, then the new state is drawn. */
async function change(group, path, body) {
group?.classList.add("busy");
try {
const state = await api(path, body);
render(state);
} catch (error) {
banner("critical", error.message);
if (lastState) render(lastState);
} finally {
group?.classList.remove("busy");
}
}
/* ------------------------------------------------------------------ tooltip */
const tip = {
node: null,
show(x, y, title, rows) {
this.node ??= $("tooltip");
const items = rows.map((r) => el("div", { class: "tip-row" },
el("span", { class: "key line", style: `background:${r.color}` }), el("b", { text: r.value }), el("span", { text: r.label })));
this.node.replaceChildren(el("div", { class: "when", text: title }), ...items);
this.node.hidden = false;
const w = this.node.offsetWidth, h = this.node.offsetHeight;
const left = x + 16 + w > innerWidth ? x - 16 - w : x + 16;
this.node.style.left = `${Math.max(4, left)}px`;
this.node.style.top = `${Math.min(innerHeight - h - 4, Math.max(4, y - h / 2))}px`;
},
hide() { if (this.node) this.node.hidden = true; },
};
/* ------------------------------------------------------------------ charts */
function niceMax(v) {
if (!(v > 0)) return 1;
const p = 10 ** Math.floor(Math.log10(v)), m = v / p;
return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 2.5 ? 2.5 : m <= 5 ? 5 : 10) * p;
}
/**
* One chart: lines (or a stacked area) over time or over a numeric x, a crosshair tooltip,
* selective end labels, an optional legend (2+ series) and a table view.
*/
class Chart {
constructor(fig, opts) {
this.o = { height: 210, unit: "", digits: 0, stacked: false, x: { type: "time" }, refs: [], ...opts };
this.fig = fig;
this.xs = [];
this.cols = {};
this.markers = [];
const legend = this.o.series.length > 1 ? el("div", { class: "legend" },
this.o.series.map((s) => el("span", {}, el("span", { class: this.o.stacked ? "key" : "key line",
style: `background:var(${s.color})` }), s.label))) : null;
this.toggle = el("button", { class: "btn table-toggle", type: "button", "aria-expanded": "false",
onclick: () => this.toggleTable() }, "Table");
this.titleNode = el("h3", { text: this.o.title });
this.subNode = el("div", { class: "sub", style: "margin:2px 0 0", text: this.o.subtitle || "" });
this.plot = el("div", { class: "plot" });
this.svg = svg("svg", { role: "img", "aria-label": this.o.title });
this.plot.append(this.svg);
this.tableNode = el("div", { class: "chart-table", hidden: true });
fig.replaceChildren(el("div", { class: "chart-head" }, el("div", {}, this.titleNode, this.subNode, legend), this.toggle),
this.plot, this.tableNode);
this.svg.addEventListener("pointermove", (e) => this.hover(e));
this.svg.addEventListener("pointerleave", () => this.unhover());
new ResizeObserver(() => this.draw()).observe(this.plot);
}
setTitle(title, subtitle) {
setText(this.titleNode, title);
setText(this.subNode, subtitle || "");
this.svg.setAttribute("aria-label", title);
}
setData(xs, cols, markers = []) {
this.xs = xs;
this.cols = cols;
this.markers = markers;
this.draw();
if (!this.tableNode.hidden) this.renderTable();
}
value(key, i) { const v = this.cols[key]?.[i]; return v == null || Number.isNaN(v) ? null : v; }
/* Stacked: each layer's top edge; plain: the value. */
levels() {
const n = this.xs.length, out = {};
let base = new Array(n).fill(0);
for (const s of this.o.series) {
const top = new Array(n);
for (let i = 0; i < n; i++) {
const v = this.value(s.key, i);
top[i] = v == null ? null : (this.o.stacked ? base[i] + v : v);
}
out[s.key] = { base, top };
if (this.o.stacked) base = top.map((v, i) => (v == null ? base[i] : v));
}
return out;
}
draw() {
const width = this.plot.clientWidth;
if (!width) return;
const H = this.o.height, m = { l: 44, r: 64, t: 10, b: 24 };
const w = width - m.l - m.r, h = H - m.t - m.b;
this.svg.setAttribute("viewBox", `0 0 ${width} ${H}`);
this.svg.replaceChildren();
const xo = this.o.x;
let x0, x1;
if (xo.type === "time") {
x1 = this.xs.length ? this.xs[this.xs.length - 1] : Date.now() / 1000;
x0 = x1 - WINDOW_S;
} else {
[x0, x1] = [xo.min, xo.max];
}
const levels = this.levels();
let dataMax = 0;
for (const s of this.o.series) for (const v of levels[s.key].top) if (v != null && v > dataMax) dataMax = v;
const yMax = typeof this.o.yMax === "function" ? this.o.yMax(dataMax) : (this.o.yMax ?? niceMax(dataMax * 1.1));
const X = (x) => m.l + ((x - x0) / (x1 - x0)) * w;
const Y = (y) => m.t + h - (Math.max(0, Math.min(yMax, y)) / yMax) * h;
this.geom = { X, Y, m, w, h, x0, x1, yMax, width, levels };
// grid + y ticks
const grid = svg("g", { class: "grid" });
// 4 steps unless that gives a ragged step (25 GiB / 4 = 6.25); then 5.
const ticks = Number.isInteger((yMax / 4) * 10) ? 4 : 5;
for (let i = 0; i <= ticks; i++) {
const v = (yMax / ticks) * i, y = Y(v);
if (i > 0) grid.append(svg("line", { x1: m.l, x2: m.l + w, y1: y, y2: y }));
const t = svg("text", { x: m.l - 8, y: y + 4, "text-anchor": "end", class: "tick" });
t.textContent = `${Number.isInteger(v) ? v.toLocaleString() : v.toFixed(1)}${this.o.unit}`;
this.svg.append(t);
}
this.svg.append(grid);
this.svg.append(svg("line", { class: "baseline", x1: m.l, x2: m.l + w, y1: Y(0), y2: Y(0) }));
// x ticks
const xticks = xo.type === "time" ? [0, 120, 240, 360, 480, 600].map((s) => x1 - WINDOW_S + s) : xo.ticks;
for (const xv of xticks) {
const t = svg("text", { x: X(xv), y: H - 6, "text-anchor": "middle", class: "tick" });
t.textContent = xo.type === "time" ? (x1 - xv < 1 ? "now" : `−${Math.round((x1 - xv) / 60)} min`) : xo.fmt(xv);
this.svg.append(t);
}
// reference lines (e.g. the warn/hot temperatures)
for (const r of this.o.refs) {
if (r.value > yMax) continue;
this.svg.append(svg("line", { class: "ref", x1: m.l, x2: m.l + w, y1: Y(r.value), y2: Y(r.value) }));
const t = svg("text", { x: m.l + 6, y: Y(r.value) - 5, class: "ref-label" });
t.textContent = r.label;
this.svg.append(t);
}
// series
const ends = [];
for (const s of this.o.series) {
const { base, top } = levels[s.key];
const segs = [];
let cur = [];
for (let i = 0; i < this.xs.length; i++) {
if (top[i] == null || this.xs[i] < x0) { if (cur.length) segs.push(cur); cur = []; continue; }
cur.push(i);
}
if (cur.length) segs.push(cur);
for (const seg of segs) {
const line = seg.map((i, k) => `${k ? "L" : "M"}${X(this.xs[i]).toFixed(1)},${Y(top[i]).toFixed(1)}`).join("");
if (this.o.stacked || this.o.area) {
const back = seg.slice().reverse().map((i) => `L${X(this.xs[i]).toFixed(1)},${Y(this.o.stacked ? base[i] : 0).toFixed(1)}`).join("");
this.svg.append(svg("path", { d: line + back + "Z", class: "series-area", fill: `var(${s.color})` }));
}
this.svg.append(svg("path", { d: line, class: "series-line", stroke: `var(${s.color})` }));
}
const last = this.lastIndex(s.key);
if (last != null && !this.o.noEndLabels) ends.push({ s, i: last, y: Y(top[last]) });
}
// operating points (fan curves): a dot with a surface ring
for (const mk of this.markers) {
if (mk.x == null || mk.y == null) continue;
this.svg.append(svg("circle", { cx: X(Math.max(x0, Math.min(x1, mk.x))), cy: Y(mk.y), r: 5, class: "marker", fill: `var(${mk.color})` }));
}
// end labels: only where they don't collide (the legend and tooltip carry the rest)
ends.sort((a, b) => a.y - b.y);
let lastY = -Infinity;
const placed = [];
for (const e of ends) {
if (e.y - lastY < 14) { placed.pop(); lastY = e.y; continue; }
placed.push(e);
lastY = e.y;
}
for (const e of placed) {
const v = this.o.stacked ? this.value(e.s.key, e.i) : levels[e.s.key].top[e.i];
const t = svg("text", { x: m.l + w + 6, y: e.y + 4, class: "end-label" });
t.textContent = `${v.toFixed(this.o.digits)}${this.o.unit}`;
this.svg.append(t);
}
this.cross = svg("line", { class: "cross", y1: m.t, y2: m.t + h, visibility: "hidden" });
this.svg.append(this.cross);
}
lastIndex(key) {
for (let i = this.xs.length - 1; i >= 0; i--) if (this.value(key, i) != null) return i;
return null;
}
hover(e) {
const g = this.geom;
if (!g || !this.xs.length) return;
const rect = this.svg.getBoundingClientRect();
const px = ((e.clientX - rect.left) / rect.width) * g.width;
const xv = g.x0 + ((px - g.m.l) / g.w) * (g.x1 - g.x0);
let best = null, bestD = Infinity;
for (let i = 0; i < this.xs.length; i++) {
const d = Math.abs(this.xs[i] - xv);
if (d < bestD && this.xs[i] >= g.x0) { best = i; bestD = d; }
}
if (best == null) return this.unhover();
const cx = g.X(this.xs[best]);
this.cross.setAttribute("x1", cx);
this.cross.setAttribute("x2", cx);
this.cross.setAttribute("visibility", "visible");
const title = this.o.x.type === "time" ? fmt.clock(this.xs[best]) : this.o.x.fmt(this.xs[best]);
const rows = this.o.series.slice().reverse().map((s) => {
const v = this.value(s.key, best);
return { color: `var(${s.color})`, label: s.label, value: v == null ? "--" : `${v.toFixed(this.o.digits)}${this.o.unit}` };
});
if (this.o.stacked && this.o.totalLabel) {
const total = this.o.series.reduce((a, s) => a + (this.value(s.key, best) ?? 0), 0);
rows.unshift({ color: "transparent", label: this.o.totalLabel, value: `${total.toFixed(this.o.digits)}${this.o.unit}` });
}
tip.show(e.clientX, e.clientY, title, rows);
}
unhover() {
this.cross?.setAttribute("visibility", "hidden");
tip.hide();
}
toggleTable() {
const open = this.tableNode.hidden;
this.tableNode.hidden = !open;
this.toggle.setAttribute("aria-expanded", String(open));
this.toggle.textContent = open ? "Hide table" : "Table";
if (open) this.renderTable();
}
renderTable() {
const time = this.o.x.type === "time";
const head = el("tr", {}, el("th", { text: time ? "Time" : this.o.x.label }),
this.o.series.map((s) => el("th", { class: "r", text: s.label })));
const rows = [];
let lastT = Infinity;
const order = time ? [...this.xs.keys()].reverse() : [...this.xs.keys()];
for (const i of order) {
if (time && lastT - this.xs[i] < 29.5) continue; // one row per 30 s
lastT = this.xs[i];
if (!time && this.xs[i] % 5 !== 0) continue;
rows.push(el("tr", {}, el("td", { class: "num", text: time ? fmt.clock(this.xs[i]) : this.o.x.fmt(this.xs[i]) }),
this.o.series.map((s) => { const v = this.value(s.key, i); return el("td", { class: "r", text: v == null ? "--" : `${v.toFixed(this.o.digits)}${this.o.unit}` }); })));
}
this.tableNode.replaceChildren(el("table", {}, el("caption", { class: "muted", style: "text-align:left;caption-side:top;padding:0 0 6px",
text: time ? "Every 30 seconds, newest first" : "" }), el("thead", {}, head), el("tbody", {}, rows)));
}
stale(on) { this.plot.classList.toggle("stale", on); }
}
/* ------------------------------------------------------------------ history */
class Series {
constructor(names) { this.names = names; this.t = []; this.cols = Object.fromEntries(names.slice(1).map((n) => [n, []])); }
load(rows) { this.t = []; for (const k in this.cols) this.cols[k] = []; for (const r of rows) this.push(r); }
push(row) {
if (!row || (this.t.length && row[0] <= this.t[this.t.length - 1])) return false;
this.t.push(row[0]);
this.names.slice(1).forEach((n, i) => this.cols[n].push(row[i + 1]));
const cutoff = row[0] - WINDOW_S - 2;
let drop = 0;
while (drop < this.t.length && this.t[drop] < cutoff) drop++;
if (drop) { this.t.splice(0, drop); for (const k in this.cols) this.cols[k].splice(0, drop); }
return true;
}
}
/* ------------------------------------------------------------------ app state */
let config = null;
let lastState = null;
let telemetry = null, fanHistory = null;
let charts = {};
let built = { profiles: false, groups: "", zones: false, backends: "" };
let strataVariant = null;
let profileShown = null;
function buildCharts() {
const temps = config.theme;
charts.power = new Chart($("chart-power"), {
title: "Power", subtitle: `Whole PC, last 10 minutes (DC watts; ${fmt.n0(temps.psu_watts)} W supply)`,
stacked: true, unit: " W", totalLabel: "Total",
series: [{ key: "other_w", label: "Other", color: "--other" }, { key: "cpu_w", label: "CPU", color: "--cpu" },
{ key: "gpu_w", label: "GPU", color: "--gpu" }],
});
charts.temps = new Chart($("chart-temps"), {
title: "Temperatures", subtitle: "Last 10 minutes", unit: "°", yMax: (m) => Math.max(100, niceMax(m)),
series: [{ key: "cpu_temp", label: "CPU", color: "--cpu" }, { key: "gpu_temp", label: "GPU", color: "--gpu" }],
refs: [{ value: temps.temp_warn, label: `warm ${temps.temp_warn}°` }, { value: temps.temp_hot, label: `hot ${temps.temp_hot}°` }],
});
charts.fans = new Chart($("chart-fans"), {
title: "Fan speeds", subtitle: "PWM duty, last 10 minutes", unit: "%", yMax: 100,
series: [{ key: "cpu_duty", label: "CPU side", color: "--cpu" }, { key: "gpu_duty", label: "GPU side", color: "--gpu" },
{ key: "top_duty", label: "Top", color: "--top" }],
});
charts.curves = new Chart($("chart-curves"), {
title: "Profile curves", unit: "%", yMax: 100, noEndLabels: true,
x: { type: "linear", min: 20, max: 100, ticks: [20, 30, 40, 50, 60, 70, 80, 90, 100], fmt: (v) => `${v} °C`, label: "Temperature" },
series: [{ key: "cpu", label: "CPU side", color: "--cpu" }, { key: "gpu", label: "GPU side", color: "--gpu" },
{ key: "top", label: "Top", color: "--top" }],
});
charts.vram = new Chart($("chart-vram"), {
title: "GPU memory used", subtitle: "Last 10 minutes", unit: " GiB", digits: 1, area: true,
series: [{ key: "vram", label: "GPU memory", color: "--gpu" }],
yMax: () => niceMax((lastState?.telemetry?.gpu?.vram_total ?? 24 * 2 ** 30) / 2 ** 30),
});
}
function curveDuty(curve, t) {
if (t <= curve[0][0]) return curve[0][1];
for (let i = 1; i < curve.length; i++) {
const [t0, d0] = curve[i - 1], [t1, d1] = curve[i];
if (t <= t1) return Math.ceil(d0 + (t - t0) * (d1 - d0) / (t1 - t0));
}
return 100;
}
function drawCurves(state) {
const p = config.profiles.find((x) => x.key === (profileShown ?? state.cooling.profile)) ?? config.profiles[0];
const xs = [], cols = { cpu: [], gpu: [], top: [] };
for (let t = 20; t <= 100; t++) {
xs.push(t);
cols.cpu.push(curveDuty(p.cpu_curve, t));
cols.gpu.push(curveDuty(p.gpu_curve, t));
cols.top.push(t < p.top_start ? 0 : curveDuty(p.top_curve, t));
}
const markers = [];
for (const g of state.cooling.groups) markers.push({ x: g.temp, y: g.duty, color: g.name === "GPU" ? "--gpu" : "--cpu" });
if (state.cooling.top) markers.push({ x: state.cooling.top.temp, y: state.cooling.top.duty, color: "--top" });
charts.curves.setTitle(`${p.name} profile curves`,
`Dots: each group now. Top fans start at ${p.top_start} °C and stop below ${p.top_stop} °C.`);
charts.curves.setData(xs, cols, state.cooling.groups.length || state.cooling.top ? markers : []);
}
/* ------------------------------------------------------------------ render: header & system */
function renderHeader(s) {
setText("hero-total", fmt.n0(s.telemetry.power?.total));
const meta = $("meta");
const elevated = s.app.token?.elevated;
meta.replaceChildren(
el("span", { class: "pill" }, el("span", { class: "dot good" }), "Live"),
el("span", { text: `Up ${fmt.dur(s.app.uptime)}` }),
el("span", { class: "pill", title: "PawnIO sensors, top fans and RAM lighting need admin rights" },
el("span", { class: `dot ${elevated ? "good" : "warning"}` }), elevated ? "Admin rights" : "No admin rights"),
);
setText("footer", `${s.app.name} ${s.app.version} · pid ${s.app.pid} · log: %LOCALAPPDATA%\\Kurgan\\kurgan.log · JSON: /api/state`);
}
function renderSystem(s) {
const t = s.telemetry;
if (!t.cpu) return;
setText("cpu-temp", fmt.n0(t.cpu.temp));
setText("cpu-detail", `${fmt.n0(t.cpu.load)}% load · ${fmt.n0(t.cpu.clock)} MHz · ${fmt.n0(t.cpu.power)} W`);
setText("gpu-temp", fmt.n0(t.gpu.temp));
setText("gpu-detail", `${fmt.n0(t.gpu.load)}% load · ${fmt.n0(t.gpu.clock)} MHz · ${fmt.n0(t.gpu.power)} W`);
setText("vram-used", fmt.gib(t.gpu.vram_used));
setText("vram-total", t.gpu.vram_total ? ` / ${fmt.gib(t.gpu.vram_total)} GiB` : "");
const share = t.gpu.vram_total ? (100 * t.gpu.vram_used) / t.gpu.vram_total : 0;
$("vram-meter").firstChild.style.width = `${share.toFixed(1)}%`;
$("vram-meter").setAttribute("aria-valuenow", share.toFixed(0));
$("vram-meter").className = `meter ${share > 92 ? "warning" : "gpu"}`;
setText("lcd-status", s.display.status);
setText("lcd-detail", s.display.frames != null ? `${fmt.n0(s.display.frames)} frames sent` : "");
}
/* ------------------------------------------------------------------ render: cooling */
function buildProfiles() {
const group = $("profiles");
group.replaceChildren(...config.profiles.map((p) => el("label", {},
el("input", { type: "radio", name: "profile", value: p.key,
onchange: () => { profileShown = p.key; change(group, "/api/cooling/profile", { profile: p.key }); } }),
el("span", { text: p.name }))));
group.addEventListener("mouseover", (e) => {
const key = e.target.closest("label")?.querySelector("input")?.value;
if (key && key !== profileShown) { profileShown = key; drawCurves(lastState); describeProfile(); }
});
group.addEventListener("mouseleave", () => { profileShown = null; drawCurves(lastState); describeProfile(); });
built.profiles = true;
}
function describeProfile() {
const key = profileShown ?? lastState.cooling.profile;
const p = config.profiles.find((x) => x.key === key);
setText("profile-desc", p ? (key === lastState.cooling.profile ? p.description : `Preview: ${p.description}`) : "");
}
function fanCard(g, kind) {
const ports = Object.entries(g.rpms ?? {});
return el("div", { class: "card", "data-group": kind },
el("div", { class: "tile" }, el("div", { class: "label" }, el("span", { class: "key", style: `background:var(--${kind})` }),
kind === "top" ? `Top fans · channels ${g.channels.join(", ")}` : `${g.name}-side case fans · ports ${g.ports.join(", ")}`)),
el("div", { class: "fan-head", style: "margin-top:4px" }, el("span", { class: "fan-duty", "data-f": "duty" }),
el("span", { class: "muted", "data-f": "temp" })),
el("div", { class: `meter ${kind}`, role: "meter", "aria-label": "PWM duty", "data-f": "meter" }, el("span")),
el("div", { class: "fan-ports", "data-f": "ports" }, ports.map(([p]) => el("span", {}, `Port ${p} `, el("b", { "data-port": p }), " rpm"))),
el("div", { "data-f": "note" }));
}
function updateFanCard(card, g, kind) {
const q = (f) => card.querySelector(`[data-f="${f}"]`);
setText(q("duty"), `${g.duty}%`);
const temp = g.temp == null ? "temperature unavailable" : `at ${fmt.n0(g.temp)} °C ${kind === "top" ? "(hotter of CPU/GPU)" : g.name}`;
setText(q("temp"), kind === "top" && !g.running ? `stopped · ${fmt.n0(g.temp)} °C` : temp);
const meter = q("meter");
meter.firstChild.style.width = `${g.duty}%`;
meter.setAttribute("aria-valuenow", g.duty);
meter.className = `meter ${g.failsafe ? "critical" : kind}`;
for (const [p, rpm] of Object.entries(g.rpms ?? {})) setText(card.querySelector(`[data-port="${p}"]`), fmt.n0(rpm));
const n = q("note");
const text = g.failsafe ? g.status : kind === "top" && g.boosted ? "Held at 100% while a case-fan group runs at 85% or more." : "";
if (n.dataset.text !== text) {
n.dataset.text = text;
n.replaceChildren(...(text ? [note(g.failsafe ? "critical" : "info", text)] : []));
}
}
function renderCooling(s) {
const c = s.cooling;
if (!built.profiles) buildProfiles();
if (!$("profiles").classList.contains("busy")) {
for (const input of $("profiles").querySelectorAll("input")) input.checked = input.value === c.profile;
}
describeProfile();
const noteNode = $("cooling-note");
if ((noteNode.dataset.text ?? "") !== (c.note ?? "")) {
noteNode.dataset.text = c.note ?? "";
noteNode.replaceChildren(...(c.note ? [note("warning", c.note)] : []));
}
const kinds = c.groups.map((g) => [g, g.name === "GPU" ? "gpu" : "cpu"]);
if (c.top) kinds.push([c.top, "top"]);
const signature = kinds.map(([g, k]) => k + (g.ports ?? g.channels).join()).join("|");
if (built.groups !== signature) {
$("fan-groups").replaceChildren(...kinds.map(([g, k]) => fanCard(g, k)));
built.groups = signature;
}
for (const [g, k] of kinds) updateFanCard($("fan-groups").querySelector(`[data-group="${k}"]`), g, k);
if (fanHistory.push(c.row)) charts.fans.setData(fanHistory.t, fanHistory.cols);
$("chart-fans").hidden = !c.groups.length;
drawCurves(s);
}
/* ------------------------------------------------------------------ render: lighting */
function buildZones(lighting) {
$("light-zones").replaceChildren(...lighting.zones.map((z) => {
const group = el("div", { class: "seg", role: "radiogroup", "aria-label": z.label });
group.append(...z.modes.map((m) => el("label", {},
el("input", { type: "radio", name: `zone-${z.key}`, value: m.key,
onchange: () => change(group, "/api/lighting", { zone: z.key, mode: m.key }) }),
el("span", { text: m.label }))));
return el("div", { class: "card zone", "data-zone": z.key }, el("h3", { text: z.label, style: "margin-bottom:10px" }),
group, el("div", { class: "status" }), el("div", { "data-f": "note" }));
}));
built.zones = true;
}
function renderLighting(s) {
if (!built.zones) buildZones(s.lighting);
for (const z of s.lighting.zones) {
const card = $("light-zones").querySelector(`[data-zone="${z.key}"]`);
const group = card.querySelector(".seg");
if (!group.classList.contains("busy")) for (const i of group.querySelectorAll("input")) i.checked = i.value === z.mode;
const bad = /unavailable|busy|error|stopped/i.test(z.status);
setText(card.querySelector(".status"), bad ? "" : (z.status === "off" ? "Off" : z.status));
const n = card.querySelector('[data-f="note"]');
const text = (bad ? z.status : "") + (z.this_run_only ? (bad ? " " : "") + "Set by a command-line option for this run; choosing here saves it." : "");
if (n.dataset.text !== text) {
n.dataset.text = text;
n.replaceChildren(...(text ? [note(bad ? "warning" : "info", text)] : []));
}
}
setText("chase-note", s.lighting.chase_ms_per_led
? `The chases share one clock: ${s.lighting.chase_ms_per_led} ms per LED now, faster as total power rises.` : "");
}
/* ------------------------------------------------------------------ render: AI */
const MODEL_STATE = {
offline: ["Not answering", ""], unloaded: ["Model unloaded · loads on the first request", ""],
sleeping: ["Model asleep · loads on the first request", ""], loading: ["Loading model", "warning"],
idle: ["Model loaded · idle", "good"], reading: ["Reading the prompt", "good"], generating: ["Generating", "good"],
failed: ["Model failed to load", "critical"],
};
const PROCESS = { running: "Running", starting: "Starting", stopping: "Stopping", external: "Running outside The Kurgan", stopped: "Stopped" };
function busyBackend(ai) {
return ai.backends.find((b) => b.key === ai.active && b.live);
}
function chooseBackend(key, variant) {
const ai = lastState.ai, busy = busyBackend(ai);
if (busy && (key !== busy.key || (variant && variant !== busy.variant)) &&
!confirm(`${busy.label} is answering a request right now. Switching stops it. Switch anyway?`)) {
render(lastState);
return;
}
change($("backends"), "/api/ai/active", variant ? { backend: key, variant } : { backend: key });
}
function buildBackends(ai) {
const cards = ai.backends.map((b) => {
const select = b.variants.length ? el("select", { "aria-label": `${b.label} model`,
onchange: (e) => { strataVariant = e.target.value; if (ai.active === b.key || lastState.ai.active === b.key) chooseBackend(b.key, strataVariant); } },
b.variants.map((v) => el("option", { value: v.key, text: v.label }))) : null;
return el("label", { class: "choice", "data-key": b.key },
el("input", { type: "radio", name: "backend", value: b.key,
onchange: () => chooseBackend(b.key, b.variants.length ? (strataVariant ?? b.variant) : null) }),
el("div", { class: "name" }, b.label, el("span", { class: "check" })),
el("div", { class: "what", "data-f": "what" }), select,
el("div", { class: "state", "data-f": "state" }));
});
cards.push(el("label", { class: "choice", "data-key": "" },
el("input", { type: "radio", name: "backend", value: "", onchange: () => chooseBackend(null) }),
el("div", { class: "name" }, "None", el("span", { class: "check" })),
el("div", { class: "what", text: "Nothing running; the GPU's memory is free. The next request to either address starts its server." }),
el("div", { class: "state", "data-f": "state" })));
$("backends").replaceChildren(...cards);
built.backends = ai.backends.map((b) => b.key).join();
}
function stateLine(b) {
const [text, kind] = b.process === "running" || b.process === "external" ? MODEL_STATE[b.model.state] ?? [b.model.state, ""]
: [PROCESS[b.process], b.process === "starting" || b.process === "stopping" ? "warning" : ""];
const pill = el("span", { class: "pill" }, el("span", { class: `dot ${kind}` }), text);
if (b.process !== "external") return pill;
return el("span", { class: "pills" }, el("span", { class: "pill" }, el("span", { class: "dot warning" }), "Outside The Kurgan"), pill);
}
function renderAI(s) {
const ai = s.ai;
if (!ai) { $("ai").hidden = true; return; }
if (built.backends !== ai.backends.map((b) => b.key).join()) buildBackends(ai);
const group = $("backends");
group.classList.toggle("busy", !!ai.transition);
for (const b of ai.backends) {
const card = group.querySelector(`[data-key="${b.key}"]`);
setText(card.querySelector('[data-f="what"]'), `${b.model_label} · ${b.route}v1`);
const select = card.querySelector("select");
if (select && document.activeElement !== select) select.value = ai.active === b.key ? b.variant : (strataVariant ?? b.variant);
card.querySelector('[data-f="state"]').replaceChildren(stateLine(b));
}
const noneState = group.querySelector('[data-key=""] [data-f="state"]');
const serving = ai.backends.some((b) => b.process !== "stopped");
noneState.replaceChildren(...(ai.active == null && !serving
? [el("span", { class: "pill" }, el("span", { class: "dot good" }), "GPU memory free")] : []));
if (!group.classList.contains("pending")) {
for (const input of group.querySelectorAll('input[type="radio"]')) input.checked = input.value === (ai.active ?? "");
}
const m = ai.idle_stop_minutes;
setText("ai-idle", m ? `A server nobody uses for ${m} minutes stops and frees the GPU's memory; the next request starts it again.`
: "Servers keep running when nobody uses them (ai.idle_stop_minutes is 0).");
const notes = [];
if (ai.transition) notes.push(note("info", `${ai.transition}…`));
if (ai.warning) notes.push(note("warning", ai.warning));
if (ai.message) notes.push(note("critical", ai.message));
$("ai-notes").replaceChildren(...notes);
renderActive(ai);
const vram = telemetry.cols.vram_used.map((v) => (v == null ? null : v / 2 ** 30));
charts.vram.setData(telemetry.t, { vram });
}
function renderActive(ai) {
const box = $("ai-active");
const b = ai.backends.find((x) => x.key === ai.active);
if (!b) {
const kv = el("dl", { class: "kv" }, ai.backends.flatMap((x) => [
el("dt", { text: x.label }), el("dd", {}, el("code", { text: x.links.api }))]));
box.replaceChildren(el("h3", { text: "No LLM server running" }),
el("p", { class: "sub", text: "A request to either address starts its server, or pick one above. The Kurgan remembers a choice made here and starts it at every logon." }),
kv);
renderRequests(null);
return;
}
const running = b.process === "running" || b.process === "external";
const st = b.model.state;
const adminLevel = b.token && ["high", "system"].includes(b.token.integrity);
const token = !b.token ? null : adminLevel ? `admin rights, ${b.token.integrity} integrity (unexpected)`
: `${b.token.elevated ? "restricted token" : "normal user"}, ${b.token.integrity} integrity`;
const kv = el("dl", { class: "kv" },
el("dt", { text: "Model" }), el("dd", { text: b.model.id ?? b.model_label }),
b.model.context ? [el("dt", { text: "Context" }), el("dd", { text: `${fmt.n0(b.model.context)} tokens` })] : null,
el("dt", { text: "API" }), el("dd", {}, el("code", { text: b.links.api }), " · no API key needed"),
b.pid ? [el("dt", { text: "Process" }), el("dd", { text: `pid ${b.pid}${b.external_program ? ` (${b.external_program})` : ""} · port ${b.port}${token ? ` · ${token}` : ""}` })] : null,
b.uptime != null ? [el("dt", { text: "Up" }), el("dd", { text: fmt.dur(b.uptime) + (b.restarts ? ` · ${b.restarts} restart${b.restarts > 1 ? "s" : ""}` : "") })] : null,
b.inflight ? [el("dt", { text: "Requests" }), el("dd", { text: `${b.inflight} in progress` })] : null,
b.idle_stop_in != null ? [el("dt", { text: "Idle stop" }), el("dd", { text: `in ${fmt.dur(b.idle_stop_in)} if unused` })] : null,
);
const canLoad = running && ["unloaded", "sleeping"].includes(st);
const canUnload = running && ["idle", "loading"].includes(st);
const actions = el("div", { class: "row", style: "margin-top:14px" },
el("button", { class: "btn", type: "button", disabled: !(canLoad || canUnload) || !!ai.action,
onclick: (e) => change(e.target, "/api/ai/model", { action: canLoad ? "load" : "unload" }) },
ai.action ? `${ai.action}…` : canUnload ? "Unload model" : "Load model"),
el("a", { class: "btn", href: b.links.chat, target: "_blank", rel: "noopener" }, `Open ${b.label} chat ↗`));
let live = null;
if (b.live) {
const L = b.live;
const text = L.phase === "reading"
? `Reading the prompt${L.progress != null ? ` · ${Math.round(L.progress * 100)}%` : ""}${L.read != null ? ` · ${fmt.n0(L.read)}${L.total ? ` of ${fmt.n0(L.total)}` : ""} tokens` : ""}`
: `Generating · ${fmt.n0(L.generated)} tokens`;
live = el("div", { class: "live" }, el("div", { class: "row" }, el("b", { text }), el("span", { class: "spacer" }),
el("span", { class: "muted num", text: `${L.tok_s != null ? `${fmt.n1(L.tok_s)} tok/s · ` : ""}${fmt.dur(L.elapsed)}` })),
L.phase === "reading" && L.progress != null
? el("div", { class: "meter", role: "progressbar", "aria-valuenow": Math.round(L.progress * 100) },
el("span", { style: `width:${(L.progress * 100).toFixed(1)}%` })) : null);
}
const avg = b.averages;
const speeds = el("div", { class: "speeds" },
el("div", {}, el("div", { class: "value", text: fmt.n1(avg.prefill_tps) }), el("div", { class: "label", text: "tok/s reading (average)" })),
el("div", {}, el("div", { class: "value", text: fmt.n1(avg.decode_tps) }), el("div", { class: "label", text: "tok/s writing (average)" })),
el("div", {}, el("div", { class: "value", text: fmt.n0(avg.requests) }), el("div", { class: "label", text: "requests" })));
const notes = [];
if (b.process === "external") notes.push(note("info", `Started outside The Kurgan${b.external_program ? ` by ${b.external_program}` : ""}. The Kurgan only watches it; retire that program's own startup task so The Kurgan can manage it.`));
if (b.error) notes.push(note("critical", b.error));
if (b.model.state === "failed" && b.model.detail) notes.push(note("critical", b.model.detail));
if (adminLevel) notes.push(note("warning", "This server is running with admin rights; it should not be."));
// replaceChildren would print a null as the text "null", so drop the empty parts first.
box.replaceChildren(...[el("div", { class: "row" }, el("h3", { text: b.label }), stateLine(b)),
kv, live, running && avg.requests ? speeds : null, ...notes, actions].filter(Boolean));
renderRequests(b);
}
function renderRequests(b) {
const list = b?.requests ?? [];
setText("requests-sub", b ? `${b.label}, newest first${list.length ? "" : " · none yet"}` : "No server selected");
if (!list.length) { $("requests").replaceChildren(); return; }
const head = el("tr", {}, ["Time", "Prompt", "Cached", "Output", "Reading tok/s", "Writing tok/s", "Took", "Result"]
.map((h, i) => el("th", { class: i && i < 7 ? "r" : "", text: h })));
const rows = list.map((r) => el("tr", {},
el("td", { class: "num", text: r.time ?? "--" }), el("td", { class: "r", text: fmt.n0(r.prompt) }),
el("td", { class: "r", text: fmt.n0(r.reused) }), el("td", { class: "r", text: fmt.n0(r.output) }),
el("td", { class: "r", text: fmt.n1(r.prefill_tps) }), el("td", { class: "r", text: fmt.n1(r.decode_tps) }),
el("td", { class: "r", text: r.duration != null ? `${fmt.n1(r.duration)} s` : "--" }), el("td", { text: r.status })));
$("requests").replaceChildren(el("table", {}, el("thead", {}, head), el("tbody", {}, rows)));
}
/* ------------------------------------------------------------------ main loop */
function render(s) {
lastState = s;
renderHeader(s);
renderSystem(s);
if (telemetry.push(s.telemetry.row)) {
charts.power.setData(telemetry.t, telemetry.cols);
charts.temps.setData(telemetry.t, telemetry.cols);
}
renderCooling(s);
renderLighting(s);
renderAI(s);
}
let failures = 0;
async function poll() {
if (document.hidden) return;
try {
const s = await api("/api/state");
if (failures) { banner(null); Object.values(charts).forEach((c) => c.stale(false)); }
failures = 0;
render(s);
} catch (error) {
failures++;
if (failures === 2) {
banner("critical", "Can't reach The Kurgan. It may be restarting; this page keeps trying.", true);
Object.values(charts).forEach((c) => c.stale(true));
$("meta").replaceChildren(el("span", { class: "pill" }, el("span", { class: "dot critical" }), "Disconnected"));
}
}
}
async function start() {
try {
config = await api("/api/config");
const history = await api("/api/history");
telemetry = new Series(history.series);
telemetry.load(history.rows);
fanHistory = new Series(history.fans.series);
fanHistory.load(history.fans.rows);
} catch (error) {
banner("critical", `Can't load The Kurgan's data: ${error.message}. Reload the page to try again.`, true);
return;
}
buildCharts();
charts.power.setData(telemetry.t, telemetry.cols);
charts.temps.setData(telemetry.t, telemetry.cols);
charts.fans.setData(fanHistory.t, fanHistory.cols);
await poll();
setInterval(poll, 1000);
document.addEventListener("visibilitychange", () => { if (!document.hidden) poll(); });
}
start();
+12
View File
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<symbol id="tank" viewBox="0 0 32 32">
<rect x="6.5" y="4" width="19" height="24" rx="1" fill="#141418"/>
<rect x="6.5" y="21" width="19" height="7" fill="#d95926"/>
<rect x="6.5" y="14.5" width="19" height="6" fill="#3987e5"/>
<rect x="6.5" y="8" width="19" height="6" fill="#199e70"/>
<rect x="9" y="5" width="2.2" height="22" fill="#fff" opacity=".25"/>
<rect x="3.5" y="1" width="25" height="4.5" rx="1.5" fill="#cecdd4"/>
<rect x="3.5" y="26.5" width="25" height="4.5" rx="1.5" fill="#cecdd4"/>
</symbol>
<use href="#tank"/>
</svg>

After

Width:  |  Height:  |  Size: 632 B

+117
View File
@@ -0,0 +1,117 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>The Kurgan</title>
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/static/style.css">
<script src="/static/app.js" defer></script>
</head>
<body>
<header class="masthead">
<div class="brand">
<svg viewBox="0 0 32 32" aria-hidden="true"><use href="/static/favicon.svg#tank"/></svg>
<h1>THE KURGAN</h1>
</div>
<nav aria-label="Sections">
<a href="#system">System</a><a href="#cooling">Cooling</a><a href="#lighting">Lighting</a><a href="#ai">AI</a>
</nav>
<div class="hero" title="Whole-PC power draw (DC, load on the power supply)">
<span class="hero-value" id="hero-total">--</span><span class="hero-unit">W</span>
<span class="hero-label">whole PC</span>
</div>
<div class="meta" id="meta" aria-live="polite"></div>
</header>
<div class="banner" id="banner" role="status" hidden></div>
<main>
<!-- ======================================================== SYSTEM -->
<section id="system" aria-labelledby="h-system">
<h2 id="h-system">System</h2>
<div class="tiles">
<div class="card tile">
<div class="label"><span class="key" style="background:var(--cpu)"></span>CPU</div>
<div class="value"><span id="cpu-temp">--</span><small>°C</small></div>
<div class="detail" id="cpu-detail">&nbsp;</div>
</div>
<div class="card tile">
<div class="label"><span class="key" style="background:var(--gpu)"></span>GPU</div>
<div class="value"><span id="gpu-temp">--</span><small>°C</small></div>
<div class="detail" id="gpu-detail">&nbsp;</div>
</div>
<div class="card tile">
<div class="label">GPU memory</div>
<div class="value"><span id="vram-used">--</span><small id="vram-total"></small></div>
<div class="meter" role="meter" aria-label="GPU memory used" id="vram-meter"><span></span></div>
</div>
<div class="card tile">
<div class="label">LCD</div>
<div class="value" style="font-size:18px;margin-top:8px" id="lcd-status">--</div>
<div class="detail" id="lcd-detail">&nbsp;</div>
</div>
</div>
<div class="grid2">
<figure class="card chart" id="chart-power"></figure>
<figure class="card chart" id="chart-temps"></figure>
</div>
</section>
<!-- ======================================================== COOLING -->
<section id="cooling" aria-labelledby="h-cooling">
<h2 id="h-cooling">Cooling</h2>
<div class="card">
<div class="row">
<div>
<h3>Fan profile</h3>
<p class="sub" style="margin:0">Applies to the Commander PRO case fans and the motherboard top fans. Fail-safes stay on in every profile.</p>
</div>
<div class="spacer"></div>
<div class="seg" role="radiogroup" aria-label="Fan profile" id="profiles"></div>
</div>
<p class="profile-desc" id="profile-desc"></p>
<div id="cooling-note"></div>
</div>
<div class="grid3" id="fan-groups"></div>
<div class="grid2">
<figure class="card chart" id="chart-fans"></figure>
<figure class="card chart" id="chart-curves"></figure>
</div>
</section>
<!-- ======================================================== LIGHTING -->
<section id="lighting" aria-labelledby="h-lighting">
<h2 id="h-lighting">Lighting</h2>
<div class="grid3" id="light-zones"></div>
<p class="muted" style="font-size:13px;margin:10px 2px 0" id="chase-note"></p>
</section>
<!-- ======================================================== AI -->
<section id="ai" aria-labelledby="h-ai">
<h2 id="h-ai">AI</h2>
<div class="card">
<div class="row" style="margin-bottom:12px">
<div>
<h3>Local LLM server</h3>
<p class="sub" style="margin:0">One runs at a time, so they never share the GPU's memory. A request to either one's address starts it, once the other has finished what it's doing; switching stops the other completely first.</p>
<p class="sub" style="margin:4px 0 0" id="ai-idle"></p>
</div>
</div>
<div class="backends" role="radiogroup" aria-label="LLM server" id="backends"></div>
<div id="ai-notes"></div>
</div>
<div class="grid2">
<div class="card" id="ai-active"></div>
<figure class="card chart" id="chart-vram"></figure>
</div>
<div class="card" style="margin-top:16px">
<h3>Recent requests</h3>
<p class="sub" id="requests-sub">Newest first</p>
<div class="table-wrap" id="requests"></div>
</div>
</section>
</main>
<footer id="footer"></footer>
<div class="tooltip" id="tooltip" role="tooltip" hidden></div>
</body>
</html>
+277
View File
@@ -0,0 +1,277 @@
/* The Kurgan - control UI. Dark by default; a selected light theme follows the OS setting. */
:root {
color-scheme: dark;
--page: #0b0b0b;
--surface: #191919;
--surface-2: #222222;
--raised: #2a2a2a;
--text: #efefef;
--text-2: #9c9c9c;
--grid: #303030;
--axis: #474747;
--border: rgba(255, 255, 255, 0.10);
--brand: #e81c2c;
--select-bg: #efefef;
--select-text: #0b0b0b;
/* series: validated together (dataviz validator, dark surface #191919) */
--cpu: #338ced;
--gpu: #00a888;
--other: #e76624;
--top: #e76624;
/* status: reserved for state, always with an icon and a word */
--good: #0aac23;
--warning: #fbb315;
--serious: #f18a59;
--critical: #dc3c3d;
--meter-track: #2c2c2c;
--meter-fill: #9c9c9c;
--font: system-ui, -apple-system, "Segoe UI", sans-serif;
}
@media (prefers-color-scheme: light) {
:root {
color-scheme: light;
--page: #f9f9f9;
--surface: #ffffff;
--surface-2: #f3f3f3;
--raised: #e9e9e9;
--text: #191919;
--text-2: #666666;
--grid: #e7e7e7;
--axis: #c2c2c2;
--border: rgba(11, 11, 11, 0.10);
--brand: #c4121f;
--select-bg: #191919;
--select-text: #ffffff;
--cpu: #257de0;
--gpu: #00b894;
--other: #f47230;
--top: #f47230;
--meter-track: #e7e7e7;
--meter-fill: #666666;
}
}
* { box-sizing: border-box; }
html { scroll-behavior: smooth; scroll-padding-top: 76px; }
body {
margin: 0;
background: var(--page);
color: var(--text);
font: 14px/1.45 var(--font);
}
a { color: inherit; }
button, select, input { font: inherit; color: inherit; }
[hidden] { display: none !important; }
/* ---------------------------------------------------------------- header */
.masthead {
position: sticky; top: 0; z-index: 10;
display: flex; align-items: center; gap: 24px; flex-wrap: wrap;
padding: 10px 24px;
background: color-mix(in srgb, var(--page) 92%, transparent);
backdrop-filter: blur(6px);
border-bottom: 1px solid var(--border);
}
.brand { display: flex; align-items: center; gap: 10px; }
.brand svg { width: 22px; height: 22px; }
.brand h1 {
margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.22em; color: var(--brand);
}
.masthead nav { display: flex; gap: 4px; }
.masthead nav a {
text-decoration: none; color: var(--text-2); padding: 4px 10px; border-radius: 6px;
}
.masthead nav a:hover, .masthead nav a:focus-visible { background: var(--surface-2); color: var(--text); }
.hero { margin-left: auto; display: flex; align-items: baseline; gap: 6px; }
.hero-value { font-size: 48px; font-weight: 600; line-height: 1; }
.hero-unit { font-size: 18px; font-weight: 600; }
.hero-label { color: var(--text-2); margin-left: 4px; }
.meta { color: var(--text-2); font-size: 13px; display: flex; gap: 14px; flex-wrap: wrap; }
.banner {
margin: 12px 24px 0; padding: 10px 14px; border-radius: 8px;
background: var(--surface); border: 1px solid var(--border);
display: flex; gap: 10px; align-items: flex-start;
}
.banner .note { margin: 0; font-size: 14px; }
/* ---------------------------------------------------------------- layout */
main { padding: 8px 24px 40px; max-width: 1480px; margin: 0 auto; }
section { margin-top: 28px; }
section > h2 {
font-size: 13px; font-weight: 600; letter-spacing: 0.12em; text-transform: uppercase;
color: var(--text-2); margin: 0 0 12px;
}
.grid2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(420px, 1fr)); gap: 16px; margin-top: 16px; }
.grid3 { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; margin-top: 16px; }
.card {
background: var(--surface); border: 1px solid var(--border); border-radius: 10px;
padding: 16px 18px; margin: 0; min-width: 0;
}
.card h3 { margin: 0 0 2px; font-size: 15px; font-weight: 600; }
.card .sub { color: var(--text-2); font-size: 13px; margin: 0 0 12px; }
.row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.spacer { flex: 1; }
.muted { color: var(--text-2); }
.num { font-variant-numeric: tabular-nums; }
/* ---------------------------------------------------------------- stat tiles */
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; }
.tile .label { color: var(--text-2); font-size: 13px; display: flex; align-items: center; gap: 6px; }
.tile .value { font-size: 30px; font-weight: 600; line-height: 1.15; margin-top: 2px; }
.tile .value small { font-size: 15px; font-weight: 600; margin-left: 2px; }
.tile .detail { color: var(--text-2); font-size: 13px; margin-top: 4px; }
.key { display: inline-block; width: 10px; height: 10px; border-radius: 2px; flex: none; }
.key.line { width: 14px; height: 2px; border-radius: 1px; }
/* ---------------------------------------------------------------- meters */
.meter { height: 8px; border-radius: 4px; background: var(--meter-track); overflow: hidden; margin-top: 8px; }
.meter > span { display: block; height: 100%; border-radius: 4px; background: var(--meter-fill); width: 0; transition: width .4s; }
.meter.cpu > span { background: var(--cpu); }
.meter.gpu > span { background: var(--gpu); }
.meter.top > span { background: var(--top); }
.meter.warning > span { background: var(--warning); }
.meter.critical > span { background: var(--critical); }
/* ---------------------------------------------------------------- controls */
.seg {
display: inline-flex; background: var(--surface-2); border-radius: 8px; padding: 3px; gap: 2px;
border: 1px solid var(--border); flex-wrap: wrap;
}
.seg label { position: relative; }
.seg input { position: absolute; opacity: 0; inset: 0; margin: 0; cursor: pointer; }
.seg span {
display: block; padding: 6px 14px; border-radius: 6px; color: var(--text-2); cursor: pointer;
white-space: nowrap; user-select: none;
}
.seg label:hover span { color: var(--text); background: var(--raised); }
.seg input:checked + span { background: var(--select-bg); color: var(--select-text); font-weight: 600; }
.seg input:focus-visible + span { outline: 2px solid var(--text); outline-offset: 1px; }
.seg.busy { opacity: 0.6; pointer-events: none; }
.btn {
border: 1px solid var(--border); background: var(--surface-2); border-radius: 8px;
padding: 7px 14px; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 6px;
}
.btn:hover:not(:disabled) { background: var(--raised); }
.btn:disabled { opacity: 0.5; cursor: default; }
.btn:focus-visible { outline: 2px solid var(--text); outline-offset: 1px; }
select {
background: var(--surface-2); border: 1px solid var(--border); border-radius: 6px; padding: 4px 8px;
}
/* ---------------------------------------------------------------- status */
.pill {
display: inline-flex; align-items: center; gap: 6px; padding: 2px 10px; border-radius: 999px;
background: var(--surface-2); border: 1px solid var(--border); font-size: 13px; white-space: nowrap;
}
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text-2); flex: none; }
.dot.good { background: var(--good); }
.dot.busy { background: var(--cpu); }
.dot.warning { background: var(--warning); }
.dot.critical { background: var(--critical); }
.note { display: flex; gap: 8px; align-items: flex-start; font-size: 13px; margin-top: 10px; }
.note svg { flex: none; width: 16px; height: 16px; margin-top: 1px; }
.note.warning svg { color: var(--warning); }
.note.critical svg { color: var(--critical); }
.note.info svg { color: var(--text-2); }
/* ---------------------------------------------------------------- fan groups */
.fan-head { display: flex; align-items: baseline; gap: 8px; }
.fan-duty { font-size: 30px; font-weight: 600; line-height: 1.1; }
.fan-ports { display: flex; gap: 14px; margin-top: 10px; color: var(--text-2); font-size: 13px; flex-wrap: wrap; }
.fan-ports b { color: var(--text); font-weight: 600; }
.profile-desc { color: var(--text-2); margin: 10px 0 0; font-size: 13px; }
/* ---------------------------------------------------------------- lighting */
.zone .status { color: var(--text-2); font-size: 13px; margin-top: 10px; min-height: 19px; }
/* ---------------------------------------------------------------- AI */
.backends { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; }
.choice {
position: relative; display: block; border: 1px solid var(--border); border-radius: 10px;
padding: 12px 14px; background: var(--surface-2); cursor: pointer;
}
.choice:hover { background: var(--raised); }
.choice input[type=radio] { position: absolute; opacity: 0; }
.choice:has(input[type=radio]:checked) { border-color: var(--text); box-shadow: inset 0 0 0 1px var(--text); }
.choice:has(input[type=radio]:focus-visible) { outline: 2px solid var(--text); outline-offset: 2px; }
.choice .name { font-weight: 600; display: flex; align-items: center; gap: 8px; }
.choice .what { color: var(--text-2); font-size: 13px; margin-top: 2px; }
.choice .state { margin-top: 8px; }
.choice select { margin-top: 8px; max-width: 100%; }
.check {
margin-left: auto; width: 18px; height: 18px; border-radius: 50%; border: 2px solid var(--axis);
display: inline-grid; place-items: center;
}
.choice:has(input[type=radio]:checked) .check { border-color: var(--text); background: var(--text); }
.choice:has(input[type=radio]:checked) .check::after {
content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--surface);
}
.backends.busy { opacity: 0.6; pointer-events: none; }
.kv { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 12px 0 0; font-size: 13px; }
.kv dt { color: var(--text-2); }
.kv dd { margin: 0; overflow-wrap: anywhere; }
.live { margin-top: 14px; padding: 12px; border-radius: 8px; background: var(--surface-2); }
.live .meter > span { background: var(--cpu); }
.speeds { display: flex; gap: 28px; margin-top: 14px; flex-wrap: wrap; }
.speeds .value { font-size: 24px; font-weight: 600; }
.speeds .label { color: var(--text-2); font-size: 13px; }
code { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font-size: 12.5px; }
/* ---------------------------------------------------------------- tables */
table { width: 100%; border-collapse: collapse; font-size: 13px; }
th { text-align: left; font-weight: 600; color: var(--text-2); padding: 6px 8px; border-bottom: 1px solid var(--axis); }
td { padding: 6px 8px; border-bottom: 1px solid var(--grid); }
td.r, th.r { text-align: right; font-variant-numeric: tabular-nums; }
.table-wrap { overflow-x: auto; }
/* ---------------------------------------------------------------- charts */
.chart-head { display: flex; align-items: flex-start; gap: 12px; flex-wrap: wrap; }
.chart-head h3 { margin: 0; }
.legend { display: flex; gap: 14px; flex-wrap: wrap; color: var(--text-2); font-size: 13px; margin-top: 4px; }
.legend span { display: inline-flex; align-items: center; gap: 6px; }
.table-toggle { margin-left: auto; font-size: 12.5px; padding: 4px 10px; }
.plot { position: relative; margin-top: 10px; }
.plot svg { display: block; width: 100%; height: 210px; overflow: visible; touch-action: none; }
.plot .grid line { stroke: var(--grid); stroke-width: 1; }
.plot .baseline { stroke: var(--axis); stroke-width: 1; }
.plot .tick { fill: var(--text-2); font-size: 11px; font-variant-numeric: tabular-nums; }
.plot .ref { stroke: var(--axis); stroke-width: 1; }
.plot .ref-label { fill: var(--text-2); font-size: 11px; }
.plot .series-line { fill: none; stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; }
.plot .series-area { opacity: 0.12; }
.plot .cross { stroke: var(--text-2); stroke-width: 1; }
.plot .marker { stroke: var(--surface); stroke-width: 2; }
.plot .end-label { fill: var(--text); font-size: 12px; font-weight: 600; }
.plot.stale { opacity: 0.45; }
.chart-table { margin-top: 10px; max-height: 260px; overflow: auto; }
.tooltip {
position: fixed; z-index: 20; pointer-events: none; min-width: 150px;
background: var(--surface-2); border: 1px solid var(--border); border-radius: 8px;
padding: 8px 10px; font-size: 13px; box-shadow: 0 4px 16px rgba(0, 0, 0, 0.35);
}
.tooltip .when { color: var(--text-2); margin-bottom: 4px; }
.tooltip .tip-row { display: flex; align-items: center; gap: 8px; }
.tooltip .tip-row b { font-weight: 600; min-width: 56px; font-variant-numeric: tabular-nums; }
.tooltip .tip-row span:last-child { color: var(--text-2); }
footer { color: var(--text-2); font-size: 12.5px; padding: 0 24px 28px; max-width: 1480px; margin: 0 auto; }
@media (max-width: 720px) {
.masthead { padding: 10px 14px; gap: 12px; }
main { padding: 8px 14px 32px; }
.hero-value { font-size: 36px; }
.grid2 { grid-template-columns: 1fr; }
}
@media (prefers-reduced-motion: reduce) {
html { scroll-behavior: auto; }
.meter > span { transition: none; }
}
/* the server card sits at the top of its row instead of stretching beside the chart */
#ai-active { align-self: start; }
.pills { display: inline-flex; gap: 6px; flex-wrap: wrap; }