diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjs index 6f352b54..3e02f8b1 100644 --- a/apps/host/server/control-runtime.mjs +++ b/apps/host/server/control-runtime.mjs @@ -207,6 +207,43 @@ 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 ?? '' }); + }, + /** A move of the models folder that the last run left unfinished (`strata models move --status`): null, or {state, from, to, bytes}. */ + async interruptedModelsMove(dataFolder) { + const result = await call(['models', 'move', '--status', ...(dataFolder ? ['--from', dataFolder] : []), '--output', 'json'], { timeoutMs: 30_000 }); + if (result.json?.ok) return result.json.interrupted ?? null; + throw failure(result, 'The models folder could not be checked.'); + }, + /** "Finish it": the same move again, from where it stopped. Same events and result as moveModels. */ + async resumeModelsMove(dataFolder, { installDir = null, cancelFile = null, onEvent = null } = {}) { + const args = ['models', 'move', '--resume', ...(dataFolder ? ['--from', dataFolder] : []), ...(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 ?? '' }); + }, + /** "Leave it": keep the old folder, remove the partial copies in the new one. */ + async leaveModelsMove(dataFolder, { installDir = null } = {}) { + const result = await call(['models', 'move', '--leave', ...(dataFolder ? ['--from', dataFolder] : []), ...(installDir ? ['--install-dir', installDir] : []), '--output', 'json'], { timeoutMs: 24 * 3600_000 }); + if (result.json?.ok) return result.json; + throw Object.assign(failure(result, 'The partial copies could not be removed.'), { code: result.json?.error?.code ?? 'leave_failed', details: result.json?.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..f8d638ad 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -966,6 +966,17 @@ 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/models-folder/interrupted'&&method==='GET')return json(res,200,{interrupted:await native.interruptedMove()}); + if(path==='/api/native/models-folder/resume'&&method==='POST'){const body=await readBody(req);return json(res,202,await native.finishInterruptedMove({stopRunning:body.stopRunning===true}));} + if(path==='/api/native/models-folder/leave'&&method==='POST')return json(res,200,await native.leaveInterruptedMove()); 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 +1021,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..7ec4a440 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,104 @@ 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}; + } + return runModelsMove(old,target,(from,to,options)=>control.moveModels(from,to,options)); + } + /* The move as a job (the progress dialog reads it). `run` is moveModels for a new move, resumeModelsMove for "Finish it". */ + function runModelsMove(old,target,run){ + rmSync(moveFile(),{force:true}); + return begin('models-move',async job=>{ + job.cancelFile=moveFile();job.summary='Starting…'; + try{ + const result=await run(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}); + } + /* "A move was interrupted. Finish it or leave it": the next start finds the unfinished move (Control keeps a note in the models folder in use). */ + async function interruptedMove(){ + if(!packaged)return null; + const now=currentModelsFolder();if(!now)return null; + if([...jobs.values()].some(j=>j.kind==='models-move'&&j.state==='running'))return null; + try{return await control.interruptedModelsMove(now);}catch{return null;} + } + async function finishInterruptedMove({stopRunning=false}={}){ + const st=await interruptedMove();if(!st)throw new Error('No move was interrupted.'); + if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or stop the download to change the folder.'); + 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); + } + return runModelsMove(st.from,st.to,(from,to,options)=>control.resumeModelsMove(from,options)); + } + async function leaveInterruptedMove(){ + const st=await interruptedMove();if(!st)throw new Error('No move was interrupted.'); + if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or stop the download to change the folder.'); + const result=await control.leaveModelsMove(st.from,{installDir:repo()}); + lastRead=0;await refresh(true); + return {done:true,folder:st.from,partial:st.to,removed:result.removed??0,restored:result.restored??0}; + } + 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,interruptedMove,finishInterruptedMove,leaveInterruptedMove,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/server/serving.mjs b/apps/host/server/serving.mjs index c98f3eb8..ced16fac 100644 --- a/apps/host/server/serving.mjs +++ b/apps/host/server/serving.mjs @@ -70,7 +70,7 @@ export function patch(body) { const s = getStore(); const serving = { ...(s.serving ?? {}) }; if (typeof body.otherDevices === 'boolean' && body.otherDevices !== !isLocal()) throw new Error('Change the host listen address and restart to update network access.'); - if (body.apiKey === null && (!isLocal() || sharing.active || tunnelActive())) throw new Error('Stop local sharing and Cloudflare before removing the API key.'); + // The key is optional (owner decision, 0.2.2): removing it while sharing or the tunnel runs is allowed; the app warns in plain words (local-share.mjs, cloudflare.mjs). if (body.apiKey === null) serving.apiKey = null; else if (typeof body.apiKey === 'string' && body.apiKey.trim()) serving.apiKey = body.apiKey.trim(); else if (body.generateKey) serving.apiKey = `sk-strata-${randomBytes(12).toString('hex')}`; diff --git a/apps/host/src/components/ModelsFolderDialog.tsx b/apps/host/src/components/ModelsFolderDialog.tsx new file mode 100644 index 00000000..4111effe --- /dev/null +++ b/apps/host/src/components/ModelsFolderDialog.tsx @@ -0,0 +1,273 @@ +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 [unfinished, setUnfinished] = useState<{ from: string; to: string } | null>(null); + const [resumed, setResumed] = useState<{ from: string; to: string } | null>(null); + 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]); + + /* A move that a crash or a stop left half done: found again at the next start, with its two choices. */ + useEffect(() => { + if (moving || outcome) return; + let live = true; + api.get<{ interrupted: { from: string; to: string } | null }>('/api/native/models-folder/interrupted') + .then(r => { if (live) setUnfinished(r.interrupted); }).catch(() => { if (live) setUnfinished(null); }); + return () => { live = false; }; + }, [moving, outcome, folder]); + async function finishMove() { + if (!unfinished) return; + setPending(true); + setError(null); + try { + const result = await api.post('/api/native/models-folder/resume', { stopRunning: true }); + setResumed(unfinished); + setUnfinished(null); + if (result.id) { setJobId(result.id); setOutcome(null); await refreshNative(true); } + } + catch (e) { setError({ message: (e as Error).message, details: ((e as ApiError).body as { details?: string } | undefined)?.details }); } + finally { setPending(false); } + } + async function leaveMove() { + if (!unfinished) return; + setPending(true); + setError(null); + try { + await api.post('/api/native/models-folder/leave', {}); + setNotice(tr('The partial copies were removed. Your models are in {0}.', [unfinished.from])); + setUnfinished(null); + await refreshNative(true); + } + catch (e) { setError({ message: (e as Error).message, details: ((e as ApiError).body as { details?: string } | undefined)?.details }); } + finally { setPending(false); } + } + + 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); setResumed(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} + {unfinished && !moving ?
+ {tr('A move was interrupted. Finish it or leave it.')}
+ {tr('Strata was moving your models from {0} to {1} when it stopped. Nothing is lost.', [unfinished.from, unfinished.to])} +

{tr('Finishing puts all your models in {1}. Leaving it keeps them in {0} and removes the partial copies from {1}.', [unfinished.from, unfinished.to])}

+
void finishMove()}>{tr('Finish the move')} void leaveMove()}>{tr('Leave it')}
+
: 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 come next.')}

+ : 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 ?? resumed?.from ?? '', savedPlan?.folder ?? resumed?.to ?? ''])}
: 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 ? (m ? `${name} (${gb(m.bytes)})` : name) : 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')}}> +
{(() => { const [before, after] = tr('{0} now live in {1}', [gb(result.total ?? 0), '@@']).split('@@'); return <>{before}{plan?.shown ?? result.to ?? ''}{after}; })()} + {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..de4074fc 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.")}

@@ -95,6 +98,7 @@ export function SettingsStorage() {
{tr(directoryPending ? 'Checking files…' : changing && loadedCount > 0 ? 'Unload and change directory' : changing ? 'Use this directory' : 'Check folder')}
: void saveDirectory(currentDirectory)}>{tr(directoryPending ? 'Checking files…' : 'Check folder')})} {tr(directoryBlocked && !directoryPending ?

{tr(!lifecycle.allowed ? lifecycle.reason : 'Finish or cancel downloads and loading to change the directory.')}

: null)} + {tr(state.setup?.app.modelsDirNotice && !notice ?

{tr(state.setup.app.modelsDirNotice)}

: null)} {tr(notice ?

{tr(notice)}

: null)} {tr(directoryError ? : null)}
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(
: null)}
{tr("Status")}
{tr(serving.running ? 'API listening' : 'API stopped')} · {tr(multipleModels ? `${runtime?.instances.length} models loaded` : loaded ? 'Model ready' : 'Model not ready')}
{tr("Local network")}
{tr(serving.sharing?.active ? "Shared on local network" : "Off")} { setError(''); setSharingOpen(true); }}>{tr(serving.sharing?.active ? "Manage / stop" : "Share")}
{tr(serving.tunnel?.status === "connected" && serving.tunnel.url ?
{tr("Cloudflare tunnel")}
{serving.tunnel.url} void navigator.clipboard.writeText(serving.tunnel!.url!)}/> setCloudflareOpen(true)}/>
: serving.tunnel?.status === "starting" ?
{tr("Cloudflare tunnel")}
{tr("Connecting\u2026")}
: null)}
{tr("API key")}
{tr(serving.access.apiKeySet ? {tr("Required \u00B7 ")}{tr(serving.access.apiKeyHint)} : null)}
{ setError(''); generateKey(); setKeyOpen(true); }}>{tr(serving.access.apiKeySet ? 'Change key' : 'Set key')}{tr(serving.access.apiKeySet ? { setError(''); setRemoveKeyOpen(true); }}>{tr("Remove key")} : null)}
{tr(serving.access.otherDevices ? {tr("Keep a key while the API is available to other devices.")} : null)}
{tr(multipleModels ?

{tr("Available models")}

{tr("One API URL \u00B7 route by model ID")}
{tr(runtime?.instances.length ?
{tr(runtime.instances.map(i =>
{tr(i.family)}{tr(i.name)} · {tr(i.memory.context / 1024)}{tr("K \u00B7 ")}{tr(deviceLabel(i.gpuIds, hardware))}
{i.apiModelId} void copyConnectionValue(i.apiModelId, 'Model ID')}/>
))}
:

{tr("Load a model in Models to make it available here.")}

)}

{tr("Set ")}model{tr(" in each request. Each model has its own queue.")}{tr(runtime?.mode === 'simulated' ? ' Design preview · responses are illustrative.' : '')}

@@ -116,7 +116,7 @@ export function ServingScreen() { {tr(error ? : null)}
- !pending && setRemoveKeyOpen(false)} actions={<> setRemoveKeyOpen(false)}>{tr("Keep key")} void operation(async () => { await setServingAccess({ apiKey: null }); setRemoveKeyOpen(false); })}>{tr(pending ? 'Removing…' : 'Remove key')}}>

{tr("Apps on this computer will be able to send requests without a key. Existing clients can keep their current key field.")}

{tr(error ? : null)}
+ !pending && setRemoveKeyOpen(false)} actions={<> setRemoveKeyOpen(false)}>{tr("Keep key")} void operation(async () => { await setServingAccess({ apiKey: null }); setRemoveKeyOpen(false); })}>{tr(pending ? 'Removing…' : 'Remove key')}}>

{tr("Apps on this computer will be able to send requests without a key. Existing clients can keep their current key field.")}

