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++
delete a downloaded native model: strata_remove (own files and run config, shared files kept), Delete in Models and Storage, real disk use per model
Niko1221ffbc60668236
diff --git a/apps/desktop/scripts/ui-flows.mjs b/apps/desktop/scripts/ui-flows.mjsindex 69e261a8f..0edb6534a 100644--- a/apps/desktop/scripts/ui-flows.mjs+++ b/apps/desktop/scripts/ui-flows.mjs@@ -30,7 +30,7 @@ const nodeExe = resolve(args.node ?? join(staged, 'node', process.platform === 'const work = mkdtempSync(join(tmpdir(), 'strata-ui-flows-'));const shots = resolve(args.shots ?? join(work, 'shots'));mkdirSync(shots, { recursive: true });-const only = new Set(String(args.only ?? 'download,models,tune,fail,theme,restart').split(','));+const only = new Set(String(args.only ?? 'download,models,tune,fail,delete,theme,restart').split(','));const isWin = process.platform === 'win32';const { chromium } = await import(pathToFileURL(join(repoHost, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core'));const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync);@@ -51,6 +51,7 @@ const python = isWin ? join(control, 'python', 'python.exe') : join(control, 'pyconst FAKE_INSTALLER = String.raw`import json, os, sys, timefrom pathlib import Path+ROOT = Path(sys.argv[sys.argv.index('--root') + 1]) if '--root' in sys.argv else Path('.')STATE = Path(os.environ['FAKE_STATE']); STATE.mkdir(parents=True, exist_ok=True)RATE = float(os.environ.get('FAKE_RATE_GB_S', '0.5'))def size(model, gb, ram, mid):@@ -71,7 +72,11 @@ def job():'download': {'file': 'model files', 'done_gb': round(done, 3), 'total_gb': TOTAL, 'remaining_gb': round(TOTAL - done, 3), 'percent': int(100 * done / TOTAL)}}def call(name, a):if name == 'strata_models': return CATALOG- if name == 'strata_status': return {'summary': 'fake', 'hardware': HARDWARE, 'recommendation': CATALOG['recommendation'], 'install': job(), 'running': []}+ if name == 'strata_remove':+ cfg = ROOT / ('strata-%s.json' % a['model'])+ if a.get('confirm') and cfg.exists(): cfg.unlink()+ return {'summary': 'Deleted', 'plan': {'gb': 83.6}, 'failed': []}+ if name == 'strata_status': return {'summary': 'fake', 'installed': {'models': [{'model': 'iq3_s', 'disk_gb': 83.6, 'disk_bytes': 83600000000}]}, 'hardware': HARDWARE, 'recommendation': CATALOG['recommendation'], 'install': job(), 'running': []}if name == 'strata_install':if a.get('cancel'):f = STATE / 'job.json'@@ -90,7 +95,7 @@ for line in sys.stdin:if 'id' not in m: continuemethod = m.get('method')if method == 'initialize': res = {'protocolVersion': '2024-11-05'}- elif method == 'tools/list': res = {'tools': [{'name': n} for n in ('strata_models', 'strata_status', 'strata_install')]}+ elif method == 'tools/list': res = {'tools': [{'name': n} for n in ('strata_models', 'strata_status', 'strata_install', 'strata_remove')]}else:p = m['params']res = {'structuredContent': call(p['name'], p.get('arguments') or {})}@@ -344,6 +349,31 @@ await scenario('tune', { installed: true, env: { FAKE_TOKEN_DELAY: '0.02', FAKE_check(page.problems.length === 0, 'no page error', page.problems.join('; '));});+// ------------------------------------------------------------------------------------------------ delete+await scenario('delete', { installed: true }, async ({ base, api, browser, dirs, shot }) => {+ const page = await newPage(browser, base);+ await clickText(page, /Go straight to the app/i);+ await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});+ await page.getByRole('button', { name: /^Load model$/ }).first().click();+ let ready = false;+ for (let i = 0; i < 90 && !ready; i++) { ready = (await api('/api/native')).body.instances.some(x => x.status === 'ready'); await delay(1000); }+ check(ready, 'a model is loaded');+ await clickText(page, /Manage models/i);+ await page.getByRole('button', { name: /^Delete$/ }).first().click();+ await delay(600);+ await shot(page, '1-delete-confirm');+ const dialog = await page.getByRole('dialog').last().innerText();+ check(/Delete this version\?/.test(dialog) && /Remove 83\.6 GB of downloaded files\. You can download this version again\./.test(dialog), 'the confirm dialog uses the existing words and the real size', dialog.replace(/\s+/g, ' ').slice(0, 200));+ check(/running model will be unloaded/i.test(dialog), 'and says the loaded model is unloaded first');+ await page.getByRole('button', { name: /^Delete version$/ }).click();+ let state = null;+ for (let i = 0; i < 40; i++) { state = (await api('/api/native')).body; if (state.instances.length === 0 && !state.installed?.models?.some(m => m.model === 'iq3_s')) break; await delay(500); }+ check(state.instances.length === 0, 'the loaded model was unloaded');+ check(!existsSync(join(dirs.install, 'strata-iq3_s.json')), 'the installer removed the run config of the model');+ check(!state.installed?.models?.some(m => m.model === 'iq3_s'), 'the model is no longer listed as downloaded');+ await shot(page, '2-after-delete');+});+// ------------------------------------------------------------------------------------------------ failawait scenario('fail', { installed: true, env: { FAKE_ENGINE_FAIL: '1' } }, async ({ base, api, browser, shot }) => {const page = await newPage(browser, base);diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjsindex e4511e7d8..02e0bf1f7 100644--- a/apps/host/server/native-control.mjs+++ b/apps/host/server/native-control.mjs@@ -55,7 +55,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},spfor(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,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 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});}@@ -84,7 +84,8 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sppackagedInstall=list.install_dir;const engine=await control.engine();const installer=await mcpCall('strata_status',{hardware:true}).catch(error=>({error:error.message}));- 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 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},@@ -117,6 +118,15 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},spfunction 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};}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.');@@ -201,7 +211,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},spconst 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});}+ function operation(kind,args={}){if(!['install','load','benchmark','tune','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==='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')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 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.diff --git a/apps/host/src/components/NativeDelete.tsx b/apps/host/src/components/NativeDelete.tsxnew file mode 100644index 000000000..07e9ba62f--- /dev/null+++ b/apps/host/src/components/NativeDelete.tsx@@ -0,0 +1,43 @@+import { tr } from '../lib/i18n';+import { useState } from 'react';+import { Btn, Dialog, ErrorNotice } from './ui';+import { nativeAction, nativeState, refreshNative, useNative, type NativeJob } from '../lib/native';+import { catalogVersionLabel, nativeCatalogModels } from '../lib/native-catalog';+import { sizeGb } from '../lib/format';++/** Delete a downloaded (native) model: its own files and run config. What another installed model still uses stays. A loaded model+ * is unloaded first by the host. Same dialog and words as deleting a version of the managed library. */+export function NativeDeleteDialog({ id, onClose }: { id: string | null; onClose: () => void }) {+ const native = useNative();+ const [pending, setPending] = useState(false), [error, setError] = useState('');+ const entry = native?.installed?.models.find(m => m.model === id);+ const label = (() => { const sizes = nativeCatalogModels(native?.catalog?.families ?? []).flatMap(f => f.sizes); const v = sizes.find(s => s.id === id); return v ? `${catalogVersionLabel(v)} · ${v.model}` : entry?.model_name ?? id ?? ''; })();+ const running = !!native?.instances.some(i => i.model === id);+ const busy = !!native?.jobs.some(j => j.state === 'running');+ const gb = entry?.diskGb ?? 0;+ function close() { if (!pending) { onClose(); setError(''); } }+ async function remove() {+ setPending(true);+ setError('');+ try {+ const job = await nativeAction<NativeJob>('operations', { kind: 'remove', args: { model: id } });+ for (let i = 0; i < 600; i++) {+ await new Promise(r => setTimeout(r, 500));+ await refreshNative(true).catch(() => undefined);+ const current = nativeState()?.jobs.find(j => j.id === job.id);+ if (current && current.state !== 'running') {+ if (current.state === 'error') throw new Error(current.error ?? 'Could not delete this version.');+ break;+ }+ }+ onClose();+ }+ catch (e) { setError(e instanceof Error ? e.message : String(e)); }+ finally { setPending(false); }+ }+ return <Dialog open={!!id} compact title={tr("Delete this version?")} onClose={close} actions={<><Btn disabled={pending} onClick={close}>{tr("Keep version")}</Btn><Btn variant="danger" disabled={pending || busy || !entry} onClick={() => void remove()}>{tr(pending ? 'Working…' : 'Delete version')}</Btn></>}>+ <p>{tr(label)}{tr(gb ? ` · ${sizeGb(gb)}` : '')}</p>+ {tr(entry ? <p className="small muted storage-delete-note">{tr('Remove {0} GB of downloaded files. You can download this version again.', [gb ? gb.toFixed(1) : '0'])}{tr(running ? ' ' : '')}{tr(running ? 'The running model will be unloaded and its files deleted.' : '')}</p> : <p className="small muted">{tr("This version is no longer downloaded.")}</p>)}+ {tr(error ? <ErrorNotice message={error}/> : null)}+ </Dialog>;+}diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsxindex e728b9272..a251f0730 100644--- a/apps/host/src/components/NativeModels.tsx+++ b/apps/host/src/components/NativeModels.tsx@@ -3,6 +3,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';import { Screen } from './layout';import { Btn, Dialog, ErrorNotice, Icon, Select } from './ui';import { installProgress, useDownloadEta } from '../lib/download-eta';+import { NativeDeleteDialog } from './NativeDelete';import { plainFailureText } from '../lib/plain-errors';import { api } from '../lib/client';import { go, setSettingsSection, selectRemoteModel, pushToast } from '../lib/store';@@ -26,6 +27,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngineconst [resourceProfile, setResourceProfile] = useState<'work' | 'performance'>('work');const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState<Record<string, any> | null>(null), [benchmark, setBenchmark] = useState(false), [jobId, setJobId] = useState(''), [manage, setManage] = useState(false);const presetPending = useRef(false);+ const [deleting, setDeleting] = useState<string | null>(null);const families = nativeCatalogModels(native?.catalog?.families ?? []);const expertSection = useRef<HTMLElement>(null);useEffect(() => { if (expert)@@ -108,7 +110,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine<aside className="stack stack--lg"><section className="st-card"><h2 className="h4">{tr("This computer")}</h2><p>{tr(native?.hardware?.ram_gb || hardware?.memory.totalGb || '—')}{tr(" GB RAM")}</p>{tr(native?.hardware?.gpus.length ? native.hardware.gpus.map(g => <p className="small" key={g.index}>{tr(g.name)} · {tr(g.vram_gb)}{tr(" GB")}</p>) : <p className="small muted">{tr("No supported GPU reported by this installation.")}</p>)}<p className="small muted">{tr("Compatibility and sizes come from your installed Strata version.")}</p></section><section className="st-card"><h2 className="h4">{tr("Model files")}</h2><p className="small muted">{tr("Strata prepares all shards, the draft layer and shared files. Completed downloads are reused.")}</p><code className="native-path">{installed?.dataFolder ?? native?.downloadDirectory ?? native?.installed?.data_folder ?? 'Choose an installation'}</code><Btn size="sm" variant="ghost" onClick={() => { setSettingsSection('Storage'); go('settings'); }}>{tr("Storage settings")}</Btn></section><Btn size="sm" variant="ghost" onClick={onOtherModels}>{tr("Other local models\u2026")}</Btn></aside></div><Dialog open={!!plan} title={tr("Download and prepare")} compact onClose={() => !pending && setPlan(null)} actions={<><Btn disabled={pending} onClick={() => setPlan(null)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={pending || !!plan?.plan?.disk_short} onClick={() => void download()}>{tr("Download & load")}</Btn></>}><p><strong>{tr(plan?.plan?.title ?? selectedFamily?.title)}</strong>{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")}</p>{tr(plan?.plan?.disk_short ? <ErrorNotice message={plan.plan.disk_short}/> : null)}<p className="small muted">{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}</p><p className="small muted">{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}</p>{tr(selectedSize?.images ? <p className="small muted">{tr("Vision encoder files are included. Picture reading loads only when enabled.")}</p> : null)}</Dialog>- <Dialog open={manage} title={tr("Manage models")} onClose={() => setManage(false)} actions={<Btn onClick={() => setManage(false)}>{tr("Done")}</Btn>}><div className="stack"><p className="strong">{tr(selectedFamily?.title)}</p><div className="st-tablewrap"><table className="st-table"><thead><tr><th>{tr("Version")}</th><th>{tr("Download")}</th><th>{tr("Status")}</th><th></th></tr></thead><tbody>{tr(selectedFamily?.sizes.map(v => <tr key={v.id}><td><strong>{tr(catalogVersionLabel(v))}</strong><small>{tr(v.model)} · {tr(v.about)}</small></td><td>{tr(v.download_gb.toFixed(1))}{tr(" GB")}</td><td>{tr(native?.instances.some(i => i.model === v.id) ? 'Loaded' : v.installed ? 'Downloaded' : 'Available')}</td><td><Btn size="sm" disabled={!!active} onClick={() => { setSize(v.id); setManage(false); }}>{tr(selectedSize?.id === v.id ? 'Selected' : 'Use version')}</Btn></td></tr>))}</tbody></table></div><Btn variant="ghost" icon="folder" onClick={() => { setManage(false); (onImport ?? onOtherModels)(); }}>{tr("Use a local GGUF\u2026")}</Btn><p className="xs muted">{tr("Choose a version, then load it from Models. Shared native files are kept together in Storage.")}</p></div></Dialog>+ <NativeDeleteDialog id={deleting} onClose={() => setDeleting(null)}/>+ <Dialog open={manage} title={tr("Manage models")} onClose={() => setManage(false)} actions={<Btn onClick={() => setManage(false)}>{tr("Done")}</Btn>}><div className="stack"><p className="strong">{tr(selectedFamily?.title)}</p><div className="st-tablewrap"><table className="st-table"><thead><tr><th>{tr("Version")}</th><th>{tr("Download")}</th><th>{tr("Status")}</th><th></th></tr></thead><tbody>{tr(selectedFamily?.sizes.map(v => <tr key={v.id}><td><strong>{tr(catalogVersionLabel(v))}</strong><small>{tr(v.model)} · {tr(v.about)}</small></td><td>{tr(v.download_gb.toFixed(1))}{tr(" GB")}</td><td>{tr(native?.instances.some(i => i.model === v.id) ? 'Loaded' : v.installed ? 'Downloaded' : 'Available')}</td><td><Btn size="sm" disabled={!!active} onClick={() => { setSize(v.id); setManage(false); }}>{tr(selectedSize?.id === v.id ? 'Selected' : 'Use version')}</Btn>{tr(native?.installed?.models.some(m => m.model === v.id) ? <> <Btn size="sm" variant="danger" disabled={!!active} onClick={() => setDeleting(v.id)}>{tr("Delete")}</Btn></> : null)}</td></tr>))}</tbody></table></div><Btn variant="ghost" icon="folder" onClick={() => { setManage(false); (onImport ?? onOtherModels)(); }}>{tr("Use a local GGUF\u2026")}</Btn><p className="xs muted">{tr("Choose a version, then load it from Models. Shared native files are kept together in Storage.")}</p></div></Dialog><NativeBenchmark open={benchmark} onClose={() => setBenchmark(false)}/></Screen>;}diff --git a/apps/host/src/components/SettingsStorage.tsx b/apps/host/src/components/SettingsStorage.tsxindex 439eb489b..a78520bf5 100644--- a/apps/host/src/components/SettingsStorage.tsx+++ b/apps/host/src/components/SettingsStorage.tsx@@ -5,10 +5,12 @@ import { changeModelDirectory, getState, lifecycleStatus, removeVariant, runtimeimport { pickerGroups, pickerVersionState } from '../lib/model-picker';import { sizeGb } from '../lib/format';import { useNative } from '../lib/native';+import { NativeDeleteDialog } from './NativeDelete';export function SettingsStorage() {const state = useStore(s => s);const native = useNative();const [selected, setSelected] = useState<string | null>(null);+ const [nativeDeleting, setNativeDeleting] = useState<string | null>(null);const [pending, setPending] = useState(false), [error, setError] = useState('');const [editing, setEditing] = useState(false), [directory, setDirectory] = useState('');const [directoryPending, setDirectoryPending] = useState(false), [directoryError, setDirectoryError] = useState(''), [notice, setNotice] = useState('');@@ -95,6 +97,10 @@ export function SettingsStorage() {...versions.map(v => ({ value: v.id, label: `${v.local ? v.name : v.family} · ${v.quant} · ${sizeGb(v.diskGb)}${v.local ? ' · Local' : ''}`, disabled: pickerVersionState(v, library?.loaded ?? null).busy })),]} onChange={id => { setError(''); setSelected(id); }}/></Field>+ {tr(native?.installed?.models.length ? <Field label={tr("Downloaded models")} hint={tr("{0} on this computer. Choose a version to delete its files.", [sizeGb((native.installed.models).reduce((n, m) => n + (m.diskGb ?? 0), 0))])}>+ <div className="stack">{tr(native.installed.models.map(m => <div className="row" key={m.model}><span><strong>{tr(m.model_name || m.model)}</strong> <small className="muted">{tr(m.model)} · {tr(sizeGb(m.diskGb ?? 0))}{tr(native.instances.some(i => i.model === m.model) ? <> · {tr('Loaded')}</> : null)}</small></span><Btn size="sm" variant="danger" disabled={!!native.jobs.some(j => j.state === 'running')} onClick={() => setNativeDeleting(m.model)}>{tr("Delete")}</Btn></div>))}</div>+ </Field> : null)}+ <NativeDeleteDialog id={nativeDeleting} onClose={() => setNativeDeleting(null)}/><Dialog open={!!selected} compact title={tr(version?.local ? 'Remove from Strata?' : `Delete ${version?.quant ?? 'model version'}?`)} onClose={close} actions={<><Btn disabled={pending} onClick={close}>{tr("Keep version")}</Btn><Btn variant="danger" disabled={pending || unavailable} onClick={() => void remove()}>{tr(pending ? 'Working…' : version?.local ? 'Remove model' : 'Delete version')}</Btn></>}><p>{tr(version ? `${version.local ? version.name : version.family} · ${version.quant} · ${sizeGb(version.diskGb)}` : 'This version is no longer downloaded.')}</p>{tr(version ? <p className="small muted storage-delete-note">{tr(version.local ? `${running ? 'The model will be unloaded and removed from Strata.' : 'The model will be removed from Strata.'} Your original GGUF files stay in their folder.` : `${running ? 'The running model will be unloaded and its files deleted.' : 'Its files will be deleted from this computer.'} You can download it again in Models.`)}</p> : null)}diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.tsindex fbdd66e22..58da20c18 100644--- a/apps/host/src/lib/native.ts+++ b/apps/host/src/lib/native.ts@@ -6,7 +6,7 @@ export interface NativeFamily {family:string;title:string;about:string;experimenexport interface NativeField {id:string;label:string;group:string;type:'number'|'boolean'|'string'|'enum'|'array';min?:number;max?:number;choices?:string[];hint?:string;supported?:boolean}export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;details?:string;result:Record<string,any>|null}export interface NativeInstance {id:string;apiModelId:string;model:string;label:string;aliases?:string[];vision?:boolean;context?:number;port:number;gpus:number[];status:'loading'|'ready'|'unloading'|'error';phase:string;loadedAt:string;error:string|null;metrics:Record<string,any>|null}-export interface NativeState {available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;missing_files?:string[]}[];data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;gpus:{index:number;name:string;vram_gb:number;usable:boolean}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean}}+export interface NativeState {available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;diskGb?:number;diskBytes?:number;missing_files?:string[]}[];data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;gpus:{index:number;name:string;vram_gb:number;usable:boolean}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean}}let state:NativeState|null=null,timer:ReturnType<typeof setInterval>|null=null,reading:Promise<void>|null=null;const listeners=new Set<()=>void>();export function refreshNative(force=false){if(reading)return reading;reading=api.get<NativeState>(`/api/native${force?'?refresh=1':''}`).then(value=>{state=value;listeners.forEach(fn=>fn());}).catch(error=>{if(state){state={...state,error:error.message,instances:state.instances.map(i=>({...i,metrics:null,phase:'unavailable'}))};listeners.forEach(fn=>fn());}}).finally(()=>{reading=null;});return reading;}diff --git a/apps/host/tests/packaged-control.test.mjs b/apps/host/tests/packaged-control.test.mjsindex 6e701882a..f4dd41b63 100644--- a/apps/host/tests/packaged-control.test.mjs+++ b/apps/host/tests/packaged-control.test.mjs@@ -131,8 +131,9 @@ function packagedFixture({ engineUsable = true } = {}) {if (message.method === 'tools/call') rpc.push(message.params);let result;if (message.method === 'initialize') result = { protocolVersion: '2024-11-05' };- else if (message.method === 'tools/list') result = { tools: ['strata_models', 'strata_status', 'strata_install'].map(name => ({ name })) };+ else if (message.method === 'tools/list') result = { tools: ['strata_models', 'strata_status', 'strata_install', 'strata_remove'].map(name => ({ name })) };else if (message.params.name === 'strata_models') result = { structuredContent: catalog };+ else if (message.params.name === 'strata_remove') result = { structuredContent: { summary: 'Deleted', plan: { gb: 1.2 }, failed: [] } };else if (message.params.name === 'strata_status') result = { structuredContent: { hardware, recommendation: catalog.recommendation, install: installJob, running: [], summary: 'x' } };else if (message.params.arguments?.confirm) { installJob = { running: false, exit_code: 0 }; result = { structuredContent: { summary: 'Install started', plan: { download_gb: 66.4 }, install: { running: true, step: 'downloading' } } }; }else if (message.params.arguments?.cancel === undefined && message.params.arguments?.confirm === undefined) result = { structuredContent: { summary: 'Install finished', install: { running: false, exit_code: 0 } } };@@ -328,3 +329,23 @@ test('packaged: a run config that points into an old Control folder is repairedassert.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(); }+});diff --git a/tests/desktop/test_control_install.py b/tests/desktop/test_control_install.pyindex d1650f066..5a251ec9e 100644--- a/tests/desktop/test_control_install.py+++ b/tests/desktop/test_control_install.py@@ -272,3 +272,81 @@ class FailedStartTests(unittest.TestCase):self.assertIn("memory guard: 5.1 GiB free", tail)self.assertTrue(tail.endswith("exit code 3"))self.assertNotIn("loading", tail.split(" | ")[0] if tail.count(" | ") > 2 else "")+++class DeleteModelTests(unittest.TestCase):+ """Deleting a downloaded model removes its own files and run config, never what another installed model still uses."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ base = Path(self.tmp.name)+ self.root = base / "install"+ self.root.mkdir()+ self.data = base / "Strata-data"+ spec = importlib.util.spec_from_file_location("strata_mcp_for_delete", ROOT / "tools" / "strata_mcp.py")+ self.mcp = importlib.util.module_from_spec(spec)+ with mock.patch.dict(os.environ, {"STRATA_CONTROL_INSTALL": "1", "STRATA_INSTALL_DIR": str(self.root)}):+ spec.loader.exec_module(self.mcp)+ self.s = self.mcp.Strata(self.root, ROOT)+ self.tools = self.mcp.Tools(self.s)++ def make(path: Path, size: int):+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b"x" * size)+ return path+ self.make = make+ mtp = self.data / "mtp" / "rt"+ make(mtp / "experts.bin", 3000)+ shared_ple = make(self.data / "models" / "Q2_0" / "shard-2.gguf", 2000) # the same second shard in both models+ for tag, size in (("iq3_s", 10000), ("q2_0", 4000)):+ folder = self.data / "models" / tag+ first = make(folder / "shard-1.gguf", size)+ make(first.with_name(first.name + ".done"), 1)+ pack = self.data / "packs" / tag+ make(pack / "tokenizer" / "vocab.json", 500)+ (self.root / f"strata-{tag}.json").write_text(json.dumps({"exe": "component:strata-engine", "args": [+ "--pack", str(pack), "--native", str(first), "--ple-gguf", str(shared_ple), "--mtp", str(mtp), "--max-context", "32768"]}), encoding="utf-8")+ (self.root / f"strata-{tag}.log").write_text("log", encoding="utf-8")++ def test_the_plan_names_what_goes_and_what_stays(self):+ plan = self.tools.strata_remove(model="iq3_s")["plan"]+ removed = {Path(x["path"]).name for x in plan["remove"]}+ kept = {Path(x["path"]).name for x in plan["keep"]}+ self.assertIn("shard-1.gguf", removed)+ self.assertIn("iq3_s", removed) # its pack folder+ self.assertIn("strata-iq3_s.json", removed)+ self.assertEqual(kept, {"shard-2.gguf", "rt"}) # the shared PLE shard and the shared MTP draft+ self.assertEqual(plan["bytes"], 10000 + 1 + 500 + 3 + (self.root / "strata-iq3_s.json").stat().st_size)++ def test_confirm_deletes_only_that_model_and_the_other_still_has_everything(self):+ result = self.tools.strata_remove(model="iq3_s", confirm=True)+ self.assertEqual(result["failed"], [])+ self.assertFalse((self.data / "models" / "iq3_s").exists()) # its folder is gone with its file+ self.assertFalse((self.data / "packs" / "iq3_s").exists())+ self.assertFalse((self.root / "strata-iq3_s.json").exists())+ self.assertTrue((self.data / "models" / "Q2_0" / "shard-2.gguf").is_file())+ self.assertTrue((self.data / "mtp" / "rt" / "experts.bin").is_file())+ self.assertTrue((self.data / "models" / "q2_0" / "shard-1.gguf").is_file())+ self.assertTrue((self.data / "packs" / "q2_0" / "tokenizer" / "vocab.json").is_file())+ self.assertTrue((self.root / "strata-q2_0.json").is_file())++ def test_the_last_model_takes_its_shared_files_with_it(self):+ self.tools.strata_remove(model="iq3_s", confirm=True)+ self.tools.strata_remove(model="q2_0", confirm=True)+ self.assertFalse((self.data / "mtp" / "rt").exists())+ self.assertFalse((self.data / "models" / "Q2_0" / "shard-2.gguf").exists())++ def test_nothing_outside_strata_s_folders_is_touched_and_each_model_reports_its_own_disk_use(self):+ outside = Path(self.tmp.name) / "elsewhere" / "mine.gguf"+ self.make(outside, 777)+ cfg = self.root / "strata-q2_0.json"+ data = json.loads(cfg.read_text())+ data["args"] += ["--ple-gguf", str(outside)]+ cfg.write_text(json.dumps(data), encoding="utf-8")+ plan = self.tools.strata_remove(model="q2_0")["plan"]+ self.assertIn("mine.gguf", {Path(x["path"]).name for x in plan["keep"]})+ self.tools.strata_remove(model="q2_0", confirm=True)+ self.assertTrue(outside.is_file())+ described = self.s.describe_config(self.root / "strata-iq3_s.json")+ self.assertGreater(described["disk_bytes"], 10000)diff --git a/tools/strata_mcp.py b/tools/strata_mcp.pyindex 64fc3e29f..476e932a1 100644--- a/tools/strata_mcp.py+++ b/tools/strata_mcp.py@@ -536,8 +536,78 @@ class Strata:"low_ram": "--resident-experts" in a or "--mmap-experts" in a,"start_script": script.name if script.exists() else None,"ready": not missing and bool(cfg), "missing_files": missing[:3],+ "disk_gb": self.removal_plan(path)["gb"], "disk_bytes": self.removal_plan(path)["bytes"],"last_used": time.strftime("%Y-%m-%d %H:%M", time.localtime(path.stat().st_mtime))}+ # ---- what a model owns on disk (Delete, and the per-model disk usage in Storage)+ FILE_FLAGS = ("--native", "--ple-gguf", "--embd-gguf", "--native-dense-gguf")+ DIR_FLAGS = ("--pack", "--mtp")++ def model_paths(self, cfg: dict) -> tuple[list, list]:+ """(the GGUF files, the folders) a run config names: --native/--ple-gguf/... and --pack/--mtp, plus any other .gguf."""+ a = [x for x in (cfg.get("args") or []) if isinstance(x, str)]+ files = [Path(a[i + 1]) for i, x in enumerate(a[:-1]) if x in self.FILE_FLAGS]+ files += [Path(x) for x in a if x.lower().endswith(".gguf") and Path(x) not in files]+ dirs = [Path(a[i + 1]) for i, x in enumerate(a[:-1]) if x in self.DIR_FLAGS]+ return files, dirs++ @staticmethod+ def tree_bytes(path: Path) -> int:+ if path.is_file():+ try:+ return path.stat().st_size+ except OSError:+ return 0+ total = 0+ for base, _d, names in os.walk(path):+ for n in names:+ try:+ total += os.stat(os.path.join(base, n)).st_size+ except OSError:+ pass+ return total++ def removal_plan(self, config: Path) -> dict:+ """What deleting this model removes and what it keeps. A file or folder another installed model's config still names+ (the shared MTP draft, a shared PLE shard) is kept; so is anything outside Strata's own folders."""+ cfg = self.read_config(config)+ files, dirs = self.model_paths(cfg)+ used_files, used_dirs = set(), set()+ for other in self.configs():+ if norm(other) == norm(config):+ continue+ f, d = self.model_paths(self.read_config(other))+ used_files |= {norm(x) for x in f}+ used_dirs |= {norm(x) for x in d}+ remove, keep = [], []++ def shared(p: Path, is_dir: bool) -> bool:+ n = norm(p)+ if n in used_files or n in used_dirs or any(is_inside(u, n) for u in used_files | used_dirs) and is_dir:+ return True+ return any(is_inside(n, u) for u in used_dirs)++ for p, is_dir in [(x, False) for x in files] + [(x, True) for x in dirs]:+ if not p.exists():+ continue+ if not self.allowed(p):+ keep.append({"path": str(p), "reason": "outside Strata's folders"})+ elif shared(p, is_dir):+ keep.append({"path": str(p), "reason": "another installed model still uses it"})+ else:+ remove.append({"path": str(p), "kind": "folder" if is_dir else "file", "bytes": self.tree_bytes(p)})+ if not is_dir:+ for extra in (p.with_name(p.name + ".done"), p.with_name(p.name + ".part")):+ if extra.exists():+ remove.append({"path": str(extra), "kind": "file", "bytes": self.tree_bytes(extra)})+ tag = config.stem[len("strata-"):]+ for extra in (config, config.with_name(config.name + ".bak"), config.with_name(f"strata-{tag}.log"),+ self.root / f"run-{tag}.bat", self.root / f"run-{tag}.sh"):+ if extra.exists():+ remove.append({"path": str(extra), "kind": "file", "bytes": self.tree_bytes(extra)})+ total = sum(x["bytes"] for x in remove)+ return {"model": tag, "remove": remove, "keep": keep, "bytes": total, "gb": round(total / 1e9, 2)}+def find_config(self, model: str | None) -> Path:have = self.configs()if not have:@@ -1008,6 +1078,13 @@ def tool_defs(models: dict, families: dict, contexts: list) -> list:"Read-only.","inputSchema": {"type": "object", "additionalProperties": False, "properties": {}},"annotations": ro},+ {"name": "strata_remove", "title": "Delete an installed model",+ "description": "Delete an installed model's own files (its model GGUFs, its pack folder, its run config) and nothing "+ "another installed model still uses (a shared MTP draft or PLE file). Without confirm=true it only "+ "returns the plan (what would be removed and how big, what is kept). Stop the model first.",+ "inputSchema": {"type": "object", "additionalProperties": False, "required": ["model"],+ "properties": {"model": installed_model, "confirm": {"type": "boolean"}}},+ "annotations": {"readOnlyHint": False, "destructiveHint": True}},{"name": "strata_install", "title": "Install Strata","description": "Install a Strata model on this PC by running Strata's setup non-interactively in the ""background (Python packages, the engine, a 58-111 GB model download, preparation, start "@@ -1187,6 +1264,39 @@ class Tools:"gpus": [{k: g.get(k) for k in ("index", "name", "vram_gb", "usable")}for g in hw.get("gpus", [])]}}+ # ---- strata_remove+ def strata_remove(self, model=None, confirm=False) -> dict:+ s = self.s+ config = s.find_config(model)+ plan = s.removal_plan(config)+ if not confirm:+ return {"summary": f"Plan: delete {plan['model']} ({plan['gb']:.1f} GB). Nothing was done yet.", "plan": plan}+ with s.lock:+ job = s.install_job()+ if job and job["running"]:+ raise ToolError("an install is running: wait for it to finish or stop it first")+ tracked = s.tracked_server()+ if tracked and not tracked.get("ended") and tracked.get("model") == plan["model"]:+ raise ToolError("this model is running: stop it first")+ failed = []+ for item in sorted(plan["remove"], key=lambda x: (x["path"] == str(config), x["path"])):+ p = Path(item["path"])+ try:+ if p.is_dir():+ shutil.rmtree(p)+ else:+ p.unlink()+ except OSError as e:+ failed.append(f"{p.name}: {e}")+ files, dirs = s.model_paths(s.read_config(config)) if config.exists() else ([], [])+ for p in {x.parent for x in [Path(i["path"]) for i in plan["remove"]] if x.suffix == ".gguf"}:+ try:+ p.rmdir() # the model's own folder, when nothing else is in it+ except OSError:+ pass+ return {"summary": f"Deleted {plan['model']} ({plan['gb']:.1f} GB)" + (f"; could not remove {len(failed)} item(s)" if failed else ""),+ "plan": plan, "failed": failed}+# ---- strata_installdef check_data_dir(self, raw: str) -> Path:s = self.sdiff --git a/tools/test_strata_mcp.py b/tools/test_strata_mcp.pyindex ab1e4608a..9dd2210ad 100644--- a/tools/test_strata_mcp.py+++ b/tools/test_strata_mcp.py@@ -233,7 +233,7 @@ class Protocol(FakeRoot):self.assertIn("tools", init["capabilities"])self.assertEqual(init["serverInfo"]["name"], "strata")names = [t["name"] for t in r[2]["result"]["tools"]]- self.assertEqual(names, ["strata_status", "strata_models", "strata_install", "strata_start", "strata_stop",+ self.assertEqual(names, ["strata_status", "strata_models", "strata_remove", "strata_install", "strata_start", "strata_stop","strata_logs", "strata_benchmark", "strata_connect_info"])for t in r[2]["result"]["tools"]:self.assertEqual(t["inputSchema"]["type"], "object")@@ -272,7 +272,7 @@ class Protocol(FakeRoot):timeout=60, env=dict(os.environ))lines = [json.loads(x) for x in p.stdout.splitlines()]self.assertEqual(sorted(m["id"] for m in lines), [1, 2, 3])- self.assertEqual(len(next(m for m in lines if m["id"] == 2)["result"]["tools"]), 8)+ self.assertEqual(len(next(m for m in lines if m["id"] == 2)["result"]["tools"]), 9)self.assertIn("ready", p.stderr)def test_not_a_strata_folder(self):