Merge f-022-int into f-dsv41-port

This commit is contained in:
Niko1221 committed 2026-10-20 18:22:49 +02:00
commit 9f78a77e01
43 files changed
+3448 -77

No files matched your search

+37
View File
@@ -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);
+12 -1
View File
@@ -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') {
+101 -6
View File
@@ -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};
}
+1 -1
View File
@@ -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')}`;
@@ -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<Choice, { possible: boolean; reason: string }>;
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 <div className="error-notice" role="alert"><Icon name="error" size={18}/><div><strong>{tr(message)}</strong>{next ? <p>{tr(next)}</p> : null}{details ? <details className="error-detail"><summary className="small">{tr('Details')}</summary><pre className="small muted">{details}</pre></details> : null}</div></div>;
}
/** 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<Plan | null>(null);
const [stage, setStage] = useState<'issue' | 'drive' | 'choose' | null>(null);
const [choice, setChoice] = useState<Choice>('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<string | null>(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<NativeJob>('/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<NativeJob & { done?: boolean; setAside?: string[] }>('/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 <>
<section className="storage-directory" aria-labelledby="models-folder-title">
<div className="storage-directory__heading"><span><Icon name="folder" size={18}/><strong id="models-folder-title">{tr('Models folder')}</strong></span><Btn size="sm" disabled={!folder || blocked || pending || !!moving} onClick={() => void pick()}>{tr(pending && !plan ? 'Waiting for the folder…' : 'Change folder')}</Btn></div>
<p className="small muted">{tr('Strata saves the big model files here.')}</p>
<code className="storage-directory__path">{folder || tr('Reading model directory…')}</code>
{free !== null ? <div className="models-free"><Bar value={used} label={tr('Disk use')}/><div className="models-free__row small"><span><strong>{tr('{0} free', [gb(free)])}</strong> {tr('on this drive')}</span><span className="muted">{tr('Your models use {0}', [gb(usage)])}</span></div></div> : null}
{blocked && !moving ? <p className="small muted">{tr('Finish or stop the download to change the folder.')}</p> : null}
{typing ? <form className="storage-directory__edit" onSubmit={e => { e.preventDefault(); if (typed.trim()) void pick(typed.trim()); }}>
<label htmlFor="models-folder-path" className="small">{tr('Directory path')}</label>
<input id="models-folder-path" className="st-input" value={typed} onChange={e => setTyped(e.target.value)} placeholder={tr('Full path to an existing folder')} spellCheck={false} autoFocus/>
<div className="row"><Btn variant="primary" type="submit" disabled={pending || !typed.trim()}>{tr('Use this directory')}</Btn></div>
</form> : null}
{unfinished && !moving ? <div className="models-notice models-notice--info" role="alert"><Icon name="info" size={18}/><div>
<strong>{tr('A move was interrupted. Finish it or leave it.')}</strong><br/>
{tr('Strata was moving your models from {0} to {1} when it stopped. Nothing is lost.', [unfinished.from, unfinished.to])}
<p className="small muted">{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])}</p>
<div className="row"><Btn variant="primary" size="sm" disabled={pending || blocked} onClick={() => void finishMove()}>{tr('Finish the move')}</Btn><Btn size="sm" disabled={pending || blocked} onClick={() => void leaveMove()}>{tr('Leave it')}</Btn></div>
</div></div> : null}
{notice ? <p className="small storage-directory__notice" role="status"><Icon name="check" size={15}/>{notice}</p> : null}
{error && !stage ? <Failure message={error.message} details={error.details}/> : null}
</section>
<Dialog className="models-dialog" open={stage === 'issue' && !!plan?.issue} compact title={tr(plan?.issue?.code === 'not_found' ? "That folder isn't there" : "That folder can't be used")} onClose={leave}
actions={<>{plan?.issue?.code === 'not_found' ? null : <Btn onClick={leave}>{tr('Cancel')}</Btn>}<Btn variant="primary" onClick={() => { leave(); void pick(); }}>{tr('Choose another folder')}</Btn></>}>
{plan?.issue ? <Failure message={plan.issue.message} details={plan.issue.details}
next={plan.issue.code === 'not_writable' ? 'Choose a folder you own, for example one in Documents or on another drive.' : plan.issue.code === 'not_found' ? 'Check that the drive is plugged in, then pick the folder again. Your models were not touched.' : undefined}/> : null}
</Dialog>
<Dialog className="models-dialog" open={stage === 'drive' && !!plan} compact title={tr('Use this folder for your models?')} onClose={leave}
actions={<><Btn onClick={leave}>{tr('Cancel')}</Btn><Btn variant="primary" onClick={() => setStage('choose')}>{tr('Continue')}</Btn></>}>
{plan ? <>
<div className="models-picked"><span className="small muted">{tr('New folder')}</span><code className="storage-directory__path">{plan.shown}</code><span className="small muted">{tr('{0} free on this drive', [gb(plan.free_bytes)])}</span></div>
<div className="models-notice models-notice--info"><Icon name="info" size={18}/><div>{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])}</div></div>
<p className="small muted">{tr('The three choices come next.')}</p>
</> : null}
</Dialog>
<Dialog className="models-dialog" open={stage === 'choose' && !!plan} title={tr('Use this folder for your models?')} onClose={() => { if (!pending) leave(); }}
actions={plan ? <>{plan.choices.move.possible ? <Btn disabled={pending} onClick={leave}>{tr('Cancel')}</Btn> : <Btn disabled={pending} onClick={() => { leave(); void pick(); }}>{tr('Choose another folder')}</Btn>}<Btn variant="primary" disabled={pending} onClick={() => void start()}>{tr(pending ? 'Working…' : choice === 'move' ? 'Move my models' : choice === 'keep' ? 'Use both folders' : 'Start empty')}</Btn></> : null}>
{plan ? <ChooseBody plan={plan} choice={choice} setChoice={setChoice} names={planNames} error={error}/> : null}
</Dialog>
<Dialog className="models-dialog" open={!!moving && !outcome} compact noClose title={tr('Moving your models')} onClose={() => undefined}
actions={<Btn disabled={stopping} onClick={() => void stop()}>{tr(stopping ? 'Stopping…' : 'Stop moving')}</Btn>}>
<div className="models-free"><Bar value={percent} label={tr('Progress')}/><div className="models-free__row small"><span><strong>{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)])}</strong></span><span className="muted">{progress && !progress.sameDrive ? timeLeft(progress.secondsLeft) : null}</span></div></div>
<p className="small">{tr('Keep Strata open. You can keep using other apps. Your models cannot be loaded until the move is done.')}</p>
{progress ? <details className="models-details"><summary>{tr('Details')}</summary><ul>
<li>{tr('Now copying: {0}, file {1} of {2}', [modelName(progress.group, native) ?? progress.group, progress.index, progress.count])}</li>
<li>{tr('From {0} to {1}', [savedPlan?.current ?? resumed?.from ?? '', savedPlan?.folder ?? resumed?.to ?? ''])}</li></ul></details> : null}
</Dialog>
<ResultDialog outcome={outcome?.job ?? null} plan={savedPlan} native={native} onClose={closeResult} onAgain={() => { 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 <>
<div className="models-picked"><span className="small muted">{tr('New folder')}</span><code className="storage-directory__path">{plan.shown}</code><span className="small muted">{tr('{0} free on this drive', [gb(plan.free_bytes)])}</span></div>
{short ? <div className="models-notice models-notice--warn" role="alert"><Icon name="warning" size={18}/><div><strong>{tr('Your models need {0}, this drive has {1} free.', [gb(plan.needed_bytes), gb(plan.free_bytes)])}</strong><br/>{tr('Free up about {0} there, pick another folder, or choose one of the other two options.', [gb(lacking)])}</div></div> : null}
<fieldset className="models-choices" aria-label={tr('What should happen to your models')}>
{options.map(o => { const possible = plan.choices[o.id].possible; return <label className="models-choice" key={o.id} data-disabled={!possible || undefined}>
<input type="radio" name="models-folder-choice" checked={choice === o.id} disabled={!possible} onChange={() => setChoice(o.id)}/>
<span><strong>{tr(o.title)}</strong>{o.id === 'move' && possible && !none ? <span className="models-choice__tag">{tr('Recommended')}</span> : null}<br/><span className="small">{tr(o.text, o.id === 'move' ? [gb(plan.models_bytes)] : undefined)}</span></span>
{o.need ? <span className="models-choice__need">{tr(o.need, o.id === 'move' ? [gb(plan.needed_bytes), gb(plan.free_bytes)] : [values[0], values[1]])}</span> : null}
</label>; })}
</fieldset>
{running ? <p className="small muted">{tr('A running model is stopped first; load it again when the move is done.')}</p> : null}
{error ? <Failure message={error.message} details={error.details}/> : null}
<details className="models-details"><summary>{tr('Details')}</summary><ul>
{names.length ? <li>{tr('{0} would move.', [list(names.map(m => `${m.label}, ${gb(m.bytes)}`))])}</li> : null}
{short ? <li>{tr('Free space is measured on the drive that holds {0}.', [plan.shown])}</li> : <>
<li>{tr('Old folder: {0}', [plan.current])}</li>
<li>{tr('Strata copies one file at a time and checks its size before it removes the old one.')}</li>
<li>{tr('You can stop at any time; files already moved stay usable.')}</li></>}
</ul></details>
</>;
}
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 <Dialog open compact title={tr(full ? 'The drive ran out of space' : 'The move stopped')} onClose={onClose}
actions={<><Btn onClick={onClose}>{tr('Close')}</Btn><Btn variant="primary" onClick={onAgain}>{tr('Choose another folder')}</Btn></>}>
<div className="error-notice" role="alert"><Icon name="error" size={18}/><div>
<strong>{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.')}</strong>
<p>{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 ?? ''])}</p>
{outcome.details ? <details className="error-detail"><summary className="small">{tr('Details')}</summary><pre className="small muted">{outcome.details}</pre></details> : null}
</div></div>
</Dialog>;
}
if (result.stopped) {
const moved = sized(result.moved ?? []), left = sized(result.remaining ?? []);
return <Dialog open compact title={tr('Moving stopped')} onClose={onClose} actions={<Btn variant="primary" onClick={onClose}>{tr('Close')}</Btn>}>
<div className="models-notice models-notice--info"><Icon name="info" size={18}/><div><strong>{tr('Nothing was lost.')}</strong><br/>
{moved ? tr('{0} is in the new folder.', [moved]) + ' ' : ''}{left ? tr('{0} is still in the old folder.', [left]) + ' ' : ''}{moved && left ? tr('Both work.') : ''}</div></div>
<p className="small muted">{tr('Models in both folders are listed as normal. You can finish moving later with Change folder.')}</p>
</Dialog>;
}
return <Dialog open compact title={tr('Your models are moved')} onClose={onClose} actions={<Btn variant="primary" onClick={onClose}>{tr('Done')}</Btn>}>
<div className="models-ok"><span className="models-ok__mark"><Icon name="check" size={20}/></span><div><strong>{(() => { const [before, after] = tr('{0} now live in {1}', [gb(result.total ?? 0), '@@']).split('@@'); return <>{before}<code className="models-path">{plan?.shown ?? result.to ?? ''}</code>{after}</>; })()}</strong>
{result.sameDrive ? null : <><br/><span className="small muted">{tr('The old copies were removed and {0} is free again on {1}.', [gb(result.total ?? 0), driveOf(result.from ?? '')])}</span></>}</div></div>
</Dialog>;
}
@@ -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 ? <ModelsFolderCard blocked={downloading}/> : null}
<section className="storage-directory" aria-labelledby="storage-directory-title">
<div className="storage-directory__heading"><span><Icon name="folder" size={18}/><strong id="storage-directory-title">{tr("Model directory")}</strong></span><Btn size="sm" disabled={!currentDirectory || directoryPending || pending} onClick={() => { setDirectory(currentDirectory); setEditing(!editing); setDirectoryError(''); setNotice(''); }}>{tr(editing ? 'Cancel' : 'Change directory')}</Btn></div>
<p className="small muted">{tr("Your models are saved here. Use an existing folder to reuse supported downloads.")}</p>
@@ -95,6 +98,7 @@ export function SettingsStorage() {
<div className="row"><Btn variant="primary" type="submit" disabled={directoryPending || directoryBlocked || !directory.trim()}>{tr(directoryPending ? 'Checking files…' : changing && loadedCount > 0 ? 'Unload and change directory' : changing ? 'Use this directory' : 'Check folder')}</Btn></div>
</form> : <Btn size="sm" icon="refresh" disabled={directoryPending || directoryBlocked || !currentDirectory} onClick={() => void saveDirectory(currentDirectory)}>{tr(directoryPending ? 'Checking files…' : 'Check folder')}</Btn>)}
{tr(directoryBlocked && !directoryPending ? <p className="small muted">{tr(!lifecycle.allowed ? lifecycle.reason : 'Finish or cancel downloads and loading to change the directory.')}</p> : null)}
{tr(state.setup?.app.modelsDirNotice && !notice ? <p className="small storage-directory__notice" role="status"><Icon name="info" size={15}/>{tr(state.setup.app.modelsDirNotice)}</p> : null)}
{tr(notice ? <p className="small storage-directory__notice" role="status"><Icon name="check" size={15}/>{tr(notice)}</p> : null)}
{tr(directoryError ? <ErrorNotice message={directoryError}/> : null)}
</section>
+4 -2
View File
@@ -384,7 +384,7 @@ export function Select<T extends string>({ 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<HTMLElement>(null);
const id = useId();
@@ -418,7 +420,7 @@ export function Dialog({ open, title, onClose, children, actions, headerActions,
return createPortal(<div className="dialog-layer">
<div className="dialog-scrim" onClick={onClose} aria-hidden="true"/>
<section ref={ref} className={cx(`${sheet ? 'dialog-surface dialog-surface--sheet' : 'dialog-surface'}${wide ? ' dialog-surface--wide' : ''}${compact ? ' dialog-surface--compact' : ''}`, className)} role="dialog" aria-modal="true" aria-labelledby={id} tabIndex={-1}>
<header className="dialog-head"><h2 className={hideTitle ? 'sr-only' : 'h3'} id={id}>{tr(title)}</h2><div className="dialog-head__actions">{tr(headerActions)}<IconBtn name="x" title={typeof title === 'string' ? tr("Close {0}", [title]) : tr("Close")} onClick={onClose}/></div></header>
<header className="dialog-head"><h2 className={hideTitle ? 'sr-only' : 'h3'} id={id}>{tr(title)}</h2><div className="dialog-head__actions">{tr(headerActions)}{noClose ? null : <IconBtn name="x" title={typeof title === 'string' ? tr("Close {0}", [title]) : tr("Close")} onClick={onClose}/>}</div></header>
<div className="dialog-body">{tr(children)}</div>
{tr(actions ? <footer className="dialog-actions">{tr(actions)}</footer> : null)}
</section>
+1 -1
View File
@@ -12,7 +12,7 @@ export interface NativeState {
/** The picture reader (strata-vision) is installed with the engine, so models marked for pictures can read them here. */
/** Strata Control's view of the engine for this computer (the app): usable false = none found or recognised; `notice` says why in plain words. */
engine?:{usable:boolean;notice?:string|null;wrongMake?:boolean;version?:string|null};
visionReader?: boolean;available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;/** The picture-reading files are on this computer (notes-split-agent8.md, item 8). */visionPrepared?:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;diskGb?:number;diskBytes?:number;/** Files this model shares with another (the picture reader, the draft layer): counted once, in `usage`. */sharedBytes?:number;/** What Delete frees: files in Strata's own folders that no other model uses. */removableGb?:number;missing_files?:string[]}[];/** What all models take on disk, from their real files, shared files counted once. */usage?:{total_bytes:number;total_gb:number;shared_bytes:number;shared_gb:number;models:Record<string,{bytes:number;gb:number}>}|null;data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;engine_vendor?:string;gpus:{index:number;name:string;vram_gb:number;usable:boolean;vendor?:string;uma?:boolean;integrated?:boolean;unified_gb?:number;problem?:string|null}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean;componentUpdates?:boolean}}
visionReader?: boolean;available:boolean;repo:string;downloadDirectory?:string;/** Free bytes on the drive that holds the models folder. */downloadFreeBytes?:number|null;downloadTotalBytes?:number|null;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;/** The picture-reading files are on this computer (notes-split-agent8.md, item 8). */visionPrepared?:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;diskGb?:number;diskBytes?:number;/** Files this model shares with another (the picture reader, the draft layer): counted once, in `usage`. */sharedBytes?:number;/** What Delete frees: files in Strata's own folders that no other model uses. */removableGb?:number;missing_files?:string[]}[];/** What all models take on disk, from their real files, shared files counted once. */usage?:{total_bytes:number;total_gb:number;shared_bytes:number;shared_gb:number;models:Record<string,{bytes:number;gb:number}>}|null;data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;engine_vendor?:string;gpus:{index:number;name:string;vram_gb:number;usable:boolean;vendor?:string;uma?:boolean;integrated?:boolean;unified_gb?:number;problem?:string|null}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean;componentUpdates?:boolean}}
let state:NativeState|null=null;
const listeners=new Set<()=>void>();
function put(value:NativeState){if(state&&JSON.stringify(state)===JSON.stringify(value))return;state=value;listeners.forEach(fn=>fn());}
+1 -1
View File
@@ -495,7 +495,7 @@ export interface SetupState {
step: number;
completedAt?: string;
history: { step: number; at: string }[];
app: { version: string; modelsDir: string; dataDir: string };
app: { version: string; modelsDir: string; dataDir: string; modelsDirNotice?: string };
}
export interface EngineEvent {
+98 -1
View File
@@ -3346,5 +3346,102 @@
"s8257": "alle {0} Min.",
"s8258": "Diese Strata-Engine hat keinen Code für die Grafikkarte, die sie verwenden wollte.",
"s8259": "Wähle unter „Ausführen auf“ eine andere Karte, oder öffne die Details: Dort steht, welche Karten gefunden wurden und wofür die Engine gebaut ist.",
"s8260": "Dieser Schalter bewirkt in der App nichts. Webseiten beliebiger Seiten können die unter „API-Server“ gezeigte API schon aufrufen. Um nur bestimmte Seiten zuzulassen oder den eigenen Server der Engine (Port 8080) zu nutzen, tragen Sie \"cors_origins\": [\"https://ihre.seite\"] in die Konfigurationsdatei des Modells ein."
"s8260": "Dieser Schalter bewirkt in der App nichts. Webseiten beliebiger Seiten können die unter „API-Server“ gezeigte API schon aufrufen. Um nur bestimmte Seiten zuzulassen oder den eigenen Server der Engine (Port 8080) zu nutzen, tragen Sie \"cors_origins\": [\"https://ihre.seite\"] in die Konfigurationsdatei des Modells ein.",
"s8301": "API-Schlüssel erstellen (empfohlen)",
"s8302": "Ohne API-Schlüssel kann jedes Gerät in diesem Netzwerk Ihr Modell nutzen.",
"s8303": "Es wird nur die Inferenz-API freigegeben. Clients brauchen Ihren API-Schlüssel, sofern einer gesetzt ist. Nutzen Sie ein vertrauenswürdiges lokales Netzwerk; diese Verbindung verwendet HTTP.",
"s8304": "Erstellen Sie einen Schlüssel, um Ihre API zu schützen. Danach kehren Sie hierher zurück. Sie können auch ohne Schlüssel fortfahren, dann kann aber jeder, der den Link findet, Ihr Modell nutzen.",
"s8305": "Sie haben schon ein unterstütztes Modell auf diesem Computer? Wählen Sie den Ordner mit den Dateien oder eine der .gguf-Dateien. Strata prüft sie, bereitet das Modell vor und lädt es. Es wird nichts kopiert oder heruntergeladen.",
"s8306": "Ordner mit den GGUF-Dateien oder eine .gguf-Datei",
"s8307": "Vollständiger Pfad zum Ordner oder zur Datei",
"s8308": "Ohne API-Schlüssel kann jeder, der diese Adresse erreicht, Ihr Modell nutzen.",
"s8309": "Strata konnte {0} nicht für Modelle verwenden ({1}); die Modelle werden daher in {2} abgelegt. Sie können in den Einstellungen einen anderen Ordner wählen.",
"s8310": "Port {0} wird bereits verwendet. Strata läuft vielleicht schon; schließen Sie es oder das andere Programm, oder starten Sie Strata mit einem anderen Port (STRATA_PORT).",
"s8311": "Windows oder eine Firewall erlaubt Strata nicht, Port {0} zu verwenden. Hyper-V, WSL und Docker reservieren Portbereiche für sich (siehe \"netsh int ipv4 show excludedportrange protocol=tcp\"). Starten Sie Strata mit einem anderen Port (STRATA_PORT), zum Beispiel 8801.",
"s8312": "{0} ist keine Adresse dieses Computers, daher kann Strata dort nicht lauschen. Prüfen Sie STRATA_BIND.",
"s8313": "Strata kann auf {0}:{1} nicht lauschen ({2}).",
"s8339": "Modellordner",
"s8340": "Strata speichert die großen Modelldateien hier.",
"s8341": "Ordner ändern",
"s8342": "Warte auf den Ordner …",
"s8343": "Speicherplatz belegt",
"s8344": "{0} frei",
"s8345": "auf diesem Laufwerk",
"s8346": "Ihre Modelle belegen {0}",
"s8347": "Beenden oder stoppen Sie den Download, um den Ordner zu ändern.",
"s8348": "Diesen Ordner gibt es nicht",
"s8349": "Dieser Ordner kann nicht verwendet werden",
"s8350": "Strata kann in {0} keine Dateien speichern.",
"s8351": "Strata kann {0} nicht finden.",
"s8352": "Wählen Sie einen Ordner außerhalb des aktuellen.",
"s8353": "Wählen Sie einen Ordner, der Ihnen gehört, zum Beispiel in Dokumente oder auf einem anderen Laufwerk.",
"s8354": "Prüfen Sie, ob das Laufwerk angeschlossen ist, und wählen Sie den Ordner erneut. Ihre Modelle wurden nicht verändert.",
"s8355": "Diesen Ordner für Ihre Modelle verwenden?",
"s8356": "Neuer Ordner",
"s8357": "{0} frei auf diesem Laufwerk",
"s8358": "Sie haben das ganze Laufwerk {0} gewählt. Strata legt seine Dateien in einem eigenen Ordner ab, Ihre Modelle liegen daher in {1}.",
"s8359": "Als Nächstes folgen die drei Möglichkeiten.",
"s8360": "Meine Modelle verschieben",
"s8361": "Beide Ordner verwenden",
"s8362": "Leer beginnen",
"s8363": "Ihre Modelle werden verschoben",
"s8364": "Verschieben stoppen",
"s8365": "{0} von {1} GB",
"s8366": "Weniger als eine Minute übrig",
"s8367": "Etwa eine Minute übrig",
"s8368": "Etwa {0} Minuten übrig",
"s8369": "Etwa {0} Stunden übrig",
"s8370": "Lassen Sie Strata geöffnet. Andere Apps können Sie weiter benutzen. Ihre Modelle lassen sich erst laden, wenn das Verschieben fertig ist.",
"s8371": "Kopiert gerade: {0}, Datei {1} von {2}",
"s8372": "Von {0} nach {1}",
"s8373": "Meine Modelle dorthin verschieben",
"s8374": "Sie haben keine Modelle zum Verschieben.",
"s8375": "Strata verschiebt Ihre {0} Modelle in den neuen Ordner. Es ist dasselbe Laufwerk, das geht also schnell.",
"s8376": "Strata kopiert Ihre {0} Modelle in den neuen Ordner, prüft sie und entfernt dann die alten Kopien.",
"s8377": "Braucht keinen zusätzlichen Platz.",
"s8378": "Benötigt {0} freien Platz im neuen Ordner. Verfügbar: {1}.",
"s8379": "Am bisherigen Ort lassen und zusätzlich den neuen Ordner verwenden",
"s8380": "Es wird nichts kopiert. Ihre aktuellen Modelle funktionieren weiter, neue Downloads landen im neuen Ordner.",
"s8381": "Braucht jetzt keinen Platz. Neue Downloads müssen in {1} passen.",
"s8382": "Braucht jetzt keinen Platz.",
"s8383": "Strata verwendet ab jetzt den neuen Ordner und zeigt Ihre aktuellen Modelle nicht mehr an. Ihre alten Dateien werden nicht gelöscht.",
"s8384": "Braucht jetzt keinen Platz. Jedes später geladene Modell braucht eigenen Platz.",
"s8385": "Ihre Modelle brauchen {0}, auf diesem Laufwerk sind {1} frei.",
"s8386": "Geben Sie dort etwa {0} frei, wählen Sie einen anderen Ordner oder nehmen Sie eine der anderen beiden Möglichkeiten.",
"s8387": "Was soll mit Ihren Modellen geschehen",
"s8388": "Ein laufendes Modell wird zuerst gestoppt; laden Sie es nach dem Verschieben erneut.",
"s8389": "{0} würden verschoben.",
"s8390": "Der freie Platz wird auf dem Laufwerk gemessen, auf dem {0} liegt.",
"s8391": "Alter Ordner: {0}",
"s8392": "Strata kopiert eine Datei nach der anderen und prüft ihre Größe, bevor die alte entfernt wird.",
"s8393": "Sie können jederzeit stoppen; bereits verschobene Dateien bleiben nutzbar.",
"s8394": "Auf dem Laufwerk ist der Platz ausgegangen",
"s8395": "Das Verschieben wurde gestoppt",
"s8396": "{0} war nach {1} voll, deshalb wurde das Verschieben gestoppt.",
"s8397": "Die Modelle konnten nicht verschoben werden.",
"s8398": "Es ging nichts verloren. Bereits verschobene Modelle liegen im neuen Ordner, die übrigen noch in {0}, und die halb kopierte Datei wurde entfernt. Schaffen Sie Platz auf {1} oder wählen Sie einen anderen Ordner und versuchen Sie es erneut.",
"s8399": "Es ging nichts verloren. Alle Ihre Modelle liegen noch in {0}, und die halb kopierte Datei wurde entfernt. Schaffen Sie Platz auf {1} oder wählen Sie einen anderen Ordner und versuchen Sie es erneut.",
"s8400": "Es ging nichts verloren. Die nicht verschobenen Modelle liegen noch in {0}. Wählen Sie einen anderen Ordner, um es erneut zu versuchen.",
"s8401": "Verschieben gestoppt",
"s8402": "Es ging nichts verloren.",
"s8403": "{0} liegt im neuen Ordner.",
"s8404": "{0} liegt noch im alten Ordner.",
"s8405": "Beide funktionieren.",
"s8406": "Modelle in beiden Ordnern werden wie gewohnt angezeigt. Das Verschieben können Sie später mit „Ordner ändern“ beenden.",
"s8407": "Ihre Modelle wurden verschoben",
"s8408": "{0} liegen jetzt in {1}",
"s8409": "Die alten Kopien wurden entfernt, auf {1} sind wieder {0} frei.",
"s8410": "Strata verwendet jetzt auch {0}. Neue Downloads landen dort, Ihre aktuellen Modelle bleiben, wo sie sind.",
"s8411": "Strata verwendet jetzt {0}. Ihre alten Modelldateien liegen noch in {1}; Strata löscht sie nicht.",
"s8412": "Das Ändern des Modellordners ist Teil der Strata-App.",
"s8413": "Ein Modell läuft. Stoppen Sie es zuerst und ändern Sie dann den Ordner.",
"s8414": "Wählen Sie einen Modellordner.",
"s8415": "Wählen Sie, was mit Ihren Modellen geschehen soll.",
"s8416": "Diese Möglichkeit gibt es hier nicht.",
"s8417": "Ein Verschieben wurde unterbrochen. Beenden Sie es oder lassen Sie es sein.",
"s8418": "Strata hat Ihre Modelle von {0} nach {1} verschoben, als es angehalten wurde. Es ist nichts verloren.",
"s8419": "Verschieben beenden",
"s8420": "Belassen",
"s8421": "Beenden legt alle Ihre Modelle in {1} ab. Belassen lässt sie in {0} und entfernt die unvollständigen Kopien aus {1}.",
"s8422": "Die unvollständigen Kopien wurden entfernt. Ihre Modelle liegen in {0}."
}
+98 -1
View File
@@ -3346,5 +3346,102 @@
"s8257": "every {0} min",
"s8258": "This Strata engine has no code for the graphics card it tried to use.",
"s8259": "Pick another card under Run on, or open Details to see which cards were found and what the engine is built for.",
"s8260": "This switch does nothing in the app. Web pages from any site can already call the API shown under Serving. To allow only some sites, or to use the engine’s own server (port 8080), add \"cors_origins\": [\"https://your.site\"] to the model’s config file."
"s8260": "This switch does nothing in the app. Web pages from any site can already call the API shown under Serving. To allow only some sites, or to use the engine’s own server (port 8080), add \"cors_origins\": [\"https://your.site\"] to the model’s config file.",
"s8301": "Create an API key (recommended)",
"s8302": "Without an API key, any device on this network can use your model.",
"s8303": "Only the inference API is shared. Clients need your API key when one is set. Use a trusted local network; this connection uses HTTP.",
"s8304": "Create a key to protect your API. You’ll return here when it’s ready. You can also continue without one, but anyone who finds the link can then use your model.",
"s8305": "Already have a supported model on this computer? Choose the folder that holds its files, or one of its .gguf files. Strata checks them, prepares the model and loads it. Nothing is copied or downloaded.",
"s8306": "Folder with the GGUF files, or one .gguf file",
"s8307": "Full path to the folder or the file",
"s8308": "Without an API key, anyone who can reach this address can use your model.",
"s8309": "Strata could not use {0} for models ({1}), so models go to {2}. You can pick another folder in Settings.",
"s8310": "Port {0} is already in use. Strata may already be running; close it or the other program, or start Strata with another port (STRATA_PORT).",
"s8311": "Windows or a firewall does not let Strata use port {0}. Hyper-V, WSL and Docker keep ranges of ports for themselves (see \"netsh int ipv4 show excludedportrange protocol=tcp\"). Start Strata with another port (STRATA_PORT), for example 8801.",
"s8312": "{0} is not an address of this computer, so Strata cannot listen on it. Check STRATA_BIND.",
"s8313": "Strata cannot listen on {0}:{1} ({2}).",
"s8339": "Models folder",
"s8340": "Strata saves the big model files here.",
"s8341": "Change folder",
"s8342": "Waiting for the folder…",
"s8343": "Disk use",
"s8344": "{0} free",
"s8345": "on this drive",
"s8346": "Your models use {0}",
"s8347": "Finish or stop the download to change the folder.",
"s8348": "That folder isn't there",
"s8349": "That folder can't be used",
"s8350": "Strata can't save files in {0}.",
"s8351": "Strata can't find {0}.",
"s8352": "Pick a folder outside the current one.",
"s8353": "Choose a folder you own, for example one in Documents or on another drive.",
"s8354": "Check that the drive is plugged in, then pick the folder again. Your models were not touched.",
"s8355": "Use this folder for your models?",
"s8356": "New folder",
"s8357": "{0} free on this drive",
"s8358": "You picked the whole drive {0}. Strata keeps its files in a folder of their own, so your models go in {1}.",
"s8359": "The three choices come next.",
"s8360": "Move my models",
"s8361": "Use both folders",
"s8362": "Start empty",
"s8363": "Moving your models",
"s8364": "Stop moving",
"s8365": "{0} of {1} GB",
"s8366": "Less than a minute left",
"s8367": "About a minute left",
"s8368": "About {0} minutes left",
"s8369": "About {0} hours left",
"s8370": "Keep Strata open. You can keep using other apps. Your models cannot be loaded until the move is done.",
"s8371": "Now copying: {0}, file {1} of {2}",
"s8372": "From {0} to {1}",
"s8373": "Move my models there",
"s8374": "You have no models to move.",
"s8375": "Strata moves your {0} of models to the new folder. This is the same drive, so it takes a moment.",
"s8376": "Strata copies your {0} of models to the new folder, checks them, then removes the old copies.",
"s8377": "Needs no extra space.",
"s8378": "Needs {0} free in the new folder. You have {1}.",
"s8379": "Keep them where they are and also use the new folder",
"s8380": "Nothing is copied. Your current models keep working, and new downloads go to the new folder.",
"s8381": "Needs no space now. New downloads must fit in {1}.",
"s8382": "Needs no space now.",
"s8383": "Strata uses the new folder from now on and does not list your current models. Your old files are not deleted.",
"s8384": "Needs no space now. Each model you download later needs its own space.",
"s8385": "Your models need {0}, this drive has {1} free.",
"s8386": "Free up about {0} there, pick another folder, or choose one of the other two options.",
"s8387": "What should happen to your models",
"s8388": "A running model is stopped first; load it again when the move is done.",
"s8389": "{0} would move.",
"s8390": "Free space is measured on the drive that holds {0}.",
"s8391": "Old folder: {0}",
"s8392": "Strata copies one file at a time and checks its size before it removes the old one.",
"s8393": "You can stop at any time; files already moved stay usable.",
"s8394": "The drive ran out of space",
"s8395": "The move stopped",
"s8396": "{0} filled up after {1}, so the move stopped.",
"s8397": "The models could not be moved.",
"s8398": "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.",
"s8399": "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.",
"s8400": "Nothing was lost. Your models that were not moved are still in {0}. Choose another folder to try again.",
"s8401": "Moving stopped",
"s8402": "Nothing was lost.",
"s8403": "{0} is in the new folder.",
"s8404": "{0} is still in the old folder.",
"s8405": "Both work.",
"s8406": "Models in both folders are listed as normal. You can finish moving later with Change folder.",
"s8407": "Your models are moved",
"s8408": "{0} now live in {1}",
"s8409": "The old copies were removed and {0} is free again on {1}.",
"s8410": "Strata now also uses {0}. New downloads go there, and your current models stay where they are.",
"s8411": "Strata now uses {0}. Your old model files are still in {1}; Strata does not delete them.",
"s8412": "Changing the models folder is part of the Strata app.",
"s8413": "A model is running. Stop it first, then change the folder.",
"s8414": "Choose a models folder.",
"s8415": "Choose what to do with your models.",
"s8416": "That choice is not possible here.",
"s8417": "A move was interrupted. Finish it or leave it.",
"s8418": "Strata was moving your models from {0} to {1} when it stopped. Nothing is lost.",
"s8419": "Finish the move",
"s8420": "Leave it",
"s8421": "Finishing puts all your models in {1}. Leaving it keeps them in {0} and removes the partial copies from {1}.",
"s8422": "The partial copies were removed. Your models are in {0}."
}
+98 -1
View File
@@ -3346,5 +3346,102 @@
"s8257": "cada {0} min",
"s8258": "Este motor de Strata no tiene código para la tarjeta gráfica que intentó usar.",
"s8259": "Elige otra tarjeta en «Ejecutar en», o abre los detalles para ver qué tarjetas se encontraron y para cuáles está compilado el motor.",
"s8260": "Este interruptor no hace nada en la app. Las páginas web de cualquier sitio ya pueden llamar a la API que se muestra en Servicio. Para permitir solo algunos sitios, o para usar el servidor propio del motor (puerto 8080), añada \"cors_origins\": [\"https://su.sitio\"] al archivo de configuración del modelo."
"s8260": "Este interruptor no hace nada en la app. Las páginas web de cualquier sitio ya pueden llamar a la API que se muestra en Servicio. Para permitir solo algunos sitios, o para usar el servidor propio del motor (puerto 8080), añada \"cors_origins\": [\"https://su.sitio\"] al archivo de configuración del modelo.",
"s8301": "Crear una clave de API (recomendado)",
"s8302": "Sin una clave de API, cualquier dispositivo de esta red puede usar tu modelo.",
"s8303": "Solo se comparte la API de inferencia. Los clientes necesitan tu clave de API si hay una. Usa una red local de confianza; esta conexión usa HTTP.",
"s8304": "Crea una clave para proteger tu API. Volverás aquí cuando esté lista. También puedes continuar sin ella, pero cualquiera que encuentre el enlace podrá usar tu modelo.",
"s8305": "¿Ya tienes un modelo compatible en este equipo? Elige la carpeta con sus archivos o uno de sus archivos .gguf. Strata los comprueba, prepara el modelo y lo carga. No se copia ni se descarga nada.",
"s8306": "Carpeta con los archivos GGUF, o un archivo .gguf",
"s8307": "Ruta completa de la carpeta o del archivo",
"s8308": "Sin una clave de API, cualquiera que pueda llegar a esta dirección podrá usar tu modelo.",
"s8309": "Strata no pudo usar {0} para los modelos ({1}), así que los modelos van a {2}. Puedes elegir otra carpeta en Ajustes.",
"s8310": "El puerto {0} ya está en uso. Puede que Strata ya se esté ejecutando; ciérralo o cierra el otro programa, o inicia Strata con otro puerto (STRATA_PORT).",
"s8311": "Windows o un cortafuegos no deja que Strata use el puerto {0}. Hyper-V, WSL y Docker reservan rangos de puertos para sí mismos (consulta \"netsh int ipv4 show excludedportrange protocol=tcp\"). Inicia Strata con otro puerto (STRATA_PORT), por ejemplo 8801.",
"s8312": "{0} no es una dirección de este equipo, así que Strata no puede escuchar en ella. Revisa STRATA_BIND.",
"s8313": "Strata no puede escuchar en {0}:{1} ({2}).",
"s8339": "Carpeta de modelos",
"s8340": "Strata guarda aquí los archivos grandes de los modelos.",
"s8341": "Cambiar carpeta",
"s8342": "Esperando la carpeta…",
"s8343": "Uso del disco",
"s8344": "{0} libres",
"s8345": "en esta unidad",
"s8346": "Tus modelos ocupan {0}",
"s8347": "Termina o detén la descarga para cambiar la carpeta.",
"s8348": "Esa carpeta no existe",
"s8349": "No se puede usar esa carpeta",
"s8350": "Strata no puede guardar archivos en {0}.",
"s8351": "Strata no encuentra {0}.",
"s8352": "Elige una carpeta fuera de la actual.",
"s8353": "Elige una carpeta tuya, por ejemplo una en Documentos o en otra unidad.",
"s8354": "Comprueba que la unidad esté conectada y vuelve a elegir la carpeta. Tus modelos no se han tocado.",
"s8355": "¿Usar esta carpeta para tus modelos?",
"s8356": "Carpeta nueva",
"s8357": "{0} libres en esta unidad",
"s8358": "Has elegido toda la unidad {0}. Strata guarda sus archivos en una carpeta propia, así que tus modelos irán en {1}.",
"s8359": "A continuación verás las tres opciones.",
"s8360": "Mover mis modelos",
"s8361": "Usar ambas carpetas",
"s8362": "Empezar vacío",
"s8363": "Moviendo tus modelos",
"s8364": "Detener el traslado",
"s8365": "{0} de {1} GB",
"s8366": "Queda menos de un minuto",
"s8367": "Queda aproximadamente un minuto",
"s8368": "Quedan aproximadamente {0} minutos",
"s8369": "Quedan aproximadamente {0} horas",
"s8370": "Mantén Strata abierto. Puedes seguir usando otras aplicaciones. Tus modelos no se podrán cargar hasta que termine el traslado.",
"s8371": "Copiando ahora: {0}, archivo {1} de {2}",
"s8372": "De {0} a {1}",
"s8373": "Mover mis modelos allí",
"s8374": "No tienes modelos que mover.",
"s8375": "Strata mueve tus {0} de modelos a la carpeta nueva. Es la misma unidad, así que tarda un instante.",
"s8376": "Strata copia tus {0} de modelos a la carpeta nueva, los comprueba y después elimina las copias antiguas.",
"s8377": "No necesita espacio adicional.",
"s8378": "Necesita {0} libres en la carpeta nueva. Tienes {1}.",
"s8379": "Dejarlos donde están y usar también la carpeta nueva",
"s8380": "No se copia nada. Tus modelos actuales siguen funcionando y las descargas nuevas van a la carpeta nueva.",
"s8381": "No necesita espacio ahora. Las descargas nuevas deben caber en {1}.",
"s8382": "No necesita espacio ahora.",
"s8383": "Strata usará la carpeta nueva a partir de ahora y no mostrará tus modelos actuales. Tus archivos antiguos no se borran.",
"s8384": "No necesita espacio ahora. Cada modelo que descargues después necesitará su propio espacio.",
"s8385": "Tus modelos necesitan {0} y esta unidad tiene {1} libres.",
"s8386": "Libera unos {0} allí, elige otra carpeta o escoge una de las otras dos opciones.",
"s8387": "Qué debe pasar con tus modelos",
"s8388": "Un modelo en ejecución se detiene antes; cárgalo de nuevo cuando termine el traslado.",
"s8389": "Se moverían {0}.",
"s8390": "El espacio libre se mide en la unidad que contiene {0}.",
"s8391": "Carpeta anterior: {0}",
"s8392": "Strata copia un archivo cada vez y comprueba su tamaño antes de eliminar el antiguo.",
"s8393": "Puedes detenerlo en cualquier momento; los archivos ya movidos siguen siendo utilizables.",
"s8394": "La unidad se quedó sin espacio",
"s8395": "El traslado se detuvo",
"s8396": "{0} se llenó tras {1}, así que el traslado se detuvo.",
"s8397": "No se pudieron mover los modelos.",
"s8398": "No se perdió nada. Los modelos ya movidos están en la carpeta nueva, el resto sigue en {0} y se eliminó el archivo copiado a medias. Libera espacio en {1} o elige otra carpeta y vuelve a intentarlo.",
"s8399": "No se perdió nada. Todos tus modelos siguen en {0} y se eliminó el archivo copiado a medias. Libera espacio en {1} o elige otra carpeta y vuelve a intentarlo.",
"s8400": "No se perdió nada. Los modelos que no se movieron siguen en {0}. Elige otra carpeta para volver a intentarlo.",
"s8401": "Traslado detenido",
"s8402": "No se perdió nada.",
"s8403": "{0} está en la carpeta nueva.",
"s8404": "{0} sigue en la carpeta anterior.",
"s8405": "Ambos funcionan.",
"s8406": "Los modelos de ambas carpetas aparecen como siempre. Puedes terminar el traslado más tarde con «Cambiar carpeta».",
"s8407": "Tus modelos se han movido",
"s8408": "{0} están ahora en {1}",
"s8409": "Se eliminaron las copias antiguas y vuelven a estar libres {0} en {1}.",
"s8410": "Strata ahora también usa {0}. Las descargas nuevas van allí y tus modelos actuales se quedan donde están.",
"s8411": "Strata ahora usa {0}. Tus archivos de modelos antiguos siguen en {1}; Strata no los borra.",
"s8412": "Cambiar la carpeta de modelos forma parte de la aplicación Strata.",
"s8413": "Hay un modelo en ejecución. Deténlo primero y después cambia la carpeta.",
"s8414": "Elige una carpeta de modelos.",
"s8415": "Elige qué hacer con tus modelos.",
"s8416": "Esa opción no es posible aquí.",
"s8417": "Se interrumpió un traslado. Termínelo o déjelo como estaba.",
"s8418": "Strata estaba trasladando sus modelos de {0} a {1} cuando se detuvo. No se ha perdido nada.",
"s8419": "Terminar el traslado",
"s8420": "Dejarlo",
"s8421": "Terminar pone todos sus modelos en {1}. Dejarlo los mantiene en {0} y elimina las copias parciales de {1}.",
"s8422": "Se eliminaron las copias parciales. Sus modelos están en {0}."
}
+98 -1
View File
@@ -3346,5 +3346,102 @@
"s8257": "{0}分ごと",
"s8258": "この Strata エンジンには、使おうとしたグラフィックスカード用のコードが含まれていません。",
"s8259": "「実行先」で別のカードを選ぶか、「詳細」を開いて、見つかったカードとエンジンの対応状況を確認してください。",
"s8260": "このスイッチはアプリでは何もしません。どのサイトのWebページも、「配信」に表示されるAPIをすでに呼び出せます。一部のサイトだけを許可したい場合や、エンジン自身のサーバー(ポート8080)を使う場合は、モデルの設定ファイルに \"cors_origins\": [\"https://your.site\"] を追加してください。"
"s8260": "このスイッチはアプリでは何もしません。どのサイトのWebページも、「配信」に表示されるAPIをすでに呼び出せます。一部のサイトだけを許可したい場合や、エンジン自身のサーバー(ポート8080)を使う場合は、モデルの設定ファイルに \"cors_origins\": [\"https://your.site\"] を追加してください。",
"s8301": "APIキーを作成する(推奨)",
"s8302": "APIキーがないと、このネットワーク上のどの機器でもモデルを使えます。",
"s8303": "共有されるのは推論APIだけです。キーを設定している場合、クライアントにはAPIキーが必要です。信頼できるローカルネットワークで使ってください。この接続はHTTPを使います。",
"s8304": "APIを守るキーを作成します。準備ができたらここに戻ります。キーなしで続けることもできますが、その場合はリンクを見つけた人なら誰でもモデルを使えます。",
"s8305": "対応モデルがすでにこのコンピューターにありますか?ファイルがあるフォルダー、または.ggufファイルを1つ選んでください。Strataがファイルを確認し、モデルを準備して読み込みます。コピーやダウンロードは行いません。",
"s8306": "GGUFファイルのフォルダー、または.ggufファイル1つ",
"s8307": "フォルダーまたはファイルのフルパス",
"s8308": "APIキーがないと、このアドレスに接続できる人なら誰でもモデルを使えます。",
"s8309": "Strataは{0}をモデルの保存先として使えなかったため({1})、モデルは{2}に保存されます。別のフォルダーは設定で選べます。",
"s8310": "ポート{0}はすでに使われています。Strataがすでに起動しているかもしれません。それか別のプログラムを閉じるか、別のポート(STRATA_PORT)でStrataを起動してください。",
"s8311": "Windowsまたはファイアウォールが、Strataによるポート{0}の使用を許可していません。Hyper-V、WSL、Dockerは一部のポート範囲を自分用に確保します(\"netsh int ipv4 show excludedportrange protocol=tcp\"で確認できます)。別のポート(STRATA_PORT)、たとえば8801でStrataを起動してください。",
"s8312": "{0}はこのコンピューターのアドレスではないため、Strataはそこで待ち受けできません。STRATA_BINDを確認してください。",
"s8313": "Strataは{0}:{1}で待ち受けできません({2})。",
"s8339": "モデルフォルダ",
"s8340": "Strata は大きなモデルファイルをここに保存します。",
"s8341": "フォルダを変更",
"s8342": "フォルダを待っています…",
"s8343": "ディスクの使用量",
"s8344": "空き {0}",
"s8345": "(このドライブ)",
"s8346": "モデルの使用量: {0}",
"s8347": "フォルダを変更するには、ダウンロードを完了するか停止してください。",
"s8348": "そのフォルダは見つかりません",
"s8349": "そのフォルダは使えません",
"s8350": "Strata は {0} にファイルを保存できません。",
"s8351": "Strata は {0} を見つけられません。",
"s8352": "現在のフォルダの外にあるフォルダを選んでください。",
"s8353": "ご自分のフォルダ(ドキュメント内や別のドライブ上など)を選んでください。",
"s8354": "ドライブが接続されているか確認してから、もう一度フォルダを選んでください。モデルには手を加えていません。",
"s8355": "このフォルダをモデル用に使いますか?",
"s8356": "新しいフォルダ",
"s8357": "このドライブの空き: {0}",
"s8358": "ドライブ全体 {0} を選びました。Strata は専用のフォルダにファイルを置くため、モデルは {1} に保存されます。",
"s8359": "次に 3 つの選択肢が表示されます。",
"s8360": "モデルを移動する",
"s8361": "両方のフォルダを使う",
"s8362": "空の状態で始める",
"s8363": "モデルを移動しています",
"s8364": "移動を停止",
"s8365": "{0} / {1} GB",
"s8366": "残り 1 分未満",
"s8367": "残り約 1 分",
"s8368": "残り約 {0} 分",
"s8369": "残り約 {0} 時間",
"s8370": "Strata を開いたままにしてください。ほかのアプリは使い続けられます。移動が終わるまでモデルは読み込めません。",
"s8371": "コピー中: {0}、ファイル {1} / {2}",
"s8372": "{0} から {1} へ",
"s8373": "モデルをそこへ移動する",
"s8374": "移動するモデルがありません。",
"s8375": "Strata はモデル {0} を新しいフォルダへ移動します。同じドライブなので、すぐに終わります。",
"s8376": "Strata はモデル {0} を新しいフォルダへコピーし、確認してから古いコピーを削除します。",
"s8377": "追加の空き容量は不要です。",
"s8378": "新しいフォルダに {0} の空きが必要です。現在の空き: {1}。",
"s8379": "今の場所に残し、新しいフォルダも使う",
"s8380": "コピーは行いません。今あるモデルはそのまま使え、新しいダウンロードは新しいフォルダに保存されます。",
"s8381": "今は空き容量は不要です。新しいダウンロードは {1} に収まる必要があります。",
"s8382": "今は空き容量は不要です。",
"s8383": "今後は新しいフォルダを使い、今のモデルは一覧に表示しません。古いファイルは削除されません。",
"s8384": "今は空き容量は不要です。あとでダウンロードするモデルごとに、その分の空きが必要です。",
"s8385": "モデルには {0} が必要ですが、このドライブの空きは {1} です。",
"s8386": "そこで約 {0} を空けるか、別のフォルダを選ぶか、ほかの 2 つの選択肢のどちらかを選んでください。",
"s8387": "モデルをどう扱うか",
"s8388": "実行中のモデルは先に停止されます。移動が終わったらもう一度読み込んでください。",
"s8389": "移動対象: {0}。",
"s8390": "空き容量は {0} があるドライブで測定しています。",
"s8391": "元のフォルダ: {0}",
"s8392": "Strata は 1 ファイルずつコピーし、サイズを確認してから古いファイルを削除します。",
"s8393": "いつでも停止できます。移動済みのファイルはそのまま使えます。",
"s8394": "ドライブの空き容量が足りなくなりました",
"s8395": "移動が停止しました",
"s8396": "{1} を移動したところで {0} がいっぱいになったため、移動を停止しました。",
"s8397": "モデルを移動できませんでした。",
"s8398": "失われたものはありません。移動済みのモデルは新しいフォルダにあり、残りは {0} にあります。途中までコピーされたファイルは削除しました。{1} の空きを増やすか別のフォルダを選んで、もう一度お試しください。",
"s8399": "失われたものはありません。モデルはすべて {0} に残っており、途中までコピーされたファイルは削除しました。{1} の空きを増やすか別のフォルダを選んで、もう一度お試しください。",
"s8400": "失われたものはありません。移動されなかったモデルは {0} に残っています。別のフォルダを選んで、もう一度お試しください。",
"s8401": "移動を停止しました",
"s8402": "失われたものはありません。",
"s8403": "{0} は新しいフォルダにあります。",
"s8404": "{0} は元のフォルダに残っています。",
"s8405": "どちらも使えます。",
"s8406": "どちらのフォルダのモデルも通常どおり一覧に表示されます。移動の続きは、あとで「フォルダを変更」から行えます。",
"s8407": "モデルを移動しました",
"s8408": "{0} が {1} に移動しました",
"s8409": "古いコピーを削除し、{1} の空きが {0} 増えました。",
"s8410": "Strata は {0} も使うようになりました。新しいダウンロードはそこに保存され、今のモデルはそのままの場所に残ります。",
"s8411": "Strata は {0} を使うようになりました。古いモデルファイルは {1} に残っており、Strata が削除することはありません。",
"s8412": "モデルフォルダの変更は Strata アプリの機能です。",
"s8413": "モデルが実行中です。先に停止してから、フォルダを変更してください。",
"s8414": "モデルフォルダを選んでください。",
"s8415": "モデルをどうするか選んでください。",
"s8416": "この選択肢はここでは使えません。",
"s8417": "移動が中断されました。完了するか、中止してください。",
"s8418": "Strata がモデルを {0} から {1} へ移動している途中で止まりました。失われたものはありません。",
"s8419": "移動を完了する",
"s8420": "中止する",
"s8421": "完了すると、すべてのモデルが {1} に入ります。中止すると、モデルは {0} に残り、{1} の不完全なコピーが削除されます。",
"s8422": "不完全なコピーを削除しました。モデルは {0} にあります。"
}
+98 -1
View File
@@ -3346,5 +3346,102 @@
"s8257": "{0}분마다",
"s8258": "이 Strata 엔진에는 사용하려던 그래픽 카드용 코드가 없습니다.",
"s8259": "“실행 장치”에서 다른 카드를 고르거나, “세부 정보”에서 찾은 카드와 엔진이 지원하는 카드를 확인하세요.",
"s8260": "이 스위치는 앱에서는 아무 일도 하지 않습니다. 어느 사이트의 웹 페이지든 ‘API 서비스’에 표시된 API를 이미 호출할 수 있습니다. 일부 사이트만 허용하거나 엔진의 자체 서버(포트 8080)를 쓰려면 모델의 설정 파일에 \"cors_origins\": [\"https://your.site\"] 를 추가하세요."
"s8260": "이 스위치는 앱에서는 아무 일도 하지 않습니다. 어느 사이트의 웹 페이지든 ‘API 서비스’에 표시된 API를 이미 호출할 수 있습니다. 일부 사이트만 허용하거나 엔진의 자체 서버(포트 8080)를 쓰려면 모델의 설정 파일에 \"cors_origins\": [\"https://your.site\"] 를 추가하세요.",
"s8301": "API 키 만들기(권장)",
"s8302": "API 키가 없으면 이 네트워크의 모든 기기가 모델을 사용할 수 있습니다.",
"s8303": "추론 API만 공유됩니다. 키를 설정한 경우 클라이언트에 API 키가 필요합니다. 신뢰할 수 있는 로컬 네트워크에서 사용하세요. 이 연결은 HTTP를 사용합니다.",
"s8304": "API를 보호할 키를 만드세요. 준비되면 이 화면으로 돌아옵니다. 키 없이 계속할 수도 있지만, 그러면 링크를 찾은 누구나 모델을 사용할 수 있습니다.",
"s8305": "이 컴퓨터에 이미 지원되는 모델이 있나요? 파일이 있는 폴더나 .gguf 파일 하나를 선택하세요. Strata가 파일을 확인하고 모델을 준비해 불러옵니다. 복사하거나 다운로드하지 않습니다.",
"s8306": "GGUF 파일이 있는 폴더 또는 .gguf 파일 하나",
"s8307": "폴더 또는 파일의 전체 경로",
"s8308": "API 키가 없으면 이 주소에 접속할 수 있는 누구나 모델을 사용할 수 있습니다.",
"s8309": "Strata가 {0}을(를) 모델 폴더로 사용할 수 없어({1}) 모델을 {2}에 저장합니다. 설정에서 다른 폴더를 고를 수 있습니다.",
"s8310": "포트 {0}을(를) 이미 사용 중입니다. Strata가 이미 실행 중일 수 있습니다. 해당 프로그램을 닫거나 다른 포트(STRATA_PORT)로 Strata를 시작하세요.",
"s8311": "Windows 또는 방화벽이 Strata의 포트 {0} 사용을 허용하지 않습니다. Hyper-V, WSL, Docker는 일부 포트 범위를 자체적으로 예약합니다(\"netsh int ipv4 show excludedportrange protocol=tcp\" 참고). 다른 포트(STRATA_PORT), 예를 들어 8801로 Strata를 시작하세요.",
"s8312": "{0}은(는) 이 컴퓨터의 주소가 아니어서 Strata가 해당 주소에서 연결을 받을 수 없습니다. STRATA_BIND를 확인하세요.",
"s8313": "Strata가 {0}:{1}에서 연결을 받을 수 없습니다({2}).",
"s8339": "모델 폴더",
"s8340": "Strata는 큰 모델 파일을 여기에 저장합니다.",
"s8341": "폴더 변경",
"s8342": "폴더를 기다리는 중…",
"s8343": "디스크 사용량",
"s8344": "{0} 여유",
"s8345": "(이 드라이브)",
"s8346": "모델이 차지하는 공간: {0}",
"s8347": "폴더를 바꾸려면 다운로드를 끝내거나 중지하세요.",
"s8348": "해당 폴더가 없습니다",
"s8349": "해당 폴더는 사용할 수 없습니다",
"s8350": "Strata가 {0}에 파일을 저장할 수 없습니다.",
"s8351": "Strata가 {0}을(를) 찾을 수 없습니다.",
"s8352": "현재 폴더 밖에 있는 폴더를 선택하세요.",
"s8353": "내 소유의 폴더(예: 문서 폴더나 다른 드라이브)를 선택하세요.",
"s8354": "드라이브가 연결되어 있는지 확인한 뒤 폴더를 다시 선택하세요. 모델은 그대로입니다.",
"s8355": "이 폴더를 모델용으로 사용할까요?",
"s8356": "새 폴더",
"s8357": "이 드라이브의 여유 공간: {0}",
"s8358": "드라이브 전체 {0}을(를) 선택했습니다. Strata는 자체 폴더에 파일을 보관하므로 모델은 {1}에 저장됩니다.",
"s8359": "다음으로 세 가지 선택지가 나옵니다.",
"s8360": "내 모델 이동",
"s8361": "두 폴더 모두 사용",
"s8362": "빈 상태로 시작",
"s8363": "모델을 이동하는 중",
"s8364": "이동 중지",
"s8365": "{0} / {1} GB",
"s8366": "1분 미만 남음",
"s8367": "약 1분 남음",
"s8368": "약 {0}분 남음",
"s8369": "약 {0}시간 남음",
"s8370": "Strata를 열어 두세요. 다른 앱은 계속 사용할 수 있습니다. 이동이 끝날 때까지 모델을 불러올 수 없습니다.",
"s8371": "복사 중: {0}, 파일 {1}/{2}",
"s8372": "{0}에서 {1}(으)로",
"s8373": "내 모델을 그쪽으로 이동",
"s8374": "이동할 모델이 없습니다.",
"s8375": "Strata가 모델 {0}을(를) 새 폴더로 옮깁니다. 같은 드라이브라 금방 끝납니다.",
"s8376": "Strata가 모델 {0}을(를) 새 폴더로 복사하고 확인한 뒤 기존 사본을 삭제합니다.",
"s8377": "추가 공간이 필요 없습니다.",
"s8378": "새 폴더에 {0}의 여유 공간이 필요합니다. 현재 {1}.",
"s8379": "지금 위치에 두고 새 폴더도 함께 사용",
"s8380": "아무것도 복사하지 않습니다. 현재 모델은 그대로 동작하고, 새로 받는 모델은 새 폴더에 저장됩니다.",
"s8381": "지금은 공간이 필요 없습니다. 새 다운로드는 {1} 안에 들어가야 합니다.",
"s8382": "지금은 공간이 필요 없습니다.",
"s8383": "앞으로 새 폴더를 사용하며 현재 모델은 목록에 표시하지 않습니다. 기존 파일은 삭제되지 않습니다.",
"s8384": "지금은 공간이 필요 없습니다. 나중에 받는 모델마다 각자의 공간이 필요합니다.",
"s8385": "모델에 {0}이(가) 필요한데 이 드라이브의 여유 공간은 {1}입니다.",
"s8386": "그곳에서 약 {0}을(를) 비우거나, 다른 폴더를 선택하거나, 나머지 두 가지 중 하나를 고르세요.",
"s8387": "모델을 어떻게 할까요",
"s8388": "실행 중인 모델은 먼저 중지됩니다. 이동이 끝나면 다시 불러오세요.",
"s8389": "{0}이(가) 이동됩니다.",
"s8390": "여유 공간은 {0}이(가) 있는 드라이브를 기준으로 측정합니다.",
"s8391": "기존 폴더: {0}",
"s8392": "Strata는 파일을 하나씩 복사하고, 크기를 확인한 뒤에 기존 파일을 삭제합니다.",
"s8393": "언제든 중지할 수 있으며, 이미 이동한 파일은 계속 사용할 수 있습니다.",
"s8394": "드라이브의 공간이 부족합니다",
"s8395": "이동이 중지되었습니다",
"s8396": "{1}을(를) 옮긴 뒤 {0}이(가) 가득 차서 이동을 중지했습니다.",
"s8397": "모델을 이동하지 못했습니다.",
"s8398": "잃어버린 것은 없습니다. 이미 이동한 모델은 새 폴더에 있고 나머지는 {0}에 그대로 있으며, 반쯤 복사된 파일은 삭제했습니다. {1}의 공간을 확보하거나 다른 폴더를 선택한 뒤 다시 시도하세요.",
"s8399": "잃어버린 것은 없습니다. 모든 모델이 {0}에 그대로 있으며, 반쯤 복사된 파일은 삭제했습니다. {1}의 공간을 확보하거나 다른 폴더를 선택한 뒤 다시 시도하세요.",
"s8400": "잃어버린 것은 없습니다. 이동하지 못한 모델은 {0}에 그대로 있습니다. 다른 폴더를 선택해 다시 시도하세요.",
"s8401": "이동 중지됨",
"s8402": "잃어버린 것은 없습니다.",
"s8403": "{0}은(는) 새 폴더에 있습니다.",
"s8404": "{0}은(는) 아직 기존 폴더에 있습니다.",
"s8405": "둘 다 사용할 수 있습니다.",
"s8406": "두 폴더의 모델 모두 평소처럼 목록에 표시됩니다. 나머지 이동은 나중에 '폴더 변경'으로 마칠 수 있습니다.",
"s8407": "모델 이동이 끝났습니다",
"s8408": "{0}이(가) 이제 {1}에 있습니다",
"s8409": "기존 사본을 삭제했으며 {1}에서 {0}이(가) 다시 확보되었습니다.",
"s8410": "이제 Strata가 {0}도 사용합니다. 새 다운로드는 그곳에 저장되고 현재 모델은 그대로 있습니다.",
"s8411": "이제 Strata가 {0}을(를) 사용합니다. 기존 모델 파일은 {1}에 그대로 있으며 Strata가 삭제하지 않습니다.",
"s8412": "모델 폴더 변경은 Strata 앱의 기능입니다.",
"s8413": "모델이 실행 중입니다. 먼저 중지한 뒤 폴더를 변경하세요.",
"s8414": "모델 폴더를 선택하세요.",
"s8415": "모델을 어떻게 할지 선택하세요.",
"s8416": "여기서는 해당 선택지를 사용할 수 없습니다.",
"s8417": "이동이 중단되었습니다. 마무리하거나 그대로 두세요.",
"s8418": "Strata가 모델을 {0}에서 {1}(으)로 옮기던 중 멈췄습니다. 잃어버린 것은 없습니다.",
"s8419": "이동 마무리",
"s8420": "그대로 두기",
"s8421": "마무리하면 모든 모델이 {1}에 들어갑니다. 그대로 두면 모델은 {0}에 남고 {1}의 불완전한 복사본이 삭제됩니다.",
"s8422": "불완전한 복사본을 삭제했습니다. 모델은 {0}에 있습니다."
}
+98 -1
View File
@@ -3346,5 +3346,102 @@
"s8257": "a cada {0} min",
"s8258": "Este motor do Strata não tem código para a placa de vídeo que tentou usar.",
"s8259": "Escolha outra placa em «Executar em» ou abra os detalhes para ver quais placas foram encontradas e para quais o motor foi compilado.",
"s8260": "Este botão não faz nada no app. Páginas web de qualquer site já podem chamar a API mostrada em API. Para permitir só alguns sites, ou para usar o servidor próprio do motor (porta 8080), adicione \"cors_origins\": [\"https://seu.site\"] ao arquivo de configuração do modelo."
"s8260": "Este botão não faz nada no app. Páginas web de qualquer site já podem chamar a API mostrada em API. Para permitir só alguns sites, ou para usar o servidor próprio do motor (porta 8080), adicione \"cors_origins\": [\"https://seu.site\"] ao arquivo de configuração do modelo.",
"s8301": "Criar uma chave de API (recomendado)",
"s8302": "Sem uma chave de API, qualquer dispositivo desta rede pode usar o seu modelo.",
"s8303": "Apenas a API de inferência é compartilhada. Os clientes precisam da sua chave de API quando houver uma. Use uma rede local confiável; esta conexão usa HTTP.",
"s8304": "Crie uma chave para proteger a sua API. Você voltará aqui quando ela estiver pronta. Também pode continuar sem ela, mas qualquer pessoa que encontrar o link poderá usar o seu modelo.",
"s8305": "Já tem um modelo compatível neste computador? Escolha a pasta com os arquivos ou um dos arquivos .gguf. O Strata verifica os arquivos, prepara o modelo e o carrega. Nada é copiado nem baixado.",
"s8306": "Pasta com os arquivos GGUF ou um arquivo .gguf",
"s8307": "Caminho completo da pasta ou do arquivo",
"s8308": "Sem uma chave de API, qualquer pessoa que consiga acessar este endereço pode usar o seu modelo.",
"s8309": "O Strata não conseguiu usar {0} para os modelos ({1}), então os modelos vão para {2}. Você pode escolher outra pasta em Configurações.",
"s8310": "A porta {0} já está em uso. O Strata pode já estar em execução; feche-o ou o outro programa, ou inicie o Strata com outra porta (STRATA_PORT).",
"s8311": "O Windows ou um firewall não deixa o Strata usar a porta {0}. Hyper-V, WSL e Docker reservam faixas de portas para si (veja \"netsh int ipv4 show excludedportrange protocol=tcp\"). Inicie o Strata com outra porta (STRATA_PORT), por exemplo 8801.",
"s8312": "{0} não é um endereço deste computador, então o Strata não pode escutar nele. Verifique STRATA_BIND.",
"s8313": "O Strata não consegue escutar em {0}:{1} ({2}).",
"s8339": "Pasta de modelos",
"s8340": "O Strata guarda aqui os arquivos grandes dos modelos.",
"s8341": "Alterar pasta",
"s8342": "Aguardando a pasta…",
"s8343": "Uso do disco",
"s8344": "{0} livres",
"s8345": "nesta unidade",
"s8346": "Seus modelos ocupam {0}",
"s8347": "Conclua ou pare o download para alterar a pasta.",
"s8348": "Essa pasta não existe",
"s8349": "Não é possível usar essa pasta",
"s8350": "O Strata não consegue salvar arquivos em {0}.",
"s8351": "O Strata não encontra {0}.",
"s8352": "Escolha uma pasta fora da atual.",
"s8353": "Escolha uma pasta sua, por exemplo em Documentos ou em outra unidade.",
"s8354": "Verifique se a unidade está conectada e escolha a pasta de novo. Seus modelos não foram alterados.",
"s8355": "Usar esta pasta para seus modelos?",
"s8356": "Pasta nova",
"s8357": "{0} livres nesta unidade",
"s8358": "Você escolheu a unidade inteira {0}. O Strata guarda seus arquivos em uma pasta própria, então seus modelos ficam em {1}.",
"s8359": "Em seguida, você verá as três opções.",
"s8360": "Mover meus modelos",
"s8361": "Usar as duas pastas",
"s8362": "Começar vazio",
"s8363": "Movendo seus modelos",
"s8364": "Parar a movimentação",
"s8365": "{0} de {1} GB",
"s8366": "Menos de um minuto restante",
"s8367": "Cerca de um minuto restante",
"s8368": "Cerca de {0} minutos restantes",
"s8369": "Cerca de {0} horas restantes",
"s8370": "Mantenha o Strata aberto. Você pode continuar usando outros aplicativos. Seus modelos só poderão ser carregados quando a movimentação terminar.",
"s8371": "Copiando agora: {0}, arquivo {1} de {2}",
"s8372": "De {0} para {1}",
"s8373": "Mover meus modelos para lá",
"s8374": "Você não tem modelos para mover.",
"s8375": "O Strata move seus {0} de modelos para a pasta nova. É a mesma unidade, então leva só um instante.",
"s8376": "O Strata copia seus {0} de modelos para a pasta nova, confere os arquivos e depois remove as cópias antigas.",
"s8377": "Não precisa de espaço extra.",
"s8378": "Precisa de {0} livres na pasta nova. Você tem {1}.",
"s8379": "Mantê-los onde estão e usar também a pasta nova",
"s8380": "Nada é copiado. Seus modelos atuais continuam funcionando e os novos downloads vão para a pasta nova.",
"s8381": "Não precisa de espaço agora. Os novos downloads precisam caber em {1}.",
"s8382": "Não precisa de espaço agora.",
"s8383": "O Strata passa a usar a pasta nova e não lista seus modelos atuais. Seus arquivos antigos não são apagados.",
"s8384": "Não precisa de espaço agora. Cada modelo baixado depois precisa do próprio espaço.",
"s8385": "Seus modelos precisam de {0}, e esta unidade tem {1} livres.",
"s8386": "Libere cerca de {0} lá, escolha outra pasta ou use uma das outras duas opções.",
"s8387": "O que deve acontecer com seus modelos",
"s8388": "Um modelo em execução é parado antes; carregue-o de novo quando a movimentação terminar.",
"s8389": "{0} seriam movidos.",
"s8390": "O espaço livre é medido na unidade que contém {0}.",
"s8391": "Pasta antiga: {0}",
"s8392": "O Strata copia um arquivo por vez e confere o tamanho antes de remover o antigo.",
"s8393": "Você pode parar a qualquer momento; os arquivos já movidos continuam utilizáveis.",
"s8394": "A unidade ficou sem espaço",
"s8395": "A movimentação parou",
"s8396": "{0} ficou cheia após {1}, então a movimentação parou.",
"s8397": "Não foi possível mover os modelos.",
"s8398": "Nada foi perdido. Os modelos já movidos estão na pasta nova, o restante continua em {0} e o arquivo copiado pela metade foi removido. Libere espaço em {1} ou escolha outra pasta e tente de novo.",
"s8399": "Nada foi perdido. Todos os seus modelos continuam em {0} e o arquivo copiado pela metade foi removido. Libere espaço em {1} ou escolha outra pasta e tente de novo.",
"s8400": "Nada foi perdido. Os modelos que não foram movidos continuam em {0}. Escolha outra pasta para tentar de novo.",
"s8401": "Movimentação interrompida",
"s8402": "Nada foi perdido.",
"s8403": "{0} está na pasta nova.",
"s8404": "{0} ainda está na pasta antiga.",
"s8405": "Ambos funcionam.",
"s8406": "Os modelos das duas pastas aparecem normalmente. Você pode concluir a movimentação depois, em “Alterar pasta”.",
"s8407": "Seus modelos foram movidos",
"s8408": "{0} agora estão em {1}",
"s8409": "As cópias antigas foram removidas e {0} voltaram a ficar livres em {1}.",
"s8410": "O Strata agora também usa {0}. Os novos downloads vão para lá, e seus modelos atuais ficam onde estão.",
"s8411": "O Strata agora usa {0}. Seus arquivos de modelo antigos continuam em {1}; o Strata não os apaga.",
"s8412": "Alterar a pasta de modelos faz parte do aplicativo Strata.",
"s8413": "Há um modelo em execução. Pare-o primeiro e depois altere a pasta.",
"s8414": "Escolha uma pasta de modelos.",
"s8415": "Escolha o que fazer com seus modelos.",
"s8416": "Essa opção não é possível aqui.",
"s8417": "Uma mudança foi interrompida. Termine-a ou deixe como estava.",
"s8418": "O Strata estava mudando seus modelos de {0} para {1} quando parou. Nada foi perdido.",
"s8419": "Terminar a mudança",
"s8420": "Deixar como está",
"s8421": "Terminar coloca todos os seus modelos em {1}. Deixar como está mantém os modelos em {0} e remove as cópias parciais de {1}.",
"s8422": "As cópias parciais foram removidas. Seus modelos estão em {0}."
}
+98 -1
View File
@@ -3346,5 +3346,102 @@
"s8257": "каждые {0} мин",
"s8258": "В этом движке Strata нет кода для видеокарты, которую он попытался использовать.",
"s8259": "Выберите другую карту в разделе «Запускать на» или откройте «Подробности»: там указано, какие карты найдены и для каких собран движок.",
"s8260": "Этот переключатель в приложении ничего не делает. Веб-страницы любого сайта уже могут обращаться к API, который показан в «API». Чтобы разрешить только некоторые сайты или использовать собственный сервер движка (порт 8080), добавьте \"cors_origins\": [\"https://your.site\"] в файл настроек модели."
"s8260": "Этот переключатель в приложении ничего не делает. Веб-страницы любого сайта уже могут обращаться к API, который показан в «API». Чтобы разрешить только некоторые сайты или использовать собственный сервер движка (порт 8080), добавьте \"cors_origins\": [\"https://your.site\"] в файл настроек модели.",
"s8301": "Создать ключ API (рекомендуется)",
"s8302": "Без ключа API любое устройство в этой сети сможет пользоваться вашей моделью.",
"s8303": "Доступен только API инференса. Если ключ задан, клиентам нужен ваш ключ API. Используйте доверенную локальную сеть: это соединение работает по HTTP.",
"s8304": "Создайте ключ, чтобы защитить API. Когда он будет готов, вы вернётесь сюда. Можно продолжить и без ключа, но тогда любой, кто найдёт ссылку, сможет пользоваться вашей моделью.",
"s8305": "Уже есть поддерживаемая модель на этом компьютере? Выберите папку с её файлами или один из файлов .gguf. Strata проверит их, подготовит модель и загрузит её. Ничего не копируется и не скачивается.",
"s8306": "Папка с файлами GGUF или один файл .gguf",
"s8307": "Полный путь к папке или файлу",
"s8308": "Без ключа API любой, кто может обратиться к этому адресу, сможет пользоваться вашей моделью.",
"s8309": "Strata не смогла использовать {0} для моделей ({1}), поэтому модели сохраняются в {2}. Другую папку можно выбрать в настройках.",
"s8310": "Порт {0} уже занят. Возможно, Strata уже запущена; закройте её или другую программу либо запустите Strata с другим портом (STRATA_PORT).",
"s8311": "Windows или брандмауэр не разрешает Strata использовать порт {0}. Hyper-V, WSL и Docker резервируют для себя диапазоны портов (см. \"netsh int ipv4 show excludedportrange protocol=tcp\"). Запустите Strata с другим портом (STRATA_PORT), например 8801.",
"s8312": "{0} не является адресом этого компьютера, поэтому Strata не может его прослушивать. Проверьте STRATA_BIND.",
"s8313": "Strata не может прослушивать {0}:{1} ({2}).",
"s8339": "Папка моделей",
"s8340": "Strata хранит здесь большие файлы моделей.",
"s8341": "Сменить папку",
"s8342": "Ждём выбор папки…",
"s8343": "Занято на диске",
"s8344": "свободно {0}",
"s8345": "на этом диске",
"s8346": "Ваши модели занимают {0}",
"s8347": "Чтобы сменить папку, дождитесь конца загрузки или остановите её.",
"s8348": "Такой папки нет",
"s8349": "Эту папку использовать нельзя",
"s8350": "Strata не может сохранять файлы в {0}.",
"s8351": "Strata не находит {0}.",
"s8352": "Выберите папку вне текущей.",
"s8353": "Выберите свою папку, например в «Документах» или на другом диске.",
"s8354": "Проверьте, что диск подключён, и выберите папку снова. Ваши модели не затронуты.",
"s8355": "Использовать эту папку для моделей?",
"s8356": "Новая папка",
"s8357": "Свободно на этом диске: {0}",
"s8358": "Вы выбрали весь диск {0}. Strata хранит свои файлы в отдельной папке, поэтому модели будут в {1}.",
"s8359": "Дальше будут три варианта.",
"s8360": "Переместить мои модели",
"s8361": "Использовать обе папки",
"s8362": "Начать с пустой",
"s8363": "Перемещение моделей",
"s8364": "Остановить перемещение",
"s8365": "{0} из {1} ГБ",
"s8366": "Осталось меньше минуты",
"s8367": "Осталось около минуты",
"s8368": "Осталось около {0} мин.",
"s8369": "Осталось около {0} ч.",
"s8370": "Не закрывайте Strata. Другими приложениями можно пользоваться. Пока перемещение не закончится, модели загрузить нельзя.",
"s8371": "Сейчас копируется: {0}, файл {1} из {2}",
"s8372": "Из {0} в {1}",
"s8373": "Переместить мои модели туда",
"s8374": "Нет моделей для перемещения.",
"s8375": "Strata переместит ваши модели ({0}) в новую папку. Это тот же диск, поэтому это займёт мгновение.",
"s8376": "Strata скопирует ваши модели ({0}) в новую папку, проверит их и удалит старые копии.",
"s8377": "Дополнительное место не нужно.",
"s8378": "В новой папке нужно {0} свободного места. Сейчас доступно {1}.",
"s8379": "Оставить на месте и дополнительно использовать новую папку",
"s8380": "Ничего не копируется. Текущие модели продолжают работать, а новые загрузки идут в новую папку.",
"s8381": "Сейчас место не нужно. Новые загрузки должны поместиться в {1}.",
"s8382": "Сейчас место не нужно.",
"s8383": "Отныне Strata использует новую папку и не показывает текущие модели. Старые файлы не удаляются.",
"s8384": "Сейчас место не нужно. Каждой модели, которую вы загрузите позже, понадобится своё место.",
"s8385": "Вашим моделям нужно {0}, а на этом диске свободно {1}.",
"s8386": "Освободите там около {0}, выберите другую папку или один из двух других вариантов.",
"s8387": "Что сделать с вашими моделями",
"s8388": "Работающая модель сначала останавливается; загрузите её снова после перемещения.",
"s8389": "Будет перемещено: {0}.",
"s8390": "Свободное место измеряется на диске, где находится {0}.",
"s8391": "Старая папка: {0}",
"s8392": "Strata копирует файлы по одному и проверяет размер, прежде чем удалить старый.",
"s8393": "Остановить можно в любой момент; уже перемещённые файлы остаются пригодными.",
"s8394": "На диске закончилось место",
"s8395": "Перемещение остановлено",
"s8396": "Диск {0} заполнился после {1}, поэтому перемещение остановлено.",
"s8397": "Не удалось переместить модели.",
"s8398": "Ничего не потеряно. Уже перемещённые модели в новой папке, остальные по-прежнему в {0}, а наполовину скопированный файл удалён. Освободите место на {1} или выберите другую папку и повторите попытку.",
"s8399": "Ничего не потеряно. Все ваши модели по-прежнему в {0}, а наполовину скопированный файл удалён. Освободите место на {1} или выберите другую папку и повторите попытку.",
"s8400": "Ничего не потеряно. Неперемещённые модели по-прежнему в {0}. Выберите другую папку и повторите попытку.",
"s8401": "Перемещение остановлено",
"s8402": "Ничего не потеряно.",
"s8403": "{0}: в новой папке.",
"s8404": "{0}: всё ещё в старой папке.",
"s8405": "Работают оба.",
"s8406": "Модели из обеих папок отображаются как обычно. Закончить перемещение можно позже через «Сменить папку».",
"s8407": "Модели перемещены",
"s8408": "{0} теперь находятся в {1}",
"s8409": "Старые копии удалены, на {1} снова свободно {0}.",
"s8410": "Теперь Strata использует и {0}. Новые загрузки идут туда, а текущие модели остаются на месте.",
"s8411": "Теперь Strata использует {0}. Старые файлы моделей остаются в {1}; Strata их не удаляет.",
"s8412": "Смена папки моделей доступна в приложении Strata.",
"s8413": "Модель запущена. Сначала остановите её, затем смените папку.",
"s8414": "Выберите папку моделей.",
"s8415": "Выберите, что сделать с моделями.",
"s8416": "Этот вариант здесь невозможен.",
"s8417": "Перенос был прерван. Завершите его или оставьте как есть.",
"s8418": "Strata переносил ваши модели из {0} в {1}, когда остановился. Ничего не потеряно.",
"s8419": "Завершить перенос",
"s8420": "Оставить как есть",
"s8421": "Если завершить, все модели окажутся в {1}. Если оставить, модели останутся в {0}, а неполные копии в {1} будут удалены.",
"s8422": "Неполные копии удалены. Ваши модели находятся в {0}."
}
+98 -1
View File
@@ -3346,5 +3346,102 @@
"s8257": "每 {0} 分钟",
"s8258": "此 Strata 引擎没有适用于它尝试使用的显卡的代码。",
"s8259": "请在“运行于”中选择另一块显卡,或打开详情,查看找到了哪些显卡以及引擎支持哪些显卡。",
"s8260": "这个开关在应用中不起作用。任何网站的网页都已经可以调用“API 服务”页面显示的 API。如果只想允许部分网站,或要使用引擎自带的服务器(端口 8080),请在模型的配置文件中添加 \"cors_origins\": [\"https://your.site\"]。"
"s8260": "这个开关在应用中不起作用。任何网站的网页都已经可以调用“API 服务”页面显示的 API。如果只想允许部分网站,或要使用引擎自带的服务器(端口 8080),请在模型的配置文件中添加 \"cors_origins\": [\"https://your.site\"]。",
"s8301": "创建 API 密钥(推荐)",
"s8302": "没有 API 密钥时,此网络中的任何设备都可以使用你的模型。",
"s8303": "只共享推理 API。如果设置了密钥,客户端需要你的 API 密钥。请在可信的本地网络中使用;此连接使用 HTTP。",
"s8304": "创建一个密钥来保护你的 API。准备好后你会回到这里。你也可以不创建而继续,但这样任何找到链接的人都可以使用你的模型。",
"s8305": "这台电脑上已经有受支持的模型了吗?请选择存放其文件的文件夹,或其中一个 .gguf 文件。Strata 会检查文件、准备模型并加载。不会复制或下载任何内容。",
"s8306": "包含 GGUF 文件的文件夹,或一个 .gguf 文件",
"s8307": "文件夹或文件的完整路径",
"s8308": "没有 API 密钥时,任何能访问此地址的人都可以使用你的模型。",
"s8309": "Strata 无法使用 {0} 存放模型({1}),因此模型会保存到 {2}。你可以在设置中选择其他文件夹。",
"s8310": "端口 {0} 已被占用。Strata 可能已经在运行;请关闭它或另一个程序,或用其他端口(STRATA_PORT)启动 Strata。",
"s8311": "Windows 或防火墙不允许 Strata 使用端口 {0}。Hyper-V、WSL 和 Docker 会为自己保留一些端口范围(请查看 \"netsh int ipv4 show excludedportrange protocol=tcp\")。请用其他端口(STRATA_PORT)启动 Strata,例如 8801。",
"s8312": "{0} 不是这台电脑的地址,Strata 无法在其上监听。请检查 STRATA_BIND。",
"s8313": "Strata 无法在 {0}:{1} 上监听({2})。",
"s8339": "模型文件夹",
"s8340": "Strata 会把体积较大的模型文件保存在这里。",
"s8341": "更改文件夹",
"s8342": "正在等待选择文件夹…",
"s8343": "磁盘使用情况",
"s8344": "可用 {0}",
"s8345": "(此驱动器)",
"s8346": "你的模型占用 {0}",
"s8347": "请先完成或停止下载,再更改文件夹。",
"s8348": "找不到该文件夹",
"s8349": "无法使用该文件夹",
"s8350": "Strata 无法在 {0} 中保存文件。",
"s8351": "Strata 找不到 {0}。",
"s8352": "请选择当前文件夹之外的文件夹。",
"s8353": "请选择你自己的文件夹,例如“文档”中的文件夹或其他驱动器上的文件夹。",
"s8354": "请检查驱动器是否已连接,然后重新选择文件夹。你的模型没有受到影响。",
"s8355": "要用这个文件夹存放你的模型吗?",
"s8356": "新文件夹",
"s8357": "此驱动器可用 {0}",
"s8358": "你选择了整个驱动器 {0}。Strata 会把文件放在自己的文件夹里,因此你的模型将存放在 {1}。",
"s8359": "接下来会出现三个选项。",
"s8360": "移动我的模型",
"s8361": "同时使用两个文件夹",
"s8362": "从空文件夹开始",
"s8363": "正在移动你的模型",
"s8364": "停止移动",
"s8365": "{0} / {1} GB",
"s8366": "剩余不到 1 分钟",
"s8367": "大约剩余 1 分钟",
"s8368": "大约剩余 {0} 分钟",
"s8369": "大约剩余 {0} 小时",
"s8370": "请保持 Strata 打开。你可以继续使用其他应用。移动完成之前无法加载你的模型。",
"s8371": "正在复制:{0},第 {1} 个文件,共 {2} 个",
"s8372": "从 {0} 到 {1}",
"s8373": "把我的模型移到那里",
"s8374": "没有可移动的模型。",
"s8375": "Strata 会把你的 {0} 模型移到新文件夹。因为是同一个驱动器,只需片刻。",
"s8376": "Strata 会把你的 {0} 模型复制到新文件夹,检查无误后再删除旧副本。",
"s8377": "不需要额外空间。",
"s8378": "新文件夹需要 {0} 可用空间。你现有 {1}。",
"s8379": "保留在原处,同时使用新文件夹",
"s8380": "不会复制任何文件。现有模型继续可用,新下载的模型会保存到新文件夹。",
"s8381": "目前不需要空间。新下载的模型必须能放进 {1}。",
"s8382": "目前不需要空间。",
"s8383": "从现在起 Strata 使用新文件夹,不再列出你现有的模型。旧文件不会被删除。",
"s8384": "目前不需要空间。之后下载的每个模型都需要各自的空间。",
"s8385": "你的模型需要 {0},此驱动器只有 {1} 可用。",
"s8386": "请在那里腾出约 {0},或选择其他文件夹,或选用另外两个选项之一。",
"s8387": "如何处理你的模型",
"s8388": "正在运行的模型会先被停止;移动完成后请重新加载。",
"s8389": "将移动:{0}。",
"s8390": "可用空间是按 {0} 所在的驱动器计算的。",
"s8391": "旧文件夹:{0}",
"s8392": "Strata 一次复制一个文件,检查大小后才会删除旧文件。",
"s8393": "你可以随时停止;已经移动的文件仍可使用。",
"s8394": "驱动器空间已用完",
"s8395": "移动已停止",
"s8396": "移动 {1} 后 {0} 已满,因此移动已停止。",
"s8397": "无法移动模型。",
"s8398": "没有任何内容丢失。已移动的模型在新文件夹中,其余的仍在 {0},复制到一半的文件已被删除。请在 {1} 上腾出空间或选择其他文件夹,然后重试。",
"s8399": "没有任何内容丢失。你的所有模型仍在 {0},复制到一半的文件已被删除。请在 {1} 上腾出空间或选择其他文件夹,然后重试。",
"s8400": "没有任何内容丢失。未移动的模型仍在 {0}。请选择其他文件夹后重试。",
"s8401": "移动已停止",
"s8402": "没有任何内容丢失。",
"s8403": "{0} 在新文件夹中。",
"s8404": "{0} 仍在旧文件夹中。",
"s8405": "两处都能使用。",
"s8406": "两个文件夹中的模型都会照常显示。你可以稍后通过“更改文件夹”继续移动。",
"s8407": "你的模型已移动",
"s8408": "{0} 现已位于 {1}",
"s8409": "旧副本已删除,{1} 上重新空出了 {0}。",
"s8410": "Strata 现在也会使用 {0}。新下载的模型会保存到那里,你现有的模型仍留在原处。",
"s8411": "Strata 现在使用 {0}。旧的模型文件仍在 {1},Strata 不会删除它们。",
"s8412": "更改模型文件夹是 Strata 应用的功能。",
"s8413": "有模型正在运行。请先停止它,再更改文件夹。",
"s8414": "请选择模型文件夹。",
"s8415": "请选择如何处理你的模型。",
"s8416": "此处无法使用该选项。",
"s8417": "移动被中断了。请完成它,或保持原样。",
"s8418": "Strata 正在把你的模型从 {0} 移到 {1} 时停止了。没有任何内容丢失。",
"s8419": "完成移动",
"s8420": "保持原样",
"s8421": "完成后,所有模型都会放到 {1}。保持原样则模型留在 {0},并删除 {1} 中不完整的副本。",
"s8422": "已删除不完整的副本。你的模型在 {0}。"
}
+2 -2
View File
@@ -86,7 +86,7 @@ export function ServingScreen() {
<section className="st-card serving-overview"><dl className="summary-list"><div><dt>{tr("API base URL")}</dt><dd className="row"><code style={{ overflowWrap: 'anywhere' }}>{serving.baseUrl}</code><IconBtn name="copy" title={tr("Copy API base URL")} onClick={() => void copyConnectionValue(serving.baseUrl, 'API base URL')}/></dd></div>{tr(!multipleModels ? <div><dt>{tr("Model ID")}</dt><dd className="row"><code>{loaded?.apiModelId ?? 'No model loaded'}</code><IconBtn name="copy" title={tr("Copy Model ID")} disabled={!loaded} onClick={() => {
if (loaded)
void copyConnectionValue(loaded.apiModelId, 'Model ID');
}}/></dd></div> : null)}<div><dt>{tr("Status")}</dt><dd><span className="api-status" data-active={serving.running}><span className="api-status__dot"/>{tr(serving.running ? 'API listening' : 'API stopped')} · {tr(multipleModels ? `${runtime?.instances.length} models loaded` : loaded ? 'Model ready' : 'Model not ready')}</span></dd></div><div><dt>{tr("Local network")}</dt><dd className="row"><span className="request-status" data-state={serving.sharing?.active ? "shared" : "queued"}>{tr(serving.sharing?.active ? "Shared on local network" : "Off")}</span><Btn size="sm" onClick={() => { setError(''); setSharingOpen(true); }}>{tr(serving.sharing?.active ? "Manage / stop" : "Share")}</Btn></dd></div>{tr(serving.tunnel?.status === "connected" && serving.tunnel.url ? <div><dt>{tr("Cloudflare tunnel")}</dt><dd className="row"><code style={{ overflowWrap: "anywhere" }}>{serving.tunnel.url}</code><IconBtn name="copy" title={tr("Copy Cloudflare tunnel URL")} onClick={() => void navigator.clipboard.writeText(serving.tunnel!.url!)}/><IconBtn name="settings" title={tr("Manage Cloudflare tunnel")} onClick={() => setCloudflareOpen(true)}/></dd></div> : serving.tunnel?.status === "starting" ? <div><dt>{tr("Cloudflare tunnel")}</dt><dd role="status">{tr("Connecting\u2026")}</dd></div> : null)}<div className="serving-access-row"><dt>{tr("API key")}</dt><dd><div className="serving-access-status">{tr(serving.access.apiKeySet ? <span className="small muted">{tr("Required \u00B7 ")}{tr(serving.access.apiKeyHint)}</span> : null)}<div className="row"><Btn size="sm" onClick={() => { setError(''); generateKey(); setKeyOpen(true); }}>{tr(serving.access.apiKeySet ? 'Change key' : 'Set key')}</Btn>{tr(serving.access.apiKeySet ? <Btn size="sm" disabled={serving.access.otherDevices} onClick={() => { setError(''); setRemoveKeyOpen(true); }}>{tr("Remove key")}</Btn> : null)}</div></div>{tr(serving.access.otherDevices ? <span className="xs muted">{tr("Keep a key while the API is available to other devices.")}</span> : null)}</dd></div></dl></section>
}}/></dd></div> : null)}<div><dt>{tr("Status")}</dt><dd><span className="api-status" data-active={serving.running}><span className="api-status__dot"/>{tr(serving.running ? 'API listening' : 'API stopped')} · {tr(multipleModels ? `${runtime?.instances.length} models loaded` : loaded ? 'Model ready' : 'Model not ready')}</span></dd></div><div><dt>{tr("Local network")}</dt><dd className="row"><span className="request-status" data-state={serving.sharing?.active ? "shared" : "queued"}>{tr(serving.sharing?.active ? "Shared on local network" : "Off")}</span><Btn size="sm" onClick={() => { setError(''); setSharingOpen(true); }}>{tr(serving.sharing?.active ? "Manage / stop" : "Share")}</Btn></dd></div>{tr(serving.tunnel?.status === "connected" && serving.tunnel.url ? <div><dt>{tr("Cloudflare tunnel")}</dt><dd className="row"><code style={{ overflowWrap: "anywhere" }}>{serving.tunnel.url}</code><IconBtn name="copy" title={tr("Copy Cloudflare tunnel URL")} onClick={() => void navigator.clipboard.writeText(serving.tunnel!.url!)}/><IconBtn name="settings" title={tr("Manage Cloudflare tunnel")} onClick={() => setCloudflareOpen(true)}/></dd></div> : serving.tunnel?.status === "starting" ? <div><dt>{tr("Cloudflare tunnel")}</dt><dd role="status">{tr("Connecting\u2026")}</dd></div> : null)}<div className="serving-access-row"><dt>{tr("API key")}</dt><dd><div className="serving-access-status">{tr(serving.access.apiKeySet ? <span className="small muted">{tr("Required \u00B7 ")}{tr(serving.access.apiKeyHint)}</span> : null)}<div className="row"><Btn size="sm" onClick={() => { setError(''); generateKey(); setKeyOpen(true); }}>{tr(serving.access.apiKeySet ? 'Change key' : 'Set key')}</Btn>{tr(serving.access.apiKeySet ? <Btn size="sm" onClick={() => { setError(''); setRemoveKeyOpen(true); }}>{tr("Remove key")}</Btn> : null)}</div></div>{tr(serving.access.otherDevices ? <span className="xs muted">{tr("Keep a key while the API is available to other devices.")}</span> : null)}</dd></div></dl></section>
{tr(multipleModels ? <section className="st-card serving-models" aria-label={tr("Available API models")}><div className="section-toolbar"><h2 className="h4">{tr("Available models")}</h2><span className="xs muted">{tr("One API URL \u00B7 route by model ID")}</span></div>
{tr(runtime?.instances.length ? <div className="serving-models__list">{tr(runtime.instances.map(i => <div key={i.id} className="serving-model"><div><strong>{tr(i.family)}</strong><small>{tr(i.name)} · {tr(i.memory.context / 1024)}{tr("K \u00B7 ")}{tr(deviceLabel(i.gpuIds, hardware))}</small></div><code>{i.apiModelId}</code><IconBtn name="copy" title={tr("Copy model ID {0}", [i.apiModelId])} onClick={() => void copyConnectionValue(i.apiModelId, 'Model ID')}/></div>))}</div> : <p className="small muted">{tr("Load a model in Models to make it available here.")}</p>)}
<p className="xs muted">{tr("Set ")}<code>model</code>{tr(" in each request. Each model has its own queue.")}{tr(runtime?.mode === 'simulated' ? ' Design preview · responses are illustrative.' : '')}</p>
@@ -116,7 +116,7 @@ export function ServingScreen() {
{tr(error ? <ErrorNotice message={error}/> : null)}
</section></div>
</Dialog>
<Dialog open={removeKeyOpen} compact title={tr("Remove API key?")} onClose={() => !pending && setRemoveKeyOpen(false)} actions={<><Btn disabled={pending} onClick={() => setRemoveKeyOpen(false)}>{tr("Keep key")}</Btn><Btn variant="danger" disabled={pending} onClick={() => void operation(async () => { await setServingAccess({ apiKey: null }); setRemoveKeyOpen(false); })}>{tr(pending ? 'Removing…' : 'Remove key')}</Btn></>}><p>{tr("Apps on this computer will be able to send requests without a key. Existing clients can keep their current key field.")}</p>{tr(error ? <ErrorNotice message={error}/> : null)}</Dialog>
<Dialog open={removeKeyOpen} compact title={tr("Remove API key?")} onClose={() => !pending && setRemoveKeyOpen(false)} actions={<><Btn disabled={pending} onClick={() => setRemoveKeyOpen(false)}>{tr("Keep key")}</Btn><Btn variant="danger" disabled={pending} onClick={() => void operation(async () => { await setServingAccess({ apiKey: null }); setRemoveKeyOpen(false); })}>{tr(pending ? 'Removing…' : 'Remove key')}</Btn></>}><p>{tr("Apps on this computer will be able to send requests without a key. Existing clients can keep their current key field.")}</p>{tr(serving.access.otherDevices ? <p className="small muted"><Icon name="warning" size={16}/>{tr(" Without an API key, anyone who can reach this address can use your model.")}</p> : null)}{tr(error ? <ErrorNotice message={error}/> : null)}</Dialog>
<CloudflareDialog open={cloudflareOpen} onClose={() => setCloudflareOpen(false)} onCreateKey={() => { setReturnToTunnel(true); setCloudflareOpen(false); generateKey(); setKeyOpen(true); }}/>
</Screen>;
}
+25
View File
@@ -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; }
+222
View File
@@ -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 <drive>\\Strata, shown as <drive>\\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);
}
});
@@ -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 */ } });
+3 -1
View File
@@ -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
+1 -1
View File
@@ -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-<name>` 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`
+14 -1
View File
@@ -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-<model>.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: <reason>`. 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.
+4 -3
View File
@@ -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
+106 -6
View File
@@ -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 {}
+4 -3
View File
@@ -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:
+37 -5
View File
@@ -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:
+189 -20
View File
@@ -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()
+5 -2
View File
@@ -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)
+1 -1
View File
@@ -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}"')
+52
View File
@@ -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.
+573
View File
@@ -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/<tag>/file.gguf)
size: int
group: str # the model it belongs to: "models/<tag>", "packs/<tag>", "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 <hex>``), 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-<model>.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}
+400
View File
@@ -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 <data>/models/<tag>: 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()
+10 -4
View File
@@ -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")):
+13 -2
View File
@@ -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")
+400
View File
@@ -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()
+1
View File
@@ -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)
+34 -2
View File
@@ -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)
+1 -1
View File
@@ -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):
+89
View File
@@ -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)
+7 -1
View File
@@ -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):
+14 -2
View File
@@ -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)