Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
merge f-split-s4b 0edf5cb9f (Harness in the app chat, Manual approvals, request slots) into f-split-int
Niko1221a16109803654
diff --cc apps/host/server/index.mjsindex 051a584af,882dfa201..d5dd44bcd--- a/apps/host/server/index.mjs+++ b/apps/host/server/index.mjs@@@ -82,14 -81,15 +83,16 @@@ const imageModels = createImageModels(/* The installed app ships Strata Control (python + strata_control) next to the host; a source checkout has none and keeps its older paths. */const CONTROL = findControl();const control = createControl({ control: CONTROL });-const native=createNativeControl({control,hardwareProbe:()=>(hardware.cachedHardware()?.gpus??[]).map((g,n)=>({index:g.index??n,vram_gb:g.vramGb})),directory:store.DATA_DIR,modelsDirectory:()=>store.MODELS_DIR,nativeDataDirectory:store.nativeDataDirectory,beforeLoad:async()=>{if(models.REAL&&models.library().loaded){if(serving.state().requests.some(r=>runtimeModels.state().instances.some(i=>i.id===r.instanceId)&&["queued","generating"].includes(r.state)))throw new Error("Finish requests before switching engines.");await models.unload();runtimeState();}},requests:()=>serving.state().requests,changed:value=>hub.send('native',value)});+const appUpdater = createAppUpdater();- const native=createNativeControl({control,appUpdater,directory:store.DATA_DIR,modelsDirectory:()=>store.MODELS_DIR,nativeDataDirectory:store.nativeDataDirectory,beforeLoad:async()=>{if(models.REAL&&models.library().loaded){if(serving.state().requests.some(r=>runtimeModels.state().instances.some(i=>i.id===r.instanceId)&&["queued","generating"].includes(r.state)))throw new Error("Finish requests before switching engines.");await models.unload();runtimeState();}},requests:()=>serving.state().requests,changed:value=>hub.send('native',value)});++const native=createNativeControl({control,appUpdater,hardwareProbe:()=>(hardware.cachedHardware()?.gpus??[]).map((g,n)=>({index:g.index??n,vram_gb:g.vramGb})),directory:store.DATA_DIR,modelsDirectory:()=>store.MODELS_DIR,nativeDataDirectory:store.nativeDataDirectory,beforeLoad:async()=>{if(models.REAL&&models.library().loaded){if(serving.state().requests.some(r=>runtimeModels.state().instances.some(i=>i.id===r.instanceId)&&["queued","generating"].includes(r.state)))throw new Error("Finish requests before switching engines.");await models.unload();runtimeState();}},requests:()=>serving.state().requests,changed:value=>hub.send('native',value)});/* The agent: chats become DeepSeek Harness sessions when that component is installed. It is a separatepinned component (STRATA_HARNESS_DIR), not part of this host, so its absence is a visible capabilitystate and the chat falls back to the direct path with a notice, never silently to another model. */const agent = createAgentBridge({dataDir: store.DATA_DIR,- componentsDir: process.env.STRATA_COMPONENTS_DIR ?? null,+ componentsDir: componentsDirectory(),+ // The installer ships the Harness next to the host (<install>/host/server -> <install>/harness).+ bundledDir: resolve(HERE, '..', '..', 'harness'),localInstances: () => native.readyInstances().map(i => ({id: i.id, label: i.label, baseUrl: `http://127.0.0.1:${i.port}/v1`, modelId: i.apiModelId,context: i.metrics?.engine?.max_context ?? i.context ?? undefined, key: i.key, vision: i.vision,diff --cc apps/host/server/native-control.mjsindex 466d69a03,968635a9c..cfec2dadf--- a/apps/host/server/native-control.mjs+++ b/apps/host/server/native-control.mjs@@@ -1,321 -1,194 +1,335 @@@-/** Native Strata control plane. All user actions are explicit; opening the UI only reads state. */-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, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs';-import { join, resolve, dirname, basename } from 'node:path';-import { fileURLToPath } from 'node:url';-import { createServer } from 'node:net';-import { NATIVE_FIELDS, validateNativeSettings, validateMcpServers, publicMcpServers, publicNativeEnv, restoreNativeEnv } from './native-settings.mjs';-import { resourceSettings } from './native-resources.mjs';-import { resolvePython, venvPython } from './python-resolver.mjs';-import os from 'node:os';-import { runtimeVision } from './native-vision.mjs';--const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'..');-const safeId=value=>typeof value==='string'&&/^[a-z0-9_-]{1,80}$/i.test(value);-const busy=requests=>requests.some(r=>['queued','generating'].includes(r.state));-function readJson(path,fallback={}){try{return JSON.parse(readFileSync(path,'utf8').replace(/^\uFEFF/,''));}catch{return fallback;}}--export function createNativeControl({directory,requests=()=>[],changed=()=>{},spawnProcess=spawn,fetcher=fetch,modelsDirectory,nativeDataDirectory=value=>value,beforeLoad=async()=>{},hardwareProbe=()=>[],control=null,defaultRepo=process.env.STRATA_NATIVE_REPO??resolve(ROOT,'../../Strata')}={}){- mkdirSync(directory,{recursive:true});- const settingsPath=join(directory,'native-host.json');- let preferences=readJson(settingsPath,{repo:defaultRepo});- let child=null,seq=0,buffer='',pending=new Map(),definitions=[],refreshing=null,lastRead=0,connecting=null;- let snapshot={available:false,repo:preferences.repo,summary:'Connect a local Strata installation.',catalog:null,installed:null,hardware:null,error:null};- const instances=new Map(),processes=new Map(),jobs=new Map(),logs=[];- const savedJobs=readJson(join(directory,'native-jobs.json'),[]);for(const j of (Array.isArray(savedJobs)?savedJobs:[]).slice(-12))jobs.set(j.id,{...j,...(j.state==='running'?{state:'error',error:'The host restarted before completion. Check diagnostics, then retry; completed files are kept.',summary:'Interrupted operation'}:{})});- /* Packaged mode: the app ships Strata Control (control-runtime.mjs). Models are run configs in an install folder, the engine- comes from the component folder, and a start is `strata runtime start` under the owner runtime. Nothing is installed,- updated or fetched from here. Without `control` (a source checkout) every path below is the original one. */- const packaged=!!control;- const NO_INSTALL='Installing, updating, tuning with calibration or rolling back model files and engines happens from the Terminal (strata install), never while the app runs.';- 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,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};}- function sourceText(){try{return readFileSync(join(packaged?control.control.dir:preferences.repo,'serve/server.py'),'utf8');}catch{return '';}}- function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));}- function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};}- function repo(){if(packaged){const base=[preferences.installDir,snapshot.installDir].find(d=>d&&existsSync(d))??control.control.dir;return realpathSync(base);}const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;}- function python(){return resolvePython({repo:preferences.repo});}- function send(method,params,timeout=30000){return new Promise((resolve,reject)=>{const id=++seq;const alarm=setTimeout(()=>{pending.delete(id);reject(new Error('The native engine did not respond in time. Check engine logs.'));},timeout);pending.set(id,{resolve,reject,alarm});child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');});}- function disconnect(){child?.kill();child=null;definitions=[];for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Native control connection closed.'));}pending.clear();}- async function connect(){if(closing)throw new Error("The host is shutting down.");if(child&&definitions.length)return;if(!connecting)connecting=startClient().finally(()=>{connecting=null;});return connecting;}- async function startClient(){- const folder=repo();- buffer='';const py0=python();const client=child=spawnProcess(py0.command,[...py0.args,join(folder,'tools/strata_mcp.py')],{cwd:folder,windowsHide:true,stdio:['pipe','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8'}});- client.stdout.on('data',chunk=>{if(child!==client)return;buffer+=chunk.toString();let end;while((end=buffer.indexOf('\n'))>=0){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);let message;try{message=JSON.parse(line);}catch{continue;}const p=pending.get(message.id);if(p){clearTimeout(p.alarm);pending.delete(message.id);message.error?p.reject(new Error(message.error.message)):p.resolve(message.result);}}});- child.stderr.on('data',chunk=>append('control',chunk.toString()));- client.on('error',error=>{if(child===client){snapshot.error=error.message;disconnect();}});- client.on('exit',()=>{if(child===client){child=null;for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Strata control stopped. Python 3.10 or newer is required.'));}pending.clear();}});- await send('initialize',{protocolVersion:'2024-11-05',capabilities:{},clientInfo:{name:'Strata UI',version:'0.1.0'}});- child.stdin.write(JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})+'\n');- definitions=(await send('tools/list',{})).tools??[];- }- async function controlTool(name){- if(name==='strata_models')return {families:[],sizes:[],note:'Model files are installed from the Terminal; the app fetches nothing while it runs.'};- if(name==='strata_status'){- const [list,engine]=await Promise.all([control.installedModels({installDir:preferences.installDir}),control.engine()]);- const models=(list.models??[]).filter(m=>m.component_status!=='invalid'&&m.source_config).map(m=>({model:m.id,config:basename(m.source_config),configPath:m.source_config,model_name:m.name,context:m.context_tokens??0,backend:m.backend,ready:m.component_status==='present',images:'off',port:undefined,last_used:null}));- const cores=os.cpus().length;- return {summary:engine.usable?`Strata Control is ready; engine ${engine.engine.version} (${engine.engine.platform}-${engine.engine.backend}).`:(engine.notice??'No engine for this PC was found.'),- installDir:list.install_dir,engine:{usable:engine.usable,notice:engine.notice,version:engine.engine?.version??null,backend:engine.backend,componentsDir:engine.components_dir},- installed:{strata_folder:list.install_dir,data_folder:null,engine:engine.engine?{version:engine.engine.version,backend:engine.engine.backend,folder:engine.engine.root}:{folder:null,version:null},models},- hardware:{cpu:{cores},ram_gb:Math.round(os.totalmem()/1024**3),gpus:[]},install:null,running:null};- }- if(name==='strata_install')throw new Error(NO_INSTALL);- throw new Error(`Strata Control has no ${name}.`);- }- async function tool(name,args={}){if(packaged)return controlTool(name,args);await connect();if(!definitions.some(d=>d.name===name))throw new Error(`This Strata installation does not support ${name}. Update the installation first.`);const result=await send('tools/call',{name,arguments:args},120000);let value=result.structuredContent;if(!value){const text=result.content?.find(c=>c.type==='text')?.text;try{value=JSON.parse(text);}catch{value={summary:text};}}if(result.isError)throw new Error(value?.error??value?.summary??'Native operation failed.');return value;}- async function refresh(force=false){- if(closing)return state();- if(refreshing)return refreshing;if(!force&&Date.now()-lastRead<15000)return state();- refreshing=(async()=>{try{const [catalog,status]=await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing;- }- function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}- function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();}- function record(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,config:readJson(path)};}- function settings(model){const {config}=record(model);const values=Object.fromEntries(NATIVE_FIELDS.map(f=>[f.id,config[f.id]??null]));if(typeof values.aliases==='string')values.aliases=values.aliases.split(',').map(v=>v.trim()).filter(Boolean);values.sampling=config.sampling??{};values.args=config.args??[];values.env=publicNativeEnv(config.env??{});return {model,values,mcp:publicMcpServers(config.mcp_servers??config.mcpServers??{}),restartNeeded:true};}- function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);}- function previousEngine(){try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}}- async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);return tool('strata_install',installArgs(args,false));}- function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),confirm};}-- function begin(kind,run,metadata={}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or cancel the current engine operation first.');const job={id:randomUUID(),kind,state:'running',startedAt:new Date().toISOString(),summary:'Starting…',result:null,error:null,...metadata};for(const [id,old] of jobs)if(jobs.size>=12&&old.state!=='running')jobs.delete(id);jobs.set(job.id,job);emit();void run(job).then(result=>{if(job.state==='running'){Object.assign(job,{state:'done',summary:result?.summary??'Complete',result,finishedAt:new Date().toISOString()});}}).catch(error=>{if(job.state==='running')Object.assign(job,{state:'error',error:error.message,summary:error.message,finishedAt:new Date().toISOString()});}).finally(()=>{if(job.kind.startsWith('update')||job.kind==='rollback')disconnect();lastRead=0;emit();void refresh(true);});return state().jobs.find(j=>j.id===job.id);}- async function watchInstall(job,current){job.summary=current.step??'Resuming preparation status…';job.result={install:current};while(job.state==='running'){await new Promise(r=>setTimeout(r,1500));const result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(!result.install?.running){if(result.install?.exit_code!==0)throw new Error(result.install?.error??'Preparation did not finish. Retry to reuse completed files.');return {summary:'Model preparation complete. Load it from Models.'};}}}- function externalRunning(){return Array.isArray(snapshot.external)?snapshot.external.filter(s=>![...instances.values()].some(i=>i.port===s.port)):[];}- async function install(job,args){if(job.state!=='running')return;if(externalRunning().length)throw new Error('Stop the native server running outside this UI before preparing files.');if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel requests before preparing model files.');for(const id of [...instances.keys()])await unload(id);if(job.state!=='running')return;let result=await tool('strata_install',installArgs(args,true));job.summary=result.summary;job.result=result;emit();for(;;){if(job.state!=='running')return;await new Promise(resolve=>setTimeout(resolve,1500));result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(result.install&&!result.install.running){if(result.install.exit_code!==0)throw new Error(result.install.error??result.summary);await refresh(true);if(args.loadAfter){const model=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;return loadEngine(job,{model,multiple:!!args.multiple,resourceProfile:args.resourceProfile,vision:args.loadVision});}return result;}}}- function terminate(proc,signal='SIGTERM'){if(!proc)return;if(process.platform!=='win32'&&proc.pid){try{process.kill(-proc.pid,signal);return;}catch{}}proc.kill(signal);}- async function stopProcess(proc){if(!proc||proc.exitCode!=null)return;await new Promise(resolve=>{const timeout=setTimeout(()=>{terminate(proc,'SIGKILL');resolve();},8000);proc.once('exit',()=>{clearTimeout(timeout);resolve();});terminate(proc);});}- async function unload(id,force=false){const instance=instances.get(id);if(!instance)throw new Error('This model is no longer loaded.');if(!force&&[...jobs.values()].some(j=>j.kind==='benchmark'&&j.state==='running'&&j.instanceId===id))throw new Error('Stop the benchmark before unloading this model.');if(!force&&busy(requests().filter(r=>r.instanceId===id)))throw new Error('Finish or cancel this model’s requests first.');instance.status='unloading';if(instance.profile){try{await control.stop(instance.profile);}catch(error){if(!force){instance.status='error';instance.error=error.message;emit();throw error;}}}else await stopProcess(processes.get(id));processes.delete(id);instances.delete(id);try{unlinkSync(instance.configPath);}catch{}if(defaultId===id)defaultId=instances.keys().next().value??null;emit();return state();}- async function loadEngine(job,args){- await refresh(true);if(job.state!=='running')return;const {config,entry}=record(args.model);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');}if(!entry.ready)throw new Error('Some model files are missing. Use Download / repair to restore them.');- if(externalRunning().length)throw new Error('A Strata server is already running outside this UI. Stop it before loading here, or connect its API in Settings → Models.');- if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.');- const vision=runtimeVision(config,args.vision);- const visionPreferences=args.vision!==undefined?{ui_vision_enabled:args.vision!=='no',ui_vision_device:args.vision==='no'?config.ui_vision_device??'yes':args.vision}:{};- const resources=args.resourceProfile?resourceSettings({...config,vision},snapshot.hardware,args.resourceProfile):null;- const cfg={...config,...visionPreferences,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),host:'127.0.0.1',open_browser:false,...validateNativeSettings(args.values??{}),vision};- if(args.gpus!==undefined){const detected=new Set((snapshot.hardware?.gpus??[]).map(g=>g.index));if(!Array.isArray(args.gpus)||!args.gpus.length||new Set(args.gpus).size!==args.gpus.length||args.gpus.some(g=>!Number.isInteger(g)||!detected.has(g)))throw new Error('Choose distinct detected GPUs. CPU-only text inference is not supported by this native adapter.');cfg.gpu=args.gpus.length===1?args.gpus[0]:args.gpus;cfg.layer_split=args.gpus.length>1?validateNativeSettings({layer_split:args.layerSplit??'auto'}).layer_split:'auto';if(cfg.layer_split!=='auto'&&cfg.layer_split.split(',').length!==args.gpus.length-1)throw new Error('Choose one layer split point between each pair of GPUs.');}- if(cfg.vram_reserve_mib!==undefined&&cfg.vram_reserve_mib!==null){cfg.args=[...(cfg.args??[])];const at=cfg.args.indexOf('--vram-reserve-mib');if(at>=0)cfg.args.splice(at,2);cfg.args.push('--vram-reserve-mib',String(cfg.vram_reserve_mib));}if(cfg.vision){if(cfg.vision_tokens!=null)cfg.vision={...cfg.vision,max_tokens:cfg.vision_tokens};if(cfg.vision_min_tokens!=null)cfg.vision={...cfg.vision,min_tokens:cfg.vision_min_tokens};}cfg.mcp={...(cfg.mcp??{}),...(cfg.mcp_timeout_s!=null?{timeout_s:cfg.mcp_timeout_s}:{}),...(cfg.mcp_max_rounds!=null?{max_rounds:cfg.mcp_max_rounds}:{}),...(cfg.mcp_max_result_chars!=null?{max_result_chars:cfg.mcp_max_result_chars}:{})};- for(const arg of cfg.args??[])if(arg.endsWith('.gguf')&&!existsSync(resolve(repo(),arg)))throw new Error('An engine argument names a missing GGUF. Restore the saved arguments or repair the files.');- /* Installed app: several requests at once by default (4, fewer where the card has no room), unless a number was chosen. */- const parallelChoice=packaged?chooseParallel({config:cfg,values:args.values??{},hardware:snapshot.hardware?.gpus?.length?snapshot.hardware:{gpus:hardwareProbe()??[]}}):null;- let parallelNote=null;- /* The agent asks for long answers (a thinking model can use most of the window): let the engine clamp the output to what is left of the context instead of refusing the request. */- if(packaged&&cfg.fit_max_tokens===undefined)cfg.fit_max_tokens=true;- if(parallelChoice){const applied=applyParallel(cfg,parallelChoice);for(const k of Object.keys(cfg))if(!(k in applied.cfg))delete cfg[k];Object.assign(cfg,applied.cfg);parallelNote=applied.note;}- const fingerprint=createHash('sha256').update(JSON.stringify({...cfg,api_key:undefined,port:undefined})).digest('hex');- const placement=Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu];const matching=[...instances.values()].find(i=>i.model===args.model&&JSON.stringify(i.gpus)===JSON.stringify(placement));- if(matching?.status==='ready'&&matching.fingerprint===fingerprint&&(args.multiple||instances.size===1))return {summary:`${matching.label} is already ready.`,instanceId:matching.id};- const wasDefault=matching?.id===defaultId;- const id=matching?.id??randomUUID();let apiModelId=matching?.apiModelId??args.model,suffix=1;while(!matching&&[...instances.values()].some(i=>i.apiModelId===apiModelId))apiModelId=`${args.model}--${++suffix}`;- cfg.aliases=[...new Set([...(Array.isArray(cfg.aliases)?cfg.aliases:typeof cfg.aliases==='string'?cfg.aliases.split(',').map(s=>s.trim()).filter(Boolean):[]),apiModelId])];- const key=randomBytes(32).toString('hex');cfg.api_key=key;cfg.port=await freePort(args.port);- const work=join(directory,'native-instances');mkdirSync(work,{recursive:true});const configPath=join(work,`${id}.json`);- const py=packaged?null:venvPython(repo());if(!packaged&&!existsSync(py))throw new Error('The Strata Python environment is missing. Use Download / repair first.');- if(job.state!=='running')return;- await beforeLoad();if(job.state!=='running')return;- if(!args.multiple){if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel native requests before switching models.');for(const id of [...instances.keys()])await unload(id);}else if(matching)await unload(matching.id);- if(job.state!=='running')return;- writeFileSync(configPath,JSON.stringify(cfg,null,2),{mode:0o600});- const instance={id,apiModelId,fingerprint,context:entry.context??0,aliases:cfg.aliases??[],vision:!!cfg.vision,model:args.model,label:entry.model_name??args.model,port:cfg.port,gpus:Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu],status:'loading',phase:'loading',parallel:cfg.parallel??1,mcpServers:cfg.mcp_servers??cfg.mcpServers??{},key,configPath,loadedAt:new Date().toISOString(),metrics:null,error:null};- let proc=null,started=null;- if(packaged){- /* The engine starts under Control's owner runtime, not as our child: a saved profile per slot, then `runtime start`. */- const used=new Set([...instances.values()].map(i=>i.profile));let slot=1;while(used.has('app-'+slot))slot++;instance.profile='app-'+slot;- instances.set(id,instance);if(!defaultId||!args.multiple||wasDefault)defaultId=id;emit();- started=control.stop(instance.profile).catch(()=>{}).then(()=>control.saveProfile(instance.profile,configPath)).then(()=>control.start(instance.profile,{waitSeconds:300})).catch(async error=>{- if(!(cfg.parallel>1)||parallelChoice?.explicit||job.state!=='running')throw error;- append(id,'Loading with several requests at once failed; trying again with one: '+error.message);- Object.keys(cfg).forEach(k=>delete cfg[k]);Object.assign(cfg,withoutParallel(JSON.parse(readFileSync(configPath,'utf8'))));- writeFileSync(configPath,JSON.stringify(cfg,null,2),{mode:0o600});parallelNote=FALLBACK_NOTE;instance.parallel=1;- await control.stop(instance.profile).catch(()=>{});await control.saveProfile(instance.profile,configPath);await control.start(instance.profile,{waitSeconds:300});- });- started.then(()=>append(id,'Strata Control reports the engine is ready.'),error=>{append(id,error.message);});- try{await started;}catch(error){instance.status='error';instance.error=error.message;emit();throw error;}- } else {- proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8',STRATA_API_KEY:''}});- instances.set(id,instance);processes.set(id,proc);if(!defaultId||!args.multiple||wasDefault)defaultId=id;- for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{const lines=chunk.toString().split('\n').filter(Boolean);lines.forEach(line=>append(id,line.replaceAll(key,'[redacted]')));job.summary=lines.at(-1)??job.summary;emit();});- proc.on('error',error=>{instance.status='error';instance.error=error.message;emit();});proc.on('exit',code=>{if(instances.has(id)&&instance.status!=='unloading'){instance.status='error';instance.error=`Engine stopped${code===null?'':` (exit ${code})`}. Open diagnostics or reload.`;emit();}});emit();- }- const deadline=Date.now()+300000;while(Date.now()<deadline&&job.state==='running'){- if(instance.status==='error')throw new Error(instance.error);- try{const response=await fetcher(`http://127.0.0.1:${instance.port}/health`,{headers:{authorization:`Bearer ${key}`},signal:AbortSignal.timeout(2000)});if(job.state!=='running'){await unload(id);return;}if(response.ok){instance.status='ready';instance.phase='idle';if(resources||args.vision!==undefined)writeModelConfig(record(args.model).path,{...config,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),...visionPreferences});emit();ensurePoll();instance.parallelNote=parallelNote;return {summary:`${instance.label} is ready.${parallelNote?' '+parallelNote:''}`,instanceId:id};}}catch{}- await new Promise(resolve=>setTimeout(resolve,1200));- }- if(job.state!=='running'){await unload(id);return;}- if(instance.profile)await control.stop(instance.profile).catch(()=>{});else await stopProcess(proc);instance.status='error';instance.error='Loading took more than five minutes. Check the engine log and free memory.';throw new Error(instance.error);- }- async function freePort(requested){for(let port=Number(requested??18500);port<=Number(requested??18500)+20;port++){if(!Number.isInteger(port)||port<1024||port>65535)throw new Error('Choose a port from 1024 to 65535.');if([...instances.values()].some(i=>i.port===port)){if(requested)throw new Error('This private engine port is already in use.');continue;}const available=await new Promise(resolve=>{const probe=createServer();probe.once('error',()=>resolve(false));probe.listen(port,'127.0.0.1',()=>probe.close(()=>resolve(true)));});if(available)return port;if(requested)throw new Error('This private engine port is already in use.');}throw new Error('No free private engine port was found.');}- async function poll(){if(polling||closing)return;polling=true;try{await Promise.all([...instances.values()].map(async instance=>{if(instance.status!=='ready')return;try{const response=await fetcher(`http://127.0.0.1:${instance.port}/metrics?requests=all`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(!response.ok)throw new Error('Metrics unavailable');instance.metrics=await response.json();const tools=await fetcher(`http://127.0.0.1:${instance.port}/mcp`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(tools.ok)instance.metrics.mcp=await tools.json();instance.phase=instance.metrics.live?.state??'idle';}catch{instance.metrics=null;instance.phase='unavailable';}}));emit();}finally{polling=false;}}- function ensurePoll(){if(!timer){timer=setInterval(()=>void poll(),2000);timer.unref?.();}void poll();}- async function benchmark(job,args){const instance=resolveInstance(args.instanceId);job.instanceId=instance.id;if(busy(requests().filter(r=>r.instanceId===instance.id)))throw new Error('Wait for this model to finish before benchmarking.');const started=Date.now();job.abort=new AbortController();const response=await fetcher(`http://127.0.0.1:${instance.port}/v1/chat/completions`,{method:'POST',headers:{'content-type':'application/json',authorization:`Bearer ${instance.key}`},signal:AbortSignal.any([job.abort.signal,AbortSignal.timeout(180000)]),body:JSON.stringify({model:instance.apiModelId,messages:[{role:'user',content:'Explain how a rainbow forms in clear, simple language.'}],temperature:0,reasoning_effort:'none',max_tokens:200,stream:false})});const body=await response.json();if(!response.ok)throw new Error(body.error?.message??'Benchmark failed.');if(job.state!=='running')return;const result={summary:'Measured benchmark complete.',at:new Date().toISOString(),model:instance.apiModelId,durationMs:Date.now()-started,tokensIn:body.usage?.prompt_tokens??null,tokensOut:body.usage?.completion_tokens??null,outputTps:body.timings?.predicted_per_second??null,promptTps:body.timings?.prompt_per_second??null,source:'engine',settings:'Greedy · thinking off · up to 200 output tokens'};writeFileSync(join(directory,'native-benchmark.json'),JSON.stringify(result,null,2),{mode:0o600});return result;}- function resolveInstance(id){const aliases=[...instances.values()].filter(i=>i.aliases?.includes(id));if(aliases.length>1&&!instances.has(id)&&![...instances.values()].some(i=>i.apiModelId===id))throw new Error('This alias matches more than one instance. Choose its exact model ID.');const i=instances.get(id)??[...instances.values()].find(i=>i.apiModelId===id)??aliases[0]??(!id&&instances.size===1?[...instances.values()][0]:undefined);if(!i)throw new Error('Choose a loaded model ID.');if(i.status!=='ready')throw new Error('This model is not ready.');return i;}- async function program(job,args){if(packaged)throw new Error(NO_INSTALL);if(externalRunning().length)throw new Error('Stop the native server running outside this UI before changing engine files.');if(instances.size)throw new Error('Unload native models before changing engine files.');const folder=repo();let {command,args:prefix}=python(),argv;- if(job.kind==='calibrate'||job.kind==='tune'){if(!state().capabilities.calibration)throw new Error('This installation calibrates NVIDIA GPUs only. Use the short benchmark on other devices.');const model=args.model??snapshot.installed?.models?.[0]?.model;const chosen=record(model);if(!chosen.entry.ready)throw new Error('Prepare this model before calibrating.');command=venvPython(folder);prefix=[];if(!existsSync(command))throw new Error('Prepare the Python environment first.');argv=['-c','import sys; from pathlib import Path; import setup; sys.exit(0 if setup.calibrate_config(Path(sys.argv[1])) else 1)',chosen.path];}- else if(job.kind==='rollback'){if(!previousEngine())throw new Error('No saved previous engine is available.');argv=[join(folder,'setup.py'),'--rollback-engine'];}- else if(job.kind==='update-engine'){if(!snapshot.installed?.models?.length)throw new Error('Prepare a model first. Its installer downloads the matching engine.');argv=[join(folder,'setup.py'),'--update'];}- else if(job.kind==='update-strata'){const status=await execute('git',['status','--porcelain'],folder);if(status.trim())throw new Error('This Strata checkout has local edits. Save or commit them before updating.');const remote=await execute('git',['remote','get-url','origin'],folder);if(!/^https:\/\/github\.com\/Niko1221\/Strata(?:\.git)?\s*$/.test(remote))throw new Error('The native installation must use the official Strata repository to update here.');await execute('git',['pull','--ff-only'],folder);argv=[join(folder,'setup.py'),'--update'];}- else throw new Error('Unsupported native operation.');- return new Promise((resolve,reject)=>{const proc=spawnProcess(command,[...prefix,...argv],{cwd:folder,windowsHide:true,detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1'}});job.process=proc;for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{chunk.toString().split('\n').filter(Boolean).forEach(line=>append(job.id,line));job.summary=chunk.toString().trim().slice(-500);emit();});proc.on('error',reject);proc.on('exit',code=>{delete job.process;code===0?resolve({summary:job.kind==='calibrate'?'Calibration complete. Native settings were saved.':'Native installation updated.'}):reject(new Error(`Operation stopped (exit ${code}). Open diagnostics for details.`));});});- }- function execute(cmd,args,cwd){return new Promise((resolve,reject)=>{let output='';const process=spawnProcess(cmd,args,{cwd,stdio:['ignore','pipe','pipe']});process.stdout.on('data',c=>{output+=c;if(output.length>100000)process.kill();});process.stderr.on('data',c=>append('update',c.toString()));process.on('error',reject);process.on('exit',code=>code===0?resolve(output):reject(new Error('Git could not update this installation. Open diagnostics.')));});}- function writeModelConfig(path,next){copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);}- async function tune(job,args){- await refresh(true);if(job.state!=='running')return;- const chosen=record(args.model);resourceSettings(chosen.config,snapshot.hardware,args.profile);- if(!chosen.entry.ready)throw new Error('Prepare the model before tuning.');- if(externalRunning().length)throw new Error('Stop the native server outside this UI before tuning.');- if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish requests before tuning.');- for(const id of [...instances.keys()])await unload(id);- if(job.state!=='running')return;- const initialValues=resourceSettings(chosen.config,snapshot.hardware,args.profile);writeModelConfig(chosen.path,{...chosen.config,...initialValues,ui_resource_profile:args.profile});- if(args.calibrate!==false&&state().capabilities.calibration){job.summary='Measuring the best engine settings for this computer…';emit();await program(job,args);}- if(job.state!=='running')return;- const current=record(args.model),values=resourceSettings(current.config,snapshot.hardware,args.profile);- const next={...current.config,...values,ui_resource_profile:args.profile};- writeModelConfig(current.path,next);- job.summary='Applying your resource preference and loading the model…';emit();- const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:args.vision});- if(job.state!=='running'||!loaded?.instanceId)return;- job.summary='Checking your model’s speed…';emit();- const measured=await benchmark(job,{instanceId:loaded.instanceId});- return {...loaded,...measured,summary:'Your model is tuned and ready.',profile:args.profile};- }- function operation(kind,args={}){if(!['install','load','benchmark','tune','calibrate','update-engine','update-strata','rollback'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):program(job,args),{guided:args.guided===true,model:args.model});}- 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')await tool('strata_install',{cancel:true});else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate'].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 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,...job})=>job);return value;};- return {state:publicState,refresh,configure,setDownloadDirectory,plan,settings,save,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};-}+/** Native Strata control plane. All user actions are explicit; opening the UI only reads state. */+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 { fileURLToPath } from 'node:url';+import { createServer } from 'node:net';+import { NATIVE_FIELDS, validateNativeSettings, validateMcpServers, publicMcpServers, publicNativeEnv, restoreNativeEnv } from './native-settings.mjs';+import { resourceSettings, saferStart } from './native-resources.mjs';+import { resolvePython, venvPython } from './python-resolver.mjs';+import os from 'node:os';+import { runtimeVision } from './native-vision.mjs';+import { componentsDirectory, installerEnvironment, controlEnvironment } from './control-runtime.mjs';+import { createEngineStep } from './engine-step.mjs';+import { createAutoTune, writeTuneConfig } from './native-autotune.mjs';+import { plainError, PHASE_TEXT } from './update-messages.mjs';++const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'..');+const safeId=value=>typeof value==='string'&&/^[a-z0-9_-]{1,80}$/i.test(value);+const busy=requests=>requests.some(r=>['queued','generating'].includes(r.state));+function readJson(path,fallback={}){try{return JSON.parse(readFileSync(path,'utf8').replace(/^\uFEFF/,''));}catch{return fallback;}}+- export function createNativeControl({directory,requests=()=>[],changed=()=>{},spawnProcess=spawn,fetcher=fetch,modelsDirectory,nativeDataDirectory=value=>value,beforeLoad=async()=>{},control=null,appUpdater=null,defaultRepo=process.env.STRATA_NATIVE_REPO??resolve(ROOT,'../../Strata')}={}){++export function createNativeControl({directory,requests=()=>[],changed=()=>{},spawnProcess=spawn,fetcher=fetch,modelsDirectory,nativeDataDirectory=value=>value,beforeLoad=async()=>{},hardwareProbe=()=>[],control=null,appUpdater=null,defaultRepo=process.env.STRATA_NATIVE_REPO??resolve(ROOT,'../../Strata')}={}){+ mkdirSync(directory,{recursive:true});+ const settingsPath=join(directory,'native-host.json');+ let preferences=readJson(settingsPath,{repo:defaultRepo});+ let child=null,seq=0,buffer='',pending=new Map(),definitions=[],refreshing=null,lastRead=0,connecting=null;+ let snapshot={available:false,repo:preferences.repo,summary:'Connect a local Strata installation.',catalog:null,installed:null,hardware:null,error:null};+ const instances=new Map(),processes=new Map(),jobs=new Map(),logs=[];+ const savedJobs=readJson(join(directory,'native-jobs.json'),[]);for(const j of (Array.isArray(savedJobs)?savedJobs:[]).slice(-12))jobs.set(j.id,{...j,...(j.state==='running'?{state:'error',error:'The host restarted before completion. Check diagnostics, then retry; completed files are kept.',summary:'Interrupted operation'}:{})});+ /* Packaged mode: the app ships Strata Control (control-runtime.mjs). Models are run configs in an install folder, the engine+ comes from the component folder, and a start is `strata runtime start` under the owner runtime. Nothing is installed,+ updated or fetched from here. Without `control` (a source checkout) every path below is the original one. */+ const packaged=!!control;+ /* The auto-tuner and the saved tunings are Strata Control's (`strata tune auto`, `strata presets`): the app runs them and follows their status file. */+ const autotuner=createAutoTune({spawnProcess,workDir:join(directory,'native-tune'),launcher:()=>{if(packaged)return {command:control.control.python,prefix:[control.control.cli],cwd:control.control.dir,env:controlEnvironment(control.control)};const py=python();return {command:py.command,prefix:[...py.args,join(repo(),'strata.py')],cwd:repo(),env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8'}};}});+ /* In the packaged app the model catalog, the GPU probe and the install job are Control's bundled tools/strata_mcp.py and+ setup.py, run on Control's own Python in the installer's mode (STRATA_CONTROL_INSTALL: no pip, no engine, no compiler).+ The install only runs when the user clicks Download; starting and serving (control.start) keep STRATA_NO_ACQUIRE. */+ const defaultInstall=()=>join(dirname(componentsDirectory()),'install');+ let packagedInstall=null;+ const NO_INSTALL='Installing, updating, tuning with calibration or rolling back model files and engines happens from the Terminal (strata install), never while the app runs.';+ 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,...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 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}};}+ 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:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));}+ const modelArena=id=>({arenaGb:(snapshot.catalog?.families??[]).flatMap(f=>f.sizes??[]).find(s=>s.id===id)?.experts_gb});+ /* A start that ends with `server_exited` carries the engine's last log line with it; the app turns the code into words and+ keeps this text under "Details" (src/lib/plain-errors.ts). */+ function humanStartError(error){const text=String(error?.message??error),tail=error?.output?.log_tail;return tail&&!text.includes(tail)?`${text}: ${tail}`:text;}+ /* A run config the app's install job wrote names files inside the app's own Control folder (`cwd`, `--expert-profile`). When the+ app is reinstalled to another folder, or an update moves Control, those absolute paths point at nothing and every installed+ model breaks. At every read of the installed models, a path that ends up inside a folder called `control` that no longer+ exists is pointed at the Control this app has now, when the file is there. The config is saved (with a .bak) only then. */+ function repairControlPaths(dir){if(!packaged||!dir||!existsSync(dir))return;let names=[];try{names=readdirSync(dir).filter(n=>/^strata-[a-z0-9_-]+\.json$/i.test(n));}catch{return;}+ const here=control.control.dir,inside=/^(.+?[\/]control)(?=[\/]|$)(.*)$/i;+ const fix=value=>{if(typeof value!=='string')return value;const m=value.match(inside);if(!m||existsSync(value)||resolve(m[1]).toLowerCase()===resolve(here).toLowerCase())return value;const candidate=join(here,m[2]);return existsSync(candidate)?candidate:value;};+ for(const name of names){const path=join(dir,name),config=readJson(path,null);if(!config||typeof config!=='object')continue;+ const next={...config,...(config.cwd!==undefined?{cwd:fix(config.cwd)}:{}),...(Array.isArray(config.args)?{args:config.args.map(fix)}:{})};+ if(JSON.stringify(next)!==JSON.stringify(config)){try{writeModelConfig(path,next);}catch{/* read-only folder: the load reports it */}}}}+ function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,diskGb:entry.diskGb??entry.disk_gb,diskBytes:entry.diskBytes??entry.disk_bytes,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};}+ function installRoot(){const found=[preferences.installDir,packagedInstall,snapshot.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());}+ function repo(){if(packaged)return installRoot();const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;}+ function python(){return resolvePython({repo:preferences.repo});}+ function send(method,params,timeout=30000){return new Promise((resolve,reject)=>{const id=++seq;const alarm=setTimeout(()=>{pending.delete(id);reject(new Error('The native engine did not respond in time. Check engine logs.'));},timeout);pending.set(id,{resolve,reject,alarm});child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');});}+ function disconnect(){child?.kill();child=null;definitions=[];for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Native control connection closed.'));}pending.clear();}+ async function connect(){if(closing)throw new Error("The host is shutting down.");if(child&&definitions.length)return;if(!connecting)connecting=startClient().finally(()=>{connecting=null;});return connecting;}+ async function startClient(){+ const folder=repo();+ buffer='';const py0=packaged?{command:control.control.python,args:[]}:python();+ const script=packaged?join(control.control.dir,'tools/strata_mcp.py'):join(folder,'tools/strata_mcp.py');+ const client=child=spawnProcess(py0.command,[...py0.args,script,...(packaged?['--root',folder,'--src',control.control.dir]:[])],{cwd:packaged?control.control.dir:folder,windowsHide:true,stdio:['pipe','pipe','pipe'],env:packaged?installerEnvironment(control.control,{installDir:folder}):{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8'}});+ client.stdout.on('data',chunk=>{if(child!==client)return;buffer+=chunk.toString();let end;while((end=buffer.indexOf('\n'))>=0){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);let message;try{message=JSON.parse(line);}catch{continue;}const p=pending.get(message.id);if(p){clearTimeout(p.alarm);pending.delete(message.id);message.error?p.reject(new Error(message.error.message)):p.resolve(message.result);}}});+ child.stderr.on('data',chunk=>append('control',chunk.toString()));+ client.on('error',error=>{if(child===client){snapshot.error=error.message;disconnect();}});+ client.on('exit',()=>{if(child===client){child=null;for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Strata control stopped. Python 3.10 or newer is required.'));}pending.clear();}});+ await send('initialize',{protocolVersion:'2024-11-05',capabilities:{},clientInfo:{name:'Strata UI',version:'0.1.0'}});+ child.stdin.write(JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})+'\n');+ definitions=(await send('tools/list',{})).tools??[];+ }+ async function controlTool(name){+ if(name==='strata_status'){+ for(const dir of [preferences.installDir,packagedInstall,installRoot()])repairControlPaths(dir);+ let list=await control.installedModels({installDir:preferences.installDir&&existsSync(preferences.installDir)?preferences.installDir:null});+ if(!preferences.installDir&&!(list.models??[]).length){const own=installRoot();if(realpathSync(list.install_dir)!==own)list=await control.installedModels({installDir:own});}+ if(!preferences.installDir&&list.install_dir&&![preferences.installDir,packagedInstall,installRoot()].some(d=>d&&resolve(d).toLowerCase()===resolve(list.install_dir).toLowerCase())){repairControlPaths(list.install_dir);list=await control.installedModels({installDir:list.install_dir});}+ packagedInstall=list.install_dir;+ const engine=await control.engine();+ const installer=await mcpCall('strata_status',{hardware:true}).catch(error=>({error:error.message}));+ const disk=Object.fromEntries((installer.installed?.models??[]).map(m=>[m.model,{diskGb:m.disk_gb,diskBytes:m.disk_bytes}]));+ const models=(list.models??[]).filter(m=>m.component_status!=='invalid'&&m.source_config).map(m=>({...(disk[m.id]??{}),model:m.id,config:basename(m.source_config),configPath:m.source_config,model_name:m.name,context:m.context_tokens??0,backend:m.backend,ready:m.component_status==='present',images:'off',port:undefined,last_used:null}));+ const cores=os.cpus().length;+ return {summary:engine.usable?`Strata Control is ready; engine ${engine.engine.version} (${engine.engine.platform}-${engine.engine.backend}).`:(engine.notice??'No engine for this PC was found.'),+ installDir:list.install_dir,engine:{usable:engine.usable,notice:engine.notice,version:engine.engine?.version??null,backend:engine.backend,componentsDir:engine.components_dir,previous:engine.previous??null,pinned:engine.pinned??null,updateNotice:engine.update_notice??null},+ installed:{strata_folder:list.install_dir,data_folder:null,engine:engine.engine?{version:engine.engine.version,backend:engine.engine.backend,folder:engine.engine.root}:{folder:null,version:null},models},+ hardware:installer.hardware?{...installer.hardware,cpu:{...(installer.hardware.cpu??{}),cores:installer.hardware.cpu?.cores??cores},gpus:installer.hardware.gpus??[]}:{cpu:{cores},ram_gb:Math.round(os.totalmem()/1024**3),gpus:[]},+ recommendation:installer.recommendation??null,installerError:installer.error??null,install:installer.install??null,running:null};+ }+ throw new Error(`Strata Control has no ${name}.`);+ }+ async function tool(name,args={}){if(packaged&&name==='strata_status')return controlTool(name,args);return mcpCall(name,args);}+ async function mcpCall(name,args={}){await connect();if(!definitions.some(d=>d.name===name))throw new Error(`This Strata installation does not support ${name}. Update the installation first.`);const result=await send('tools/call',{name,arguments:args},120000);let value=result.structuredContent;if(!value){const text=result.content?.find(c=>c.type==='text')?.text;try{value=JSON.parse(text);}catch{value={summary:text};}}if(result.isError)throw new Error(value?.error??value?.summary??'Native operation failed.');return value;}+ async function refresh(force=false){+ if(closing)return state();+ /* A read that is not forced never makes the window wait for the (slow) status of Control: it gets the last state at once, and a stale one+ is refreshed in the background. Only the first read, and a forced one after an operation, waits. */+ if(refreshing)return !force&&snapshot.available?state():refreshing;if(!force&&Date.now()-lastRead<45000)return state();+ refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);const noImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,images:false,sizes:(f.sizes??[]).map(s=>({...s,images:false}))}))}:c;snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:packaged?noImages(catalog):catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});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.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();}+ function record(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,config:readJson(path)};}+ function settings(model){const {config}=record(model);const values=Object.fromEntries(NATIVE_FIELDS.map(f=>[f.id,config[f.id]??null]));if(typeof values.aliases==='string')values.aliases=values.aliases.split(',').map(v=>v.trim()).filter(Boolean);values.sampling=config.sampling??{};values.args=config.args??[];values.env=publicNativeEnv(config.env??{});return {model,values,mcp:publicMcpServers(config.mcp_servers??config.mcpServers??{}),restartNeeded:true};}+ function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);}+ function previousEngine(){if(packaged)return !!snapshot.engine?.previous;try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}}+ async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);return tool('strata_install',installArgs(args,false));}+ function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port','gguf_dir'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),...(packaged?{vision:'no'}:{}),confirm};}++ function begin(kind,run,metadata={}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or cancel the current engine operation first.');const job={id:randomUUID(),kind,state:'running',startedAt:new Date().toISOString(),summary:'Starting…',result:null,error:null,...metadata};for(const [id,old] of jobs)if(jobs.size>=12&&old.state!=='running')jobs.delete(id);jobs.set(job.id,job);emit();void run(job).then(result=>{if(job.state==='running'){Object.assign(job,{state:'done',summary:result?.summary??'Complete',result,finishedAt:new Date().toISOString()});}}).catch(error=>{if(job.state==='running')Object.assign(job,{state:'error',error:error.message,summary:error.message,...(error.details?{details:error.details}:{}),finishedAt:new Date().toISOString()});}).finally(()=>{if(job.kind.startsWith('update')||job.kind==='rollback')disconnect();lastRead=0;emit();void refresh(true);});return state().jobs.find(j=>j.id===job.id);}+ async function watchInstall(job,current){job.summary=current.step??'Resuming preparation status…';job.result={install:current};while(job.state==='running'){await new Promise(r=>setTimeout(r,1500));const result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(!result.install?.running){if(result.install?.exit_code!==0)throw new Error(result.install?.error??'Preparation did not finish. Retry to reuse completed files.');return {summary:'Model preparation complete. Load it from Models.'};}}}+ function externalRunning(){return Array.isArray(snapshot.external)?snapshot.external.filter(s=>![...instances.values()].some(i=>i.port===s.port)):[];}+ async function install(job,args){+ if(job.state!=='running')return;+ if(externalRunning().length)throw new Error('Stop the native server running outside this UI before preparing files.');+ if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel requests before preparing model files.');+ for(const id of [...instances.keys()])await unload(id);+ if(job.state!=='running')return;+ let result=await tool('strata_install',installArgs(args,true));+ /* The engine comes with the model: the same job makes sure this PC has a usable engine (none installed, or a newer compatible+ one in the signed feed) through Control's component updater, and shows it in the job's own progress (install.engine, install.parts,+ one combined download total). A failed engine download keeps the model files and ends with a retry message. */+ job.engineAbort=new AbortController();+ const engineStep=packaged&&typeof control.update==='function'?createEngineStep({control,signal:job.engineAbort.signal,onChange:()=>{if(job.rawResult)publish(job.rawResult);else emit();}}):null;+ const publish=r=>{job.rawResult=r;job.summary=r.summary;job.result=engineStep&&r.install?{...r,install:engineStep.merge(r.install)}:r;emit();};+ publish(result);+ const engineTask=engineStep?engineStep.run():null;+ try{+ for(;;){+ if(job.state!=='running')return;+ await new Promise(resolve=>setTimeout(resolve,1500));+ result=await tool('strata_install');+ publish(result);+ if(result.install&&!result.install.running){+ if(result.install.exit_code!==0)throw new Error(result.install.error??result.summary);+ if(engineTask){job.summary='Model files are ready. Finishing the engine for this PC…';emit();await engineTask;publish(result);}+ await refresh(true);+ const note=engineStep?.summaryNote();+ const finalResult=engineStep?job.result:result;+ if(note)return {...finalResult,summary:note};+ if(args.loadAfter){const model=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;return loadEngine(job,{model,multiple:!!args.multiple,resourceProfile:args.resourceProfile,vision:args.loadVision});}+ return finalResult;+ }+ }+ }catch(error){job.engineAbort?.abort();throw error;}+ }+ function terminate(proc,signal='SIGTERM'){if(!proc)return;if(process.platform!=='win32'&&proc.pid){try{process.kill(-proc.pid,signal);return;}catch{}}proc.kill(signal);}+ async function stopProcess(proc){if(!proc||proc.exitCode!=null)return;await new Promise(resolve=>{const timeout=setTimeout(()=>{terminate(proc,'SIGKILL');resolve();},8000);proc.once('exit',()=>{clearTimeout(timeout);resolve();});terminate(proc);});}+ async function unload(id,force=false){const instance=instances.get(id);if(!instance)throw new Error('This model is no longer loaded.');if(!force&&[...jobs.values()].some(j=>j.kind==='benchmark'&&j.state==='running'&&j.instanceId===id))throw new Error('Stop the benchmark before unloading this model.');if(!force&&busy(requests().filter(r=>r.instanceId===id)))throw new Error('Finish or cancel this model’s requests first.');instance.status='unloading';if(instance.profile){try{await control.stop(instance.profile);}catch(error){if(!force){instance.status='error';instance.error=error.message;emit();throw error;}}}else await stopProcess(processes.get(id));processes.delete(id);instances.delete(id);try{unlinkSync(instance.configPath);}catch{}if(defaultId===id)defaultId=instances.keys().next().value??null;emit();return state();}+ /* Delete a downloaded model: stop it first, then the installer removes the model's own files and its run config and keeps+ whatever another installed model still uses (shared MTP draft, shared PLE shard). */+ async function removeModel(job,args){if(!safeId(args.model))throw new Error('Choose an installed model.');+ if(externalRunning().length)throw new Error('Stop the native server running outside this UI before deleting a model.');+ for(const instance of [...instances.values()].filter(i=>i.model===args.model)){if(busy(requests().filter(r=>r.instanceId===instance.id)))throw new Error('Finish or cancel requests before deleting this model.');await unload(instance.id);}+ job.summary='Deleting downloaded files…';emit();+ const result=await tool('strata_remove',{model:args.model,confirm:true});+ if(result.failed?.length)throw new Error(`Some files could not be removed: ${result.failed.slice(0,3).join('; ')}`);+ await refresh(true);return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};}+ /* The configuration a load starts the engine with (before its port and key): the saved model config, the user's choices and the resource profile. The tuner measures exactly this, so a saved tuning belongs to the same choices a load makes. */+ function buildConfig(args,config){+ const vision=runtimeVision(config,args.vision);+ const visionPreferences=args.vision!==undefined?{ui_vision_enabled:args.vision!=='no',ui_vision_device:args.vision==='no'?config.ui_vision_device??'yes':args.vision}:{};+ const resources=args.resourceProfile?resourceSettings({...config,vision},snapshot.hardware,args.resourceProfile,modelArena(args.model)):null;+ const cfg={...config,...visionPreferences,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),host:'127.0.0.1',open_browser:false,...validateNativeSettings(args.values??{}),vision};+ if(args.gpus!==undefined){const detected=new Set((snapshot.hardware?.gpus??[]).map(g=>g.index));if(!Array.isArray(args.gpus)||!args.gpus.length||new Set(args.gpus).size!==args.gpus.length||args.gpus.some(g=>!Number.isInteger(g)||!detected.has(g)))throw new Error('Choose distinct detected GPUs. CPU-only text inference is not supported by this native adapter.');cfg.gpu=args.gpus.length===1?args.gpus[0]:args.gpus;cfg.layer_split=args.gpus.length>1?validateNativeSettings({layer_split:args.layerSplit??'auto'}).layer_split:'auto';if(cfg.layer_split!=='auto'&&cfg.layer_split.split(',').length!==args.gpus.length-1)throw new Error('Choose one layer split point between each pair of GPUs.');}+ if(cfg.vram_reserve_mib!==undefined&&cfg.vram_reserve_mib!==null){cfg.args=[...(cfg.args??[])];const at=cfg.args.indexOf('--vram-reserve-mib');if(at>=0)cfg.args.splice(at,2);cfg.args.push('--vram-reserve-mib',String(cfg.vram_reserve_mib));}if(cfg.vision){if(cfg.vision_tokens!=null)cfg.vision={...cfg.vision,max_tokens:cfg.vision_tokens};if(cfg.vision_min_tokens!=null)cfg.vision={...cfg.vision,min_tokens:cfg.vision_min_tokens};}cfg.mcp={...(cfg.mcp??{}),...(cfg.mcp_timeout_s!=null?{timeout_s:cfg.mcp_timeout_s}:{}),...(cfg.mcp_max_rounds!=null?{max_rounds:cfg.mcp_max_rounds}:{}),...(cfg.mcp_max_result_chars!=null?{max_result_chars:cfg.mcp_max_result_chars}:{})};+ for(const arg of cfg.args??[])if(arg.endsWith('.gguf')&&!existsSync(resolve(repo(),arg)))throw new Error('An engine argument names a missing GGUF. Restore the saved arguments or repair the files.');+ return {cfg,resources,visionPreferences};+ }+ async function loadEngine(job,args){+ await refresh(true);if(job.state!=='running')return;const {config,entry}=record(args.model);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');}if(!entry.ready)throw new Error('Some model files are missing. Use Download / repair to restore them.');+ if(externalRunning().length)throw new Error('A Strata server is already running outside this UI. Stop it before loading here, or connect its API in Settings → Models.');+ if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.');+ const {cfg,resources,visionPreferences}=buildConfig(args,config);++ /* Installed app: several requests at once by default (4, fewer where the card has no room), unless a number was chosen. */++ const parallelChoice=packaged?chooseParallel({config:cfg,values:args.values??{},hardware:snapshot.hardware?.gpus?.length?snapshot.hardware:{gpus:hardwareProbe()??[]}}):null;++ let parallelNote=null;++ /* The agent asks for long answers (a thinking model can use most of the window): let the engine clamp the output to what is left of the context instead of refusing the request. */++ if(packaged&&cfg.fit_max_tokens===undefined)cfg.fit_max_tokens=true;++ if(parallelChoice){const applied=applyParallel(cfg,parallelChoice);for(const k of Object.keys(cfg))if(!(k in applied.cfg))delete cfg[k];Object.assign(cfg,applied.cfg);parallelNote=applied.note;}+ const fingerprint=createHash('sha256').update(JSON.stringify({...cfg,api_key:undefined,port:undefined})).digest('hex');+ const placement=Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu];const matching=[...instances.values()].find(i=>i.model===args.model&&JSON.stringify(i.gpus)===JSON.stringify(placement));+ if(matching?.status==='ready'&&matching.fingerprint===fingerprint&&(args.multiple||instances.size===1))return {summary:`${matching.label} is already ready.`,instanceId:matching.id};+ const wasDefault=matching?.id===defaultId;+ const id=matching?.id??randomUUID();let apiModelId=matching?.apiModelId??args.model,suffix=1;while(!matching&&[...instances.values()].some(i=>i.apiModelId===apiModelId))apiModelId=`${args.model}--${++suffix}`;+ cfg.aliases=[...new Set([...(Array.isArray(cfg.aliases)?cfg.aliases:typeof cfg.aliases==='string'?cfg.aliases.split(',').map(s=>s.trim()).filter(Boolean):[]),apiModelId])];+ const key=randomBytes(32).toString('hex');cfg.api_key=key;cfg.port=await freePort(args.port);+ const work=join(directory,'native-instances');mkdirSync(work,{recursive:true});const configPath=join(work,`${id}.json`);+ const py=packaged?null:venvPython(repo());if(!packaged&&!existsSync(py))throw new Error('The Strata Python environment is missing. Use Download / repair first.');+ if(job.state!=='running')return;+ await beforeLoad();if(job.state!=='running')return;+ if(!args.multiple){if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel native requests before switching models.');for(const id of [...instances.keys()])await unload(id);}else if(matching)await unload(matching.id);+ if(job.state!=='running')return;+ writeFileSync(configPath,JSON.stringify(cfg,null,2),{mode:0o600});- const instance={id,apiModelId,fingerprint,context:entry.context??0,aliases:cfg.aliases??[],vision:!!cfg.vision,model:args.model,label:entry.model_name??args.model,port:cfg.port,gpus:Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu],status:'loading',phase:'loading',key,configPath,loadedAt:new Date().toISOString(),metrics:null,error:null};++ const instance={id,apiModelId,fingerprint,context:entry.context??0,aliases:cfg.aliases??[],vision:!!cfg.vision,model:args.model,label:entry.model_name??args.model,port:cfg.port,gpus:Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu],status:'loading',phase:'loading',parallel:cfg.parallel??1,mcpServers:cfg.mcp_servers??cfg.mcpServers??{},key,configPath,loadedAt:new Date().toISOString(),metrics:null,error:null};+ let proc=null,started=null,retried=null;+ if(packaged){+ /* The engine starts under Control's owner runtime, not as our child: a saved profile per slot, then `runtime start`. */+ const used=new Set([...instances.values()].map(i=>i.profile));let slot=1;while(used.has('app-'+slot))slot++;instance.profile='app-'+slot;+ instances.set(id,instance);if(!defaultId||!args.multiple||wasDefault)defaultId=id;emit();+ const startWith=value=>{writeFileSync(configPath,JSON.stringify(value,null,2),{mode:0o600});return control.stop(instance.profile).catch(()=>{}).then(()=>control.saveProfile(instance.profile,configPath)).then(()=>control.start(instance.profile,{waitSeconds:300}));};+ started=startWith(cfg);+ started.then(()=>append(id,'Strata Control reports the engine is ready.'),error=>{append(id,error.message);});+ try{await started;}catch(error){const said=humanStartError(error);- /* A start that died gets ONE automatic second try with a safer memory setting (never saved, never repeated), unless the caller says no. */- const safer=args.retrySafer===false||job.state!=='running'?null:saferStart(cfg,snapshot.hardware,modelArena(args.model),said);- if(!safer){instance.status='error';instance.error=said;emit();throw new Error(said);}- retried=safer;append(id,`The first start stopped (${said}). Starting once more: ${safer.detail}`);job.summary=safer.words;job.details=[said,`Second try: ${safer.detail}`];instance.notice=safer.words;emit();- try{await startWith(safer.config);append(id,'Strata Control reports the engine is ready (second try).');}- catch(second){const said2=humanStartError(second);instance.status='error';instance.error=said2===said?said2:`${said2} (after one automatic second try with a safer setting: ${safer.detail}; the first stop was: ${said})`;emit();throw new Error(instance.error);}}++ /* ONE automatic second try in all, never saved, never repeated (args.retrySafer false turns it off): with a safer memory setting when the++ failure looks like a memory stop, and without several-requests-at-once when that was the app's own default (not a number the user chose).++ Both changes ride on the same single try, with the plain sentence of the memory change when there is one. */++ const allowed=args.retrySafer!==false&&job.state==='running';++ const safer=allowed?saferStart(cfg,snapshot.hardware,modelArena(args.model),said):null;++ const dropParallel=allowed&&cfg.parallel>1&&!parallelChoice?.explicit;++ if(!safer&&!dropParallel){instance.status='error';instance.error=said;emit();throw new Error(said);}++ let retryConfig=safer?safer.config:cfg;if(dropParallel)retryConfig=withoutParallel(retryConfig);++ const words=safer?safer.words:FALLBACK_NOTE,detail=[safer?.detail,dropParallel?'one request at a time':null].filter(Boolean).join('; ');++ retried={words,detail};if(dropParallel){instance.parallel=1;if(!safer)parallelNote=FALLBACK_NOTE;}++ append(id,`The first start stopped (${said}). Starting once more: ${detail}`);job.summary=words;job.details=[said,`Second try: ${detail}`];instance.notice=words;emit();++ try{await startWith(retryConfig);append(id,'Strata Control reports the engine is ready (second try).');}++ catch(second){const said2=humanStartError(second);instance.status='error';instance.error=said2===said?said2:`${said2} (after one automatic second try with a safer setting: ${detail}; the first stop was: ${said})`;emit();throw new Error(instance.error);}}+ } else {+ proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8',STRATA_API_KEY:''}});+ instances.set(id,instance);processes.set(id,proc);if(!defaultId||!args.multiple||wasDefault)defaultId=id;+ for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{const lines=chunk.toString().split('\n').filter(Boolean);lines.forEach(line=>append(id,line.replaceAll(key,'[redacted]')));job.summary=lines.at(-1)??job.summary;emit();});+ proc.on('error',error=>{instance.status='error';instance.error=error.message;emit();});proc.on('exit',code=>{if(instances.has(id)&&instance.status!=='unloading'){instance.status='error';instance.error=`Engine stopped${code===null?'':` (exit ${code})`}. Open diagnostics or reload.`;emit();}});emit();+ }+ const deadline=Date.now()+300000;while(Date.now()<deadline&&job.state==='running'){+ if(instance.status==='error')throw new Error(instance.error);- try{const response=await fetcher(`http://127.0.0.1:${instance.port}/health`,{headers:{authorization:`Bearer ${key}`},signal:AbortSignal.timeout(2000)});if(job.state!=='running'){await unload(id);return;}if(response.ok){instance.status='ready';instance.phase='idle';if(resources||args.vision!==undefined)writeModelConfig(record(args.model).path,{...config,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),...visionPreferences});emit();ensurePoll();return {summary:retried?`${instance.label} is ready, after a second try: ${retried.words}`:`${instance.label} is ready.`,instanceId:id};}}catch{}++ try{const response=await fetcher(`http://127.0.0.1:${instance.port}/health`,{headers:{authorization:`Bearer ${key}`},signal:AbortSignal.timeout(2000)});if(job.state!=='running'){await unload(id);return;}if(response.ok){instance.status='ready';instance.phase='idle';if(resources||args.vision!==undefined)writeModelConfig(record(args.model).path,{...config,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),...visionPreferences});emit();ensurePoll();instance.parallelNote=parallelNote;return {summary:retried?`${instance.label} is ready, after a second try: ${retried.words}`:`${instance.label} is ready.${parallelNote?' '+parallelNote:''}`,instanceId:id};}}catch{}+ await new Promise(resolve=>setTimeout(resolve,1200));+ }+ if(job.state!=='running'){await unload(id);return;}+ if(instance.profile)await control.stop(instance.profile).catch(()=>{});else await stopProcess(proc);instance.status='error';instance.error='Loading took more than five minutes. Check the engine log and free memory.';throw new Error(instance.error);+ }+ async function freePort(requested){for(let port=Number(requested??18500);port<=Number(requested??18500)+20;port++){if(!Number.isInteger(port)||port<1024||port>65535)throw new Error('Choose a port from 1024 to 65535.');if([...instances.values()].some(i=>i.port===port)){if(requested)throw new Error('This private engine port is already in use.');continue;}const available=await new Promise(resolve=>{const probe=createServer();probe.once('error',()=>resolve(false));probe.listen(port,'127.0.0.1',()=>probe.close(()=>resolve(true)));});if(available)return port;if(requested)throw new Error('This private engine port is already in use.');}throw new Error('No free private engine port was found.');}+ let pollCount=0;+ /* The engine's metrics carry every finished request with `?requests=all`: a long session makes that a large JSON that the host parses and+ pushes to the window every 2 s. The last dozen is what the app shows live; the full list is refreshed every tenth poll. */+ async function poll(){if(polling||closing)return;polling=true;const full=pollCount++%10===0;try{await Promise.all([...instances.values()].map(async instance=>{if(instance.status!=='ready')return;try{const response=await fetcher(`http://127.0.0.1:${instance.port}/metrics${full?'?requests=all':''}`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(!response.ok)throw new Error('Metrics unavailable');const fresh=await response.json();const older=instance.metrics?.requests,recent=fresh.requests;instance.metrics=full||!Array.isArray(older)||!Array.isArray(recent)||!recent.length?fresh:{...fresh,requests:[...recent,...older.filter(r=>Number(r.time)<Math.min(...recent.map(x=>Number(x.time))))]};const tools=await fetcher(`http://127.0.0.1:${instance.port}/mcp`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(tools.ok)instance.metrics.mcp=await tools.json();instance.phase=instance.metrics.live?.state??'idle';}catch{instance.metrics=null;instance.phase='unavailable';}}));emit();}finally{polling=false;}}+ function ensurePoll(){if(!timer){timer=setInterval(()=>void poll(),2000);timer.unref?.();}void poll();}+ async function benchmark(job,args){const instance=resolveInstance(args.instanceId);job.instanceId=instance.id;if(busy(requests().filter(r=>r.instanceId===instance.id)))throw new Error('Wait for this model to finish before benchmarking.');const started=Date.now();job.abort=new AbortController();const response=await fetcher(`http://127.0.0.1:${instance.port}/v1/chat/completions`,{method:'POST',headers:{'content-type':'application/json',authorization:`Bearer ${instance.key}`},signal:AbortSignal.any([job.abort.signal,AbortSignal.timeout(180000)]),body:JSON.stringify({model:instance.apiModelId,messages:[{role:'user',content:'Explain how a rainbow forms in clear, simple language.'}],temperature:0,reasoning_effort:'none',max_tokens:200,stream:false})});const body=await response.json();if(!response.ok)throw new Error(body.error?.message??'Benchmark failed.');if(job.state!=='running')return;const result={summary:'Measured benchmark complete.',at:new Date().toISOString(),model:instance.apiModelId,durationMs:Date.now()-started,tokensIn:body.usage?.prompt_tokens??null,tokensOut:body.usage?.completion_tokens??null,outputTps:body.timings?.predicted_per_second??null,promptTps:body.timings?.prompt_per_second??null,source:'engine',settings:'Greedy · thinking off · up to 200 output tokens'};writeFileSync(join(directory,'native-benchmark.json'),JSON.stringify(result,null,2),{mode:0o600});return result;}+ function resolveInstance(id){const aliases=[...instances.values()].filter(i=>i.aliases?.includes(id));if(aliases.length>1&&!instances.has(id)&&![...instances.values()].some(i=>i.apiModelId===id))throw new Error('This alias matches more than one instance. Choose its exact model ID.');const i=instances.get(id)??[...instances.values()].find(i=>i.apiModelId===id)??aliases[0]??(!id&&instances.size===1?[...instances.values()][0]:undefined);if(!i)throw new Error('Choose a loaded model ID.');if(i.status!=='ready')throw new Error('This model is not ready.');return i;}+ async function program(job,args){if(packaged)return componentProgram(job);if(externalRunning().length)throw new Error('Stop the native server running outside this UI before changing engine files.');if(instances.size)throw new Error('Unload native models before changing engine files.');const folder=repo();let {command,args:prefix}=python(),argv;+ if(job.kind==='calibrate'||job.kind==='tune'){if(!state().capabilities.calibration)throw new Error('This installation calibrates NVIDIA GPUs only. Use the short benchmark on other devices.');const model=args.model??snapshot.installed?.models?.[0]?.model;const chosen=record(model);if(!chosen.entry.ready)throw new Error('Prepare this model before calibrating.');command=venvPython(folder);prefix=[];if(!existsSync(command))throw new Error('Prepare the Python environment first.');argv=['-c','import sys; from pathlib import Path; import setup; sys.exit(0 if setup.calibrate_config(Path(sys.argv[1])) else 1)',chosen.path];}+ else if(job.kind==='rollback'){if(!previousEngine())throw new Error('No saved previous engine is available.');argv=[join(folder,'setup.py'),'--rollback-engine'];}+ else if(job.kind==='update-engine'){if(!snapshot.installed?.models?.length)throw new Error('Prepare a model first. Its installer downloads the matching engine.');argv=[join(folder,'setup.py'),'--update'];}+ else if(job.kind==='update-strata'){const status=await execute('git',['status','--porcelain'],folder);if(status.trim())throw new Error('This Strata checkout has local edits. Save or commit them before updating.');const remote=await execute('git',['remote','get-url','origin'],folder);if(!/^https:\/\/github\.com\/Niko1221\/Strata(?:\.git)?\s*$/.test(remote))throw new Error('The native installation must use the official Strata repository to update here.');await execute('git',['pull','--ff-only'],folder);argv=[join(folder,'setup.py'),'--update'];}+ else throw new Error('Unsupported native operation.');+ return new Promise((resolve,reject)=>{const proc=spawnProcess(command,[...prefix,...argv],{cwd:folder,windowsHide:true,detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1'}});job.process=proc;for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{chunk.toString().split('\n').filter(Boolean).forEach(line=>append(job.id,line));job.summary=chunk.toString().trim().slice(-500);emit();});proc.on('error',reject);proc.on('exit',code=>{delete job.process;code===0?resolve({summary:job.kind==='calibrate'?'Calibration complete. Native settings were saved.':'Native installation updated.'}):reject(new Error(`Operation stopped (exit ${code}). Open diagnostics for details.`));});});+ }+ /* Packaged app: engine and Control updates and the engine rollback go through Control's explicit update step (`strata update`,+ `strata components rollback`), never through git, setup.py or a download in this process. The app itself is updated by the+ shell's signed Tauri updater. Models are not part of any of it. */+ async function componentProgram(job){+ if(!['update-engine','update-strata','rollback'].includes(job.kind)||typeof control.update!=='function')throw new Error(NO_INSTALL);+ if(instances.size)throw new Error('Unload native models before changing engine files.');+ job.abort=new AbortController();+ const subject=job.kind==='update-strata'?'Strata':'engine';+ try{return await componentSteps(job,subject);}catch(error){throw error?.details!==undefined&&error.message?error:plainError(error,subject);}+ }+ async function componentSteps(job,subject){+ const onEvent=event=>{+ if(event.event==='progress'){job.summary=`Downloading: ${event.percent}%`;job.result={install:{step:job.summary,download:{file:event.label,percent:event.percent}}};}+ else if(event.event==='phase'&&PHASE_TEXT[event.phase])job.summary=PHASE_TEXT[event.phase];+ else if(event.event==='waiting')job.summary='Waiting for the running model to stop…';+ emit();+ };+ if(job.kind==='rollback'){const done=await control.rollbackEngine();return {summary:'The previous engine is back. Your models and settings are unchanged.',result:done};}+ if(job.kind==='update-engine'){const done=await control.update({engine:true,control:false,onEvent,signal:job.abort.signal});return {summary:updateSummary(done),result:done};}+ const done=await control.update({engine:false,control:true,onEvent,signal:job.abort.signal});+ const notes=[updateSummary(done)];+ if(appUpdater){+ job.summary='Looking for a new version of the app…';emit();+ const verdict=await appUpdater.check();+ if(verdict.available){await appUpdater.install({signal:job.abort.signal,onProgress:p=>{if(p.total){job.summary=`Downloading the app update: ${Math.round(100*p.downloaded/p.total)}%`;job.result={install:{step:job.summary,download:{file:'Strata app',percent:Math.round(100*p.downloaded/p.total)}}};emit();}}});notes.push('The app update is installed. Strata will restart.');}+ }+ return {summary:notes.filter(Boolean).join(' '),result:done};+ }+ function updateSummary(done){const r=(done.results??[]).filter(x=>x.status==='updated').map(x=>x.component==='engine'?'The engine is updated and ready.':'Strata is updated. It takes effect the next time you open the app.');return r.length?r.join(' '):'Everything is already up to date.';}+ function execute(cmd,args,cwd){return new Promise((resolve,reject)=>{let output='';const process=spawnProcess(cmd,args,{cwd,stdio:['ignore','pipe','pipe']});process.stdout.on('data',c=>{output+=c;if(output.length>100000)process.kill();});process.stderr.on('data',c=>append('update',c.toString()));process.on('error',reject);process.on('exit',code=>code===0?resolve(output):reject(new Error('Git could not update this installation. Open diagnostics.')));});}+ function writeModelConfig(path,next){copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);}+ async function tune(job,args){+ await refresh(true);if(job.state!=='running')return;+ const chosen=record(args.model);resourceSettings(chosen.config,snapshot.hardware,args.profile,modelArena(args.model));+ if(!chosen.entry.ready)throw new Error('Prepare the model before tuning.');+ if(externalRunning().length)throw new Error('Stop the native server outside this UI before tuning.');+ if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish requests before tuning.');+ for(const id of [...instances.keys()])await unload(id);+ if(job.state!=='running')return;+ const initialValues=resourceSettings(chosen.config,snapshot.hardware,args.profile,modelArena(args.model));writeModelConfig(chosen.path,{...chosen.config,...initialValues,ui_resource_profile:args.profile});+ if(args.calibrate!==false&&state().capabilities.calibration){job.summary='Measuring the best engine settings for this computer…';emit();await program(job,args);}+ if(job.state!=='running')return;+ const current=record(args.model),values=resourceSettings(current.config,snapshot.hardware,args.profile,modelArena(args.model));+ const next={...current.config,...values,ui_resource_profile:args.profile};+ writeModelConfig(current.path,next);+ job.summary='Applying your resource preference and loading the model…';emit();+ const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:current.config.vision?args.vision:'no'});+ if(job.state!=='running'||!loaded?.instanceId)return;+ job.summary='Checking your model’s speed…';emit();+ const measured=await benchmark(job,{instanceId:loaded.instanceId});+ return {...loaded,...measured,summary:'Your model is tuned and ready.',profile:args.profile};+ }+ /* What the tuner measures is what a load would start: the saved model config with the user's choices and the resource profile. */+ function tuneConfig(args){const {config,entry}=record(args.model);if(!entry.ready)throw new Error('Prepare the model before tuning it.');const {cfg}=buildConfig({model:args.model,vision:args.vision,resourceProfile:args.resourceProfile,gpus:args.gpus},config);return {path:writeTuneConfig(directory,args.model,cfg),entry};}+ async function tuneStatus(args){await refresh();const {path}=tuneConfig(args);return autotuner.status(path);}+ async function autotune(job,args){+ await refresh(true);if(job.state!=='running')return;+ if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');}+ const {path}=tuneConfig(args);+ if(externalRunning().length)throw new Error('Stop the native server running outside this UI before tuning.');+ if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish requests before tuning.');+ for(const id of [...instances.keys()])await unload(id);+ if(job.state!=='running')return;+ job.summary='Finding the fastest settings for your PC…';emit();+ const room=args.resourceProfile==='work';+ 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.');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});}+ 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();}+ 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,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,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close};+}diff --cc apps/host/src/locales/de.jsonindex aa7e91109,dcb164e31..9abc7d78a--- a/apps/host/src/locales/de.json+++ b/apps/host/src/locales/de.json@@@ -2569,48 -2569,11 +2569,55 @@@"s2568": "Ausgeführt","s2569": "In diesem Modus nicht erlaubt. Es wurde nichts ausgeführt.","s2570": "Vorschau erneut abspielen",- "s2571": "Was diese Aufgabe darf",- "s2572": "Nur ansehen, nichts ändern",- "s2573": "Vor jeder Änderung anhalten und mir Bescheid geben",- "s2574": "Darf Änderungen vornehmen",- "s2575": "Aufgabe abgeschlossen",- "s2576": "Aufgabe braucht Ihr Ja",- "s2577": "Aufgabe fehlgeschlagen"+ "s2571": "Noch etwa {0} Min.",+ "s2572": "Noch etwa {0} Std. {1} Min.",+ "s2573": "Noch etwa {0} Std.",+ "s2574": "Standardmäßig folgt es den Einstellungen Ihres Computers.",+ "s2575": "Für dieses Modell ist das Lesen von Bildern nicht verfügbar.",+ "s2576": "Schalten Sie das Lesen von Bildern aus und versuchen Sie es erneut.",+ "s2577": "Das Modell wurde beim Start beendet, wahrscheinlich weil dem PC der Arbeitsspeicher ausging.",+ "s2578": "Schließen Sie andere Programme und versuchen Sie es erneut, oder wählen Sie „20 % für meine Arbeit frei lassen“. Im Expertenmodus können Sie außerdem die Option für wenig Arbeitsspeicher aktivieren, damit ein Teil des Modells von der SSD gelesen wird.",+ "s2579": "Das Laden dauert zu lange.",+ "s2580": "Dem PC fehlt möglicherweise Arbeitsspeicher. Schließen Sie andere Programme und versuchen Sie es erneut.",+ "s2581": "Die Strata-Engine für diesen Computer ist noch nicht installiert.",+ "s2582": "Sie wird beim Herunterladen eines Modells hinzugefügt. Laden Sie Ihr Modell erneut herunter, um sie hinzuzufügen.",+ "s2583": "Der Download konnte das Internet nicht erreichen.",+ "s2584": "Prüfen Sie Ihre Verbindung und drücken Sie dann „Download fortsetzen“.",+ "s2585": "Eine heruntergeladene Datei hat die Sicherheitsprüfung von Strata nicht bestanden.",+ "s2586": "Drücken Sie „Download fortsetzen“, dann lädt Strata sie erneut herunter.",+ "s2587": "Der Coding-Assistent ist auf diesem Computer noch nicht installiert.",+ "s2588": "Der Chat funktioniert auch ohne ihn.",+ "s2589": "Strata konnte seine eigenen Komponenten nicht lesen.",+ "s2590": "Schließen Sie Strata und öffnen Sie es erneut. Tritt das Problem weiterhin auf, installieren Sie die App neu.",+ "s2591": "Etwas ist schiefgelaufen.",+ "s2592": "Versuchen Sie es erneut. Tritt das Problem weiterhin auf, öffnen Sie „Details“ und geben Sie diese bei einer Supportanfrage an.",+ "s2593": "Ihr Computer wird geprüft …",+ "s2594": "Alles wird vorbereitet …",+ "s2595": "Ihr Modell wird heruntergeladen …",+ "s2596": "Ihr Modell wird für Strata vorbereitet …",+ "s2597": "Komponente aktualisieren",+ "s2598": "Aktualisiert die Engine für diesen Computer. Ihre Modelle und Einstellungen bleiben erhalten.",+ "s2599": "Gespeichert unter {0}",+ "s2600": "Haben Sie bereits ein unterstütztes Modell auf diesem Computer? Wählen Sie den Ordner mit seinen Dateien. Strata prüft sie, bereitet das Modell vor und lädt es. Es wird nichts kopiert oder heruntergeladen.",+ "s2601": "Ordner mit den GGUF-Dateien",+ "s2602": "Vollständiger Pfad zum Ordner",+ "s2603": "Dateien prüfen",+ "s2604": "Modell gefunden",+ "s2605": "{0} Dateien · {1}",+ "s2606": "Vorbereiten und laden",+ "s2607": "Teile dieses Modells fehlen, oder der Ordner enthält mehr als ein Modell.",+ "s2608": "Legen Sie alle Teile eines Modells in einen Ordner und prüfen Sie erneut.",+ "s2609": "Strata kann diese Dateien noch nicht ausführen.",+ "s2610": "Strata führt die Qwen3.8-Flash-Next-Modelle aus. Laden Sie eines unter „Modelle“ herunter oder wählen Sie einen Ordner mit dessen Dateien.",+ "s2611": "Diese Dateien konnten nicht geprüft werden.",+ "s2612": "Prüfen Sie, ob der Ordner vollständige GGUF-Dateien enthält, und versuchen Sie es erneut.",+ "s2613": "Denkbudget",- "s2614": "Unbegrenzt"++ "s2614": "Unbegrenzt",++ "s2615": "Was diese Aufgabe darf",++ "s2616": "Nur ansehen, nichts ändern",++ "s2617": "Vor jeder Änderung anhalten und mir Bescheid geben",++ "s2618": "Darf Änderungen vornehmen",++ "s2619": "Aufgabe abgeschlossen",++ "s2620": "Aufgabe braucht Ihr Ja",++ "s2621": "Aufgabe fehlgeschlagen"}diff --cc apps/host/src/locales/en.jsonindex 5a850a02f,78d647181..dfacd7dd2--- a/apps/host/src/locales/en.json+++ b/apps/host/src/locales/en.json@@@ -2569,48 -2569,11 +2569,55 @@@"s2568": "Ran","s2569": "Not allowed in this mode. Nothing ran.","s2570": "Replay preview",- "s2571": "What this task may do",- "s2572": "Look only, change nothing",- "s2573": "Stop and tell me before changing anything",- "s2574": "Allowed to make changes",- "s2575": "Task finished",- "s2576": "Task needs your yes",- "s2577": "Task failed"+ "s2571": "About {0} min left",+ "s2572": "About {0} h {1} min left",+ "s2573": "About {0} h left",+ "s2574": "System follows your computer by default.",+ "s2575": "Picture reading isn’t available for this model.",+ "s2576": "Turn off picture reading and try again.",+ "s2577": "The model stopped while starting, most likely because the PC ran low on memory.",+ "s2578": "Close other programs and try again, or choose “Leave 20% for my work”. In Expert mode you can also turn on the low-RAM option, so part of the model is read from the SSD.",+ "s2579": "Loading is taking too long.",+ "s2580": "The PC may be short on memory. Close other programs and try again.",+ "s2581": "Strata’s engine for this computer isn’t installed yet.",+ "s2582": "It is added when you download a model. Download your model again to add it.",+ "s2583": "The download couldn’t reach the internet.",+ "s2584": "Check your connection, then press Resume download.",+ "s2585": "A downloaded file didn’t pass Strata’s safety check.",+ "s2586": "Press Resume download and Strata will fetch it again.",+ "s2587": "The coding assistant isn’t installed on this computer yet.",+ "s2588": "Chat works without it.",+ "s2589": "Strata couldn’t read its own components.",+ "s2590": "Close and reopen Strata. If this keeps happening, reinstall the app.",+ "s2591": "Something went wrong.",+ "s2592": "Try again. If it keeps happening, open Details and share them when you ask for help.",+ "s2593": "Checking your computer…",+ "s2594": "Getting things ready…",+ "s2595": "Downloading your model…",+ "s2596": "Preparing your model for Strata…",+ "s2597": "Update component",+ "s2598": "Update the engine for this computer. Your models and settings are kept.",+ "s2599": "Saved to {0}",+ "s2600": "Already have a supported model on this computer? Choose the folder that holds its files. Strata checks them, prepares the model and loads it. Nothing is copied or downloaded.",+ "s2601": "Folder with the GGUF files",+ "s2602": "Full path to the folder",+ "s2603": "Check files",+ "s2604": "Model found",+ "s2605": "{0} files · {1}",+ "s2606": "Prepare and load",+ "s2607": "Some parts of this model are missing, or the folder holds more than one model.",+ "s2608": "Put every part of one model in one folder, then check again.",+ "s2609": "Strata can’t run these files yet.",+ "s2610": "Strata runs the Qwen3.8-Flash-Next models. Download one from Models, or choose a folder with its files.",+ "s2611": "These files could not be checked.",+ "s2612": "Check that the folder holds complete GGUF files, then try again.",+ "s2613": "Thinking budget",- "s2614": "No limit"++ "s2614": "No limit",++ "s2615": "What this task may do",++ "s2616": "Look only, change nothing",++ "s2617": "Stop and tell me before changing anything",++ "s2618": "Allowed to make changes",++ "s2619": "Task finished",++ "s2620": "Task needs your yes",++ "s2621": "Task failed"}diff --cc apps/host/src/locales/es.jsonindex 79ffb4cc4,2e5ba376f..c5eb8725d--- a/apps/host/src/locales/es.json+++ b/apps/host/src/locales/es.json@@@ -2569,48 -2569,11 +2569,55 @@@"s2568": "Ejecutado","s2569": "No se permite en este modo. No se ejecutó nada.","s2570": "Repetir vista previa",- "s2571": "Qué puede hacer esta tarea",- "s2572": "Solo mirar, no cambiar nada",- "s2573": "Detenerse y avisarme antes de cambiar algo",- "s2574": "Puede hacer cambios",- "s2575": "Tarea terminada",- "s2576": "La tarea necesita tu visto bueno",- "s2577": "La tarea falló"+ "s2571": "Quedan unos {0} min",+ "s2572": "Quedan unas {0} h {1} min",+ "s2573": "Quedan unas {0} h",+ "s2574": "De forma predeterminada sigue el ajuste de tu equipo.",+ "s2575": "La lectura de imágenes no está disponible para este modelo.",+ "s2576": "Desactiva la lectura de imágenes e inténtalo de nuevo.",+ "s2577": "El modelo se detuvo al iniciarse, probablemente porque el equipo se quedó sin memoria.",+ "s2578": "Cierra otros programas e inténtalo de nuevo, o elige «Dejar el 20 % para mi trabajo». En el modo experto también puedes activar la opción de poca RAM para que una parte del modelo se lea desde el SSD.",+ "s2579": "La carga está tardando demasiado.",+ "s2580": "Puede que al equipo le falte memoria. Cierra otros programas e inténtalo de nuevo.",+ "s2581": "El motor de Strata para este equipo aún no está instalado.",+ "s2582": "Se añade al descargar un modelo. Vuelve a descargar tu modelo para añadirlo.",+ "s2583": "La descarga no pudo conectarse a internet.",+ "s2584": "Revisa tu conexión y pulsa «Reanudar descarga».",+ "s2585": "Un archivo descargado no superó la comprobación de seguridad de Strata.",+ "s2586": "Pulsa «Reanudar descarga» y Strata la obtendrá de nuevo.",+ "s2587": "El asistente de programación aún no está instalado en este equipo.",+ "s2588": "El chat funciona sin él.",+ "s2589": "Strata no pudo leer sus propios componentes.",+ "s2590": "Cierra y vuelve a abrir Strata. Si sigue ocurriendo, reinstala la aplicación.",+ "s2591": "Algo salió mal.",+ "s2592": "Inténtalo de nuevo. Si sigue ocurriendo, abre «Detalles» y compártelos cuando pidas ayuda.",+ "s2593": "Revisando tu equipo…",+ "s2594": "Preparando todo…",+ "s2595": "Descargando tu modelo…",+ "s2596": "Preparando tu modelo para Strata…",+ "s2597": "Actualizar componente",+ "s2598": "Actualiza el motor de este equipo. Tus modelos y ajustes se conservan.",+ "s2599": "Guardado en {0}",+ "s2600": "¿Ya tienes un modelo compatible en este equipo? Elige la carpeta con sus archivos. Strata los comprueba, prepara el modelo y lo carga. No se copia ni se descarga nada.",+ "s2601": "Carpeta con los archivos GGUF",+ "s2602": "Ruta completa de la carpeta",+ "s2603": "Comprobar archivos",+ "s2604": "Modelo encontrado",+ "s2605": "{0} archivos · {1}",+ "s2606": "Preparar y cargar",+ "s2607": "Faltan partes de este modelo, o la carpeta contiene más de un modelo.",+ "s2608": "Pon todas las partes de un modelo en una carpeta y vuelve a comprobar.",+ "s2609": "Strata aún no puede ejecutar estos archivos.",+ "s2610": "Strata ejecuta los modelos Qwen3.8-Flash-Next. Descarga uno en Modelos o elige una carpeta con sus archivos.",+ "s2611": "No se pudieron comprobar estos archivos.",+ "s2612": "Comprueba que la carpeta tenga archivos GGUF completos e inténtalo de nuevo.",+ "s2613": "Presupuesto de razonamiento",- "s2614": "Sin límite"++ "s2614": "Sin límite",++ "s2615": "Qué puede hacer esta tarea",++ "s2616": "Solo mirar, no cambiar nada",++ "s2617": "Detenerse y avisarme antes de cambiar algo",++ "s2618": "Puede hacer cambios",++ "s2619": "Tarea terminada",++ "s2620": "La tarea necesita tu visto bueno",++ "s2621": "La tarea falló"}diff --cc apps/host/src/locales/ja.jsonindex 57dc07650,db2ccdca5..9d9ccced3--- a/apps/host/src/locales/ja.json+++ b/apps/host/src/locales/ja.json@@@ -2569,48 -2569,11 +2569,55 @@@"s2568": "実行済み","s2569": "このモードでは許可されていません。何も実行していません。","s2570": "プレビューを再生",- "s2571": "このタスクができること",- "s2572": "見るだけで何も変更しない",- "s2573": "変更の前に止まって知らせる",- "s2574": "変更を許可する",- "s2575": "タスクが完了しました",- "s2576": "タスクに許可が必要です",- "s2577": "タスクが失敗しました"+ "s2571": "あと約 {0} 分",+ "s2572": "あと約 {0} 時間 {1} 分",+ "s2573": "あと約 {0} 時間",+ "s2574": "既定ではお使いのコンピューターの設定に従います。",+ "s2575": "このモデルでは画像の読み取りを使えません。",+ "s2576": "画像の読み取りをオフにして、もう一度お試しください。",+ "s2577": "モデルの起動中に停止しました。パソコンのメモリ不足が原因と考えられます。",+ "s2578": "他のプログラムを閉じてもう一度お試しいただくか、「作業用に 20% を残す」を選んでください。エキスパートモードでは、低メモリのオプションをオンにして、モデルの一部を SSD から読み込むこともできます。",+ "s2579": "読み込みに時間がかかっています。",+ "s2580": "パソコンのメモリが足りない可能性があります。他のプログラムを閉じて、もう一度お試しください。",+ "s2581": "このコンピューター用の Strata エンジンはまだインストールされていません。",+ "s2582": "モデルをダウンロードするときに一緒に追加されます。もう一度モデルをダウンロードして追加してください。",+ "s2583": "ダウンロードがインターネットに接続できませんでした。",+ "s2584": "接続を確認してから、「ダウンロードを再開」を押してください。",+ "s2585": "ダウンロードしたファイルが Strata の安全性チェックに合格しませんでした。",+ "s2586": "「ダウンロードを再開」を押すと、Strata がもう一度取得します。",+ "s2587": "このコンピューターにはコーディングアシスタントがまだインストールされていません。",+ "s2588": "これがなくてもチャットは使えます。",+ "s2589": "Strata が自身のコンポーネントを読み取れませんでした。",+ "s2590": "Strata を閉じて開き直してください。それでも改善しない場合は、アプリを再インストールしてください。",+ "s2591": "問題が発生しました。",+ "s2592": "もう一度お試しください。それでも解決しない場合は「詳細」を開き、サポートに問い合わせる際に共有してください。",+ "s2593": "お使いのコンピューターを確認しています…",+ "s2594": "準備をしています…",+ "s2595": "モデルをダウンロードしています…",+ "s2596": "Strata 用にモデルを準備しています…",+ "s2597": "コンポーネントを更新",+ "s2598": "このコンピューター用のエンジンを更新します。モデルと設定はそのまま残ります。",+ "s2599": "{0} に保存しました",+ "s2600": "対応モデルがすでにこのコンピューターにありますか? そのファイルがあるフォルダーを選んでください。Strata がファイルを確認し、モデルを準備して読み込みます。コピーやダウンロードは行いません。",+ "s2601": "GGUF ファイルのフォルダー",+ "s2602": "フォルダーのフルパス",+ "s2603": "ファイルを確認",+ "s2604": "モデルが見つかりました",+ "s2605": "{0} ファイル · {1}",+ "s2606": "準備して読み込む",+ "s2607": "このモデルの一部が足りないか、フォルダーに複数のモデルが入っています。",+ "s2608": "1 つのモデルのすべてのパーツを 1 つのフォルダーに入れてから、もう一度確認してください。",+ "s2609": "Strata はこれらのファイルをまだ実行できません。",+ "s2610": "Strata は Qwen3.8-Flash-Next のモデルを実行します。「モデル」からダウンロードするか、そのファイルのフォルダーを選んでください。",+ "s2611": "これらのファイルを確認できませんでした。",+ "s2612": "フォルダーに完全な GGUF ファイルがあることを確認して、もう一度お試しください。",+ "s2613": "思考の上限",- "s2614": "上限なし"++ "s2614": "上限なし",++ "s2615": "このタスクができること",++ "s2616": "見るだけで何も変更しない",++ "s2617": "変更の前に止まって知らせる",++ "s2618": "変更を許可する",++ "s2619": "タスクが完了しました",++ "s2620": "タスクに許可が必要です",++ "s2621": "タスクが失敗しました"}diff --cc apps/host/src/locales/ko.jsonindex fd3502de3,b142078e4..a2be9a2e1--- a/apps/host/src/locales/ko.json+++ b/apps/host/src/locales/ko.json@@@ -2569,48 -2569,11 +2569,55 @@@"s2568": "실행됨","s2569": "이 모드에서는 허용되지 않습니다. 실행된 항목이 없습니다.","s2570": "미리보기 다시 재생",- "s2571": "이 작업이 할 수 있는 일",- "s2572": "보기만 하고 아무것도 바꾸지 않기",- "s2573": "변경하기 전에 멈추고 알려 주기",- "s2574": "변경 허용",- "s2575": "작업 완료",- "s2576": "작업에 승인이 필요합니다",- "s2577": "작업 실패"+ "s2571": "약 {0}분 남음",+ "s2572": "약 {0}시간 {1}분 남음",+ "s2573": "약 {0}시간 남음",+ "s2574": "기본적으로 컴퓨터 설정을 따릅니다.",+ "s2575": "이 모델에서는 이미지 읽기를 사용할 수 없습니다.",+ "s2576": "이미지 읽기를 끄고 다시 시도하세요.",+ "s2577": "모델이 시작 중에 멈췄습니다. 컴퓨터의 메모리가 부족했을 가능성이 큽니다.",+ "s2578": "다른 프로그램을 닫고 다시 시도하거나 “작업용으로 20% 남기기”를 선택하세요. 전문가 모드에서는 저메모리 옵션을 켜서 모델의 일부를 SSD에서 읽게 할 수도 있습니다.",+ "s2579": "불러오는 데 시간이 너무 오래 걸립니다.",+ "s2580": "컴퓨터의 메모리가 부족할 수 있습니다. 다른 프로그램을 닫고 다시 시도하세요.",+ "s2581": "이 컴퓨터용 Strata 엔진이 아직 설치되지 않았습니다.",+ "s2582": "모델을 다운로드할 때 함께 추가됩니다. 모델을 다시 다운로드하여 추가하세요.",+ "s2583": "다운로드가 인터넷에 연결되지 않았습니다.",+ "s2584": "연결을 확인한 다음 “다운로드 재개”를 누르세요.",+ "s2585": "다운로드한 파일이 Strata의 안전 검사를 통과하지 못했습니다.",+ "s2586": "“다운로드 재개”를 누르면 Strata가 다시 받아옵니다.",+ "s2587": "이 컴퓨터에는 코딩 어시스턴트가 아직 설치되지 않았습니다.",+ "s2588": "없어도 채팅은 사용할 수 있습니다.",+ "s2589": "Strata가 자체 구성 요소를 읽지 못했습니다.",+ "s2590": "Strata를 닫았다가 다시 여세요. 계속되면 앱을 다시 설치하세요.",+ "s2591": "문제가 발생했습니다.",+ "s2592": "다시 시도하세요. 계속되면 “세부 정보”를 열어 도움을 요청할 때 함께 알려 주세요.",+ "s2593": "컴퓨터를 확인하는 중…",+ "s2594": "준비하는 중…",+ "s2595": "모델을 다운로드하는 중…",+ "s2596": "Strata용으로 모델을 준비하는 중…",+ "s2597": "구성 요소 업데이트",+ "s2598": "이 컴퓨터용 엔진을 업데이트합니다. 모델과 설정은 그대로 유지됩니다.",+ "s2599": "{0}에 저장했습니다",+ "s2600": "이 컴퓨터에 이미 지원되는 모델이 있나요? 파일이 있는 폴더를 선택하세요. Strata가 파일을 확인하고 모델을 준비한 뒤 불러옵니다. 복사하거나 다운로드하지 않습니다.",+ "s2601": "GGUF 파일이 있는 폴더",+ "s2602": "폴더의 전체 경로",+ "s2603": "파일 확인",+ "s2604": "모델을 찾았습니다",+ "s2605": "파일 {0}개 · {1}",+ "s2606": "준비 후 불러오기",+ "s2607": "이 모델의 일부가 없거나 폴더에 모델이 둘 이상 들어 있습니다.",+ "s2608": "한 모델의 모든 파일을 한 폴더에 넣은 뒤 다시 확인하세요.",+ "s2609": "Strata가 아직 이 파일을 실행할 수 없습니다.",+ "s2610": "Strata는 Qwen3.8-Flash-Next 모델을 실행합니다. 모델 화면에서 내려받거나 해당 파일이 있는 폴더를 선택하세요.",+ "s2611": "이 파일을 확인할 수 없습니다.",+ "s2612": "폴더에 완전한 GGUF 파일이 있는지 확인한 뒤 다시 시도하세요.",+ "s2613": "생각 예산",- "s2614": "제한 없음"++ "s2614": "제한 없음",++ "s2615": "이 작업이 할 수 있는 일",++ "s2616": "보기만 하고 아무것도 바꾸지 않기",++ "s2617": "변경하기 전에 멈추고 알려 주기",++ "s2618": "변경 허용",++ "s2619": "작업 완료",++ "s2620": "작업에 승인이 필요합니다",++ "s2621": "작업 실패"}diff --cc apps/host/src/locales/pt.jsonindex ed959b996,985eaa1a1..9dd4a1951--- a/apps/host/src/locales/pt.json+++ b/apps/host/src/locales/pt.json@@@ -2569,48 -2569,11 +2569,55 @@@"s2568": "Executado","s2569": "Não permitido neste modo. Nada foi executado.","s2570": "Repetir prévia",- "s2571": "O que esta tarefa pode fazer",- "s2572": "Só olhar, sem alterar nada",- "s2573": "Parar e avisar antes de alterar algo",- "s2574": "Pode fazer alterações",- "s2575": "Tarefa concluída",- "s2576": "A tarefa precisa do seu sim",- "s2577": "A tarefa falhou"+ "s2571": "Faltam cerca de {0} min",+ "s2572": "Faltam cerca de {0} h {1} min",+ "s2573": "Faltam cerca de {0} h",+ "s2574": "Por padrão, segue a configuração do seu computador.",+ "s2575": "A leitura de imagens não está disponível para este modelo.",+ "s2576": "Desative a leitura de imagens e tente novamente.",+ "s2577": "O modelo parou ao iniciar, provavelmente porque o computador ficou sem memória.",+ "s2578": "Feche outros programas e tente novamente, ou escolha “Deixar 20% para o meu trabalho”. No modo especialista, você também pode ativar a opção de pouca RAM, para que parte do modelo seja lida do SSD.",+ "s2579": "O carregamento está levando tempo demais.",+ "s2580": "O computador pode estar com pouca memória. Feche outros programas e tente novamente.",+ "s2581": "O motor do Strata para este computador ainda não está instalado.",+ "s2582": "Ele é adicionado ao baixar um modelo. Baixe seu modelo novamente para adicioná-lo.",+ "s2583": "O download não conseguiu acessar a internet.",+ "s2584": "Verifique sua conexão e pressione “Retomar download”.",+ "s2585": "Um arquivo baixado não passou na verificação de segurança do Strata.",+ "s2586": "Pressione “Retomar download” e o Strata o baixará novamente.",+ "s2587": "O assistente de programação ainda não está instalado neste computador.",+ "s2588": "O chat funciona sem ele.",+ "s2589": "O Strata não conseguiu ler seus próprios componentes.",+ "s2590": "Feche e abra o Strata novamente. Se o problema continuar, reinstale o aplicativo.",+ "s2591": "Algo deu errado.",+ "s2592": "Tente novamente. Se o problema continuar, abra “Detalhes” e compartilhe-os ao pedir ajuda.",+ "s2593": "Verificando seu computador…",+ "s2594": "Preparando tudo…",+ "s2595": "Baixando seu modelo…",+ "s2596": "Preparando seu modelo para o Strata…",+ "s2597": "Atualizar componente",+ "s2598": "Atualiza o motor deste computador. Seus modelos e configurações são mantidos.",+ "s2599": "Salvo em {0}",+ "s2600": "Já tem um modelo compatível neste computador? Escolha a pasta com os arquivos dele. O Strata os verifica, prepara o modelo e o carrega. Nada é copiado ou baixado.",+ "s2601": "Pasta com os arquivos GGUF",+ "s2602": "Caminho completo da pasta",+ "s2603": "Verificar arquivos",+ "s2604": "Modelo encontrado",+ "s2605": "{0} arquivos · {1}",+ "s2606": "Preparar e carregar",+ "s2607": "Faltam partes deste modelo, ou a pasta contém mais de um modelo.",+ "s2608": "Coloque todas as partes de um modelo em uma pasta e verifique de novo.",+ "s2609": "O Strata ainda não consegue executar esses arquivos.",+ "s2610": "O Strata executa os modelos Qwen3.8-Flash-Next. Baixe um em Modelos ou escolha uma pasta com os arquivos dele.",+ "s2611": "Não foi possível verificar esses arquivos.",+ "s2612": "Verifique se a pasta tem arquivos GGUF completos e tente novamente.",+ "s2613": "Orçamento de raciocínio",- "s2614": "Sem limite"++ "s2614": "Sem limite",++ "s2615": "O que esta tarefa pode fazer",++ "s2616": "Só olhar, sem alterar nada",++ "s2617": "Parar e avisar antes de alterar algo",++ "s2618": "Pode fazer alterações",++ "s2619": "Tarefa concluída",++ "s2620": "A tarefa precisa do seu sim",++ "s2621": "A tarefa falhou"}diff --cc apps/host/src/locales/ru.jsonindex 2eaebcb96,c385819b0..febda4159--- a/apps/host/src/locales/ru.json+++ b/apps/host/src/locales/ru.json@@@ -2569,48 -2569,11 +2569,55 @@@"s2568": "Выполнено","s2569": "В этом режиме не разрешено. Ничего не запущено.","s2570": "Повторить просмотр",- "s2571": "Что может делать эта задача",- "s2572": "Только смотреть, ничего не менять",- "s2573": "Остановиться и сообщить перед изменением",- "s2574": "Разрешено вносить изменения",- "s2575": "Задача выполнена",- "s2576": "Задаче нужно ваше согласие",- "s2577": "Задача не удалась"+ "s2571": "Осталось около {0} мин",+ "s2572": "Осталось около {0} ч {1} мин",+ "s2573": "Осталось около {0} ч",+ "s2574": "По умолчанию используется настройка вашего компьютера.",+ "s2575": "Чтение изображений недоступно для этой модели.",+ "s2576": "Отключите чтение изображений и повторите попытку.",+ "s2577": "Модель остановилась при запуске, скорее всего из-за нехватки памяти на компьютере.",+ "s2578": "Закройте другие программы и повторите попытку или выберите «Оставить 20% для моей работы». В режиме эксперта можно также включить режим малого объёма ОЗУ: часть модели будет читаться с SSD.",+ "s2579": "Загрузка занимает слишком много времени.",+ "s2580": "Возможно, на компьютере не хватает памяти. Закройте другие программы и повторите попытку.",+ "s2581": "Движок Strata для этого компьютера ещё не установлен.",+ "s2582": "Он добавляется при загрузке модели. Загрузите модель ещё раз, чтобы добавить его.",+ "s2583": "Не удалось подключиться к интернету для загрузки.",+ "s2584": "Проверьте подключение и нажмите «Возобновить загрузку».",+ "s2585": "Загруженный файл не прошёл проверку безопасности Strata.",+ "s2586": "Нажмите «Возобновить загрузку», и Strata загрузит файл заново.",+ "s2587": "Помощник по программированию ещё не установлен на этом компьютере.",+ "s2588": "Чат работает и без него.",+ "s2589": "Strata не удалось прочитать собственные компоненты.",+ "s2590": "Закройте и снова откройте Strata. Если проблема повторяется, переустановите приложение.",+ "s2591": "Что-то пошло не так.",+ "s2592": "Повторите попытку. Если проблема остаётся, откройте «Подробности» и приложите их, когда будете обращаться за помощью.",+ "s2593": "Проверяем ваш компьютер…",+ "s2594": "Подготовка…",+ "s2595": "Загружаем вашу модель…",+ "s2596": "Готовим вашу модель для Strata…",+ "s2597": "Обновить компонент",+ "s2598": "Обновляет движок для этого компьютера. Ваши модели и настройки сохраняются.",+ "s2599": "Сохранено в {0}",+ "s2600": "Уже есть поддерживаемая модель на этом компьютере? Выберите папку с её файлами. Strata проверит их, подготовит модель и загрузит её. Ничего не копируется и не скачивается.",+ "s2601": "Папка с файлами GGUF",+ "s2602": "Полный путь к папке",+ "s2603": "Проверить файлы",+ "s2604": "Модель найдена",+ "s2605": "Файлов: {0} · {1}",+ "s2606": "Подготовить и загрузить",+ "s2607": "Не хватает частей этой модели, либо в папке больше одной модели.",+ "s2608": "Положите все части одной модели в одну папку и проверьте снова.",+ "s2609": "Strata пока не может запустить эти файлы.",+ "s2610": "Strata запускает модели Qwen3.8-Flash-Next. Скачайте одну в разделе «Модели» или выберите папку с её файлами.",+ "s2611": "Не удалось проверить эти файлы.",+ "s2612": "Убедитесь, что в папке полные файлы GGUF, и повторите попытку.",+ "s2613": "Лимит размышлений",- "s2614": "Без ограничений"++ "s2614": "Без ограничений",++ "s2615": "Что может делать эта задача",++ "s2616": "Только смотреть, ничего не менять",++ "s2617": "Остановиться и сообщить перед изменением",++ "s2618": "Разрешено вносить изменения",++ "s2619": "Задача выполнена",++ "s2620": "Задаче нужно ваше согласие",++ "s2621": "Задача не удалась"}diff --cc apps/host/src/locales/zh.jsonindex 47a1a1028,f481539c0..19e2e7550--- a/apps/host/src/locales/zh.json+++ b/apps/host/src/locales/zh.json@@@ -2569,48 -2569,11 +2569,55 @@@"s2568": "已运行","s2569": "此模式下不允许,未执行任何操作。","s2570": "重播预览",- "s2571": "此任务可以做什么",- "s2572": "只查看,不做任何更改",- "s2573": "更改前先停下并告诉我",- "s2574": "允许进行更改",- "s2575": "任务已完成",- "s2576": "任务需要你的确认",- "s2577": "任务失败"+ "s2571": "大约还需 {0} 分钟",+ "s2572": "大约还需 {0} 小时 {1} 分钟",+ "s2573": "大约还需 {0} 小时",+ "s2574": "默认跟随你的电脑设置。",+ "s2575": "此模型暂不支持读取图片。",+ "s2576": "请关闭图片读取后重试。",+ "s2577": "模型在启动时停止了,很可能是因为电脑内存不足。",+ "s2578": "请关闭其他程序后重试,或选择“为我的工作留出 20%”。在专家模式中,你还可以开启低内存选项,让模型的一部分从固态硬盘读取。",+ "s2579": "加载时间过长。",+ "s2580": "电脑内存可能不足。请关闭其他程序后重试。",+ "s2581": "这台电脑还没有安装 Strata 引擎。",+ "s2582": "下载模型时会一并添加。请重新下载你的模型来添加它。",+ "s2583": "下载无法连接到互联网。",+ "s2584": "请检查网络连接,然后点击“继续下载”。",+ "s2585": "有一个下载的文件未通过 Strata 的安全检查。",+ "s2586": "点击“继续下载”,Strata 会重新获取该文件。",+ "s2587": "这台电脑还没有安装编程助手。",+ "s2588": "没有它也可以正常聊天。",+ "s2589": "Strata 无法读取自身的组件。",+ "s2590": "请关闭并重新打开 Strata。如果问题持续出现,请重新安装该应用。",+ "s2591": "出了点问题。",+ "s2592": "请重试。如果问题持续出现,请展开“详情”,并在求助时一并提供。",+ "s2593": "正在检查你的电脑…",+ "s2594": "正在做准备…",+ "s2595": "正在下载你的模型…",+ "s2596": "正在为 Strata 准备你的模型…",+ "s2597": "更新组件",+ "s2598": "更新这台电脑的引擎。你的模型和设置会保留。",+ "s2599": "已保存到 {0}",+ "s2600": "这台电脑上已经有受支持的模型了吗?请选择存放其文件的文件夹。Strata 会检查文件、准备模型并加载它,不会复制或下载任何内容。",+ "s2601": "存放 GGUF 文件的文件夹",+ "s2602": "文件夹的完整路径",+ "s2603": "检查文件",+ "s2604": "找到模型",+ "s2605": "{0} 个文件 · {1}",+ "s2606": "准备并加载",+ "s2607": "此模型缺少部分文件,或该文件夹里有多个模型。",+ "s2608": "请把同一个模型的所有文件放在一个文件夹里,然后重新检查。",+ "s2609": "Strata 暂时无法运行这些文件。",+ "s2610": "Strata 运行 Qwen3.8-Flash-Next 模型。请在“模型”中下载其中一个,或选择存放其文件的文件夹。",+ "s2611": "无法检查这些文件。",+ "s2612": "请确认文件夹里是完整的 GGUF 文件,然后重试。",+ "s2613": "思考预算",- "s2614": "不限制"++ "s2614": "不限制",++ "s2615": "此任务可以做什么",++ "s2616": "只查看,不做任何更改",++ "s2617": "更改前先停下并告诉我",++ "s2618": "允许进行更改",++ "s2619": "任务已完成",++ "s2620": "任务需要你的确认",++ "s2621": "任务失败"}diff --cc apps/host/tests/packaged-control.test.mjsindex e16ececa1,9f5029f1b..0b7827ea6--- a/apps/host/tests/packaged-control.test.mjs+++ b/apps/host/tests/packaged-control.test.mjs@@@ -287,148 -210,3 +287,169 @@@ test('createControl asks the CLI for th]);assert.equal(createControl({ control: null }), null);});++test('packaged: the catalog offers no picture reading (app installs have none), and an install asks for none', async () => {+ const f = packagedFixture();+ try {+ const state = await f.native.refresh(true);+ assert.ok(state.catalog.families[0].sizes.every(s => s.images === false));+ assert.ok(state.catalog.families.every(fam => fam.images === false));+ await f.native.plan({ family: 'qwen', model: 'Q2_0', vision: 'yes' });+ assert.equal(f.rpc.at(-1).arguments.vision, 'no');+ } finally { await f.native.close(); f.cleanup(); }+});++test('packaged: an engine that stops while loading keeps the code and the last engine line for the Details disclosure', async () => {+ const f = packagedFixture();+ try {+ await f.native.refresh(true);+ f.failStart({ message: 'server_exited', output: { log_tail: 'memory guard: 5.1 GiB free is under the 6 GiB limit' } });+ const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);+ assert.equal(job.state, 'error');+ assert.match(job.error, /^server_exited: memory guard: 5\.1 GiB free/);+ } finally { await f.native.close(); f.cleanup(); }+});++test('packaged: a start that died because Windows ran out of locked memory is tried once more with a smaller pin, said in plain words, and the saved settings stay as they were', async () => {+ const f = packagedFixture();+ try {+ await f.native.refresh(true);+ f.failStart({ message: 'server_exited', output: { log_tail: 'verify: mapped staging allocation failed [pinned-memory-exhausted] the OS gave no more page-locked memory; start again with STRATA_ARENA_PIN_GIB=26 (pin less of the expert arena)' } }, 1);+ const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);+ assert.equal(job.state, 'done', job.error);+ assert.equal(f.calls.filter(c => c[0] === 'start').length, 2, 'one try and exactly one more');+ assert.match(job.result.summary, /ready, after a second try: Windows would not lock as much memory/);+ assert.match(job.details[0], /pinned-memory-exhausted/);+ assert.match(job.details[1], /STRATA_ARENA_PIN_GIB=26/);+ const instance = f.native.state().instances[0];+ assert.equal(instance.status, 'ready');+ const saved = JSON.parse(readFileSync(join(f.install, 'strata-iq2_xs.json'), 'utf8'));+ assert.equal(saved.env, undefined, 'the safer setting is for this start only; the model config is not changed');+ } finally { await f.native.close(); f.cleanup(); }+});++test('packaged: the second try is the last one: a second failure is reported with both, and nothing loops', async () => {+ const f = packagedFixture();+ try {+ await f.native.refresh(true);+ f.failStart({ message: 'server_exited', output: { log_tail: 'mapped staging allocation failed [pinned-memory-exhausted]' } });+ const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);+ assert.equal(job.state, 'error');+ assert.equal(f.calls.filter(c => c[0] === 'start').length, 2);+ assert.doesNotMatch(job.error, /first stop was/, 'the same stop twice is said once, not repeated');+ assert.match(job.details.join(' '), /Second try/, 'the second try stays in the details');+ } finally { await f.native.close(); f.cleanup(); }+});++test('packaged: retrySafer false keeps the single try', async () => {+ const f = packagedFixture();+ try {+ await f.native.refresh(true);+ f.failStart({ message: 'server_exited', output: { log_tail: 'mapped staging allocation failed [pinned-memory-exhausted]' } });+ const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs', retrySafer: false }).id);+ assert.equal(job.state, 'error');+ assert.equal(f.calls.filter(c => c[0] === 'start').length, 1);+ } finally { await f.native.close(); f.cleanup(); }+});++test('packaged: a run config that points into an old Control folder is repaired to this Control (a reinstall or an update moved it)', async () => {+ const f = packagedFixture();+ try {+ const here = join(f.root, 'control');+ mkdirSync(join(here, 'data'), { recursive: true });+ writeFileSync(join(here, 'data', 'expert-profile.bin'), 'profile');+ const path = join(f.install, 'strata-iq2_xs.json');+ const old = 'C:/Users/Alex/AppData/Local/Temp/strata-life-install/control';+ writeFileSync(path, JSON.stringify({ exe: 'component:strata-engine', cwd: old, args: ['--pack', 'D:/Strata/packs/x', '--expert-profile', old + '/data/expert-profile.bin', '--max-context', '32768'], model_name: 'x', port: 8080 }));+ await f.native.refresh(true);+ const repaired = JSON.parse(readFileSync(path, 'utf8'));+ assert.equal(repaired.cwd.toLowerCase(), here.toLowerCase());+ assert.equal(repaired.args[repaired.args.indexOf('--expert-profile') + 1].toLowerCase(), join(here, 'data', 'expert-profile.bin').toLowerCase());+ assert.equal(repaired.args[1], 'D:/Strata/packs/x', 'paths outside Control are left alone');+ assert.ok(existsSync(path + '.bak'), 'the old config is kept');+ // a config that is already right, or whose new target is not there, is not touched+ const before = readFileSync(path, 'utf8');+ await f.native.refresh(true);+ assert.equal(readFileSync(path, 'utf8'), before);+ } finally { await f.native.close(); f.cleanup(); }+});++test('packaged: deleting a downloaded model unloads it first, then the installer removes its files', async () => {+ const f = packagedFixture();+ try {+ await f.native.refresh(true);+ const load = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);+ assert.equal(load.state, 'done', load.error);+ assert.equal(f.native.state().instances.length, 1);+ const job = await finish(f.native, f.native.operation('remove', { model: 'iq2_xs' }).id);+ assert.equal(job.state, 'done', job.error);+ assert.equal(f.native.state().instances.length, 0, 'the loaded model was unloaded first');+ assert.deepEqual(f.calls.filter(c => c[0] === 'stop').at(-1), ['stop', 'app-1']);+ const removed = f.rpc.filter(c => c.name === 'strata_remove');+ assert.equal(removed.length, 1);+ assert.deepEqual(removed[0].arguments, { model: 'iq2_xs', confirm: true });+ assert.equal(f.others().length, 0);+ const bad = await finish(f.native, f.native.operation('remove', { model: '../x' }).id);+ assert.equal(bad.state, 'error', 'an id that is not an installed model is refused');+ } finally { await f.native.close(); f.cleanup(); }+});++test('packaged: a local GGUF folder is checked by Control, then installed from where it is (no download)', async () => {+ const f = packagedFixture();+ try {+ await f.native.refresh(true);+ const preview = await f.native.localPreview('D:/models/iq3s');+ assert.equal(preview.candidate_selection.model, 'IQ3_S');+ assert.deepEqual(f.calls.find(c => c[0] === 'importPlan'), ['importPlan', 'D:/models/iq3s']);+ await assert.rejects(() => f.native.localPreview(' '), /Choose a folder/);+ await f.native.plan({ family: 'qwen', model: 'IQ3_S', gguf_dir: 'D:/models/iq3s' });+ assert.equal(f.rpc.at(-1).arguments.gguf_dir, 'D:/models/iq3s');+ } finally { await f.native.close(); f.cleanup(); }+});++test('packaged: the install job also fetches the engine through Control (merge of the model progress and the engine step); a failed engine keeps the model and says so', async () => {+ const report = { engine: { status: 'install', offered: { version: '0.1.46' }, download_bytes: 5e8 } };+ const f = packagedFixture({ engineUsable: false, updater: { report, async update(options) {+ options.onEvent({ event: 'progress', phase: 'download', percent: 50, done: 2.5e8, total: 5e8 });+ return { ok: true, results: [{ component: 'engine', status: 'updated', installed_after: { version: '0.1.46' } }] };+ } } });+ try {+ await f.native.refresh(true);+ const job = await finish(f.native, f.native.operation('install', { family: 'qwen', model: 'Q2_0' }).id);+ assert.equal(job.state, 'done', job.error);+ assert.equal(job.result.install.engine.state, 'done');+ assert.deepEqual(job.result.install.parts.map(p => p.kind), ['model', 'engine']);+ assert.deepEqual(f.calls.filter(c => c[0] === 'update'), [['update', true, false]], 'the engine only, from this install job');+ assert.equal(f.calls.filter(c => ['saveProfile', 'start'].includes(c[0])).length, 0);+ } finally { await f.native.close(); f.cleanup(); }+ const g = packagedFixture({ engineUsable: false, updater: { report, async update() { throw new Error('the download of http://x/e.tar.gz was interrupted after 100 of 200 bytes (ConnectionResetError)'); } } });+ try {+ await g.native.refresh(true);+ const job = await finish(g.native, g.native.operation('install', { family: 'qwen', model: 'Q2_0' }).id);+ assert.equal(job.state, 'done', job.error);+ assert.match(job.summary, /Your model is ready\. The engine for this PC couldn't be downloaded/);+ assert.equal(job.result.install.engine.state, 'failed');+ assert.doesNotMatch(job.summary, /http|ConnectionReset|bytes/);+ } finally { await g.native.close(); g.cleanup(); }+});++++test('packaged: the app default of several requests at once and the memory retry share ONE second try, never two', async () => {++ const f = packagedFixture(); f.hardware.gpus[0].vram_gb = 48;++ try {++ await f.native.refresh(true);++ f.failStart({ message: 'server_exited', output: { log_tail: 'something else went wrong' } }, 1);++ const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);++ assert.equal(job.state, 'done', job.error);++ assert.equal(f.calls.filter(c => c[0] === 'start').length, 2, 'the failed first start and one second try');++ assert.match(job.result.summary, /after a second try/);++ assert.equal(f.native.state().instances[0].parallel, 1, 'the second try runs one request at a time');++ } finally { await f.native.close(); f.cleanup(); }++ const g = packagedFixture(); g.hardware.gpus[0].vram_gb = 48;++ try {++ await g.native.refresh(true);++ g.failStart({ message: 'server_exited', output: { log_tail: 'mapped staging allocation failed [pinned-memory-exhausted]' } });++ const job = await finish(g.native, g.native.operation('load', { model: 'iq2_xs' }).id);++ assert.equal(job.state, 'error');++ assert.equal(g.calls.filter(c => c[0] === 'start').length, 2, 'memory change and parallel drop ride on the same single try');++ } finally { await g.native.close(); g.cleanup(); }++});