okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5d9f47922
main
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 ) => { 26for ( let i = messages . length - 1 ; i >= 0 ; i -- ) { 27if ( messages [ i ]. role !== "user" ) continue ; 28const c = messages [ i ]. content ; 29return typeof c === "string" ?c :( c . find (( p ) => p . type === "text" ) || {}). text || "" ; 30} 31return "" ; 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 } = {}) { 42const state = { requests :[], aborted :0 , completed :0 , loaded, calls :[], answers :0 }; 43const server = http . createServer ( async ( req , res ) => { 44const url = new URL ( req . url , "http://x" ); 45const p = url . pathname . replace ( / \/ + $ / , "" ); 46state . calls . push ( ` ${ req . method } ${ p } ` ); 47const json = ( code , body ) => { res . writeHead ( code , { "Content-Type" :"application/json" }); res . end ( JSON . stringify ( body )); }; 48if ( req . method === "GET" ) { 49if ( p === "" ) return file ( res , path . join ( root , "index.html" ), undefined , csp && PAGE_CSP ?{ "Content-Security-Policy" :PAGE_CSP } :{}); 50if ( p . startsWith ( "/web/" )) return file ( res , path . join ( root , p . slice ( 5 )), root ); 51if ( p . startsWith ( "/fonts/" )) return file ( res , path . join ( root , "fonts" , p . slice ( 7 )), root ); 52if ( p === "/health" ) return json ( 200 , { status :"ok" , max_context :32768 , model :"Mock-Model" , images :true , image_generation :false , loaded :state . loaded , service :"strata" }); 53if ( p === "/metrics" ) return json ( 200 , metrics ( state )); 54if ( p === "/mcp" ) return json ( 200 , { servers :[], tools :0 }); 55if ( p === "/settings" ) return json ( 200 , { shared :false , defaults :null }); 56return json ( 404 , { error :{ message :"not found" } }); 57} 58let body = "" ; 59for await ( const part of req ) body += part ; 60if ( p === "/unload" ) { await sleep ( 150 ); state . loaded = false ; return json ( 200 , { status :"unloaded" }); } 61if ( p === "/load" ) { await sleep ( 300 ); state . loaded = true ; return json ( 200 , { status :"loaded" }); } 62if ( p === "/settings" ) return json ( 200 , { shared :false }); 63if ( p !== "/v1/chat/completions" ) return json ( 404 , { error :{ message :"not found" } }); 64const b = JSON . parse ( body || "{}" ); 65state . requests . push ( b ); 66const text = lastUser ( b . messages || []); 67if ( text . includes ( "#error" )) return json ( 500 , { error :{ message :"The mock engine failed on purpose." } }); 68state . loaded = true ; 69res . writeHead ( 200 , { "Content-Type" :"text/event-stream" , "Cache-Control" :"no-cache" }); 70let closed = false ; 71res . on ( "close" , () => { if ( ! res . writableEnded ) { closed = true ; state . aborted ++ ; } }); 72const send = ( o ) => { if ( ! closed ) res . write ( "data: " + JSON . stringify ( o ) + "\n\n" ); }; 73const say = async ( s , ms = 0 , step = 6 ) => { 74for ( let i = 0 ; i < s . length && ! closed ; i += step ) { send ({ choices :[{ delta :{ content :s . slice ( i , i + step ) } }] }); if ( ms ) await sleep ( ms ); } 75}; 76state . answers ++ ; 77if ( text . includes ( "#think" )) { 78for ( const w of [ "Let me think " , "about this " , "for a moment." ]) { send ({ choices :[{ delta :{ reasoning_content :w } }] }); await sleep ( 30 ); } 79await say ( "Thought through. The answer is 42." ); 80} else if ( text . includes ( "#math" )) await say ( MATH , 4 ); 81else if ( text . includes ( "#svg" )) await say ( SVG , 2 ); 82else if ( text . includes ( "#html" )) await say ( HTML , 2 ); 83else if ( text . includes ( "#hold" )) { await say ( "Working on it" , 20 ); while ( ! closed ) await sleep ( 50 ); return ; } 84else 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 ); } 85else if ( text . includes ( "#tool" )) { 86await say ( "Let me look that up. " , 5 ); 87const id = "call-1" ; 88send ({ strata_mcp :{ event :"call" , id, name :"fs__read" , server :"fs" , tool :"read" , arguments :{ path :"notes.txt" }, round :0 } }); 89await sleep ( 900 ); 90send ({ strata_mcp :{ event :"result" , id, text :"The file says hello." , ok :true , chars :20 , ms :900 } }); 91await say ( "The file says hello." , 5 ); 92} else await say ( `Mock answer ${ state . answers } .` , 5 ); 93if ( ! closed ) { 94send ({ choices :[{ delta :{}, finish_reason :"stop" }], usage :{ completion_tokens :12 } }); 95res . write ( "data: [DONE]\n\n" ); 96res . end (); 97state . completed ++ ; 98} 99}); 100await new Promise (( r ) => server . listen ( port , "127.0.0.1" , r )); 101return { 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 = {}) { 105const resolved = path . resolve ( f ); 106if ( root && ! resolved . startsWith ( path . resolve ( root ) + path . sep )) { res . writeHead ( 404 ); return res . end (); } 107fs . readFile ( resolved , ( err , data ) => { 108if ( err ) { res . writeHead ( 404 , { "Content-Type" :"application/json" }); return res . end ( '{"error":{"message":"not found"}}' ); } 109res . writeHead ( 200 , { "Content-Type" :TYPES [ path . extname ( resolved )] || "application/octet-stream" , "Cache-Control" :"no-cache" , ...extra }); 110res . end ( data ); 111}); 112} 113 114function metrics ( state ) { 115const spark = Array . from ({ length :30 }, ( _ , i ) => 20 + 10 * Math . sin ( i / 3 )); 116return { 117live :{ state :state . loaded ?"idle" :"unloaded" , queued :0 }, 118engine :{ model :"Mock-Model" , version :"0.0" , max_context :32768 , expert_slots :1200 , expert_cache_mib :9000 }, 119hardware :{ 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 }, 120hardware_static :{ gpu_name :"Mock GPU" , cpu_name :"Mock CPU" , threads :16 , cores :8 , psutil :true }, 121history :{ 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 }, 122requests :[], totals :null , requests_kept :0 , conversation_cache :null , 123}; 124} 125 126if ( process . argv [ 1 ] === fileURLToPath ( import . meta. url )) { 127const mock = await startMock ({ port :Number ( process . argv [ 2 ] || 0 ) }); 128console . log ( "mock server on " + mock . url ); 129}