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")}