first-run feedback: combined download progress with an ETA, catalog without pictures for app installs, RAM budget for the 20% profile, human engine-start errors, installed model preferred in Models, system theme default, NSIS ignores a remembered temp install folder

This commit is contained in:
Niko1221 committed 2026-10-15 19:10:26 +02:00
1 parent 8a9d724e6e
commit 7b2082dbb0
16 files changed
+1256 -24

No files matched your search

File diff suppressed because it is too large. Load diff
+1
View File
@@ -44,6 +44,7 @@
"windows": {
"nsis": {
"installMode": "currentUser",
"template": "nsis/installer.nsi",
"compression": "lzma",
"languages": [
"English"
+2 -1
View File
@@ -11,7 +11,8 @@
// Set the saved appearance before CSS and logo images are painted.
try {
const saved = JSON.parse(localStorage.getItem('strata.prefs.v2') || localStorage.getItem('strata.prefs.v1') || '{}');
const theme = saved.theme === 'dark' || (saved.theme === 'system' && matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light';
const choice = saved.theme ?? 'system';
const theme = choice === 'dark' || (choice === 'system' && matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light';
document.documentElement.dataset.theme = theme;
document.querySelector('meta[name="theme-color"]').content = theme === 'dark' ? '#0e1113' : '#f9fafb';
} catch { document.documentElement.dataset.theme = 'light'; }
+14 -8
View File
@@ -41,6 +41,12 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};}
function sourceText(){try{return readFileSync(join(packaged?control.control.dir:preferences.repo,'serve/server.py'),'utf8');}catch{return '';}}
function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));}
const modelArena=id=>({arenaGb:(snapshot.catalog?.families??[]).flatMap(f=>f.sizes??[]).find(s=>s.id===id)?.experts_gb});
/* A start that ends with `server_exited` says nothing a person can act on. The usual cause is the PC running low on memory
(the engine's own guard, or the OS); say that, what to try, and the last thing the engine wrote. */
function humanStartError(error){const text=String(error?.message??error),tail=error?.output?.log_tail;
if(!/server_exited|exited|memory|killed|oom/i.test(text)&&!/memory|alloc|guard|killed/i.test(tail??''))return text;
return `The engine stopped before it was ready, most likely because the PC ran low on memory. Close other programs and try again, choose “Leave 20% for my work”, or turn on the low-RAM option so part of the model is read from the SSD instead of kept in memory.${tail?` Last engine message: ${tail}`:''}`;}
function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};}
function installRoot(){const found=[preferences.installDir,packagedInstall,snapshot.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());}
function repo(){if(packaged)return installRoot();const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;}
@@ -83,7 +89,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
async function refresh(force=false){
if(closing)return state();
if(refreshing)return refreshing;if(!force&&Date.now()-lastRead<15000)return state();
refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing;
refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);const noImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,images:false,sizes:(f.sizes??[]).map(s=>({...s,images:false}))}))}:c;snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:packaged?noImages(catalog):catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing;
}
function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};packagedInstall=null;disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}
function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();}
@@ -92,7 +98,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);}
function previousEngine(){try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}}
async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);return tool('strata_install',installArgs(args,false));}
function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),confirm};}
function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),...(packaged?{vision:'no'}:{}),confirm};}
function begin(kind,run,metadata={}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or cancel the current engine operation first.');const job={id:randomUUID(),kind,state:'running',startedAt:new Date().toISOString(),summary:'Starting…',result:null,error:null,...metadata};for(const [id,old] of jobs)if(jobs.size>=12&&old.state!=='running')jobs.delete(id);jobs.set(job.id,job);emit();void run(job).then(result=>{if(job.state==='running'){Object.assign(job,{state:'done',summary:result?.summary??'Complete',result,finishedAt:new Date().toISOString()});}}).catch(error=>{if(job.state==='running')Object.assign(job,{state:'error',error:error.message,summary:error.message,finishedAt:new Date().toISOString()});}).finally(()=>{if(job.kind.startsWith('update')||job.kind==='rollback')disconnect();lastRead=0;emit();void refresh(true);});return state().jobs.find(j=>j.id===job.id);}
async function watchInstall(job,current){job.summary=current.step??'Resuming preparation status…';job.result={install:current};while(job.state==='running'){await new Promise(r=>setTimeout(r,1500));const result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(!result.install?.running){if(result.install?.exit_code!==0)throw new Error(result.install?.error??'Preparation did not finish. Retry to reuse completed files.');return {summary:'Model preparation complete. Load it from Models.'};}}}
@@ -107,7 +113,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.');
const vision=runtimeVision(config,args.vision);
const visionPreferences=args.vision!==undefined?{ui_vision_enabled:args.vision!=='no',ui_vision_device:args.vision==='no'?config.ui_vision_device??'yes':args.vision}:{};
const resources=args.resourceProfile?resourceSettings({...config,vision},snapshot.hardware,args.resourceProfile):null;
const resources=args.resourceProfile?resourceSettings({...config,vision},snapshot.hardware,args.resourceProfile,modelArena(args.model)):null;
const cfg={...config,...visionPreferences,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),host:'127.0.0.1',open_browser:false,...validateNativeSettings(args.values??{}),vision};
if(args.gpus!==undefined){const detected=new Set((snapshot.hardware?.gpus??[]).map(g=>g.index));if(!Array.isArray(args.gpus)||!args.gpus.length||new Set(args.gpus).size!==args.gpus.length||args.gpus.some(g=>!Number.isInteger(g)||!detected.has(g)))throw new Error('Choose distinct detected GPUs. CPU-only text inference is not supported by this native adapter.');cfg.gpu=args.gpus.length===1?args.gpus[0]:args.gpus;cfg.layer_split=args.gpus.length>1?validateNativeSettings({layer_split:args.layerSplit??'auto'}).layer_split:'auto';if(cfg.layer_split!=='auto'&&cfg.layer_split.split(',').length!==args.gpus.length-1)throw new Error('Choose one layer split point between each pair of GPUs.');}
if(cfg.vram_reserve_mib!==undefined&&cfg.vram_reserve_mib!==null){cfg.args=[...(cfg.args??[])];const at=cfg.args.indexOf('--vram-reserve-mib');if(at>=0)cfg.args.splice(at,2);cfg.args.push('--vram-reserve-mib',String(cfg.vram_reserve_mib));}if(cfg.vision){if(cfg.vision_tokens!=null)cfg.vision={...cfg.vision,max_tokens:cfg.vision_tokens};if(cfg.vision_min_tokens!=null)cfg.vision={...cfg.vision,min_tokens:cfg.vision_min_tokens};}cfg.mcp={...(cfg.mcp??{}),...(cfg.mcp_timeout_s!=null?{timeout_s:cfg.mcp_timeout_s}:{}),...(cfg.mcp_max_rounds!=null?{max_rounds:cfg.mcp_max_rounds}:{}),...(cfg.mcp_max_result_chars!=null?{max_result_chars:cfg.mcp_max_result_chars}:{})};
@@ -134,7 +140,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
instances.set(id,instance);if(!defaultId||!args.multiple||wasDefault)defaultId=id;emit();
started=control.stop(instance.profile).catch(()=>{}).then(()=>control.saveProfile(instance.profile,configPath)).then(()=>control.start(instance.profile,{waitSeconds:300}));
started.then(()=>append(id,'Strata Control reports the engine is ready.'),error=>{append(id,error.message);});
try{await started;}catch(error){instance.status='error';instance.error=error.message;emit();throw error;}
try{await started;}catch(error){const said=humanStartError(error);instance.status='error';instance.error=said;emit();throw new Error(said);}
} else {
proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8',STRATA_API_KEY:''}});␍
instances.set(id,instance);processes.set(id,proc);if(!defaultId||!args.multiple||wasDefault)defaultId=id;␍
@@ -166,20 +172,20 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
function writeModelConfig(path,next){copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);}
async function tune(job,args){
await refresh(true);if(job.state!=='running')return;
const chosen=record(args.model);resourceSettings(chosen.config,snapshot.hardware,args.profile);
const chosen=record(args.model);resourceSettings(chosen.config,snapshot.hardware,args.profile,modelArena(args.model));
if(!chosen.entry.ready)throw new Error('Prepare the model before tuning.');
if(externalRunning().length)throw new Error('Stop the native server outside this UI before tuning.');
if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish requests before tuning.');
for(const id of [...instances.keys()])await unload(id);
if(job.state!=='running')return;
const initialValues=resourceSettings(chosen.config,snapshot.hardware,args.profile);writeModelConfig(chosen.path,{...chosen.config,...initialValues,ui_resource_profile:args.profile});
const initialValues=resourceSettings(chosen.config,snapshot.hardware,args.profile,modelArena(args.model));writeModelConfig(chosen.path,{...chosen.config,...initialValues,ui_resource_profile:args.profile});
if(args.calibrate!==false&&state().capabilities.calibration){job.summary='Measuring the best engine settings for this computer…';emit();await program(job,args);}
if(job.state!=='running')return;
const current=record(args.model),values=resourceSettings(current.config,snapshot.hardware,args.profile);
const current=record(args.model),values=resourceSettings(current.config,snapshot.hardware,args.profile,modelArena(args.model));
const next={...current.config,...values,ui_resource_profile:args.profile};
writeModelConfig(current.path,next);
job.summary='Applying your resource preference and loading the model…';emit();
const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:args.vision});
const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:current.config.vision?args.vision:'no'});
if(job.state!=='running'||!loaded?.instanceId)return;
job.summary='Checking your model’s speed…';emit();
const measured=await benchmark(job,{instanceId:loaded.instanceId});
+10 -2
View File
@@ -1,5 +1,5 @@
/** Headroom is a worker/memory budget, not a hard utilisation throttle. */
export function resourceSettings(config,hardware,profile){
export function resourceSettings(config,hardware,profile,model={}){
if(!['work','performance'].includes(profile))throw new Error('Choose a resource preference.');
const args=[...(config.args??[])];
const remove=flag=>{for(let at=args.indexOf(flag);at>=0;at=args.indexOf(flag))args.splice(at,2);};
@@ -20,5 +20,13 @@ export function resourceSettings(config,hardware,profile){
const gpuMemory=(hardware?.gpus??[]).filter(g=>placement.includes(g.index)).map(g=>g.vram_gb).filter(n=>Number.isFinite(n)&&n>0);
const reserve=profile==='work'&&gpuMemory.length?Math.max(safety,Math.floor(Math.min(...gpuMemory)*1024*.2)):safety;
remove('--vram-reserve-mib');args.push('--vram-reserve-mib',String(reserve));
return {args,vram_reserve_mib:reserve,ui_resource_baseline:baseline};
// RAM: "leave 20% for my work" keeps the model's RAM within 80% of the PC. A model whose experts do not fit there (the
// setup rule: experts plus 10 GB) keeps only that many GiB of them in RAM and reads the rest from the model files
// (--resident-budget-gib, which implies --mmap-experts). Full performance takes the budget out again.
if(baseline.ramBudget)remove('--resident-budget-gib');
const ram=Number(hardware?.ram_gb)||0,arena=Number(model?.arenaGb)||0;let ramBudget=false;
if(profile==='work'&&ram>0&&arena>0&&!['--resident-experts','--mmap-experts','--resident-budget-gib'].some(f=>args.includes(f))&&ram*.8<arena+10){
args.push('--resident-budget-gib',String(Math.max(8,Math.min(Math.floor(ram*.8)-10,Math.floor(arena/1.073741824)))));ramBudget=true;
}
return {args,vram_reserve_mib:reserve,ui_resource_baseline:{...baseline,ramBudget}};
}
+4 -2
View File
@@ -12,6 +12,7 @@ import { nativeAction, useNative, type NativeJob } from '../lib/native';
import { completeSetup, completeSetupStep, go, newSession, openSetup, selectRemoteModel, setSettingsSection, useStore } from '../lib/store';
import type { LocalModelFolder, SetupState } from '../lib/types';
import { downloadCounter, modelFolderLabel, onboardingError } from '../lib/onboarding-download';
import { useDownloadEta } from '../lib/download-eta';
import { nativeCatalogModels, catalogVersionLabel } from '../lib/native-catalog';
type Choices = NonNullable<NonNullable<SetupState['choices']>['onboarding']>;
function radioKeys(event: KeyboardEvent<HTMLDivElement>) { if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key))
@@ -66,7 +67,7 @@ export function GuidedSetup() {
navigate('chat', undefined, { settings: '1' });
}
else
go(manual ? 'models' : 'chat');
go(manual || preparing ? 'models' : 'chat');
}
catch (e) {
leaving.current = false;
@@ -161,6 +162,7 @@ export function GuidedSetup() {
return () => { cancelled = true; };
}, [step, plan, preparing, native?.available, version?.id, context, directory]);
const counter = downloadCounter(plan?.plan?.download_gb ?? version?.download_gb, progress, preparing);
const eta = useDownloadEta(preparing ? progress : undefined, installJob?.id);
const title = step === 1 ? 'State of the art. At home.' : step === 2 ? 'Select the model you want to run.' : step === 3 ? 'Downloading the model...' : tuneJob?.state === 'running' ? 'A little tuning. A better fit.' : 'How you would like to work with Strata?';
function changeDownloadFolder() { void perform(async () => { await advance(2); setFolderOpen(true); }); }
return <div className="setup guided-onboarding" data-step={step}>
@@ -183,7 +185,7 @@ export function GuidedSetup() {
</> : <div className="onboard-engine-connect"><Icon name="models" size={24}/><strong>{tr("Connect your Strata installation")}</strong><Btn onClick={() => void skip(false, 'Engine')}>{tr("Connect engine")}</Btn></div>)}
</div> : step === 3 ? <div className="onboard-prepare-stage">
<section className="onboard-download"><div className="onboard-download-identity"><Icon name="models" size={19}/><strong>{tr(selectedFamily?.title)}</strong><span>{tr(version ? catalogVersionLabel(version) : '')}</span><small>{tr(version?.model)}</small></div><OnboardingArt kind="download" progress={progress?.percent ?? 0} counter={counter}/><div className="onboard-download-info">
{tr(preparing ? <div><strong className="onboard-download-status">{tr(progress ? 'Downloading model files…' : 'Preparing your model…')}</strong><div className="onboard-progress" data-indeterminate={!progress}>{tr(progress ? <progress max={100} value={progress.percent ?? 0} aria-label={tr("Current file download progress")}/> : <span />)}</div><div className="onboard-progress-meta"><span>{tr(progress ? `${progress.percent ?? 0}% of this file` : 'Getting files ready…')}</span><button disabled={pending} onClick={() => void perform(async () => { await nativeAction(`operations/${installJob!.id}/cancel`); })}>{tr("Stop")}</button></div></div> : <>{tr(stopped ? <OnboardingError message={installJob?.error ?? 'Download stopped. Ready when you are.'} onFolder={changeDownloadFolder}/> : null)}{tr(plan?.plan?.disk_short ? <OnboardingError message={plan.plan.disk_short} onFolder={changeDownloadFolder}/> : null)}</>)}
{tr(preparing ? <div><strong className="onboard-download-status">{tr(progress ? 'Downloading model files…' : 'Preparing your model…')}</strong><div className="onboard-progress" data-indeterminate={!progress}>{tr(progress ? <progress max={100} value={progress.percent ?? 0} aria-label={tr("Current file download progress")}/> : <span />)}</div><div className="onboard-progress-meta"><span>{tr(progress ? `${progress.percent ?? 0}%${Number.isFinite(progress.done_gb) && Number.isFinite(progress.total_gb) ? ` · ${progress.done_gb!.toFixed(1)} / ${progress.total_gb!.toFixed(1)} GB` : ''}` : 'Getting files ready…')}</span><div className="onboard-progress-actions">{tr(eta ? <span aria-live="off">{eta}</span> : null)}<button disabled={pending} onClick={() => void perform(async () => { await nativeAction(`operations/${installJob!.id}/cancel`); })}>{tr("Stop")}</button></div></div></div> : <>{tr(stopped ? <OnboardingError message={installJob?.error ?? 'Download stopped. Ready when you are.'} onFolder={changeDownloadFolder}/> : null)}{tr(plan?.plan?.disk_short ? <OnboardingError message={plan.plan.disk_short} onFolder={changeDownloadFolder}/> : null)}</>)}
<small className="onboard-download-location" title={tr(folder)}><Icon name="folder" size={16}/><span><span>{tr("Save to")}</span><strong>{tr(modelFolderLabel(folder))}</strong></span>{tr(!preparing ? <button type="button" onClick={changeDownloadFolder}>{tr("Change")}</button> : null)}</small>
</div></section><OnboardingTour page={tour} onChange={setTour}/>
</div> : <div className="onboard-tune-stage">
+13 -4
View File
@@ -2,6 +2,7 @@ import { tr } from '../lib/i18n';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Screen } from './layout';
import { Btn, Dialog, ErrorNotice, Icon, Select } from './ui';
import { useDownloadEta } from '../lib/download-eta';
import { api } from '../lib/client';
import { go, setSettingsSection, selectRemoteModel, pushToast } from '../lib/store';
import { nativeAction, useNative, type NativeJob } from '../lib/native';
@@ -30,15 +31,23 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
expertSection.current?.scrollIntoView({ block: 'start', behavior: 'smooth' }); }, [expert]);
const selectedFamily = families.find(f => f.family === family || f.sizes.some(size => size.sourceFamily === family)) ?? families[0], selectedSize = selectedFamily?.sizes.find(s => s.id === size) ?? selectedFamily?.sizes[0];
const installed = native?.installed?.models.find(m => m.model === selectedSize?.id);
// A model that is already on this PC loads as it was prepared: the page shows its settings, so loading it never asks to download.
useEffect(() => { if (installed?.ready) {
if (installed.context)
setContext(installed.context);
if (installed.kv)
setKv(installed.kv as typeof kv);
setLowRam((installed.lowRamMode ?? 'auto') as typeof lowRam);
} }, [installed?.model, installed?.ready, installed?.context, installed?.kv, installed?.lowRamMode]);
const active = native?.jobs.find(j => j.state === 'running');
const job = native?.jobs.find(j => j.id === jobId) ?? (!jobId ? native?.jobs.filter(j => ['load', 'install'].includes(j.kind)).at(-1) : undefined);
const noFit = selectedSize?.on_this_pc === 'does not fit';
const values = useMemo(() => ({ family: selectedSize?.sourceFamily, model: selectedSize?.model, context, vision: selectedSize?.images ? vision : 'no', kv, low_ram: lowRam, resourceProfile, ...(expert && gpus.length ? { gpus: gpus.join(',') } : {}), loadAfter: true, multiple: expert && multiple }), [selectedSize?.sourceFamily, selectedSize?.model, context, vision, kv, lowRam, resourceProfile, gpus.join(','), expert, multiple]);
const downloadValues = { ...values, vision: selectedSize?.images ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no' };
useEffect(() => { if (!native?.catalog || family)
return; const current = native.instances.find(i => i.id === native.defaultId); const rec = native.catalog.recommendation ?? { family: null, model: null }; const loadedFamily = families.find(f => f.sizes.some(s => s.id === current?.model)); const f = loadedFamily ?? families.find(f => f.family === rec.family || f.sizes.some(s => s.sourceFamily === rec.family)) ?? families[0]; if (f) {
return; const current = native.instances.find(i => i.id === native.defaultId); const rec = native.catalog.recommendation ?? { family: null, model: null }; const loadedFamily = families.find(f => f.sizes.some(s => s.id === current?.model)); const have = new Set((native.installed?.models ?? []).filter(m => m.ready).map(m => m.model)); const installedFamily = families.find(f => f.sizes.some(s => have.has(s.id))); const f = loadedFamily ?? installedFamily ?? families.find(f => f.family === rec.family || f.sizes.some(s => s.sourceFamily === rec.family)) ?? families[0]; if (f) {
setFamily(f.family);
setSize(f.sizes.find(s => s.id === current?.model || s.model === rec.model)?.id ?? f.sizes[0]?.id ?? '');
setSize(f.sizes.find(s => s.id === current?.model)?.id ?? f.sizes.find(s => have.has(s.id))?.id ?? f.sizes.find(s => s.model === rec.model)?.id ?? f.sizes[0]?.id ?? '');
setContext(('context' in rec ? rec.context : undefined) ?? 32768);
} }, [native?.catalog]);
useEffect(() => { if (presetPending.current) {
@@ -102,7 +111,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
}
export function NativeProgress({ job }: {
job: NativeJob;
}) { const download = job.result?.install?.download; const [stopping, setStopping] = useState(false), [error, setError] = useState(''); async function stop() { setStopping(true); setError(''); try {
}) { const download = job.result?.install?.download; const eta = useDownloadEta(job.kind === 'install' ? download : undefined, job.id); const [stopping, setStopping] = useState(false), [error, setError] = useState(''); async function stop() { setStopping(true); setError(''); try {
await nativeAction(`operations/${job.id}/cancel`);
}
catch (e) {
@@ -110,4 +119,4 @@ catch (e) {
}
finally {
setStopping(false);
} } return <section className="st-card native-progress" aria-live="polite"><div className="section-toolbar"><h2 className="h4">{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : 'Engine operation')}</h2>{tr(job.kind === 'install' || job.kind === 'load' ? <Btn size="sm" disabled={stopping} onClick={() => void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}</Btn> : null)}</div><p className="small">{tr(job.kind === 'install' ? (job.result?.install?.step ?? 'Downloading and preparing model files…') : job.summary)}</p>{tr(download ? <><progress max={100} value={download.percent ?? 0}/><p className="xs muted">{tr(download.file)} · {tr(download.percent ?? 0)}%</p></> : null)}<details><summary className="small">{tr("Details")}</summary><p className="small muted">{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}</p></details>{tr(error ? <ErrorNotice message={error}/> : null)}</section>; }
} } return <section className="st-card native-progress" aria-live="polite"><div className="section-toolbar"><h2 className="h4">{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : 'Engine operation')}</h2>{tr(job.kind === 'install' || job.kind === 'load' ? <div className="onboard-progress-actions">{tr(eta ? <span className="small muted">{eta}</span> : null)}<Btn size="sm" disabled={stopping} onClick={() => void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}</Btn></div> : null)}</div><p className="small">{tr(job.kind === 'install' ? (job.result?.install?.step ?? 'Downloading and preparing model files…') : job.summary)}</p>{tr(download ? <><progress max={100} value={download.percent ?? 0}/><p className="xs muted">{tr(download.file)} · {tr(download.percent ?? 0)}%{tr(Number.isFinite(download.done_gb) && Number.isFinite(download.total_gb) ? ` · ${download.done_gb!.toFixed(1)} / ${download.total_gb!.toFixed(1)} GB` : '')}</p></> : null)}<details><summary className="small">{tr("Details")}</summary><p className="small muted">{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}</p></details>{tr(error ? <ErrorNotice message={error}/> : null)}</section>; }
+36
View File
@@ -0,0 +1,36 @@
import { useEffect, useRef, useState } from 'react';
import { tr } from './i18n';
/** Minutes left from recent samples of "GB done": the rate over the last minute and a half, so a stall or a burst does not
* swing the estimate. Null until there is enough to say (about 10 s of samples) or when nothing is moving. */
export function etaMinutes(samples: { at: number; done: number }[], remainingGb: number | undefined): number | null {
if (!Number.isFinite(remainingGb) || samples.length < 2) return null;
const first = samples[0], last = samples[samples.length - 1];
const seconds = (last.at - first.at) / 1000, gained = last.done - first.done;
if (seconds < 10 || gained <= 0) return null;
return Math.max(1, Math.ceil((remainingGb! / (gained / seconds)) / 60));
}
export function etaLabel(minutes: number | null): string {
if (minutes === null) return '';
if (minutes >= 90) { const h = Math.floor(minutes / 60), m = minutes % 60; return `${tr('About')} ${h} ${tr('h')}${m ? ` ${m} ${tr('min')}` : ''} ${tr('left')}`; }
return `${tr('About')} ${minutes} ${tr('min left')}`;
}
/** The approximate time left of a running download, for the progress bar. `key` restarts the estimate for another job. */
export function useDownloadEta(download: { done_gb?: number; remaining_gb?: number } | undefined, key: string | undefined): string {
const samples = useRef<{ at: number; done: number }[]>([]);
const owner = useRef<string | undefined>(undefined);
const [label, setLabel] = useState('');
const done = download?.done_gb, remaining = download?.remaining_gb;
useEffect(() => {
if (owner.current !== key) { owner.current = key; samples.current = []; }
if (!Number.isFinite(done)) { setLabel(''); return; }
const now = Date.now();
const list = samples.current;
if (!list.length || list[list.length - 1].done !== done) list.push({ at: now, done: done! });
while (list.length > 2 && now - list[0].at > 90_000) list.shift();
setLabel(etaLabel(etaMinutes(list, remaining)));
}, [done, remaining, key]);
return label;
}
+1 -1
View File
@@ -136,7 +136,7 @@ export interface Prefs {
const PREFS_DEFAULTS: Prefs = {
language: 'en',
fontFamily: '',
theme: 'light',
theme: 'system',
contrast: 'standard',
rail: false,
focus: false,
+1 -1
View File
@@ -26,7 +26,7 @@ export function SettingsScreen() {
{ section: 'General', label: 'Language', hint: 'Choose the language used throughout Strata.', control: <Select translateLabels={false} ariaLabel={tr("Language")} value={prefs.language} options={[...LANGUAGES]} onChange={value => setLanguage(value as typeof prefs.language)}/> },
{ section: 'Reading & focus', label: 'Font', hint: 'Choose an installed font for the interface and conversations.', control: <FontChoice /> },
{ section: 'General', label: 'Keyboard shortcuts', hint: 'Set the key combinations that feel natural to you.', aliases: 'command keys hotkeys', control: <Btn size="sm" onClick={() => setShortcuts(true)}>{tr("Edit shortcuts")}</Btn> },
{ section: 'Reading & focus', label: 'Appearance', hint: 'Light is the default. System follows your computer.', aliases: 'theme light dark system automatic', control: <Select value={prefs.theme} ariaLabel={tr("Appearance")} options={[{ value: 'light', label: 'Light' }, { value: 'dark', label: 'Dark' }, { value: 'system', label: 'System' }]} onChange={setTheme}/> },
{ section: 'Reading & focus', label: 'Appearance', hint: 'System follows your computer by default.', aliases: 'theme light dark system automatic', control: <Select value={prefs.theme} ariaLabel={tr("Appearance")} options={[{ value: 'light', label: 'Light' }, { value: 'dark', label: 'Dark' }, { value: 'system', label: 'System' }]} onChange={setTheme}/> },
{ section: 'Reading & focus', label: 'Reading size', hint: 'Conversation text size. Interface controls stay separate.', aliases: 'font text zoom', control: <label className="row"><input aria-label={tr("Reading text size")} type="range" className="st-slider" min={CONTENT_FONT_RANGE.min} max={CONTENT_FONT_RANGE.max} value={prefs.contentFontSize} onChange={e => setContentFontSize(Number(e.target.value))}/><output>{tr(prefs.contentFontSize)}{tr(" px")}</output></label> },
{ section: 'Reading & focus', label: 'Interface size', hint: 'Scale navigation and controls.', aliases: 'zoom scale 90% 100% 110% 125%', control: <Select value={String(prefs.uiScale)} ariaLabel={tr("Interface size")} options={UI_SCALES.map(v => ({ value: String(v), label: `${Math.round(v * 100)}%` }))} onChange={v => setUiScale(Number(v))}/> },
{ section: 'Reading & focus', label: 'Spacing', hint: 'Comfortable spacing by default.', aliases: 'density comfortable compact', control: <Select value={prefs.density} ariaLabel={tr("Interface spacing")} options={[{ value: 'comfortable', label: 'Comfortable' }, { value: 'compact', label: 'Compact' }]} onChange={setDensity}/> },
+1
View File
@@ -241,3 +241,4 @@
@keyframes onboard-sharing-app{0%,100%{transform:translateY(0)}50%{transform:translateY(-3px)}}
@keyframes onboard-sharing-flow{to{transform:translateX(100%)}}
@media(max-width:700px){.onboard-sharing{grid-template-columns:1fr;gap:20px;padding:22px}.onboard-sharing-computer{width:min(300px,100%);justify-self:center}.onboard-sharing-caption{font-size:14px}.onboard-sharing-numbers{justify-content:space-between;gap:20px}.onboard-sharing-headroom{padding-left:20px}.guided-onboarding .onboard-resource-options>button{padding:16px;grid-template-columns:1fr;gap:7px}.guided-onboarding .onboard-resource-options small{grid-column:1;grid-row:4;justify-self:start}.guided-onboarding .onboard-resource-options strong{font-size:13px}.guided-onboarding .onboard-resource-options p{font-size:11px}.guided-onboarding .onboard-load-vision,.guided-onboarding .onboard-calibration{padding:14px}.guided-onboarding .onboard-load-vision strong,.guided-onboarding .onboard-calibration strong{font-size:12px}}
.onboard-progress-actions{display:flex;align-items:center;gap:10px}
+30 -2
View File
@@ -97,6 +97,7 @@ function packagedFixture({ engineUsable = true } = {}) {
const calls = [];
const spawned = [];
const rpc = [];
let startFailure = null;
const control = {
control: { dir: join(root, 'control'), python: join(root, 'control', 'python', 'python.exe') }, version: '0.1.45',
async installedModels(options) { calls.push(['installedModels', options?.installDir ?? null]); return { install_dir: install, models: configs.map(c => ({ id: c.id, name: `Qwen ${c.id}`, source_config: c.path, component_status: 'present', context_tokens: 32768, backend: 'cuda' })) }; },
@@ -107,7 +108,7 @@ function packagedFixture({ engineUsable = true } = {}) {
: { usable: false, notice: 'No engine for this PC was found in E:\\c: the component folder holds no engine package. The app never downloads an engine while it starts or serves.', backend: 'cuda', engine: null, components_dir: 'E:\\c' };
},
async saveProfile(name, path) { calls.push(['saveProfile', name, basename(path)]); return {}; },
async start(name, options) { calls.push(['start', name, options?.waitSeconds]); return { ok: true, state: 'ready' }; },
async start(name, options) { calls.push(['start', name, options?.waitSeconds]); if (startFailure) { const e = new Error(startFailure.message); e.output = startFailure.output; throw e; } return { ok: true, state: 'ready' }; },
async stop(name) { calls.push(['stop', name]); return { ok: true, state: 'stopped' }; },
};
const requests = [];
@@ -142,7 +143,7 @@ function packagedFixture({ engineUsable = true } = {}) {
};
const native = createNativeControl({ control, directory: data, spawnProcess, fetcher, requests: () => requests });
const others = () => spawned.filter(s => !String(s.args[0]).endsWith('strata_mcp.py'));
return { native, calls, spawned, others, rpc, catalog, hardware, install, root, cleanup: () => { rmSync(root, { recursive: true, force: true }); } };
return { native, calls, spawned, others, rpc, failStart: v => { startFailure = v; }, catalog, hardware, install, root, cleanup: () => { rmSync(root, { recursive: true, force: true }); } };
}
const finish = async (native, id) => { for (let i = 0; i < 400; i++) { const job = native.state().jobs.find(j => j.id === id); if (job.state !== 'running') return job; await new Promise(r => setTimeout(r, 10)); } throw new Error('job did not finish'); };
@@ -283,3 +284,30 @@ test('createControl asks the CLI for the engine, models and runtime and reads th
]);
assert.equal(createControl({ control: null }), null);
});
test('packaged: the catalog offers no picture reading (app installs have none), and an install asks for none', async () => {
const f = packagedFixture();
try {
const state = await f.native.refresh(true);
assert.ok(state.catalog.families[0].sizes.every(s => s.images === false));
assert.ok(state.catalog.families.every(fam => fam.images === false));
await f.native.plan({ family: 'qwen', model: 'Q2_0', vision: 'yes' });
assert.equal(f.rpc.at(-1).arguments.vision, 'no');
} finally { await f.native.close(); f.cleanup(); }
});
test('packaged: an engine that stops while loading is explained in words, with the engine\'s last line', async () => {
const f = packagedFixture();
try {
await f.native.refresh(true);
const control = f.native;
// the fixture's Control starts fine; make start fail the way Control reports a dead engine
f.failStart({ message: 'server_exited', output: { log_tail: 'memory guard: 5.1 GiB free is under the 6 GiB limit' } });
const job = await finish(control, control.operation('load', { model: 'iq2_xs' }).id);
assert.equal(job.state, 'error');
assert.match(job.error, /ran low on memory/);
assert.match(job.error, /Leave 20% for my work/);
assert.match(job.error, /memory guard: 5\.1 GiB free/);
assert.doesNotMatch(job.error, /^server_exited$/);
} finally { await f.native.close(); f.cleanup(); }
});
+31
View File
@@ -0,0 +1,31 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { resourceSettings } from '../server/native-resources.mjs';
const pc64 = { cpu: { cores: 12 }, ram_gb: 63, gpus: [{ index: 0, name: 'NVIDIA GeForce RTX 5070', vram_gb: 11.9 }] };
const iq3s = { arenaGb: 50.3 };
const config = { gpu: 0, args: ['--native', 'x.gguf', '--max-context', '32768', '--pool-workers', '12'] };
const flag = (args, name) => args[args.indexOf(name) + 1];
test('"leave 20% for my work" keeps the model within 80% of the RAM: a RAM budget for the experts', () => {
const work = resourceSettings(config, pc64, 'work', iq3s);
assert.ok(work.args.includes('--resident-budget-gib'), 'a model whose experts do not fit 80% of 63 GB gets a RAM budget');
const gib = Number(flag(work.args, '--resident-budget-gib'));
assert.ok(gib + 10 <= 63 * 0.8, `${gib} GiB plus the 10 GB the rest needs stays inside 80% of the RAM`);
assert.equal(work.ui_resource_baseline.ramBudget, true);
});
test('full performance takes that budget out again and keeps what the installation had', () => {
const work = resourceSettings(config, pc64, 'work', iq3s);
const back = resourceSettings({ ...config, args: work.args, ui_resource_profile: 'work', ui_resource_baseline: work.ui_resource_baseline }, pc64, 'performance', iq3s);
assert.equal(back.args.includes('--resident-budget-gib'), false);
assert.equal(flag(back.args, '--pool-workers'), '12');
});
test('a model that fits, or one that already has a RAM mode, is left alone', () => {
assert.equal(resourceSettings(config, { ...pc64, ram_gb: 128 }, 'work', iq3s).args.includes('--resident-budget-gib'), false);
assert.equal(resourceSettings(config, pc64, 'work', { arenaGb: 34 }).args.includes('--resident-budget-gib'), false, 'Q2_0 fits 80% of 63 GB with 10 to spare');
const own = { ...config, args: [...config.args, '--mmap-experts'] };
assert.equal(resourceSettings(own, pc64, 'work', iq3s).args.includes('--resident-budget-gib'), false);
assert.equal(resourceSettings(config, pc64, 'work').args.includes('--resident-budget-gib'), false, 'no model size, no change');
});
+12 -1
View File
@@ -797,6 +797,17 @@ class Host:
if "error" in result:
self.last_error = result["error"]
def _log_tail(self, limit: int = 4096) -> str | None:
"""The last line the server wrote (a failed start is explained by it), or None. Bounded read, never raises."""
try:
with open(self.state_path.parent / f"{self.name}.server.log", "rb") as stream:
stream.seek(0, os.SEEK_END)
stream.seek(max(0, stream.tell() - limit))
lines = [x.strip() for x in stream.read().decode("utf-8", "replace").splitlines() if x.strip()]
except OSError:
return None
return lines[-1][:300] if lines else None
def _status(self) -> dict:
child = self.child
base = {"ok": True, "profile": self.name, "host_pid": os.getpid(),
@@ -809,7 +820,7 @@ class Host:
return {**base, "state": "stopped"}
if child.poll() is not None:
return {**base, "ok": False, "state": "failed", "exit_code": child.returncode,
"error": self.last_error or "server_exited"}
"error": self.last_error or "server_exited", "log_tail": self._log_tail()}
if self.ready_path is not None:
try:
ready = json.loads(self.ready_path.read_text(encoding="utf-8"))
+26
View File
@@ -191,6 +191,32 @@ class InstallerServerTests(unittest.TestCase):
self.assertFalse((self.root / ".venv").exists(), "no virtual environment, no pip")
self.assertIsNotNone(s)
def test_a_two_file_model_has_one_combined_progress(self):
"""The bar went 70 GB -> 0 -> up again because each file reported its own total. One total for the whole model now."""
folder = self.root / "Strata-data" / "models" / "IQ3_S"
folder.mkdir(parents=True)
job = {"folder": str(folder), "total_gb": 0.004}
step5 = {"step": "5/7: downloading Qwen3.8-Flash-Next IQ3_S"}
seen = []
# file 1 downloading, then complete, then file 2 starts: the combined figure only goes up
for name, size in (("a.gguf.part", 400_000), ("a.gguf.part", 1_500_000)):
(folder / name).write_bytes(b"x" * size)
seen.append(self.mcp.combined_progress(dict(step5), job)["download"])
(folder / "a.gguf.part").rename(folder / "a.gguf")
(folder / "b.gguf.part").write_bytes(b"x" * 100_000)
seen.append(self.mcp.combined_progress(dict(step5), job)["download"])
(folder / "b.gguf.part").write_bytes(b"x" * 1_000_000)
seen.append(self.mcp.combined_progress(dict(step5), job)["download"])
done = [d["done_gb"] for d in seen]
self.assertEqual(done, sorted(done), done)
self.assertEqual(seen[-1]["total_gb"], 0.004)
self.assertAlmostEqual(seen[-1]["remaining_gb"], 0.004 - seen[-1]["done_gb"], places=2)
self.assertTrue(all(d["file"] == "model files" for d in seen))
# not a download any more once setup is preparing the files
self.assertNotIn("download", self.mcp.combined_progress({"step": "6/7: preparing the model for Strata", "download": {"x": 1}}, job))
# a resumed install counts what is already on disk
self.assertGreater(self.mcp.combined_progress(dict(step5), job)["download"]["done_gb"], 0)
@unittest.skipUnless(os.name == "nt" or sys.platform.startswith("linux"), "a PC with a GPU probe")
def test_a_real_install_reaches_the_model_download_with_nothing_else_acquired(self):
"""setup.py in the app's mode, as the install job runs it: steps 1-4 pass (PC check, packages bundled, engine component
+30 -2
View File
@@ -847,6 +847,7 @@ class Strata:
log_path = Path(j.get("log", ""))
tail = read_tail(log_path, 400) if log_path.name else []
prog = install_progress(tail)
prog = combined_progress(prog, j)
out = {"running": running, "started": j.get("started"), "model": j.get("model"), "family": j.get("family"),
"log": str(log_path), **prog}
if not running:
@@ -862,6 +863,31 @@ class Strata:
return out
def combined_progress(prog: dict, job: dict) -> dict:
"""One total for the whole model: the bytes of all its files (finished, partial and the one in flight, read from the
model's folder) over the download size, instead of each file's own 0-100% (a two-file model went 70 GB -> 0 -> up
again). Only while the download step runs; later steps are not a download."""
folder, total = job.get("folder"), job.get("total_gb")
step = str(prog.get("step") or "")
if not folder or not total or not step.startswith("5/"):
prog.pop("download", None)
return prog
done = 0
try:
for entry in os.scandir(folder):
if entry.is_file() and (entry.name.endswith(".gguf") or entry.name.endswith(".part")):
done += entry.stat().st_size
except OSError:
pass
if not done: # nothing on disk yet: the log's own line is all there is
return prog
done_gb = min(done / 1e9, float(total))
prog["download"] = {"file": "model files", "done_gb": round(done_gb, 3), "total_gb": float(total),
"remaining_gb": round(max(0.0, float(total) - done_gb), 3),
"percent": min(99, int(100 * done_gb / float(total))) if total else 0}
return prog
def install_progress(lines: list[str]) -> dict:
"""setup's progress from its output: the step, a download's percentage, a failure."""
step, title, dl, err = None, None, None, None
@@ -1305,7 +1331,8 @@ class Tools:
installed = (s.root / f"strata-{tag.lower()}.json").exists()
plan = {"title": f"{families[family]['title']} {model}", "family": family, "model": model,
"context": context, "images": vision or "no", "download_gb": models[model]["download_gb"],
"partly_downloaded": partly, "ram": fit, "data_folder": str(target), "disk_free_gb": free,
"partly_downloaded": partly, "ram": fit, "data_folder": str(target), "model_folder": str(have_dir),
"disk_free_gb": free,
"disk_needed_gb": round(need), "disk_short": short, "already_installed": installed,
"setup_command": ("START-HERE.bat " if WIN else "./setup.sh ") + " ".join(args),
"takes": "about 20-90 minutes, mostly the download; the PC stays usable",
@@ -1342,7 +1369,8 @@ class Tools:
if ident is None and p.poll() and s.state("install-result").get("job") != job_id:
raise ToolError("setup did not start: " + " | ".join(read_tail(log_path, 5)))
s.save_state("install", {"job": job_id, "pid": p.pid, "ident": ident, "log": str(log_path),
"model": plan["model"], "family": plan["family"],
"model": plan["model"], "family": plan["family"], "folder": plan.get("model_folder"),
"total_gb": plan.get("download_gb"),
"started": time.strftime("%Y-%m-%d %H:%M:%S"), "args": args})
return {"summary": f"Install of {plan['title']} started in the background (about 20-90 minutes, mostly the "
f"{plan['download_gb']:.0f} GB download). Call strata_install again to see the progress; "