Merge f-022-modelsui: change the models folder in Settings > Storage (move / keep / start empty), as in the approved mockup

This commit is contained in:
Niko1221 committed 2026-10-20 16:46:46 +02:00
commit 031adf99bf
21 files changed
+1993 -20

No files matched your search

+17
View File
@@ -207,6 +207,23 @@ export function createControl({ control = findControl(), env = process.env, run
if (result.json?.plan && Array.isArray(result.json.plan.issues)) return result.json.plan;
throw failure(result, 'The files could not be checked.');
},
/** What picking `to` as the models folder means (sizes, free space, which choices are possible, why not): nothing is changed. */
async planModelsMove(from, to) {
const result = await call(['models', 'move', to, ...(from ? ['--from', from] : []), '--plan', '--output', 'json'], { timeoutMs: 120_000 });
if (result.json?.plan) return result.json.plan;
throw failure(result, 'The folder could not be checked.');
},
/**
* Move the model files to `to` (copied, checked, then the old copies removed). `onEvent` gets the progress lines; a file at `cancelFile` stops it
* safely. Resolves with the summary (done / stopped, what moved, what is left); a failure is a ControlError whose `output` carries the details.
*/
async moveModels(from, to, { installDir = null, cancelFile = null, onEvent = null } = {}) {
const args = ['models', 'move', to, ...(from ? ['--from', from] : []), ...(installDir ? ['--install-dir', installDir] : []), ...(cancelFile ? ['--cancel-file', cancelFile] : []), '--output', 'jsonl'];
const result = await call(args, { timeoutMs: 24 * 3600_000, onLine: onEvent ?? (() => {}) });
if (result.json?.ok && result.json.event === 'result') return result.json;
const error = result.json?.error;
throw Object.assign(new ControlError(error?.message ?? (result.stderr.split(/\r?\n/).filter(Boolean).pop() || 'The models could not be moved.'), { exitCode: result.code, output: result.json }), { code: error?.code ?? 'move_failed', details: error?.details ?? '' });
},
async saveProfile(name, configPath) {
const listed = await call(['profile', 'list', '--output', 'json'], { timeoutMs: 20_000 });
const known = (listed.json?.profiles ?? []).some(p => p.id === name);
+9 -1
View File
@@ -966,6 +966,14 @@ async function api(req, res, path, method, url) {
if(path==='/api/native'&&method==='GET')return json(res,200,await native.refresh(url.searchParams.get('refresh')==='1'));
if(path==='/api/native'&&method==='PATCH')return json(res,200,await native.configure(await readBody(req)));
if(path==='/api/native/directory'&&method==='POST')return json(res,200,native.setDownloadDirectory((await readBody(req)).directory));
/* Settings > Storage > Models folder: pick (or type) a folder, say what it means, then start the choice. Copying is Control's (strata models move). */
if(path==='/api/native/models-folder/plan'&&method==='POST'){
const typed=await typedFolder((await readBody(req)).path,{isAbsolute});
const picked=typed?{path:typed}:await chooseFolder('Choose a folder for your models');
if(picked.unavailable){const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});}
if(picked.cancelled)return json(res,200,{cancelled:true});
return json(res,200,{plan:await native.planModelsFolder(picked.path)});}
if(path==='/api/native/models-folder/start'&&method==='POST'){const body=await readBody(req);const result=await native.startModelsFolder({folder:body.path,choice:body.choice,stopRunning:body.stopRunning===true});return json(res,result.id?202:200,result);}
if(path==='/api/native/plan'&&method==='POST')return json(res,200,await native.plan(await readBody(req)));
if(path==='/api/native/operations'&&method==='POST'){if(storageChanging)return error(res,409,'Wait for the model folder check to finish.');const body=await readBody(req);return json(res,202,native.operation(body.kind,body.args));}
if(path==='/api/native/logs'&&method==='GET')return json(res,200,{logs:native.logs()});
@@ -1010,7 +1018,7 @@ async function api(req, res, path, method, url) {
if(nativeSettingsFile&&method==='POST')return json(res,200,await native.openSettingsFile(nativeSettingsFile[1]));
// Credentials are handled only on the host. Responses and events expose a key-set flag.
return error(res,404,'Unknown native control action.');}catch(e){return error(res,/Finish|Unload|running|current operation/.test(e.message)?409:400,e.message);}}
return error(res,404,'Unknown native control action.');}catch(e){return error(res,/Finish|Unload|running|current operation/.test(e.message)?409:400,e.message,{...(e.code&&typeof e.code==='string'?{code:e.code}:{}),...(e.details?{details:String(e.details)}:{})});}}
if (path === '/api/model-providers' && method === 'GET') return json(res, 200, withPictureAnswers(modelProviders.list()));
if (path === '/api/model-providers/discover' && method === 'POST') {
+74 -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,77 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};}
return autotuner.start(job,job.kind==='recheck'?'recheck':'tune',{configPath:path,presetId:args.presetId,mode:args.mode,use:args.use,goal:room?'room':'speed',leaveRam:room?20:0,allowSmallDifferences:args.allowSmallDifferences===true,name:args.name},{onProgress:p=>{job.summary=p.text??job.summary;emit();}});
}
function operation(kind,args={}){if(!['install','load','benchmark','tune','autotune','recheck','calibrate','update-engine','update-strata','rollback','remove'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');if(kind==='install'||kind==='load'){const refusal=engineRefusal(snapshot.catalog,args.model,snapshot.engineInfo);if(refusal)throw new Error(refusal);}return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):kind==='autotune'||kind==='recheck'?autotune(job,args):kind==='remove'?removeModel(job,args):program(job,args),{guided:args.guided===true,model:args.model,...(args.family?{family:args.family}:{})});}
async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install'){job.engineAbort?.abort();await tool('strata_install',{cancel:true});}else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate','autotune','recheck'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();}
/* ---- The models folder card (0.2.2): what a picked folder means, and the three choices. The copying is Control's (strata models move). ---- */
const currentModelsFolder=()=>preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder)??null;
const moveFile=()=>join(directory,'models-move.cancel');
const folderWords=error=>({message:error.message,details:error.details||''});
/** A picked folder as the data folder: a whole drive (D:\) becomes D:\Strata, and the person is told (the models then live in D:\Strata\Models). */
function pickedModelsFolder(input){
if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a models folder.');
const picked=resolve(input.trim()),target=dataFolderFromPick(picked);
return {picked,folder:target.path,wholeDrive:!!target.note,shown:target.note?join(target.path,'Models'):target.path};
}
async function planModelsFolder(input){
if(!packaged)throw new Error('Changing the models folder is part of the Strata app.');
const now=currentModelsFolder();if(!now)throw new Error('Strata is still reading your models folder. Try again in a moment.');
const pick=pickedModelsFolder(input),plan=await control.planModelsMove(now,pick.folder);
return {...plan,...pick,current:now,running:instances.size,busy:[...jobs.values()].some(j=>j.state==='running')};
}
/* "Start empty": the old models are no longer listed. Their run configs are moved (not deleted) into old-models beside the others; the model files are not touched. */
function setAsideConfigs(old){
const folder=repo(),kept=join(folder,'old-models'),aside=[];
const under=value=>typeof value==='string'&&[ 'models','packs','mtp' ].some(item=>{const base=join(old,item).toLowerCase();const v=value.toLowerCase();return v===base||v.startsWith(base+sep)||v.startsWith(base+'/');});
const scan=value=>Array.isArray(value)?value.some(scan):value&&typeof value==='object'?Object.values(value).some(scan):under(value);
for(const name of readdirSync(folder)){
if(!/^strata-[a-z0-9_-]+\.json$/i.test(name)||name.endsWith('.shared-settings.json'))continue;
if(!scan(readJson(join(folder,name))))continue;
mkdirSync(kept,{recursive:true});renameSync(join(folder,name),join(kept,name));aside.push(name);
}
return aside;
}
async function startModelsFolder({folder:input,choice,stopRunning=false}){
if(!packaged)throw new Error('Changing the models folder is part of the Strata app.');
if(!['move','keep','empty'].includes(choice))throw new Error('Choose what to do with your models.');
if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or stop the download to change the folder.');
const plan=await planModelsFolder(input);
if(plan.issue)throw Object.assign(new Error(plan.issue.message),{details:plan.issue.details,code:plan.issue.code});
if(!plan.choices[choice].possible)throw Object.assign(new Error(plan.choices[choice].reason||'That choice is not possible here.'),{code:'not_possible'});
if(instances.size){
if(!stopRunning)throw Object.assign(new Error('A model is running. Stop it first, then change the folder.'),{code:'running'});
for(const id of [...instances.keys()])await unload(id);
}
const old=plan.current,target=plan.folder;
if(choice!=='move'){
makeFolder(target);
const aside=choice==='empty'?setAsideConfigs(old):[];
setDownloadDirectory(target);lastRead=0;await refresh(true);
return {done:true,choice,folder:target,oldFolder:old,setAside:aside};
}
rmSync(moveFile(),{force:true});
return begin('models-move',async job=>{
job.cancelFile=moveFile();job.summary='Starting…';
try{
const result=await control.moveModels(old,target,{installDir:repo(),cancelFile:moveFile(),onEvent:event=>{
if(event.event!=='progress')return;
job.progress={done:event.done,total:event.total,file:event.file,group:event.group,index:event.index,count:event.count,secondsLeft:event.seconds_left||0,sameDrive:!!event.same_drive};
job.summary=`${Math.round(event.done/1e8)/10} of ${Math.round(event.total/1e8)/10} GB`;emit();}});
const finished={done:!!result.done,stopped:!!result.stopped,moved:result.moved??[],remaining:result.remaining??[],bytes:result.bytes_moved??0,total:result.total_bytes??0,from:old,to:target,files:result.files_moved??0,sameDrive:!!result.same_drive};
/* Only a whole move changes the folder the app uses: a stopped move leaves it where it was, and every model works where it is. */
if(result.done){setDownloadDirectory(target,{insideJob:true});finished.folder=target;}
job.progress=null;
return {summary:result.done?'Your models are moved.':'Moving stopped. Nothing was lost.',...finished};
}catch(error){
const left=error.output;
job.result={failed:true,code:error.code,moved:left?.moved??[],remaining:left?.remaining??[],bytes:left?.bytes_moved??0,total:left?.total_bytes??0,from:old,to:target};
job.progress=null;
throw error;
}finally{rmSync(moveFile(),{force:true});}
},{family:undefined});
}
async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install'){job.engineAbort?.abort();await tool('strata_install',{cancel:true});}else if(job.kind==='models-move'){/* a safe stop: the copy in flight is dropped, files already moved stay */try{writeFileSync(job.cancelFile,'stop');}catch{/* the run ends anyway */}job.summary='Stopping…';emit();return state();}else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate','autotune','recheck'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();}
async function close(){closing=true;clearInterval(timer);const installing=packaged&&child&&[...jobs.values()].some(j=>j.kind==='install'&&j.state==='running');if(installing)await send('tools/call',{name:'strata_install',arguments:{cancel:true}},15000).catch(()=>{});const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();}
// Remove nonserializable process references from public jobs.
const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,engineAbort,rawResult,...job})=>job);return value;};
async function localPreview(path){if(!packaged)throw new Error('Checking local model files is part of the Strata app.');if(typeof path!=='string'||!path.trim()||[...path].some(c=>c.charCodeAt(0)<32))throw new Error('Choose a folder.');return control.importPlan(path.trim());}
return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,plan,settings,save,settingsFile,openSettingsFile,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close};
return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,planModelsFolder,startModelsFolder,plan,settings,save,settingsFile,openSettingsFile,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close};
}
@@ -0,0 +1,230 @@
import { tr, localeTag } from '../lib/i18n';
import { useEffect, useMemo, useState } from 'react';
import { Bar, Btn, Dialog, Icon } from './ui';
import { api, ApiError } from '../lib/client';
import { nativeAction, refreshNative, useNative, type NativeJob, type NativeState } from '../lib/native';
import { nativeShortName } from '../lib/native-names';
import { sizeGb } from '../lib/format';
type Choice = 'move' | 'keep' | 'empty';
interface Plan {
ok: boolean;
issue: { code: string; message: string; details: string } | null;
old: string; new: string; same_drive: boolean;
free_bytes: number; models_bytes: number; needed_bytes: number;
models: { group: string; name: string; bytes: number }[];
choices: Record<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 folder = native?.downloadDirectory ?? '';
const free = native?.downloadFreeBytes ?? null;
const usage = native?.installed?.usage?.total_bytes ?? 0;
const moving = native?.jobs.find(j => j.kind === 'models-move' && j.state === 'running') ?? null;
const finished = jobId ? native?.jobs.find(j => j.id === jobId && j.kind === 'models-move' && j.state !== 'running') : undefined;
useEffect(() => { if (finished && !outcome) { setOutcome({ job: finished }); setStopping(false); void refreshNative(true); } }, [finished, outcome]);
const total = native?.downloadTotalBytes ?? null;
const used = free !== null && total ? Math.min(100, Math.max(1, ((total - free) / total) * 100)) : 0;
useEffect(() => { if (moving && !jobId) setJobId(moving.id); }, [moving, jobId]);
function leave() { setPlan(null); setStage(null); setError(null); setTyping(false); }
async function pick(path = '') {
setPending(true);
setError(null);
setNotice('');
try {
const result = await api.post<{ cancelled?: boolean; plan?: Plan }>('/api/native/models-folder/plan', { path });
if (result.cancelled || !result.plan) return;
const next = result.plan;
setTyping(false);
setPlan(next);
if (next.issue?.code === 'same') { setPlan(null); return; }
setChoice(next.choices.move.possible ? 'move' : 'keep');
setStage(next.issue ? 'issue' : next.wholeDrive ? 'drive' : 'choose');
}
catch (e) {
if (e instanceof ApiError && e.status === 501) { setTyping(true); setError({ message: e.message }); }
else setError({ message: (e as Error).message, details: ((e as ApiError).body as { details?: string } | undefined)?.details });
}
finally { setPending(false); }
}
async function start() {
if (!plan) return;
setPending(true);
setError(null);
try {
const result = await api.post<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); 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}
{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 ?? '', savedPlan?.folder ?? ''])}</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 ? `${name} (${gb(m?.bytes ?? 0)})` : null; }).filter((x): x is string => !!x));
if (outcome.state === 'error') {
const full = result.code === 'disk_full';
const where = driveOf(result.to ?? '');
const some = (result.moved?.length ?? 0) > 0;
return <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>
+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());}
+79 -1
View File
@@ -3359,5 +3359,83 @@
"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})."
"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."
}
+79 -1
View File
@@ -3359,5 +3359,83 @@
"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})."
"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."
}
+79 -1
View File
@@ -3359,5 +3359,83 @@
"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})."
"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í."
}
+79 -1
View File
@@ -3359,5 +3359,83 @@
"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})。"
"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": "この選択肢はここでは使えません。"
}
+79 -1
View File
@@ -3359,5 +3359,83 @@
"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})."
"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": "여기서는 해당 선택지를 사용할 수 없습니다."
}
+79 -1
View File
@@ -3359,5 +3359,83 @@
"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})."
"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."
}
+79 -1
View File
@@ -3359,5 +3359,83 @@
"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})."
"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": "Этот вариант здесь невозможен."
}
+79 -1
View File
@@ -3359,5 +3359,83 @@
"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})。"
"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": "此处无法使用该选项。"
}
+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; }
+181
View File
@@ -0,0 +1,181 @@
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 } = {}) {
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 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('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)) >= 8261 && Number(k.slice(1)) <= 8338);
assert.equal(ours.length, 78);
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);
}
});
+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
+51 -1
View File
@@ -159,6 +159,13 @@ 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")
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 +502,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 +554,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:
@@ -600,6 +609,47 @@ 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]
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 _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 {}
+480
View File
@@ -0,0 +1,480 @@
"""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 interrupted(data: Path) -> dict | None:
"""The unfinished move recorded in a data folder (``models-move.json``), for 'A move was interrupted'."""
st = _read_state(data)
return st if st.get("state") == "running" else None
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 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] = []
state = {"state": "running", "from": str(old), "to": str(new), "started": now(), "bytes": total}
_write_state(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())
_write_state(new, **state)
_quiet_remove(new / STATE_FILE)
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")
_write_state(new, **state)
_quiet_remove(new / STATE_FILE) if not moved_groups and not files_moved else None
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)
_write_state(new, **state)
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
+283
View File
@@ -0,0 +1,283 @@
"""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 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):
with self.copy_mode():
with self.assertRaises(mm.MoveError):
with mock.patch.object(mm, "_copy_verified", side_effect=mm.MoveError("io", "x")):
self.run_move()
self.assertEqual(mm.interrupted(self.new), None) # failed is not "running"
mm._write_state(self.new, state="running", **{"from": str(self.old), "to": str(self.new)})
self.assertEqual(mm.interrupted(self.new)["from"], str(self.old))
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 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()