diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjs index 6f352b54..0447572d 100644 --- a/apps/host/server/control-runtime.mjs +++ b/apps/host/server/control-runtime.mjs @@ -207,6 +207,23 @@ export function createControl({ control = findControl(), env = process.env, run if (result.json?.plan && Array.isArray(result.json.plan.issues)) return result.json.plan; throw failure(result, 'The files could not be checked.'); }, + /** What picking `to` as the models folder means (sizes, free space, which choices are possible, why not): nothing is changed. */ + async planModelsMove(from, to) { + const result = await call(['models', 'move', to, ...(from ? ['--from', from] : []), '--plan', '--output', 'json'], { timeoutMs: 120_000 }); + if (result.json?.plan) return result.json.plan; + throw failure(result, 'The folder could not be checked.'); + }, + /** + * Move the model files to `to` (copied, checked, then the old copies removed). `onEvent` gets the progress lines; a file at `cancelFile` stops it + * safely. Resolves with the summary (done / stopped, what moved, what is left); a failure is a ControlError whose `output` carries the details. + */ + async moveModels(from, to, { installDir = null, cancelFile = null, onEvent = null } = {}) { + const args = ['models', 'move', to, ...(from ? ['--from', from] : []), ...(installDir ? ['--install-dir', installDir] : []), ...(cancelFile ? ['--cancel-file', cancelFile] : []), '--output', 'jsonl']; + const result = await call(args, { timeoutMs: 24 * 3600_000, onLine: onEvent ?? (() => {}) }); + if (result.json?.ok && result.json.event === 'result') return result.json; + const error = result.json?.error; + throw Object.assign(new ControlError(error?.message ?? (result.stderr.split(/\r?\n/).filter(Boolean).pop() || 'The models could not be moved.'), { exitCode: result.code, output: result.json }), { code: error?.code ?? 'move_failed', details: error?.details ?? '' }); + }, async saveProfile(name, configPath) { const listed = await call(['profile', 'list', '--output', 'json'], { timeoutMs: 20_000 }); const known = (listed.json?.profiles ?? []).some(p => p.id === name); diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 30a5557a..eb454cb4 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -966,6 +966,14 @@ async function api(req, res, path, method, url) { if(path==='/api/native'&&method==='GET')return json(res,200,await native.refresh(url.searchParams.get('refresh')==='1')); if(path==='/api/native'&&method==='PATCH')return json(res,200,await native.configure(await readBody(req))); if(path==='/api/native/directory'&&method==='POST')return json(res,200,native.setDownloadDirectory((await readBody(req)).directory)); + /* Settings > Storage > Models folder: pick (or type) a folder, say what it means, then start the choice. Copying is Control's (strata models move). */ + if(path==='/api/native/models-folder/plan'&&method==='POST'){ + const typed=await typedFolder((await readBody(req)).path,{isAbsolute}); + const picked=typed?{path:typed}:await chooseFolder('Choose a folder for your models'); + if(picked.unavailable){const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});} + if(picked.cancelled)return json(res,200,{cancelled:true}); + return json(res,200,{plan:await native.planModelsFolder(picked.path)});} + if(path==='/api/native/models-folder/start'&&method==='POST'){const body=await readBody(req);const result=await native.startModelsFolder({folder:body.path,choice:body.choice,stopRunning:body.stopRunning===true});return json(res,result.id?202:200,result);} if(path==='/api/native/plan'&&method==='POST')return json(res,200,await native.plan(await readBody(req))); if(path==='/api/native/operations'&&method==='POST'){if(storageChanging)return error(res,409,'Wait for the model folder check to finish.');const body=await readBody(req);return json(res,202,native.operation(body.kind,body.args));} if(path==='/api/native/logs'&&method==='GET')return json(res,200,{logs:native.logs()}); @@ -1010,7 +1018,7 @@ async function api(req, res, path, method, url) { if(nativeSettingsFile&&method==='POST')return json(res,200,await native.openSettingsFile(nativeSettingsFile[1])); // Credentials are handled only on the host. Responses and events expose a key-set flag. - return error(res,404,'Unknown native control action.');}catch(e){return error(res,/Finish|Unload|running|current operation/.test(e.message)?409:400,e.message);}} + return error(res,404,'Unknown native control action.');}catch(e){return error(res,/Finish|Unload|running|current operation/.test(e.message)?409:400,e.message,{...(e.code&&typeof e.code==='string'?{code:e.code}:{}),...(e.details?{details:String(e.details)}:{})});}} if (path === '/api/model-providers' && method === 'GET') return json(res, 200, withPictureAnswers(modelProviders.list())); if (path === '/api/model-providers/discover' && method === 'POST') { diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 618abeed..75f7c0ce 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -2,8 +2,8 @@ import { spawn } from 'node:child_process'; import {chooseParallel,applyParallel,withoutParallel,FALLBACK_NOTE} from './native-parallel.mjs'; import { randomBytes, randomUUID, createHash } from 'node:crypto'; -import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs'; -import { join, resolve, dirname, basename } from 'node:path'; +import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, rmSync, statfsSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs'; +import { join, resolve, dirname, basename, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createServer } from 'node:net'; import { NATIVE_FIELDS, APP_OWNED_FIELDS, withoutDraftLayer, validateNativeSettings, validateMcpServers, publicMcpServers, publicNativeEnv, restoreNativeEnv } from './native-settings.mjs'; @@ -52,7 +52,8 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp let defaultId=null,timer=null,closing=false,polling=false; const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);}; const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();}; - function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,mcpServers,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,engineAbort,rawResult,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),componentUpdates:packaged&&typeof control.update==='function',calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};} + function diskSpace(path){try{const s=statfsSync(path);return {free:Number(s.bavail)*Number(s.bsize),total:Number(s.blocks)*Number(s.bsize)};}catch{return null;}} + function state(){const folder=preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),space=folder?diskSpace(folder):null;return {...snapshot,downloadDirectory:folder,downloadFreeBytes:space?.free??null,downloadTotalBytes:space?.total??null,fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,mcpServers,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,engineAbort,rawResult,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),componentUpdates:packaged&&typeof control.update==='function',calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};} let sourceCache={path:'',time:0,text:''}; function sourceText(){try{const path=join(packaged?control.control.dir:preferences.repo,'serve/server.py'),time=statSync(path).mtimeMs;if(sourceCache.path===path&&sourceCache.time===time)return sourceCache.text;sourceCache={path,time,text:readFileSync(path,'utf8')};return sourceCache.text;}catch{return '';}} function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:APP_OWNED_FIELDS.includes(field.id)||field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));} @@ -126,7 +127,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp 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})]);let visionReader=false;if(packaged){try{const e=await control.engine();const root=e?.engine?.root??(e?.engine?.exe?dirname(e.engine.exe):'');visionReader=!!root&&['strata-vision','strata-vision.exe'].some(n=>existsSync(join(root,n)));}catch{visionReader=false;}}const markImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,imagesCapable:!!f.images,images:!!f.images&&visionReader,sizes:(f.sizes??[]).map(s=>({...s,imagesCapable:!!s.images,images:!!s.images&&visionReader}))}))}: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:markEngine(packaged?markImages(catalog):catalog,status.engine),engineInfo:{version:status.engine?.version??null,source:status.engine?.source??null},visionReader:packaged?visionReader:true,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;});const run=refreshing;if(!force&&snapshot.available){run.catch(()=>{});return state();}return run; } 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.');let path;try{path=realpathSync(input.trim());}catch{throw new Error('That folder does not exist. Check the path, or that the drive is connected.');}if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');/* A whole drive (D:\) is not filled with models: D:\Strata is made and used. */if(isDriveRoot(path)){const own=dataFolderFromPick(path).path;makeFolder(own);path=realpathSync(own);}try{accessSync(path,constants.R_OK|constants.W_OK);}catch{throw new Error('Strata cannot write in that folder. Choose a folder you can save files in.');}preferences={...preferences,downloadDirectory:path};/* the same choice for the installer and the Terminal: the Control settings file */if(packaged)rememberDataFolder(controlSettingsFile(),path,Date.now()/1000,true);writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});shareDataFolder();emit();return state();} + function setDownloadDirectory(input,{insideJob=false}={}){if(!insideJob&&[...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.');let path;try{path=realpathSync(input.trim());}catch{throw new Error('That folder does not exist. Check the path, or that the drive is connected.');}if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');/* A whole drive (D:\) is not filled with models: D:\Strata is made and used. */if(isDriveRoot(path)){const own=dataFolderFromPick(path).path;makeFolder(own);path=realpathSync(own);}try{accessSync(path,constants.R_OK|constants.W_OK);}catch{throw new Error('Strata cannot write in that folder. Choose a folder you can save files in.');}preferences={...preferences,downloadDirectory:path};/* the same choice for the installer and the Terminal: the Control settings file */if(packaged)rememberDataFolder(controlSettingsFile(),path,Date.now()/1000,true);writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});shareDataFolder();emit();return state();} function recordFile(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path};} function record(model){const {entry,path}=recordFile(model);return {entry,path,config:readJson(path)};} /* The text file a power user edits by hand: where it is and what is wrong in it (run-config-check.mjs). */ @@ -377,10 +378,77 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} return autotuner.start(job,job.kind==='recheck'?'recheck':'tune',{configPath:path,presetId:args.presetId,mode:args.mode,use:args.use,goal:room?'room':'speed',leaveRam:room?20:0,allowSmallDifferences:args.allowSmallDifferences===true,name:args.name},{onProgress:p=>{job.summary=p.text??job.summary;emit();}}); } function operation(kind,args={}){if(!['install','load','benchmark','tune','autotune','recheck','calibrate','update-engine','update-strata','rollback','remove'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');if(kind==='install'||kind==='load'){const refusal=engineRefusal(snapshot.catalog,args.model,snapshot.engineInfo);if(refusal)throw new Error(refusal);}return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):kind==='autotune'||kind==='recheck'?autotune(job,args):kind==='remove'?removeModel(job,args):program(job,args),{guided:args.guided===true,model:args.model,...(args.family?{family:args.family}:{})});} - async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install'){job.engineAbort?.abort();await tool('strata_install',{cancel:true});}else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate','autotune','recheck'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} + /* ---- The models folder card (0.2.2): what a picked folder means, and the three choices. The copying is Control's (strata models move). ---- */ + const currentModelsFolder=()=>preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder)??null; + const moveFile=()=>join(directory,'models-move.cancel'); + const folderWords=error=>({message:error.message,details:error.details||''}); + /** A picked folder as the data folder: a whole drive (D:\) becomes D:\Strata, and the person is told (the models then live in D:\Strata\Models). */ + function pickedModelsFolder(input){ + if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a models folder.'); + const picked=resolve(input.trim()),target=dataFolderFromPick(picked); + return {picked,folder:target.path,wholeDrive:!!target.note,shown:target.note?join(target.path,'Models'):target.path}; + } + async function planModelsFolder(input){ + if(!packaged)throw new Error('Changing the models folder is part of the Strata app.'); + const now=currentModelsFolder();if(!now)throw new Error('Strata is still reading your models folder. Try again in a moment.'); + const pick=pickedModelsFolder(input),plan=await control.planModelsMove(now,pick.folder); + return {...plan,...pick,current:now,running:instances.size,busy:[...jobs.values()].some(j=>j.state==='running')}; + } + /* "Start empty": the old models are no longer listed. Their run configs are moved (not deleted) into old-models beside the others; the model files are not touched. */ + function setAsideConfigs(old){ + const folder=repo(),kept=join(folder,'old-models'),aside=[]; + const under=value=>typeof value==='string'&&[ 'models','packs','mtp' ].some(item=>{const base=join(old,item).toLowerCase();const v=value.toLowerCase();return v===base||v.startsWith(base+sep)||v.startsWith(base+'/');}); + const scan=value=>Array.isArray(value)?value.some(scan):value&&typeof value==='object'?Object.values(value).some(scan):under(value); + for(const name of readdirSync(folder)){ + if(!/^strata-[a-z0-9_-]+\.json$/i.test(name)||name.endsWith('.shared-settings.json'))continue; + if(!scan(readJson(join(folder,name))))continue; + mkdirSync(kept,{recursive:true});renameSync(join(folder,name),join(kept,name));aside.push(name); + } + return aside; + } + async function startModelsFolder({folder:input,choice,stopRunning=false}){ + if(!packaged)throw new Error('Changing the models folder is part of the Strata app.'); + if(!['move','keep','empty'].includes(choice))throw new Error('Choose what to do with your models.'); + if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or stop the download to change the folder.'); + const plan=await planModelsFolder(input); + if(plan.issue)throw Object.assign(new Error(plan.issue.message),{details:plan.issue.details,code:plan.issue.code}); + if(!plan.choices[choice].possible)throw Object.assign(new Error(plan.choices[choice].reason||'That choice is not possible here.'),{code:'not_possible'}); + if(instances.size){ + if(!stopRunning)throw Object.assign(new Error('A model is running. Stop it first, then change the folder.'),{code:'running'}); + for(const id of [...instances.keys()])await unload(id); + } + const old=plan.current,target=plan.folder; + if(choice!=='move'){ + makeFolder(target); + const aside=choice==='empty'?setAsideConfigs(old):[]; + setDownloadDirectory(target);lastRead=0;await refresh(true); + return {done:true,choice,folder:target,oldFolder:old,setAside:aside}; + } + rmSync(moveFile(),{force:true}); + return begin('models-move',async job=>{ + job.cancelFile=moveFile();job.summary='Starting…'; + try{ + const result=await control.moveModels(old,target,{installDir:repo(),cancelFile:moveFile(),onEvent:event=>{ + if(event.event!=='progress')return; + job.progress={done:event.done,total:event.total,file:event.file,group:event.group,index:event.index,count:event.count,secondsLeft:event.seconds_left||0,sameDrive:!!event.same_drive}; + job.summary=`${Math.round(event.done/1e8)/10} of ${Math.round(event.total/1e8)/10} GB`;emit();}}); + const finished={done:!!result.done,stopped:!!result.stopped,moved:result.moved??[],remaining:result.remaining??[],bytes:result.bytes_moved??0,total:result.total_bytes??0,from:old,to:target,files:result.files_moved??0,sameDrive:!!result.same_drive}; + /* Only a whole move changes the folder the app uses: a stopped move leaves it where it was, and every model works where it is. */ + if(result.done){setDownloadDirectory(target,{insideJob:true});finished.folder=target;} + job.progress=null; + return {summary:result.done?'Your models are moved.':'Moving stopped. Nothing was lost.',...finished}; + }catch(error){ + const left=error.output; + job.result={failed:true,code:error.code,moved:left?.moved??[],remaining:left?.remaining??[],bytes:left?.bytes_moved??0,total:left?.total_bytes??0,from:old,to:target}; + job.progress=null; + throw error; + }finally{rmSync(moveFile(),{force:true});} + },{family:undefined}); + } + async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install'){job.engineAbort?.abort();await tool('strata_install',{cancel:true});}else if(job.kind==='models-move'){/* a safe stop: the copy in flight is dropped, files already moved stay */try{writeFileSync(job.cancelFile,'stop');}catch{/* the run ends anyway */}job.summary='Stopping…';emit();return state();}else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate','autotune','recheck'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} async function close(){closing=true;clearInterval(timer);const installing=packaged&&child&&[...jobs.values()].some(j=>j.kind==='install'&&j.state==='running');if(installing)await send('tools/call',{name:'strata_install',arguments:{cancel:true}},15000).catch(()=>{});const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();} // Remove nonserializable process references from public jobs. const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,engineAbort,rawResult,...job})=>job);return value;}; async function localPreview(path){if(!packaged)throw new Error('Checking local model files is part of the Strata app.');if(typeof path!=='string'||!path.trim()||[...path].some(c=>c.charCodeAt(0)<32))throw new Error('Choose a folder.');return control.importPlan(path.trim());} - return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,plan,settings,save,settingsFile,openSettingsFile,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; + return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,planModelsFolder,startModelsFolder,plan,settings,save,settingsFile,openSettingsFile,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; } diff --git a/apps/host/src/components/ModelsFolderDialog.tsx b/apps/host/src/components/ModelsFolderDialog.tsx new file mode 100644 index 00000000..bf628542 --- /dev/null +++ b/apps/host/src/components/ModelsFolderDialog.tsx @@ -0,0 +1,230 @@ +import { tr, localeTag } from '../lib/i18n'; +import { useEffect, useMemo, useState } from 'react'; +import { Bar, Btn, Dialog, Icon } from './ui'; +import { api, ApiError } from '../lib/client'; +import { nativeAction, refreshNative, useNative, type NativeJob, type NativeState } from '../lib/native'; +import { nativeShortName } from '../lib/native-names'; +import { sizeGb } from '../lib/format'; + +type Choice = 'move' | 'keep' | 'empty'; +interface Plan { + ok: boolean; + issue: { code: string; message: string; details: string } | null; + old: string; new: string; same_drive: boolean; + free_bytes: number; models_bytes: number; needed_bytes: number; + models: { group: string; name: string; bytes: number }[]; + choices: Record; + folder: string; picked: string; wholeDrive: boolean; shown: string; current: string; running: number; busy: boolean; +} +interface Outcome { done?: boolean; stopped?: boolean; failed?: boolean; code?: string; moved?: string[]; remaining?: string[]; bytes?: number; total?: number; from?: string; to?: string; sameDrive?: boolean } + +const gb = (bytes: number) => sizeGb(bytes / 1e9); +const driveOf = (path: string) => /^[A-Za-z]:/.test(path) ? path.slice(0, 2) : path; +const list = (items: string[]) => { try { return new Intl.ListFormat(localeTag(), { type: 'conjunction' }).format(items); } catch { return items.join(', '); } }; + +/** The model a folder name belongs to, in the words the Storage list uses ("Gyro-S"); the draft layer and loose files have no name of their own. */ +function modelName(group: string, native: NativeState | null) { + const hit = native?.installed?.models.find(m => m.model.toLowerCase() === group.toLowerCase()); + return hit ? nativeShortName(hit.model) : null; +} + +function timeLeft(seconds: number) { + if (seconds <= 0) return null; + if (seconds < 60) return tr('Less than a minute left'); + const minutes = Math.ceil(seconds / 60); + if (minutes <= 1) return tr('About a minute left'); + if (minutes < 120) return tr('About {0} minutes left', [minutes]); + return tr('About {0} hours left', [Math.ceil(minutes / 60)]); +} + +function Failure({ message, next, details }: { message: string; next?: string; details?: string }) { + return
{tr(message)}{next ?

{tr(next)}

: null}{details ?
{tr('Details')}
{details}
: null}
; +} + +/** Settings > Storage > Models folder: the card, the folder dialog with its three choices, the progress of a move and what came of it. */ +export function ModelsFolderCard({ blocked }: { blocked: boolean }) { + const native = useNative(); + const [plan, setPlan] = useState(null); + const [stage, setStage] = useState<'issue' | 'drive' | 'choose' | null>(null); + const [choice, setChoice] = useState('move'); + const [pending, setPending] = useState(false); + const [error, setError] = useState<{ message: string; details?: string } | null>(null); + const [typing, setTyping] = useState(false), [typed, setTyped] = useState(''); + const [jobId, setJobId] = useState(null); + const [outcome, setOutcome] = useState<{ job: NativeJob } | null>(null); + const [notice, setNotice] = useState(''); + const [stopping, setStopping] = useState(false); + const folder = native?.downloadDirectory ?? ''; + const free = native?.downloadFreeBytes ?? null; + const usage = native?.installed?.usage?.total_bytes ?? 0; + const moving = native?.jobs.find(j => j.kind === 'models-move' && j.state === 'running') ?? null; + const finished = jobId ? native?.jobs.find(j => j.id === jobId && j.kind === 'models-move' && j.state !== 'running') : undefined; + useEffect(() => { if (finished && !outcome) { setOutcome({ job: finished }); setStopping(false); void refreshNative(true); } }, [finished, outcome]); + const total = native?.downloadTotalBytes ?? null; + const used = free !== null && total ? Math.min(100, Math.max(1, ((total - free) / total) * 100)) : 0; + useEffect(() => { if (moving && !jobId) setJobId(moving.id); }, [moving, jobId]); + + function leave() { setPlan(null); setStage(null); setError(null); setTyping(false); } + async function pick(path = '') { + setPending(true); + setError(null); + setNotice(''); + try { + const result = await api.post<{ cancelled?: boolean; plan?: Plan }>('/api/native/models-folder/plan', { path }); + if (result.cancelled || !result.plan) return; + const next = result.plan; + setTyping(false); + setPlan(next); + if (next.issue?.code === 'same') { setPlan(null); return; } + setChoice(next.choices.move.possible ? 'move' : 'keep'); + setStage(next.issue ? 'issue' : next.wholeDrive ? 'drive' : 'choose'); + } + catch (e) { + if (e instanceof ApiError && e.status === 501) { setTyping(true); setError({ message: e.message }); } + else setError({ message: (e as Error).message, details: ((e as ApiError).body as { details?: string } | undefined)?.details }); + } + finally { setPending(false); } + } + async function start() { + if (!plan) return; + setPending(true); + setError(null); + try { + const result = await api.post('/api/native/models-folder/start', { path: plan.picked, choice, stopRunning: true }); + if (result.id) { setJobId(result.id); setOutcome(null); setStage(null); await refreshNative(true); setPlan(prev => prev); return; } + setNotice(choice === 'keep' ? tr('Strata now also uses {0}. New downloads go there, and your current models stay where they are.', [plan.shown]) + : tr('Strata now uses {0}. Your old model files are still in {1}; Strata does not delete them.', [plan.shown, plan.current])); + await refreshNative(true); + leave(); + } + catch (e) { setError({ message: (e as Error).message, details: ((e as ApiError).body as { details?: string } | undefined)?.details }); } + finally { setPending(false); } + } + async function stop() { + if (!moving) return; + setStopping(true); + try { await nativeAction(`operations/${moving.id}/cancel`); } + catch (e) { setError({ message: (e as Error).message }); } + } + function closeResult() { setOutcome(null); setJobId(null); leave(); setNotice(''); } + + const progress = moving?.progress as { done: number; total: number; file: string; group: string; index: number; count: number; secondsLeft: number; sameDrive: boolean } | null | undefined; + const percent = progress && progress.total > 0 ? Math.round((progress.done / progress.total) * 100) : 0; + const planNames = useMemo(() => (plan?.models ?? []).map(m => ({ ...m, label: modelName(m.group, native) })).filter(m => m.label), [plan, native]); + const savedPlan = useMemo(() => plan, [plan]); + + return <> +
+
{tr('Models folder')} void pick()}>{tr(pending && !plan ? 'Waiting for the folder…' : 'Change folder')}
+

{tr('Strata saves the big model files here.')}

+ {folder || tr('Reading model directory…')} + {free !== null ?
{tr('{0} free', [gb(free)])} {tr('on this drive')}{tr('Your models use {0}', [gb(usage)])}
: null} + {blocked && !moving ?

{tr('Finish or stop the download to change the folder.')}

: null} + {typing ?
{ e.preventDefault(); if (typed.trim()) void pick(typed.trim()); }}> + + setTyped(e.target.value)} placeholder={tr('Full path to an existing folder')} spellCheck={false} autoFocus/> +
{tr('Use this directory')}
+
: null} + {notice ?

{notice}

: null} + {error && !stage ? : null} +
+ + {plan?.issue?.code === 'not_found' ? null : {tr('Cancel')}} { leave(); void pick(); }}>{tr('Choose another folder')}}> + {plan?.issue ? : null} + + + {tr('Cancel')} setStage('choose')}>{tr('Continue')}}> + {plan ? <> +
{tr('New folder')}{plan.shown}{tr('{0} free on this drive', [gb(plan.free_bytes)])}
+
{tr('You picked the whole drive {0}. Strata keeps its files in a folder of their own, so your models go in {1}.', [plan.picked, plan.shown])}
+

{tr('The three choices follow, as in step 2.')}

+ : null} +
+ + { if (!pending) leave(); }} + actions={plan ? <>{plan.choices.move.possible ? {tr('Cancel')} : { leave(); void pick(); }}>{tr('Choose another folder')}} void start()}>{tr(pending ? 'Working…' : choice === 'move' ? 'Move my models' : choice === 'keep' ? 'Use both folders' : 'Start empty')} : null}> + {plan ? : null} + + + undefined} + actions={ void stop()}>{tr(stopping ? 'Stopping…' : 'Stop moving')}}> +
{tr('{0} of {1} GB', [progress ? (progress.done / 1e9 >= 10 ? Math.round(progress.done / 1e9) : (progress.done / 1e9).toFixed(1)) : 0, Math.round((progress?.total ?? 0) / 1e9)])}{progress && !progress.sameDrive ? timeLeft(progress.secondsLeft) : null}
+