{tr(serving.access.otherDevices ?

{tr(" Without an API key, anyone who can reach this address can use your model.")}

: null)}{tr(error ? : null)}
setCloudflareOpen(false)} onCreateKey={() => { setReturnToTunnel(true); setCloudflareOpen(false); generateKey(); setKeyOpen(true); }}/> ; } diff --git a/apps/host/src/styles/annotation-fixes.css b/apps/host/src/styles/annotation-fixes.css index 5eecaf9d..8d31cb62 100644 --- a/apps/host/src/styles/annotation-fixes.css +++ b/apps/host/src/styles/annotation-fixes.css @@ -746,3 +746,28 @@ html[data-motion='reduced'] .task-tree-row[data-leaving] { opacity: 0; } .native-cards__opt small { display:block; margin-top:4px; font-size:12px; line-height:1.55; color:var(--st-ink-muted); } .native-cards__opt small[data-warn="true"] { color:var(--st-ink-soft); } .native-cards__note { margin:2px 0 0; } + +/* Settings > Storage > Models folder (0.2.2): free-space line, the three choices, notices, the result mark. */ +.models-free { display:grid; gap:6px; margin-top:10px; } +.models-free__row { display:flex; justify-content:space-between; gap:12px; flex-wrap:wrap; } +.models-picked { display:grid; gap:4px; } +.models-picked .storage-directory__path { margin:0; } +.models-choices { display:grid; gap:10px; border:0; padding:0; margin:0; } +.models-choice { display:grid; grid-template-columns:auto 1fr; gap:4px 12px; padding:14px 16px; border:1px solid var(--st-line); border-radius:var(--st-r-md); background:var(--st-surface); cursor:pointer; } +.models-choice:has(input:checked) { border-color:var(--st-accent); background:var(--st-accent-tint); } +.models-choice:has(input:disabled) { opacity:.55; cursor:not-allowed; background:var(--st-surface-2); } +.models-choice input { margin:4px 0 0; accent-color:var(--st-accent); } +.models-choice strong { font-weight:700; } +.models-choice__need { grid-column:2; font-size:var(--st-fs-xs); color:var(--st-ink-muted); font-variant-numeric:tabular-nums; } +.models-choice__tag { font-size:var(--st-fs-xs); font-weight:700; color:var(--st-accent-text); margin-left:8px; } +.models-notice { display:flex; gap:10px; align-items:flex-start; padding:12px 14px; border-radius:12px; font-size:var(--st-fs-sm); } +.models-notice--warn { background:var(--st-warn-tint); color:var(--st-warn-text); } +.models-notice--info { background:var(--st-info-tint); color:var(--st-info-text); } +.models-notice .st-icon { flex:none; } +.models-details summary { cursor:pointer; color:var(--st-accent-text); font-weight:700; font-size:var(--st-fs-sm); } +.models-details ul { margin:8px 0 0; padding-left:18px; color:var(--st-ink-soft); font-size:var(--st-fs-sm); } +.models-ok { display:flex; align-items:center; gap:12px; } +.models-ok__mark { display:grid; place-items:center; flex:none; width:44px; height:44px; border-radius:50%; background:var(--st-accent-tint); color:var(--st-accent-text); } +.models-dialog .dialog-body { display:grid; gap:14px; } +.models-path { font-family:var(--st-font-mono); font-size:12px; font-weight:400; background:var(--st-surface-2); padding:2px 6px; border-radius:6px; overflow-wrap:anywhere; } +.models-dialog .storage-directory__path { margin:0; } diff --git a/apps/host/tests/models-folder.test.mjs b/apps/host/tests/models-folder.test.mjs new file mode 100644 index 00000000..e3b4b0e1 --- /dev/null +++ b/apps/host/tests/models-folder.test.mjs @@ -0,0 +1,222 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { createNativeControl } from '../server/native-control.mjs'; +import { createControl } from '../server/control-runtime.mjs'; + +/** The host in the packaged app with a stand-in for Strata Control: the move itself is Control's (tests/terminal/test_models_move.py). */ +function fixture(t, { plan = {}, move = null, unfinished = null } = {}) { + const root = realpathSync(mkdtempSync(join(tmpdir(), 'strata-mfolder-'))); + const install = join(root, 'install'), data = join(root, 'host'), oldFolder = join(root, 'old'), newFolder = join(root, 'new'); + for (const d of [install, data, oldFolder, newFolder]) mkdirSync(d, { recursive: true }); + const earlier = { install: process.env.STRATA_INSTALL_DIR, terminal: process.env.STRATA_TERMINAL_SETTINGS_FILE, settings: process.env.STRATA_SETTINGS_FILE, comp: process.env.STRATA_COMPONENTS_DIR }; + process.env.STRATA_INSTALL_DIR = install; + process.env.STRATA_TERMINAL_SETTINGS_FILE = join(root, 'terminal-settings.json'); + process.env.STRATA_COMPONENTS_DIR = join(root, 'components'); + delete process.env.STRATA_SETTINGS_FILE; + const calls = []; + const control = { + control: { dir: join(root, 'control'), python: join(root, 'control', 'python.exe'), cli: join(root, 'control', 'strata.py') }, version: '0.2.2', + async installedModels() { return { install_dir: install, models: [] }; }, + async engine() { return { usable: true, engine: { version: '0.2.2', root: root } }; }, + async importPlan() { return {}; }, + async planModelsMove(from, to) { + calls.push(['plan', from, to]); + return { ok: true, issue: null, old: from, new: to, same_drive: false, free_bytes: 900e9, models_bytes: 74e9, needed_bytes: 77.7e9, models: [{ group: 'gyro-s', name: 'gyro-s', bytes: 58e9 }, { group: 'coder', name: 'coder', bytes: 16e9 }], + choices: { move: { possible: true, reason: '' }, keep: { possible: true, reason: '' }, empty: { possible: true, reason: '' } }, ...plan }; + }, + async moveModels(from, to, options) { + calls.push(['move', from, to, options.installDir]); + if (move) return move(from, to, options); + options.onEvent({ event: 'progress', done: 5e9, total: 74e9, file: 'models/gyro-s/a.gguf', group: 'gyro-s', index: 1, count: 3, seconds_left: 300, same_drive: false }); + return { ok: true, event: 'result', done: true, stopped: false, moved: ['gyro-s', 'coder'], remaining: [], bytes_moved: 74e9, total_bytes: 74e9, files_moved: 3, same_drive: false }; + }, + async interruptedModelsMove(from) { calls.push(['status', from]); return unfinished; }, + async resumeModelsMove(from, options) { + calls.push(['resume', from, options.installDir]); + options.onEvent({ event: 'progress', done: 20e9, total: 74e9, file: 'models/coder/c.gguf', group: 'coder', index: 2, count: 3, seconds_left: 120, same_drive: false }); + return { ok: true, event: 'result', done: true, stopped: false, moved: ['coder'], remaining: [], bytes_moved: 74e9, total_bytes: 74e9, files_moved: 2, same_drive: false }; + }, + async leaveModelsMove(from, options) { calls.push(['leave', from, options.installDir]); return { ok: true, removed: 1, restored: 1, bytes_removed: 5 }; }, + async stop() { return { ok: true }; }, + }; + const spawnProcess = () => { throw new Error('the host starts no process here'); }; + const native = createNativeControl({ control, directory: data, spawnProcess, fetcher: async () => Response.json({}), requests: () => [] }); + t.after(() => { + for (const [key, name] of [['install', 'STRATA_INSTALL_DIR'], ['terminal', 'STRATA_TERMINAL_SETTINGS_FILE'], ['settings', 'STRATA_SETTINGS_FILE'], ['comp', 'STRATA_COMPONENTS_DIR']]) { + if (earlier[key] === undefined) delete process.env[name]; else process.env[name] = earlier[key]; + } + rmSync(root, { recursive: true, force: true }); + }); + native.setDownloadDirectory(oldFolder); + return { native, control, calls, root, install, oldFolder, newFolder, terminalFile: process.env.STRATA_TERMINAL_SETTINGS_FILE }; +} +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'); }; + +test('the plan says what the picked folder means and keeps the person\'s spelling of it', async t => { + const f = fixture(t); + const plan = await f.native.planModelsFolder(f.newFolder); + assert.equal(plan.current, f.oldFolder); + assert.equal(plan.folder, f.newFolder); + assert.equal(plan.wholeDrive, false); + assert.equal(plan.shown, f.newFolder); + assert.equal(plan.models.length, 2); + assert.deepEqual(f.calls[0], ['plan', f.oldFolder, f.newFolder]); +}); + +test('a whole drive is planned as \\Strata, shown as \\Strata\\Models', async t => { + const f = fixture(t); + const root = f.root.slice(0, f.root.indexOf(process.platform === 'win32' ? '\\' : '/') + 1) || '/'; + const plan = await f.native.planModelsFolder(root); + assert.equal(plan.wholeDrive, true); + assert.equal(plan.folder, join(root, 'Strata')); + assert.equal(plan.shown, join(root, 'Strata', 'Models')); + rmSync(join(root, 'Strata'), { recursive: true, force: true }); +}); + +test('the card is blocked while a model runs or a job runs: a running model must be stopped on purpose', async t => { + const f = fixture(t); + await assert.rejects(f.native.startModelsFolder({ folder: f.newFolder, choice: 'bogus' }), /Choose what to do/); + const refused = fixture(t, { plan: { choices: { move: { possible: false, reason: 'Your models need 77 GB, this drive has 38 GB free.' }, keep: { possible: true, reason: '' }, empty: { possible: true, reason: '' } } } }); + await assert.rejects(refused.native.startModelsFolder({ folder: refused.newFolder, choice: 'move' }), /need 77 GB/); + assert.equal(refused.calls.some(c => c[0] === 'move'), false); +}); + +test('Keep: the new folder is used for new downloads, nothing is moved, both settings files follow', async t => { + const f = fixture(t); + writeFileSync(f.terminalFile, JSON.stringify({ data_dir: f.oldFolder, data_dir_at: 1 })); // the Terminal had chosen the old folder + const result = await f.native.startModelsFolder({ folder: f.newFolder, choice: 'keep' }); + assert.equal(result.done, true); + assert.equal(f.native.state().downloadDirectory, f.newFolder); + assert.equal(f.calls.some(c => c[0] === 'move'), false); + assert.equal(JSON.parse(readFileSync(f.terminalFile, 'utf8')).data_dir, f.newFolder); +}); + +test('Start empty: the old models are no longer listed (their run configs are set aside, not deleted), the model files stay', async t => { + const f = fixture(t); + const oldFile = join(f.oldFolder, 'models', 'gyro-s', 'a.gguf'); + mkdirSync(join(f.oldFolder, 'models', 'gyro-s'), { recursive: true }); + writeFileSync(oldFile, 'x'); + writeFileSync(join(f.install, 'strata-gyro-s.json'), JSON.stringify({ args: ['--native', oldFile] })); + writeFileSync(join(f.install, 'strata-other.json'), JSON.stringify({ args: ['--native', join(f.root, 'elsewhere', 'b.gguf')] })); + const result = await f.native.startModelsFolder({ folder: f.newFolder, choice: 'empty' }); + assert.deepEqual(result.setAside, ['strata-gyro-s.json']); + assert.equal(existsSync(join(f.install, 'strata-gyro-s.json')), false); + assert.equal(existsSync(join(f.install, 'old-models', 'strata-gyro-s.json')), true); + assert.equal(existsSync(join(f.install, 'strata-other.json')), true, 'a model elsewhere is not touched'); + assert.equal(existsSync(oldFile), true); + assert.equal(f.native.state().downloadDirectory, f.newFolder); +}); + +test('Move: a job with progress; the folder changes only when everything moved', async t => { + const f = fixture(t); + const job = await f.native.startModelsFolder({ folder: f.newFolder, choice: 'move' }); + assert.equal(job.kind, 'models-move'); + const done = await finish(f.native, job.id); + assert.equal(done.state, 'done'); + assert.equal(done.result.done, true); + assert.equal(done.result.sameDrive, false); + assert.equal(f.native.state().downloadDirectory, f.newFolder); + assert.deepEqual(f.calls.find(c => c[0] === 'move').slice(1), [f.oldFolder, f.newFolder, f.install]); +}); + +test('Move stopped: the folder stays, what moved is reported', async t => { + const f = fixture(t, { move: async () => ({ ok: true, event: 'result', done: false, stopped: true, moved: ['coder'], remaining: ['gyro-s'], bytes_moved: 16e9, total_bytes: 74e9, files_moved: 1, same_drive: false }) }); + const job = await f.native.startModelsFolder({ folder: f.newFolder, choice: 'move' }); + const done = await finish(f.native, job.id); + assert.equal(done.result.stopped, true); + assert.deepEqual(done.result.moved, ['coder']); + assert.equal(f.native.state().downloadDirectory, f.oldFolder, 'a partial move never points the app at an incomplete folder'); +}); + +test('Move failed (disk full): the folder stays and the job says what happened', async t => { + const f = fixture(t, { move: async () => { throw Object.assign(new Error('The drive ran out of space.'), { code: 'disk_full', details: 'ENOSPC: no space left on device', output: { moved: ['coder'], remaining: ['gyro-s'], bytes_moved: 52e9, total_bytes: 74e9 } }); } }); + const job = await f.native.startModelsFolder({ folder: f.newFolder, choice: 'move' }); + const done = await finish(f.native, job.id); + assert.equal(done.state, 'error'); + assert.equal(done.result.code, 'disk_full'); + assert.equal(done.result.bytes, 52e9); + assert.match(done.details, /ENOSPC/); + assert.equal(f.native.state().downloadDirectory, f.oldFolder); +}); + +test('Move: Stop writes the cancel file and the run ends by itself', async t => { + let release; + const f = fixture(t, { move: (from, to, options) => new Promise(resolve => { release = () => resolve({ ok: true, event: 'result', done: false, stopped: existsSync(options.cancelFile), moved: [], remaining: ['gyro-s', 'coder'], bytes_moved: 0, total_bytes: 74e9, files_moved: 0, same_drive: false }); }) }); + const job = await f.native.startModelsFolder({ folder: f.newFolder, choice: 'move' }); + await f.native.cancel(job.id); + assert.equal(f.native.state().jobs.find(j => j.id === job.id).state, 'running', 'it ends when Control has cleaned up, not before'); + release(); + const done = await finish(f.native, job.id); + assert.equal(done.result.stopped, true); + assert.equal(f.native.state().downloadDirectory, f.oldFolder); +}); + +test('a move needs the app: the Control command line is built from the plan and the cancel file', async () => { + const seen = []; + const control = createControl({ control: { dir: '/c', python: '/c/py', cli: '/c/strata.py' }, run: async (args, options) => { seen.push([args, options]); return args.includes('--plan') ? { code: 0, json: { ok: true, plan: { ok: true } }, text: '', stderr: '' } : { code: 0, json: { ok: true, event: 'result', done: true }, text: '', stderr: '' }; } }); + assert.deepEqual(await control.planModelsMove('/old', '/new'), { ok: true }); + assert.deepEqual(seen[0][0], ['models', 'move', '/new', '--from', '/old', '--plan', '--output', 'json']); + const result = await control.moveModels('/old', '/new', { installDir: '/i', cancelFile: '/c.cancel' }); + assert.equal(result.done, true); + assert.deepEqual(seen[1][0], ['models', 'move', '/new', '--from', '/old', '--install-dir', '/i', '--cancel-file', '/c.cancel', '--output', 'jsonl']); + const failing = createControl({ control: { dir: '/c', python: '/c/py', cli: '/c/strata.py' }, run: async () => ({ code: 5, json: { ok: false, error: { code: 'disk_full', message: 'The drive ran out of space.', details: 'ENOSPC' }, moved: [] }, text: '', stderr: '' }) }); + await assert.rejects(failing.moveModels('/o', '/n'), e => e.code === 'disk_full' && e.details === 'ENOSPC' && /ran out of space/.test(e.message)); +}); + +test('an unfinished move is found at the next start, and Finish resumes it as a job that changes the folder only when done', async t => { + const f = fixture(t); + f.control.interruptedModelsMove = async from => { f.calls.push(['status', from]); return { state: 'failed', from: f.oldFolder, to: f.newFolder, bytes: 74e9 }; }; + assert.equal((await f.native.interruptedMove()).to, f.newFolder); + assert.deepEqual(f.calls[0], ['status', f.oldFolder]); + const job = await f.native.finishInterruptedMove({ stopRunning: true }); + const done = await finish(f.native, job.id); + assert.equal(done.state, 'done'); + assert.equal(f.calls.find(c => c[0] === 'resume')[1], f.oldFolder); + assert.equal(f.native.state().downloadDirectory, f.newFolder); +}); + +test('Leave it keeps the old folder and asks Control to remove the partial copies; nothing interrupted means nothing to do', async t => { + const f = fixture(t); + assert.equal(await f.native.interruptedMove(), null); + await assert.rejects(f.native.leaveInterruptedMove(), /No move was interrupted/); + f.control.interruptedModelsMove = async () => ({ state: 'running', from: f.oldFolder, to: f.newFolder, bytes: 1 }); + const result = await f.native.leaveInterruptedMove(); + assert.equal(result.folder, f.oldFolder); + assert.deepEqual(f.calls.find(c => c[0] === 'leave').slice(0, 2), ['leave', f.oldFolder]); + assert.equal(f.native.state().downloadDirectory, f.oldFolder); +}); + +test('the Control command lines for status, resume and leave', async () => { + const seen = []; + const control = createControl({ control: { dir: '/c', python: '/c/py', cli: '/c/strata.py' }, run: async args => { seen.push(args); return args.includes('--status') ? { code: 0, json: { ok: true, interrupted: { from: '/o', to: '/n' } }, text: '', stderr: '' } : args.includes('--leave') ? { code: 0, json: { ok: true, removed: 0 }, text: '', stderr: '' } : { code: 0, json: { ok: true, event: 'result', done: true }, text: '', stderr: '' }; } }); + assert.equal((await control.interruptedModelsMove('/o')).to, '/n'); + await control.resumeModelsMove('/o', { installDir: '/i', cancelFile: '/c.cancel' }); + await control.leaveModelsMove('/o', { installDir: '/i' }); + assert.deepEqual(seen[0], ['models', 'move', '--status', '--from', '/o', '--output', 'json']); + assert.deepEqual(seen[1], ['models', 'move', '--resume', '--from', '/o', '--install-dir', '/i', '--cancel-file', '/c.cancel', '--output', 'jsonl']); + assert.deepEqual(seen[2], ['models', 'move', '--leave', '--from', '/o', '--install-dir', '/i', '--output', 'json']); +}); + +test('the models folder strings exist in all 8 languages with the same placeholders', () => { + const read = lang => JSON.parse(readFileSync(new URL(`../src/locales/${lang}.json`, import.meta.url), 'utf8')); + const en = read('en'); + const ours = Object.keys(en).filter(k => Number(k.slice(1)) >= 8339 && Number(k.slice(1)) <= 8422); + assert.equal(ours.length, 84); + for (const lang of ['de', 'es', 'ja', 'ko', 'pt', 'ru', 'zh']) { + const text = read(lang); + for (const key of ours) { + assert.ok(text[key], `${lang} ${key}`); + assert.deepEqual((text[key].match(/\{\d\}/g) ?? []).sort(), (en[key].match(/\{\d\}/g) ?? []).sort(), `${lang} ${key} placeholders`); + } + } + // every string the dialog shows through tr() is in the catalogue + const source = readFileSync(new URL('../src/components/ModelsFolderDialog.tsx', import.meta.url), 'utf8'); + const values = new Set(Object.values(en)); + for (const text of ['Models folder', 'Change folder', 'Move my models', 'Use both folders', 'Start empty', 'Stop moving', 'Your models are moved', 'Moving stopped']) { + assert.ok(source.includes(text) && values.has(text), text); + } +}); diff --git a/apps/host/tests/serving-key-optional.test.mjs b/apps/host/tests/serving-key-optional.test.mjs new file mode 100644 index 00000000..83c550a8 --- /dev/null +++ b/apps/host/tests/serving-key-optional.test.mjs @@ -0,0 +1,23 @@ +/** The API key is optional (owner decision, 0.2.2): removing it while sharing or the Cloudflare tunnel runs is allowed, and the key stays removed. */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +const home = mkdtempSync(join(tmpdir(), 'strata-serving-key-')); +process.env.STRATA_HOME = home; +const serving = await import('../server/serving.mjs'); + +test('removing the API key while local sharing and the tunnel run is allowed', () => { + serving.init({ send() {} }, { port: 8080, host: '127.0.0.1' }); + serving.patch({ generateKey: true }); + assert.equal(serving.state().access.apiKeySet, true); + serving.setSharing({ active: true, url: 'http://192.168.1.5:8792/v1' }); + serving.setTunnel({ status: 'connected', mode: 'quick', url: 'https://example.trycloudflare.com', error: null, installed: true, originUrl: null }); + assert.equal(serving.state().access.otherDevices, true); + const after = serving.patch({ apiKey: null }); + assert.equal(after.access.apiKeySet, false); + assert.equal(serving.authorized({ headers: {} }), true); +}); +test.after(() => { try { rmSync(home, { recursive: true, force: true }); } catch { /* temp folder */ } }); diff --git a/docs/INSTALL.md b/docs/INSTALL.md index d860d042..afb1e866 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -311,7 +311,9 @@ The model files are the only big part (70 to 190 GB). Put them where there is ro - **In the app:** the first screen shows the model folder with a button to change it, and Settings > Storage changes it later. Pick a folder you can save files in; a whole drive (`D:\`) becomes `D:\Strata`, which Strata makes and says so. - Models you already have in the old folder stay there and keep working; nothing is moved or deleted for you. + Change folder then asks what to do with your models: move them (copied file by file and checked before the old copies are removed; you can stop at any time), + keep them where they are and also use the new folder, or start empty (the old files are never deleted). From the Terminal the same move is + `strata models move NEW_FOLDER` (add `--plan` to see what it would do first). - **In the Terminal:** `strata launch --data-dir D:\Strata` once. The folder is remembered for the next `strata launch` and `strata models list`. Until you give it one, the Terminal uses the folder the app chose; the app keeps its own setting (Settings > Storage) and does not read the Terminal's. `--move-data` moves the models you already have into it; without it they stay where they diff --git a/docs/TERMINAL_LAUNCH.md b/docs/TERMINAL_LAUNCH.md index 80549729..23444e1d 100644 --- a/docs/TERMINAL_LAUNCH.md +++ b/docs/TERMINAL_LAUNCH.md @@ -70,7 +70,7 @@ strata launch --list-presets | --delete-preset NAME | --status | --stop [--prese `strata launch --help` lists everything with examples. An unknown model or flag gets a plain message with the closest match. Presets are small files in `launch-presets/` beside the profiles folder; the run uses the shared profile `launch-` and the shared tuning presets (`strata presets`), so the app sees them too. Flags next to `--preset` change that start only -(add `--save-preset` to keep them). +(add `--save-preset` to keep them). `--plan` shows the model (also for your own files, which it recognises), the context, the picture setting and what would be downloaded and how big (0 when everything is already here). A model that was tuned before for the same choices on the same computer is not measured again by `--tune quick`; the stored result is used and the run says so. Add `--retune` to measure again. ## Connect your apps: `strata connect` diff --git a/docs/release-notes-0.2.2.md b/docs/release-notes-0.2.2.md index 77499fea..15a55b09 100644 --- a/docs/release-notes-0.2.2.md +++ b/docs/release-notes-0.2.2.md @@ -1,6 +1,19 @@ -**0.2.2 (draft).** Only the items of the `f-022-rx6000` and `f-022-numa` branches are written here; the coordinator adds the rest. +**0.2.2 (DRAFT, not released).** Written from the notes of each merged stream; the coordinator edits it before the release. Items of the `f-022-iopf`, `f-022-flow`, `f-022-pkgspeed` and `f-022-modelsdir` branches are not merged and are not listed. ## What is new - **An engine package for the RX 6000 series (built, not tested on a real RX 6000 card).** Linux has `rx6000` and Windows has `rdna2`, each with GPU code for gfx1030 and gfx1031 (RX 6800, 6900 and 6950 series, RX 6700 XT). They are offered to a PC whose card reports one of those two and to no other: the RX 7000, RX 9000 and Strix Halo packages are unchanged, and a PC with an RX 7000 or 9000 card next to an RX 6000 card keeps the package it had. The engine runs plain kernels on these cards (RDNA2 has no matrix cores, so none of the RX 7000 / RX 9000 or Radeon 780M prompt paths apply) and plain hipBLAS (hipBLASLt ships no kernels for gfx1030, so there is no tuning table). Setup and the app say once that this package was built and not tested on a real RX 6000 card. What was checked: the Linux package builds, every program in it has code for exactly gfx1030 and gfx1031, the rocBLAS kernel files for both are in it, every library it imports is in the package or belongs to the system, and the whole engine (all targets, tests included) compiles for gfx1030 and gfx1031. What was not: a model on an RX 6000 card, on either system, and the Windows package itself (the Windows build scripts take the new architecture list, but no Windows `rdna2` package has been built). Earlier reports on these cards came from people who built the engine from source ([docs/AMD_HIP.md](AMD_HIP.md#rdna2-gfx1030)). If something goes wrong, open an issue with the end of `strata-.log`. - **The CPU expert pool splits per NUMA node on a machine with two or more NUMA nodes (built from the report in #3201, not tested on a two-socket machine).** Until now the pool kept its workers on the host thread's socket, because workers on the other socket read the experts across the link and were slower. The split gives each socket its own slice of the pool with its own task counter, and places each socket's half of every CPU-side expert in that socket's memory, so a slice reads local memory only. The reporter measured +10 to +14 % decode on a dual Xeon Gold 6226 (59.3 against 54.05 tok/s with the IOMMU in passthrough); a second reporter's dual Xeon E5-2670 v2 preferred more workers across both sockets, which the split also uses. It starts by itself when the machine has two or more NUMA nodes with CPUs and runs only when it can (Linux, two nodes, pinned threads, enough free memory per node); otherwise the pool is exactly what it was and the log says why. **A machine with one NUMA node runs the same code path as 0.2.1:** the identity gate (10 prompts, exact_pp 4K and 20K) is byte-identical and the single-request speed A/B is not slower on the one-node test boxes (numbers in the notes of the branch). `STRATA_NUMA_POOL=0` turns the split off; `STRATA_NUMA_SPLIT=1` still asks for it on any machine. The start-up log says what it did: `NUMA pool on: 2 NUMA nodes found ...` or `NUMA pool off: `. On Windows the node count is read but the split itself is Linux-only for now, so a two-node Windows PC logs the reason and runs as before. The logic runs in unit tests on made-up two-, three- and four-node machines; we have no two-socket machine, so the placement and the speed on real ones are the reporters' numbers, not ours. Do not wrap the server in `numactl --cpunodebind` or `--membind`: it pulls both halves onto one node. Thanks to baptisterajaut for the branch this is built on, and to xrip and Tworks25 for their numbers. Please send the start-up lines and a decode run with and without `STRATA_NUMA_POOL=0` from a two-socket machine. +- **The API key is optional.** The server, `strata launch`, the Terminal and the app no longer refuse to share without a key. Say so (`--no-api-key`, or `"api_key": "none"` in the server config) and it starts, with one plain warning that anyone who can reach the port can use the model and its tools; a public Cloudflare address gets a stronger one. The Terminal and the app still offer to make a key and do by default. In the app, Remove key now also works while local sharing or the tunnel runs. Fixes the refusals reported in #3198 and #3401. +- **Your own GGUF files load again.** "Use a local GGUF", `strata launch --model-path` and `strata models import` now accept what `setup.py --gguf-dir` always accepted: a folder with the files, the folder above it (a whole Hugging Face download, or an old Strata data folder), or one `.gguf` file. Unsloth sets whose first file holds no tensors, linked files (Hugging Face cache, Ollama) and folders with several sizes work; when a file is unusable, the message names the file and says why. Setup no longer deletes your own file when its checksum differs. The download and prepare steps use plain words, the checksum pass shows its own progress instead of a stuck 99 % download bar, and a model folder you pick (a whole drive becomes `D:\Strata`) is accepted by the installer whatever it is called. Reports #3316, #3292, #3190. +- **Problems with the computer's own setup are repaired or explained, not refused.** If the Windows runtime folder lists another account, Strata locks it down itself instead of stopping. A Documents folder that cannot be used (Controlled folder access, an offline OneDrive) falls back to the Strata home folder and Settings > Storage says so. A port that is taken or reserved gets one sentence with the next step. Local requests ignore a system proxy. File-in-use errors and a full disk say what happened. `strata launch` asks plain questions in a terminal that reports a tty late. `strata update` copes with a slow `--version`, a busy graphics card is not held against an engine, pre-release Control builds hand over correctly, and a wrong PC clock is named as the reason a feed or certificate looks bad. install.sh and install.ps1 give clearer messages (ARM, TLS 1.2, proxy credentials, no `tar.exe`). +- **One speed number everywhere.** Answer speed is every token the model produced (thinking, answer, tool calls; with MTP the kept tokens) divided by decode time. The chat footer, the monitor, the model API and the server console used different definitions: an agent turn read about 632 tok/s in 0.2.0-beta, then fell to the real 50 to 75 in 0.2.1, and some places divided by the whole request, which reads about half. The footer now shows the last reply's own speed, the popover has a "Prompt reading" row, and the console no longer prints a million tok/s for a one-token reply. +- **`strata bench run`, first real runs.** Run on two test PCs with the 0.2.1 release, it showed that the release archive carried no commit (every run was `nonconforming`), that the drive lookup failed on LVM, that the CUDA runtime was missing from the nvidia-smi 615 output, and that the engine log in the result was empty. All four are fixed, the protocol text now says 2 to 4 minutes for the required part, and results get a Capped column for answers that stopped at the token limit. Package building refuses to make a distributable archive without a commit. +- **`strata update` takes effect on the next command.** When an update installs a newer Control, the Terminal hands over to it by itself. Terminals 0.1.46 and 0.1.46.1 cannot do this (the code is in the Terminal): reinstall the Terminal once. +- **A stale update notice goes away.** After a version change the app and the Terminal no longer keep showing an offer for a version you already have. +- **Idle GPU time was measured, with no default change.** On a two-card test PC decode leaves about half of the card time idle (batch 51 %), on a one-card PC 5 %. Overlap gave +0.3, +2.1 and -0.3 % against 2.8 % noise; pipeline windows and batch groups help in one case and cost 5 to 15 % in others, so nothing is switched on. Raw numbers are in `bench/results/2026-10-20-0.2.1-idle-gpu/`. +- **Small fixes.** `--mtp 2` is no longer checked as a folder (#3298); owner-only checks understand Windows account aliases (#3302, thanks jackbapa); `strata bench` with its own server sets its port (#3188); `calibrate` checks the report folder first (#3187); the CUDA 12.0 and 12.1 build error `__half_as_ushort` (#3368, thanks yudhanjaya, built with CUDA 12.6 only); the AMD picture reader builds position independent (#3359); the Mac setup installs cmake and ninja before it builds (#3403); the picture reader recreates its work folder if a temp cleaner removed it (#3370); a list of GPUs such as `"0,1"` is accepted (#3275, thanks MEsfits); `thinking_budget_tokens` is read (#2141) and the Anthropic usage numbers add up to the prompt (#2289, thanks xrip); an engine that cannot start is a 503 with the reason (#2496, thanks devYRPauli); the serve web page no longer scrolls sideways on a phone (#2971, thanks ctr-137); folders in a Trash or Recycle Bin are not offered as installs (#3410). Ported pull requests keep their authors. +- **From the issues labelled needs-format.** The app numbers Radeon cards the way HIP does when an integrated GPU is present (#3418). The hardware report counts physical cores, so the Work profile asks for 6 pool workers on an 8-core CPU instead of 12 (#3417; the reporter measured 27.9 against 38.1 tok/s). Three trellis CPU tests skip on a ggml without trellis types, and the ISA guard knows the AVX-512 files (#3358, tests and build only; the memory fault on gfx1011 is not touched). +- **Docker image build.** The terminal stage no longer needs git in the image (it failed with `FileNotFoundError`); the commit comes in as a build argument. +- **The app and the Terminal share one models folder.** Each of the two settings files now remembers when the models folder was chosen; the one changed last wins and the other follows. Nothing is moved. A folder picked in the Terminal was not seen by the app before, so the same model could be downloaded twice. +- **Docker.** An old (0.1.x) volume with `/data/models`, `/data/packs` and `/data/mtp` is moved into `/data/Strata-data` by rename instead of being downloaded and packed again (it used to start a 70 GB download). A card without `--gpus` stops at once with the `--gpus all` hint instead of after minutes of setup. A missing or empty `MODEL_PATH` gets a plain message. Settings that name another image's component folder (a CUDA 12 image on a CUDA 13 volume) are made again. Tested on one RTX 3060 PC; no AMD or Intel image and no Docker Desktop. diff --git a/setup.py b/setup.py index f56e24dc..af4d1e34 100644 --- a/setup.py +++ b/setup.py @@ -63,6 +63,7 @@ import zipfile from pathlib import Path from strata_control import acquisition +from strata_control import atomic from strata_control import draft_layer from strata_control.discovery import in_trash from strata_control import user_args @@ -2108,7 +2109,7 @@ def _save_pieces(part: Path, total: int, done: set): side = part.with_name(part.name + ".chunks") tmp = side.with_name(side.name + ".tmp") tmp.write_text(json.dumps({"v": 1, "total": total, "chunk": DL_CHUNK, "done": _ranges(done)}), encoding="utf-8") - os.replace(tmp, side) + atomic.replace(tmp, side) except OSError: pass # only costs re-downloading a few pieces after a stop @@ -5438,7 +5439,7 @@ def move_into(src: Path, dst: Path) -> None: if not dst.exists(): try: dst.parent.mkdir(parents=True, exist_ok=True) - os.replace(src, dst) + atomic.replace(src, dst) return except OSError: if not src.is_dir(): @@ -5608,7 +5609,7 @@ def write_config(path: Path, cfg: dict): a setup stopped half-way (a closed window, a full disk) never leaves an empty strata-*.json behind.""" tmp = path.with_name(path.name + ".tmp") tmp.write_text(json.dumps(cfg, indent=1), encoding="utf-8") - os.replace(tmp, path) + atomic.replace(tmp, path) # #629: the run config's keys setup writes itself (and rewrites on every setup run); any other key is the user's - a diff --git a/strata_cli/cli.py b/strata_cli/cli.py index 80e66518..97b8554a 100644 --- a/strata_cli/cli.py +++ b/strata_cli/cli.py @@ -159,6 +159,16 @@ def parser() -> argparse.ArgumentParser: models_import.add_argument("--plan", action="store_true", required=True, help="inspect only; adoption requires a qualified model workflow") models_import.add_argument("--output", choices=("human", "json"), default="human") + models_move = models_sp.add_parser("move", help="move the model files (models, packs, mtp) to another folder: copied, checked, then the old copies removed") + models_move.add_argument("to", metavar="NEW_FOLDER", nargs="?", help="not needed with --resume, --leave or --status") + models_move.add_argument("--resume", action="store_true", help="finish a move that was interrupted") + models_move.add_argument("--leave", action="store_true", help="give up an interrupted move: keep the old folder and remove the partial copies") + models_move.add_argument("--status", action="store_true", help="say whether a move was interrupted (changes nothing)") + models_move.add_argument("--from", dest="source", metavar="OLD_FOLDER", help="the folder the models are in now (default: the data folder in use)") + models_move.add_argument("--install-dir", help="absolute path to a Strata installation whose run configs should follow the files") + models_move.add_argument("--plan", action="store_true", help="say what would happen and change nothing") + models_move.add_argument("--cancel-file", metavar="PATH", help="stop (safely) when this file appears") + models_move.add_argument("--output", choices=("human", "json", "jsonl"), default="human") engine = sp.add_parser("engine", help="engine tuning and component actions") engine_sp = engine.add_subparsers(dest="engine_command", required=True) calibrate = engine_sp.add_parser("calibrate", help="measure, review and apply engine tuning") @@ -495,7 +505,7 @@ def parser() -> argparse.ArgumentParser: code_sessions.add_argument("--output", choices=("human", "json"), default="human") for one_shot in (profile_create, profile_list, profile_show, profile_validate, profile_set, profile_source, profile_edit, profile_history, profile_rollback, doctor, - components_verify, models_list, models_inspect, models_import, calibrate, + components_verify, models_list, models_inspect, models_import, models_move, calibrate, runtime_start, runtime_status, runtime_verify, runtime_stop, runtime_cleanup, runtime_restart, *ops_items, bench_run, bench_report, bench_compare, code_sessions, *update_parsers): one_shot.add_argument("--json", action="store_true", help="alias for --output json") @@ -547,6 +557,8 @@ def _models(a: argparse.Namespace) -> int: print(_import_problem(result), file=sys.stderr) return 5 return _success({"plan": result}, machine=a.output == "json", human=_import_words(result)) + if a.models_command == "move": + return _models_move(a) if a.models_command == "list": if a.served: if a.install_dir: @@ -591,11 +603,8 @@ def _models(a: argparse.Namespace) -> int: def _import_problem(plan: dict) -> str: """Why `models import --plan` refused, in plain words (the codes stay in --output json).""" - from strata_cli.launch.runner import plain_issue - issues = [str(x) for x in plan.get("issues") or []] - if "multiple_model_groups" in issues: # several models in one folder: "not a size Strata knows" would only confuse - issues = [x for x in issues if x != "unrecognized_or_unsupported_model_variant"] - words = "; ".join(dict.fromkeys(plain_issue(x) for x in issues)) + from strata_control import models as own_models + words = own_models.problem_words(plan.get("issues") or []) text = f"These files cannot be used as they are: {words}." holds = next((m for m in plan.get("messages") or [] if "holds" in m), "") if holds: @@ -603,6 +612,97 @@ def _import_problem(plan: dict) -> str: return text +def _models_move(a: argparse.Namespace) -> int: + from strata_control import discovery, models, models_move as mm + machine = a.output in ("json", "jsonl") + old = Path(a.source) if a.source else discovery.data_dir(Path.home() / "Strata")[0] + if a.status or a.resume or a.leave: + return _models_move_unfinished(a, old) + if not a.to: + print("strata: name the new folder, or use --resume / --leave / --status for an interrupted move.", file=sys.stderr) + return 2 + new = Path(a.to).expanduser() + if a.plan: + result = mm.plan(old, new) + if machine: + print(json.dumps({"schema_version": 1, "ok": result["ok"], "plan": result}, ensure_ascii=False, allow_nan=False)) + else: + print(result["issue"]["message"] if result["issue"] else + f"{len(result['models'])} model(s), {result['models_bytes'] / 1e9:.1f} GB; {result['free_bytes'] / 1e9:.1f} GB free in {new}.") + return 0 if result["ok"] else 5 + try: + installs = [models.resolve_install(a.install_dir)[0]] if a.install_dir else [p for p, _s in models.all_installs()] + except Exception: + installs = [] + configs = [c for i in installs for c in mm.config_files(i)] + cancel = Path(a.cancel_file) if a.cancel_file else None + + def show(event: dict) -> None: + if a.output == "jsonl": + print(json.dumps(event, ensure_ascii=False, allow_nan=False), flush=True) + elif not machine: + print(f"\r{event['done'] / 1e9:.1f} of {event['total'] / 1e9:.1f} GB {event['file']}", end="", flush=True) + try: + summary = mm.move(old, new, on_progress=show, cancelled=(lambda: cancel.exists()) if cancel else None, configs=configs) + except mm.MoveError as e: + extra = getattr(e, "summary", {}) + if machine: + print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": e.code, "message": str(e), "details": e.details}, **extra}, ensure_ascii=False)) + else: + print(f"\nstrata: {e} {e.details}".rstrip(), file=sys.stderr) + return 5 + if machine: + print(json.dumps({"schema_version": 1, "ok": True, "event": "result", **summary}, ensure_ascii=False)) + else: + print("\n" + ("Your models are moved." if summary["done"] else "Moving stopped. Nothing was lost.")) + return 0 if summary["done"] else 6 + + +def _interrupted_words(st: dict) -> str: + return (f"A move of your models was interrupted. They are in {st['from']} and {st['to']}. " + "Finish it: strata models move --resume. Leave it (keep the models in the first folder): strata models move --leave.") + + +def _models_move_unfinished(a: argparse.Namespace, old: Path) -> int: + """`strata models move --status | --resume | --leave`: the move the last run left unfinished (A move was interrupted. Finish it or leave it).""" + from strata_control import models, models_move as mm + machine = a.output in ("json", "jsonl") + st = mm.interrupted(old) + if a.status: + if machine: + print(json.dumps({"schema_version": 1, "ok": True, "interrupted": st}, ensure_ascii=False, allow_nan=False)) + else: + print(_interrupted_words(st) if st else "No move was interrupted.") + return 0 + if not st: + if machine: + print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": "nothing", "message": "No move was interrupted.", "details": ""}})) + else: + print("strata: no move was interrupted.", file=sys.stderr) + return 5 + try: + installs = [models.resolve_install(a.install_dir)[0]] if a.install_dir else [p for p, _s in models.all_installs()] + except Exception: + installs = [] + configs = [c for i in installs for c in mm.config_files(i)] + if a.leave: + try: + result = mm.leave(Path(st["from"]), Path(st["to"]), configs=configs) + except mm.MoveError as e: + if machine: + print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": e.code, "message": str(e), "details": e.details}}, ensure_ascii=False)) + else: + print(f"strata: {e} {e.details}".rstrip(), file=sys.stderr) + return 5 + if machine: + print(json.dumps({"schema_version": 1, "ok": True, "event": "result", "left": True, **result}, ensure_ascii=False)) + else: + print(f"Done. Your models stay in {st['from']}; the partial copies in {st['to']} were removed.") + return 0 + a.to, a.source, a.resume, a.status, a.leave = st["to"], st["from"], False, False, False + return _models_move(a) + + def _import_words(plan: dict) -> str: """The plain-words result of `strata models import --plan`: what the files are, what is already set up, what changes (nothing).""" cand = plan.get("candidate_selection") or {} diff --git a/strata_cli/launch/app.py b/strata_cli/launch/app.py index b0a8500a..8a327b95 100644 --- a/strata_cli/launch/app.py +++ b/strata_cli/launch/app.py @@ -43,6 +43,7 @@ class Ctx: glyphs: Glyphs = field(default_factory=Glyphs) feed: str | None = None move_data: bool = False + retune: bool = False notes: list[str] = field(default_factory=list) start_own_files: bool = False picked_in_list: bool = False @@ -263,7 +264,7 @@ class LaunchApp(App): s = self.ctx.settings self.cancel = threading.Event() self.runner = Runner(s, catalog=self.ctx.catalog, emit=self._emit, cancel=self.cancel, feed=self.ctx.feed, confirm=self._ask_from_run, - move_data=self.ctx.move_data) + move_data=self.ctx.move_data, retune=self.ctx.retune) gb = getattr(self.runner, "download_gb", lambda: 0.0)() if not confirmed else 0.0 if gb >= 1.0: free = self.ctx.catalog.disk_free(s.data_dir or self.ctx.catalog.data_dir()) @@ -404,7 +405,7 @@ def run_monitor(info: dict, *, keep_default: bool = True, color: str = "auto") - def run_tui(settings: S.LaunchSettings | None, *, catalog: Catalog | None = None, feed: str | None = None, auto_run: bool = False, - save: bool = False, open_page: bool = False, move_data: bool = False) -> int: + save: bool = False, open_page: bool = False, move_data: bool = False, retune: bool = False) -> int: """Open the launch screens. `settings` given and `auto_run`: skip the questions and go straight to the run.""" catalog = catalog or Catalog() print("Looking at this computer…", flush=True) @@ -419,7 +420,7 @@ def run_tui(settings: S.LaunchSettings | None, *, catalog: Catalog | None = None s.name = f"{s.model or 'model'} {S.context_label(s.context)}" if save: store.save(s, s.name) - ctx = Ctx(catalog=catalog, computer=computer, rows=rows, settings=s, glyphs=Glyphs(), feed=feed, move_data=move_data) + ctx = Ctx(catalog=catalog, computer=computer, rows=rows, settings=s, glyphs=Glyphs(), feed=feed, move_data=move_data, retune=retune) app = LaunchApp(ctx, auto_run=auto_run) result = app.run() if getattr(app, "return_code", 0) not in (0, None) or getattr(app, "_exception", None) is not None: diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 7abd7b79..bd401cd3 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -30,6 +30,9 @@ examples: """ +PICTURE_WORDS = {"off": "off", "on": "on", "cpu": "on (the reader runs on the processor)", "gpu": "on (the reader runs on the graphics card)"} + + def _choice(label: str, options: tuple[str, ...]): def convert(value: str) -> str: v = str(value).strip().lower() @@ -110,6 +113,9 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser] a.add_argument("--no-api-key", action="store_true", help="share beyond this computer without an API key (a warning is shown, nothing is refused)") o = p.add_argument_group("running") o.add_argument("--save-preset", metavar="NAME", help="save these choices under this name") + o.add_argument("--retune", action="store_true", + help="with --tune (quick is used when --tune is not given): measure again even when this model was already tuned on this computer " + "(by default a stored tuning result is reused and no measuring is done)") o.add_argument("--no-tui", action="store_true", help="no screens: serve, print the address and return") o.add_argument("--open", action="store_true", help="open the server's web page in your browser once it is serving (nothing opens a browser without this)") o.add_argument("--yes", action="store_true", help="do not ask questions (for one: whether to download the model on a computer with no engine yet)") @@ -311,6 +317,17 @@ def _say(line: str = "") -> None: sys.stdout.flush() +def _interrupted_move_notice() -> None: + """One line when a move of the models folder was left unfinished (never blocks the launch).""" + try: + from strata_control import discovery, models_move + st = models_move.interrupted(discovery.data_dir(Path.home() / "Strata")[0]) + except Exception: + return + if st: + _say("A move of your models was interrupted. Finish it with `strata models move --resume`, or keep them where they are with `strata models move --leave`.") + + def _printer(quiet: bool = False): """An emit callback that prints readable lines: new text once, progress in steps of 10% when not on a terminal.""" state = {"last": None, "pct": -10, "stage": None} @@ -541,6 +558,8 @@ def run_launch(a: argparse.Namespace) -> int: if a.model or a.model_path: return fail(str(e), 5) s, notices = settings_from_args(a, catalog) + if not machine: + _interrupted_move_notice() have_choices = bool(a.preset or a.model or a.model_path or a.context or a.vision or a.parallel or a.access or a.tune) interactive = sys.stdin.isatty() and sys.stdout.isatty() and not a.no_tui and not machine and not a.plan plain_questions = False @@ -559,6 +578,14 @@ def run_launch(a: argparse.Namespace) -> int: return _tui(app.run_tui, None, catalog=catalog, feed=a.feed, open_page=bool(a.open)) if catalog is None: return fail("This Terminal does not carry the model list. Install it again with the one-line installer.", 5) + if getattr(a, "retune", False) and s.tune == "skip": + s.tune = "quick" + runner = Runner(s, catalog=catalog, emit=_printer(machine), feed=a.feed, assume_yes=bool(a.yes or machine), confirm=_ask_yes, + retune=bool(getattr(a, "retune", False))) + try: + runner.check_own_files() # the person's own files: a wrong path is said now, and the files name the model + except LaunchError as e: + return fail(f"{e.text}" + (f" {e.next}" if e.next else ""), e.code) s, notes = apply_defaults(s, catalog) errors = [n for n in notes if n.level == "error"] if errors: @@ -569,8 +596,7 @@ def run_launch(a: argparse.Namespace) -> int: if not s.name: s.name = f"{s.model or 'model'} {S.context_label(s.context)}" move_data = _move_data_choice(a, s, catalog, machine) - runner = Runner(s, catalog=catalog, emit=_printer(machine), feed=a.feed, assume_yes=bool(a.yes or machine), confirm=_ask_yes, - move_data=move_data) + runner.s, runner.move_data = s, move_data if a.plan: plan = runner.plan() plan["warnings"] = [n.line() for n in notes] @@ -578,8 +604,14 @@ def run_launch(a: argparse.Namespace) -> int: print(json.dumps({"schema_version": 1, "ok": True, "plan": plan})) else: _say(f"Plan for '{s.name}':") - _say(f" model {s.family} {s.model}" if s.model else f" model your files at {s.model_path}") - _say(f" context {S.context_label(s.context)} pictures {s.vision} parallel {s.parallel or 'fit to your card'}") + m = plan.get("model") or {} + size = f", {m['model_gb']:.0f} GB" if m.get("model_gb") else "" + if s.model_path: + _say(f" model {m.get('title') or 'your model files'}{size} (your files in {s.model_path})") + else: + _say(f" model {m.get('title') or f'{s.family} {s.model}'}{size}") + _say(f" context {S.context_label(s.context)} pictures {PICTURE_WORDS.get(s.vision or 'off', s.vision)} parallel {s.parallel or 'fit to your card'}") + _say(f" download {(plan.get('download') or {}).get('text', '')}") _say(f" tuning {s.tune} access {S.ACCESS_WORDS[s.access]}, port {s.port}" + (" API key on" if s.api_key else "")) for n in notes: @@ -605,7 +637,7 @@ def run_launch(a: argparse.Namespace) -> int: if interactive and have_choices: from strata_cli.launch import app return _tui(app.run_tui, s, catalog=catalog, feed=a.feed, auto_run=True, save=bool(a.save_preset), open_page=bool(a.open), - move_data=move_data) + move_data=move_data, retune=bool(getattr(a, "retune", False))) try: result = runner.run() except LaunchError as e: diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 709675b8..d8c22364 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -310,12 +310,23 @@ def download_text(dl: dict, already: bool, label: str | None = None) -> str: return f"{label}: {dl['done_gb']:.1f} of {dl['total_gb']:.1f} GB" if label else f"Downloading {dl['done_gb']:.1f} of {dl['total_gb']:.1f} GB" +_END = object() + + +def _elapsed(seconds: float) -> str: + """'40 s', '3 min' (plain, rounded down).""" + seconds = int(seconds) + return f"{seconds} s" if seconds < 90 else f"{seconds // 60} min" + + class Runner: def __init__(self, s: S.LaunchSettings, *, catalog: Catalog | None = None, emit: Callable[[Event], None] | None = None, cancel: threading.Event | None = None, feed: str | None = None, python: str | None = None, components_dir: str | None = None, hardware: dict | None = None, - confirm: Callable[[str, str], bool] | None = None, assume_yes: bool = False, move_data: bool = False): + confirm: Callable[[str, str], bool] | None = None, assume_yes: bool = False, move_data: bool = False, + retune: bool = False): self.s = s + self.retune = retune # --retune: measure again even when a tuning result for this model on this computer is stored self.move_data = move_data # --move-data / the answer "move": the model files already here go to the new --data-dir self.confirm = confirm # asked (title, text) before a model is downloaded with no engine; True = go on self.assume_yes = assume_yes # --yes: no questions @@ -331,6 +342,7 @@ class Runner: self.notices: list[str] = [] self.tune_result: dict | None = None self.config_path: Path | None = None + self._own_checked = False # ---- small helpers def emit(self, stage: str, text: str, pct: float | None = None, level: str = "info", **data: Any) -> None: @@ -623,10 +635,55 @@ class Runner: """(title, text) of the question before a download starts, naming exactly what is fetched.""" return self.model_state().question() + #: seconds of silence from setup before a "still working" line (packing a 40 GB model prints nothing for minutes) + HEARTBEAT_S = 30.0 + + def _read_lines(self, p: subprocess.Popen): + """The lines setup prints, and None whenever a second passes with none, so a silent step can say it is still going and a cancel is + seen at once.""" + import queue + q: queue.Queue = queue.Queue() + + def pump() -> None: + try: + for ln in p.stdout: # type: ignore[union-attr] + q.put(ln) + finally: + q.put(_END) + threading.Thread(target=pump, daemon=True).start() + while True: + try: + ln = q.get(timeout=min(1.0, max(0.05, self.HEARTBEAT_S / 2))) + except queue.Empty: + yield None + continue + if ln is _END: + return + yield ln + + def progress_job(self) -> dict: + """What the download figure is counted over: the folder setup writes the model into (the data folder it is GIVEN, which may be the + person's --data-dir and not the default one) and every file of the install with the catalog's total, so a model in several shards + shows 'of 66.4 GB' from the start and not the size of the file being fetched.""" + s, cat = self.s, self.catalog + data = Path(s.data_dir) if s.data_dir else (self.existing_data_dir() or cat.data_dir()) + models_dir = data / "models" + job = {"folder": str(models_dir / cat.tag_of(s.family, s.model)), + "total_gb": float(next((r.download_gb for r in cat.rows() if r.family == s.family and r.model == s.model), 0) or 0)} + try: + setup_module = cat.strata.setup_module() + if setup_module is not None and not s.model_path: + job["files"] = cat.mcp.expected_files(setup_module, str(s.family), str(s.model), models_dir, self.vision_word() != "no") + first = next((f for f in job["files"] if f.get("role") == "model"), None) + if first: # the folder setup names it (Q2_0), not the lower-case run-config tag (q2_0) + job["folder"] = str(Path(first["path"]).parent) + except Exception: # noqa: BLE001 - progress is a convenience; the folder scan still counts + pass + return job + def ensure_model(self) -> Path: s, cat = self.s, self.catalog - if s.model_path: - self.resolve_own_files() + self.check_own_files() self.resolved_vision() if not (s.family and s.model): raise LaunchError("No model was chosen.", "Choose a model, or use --model NAME (strata launch --help lists them).", 2) @@ -641,7 +698,8 @@ class Runner: adopted = self.adopt_prepared_files("no Mac model installer in this Terminal") if adopted is not None: return adopted - self.emit("model", f"Getting {title} ready (a download may be large; it continues where it stopped if interrupted)…", 0) + self.emit("model", f"Preparing {title} from your model files…" if s.model_path else + f"Getting {title} ready (a download may be large; it continues where it stopped if interrupted)…", 0) argv = [self.python, str(cat.src / "setup.py"), *self.setup_args()] env = self._env() env.update(STRATA_CONTROL_INSTALL="1", STRATA_INSTALL_DIR=str(cat.root), PYTHONNOUSERSITE="1") @@ -656,20 +714,32 @@ class Runner: p = self._spawn(argv, env=env, cwd=str(cat.src)) lines: list[str] = [] already: bool | None = None # all the model's files were on disk before this run wrote anything - folder = str(cat.data_dir() / "models" / cat.tag_of(s.family, s.model)) - total = float(next((r.download_gb for r in cat.rows() if r.family == s.family and r.model == s.model), 0) or 0) - for line in p.stdout: # type: ignore[union-attr] + job = self.progress_job() + step_seen, step_since, quiet_since, said = None, time.monotonic(), time.monotonic(), None + for line in self._read_lines(p): if self.cancel.is_set(): self._stop_children() raise Cancelled() + if line is None: # nothing printed for a while: the long steps (packing, converting) are silent + if said and said[1] != "download" and time.monotonic() - quiet_since >= self.HEARTBEAT_S: + quiet_since = time.monotonic() + self.emit("model", f"{said[0]} (still working, {_elapsed(time.monotonic() - step_since)} so far)", None, step=step_seen) + continue + quiet_since = time.monotonic() line = line.rstrip() if not line: continue lines.append(line) lines[:] = lines[-1500:] prog = cat.mcp.install_progress(lines) - prog = cat.mcp.combined_progress(prog, {"folder": folder, "total_gb": total}) + prog = cat.mcp.combined_progress(prog, job) dl, phase, label = prog.get("download"), prog.get("phase"), prog.get("label") + if prog.get("step") != step_seen: + step_seen, step_since = prog.get("step"), time.monotonic() + if label and not dl: + said = (label, phase) + else: + said = None if dl and dl.get("total_gb", 0) >= 0.05 and not (s.model_path and phase == "download"): if phase == "download" and already is None: already = float(dl["percent"]) >= 99.5 @@ -695,7 +765,8 @@ class Runner: if adopted is not None: return adopted raise LaunchError("The model could not be installed." + (f" {err}." if err else ""), - hint or "Run it again: finished steps are skipped and a download continues where it stopped.", 6) + hint or ("Run it again: finished steps are skipped." if s.model_path else + "Run it again: finished steps are skipped and a download continues where it stopped."), 6) path, _desc = self.installed_state() if path is None: raise LaunchError("Setup finished but no run config was written for this model.", @@ -737,12 +808,22 @@ class Runner: self.emit("model", f"Used your prepared model files and wrote the run settings ({path.name}); this card is not one the built-in downloader sets up.", 100, level="warn") return path + def check_own_files(self) -> None: + """The person's own model files, looked at once: a path that is not there or holds no model is said in plain words first, and the + files are matched to the catalog model (resolve_own_files). Nothing else is done with a path that was already checked.""" + if self.s.model_path and not self._own_checked: + self.resolve_own_files() + self._own_checked = True + def resolve_own_files(self) -> None: """"Use model files I already have": the fingerprint table says which catalog model the files are, and which folder holds them (the person may have named the folder above it). When the person also named the model (--model), the files are never refused here: setup takes the files of that model out of the folder by name, as it always did (0.1.45), and says what is wrong when it cannot.""" from strata_control import models s = self.s + problem = models.own_path_problem(s.model_path) + if problem: # before the engine or setup are touched, with the path as typed + raise LaunchError(problem[0], problem[1], 2) given = bool(s.family and s.model) try: plan = models.plan_import(models.absolute(s.model_path)) @@ -760,7 +841,7 @@ class Runner: sel = plan.get("candidate_selection") or {} fam, model = sel.get("family"), sel.get("model") if not (fam and model) or plan.get("issues"): - issues = "; ".join(plain_issue(str(x)) for x in (plan.get("issues") or [])[:3]) or "they are not a model Strata knows" + issues = models.problem_words(plan.get("issues") or []) or "they are not a model Strata knows" more = " " + next((m for m in plan.get("messages") or [] if "holds" in m), "") raise LaunchError(f"These files cannot be used as they are ({issues}).{more.rstrip()}", "Choose the matching model in the list, or check that every shard is in the folder.", 5) @@ -811,16 +892,23 @@ class Runner: if s.tune == "skip": return from strata_control import presets - if s.tuned_preset: - try: - presets.find(s.tuned_preset) - self.emit("tune", "This preset is already tuned for this computer.", 100) + if not self.retune: + if s.tuned_preset: + try: + presets.find(s.tuned_preset) + self.emit("tune", "This preset is already tuned for this computer.", 100) + return + except presets.PresetError: + pass + elif s.tuned_at: # measured before: the standard settings were already the fastest, nothing was saved + self.emit("tune", f"Already tuned on {s.tuned_at}: this computer runs best with the standard settings. Nothing to do.", 100) + return + stored = self.stored_tuning() + if stored: # the same model and choices were tuned on this computer before (a run by flags, no preset) + s.tuned_preset, s.tuned_at = stored["id"], stored["date"] + self.emit("tune", f"This model was already tuned for this computer on {stored['date']} ('{stored['name']}'), so that result is used " + "and nothing is measured again. Add --retune to measure again.", 100) return - except presets.PresetError: - pass - elif s.tuned_at: # measured before: the standard settings were already the fastest, nothing was saved - self.emit("tune", f"Already tuned on {s.tuned_at}: this computer runs best with the standard settings. Nothing to do.", 100) - return mode = "thorough" if s.tune == "thorough" else "quick" status_file = launch_dir() / f"{self.name}.tune.json" try: @@ -866,6 +954,22 @@ class Runner: s.tuned_at = time.strftime("%Y-%m-%d") self.emit("tune", f"Tuning result: {word}. {sentence}", 100, level="info" if word in ("faster", "already fastest") else "warn", word=word) + def stored_tuning(self) -> dict | None: + """The tuning result stored for this launch's model, choices and computer (the active preset of its slot in the shared presets store, + which the start applies), or None. A result whose computer changed in a way that matters (a different card, processor or memory, + another model file) is not reused: it is measured again.""" + if self.config_path is None: + return None + from strata_control import presets + try: + _cfg, info = presets.overlay(read_config(self.config_path)) + if not info.get("applied") or not info.get("preset"): + return None + made = str(presets.load(info["preset"]["id"]).get("created") or "")[:10] + return {"id": info["preset"]["id"], "name": info["preset"]["name"], "date": made or time.strftime("%Y-%m-%d")} + except Exception: # noqa: BLE001 - an unreadable store means: measure + return None + tune_word: str | None = None # ---- 5. start @@ -933,14 +1037,79 @@ class Runner: return tunnel # ---- all of it + def row(self): + """The catalog row of the chosen model (None for a model the list does not carry).""" + s = self.s + return next((r for r in self.catalog.rows() if (r.family, r.model) == (s.family, s.model)), None) + + def download_plan(self) -> dict: + """What this launch would download, in numbers and words (nothing is changed): the model's missing files, and for a model that is + not on this computer yet also the draft layer and the picture reader that setup fetches after it. 0 when everything is here.""" + from strata_control import engine_component + from strata_control.discovery import MMPROJ_GB, MTP_FETCH_GB + s = self.s + st = self.model_state() + parts = [{"kind": p.kind, "label": p.label, "gb": round(p.gb, 1)} for p in st.parts if p.gb >= 0.05] # a part already on disk is not a download + row = self.row() + helpers = s.family in ("qwen", "swift", "coder", "unsloth") + wants_pictures = s.vision not in (None, "off") and row is not None and bool(row.images) + if helpers and (st.own_files or not st.installed): + # a model that is not set up yet (or the person's own files) comes without the draft layer and the picture reader: setup fetches them + # next to the prepared data, unless they are there already + have = {p["kind"] for p in parts} + try: + data = Path(st.folder) if st.folder else (Path(s.data_dir) if s.data_dir else (self.existing_data_dir() or self.catalog.data_dir())) + if s.mtp != "off" and "mtp" not in have and not (data / "mtp" / "rt" / "experts.bin").is_file(): + parts.append({"kind": "mtp", "label": "the draft layer", "gb": MTP_FETCH_GB}) + has_reader = list((data / "models").glob("mmproj*.gguf")) or list((data / "Models").glob("mmproj*.gguf")) + if wants_pictures and "mmproj" not in have and not has_reader: + parts.append({"kind": "mmproj", "label": "the picture reader", "gb": MMPROJ_GB}) + except OSError: + pass + gb = round(sum(p["gb"] for p in parts), 1) + engine = True + try: + engine = bool(engine_component.status(Path(self.components_dir) if self.components_dir else None).get("usable")) + except Exception: # noqa: BLE001 - the plan must not fail on this + pass + if gb < 0.05: + text = ("Nothing to download: your model files are used where they are." if st.own_files + else "Nothing to download: the model is already on this computer.") + else: + names = [f"{p['label']} ({p['gb']:.1f} GB)" for p in parts] + what = names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1] + text = f"About {gb:.1f} GB to download: {what}." + if st.on_disk_gb >= 1: + text += f" {st.on_disk_gb:.0f} GB of the model is already in its folder." + if st.own_files: + text += " Your model files are used where they are." + if not engine: + text += " The engine for your graphics card is downloaded first (from the update source; its size is shown when it starts)." + return {"gb": gb, "parts": parts, "engine_missing": not engine, "own_files": st.own_files, "text": text} + def plan(self) -> dict: s = self.s + self.check_own_files() warns = [n.line() for n in (*S.check_access(s),)] + row = self.row() + try: + self.resolved_vision() + except Exception: # noqa: BLE001 + pass + try: + download = self.download_plan() + except Exception: # noqa: BLE001 - a plan that cannot count the download still shows the rest + download = {"gb": None, "parts": [], "engine_missing": None, "own_files": bool(s.model_path), + "text": "How much would be downloaded could not be worked out here."} + title = row.title if row is not None else (f"{s.family} {s.model}" if s.model else None) + model = {"title": title, "family": s.family, "model": s.model, "model_gb": row.download_gb if row is not None else None, + "own_files": bool(s.model_path), "folder": s.model_path} return {"profile": self.profile, "settings": s.to_dict(with_key=False), "warnings": warns, - "flags": S.flags_text(s), "steps": list(STAGES)} + "flags": S.flags_text(s), "steps": list(STAGES), "model": model, "download": download} def run(self, *, start: bool = True) -> Result: try: + self.check_own_files() # a wrong --model-path is said before the engine is downloaded self.ensure_engine() self.check_cancel() base = self.ensure_model() diff --git a/strata_cli/launch/screens.py b/strata_cli/launch/screens.py index f2ec0db7..53730937 100644 --- a/strata_cli/launch/screens.py +++ b/strata_cli/launch/screens.py @@ -492,8 +492,11 @@ class ModelScreen(Base): self.check_own(path) def check_own(self, path: str) -> None: - from strata_cli.launch.runner import plain_issue from strata_control import models + problem = models.own_path_problem(path) + if problem: + self.say(f"{problem[0]} {problem[1]}", True) + return try: plan = models.plan_import(models.absolute(path)) except Exception as e: # noqa: BLE001 @@ -510,7 +513,7 @@ class ModelScreen(Base): self.menu().select((sel["family"], sel["model"])) self.paint() else: - why = "; ".join(plain_issue(str(x)) for x in (plan.get("issues") or [])[:3]) or "they are not a model Strata knows" + why = models.problem_words(plan.get("issues") or []) or "they are not a model Strata knows" holds = next((m for m in plan.get("messages") or [] if "holds" in m), "") self.say(f"These files cannot be used as they are ({why}). " + (holds + " " if holds else "") + "Check that every shard is in the folder, or pick a model from the list.", True) diff --git a/strata_cli/launch/settings.py b/strata_cli/launch/settings.py index 8079fb16..26588879 100644 --- a/strata_cli/launch/settings.py +++ b/strata_cli/launch/settings.py @@ -270,7 +270,7 @@ def flags_text(s: LaunchSettings, *, preset: str | None = None) -> str: else: if s.model_path: parts.append(f'--model-path "{s.model_path}"') - elif s.model: + if s.model: # own files the table recognised say which model they are, so the line stays exact parts.append(f"--model {s.model.lower()}" + (f" --family {s.family}" if s.family and s.family != "qwen" else "")) if s.data_dir: parts.append(f'--data-dir "{s.data_dir}"') diff --git a/strata_control/models.py b/strata_control/models.py index 74914ed2..a42d8539 100644 --- a/strata_control/models.py +++ b/strata_control/models.py @@ -339,6 +339,34 @@ def plain_issue(code: str) -> str: return f"{name}: {words}" if name else words +def problem_words(issues: list, limit: int = 3) -> str: + """The problems of a file set as ONE sentence part, each said once: the same reason for several files names the files together + ("a.gguf and b.gguf: the file is cut short"), a reason that was already given is not given again, and a long list is cut with a count. + A folder that holds several models does not also say "not a size Strata knows".""" + codes = [str(x) for x in issues or []] + if "multiple_model_groups" in codes: + codes = [x for x in codes if x != "unrecognized_or_unsupported_model_variant"] + by_reason: dict[str, list[str]] = {} + for code in codes: + words = plain_issue(code) + name, sep, reason = words.partition(": ") + if sep and name.lower().endswith(".gguf"): + by_reason.setdefault(reason, []).append(name) + else: + by_reason.setdefault(words, []) + parts = [] + for reason, names in by_reason.items(): + if not names: + parts.append(reason) + elif len(names) <= 2: + parts.append(f"{' and '.join(names)}: {reason}") + else: + parts.append(f"{names[0]}, {names[1]} and {len(names) - 2} more files: {reason}") + if len(parts) > limit: + parts = parts[:limit] + [f"and {len(parts) - limit} more problem" + ("s" if len(parts) - limit > 1 else "")] + return "; ".join(parts) + + UNSUPPORTED_MODEL_TYPE = ("This model type isn't supported by the Strata engine. " "Add it as a Custom model API (llama-server) instead.") # The picture readers Strata ships a pinned copy of (setup downloads and checks one of these next to the model). @@ -496,6 +524,30 @@ def import_target(picked: str, plan: dict) -> str: return plan.get("model_dir") or picked +def own_path_problem(picked: str) -> tuple[str, str] | None: + """(what is wrong, what to do) when the path a person gave for their own model files is not there or holds no model file, in plain + words; None when there is something to look at. Said before anything is installed or downloaded, with the path the person typed.""" + path = Path(absolute(picked)) + kind = "file" if path.name.lower().endswith(".gguf") else "folder" + try: + if not path.exists(): + if path.is_symlink(): + return (f"This {kind} is a shortcut to something that is not there any more: {path}.", + "Point it at the real folder, or at the .gguf file itself. Nothing was downloaded or changed.") + return (f"This {kind} does not exist: {path}.", + "Check the spelling, and that the drive or folder is connected (in Docker or a virtual machine it has to be shared with it). " + "Nothing was downloaded or changed.") + if path.is_dir(): + has_files = any(entry.name.lower().endswith(".gguf") for entry in os.scandir(path)) + if not has_files and not _folders_with_models(path): + return (f"There are no .gguf model files in {path}, nor in the folders inside it.", + "Point it at the folder that holds the model's .gguf files (names like ...-00001-of-00002.gguf), or at one of the files. " + "Nothing was downloaded or changed.") + except OSError: + return None + return None + + def plan_import(raw_path: str) -> dict: """Inspect a local candidate without copying, parsing tensors or adopting it. diff --git a/strata_control/models_move.py b/strata_control/models_move.py new file mode 100644 index 00000000..8929ab9b --- /dev/null +++ b/strata_control/models_move.py @@ -0,0 +1,573 @@ +"""Move the model files (models, packs, mtp) from one data folder to another (0.2.2, Settings > Storage > Models folder). + +The desktop app and the Terminal both use this: ``strata models move``. Rules, in the order they matter: + +* Nothing is deleted until its copy is whole and checked. One file at a time: copy to ``name.part``, compare the size, read the copy + back and compare its SHA-256 with the original's (and with the pinned SHA-256 in the file's ``.done`` mark when it has one), rename it + into place, only then remove the original. The extra space needed is never more than the move itself. +* Stopping is safe. The file in flight is discarded (its ``.part`` is removed), files already moved stay, and the run configs are + rewritten for every model whose files are all in the new folder. The data folder in the settings is changed by the caller only + when the whole move is done, so the app is never pointed at an incomplete folder. +* The same drive is a rename (instant). Another drive is a copy. +* A crash leaves at worst a model in both folders; ``name.part`` files are never trusted. +""" + +from __future__ import annotations + +import errno +import hashlib +import json +import os +import re +import shutil +import tempfile +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Callable + +ITEMS = ("models", "packs", "mtp") +STATE_FILE = "models-move.json" +MARGIN = 1.05 # room beside the files themselves: 5 % +CHUNK = 8 * 1024 * 1024 + + +class MoveError(Exception): + """A move that stopped for a reason the person can act on. ``code`` is one of: not_found, not_writable, inside, disk_full, verify, busy, io.""" + + def __init__(self, code: str, message: str, details: str = ""): + super().__init__(message) + self.code = code + self.details = details + + +class Stopped(Exception): + """The person asked to stop.""" + + +@dataclass +class Entry: + rel: str # path under the data folder, with "/" (models//file.gguf) + size: int + group: str # the model it belongs to: "models/", "packs/", "mtp" + + +# ----------------------------------------------------------------------------------------------- what is there + +def _item_dirs(data: Path) -> list[Path]: + """The models / packs / mtp folders of a data folder (any spelling of the name: ``Models`` and ``models`` are one library).""" + try: + names = sorted(p for p in data.iterdir() if p.is_dir() and p.name.lower() in ITEMS) + except OSError: + return [] + return names + + +def inventory(data: Path) -> list[Entry]: + """Every file Strata keeps in a data folder: nothing else is touched. Unfinished downloads (``.part``) are left where they are.""" + found: list[Entry] = [] + for top in _item_dirs(data): + for root, _dirs, files in os.walk(top): + for name in files: + if name.endswith(".part"): + continue + path = Path(root) / name + try: + size = path.stat().st_size + except OSError: + continue + rel = path.relative_to(data).as_posix() + parts = rel.split("/") + kind = parts[0].lower() + group = kind if kind == "mtp" or len(parts) < 3 else parts[1].lower() # a model's GGUF files and its pack are one model + found.append(Entry(rel, size, group)) + found.sort(key=lambda e: (e.group, e.rel)) + return found + + +def groups(entries: list[Entry]) -> list[dict]: + """The models in a list of files, for the person: name (the folder name), bytes.""" + out: dict[str, int] = {} + for e in entries: + out[e.group] = out.get(e.group, 0) + e.size + return [{"group": g, "name": g, "bytes": b} for g, b in out.items()] + + +def _near(path: Path) -> Path: + """The folder that exists and holds ``path`` (or ``path`` itself).""" + p = path + while not p.exists() and p.parent != p: + p = p.parent + return p + + +def same_drive(a: Path, b: Path) -> bool: + """Both folders are on one volume (a move is then a rename). STRATA_MOVE_ALWAYS_COPY=1 copies anyway: for testing the copy path on one disk.""" + if os.environ.get("STRATA_MOVE_ALWAYS_COPY") == "1": + return False + try: + return os.stat(_near(a)).st_dev == os.stat(_near(b)).st_dev + except OSError: + return False + + +def _same(a: Path, b: Path) -> bool: + return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b)) + + +def _inside(child: Path, parent: Path) -> bool: + c, p = os.path.normcase(os.path.abspath(child)), os.path.normcase(os.path.abspath(parent)) + return c != p and c.startswith(p.rstrip(os.sep) + os.sep) + + +def _write_test(folder: Path) -> str | None: + """None when files can be written in ``folder`` (made if missing); else the raw refusal.""" + try: + folder.mkdir(parents=True, exist_ok=True) + fd, name = tempfile.mkstemp(prefix=".strata-write-test", dir=folder) + os.close(fd) + os.remove(name) + return None + except OSError as e: + return f"{errno.errorcode.get(e.errno, e.errno)}: {e.strerror or e}, {e.filename or folder}" + + +# ----------------------------------------------------------------------------------------------- plan + +def plan(old: Path, new: Path, *, free=None, write_test: bool = True) -> dict: + """What picking ``new`` for the models folder means, without changing anything. + + Returns ``{ok, issue, old, new, same, same_drive, free_bytes, models_bytes, needed_bytes, models, choices}``. ``issue`` is None or + ``{code, message, details}``: not_found (the folder or its drive is gone), not_writable, inside (one folder inside the other), + same (nothing to do). ``choices`` says which of move / keep / empty can be done and why not. + """ + old, new = Path(old), Path(new) + free = free or (lambda p: shutil.disk_usage(p).free) + entries = inventory(old) if old.is_dir() else [] + total = sum(e.size for e in entries) + result = {"ok": False, "issue": None, "old": str(old), "new": str(new), "same": False, "same_drive": False, "free_bytes": 0, + "models_bytes": total, "needed_bytes": 0, "models": groups(entries), "choices": {}} + + def refuse(code, message, details=""): + result["issue"] = {"code": code, "message": message, "details": details} + result["choices"] = {k: {"possible": False, "reason": message} for k in ("move", "keep", "empty")} + return result + + if _same(old, new): + result["same"] = True + return refuse("same", "That is the folder Strata already uses.") + if _inside(new, old) or _inside(old, new): + return refuse("inside", "Pick a folder outside the current one.") + if not new.exists(): + # a folder that will be made is fine when its parent is there; a drive that is not plugged in is not + drive = Path(new.anchor) if new.anchor else None + if drive is not None and not drive.exists(): + return refuse("not_found", f"Strata can't find {new}.", f"{drive} does not exist") + if write_test: + raw = _write_test(new) + if raw: + return refuse("not_writable", f"Strata can't save files in {new}.", raw) + result["same_drive"] = same_drive(old, new) + try: + result["free_bytes"] = int(free(_near(new))) + except OSError: + result["free_bytes"] = 0 + # a same-drive move is a rename: it needs no room + needed = 0 if result["same_drive"] else int(total * MARGIN) + result["needed_bytes"] = needed + can_move = bool(entries) and result["free_bytes"] >= needed + reason_move = "" if can_move else ("You have no models to move." if not entries + else f"Your models need {_gb(needed)}, this drive has {_gb(result['free_bytes'])} free.") + result["choices"] = {"move": {"possible": can_move, "reason": reason_move}, "keep": {"possible": True, "reason": ""}, + "empty": {"possible": True, "reason": ""}} + result["ok"] = True + return result + + +def _gb(n: int) -> str: + g = n / 1e9 + return f"{g:.0f} GB" if g >= 10 else f"{g:.1f} GB" + + +# ----------------------------------------------------------------------------------------------- the move + +def _sha256_of(path: Path, stop: Callable[[], bool], tick: Callable[[int], None] | None = None) -> str: + h = hashlib.sha256() + with open(path, "rb") as f: + while True: + if stop(): + raise Stopped() + block = f.read(CHUNK) + if not block: + break + h.update(block) + if tick: + tick(len(block)) + return h.hexdigest() + + +def _pinned(src: Path) -> str | None: + """The SHA-256 a finished download wrote in its ``.done`` mark (setup.py: ``sha256 ``), when there is one.""" + mark = src.with_name(src.name + ".done") + try: + m = re.search(r"sha256\s+([0-9a-fA-F]{64})", mark.read_text(encoding="utf-8", errors="replace")) + except OSError: + return None + return m.group(1).lower() if m else None + + +def _disk_full(e: OSError) -> bool: + return e.errno in (errno.ENOSPC, errno.EDQUOT) or getattr(e, "winerror", None) in (112, 39) + + +def _copy_verified(src: Path, dst: Path, size: int, stop: Callable[[], bool], tick: Callable[[int], None]) -> None: + """Copy src to dst (through dst.part), prove the copy is the same file, rename it into place. The source is left alone.""" + part = dst.with_name(dst.name + ".part") + dst.parent.mkdir(parents=True, exist_ok=True) + h = hashlib.sha256() + try: + with open(src, "rb") as fin, open(part, "wb") as fout: + while True: + if stop(): + raise Stopped() + block = fin.read(CHUNK) + if not block: + break + h.update(block) + fout.write(block) + tick(len(block)) + fout.flush() + os.fsync(fout.fileno()) + if part.stat().st_size != size: + raise MoveError("verify", f"The copy of {src.name} has the wrong size.", f"{part.stat().st_size} != {size}") + want = h.hexdigest() + pinned = _pinned(src) + if pinned and pinned != want: + raise MoveError("verify", f"{src.name} does not match its saved checksum, so it was not moved.", f"sha256 {want} != pinned {pinned}") + got = _sha256_of(part, stop) + if got != want: + raise MoveError("verify", f"The copy of {src.name} did not match the original.", f"sha256 {got} != {want}") + os.replace(part, dst) + except OSError as e: + _quiet_remove(part) + if _disk_full(e): + raise MoveError("disk_full", "The drive ran out of space.", f"{errno.errorcode.get(e.errno, e.errno)}: {e.strerror}, {e.filename or dst}") from e + raise MoveError("io", f"Strata could not copy {src.name}.", f"{type(e).__name__}: {e}") from e + except BaseException: + _quiet_remove(part) + raise + + +def _quiet_remove(path: Path) -> None: + try: + os.remove(path) + except OSError: + pass + + +def _read_state(new: Path) -> dict: + try: + return json.loads((new / STATE_FILE).read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + + +def _write_state(new: Path, **fields) -> None: + try: + tmp = new / (STATE_FILE + ".tmp") + tmp.write_text(json.dumps(fields, indent=1), encoding="utf-8") + os.replace(tmp, new / STATE_FILE) + except OSError: + pass + + +def _save_state(old: Path, new: Path, **fields) -> None: + """The state goes in the new folder and, as a pointer, in the old one: the old folder stays the data folder until the move is done, + so that is where the next start looks.""" + _write_state(new, **fields) + _write_state(old, **fields) + + +def _clear_state(*folders: Path) -> None: + for f in folders: + _quiet_remove(Path(f) / STATE_FILE) + + +def _same_path(a, b) -> bool: + try: + return _same(Path(a), Path(b)) + except (OSError, ValueError, TypeError): + return False + + +def interrupted(data: Path) -> dict | None: + """The unfinished move recorded in the data folder (``models-move.json``), for 'A move was interrupted. Finish it or leave it'. + + A move that is running right now (its process is alive) is not interrupted. A stopped or failed move that left files in both folders is. + Returns ``{state, from, to, bytes}`` or None. + """ + data = Path(data) + st = _read_state(data) + if st.get("state") not in ("running", "stopped", "failed") or not st.get("from") or not st.get("to"): + return None + if not _same_path(st["from"], data): # a pointer left in some other folder is not ours + return None + if not Path(st["from"]).is_dir(): + return None + pid, token = st.get("pid"), st.get("token") + if st["state"] == "running" and isinstance(pid, int) and token and pid != os.getpid(): + try: + from strata_control import procs + if procs.start_token(pid) == token: + return None + except Exception: + pass + return st + + +def repoint_config(cfg_file: Path, old: Path, new: Path) -> bool: + """A run config whose model files moved from ``old`` to ``new`` names them there (each path only when its file is now there and no longer + at the old place). Same rule as setup.py repoint_config. Returns whether the file changed.""" + try: + cfg = json.loads(cfg_file.read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + return False + + def fix(v): + if isinstance(v, list): + return [fix(x) for x in v] + if isinstance(v, dict): + return {k: fix(x) for k, x in v.items()} + if isinstance(v, str): + o = str(old) + nv, no = os.path.normcase(v), os.path.normcase(o) + if nv.startswith(no + os.sep) or nv.startswith(no + "/"): + rest = v[len(o):] + if re.split(r"[\\/]", rest.lstrip("\\/"))[0].lower() in ITEMS: + n = str(new) + rest + if Path(n).exists() and not Path(v).exists(): + return n + return v + + fixed = fix(cfg) + if fixed == cfg: + return False + tmp = cfg_file.with_name(cfg_file.name + ".move-tmp") + tmp.write_text(json.dumps(fixed, indent=2) + "\n", encoding="utf-8") + os.replace(tmp, cfg_file) + return True + + +def config_files(install: Path | None) -> list[Path]: + """The ``strata-.json`` run configs of an install folder.""" + if not install or not Path(install).is_dir(): + return [] + return [p for p in Path(install).glob("strata-*.json") if not p.name.endswith(".shared-settings.json")] + + +def _prune(folder: Path, stop_at: Path) -> None: + """Remove empty folders from ``folder`` upward, never ``stop_at`` itself.""" + p = folder + while p != stop_at and _inside(p, stop_at): + try: + p.rmdir() + except OSError: + return + p = p.parent + + +def move(old: Path, new: Path, *, on_progress: Callable[[dict], None] | None = None, cancelled: Callable[[], bool] | None = None, + configs: list[Path] | None = None, now: Callable[[], float] = time.time) -> dict: + """Move the model files from ``old`` to ``new``. Returns the summary; raises MoveError (nothing lost) or Stopped. + + ``summary = {done: bool, stopped: bool, moved: [group], remaining: [group], bytes_moved, total_bytes, files_moved, same_drive}``. + """ + old, new = Path(old), Path(new) + emit = on_progress or (lambda _e: None) + stop = cancelled or (lambda: False) + p = plan(old, new, write_test=True) + if p["issue"]: + raise MoveError(p["issue"]["code"], p["issue"]["message"], p["issue"]["details"]) + entries = inventory(old) + total = sum(e.size for e in entries) + if not p["choices"]["move"]["possible"] and entries: + raise MoveError("disk_full", p["choices"]["move"]["reason"]) + # unfinished copies of an earlier run are never trusted + for top in _item_dirs(new): + for root, _d, files in os.walk(top): + for name in files: + if name.endswith(".part"): + _quiet_remove(Path(root) / name) + same = p["same_drive"] + todo = {e.group: [] for e in entries} + for e in entries: + todo[e.group].append(e) + left = {g: len(v) for g, v in todo.items()} + moved_groups: list[str] = [] + before = _read_state(old) + if not (_same_path(before.get("from", ""), old) and _same_path(before.get("to", ""), new)): + before = {} + try: + from strata_control import procs + token = procs.start_token(os.getpid()) + except Exception: + token = None + state = {"state": "running", "from": str(old), "to": str(new), "started": now(), "bytes": total, "pid": os.getpid(), "token": token, + "files": sorted({e.rel for e in entries} | set(before.get("files") or []))} + _save_state(old, new, **state) + done_bytes = 0 + files_moved = 0 + last_emit = [0.0] + started = now() + seen_inodes: dict[tuple, Path] = {} + base_event = lambda **kw: {"event": "progress", "total": total, "same_drive": same, **kw} + + def progress(current: str, group: str, index: int, force: bool = False): + t = now() + if not force and t - last_emit[0] < 0.25: + return + last_emit[0] = t + rate = done_bytes / max(t - started, 0.001) + emit(base_event(done=done_bytes, file=current, group=group, index=index, count=len(entries), + seconds_left=(int((total - done_bytes) / rate) if rate > 0 and not same else 0))) + + def repoint(only_whole: bool = True): + for cfg in (configs or []): + try: + repoint_config(cfg, old, new) + except OSError: + pass + + try: + for index, e in enumerate(entries, 1): + if stop(): + raise Stopped() + src, dst = old / e.rel, new / e.rel + progress(e.rel, e.group, index, force=True) + if not src.exists(): + done_bytes += e.size + left[e.group] -= 1 + else: + if same: + dst.parent.mkdir(parents=True, exist_ok=True) + try: + if dst.exists(): + os.remove(dst) + os.replace(src, dst) + except OSError as err: + raise MoveError("io", f"Strata could not move {src.name}.", f"{type(err).__name__}: {err}") from err + done_bytes += e.size + else: + ino = None + try: + st = src.stat() + ino = (st.st_dev, st.st_ino) if st.st_nlink > 1 and st.st_ino else None + except OSError: + pass + if ino and ino in seen_inodes and seen_inodes[ino].exists(): + # the same file under two names (a shared pack): one copy, the second name links to it + try: + dst.parent.mkdir(parents=True, exist_ok=True) + if dst.exists(): + os.remove(dst) + os.link(seen_inodes[ino], dst) + except OSError: + _copy_verified(src, dst, e.size, stop, lambda n: None) + done_bytes += e.size + else: + resumed = False + if dst.exists() and dst.stat().st_size == e.size: + # a crash between the rename and the delete: the copy may be whole; prove it before the original goes + resumed = _sha256_of(dst, stop) == _sha256_of(src, stop) + if resumed: + done_bytes += e.size + else: + def tick(n, group=e.group, rel=e.rel, idx=index): + nonlocal done_bytes + done_bytes += n + progress(rel, group, idx) + before = done_bytes + try: + _copy_verified(src, dst, e.size, stop, tick) + except BaseException: + done_bytes = before + raise + if ino: + seen_inodes[ino] = dst + try: + os.remove(src) + except OSError as err: + raise MoveError("io", f"Strata copied {src.name} but could not remove the old copy.", f"{type(err).__name__}: {err}") from err + _prune(src.parent, old) + files_moved += 1 + left[e.group] -= 1 + if left[e.group] == 0: + moved_groups.append(e.group) + repoint() + repoint() + state.update(state="done", finished=now()) + _clear_state(old, new) + return {"done": True, "stopped": False, "moved": moved_groups, "remaining": [], "bytes_moved": done_bytes, "total_bytes": total, + "files_moved": files_moved, "same_drive": same} + except Stopped: + repoint() + state.update(state="stopped") + if files_moved: + _save_state(old, new, **state) + else: + _clear_state(old, new) + remaining = [g for g, n in left.items() if n > 0] + return {"done": False, "stopped": True, "moved": moved_groups, "remaining": remaining, "bytes_moved": done_bytes, "total_bytes": total, + "files_moved": files_moved, "same_drive": same} + except MoveError as err: + repoint() + state.update(state="failed", error=err.code) + if files_moved: + _save_state(old, new, **state) + else: + _clear_state(old, new) + err.summary = {"moved": moved_groups, "remaining": [g for g, n in left.items() if n > 0], "bytes_moved": done_bytes, "total_bytes": total, + "files_moved": files_moved} + raise + + +def leave(old: Path, new: Path, *, configs: list[Path] | None = None) -> dict: + """'Leave it': give up an unfinished move and keep the old folder as the complete one. + + Only the files the move itself listed are touched. A copy in the new folder whose original is still in the old one is removed; a file + that exists only in the new folder (its original went after a checked copy) is put back in the old folder, so nothing is lost. + ``.part`` files are removed and the run configs point at the old folder again. Returns ``{removed, restored, bytes_removed}``. + """ + old, new = Path(old), Path(new) + st = _read_state(old) or _read_state(new) + rels = [r for r in (st.get("files") or []) if isinstance(r, str) and r and ".." not in Path(r).parts and not Path(r).is_absolute()] + removed = restored = bytes_removed = 0 + for rel in rels: + src, dst = old / rel, new / rel + _quiet_remove(Path(str(dst) + ".part")) + if not dst.exists(): + continue + try: + size = dst.stat().st_size + if src.exists(): + os.remove(dst) + removed += 1 + bytes_removed += size + else: + src.parent.mkdir(parents=True, exist_ok=True) + if same_drive(old, new): + os.replace(dst, src) + else: + _copy_verified(dst, src, size, lambda: False, lambda n: None) + os.remove(dst) + restored += 1 + except OSError as e: + raise MoveError("io", f"Strata could not clean up {dst.name}.", f"{type(e).__name__}: {e}") from e + _prune(dst.parent, new) + for cfg in (configs or []): + try: + repoint_config(cfg, new, old) + except OSError: + pass + _clear_state(old, new) + return {"removed": removed, "restored": restored, "bytes_removed": bytes_removed} diff --git a/tests/terminal/test_flow2_022.py b/tests/terminal/test_flow2_022.py new file mode 100644 index 00000000..fec09536 --- /dev/null +++ b/tests/terminal/test_flow2_022.py @@ -0,0 +1,400 @@ +"""0.2.2 flow walk, second round (phaseA-tests/flow-findings-022.md): what `strata launch` says and does with your own model files, the +plan, the download figure, the long silent step and a tuning result that already exists.""" + +from __future__ import annotations + +import json +import os +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from strata_cli.launch import settings as S +from strata_cli.launch.catalog import Catalog +from strata_cli.launch.runner import LaunchError, Runner +from tests.terminal.launch_support import HW_12, Home, run_cli +from tests.terminal.test_own_files import IQ3XXS, Q2, gguf_bytes + + +class Base(unittest.TestCase): + def setUp(self): + self.home = Home().__enter__() + self.addCleanup(self.home.__exit__, None, None, None) + p = mock.patch.object(Catalog, "hardware", lambda self, fresh=False: dict(HW_12, disk_free_gb=500.0)) + p.start() + self.addCleanup(p.stop) + self.tmp = tempfile.TemporaryDirectory(prefix="strata-flow2-") + self.addCleanup(self.tmp.cleanup) + self.base = Path(self.tmp.name) + + def files(self, folder: Path, names: list[str], kind: str) -> Path: + folder.mkdir(parents=True, exist_ok=True) + for n in names: + (folder / n).write_bytes(gguf_bytes([kind])) + return folder + + def runner(self, **kw) -> Runner: + return Runner(S.LaunchSettings(**kw), catalog=Catalog(hardware=HW_12)) + + +class MissingOwnFiles(Base): + """Finding 2: a --model-path that is not there, or holds no model, is said in plain words before anything starts.""" + + def test_a_folder_that_does_not_exist_is_named_and_nothing_is_promised(self): + missing = self.base / "models" + code, out, err = run_cli(["launch", "--plan", "--model-path", str(missing)]) + self.assertEqual(code, 2) + self.assertIn(f"This folder does not exist: {missing}", err) + self.assertNotIn("Qwen", err) + self.assertNotIn("continues where it stopped", err) + self.assertNotIn("could not be installed", err) + + def test_a_missing_file_says_file(self): + code, out, err = run_cli(["launch", "--plan", "--model-path", str(self.base / "x-00001-of-00002.gguf")]) + self.assertEqual(code, 2) + self.assertIn("This file does not exist", err) + + def test_an_empty_folder_says_there_are_no_gguf_files(self): + empty = self.base / "empty" + empty.mkdir() + code, out, err = run_cli(["launch", "--plan", "--model", "q2_0", "--model-path", str(empty)]) + self.assertEqual(code, 2) + self.assertIn("no .gguf model files", err) + self.assertIn("...-00001-of-00002.gguf", err) + + def test_machine_output_carries_the_same_words(self): + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model-path", str(self.base / "gone")]) + self.assertEqual(code, 2) + self.assertIn("This folder does not exist", json.loads(out)["error"]["message"]) + + def test_the_engine_is_not_touched_for_a_wrong_path(self): + r = self.runner(model_path=str(self.base / "gone")) + with mock.patch.object(Runner, "ensure_engine", side_effect=AssertionError("engine step must not start")): + with self.assertRaises(LaunchError) as ctx: + r.run() + self.assertEqual(ctx.exception.code, 2) + self.assertIn("does not exist", ctx.exception.text) + + def test_the_failure_hint_of_own_files_promises_no_download(self): + r = self.runner(model_path=str(self.files(self.base / "m", Q2, "Q2_0")), family="qwen", model="Q2_0") + proc = mock.Mock() + proc.stdout = iter(["=== Step 5: Getting the model files ===", "[X] missing /m/x.gguf"]) + proc.wait.return_value = 1 + with mock.patch.object(Runner, "_spawn", return_value=proc), mock.patch.object(Runner, "adopt_prepared_files", return_value=None): + with self.assertRaises(LaunchError) as ctx: + r.ensure_model() + self.assertNotIn("download", ctx.exception.next) + self.assertIn("finished steps are skipped", ctx.exception.next) + + def test_the_screens_say_the_same(self): + from strata_control import models + text, nxt = models.own_path_problem(str(self.base / "nope")) + self.assertIn("This folder does not exist", text) + self.assertIn("Nothing was downloaded", nxt) + self.assertIsNone(models.own_path_problem(str(self.files(self.base / "ok", IQ3XXS, "IQ3_XXS")))) + + def test_a_folder_one_level_above_the_files_is_not_called_empty(self): + self.files(self.base / "repo" / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + from strata_control import models + self.assertIsNone(models.own_path_problem(str(self.base / "repo"))) + + +class LinkedShards(Base): + """Finding 3: shards that are links are accepted with no --model, as with --model, and a problem is said once.""" + + def links(self, names: list[str], real: bool = True) -> Path: + blobs = self.base / "blobs" + snap = self.base / "snap" + blobs.mkdir(exist_ok=True) + snap.mkdir(exist_ok=True) + for i, n in enumerate(names): + target = blobs / f"sha{i}" + if real: + target.write_bytes(gguf_bytes(["Q2_0"])) + try: + os.symlink(target, snap / n) + except (OSError, NotImplementedError): + self.skipTest("this account cannot create symbolic links") + return snap + + def test_linked_shards_without_a_model_name_are_used(self): + snap = self.links(Q2) + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model-path", str(snap)]) + self.assertEqual(code, 0, err or out) + s = json.loads(out)["plan"]["settings"] + self.assertEqual((s["family"], s["model"]), ("qwen", "Q2_0")) + self.assertEqual(Path(s["model_path"]), snap) # the link names stay (the shard names are what setup reads) + + def test_linked_shards_with_the_model_named_give_the_same_folder(self): + snap = self.links(Q2) + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "q2_0", "--model-path", str(snap)]) + self.assertEqual(code, 0, err or out) + self.assertEqual(Path(json.loads(out)["plan"]["settings"]["model_path"]), snap) + + def test_links_to_nothing_are_one_sentence_not_one_per_file(self): + snap = self.links(Q2, real=False) + code, out, err = run_cli(["launch", "--plan", "--model-path", str(snap)]) + self.assertEqual(code, 5) + self.assertEqual(err.count("shortcut"), 1, err) + self.assertIn(Q2[0], err) + self.assertIn(Q2[1], err) + + def test_the_same_problem_for_many_files_is_said_once(self): + from strata_control import models + issues = [f"m-0000{i}-of-00005.gguf: GGUF metadata is truncated" for i in range(1, 6)] + ["incomplete_or_invalid_shard_set"] + words = models.problem_words(issues) + self.assertEqual(words.count("the file is cut short"), 1) + self.assertIn("m-00001-of-00005.gguf, m-00002-of-00005.gguf and 3 more files", words) + self.assertEqual(models.problem_words(["a.gguf: GGUF metadata is truncated", "b.gguf: GGUF metadata is truncated"]), + "a.gguf and b.gguf: the file is cut short (a download or copy that did not finish)") + self.assertEqual(models.problem_words(["multiple_model_groups", "unrecognized_or_unsupported_model_variant"]), + "the folder holds more than one model") + many = [f"unsupported_or_missing_architecture", "incomplete_or_invalid_shard_set", "multiple_model_groups", + "unsupported_or_incomplete_tokenizer_metadata", "missing_or_unexpected_expert_quantization"] + self.assertTrue(models.problem_words(many).endswith("and 2 more problems")) + + + +class PlanWords(Base): + """Findings 1 and 7: --plan shows the real model, the picture setting, a copyable line, and what would be downloaded.""" + + def plan_text(self, *args): + code, out, err = run_cli(["launch", "--plan", *args]) + self.assertEqual(code, 0, err or out) + return out + + def test_own_files_show_the_model_they_are(self): + folder = self.files(self.base / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + out = self.plan_text("--model-path", str(folder)) + self.assertIn("Plan for 'IQ3_XXS", out) + self.assertNotIn("model default", out) + self.assertNotIn("None", out) + self.assertIn("Qwen3.8-Flash-Next IQ3_XXS", out) + self.assertIn(f"your files in {folder}", out) + self.assertRegex(out, r"pictures (on|off)") + self.assertIn("--model iq3_xxs", out.split("same as")[1]) # the copyable line names the model too + self.assertIn(f'--model-path "{folder}"', out.split("same as")[1]) + + def test_a_named_catalog_model_shows_its_size_and_the_download(self): + out = self.plan_text("--model", "q2_0") + self.assertIn("Qwen3.8-Flash-Next Q2_0, 66 GB", out) + self.assertRegex(out, r"download\s+About 7\d\.\d GB to download: the model \(66\.4 GB\), the draft layer \(5\.2 GB\)") + self.assertIn("The engine for your graphics card is downloaded first", out) + + def test_nothing_is_downloaded_when_everything_is_here(self): + folder = self.files(self.base / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + data = self.base / "Strata" + (data / "models" / "x").mkdir(parents=True) + (data / "mtp" / "rt").mkdir(parents=True) + (data / "mtp" / "rt" / "experts.bin").write_bytes(b"x") + (data / "models" / "mmproj-Qwen3.8-Flash-Next-BF16.gguf").write_bytes(b"x") + # the files sit under /models/: the draft layer and the picture reader are found beside them + moved = data / "models" / "iq3_xxs" + folder.rename(moved) + out = self.plan_text("--model-path", str(moved)) + self.assertIn("download Nothing to download: your model files are used where they are.", out) + + def test_own_files_with_no_draft_layer_say_what_is_fetched(self): + folder = self.files(self.base / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + with mock.patch.object(Runner, "existing_data_dir", return_value=None), mock.patch.object(Catalog, "data_dir", return_value=self.base / "emptydata"): + out = self.plan_text("--model-path", str(folder), "--vision", "off") + self.assertIn("About 5.2 GB to download: the draft layer (5.2 GB). Your model files are used where they are.", out) + + def test_a_model_whose_files_are_all_on_disk_does_not_list_a_zero_download(self): + from strata_cli.launch.modelstate import ModelState, Part + data = self.base / "d" + (data / "mtp" / "rt").mkdir(parents=True) + (data / "mtp" / "rt" / "experts.bin").write_bytes(b"x") + whole = ModelState(installed=False, parts=[Part("weights", "the model", 0.0)], on_disk_gb=66.4, total_gb=66.4) + with mock.patch.object(Runner, "model_state", return_value=whole): + out = self.plan_text("--model", "q2_0", "--data-dir", str(data), "--vision", "off") + self.assertIn("download Nothing to download: the model is already on this computer.", out) + out = self.plan_text("--model", "q2_0", "--data-dir", str(self.base / "other"), "--vision", "off") + self.assertIn("About 5.2 GB to download: the draft layer (5.2 GB). 66 GB of the model is already in its folder.", out) + self.assertNotIn("0.0 GB", out) + + def test_json_plan_carries_the_numbers(self): + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "q2_0", "--mtp", "off", "--vision", "off"]) + self.assertEqual(code, 0, err) + plan = json.loads(out)["plan"] + self.assertEqual(plan["model"]["title"], "Qwen3.8-Flash-Next Q2_0") + self.assertEqual(plan["model"]["model_gb"], 66.4) + self.assertEqual(plan["download"]["gb"], 66.4) + self.assertEqual([p["kind"] for p in plan["download"]["parts"]], ["weights"]) + + + +class DownloadTotal(Base): + """Finding 4: the figure counts every shard (and the picture reader), in the folder the setup is really given.""" + + def run_lines(self, runner: Runner, lines: list[str]) -> list[str]: + seen: list[str] = [] + runner.emit_cb = lambda ev: seen.append(ev.text) + proc = mock.Mock() + proc.stdout = iter(lines) + proc.wait.return_value = 1 # stop after the lines: the failure path is not what is looked at + with mock.patch.object(Runner, "_spawn", return_value=proc), mock.patch.object(Runner, "adopt_prepared_files", return_value=None): + with self.assertRaises(LaunchError): + runner.ensure_model() + return seen + + def test_the_total_is_the_whole_model_in_the_chosen_data_folder(self): + data = self.base / "mydata" + folder = data / "models" / "Q2_0" + folder.mkdir(parents=True) + first = folder / (Q2[0] + ".part") + first.write_bytes(bytes(100_000_000)) + r = self.runner(family="qwen", model="Q2_0", data_dir=str(data), vision="on", context=32768) + job = r.progress_job() + self.assertEqual(Path(job["folder"]), folder) + self.assertEqual(len(job["files"]), 3) # two shards and the picture reader + seen = self.run_lines(r, ["=== Step 5: Getting the model files ===", f"{Q2[0]}: 0.10 / 37.60 GB (0%)"]) + text = [x for x in seen if "GB" in x] + self.assertTrue(text, seen) + self.assertIn("of 67.3 GB", text[-1]) # 66.4 GB of shards + 0.9 GB picture reader + self.assertNotIn("37.6", " ".join(text)) + + def test_the_default_data_folder_is_used_when_none_was_chosen(self): + r = self.runner(family="qwen", model="Q2_0", vision="off", context=32768) + self.assertEqual(Path(r.progress_job()["folder"]).parts[-2:], ("models", "Q2_0")) + self.assertEqual(len(r.progress_job()["files"]), 2) + + + +class QuietStep(Base): + """Finding 5: setup step 6 (packing) prints nothing for minutes: the person sees the plain sentence and a 'still working' line.""" + + def slow(self, steps): + import time + for delay, line in steps: + time.sleep(delay) + yield line + "\n" + + def run_steps(self, steps, heartbeat=0.3): + r = self.runner(family="qwen", model="Q2_0", vision="off", context=32768) + r.HEARTBEAT_S = heartbeat + seen = [] + r.emit_cb = lambda ev: seen.append(ev.text) + proc = mock.Mock() + proc.stdout = self.slow(steps) + proc.wait.return_value = 1 + with mock.patch.object(Runner, "_spawn", return_value=proc), mock.patch.object(Runner, "adopt_prepared_files", return_value=None): + with self.assertRaises(LaunchError): + r.ensure_model() + return seen + + def test_a_silent_pack_step_says_what_it_does_and_that_it_is_still_going(self): + seen = self.run_steps([(0, "=== Step 5: Getting the model files ==="), (0, "all model files present"), + (0, "=== Step 6: Preparing the model for Strata ==="), + (0, "> python tools/iq_pack.py --gguf x --out y --experts-bin"), (1.6, "[X] stopped for the test")]) + pack = [x for x in seen if x.startswith("Packing the experts into one file")] + self.assertTrue(pack, seen) + self.assertEqual(pack[0], "Packing the experts into one file for low-memory mode (one time)") + beats = [x for x in pack if "still working" in x] + self.assertGreaterEqual(len(beats), 2, seen) # a line every interval of silence + self.assertNotIn("Setup step 6", " ".join(seen)) + + def test_no_heartbeat_while_lines_keep_coming(self): + seen = self.run_steps([(0, "=== Step 6: Preparing the model for Strata ==="), (0, "> python tools/iq_pack.py --gguf x --out y --experts-bin")] + + [(0.1, f" layer {i}") for i in range(5)] + [(0, "[X] stopped")], heartbeat=2.0) + self.assertFalse([x for x in seen if "still working" in x]) + + def test_the_plain_printer_shows_each_heartbeat(self): + import io + from strata_cli.launch import cmd + from strata_cli.launch.runner import Event + buf = io.StringIO() + with mock.patch.object(cmd.sys, "stdout", buf): + emit = cmd._printer() + emit(Event("model", "Packing (still working, 30 s so far)")) + emit(Event("model", "Packing (still working, 60 s so far)")) + emit(Event("model", "Packing (still working, 60 s so far)")) + self.assertEqual(buf.getvalue().count("still working"), 2) + + + +class StoredTuning(Base): + """Finding 6: a run by flags (no saved preset) reuses the tuning result stored for the same model, choices and computer.""" + + IDENT = {"hardware": {"hard": {"gpus": ["RTX 5070"], "cpu": "test", "logical": 16, "ram_gib": 64}, "soft": {}}, + "engine": {"backend": "cuda"}, "model": {"sha256_shard1": "abc"}} + + def setUp(self): + super().setUp() + from strata_control import presets + self.presets = presets + self.cfg_path = self.base / "launch.json" + self.cfg = {"args": ["--native", "x/model-00001-of-00002.gguf", "--max-context", "32768", "--kv", "int8"], "model_name": "qwen"} + self.cfg_path.write_text(json.dumps(self.cfg), encoding="utf-8") + self.ident = json.loads(json.dumps(self.IDENT)) + p = mock.patch.object(presets, "current_identity", lambda cfg, **kw: self.ident) + p.start() + self.addCleanup(p.stop) + + def store(self): + return self.presets.create({"settings": {"args": {}, "env": {}, "per_request": {}}, "outcome": "improved"}, + choices=self.presets.choices_from_config(self.cfg), identity=self.ident, name="Q2 32K - Full speed") + + def runner_for_tune(self, retune=False): + r = self.runner(family="qwen", model="Q2_0", tune="quick") + r.retune = retune + r.config_path = self.cfg_path + return r + + def run_tune(self, r): + seen = [] + r.emit_cb = lambda ev: seen.append(ev.text) + with mock.patch.object(Runner, "_spawn", side_effect=RuntimeError("the tuner started")) as spawn: + try: + r.tune() + started = False + except RuntimeError: + started = True + return seen, started + + def test_nothing_stored_means_it_is_measured(self): + seen, started = self.run_tune(self.runner_for_tune()) + self.assertTrue(started) + + def test_a_stored_result_is_used_and_said(self): + saved = self.store() + r = self.runner_for_tune() + seen, started = self.run_tune(r) + self.assertFalse(started) + text = seen[-1] + self.assertIn("already tuned for this computer", text) + self.assertIn("Q2 32K - Full speed", text) + self.assertIn("--retune", text) + self.assertEqual(r.s.tuned_preset, saved["id"]) + self.assertTrue(r.s.is_tuned) + + def test_retune_measures_again(self): + self.store() + seen, started = self.run_tune(self.runner_for_tune(retune=True)) + self.assertTrue(started) + + def test_another_context_is_another_result(self): + self.store() + self.cfg["args"][3] = "65536" + self.cfg_path.write_text(json.dumps(self.cfg), encoding="utf-8") + seen, started = self.run_tune(self.runner_for_tune()) + self.assertTrue(started) + + def test_a_changed_graphics_card_is_measured_again(self): + self.store() + self.ident["hardware"]["hard"]["gpus"] = ["RTX 4090"] + seen, started = self.run_tune(self.runner_for_tune()) + self.assertTrue(started) + + def test_the_flag_asks_for_a_new_measurement_and_implies_quick(self): + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "q2_0", "--retune"]) + self.assertEqual(code, 0, err) + self.assertEqual(json.loads(out)["plan"]["settings"]["tune"], "quick") + code, out, err = run_cli(["launch", "--help"]) + self.assertIn("--retune", out) + + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/terminal/test_launch.py b/tests/terminal/test_launch.py index a6255e8d..18fd91bd 100644 --- a/tests/terminal/test_launch.py +++ b/tests/terminal/test_launch.py @@ -795,10 +795,16 @@ class FlagsCommand(unittest.TestCase): self.assertEqual(p["settings"]["api_key"], "set") def test_model_path_is_used_instead_of_a_catalog_model(self): - p = self.plan("--model-path", "/data/models/IQ3_XXS") - s = p["settings"] - self.assertEqual(s["model_path"], str(Path("/data/models/IQ3_XXS"))) - self.assertIsNone(s["model"]) + import tempfile + from tests.terminal.test_own_files import IQ3XXS, gguf_bytes + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) / "IQ3_XXS" + folder.mkdir() + for n in IQ3XXS: + (folder / n).write_bytes(gguf_bytes(["IQ3_XXS"])) + s = self.plan("--model-path", str(folder))["settings"] + self.assertEqual(s["model_path"], str(folder)) + self.assertEqual((s["family"], s["model"]), ("qwen", "IQ3_XXS")) # the files say which model they are def test_no_choices_and_no_terminal_does_not_start_anything(self): with mock.patch.dict(os.environ, {"CI": "1"}), mock.patch.object(Runner, "run", side_effect=AssertionError("must not run")): diff --git a/tests/terminal/test_launch_tui.py b/tests/terminal/test_launch_tui.py index 003fb305..e9b0a6f5 100644 --- a/tests/terminal/test_launch_tui.py +++ b/tests/terminal/test_launch_tui.py @@ -259,7 +259,7 @@ class ModelStep(Base): async def case(app, pilot, ctx): await press(pilot, "enter", "o") self.assertIn("Type or paste the folder", text_of(app)) - with mock.patch("strata_control.models.plan_import", return_value=plan) as pi: + with mock.patch("strata_control.models.plan_import", return_value=plan) as pi, mock.patch("strata_control.models.own_path_problem", return_value=None): await typed(pilot, "/data/models/IQ3_XXS") await press(pilot, "enter") self.assertEqual(ctx.settings.model_path, os.path.abspath("/data/models/IQ3_XXS")) @@ -274,7 +274,7 @@ class ModelStep(Base): async def case(app, pilot, ctx): await press(pilot, "enter", "o") - with mock.patch("strata_control.models.plan_import", return_value=plan): + with mock.patch("strata_control.models.plan_import", return_value=plan), mock.patch("strata_control.models.own_path_problem", return_value=None): await typed(pilot, "/x") await press(pilot, "enter") t = flat(app) @@ -283,6 +283,17 @@ class ModelStep(Base): self.assertIsNone(ctx.settings.model_path) self.run_app(case) + def test_own_files_folder_that_is_not_there_is_named(self): + async def case(app, pilot, ctx): + await press(pilot, "enter", "o") + await typed(pilot, "/no/such/folder") + await press(pilot, "enter") + t = flat(app) + self.assertIn("does not exist", t) + self.assertIn("Nothing was downloaded", t) + self.assertIsNone(ctx.settings.model_path) + self.run_app(case) + def test_own_files_path_from_the_start_screen(self): async def case(app, pilot, ctx): await press(pilot, "down", "enter") diff --git a/tests/terminal/test_models_move.py b/tests/terminal/test_models_move.py new file mode 100644 index 00000000..b11fec0b --- /dev/null +++ b/tests/terminal/test_models_move.py @@ -0,0 +1,400 @@ +"""Moving the models to another folder (strata models move): same drive, another drive, stop, a failed check, disk full, resume.""" +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from strata_control import models_move as mm + + +def sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +class MoveCase(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="strata-move-") + self.addCleanup(self.tmp.cleanup) + self.base = Path(self.tmp.name) + self.old = self.base / "old" + self.new = self.base / "new" + self.files = { + "models/gyro-s/a.gguf": b"A" * 300_000, + "models/gyro-s/b.gguf": b"B" * 200_000, + "packs/gyro-s/dense.bin": b"D" * 100_000, + "models/coder/c.gguf": b"C" * 150_000, + "mtp/rt/experts.bin": b"M" * 50_000, + } + for rel, data in self.files.items(): + f = self.old / rel + f.parent.mkdir(parents=True, exist_ok=True) + f.write_bytes(data) + # a finished download carries the pinned checksum in its mark + (self.old / "models/gyro-s/a.gguf.done").write_text(f"done sha256 {sha(self.files['models/gyro-s/a.gguf'])}\n") + (self.old / "notes.txt").write_text("not a model file") # Strata moves its own folders only + self.install = self.base / "install" + self.install.mkdir() + self.config = self.install / "strata-gyro-s.json" + self.config.write_text(json.dumps({"args": ["--native", str(self.old / "models/gyro-s/a.gguf"), "--pack", str(self.old / "packs/gyro-s")], + "mtp": str(self.old / "mtp/rt")})) + self.total = sum(len(v) for v in self.files.values()) + + def tree(self, root: Path) -> set[str]: + return {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file() and p.name != mm.STATE_FILE} + + def copy_mode(self): + """Another drive: the files are copied, whatever this machine's volumes are.""" + return mock.patch.object(mm, "same_drive", return_value=False) + + def break_after(self, n): + """A copy that works n times, then fails: a move cut off part way.""" + real, calls = mm._copy_verified, [0] + + def flaky(*args, **kw): + calls[0] += 1 + if calls[0] > n: + raise mm.MoveError("io", "cut off") + return real(*args, **kw) + return mock.patch.object(mm, "_copy_verified", side_effect=flaky) + + def cut_off(self, n=1): + with self.copy_mode(), self.break_after(n): + with self.assertRaises(mm.MoveError): + self.run_move() + + def run_move(self, **kw): + events = [] + summary = mm.move(self.old, self.new, on_progress=events.append, configs=[self.config], **kw) + return summary, events + + +class PlanTests(MoveCase): + def test_plan_numbers_and_choices(self): + with self.copy_mode(): + p = mm.plan(self.old, self.new, free=lambda _p: 10**9) + self.assertTrue(p["ok"]) + self.assertGreaterEqual(p["models_bytes"], self.total) + self.assertGreater(p["needed_bytes"], p["models_bytes"]) # the 5 % margin + self.assertTrue(p["choices"]["move"]["possible"]) + self.assertEqual({m["name"] for m in p["models"]}, {"gyro-s", "coder", "mtp"}) + + def test_not_enough_room_switches_move_off(self): + with self.copy_mode(): + p = mm.plan(self.old, self.new, free=lambda _p: 1000) + self.assertTrue(p["ok"]) + self.assertFalse(p["choices"]["move"]["possible"]) + self.assertIn("free", p["choices"]["move"]["reason"]) + self.assertTrue(p["choices"]["keep"]["possible"] and p["choices"]["empty"]["possible"]) + + def test_same_drive_needs_no_room(self): + p = mm.plan(self.old, self.new, free=lambda _p: 0) + self.assertTrue(p["same_drive"]) + self.assertTrue(p["choices"]["move"]["possible"]) + + def test_inside_and_same_are_refused(self): + self.assertEqual(mm.plan(self.old, self.old / "sub")["issue"]["code"], "inside") + self.assertEqual(mm.plan(self.old / "sub", self.old)["issue"]["code"], "inside") + self.assertEqual(mm.plan(self.old, self.old)["issue"]["code"], "same") + + def test_a_folder_that_cannot_be_written_is_refused(self): + with mock.patch.object(mm, "_write_test", return_value="EPERM: operation not permitted, mkdir 'x'"): + p = mm.plan(self.old, self.new) + self.assertEqual(p["issue"]["code"], "not_writable") + self.assertIn("EPERM", p["issue"]["details"]) + + def test_nothing_is_changed_by_a_plan(self): + before = self.tree(self.old) + mm.plan(self.old, self.new) + self.assertEqual(self.tree(self.old), before) + + +class MoveTests(MoveCase): + def check_whole(self): + self.assertEqual({k for k in self.tree(self.new) if not k.endswith(".done")}, set(self.files)) + for rel, data in self.files.items(): + self.assertEqual((self.new / rel).read_bytes(), data) + self.assertEqual(self.tree(self.old), {"notes.txt"}) # only what is not Strata's own is left + cfg = json.loads(self.config.read_text()) + self.assertEqual(Path(cfg["args"][1]), self.new / "models/gyro-s/a.gguf") + self.assertEqual(Path(cfg["mtp"]), self.new / "mtp/rt") + self.assertFalse((self.new / mm.STATE_FILE).exists()) + + def test_same_drive_is_a_rename(self): + with mock.patch.object(shutil, "copyfileobj", side_effect=AssertionError("copied")), mock.patch.object(mm, "_copy_verified", side_effect=AssertionError("copied")): + summary, _events = self.run_move() + self.assertTrue(summary["done"] and summary["same_drive"]) + self.check_whole() + + def test_another_drive_copies_checks_and_removes(self): + with self.copy_mode(): + summary, events = self.run_move() + self.assertTrue(summary["done"] and not summary["same_drive"]) + self.assertEqual(summary["files_moved"], len(self.files) + 1) # + the .done mark + self.check_whole() + self.assertTrue(events and events[-1]["done"] <= self.total + 100) + self.assertEqual(events[0]["event"], "progress") + + def test_stop_keeps_what_moved_and_removes_the_partial_copy(self): + calls = {"n": 0} + + def stop(): + calls["n"] += 1 + return calls["n"] > 6 # a few chunks into the second file or so + with self.copy_mode(): + summary, _events = self.run_move(cancelled=stop) + self.assertTrue(summary["stopped"] and not summary["done"]) + self.assertEqual([p for p in self.new.rglob("*.part")], []) + # every file is in exactly one place, nothing is lost + for rel, data in self.files.items(): + places = [r for r in (self.old, self.new) if (r / rel).exists()] + self.assertEqual(len(places), 1, rel) + self.assertEqual((places[0] / rel).read_bytes(), data) + self.assertTrue(summary["remaining"]) + # a model that moved whole now points at the new folder; one that did not stays where it is + cfg = json.loads(self.config.read_text()) + for value in (cfg["args"][1], cfg["args"][3], cfg["mtp"]): + self.assertTrue(Path(value).exists(), value) + + def test_stop_before_anything_leaves_the_old_folder_as_it_was(self): + with self.copy_mode(): + summary, _ = self.run_move(cancelled=lambda: True) + self.assertTrue(summary["stopped"]) + self.assertEqual(summary["files_moved"], 0) + self.assertEqual({k for k in self.tree(self.old) if not k.endswith(".done")}, set(self.files) | {"notes.txt"}) + self.assertFalse((self.new / mm.STATE_FILE).exists()) + + def test_a_copy_that_does_not_match_is_never_trusted(self): + real = mm._sha256_of + calls = {"n": 0} + + def lies(path, stop, tick=None): + calls["n"] += 1 + return "0" * 64 if str(path).endswith(".part") and calls["n"] == 1 else real(path, stop, tick) + with self.copy_mode(), mock.patch.object(mm, "_sha256_of", side_effect=lies): + with self.assertRaises(mm.MoveError) as caught: + self.run_move() + self.assertEqual(caught.exception.code, "verify") + self.assertEqual(list(self.new.rglob("*.part")), []) + self.assertEqual({k for k in self.tree(self.old) if not k.endswith(".done")}, set(self.files) | {"notes.txt"}) # the original is untouched + + def test_a_file_that_differs_from_its_pinned_checksum_is_not_moved(self): + (self.old / "models/gyro-s/a.gguf.done").write_text("done sha256 " + "1" * 64) + with self.copy_mode(): + with self.assertRaises(mm.MoveError) as caught: + self.run_move() + self.assertEqual(caught.exception.code, "verify") + self.assertTrue((self.old / "models/gyro-s/a.gguf").exists()) + self.assertFalse((self.new / "models/gyro-s/a.gguf").exists()) + + def test_disk_full_stops_at_once_and_loses_nothing(self): + real = mm._copy_verified + seen = {"n": 0} + + def full(src, dst, size, stop, tick): + seen["n"] += 1 + if seen["n"] == 3: + part = dst.with_name(dst.name + ".part") + part.parent.mkdir(parents=True, exist_ok=True) + part.write_bytes(b"half") + try: + raise OSError(28, "No space left on device", str(dst)) + except OSError as e: + mm._quiet_remove(part) + raise mm.MoveError("disk_full", "The drive ran out of space.", str(e)) from e + return real(src, dst, size, stop, tick) + with self.copy_mode(), mock.patch.object(mm, "_copy_verified", side_effect=full): + with self.assertRaises(mm.MoveError) as caught: + self.run_move() + self.assertEqual(caught.exception.code, "disk_full") + self.assertEqual(list(self.new.rglob("*.part")), []) + for rel, data in self.files.items(): + places = [r for r in (self.old, self.new) if (r / rel).exists()] + self.assertEqual(len(places), 1, rel) + self.assertIn("remaining", caught.exception.summary) + + def test_a_real_disk_full_error_is_named(self): + with mock.patch("builtins.open", side_effect=OSError(28, "No space left on device", "x")): + with self.assertRaises(mm.MoveError) as caught: + mm._copy_verified(self.old / "models/coder/c.gguf", self.new / "x.gguf", 1, lambda: False, lambda n: None) + self.assertEqual(caught.exception.code, "disk_full") + + def test_a_crash_leaves_a_part_and_the_next_run_finishes(self): + stale = self.new / "models/gyro-s/a.gguf.part" + stale.parent.mkdir(parents=True) + stale.write_bytes(b"cut off") + # a file that was copied and renamed, but whose original was not removed yet + done = self.new / "models/coder/c.gguf" + done.parent.mkdir(parents=True) + done.write_bytes(self.files["models/coder/c.gguf"]) + with self.copy_mode(): + summary, _ = self.run_move() + self.assertTrue(summary["done"]) + self.check_whole() + + def test_an_interrupted_move_is_remembered(self): + self.cut_off(1) + st = mm.interrupted(self.old) # the old folder is still the data folder: it holds the pointer + self.assertEqual(st["to"], str(self.new)) + self.assertEqual(st["state"], "failed") + self.assertEqual(mm.interrupted(self.base / "elsewhere"), None) + mm._write_state(self.old, state="running", pid=os.getpid() + 7, token=None, **{"from": str(self.old), "to": str(self.new)}) + self.assertEqual(mm.interrupted(self.old)["state"], "running") + + def test_a_move_that_is_running_now_is_not_interrupted(self): + from strata_control import procs + mm._write_state(self.old, state="running", pid=os.getpid() + 7, token="t", **{"from": str(self.old), "to": str(self.new)}) + with mock.patch.object(procs, "start_token", return_value="t"): + self.assertIsNone(mm.interrupted(self.old)) + with mock.patch.object(procs, "start_token", return_value=None): + self.assertIsNotNone(mm.interrupted(self.old)) + + def test_nothing_moved_leaves_nothing_to_ask_about(self): + self.cut_off(0) + self.assertIsNone(mm.interrupted(self.old)) + self.assertFalse((self.new / mm.STATE_FILE).exists()) + + def test_finish_resumes_the_move(self): + self.cut_off(1) + st = mm.interrupted(self.old) + with self.copy_mode(): + summary = mm.move(Path(st["from"]), Path(st["to"]), configs=[self.config]) + self.assertTrue(summary["done"]) + self.check_whole() + self.assertIsNone(mm.interrupted(self.old)) + self.assertFalse((self.old / mm.STATE_FILE).exists() or (self.new / mm.STATE_FILE).exists()) + + def test_leave_keeps_the_old_folder_complete(self): + self.cut_off(1) + (self.new / "models/stray.gguf.part").write_bytes(b"x") # not listed by the move, but a .part of ours is + (self.new / "models/gyro-s").mkdir(parents=True, exist_ok=True) + (self.new / "models/gyro-s/a.gguf.part").write_bytes(b"cut") + theirs = self.new / "models/own/mine.gguf" # a file of the person's, not part of the move + theirs.parent.mkdir(parents=True) + theirs.write_bytes(b"mine") + st = mm.interrupted(self.old) + with self.copy_mode(): + result = mm.leave(Path(st["from"]), Path(st["to"]), configs=[self.config]) + self.assertGreaterEqual(result["restored"] + result["removed"], 1) + for rel, data in self.files.items(): + self.assertEqual((self.old / rel).read_bytes(), data, rel) + self.assertFalse((self.new / rel).exists(), rel) + self.assertEqual(list(self.new.rglob("*.part")), [(self.new / "models/stray.gguf.part")]) + self.assertTrue(theirs.exists()) + self.assertIsNone(mm.interrupted(self.old)) + self.assertFalse((self.new / mm.STATE_FILE).exists()) + cfg = json.loads(self.config.read_text()) + self.assertTrue(all(str(self.new) not in str(v) for v in cfg.values())) + self.assertIn(str(self.old / "models/gyro-s/a.gguf"), cfg["args"]) + + def test_leave_after_a_crash_removes_the_duplicate(self): + self.cut_off(1) + dup = self.new / "models/coder/c.gguf" # copied and renamed, original not yet removed + dup.parent.mkdir(parents=True, exist_ok=True) + dup.write_bytes(self.files["models/coder/c.gguf"]) + mm.leave(self.old, self.new) + self.assertFalse(dup.exists()) + self.assertTrue((self.old / "models/coder/c.gguf").exists()) + + def test_configs_are_rewritten_only_for_files_that_are_there(self): + self.config.write_text(json.dumps({"args": ["--native", str(self.old / "models/gone.gguf")]})) + with self.copy_mode(): + self.run_move() + self.assertEqual(json.loads(self.config.read_text())["args"][1], str(self.old / "models/gone.gguf")) + + @unittest.skipUnless(os.environ.get("STRATA_TEST_OTHER_VOLUME"), "set STRATA_TEST_OTHER_VOLUME to a folder on another volume (e.g. a subst or USB drive)") + def test_a_real_second_volume(self): + other = Path(os.environ["STRATA_TEST_OTHER_VOLUME"]) / f"strata-move-{os.getpid()}" + self.addCleanup(shutil.rmtree, other, True) + self.new = other + summary, _ = self.run_move() + self.assertTrue(summary["done"]) + self.check_whole() + + +class CommandLineTests(MoveCase): + def test_json_plan_and_run(self): + from strata_cli import cli + import contextlib + import io + out = io.StringIO() + with contextlib.redirect_stdout(out), self.copy_mode(): + code = cli.main(["models", "move", str(self.new), "--from", str(self.old), "--plan", "--output", "json"]) + self.assertEqual(code, 0) + self.assertTrue(json.loads(out.getvalue())["plan"]["choices"]["move"]["possible"]) + out = io.StringIO() + with contextlib.redirect_stdout(out), self.copy_mode(): + code = cli.main(["models", "move", str(self.new), "--from", str(self.old), "--install-dir", str(self.install), "--output", "jsonl"]) + self.assertEqual(code, 0, out.getvalue()) + lines = [json.loads(line) for line in out.getvalue().splitlines() if line.startswith("{")] + self.assertEqual(lines[-1]["event"], "result") + self.assertTrue(lines[-1]["done"]) + self.assertTrue((self.new / "models/coder/c.gguf").exists()) + + def run_cli(self, *argv): + from strata_cli import cli + from strata_control import discovery + import contextlib + import io + out = io.StringIO() + with contextlib.redirect_stdout(out), self.copy_mode(), mock.patch.object(discovery, "data_dir", return_value=(self.old, "settings")): + code = cli.main(["models", "move", *argv]) + return code, out.getvalue() + + def test_status_resume_and_leave(self): + code, text = self.run_cli("--status", "--output", "json") + self.assertEqual((code, json.loads(text)["interrupted"]), (0, None)) + self.assertEqual(self.run_cli("--resume", "--output", "json")[0], 5) + self.cut_off(1) + code, text = self.run_cli("--status", "--output", "json") + self.assertEqual(json.loads(text)["interrupted"]["to"], str(self.new)) + self.assertIn("--resume", self.run_cli("--status")[1]) + code, text = self.run_cli("--leave", "--install-dir", str(self.install), "--output", "json") + self.assertEqual(code, 0, text) + self.assertTrue((self.old / "models/coder/c.gguf").exists()) + self.cut_off(1) + code, text = self.run_cli("--resume", "--install-dir", str(self.install), "--output", "jsonl") + self.assertEqual(code, 0, text) + self.assertTrue([json.loads(l) for l in text.splitlines() if l.startswith("{")][-1]["done"]) + self.assertTrue((self.new / "models/coder/c.gguf").exists()) + self.assertFalse((self.old / "models/coder/c.gguf").exists()) + + def test_launch_says_it_in_one_line(self): + from strata_cli.launch import cmd + from strata_control import discovery + import contextlib + import io + self.cut_off(1) + with mock.patch.object(discovery, "data_dir", return_value=(self.old, "settings")): + out = io.StringIO() + with contextlib.redirect_stdout(out): + cmd._interrupted_move_notice() + self.assertEqual(len(out.getvalue().strip().splitlines()), 1) + self.assertIn("models move --resume", out.getvalue()) + mm.leave(self.old, self.new) + out = io.StringIO() + with contextlib.redirect_stdout(out): + cmd._interrupted_move_notice() + self.assertEqual(out.getvalue(), "") + + def test_the_cancel_file_stops_the_run(self): + from strata_cli import cli + import contextlib + import io + cancel = self.base / "cancel" + cancel.write_text("x") + out = io.StringIO() + with contextlib.redirect_stdout(out), self.copy_mode(): + code = cli.main(["models", "move", str(self.new), "--from", str(self.old), "--cancel-file", str(cancel), "--output", "json"]) + self.assertEqual(code, 6) + self.assertTrue(json.loads(out.getvalue().splitlines()[-1])["stopped"]) + self.assertTrue((self.old / "models/coder/c.gguf").exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/terminal/test_updater.py b/tests/terminal/test_updater.py index 29f77922..f8b6747c 100644 --- a/tests/terminal/test_updater.py +++ b/tests/terminal/test_updater.py @@ -48,6 +48,7 @@ class UpdaterCase(unittest.TestCase): patch = mock.patch.object(target, value, return_value=["sm_86"] if value == "cuda_archs_present" else "610.47") patch.start() self.addCleanup(patch.stop) + ec.register_signature_verifier(None) # a verifier an earlier test file left behind (it holds the shipped keys only) must not decide here self.addCleanup(ec.register_signature_verifier, None) # the tests sign with throwaway keys that they hand over explicitly: the release key shipped in update_keys.json is not in play here # (ReleaseKeys below checks the shipped file itself) diff --git a/tools/iq_pack.py b/tools/iq_pack.py index b48af1aa..b33723a0 100644 --- a/tools/iq_pack.py +++ b/tools/iq_pack.py @@ -731,16 +731,48 @@ def main() -> int: # experts.bin, and an experts.bin without its sidecar is never reused sidecar.unlink(missing_ok=True) part = out / "experts.bin.tmp" - with open(part, "wb") as fo: - for l, gt, dt, off, blob, ts in layout: + progress = out / "experts.bin.tmp.json" + # A stop part-way (a kill, a power cut) used to cost the whole write again (40 GB, minutes). The finished layers are kept: + # after every layer the file is flushed to disk and experts.bin.tmp.json says how many layers are in it and which source they were + # cut from. The next run continues at that layer when the source is the same and the last kept layer still matches the GGUF. + start = 0 + if part.exists(): + done = read_json(progress) + k = done.get("layers") if isinstance(done, dict) and done.get("want") == want else None + if isinstance(k, int) and 0 < k <= len(layout) and part.stat().st_size >= (layout[k][3] if k < len(layout) else offset): + l, gt, dt, off, blob, ts = layout[k - 1] + last = layer_blobs(l, blob, ts) + if last is not None: + with open(part, "rb") as f: + f.seek(off) + kept = f.read(n_expert * blob) + if kept == last.tobytes(): + start = k + if start: + print("the earlier packing was interrupted: keeping its first %d of %d layers and continuing with layer %d" + % (start, len(layout), start), flush=True) + else: + print("the earlier packing was interrupted and cannot be continued: starting it again", flush=True) + resume_at = layout[start][3] if start < len(layout) else offset + with open(part, "r+b" if start else "wb") as fo: + if start: + fo.truncate(resume_at) # whatever followed the last recorded layer is a partial write + fo.seek(resume_at) + for l, gt, dt, off, blob, ts in layout[start:]: chunk = layer_blobs(l, blob, ts) if chunk is None: return 1 fo.write(chunk.tobytes()) + fo.flush() + os.fsync(fo.fileno()) + note = out / "experts.bin.tmp.json.new" + note.write_text(json.dumps({"want": want, "layers": l + 1}), encoding="utf-8") + note.replace(progress) if l % 8 == 0: print(" layer %2d %-8s/%-7s blob %8d at %.2f GiB" % (l, ts[0].type_name, ts[2].type_name, blob, off / 2**30), flush=True) part.replace(path) + progress.unlink(missing_ok=True) side_tmp = out / "experts.bin.src.json.tmp" side_tmp.write_text(json.dumps(want, indent=2) + "\n", encoding="utf-8") side_tmp.replace(sidecar) diff --git a/tools/test_calibrate.py b/tools/test_calibrate.py index defa9432..97e33597 100644 --- a/tools/test_calibrate.py +++ b/tools/test_calibrate.py @@ -442,7 +442,7 @@ class SetupIntegration(unittest.TestCase): self.assertNotIn("an earlier start", out.getvalue()) out = io.StringIO() with mock.patch.object(self.S, "ROOT", Path(self.tmp.name)), \ - mock.patch.object(self.S, "data_folder", lambda d: (Path(self.tmp.name) / "data", [])), \ + mock.patch.object(self.S, "data_folder", lambda d, *a, **k: (Path(self.tmp.name) / "data", [])), \ mock.patch.object(self.S, "update_installed_engine", lambda *a: None), \ mock.patch.object(sys, "argv", ["setup.py", "--calibrate", "--no-start"]), \ contextlib.redirect_stdout(out): diff --git a/tools/test_iq_pack.py b/tools/test_iq_pack.py index 580bf274..0e0f5e8b 100644 --- a/tools/test_iq_pack.py +++ b/tools/test_iq_pack.py @@ -515,6 +515,95 @@ class SplitArtifactTests(unittest.TestCase): self.assertEqual(rc, 0, log) self.assertEqual((pack / "experts.bin").read_bytes(), expected_experts(iq_pack.Model(paths[0]))) + def test_interrupted_pack_continues_at_the_next_layer(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + paths = split_model(root) + pack = root / "pack" + real = np.concatenate + calls = [] + + def dies_on_layer_1(parts, axis): + calls.append(1) + if len(calls) == 2: + raise KeyboardInterrupt("killed") + return real(parts, axis=axis) + with patch.object(iq_pack.np, "concatenate", dies_on_layer_1): + with self.assertRaises(KeyboardInterrupt): + run_pack(paths[0], pack, "--experts-bin") + want = expected_experts(iq_pack.Model(paths[0])) + lines = [ln.split() for ln in (pack / "native_experts.txt").read_text().splitlines() if ln and not ln.startswith("#")] + one_layer = int(lines[1][3]) # where layer 1 starts + self.assertFalse((pack / "experts.bin").exists()) + self.assertEqual((pack / "experts.bin.tmp").stat().st_size, one_layer) # layer 0 is on disk + self.assertEqual(json.loads((pack / "experts.bin.tmp.json").read_text())["layers"], 1) + # a partial write after the recorded layer (the kill came mid-write) is cut off + with open(pack / "experts.bin.tmp", "ab") as f: + f.write(b"garbage") + written = [] + real_layer = iq_pack.np.concatenate + + def counting(parts, axis): + written.append(1) + return real_layer(parts, axis=axis) + with patch.object(iq_pack.np, "concatenate", counting): + rc, log = run_pack(paths[0], pack, "--experts-bin") + self.assertEqual(rc, 0, log) + self.assertIn("keeping its first 1 of 2 layers and continuing with layer 1", log) + self.assertEqual((pack / "experts.bin").read_bytes(), want) + self.assertEqual(len(written), 2) # one layer re-read to check the kept one, one layer written + self.assertFalse((pack / "experts.bin.tmp").exists()) + self.assertFalse((pack / "experts.bin.tmp.json").exists()) + self.assertEqual(json.loads((pack / "experts.bin.src.json").read_text())["bytes"], len(want)) + + def test_interrupted_pack_of_another_model_is_not_continued(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + (root / "a").mkdir() + (root / "b").mkdir() + other = split_model(root / "a", name="other", seed=100) + paths = split_model(root / "b") + pack = root / "pack" + real = np.concatenate + calls = [] + + def dies_on_layer_1(parts, axis): + calls.append(1) + if len(calls) == 2: + raise KeyboardInterrupt("killed") + return real(parts, axis=axis) + with patch.object(iq_pack.np, "concatenate", dies_on_layer_1): + with self.assertRaises(KeyboardInterrupt): + run_pack(other[0], pack, "--experts-bin") + rc, log = run_pack(paths[0], pack, "--experts-bin") # the same geometry, other weights + self.assertEqual(rc, 0, log) + self.assertIn("cannot be continued: starting it again", log) + self.assertEqual((pack / "experts.bin").read_bytes(), expected_experts(iq_pack.Model(paths[0]))) + + def test_a_kept_layer_that_no_longer_matches_is_not_trusted(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + paths = split_model(root) + pack = root / "pack" + real = np.concatenate + calls = [] + + def dies_on_layer_1(parts, axis): + calls.append(1) + if len(calls) == 2: + raise KeyboardInterrupt("killed") + return real(parts, axis=axis) + with patch.object(iq_pack.np, "concatenate", dies_on_layer_1): + with self.assertRaises(KeyboardInterrupt): + run_pack(paths[0], pack, "--experts-bin") + data = bytearray((pack / "experts.bin.tmp").read_bytes()) + data[0] ^= 0xFF # the disk lost a bit + (pack / "experts.bin.tmp").write_bytes(bytes(data)) + rc, log = run_pack(paths[0], pack, "--experts-bin") + self.assertEqual(rc, 0, log) + self.assertIn("cannot be continued", log) + self.assertEqual((pack / "experts.bin").read_bytes(), expected_experts(iq_pack.Model(paths[0]))) + def test_stale_same_size_experts_bin(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) diff --git a/tools/test_setup_menu.py b/tools/test_setup_menu.py index 1f176836..284f7703 100644 --- a/tools/test_setup_menu.py +++ b/tools/test_setup_menu.py @@ -6,6 +6,7 @@ install removing a stale strata_kq library. """ from __future__ import annotations +import re import sys import tempfile import unittest @@ -155,7 +156,12 @@ class EnginePlaceholders(unittest.TestCase): self.assertEqual(setup.MIN_ENGINE, (0, 1, 45)) for m in ("UD-Q5_K_XL", "UD-Q6_K_XL", "NVFP4", "NVFP4-NVIDIA"): self.assertEqual(setup.MODELS[m]["engine"], (0, 1, 44), m) - self.assertIn("0.1.45", (ROOT / "CMakeLists.txt").read_text(encoding="utf-8").split("project(strata VERSION", 1)[1][:12]) + # No minimum may name an engine newer than this tree (a placeholder for a release that does not exist yet would make setup + # ask for an engine nobody can download). The tree's version is read from CMakeLists.txt, so this does not go stale each release. + text = (ROOT / "CMakeLists.txt").read_text(encoding="utf-8") + tree = tuple(int(n) for n in re.search(r"project\(strata VERSION ([0-9.]+)", text).group(1).split(".")) + for what, minimum in [("MIN_ENGINE", setup.MIN_ENGINE), ("NVFP4_ENGINE", setup.NVFP4_ENGINE)] + [(m, setup.MODELS[m]["engine"]) for m in setup.MODELS if "engine" in setup.MODELS[m]]: + self.assertLessEqual(tuple(minimum), tree[:len(minimum)], f"{what} {minimum} is ahead of the tree {tree}") class KqLibrary(unittest.TestCase): diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py index b758db55..1fc97070 100644 --- a/tools/test_setup_unsloth.py +++ b/tools/test_setup_unsloth.py @@ -11,6 +11,7 @@ import contextlib import hashlib import io import json +import shutil import sys import tempfile import types @@ -186,6 +187,8 @@ class Base(unittest.TestCase): mock.patch.object(setup, "cpu_cores", lambda: None), # #642: not a hybrid CPU mock.patch.object(setup, "page_file_gb", lambda: 16.0), mock.patch.object(setup, "free_gb", lambda p: free), + # whatever else asks the disk (shutil.disk_usage) gets the same answer: the tests never depend on this PC's free space + mock.patch.object(shutil, "disk_usage", lambda p: shutil._ntuple_diskusage(int(max(free, 1000) * 1e9), int(max(free, 1000) * 1e9 - free * 1e9), int(free * 1e9))), mock.patch.object(setup, "rotational_disk", lambda p: None), # #605: not the test PC's disk mock.patch.object(setup, "is_wsl", lambda: False), # #974: the tests are not run inside WSL mock.patch.object(setup, "pip_install", lambda *a, **k: None), @@ -193,7 +196,7 @@ class Base(unittest.TestCase): mock.patch.object(setup, "get_prebuilt", lambda *a, **k: eng), mock.patch.object(setup, "download", fake_download), mock.patch.object(setup, "check_shards", lambda shards: None), - mock.patch.object(setup, "verify_sha256", lambda s, size, sha: self.verified.append((s.name, size, sha))), + mock.patch.object(setup, "verify_sha256", lambda s, size, sha, own=False: self.verified.append((s.name, size, sha))), mock.patch.object(setup, "run", fake_run), mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None), mock.patch.object(setup, "write_run_script", lambda tag, cfg, port, *_: self.t / f"start-{tag}.bat"), @@ -298,8 +301,17 @@ class Main(Base): import shutil shutil.rmtree(self.t / "data" / "mtp", ignore_errors=True) # #897: a draft layer already there needs less room (d / (list(setup.UNSLOTH_SHARDS)[0] + ".part")).write_bytes(b"x" * 1_500_000) - with mock.patch.dict(setup.MODELS[M], {"download_gb": 0.003}): # 1.5 MB still missing: no room + with mock.patch.dict(setup.MODELS[M], {"download_gb": 0.003}): # 1.5 MB still missing, but the 8 GB working room is only a guess (0.2.2): setup warns and goes on code, out, cfg = self.main(["--context", "8192"], free=8.001) + self.assertEqual(code, 0, out) + self.assertNotIn("not enough free disk space", out) + self.assertIn("little free disk space", out) + for f in d.iterdir(): + f.unlink() + shutil.rmtree(self.t / "data" / "mtp", ignore_errors=True) + (d / (list(setup.UNSLOTH_SHARDS)[0] + ".part")).write_bytes(b"x" * 1_500_000) + with mock.patch.dict(setup.MODELS[M], {"download_gb": 3.0}): # 1.5 GB of real files still to write, 1 GB free: refuse + code, out, cfg = self.main(["--context", "8192"], free=1.0) self.assertEqual(code, 1) self.assertIn("not enough free disk space", out)