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 { fileURLToPath } from 'node:url' ; 3import test from 'node:test' ; 4import assert from 'node:assert/strict' ; 5import { spawn , spawnSync } from 'node:child_process' ; 6import { createHash } from 'node:crypto' ; 7import { mkdirSync , mkdtempSync , readFileSync , realpathSync , rmSync , writeFileSync , symlinkSync , utimesSync } from 'node:fs' ; 8import { tmpdir } from 'node:os' ; 9import { join } from 'node:path' ; 10import { createServer } from 'node:net' ; 11import { locateModelFile } from '../server/model-files.mjs' ; 12import { createImageModels , IMAGE_CATALOG } from '../server/image-models.mjs' ; 13const cwd = fileURLToPath ( new URL ( '..' , import . meta. url )); 14const pause = ms => new Promise ( resolve => setTimeout ( resolve , ms )); 15function fixture ( t ) { const home = realpathSync ( mkdtempSync ( join ( tmpdir (), 'strata-directory-' ))); t . after (() => rmSync ( home ,{ recursive :true , force :true })); return home ; } 16 17test ( 'existing flat and Strata-layout weights are found; partial, wrong-header and outside symlinks are rejected' , t => { 18const home = fixture ( t ), folder = join ( home , 'models' ); mkdirSync ( folder ); 19const bytes = Buffer . from ( 'GGUFsmall-known-fixture' ), model = { id :'known' , source :{ file :'known.gguf' , bytes :bytes . length }}; 20const flat = join ( folder , model . source . file ); writeFileSync ( flat , bytes ); 21assert . equal ( locateModelFile ( folder , model ), flat ); 22writeFileSync ( flat , bytes . subarray ( 0 , 5 )); assert . equal ( locateModelFile ( folder , model ), null ); 23writeFileSync ( flat , Buffer . from ( 'bad!small-known-fixture' )); assert . equal ( locateModelFile ( folder , model ), null ); 24rmSync ( flat ); const outside = join ( home , 'external.gguf' ); writeFileSync ( outside , bytes ); symlinkSync ( outside , flat ); 25assert . equal ( locateModelFile ( folder , model ), null ); rmSync ( flat ); 26mkdirSync ( join ( folder , model . id )); const nested = join ( folder , model . id , model . source . file ); writeFileSync ( nested , bytes ); 27assert . equal ( locateModelFile ( folder , model ), nested ); 28}); 29 30test ( 'directory preferences survive restart, scope demo installs, and reject bad paths without changing app data' , t => { 31const home = fixture ( t ), next = join ( home , 'existing models' ); mkdirSync ( next ); 32const result = spawnSync ( process . execPath ,[ '--input-type=module' , '-e' , ` 33import assert from 'node:assert/strict';import {join} from 'node:path';import {existsSync} from 'node:fs'; 34const store=await import('./server/store.mjs');const models=await import('./server/models.mjs'); 35const original=store.MODELS_DIR,id='qwen38-q4_k_m';store.update({installed:{[id]:{simulated:true}},setup:{complete:true,step:4},serving:{apiKey:'fixture-only-key'}}); 36for(const path of ['relative/path',join(store.HOME,'missing'),store.DATA_DIR,store.HOME])assert.throws(()=>store.validateModelsDirectory(path)); 37assert.equal(store.MODELS_DIR,original);assert.equal(existsSync(join(store.HOME,'missing')),false); 38store.changeModelsDirectory( ${ JSON . stringify ( next )} );models.init({send(){}}); 39assert.equal(models.isOnDisk(id),false);assert.equal(store.get().setup.complete,true);assert.equal(store.get().serving.apiKey,'fixture-only-key'); 40store.changeModelsDirectory(original);models.init({send(){}});assert.equal(models.isOnDisk(id),true); 41store.changeModelsDirectory( ${ JSON . stringify ( next )} ); 42` ],{ cwd, env :{ ...process . env , STRATA_HOME :home , STRATA_MODELS_DIR :join ( home , 'models' ), STRATA_REAL_ENGINE :'0' }, encoding :'utf8' }); 43assert . equal ( result . status , 0 , result . stderr ); 44const restarted = spawnSync ( process . execPath ,[ '--input-type=module' , '-e' , `const store=await import('./server/store.mjs');console.log(store.MODELS_DIR);` ],{ cwd, env :{ ...process . env , STRATA_HOME :home , STRATA_MODELS_DIR :join ( home , 'models' )}, encoding :'utf8' }); 45assert . equal ( restarted . stdout . trim (), next ); 46}); 47 48test ( 'real library reuses a known flat GGUF and deletion preserves other files' , t => { 49const home = fixture ( t ), next = join ( home , 'ggufs' ); mkdirSync ( next ); 50const result = spawnSync ( process . execPath ,[ '--input-type=module' , '-e' , ` 51import assert from 'node:assert/strict';import fs from 'node:fs';import {join} from 'node:path'; 52const store=await import('./server/store.mjs');const {VARIANTS}=await import('./server/catalog.mjs');const models=await import('./server/models.mjs'); 53const v=VARIANTS[0],bytes=Buffer.from('GGUFsmall-catalog-fixture');v.source.bytes=bytes.length; 54const file=join( ${ JSON . stringify ( next )} ,v.source.file),other=join( ${ JSON . stringify ( next )} ,'unrelated.gguf');fs.writeFileSync(file,bytes);fs.writeFileSync(other,'keep'); 55store.changeModelsDirectory( ${ JSON . stringify ( next )} );models.init({send(){}}); 56assert.equal(models.isOnDisk(v.id),true);assert.equal(models.pathFor(v),file);assert.equal(models.library().variants[0].state,'installed'); 57models.remove(v.id);assert.equal(fs.existsSync(file),false);assert.equal(fs.readFileSync(other,'utf8'),'keep'); 58` ],{ cwd, env :{ ...process . env , STRATA_HOME :home , STRATA_MODELS_DIR :join ( home , 'models' ), STRATA_REAL_ENGINE :'1' }, encoding :'utf8' }); 59assert . equal ( result . status , 0 , result . stderr ); 60}); 61 62test ( 'image downloads are scoped per directory and existing real image files require the pinned hash' , async t => { 63const home = fixture ( t ), dataDir = join ( home , 'data' ), first = join ( home , 'first' ), second = join ( home , 'second' ); mkdirSync ( first ); mkdirSync ( second ); 64let directory = first ; const demo = createImageModels ({ dataDir, modelsDir :() => directory , demoDuration :10 }); demo . install ( 'q4' ); await demo . whenIdle (); demo . select ( 'q4' ); demo . apply (); 65directory = second ; await demo . rescan ( true ); assert . equal ( demo . library (). variants [ 0 ]. state , 'available' ); assert . equal ( demo . library (). applied , 'off' ); 66directory = first ; await demo . rescan ( true ); assert . equal ( demo . library (). variants [ 0 ]. state , 'installed' ); 67const bytes = Buffer . from ( 'GGUFverified-small-image' ), catalog = { ...IMAGE_CATALOG , variants :[{ ...IMAGE_CATALOG . variants [ 0 ], bytes :bytes . length , sha256 :createHash ( 'sha256' ). update ( bytes ). digest ( 'hex' )}]}; 68writeFileSync ( join ( second , catalog . variants [ 0 ]. file ), bytes ); 69const real = createImageModels ({ dataDir :join ( home , 'real-data' ), modelsDir :second , real :true , catalog}); await real . rescan (); assert . equal ( real . library (). variants [ 0 ]. state , 'installed' ); 70writeFileSync ( join ( second , catalog . variants [ 0 ]. file ), Buffer . from ( 'GGUFmodified-small-image' )); utimesSync ( join ( second , catalog . variants [ 0 ]. file ), new Date ( Date . now () + 5000 ), new Date ( Date . now () + 5000 )); await real . rescan (); // same size; a fast PC can rewrite it inside one mtime tick (Windows ~15.6 ms)assert.equal(real.library().variants[0].state,'available'); 71}); 72 73async function freePort (){ const server = createServer (); await new Promise ( r => server . listen ( 0 , '127.0.0.1' , r )); const port = server . address (). port ; await new Promise ( r => server . close ( r )); return port ;} 74test ( 'directory API protects loaded models, active requests and downloads, then rescans without moving files' ,{ timeout :30000 }, async t => { 75const home = fixture ( t ), next = join ( home , 'existing' ); mkdirSync ( next ); mkdirSync ( join ( home , 'data' )); mkdirSync ( join ( home , 'models' )); 76const original = join ( home , 'models' ), keep = join ( original , 'keep.txt' ); writeFileSync ( keep , 'preserve' ); 77writeFileSync ( join ( home , 'data' , 'state.json' ), JSON . stringify ({ installed :{ 'qwen38-q4_k_m' :{ simulated :true }}, loaded :'qwen38-q4_k_m' , setup :{ complete :true , flowVersion :2 , step :4 }})); 78const port = await freePort (), base = `http://127.0.0.1: ${ port } ` ; 79const host = spawn ( process . execPath ,[ 'server/index.mjs' ],{ cwd, env :{ ...process . env , STRATA_HOME :home , STRATA_MODELS_DIR :join ( home , 'models' ), STRATA_REAL_ENGINE :'0' , STRATA_TEST_HARDWARE :ROOMY_HOST , STRATA_PORT :String ( port ), STRATA_BIND :'127.0.0.1' }, stdio :'ignore' }); 80async function call ( path , body ){ const response = await fetch ( base + path ,{ method :body === undefined ?'GET' :'POST' , headers :{ 'content-type' :'application/json' }, body :body === undefined ?undefined :JSON . stringify ( body )}); return { status :response . status , body :await response . json ()};} 81try { 82let ready = false ; for ( let i = 0 ; i < 100 ; i ++ ){ try { ready = ( await call ( '/api/runtime' )). status === 200 ; if ( ready ) break ;} catch {} await pause ( 100 );} assert . ok ( ready ); 83assert . equal (( await call ( '/api/storage/models-directory' ,{ directory :next })). status , 409 ); 84assert . equal (( await call ( '/api/models' )). body . disk . modelsDir , original ); 85assert . equal (( await call ( '/api/storage/models-directory' ,{ directory :join ( home , 'missing' ), unload :true })). status , 400 ); 86assert . equal (( await call ( '/api/runtime' )). body . instances . length , 1 ); 87const same = await call ( '/api/storage/models-directory' ,{ directory :original }); assert . equal ( same . status , 200 ); assert . equal ( same . body . runtime . instances . length , 1 ); 88const controller = new AbortController (); const response = await fetch ( base + '/v1/chat/completions' ,{ method :'POST' , headers :{ 'content-type' :'application/json' }, body :JSON . stringify ({ stream :true , messages :[{ role :'user' , content :'hello' }]}), signal :controller . signal }); assert . equal ( response . status , 200 ); 89assert . equal (( await call ( '/api/storage/models-directory' ,{ directory :next , unload :true })). status , 409 ); 90for ( const r of ( await call ( '/api/serving' )). body . requests ) await call ( `/api/serving/requests/ ${ r . id } /cancel` ,{}); controller . abort (); 91for ( let i = 0 ; i < 30 ; i ++ ){ if ( ! ( await call ( '/api/serving' )). body . stats . running ) break ; await pause ( 100 );} 92await call ( '/api/image-models/q4/install' ,{}); assert . equal (( await call ( '/api/storage/models-directory' ,{ directory :next , unload :true })). status , 409 ); await call ( '/api/image-models/q4/cancel' ,{}); 93await call ( '/api/models/qwen36-q2_k/install' ,{}); assert . equal (( await call ( '/api/storage/models-directory' ,{ directory :next , unload :true })). status , 409 ); await call ( '/api/models/qwen36-q2_k/cancel' ,{}); 94const changed = await call ( '/api/storage/models-directory' ,{ directory :next , unload :true }); assert . equal ( changed . status , 200 , JSON . stringify ( changed . body )); assert . equal ( changed . body . runtime . instances . length , 0 ); assert . equal ( changed . body . library . disk . modelsDir , next ); assert . equal ( changed . body . hardware . disk . modelsDir , next ); assert . equal ( changed . body . setup . app . modelsDir , next ); assert . equal ( changed . body . setup . complete , true ); assert . equal ( changed . body . library . variants . find ( v => v . id === 'qwen38-q4_k_m' ). state , 'available' ); assert . equal ( readFileSync ( keep , 'utf8' ), 'preserve' ); 95const back = await call ( '/api/storage/models-directory' ,{ directory :original }); assert . equal ( back . status , 200 ); assert . equal ( back . body . library . variants . find ( v => v . id === 'qwen38-q4_k_m' ). state , 'installed' ); assert . equal ( back . body . runtime . instances . length , 0 ); 96} finally { host . kill ( 'SIGTERM' ); await new Promise ( r => host . once ( 'exit' , r ));} 97});