From 0d721cf87b576a32f584b5bf7c9bd2390460a2ad Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 27 Sep 2026 12:00:33 +0200 Subject: [PATCH] Web app: Chat, Monitor and About tabs (#22) The browser page at http://127.0.0.1:8080 is now the Strata app, in the Strata design language (serve/web, same origin, no CDN): - Chat: streaming answers, collapsible thinking, Markdown with code copy, images when enabled, sampling/thinking settings, export, new chat. - Monitor: live model state (reading with progress / generating at tok/s), GPU load, VRAM, temperature, power, PCIe traffic, CPU, RAM, disk, the context fill and the last requests, each with a minute of history. - About: the model and engine settings, this PC, the API addresses. Server: GET /metrics (API key when set), /web/* app files, /fonts/* only when installed locally (not shipped; the page falls back to the system font). serve/telemetry.py reads NVML via ctypes and psutil (new setup dependency) with fallbacks. The engine prints an INFO line before READY (kv, expert slots, speculation); older servers ignore it and the server works with older engines. Based on the dashboard idea in PR #22 by code-martin. --- .gitignore | 3 + README.md | 5 +- docs/DETAILS.md | 13 +- serve/index.html | 152 --------- serve/server.py | 110 ++++++- serve/telemetry.py | 246 ++++++++++++++ serve/test_server.py | 64 ++++ serve/web/app.css | 140 ++++++++ serve/web/app.js | 681 +++++++++++++++++++++++++++++++++++++++ serve/web/components.css | 128 ++++++++ serve/web/index.html | 205 ++++++++++++ serve/web/sprite.svg | 34 ++ serve/web/tokens.css | 88 +++++ setup.py | 4 +- src/program/generate.cpp | 12 + 15 files changed, 1725 insertions(+), 160 deletions(-) delete mode 100644 serve/index.html create mode 100644 serve/telemetry.py create mode 100644 serve/web/app.css create mode 100644 serve/web/app.js create mode 100644 serve/web/components.css create mode 100644 serve/web/index.html create mode 100644 serve/web/sprite.svg create mode 100644 serve/web/tokens.css diff --git a/.gitignore b/.gitignore index e8501e9f..accfb257 100644 --- a/.gitignore +++ b/.gitignore @@ -46,3 +46,6 @@ build-vision.bat /dist/ *.done /third_party/*.zip + +# the web app's fonts (GT Walsheim Pro, commercial licence): local only, never published +serve/web/fonts/ diff --git a/README.md b/README.md index c5867ae9..2b1fd572 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ model - is set up for you. - **Images?** Whether it should also read pictures Then it downloads everything (the model is ~70 GB, so the first time takes a while - you can stop and it picks up -where it left off) and **starts the model**. Your browser opens a chat page at `http://127.0.0.1:8080`. +where it left off) and **starts the model**. Your browser opens the Strata app at `http://127.0.0.1:8080`. **Next time**, just double-click `START-HERE.bat` again: it starts right away, nothing is downloaded twice. Close its window to stop the model. @@ -91,7 +91,8 @@ Not sure? Take **IQ2_XS**. You can add another one later with `START-HERE.bat -- ## Using it -- **Chat in the browser:** `http://127.0.0.1:8080` - a simple chat page (it opens by itself when the model starts). +- **In the browser:** `http://127.0.0.1:8080` - the Strata app (it opens by itself when the model starts): **Chat**, a + live **Monitor** of the model and your GPU/CPU/RAM, and **About** with the settings and addresses. - **Chat in the terminal:** `.venv\Scripts\python chat.py` - **Your apps and coding agents:** add it as an "OpenAI-compatible" provider with base URL **`http://127.0.0.1:8080/v1`**, any API key and any model name. Apps that use Anthropic's API: `http://127.0.0.1:8080/v1/messages`. diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 11d70011..ceadcd97 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -130,8 +130,16 @@ Windows, `build-essential` + CUDA on Ubuntu) and compiles the engine for your GP 4. **Images?** yes / no (see [Images](#images-vision)). Then it downloads and prepares everything (the model is 66-76 GB, so the first start takes a while; an interrupted -download continues where it stopped) and **starts the model**: your browser opens `http://127.0.0.1:8080`, a small -page that shows it is running and lets you chat. The API is at `http://127.0.0.1:8080/v1` for your apps. +download continues where it stopped) and **starts the model**: your browser opens `http://127.0.0.1:8080`, the Strata +app. It has three tabs: +- **Chat:** streaming answers, the model's thinking (folded away once it answers), code with a copy button, pictures when + images are on, and sampling and thinking-level settings. Chats stay in your browser. +- **Monitor:** what the model is doing (reading the prompt, with progress, or writing, at how many tokens/s); GPU load, + VRAM, temperature, power and PCIe traffic; CPU, RAM and disk; the context in use; the last requests. +- **About:** the model and engine settings, and the addresses to connect other apps. + +`http://127.0.0.1:8080/?q=your question` opens it with a new chat already asking. The API is at +`http://127.0.0.1:8080/v1` for your apps. **Every time after that**, `START-HERE.bat` just starts the model (30-90 s to load 34-43 GB into RAM). Nothing is downloaded again. Closing the window stops the model. @@ -176,6 +184,7 @@ The server listens on `http://127.0.0.1:8080` (change with `--port` in setup, or | Anthropic Messages (stream and non-stream, tools) | `POST /v1/messages` | | Model list / health | `GET /v1/models`, `GET /health` | | What the model is doing right now | `GET /status` | +| Everything the Monitor tab shows (engine, live state, last requests, hardware) | `GET /metrics` | ```bash curl http://127.0.0.1:8080/v1/chat/completions -H "Content-Type: application/json" -d '{ diff --git a/serve/index.html b/serve/index.html deleted file mode 100644 index 1da0b5ce..00000000 --- a/serve/index.html +++ /dev/null @@ -1,152 +0,0 @@ - - - - - -Strata - - - -
-
-

Strata connecting ...

-
- Model- - Context- - Images- - OpenAI API (any API key) - Anthropic API -
-

Point any app with an "OpenAI-compatible" or "Anthropic" provider at these - addresses. Close the Strata window to stop the model.

-
- -
- -
-
- - - - -
-
- - - - -
-
-
- - - diff --git a/serve/server.py b/serve/server.py index 4f968094..c0e12dc0 100644 --- a/serve/server.py +++ b/serve/server.py @@ -19,6 +19,7 @@ talks to it over stdin/stdout; `MockEngine` is a scripted stand-in that makes ev from __future__ import annotations import argparse +import collections import base64 import hashlib import json @@ -88,7 +89,17 @@ class StrataEngine: self.max_context = 0 self.can_stop = False # the engine honours a STOP line mid-request (READY stop) self.last = {} + self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab) + self.progress = None # (read, total) prompt tokens while a prompt is read, from PP lines + try: # a ready-made engine's BUILD.json says its version + self.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version") + except (OSError, ValueError): + self.info["version"] = None for line in self.proc.stdout: + if line.startswith("INFO "): + for kv in line.split()[1:]: + k, _, v = kv.partition("=") + self.info[k] = int(v) if v.lstrip("-").isdigit() else v if line.startswith("READY"): f = line.split() self.max_context = int(f[1]) @@ -109,6 +120,8 @@ class StrataEngine: f = line.split() self.last = {"generated": int(f[1]), "prompt_tokens": int(f[2]), "prompt_ms": float(f[3]), "decode_ms": float(f[4]), "finish": f[5]} + if len(f) >= 9: # the conversation cache's fields (engine 0.1.3+) + self.last.update(drafts_accepted=int(f[6]), drafts_offered=int(f[7]), reused=int(f[8])) @staticmethod def sampling_keys(sampling: dict) -> str: @@ -153,6 +166,7 @@ class StrataEngine: """Yields token ids, and None as a heartbeat every 10 s while the engine is quiet (reading a long prompt): the HTTP layer turns it into an SSE comment, which keeps clients' watchdogs calm and notices a client that has gone. A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new.""" + self.progress = None head = f"GENI {int(max_new)} {embeddings}" if embeddings else \ f"GEN {int(max_new)}{self.sampling_keys(sampling or {}) if not embeddings else ''}" self.proc.stdin.write(f"{head} {','.join(str(int(t)) for t in ids)}\n") @@ -174,7 +188,10 @@ class StrataEngine: if cancel.is_set(): return yield int(line[2:]) - elif line.startswith("PP "): # prompt progress, one per chunk: also a heartbeat (the + elif line.startswith("PP "): + f = line.split() + if len(f) >= 3 and f[1].isdigit() and f[2].isdigit(): + self.progress = (int(f[1]), int(f[2])) # prompt progress, one per chunk: also a heartbeat (the if cancel.is_set(): # lines reset the 10 s wait, so without this a long prompt return # would send no keep-alives at all) yield None @@ -365,10 +382,52 @@ class Service: self.embeddings = threading.local() # the current request's image embeddings file (GENI) self.api_key = "" # when set, /v1/* needs it (Bearer or x-api-key) self.status = {"busy": False, "queued": 0} # GET /status: what the model is doing right now + self.history = collections.deque(maxlen=30) # the last finished requests, newest last (GET /metrics) self.status_lock = threading.Lock() self.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) + tokenizer.encode("<|endoftext|>", parse_special=True)) + def start_telemetry(self): + """The hardware sampler behind GET /metrics (serve/telemetry.py), recording this server's tok/s too.""" + if getattr(self, "telemetry", None) is None: + from serve.telemetry import Telemetry + self.telemetry = Telemetry(extra=lambda: {"tok_s": self._tok_s()}) + + def _tok_s(self): + with self.status_lock: + s = dict(self.status) + if not s.get("busy") or not s.get("first_token"): + return 0.0 + return s["generated"] / max(1e-6, time.time() - s["first_token"]) + + def metrics(self) -> dict: + """GET /metrics: what the Monitor tab shows - the engine's facts, what it is doing, the last requests, and + the hardware (with a minute of history per series).""" + with self.status_lock: + s = dict(self.status) + hist = list(self.history) + now = time.time() + progress = getattr(self.engine, "progress", None) + if s.get("busy") and s.get("first_token") is None: + state = "reading" + elif s.get("busy"): + state = "generating" + else: + state = "idle" + live = {"state": state, "queued": s.get("queued", 0), "phase": s.get("phase") if s.get("busy") else None, + "prompt_tokens": s.get("prompt_tokens") if s.get("busy") else None, + "prompt_read": None, "prompt_total": None, "generated": s.get("generated") if s.get("busy") else None, + "max_tokens": s.get("max_tokens") if s.get("busy") else None, + "elapsed_s": round(now - s["started"], 1) if s.get("busy") and s.get("started") else None, + "tok_s": round(self._tok_s(), 1) if state == "generating" else None} + if state == "reading" and progress: + live["prompt_read"], live["prompt_total"] = progress + engine = {"model": self.model, "max_context": self.engine.max_context, "images": self.vision is not None, + **dict(getattr(self.engine, "info", {}) or {})} + tel = self.telemetry.snapshot() if getattr(self, "telemetry", None) else {"now": {}, "history": {}, "static": {}} + return {"engine": engine, "live": live, "requests": hist[::-1], "hardware": tel["now"], "hardware_static": + tel["static"], "history": tel["history"], "time": now} + def prepare(self, messages, tools, kwargs, max_new=None): """-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited": the rest of the context.""" @@ -497,6 +556,14 @@ class Service: Path(emb).unlink(missing_ok=True) with self.status_lock: if self.status.get("busy"): + last = dict(getattr(self.engine, "last", {}) or {}) + started = self.status.get("started", time.time()) + self.history.append({ + "time": started, "duration_s": round(time.time() - started, 1), "finish": finish, + "prompt_tokens": len(ids), "reused": last.get("reused"), "output_tokens": n, + "prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"), + "decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1) + if n and last.get("generated") and last.get("decode_ms") else None}) now = time.time() el = now - self.status.get("started", now) ft = self.status.get("first_token") @@ -713,8 +780,46 @@ def make_handler(svc: Service): def do_GET(self): path = self.path.split("?")[0].rstrip("/") + if path.startswith("/fonts/"): + # the web app's fonts, only if they are installed locally (serve/web/fonts); the page falls back + # to the system font without them + name = path[len("/fonts/"):] + f = ROOT / "serve" / "web" / "fonts" / name + if "/" in name or "\\" in name or not name.endswith(".woff2") or not f.is_file(): + self._json(404, {"error": {"message": "not found"}}) + return + body = f.read_bytes() + self.send_response(200) + self.send_header("Content-Type", "font/woff2") + self.send_header("Cache-Control", "max-age=86400") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + if path.startswith("/web/"): + # the web app's own files (serve/web): styles, script, icon sprite - same origin, no CDN + name = path[len("/web/"):] + types = {".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8", + ".svg": "image/svg+xml"} + f = ROOT / "serve" / "web" / name + ext = os.path.splitext(name)[1] + if "/" in name or "\\" in name or ext not in types or not f.is_file(): + self._json(404, {"error": {"message": "not found"}}) + return + body = f.read_bytes() + self.send_response(200) + self.send_header("Content-Type", types[ext]) + self.send_header("Cache-Control", "no-cache") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + if path == "/metrics": + if self._authorized(): + self._json(200, svc.metrics()) + return if path == "": - body = (ROOT / "serve" / "index.html").read_bytes() + body = (ROOT / "serve" / "web" / "index.html").read_bytes() self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(body))) @@ -815,6 +920,7 @@ class Server(ThreadingHTTPServer): def serve(svc: Service, host="127.0.0.1", port=8095) -> ThreadingHTTPServer: + svc.start_telemetry() httpd = Server((host, port), make_handler(svc)) threading.Thread(target=httpd.serve_forever, daemon=True).start() return httpd diff --git a/serve/telemetry.py b/serve/telemetry.py new file mode 100644 index 00000000..1bb9b292 --- /dev/null +++ b/serve/telemetry.py @@ -0,0 +1,246 @@ +"""serve/telemetry.py - hardware readings for the web app's Monitor tab (idea from PR #22 by code-martin). + +A background thread samples once a second and keeps the last 60 readings of each series for the sparklines: +- GPU: NVIDIA's own NVML library (nvml.dll / libnvidia-ml.so.1, installed with every driver) through ctypes, so no + pip package is needed: load, VRAM, temperature, power, PCIe link and throughput. +- CPU, RAM, disk: `psutil` when it is installed (setup installs it); without it the CPU and RAM readings fall back to + the OS (Windows GlobalMemoryStatusEx / GetSystemTimes, Linux /proc) and the disk rate is absent. +Anything that cannot be read is None; nothing here can stop the server. +""" +from __future__ import annotations + +import collections +import ctypes +import os +import platform +import sys +import threading +import time + +HISTORY = 60 + + +# ------------------------------------------------------------------------------------------------ NVML +class _Nvml: + class Util(ctypes.Structure): + _fields_ = [("gpu", ctypes.c_uint), ("memory", ctypes.c_uint)] + + class Mem(ctypes.Structure): + _fields_ = [("total", ctypes.c_ulonglong), ("free", ctypes.c_ulonglong), ("used", ctypes.c_ulonglong)] + + def __init__(self, index=0): + self.lib = self.dev = None + names = ["nvml.dll", os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), + "NVIDIA Corporation", "NVSMI", "nvml.dll")] if os.name == "nt" \ + else ["libnvidia-ml.so.1", "libnvidia-ml.so"] + for n in names: + try: + self.lib = ctypes.CDLL(n) + break + except OSError: + continue + if self.lib is None: + return + try: + init = getattr(self.lib, "nvmlInit_v2", None) or self.lib.nvmlInit + if init() != 0: + self.lib = None + return + h = ctypes.c_void_p() + get = getattr(self.lib, "nvmlDeviceGetHandleByIndex_v2", None) or self.lib.nvmlDeviceGetHandleByIndex + if get(ctypes.c_uint(index), ctypes.byref(h)) != 0: + self.lib = None + return + self.dev = h + except (AttributeError, OSError): + self.lib = None + + def ok(self): + return self.lib is not None and self.dev is not None + + def _uint(self, fn, *args): + v = ctypes.c_uint() + try: + return v.value if getattr(self.lib, fn)(self.dev, *args, ctypes.byref(v)) == 0 else None + except (AttributeError, OSError): + return None + + def name(self): + buf = ctypes.create_string_buffer(96) + try: + if self.lib.nvmlDeviceGetName(self.dev, buf, ctypes.c_uint(96)) == 0: + return buf.value.decode(errors="replace") + except (AttributeError, OSError): + pass + return None + + def read(self): + out = {} + u = self.Util() + try: + if self.lib.nvmlDeviceGetUtilizationRates(self.dev, ctypes.byref(u)) == 0: + out["util"] = u.gpu + except (AttributeError, OSError): + pass + m = self.Mem() + try: + if self.lib.nvmlDeviceGetMemoryInfo(self.dev, ctypes.byref(m)) == 0: + out["mem_used"], out["mem_total"] = m.used, m.total + except (AttributeError, OSError): + pass + out["temp"] = self._uint("nvmlDeviceGetTemperature", ctypes.c_uint(0)) # NVML_TEMPERATURE_GPU + mw = self._uint("nvmlDeviceGetPowerUsage") + out["power"] = mw / 1000.0 if mw is not None else None + lim = self._uint("nvmlDeviceGetEnforcedPowerLimit") + out["power_limit"] = lim / 1000.0 if lim is not None else None + out["pcie_gen"] = self._uint("nvmlDeviceGetCurrPcieLinkGeneration") # drops at idle (power saving) + out["pcie_gen_max"] = self._uint("nvmlDeviceGetMaxPcieLinkGeneration") + out["pcie_width"] = self._uint("nvmlDeviceGetCurrPcieLinkWidth") + rx = self._uint("nvmlDeviceGetPcieThroughput", ctypes.c_uint(1)) # NVML_PCIE_UTIL_RX_BYTES, KB/s + tx = self._uint("nvmlDeviceGetPcieThroughput", ctypes.c_uint(0)) + out["pcie_rx_mb"] = rx / 1024.0 if rx is not None else None + out["pcie_tx_mb"] = tx / 1024.0 if tx is not None else None + return out + + +# ------------------------------------------------------------------------------------------------ CPU / RAM +def _cpu_name(): + if os.name == "nt": + try: + import winreg + k = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") + return winreg.QueryValueEx(k, "ProcessorNameString")[0].strip() + except OSError: + pass + elif os.path.exists("/proc/cpuinfo"): + for line in open("/proc/cpuinfo", encoding="utf-8", errors="replace"): + if line.startswith("model name"): + return line.split(":", 1)[1].strip() + return platform.processor() or None + + +class _CpuRamFallback: + """CPU load and RAM without psutil.""" + + def __init__(self): + self.prev = self._times() + + def _times(self): + if os.name == "nt": + idle, kern, user = (ctypes.c_ulonglong() for _ in range(3)) + if ctypes.windll.kernel32.GetSystemTimes(ctypes.byref(idle), ctypes.byref(kern), ctypes.byref(user)): + return idle.value, kern.value + user.value # kernel time includes idle + return None + try: + f = [int(x) for x in open("/proc/stat").readline().split()[1:]] + return f[3] + f[4], sum(f) + except (OSError, ValueError): + return None + + def cpu(self): + cur = self._times() + prev, self.prev = self.prev, cur + if not cur or not prev or cur[1] == prev[1]: + return None + return max(0.0, min(100.0, 100.0 * (1 - (cur[0] - prev[0]) / (cur[1] - prev[1])))) + + @staticmethod + def ram(): + if os.name == "nt": + class MS(ctypes.Structure): + _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), + ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), + ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), + ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), + ("ullAvailExtendedVirtual", ctypes.c_ulonglong)] + m = MS() + m.dwLength = ctypes.sizeof(MS) + if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)): + return m.ullTotalPhys - m.ullAvailPhys, m.ullTotalPhys + return None, None + try: + info = dict(line.split(":", 1) for line in open("/proc/meminfo")) + total = int(info["MemTotal"].split()[0]) * 1024 + avail = int(info["MemAvailable"].split()[0]) * 1024 + return total - avail, total + except (OSError, KeyError, ValueError): + return None, None + + +# ------------------------------------------------------------------------------------------------ the sampler +class Telemetry: + def __init__(self, extra=None): + """`extra()` -> dict of more series to record each second (the server's tok/s).""" + self.extra = extra + self.lock = threading.Lock() + self.now: dict = {} + self.hist = collections.defaultdict(lambda: collections.deque(maxlen=HISTORY)) + self.gpu = _Nvml() + try: + import psutil # noqa: F401 + self.ps = sys.modules["psutil"] + except ImportError: + self.ps = None + self.fallback = _CpuRamFallback() + self.static = { + "gpu_name": self.gpu.name() if self.gpu.ok() else None, + "cpu_name": _cpu_name(), + "cores": (self.ps.cpu_count(logical=False) if self.ps else None) or None, + "threads": os.cpu_count(), + "psutil": self.ps is not None, + } + self._disk_prev = None + threading.Thread(target=self._loop, daemon=True).start() + + def _disk(self): + if not self.ps: + return None, None + try: + c = self.ps.disk_io_counters() + except (OSError, RuntimeError): + return None, None + t = time.time() + prev, self._disk_prev = self._disk_prev, (t, c.read_bytes, c.write_bytes) + if prev is None or t <= prev[0]: + return None, None + dt = t - prev[0] + return (c.read_bytes - prev[1]) / dt / 2**20, (c.write_bytes - prev[2]) / dt / 2**20 + + def sample(self): + s = {} + if self.gpu.ok(): + g = self.gpu.read() + s.update({f"gpu_{k}": v for k, v in g.items()}) + if self.ps: + try: + s["cpu"] = self.ps.cpu_percent(interval=None) + vm = self.ps.virtual_memory() + s["ram_used"], s["ram_total"] = vm.total - vm.available, vm.total + except (OSError, RuntimeError): + pass + else: + s["cpu"] = self.fallback.cpu() + s["ram_used"], s["ram_total"] = self.fallback.ram() + s["disk_read_mb"], s["disk_write_mb"] = self._disk() + if self.extra: + try: + s.update(self.extra()) + except Exception: # noqa: BLE001 - telemetry must never take the server down + pass + return s + + def _loop(self): + while True: + s = self.sample() + with self.lock: + self.now = s + for k in ("gpu_util", "gpu_mem_used", "gpu_temp", "gpu_power", "gpu_pcie_rx_mb", "cpu", "ram_used", + "disk_read_mb", "tok_s"): + v = s.get(k) + self.hist[k].append(round(v, 2) if isinstance(v, float) else v) + time.sleep(1.0) + + def snapshot(self): + with self.lock: + return {"now": dict(self.now), "history": {k: list(v) for k, v in self.hist.items()}, + "static": dict(self.static)} diff --git a/serve/test_server.py b/serve/test_server.py index 937e3bd5..00cc0b6d 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -126,5 +126,69 @@ class MaxTokens(unittest.TestCase): del os.environ["STRATA_DEBUG"] +class WebApp(unittest.TestCase): + """The web app (PR #22's dashboard idea, rebuilt): its page and files, and GET /metrics.""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.svc = Service(RecordingEngine(tok, "\n\nhello", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + + def get(self, path, headers=None): + req = urllib.request.Request(self.base + path, headers=headers or {}) + try: + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, r.headers.get("Content-Type", ""), r.read() + except urllib.error.HTTPError as e: + return e.code, e.headers.get("Content-Type", ""), e.read() + + def test_page_and_files(self): + code, ctype, body = self.get("/") + self.assertEqual(code, 200) + self.assertIn("text/html", ctype) + self.assertIn(b"/web/app.js", body) + for path, want in (("/web/app.js", "javascript"), ("/web/app.css", "text/css"), ("/web/tokens.css", "text/css"), + ("/web/components.css", "text/css"), ("/web/sprite.svg", "image/svg+xml")): + with self.subTest(path=path): + code, ctype, _ = self.get(path) + self.assertEqual(code, 200) + self.assertIn(want, ctype) + + def test_only_the_app_files_are_served(self): + for path in ("/web/..%2Fserver.py", "/web/index.html", "/web/test.py", "/fonts/..%2F..%2Fsetup.py", + "/fonts/missing.woff2", "/fonts/x.ttf"): + with self.subTest(path=path): + self.assertEqual(self.get(path)[0], 404) + + def test_metrics(self): + data = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 5}).encode() + urllib.request.urlopen(urllib.request.Request(self.base + "/v1/chat/completions", data=data, + headers={"Content-Type": "application/json"}), timeout=10).read() + code, ctype, body = self.get("/metrics") + self.assertEqual(code, 200) + m = json.loads(body) + for key in ("engine", "live", "requests", "hardware", "hardware_static", "history"): + self.assertIn(key, m) + self.assertEqual(m["engine"]["max_context"], CTX) + self.assertEqual(m["live"]["state"], "idle") + self.assertEqual(m["requests"][0]["output_tokens"], 5) + + def test_metrics_need_the_key_when_one_is_set(self): + self.svc.api_key = "secret" + try: + self.assertEqual(self.get("/metrics")[0], 401) + self.assertEqual(self.get("/metrics", {"Authorization": "Bearer secret"})[0], 200) + self.assertEqual(self.get("/")[0], 200) # the page itself asks for the key + finally: + self.svc.api_key = "" + + if __name__ == "__main__": unittest.main() diff --git a/serve/web/app.css b/serve/web/app.css new file mode 100644 index 00000000..07643503 --- /dev/null +++ b/serve/web/app.css @@ -0,0 +1,140 @@ +/* Strata web app - layout on top of tokens.css + components.css (the Strata UI kit). Colours, type, radii and + shadows come only from the kit's tokens. */ +[hidden] { display: none !important; } +html, body { height: 100%; } +body { display: flex; flex-direction: column; overflow: hidden; } +main { flex: 1; min-height: 0; display: flex; } +.view { flex: 1; min-height: 0; display: flex; flex-direction: column; } +.view[hidden] { display: none; } +.muted { color: var(--st-ink-muted); } +.small { font-size: var(--st-fs-xs); } +.card-title { font-weight: var(--st-fw-bold); font-size: var(--st-fs-base); color: var(--st-ink); } +.st-header { position: relative; z-index: 2; flex: none; } +.st-header .st-tabs { margin-left: var(--st-s-4); } +#drawer-close .st-icon { transform: rotate(-90deg); } + +/* ---------------------------------------------------------------- chat */ +.chat-scroll { flex: 1; min-height: 0; overflow-y: auto; } +.chat { max-width: 860px; margin: 0 auto; padding: var(--st-s-8) var(--st-s-6) var(--st-s-6); display: flex; + flex-direction: column; gap: var(--st-s-6); } +.chat-empty { margin: 12vh auto 0; text-align: center; } +.chat-empty__title { font-weight: var(--st-fw-black); font-size: var(--st-fs-display); line-height: var(--st-lh-tight); + letter-spacing: -.02em; } +.chat-empty__sub { margin-top: var(--st-s-3); color: var(--st-ink-muted); } +.st-msg { width: 100%; } +.st-msg--assistant { align-self: flex-start; } +.st-msg--assistant .st-bubble { width: 100%; } +.st-msg--user .st-bubble { white-space: pre-wrap; overflow-wrap: anywhere; } +.st-bubble > :first-child { margin-top: 0; } +.st-bubble > :last-child { margin-bottom: 0; } +.st-bubble p, .st-bubble ul, .st-bubble ol { margin: 0 0 var(--st-s-3); } +.st-bubble ul, .st-bubble ol { padding-left: var(--st-s-6); } +.st-bubble li + li { margin-top: var(--st-s-1); } +.st-bubble h3 { font-size: var(--st-fs-lg); margin: var(--st-s-4) 0 var(--st-s-2); color: var(--st-ink); } +.st-bubble h4 { font-size: var(--st-fs-base); margin: var(--st-s-3) 0 var(--st-s-2); color: var(--st-ink); } +.st-bubble code.inline { font: 400 .9em var(--st-font-mono); background: var(--st-surface-2); border: 1px solid var(--st-line-soft); + border-radius: 6px; padding: 1px 5px; } +.st-bubble .st-code { margin: var(--st-s-3) 0; } +.st-bubble blockquote { margin: 0 0 var(--st-s-3); padding-left: var(--st-s-3); border-left: 3px solid var(--st-line); + color: var(--st-ink-muted); } +.st-bubble hr { border: 0; border-top: 1px solid var(--st-line); margin: var(--st-s-4) 0; } +.st-bubble table { border-collapse: collapse; margin: 0 0 var(--st-s-3); font-size: var(--st-fs-md); } +.st-bubble th, .st-bubble td { border: 1px solid var(--st-line); padding: 6px 10px; text-align: left; } +.msg-images { display: flex; flex-wrap: wrap; gap: var(--st-s-2); justify-content: flex-end; } +.msg-images img { max-width: 220px; max-height: 180px; border-radius: var(--st-r-md); border: 1px solid var(--st-line); } +.st-msg .st-collapse { width: 100%; } +.st-collapse__body.thinking { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 420px; overflow-y: auto; } +.st-msg__meta .st-btn--icon { width: 28px; height: 28px; } +.st-msg__meta .st-btn--icon .st-icon { width: 16px; height: 16px; } +.cursor::after { content: ""; display: inline-block; width: 8px; height: 1.1em; margin-left: 2px; vertical-align: -3px; + border-radius: 2px; background: var(--st-accent); animation: blink 1s steps(2) infinite; } +@keyframes blink { 50% { opacity: 0; } } +.msg-error { color: var(--st-danger-text); background: var(--st-danger-tint); border-radius: var(--st-r-md); padding: 10px 14px; + font-size: var(--st-fs-md); } + +.composer-wrap { flex: none; padding: 0 var(--st-s-6) var(--st-s-6); } +.st-composer { max-width: 860px; margin: 0 auto; } +.st-composer textarea { max-height: 40vh; } +.st-btn--send { width: 42px; padding: 0; } +.composer-hint { font-size: var(--st-fs-xs); color: var(--st-ink-muted); margin-right: var(--st-s-2); font-variant-numeric: tabular-nums; } +.attachments { display: flex; flex-wrap: wrap; gap: var(--st-s-2); padding: 2px 4px 0; } +.chip { display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 6px 0 10px; border-radius: var(--st-r-pill); + background: var(--st-surface-2); border: 1px solid var(--st-line); font-size: var(--st-fs-xs); color: var(--st-ink-soft); } +.chip .st-btn--icon { width: 22px; height: 22px; border-radius: 50%; } +.chip .st-btn--icon .st-icon { width: 14px; height: 14px; } + +/* ---------------------------------------------------------------- monitor */ +.view--monitor, .view--about { overflow-y: auto; } +.monitor, .about { max-width: 1240px; width: 100%; margin: 0 auto; padding: var(--st-s-6); display: flex; flex-direction: column; + gap: var(--st-s-5); } +.state-card { display: flex; flex-direction: column; gap: var(--st-s-3); } +.state-card__head { display: flex; align-items: center; gap: var(--st-s-4); flex-wrap: wrap; } +.badges { display: flex; gap: var(--st-s-2); flex-wrap: wrap; } +.badges .st-badge { opacity: .38; transition: opacity var(--st-dur); } +.badges .st-badge.on { opacity: 1; } +.state-card__row { display: flex; justify-content: space-between; gap: var(--st-s-4); font-size: var(--st-fs-sm); + font-weight: var(--st-fw-medium); font-variant-numeric: tabular-nums; } +.metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: var(--st-s-4); } +.metric-card { padding: var(--st-s-4) var(--st-s-5); } +.st-metric__value small { font-size: var(--st-fs-md); font-weight: var(--st-fw-medium); color: var(--st-ink-muted); margin-left: 4px; } +.st-metric__sub { font-size: var(--st-fs-xs); color: var(--st-ink-muted); font-variant-numeric: tabular-nums; min-height: 1em; } +.st-metric__spark { display: block; overflow: visible; } +.st-metric__spark[data-tone="warn"] { color: var(--st-warn); } +.st-metric__spark[data-tone="info"] { color: var(--st-info); } +.monitor-row { display: grid; grid-template-columns: minmax(260px, 1fr) minmax(0, 2.4fr); gap: var(--st-s-4); } +.ctx-card { display: flex; flex-direction: column; gap: var(--st-s-2); } +.ctx-gauge { position: relative; width: 150px; height: 150px; margin: var(--st-s-2) auto var(--st-s-3); } +.ctx-gauge .st-gauge { width: 150px; height: 150px; } +.ctx-gauge .st-gauge__fill { transition: stroke-dasharray 400ms var(--st-ease); } +.ctx-gauge__label { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; + font-size: var(--st-fs-xs); } +.ctx-gauge__pct { font-weight: var(--st-fw-black); font-size: var(--st-fs-xl); line-height: 1.1; font-variant-numeric: tabular-nums; } +.bar-row { display: flex; justify-content: space-between; font-size: var(--st-fs-sm); font-weight: var(--st-fw-medium); + margin-top: var(--st-s-2); font-variant-numeric: tabular-nums; } +.req-card { display: flex; flex-direction: column; gap: var(--st-s-3); min-width: 0; } +.table-wrap { overflow-x: auto; } + +/* ---------------------------------------------------------------- about */ +.about { max-width: 860px; } +.about .st-card { display: flex; flex-direction: column; gap: var(--st-s-3); } +.about p { margin: 0; } +.facts { display: grid; grid-template-columns: minmax(140px, max-content) 1fr; gap: 10px var(--st-s-6); margin: 0; font-size: var(--st-fs-md); } +.facts dt { color: var(--st-ink-muted); } +.facts dd { margin: 0; color: var(--st-ink-soft); font-variant-numeric: tabular-nums; display: flex; align-items: center; gap: 6px; + overflow-wrap: anywhere; } +.facts dd code { font: 400 13px var(--st-font-mono); } +.facts .st-btn--icon { width: 28px; height: 28px; } +.facts .st-btn--icon .st-icon { width: 16px; height: 16px; } +.toggle-row { display: flex; align-items: center; justify-content: space-between; gap: var(--st-s-4); font-size: var(--st-fs-sm); + font-weight: var(--st-fw-medium); color: var(--st-ink-soft); } + +/* ---------------------------------------------------------------- drawer */ +.st-drawer { z-index: 40; } +.scrim { position: fixed; inset: 0; background: rgba(15, 23, 42, .18); z-index: 39; } +.seg { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; padding: 4px; background: var(--st-surface-2); + border: 1px solid var(--st-line); border-radius: var(--st-r-md); } +.seg button { height: 32px; border: 0; border-radius: 10px; background: transparent; color: var(--st-ink-muted); + font: 500 var(--st-fs-sm)/1 var(--st-font); cursor: pointer; } +.seg button[aria-checked="true"] { background: var(--st-surface); color: var(--st-ink); font-weight: var(--st-fw-bold); + box-shadow: var(--st-sh-card); } +.drawer-actions { display: grid; grid-template-columns: 1fr 1fr; gap: var(--st-s-3); margin-top: var(--st-s-2); } +.st-toast { animation: toast-in 180ms var(--st-ease); } +@keyframes toast-in { from { opacity: 0; transform: translateY(6px); } } + +/* ---------------------------------------------------------------- narrow screens */ +@media (max-width: 1000px) { + .metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .monitor-row { grid-template-columns: 1fr; } +} +@media (max-width: 640px) { + .st-header { padding: 0 var(--st-s-3); gap: var(--st-s-2); } + .st-header .st-tabs { margin-left: 0; } + .st-tab { padding: 0 10px; } + .st-tab .st-icon { display: none; } + #pill-text { display: none; } + .chat { padding: var(--st-s-5) var(--st-s-4); } + .composer-wrap { padding: 0 var(--st-s-3) var(--st-s-3); } + .monitor, .about { padding: var(--st-s-4); } + .facts { grid-template-columns: 1fr; gap: 2px; } + .facts dd { margin-bottom: var(--st-s-2); } +} diff --git a/serve/web/app.js b/serve/web/app.js new file mode 100644 index 00000000..f225188e --- /dev/null +++ b/serve/web/app.js @@ -0,0 +1,681 @@ +// serve/web/app.js - the Strata web app: Chat, Monitor, About. No framework, no network beyond this server. +// The Monitor tab rebuilds PR #22's dashboard idea (code-martin) on the server's own /metrics. +"use strict"; + +const $ = (id) => document.getElementById(id); +const SPRITE = "/web/sprite.svg"; +const icon = (name, cls = "st-icon") => ``; +const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); +const fmt = (n, d = 0) => (n == null || Number.isNaN(n) ? "–" : Number(n).toLocaleString(undefined, {maximumFractionDigits: d, minimumFractionDigits: d})); +const kfmt = (n) => (n == null ? "–" : n >= 1000 ? `${fmt(n / 1000, n >= 10000 ? 0 : 1)}k` : fmt(n)); +// a context size: 32768 -> "32K" (powers of two), else like kfmt +const ctxfmt = (n) => (n && n % 1024 === 0 ? `${fmt(n / 1024)}K` : kfmt(n)); +const gb = (b, d = 1) => (b == null ? "–" : fmt(b / 1073741824, d)); // memory: binary GB, as Windows shows it + +const store = { + get(k, d) { try { const v = localStorage.getItem("strata." + k); return v === null ? d : JSON.parse(v); } catch (e) { return d; } }, + set(k, v) { try { localStorage.setItem("strata." + k, JSON.stringify(v)); } catch (e) { /* private mode: in memory only */ } }, +}; + +// ------------------------------------------------------------------ toasts +function toast(kind, title, text = "", ms = 3500, action = null) { + const names = {info: "info", success: "check", warn: "warning", error: "error"}; + const el = document.createElement("div"); + el.className = `st-toast st-toast--${kind}`; + el.innerHTML = `${icon(names[kind] || "info")}
`; + el.querySelector(".st-toast__title").textContent = title; + el.querySelector(".t-text").textContent = text; + if (action) { + const b = document.createElement("button"); + b.className = "st-btn st-btn--secondary"; + b.style.height = "32px"; + b.style.marginLeft = "auto"; + b.textContent = action.label; + b.onclick = () => { action.run(); el.remove(); }; + el.appendChild(b); + } + $("toasts").appendChild(el); + setTimeout(() => el.remove(), ms); +} + +async function copyText(text, btn) { + try { + await navigator.clipboard.writeText(text); + } catch (e) { // http on another host: no async clipboard + const ta = document.createElement("textarea"); + ta.value = text; document.body.appendChild(ta); ta.select(); document.execCommand("copy"); ta.remove(); + } + if (btn) { + const use = btn.querySelector("use"); + use.setAttribute("href", `${SPRITE}#i-check`); + setTimeout(() => use.setAttribute("href", `${SPRITE}#i-copy`), 1500); + } + toast("success", "Copied to clipboard", "", 1800); +} + +// ------------------------------------------------------------------ theme and tabs +function setTheme(t) { + document.documentElement.dataset.theme = t; + try { localStorage.setItem("strata.theme", t); } catch (e) { /* ignore */ } + $("theme-icon").setAttribute("href", `${SPRITE}#i-${t === "dark" ? "sun" : "moon"}`); + $("dark-toggle").setAttribute("aria-checked", String(t === "dark")); +} +$("theme-btn").onclick = () => setTheme(document.documentElement.dataset.theme === "dark" ? "light" : "dark"); +$("dark-toggle").onclick = () => setTheme(document.documentElement.dataset.theme === "dark" ? "light" : "dark"); +setTheme(document.documentElement.dataset.theme || "light"); + +let tab = "chat"; +function showTab(name) { + tab = ["chat", "monitor", "about"].includes(name) ? name : "chat"; + for (const b of document.querySelectorAll(".st-tab")) b.setAttribute("aria-selected", String(b.dataset.tab === tab)); + for (const v of ["chat", "monitor", "about"]) $(`view-${v}`).hidden = v !== tab; + if (location.hash.slice(1) !== tab) history.replaceState(null, "", tab === "chat" ? location.pathname : `#${tab}`); + if (tab === "chat") $("input").focus(); + if (lastMetrics) render(lastMetrics); +} +for (const b of document.querySelectorAll(".st-tab")) b.onclick = () => showTab(b.dataset.tab); +window.addEventListener("hashchange", () => showTab(location.hash.slice(1))); + +// ------------------------------------------------------------------ server access +function headers(json = false) { + const h = {}; + const key = store.get("apikey", ""); + if (key) h.Authorization = "Bearer " + key; + if (json) h["Content-Type"] = "application/json"; + return h; +} +$("api-key").value = store.get("apikey", ""); +$("api-key").onchange = () => { store.set("apikey", $("api-key").value.trim()); toast("success", "API key saved", "Kept in this browser only."); }; + +let health = {model: "strata", images: false, max_context: 0}; +async function loadHealth() { + try { + health = await (await fetch("/health")).json(); + $("attach-btn").hidden = !health.images; + $("chat-empty-sub").textContent = `${health.model} runs on this PC. Nothing leaves it.`; + } catch (e) { + setTimeout(loadHealth, 2000); + } +} + +// ------------------------------------------------------------------ Monitor +const METRICS = [ + {key: "speed", label: "Speed", icon: "gauge", unit: "tok/s", series: "tok_s"}, + {key: "gpu", label: "GPU load", icon: "gpu", unit: "%", series: "gpu_util", max: 100}, + {key: "vram", label: "VRAM", icon: "layers", unit: "GB", series: "gpu_mem_used"}, + {key: "temp", label: "GPU temp", icon: "thermometer", unit: "°C", series: "gpu_temp", tone: "warn"}, + {key: "power", label: "Power", icon: "bolt", unit: "W", series: "gpu_power"}, + {key: "pcie", label: "PCIe", icon: "link", unit: "", series: "gpu_pcie_rx_mb", tone: "info"}, + {key: "cpu", label: "CPU", icon: "cpu", unit: "%", series: "cpu", max: 100}, + {key: "disk", label: "Disk read", icon: "disk", unit: "MB/s", series: "disk_read_mb", tone: "info"}, +]; +$("metrics").innerHTML = METRICS.map((m) => ` +
+ ${icon(m.icon, "st-icon st-icon--sm")}${esc(m.label)} + – + + + +
`).join(""); + +function spark(id, values, max) { + const svg = $(id); + const v = (values || []).map((x) => (x == null ? 0 : x)); + if (v.length < 2) { svg.querySelector(".line").setAttribute("d", ""); svg.querySelector(".area").setAttribute("d", ""); return; } + const top = Math.max(max || 0, ...v, 1e-9); + const pts = v.map((x, i) => [(i / (v.length - 1)) * 100, 30 - (x / top) * 26]); + const line = pts.map((p, i) => `${i ? "L" : "M"}${p[0].toFixed(2)},${p[1].toFixed(2)}`).join(""); + svg.querySelector(".line").setAttribute("d", line); + svg.querySelector(".area").setAttribute("d", `${line}L100,32L0,32Z`); +} +function setMetric(key, value, unit, sub) { + $(`mv-${key}`).innerHTML = value == null ? "–" : `${esc(value)}${unit ? `${esc(unit)}` : ""}`; + $(`ms-${key}`).textContent = sub || ""; +} + +let lastMetrics = null, metricsFailures = 0, keyWarned = false; +async function poll() { + try { + const r = await fetch("/metrics", {headers: headers()}); + if (r.status === 401) { + setPill("error", "API key needed"); + if (!keyWarned) { keyWarned = true; toast("warn", "API key needed", "This server needs a key: add it under About > Settings.", 6000); } + } else if (r.ok) { + lastMetrics = await r.json(); + metricsFailures = 0; + render(lastMetrics); + } else { + throw new Error(`HTTP ${r.status}`); + } + } catch (e) { + if (++metricsFailures === 3) setPill("error", "Server not reachable"); + } + setTimeout(poll, 1000); +} + +function setPill(state, text) { + $("pill").dataset.state = state === "error" ? "queued" : state; + $("pill-text").textContent = text; +} + +function render(m) { + const live = m.live || {}, hw = m.hardware || {}, st = m.hardware_static || {}, eng = m.engine || {}, h = m.history || {}; + const last = (m.requests || [])[0]; + // the header pill + if (live.state === "reading") { + const pct = live.prompt_total ? Math.round((100 * live.prompt_read) / live.prompt_total) : null; + setPill("reading", pct != null ? `Reading prompt · ${pct}%` : "Reading prompt"); + } else if (live.state === "generating") { + setPill("generating", `Generating · ${fmt(live.tok_s, 1)} tok/s`); + } else { + setPill("idle", "Idle"); + } + if (live.queued > 0) setPill("queued", `${live.queued} queued`); + if (tab === "monitor") renderMonitor(live, hw, st, eng, h, last, m.requests || []); + if (tab === "about") renderAbout(eng, hw, st); +} + +function renderMonitor(live, hw, st, eng, h, last, requests) { + // model state + const on = live.queued > 0 ? "queued" : live.state; + for (const b of document.querySelectorAll("#state-badges .st-badge")) b.classList.toggle("on", b.dataset.s === on || b.dataset.s === live.state); + const prog = $("state-progress"); + let label = "Waiting for a request", detail = "", pct = 0; + if (live.state === "reading") { + label = "Reading prompt"; + prog.dataset.tone = "info"; + if (live.prompt_total) { + pct = (100 * live.prompt_read) / live.prompt_total; + detail = `${fmt(live.prompt_read)} / ${fmt(live.prompt_total)} tokens · ${fmt(pct)}%`; + } else { + detail = `${fmt(live.prompt_tokens)} tokens`; + } + } else if (live.state === "generating") { + label = live.phase ? live.phase[0].toUpperCase() + live.phase.slice(1) : "Generating"; + delete prog.dataset.tone; + pct = live.max_tokens ? Math.min(100, (100 * live.generated) / live.max_tokens) : 0; + detail = `${fmt(live.generated)} tokens · ${fmt(live.tok_s, 1)} tok/s`; + } else if (last) { + delete prog.dataset.tone; + detail = `last: ${fmt(last.output_tokens)} tokens${last.decode_tok_s ? ` at ${fmt(last.decode_tok_s, 1)} tok/s` : ""}`; + } + $("state-label").textContent = label; + $("state-detail").textContent = detail; + $("state-bar").style.width = `${pct}%`; + + // the eight cards + const speed = live.state === "generating" ? live.tok_s : last ? last.decode_tok_s : null; + setMetric("speed", speed == null ? null : fmt(speed, 1), "tok/s", live.state === "generating" ? "now" : last ? "last request" : ""); + spark("sp-speed", h.tok_s); + setMetric("gpu", hw.gpu_util == null ? null : fmt(hw.gpu_util), "%", st.gpu_name || ""); + spark("sp-gpu", h.gpu_util, 100); + 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", + eng.expert_slots ? `${fmt(eng.expert_slots)} experts cached` : ""); + spark("sp-vram", h.gpu_mem_used, hw.gpu_mem_total); + setMetric("temp", hw.gpu_temp == null ? null : fmt(hw.gpu_temp), "°C", ""); + spark("sp-temp", h.gpu_temp, 90); + setMetric("power", hw.gpu_power == null ? null : fmt(hw.gpu_power), "W", hw.gpu_power_limit ? `of ${fmt(hw.gpu_power_limit)} W limit` : ""); + spark("sp-power", h.gpu_power, hw.gpu_power_limit); + const gen = hw.gpu_pcie_gen_max || hw.gpu_pcie_gen; + setMetric("pcie", gen ? `Gen${gen}` : null, hw.gpu_pcie_width ? `x${hw.gpu_pcie_width}` : "", + hw.gpu_pcie_rx_mb == null ? "" : `to GPU ${fmt(hw.gpu_pcie_rx_mb, hw.gpu_pcie_rx_mb < 10 ? 1 : 0)} MB/s` + + (hw.gpu_pcie_gen && gen && hw.gpu_pcie_gen < gen ? ` · idle Gen${hw.gpu_pcie_gen}` : "")); + spark("sp-pcie", h.gpu_pcie_rx_mb); + setMetric("cpu", hw.cpu == null ? null : fmt(hw.cpu), "%", st.threads ? `${st.cores ? `${st.cores} cores · ` : ""}${st.threads} threads` : ""); + spark("sp-cpu", h.cpu, 100); + if (hw.disk_read_mb == null) { + setMetric("disk", null, "", st.psutil ? "" : "needs psutil (setup installs it)"); + } else { + const big = hw.disk_read_mb >= 1000; + 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", + hw.disk_write_mb == null ? "" : `write ${fmt(hw.disk_write_mb, 1)} MB/s`); + } + spark("sp-disk", h.disk_read_mb); + + // context fill: the running request, else the last one + const ctx = eng.max_context || 0; + let used = 0; + if (live.state !== "idle") used = (live.prompt_tokens || 0) + (live.generated || 0); + else if (last) used = (last.prompt_tokens || 0) + (last.output_tokens || 0); + const frac = ctx ? Math.min(1, used / ctx) : 0; + $("ctx-fill").setAttribute("stroke-dasharray", `${(235.6 * frac).toFixed(1)} 314.2`); + $("ctx-fill").style.opacity = 235.6 * frac >= 3 ? "1" : "0"; // a near-zero arc would draw just its round cap + $("ctx-pct").textContent = `${Math.round(frac * 100)}%`; + $("ctx-sub").textContent = ctx ? `${kfmt(used)} / ${ctxfmt(ctx)}` : "–"; + const cacheBytes = (eng.expert_cache_mib || 0) * 1048576; + $("slots-text").textContent = eng.expert_slots ? `${fmt(eng.expert_slots)} · ${gb(cacheBytes)} GB` : "–"; + $("slots-bar").style.width = hw.gpu_mem_total ? `${Math.min(100, (100 * cacheBytes) / hw.gpu_mem_total)}%` : "0%"; + $("ram-text").textContent = hw.ram_total ? `${gb(hw.ram_used)} / ${gb(hw.ram_total, 0)} GB` : "–"; + const ramPct = hw.ram_total ? (100 * hw.ram_used) / hw.ram_total : 0; + $("ram-bar").style.width = `${ramPct}%`; + if (ramPct > 92) $("ram-progress").dataset.tone = "danger"; else delete $("ram-progress").dataset.tone; + $("temp-text").textContent = hw.gpu_temp == null ? "–" : `${fmt(hw.gpu_temp)} °C`; + $("temp-bar").style.width = hw.gpu_temp == null ? "0%" : `${Math.min(100, hw.gpu_temp)}%`; + + // recent requests + const body = $("req-body"); + if (!requests.length) { + body.innerHTML = `No requests yet`; + } else { + const badge = {stop: ["", "Done"], length: ["", "Max tokens"], cancel: ["st-badge--queued", "Stopped"], + disconnect: ["st-badge--queued", "Closed"], error: ["st-badge--error", "Error"]}; + body.innerHTML = requests.slice(0, 12).map((r) => { + const [cls, text] = badge[r.finish] || ["", r.finish || "–"]; + const t = new Date(r.time * 1000).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit", second: "2-digit"}); + return `${esc(t)}${esc(text)}${fmt(r.prompt_tokens)} + ${fmt(r.reused)}${fmt(r.output_tokens)}${fmt(r.decode_tok_s, 1)} + ${fmt(r.duration_s, 1)} s`; + }).join(""); + } +} + +function facts(el, rows) { + el.innerHTML = rows.filter((r) => r[1] != null && r[1] !== "").map(([k, v, copy]) => + `
${esc(k)}
${copy ? `${esc(v)}` : esc(v)}
`).join(""); +} +function renderAbout(eng, hw, st) { + const kv = {int8: "8-bit", q4_0: "4-bit (Hadamard-rotated)", fp16: "16-bit"}[eng.kv] || eng.kv; + facts($("facts-engine"), [ + ["Model", eng.model], + ["Engine", eng.version ? `v${eng.version}` : "built from source"], + ["Context", eng.max_context ? `${fmt(eng.max_context)} tokens` : null], + ["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], + ["Experts in VRAM", eng.expert_slots ? `${fmt(eng.expert_slots)} (${gb((eng.expert_cache_mib || 0) * 1048576)} GB)` : null], + ["Speculation", eng.spec ? `MTP drafts up to ${Math.max(0, (eng.mtp_max || eng.spec) - 1)} tokens${eng.lookup ? ", prompt lookup on" : ""}` : null], + ["Images", eng.images ? "on" : "off"], + ]); + facts($("facts-hw"), [ + ["GPU", st.gpu_name ? `${st.gpu_name}${hw.gpu_mem_total ? `, ${gb(hw.gpu_mem_total, 0)} GB` : ""}` : "not readable (NVML)"], + ["CPU", st.cpu_name ? `${st.cpu_name}${st.threads ? `, ${st.threads} threads` : ""}` : null], + ["RAM", hw.ram_total ? `${gb(hw.ram_total, 0)} GB` : null], + ]); + const base = location.origin; + facts($("facts-api"), [ + ["OpenAI base URL", `${base}/v1`, true], + ["Anthropic base URL", base, true], + ["Model name", eng.model, true], + ]); +} +document.addEventListener("click", (e) => { + const b = e.target.closest("[data-copy]"); + if (b) copyText(b.dataset.copy, b); +}); + +// ------------------------------------------------------------------ Markdown (escaped first, then formatted) +function inline(s) { + const codes = []; + s = s.replace(/`([^`\n]+)`/g, (_, c) => { codes.push(c); return `\u0000${codes.length - 1}\u0000`; }); + s = esc(s) + .replace(/\*\*([^*\n]+)\*\*/g, "$1") + .replace(/(^|[^*\w])\*([^*\n]+)\*(?![*\w])/g, "$1$2") + .replace(/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g, '$1'); + return s.replace(/\u0000(\d+)\u0000/g, (_, i) => `${esc(codes[+i])}`); +} +function codeBlock(lang, code) { + return `
${esc(lang || "code")}` + + `
` + + `
${esc(code)}
`; +} +function blocks(text) { + const out = [], lines = text.split("\n"); + let para = [], list = null; + const flushPara = () => { if (para.length) out.push(`

${para.map(inline).join("
")}

`); para = []; }; + const flushList = () => { if (list) out.push(`<${list.tag}>${list.items.map((i) => `
  • ${inline(i)}
  • `).join("")}`); list = null; }; + for (let i = 0; i < lines.length; i++) { + const l = lines[i]; + let m; + if (!l.trim()) { flushPara(); flushList(); continue; } + if ((m = l.match(/^(#{1,6})\s+(.*)$/))) { flushPara(); flushList(); out.push(`<${m[1].length <= 2 ? "h3" : "h4"}>${inline(m[2])}`); continue; } + if (/^\s*([-*_])\s*\1\s*\1[\s\1]*$/.test(l)) { flushPara(); flushList(); out.push("
    "); continue; } + if ((m = l.match(/^>\s?(.*)$/))) { flushPara(); flushList(); out.push(`
    ${inline(m[1])}
    `); continue; } + if (/^\s*\|.*\|\s*$/.test(l) && i + 1 < lines.length && /^\s*\|?[\s:-]+\|[\s|:-]*$/.test(lines[i + 1])) { + flushPara(); flushList(); + const cells = (row) => row.trim().replace(/^\||\|$/g, "").split("|").map((c) => inline(c.trim())); + let html = `${cells(l).map((c) => ``).join("")}`; + i += 2; + while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) html += `${cells(lines[i++]).map((c) => ``).join("")}`; + i--; + out.push(html + "
    ${c}
    ${c}
    "); + continue; + } + if ((m = l.match(/^\s*(?:[-*+]|(\d+)[.)])\s+(.*)$/))) { + flushPara(); + const tag = m[1] ? "ol" : "ul"; + if (!list || list.tag !== tag) { flushList(); list = {tag, items: []}; } + list.items.push(m[2]); + continue; + } + if (list && /^\s{2,}\S/.test(l)) { list.items[list.items.length - 1] += " " + l.trim(); continue; } + flushList(); + para.push(l); + } + flushPara(); flushList(); + return out.join(""); +} +function markdown(text) { + let html = "", rest = text; + for (;;) { + const m = rest.match(/(^|\n)```([^\n`]*)\n/); + if (!m) { html += blocks(rest); break; } + html += blocks(rest.slice(0, m.index)); + rest = rest.slice(m.index + m[0].length); + const end = rest.match(/(^|\n)```[ \t]*(\n|$)/); + if (!end) { html += codeBlock(m[2].trim(), rest); break; } // still streaming + html += codeBlock(m[2].trim(), rest.slice(0, end.index)); + rest = rest.slice(end.index + end[0].length); + } + return html; +} + +// ------------------------------------------------------------------ Chat +const DEFAULTS = {thinking: "high", temperature: 0.6, top_p: 0.95, top_k: 20, max: "", seed: "", show: true}; +let settings = {...DEFAULTS, ...store.get("sampling", {})}; +let messages = store.get("chat", []); +let attachments = []; // {name, url} +let busy = null; // {controller, msg} + +function saveChat() { + store.set("chat", messages.map((m) => ({...m, images: (m.images || []).map((i) => ({name: i.name}))}))); +} +function timeStr(t) { return new Date(t).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit"}); } + +function msgEl(m, i) { + const el = document.createElement("div"); + el.className = `st-msg st-msg--${m.role}`; + el.dataset.i = i; + if (m.role === "user") { + if (m.images && m.images.length) { + const wrap = document.createElement("div"); + wrap.className = "msg-images"; + for (const im of m.images) { + if (im.url) { const img = document.createElement("img"); img.src = im.url; img.alt = im.name || "image"; wrap.appendChild(img); } + else { const c = document.createElement("span"); c.className = "chip"; c.innerHTML = icon("image", "st-icon st-icon--sm"); c.append(im.name || "image"); wrap.appendChild(c); } + } + el.appendChild(wrap); + } + const b = document.createElement("div"); + b.className = "st-bubble"; + b.textContent = m.text; + el.appendChild(b); + const meta = document.createElement("div"); + meta.className = "st-msg__meta"; + meta.textContent = `You · ${timeStr(m.time)}`; + el.appendChild(meta); + } else { + el.innerHTML = `` + + `
    ` + + `
    `; + updateAssistant(el, m, false); + } + return el; +} +function updateAssistant(el, m, streaming) { + const det = el.querySelector("details"); + if (m.reasoning) { + det.hidden = false; + const thinkingNow = streaming && !m.text; + el.querySelector(".think-title").textContent = thinkingNow ? "Thinking…" : + m.thinkSecs != null ? `Thought for ${fmt(m.thinkSecs, 1)} s` : "Thoughts"; + const body = el.querySelector(".thinking"); + if (det.open || thinkingNow) body.textContent = m.reasoning; + else body.dataset.pending = "1"; + // open while it streams (if wanted), closed once the answer starts - unless the user toggled it themselves + if (thinkingNow && settings.show && !det.dataset.touched && !det.open) { det._auto = true; det.open = true; } + if (!thinkingNow && det.open && !det.dataset.touched) { det._auto = true; det.open = false; } + } + const bubble = el.querySelector(".st-bubble"); + if (m.error) { + bubble.innerHTML = `
    `; + bubble.firstChild.textContent = m.error; + } else if (!m.text && streaming) { + bubble.innerHTML = m.reasoning ? `Writing` : ``; + } else { + bubble.innerHTML = markdown(m.text || ""); + if (streaming) bubble.classList.add("cursor"); else bubble.classList.remove("cursor"); + } + el.querySelector(".meta-text").textContent = m.meta || (streaming ? "" : m.stopped ? "Stopped" : ""); + el.querySelector("[data-msg-copy]").hidden = streaming || !m.text; +} +function renderChat() { + const chat = $("chat"); + chat.querySelectorAll(".st-msg").forEach((e) => e.remove()); + $("chat-empty").hidden = messages.length > 0; + messages.forEach((m, i) => chat.appendChild(msgEl(m, i))); + scrollDown(true); +} +function nearBottom() { const s = $("chat-scroll"); return s.scrollHeight - s.scrollTop - s.clientHeight < 120; } +function scrollDown(force) { const s = $("chat-scroll"); if (force || nearBottom()) s.scrollTop = s.scrollHeight; } + +$("chat").addEventListener("click", (e) => { + const cc = e.target.closest("[data-code-copy]"); + if (cc) { copyText(cc.closest(".st-code").querySelector("pre").textContent, cc); return; } + const mc = e.target.closest("[data-msg-copy]"); + if (mc) { const i = +mc.closest(".st-msg").dataset.i; copyText(messages[i].text, mc); } +}); +$("chat").addEventListener("toggle", (e) => { + const d = e.target; + if (d.tagName !== "DETAILS") return; + if (d._auto) { d._auto = false; return; } // our own open/close, not the user's + d.dataset.touched = "1"; + const body = d.querySelector(".thinking"); + if (d.open && body.dataset.pending) { body.textContent = messages[+d.closest(".st-msg").dataset.i].reasoning; delete body.dataset.pending; } +}, true); + +function apiMessages() { + const out = []; + for (const m of messages) { + if (m.role === "user") { + const imgs = (m.images || []).filter((i) => i.url); + out.push({role: "user", content: imgs.length ? [{type: "text", text: m.text}, + ...imgs.map((i) => ({type: "image_url", image_url: {url: i.url}}))] : m.text}); + } else if (m.text && !m.error) { + out.push({role: "assistant", content: m.text}); + } + } + return out; +} + +function setBusy(on) { + $("stop-btn").hidden = !on; + $("send-btn").disabled = on; + $("composer-hint").textContent = on ? "" : "Shift+Enter: new line"; +} + +async function send() { + const text = $("input").value.trim(); + if ((!text && !attachments.length) || busy) return; + messages.push({role: "user", text, images: attachments, time: Date.now()}); + attachments = []; + renderAttachments(); + $("input").value = ""; + autosize(); + const m = {role: "assistant", text: "", reasoning: "", time: Date.now()}; + messages.push(m); + renderChat(); + const el = $("chat").lastElementChild; + const controller = new AbortController(); + busy = {controller, msg: m}; + setBusy(true); + + const body = {model: health.model, messages: apiMessages(), stream: true, + reasoning_effort: settings.thinking}; + if (settings.temperature > 0) { + Object.assign(body, {temperature: +settings.temperature, top_p: +settings.top_p, top_k: +settings.top_k}); + } else { + body.temperature = 0; + } + if (settings.seed) body.seed = +settings.seed; + if (settings.max) body.max_tokens = +settings.max; + + let firstAt = null, thinkStart = null, usage = null, frame = 0; + const paint = () => { frame = 0; updateAssistant(el, m, true); scrollDown(); }; + try { + const r = await fetch("/v1/chat/completions", {method: "POST", headers: headers(true), body: JSON.stringify(body), + signal: controller.signal}); + if (!r.ok) { + let msg = `HTTP ${r.status}`; + try { msg = (await r.json()).error.message || msg; } catch (e) { /* not json */ } + if (r.status === 401) msg = "This server needs an API key: add it under About > Settings."; + throw new Error(msg); + } + const reader = r.body.getReader(), dec = new TextDecoder(); + let buf = ""; + for (;;) { + const {value, done} = await reader.read(); + if (done) break; + buf += dec.decode(value, {stream: true}); + let nl; + while ((nl = buf.indexOf("\n")) >= 0) { + const line = buf.slice(0, nl).trim(); + buf = buf.slice(nl + 1); + if (!line.startsWith("data:")) continue; // ": keep-alive" comments while a long prompt is read + const data = line.slice(5).trim(); + if (data === "[DONE]") continue; + let j; + try { j = JSON.parse(data); } catch (e) { continue; } + if (j.error) throw new Error(j.error.message || "the engine reported an error"); + if (j.usage) usage = j.usage; + const d = (j.choices && j.choices[0] && j.choices[0].delta) || {}; + if (d.reasoning_content) { if (!firstAt) firstAt = performance.now(); if (!thinkStart) thinkStart = performance.now(); m.reasoning += d.reasoning_content; } + if (d.content) { + if (!firstAt) firstAt = performance.now(); + if (thinkStart && m.thinkSecs == null) m.thinkSecs = (performance.now() - thinkStart) / 1000; + m.text += d.content; + } + if (!frame) frame = requestAnimationFrame(paint); + } + } + } catch (e) { + if (e.name === "AbortError") m.stopped = true; + else { m.error = e.message || String(e); toast("error", "The request failed", m.error, 6000); } + } + if (thinkStart && m.thinkSecs == null) m.thinkSecs = (performance.now() - thinkStart) / 1000; + const n = usage ? usage.completion_tokens : null; + if (n && firstAt) { + const secs = (performance.now() - firstAt) / 1000; + m.meta = `${fmt(n)} tokens${secs > 0.25 ? ` · ${fmt(n / secs, 1)} tok/s` : ""}${m.stopped ? " · stopped" : ""}`; + } else if (m.stopped) { + m.meta = "Stopped"; + } + busy = null; + setBusy(false); + if (frame) cancelAnimationFrame(frame); + updateAssistant(el, m, false); + saveChat(); + scrollDown(); +} + +$("composer").onsubmit = (e) => { e.preventDefault(); send(); }; +$("stop-btn").onclick = () => { if (busy) busy.controller.abort(); }; +$("input").addEventListener("keydown", (e) => { + if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); send(); } +}); +function autosize() { const t = $("input"); t.style.height = "auto"; t.style.height = `${Math.min(t.scrollHeight, innerHeight * 0.4)}px`; } +$("input").addEventListener("input", autosize); + +$("new-btn").onclick = () => { + if (busy) { toast("warn", "Still writing", "Stop the answer first."); return; } + if (!messages.length) return; + const backup = messages; + messages = []; + saveChat(); + renderChat(); + toast("info", "New chat", "The last one was cleared.", 6000, {label: "Undo", run: () => { messages = backup; saveChat(); renderChat(); }}); +}; +$("export-btn").onclick = () => { + if (!messages.length) { toast("info", "Nothing to save yet"); return; } + const md = messages.map((m) => m.role === "user" ? `## You\n\n${m.text}\n` : + `## ${health.model}\n\n${m.reasoning ? `
    Thinking\n\n${m.reasoning}\n\n
    \n\n` : ""}${m.text || m.error || ""}\n`).join("\n"); + const a = document.createElement("a"); + a.href = URL.createObjectURL(new Blob([md], {type: "text/markdown"})); + a.download = `strata-chat-${new Date().toISOString().slice(0, 16).replace(/[:T]/g, "-")}.md`; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 5000); +}; + +// pictures: the attach button, or paste into the message box +function addFiles(files) { + for (const f of files) { + if (!f.type.startsWith("image/")) continue; + if (f.size > 20e6) { toast("warn", "Picture too large", `${f.name} is over 20 MB.`); continue; } + const r = new FileReader(); + r.onload = () => { attachments.push({name: f.name || "pasted image", url: r.result}); renderAttachments(); }; + r.readAsDataURL(f); + } +} +function renderAttachments() { + const box = $("attachments"); + box.hidden = !attachments.length; + box.innerHTML = ""; + attachments.forEach((a, i) => { + const c = document.createElement("span"); + c.className = "chip"; + c.innerHTML = icon("image", "st-icon st-icon--sm"); + c.append(a.name); + const x = document.createElement("button"); + x.type = "button"; x.className = "st-btn st-btn--icon"; x.setAttribute("aria-label", "Remove"); + x.innerHTML = icon("trash"); + x.onclick = () => { attachments.splice(i, 1); renderAttachments(); }; + c.appendChild(x); + box.appendChild(c); + }); +} +$("attach-btn").onclick = () => $("file").click(); +$("file").onchange = () => { addFiles($("file").files); $("file").value = ""; }; +$("input").addEventListener("paste", (e) => { + if (!health.images) return; + const files = [...(e.clipboardData || {}).files || []].filter((f) => f.type.startsWith("image/")); + if (files.length) { e.preventDefault(); addFiles(files); } +}); + +// ------------------------------------------------------------------ the sampling drawer +function openDrawer(open) { + $("drawer").dataset.open = String(open); + $("drawer").setAttribute("aria-hidden", String(!open)); + $("scrim").hidden = !open; + if (open) loadDrawer(); +} +function loadDrawer(s = settings) { + for (const b of $("s-thinking").children) b.setAttribute("aria-checked", String(b.dataset.v === s.thinking)); + $("s-temp").value = s.temperature; $("s-topp").value = s.top_p; $("s-topk").value = s.top_k; + $("s-max").value = s.max; $("s-seed").value = s.seed; + $("s-show").setAttribute("aria-checked", String(!!s.show)); + outputs(); +} +function outputs() { + const t = +$("s-temp").value; + $("o-temp").textContent = t === 0 ? "0 · greedy" : t.toFixed(2); + $("o-topp").textContent = (+$("s-topp").value).toFixed(2); + $("o-topk").textContent = $("s-topk").value; + const sel = [...$("s-thinking").children].find((b) => b.getAttribute("aria-checked") === "true"); + $("o-thinking").textContent = sel ? {none: "answers right away", low: "short", medium: "medium", high: "thorough (default)"}[sel.dataset.v] : ""; + for (const id of ["s-topp", "s-topk"]) $(id).disabled = t === 0; +} +for (const b of $("s-thinking").children) b.onclick = () => { for (const x of $("s-thinking").children) x.setAttribute("aria-checked", String(x === b)); outputs(); }; +for (const id of ["s-temp", "s-topp", "s-topk"]) $(id).oninput = outputs; +$("s-show").onclick = () => $("s-show").setAttribute("aria-checked", String($("s-show").getAttribute("aria-checked") !== "true")); +$("s-reset").onclick = () => loadDrawer(DEFAULTS); +$("s-apply").onclick = () => { + const sel = [...$("s-thinking").children].find((b) => b.getAttribute("aria-checked") === "true"); + settings = {thinking: sel ? sel.dataset.v : "high", temperature: +$("s-temp").value, top_p: +$("s-topp").value, + top_k: +$("s-topk").value, max: $("s-max").value.trim(), seed: $("s-seed").value.trim(), + show: $("s-show").getAttribute("aria-checked") === "true"}; + store.set("sampling", settings); + openDrawer(false); + toast("success", "Sampling saved", settings.temperature === 0 ? "Greedy: the same question gives the same answer." : ""); +}; +$("sampling-btn").onclick = () => openDrawer(true); +$("drawer-close").onclick = () => openDrawer(false); +$("scrim").onclick = () => openDrawer(false); +document.addEventListener("keydown", (e) => { if (e.key === "Escape" && $("drawer").dataset.open === "true") openDrawer(false); }); + +// ------------------------------------------------------------------ start +setBusy(false); +renderChat(); +const startQuestion = new URLSearchParams(location.search).get("q"); // /?q=... starts a chat (a shortcut) +if (startQuestion) history.replaceState(null, "", location.pathname + location.hash); +loadHealth().then(() => { if (startQuestion) { $("input").value = startQuestion; send(); } }); +showTab(location.hash.slice(1) || "chat"); +poll(); diff --git a/serve/web/components.css b/serve/web/components.css new file mode 100644 index 00000000..899f5257 --- /dev/null +++ b/serve/web/components.css @@ -0,0 +1,128 @@ +/* Strata UI — components. Requires tokens.css. */ +*,*::before,*::after{box-sizing:border-box} +html,body{margin:0;background:var(--st-bg);color:var(--st-ink);font-family:var(--st-font);font-size:var(--st-fs-base);line-height:var(--st-lh-body);-webkit-font-smoothing:antialiased} +a{color:var(--st-accent-text);text-decoration:none} a:hover{text-decoration:underline} +:focus-visible{outline:2px solid var(--st-focus);outline-offset:2px} + +/* icon — */ +.st-icon{width:20px;height:20px;flex:none;color:inherit} +.st-icon--sm{width:16px;height:16px} .st-icon--lg{width:24px;height:24px} + +/* header */ +.st-header{display:flex;align-items:center;gap:var(--st-s-4);height:60px;padding:0 var(--st-s-6);background:var(--st-surface);border-bottom:1px solid var(--st-line)} +.st-header__brand{font-weight:900;font-size:var(--st-fs-lg);letter-spacing:-.01em} +.st-header__spacer{flex:1} + +/* status pill */ +.st-pill{display:inline-flex;align-items:center;gap:8px;height:30px;padding:0 12px;border-radius:var(--st-r-pill);border:1px solid var(--st-line);background:var(--st-surface-2);font-size:var(--st-fs-sm);font-weight:500;color:var(--st-ink-soft);font-variant-numeric:tabular-nums} +.st-pill__dot{width:8px;height:8px;border-radius:50%;background:var(--st-ink-muted)} +.st-pill[data-state="generating"] .st-pill__dot{background:var(--st-accent);box-shadow:0 0 0 4px var(--st-accent-tint)} +.st-pill[data-state="reading"] .st-pill__dot{background:var(--st-info);box-shadow:0 0 0 4px var(--st-info-tint)} +.st-pill[data-state="queued"] .st-pill__dot{background:var(--st-warn)} + +/* tabs */ +.st-tabs{display:flex;gap:4px;padding:4px;background:var(--st-surface-2);border:1px solid var(--st-line);border-radius:var(--st-r-md)} +.st-tab{display:inline-flex;align-items:center;gap:8px;height:36px;padding:0 14px;border:0;border-radius:10px;background:transparent;color:var(--st-ink-muted);font:500 var(--st-fs-md)/1 var(--st-font);cursor:pointer} +.st-tab:hover{color:var(--st-ink)} +.st-tab[aria-selected="true"]{background:var(--st-surface);color:var(--st-ink);font-weight:700;box-shadow:var(--st-sh-card)} + +/* card + metric */ +.st-card{background:var(--st-surface);border:1px solid var(--st-line);border-radius:var(--st-r-lg);box-shadow:var(--st-sh-card);padding:var(--st-s-5)} +.st-metric{display:flex;flex-direction:column;gap:10px} +.st-metric__label{display:flex;align-items:center;gap:8px;font-size:var(--st-fs-sm);font-weight:500;color:var(--st-ink-muted)} +.st-metric__value{font-weight:900;font-size:var(--st-fs-stat);line-height:1;letter-spacing:-.01em;font-variant-numeric:tabular-nums} +.st-metric__unit{font-weight:500;font-size:var(--st-fs-md);color:var(--st-ink-muted);margin-left:4px} +.st-metric__spark{width:100%;height:32px;color:var(--st-accent)} + +/* progress + gauge */ +.st-progress{height:8px;border-radius:var(--st-r-pill);background:var(--st-surface-2);border:1px solid var(--st-line-soft);overflow:hidden} +.st-progress__bar{height:100%;border-radius:inherit;background:var(--st-accent);transition:width var(--st-dur) var(--st-ease)} +.st-progress[data-tone="info"] .st-progress__bar{background:var(--st-info)} +.st-progress[data-tone="warn"] .st-progress__bar{background:var(--st-warn)} +.st-progress[data-tone="danger"] .st-progress__bar{background:var(--st-danger)} +/* gauge: see README for SVG markup (stroke-dasharray on a 270° arc) */ +.st-gauge{position:relative;width:120px;height:120px} +.st-gauge__track{stroke:var(--st-surface-2)} .st-gauge__fill{stroke:var(--st-accent)} + +/* table */ +.st-table{width:100%;border-collapse:collapse;font-size:var(--st-fs-md);font-variant-numeric:tabular-nums} +.st-table th{text-align:left;font-weight:500;font-size:var(--st-fs-xs);letter-spacing:.04em;text-transform:uppercase;color:var(--st-ink-muted);padding:10px 12px;border-bottom:1px solid var(--st-line)} +.st-table td{padding:12px;border-bottom:1px solid var(--st-line-soft);color:var(--st-ink-soft)} +.st-table tr:hover td{background:var(--st-surface-2)} +.st-table .num{text-align:right} + +/* badges */ +.st-badge{display:inline-flex;align-items:center;gap:6px;height:24px;padding:0 10px;border-radius:var(--st-r-pill);font-size:var(--st-fs-xs);font-weight:700;background:var(--st-surface-2);color:var(--st-ink-muted);border:1px solid var(--st-line)} +.st-badge::before{content:"";width:6px;height:6px;border-radius:50%;background:currentColor} +.st-badge--reading{background:var(--st-info-tint);color:var(--st-info-text);border-color:transparent} +.st-badge--generating{background:var(--st-accent-tint);color:var(--st-accent-text);border-color:transparent} +.st-badge--queued{background:var(--st-warn-tint);color:var(--st-warn-text);border-color:transparent} +.st-badge--error{background:var(--st-danger-tint);color:var(--st-danger-text);border-color:transparent} + +/* chat */ +.st-msg{display:flex;flex-direction:column;gap:6px;max-width:720px} +.st-msg--user{align-self:flex-end;align-items:flex-end} +.st-bubble{padding:12px 16px;border-radius:var(--st-r-lg);font-size:var(--st-fs-base);line-height:1.55;color:var(--st-ink-soft)} +.st-msg--user .st-bubble{background:var(--st-accent);color:var(--st-accent-ink);border-bottom-right-radius:6px} +.st-msg--assistant .st-bubble{background:var(--st-surface);border:1px solid var(--st-line);border-bottom-left-radius:6px} +.st-msg__meta{font-size:var(--st-fs-xs);color:var(--st-ink-muted);display:flex;gap:8px;align-items:center} + +/* collapsible —
    …
    …
    */ +.st-collapse{border:1px solid var(--st-line);border-radius:var(--st-r-md);background:var(--st-surface-2)} +.st-collapse>summary{list-style:none;display:flex;align-items:center;gap:8px;padding:10px 14px;cursor:pointer;font-size:var(--st-fs-sm);font-weight:500;color:var(--st-ink-muted)} +.st-collapse>summary::-webkit-details-marker{display:none} +.st-collapse>summary .st-chev{margin-left:auto;transition:transform var(--st-dur) var(--st-ease)} +.st-collapse[open]>summary .st-chev{transform:rotate(180deg)} +.st-collapse__body{padding:0 14px 14px;font-size:var(--st-fs-sm);color:var(--st-ink-muted);line-height:1.6} + +/* code */ +.st-code{border-radius:var(--st-r-md);background:var(--st-code-bg);color:var(--st-code-ink);overflow:hidden} +.st-code__head{display:flex;align-items:center;justify-content:space-between;padding:8px 8px 8px 14px;font:500 var(--st-fs-xs)/1 var(--st-font);color:#9aa3ab;border-bottom:1px solid rgba(255,255,255,.06)} +.st-code pre{margin:0;padding:14px;overflow:auto;font:400 13px/1.6 var(--st-font-mono)} +.st-code .st-btn--icon{color:#9aa3ab} .st-code .st-btn--icon:hover{background:rgba(255,255,255,.08);color:#fff} + +/* composer */ +.st-composer{display:flex;flex-direction:column;gap:8px;padding:10px;background:var(--st-surface);border:1px solid var(--st-line);border-radius:var(--st-r-lg);box-shadow:var(--st-sh-bar)} +.st-composer:focus-within{border-color:var(--st-focus)} +.st-composer textarea{border:0;outline:0;resize:none;background:transparent;color:var(--st-ink);font:400 var(--st-fs-base)/1.5 var(--st-font);padding:6px 8px;min-height:48px} +.st-composer__bar{display:flex;align-items:center;gap:6px} +.st-composer__bar .spacer{flex:1} + +/* drawer */ +.st-drawer{position:fixed;top:0;right:0;bottom:0;width:360px;max-width:100vw;background:var(--st-surface);border-left:1px solid var(--st-line);box-shadow:var(--st-sh-pop);display:flex;flex-direction:column;transform:translateX(100%);transition:transform 220ms var(--st-ease)} +.st-drawer[data-open="true"]{transform:none} +.st-drawer__head{display:flex;align-items:center;justify-content:space-between;padding:18px 20px;border-bottom:1px solid var(--st-line)} +.st-drawer__body{padding:20px;display:flex;flex-direction:column;gap:22px;overflow:auto} + +/* buttons */ +.st-btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;height:42px;padding:0 18px;border-radius:var(--st-r-md);border:0;font:700 var(--st-fs-md)/1 var(--st-font);cursor:pointer;transition:background var(--st-dur),transform 120ms} +.st-btn:active{transform:translateY(1px)} +.st-btn--primary{background:var(--st-accent);color:var(--st-accent-ink);box-shadow:0 6px 16px rgba(16,185,129,.24),inset 0 1px 0 rgba(255,255,255,.18)} +.st-btn--primary:hover{background:var(--st-accent-hover)} +.st-btn--secondary{background:transparent;color:var(--st-ink);border:1.5px solid var(--st-line)} +.st-btn--secondary:hover{background:var(--st-surface-2)} +.st-btn--danger{background:var(--st-danger-tint);color:var(--st-danger-text)} +.st-btn--icon{width:36px;height:36px;padding:0;border-radius:10px;background:transparent;color:var(--st-ink-muted)} +.st-btn--icon:hover{background:var(--st-surface-2);color:var(--st-ink)} +.st-btn:disabled{opacity:.45;cursor:not-allowed} + +/* form controls */ +.st-field{display:flex;flex-direction:column;gap:8px} +.st-label{display:flex;justify-content:space-between;font-size:var(--st-fs-sm);font-weight:500;color:var(--st-ink-soft)} +.st-label output{font-variant-numeric:tabular-nums;color:var(--st-ink-muted)} +.st-input{height:44px;padding:0 14px;border-radius:var(--st-r-md);border:1.5px solid var(--st-line);background:var(--st-surface);color:var(--st-ink);font:400 var(--st-fs-md) var(--st-font)} +.st-input:focus{outline:0;border-color:var(--st-focus);box-shadow:0 0 0 3px color-mix(in srgb,var(--st-focus) 20%,transparent)} +.st-slider{width:100%;accent-color:var(--st-accent)} +.st-toggle{position:relative;width:40px;height:24px;border-radius:var(--st-r-pill);border:0;background:var(--st-line);cursor:pointer;transition:background var(--st-dur)} +.st-toggle::after{content:"";position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.2);transition:transform var(--st-dur) var(--st-ease)} +.st-toggle[aria-checked="true"]{background:var(--st-accent)} +.st-toggle[aria-checked="true"]::after{transform:translateX(16px)} + +/* toast / alert */ +.st-toast{display:flex;align-items:flex-start;gap:12px;padding:14px 16px;border-radius:var(--st-r-md);background:var(--st-surface);border:1px solid var(--st-line);box-shadow:var(--st-sh-pop);font-size:var(--st-fs-md);color:var(--st-ink-soft);max-width:420px} +.st-toast__title{font-weight:700;color:var(--st-ink)} +.st-toast--info .st-icon{color:var(--st-info)} +.st-toast--success .st-icon{color:var(--st-accent)} +.st-toast--warn .st-icon{color:var(--st-warn)} +.st-toast--error .st-icon{color:var(--st-danger)} +.st-toasts{position:fixed;right:20px;bottom:20px;display:flex;flex-direction:column;gap:10px;z-index:50} diff --git a/serve/web/index.html b/serve/web/index.html new file mode 100644 index 00000000..5fc9bec6 --- /dev/null +++ b/serve/web/index.html @@ -0,0 +1,205 @@ + + + + + +Strata + + + + + + +
    + Strata + + + + Connecting… + +
    + +
    + +
    +
    +
    +
    +
    Ask anything
    +
    The model runs on this PC. Nothing leaves it.
    +
    +
    +
    +
    +
    + + +
    + + + + + + + + + +
    +
    +
    +
    + + + + + + +
    + + + + +
    + + + diff --git a/serve/web/sprite.svg b/serve/web/sprite.svg new file mode 100644 index 00000000..598f6234 --- /dev/null +++ b/serve/web/sprite.svg @@ -0,0 +1,34 @@ +AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYToyMjRkYzc2Ny1hNTJmLTRhNTgtYmRhNi0wNjNjZjgxZDE0ZDkAAAADl2p1bWIAAAApanVtZGMyYXMAEQAQgAAAqgA4m3EDYzJwYS5hc3NlcnRpb25zAAAAALxqdW1iAAAARGp1bWRjYm9yABEAEIAAAKoAOJtxE2MycGEuaW5ncmVkaWVudC52MwAAAAAYYzJzaFpCcvmnJ1xuOVFbOGxO7IQAAABwY2JvcqNpZGM6Zm9ybWF0bWltYWdlL3N2Zyt4bWxqaW5zdGFuY2VJRHgseG1wOmlpZDpjZTVmMTYyMy1hMGY4LTRjNDgtYmQ1MC0yOGRhYTVkZGQ3OWZscmVsYXRpb25zaGlwaHBhcmVudE9mAAAB4mp1bWIAAABBanVtZGNib3IAEQAQgAAAqgA4m3ETYzJwYS5hY3Rpb25zLnYyAAAAABhjMnNohRiWe4A1zTyq58r9HwVbdgAAAZljYm9yomdhY3Rpb25zgqJmYWN0aW9ua2MycGEub3BlbmVkanBhcmFtZXRlcnOha2luZ3JlZGllbnRzgaJjd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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPZYQAWvLruRfR0RxgkmvmgF8qVD0dQ7tTCsSMumVT6Kz8rMYbOspIf18RMz8a0P6WmnC265RomT3B4qAIos8XVuMBY= + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/serve/web/tokens.css b/serve/web/tokens.css new file mode 100644 index 00000000..310cfee2 --- /dev/null +++ b/serve/web/tokens.css @@ -0,0 +1,88 @@ +/* Strata UI — tokens. Derived from the Gainsty design system. + Light is default; dark via . + Values marked (derived) are not in the Gainsty source and were added for the app. */ + +@font-face{font-family:"GT Walsheim Pro";src:url("/fonts/GTWalsheimPro-Regular.woff2") format("woff2");font-weight:400;font-display:swap} +@font-face{font-family:"GT Walsheim Pro";src:url("/fonts/GTWalsheimPro-Medium.woff2") format("woff2");font-weight:500;font-display:swap} +@font-face{font-family:"GT Walsheim Pro";src:url("/fonts/GTWalsheimPro-Bold.woff2") format("woff2");font-weight:700;font-display:swap} +@font-face{font-family:"GT Walsheim Pro";src:url("/fonts/GTWalsheimPro-Black.woff2") format("woff2");font-weight:900;font-display:swap} + +:root{ + /* type */ + --st-font:"GT Walsheim Pro",system-ui,-apple-system,"Segoe UI",Roboto,sans-serif; + --st-font-mono:ui-monospace,"SF Mono","Cascadia Code",Consolas,"Liberation Mono",monospace; /* (derived) */ + --st-fs-xs:12px; --st-fs-sm:13px; --st-fs-md:14px; --st-fs-base:16px; + --st-fs-lg:18px; --st-fs-xl:24px; --st-fs-stat:32px; --st-fs-display:40px; + --st-fw-regular:400; --st-fw-medium:500; --st-fw-bold:700; --st-fw-black:900; + --st-lh-tight:1.1; --st-lh-body:1.55; + + /* spacing (4pt) */ + --st-s-1:4px; --st-s-2:8px; --st-s-3:12px; --st-s-4:16px; --st-s-5:20px; + --st-s-6:24px; --st-s-8:32px; --st-s-10:40px; --st-s-12:48px; --st-s-16:64px; + + /* radius */ + --st-r-sm:8px; --st-r-md:14px; --st-r-lg:20px; --st-r-xl:24px; --st-r-pill:9999px; + + /* motion (derived) */ + --st-ease:cubic-bezier(.2,.7,.2,1); --st-dur:160ms; + + /* color — light */ + --st-bg:#f9fafb; + --st-surface:#ffffff; + --st-surface-2:#f7f7f7; + --st-line:#dee5ee; + --st-line-soft:#eeeeee; + --st-ink:#221e1f; + --st-ink-soft:#303030; + --st-ink-muted:#6f6f6f; /* Gainsty #7a7a7a darkened slightly for 4.5:1 on white */ + --st-icon:#2F384C; /* Anron default */ + + --st-accent:#10b981; + --st-accent-hover:#0c8a60; + --st-accent-ink:#ffffff; + --st-accent-tint:#ecfdf5; + --st-accent-text:#0c8a60; /* accent used as text on light */ + --st-focus:#405de6; + + --st-info:#0f97ff; --st-info-tint:#e8f4ff; --st-info-text:#0668c2; + --st-warn:#e39b0b; --st-warn-tint:#fff6e0; --st-warn-text:#8a5a00; /* (derived) */ + --st-danger:#e0283f; --st-danger-tint:#fdecee; --st-danger-text:#b01a2e; /* (derived) */ + + --st-code-bg:#1b1f23; --st-code-ink:#e6e9ec; /* code blocks stay dark in both themes (derived) */ + + --st-sh-card:0 18px 7px rgba(0,0,0,.01),0 10px 6px rgba(0,0,0,.02),0 4px 4px rgba(0,0,0,.03),0 1px 2px rgba(0,0,0,.04); + --st-sh-bar:0 54px 21px rgba(0,0,0,.01),0 30px 18px rgba(0,0,0,.03),0 13px 13px rgba(0,0,0,.05),0 3px 7px rgba(0,0,0,.06); + --st-sh-pop:0 10px 40px rgba(15,23,42,.08),0 1px 3px rgba(15,23,42,.06); + color-scheme:light; +} + +/* color — dark (all derived) */ +[data-theme="dark"]{ + --st-bg:#0e1113; + --st-surface:#161a1d; + --st-surface-2:#1d2226; + --st-line:#2a3036; + --st-line-soft:#22272c; + --st-ink:#eef1f3; + --st-ink-soft:#c7cdd3; + --st-ink-muted:#8e979f; + --st-icon:#c7cdd3; + + --st-accent:#34d399; + --st-accent-hover:#4ade80; + --st-accent-ink:#052e20; + --st-accent-tint:rgba(52,211,153,.12); + --st-accent-text:#4ade80; + --st-focus:#7b93ff; + + --st-info:#3aa9ff; --st-info-tint:rgba(58,169,255,.12); --st-info-text:#7cc4ff; + --st-warn:#f5b53d; --st-warn-tint:rgba(245,181,61,.12); --st-warn-text:#f8c96a; + --st-danger:#ff5a6e; --st-danger-tint:rgba(255,90,110,.12);--st-danger-text:#ff8a98; + + --st-code-bg:#0a0c0e; --st-code-ink:#e6e9ec; + + --st-sh-card:0 1px 2px rgba(0,0,0,.4); + --st-sh-bar:0 12px 32px rgba(0,0,0,.45),0 2px 6px rgba(0,0,0,.35); + --st-sh-pop:0 16px 48px rgba(0,0,0,.55),0 1px 3px rgba(0,0,0,.4); + color-scheme:dark; +} diff --git a/setup.py b/setup.py index 0cafb35b..0e9f8394 100644 --- a/setup.py +++ b/setup.py @@ -55,7 +55,7 @@ PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip" CUDA_WHEELS = ["nvidia-cublas==13.0.2.14", "nvidia-cuda-runtime==13.0.96"] MIN_DRIVER = 580 # CUDA 13.0 MIN_ENGINE = (0, 1, 7) # per-request sampling on the GEN line (the server sends it), v0.1.7 -PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow"] +PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow", "psutil"] MODELS = { "Q2_0": {"about": "2-bit, the fastest", "download_gb": 66.4, "ram_gb": 48, "arena_gb": 34.0}, @@ -791,7 +791,7 @@ def main() -> int: # ---- 3. python packages step(3, "Python packages") - pip_install(PY_PACKAGES, "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow") + pip_install(PY_PACKAGES, "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil") # ---- 4. the engine step(4, "the Strata engine") diff --git a/src/program/generate.cpp b/src/program/generate.cpp index ec781633..943abbec 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2178,6 +2178,18 @@ int main(int argc, char** argv) { (long long) (free_b >> 20), free_b < ((size_t) 128 << 20) ? " - LOW: requests may stall; lower --max-context or raise --vram-reserve-mib" : ""); } + // what the server's Monitor tab shows (servers before 0.1.8 skip unknown lines until READY) + { + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + std::printf("INFO context=%lld kv=%s kv_resident=%lld expert_slots=%lld expert_cache_mib=%lld spec=%d " + "mtp_max=%d lookup=%d vram_free_mib=%lld\n", + (long long) o.max_context, o.kv.c_str(), + (long long) (g.n_qsa_layers() > 0 && ss.qsa_states[0].kv_mode == 1 + ? ss.qsa_states[0].n_slots * 4 : 0), + (long long) xcache.slots(), (long long) (xcache.bytes() >> 20), o.spec, o.mtp_max_t, + o.suffix_draft, (long long) (free_b >> 20)); + } std::printf("READY %lld stop\n", (long long) o.max_context); // "stop": this engine honours STOP std::fflush(stdout); std::string line;