serve: add standalone API request monitor

This commit is contained in:
Ricardo Ambrogi authored and Niko1221 committed 2026-10-01 08:31:48 +02:00
1 parent d3bf912ea0
commit 24d011807c
5 files changed
+455 -3

No files matched your search

+14
View File
@@ -814,3 +814,17 @@ tools/MCP are refused explicitly. Without `response_format`, ordinary text and t
Structured SSE buffers the answer while sending keep-alive comments. It emits content only after validation,
then usage/timings and `[DONE]`; failures emit an SSE error and `[DONE]` without invalid content deltas.
`/v1/status.structured_output` advertises the formats, validation method and buffered streaming behavior.
### API request monitor
Open `/api-monitor` to inspect API traffic without opening a chat. It shows the model state, safe
load/unload controls, active/queued requests, original request bodies, output, separate reasoning and
non-stream response bodies. Total wall-clock includes FIFO waits and automatic loading; load, queue,
first-token, prompt/output tokens and engine decode timing are shown separately.
`GET /api/requests` returns compact summaries; `GET /api/requests?id=<id>` returns one retained request.
Both use the existing API-key check. The monitor retains the newest **100 requests in memory** until restart,
with **262,144 characters per input/output/reasoning/response field** and visible truncation flags. The actual API
responses are unaffected. Headers are not recorded, and the monitor key is kept in this tab's session storage.
Treat request history as sensitive input/output when exposing Strata on a network: set an API key as above.
The page uses relative URLs and works through the existing host binding or a reverse proxy.
+123 -3
View File
@@ -709,6 +709,8 @@ class Service:
self.trusted_origins: list[str] = []
self.status = {"busy": False, "queued": 0} # GET /status: what the model is doing right now
self.rate = collections.deque(maxlen=32) # (time, generated) samples for the live tok/s window
self.api_requests = collections.deque(maxlen=100) # bounded I/O in memory; no headers or API keys
self.request_trace = threading.local()
self.history = collections.deque(maxlen=500) # the last finished requests, newest last (GET /metrics)
# since the server started (the Monitor's totals, issue #35)
self.totals = {"since": time.time(), "requests": 0, "prompt_tokens": 0, "reused": 0, "output_tokens": 0,
@@ -802,8 +804,21 @@ class Service:
self.last_request_at = time.time()
if self.loaded() and not self._vision_down():
return
trace = getattr(self.request_trace, "record", None)
waiting = time.perf_counter()
with self.fifo:
self.ensure_loaded()
loading = time.perf_counter()
if trace is not None:
with self.status_lock:
trace["queue_s"] += round(loading - waiting, 3)
trace["state"] = "loading"
try:
self.ensure_loaded()
finally:
if trace is not None:
with self.status_lock:
trace["load_s"] += round(time.perf_counter() - loading, 3)
trace["state"] = "queued"
def unload(self, idle_for: float | None = None) -> str:
"""Stop the engine between requests: "unloaded", "not loaded", "busy" (a request is running or waiting, or
@@ -915,6 +930,34 @@ class Service:
reading = self.status.get("busy") and self.status.get("first_token") is None
return getattr(self.engine, "prefill_tok_s_mean", None) if reading else 0.0
def begin_request(self, path, req):
raw = json.dumps(req, ensure_ascii=False, indent=2)
record = {"id": uuid.uuid4().hex[:12], "path": path, "model": req.get("model") or self.model,
"started_at": time.time(), "state": "queued", "stream": bool(req.get("stream")),
"response_format": (req.get("response_format") or {}).get("type")
if isinstance(req.get("response_format"), dict) else None,
"input": raw[:262144], "input_truncated": len(raw) > 262144,
"output": "", "reasoning": "", "output_truncated": False, "reasoning_truncated": False,
"queue_s": 0.0, "load_s": 0.0, "first_token_s": None,
"_clock": time.perf_counter()}
with self.status_lock:
self.api_requests.append(record)
self.request_trace.record = record
return record
def request_records(self, request_id=None):
with self.status_lock:
records = list(self.api_requests)
if request_id:
record = next((r for r in records if r["id"] == request_id), None)
if record is None:
return None
return {k: v for k, v in record.items() if not k.startswith("_")}
return [{k: v for k, v in r.items()
if k not in ("input", "output", "reasoning", "response") and not k.startswith("_")}
| {"wallclock_s": r.get("wallclock_s", round(time.perf_counter() - r["_clock"], 3))}
for r in reversed(records)]
def metrics(self, all_requests=False) -> 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)."""
@@ -1093,12 +1136,17 @@ class Service:
# Identity token: only a DONE line replaces engine.last, so a request that died, errored or was
# disconnected must not have the PREVIOUS request's decode figures recorded as its own.
engine_last0 = getattr(self.engine, "last", None)
trace = getattr(self.request_trace, "record", None)
waiting = time.perf_counter()
with self.status_lock:
self.status["queued"] += 1
try:
with self.fifo:
try:
with self.status_lock:
if trace is not None:
trace["queue_s"] += round(time.perf_counter() - waiting, 3)
trace["state"] = "generating"
self.status["queued"] -= 1
# issue #27: it died in an earlier request (or was unloaded) - start it again instead of failing
self.ensure_loaded()
@@ -1122,6 +1170,9 @@ class Service:
yield "ping", None
continue
n += 1
if trace is not None and trace["first_token_s"] is None:
with self.status_lock:
trace["first_token_s"] = round(time.perf_counter() - trace["_clock"], 3)
if t in self.stop_ids:
finish = "stop"
raw_ids.append(t)
@@ -1617,6 +1668,14 @@ def make_handler(svc: Service):
self.end_headers()
def _json(self, code, obj):
if getattr(self, "record", None) is not None:
with svc.status_lock:
self.record["http_status"] = code
raw = json.dumps(obj, ensure_ascii=False, indent=2)
self.record.update(response=raw[:262144], response_truncated=len(raw) > 262144)
for key in ("error", "usage", "timings"):
if key in obj:
self.record[key] = obj[key]
body = json.dumps(obj, ensure_ascii=False).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
@@ -1675,6 +1734,15 @@ def make_handler(svc: Service):
# the last 12 requests; `?requests=all` every one kept (the Monitor's "Show all", issue #35)
self._json(200, svc.metrics(all_requests="requests=all" in self.path))
return
if path == "/api/requests":
if self._authorized():
request_id = parse_qs(urlsplit(self.path).query).get("id", [None])[0]
records = svc.request_records(request_id)
self._json(404 if records is None else 200,
{"error": {"message": "request no longer retained"}} if records is None else
records if request_id else {"requests": records, "retention": 100, "persistent": False,
"loaded": svc.loaded(), "auto_load": hasattr(svc.engine, "restart")})
return
if path == "/settings":
if self._authorized():
self._json(200, {"shared": bool(svc.shared), "defaults": svc.shared})
@@ -1684,8 +1752,8 @@ def make_handler(svc: Service):
if self._authorized():
self._json(200, svc.mcp.status() if svc.mcp else {"servers": [], "tools": 0})
return
if path == "":
body = (ROOT / "serve" / "web" / "index.html").read_bytes()
if path in ("", "/api-monitor"):
body = (ROOT / "serve" / "web" / ("monitor.html" if path else "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)))
@@ -1786,6 +1854,8 @@ def make_handler(svc: Service):
result = "loaded"
self._json(200, {"status": result, **svc.v1_status()})
return
if path in ("/v1/chat/completions", "/v1/messages"):
self.record = svc.begin_request(path, req)
if path == "/v1/chat/completions":
self._openai(req)
elif path == "/v1/messages":
@@ -1808,6 +1878,18 @@ def make_handler(svc: Service):
except EngineStuck as e: # an unload or restart that could not end the engine
self._json(503, {"error": {"type": "server_error", "message": str(e)}})
except OSError:
if getattr(self, "record", None) is not None:
self.record["outcome"] = "disconnected"
finally:
record = getattr(self, "record", None)
if record is not None:
with svc.status_lock:
record["wallclock_s"] = round(time.perf_counter() - record["_clock"], 3)
record["finished_at"] = time.time()
record["state"] = "error" if record.get("error") else record.get("outcome", "completed")
svc.request_trace.record = None
def _props(self):
model = parse_qs(urlsplit(self.path).query).get("model", [svc.model])[0]
if model != svc.model:
@@ -1866,6 +1948,8 @@ def make_handler(svc: Service):
self._json(200, {"shared": bool(shared), "defaults": shared})
def _sse(self):
if getattr(self, "record", None) is not None:
self.record["http_status"] = 200
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
@@ -1873,6 +1957,34 @@ def make_handler(svc: Service):
self._cors()
self.end_headers()
def _capture(self, items, api):
"""Retain bounded input/output for the monitor without changing the API response."""
try:
for item in items:
if item is not None:
if api == "openai":
delta = item["choices"][0]["delta"]
content, reasoning = delta.get("content", ""), delta.get("reasoning_content", "")
usage, timings = item.get("usage"), item.get("timings")
else:
_, event = item
delta = event.get("delta", {})
content, reasoning = delta.get("text", ""), delta.get("thinking", "")
usage, timings = event.get("usage"), None
with svc.status_lock:
for name, value in (("output", content), ("reasoning", reasoning)):
if value:
combined = self.record[name] + value
self.record[name] = combined[:262144]
self.record[name + "_truncated"] |= len(combined) > 262144
if usage:
self.record["usage"] = usage
if timings:
self.record["timings"] = timings
yield item
finally:
items.close()
def _openai(self, req):
req = svc.with_shared(req, "openai")
messages, tools, kw = openai_to_messages(req)
@@ -1899,6 +2011,7 @@ def make_handler(svc: Service):
chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run)
if validator is not None:
chunks = structured_chunks(chunks, validator)
chunks = self._capture(chunks, "openai")
if not req.get("stream"):
return self._json(200, openai_collect(chunks))
self._sse()
@@ -1911,16 +2024,19 @@ def make_handler(svc: Service):
self.wfile.flush()
self.wfile.write(b"data: [DONE]\n\n")
except OSError:
self.record["outcome"] = "disconnected"
cancel.set() # client went away: stop the engine
chunks.close()
except EngineDied as e: # mid-stream: say so, then end the stream properly
err = {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}}
self.record["error"] = err["error"]
self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")
except StructuredOutputError as e:
err = {"error": {"type": "structured_output_failed", "code": "structured_output_failed", "message": str(e)}}
self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")
except ValueError as e: # the engine's ERR after the stream started: the
err = {"error": {"type": "server_error", "message": str(e)}} # headers are sent, so no 400 now
self.record["error"] = err["error"]
self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")
def _count_tokens(self, req):
@@ -1941,6 +2057,7 @@ def make_handler(svc: Service):
_debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids))
cancel = threading.Event()
events = anthropic_events(svc, req, ids, thinking, tools, max_new, cancel)
events = self._capture(events, "anthropic")
if not req.get("stream"):
return self._json(200, anthropic_collect(events))
self._sse()
@@ -1954,13 +2071,16 @@ def make_handler(svc: Service):
json.dumps(e, ensure_ascii=False).encode() + b"\n\n")
self.wfile.flush()
except OSError:
self.record["outcome"] = "disconnected"
cancel.set()
events.close()
except EngineDied as e: # mid-stream: Anthropic's error event
err = {"type": "error", "error": {"type": "api_error", "message": f"{e}; the next request restarts it"}}
self.record["error"] = err["error"]
self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n")
except ValueError as e: # the engine's ERR after the stream started
err = {"type": "error", "error": {"type": "api_error", "message": str(e)}}
self.record["error"] = err["error"]
self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n")
return Handler
+170
View File
@@ -0,0 +1,170 @@
"""Request inspection through HTTP; no native model or GPU is required."""
import json
import threading
import time
import unittest
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from unittest import mock
from serve.frontend import ChatTemplate
from serve.server import ByteTokenizer, EngineDied, MockEngine, Service, serve
class ReloadableEngine(MockEngine):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.running, self.unloaded = True, False
def alive(self):
return self.running
def unload(self):
self.running, self.unloaded = False, True
def restart(self):
self.running, self.unloaded = True, False
class Monitor(unittest.TestCase):
def setUp(self):
self.tok = ByteTokenizer()
self.engine = ReloadableEngine(self.tok, "Thought.</think>\nHello <script>alert(1)</script>.", max_context=16384)
self.svc = Service(self.engine, self.tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
self.httpd = serve(self.svc, port=0)
self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
def tearDown(self):
self.httpd.shutdown()
self.httpd.server_close()
def request(self, path, body=None, headers=None):
req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None,
headers={"Content-Type": "application/json", **(headers or {})})
try:
response = urllib.request.urlopen(req, timeout=10)
except urllib.error.HTTPError as error:
response = error
with response:
raw = response.read().decode()
return response.status, json.loads(raw) if "application/json" in response.headers.get("Content-Type", "") else raw
def chat(self, api="openai", **kwargs):
return self.request("/v1/messages" if api == "anthropic" else "/v1/chat/completions",
{"messages": [{"role": "user", "content": "Say hello."}],
"max_tokens": 256, "reasoning_effort": "low", **kwargs})
def latest(self):
summary = self.request("/api/requests")[1]["requests"][0]
return self.request("/api/requests?id=" + summary["id"])[1]
def test_output_and_reasoning_for_both_dialects_and_stream_modes(self):
for api in ("openai", "anthropic"):
for stream in (False, True):
with self.subTest(api=api, stream=stream):
code, reply = self.chat(api, stream=stream)
self.assertEqual(code, 200)
record = self.latest()
self.assertEqual(record["state"], "completed")
self.assertEqual(record["http_status"], 200)
self.assertIn("Say hello.", record["input"])
self.assertIn("<script>alert(1)</script>", record["output"])
self.assertIn("Thought.", record["reasoning"])
self.assertGreater(record["usage"].get("completion_tokens", record["usage"].get("output_tokens", 0)), 0)
self.assertGreaterEqual(record["wallclock_s"], record["first_token_s"])
self.assertNotIn("_clock", record)
if not stream:
self.assertEqual(json.loads(record["response"]), reply)
else:
self.assertNotIn("response", record)
def test_error_and_engine_death_are_not_successes(self):
self.assertEqual(self.chat(max_tokens=20000)[0], 400)
self.assertEqual(self.latest()["state"], "error")
for api in ("openai", "anthropic"):
for stream in (False, True):
with self.subTest(api=api, stream=stream), mock.patch.object(self.engine, "generate", side_effect=EngineDied("stopped")):
self.chat(api, stream=stream)
record = self.latest()
self.assertEqual(record["state"], "error")
self.assertIn("stopped", record["error"]["message"])
self.assertEqual(record["output"], "")
self.assertNotIn("timings", record)
def test_history_is_authorized_and_does_not_capture_headers(self):
self.svc.api_key = "secret"
auth = {"Authorization": "Bearer secret"}
self.assertEqual(self.request("/api/requests")[0], 401)
self.assertEqual(self.request("/api/requests?id=missing")[0], 401)
self.assertEqual(len(self.svc.api_requests), 0)
self.assertEqual(self.request("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]}, auth)[0], 200)
summary = self.request("/api/requests", headers=auth)[1]["requests"][0]
self.assertNotIn("input", summary)
self.assertNotIn("output", summary)
self.assertEqual(self.request("/api/requests?id=" + summary["id"])[0], 401)
detail = self.request("/api/requests?id=" + summary["id"], headers=auth)[1]
self.assertNotIn("secret", json.dumps(detail))
def test_capture_is_bounded_and_eviction_returns_404(self):
huge = "x" * 262200
first = self.svc.begin_request("/v1/chat/completions", {"messages": [{"content": huge}]})
self.assertEqual(len(first["input"]), 262144)
self.assertTrue(first["input_truncated"])
for _ in range(100):
self.svc.begin_request("/v1/chat/completions", {"messages": []})
self.assertEqual(len(self.request("/api/requests")[1]["requests"]), 100)
self.assertEqual(self.request("/api/requests?id=" + first["id"])[0], 404)
# Exercise output capture without making a mock engine emit 262K tokens.
handler = object.__new__(self.httpd.RequestHandlerClass)
handler.record = self.svc.api_requests[-1]
chunk = {"choices": [{"delta": {"content": huge, "reasoning_content": huge}}]}
list(handler._capture((item for item in [chunk]), "openai"))
for field in ("output", "reasoning"):
self.assertEqual(len(handler.record[field]), 262144)
self.assertTrue(handler.record[field + "_truncated"])
def test_queue_wait_and_loading_are_attributed_separately(self):
self.engine.unload()
entered, release = threading.Event(), threading.Event()
original = self.engine.restart
def restart():
entered.set()
self.assertTrue(release.wait(5))
original()
with mock.patch.object(self.engine, "restart", side_effect=restart), ThreadPoolExecutor(max_workers=2) as pool:
first = pool.submit(self.chat)
self.assertTrue(entered.wait(5))
second = pool.submit(self.chat)
deadline = time.monotonic() + 5
while len(self.svc.api_requests) < 2 and time.monotonic() < deadline:
time.sleep(0.01)
self.assertEqual(len(self.svc.api_requests), 2)
history = self.request("/api/requests")[1]
self.assertEqual({r["state"] for r in history["requests"]}, {"queued", "loading"})
self.assertFalse(history["loaded"])
self.assertTrue(history["auto_load"])
time.sleep(0.03)
release.set()
self.assertEqual(first.result()[0], 200)
self.assertEqual(second.result()[0], 200)
records = list(self.svc.api_requests)
self.assertGreater(records[0]["load_s"], 0.02)
self.assertGreater(records[1]["queue_s"], 0.02)
self.assertLess(records[1]["load_s"], records[0]["load_s"])
self.assertTrue(all(r["state"] == "completed" for r in records))
def test_page_and_relative_assets_are_served(self):
code, html = self.request("/api-monitor")
self.assertEqual(code, 200)
self.assertIn('src="/web/monitor.js"', html)
code, script = self.request("/web/monitor.js")
self.assertEqual(code, 200)
self.assertIn("textContent", script)
self.assertNotIn("innerHTML", script)
self.assertEqual(self.request("/web/../server.py")[0], 404)
if __name__ == "__main__":
unittest.main()
+37
View File
@@ -0,0 +1,37 @@
<!doctype html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Strata API Monitor</title>
<link rel="stylesheet" href="/web/tokens.css">
<style>
*{box-sizing:border-box}body{margin:0;background:var(--st-bg);color:var(--st-ink);font:15px/1.5 var(--st-font)}
button,input,select{font:inherit}button{cursor:pointer;color:inherit;background:var(--st-surface-2);border:1px solid var(--st-line);border-radius:9px;padding:8px 13px}button:hover{border-color:var(--st-accent)}button:disabled{opacity:.4;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--st-focus);outline-offset:3px}[hidden]{display:none!important}
header{height:70px;padding:0 32px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--st-line);background:var(--st-surface)}.brand{font-size:23px;font-weight:700;letter-spacing:-.5px}.brand span{font-size:13px;font-weight:400;margin-left:14px;color:var(--st-ink-muted)}main{max-width:1560px;margin:auto;padding:28px 32px}.top{display:flex;align-items:center;justify-content:space-between;gap:24px}h1{margin:0;font-size:29px;letter-spacing:-.7px}h2{font-size:17px;margin:0}.sub,.muted{color:var(--st-ink-muted)}.sub{margin:4px 0 0}.controls{display:flex;gap:8px;flex-wrap:wrap}.primary{background:var(--st-accent);color:var(--st-accent-ink);border-color:transparent}.notice{margin-top:16px;padding:10px 14px;background:var(--st-danger-tint);color:var(--st-danger-text);border-radius:9px}.cards{display:grid;grid-template-columns:2fr repeat(3,1fr);gap:14px;margin:24px 0}.card{padding:18px 20px;border:1px solid var(--st-line);border-radius:13px;background:var(--st-surface)}.label{font-size:12px;color:var(--st-ink-muted);text-transform:uppercase;letter-spacing:.8px}.value{font-size:28px;font-weight:500;line-height:1.4;margin-top:3px}.model{font:12px var(--st-font-mono);overflow-wrap:anywhere;margin-top:4px;color:var(--st-ink-muted)}.dot{display:inline-block;width:9px;height:9px;border-radius:100%;background:var(--st-ink-muted);margin-right:9px}.loaded .dot{background:var(--st-accent)}.busy .dot{background:var(--st-warn)}.panel{border:1px solid var(--st-line);border-radius:14px;background:var(--st-surface);overflow:hidden}.panel-bar{padding:15px 20px;border-bottom:1px solid var(--st-line);display:flex;align-items:center;justify-content:space-between;gap:12px}.filters{display:flex;gap:8px}input,select{color:inherit;border:1px solid var(--st-line);background:var(--st-bg);padding:7px 10px;border-radius:8px}#search{width:190px}.workspace{display:grid;grid-template-columns:minmax(340px,38%) minmax(0,1fr);min-height:480px}.requests{border-right:1px solid var(--st-line);max-height:650px;overflow:auto}.request{display:block;width:100%;border:0;border-bottom:1px solid var(--st-line-soft);border-radius:0;padding:15px 20px;text-align:left;background:transparent}.request.selected{background:var(--st-accent-tint);box-shadow:inset 3px 0 var(--st-accent)}.request:hover{background:var(--st-surface-2)}.row{display:flex;justify-content:space-between;gap:12px}.endpoint{font:12px var(--st-font-mono);margin:8px 0 5px;overflow-wrap:anywhere}.tag{font-size:11px;border-radius:5px;padding:2px 6px;background:var(--st-surface-2);color:var(--st-ink-muted)}.tag.completed{color:var(--st-accent-text);background:var(--st-accent-tint)}.tag.error{color:var(--st-danger-text);background:var(--st-danger-tint)}.tag.loading,.tag.generating,.tag.queued{color:var(--st-warn-text);background:var(--st-warn-tint)}.small{font-size:12px;color:var(--st-ink-muted)}.detail{min-width:0;padding:20px}.empty{padding:70px 24px;text-align:center;color:var(--st-ink-muted)}.empty strong{display:block;color:var(--st-ink);font-size:18px;margin-bottom:6px}.detail-title{font:13px var(--st-font-mono)}.facts{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin:18px 0}.fact{background:var(--st-bg);border-radius:8px;padding:9px 11px}.fact span{font-size:11px;color:var(--st-ink-muted);display:block}.fact b{font-weight:500;font-size:16px}.tabs{display:flex;align-items:center;gap:5px;border-bottom:1px solid var(--st-line);padding-bottom:10px}.tabs button{padding:6px 10px;border-color:transparent;background:transparent;font-size:13px}.tabs button[aria-selected=true]{background:var(--st-surface-2);color:var(--st-accent-text)}.tabs #copy{margin-left:auto;border-color:var(--st-line)}pre{margin:14px 0 0;padding:15px;background:var(--st-bg);border:1px solid var(--st-line-soft);border-radius:9px;font:12px/1.6 var(--st-font-mono);white-space:pre-wrap;overflow-wrap:anywhere;max-height:400px;overflow:auto;min-height:180px}.detail-error{margin:12px 0;padding:10px 12px;border-radius:8px;background:var(--st-danger-tint);color:var(--st-danger-text);font-size:12px;overflow-wrap:anywhere}footer{margin-top:14px;font-size:12px;color:var(--st-ink-muted);display:flex;justify-content:space-between;gap:20px}#auth{margin-top:16px;padding:14px;display:flex;gap:10px;align-items:center}#auth input{flex:1;max-width:400px}
@media(max-width:950px){.cards{grid-template-columns:repeat(2,1fr)}.workspace{grid-template-columns:1fr}.requests{border-right:0;border-bottom:1px solid var(--st-line);max-height:260px}.top{align-items:flex-start}.brand span{display:none}}@media(max-width:600px){main{padding:20px 14px}header{padding:0 16px}.top{flex-direction:column;gap:14px}.cards{gap:8px}.card{padding:12px}.value{font-size:23px}.panel-bar{align-items:flex-start;flex-direction:column}#search{width:160px}.facts{grid-template-columns:repeat(2,1fr)}footer{flex-direction:column;gap:4px}}
</style>
<script defer src="/web/monitor.js"></script>
</head>
<body>
<header><div class="brand">Strata <span>Local inference</span></div><div class="controls"><button id="key">API key</button><button id="theme" aria-label="Switch color theme">Light / dark</button></div></header>
<main>
<div class="top"><div><h1>API Monitor</h1><p class="sub">Model status and every request, in one place.</p></div><div class="controls"><button id="load" class="primary" disabled>Load model</button><button id="unload" disabled>Unload model</button></div></div>
<div id="error" class="notice" role="status" hidden></div>
<form id="auth" class="panel" hidden><label for="api-key">API key</label><input id="api-key" type="password" autocomplete="off" placeholder="Only needed if the server has a key"><button class="primary">Connect</button></form>
<div class="cards">
<div class="card"><div class="label">Model</div><div id="model-state" class="value"><span class="dot"></span><span id="loaded">Connecting…</span></div><div id="model" class="model">127.0.0.1:5001/v1</div></div>
<div class="card"><div class="label">Requests retained</div><div id="count" class="value">—</div><div id="active" class="small">Waiting for server</div></div>
<div class="card"><div class="label">Last wall-clock</div><div id="wall" class="value">—</div><div class="small">Includes queue and model loading</div></div>
<div class="card"><div class="label">Last decode speed</div><div id="speed" class="value">—</div><div class="small">Engine timing · tokens / second</div></div>
</div>
<section class="panel"><div class="panel-bar"><h2>Requests</h2><div class="filters"><input id="search" aria-label="Filter requests" placeholder="Search ID or endpoint"><select id="filter" aria-label="Request status"><option value="all">All statuses</option><option value="active">Active</option><option value="completed">Completed</option><option value="error">Errors</option></select></div></div>
<div class="workspace"><div id="requests" class="requests" aria-label="Request list"></div><div class="detail">
<div id="no-selection" class="empty"><strong>Inspect a request</strong>Select a request to see its input, output, and timings.</div>
<div id="selection" hidden><div class="row"><div id="detail-title" class="detail-title"></div><span id="detail-status" class="tag"></span></div><div id="detail-time" class="small"></div>
<div class="facts"><div class="fact"><span>Wall-clock</span><b id="detail-wall">—</b></div><div class="fact"><span>Model load</span><b id="detail-load">—</b></div><div class="fact"><span>Queue wait</span><b id="detail-queue">—</b></div><div class="fact"><span>First token</span><b id="detail-first">—</b></div><div class="fact"><span>Prompt tokens</span><b id="detail-prompt">—</b></div><div class="fact"><span>Output tokens</span><b id="detail-tokens">—</b></div><div class="fact"><span>Decode speed</span><b id="detail-speed">—</b></div><div class="fact"><span>Response format</span><b id="detail-format">—</b></div></div>
<div id="detail-error" class="detail-error" hidden></div><div class="tabs" role="tablist" aria-label="Request content"><button role="tab" data-pane="input" aria-selected="true">Input</button><button role="tab" data-pane="output" aria-selected="false">Output</button><button role="tab" data-pane="reasoning" aria-selected="false">Reasoning</button><button role="tab" data-pane="response" aria-selected="false">API response</button><button id="copy">Copy</button></div>
<div id="content-note" class="small" style="margin-top:10px"></div><pre id="content" role="tabpanel" aria-label="Request content"></pre></div>
</div></div></section>
<footer><span>Last 100 requests kept in memory until restart. Inputs and outputs stay on this machine.</span><span id="updated">Connecting…</span></footer>
</main>
</body></html>
+111
View File
@@ -0,0 +1,111 @@
"use strict";
const $ = id => document.getElementById(id);
let selected = null, detail = null, pane = "input", records = [], state = null, operating = false, stamp = "", actionError = "";
let apiKey = sessionStorage.getItem("strata.monitor.key") || "";
document.documentElement.dataset.theme = localStorage.getItem("strata.theme") || "dark";
const seconds = n => typeof n === "number" ? `${n.toFixed(2)} s` : "—";
const speed = n => typeof n === "number" ? n.toFixed(1) : "—";
const active = r => !["completed", "error", "disconnected"].includes(r.state);
function text(id, value) { const el = $(id); if (el.textContent !== String(value)) el.textContent = value; }
async function api(path, body) {
const response = await fetch(path, {cache:"no-store", headers:{...(apiKey ? {Authorization:`Bearer ${apiKey}`} : {}), ...(body !== undefined ? {"Content-Type":"application/json"} : {})}, ...(body !== undefined ? {method:"POST", body:JSON.stringify(body)} : {})});
const value = await response.json();
if (!response.ok) {
if (response.status === 401) $("auth").hidden = false;
throw new Error(value.error?.message || `HTTP ${response.status}`);
}
return value;
}
function notice(message) { $("error").hidden = !message; text("error", message || ""); }
function list() {
const query = $("search").value.toLowerCase(), filter = $("filter").value;
const visible = records.filter(r => `${r.id} ${r.path} ${r.model}`.toLowerCase().includes(query) && (filter === "all" || (filter === "active" ? active(r) : r.state === filter)));
const nextStamp = JSON.stringify([visible, selected]);
if (stamp === nextStamp) return;
stamp = nextStamp;
const focusId = document.activeElement?.dataset.request;
$("requests").replaceChildren();
if (!visible.length) {
const empty = document.createElement("div"); empty.className = "empty";
empty.textContent = records.length ? "No matching requests." : "No requests yet. API calls will appear here automatically.";
$("requests").append(empty);
}
for (const r of visible) {
const button = document.createElement("button"); button.className = `request${selected === r.id ? " selected" : ""}`;
button.dataset.request = r.id; button.setAttribute("aria-label", `Request ${r.id}`); button.setAttribute("aria-pressed", String(selected === r.id));
const row = document.createElement("div"); row.className = "row";
const time = document.createElement("span"); time.textContent = new Date(r.started_at * 1000).toLocaleTimeString();
const tag = document.createElement("span"); tag.className = `tag ${r.state}`; tag.textContent = r.state;
row.append(time, tag);
const endpoint = document.createElement("div"); endpoint.className = "endpoint"; endpoint.textContent = `POST ${r.path}`;
const meta = document.createElement("div"); meta.className = "small";
meta.textContent = `${r.id} · ${seconds(r.wallclock_s)} · ${r.stream ? "stream" : "JSON response"}${r.http_status ? ` · HTTP ${r.http_status}` : ""}`;
button.append(row, endpoint, meta);
button.onclick = async () => { selected = r.id; detail = null; list(); await showDetail(); };
$("requests").append(button);
if (focusId === r.id) button.focus({preventScroll:true});
}
}
function content() {
if (!detail) return;
let value = detail[pane] || (pane === "response" && detail.stream ? "Streaming response: see Output and the request error, if any." : "No content.");
if (pane === "output") { try { value = JSON.stringify(JSON.parse(value), null, 2); } catch (_) {} }
text("content", value);
const note = pane === "output" && detail.error ? "Raw model output retained for diagnosis. The API returned an error." : pane === "input" ? "Original request body." : pane === "output" ? "Model answer. JSON is formatted here for readability." : pane === "reasoning" ? "Separate reasoning content, when enabled." : "API response body.";
text("content-note", note + (detail[`${pane}_truncated`] ? " Monitor capture truncated at 256K characters; the API response was not shortened." : ""));
}
async function showDetail() {
if (!selected) return;
const id = selected;
const value = await api(`/api/requests?id=${encodeURIComponent(id)}`);
if (selected !== id) return;
detail = value; $("selection").hidden = false; $("no-selection").hidden = true;
text("detail-title", `${value.id} · ${value.path}`);
text("detail-status", value.state); $("detail-status").className = `tag ${value.state}`;
text("detail-time", new Date(value.started_at * 1000).toLocaleString());
text("detail-wall", seconds(value.wallclock_s ?? ((Date.now() / 1000) - value.started_at)));
text("detail-load", seconds(value.load_s)); text("detail-queue", seconds(value.queue_s)); text("detail-first", seconds(value.first_token_s));
text("detail-prompt", value.usage?.prompt_tokens ?? value.usage?.input_tokens ?? "—");
text("detail-tokens", value.usage?.completion_tokens ?? value.usage?.output_tokens ?? "—");
text("detail-speed", speed(value.timings?.predicted_per_second)); text("detail-format", value.response_format || "text");
$("detail-error").hidden = !value.error; text("detail-error", value.error?.message || ""); content();
}
async function refresh() {
try {
const [status, history] = await Promise.all([api("/v1/status"), api("/api/requests")]);
state = status; records = history.requests;
status.loaded = history.loaded; status.auto_load = history.auto_load;
if (selected && !records.some(r => r.id === selected)) {
selected = detail = null; $("selection").hidden = true; $("no-selection").hidden = false;
}
const inflight = Math.max(status.activity.in_flight, records.filter(active).length);
const loading = records.some(r => r.state === "loading");
text("loaded", loading ? "Loading…" : inflight ? "In use" : status.loaded ? "Loaded" : "Unloaded");
$("model-state").className = `value ${inflight || loading ? "busy" : status.loaded ? "loaded" : ""}`;
text("model", status.model); text("count", records.length);
text("active", inflight ? `${inflight} active / queued` : status.auto_load ? "Loads automatically on the next request" : "No active requests");
const last = records.find(r => !active(r));
text("wall", last ? seconds(last.wallclock_s) : "—"); text("speed", speed(last?.timings?.predicted_per_second));
$("load").disabled = operating || Boolean(inflight) || status.loaded; $("unload").disabled = operating || Boolean(inflight) || !status.loaded;
list(); if (selected) await showDetail();
text("updated", `Live · updated ${new Date().toLocaleTimeString()}`);
if (!operating) notice(actionError);
} catch (error) { notice(error.message); text("updated", "Disconnected · retrying"); $("load").disabled = $("unload").disabled = true; }
}
async function control(load) {
actionError = "";
operating = true; $("load").disabled = $("unload").disabled = true;
text("loaded", load ? "Loading…" : "Unloading…");
try { await api(load ? "/load" : "/unload", {}); notice(""); }
catch (error) { actionError = error.message; notice(actionError); }
finally { operating = false; await refresh(); }
}
$("load").onclick = () => control(true); $("unload").onclick = () => control(false);
$("key").onclick = () => { $("auth").hidden = !$("auth").hidden; if (!$("auth").hidden) $("api-key").focus(); };
$("auth").onsubmit = async event => { event.preventDefault(); apiKey = $("api-key").value.trim(); sessionStorage.setItem("strata.monitor.key", apiKey); $("auth").hidden = true; await refresh(); };
$("theme").onclick = () => { const theme = document.documentElement.dataset.theme === "dark" ? "light" : "dark"; document.documentElement.dataset.theme = theme; localStorage.setItem("strata.theme", theme); };
$("search").oninput = list; $("filter").onchange = list;
document.querySelectorAll("[data-pane]").forEach(button => { button.onclick = () => { pane = button.dataset.pane; document.querySelectorAll("[data-pane]").forEach(b => b.setAttribute("aria-selected", String(b === button))); content(); }; });
$("copy").onclick = async () => { try { await navigator.clipboard.writeText($("content").textContent); text("copy", "Copied"); setTimeout(() => text("copy", "Copy"), 1500); } catch (_) { notice("Clipboard unavailable; select the text to copy it."); } };
async function poll() { await refresh(); setTimeout(poll, 2000); }
poll();