{tr('Keep Strata open. You can keep using other apps. Your models cannot be loaded until the move is done.')}

+ {progress ?
{tr('Details')}
    +
  • {tr('Now copying: {0}, file {1} of {2}', [modelName(progress.group, native) ?? progress.group, progress.index, progress.count])}
  • +
  • {tr('From {0} to {1}', [savedPlan?.current ?? '', savedPlan?.folder ?? ''])}
: null} +
+ + { closeResult(); void pick(); }}/> + ; +} + +function ChooseBody({ plan, choice, setChoice, names, error }: { plan: Plan; choice: Choice; setChoice: (c: Choice) => void; names: (Plan['models'][number] & { label: string | null })[]; error: { message: string; details?: string } | null }) { + const none = plan.models_bytes === 0; + const short = !none && !plan.choices.move.possible; + const lacking = Math.max(0, plan.needed_bytes - plan.free_bytes); + const options: { id: Choice; title: string; text: string; need: string }[] = [ + { id: 'move', title: 'Move my models there', text: none ? 'You have no models to move.' : plan.same_drive ? 'Strata moves your {0} of models to the new folder. This is the same drive, so it takes a moment.' : 'Strata copies your {0} of models to the new folder, checks them, then removes the old copies.', + need: none ? '' : plan.same_drive ? 'Needs no extra space.' : 'Needs {0} free in the new folder. You have {1}.' }, + { id: 'keep', title: 'Keep them where they are and also use the new folder', text: 'Nothing is copied. Your current models keep working, and new downloads go to the new folder.', need: short ? 'Needs no space now. New downloads must fit in {1}.' : 'Needs no space now.' }, + { id: 'empty', title: 'Start empty', text: 'Strata uses the new folder from now on and does not list your current models. Your old files are not deleted.', need: 'Needs no space now. Each model you download later needs its own space.' }, + ]; + const values = [gb(plan.models_bytes), gb(plan.free_bytes)]; + const running = plan.running > 0; + return <> +
{tr('New folder')}{plan.shown}{tr('{0} free on this drive', [gb(plan.free_bytes)])}
+ {short ?
{tr('Your models need {0}, this drive has {1} free.', [gb(plan.needed_bytes), gb(plan.free_bytes)])}
{tr('Free up about {0} there, pick another folder, or choose one of the other two options.', [gb(lacking)])}
: null} +
+ {options.map(o => { const possible = plan.choices[o.id].possible; return ; })} +
+ {running ?

{tr('A running model is stopped first; load it again when the move is done.')}

: null} + {error ? : null} +
{tr('Details')}
    + {names.length ?
  • {tr('{0} would move.', [list(names.map(m => `${m.label}, ${gb(m.bytes)}`))])}
  • : null} + {short ?
  • {tr('Free space is measured on the drive that holds {0}.', [plan.shown])}
  • : <> +
  • {tr('Old folder: {0}', [plan.current])}
  • +
  • {tr('Strata copies one file at a time and checks its size before it removes the old one.')}
  • +
  • {tr('You can stop at any time; files already moved stay usable.')}
  • } +
+ ; +} + +function ResultDialog({ outcome, plan, native, onClose, onAgain }: { outcome: NativeJob | null; plan: Plan | null; native: NativeState | null; onClose: () => void; onAgain: () => void }) { + if (!outcome) return null; + const result = (outcome.result ?? {}) as Outcome; + const sized = (groups: string[]) => list(groups.map(g => { const m = plan?.models.find(x => x.group === g); const name = modelName(g, native); return name ? `${name} (${gb(m?.bytes ?? 0)})` : null; }).filter((x): x is string => !!x)); + if (outcome.state === 'error') { + const full = result.code === 'disk_full'; + const where = driveOf(result.to ?? ''); + const some = (result.moved?.length ?? 0) > 0; + return {tr('Close')}{tr('Choose another folder')}}> +
+ {full ? tr('{0} filled up after {1}, so the move stopped.', [where, gb(result.bytes ?? 0)]) : tr(outcome.error ?? 'The models could not be moved.')} +

{full ? (some ? tr('Nothing was lost. Models already moved are in the new folder, the rest are still in {0}, and the half-copied file was removed. Free up space on {1} or choose another folder, then try again.', [result.from ?? '', where]) + : tr('Nothing was lost. All your models are still in {0}, and the half-copied file was removed. Free up space on {1} or choose another folder, then try again.', [result.from ?? '', where])) + : tr('Nothing was lost. Your models that were not moved are still in {0}. Choose another folder to try again.', [result.from ?? ''])}

+ {outcome.details ?
{tr('Details')}
{outcome.details}
: null} +
+
; + } + if (result.stopped) { + const moved = sized(result.moved ?? []), left = sized(result.remaining ?? []); + return {tr('Close')}}> +
{tr('Nothing was lost.')}
+ {moved ? tr('{0} is in the new folder.', [moved]) + ' ' : ''}{left ? tr('{0} is still in the old folder.', [left]) + ' ' : ''}{moved && left ? tr('Both work.') : ''}
+

