okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ffb3d9b31
main
1import { ROOMY_HOST } from './helpers/hardware.mjs' ; // the demo model loads whatever the memory of the PC running the test (a 7 GB Mac runner did not) 2import assert from 'node:assert/strict' ; 3import { test } from 'node:test' ; 4import http from 'node:http' ; 5import { mkdtemp , mkdir , readFile , writeFile , rm } from 'node:fs/promises' ; 6import { tmpdir } from 'node:os' ; 7import { join } from 'node:path' ; 8import { spawn } from 'node:child_process' ; 9import { transform } from 'esbuild' ; 10import { RequestQueue } from '../server/request-queue.mjs' ; 11import { selectSkills , skillInstructions } from '../server/skill-selection.mjs' ; 12 13const wait = ms => new Promise ( resolve => setTimeout ( resolve , ms )); 14const listen = server => new Promise ( resolve => server . listen ( 0 , '127.0.0.1' , () => resolve ( server . address (). port ))); 15const close = server => new Promise ( resolve => server . close ( resolve )); 16 17test ( 'a cancelled queued request never executes or interrupts the active task' , async () => { 18const queue = new RequestQueue (); 19const active = new AbortController (), queued = new AbortController (); 20let finish , ran = false ; 21const first = queue . run ( active . signal , () => new Promise ( resolve => { finish = resolve ; })); 22const second = queue . run ( queued . signal , () => { ran = true ; }); 23assert . equal ( queue . waiting , 1 ); 24queued . abort (); 25await assert . rejects ( second , { name :'AbortError' }); 26assert . equal ( ran , false ); assert . equal ( active . signal . aborted , false ); 27finish ( 'done' ); assert . equal ( await first , 'done' ); 28assert . equal ( await queue . run ( new AbortController (). signal , () => 'next' ), 'next' ); 29}); 30 31test ( 'skill instructions require both enabled state and a matching workspace' , () => { 32const skills = [ 33{ id :'global' , name :'Global review' , enabled :true , triggers :[ 'review' ], body :'Check correctness.' }, 34{ id :'scoped' , name :'Local review' , enabled :true , onlyIn :'a' , triggers :[ 'review' ], body :'Check project rules.' }, 35{ id :'disabled' , name :'Disabled' , enabled :false , onlyIn :'a' , triggers :[ 'review' ], body :'Never inject me.' }, 36]; 37assert . deepEqual ( selectSkills ( skills , 'review this' , 'a' ). map ( s => s . id ), [ 'global' , 'scoped' ]); 38assert . deepEqual ( selectSkills ( skills , 'review this' , 'b' ). map ( s => s . id ), [ 'global' ]); 39assert . deepEqual ( selectSkills ( skills , 'hello' , 'a' ), []); 40assert . match ( skillInstructions ( selectSkills ( skills , 'review this' , 'a' )), / Check project rules / ); 41}); 42 43test ( 'stream usage comes from the server, includes reasoning latency and preserves instructions' , async () => { 44const home = await mkdtemp ( join ( tmpdir (), 'strata-stream-test-' )); 45process . env . STRATA_HOME = home ; 46process . env . STRATA_MODELS_DIR = join ( home , 'models' ); 47const { proxyCompletion} = await import ( '../server/inference.mjs' ); 48let request ; 49const fixture = http . createServer ( async ( req , res ) => { 50let body = '' ; for await ( const chunk of req ) body += chunk ; 51request = JSON . parse ( body ); 52res . writeHead ( 200 , { 'content-type' :'text/event-stream' }); 53// Deliberately split one SSE line and finish without a trailing newline. 54res . write ( 'data: {"choices":[{"delta":{"reasoning_content":"Check it"}}]}\n\n' ); 55await wait ( 20 ); 56res . write ( 'data: {"choices":[{"delta":{"content":"Several words in a single' ); 57res . write ( ' chunk"}}]}\n\n' ); 58res . end ( 'data: {"choices":[],"usage":{"prompt_tokens":31,"completion_tokens":9,"prompt_tokens_details":{"cached_tokens":7}}}' ); 59}); 60const port = await listen ( fixture ); 61try { 62const frames = []; 63const result = await proxyCompletion ({ baseUrl :`http://127.0.0.1: ${ port } ` , message :'review' , history :[{ role :'system' , content :'Client instruction' }], systemPrompt :'Skill: review\nCheck correctness.' , onFrame :f => frames . push ( f ), signal :new AbortController (). signal }); 64assert . equal ( result . tokensOut , 9 ); assert . equal ( result . tokensIn , 31 ); assert . equal ( result . cachedTokens , 7 ); 65assert . equal ( result . usageSource , 'reported' ); assert . ok ( result . ttftMs < result . durationMs ); 66assert . match ( request . messages [ 0 ]. content , / Check correctness / ); assert . equal ( request . messages [ 1 ]. content , 'Client instruction' ); 67assert . equal ( frames . filter ( f => f . type === 'delta' ). length , 1 ); 68} finally { await close ( fixture ); await rm ( home , { recursive :true , force :true }); } 69}); 70 71test ( 'a stream without usage never presents chunks as tokens' , async () => { 72const { proxyCompletion} = await import ( '../server/inference.mjs' ); 73const fixture = http . createServer (( req , res ) => { req . resume (); res . writeHead ( 200 , { 'content-type' :'text/event-stream' }); res . end ( 'data: {"choices":[{"delta":{"content":"many words"}}]}\n\ndata: [DONE]\n\n' ); }); 74const port = await listen ( fixture ); 75try { 76const result = await proxyCompletion ({ baseUrl :`http://127.0.0.1: ${ port } ` , message :'hello' , onFrame :() => {}, signal :new AbortController (). signal }); 77assert . equal ( result . tokensIn , null ); assert . equal ( result . tokensOut , null ); assert . equal ( result . tps , null ); assert . equal ( result . usageSource , 'unavailable' ); 78} finally { await close ( fixture ); } 79}); 80 81test ( 'Serving cancellation stops active and queued demo requests; test keys enforce access' , { timeout :90000 }, async () => { 82const home = await mkdtemp ( join ( tmpdir (), 'strata-request-host-' )); 83await mkdir ( join ( home , 'data' )); 84const id = 'qwen38-q4_k_m' ; 85await writeFile ( join ( home , 'data/state.json' ), JSON . stringify ({ installed :{ [ id ] :{ installedAt :new Date (). toISOString (), bytes :491400032 , simulated :true } }, beginner :{ priority :'balanced' , contextLength :'32k' , readImages :false , gpuIdle :'never' }, current :id , loaded :id })); 86const socket = http . createServer (); const port = await listen ( socket ); await close ( socket ); 87const host = spawn ( process . execPath , [ 'server/index.mjs' ], { cwd :join ( import . meta. dirname , '..' ), env :{ ...process . env , STRATA_HOME :home , STRATA_MODELS_DIR :join ( home , 'models' ), STRATA_PORT :String ( port ), STRATA_REAL_ENGINE :'0' , STRATA_TEST_HARDWARE :ROOMY_HOST }, stdio :'ignore' }); 88const base = `http://127.0.0.1: ${ port } ` ; 89const call = async ( path , method = 'GET' , body , key ) => { 90const res = await fetch ( base + path , { method, headers :{ 'content-type' :'application/json' , ...( key ?{ authorization :`Bearer ${ key } ` } :{}) }, body :body ?JSON . stringify ( body ) :undefined }); 91return { status :res . status , data :await res . json () }; 92}; 93try { 94// A host started on a loaded computer can take many seconds to listen; wait for it, and say so if it never does (a 4 s wait made this test flaky). 95let up = false ; 96for ( let i = 0 ; i < 600 && ! up ; i ++ ) { try { up = ( await call ( '/api/health' )). status === 200 ; } catch {} if ( ! up ) await wait ( 50 ); } 97assert . ok ( up , 'the host did not start listening within 30 s' ); 98const stream = () => fetch ( base + '/api/chat/stream' , { method :'POST' , headers :{ 'content-type' :'application/json' }, body :JSON . stringify ({ message :'Explain this test in detail' }) }). then ( r => r . text ()); 99const first = stream (); await wait ( 100 ); const second = stream (); await wait ( 100 ); 100let rows = ( await call ( '/api/serving' )). data . requests ; 101const active = rows . find ( r => r . state === 'generating' ), queued = rows . find ( r => r . state === 'queued' ); 102assert . ok ( active ); assert . ok ( queued ); 103await call ( `/api/serving/requests/ ${ queued . id } /cancel` , 'POST' ); 104const secondFrames = ( await second ). trim (). split ( '\n' ). map ( JSON . parse ); 105assert . equal ( secondFrames . some ( f => f . type === 'done' ), false ); assert . ok ( secondFrames . some ( f => f . type === 'error' )); 106rows = ( await call ( '/api/serving' )). data . requests ; 107assert . equal ( rows . find ( r => r . id === active . id ). state , 'generating' ); 108await call ( `/api/serving/requests/ ${ active . id } /cancel` , 'POST' ); 109const firstFrames = ( await first ). trim (). split ( '\n' ). map ( JSON . parse ); 110assert . equal ( firstFrames . some ( f => f . type === 'done' ), false ); assert . ok ( firstFrames . some ( f => f . type === 'error' )); 111rows = ( await call ( '/api/serving' )). data . requests ; 112assert . ok ( rows . every ( r => r . state === 'error' && ! r . cancellable && r . durationMs > 0 )); 113await call ( '/api/serving' , 'PATCH' , { apiKey :'disposable-test-key' }); 114assert . equal (( await call ( '/v1/models' )). status , 401 ); 115assert . equal (( await call ( '/v1/models' , 'GET' , undefined , 'disposable-test-key' )). status , 200 ); 116await call ( '/api/serving' , 'PATCH' , { apiKey :null }); 117assert . equal (( await call ( '/v1/models' )). status , 200 ); 118} finally { 119const ended = new Promise ( resolve => host . once ( 'exit' , resolve )); host . kill ( 'SIGTERM' ); await ended ; 120await rm ( home , { recursive :true , force :true }); 121} 122}); 123 124// Reproduces the browser-observed race: final SSE event arrives before the 125// slower HTTP response carrying the earlier Cancelling state. 126test ( 'a late cancel response cannot overwrite a completed request event' , async () => { 127const source = await readFile ( new URL ( '../src/lib/serving-state.ts' , import . meta. url ), 'utf8' ); 128const compiled = await transform ( source , { loader :'ts' , format :'esm' }); 129const { newestServingState} = await import ( `data:text/javascript;base64, ${ Buffer . from ( compiled . code ). toString ( 'base64' )} ` ); 130const cancelling = { revision :100 , requests :[{ state :'generating' , cancelRequested :true }] }; 131const completed = { revision :101 , requests :[{ state :'error' , cancellable :false }] }; 132assert . equal ( newestServingState ( completed , cancelling ), completed ); 133assert . equal ( newestServingState ( cancelling , completed ), completed ); 134assert . equal ( newestServingState ( null , completed ), completed ); 135});