okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
326e39118
main
1#!/usr/bin/env node 2/** 3* Prove the INSTALLED app layout can start and stop an engine with nothing acquired, using a stub engine. 4* 5* node apps/desktop/scripts/installed-flow.mjs --install <folder the installer wrote> [--work <scratch>] [--spy <acquire-spy.mjs>] 6* 7* It starts the installed host with the installed node.exe exactly as the Tauri shell does (STRATA_PACKAGED=1, 8* STRATA_NO_ACQUIRE=1; Control found beside the host), against a scratch component folder holding a fake engine 9* package and a scratch install folder holding one run config. Everything per-user (profiles, runtime state, host data, 10* components) lives under --work, so the real profile of whoever runs this is never read or written. 11* 12* Steps (each one printed, the run exits 1 if any fails): 13* host health, Control status (engine usable, acquiring forbidden), models from Control, load through the host 14* (profile + `runtime start` under the owner runtime), a chat answer from the stub engine, a second client attaches to 15* the same owner/instance, unload stops it, no engine for this PC is a notice with nothing started, the Tauri-style 16* clean shutdown stops the engines the host started, a hard-killed host takes its engine with it. 17* With --spy the host runs under tests/helpers/acquire-spy.mjs and the run fails on any attempt to reach the internet or 18* run an installer. 19* 20* REAL mode (a test box with a GPU): --components <folder holding engine/<package>> --models <folder with strata-<id>.json 21* whose engine is "component:strata-engine"> --model <id> [--backend cuda]. The same host and Control, a real engine and a 22* real model: load, a real answer, ownership, unload, the missing-engine notice, load again, clean shutdown. The stub-only 23* steps (the marker file, the hard-kill report) are left out. 24*/ 25import { spawn , spawnSync } from 'node:child_process' ; 26import { createHash , randomBytes } from 'node:crypto' ; 27import { existsSync , mkdirSync , mkdtempSync , readFileSync , readdirSync , renameSync , rmSync , writeFileSync , chmodSync } from 'node:fs' ; 28import { createServer } from 'node:net' ; 29import { tmpdir } from 'node:os' ; 30import { join , resolve } from 'node:path' ; 31import { pathToFileURL } from 'node:url' ; 32 33const args = Object . fromEntries ( process . argv . slice ( 2 ). reduce (( acc , a , i , all ) => ( a . startsWith ( '--' ) ?[ ...acc , [ a . slice ( 2 ), all [ i + 1 ]?. startsWith ( '--' ) || all [ i + 1 ] === undefined ?true :all [ i + 1 ]]] :acc ), [])); 34if ( ! args . install ) { console . error ( 'usage: installed-flow.mjs --install <folder> [--work <dir>] [--spy <acquire-spy.mjs>]' ); process . exit ( 2 ); } 35const install = resolve ( args . install ); 36const isWin = process . platform === 'win32' ; 37const node = join ( install , 'node' , isWin ?'node.exe' :'node' ); 38const hostEntry = join ( install , 'host' , 'server' , 'index.mjs' ); 39const controlDir = join ( install , 'control' ); 40const python = isWin ?join ( controlDir , 'python' , 'python.exe' ) :join ( controlDir , 'python' , 'bin' , 'python3' ); 41const real = !! args . components ; 42const modelId = String ( args . model ?? 'stub' ); 43const work = resolve ( args . work ?? mkdtempSync ( join ( tmpdir (), 'strata-installed-flow-' ))); 44mkdirSync ( work , { recursive :true }); 45const dirs = { components :real ?resolve ( args . components ) :join ( work , 'components' ), models :real ?resolve ( args . models ) :join ( work , 'models' ), profiles :join ( work , 'profiles' ), runtime :join ( work , 'runtime' ), home :join ( work , 'home' ) }; 46// the runtime and profile folders are created by Control itself, with the owner-only ACL it insists on 47for ( const [ name , d ] of Object . entries ( dirs )) if ( ! [ 'runtime' , 'profiles' ]. includes ( name ) && ! ( real && [ 'components' , 'models' ]. includes ( name ))) mkdirSync ( d , { recursive :true }); 48 49const steps = []; 50const record = ( name , ok , detail = '' ) => { steps . push ({ name, ok :!! ok , detail :String ( detail ) }); console . log ( ` ${ ok ? 'ok ' : 'FAIL' } ${ name } ${ detail ? ' ' + detail : '' } ` ); }; 51const delay = ms => new Promise ( r => setTimeout ( r , ms )); 52const freePort = async () => { const s = createServer (); await new Promise ( r => s . listen ( 0 , '127.0.0.1' , r )); const p = s . address (). port ; await new Promise ( r => s . close ( r )); return p ; }; 53const sha = buf => createHash ( 'sha256' ). update ( buf ). digest ( 'hex' ); 54 55// ------------------------------------------------------------------------------ fixtures 56const baseEnv = { 57 ...process . env , 58STRATA_COMPONENTS_DIR :dirs . components , STRATA_PROFILE_DIR :dirs . profiles , STRATA_RUNTIME_DIR :dirs . runtime , 59STRATA_INSTALL_DIR :dirs . models , STRATA_ENGINE_BACKEND :String ( args . backend ?? 'cuda' ), STRATA_HOME :dirs . home , STRATA_MODELS_DIR :real ?join ( work , 'models-unused' ) :dirs . models , 60APPDATA :join ( work , 'appdata' ), XDG_CONFIG_HOME :join ( work , 'xdg' ), PYTHONDONTWRITEBYTECODE :'1' , 61}; 62delete baseEnv . STRATA_API_KEY ; 63mkdirSync ( baseEnv . APPDATA , { recursive :true }); 64const mark = join ( work , 'engine-ran.json' ); 65 66const FAKE_ENGINE = `import os, sys, json 67from pathlib import Path 68Path(os.environ['FAKE_ENGINE_MARK']).write_text(json.dumps({'pid': os.getpid(), 'script': os.path.abspath(__file__), 'argv': sys.argv[1:]})) 69print('READY 4096 stop', flush=True) 70for line in sys.stdin: 71if line.strip() == 'QUIT': break 72if line.startswith(('GEN ', 'BGEN ')): 73slot = int(line.split()[1]) if line.startswith('BGEN ') else None 74print('T 97', flush=True) 75print('DONE 1 1 1.0 1.0 length 0 0 0', flush=True) 76if slot is not None: print(f'BADM {slot} 0', flush=True) 77` ; 78 79function installFakeEngine () { 80const platform = isWin ?'windows-x86_64' :'linux-x86_64' ; 81const folder = join ( dirs . components , 'engine' , `0.1.45- ${ platform } -cuda` ); 82mkdirSync ( folder , { recursive :true }); 83writeFileSync ( join ( folder , 'engine_main.py' ), FAKE_ENGINE ); 84const entry = isWin ?'engine.cmd' :'engine' ; 85writeFileSync ( join ( folder , entry ), isWin 86 ?`@echo off\r\n" ${ python } " "%~dp0engine_main.py" %*\r\n` 87 :`#!/bin/sh\nexec " ${ python } " "$(dirname "$0")/engine_main.py" "$@"\n` ); 88if ( ! isWin ) chmodSync ( join ( folder , entry ), 0o755 ); 89const files = [ entry , 'engine_main.py' ]. map ( p => { const b = readFileSync ( join ( folder , p )); return { path :p , sha256 :sha ( b ), bytes :b . length }; }); 90writeFileSync ( join ( folder , 'engine-component.json' ), JSON . stringify ({ schema_version :1 , id :'strata-engine' , version :'0.1.45' , platform, backend :'cuda' , entrypoint :entry , files})); 91return folder ; 92} 93 94function makeTokenizerAndConfig () { 95const tok = join ( dirs . models , 'tokenizer' ); 96mkdirSync ( tok , { recursive :true }); 97const script = `import json, sys\nfrom tools.strata_tokenizer import BYTE_TO_UNICODE\ntok = sys.argv[1]\ntokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ['ab', '<|im_start|>', '<|im_end|>', '<|endoftext|>']\njson.dump({t: i for i, t in enumerate(tokens)}, open(tok + '/vocab.json', 'w'))\nopen(tok + '/merges.txt', 'w').write('a b')\njson.dump([0] * 257 + [3, 3, 3], open(tok + '/token_type.json', 'w'))\n` ; 98const done = spawnSync ( python , [ '-c' , script , tok ], { cwd :controlDir , env :{ ...baseEnv , PYTHONNOUSERSITE :'1' }, encoding :'utf8' }); 99if ( done . status !== 0 ) throw new Error ( 'tokenizer fixture failed: ' + done . stderr ); 100writeFileSync ( join ( dirs . models , 'strata-stub.json' ), JSON . stringify ({ exe :'component:strata-engine' , backend :'cuda' , tokenizer :tok , args :[], cwd :work , model_name :'stub' , host :'127.0.0.1' , port :0 })); 101} 102 103const control = ( ...argv ) => spawnSync ( python , [ join ( controlDir , 'strata.py' ), ...argv , '--output' , 'json' ], { cwd :controlDir , env :{ ...baseEnv , PYTHONNOUSERSITE :'1' , STRATA_NO_ACQUIRE :'1' , FAKE_ENGINE_MARK :mark }, encoding :'utf8' , timeout :120000 }); 104const controlJson = ( ...argv ) => { const r = control ( ...argv ); let json = null ; try { json = JSON . parse ( r . stdout . slice ( r . stdout . indexOf ( '{' ))); } catch { /* not json */ } return { code :r . status , json, text :r . stdout + r . stderr }; }; 105const alive = pid => { try { process . kill ( pid , 0 ); return true ; } catch { return false ; } }; 106 107// ------------------------------------------------------------------------------ the host 108let host = null , port = 0 , base = '' , spyLog = null , shutdownToken = randomBytes ( 32 ). toString ( 'hex' ); 109async function startHost () { 110port = await freePort (); base = `http://127.0.0.1: ${ port } ` ; 111const hostArgs = [ ...( args . spy ?[ '--import' , pathToFileURL ( resolve ( args . spy )). href ] :[]), hostEntry ]; 112if ( args . spy ) { spyLog = join ( work , 'acquire-spy.log' ); writeFileSync ( spyLog , '' ); } 113host = spawn ( node , hostArgs , { 114cwd :join ( install , 'host' ), stdio :[ 'ignore' , 'pipe' , 'pipe' ], windowsHide :true , 115env :{ ...baseEnv , STRATA_PORT :String ( port ), STRATA_DIST :join ( install , 'host' , 'dist' ), NODE_ENV :'production' , STRATA_PACKAGED :'1' , STRATA_REAL_ENGINE :'1' , 116STRATA_NO_ACQUIRE :'1' , STRATA_SHUTDOWN_TOKEN :shutdownToken , FAKE_ENGINE_MARK :mark , STRATA_SHARE_PORT :String ( await freePort ()), STRATA_TUNNEL_PORT :String ( await freePort ()), 117 ...( spyLog ?{ ACQUIRE_SPY_LOG :spyLog } :{}) }, 118}); 119let log = '' ; 120host . stdout . on ( 'data' , c => { log += c ; }); host . stderr . on ( 'data' , c => { log += c ; }); 121host . hostLog = () => log ; 122for ( let i = 0 ; i < 200 ; i ++ ) { try { if (( await fetch ( base + '/api/health' )). ok ) return true ; } catch { /* not yet */ } await delay ( 150 ); } 123return false ; 124} 125/** The host started the way the Tauri shell starts it, by a stand-in shell (a node process) that can then be killed hard. */ 126async function startHostViaShell () { 127port = await freePort (); base = `http://127.0.0.1: ${ port } ` ; 128const spec = { command :node , args :[ hostEntry ], options :{ 129cwd :join ( install , 'host' ), stdio :'ignore' , windowsHide :true , 130env :{ ...baseEnv , STRATA_PORT :String ( port ), STRATA_DIST :join ( install , 'host' , 'dist' ), NODE_ENV :'production' , STRATA_PACKAGED :'1' , STRATA_REAL_ENGINE :'1' , 131STRATA_NO_ACQUIRE :'1' , STRATA_SHUTDOWN_TOKEN :shutdownToken , STRATA_EXIT_WITH_PARENT :'1' , FAKE_ENGINE_MARK :mark , 132STRATA_SHARE_PORT :String ( await freePort ()), STRATA_TUNNEL_PORT :String ( await freePort ()) } } }; 133const shell = spawn ( node , [ '-e' , "const s=JSON.parse(process.env.HOST_SPEC);const c=require('node:child_process').spawn(s.command,s.args,s.options);console.log(c.pid);setInterval(()=>{},1000);" ], 134{ env :{ ...process . env , HOST_SPEC :JSON . stringify ( spec ) }, stdio :[ 'ignore' , 'pipe' , 'inherit' ], windowsHide :true }); 135const hostPid = await new Promise ( r => shell . stdout . once ( 'data' , c => r ( Number ( String ( c ). trim ())))); 136for ( let i = 0 ; i < 200 ; i ++ ) { try { if (( await fetch ( base + '/api/health' )). ok ) return { shell, hostPid}; } catch { /* not yet */ } await delay ( 150 ); } 137return { shell, hostPid, failed :true }; 138} 139const call = async ( path , method = 'GET' , body ) => { 140const response = await fetch ( base + path , { method, headers :{ 'content-type' :'application/json' }, body :body === undefined ?undefined :JSON . stringify ( body ) }); 141return { status :response . status , body :await response . json (). catch (() => null ) }; 142}; 143async function waitJob ( id , seconds = 120 ) { 144for ( let i = 0 ; i < seconds * 5 ; i ++ ) { 145const state = ( await call ( '/api/native' )). body ; 146const job = state . jobs . find ( j => j . id === id ); 147if ( job && job . state !== 'running' ) return { job, state}; 148await delay ( 200 ); 149} 150throw new Error ( 'operation did not finish' ); 151} 152async function stopHost ( hard = false ) { 153if ( ! host || host . exitCode !== null ) return ; 154if ( hard ) { if ( isWin ) spawnSync ( 'taskkill' , [ '/PID' , String ( host . pid ), '/T' , '/F' ], { windowsHide :true }); else host . kill ( 'SIGKILL' ); } 155else host . kill (); 156for ( let i = 0 ; i < 100 && host . exitCode === null ; i ++ ) await delay ( 100 ); 157} 158 159async function main () { 160for ( const need of [ node , hostEntry , python , join ( controlDir , 'strata.py' )]) if ( ! existsSync ( need )) { record ( 'installed layout' , false , `missing ${ need } ` ); return ; } 161record ( 'installed layout' , true , install ); 162if ( real ) { 163const packages = existsSync ( join ( dirs . components , 'engine' )) ?readdirSync ( join ( dirs . components , 'engine' )) :[]; 164record ( 'fixtures' , packages . length > 0 && existsSync ( join ( dirs . models , `strata- ${ modelId } .json` )), `engine package(s) ${ packages . join ( ', ' )} in ${ dirs . components } ; run config strata- ${ modelId } .json in ${ dirs . models } ` ); 165} else { 166installFakeEngine (); 167makeTokenizerAndConfig (); 168record ( 'fixtures' , true , `stub engine package in ${ dirs . components } ; run config strata-stub.json` ); 169} 170 171if ( ! ( await startHost ())) { record ( 'host healthy' , false , host . hostLog (). slice ( - 600 )); return ; } 172record ( 'host healthy' , true , base ); 173 174const status = ( await call ( '/api/control/status' )). body ; 175record ( 'Control status: bundled, engine usable, acquiring forbidden' , status . control ?. python ?. startsWith ( controlDir ) && status . engine ?. usable === true && status . acquisition ?. forbidden === true , 176`python= ${ status . control ?. python } ; engine= ${ status . engine ?. engine ?. version } ; forbidden= ${ status . acquisition ?. forbidden } ` ); 177 178const native = ( await call ( '/api/native?refresh=1' )). body ; 179const model = native . installed ?. models ?. find ( m => m . model === modelId ); 180record ( 'models come from Control' , native . available && model ?. ready === true && native . packaged === true , `available= ${ native . available } ; model ready= ${ model ?. ready } ; ${ native . summary ?? native . error } ` ); 181 182// ---- load 183const started = ( await call ( '/api/native/operations' , 'POST' , { kind :'load' , args :{ model :modelId } })). body ; 184const loaded = await waitJob ( started . id , 400 ); 185const instance = loaded . state . instances [ 0 ]; 186record ( 'load through the host starts the engine under Control' , loaded . job . state === 'done' && instance ?. status === 'ready' , `job= ${ loaded . job . state } ${ loaded . job . error ?? '' } ; instance= ${ instance ?. status } ` ); 187let ran = existsSync ( mark ) ?JSON . parse ( readFileSync ( mark , 'utf8' )) :null ; 188if ( real ) { 189const listed = spawnSync ( 'ps' , [ '-eo' , 'pid,args' ], { encoding :'utf8' }). stdout . split ( '\n' ). filter ( l => l . includes ( ` ${ dirs . components } /engine/` ) && l . includes ( '--serve' )); 190ran = listed . length ?{ pid :Number ( listed [ 0 ]. trim (). split ( / \s +/ )[ 0 ]), script :listed [ 0 ]. trim (). split ( / \s +/ )[ 1 ] } :null ; 191record ( 'the engine process running is the binary from the component folder' , !! ran , listed [ 0 ] ?listed [ 0 ]. trim (). slice ( 0 , 160 ) :'no engine process under the component folder' ); 192} else { 193record ( 'the engine that ran is the one in the component folder' , ran && ran . script . toLowerCase (). startsWith ( dirs . components . toLowerCase ()), ran ?. script ?? 'engine never ran' ); 194} 195 196const runtime = controlJson ( 'runtime' , 'status' , '--profile' , 'app-1' ); 197record ( 'a second client sees the same owner and instance (ownership)' , runtime . json ?. state === 'ready' && !! runtime . json . owner_id && !! runtime . json . instance_id && runtime . json . host_pid !== host . pid , 198`state= ${ runtime . json ?. state } ; owner= ${ String ( runtime . json ?. owner_id ). slice ( 0 , 8 )} ; instance= ${ String ( runtime . json ?. instance_id ). slice ( 0 , 8 )} ; owner host pid ${ runtime . json ?. host_pid } is not the app host ( ${ host . pid } )` ); 199 200// ---- answer 201const chat = await call ( '/v1/chat/completions' , 'POST' , real 202 ?{ model :instance ?. apiModelId ?? modelId , messages :[{ role :'user' , content :'Reply with exactly one word: pong' }], max_tokens :200 , temperature :0 , reasoning_effort :'none' , stream :false } 203 :{ model :instance ?. apiModelId ?? modelId , messages :[{ role :'user' , content :'hi' }], max_tokens :4 , stream :false }); 204const message = chat . body ?. choices ?.[ 0 ]?. message ?? {}; 205const answer = ` ${ message . content ?? '' } ${ message . reasoning_content ?? '' } ` ; // the stub emits token 97 ("a"); the server files it as reasoning 206record ( real ?'the real model answers through the host (the answer text is checked)' :'the engine answers through the host (the stub token, not an error)' , 207chat . status === 200 && ( real ?/ pong / i . test ( answer ) :answer === 'a' ), `status= ${ chat . status } ; answer= ${ JSON . stringify ( answer . slice ( 0 , 200 ))} ${ chat . status === 200 ? '' : ' ' + JSON . stringify ( chat . body ). slice ( 0 , 160 )} ` ); 208 209// ---- unload 210const unloaded = await call ( `/api/native/instances/ ${ instance . id } /unload` , 'POST' , {}); 211await delay ( 500 ); 212const after = controlJson ( 'runtime' , 'status' , '--profile' , 'app-1' ); 213for ( let i = 0 ; i < 100 && ran && alive ( ran . pid ); i ++ ) await delay ( 100 ); // a real engine takes a moment to release the GPU 214record ( 'unload stops the engine' , unloaded . status === 200 && after . json ?. state === 'stopped' && ( ! ran || ! alive ( ran . pid )), `status= ${ unloaded . status } ; runtime= ${ after . json ?. state } ; engine pid ${ ran ?. pid } alive= ${ ran ? alive ( ran . pid ) : 'n/a' } ` ); 215 216// ---- no engine for this PC 217const hidden = join ( dirs . components , real ?'engine.hidden-by-flow' :'engine.gone' ); 218renameSync ( join ( dirs . components , 'engine' ), hidden ); 219rmSync ( mark , { force :true }); 220const missing = await waitJob (( await call ( '/api/native/operations' , 'POST' , { kind :'load' , args :{ model :modelId } })). body . id ); 221record ( 'no engine for this PC is a notice and nothing is started' , missing . job . state === 'error' && / No engine for this PC / . test ( missing . job . error ) && / never downloads / . test ( missing . job . error ) && ! existsSync ( mark ), 222` ${ missing . job . state } : ${ String ( missing . job . error ). slice ( 0 , 160 )} ` ); 223const refused = await waitJob (( await call ( '/api/native/operations' , 'POST' , { kind :'install' , args :{ family :'qwen' , model :'IQ2_XS' } })). body . id ); 224record ( 'installing from the app is refused (Terminal only)' , refused . job . state === 'error' && / Terminal / . test ( refused . job . error ), refused . job . error ); 225const binary = await call ( '/api/engine/binary' , 'POST' ); 226record ( 'the llama.cpp download route is refused' , binary . status === 409 && / never downloads / . test ( binary . body ?. error ?? '' ), ` ${ binary . status } ${ binary . body ?. error } ` ); 227 228// ---- clean shutdown (what the Tauri shell does on exit) 229renameSync ( hidden , join ( dirs . components , 'engine' )); 230rmSync ( mark , { force :true }); 231const again = await waitJob (( await call ( '/api/native/operations' , 'POST' , { kind :'load' , args :{ model :modelId } })). body . id , 400 ); 232let ran2 = existsSync ( mark ) ?JSON . parse ( readFileSync ( mark , 'utf8' )) :null ; 233if ( real ) { 234const listed = spawnSync ( 'ps' , [ '-eo' , 'pid,args' ], { encoding :'utf8' }). stdout . split ( '\n' ). filter ( l => l . includes ( ` ${ dirs . components } /engine/` ) && l . includes ( '--serve' )); 235ran2 = listed . length ?{ pid :Number ( listed [ 0 ]. trim (). split ( / \s +/ )[ 0 ]) } :null ; 236} 237record ( 'load again after the engine package returns' , again . job . state === 'done' , again . job . error ?? '' ); 238const wrong = await fetch ( base + '/api/control/shutdown' , { method :'POST' , headers :{ 'x-strata-shutdown' :'nope' } }); 239record ( 'shutdown without the shell\'s secret is refused' , wrong . status === 403 , String ( wrong . status )); 240const exited = new Promise ( r => host . once ( 'exit' , code => r ( code ))); 241const stopping = await fetch ( base + '/api/control/shutdown' , { method :'POST' , headers :{ 'x-strata-shutdown' :shutdownToken } }); 242const code = await Promise . race ([ exited , delay ( 90000 ). then (() => 'timeout' )]); 243for ( let i = 0 ; i < 100 && ran2 && alive ( ran2 . pid ); i ++ ) await delay ( 100 ); 244const final = controlJson ( 'runtime' , 'status' , '--profile' , 'app-1' ); 245record ( 'clean shutdown stops the engine the app started and exits' , stopping . status === 202 && code === 0 && final . json ?. state === 'stopped' && ( ! ran2 || ! alive ( ran2 . pid )), `status= ${ stopping . status } ; host exit= ${ code } ; runtime= ${ final . json ?. state } ; engine alive= ${ ran2 ? alive ( ran2 . pid ) : 'n/a' } ` ); 246 247// ---- hard kill: an engine whose app host dies ends with it (the owner follows the host: runtime start --die-with-pid) 248if ( ! ( await startHost ())) { record ( 'host restarts' , false , host . hostLog (). slice ( - 400 )); return ; } 249await call ( '/api/native?refresh=1' ); 250rmSync ( mark , { force :true }); 251const third = await waitJob (( await call ( '/api/native/operations' , 'POST' , { kind :'load' , args :{ model :modelId } })). body . id , 400 ); 252let ran3 = existsSync ( mark ) ?JSON . parse ( readFileSync ( mark , 'utf8' )) :null ; 253if ( real ) { 254const listed = spawnSync ( 'ps' , [ '-eo' , 'pid,args' ], { encoding :'utf8' }). stdout . split ( '\n' ). filter ( l => l . includes ( ` ${ dirs . components } /engine/` ) && l . includes ( '--serve' )); 255ran3 = listed . length ?{ pid :Number ( listed [ 0 ]. trim (). split ( / \s +/ )[ 0 ]) } :null ; 256record ( '(real) the engine is up before the host is killed' , !! ran3 , listed [ 0 ] ?listed [ 0 ]. trim (). slice ( 0 , 120 ) :'no engine process' ); 257} 258await stopHost ( true ); 259for ( let i = 0 ; i < 600 && ran3 && alive ( ran3 . pid ); i ++ ) await delay ( 100 ); // the owner notices within a second, drains, stops 260const orphan = controlJson ( 'runtime' , 'status' , '--profile' , 'app-1' ); 261record ( 'a hard-killed app host takes its engine with it' , third . job . state === 'done' && ( ! ran3 || ! alive ( ran3 . pid )), `engine alive= ${ ran3 ? alive ( ran3 . pid ) : 'n/a' } ; runtime= ${ orphan . json ?. state ?? orphan . json ?. error ?. message } ` ); 262const cleanup = controlJson ( 'runtime' , 'stop' , '--profile' , 'app-1' ); 263record ( 'nothing is left to stop afterwards' , / stopped | not managed / . test ( JSON . stringify ( cleanup . json )) && controlJson ( 'runtime' , 'status' , '--profile' , 'app-1' ). json ?. state === 'stopped' , JSON . stringify ( cleanup . json ). slice ( 0 , 160 )); 264 265// ---- the shell itself is killed (what the desktop shell's crash or kill looks like to the host): the host leaves, and 266// its engine with it, with nothing announced. Windows also has the job object; this is the path that works everywhere. 267const started2 = await startHostViaShell (); 268if ( started2 . failed ) { record ( 'host starts under a stand-in shell' , false , '' ); try { started2 . shell . kill ( 'SIGKILL' ); } catch { /* gone */ } } 269else { 270await call ( '/api/native?refresh=1' ); 271rmSync ( mark , { force :true }); 272const fourth = await waitJob (( await call ( '/api/native/operations' , 'POST' , { kind :'load' , args :{ model :modelId } })). body . id , 400 ); 273let ran4 = existsSync ( mark ) ?JSON . parse ( readFileSync ( mark , 'utf8' )) :null ; 274if ( real ) { 275const listed = spawnSync ( 'ps' , [ '-eo' , 'pid,args' ], { encoding :'utf8' }). stdout . split ( '\n' ). filter ( l => l . includes ( ` ${ dirs . components } /engine/` ) && l . includes ( '--serve' )); 276ran4 = listed . length ?{ pid :Number ( listed [ 0 ]. trim (). split ( / \s +/ )[ 0 ]) } :null ; 277} 278if ( isWin ) spawnSync ( 'taskkill' , [ '/PID' , String ( started2 . shell . pid ), '/F' ], { windowsHide :true }); else started2 . shell . kill ( 'SIGKILL' ); 279for ( let i = 0 ; i < 100 && alive ( started2 . hostPid ); i ++ ) await delay ( 100 ); 280const hostGone = ! alive ( started2 . hostPid ); 281for ( let i = 0 ; i < 900 && ran4 && alive ( ran4 . pid ); i ++ ) await delay ( 100 ); 282const engineGone = ! ran4 || ! alive ( ran4 . pid ); 283record ( 'a killed shell takes the host and its engine with it' , fourth . job . state === 'done' && hostGone && engineGone , 284`host pid ${ started2 . hostPid } gone= ${ hostGone } ; engine pid ${ ran4 ?. pid } gone= ${ engineGone } ; runtime= ${ controlJson ( 'runtime' , 'status' , '--profile' , 'app-1' ). json ?. state } ` ); 285controlJson ( 'runtime' , 'stop' , '--profile' , 'app-1' ); 286} 287 288await finishSpy (); 289} 290 291async function finishSpy () { 292if ( spyLog ) { 293const attempts = readFileSync ( spyLog , 'utf8' ). split ( '\n' ). filter ( Boolean ); 294record ( 'no acquisition attempt by the host during the whole run (spy)' , attempts . length === 0 , attempts . join ( ' | ' )); 295} 296} 297 298try { await main (); } 299catch ( error ) { record ( 'flow' , false , error . stack ?? error . message ); } 300finally { 301try { const hid = join ( dirs . components , 'engine.hidden-by-flow' ); if ( real && existsSync ( hid ) && ! existsSync ( join ( dirs . components , 'engine' ))) renameSync ( hid , join ( dirs . components , 'engine' )); } catch { /* reported by the run */ } 302await stopHost ( true ); 303controlJson ( 'runtime' , 'stop' , '--profile' , 'app-1' ); 304controlJson ( 'runtime' , 'stop' , '--profile' , 'app-2' ); 305} 306const failed = steps . filter ( s => ! s . ok ); 307writeFileSync ( join ( work , 'installed-flow.json' ), JSON . stringify ({ ok :failed . length === 0 , install, work, steps}, null , 1 )); 308console . log ( `\n ${ steps . length - failed . length } / ${ steps . length } ok; report ${ join ( work , 'installed-flow.json' )} ` ); 309if ( ! args . keep && ! args . work && failed . length === 0 ) { try { rmSync ( work , { recursive :true , force :true }); } catch { /* leave it */ } } 310process . exit ( failed . length ?1 :0 );