okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
22a3d7068
main
1/** 2* #4878: a quiet desktop chat stream stays open. The chat answer is NDJSON; during a long silence (prompt processing, a tool, 3* an approval wait) a `{"type":"beat"}` frame goes out every 15 seconds so the web view does not drop the request at 60 s. 4* - the helper, with fake timers: a 60-second tool wait gives the beats, and the timer ends on finish, on close, on error and 5* on stop(), with no interval left behind; 6* - the real route, against a real host and a scripted API model that goes silent: beats arrive, a client that goes away 7* cancels the model request before the next beat, the next message works, and two chats stay independent. 8* The frontend consumer (src/lib/store.ts) has no branch for an unknown frame type, so `beat` changes nothing there; the last 9* test pins that. 10*/ 11import test from 'node:test' ; 12import assert from 'node:assert/strict' ; 13import { EventEmitter } from 'node:events' ; 14import { spawn , spawnSync } from 'node:child_process' ; 15import { mkdirSync , mkdtempSync , readFileSync , rmSync } from 'node:fs' ; 16import { createServer } from 'node:net' ; 17import { tmpdir } from 'node:os' ; 18import { join , resolve } from 'node:path' ; 19import { startScriptedWorker } from './helpers/scripted-worker.mjs' ; 20import { BEAT_MS , beatInterval , keepStreamAlive } from '../server/stream-beat.mjs' ; 21 22/** A response stand-in: records writes, emits finish/close like http.ServerResponse. */ 23function fakeResponse () { 24const res = new EventEmitter (); 25res . writes = []; 26res . writableEnded = false ; 27res . destroyed = false ; 28res . write = chunk => { res . writes . push ( String ( chunk )); return true ; }; 29res . end = () => { res . writableEnded = true ; res . emit ( 'finish' ); res . emit ( 'close' ); }; 30return res ; 31} 32const beats = res => res . writes . filter ( w => w === '{"type":"beat"}\n' ). length ; 33const listeners = res => [ 'finish' , 'close' , 'error' ]. reduce (( n , e ) => n + res . listenerCount ( e ), 0 ); 34 35test ( 'the interval is 15 s; a tester can shorten it; nonsense is the default' , () => { 36assert . equal ( BEAT_MS , 15_000 ); 37assert . equal ( beatInterval ({}), 15_000 ); 38assert . equal ( beatInterval ({ STRATA_STREAM_BEAT_MS :'200' }), 200 ); 39for ( const bad of [ '0' , '-5' , 'abc' , '' , '5' , '999999' , 'NaN' ]) assert . equal ( beatInterval ({ STRATA_STREAM_BEAT_MS :bad }), 15_000 , bad ); 40}); 41 42test ( 'a 60-second silent tool wait carries a beat every 15 s, each a whole NDJSON line' , t => { 43t . mock . timers . enable ({ apis :[ 'setInterval' ] }); 44const res = fakeResponse (); 45const stop = keepStreamAlive ( res ); 46t . mock . timers . tick ( 14_999 ); 47assert . equal ( beats ( res ), 0 , 'nothing before 15 s' ); 48t . mock . timers . tick ( 1 ); 49assert . equal ( beats ( res ), 1 ); 50t . mock . timers . tick ( 45_000 ); 51assert . equal ( beats ( res ), 4 , 'four beats in 60 s' ); 52for ( const w of res . writes ) assert . deepEqual ( JSON . parse ( w ), { type :'beat' }); 53assert . ok ( res . writes . every ( w => w . endsWith ( '\n' ) && w . indexOf ( '\n' ) === w . length - 1 )); 54stop (); 55}); 56 57test ( 'the timer is cleared on finish, on close, on error and by stop(): nothing beats afterwards, no listener is left' , t => { 58t . mock . timers . enable ({ apis :[ 'setInterval' ] }); 59for ( const how of [ 'finish' , 'close' , 'error' , 'stop' , 'end' ]) { 60const res = fakeResponse (); 61const stop = keepStreamAlive ( res ); 62t . mock . timers . tick ( 15_000 ); 63assert . equal ( beats ( res ), 1 , how ); 64if ( how === 'stop' ) stop (); else if ( how === 'end' ) res . end (); else res . emit ( how , new Error ( 'x' )); 65const after = res . writes . length ; 66t . mock . timers . tick ( 120_000 ); 67assert . equal ( res . writes . length , after , ` ${ how } : no beat after the end` ); 68assert . equal ( listeners ( res ), 0 , ` ${ how } : no listener left on the response` ); 69stop (); // calling it again is harmless 70} 71}); 72 73test ( 'a response that was destroyed or ended without an event is not written to, and its timer goes at the next tick' , t => { 74t . mock . timers . enable ({ apis :[ 'setInterval' ] }); 75const a = fakeResponse (); keepStreamAlive ( a ); a . destroyed = true ; 76const b = fakeResponse (); keepStreamAlive ( b ); b . writableEnded = true ; 77const c = fakeResponse (); keepStreamAlive ( c ); c . write = () => { throw new Error ( 'socket closed' ); }; 78t . mock . timers . tick ( 15_000 ); 79assert . equal ( a . writes . length + b . writes . length , 0 ); 80t . mock . timers . tick ( 120_000 ); 81assert . equal ( a . writes . length + b . writes . length , 0 ); 82assert . equal ( listeners ( a ) + listeners ( b ) + listeners ( c ), 0 ); 83}); 84 85test ( 'two responses beat independently: ending one leaves the other beating' , t => { 86t . mock . timers . enable ({ apis :[ 'setInterval' ] }); 87const one = fakeResponse (), two = fakeResponse (); 88keepStreamAlive ( one ); keepStreamAlive ( two ); 89t . mock . timers . tick ( 30_000 ); 90assert . equal ( beats ( one ), 2 ); assert . equal ( beats ( two ), 2 ); 91one . emit ( 'close' ); 92t . mock . timers . tick ( 30_000 ); 93assert . equal ( beats ( one ), 2 , 'the closed chat stops' ); 94assert . equal ( beats ( two ), 4 , 'the other keeps going' ); 95}); 96 97/* ---------------------------------------------------------------- the real route --- */ 98 99const HOST = resolve ( import . meta. dirname , '..' , 'server' , 'index.mjs' ); 100const freePort = () => new Promise ( r => { const s = createServer (); s . listen ( 0 , '127.0.0.1' , () => { const p = s . address (). port ; s . close (() => r ( p )); }); }); 101const sleep = ms => new Promise ( r => setTimeout ( r , ms )); 102const cleanup = dir => { try { rmSync ( dir , { recursive :true , force :true , maxRetries :3 }); } catch { /* best effort */ } }; 103 104async function setup ( t , beatMs ) { 105const worker = await startScriptedWorker ({ model :'cloud-model' }); 106const home = mkdtempSync ( join ( tmpdir (), 'strata-beat-' )); 107const ws = join ( home , 'workspace' ); mkdirSync ( ws , { recursive :true }); 108const port = await freePort (); 109const env = { 110 ...process . env , STRATA_HOME :home , STRATA_PORT :String ( port ), STRATA_WORKSPACE :ws , STRATA_REAL_ENGINE :'0' , 111STRATA_COMPONENTS_DIR :join ( home , 'components' ), STRATA_STREAM_BEAT_MS :String ( beatMs ), 112STRATA_SETTINGS_FILE :join ( home , 'app-settings.json' ), LOCALAPPDATA :join ( home , 'Local' ), APPDATA :join ( home , 'Roaming' ), 113XDG_DATA_HOME :join ( home , 'xdg-data' ), XDG_STATE_HOME :join ( home , 'xdg-state' ), XDG_CONFIG_HOME :join ( home , 'xdg-config' ), 114STRATA_SHARE_PORT :String ( await freePort ()), STRATA_TUNNEL_PORT :String ( await freePort ()), 115}; 116delete env . STRATA_HARNESS_DIR ; 117const child = spawn ( process . execPath , [ HOST ], { env, stdio :[ 'ignore' , 'pipe' , 'pipe' ], windowsHide :true }); 118let log = '' ; 119child . stdout . on ( 'data' , d => { log += d ; }); child . stderr . on ( 'data' , d => { log += d ; }); 120t . after ( async () => { 121if ( child . exitCode === null ) { 122if ( process . platform === 'win32' ) spawnSync ( 'taskkill' , [ '/PID' , String ( child . pid ), '/T' , '/F' ], { windowsHide :true }); 123else child . kill ( 'SIGTERM' ); 124await new Promise ( r => child . once ( 'exit' , r )); 125} 126await worker . close (); cleanup ( home ); 127}); 128const base = `http://127.0.0.1: ${ port } ` ; 129for ( let i = 0 ; i < 100 ; i ++ ) { 130try { if (( await fetch ( ` ${ base } /api/health` )). ok ) break ; } catch { /* not up yet */ } 131if ( child . exitCode !== null ) throw new Error ( `the host exited: ${ log . slice ( - 500 )} ` ); 132await sleep ( 100 ); 133} 134const saved = await fetch ( ` ${ base } /api/model-providers` , { method :'POST' , headers :{ 'content-type' :'application/json' }, body :JSON . stringify ({ kind :'custom' , name :'Scripted API' , baseUrl :worker . url , protocol :'openai-chat' , apiKey :'sk-host-test-0123456789' , models :[{ id :'cloud-model' , name :'Cloud model' , contextMax :64000 }] }) }); 135assert . equal ( saved . status , 200 ); 136const connectionId = ( await saved . json ()). connections [ 0 ]. id ; 137const remoteModel = { connectionId, modelId :'cloud-model' }; 138/** Open a chat stream; frames are handed to onFrame as they arrive; abort() drops the connection like a client that left. */ 139const chat = ( sessionId , message , onFrame = () => {}) => { 140const controller = new AbortController (); 141const frames = []; 142const done = ( async () => { 143const res = await fetch ( ` ${ base } /api/chat/stream` , { method :'POST' , headers :{ 'content-type' :'application/json' }, signal :controller . signal , body :JSON . stringify ({ sessionId, message, remoteModel, history :[], agent :false }) }); 144assert . equal ( res . status , 200 ); 145let buffer = '' ; 146const decoder = new TextDecoder (); 147for await ( const chunk of res . body ) { 148buffer += decoder . decode ( chunk , { stream :true }); 149let i ; 150while (( i = buffer . indexOf ( '\n' )) >= 0 ) { const line = buffer . slice ( 0 , i ). trim (); buffer = buffer . slice ( i + 1 ); if ( line ) { const f = JSON . parse ( line ); frames . push ( f ); onFrame ( f ); } } 151} 152return frames ; 153})(); 154return { frames, done, abort :() => controller . abort () }; 155}; 156return { worker, chat, alive :() => child . exitCode === null , log :() => log }; 157} 158const until = async ( fn , ms = 8000 ) => { const end = Date . now () + ms ; while ( Date . now () < end ) { if ( fn ()) return true ; await sleep ( 25 ); } return false ; }; 159 160test ( 'route: a silent API model gets beats; a client that leaves cancels the model request before the next beat' , { timeout :40_000 }, async t => { 161const s = await setup ( t , 300 ); 162let first = null ; 163const quiet = s . chat ( 'chat-beat-a' , 'SCRIPT:hang' , f => { if ( f . type === 'beat' && first === null ) first = Date . now (); }); 164assert . ok ( await until (() => quiet . frames . filter ( f => f . type === 'beat' ). length >= 2 ), 'two beats while the model says nothing' ); 165const framesBefore = quiet . frames . length ; 166quiet . abort (); 167await assert . rejects ( quiet . done , { name :'AbortError' }); 168// the next beat is 300 ms away: the model request must already be cancelled well before it 169assert . ok ( await until (() => s . worker . aborted >= 1 , 1500 ), 'disconnect cancelled the direct model request' ); 170assert . ok ( framesBefore >= 2 ); 171const next = s . chat ( 'chat-beat-a' , 'SCRIPT:echo still works' ); 172const frames = await next . done ; 173assert . equal ( frames . filter ( f => f . type === 'delta' ). map ( f => f . text ). join ( '' ), 'still works' ); 174assert . equal ( frames . at ( - 1 ). type , 'done' ); 175assert . ok ( s . alive (), 'the host is alive' ); 176}); 177 178test ( 'route: two chats at once are independent; leaving one does not touch the other' , { timeout :40_000 }, async t => { 179const s = await setup ( t , 250 ); 180const a = s . chat ( 'chat-beat-1' , 'SCRIPT:hang' ); 181const b = s . chat ( 'chat-beat-2' , 'SCRIPT:hang' ); 182const count = c => c . frames . filter ( f => f . type === 'beat' ). length ; 183assert . ok ( await until (() => count ( a ) >= 2 && count ( b ) >= 2 ), 'both beat' ); 184a . abort (); 185await assert . rejects ( a . done , { name :'AbortError' }); 186assert . ok ( await until (() => s . worker . aborted === 1 , 1500 ), 'exactly the one request was cancelled' ); 187const frozen = count ( a ); 188const bBefore = count ( b ); 189assert . ok ( await until (() => count ( b ) >= bBefore + 2 ), 'the other chat keeps getting beats' ); 190assert . equal ( count ( a ), frozen , 'the chat that left gets nothing more' ); 191assert . equal ( s . worker . aborted , 1 , 'the other model request was not cancelled' ); 192b . abort (); 193await assert . rejects ( b . done , { name :'AbortError' }); 194assert . ok ( await until (() => s . worker . aborted === 2 , 1500 )); 195assert . ok ( s . alive ()); 196}); 197 198test ( 'route: a normal answer is unchanged (beats only fill silence) and the stream still ends' , { timeout :40_000 }, async t => { 199const s = await setup ( t , 20_000 ); // longer than the test: no beat should appear in a fast answer 200const frames = await s . chat ( 'chat-beat-fast' , 'SCRIPT:echo hello there' ). done ; 201assert . equal ( frames . filter ( f => f . type === 'delta' ). map ( f => f . text ). join ( '' ), 'hello there' ); 202assert . equal ( frames . filter ( f => f . type === 'beat' ). length , 0 ); 203assert . equal ( frames . at ( - 1 ). type , 'done' ); 204}); 205 206test ( 'the desktop consumer ignores a frame type it does not know (so beat changes nothing there)' , () => { 207const store = readFileSync ( resolve ( import . meta. dirname , '..' , 'src' , 'lib' , 'store.ts' ), 'utf8' ); 208const start = store . indexOf ( "if (type === 'delta' || type === 'reasoning') { queueText" ); 209const doneAt = store . indexOf ( "} else if (type === 'done') {" , start ); 210assert . ok ( start > 0 && doneAt > start , 'found the frame handler' ); 211// the chain is if / else if only and its last branch is `done`: no final `else` follows it, so an unknown type falls through silently 212assert . match ( store . slice ( doneAt , doneAt + 2500 ), / flushSessions\(\);\s * \}\s * \}, / ); 213assert . ok ( ! store . slice ( start , doneAt ). includes ( "type === 'beat'" ), 'no special case is needed' ); 214const client = readFileSync ( resolve ( import . meta. dirname , '..' , 'src' , 'lib' , 'client.ts' ), 'utf8' ); 215assert . match ( client , / onFrame\(JSON\.parse\(line\) / ); 216});