okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a2f602398
main
1/** Screenshot-only first-launch fixture. No weights, subprocesses or production writes. */ 2import http from 'node:http' ; 3import { readFile , writeFile } from 'node:fs/promises' ; 4import { resolve , extname } from 'node:path' ; 5import { createEnginePreview } from './engine-preview.mjs' ; 6 7const root = resolve ( import . meta. dirname , '../../dist' ), upstream = process . env . STRATA_ONBOARDING_UPSTREAM ?? 'http://127.0.0.1:5161' ; 8const native = process . env . STRATA_UI_PREVIEW === '1' ?JSON . parse ( await readFile ( new URL ( './ui-preview-native.json' , import . meta. url ), 'utf8' )) :await ( await fetch ( upstream + '/api/native' )). json (); 9native . hardware = { cpu :{ cores :16 }, ram_gb :128 , gpus :[{ index :0 , name :'NVIDIA RTX 4090' , vram_gb :24 , usable :true }], disk_free_gb :250 }; 10if ( process . env . STRATA_ONBOARDING_SCENARIO === 'multi-gpu' ) native . hardware . gpus . push ({ index :1 , name :'NVIDIA RTX 3090' , vram_gb :24 , usable :true }); 11if ( process . env . STRATA_ONBOARDING_GPUS ) native . hardware . gpus = JSON . parse ( process . env . STRATA_ONBOARDING_GPUS ); 12native . catalog . this_pc = native . hardware ; 13native . catalog . recommendation = { family :'qwen' , model :'Q2_0' , context :32768 }; 14native . catalog . summary = 'Supported hardware fixture' ; 15for ( const family of native . catalog . families ) for ( const size of family . sizes ){ size . on_this_pc = 'fits' ; size . installed = false ;} 16if ( process . env . STRATA_ONBOARDING_SCENARIO === 'limited' ){ 17for ( const family of native . catalog . families ) for ( const size of family . sizes ) size . on_this_pc = 'does not fit' ; 18native . catalog . families . find ( f => f . family === 'swift' ). sizes [ 0 ]. on_this_pc = 'fits' ; 19native . catalog . recommendation . why = 'Selected model is incompatible in this fixture; Swift Compact is available.' ; 20} 21native . repo = '/Applications/Strata/engine' ; 22native . downloadDirectory = '/Users/example/Documents/Strata/Models' ; 23native . installed = { models :[], data_folder :'/Models/Strata' , engine :{ version :native . version }}; 24native . instances = []; native . jobs = []; native . defaultId = null ; native . external = []; 25native . summary = 'Choose a version to get started' ; native . error = null ; native . capabilities . calibration = true ; 26/* UI preview: several installed engines and an engine update, kept in memory (Settings > Engine, About). */ 27const enginePreview = process . env . STRATA_UI_PREVIEW === '1' ?createEnginePreview ( native ) :null ; 28let setup = { complete :false , dismissed :false , choices :{}, step :1 , flowVersion :2 , history :[], app :{ version :'0.1.0' , modelsDir :'/Models' , dataDir :'/Strata/data' }}; 29let selected = null ; 30let loadVision = 'no' ; 31const events = new Set (); 32const modelSettings = new Map (); 33const automatic = process . env . STRATA_ONBOARDING_PREVIEW === '1' ; 34function later ( id , delay , action ){ const timer = setTimeout (() => { if ( job ()?. id === id && job (). state === 'running' ) action ();}, delay ); timer . unref ();} 35const job = () => native . jobs . at ( - 1 ); 36function stage ( name ){ 37if ( ! job ()) throw new Error ( 'Begin Download & load in the UI first.' ); 38if ( name === 'download' ) Object . assign ( job (),{ state :'running' , kind :'install' , summary :'Downloading model files' , result :{ install :{ running :true , step :'Downloading model files' , download :{ file :`Qwen3.8-Flash-Next- ${ selected ?. model ?? 'Q2_0' } -00001-of-00003.gguf` , percent :38 , done_gb :8.4 , total_gb :22.1 }}}}); 39else if ( name === 'prepare' ) Object . assign ( job (),{ state :'running' , kind :'install' , summary :'Preparing model files' , result :{ install :{ running :true , step :'Packing model files for your computer' }}}); 40else if ( name === 'loading' ) Object . assign ( job (),{ state :'running' , kind :'install' , summary :'Loading model' , result :{ install :{ running :true , step :'Loading model into memory' }}}); 41else if ( name === 'tuning' ) Object . assign ( job (),{ state :'running' , kind :'tune' , summary :'Measuring the best engine settings for this computer…' }); 42else if ( name === 'prepared' || name === 'ready' ){ 43const family = native . catalog . families . find ( f => f . family === selected . family ), size = family . sizes . find ( s => s . model === selected . model ); 44size . installed = true ; 45native . installed . models = [{ model :size . id , config :`strata- ${ size . id } .json` , model_name :family . title , ready :true , context :selected . context , kv :selected . kv , images :selected . vision === 'no' ?'off' :'gpu' , lowRamMode :selected . low_ram , dataFolder :'/Models/Strata' }]; 46if ( name === 'ready' ){ native . installed . models [ 0 ]. visionEnabled = loadVision !== 'no' ; native . instances = [{ id :'onboarding-model' , apiModelId :size . id , model :size . id , label :family . title , aliases :[], vision :loadVision !== 'no' , context :selected . context , port :5262 , gpus :[ 0 ], status :'ready' , phase :'idle' , loadedAt :new Date (). toISOString (), error :null , metrics :null }];} 47if ( name === 'ready' ) native . defaultId = 'onboarding-model' ; native . summary = name === 'ready' ?'Model ready' :'Model prepared' ; 48Object . assign ( job (),{ state :'done' , summary :'Model ready' , result :{ install :{ running :false , exit_code :0 }}}); 49} else throw new Error ( 'Unknown fixture stage' ); 50} 51// Open the final setup stage directly for design review, without simulating a download first. 52if ([ 'make-it-yours' , 'ready' ]. includes ( process . env . STRATA_ONBOARDING_START )){ 53const family = native . catalog . families . find ( f => f . family === native . catalog . recommendation . family ) ?? native . catalog . families [ 0 ]; 54const size = family . sizes . find ( s => s . model === native . catalog . recommendation . model ) ?? family . sizes [ 0 ]; 55selected = { family :family . family , model :size . model , context :32768 , vision :family . images ?'yes' :'no' , kv :'int8' , low_ram :'auto' }; 56native . jobs . push ({ id :'preview-prepared' , kind :'install' , guided :true , model :size . model , state :'running' , startedAt :new Date (). toISOString (), error :null , result :null }); 57stage ( 'prepared' ); 58setup = { ...setup , step :4 , choices :{ onboarding :{ step :4 , family :family . family , size :size . id , context :32768 , vision :false , profile :'work' , calibrate :true , installJobId :'preview-prepared' }}}; 59if ( process . env . STRATA_ONBOARDING_START === 'ready' ){ 60stage ( 'ready' ); setup . complete = true ; 61if ( process . env . STRATA_ONBOARDING_SCENARIO === 'telemetry' ){ 62const series = ( base , amplitude ) => Array . from ({ length :60 },( _ , i ) => Math . round (( base + Math . sin ( i / 6 ) * amplitude ) * 100 ) / 100 ); 63native . instances [ 0 ]. phase = 'generating' ; native . instances [ 0 ]. metrics = { time :Date . now () / 1000 , engine :{ max_context :32768 , expert_slots :64 , experts :256 , expert_cache_mib :8192 }, live :{ state :'generating' , running :1 , queued :0 , prompt_tokens :4096 , generated :128 , max_tokens :512 , tok_s :24.8 , prefill_tok_s_mean :642 }, requests :[{ id :'fixture-request' , time :Date . now () / 1000 - 40 , prompt_tokens :2048 , reused :1024 , output_tokens :360 , decode_tok_s :24 , duration_s :15 , prompt_ms :1600 }], totals :{ requests :1 , prompt_tokens :2048 , reused :1024 , output_tokens :360 , prompt_ms :1600 , decode_ms :15000 }, hardware :{ cpu :34 , ram_used :24 * 1024 ** 3 , ram_total :128 * 1024 ** 3 , gpu_util :78 , gpu_mem_used :18 * 1024 ** 3 , gpu_mem_total :24 * 1024 ** 3 , gpu_temp :63 , gpu_power :185 , gpu_power_limit :450 , gpu_pcie_gen :4 , gpu_pcie_gen_max :4 , gpu_pcie_width :16 , gpu_pcie_rx_mb :240 , disk_read_mb :180 , disk_write_mb :12 }, history :{ tok_s :series ( 24 , 3 ), prefill_tok_s_mean :series ( 640 , 85 ), gpu_util :series ( 78 , 9 ), gpu_mem_used :series ( 18 * 1024 ** 3 , 0.3 * 1024 ** 3 ), gpu_temp :series ( 62 , 2 ), gpu_power :series ( 185 , 18 ), gpu_pcie_rx_mb :series ( 240 , 40 ), cpu :series ( 34 , 7 ), ram_used :series ( 24 * 1024 ** 3 , 0.3 * 1024 ** 3 ), disk_read_mb :series ( 180 , 40 )}}; 64} 65} 66} 67if ( process . env . STRATA_ONBOARDING_GPUS ){ native . instances = []; native . defaultId = null ;} /* GPU roles previews: the model is prepared, not loaded, so the roles shown are the recommendation */ 68if ( process . env . STRATA_PREVIEW_STATE_FILE ){ const saved = JSON . parse ( await readFile ( process . env . STRATA_PREVIEW_STATE_FILE , 'utf8' )); Object . assign ( native , saved . native ); setup = saved . setup ; const running = native . instances . find ( i => i . id === native . defaultId ), entry = native . installed . models . find ( m => m . model === running ?. model ), family = native . catalog . families . find ( f => f . sizes . some ( s => s . id === entry ?. model )), size = family ?. sizes . find ( s => s . id === entry ?. model ); if ( family && size ){ selected = { family :family . family , model :size . model , context :entry . context ?? 32768 , vision :entry . images === 'off' ?'no' :'yes' , kv :entry . kv ?? 'int8' , low_ram :entry . lowRamMode ?? 'auto' }; loadVision = entry . visionEnabled === false ?'no' :selected . vision ;}} 69/* Load with Read pictures on and no picture files (STRATA_PICTURES_SCENARIO=online|offline): the model is downloaded, the Models page offers a plain Load, and the Load fetches the 70picture files (online) or loads without pictures and says so (offline). What the page posted is kept for the test: GET /__fixture/posted. Nothing is downloaded or started. */ 71const picturesScenario = process . env . STRATA_PICTURES_SCENARIO ?? '' ; 72const posted = []; 73if ( picturesScenario ){ 74const family = native . catalog . families . find ( f => f . family === 'qwen' ), size = family . sizes . find ( s => s . model === 'IQ3_S' ) ?? family . sizes [ 0 ]; 75size . installed = true ; native . packaged = true ; native . visionReader = true ; 76native . installed . models = [{ model :size . id , config :`strata- ${ size . id } .json` , model_name :family . title , ready :true , context :131072 , contextChosen :true , kv :'int8' , images :'off' , visionPrepared :false , lowRamMode :'auto' , runDataFolder :'/Users/example/qwen-own' , ownGgufDir :'/Users/example/qwen-own/IQ3_S' }]; 77native . instances = []; native . defaultId = null ; native . jobs = []; native . summary = 'Ready' ; setup = { ...setup , complete :true , step :4 }; 78} 79function pictureLoad ( body ){ 80posted . push ({ kind :body . kind , args :body . args }); 81const family = native . catalog . families . find ( f => f . family === 'qwen' ), size = family . sizes . find ( s => s . id === body . args . model ), id = `pictures- ${ native . jobs . length } ` ; 82const bar = percent => ({ install :{ download :{ file :'picture reader' , percent, done_gb :0.9 * percent / 100 , total_gb :0.9 , remaining_gb :0.9 * ( 100 - percent ) / 100 }}}); 83const done = ( vision , note ) => { const j = native . jobs . find ( x => x . id === id ); if ( flip ){ family . sizes . forEach ( x => { x . images = true ;}); native . visionReader = true ; native . installed . models [ 0 ]. visionEnabled = true ;} Object . assign ( j ,{ state :'done' , summary :` ${ family . title } is ready.` , result :null }); 84if ( vision ){ native . installed . models [ 0 ]. images = 'yes' ; native . installed . models [ 0 ]. visionPrepared = true ;} 85if ( body . kind === 'load' ){ native . instances = [{ id :'onboarding-model' , apiModelId :size . id , model :size . id , label :family . title , aliases :[], vision, context :131072 , port :5262 , gpus :[ 0 ], status :'ready' , phase :'idle' , loadedAt :new Date (). toISOString (), error :null , metrics :null , ...( note ?{ picturesNote :note } :{})}]; native . defaultId = 'onboarding-model' ;}}; 86const flip = picturesScenario === 'flip' , online = picturesScenario === 'online' || flip ; 87/* flip: what the host can report while it is busy with the load (the reader probe drops out, the saved choice reads as off for a moment): the page must not follow it */ 88if ( flip ){ family . sizes . forEach ( x => { x . imagesCapable = true ; x . images = false ;}); native . visionReader = false ; native . installed . models [ 0 ]. visionEnabled = false ; native . installed . models [ 0 ]. visionPrepared = true ; native . installed . models [ 0 ]. images = 'off' ;} 89native . jobs . push ({ id, kind :body . kind , model :body . args . model , state :'running' , startedAt :new Date (). toISOString (), summary :online ?'Downloading the picture files (0.9 GB, once)…' :'Downloading the picture files (0.9 GB, once)…' , error :null , result :bar ( 0 )}); 90const at = ( ms , action ) => setTimeout (() => { const j = native . jobs . find ( x => x . id === id ); if ( j ?. state === 'running' ) action ( j );}, ms ). unref (); 91if ( online ){ at ( 1500 , j => { j . result = bar ( 33 );}); at ( 3000 , j => { j . result = bar ( 66 );}); at ( 4500 , j => { j . summary = 'Loading the model…' ; j . result = null ;}); at ( 6500 ,() => done ( true , null ));} 92else { at ( 1500 , j => { j . summary = 'Loading the model…' ; j . result = null ;}); at ( 3500 ,() => done ( false , 'No internet connection: the model is loaded without picture reading. Load it again when you are online.' ));} 93return native . jobs . at ( - 1 ); 94} 95const server = http . createServer ( async ( req , res ) => { try { 96const path = new URL ( req . url , 'http://fixture' ). pathname ; let payload = '' ; if ( req . method !== 'GET' ) for await ( const chunk of req ) payload += chunk ; const body = payload ?JSON . parse ( payload ) :{}; 97const json = ( value , status = 200 ) => { res . writeHead ( status ,{ 'content-type' :'application/json' }); res . end ( JSON . stringify ( value ));}; 98if ( process . env . STRATA_CAPTURE_OUTPUT && path === '/__fixture/capture' && req . method === 'POST' ){ 99if ( typeof body . dataUrl !== 'string' ||! body . dataUrl . startsWith ( 'data:image/png;base64,' )) throw new Error ( 'A PNG export is required' ); 100await writeFile ( process . env . STRATA_CAPTURE_OUTPUT , Buffer . from ( body . dataUrl . slice ( 'data:image/png;base64,' . length ), 'base64' )); 101return json ({ saved :true , width :body . width , height :body . height }); 102} 103if ( process . env . STRATA_CAPTURE_OUTPUT && path === '/__fixture/html-to-image.js' ){ 104res . writeHead ( 200 ,{ 'content-type' :'text/javascript' }); res . end ( await readFile ( resolve ( import . meta. dirname , '../../node_modules/html-to-image/dist/html-to-image.js' ))); return ; 105} 106if ( process . env . STRATA_CAPTURE_OUTPUT && path === '/__fixture/export.js' ){ 107res . writeHead ( 200 ,{ 'content-type' :'text/javascript' }); res . end ( await readFile ( resolve ( import . meta. dirname , 'onboarding-export.js' ))); return ; 108} 109if ( enginePreview && await enginePreview . handle ( path , req . method , body , json )) return ; 110if ( path === '/__fixture/stage' && req . method === 'POST' ){ stage ( body . stage ); return json ({ stage :body . stage });} 111if ( path === '/api/native' && req . method === 'GET' ) return json ( native ); 112if ( path === '/__fixture/posted' && req . method === 'GET' ) return json ( posted ); 113if ( / ^\/api\/native\/models\/ [ ^ / ] + \/settings$ / . test ( path )){ const model = path . split ( '/' )[ 4 ]; if ( req . method === 'PATCH' ) modelSettings . set ( model ,{ model, values :body . values ?? {}, mcp :body . mcp ?? {}}); return json ( modelSettings . get ( model ) ?? { model, values :{ sampling :{}, args :[], env :{}}, mcp :{}, restartNeeded :true });} 114if ( path === '/api/native/directory' ){ native . downloadDirectory = body . directory ; return json ( native );} 115if ( path === '/api/local-models/browse' ) return json ({ directory :new URL ( req . url , 'http://fixture' ). searchParams . get ( 'directory' ) ?? '/Models/Strata' , parent :'/Models' , entries :[{ name :'downloads' , path :'/Models/Strata/downloads' , kind :'folder' },{ name :'models' , path :'/Models/Strata/models' , kind :'folder' }], shortcuts :[], truncated :false }); 116if ( path === '/api/native/plan' ){ 117const family = native . catalog . families . find ( f => f . family === body . family ), size = family . sizes . find ( s => s . model === body . model ); 118return json ({ plan :{ title :family . title , download_gb :size . download_gb , disk_short :null }}); 119} 120if ( path === '/api/native/operations' && req . method === 'POST' ){ 121if ( picturesScenario && [ 'load' , 'pictures' ]. includes ( body . kind )) return json ( pictureLoad ( body )); 122if ( ! [ 'install' , 'tune' ]. includes ( body . kind )) throw new Error ( 'Only fixture preparation and tuning are supported' ); 123if ( body . kind === 'install' ) selected = body . args ; 124if ( body . kind === 'tune' ) loadVision = body . args . vision ?? 'no' ; 125native . jobs . push ({ id :`onboarding- ${ body . kind } - ${ native . jobs . length } ` , kind :body . kind , guided :true , model :body . args . model , state :'running' , startedAt :new Date (). toISOString (), summary :'Starting…' , error :null , result :null }); 126stage ( body . kind === 'install' ?'download' :'tuning' ); 127if ( automatic ){ const id = job (). id ; if ( body . kind === 'install' ){ later ( id , 4000 ,() => { job (). result . install . download . percent = 72 ; job (). result . install . download . done_gb = 15.9 ;}); later ( id , 8000 ,() => stage ( 'prepare' )); later ( id , 12000 ,() => stage ( 'prepared' ));} else { later ( id , 4000 ,() => { job (). summary = 'Applying your preference and loading the model…' ;}); later ( id , 8000 ,() => stage ( 'ready' ));}} 128return json ( job ()); 129} 130if ( / ^\/api\/native\/operations\/ [ ^ / ] + \/cancel$ / . test ( path )){ Object . assign ( job (),{ state :'cancelled' , summary :'Preparation stopped' }); return json ( job ());} 131if ( path === '/api/setup' && req . method === 'GET' ) return json ( setup ); 132if ( path === '/api/setup/step' && req . method === 'POST' ){ setup = { ...setup , ...body }; return json ( setup );} 133if ( path === '/api/setup/complete' && req . method === 'POST' ){ 134if ( ! native . instances . some ( i => i . status === 'ready' )) throw new Error ( 'Load a model first' ); 135setup = { ...setup , complete :true , step :4 }; return json ( setup ); 136} 137if ( path === '/api/workspaces' ) return json ({ workspaces :[]}); 138if ( path === '/api/events' ){ 139res . writeHead ( 200 ,{ 'content-type' :'text/event-stream' , 'cache-control' :'no-cache' }); res . write ( 'data: {}\n\n' ); events . add ( res ); 140req . on ( 'close' ,() => events . delete ( res )); return ; 141} 142if ( path . startsWith ( '/api/' )){ 143if ( req . method !== 'GET' ) throw new Error ( 'Production mutations are blocked by this fixture' ); 144const response = await fetch ( upstream + req . url ), value = await response . json (); 145if ( path === '/api/hardware' ) Object . assign ( value ,{ gpus :native . hardware . gpus . map ( g => ({ index :g . index , id :`gpu- ${ g . index } ` , vendor :'nvidia' , name :g . name , vramGb :g . vram_gb , backend :'cuda' , unified :false })), memory :{ totalGb :128 , usedGb :16 , freeGb :112 , pressure :'low' }, accelerator :{ backend :'cuda' , unified :false , usableVramGb :native . hardware . gpus . reduce (( sum , g ) => sum + g . vram_gb , 0 ), label :'Fixture GPUs' }}); 146if ( path === '/api/models' ) value . loaded = null ; 147if ( path === '/api/runtime' ) Object . assign ( value ,{ instances :[], defaultId :null }); 148return json ( value , response . status ); 149} 150const file = path === '/' ?'/index.html' :path ; if ( file . includes ( '..' )) throw new Error ( 'Invalid fixture path' ); 151let content = await readFile ( root + file ); 152if ( process . env . STRATA_CAPTURE_OUTPUT && file === '/index.html' ) content = Buffer . from ( content . toString (). replace ( '</body>' , '<script src="/__fixture/html-to-image.js"></script><script src="/__fixture/export.js"></script></body>' )); 153res . writeHead ( 200 ,{ 'content-type' :({ '.html' :'text/html' , '.js' :'text/javascript' , '.css' :'text/css' , '.svg' :'image/svg+xml' , '.woff2' :'font/woff2' , '.png' :'image/png' })[ extname ( file )] ?? 'application/octet-stream' }); res . end ( content ); 154} catch ( e ){ res . writeHead ( 400 ,{ 'content-type' :'application/json' }); res . end ( JSON . stringify ({ error :e . message }));}}); 155const heartbeat = setInterval (() => { for ( const response of events ) response . write ( 'data: {}\n\n' );}, 1000 ); 156const port = Number ( process . env . STRATA_ONBOARDING_PORT ?? 5271 ); 157server . listen ( port , '127.0.0.1' ,() => console . log ( `Disposable onboarding screenshots: http://127.0.0.1: ${ port } ` )); 158function stop (){ clearInterval ( heartbeat ); server . closeAllConnections (); server . close (() => process . exit ( 0 ));} 159process . on ( 'SIGTERM' , stop ); process . on ( 'SIGINT' , stop );