{tr('Models in both folders are listed as normal. You can finish moving later with Change folder.')}

+
; + } + return {tr('Done')}}> +
{tr('{0} now live in {1}', [gb(result.total ?? 0), plan?.shown ?? result.to ?? ''])} + {result.sameDrive ? null : <>
{tr('The old copies were removed and {0} is free again on {1}.', [gb(result.total ?? 0), driveOf(result.from ?? '')])}}
+
; +} diff --git a/apps/host/src/components/SettingsStorage.tsx b/apps/host/src/components/SettingsStorage.tsx index ba0dab55..9fbf9344 100644 --- a/apps/host/src/components/SettingsStorage.tsx +++ b/apps/host/src/components/SettingsStorage.tsx @@ -6,6 +6,7 @@ import { pickerGroups, pickerVersionState } from '../lib/model-picker'; import { sizeGb } from '../lib/format'; import { useNative } from '../lib/native'; import { NativeDeleteDialog } from './NativeDelete'; +import { ModelsFolderCard } from './ModelsFolderDialog'; import { nativeShortName } from '../lib/native-names'; export function SettingsStorage() { const state = useStore(s => s); @@ -77,7 +78,9 @@ export function SettingsStorage() { setPending(false); } } + const downloading = !!native?.jobs.some(j => j.state === 'running' && j.kind !== 'models-move') || !!library?.downloads.active || !!state.imageModels?.variants.some(v => v.state === 'downloading'); return <> + {native?.available && native.downloadDirectory ? : null}
{tr("Model directory")} { setDirectory(currentDirectory); setEditing(!editing); setDirectoryError(''); setNotice(''); }}>{tr(editing ? 'Cancel' : 'Change directory')}

{tr("Your models are saved here. Use an existing folder to reuse supported downloads.")}

diff --git a/apps/host/src/components/ui.tsx b/apps/host/src/components/ui.tsx index a319355f..8a475f0e 100644 --- a/apps/host/src/components/ui.tsx +++ b/apps/host/src/components/ui.tsx @@ -384,7 +384,7 @@ export function Select({ value, valueSuffix, options, onChange ); } /** One modal surface for confirmations and narrow-screen inspectors. */ -export function Dialog({ open, title, onClose, children, actions, headerActions, compact = false, sheet = false, wide = false, hideTitle = false, className }: { +export function Dialog({ open, title, onClose, children, actions, headerActions, compact = false, sheet = false, wide = false, hideTitle = false, className, noClose = false }: { open: boolean; title: ReactNode; onClose: () => void; @@ -396,6 +396,8 @@ export function Dialog({ open, title, onClose, children, actions, headerActions, wide?: boolean; hideTitle?: boolean; className?: string; + /** No close button: the person must use the dialog's own buttons (a move that is running). */ + noClose?: boolean; }) { const ref = useRef(null); const id = useId(); @@ -418,7 +420,7 @@ export function Dialog({ open, title, onClose, children, actions, headerActions, return createPortal(