okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221rc1 merge gui-fb2 (35d4781f1): two files conflicted (apps/host/server/native-control.mjs, apps/host/src/components/NativeModels.tsx), resolved at token level; images/visionPrepared take both the DeepSeek tower check and picturesMissinga2f602398

main
17.0 KiB159 linesraw
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'){
17 for(const family of native.catalog.families)for(const size of family.sizes)size.on_this_pc='does not fit';
18 native.catalog.families.find(f=>f.family==='swift').sizes[0].on_this_pc='fits';
19 native.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){
37 if(!job())throw new Error('Begin Download & load in the UI first.');
38 if(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}}}});
39 else 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'}}});
40 else if(name==='loading')Object.assign(job(),{state:'running',kind:'install',summary:'Loading model',result:{install:{running:true,step:'Loading model into memory'}}});
41 else if(name==='tuning')Object.assign(job(),{state:'running',kind:'tune',summary:'Measuring the best engine settings for this computer…'});
42 else if(name==='prepared'||name==='ready'){
43  const family=native.catalog.families.find(f=>f.family===selected.family),size=family.sizes.find(s=>s.model===selected.model);
44  size.installed=true;
45  native.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'}];
46  if(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}];}
47  if(name==='ready')native.defaultId='onboarding-model';native.summary=name==='ready'?'Model ready':'Model prepared';
48  Object.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)){
53 const family=native.catalog.families.find(f=>f.family===native.catalog.recommendation.family)??native.catalog.families[0];
54 const size=family.sizes.find(s=>s.model===native.catalog.recommendation.model)??family.sizes[0];
55 selected={family:family.family,model:size.model,context:32768,vision:family.images?'yes':'no',kv:'int8',low_ram:'auto'};
56 native.jobs.push({id:'preview-prepared',kind:'install',guided:true,model:size.model,state:'running',startedAt:new Date().toISOString(),error:null,result:null});
57 stage('prepared');
58 setup={...setup,step:4,choices:{onboarding:{step:4,family:family.family,size:size.id,context:32768,vision:false,profile:'work',calibrate:true,installJobId:'preview-prepared'}}};
59 if(process.env.STRATA_ONBOARDING_START==='ready'){
60  stage('ready');setup.complete=true;
61  if(process.env.STRATA_ONBOARDING_SCENARIO==='telemetry'){
62   const series=(base,amplitude)=>Array.from({length:60},(_,i)=>Math.round((base+Math.sin(i/6)*amplitude)*100)/100);
63   native.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
70   picture 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){
74 const family=native.catalog.families.find(f=>f.family==='qwen'),size=family.sizes.find(s=>s.model==='IQ3_S')??family.sizes[0];
75 size.installed=true;native.packaged=true;native.visionReader=true;
76 native.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'}];
77 native.instances=[];native.defaultId=null;native.jobs=[];native.summary='Ready';setup={...setup,complete:true,step:4};
78}
79function pictureLoad(body){
80 posted.push({kind:body.kind,args:body.args});
81 const family=native.catalog.families.find(f=>f.family==='qwen'),size=family.sizes.find(s=>s.id===body.args.model),id=`pictures-${native.jobs.length}`;
82 const 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}}});
83 const 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});
84  if(vision){native.installed.models[0].images='yes';native.installed.models[0].visionPrepared=true;}
85  if(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';}};
86 const 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 */
88 if(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';}
89 native.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)});
90 const at=(ms,action)=>setTimeout(()=>{const j=native.jobs.find(x=>x.id===id);if(j?.state==='running')action(j);},ms).unref();
91 if(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));}
92 else{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.'));}
93 return native.jobs.at(-1);
94}
95const server=http.createServer(async(req,res)=>{try{
96 const 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):{};
97 const json=(value,status=200)=>{res.writeHead(status,{'content-type':'application/json'});res.end(JSON.stringify(value));};
98 if(process.env.STRATA_CAPTURE_OUTPUT&&path==='/__fixture/capture'&&req.method==='POST'){
99  if(typeof body.dataUrl!=='string'||!body.dataUrl.startsWith('data:image/png;base64,'))throw new Error('A PNG export is required');
100  await writeFile(process.env.STRATA_CAPTURE_OUTPUT,Buffer.from(body.dataUrl.slice('data:image/png;base64,'.length),'base64'));
101  return json({saved:true,width:body.width,height:body.height});
102 }
103 if(process.env.STRATA_CAPTURE_OUTPUT&&path==='/__fixture/html-to-image.js'){
104  res.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 }
106 if(process.env.STRATA_CAPTURE_OUTPUT&&path==='/__fixture/export.js'){
107  res.writeHead(200,{'content-type':'text/javascript'});res.end(await readFile(resolve(import.meta.dirname,'onboarding-export.js')));return;
108 }
109 if(enginePreview&&await enginePreview.handle(path,req.method,body,json))return;
110 if(path==='/__fixture/stage'&&req.method==='POST'){stage(body.stage);return json({stage:body.stage});}
111 if(path==='/api/native'&&req.method==='GET')return json(native);
112 if(path==='/__fixture/posted'&&req.method==='GET')return json(posted);
113 if(/^\/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});}
114 if(path==='/api/native/directory'){native.downloadDirectory=body.directory;return json(native);}
115 if(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});
116 if(path==='/api/native/plan'){
117  const family=native.catalog.families.find(f=>f.family===body.family),size=family.sizes.find(s=>s.model===body.model);
118  return json({plan:{title:family.title,download_gb:size.download_gb,disk_short:null}});
119 }
120 if(path==='/api/native/operations'&&req.method==='POST'){
121  if(picturesScenario&&['load','pictures'].includes(body.kind))return json(pictureLoad(body));
122  if(!['install','tune'].includes(body.kind))throw new Error('Only fixture preparation and tuning are supported');
123  if(body.kind==='install')selected=body.args;
124  if(body.kind==='tune')loadVision=body.args.vision??'no';
125  native.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});
126  stage(body.kind==='install'?'download':'tuning');
127  if(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'));}}
128  return json(job());
129 }
130 if(/^\/api\/native\/operations\/[^/]+\/cancel$/.test(path)){Object.assign(job(),{state:'cancelled',summary:'Preparation stopped'});return json(job());}
131 if(path==='/api/setup'&&req.method==='GET')return json(setup);
132 if(path==='/api/setup/step'&&req.method==='POST'){setup={...setup,...body};return json(setup);}
133 if(path==='/api/setup/complete'&&req.method==='POST'){
134  if(!native.instances.some(i=>i.status==='ready'))throw new Error('Load a model first');
135  setup={...setup,complete:true,step:4};return json(setup);
136 }
137 if(path==='/api/workspaces')return json({workspaces:[]});
138 if(path==='/api/events'){
139  res.writeHead(200,{'content-type':'text/event-stream','cache-control':'no-cache'});res.write('data: {}\n\n');events.add(res);
140  req.on('close',()=>events.delete(res));return;
141 }
142 if(path.startsWith('/api/')){
143  if(req.method!=='GET')throw new Error('Production mutations are blocked by this fixture');
144  const response=await fetch(upstream+req.url),value=await response.json();
145  if(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'}});
146  if(path==='/api/models')value.loaded=null;
147  if(path==='/api/runtime')Object.assign(value,{instances:[],defaultId:null});
148  return json(value,response.status);
149 }
150 const file=path==='/'?'/index.html':path;if(file.includes('..'))throw new Error('Invalid fixture path');
151 let content=await readFile(root+file);
152 if(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>'));
153 res.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);