okami.mom/strata

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

Niko1221Merge f-027-web: the served web chat page for 0.2.75d9f47922

main
8.3 KiB129 linesraw
1// A stand-in for the Strata server for tests of the served web page (serve/web): it serves the page's own files and
2// answers the few calls the page makes with scripted text. No model, no GPU, no Python. Used by browser_test.mjs and shots.mjs.
3//
4//   import { startMock } from "./mock.mjs";
5//   const mock = await startMock();           // { url, state, stop() }
6//
7// What the page asks and what it gets: GET /health /metrics /mcp /settings /config, POST /load /unload,
8// POST /v1/chat/completions (streamed). The reply depends on a word in the last user message:
9//   #math   inline and display formulas, a price      #svg / #html  a fenced svg / html block     #think  reasoning first
10//   #long   a slow answer (about 6 s) to interrupt    #hold  never ends until the page stops it   #tool   an MCP tool call, then text
11//   #error  a 500                                      anything else: "Mock answer N."
12import http from "node:http";
13import fs from "node:fs";
14import path from "node:path";
15import { fileURLToPath } from "node:url";
16
17const here = path.dirname(fileURLToPath(import.meta.url));
18export const WEB = path.resolve(here, "..", "..", "serve", "web");
19const TYPES = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8",
20  ".svg": "image/svg+xml", ".json": "application/json; charset=utf-8", ".woff2": "font/woff2" };
21
22// the one header the real server puts on the page (serve/server.py, PAGE_CSP): read from the source so the two cannot drift
23const PAGE_CSP = (/^PAGE_CSP = "(.*)"$/m.exec(fs.readFileSync(path.join(here, "..", "..", "serve", "server.py"), "utf8")) || [])[1] || "";
24const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
25const lastUser = (messages) => {
26  for (let i = messages.length - 1; i >= 0; i--) {
27    if (messages[i].role !== "user") continue;
28    const c = messages[i].content;
29    return typeof c === "string" ? c : (c.find((p) => p.type === "text") || {}).text || "";
30  }
31  return "";
32};
33
34const MATH = "The area is $\\pi r^2$ and the sum is\n\n$$\\sum_{k=1}^{n} k = \\frac{n(n+1)}{2}$$\n\nIt costs $5 or $10, and `$x$` is code.\n\n" +
35  "A bad one: $\\frac{1}{$ and a link-ish \\href{javascript:alert(1)}{click}: $\\href{javascript:alert(1)}{click}$.";
36const SVG = "Here is a circle:\n\n```svg\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 100 100\" width=\"120\" height=\"120\">" +
37  "<circle cx=\"50\" cy=\"50\" r=\"40\" fill=\"#10b981\"/><text x=\"50\" y=\"56\" text-anchor=\"middle\" fill=\"white\" font-size=\"18\">SVG</text></svg>\n```\n";
38const HTML = "A small page:\n\n```html\n<!doctype html><html><body style=\"font-family:sans-serif\"><h2>Hello</h2>" +
39  "<p id=\"p\">Static text.</p><script>document.getElementById('p').textContent='Script ran.'</script></body></html>\n```\n";
40
41export async function startMock({ port = 0, root = WEB, loaded = true, csp = true } = {}) {
42  const state = { requests: [], aborted: 0, completed: 0, loaded, calls: [], answers: 0 };
43  const server = http.createServer(async (req, res) => {
44    const url = new URL(req.url, "http://x");
45    const p = url.pathname.replace(/\/+$/, "");
46    state.calls.push(`${req.method} ${p}`);
47    const json = (code, body) => { res.writeHead(code, { "Content-Type": "application/json" }); res.end(JSON.stringify(body)); };
48    if (req.method === "GET") {
49      if (p === "") return file(res, path.join(root, "index.html"), undefined, csp && PAGE_CSP ? { "Content-Security-Policy": PAGE_CSP } : {});
50      if (p.startsWith("/web/")) return file(res, path.join(root, p.slice(5)), root);
51      if (p.startsWith("/fonts/")) return file(res, path.join(root, "fonts", p.slice(7)), root);
52      if (p === "/health") return json(200, { status: "ok", max_context: 32768, model: "Mock-Model", images: true, image_generation: false, loaded: state.loaded, service: "strata" });
53      if (p === "/metrics") return json(200, metrics(state));
54      if (p === "/mcp") return json(200, { servers: [], tools: 0 });
55      if (p === "/settings") return json(200, { shared: false, defaults: null });
56      return json(404, { error: { message: "not found" } });
57    }
58    let body = "";
59    for await (const part of req) body += part;
60    if (p === "/unload") { await sleep(150); state.loaded = false; return json(200, { status: "unloaded" }); }
61    if (p === "/load") { await sleep(300); state.loaded = true; return json(200, { status: "loaded" }); }
62    if (p === "/settings") return json(200, { shared: false });
63    if (p !== "/v1/chat/completions") return json(404, { error: { message: "not found" } });
64    const b = JSON.parse(body || "{}");
65    state.requests.push(b);
66    const text = lastUser(b.messages || []);
67    if (text.includes("#error")) return json(500, { error: { message: "The mock engine failed on purpose." } });
68    state.loaded = true;
69    res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" });
70    let closed = false;
71    res.on("close", () => { if (!res.writableEnded) { closed = true; state.aborted++; } });
72    const send = (o) => { if (!closed) res.write("data: " + JSON.stringify(o) + "\n\n"); };
73    const say = async (s, ms = 0, step = 6) => {
74      for (let i = 0; i < s.length && !closed; i += step) { send({ choices: [{ delta: { content: s.slice(i, i + step) } }] }); if (ms) await sleep(ms); }
75    };
76    state.answers++;
77    if (text.includes("#think")) {
78      for (const w of ["Let me think ", "about this ", "for a moment."]) { send({ choices: [{ delta: { reasoning_content: w } }] }); await sleep(30); }
79      await say("Thought through. The answer is 42.");
80    } else if (text.includes("#math")) await say(MATH, 4);
81    else if (text.includes("#svg")) await say(SVG, 2);
82    else if (text.includes("#html")) await say(HTML, 2);
83    else if (text.includes("#hold")) { await say("Working on it", 20); while (!closed) await sleep(50); return; }
84    else if (text.includes("#long")) { await say("This is a long answer that goes on for a while so that it can be interrupted. ".repeat(3), 40, 4); }
85    else if (text.includes("#tool")) {
86      await say("Let me look that up. ", 5);
87      const id = "call-1";
88      send({ strata_mcp: { event: "call", id, name: "fs__read", server: "fs", tool: "read", arguments: { path: "notes.txt" }, round: 0 } });
89      await sleep(900);
90      send({ strata_mcp: { event: "result", id, text: "The file says hello.", ok: true, chars: 20, ms: 900 } });
91      await say("The file says hello.", 5);
92    } else await say(`Mock answer ${state.answers}.`, 5);
93    if (!closed) {
94      send({ choices: [{ delta: {}, finish_reason: "stop" }], usage: { completion_tokens: 12 } });
95      res.write("data: [DONE]\n\n");
96      res.end();
97      state.completed++;
98    }
99  });
100  await new Promise((r) => server.listen(port, "127.0.0.1", r));
101  return { url: `http://127.0.0.1:${server.address().port}`, state, stop: () => new Promise((r) => { server.closeAllConnections?.(); server.close(r); }) };
102}
103
104function file(res, f, root, extra = {}) {
105  const resolved = path.resolve(f);
106  if (root && !resolved.startsWith(path.resolve(root) + path.sep)) { res.writeHead(404); return res.end(); }
107  fs.readFile(resolved, (err, data) => {
108    if (err) { res.writeHead(404, { "Content-Type": "application/json" }); return res.end('{"error":{"message":"not found"}}'); }
109    res.writeHead(200, { "Content-Type": TYPES[path.extname(resolved)] || "application/octet-stream", "Cache-Control": "no-cache", ...extra });
110    res.end(data);
111  });
112}
113
114function metrics(state) {
115  const spark = Array.from({ length: 30 }, (_, i) => 20 + 10 * Math.sin(i / 3));
116  return {
117    live: { state: state.loaded ? "idle" : "unloaded", queued: 0 },
118    engine: { model: "Mock-Model", version: "0.0", max_context: 32768, expert_slots: 1200, expert_cache_mib: 9000 },
119    hardware: { gpu_util: 35, gpu_mem_used: 9e9, gpu_mem_total: 12e9, gpu_temp: 61, gpu_power: 140, cpu: 22, ram_total: 64e9, ram_used: 30e9, disk_read_mb: 5 },
120    hardware_static: { gpu_name: "Mock GPU", cpu_name: "Mock CPU", threads: 16, cores: 8, psutil: true },
121    history: { tok_s: spark, gpu_util: spark, gpu_mem_used: spark, gpu_temp: spark, gpu_power: spark, cpu: spark, disk_read_mb: spark, gpu_pcie_rx_mb: spark, prefill_tok_s_mean: spark },
122    requests: [], totals: null, requests_kept: 0, conversation_cache: null,
123  };
124}
125
126if (process.argv[1] === fileURLToPath(import.meta.url)) {
127  const mock = await startMock({ port: Number(process.argv[2] || 0) });
128  console.log("mock server on " + mock.url);
129}