diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 296d88da..10c04853 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -3526,6 +3526,7 @@ checksum = "ff7589a1859b09232522bb9edf076ca7fcf14ded96685d3fa629db73023ffbb7" name = "strata-desktop" version = "0.2.0-beta" dependencies = [ + "gtk", "serde", "serde_json", "tauri", @@ -3533,6 +3534,7 @@ dependencies = [ "tauri-plugin-shell", "tauri-plugin-single-instance", "tauri-plugin-updater", + "webkit2gtk", ] [[package]] diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index fa2c738a..e5890a28 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -6,6 +6,11 @@ edition = "2021" rust-version = "1.77" license = "MIT" +# Linux: the drop of a file on the window is read straight from the GTK drag signals (see hook_linux_drops in main.rs); the versions are the ones Tauri itself uses. +[target.'cfg(target_os = "linux")'.dependencies] +gtk = "0.18" +webkit2gtk = "2.0" + [build-dependencies] tauri-build = { version = "2", features = [] } diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index c303dfab..8b139ad0 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -914,9 +914,118 @@ fn open_window(app: &tauri::App, port: u16, shell_token: &str) -> Result<(), Box } }); } + #[cfg(target_os = "linux")] + hook_linux_drops(&window, port, shell_token); Ok(()) } +/// A file:// address from a drag, as a path (percent-escapes decoded); anything else (http, mailto, text) is not a dropped file. +#[cfg_attr(windows, allow(dead_code))] +fn file_uri_to_path(uri: &str) -> Option { + let rest = uri.trim().strip_prefix("file://")?; + // file://host/path: only an empty or local host is a file on this computer + let rest = match rest.find('/') { Some(0) => rest, Some(i) if rest[..i].eq_ignore_ascii_case("localhost") => &rest[i..], _ => return None }; + let bytes = rest.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' && i + 2 < bytes.len() { + if let Some(v) = std::str::from_utf8(&bytes[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()) { out.push(v); i += 3; continue; } + } + out.push(bytes[i]); + i += 1; + } + let path = String::from_utf8(out).ok()?; + if path.contains('\0') { None } else { Some(path) } +} + +/// Linux: WebKitGTK 2.52 gives the page a file drag without the files, and the window library's own drop handler never sees one, so the +/// shell reads the drop itself from the GTK drag signals of the page widget: the file:// addresses arrive with the drag data, the drop hands +/// them to the host exactly as the other systems do (hand_over_drop), and the page shows its drop box meanwhile (QA, drop on the chat). +#[cfg(target_os = "linux")] +fn hook_linux_drops(window: &tauri::WebviewWindow, port: u16, token: &str) { + use gtk::prelude::*; + use std::cell::{Cell, RefCell}; + use std::rc::Rc; + let target = window.clone(); + let token = token.to_string(); + let _ = window.with_webview(move |platform| { + let view = platform.inner(); + let paths: Rc>> = Rc::new(RefCell::new(Vec::new())); + let hovering = Rc::new(Cell::new(false)); + let generation = Rc::new(Cell::new(0u32)); + { + let (paths, hovering, generation, target) = (paths.clone(), hovering.clone(), generation.clone(), target.clone()); + view.connect_drag_data_received(move |_, _, _, _, data, _, _| { + let list: Vec = data.uris().iter().filter_map(|u| file_uri_to_path(u.as_str())).collect(); + if list.is_empty() { return; } + *paths.borrow_mut() = list; + generation.set(generation.get() + 1); + if !hovering.replace(true) { let _ = target.eval(&drag_script("enter")); } + }); + } + { + // WebKit only accepts a drag when the page says so, and the page is not given the files: once the addresses of a file drag are known, + // the shell accepts it (as a copy) itself, so GTK goes on to deliver the drop. + let paths = paths.clone(); + view.connect_drag_motion(move |_, ctx, _, _, time| { + if paths.borrow().is_empty() { return false; } + ctx.drag_status(gtk::gdk::DragAction::COPY, time); + true + }); + } + { + let (paths, hovering, generation, target) = (paths.clone(), hovering.clone(), generation.clone(), target.clone()); + let token = token.clone(); + view.connect_drag_drop(move |_, ctx, _, _, time| { + generation.set(generation.get() + 1); + let list = std::mem::take(&mut *paths.borrow_mut()); + if list.is_empty() { return false; } // not a file: the page deals with it + hovering.set(false); + ctx.drop_finish(true, time); + let _ = target.eval(&drag_script("leave")); + hand_over_drop(target.clone(), port, token.clone(), list); + true + }); + } + { + let (paths, hovering, target, token) = (paths.clone(), hovering.clone(), target.clone(), token.clone()); + view.connect_drag_leave(move |widget, _, _| { + // WebKit's own handling of a drop never reaches this widget's drop signal, but GTK does say "leave" at the moment of the drop: + // a leave with every mouse button already up (and a file drag known) is the drop. A leave with the button still down is the + // pointer going out of the window. + if hovering.get() && !paths.borrow().is_empty() && pointer_buttons_up(widget) { + let list = std::mem::take(&mut *paths.borrow_mut()); + hovering.set(false); + let _ = target.eval(&drag_script("leave")); + hand_over_drop(target.clone(), port, token.clone(), list); + } + }); + } + view.connect_drag_leave(move |_, _, _| { + // only a leave that nothing follows ends the drag (a drop is handled above and clears the state) + let seen = generation.get(); + let (paths, hovering, generation, target) = (paths.clone(), hovering.clone(), generation.clone(), target.clone()); + gtk::glib::idle_add_local_once(move || { + if generation.get() == seen && hovering.replace(false) { + paths.borrow_mut().clear(); + let _ = target.eval(&drag_script("leave")); + } + }); + }); + }); +} + +/// True when no mouse button is held down (GTK drag drop: the button is already up when the drop arrives). +#[cfg(target_os = "linux")] +fn pointer_buttons_up(widget: &webkit2gtk::WebView) -> bool { + use gtk::prelude::*; + let Some(window) = widget.window() else { return false }; + let Some(pointer) = gtk::gdk::Display::default().and_then(|d| d.default_seat()).and_then(|s| s.pointer()) else { return false }; + let (_, _, _, mask) = window.device_position(&pointer); + !mask.intersects(gtk::gdk::ModifierType::BUTTON1_MASK | gtk::gdk::ModifierType::BUTTON2_MASK | gtk::gdk::ModifierType::BUTTON3_MASK) +} + /// The script that tells the page a file drag is over the window (`state` is "enter" or "leave"); the page shows its drop box (apps/host DropZone). #[cfg_attr(windows, allow(dead_code))] fn drag_script(state: &str) -> String { @@ -1013,6 +1122,15 @@ fn run_window_process() -> ! { mod tests { use super::*; + #[test] + fn dropped_file_addresses_become_paths_and_nothing_else_does() { + assert_eq!(file_uri_to_path("file:///home/me/My%20Pictures/a%2Bb.png").as_deref(), Some("/home/me/My Pictures/a+b.png")); + assert_eq!(file_uri_to_path("file://localhost/tmp/x.txt").as_deref(), Some("/tmp/x.txt")); + assert_eq!(file_uri_to_path(" file:///tmp/%C4%8C.txt\r\n").as_deref(), Some("/tmp/\u{10C}.txt")); + for bad in ["http://example.com/a.png", "file://otherhost/tmp/x", "mailto:a@b.c", "/tmp/plain", "file://", "file:///tmp/a%00b"] { assert_eq!(file_uri_to_path(bad), None, "{bad}"); } + assert_eq!(file_uri_to_path("file:///100%").as_deref(), Some("/100%")); + } + #[test] fn the_scripts_the_shell_sends_the_page_for_a_file_drop() { assert_eq!(drag_script("enter"), "window.dispatchEvent(new CustomEvent('strata:native-drag', { detail: 'enter' }));"); diff --git a/apps/host/server/app-version.mjs b/apps/host/server/app-version.mjs index ee915faf..73ded1ee 100644 --- a/apps/host/server/app-version.mjs +++ b/apps/host/server/app-version.mjs @@ -17,3 +17,9 @@ export function appVersionFrom({ env = process.env, here }) { } catch { /* not a checkout */ } return 'dev'; } + +/** The version "Strata" means on screen and in the update check: the app's own, not Strata Control's (see src/lib/app-version.ts). */ +export function appVersionToShow(app, control) { + const real = value => (typeof value === 'string' && value.trim() && value.trim().toLowerCase() !== 'dev' ? value.trim() : null); + return real(app) ?? real(control) ?? (typeof app === 'string' && app.trim() ? app.trim() : null); +} diff --git a/apps/host/server/engine-step.mjs b/apps/host/server/engine-step.mjs index da774247..1274c7b5 100644 --- a/apps/host/server/engine-step.mjs +++ b/apps/host/server/engine-step.mjs @@ -75,8 +75,11 @@ export function createEngineStep({ control, signal = null, onChange = () => {} } const modelRemaining = Number.isFinite(model?.remaining_gb) ? model.remaining_gb : null; const active = !['done', 'current', 'skipped', 'failed'].includes(part.state); const engineRemaining = active || part.state === 'done' ? Math.max(0, part.total_gb - part.done_gb) : 0; + /* The install knows its files (strata_mcp files_progress): the model's parts and the picture reader, each counted. Without that, one + model part from the combined figures. The engine is added either way. */ + const own = Array.isArray(install.parts) && install.parts.some(p => p?.kind === 'model') ? install.parts.filter(p => p?.kind !== 'engine') : null; const parts = [ - { kind: 'model', name: model?.file ?? install.model ?? 'Model', state: install.running === false ? 'done' : 'downloading', done_gb: modelDone ?? 0, total_gb: round((modelDone ?? 0) + (modelRemaining ?? 0)) }, + ...(own ?? [{ kind: 'model', name: model?.file ?? install.model ?? 'Model', state: install.running === false ? 'done' : 'downloading', done_gb: modelDone ?? 0, total_gb: round((modelDone ?? 0) + (modelRemaining ?? 0)) }]), { ...part }, ]; const merged = { ...install, engine: { ...part }, parts }; diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 7f9f3e02..6db8848d 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -59,10 +59,11 @@ import { createChatFolders, openFile, resolveChatFile, previewFile, rawFile, cre import { createLlmProxy, samplingFromExpert } from './agent/llm-shape.mjs'; import { checkUpdates, checkComponentUpdates } from './updates.mjs'; import { createAppUi } from './app-ui.mjs'; -import { appVersionFrom } from './app-version.mjs'; +import { appVersionFrom, appVersionToShow } from './app-version.mjs'; import { createImageModels } from './image-models.mjs'; import { createRuntimeModels } from './runtime-models.mjs'; import { createNativeControl } from './native-control.mjs'; +import { nativeUnloadPlan } from './storage-check.mjs'; import { installBundledEngine } from './bundled-engine.mjs'; import { findControl, createControl, componentsDirectory } from './control-runtime.mjs'; import { forbidden as acquisitionForbidden } from './acquisition.mjs'; @@ -1287,7 +1288,7 @@ async function api(req, res, path, method, url) { if (path === '/api/setup' && method === 'GET') return json(res, 200, setupState()); if (path === '/api/updates/check' && method === 'GET' && control?.updateCheck) return json(res, 200, await checkComponentUpdates({ control, appUpdater, appVersion: process.env.STRATA_APP_VERSION || null })); - if (path === '/api/updates/check' && method === 'GET') return json(res, 200, await checkUpdates({ appVersion:native.state().version??setupState().app.version, engineVersion:native.state().available?(native.state().installed?.engine?.version??null):(await engine.config()).engine.version })); + if (path === '/api/updates/check' && method === 'GET') return json(res, 200, await checkUpdates({ appVersion:appVersionToShow(setupState().app.version,native.state().version), engineVersion:native.state().available?(native.state().installed?.engine?.version??null):(await engine.config()).engine.version })); if (path === '/api/setup/step' && method === 'POST') { const body = await readBody(req); @@ -1349,7 +1350,9 @@ async function api(req, res, path, method, url) { if (storageChanging || modelOperations || models.directoryBusy() || imageModels.busy()||native.state().jobs.some(j=>j.state==='running')) return error(res, 409, 'Finish or cancel model downloads and loading before changing the folder.'); if (serving.state().requests.some(r => ['queued', 'generating'].includes(r.state))) return error(res, 409, 'Finish or cancel model requests before changing the folder.'); if (changed && instances.length && body.unload !== true) return error(res, 409, 'Unload the current models before changing the folder.'); - if(native.state().instances.length){if(!body.unload)return error(res,409,'Unload native models before changing the model folder.');for(const instance of native.state().instances)await native.unload(instance.id);} + const nativePlan=nativeUnloadPlan({changed,unload:body.unload,instances:native.state().instances}); + if(nativePlan.refuse)return error(res,409,nativePlan.refuse); + for(const id of nativePlan.ids)await native.unload(id); storageChanging = true; try { if (changed) { diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index a7c1c8f9..147ff225 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -25,6 +25,8 @@ 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;}} +/** The plain words for "no usable engine": the model still downloads, but loading needs the engine (owner decision 2026-10-18). */ +export const ENGINE_NOT_RECOGNISED='Strata didn’t recognise an engine for this computer. The model is downloaded, but it can’t run until the right engine is installed. Open Settings → Engine.'; export function createNativeControl({directory,requests=()=>[],changed=()=>{},spawnProcess=spawn,fetcher=fetch,modelsDirectory,nativeDataDirectory=value=>value,beforeLoad=async()=>{},hardwareProbe=()=>[],control=null,ready=null,appUpdater=null,defaultRepo=process.env.STRATA_NATIVE_REPO??resolve(ROOT,'../../Strata')}={}){ mkdirSync(directory,{recursive:true}); const settingsPath=join(directory,'native-host.json'); @@ -67,7 +69,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp 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,visionPrepared:!!cfg.vision,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,sharedBytes:entry.sharedBytes??entry.shared_bytes,removableGb:entry.removableGb??entry.removable_gb,dataFolder,visionPrepared:!!cfg.vision,/* Picture reading is ON unless the person turned it off: no saved choice and not loaded is undefined, not false (owner rule: pictures on by default). */visionEnabled:cfg.ui_vision_enabled??(()=>{const running=[...instances.values()].find(i=>i.model===entry.model&&i.status==='ready');return running?!!running.vision:undefined;})(),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].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});} @@ -96,12 +98,12 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp 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 disk=Object.fromEntries((installer.installed?.models??[]).map(m=>[m.model,{diskGb:m.disk_gb,diskBytes:m.disk_bytes,sharedBytes:m.shared_bytes,removableGb:m.removable_gb,partsMissing:m.parts_missing??0}])); + 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'&&!(disk[m.id]?.partsMissing),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}, + 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,usage:installer.installed?.usage??null}, 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}; } @@ -204,7 +206,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} return {cfg,resources,visionPreferences,parallelChoice,parallelNote}; } async function loadEngine(job,args){ - await refresh(true);if(job.state!=='running')return;const {config,entry,path:configFile}=record(args.model);assertSettingsFile(configFile);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.'); + await refresh(true);if(job.state!=='running')return;const {config,entry,path:configFile}=record(args.model);assertSettingsFile(configFile);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(ENGINE_NOT_RECOGNISED+(engine.notice?` ${engine.notice}`:''));}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,parallelChoice,parallelNote:chosenNote}=buildConfig(args,config); @@ -345,7 +347,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} async function tuneOff(args){await refresh();const {path}=tuneConfig(args);return autotuner.off(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.');} + if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(ENGINE_NOT_RECOGNISED+(engine.notice?` ${engine.notice}`:''));} 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.'); @@ -355,7 +357,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} 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.');if(kind==='install'||kind==='load'){const refusal=engineRefusal(snapshot.catalog,args.model,snapshot.engineInfo);if(refusal)throw new Error(refusal);}return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):kind==='autotune'||kind==='recheck'?autotune(job,args):kind==='remove'?removeModel(job,args):program(job,args),{guided:args.guided===true,model:args.model});} + function operation(kind,args={}){if(!['install','load','benchmark','tune','autotune','recheck','calibrate','update-engine','update-strata','rollback','remove'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');if(kind==='install'||kind==='load'){const refusal=engineRefusal(snapshot.catalog,args.model,snapshot.engineInfo);if(refusal)throw new Error(refusal);}return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):kind==='autotune'||kind==='recheck'?autotune(job,args):kind==='remove'?removeModel(job,args):program(job,args),{guided:args.guided===true,model:args.model,...(args.family?{family:args.family}:{})});} async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install'){job.engineAbort?.abort();await tool('strata_install',{cancel:true});}else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate','autotune','recheck'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} 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/server/native-vision.mjs b/apps/host/server/native-vision.mjs index 922ddfd2..0394ea02 100644 --- a/apps/host/server/native-vision.mjs +++ b/apps/host/server/native-vision.mjs @@ -5,5 +5,6 @@ export function runtimeVision(config,requested){ if(mode==='no')return undefined; if(mode===undefined)return config.vision; if(!config.vision)throw new Error('Prepare this model’s vision files before enabling picture reading.'); + if(mode==='cpu'&&config.vision.cpu_exe){const {cpu_exe,...rest}=config.vision;return {...rest,exe:cpu_exe,gpu:false};} // AMD: the CPU reader program, not the HIP one with the GPU hidden return {...config.vision,...(mode==='cpu'?{gpu:false}:mode==='gpu'?{gpu:true}:{})}; } diff --git a/apps/host/server/storage-check.mjs b/apps/host/server/storage-check.mjs new file mode 100644 index 00000000..fc09a197 --- /dev/null +++ b/apps/host/server/storage-check.mjs @@ -0,0 +1,13 @@ +/** + * What changing (or only checking) the model folder does to the models that are loaded. + * + * "Check folder" reads the SAME folder again, so nothing that is loaded may be touched: it used to unload every optimized model + * and the status went to "No model loaded" (QA 2026-10-18, O01). Only an actual change of folder unloads them, and only when + * the person agreed (the screen says so first and offers "Unload and change directory"). + */ +export function nativeUnloadPlan({ changed, unload, instances }) { + const running = Array.isArray(instances) ? instances : []; + if (!running.length || !changed) return { refuse: null, ids: [] }; + if (unload !== true) return { refuse: 'Unload native models before changing the model folder.', ids: [] }; + return { refuse: null, ids: running.map(i => i.id) }; +} diff --git a/apps/host/src/components/DownloadParts.tsx b/apps/host/src/components/DownloadParts.tsx new file mode 100644 index 00000000..0827ad02 --- /dev/null +++ b/apps/host/src/components/DownloadParts.tsx @@ -0,0 +1,17 @@ +import { tr } from '../lib/i18n'; + +export interface InstallPart { kind?: string; name?: string; state?: string; done_gb?: number; total_gb?: number; files_done?: number; files_total?: number } + +/** + * The parts of a download, one line each: the model (with "2/4" when it comes in parts), the picture reader, the engine. A model in several + * parts is only downloaded when every line says Done, so a person can see which part is under way instead of one bar that restarts. + */ +export function DownloadParts({ parts }: { parts: InstallPart[] | undefined }) { + if (!parts || parts.length < 2) return null; + return
    + {parts.map(p =>
  • + {tr(p.name)}{(p.files_total ?? 0) > 1 ? ` ${p.files_done ?? 0}/${p.files_total}` : ''} + {p.state === 'done' || p.state === 'current' ? tr('Done') : p.state === 'waiting' || p.state === 'pending' ? tr('Waiting') : Number.isFinite(p.done_gb) && Number.isFinite(p.total_gb) ? `${p.done_gb!.toFixed(1)} / ${p.total_gb!.toFixed(1)} GB` : ''} +
  • )} +
; +} diff --git a/apps/host/src/components/EngineWarning.tsx b/apps/host/src/components/EngineWarning.tsx new file mode 100644 index 00000000..cbaa13c9 --- /dev/null +++ b/apps/host/src/components/EngineWarning.tsx @@ -0,0 +1,12 @@ +import { tr } from '../lib/i18n'; +import { Icon } from './ui'; +import type { NativeState } from '../lib/native'; + +/** The app could not find or recognise an engine for this computer (none installed and none in the feed, another card family, a driver that is too old). It still downloads the model + * (owner decision 2026-10-18) and says so before and during the download; loading says the same with the next step. */ +export const engineMissing = (native: NativeState | null | undefined) => !!native?.engine && native.engine.usable === false; + +export function EngineWarning({ native }: { native: NativeState | null | undefined }) { + if (!engineMissing(native)) return null; + return

{tr("Strata didn’t recognise an engine for this computer. The model will download, but it may not run until the right engine is installed (Settings → Engine).")}

{native?.engine?.notice ? {native.engine.notice} : null}
; +} diff --git a/apps/host/src/components/GuidedSetup.tsx b/apps/host/src/components/GuidedSetup.tsx index 15682632..3697fdb7 100644 --- a/apps/host/src/components/GuidedSetup.tsx +++ b/apps/host/src/components/GuidedSetup.tsx @@ -12,7 +12,11 @@ import { nativeAction, useNative, type NativeJob } from '../lib/native'; import { completeSetup, completeSetupStep, go, newSession, openSetup, selectRemoteModel, setSettingsSection, useStore } from '../lib/store'; import type { LocalModelFolder, SetupState } from '../lib/types'; import { downloadCounter, modelFolderLabel, onboardingError } from '../lib/onboarding-download'; -import { installProgress, useDownloadEta } from '../lib/download-eta'; +import { installProgress, installStage, stageText, useDownloadEta } from '../lib/download-eta'; +import { VersionPicker } from './VersionPicker'; +import { DownloadParts } from './DownloadParts'; +import { EngineWarning } from './EngineWarning'; +import { recommendedVersions } from '../lib/native-fit'; import { nativeCatalogModels, catalogVersionLabel } from '../lib/native-catalog'; type Choices = NonNullable['onboarding']>; function radioKeys(event: KeyboardEvent) { if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) @@ -161,6 +165,12 @@ export function GuidedSetup() { } }); return () => { cancelled = true; }; }, [step, plan, preparing, native?.available, version?.id, context, directory]); + const recommendedCards = recommendedVersions(selectedFamily?.sizes ?? []).map(x => x.v); + // The recommended four first, then a list with every other version (the Models page's version list); a family without a recommended set shows them all. + const cards = recommendedCards.length ? recommendedCards : selectedFamily?.sizes ?? []; + const others = recommendedCards.length ? (selectedFamily?.sizes ?? []).filter(v => !recommendedCards.includes(v)) : []; + const readyIds = new Set((native?.installed?.models ?? []).filter(m => m.ready).map(m => m.model)); + const versionCard = (v: NonNullable) => ; const counter = downloadCounter(plan?.plan?.download_gb ?? version?.download_gb, progress, preparing); const eta = useDownloadEta(preparing ? progress : undefined, installJob?.id); const title = step === 1 ? 'State of the art. At home.' : step === 2 ? 'Select the model you want to run.' : step === 3 ? 'Downloading the model...' : tuneJob?.state === 'running' ? 'A little tuning. A better fit.' : 'How you would like to work with Strata?'; @@ -179,13 +189,14 @@ export function GuidedSetup() {
{tr("Model")}
({ value: String(n), label: `${n / 1024}K` }))} onChange={value => setContext(Number(value))}/>
{tr(!version || version.needsNewerEngine ?

{tr("This model needs a newer engine. Update your engine or import a local GGUF for this model.")}

: null)}
{tr("Choose a version")}{tr(version ? `${catalogVersionLabel(version)} selected` : '')}
-
{tr(selectedFamily.sizes.map(v => ))}
+
{tr(cards.map(v => versionCard(v)))}
+ {tr(others.length ?
g.usable !== false).map(g => g.vram_gb)) } : null} downloaded={readyIds} showRecommended={false} moreLabel="More versions" onSelect={id => { setSize(id); setPlan(null); }} onOwnGguf={() => setFolderOpen(true)}/>
: null)}
{tr(directory ? 'Your model folder' : 'Already downloaded the model?')}{tr(directory || "Choose the folder and we'll start your models with Strata.")}
setFolderOpen(v => !v)}>{tr(folderOpen ? 'Close' : directory ? 'Change' : 'Choose folder')}
{tr(folderOpen ? void perform(async () => { await nativeAction('directory', { directory: path }); setDirectory(path); setFolderOpen(false); setPlan(null); })}/> : null)} :
{tr("Connect your Strata installation")} void skip(false, 'Engine')}>{tr("Connect engine")}
)}
: step === 3 ?
-
{tr(selectedFamily?.title)}{tr(version ? catalogVersionLabel(version) : '')}{tr(version?.model)}
- {tr(preparing ?
{tr(progress ? 'Downloading model files…' : 'Preparing your model…')}
{tr(progress ? : )}
{tr(progress ? `${progress.percent ?? 0}%${Number.isFinite(progress.done_gb) && Number.isFinite(progress.total_gb) ? ` · ${progress.done_gb!.toFixed(1)} / ${progress.total_gb!.toFixed(1)} GB` : ''}` : 'Getting files ready…')}
{tr(eta ? {eta} : null)}
: <>{tr(stopped ? : null)}{tr(plan?.plan?.disk_short ? : null)})} +
{tr(selectedFamily?.title)}{tr(version ? catalogVersionLabel(version) : '')}{tr(version?.model)}
+ {tr(preparing ?
{tr(progress ? stageText(installStage(installJob?.result?.install)) : 'Preparing your model…')}
{tr(progress ? : )}
{tr(progress ? `${progress.percent ?? 0}%${Number.isFinite(progress.done_gb) && Number.isFinite(progress.total_gb) ? ` · ${progress.done_gb!.toFixed(1)} / ${progress.total_gb!.toFixed(1)} GB` : ''}` : 'Getting files ready…')}
{tr(eta ? {eta} : null)}
: <>{tr(stopped ? : null)}{tr(plan?.plan?.disk_short ? : null)})} {tr("Save to")}{tr(modelFolderLabel(folder))}{tr(!preparing ? : null)}
:
diff --git a/apps/host/src/components/NativeDelete.tsx b/apps/host/src/components/NativeDelete.tsx index 07e9ba62..97cf3fd3 100644 --- a/apps/host/src/components/NativeDelete.tsx +++ b/apps/host/src/components/NativeDelete.tsx @@ -14,7 +14,9 @@ export function NativeDeleteDialog({ id, onClose }: { id: string | null; onClose 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; + const size = entry?.diskGb ?? 0, gb = entry?.removableGb ?? size; + // Files in the person's own folder (an adopted GGUF) stay where they are: only the entry is removed. + const keepsFiles = entry?.removableGb === 0 && size > 0; function close() { if (!pending) { onClose(); setError(''); } } async function remove() { setPending(true); @@ -36,8 +38,8 @@ export function NativeDeleteDialog({ id, onClose }: { id: string | null; onClose finally { setPending(false); } } return {tr("Keep version")} void remove()}>{tr(pending ? 'Working…' : 'Delete version')}}> -

{tr(label)}{tr(gb ? ` · ${sizeGb(gb)}` : '')}

- {tr(entry ?

{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.' : '')}

:

{tr("This version is no longer downloaded.")}

)} +

{tr(label)}{tr(size ? ` · ${sizeGb(size)}` : '')}

+ {tr(!entry ?

{tr("This version is no longer downloaded.")}

:

{keepsFiles ? tr('These files are in your own folder, so they stay there. Only the entry in Strata is removed.') : tr('Remove {0} GB of downloaded files. You can download this version again.', [gb ? gb.toFixed(1) : '0'])}{tr(running ? ' ' : '')}{tr(running ? (keepsFiles ? 'The running model will be unloaded.' : 'The running model will be unloaded and its files deleted.') : '')}

)} {tr(error ? : null)}
; } diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index b852f935..05827343 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -6,7 +6,10 @@ import { FamilySwitch } from './FamilySwitch'; import { PcFitCard } from './PcFitCard'; import { fitOn } from '../lib/native-fit'; import { Btn, Dialog, ErrorNotice, Icon, Select } from './ui'; -import { installProgress, useDownloadEta } from '../lib/download-eta'; +import { installProgress, installStage, stageText, useDownloadEta } from '../lib/download-eta'; +import { useKept } from '../lib/kept-state'; +import { DownloadParts } from './DownloadParts'; +import { EngineWarning } from './EngineWarning'; import { sizeGb } from '../lib/format'; import { NativeDeleteDialog } from './NativeDelete'; import { plainFailureText } from '../lib/plain-errors'; @@ -31,12 +34,14 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine onReady?: () => void; }) { const native = useNative(), imageLibrary = useStore(s => s.imageModels), hardware = useStore(s => s.hardware); - const [family, setFamily] = useState(''), [size, setSize] = useState(''), [context, setContext] = useState(32768), [vision, setVision] = useState('yes'); + // The choices are kept while the page is closed (Models -> Monitor -> Models used to start them over and a person lost track of what was downloading). + const [family, setFamily] = useKept('models.family', ''), [size, setSize] = useKept('models.size', ''), [context, setContext] = useKept('models.context', 32768), [vision, setVision] = useKept('models.vision', 'yes'); const manual = useStore(s => s.setup?.choices?.onboarding?.manual ?? false); - const [expert, setExpert] = useState(manual), [multiple, setMultiple] = useState(false), [gpus, setGpus] = useState([]), [kv, setKv] = useState('int8'), [lowRam, setLowRam] = useState('auto'), [split, setSplit] = useState('auto'), [deviceChoice, setDeviceChoice] = useState('auto'); - const [cardsKey, setCardsKey] = useState(null); - const [resourceProfile, setResourceProfile] = useState<'work' | 'performance'>('work'); - const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState | null>(null), [loadedError, setLoadedError] = useState(''), [tuneOpen, setTuneOpen] = useState(false), [jobId, setJobId] = useState(''), [manage, setManage] = useState(false); + const [expert, setExpert] = useKept('models.expert', manual), [multiple, setMultiple] = useKept('models.multiple', false), [gpus, setGpus] = useKept('models.gpus', []), [kv, setKv] = useKept('models.kv', 'int8'), [lowRam, setLowRam] = useKept('models.lowRam', 'auto'), [split, setSplit] = useKept('models.split', 'auto'), [deviceChoice, setDeviceChoice] = useKept('models.device', 'auto'); + const [cardsKey, setCardsKey] = useKept('models.cards', null); + const [resourceProfile, setResourceProfile] = useKept<'work' | 'performance'>('models.profile', 'work'); + const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState | null>(null), [loadedError, setLoadedError] = useState(''), [tuneOpen, setTuneOpen] = useState(false), [jobId, setJobId] = useKept('models.job', ''), [manage, setManage] = useState(false); + const [toastedJob, setToastedJob] = useKept('models.toasted', ''), [appliedSig, setAppliedSig] = useKept('models.applied', ''); const presetPending = useRef(false); const [deleting, setDeleting] = useState(null); const families = nativeCatalogModels(native?.catalog?.families ?? []); @@ -56,15 +61,11 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const keptUse = keptModels.map(i => { const s = sizeOf(i.model); const card = pcGpus.find(g => g.index === i.gpus[0]); const f = s && pcRam ? fitOn(s, { ram_gb: pcRam, vram_gb: card?.vram_gb ?? pcVram }) : null; return { gpus: i.gpus, ram: f?.ramUseGb ?? 0, vram: f?.vramUseGb ?? 0 }; }); const keptRam = keptUse.reduce((n, u) => n + u.ram, 0); const keptVramOn = (cards: number[]) => keptUse.filter(u => u.gpus.some(g => cards.includes(g))).reduce((n, u) => n + u.vram, 0); + // The versions that are really on this computer: a config whose files are all there (every part of a model in parts). + const readyIds = useMemo(() => new Set(downloaded.filter(m => m.ready).map(m => m.model)), [downloaded]); + // What a running job works on, by its name in the list: "Qwen3.8-Flash-Next · Gyro · Smallest". + const jobLabel = (j: NativeJob) => { const v = allSizes.find(s => s.id === j.model || (s.model === j.model && (!j.family || s.sourceFamily === j.family))); const f = v && families.find(x => x.sizes.includes(v)); return v ? [f?.title, catalogVersionLabel(v)].filter(Boolean).join(' · ') : ''; }; const loadedSelected = native?.instances.find(i => i.model === selectedSize?.id && i.status === 'ready'); - // A model that is already on this PC loads as it was prepared: the page shows its settings, so loading it never asks to download. - useEffect(() => { if (installed?.ready) { - if (installed.context) - setContext(installed.context); - if (installed.kv) - setKv(installed.kv as typeof kv); - setLowRam((installed.lowRamMode ?? 'auto') as typeof lowRam); - } }, [installed?.model, installed?.ready, installed?.context, installed?.kv, installed?.lowRamMode]); // What the running model was really started with is what the page shows: after Load the highlight must still be the profile that was applied. useEffect(() => { if (loadedSelected?.resourceProfile) setResourceProfile(loadedSelected.resourceProfile); }, [loadedSelected?.id, loadedSelected?.resourceProfile]); @@ -93,7 +94,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const gpuNumbers = (text: string) => text.replace(/\(card (\d+)\)/g, (_m, n) => `(GPU ${Number(n) + 1})`); // The fit sentence for a card choice, less what the kept models take of RAM and of that card's memory. const lessKept = (words: string, cards: number[]) => { const gone = Math.round(keptRam + keptVramOn(cards)); return gone > 0 ? words.replace(/of the (\d+) GB available/, (_m, n) => `of the ${Math.max(0, Number(n) - gone)} GB available`) : words; }; - useEffect(() => { setCardsKey(null); }, [selectedSize?.id]); + const shownSize = useRef(selectedSize?.id); + useEffect(() => { if (shownSize.current !== selectedSize?.id) { shownSize.current = selectedSize?.id; setCardsKey(null); } }, [selectedSize?.id]); const values = useMemo(() => ({ family: selectedSize?.sourceFamily, model: selectedSize?.model, context, vision: selectedSize?.images ? vision : 'no', kv, low_ram: lowRam, resourceProfile, ...(expert && gpus.length ? { gpus: gpus.join(',') } : cardsGpus.length > 1 ? { gpus: cardsGpus.join(',') } : cardsGpus.length === 1 ? { gpu: cardsGpus[0] } : {}), loadAfter: true, multiple: expert && multiple }), [selectedSize?.sourceFamily, selectedSize?.model, context, vision, kv, lowRam, resourceProfile, gpus.join(','), cardsGpus.join(','), expert, multiple]); const downloadValues = { ...values, vision: selectedSize?.images ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no' }; useEffect(() => { if (!native?.catalog || family) @@ -102,19 +104,36 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine setSize(f.sizes.find(s => s.id === current?.model)?.id ?? f.sizes.find(s => have.has(s.id))?.id ?? f.sizes.find(s => s.model === rec.model)?.id ?? f.sizes[0]?.id ?? ''); setContext(('context' in rec ? rec.context : undefined) ?? 32768); } }, [native?.catalog]); - useEffect(() => { if (presetPending.current) { - presetPending.current = false; - return; - } if (installed) { - setContext(installed.context ?? 32768); - setVision(installed.visionEnabled === false || installed.images === 'off' ? 'no' : installed.visionDevice ?? installed.images ?? 'yes'); - setKv(installed.kv ?? 'int8'); - setLowRam(installed.lowRamMode ?? 'auto'); - // A model never tuned has no saved choice: keep the page's own (Leave 20%) rather than flipping to Full performance. - if (installed.resourceProfile && !loadedSelected?.resourceProfile) - setResourceProfile(installed.resourceProfile); - } }, [installed?.model, installed?.context, installed?.kv, installed?.images, installed?.visionEnabled, installed?.visionDevice, installed?.lowRamMode, installed?.resourceProfile]); - useEffect(() => { if (jobId && job?.state === 'done' && (job.kind === 'load' || job.kind === 'install')) { + // The version that is selected: a model already on this PC shows the settings it was prepared with (so loading it never asks to download); + // a model that is not yet downloaded starts with Read pictures ON (owner rule: pictures on by default). This runs when the SELECTION or the + // installed settings change, not when the page opens again: coming back from another tab keeps what was chosen. + useEffect(() => { + if (presetPending.current) { + presetPending.current = false; + return; + } + if (!selectedSize) + return; + const sig = installed ? ['have', installed.model, installed.ready, installed.context, installed.kv, installed.images, installed.visionEnabled, installed.visionDevice, installed.lowRamMode, installed.resourceProfile].join('|') : `new|${selectedSize.id}`; + if (sig === appliedSig) + return; + setAppliedSig(sig); + if (installed) { + if (installed.context) + setContext(installed.context); + // Off only when the person turned it off (a saved choice); a model prepared without the picture files (images 'off') still starts with it ON. + setVision(installed.visionEnabled === false ? 'no' : installed.visionDevice ?? (installed.images && installed.images !== 'off' ? installed.images : 'yes')); + setKv(installed.kv ?? 'int8'); + setLowRam(installed.lowRamMode ?? 'auto'); + // A model never tuned has no saved choice: keep the page's own (Leave 20%) rather than flipping to Full performance. + if (installed.resourceProfile && !loadedSelected?.resourceProfile) + setResourceProfile(installed.resourceProfile); + } + else + setVision('yes'); + }, [selectedSize?.id, installed?.model, installed?.ready, installed?.context, installed?.kv, installed?.images, installed?.visionEnabled, installed?.visionDevice, installed?.lowRamMode, installed?.resourceProfile]); + useEffect(() => { if (jobId && job?.state === 'done' && job.id !== toastedJob && (job.kind === 'load' || job.kind === 'install')) { + setToastedJob(job.id); selectRemoteModel(null); pushToast('success', 'Model ready', 'Start a new chat when you’re ready.'); } }, [job?.state]); @@ -153,7 +172,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(selectedSize ? <>
{tr("Version")} { const f = families.find(f => f.family === v.family || f.sizes.some(s => s.sourceFamily === v.family)); if (!f) return; presetPending.current = true; setFamily(f.family); setSize(f.sizes.find(s => s.model === v.model && (s.sourceFamily === v.family || f.family === v.family))?.id ?? ''); setContext(v.context ?? 32768); setVision(v.vision ?? 'no'); setKv(v.kv ?? 'int8'); setLowRam(v.low_ram ?? 'auto'); }}/> setManage(true)}>{tr("Manage models")}
-
{ const f = families.find(f => f.sizes.some(s => s.id === id)); if (f) { setFamily(f.family); setSize(id); setError(''); } }} onOwnGguf={() => (onImport ?? onOtherModels)()}/>
+
{ const f = families.find(f => f.sizes.some(s => s.id === id)); if (f) { setFamily(f.family); setSize(id); setError(''); } }} onOwnGguf={() => (onImport ?? onOtherModels)()}/>
{tr(noFit ?

{tr("May run slower \u00B7 Model data can be read from SSD.")}

: null)}
{tr("Conversation context")} setVision(e.target.checked ? 'yes' : 'no')}/>{tr("Read pictures ")}{tr("On by default")}{tr("Understand photos, screenshots and charts. The picture files download automatically. Turn it off to save memory.")}{tr(expert && vision !== 'no' ? ({ 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); }}/> + + {tr(rows ?
    + {tr(nativeModels.map(m =>
  • {nativeShortName(m.model)}{tr(native?.instances.some(i => i.model === m.model) ? {tr('Loaded')} : null)}{tr(sizeGb(m.diskGb ?? 0))} j.state === 'running')} onClick={() => setNativeDeleting(m.model)}>{tr("Delete")}
  • ))} + {tr(versions.map(v =>
  • {`${v.local ? v.name : v.family} · ${v.quant}`}{tr(v.local ? {tr('Local')} : null)}{tr(v.id === library?.loaded ? {tr('Loaded')} : null)}{tr(sizeGb(v.diskGb))} { setError(''); setSelected(v.id); }}>{tr("Delete")}
  • ))} + {tr(sharedGb > 0 ?
  • {tr("Shared files")}{tr("Used by more than one model")}{tr(sizeGb(sharedGb))}
  • : null)} +
:

{tr("No downloaded models")}

)}
- {tr(native?.installed?.models.length ? n + (m.diskGb ?? 0), 0))])}> -
    {tr(native.installed.models.map(m =>
  • {nativeShortName(m.model)}{tr(native.instances.some(i => i.model === m.model) ? {tr('Loaded')} : null)}{tr(sizeGb(m.diskGb ?? 0))} j.state === 'running')} onClick={() => setNativeDeleting(m.model)}>{tr("Delete")}
  • ))}
-
: null)} setNativeDeleting(null)}/> {tr("Keep version")} void remove()}>{tr(pending ? 'Working…' : version?.local ? 'Remove model' : 'Delete version')}}>

{tr(version ? `${version.local ? version.name : version.family} · ${version.quant} · ${sizeGb(version.diskGb)}` : 'This version is no longer downloaded.')}

diff --git a/apps/host/src/components/SettingsUpdates.tsx b/apps/host/src/components/SettingsUpdates.tsx index 1f3e65c9..42cb142d 100644 --- a/apps/host/src/components/SettingsUpdates.tsx +++ b/apps/host/src/components/SettingsUpdates.tsx @@ -6,11 +6,12 @@ import { useStore } from '../lib/store'; import type { SoftwareUpdate, UpdateCheckResult } from '../lib/types'; import { nativeAction, useNative } from '../lib/native'; import { NativeProgress } from './NativeModels'; +import { appVersionLabel } from '../lib/app-version'; /** Installed versions are real host values. Installation needs a host updater. */ export function SettingsUpdates() { const native = useNative(); const [confirm, setConfirm] = useState(''); - const appVersion = useStore(s => s.setup?.app.version); + const appVersion = appVersionLabel(useStore(s => s.setup?.app.version), native?.version); const engineVersion = useStore(s => s.engine?.engine.version); const [rollback, setRollback] = useState(false); const [component, setComponent] = useState<'strata' | 'engine'>('strata'); @@ -19,7 +20,7 @@ export function SettingsUpdates() { const [error, setError] = useState(''); const request = useRef(null); useEffect(() => () => request.current?.abort(), []); - const installed = component === 'strata' ? native?.version ?? appVersion : native?.available ? (native.installed?.engine?.version ?? 'Not installed') : engineVersion; + const installed = component === 'strata' ? appVersion : native?.available ? (native.installed?.engine?.version ?? 'Not installed') : engineVersion; const active = native?.jobs.find(j => j.state === 'running'); async function operate(kind: string) { setError(''); @@ -68,7 +69,7 @@ export function SettingsUpdates() { } return <>
- {tr(versionRow('Strata', native?.version ?? appVersion, result?.strata))} + {tr(versionRow('Strata', appVersion, result?.strata))} {tr(versionRow('Engine', native?.available ? (native.installed?.engine?.version ?? 'Not installed') : engineVersion, result?.engine))}
void check()}>{tr(checking ? 'Checking…' : error || result?.strata.status === 'error' ? 'Try again' : result ? 'Check again' : 'Check for updates')} setRollback(true)}>{tr("Roll back\u2026")}
{tr(checking ? 'Checking for new versions…' : error ? {tr(error)} : result ? <>{tr(result.strata.message)} {tr(result.engine.message)} {tr("Checked at ")}{tr(new Date(result.checkedAt).toLocaleTimeString(localeTag(), { hour: '2-digit', minute: '2-digit' }))} : null)}
@@ -85,3 +86,12 @@ export function SettingsUpdates() { setConfirm('')} actions={<> setConfirm('')}>{tr("Cancel")} 0} onClick={() => void operate(confirm)}>{tr("Update")}}>

{tr("The native installer updates the installation. Model files and settings are kept. Unload native models before updating.")}

{tr((native?.instances.length ?? 0) > 0 ?

{tr("Open Models and unload the running native models first.")}

: null)}
; } + +/** "Strata 0.2.0-beta · Engine 0.1.45.3": the app's own version first, the engine's beside it (About). */ +export function AboutVersions() { + const native = useNative(); + const app = appVersionLabel(useStore(s => s.setup?.app.version), native?.version); + const engineVersion = useStore(s => s.engine?.engine.version); + const engine = native?.available ? native.installed?.engine?.version : engineVersion; + return

{tr("Strata")} {app ?? ''}{engine ? · {tr("Engine")} {engine} : null}

; +} diff --git a/apps/host/src/components/VersionPicker.tsx b/apps/host/src/components/VersionPicker.tsx index b173a737..c0b9e726 100644 --- a/apps/host/src/components/VersionPicker.tsx +++ b/apps/host/src/components/VersionPicker.tsx @@ -3,14 +3,16 @@ import { tr } from '../lib/i18n'; import { Icon } from './ui'; import { FloatingMenu } from './FloatingMenu'; import { cx } from '../lib/format'; -import type { CatalogVersion } from '../lib/native-catalog'; -import { RECOMMENDED, VERSION_GROUPS, fitOn, groupOpen, type FitHardware } from '../lib/native-fit'; +import { versionNote, type CatalogVersion } from '../lib/native-catalog'; +import { nvfp4Version } from '../lib/native-names'; +import { VERSION_GROUPS, fitOn, groupOpen, recommendedVersions, type FitHardware } from '../lib/native-fit'; /** The name a version goes by in the list: the quantization, with the maker where the quantization alone is ambiguous. */ export function versionName(v: CatalogVersion, withMaker = false): string { switch (v.sourceFamily) { case 'swift': return `Swift ${v.model}`; case 'unsloth': return `Unsloth ${v.model}`; + case 'nvfp4': return tr(nvfp4Version(v.model)?.name ?? v.model); case 'coder': return `Coder ${v.model}`; case 'qwen': return withMaker ? `${v.model} (GSQ-RCO)` : v.model; default: return v.model; @@ -24,43 +26,52 @@ const gb = (n: number) => `${Number.isInteger(n) ? n : n.toFixed(1)} GB`; * which stays on the SSD, is not in it); the download size is secondary. "Uses SSD N GB" appears only where this computer would read * part of the model from its SSD. The first group is a fixed list of four; the rest fold away. */ -export function VersionPicker({ versions, selectedId, hardware, onSelect, onOwnGguf }: { +export function VersionPicker({ versions, selectedId, hardware, onSelect, onOwnGguf, downloaded, showRecommended = true, moreLabel }: { versions: CatalogVersion[]; selectedId: string; hardware: FitHardware | null | undefined; onSelect: (id: string) => void; onOwnGguf: () => void; + /** The versions already on this computer (ready to load): each gets a small "Downloaded" tag. */ + downloaded?: ReadonlySet; + /** False where the recommended four are shown elsewhere (the first-run page): the menu then holds only the groups. */ + showRecommended?: boolean; + /** What the button says while the selected version is one of the recommended four shown elsewhere. */ + moreLabel?: string; }) { const trigger = useRef(null); const [open, setOpen] = useState(false); // A group is open when the person opened it; until they touch it, only the group that holds the selected version is open. const [opened, setOpened] = useState>({}); const selected = versions.find(v => v.id === selectedId); - const recommended = RECOMMENDED.map(r => ({ r, v: versions.find(v => v.sourceFamily === r.family && v.model === r.model) })).filter((x): x is { r: typeof RECOMMENDED[number]; v: CatalogVersion } => !!x.v); + const recommended = recommendedVersions(versions); + // Where the recommended four are shown outside the menu, the menu holds only the others. + const apart = new Set(showRecommended ? [] : recommended.map(x => x.v.id)); + const rest = versions.filter(v => !apart.has(v.id)); const groups = [ - ...VERSION_GROUPS.map(g => ({ id: g.id, title: g.title, items: versions.filter(v => g.families.includes(v.sourceFamily)) })), - { id: 'other', title: 'Qwen3.6 models', items: versions.filter(v => !VERSION_GROUPS.some(g => g.families.includes(v.sourceFamily))) }, + ...VERSION_GROUPS.map(g => ({ id: g.id, title: g.title, items: rest.filter(v => g.families.includes(v.sourceFamily)) })), + { id: 'other', title: 'Qwen3.6 models', items: rest.filter(v => !VERSION_GROUPS.some(g => g.families.includes(v.sourceFamily))) }, ].filter(g => g.items.length); const row = (v: CatalogVersion, label: string, note?: string) => { const fit = fitOn(v, hardware); const on = v.id === selectedId; + const line = versionNote(v.model); return ; }; - const fit = selected ? fitOn(selected, hardware) : null; + const fit = selected && !apart.has(selected.id) ? fitOn(selected, hardware) : null; return <> {tr(open ? setOpen(false)}>
-
{tr("Recommended")}{tr("RAM + VRAM")}{tr("Download")}
- {tr(recommended.map(({ r, v }) => row(v, versionName(v, true), r.note)))} + {tr(showRecommended ? <>
{tr("Recommended")}{tr("RAM + VRAM")}{tr("Download")}
{tr(recommended.map(({ r, v }) => row(v, versionName(v, true), r.note)))} :
{tr("All other versions")}{tr("RAM + VRAM")}{tr("Download")}
)} {tr(groups.map(g => { const closed = !groupOpen(opened, g.id, g.items.some(v => v.id === selectedId)); return
diff --git a/apps/host/src/lib/app-version.ts b/apps/host/src/lib/app-version.ts new file mode 100644 index 00000000..258c97f8 --- /dev/null +++ b/apps/host/src/lib/app-version.ts @@ -0,0 +1,9 @@ +/** + * The version the person sees as "Strata". It is the DESKTOP APP's version (0.2.0-beta), not that of Strata Control, the tools the app runs + * (0.1.45, the version of the Terminal). Showing Control's number as "Strata" made a tester report "Strata 0.1.45" for the 0.2.0-beta app. + * Without a real app version (a source checkout reports 'dev') the other number is the best there is. + */ +export function appVersionLabel(app: string | null | undefined, control?: string | null): string | undefined { + const real = (v: string | null | undefined) => (typeof v === 'string' && v.trim() && v.trim().toLowerCase() !== 'dev' ? v.trim() : undefined); + return real(app) ?? real(control) ?? (typeof app === 'string' && app.trim() ? app.trim() : undefined); +} diff --git a/apps/host/src/lib/client.ts b/apps/host/src/lib/client.ts index 7dd3f1ca..1b80353f 100644 --- a/apps/host/src/lib/client.ts +++ b/apps/host/src/lib/client.ts @@ -47,7 +47,7 @@ export interface StreamEvent { export function onEvent(handler: (e: StreamEvent) => void, onStatus?: (s: 'live' | 'offline') => void) { let source: EventSource; let seenAt = Date.now(); - const names = ['engine', 'monitor', 'models', 'image-models', 'runtime', 'providers', 'serving', 'download', 'log', 'setup', 'skills', 'task', 'goal', 'timeskip', 'plan', 'queue']; + const names = ['engine', 'monitor', 'models', 'native', 'image-models', 'runtime', 'providers', 'serving', 'download', 'log', 'setup', 'skills', 'task', 'goal', 'timeskip', 'plan', 'queue']; const connect = () => { source?.close(); seenAt = Date.now(); diff --git a/apps/host/src/lib/download-eta.ts b/apps/host/src/lib/download-eta.ts index 64b5c556..5d02f905 100644 --- a/apps/host/src/lib/download-eta.ts +++ b/apps/host/src/lib/download-eta.ts @@ -53,3 +53,22 @@ export function installProgress(install: InstallParts | undefined): { done_gb: n if (d && Number.isFinite(d.done_gb) && Number.isFinite(d.total_gb)) return { done_gb: d.done_gb!, total_gb: d.total_gb!, remaining_gb: Number.isFinite(d.remaining_gb) ? d.remaining_gb! : Math.max(0, d.total_gb! - d.done_gb!), percent: d.percent ?? 0, file: d.file }; return undefined; } + +/** Which part of a multi-part install is being fetched now: the model's parts (with "part 2 of 4"), the picture reader or the engine. */ +export interface InstallStage { kind: 'model' | 'vision' | 'engine' | 'other'; index?: number; count?: number } +export function installStage(install: { parts?: { kind?: string; state?: string; files_done?: number; files_total?: number }[]; running?: boolean } | undefined): InstallStage | undefined { + const parts = install?.parts ?? []; + const now = parts.find(p => p.state === 'downloading') ?? parts.find(p => !['done', 'current', 'skipped', 'failed'].includes(p.state ?? '')); + if (!now) return undefined; + const kind = now.kind === 'model' || now.kind === 'vision' || now.kind === 'engine' ? now.kind : 'other'; + const count = Number(now.files_total) > 1 ? Number(now.files_total) : undefined; + return { kind, ...(count ? { index: Math.min(count, Number(now.files_done ?? 0) + 1), count } : {}) }; +} +/** The sentence for it, in plain words. */ +export function stageText(stage: InstallStage | undefined): string { + if (!stage) return tr('Downloading model files…'); + if (stage.kind === 'vision') return tr('Downloading the picture reader…'); + if (stage.kind === 'engine') return tr('Downloading the engine for this PC…'); + if (stage.count && stage.index) return tr('Downloading model files · part {0} of {1}', [stage.index, stage.count]); + return tr('Downloading model files…'); +} diff --git a/apps/host/src/lib/kept-state.ts b/apps/host/src/lib/kept-state.ts new file mode 100644 index 00000000..2d162640 --- /dev/null +++ b/apps/host/src/lib/kept-state.ts @@ -0,0 +1,23 @@ +import { useCallback, useEffect, useState, type Dispatch, type SetStateAction } from 'react'; + +/** + * A piece of screen state that survives leaving the screen. The Models page keeps its choices (version, context, computer use, picture + * reading ...) in useState, so going to Monitor and back reset them and a person lost track of what they were downloading. Kept values + * live in memory for the whole session (not on disk: a new start begins from the installed model again). + */ +const kept = new Map(); + +export function useKept(key: string, initial: T): [T, Dispatch>] { + const [value, setValue] = useState(() => (kept.has(key) ? kept.get(key) as T : initial)); + useEffect(() => { kept.set(key, value); }, [key, value]); + const set = useCallback>>(next => setValue(old => { + const result = typeof next === 'function' ? (next as (o: T) => T)(old) : next; + kept.set(key, result); + return result; + }), [key]); + return [value, set]; +} + +export const keptValue = (key: string): T | undefined => kept.get(key) as T | undefined; +/** Forget everything kept (tests, and a changed installation). */ +export const forgetKept = () => kept.clear(); diff --git a/apps/host/src/lib/native-catalog.ts b/apps/host/src/lib/native-catalog.ts index aee650b4..92f983f7 100644 --- a/apps/host/src/lib/native-catalog.ts +++ b/apps/host/src/lib/native-catalog.ts @@ -1,9 +1,12 @@ import type {NativeFamily,NativeSize} from './native'; import {tr} from './i18n'; +import {nvfp4Version} from './native-names'; export interface CatalogVersion extends NativeSize{sourceFamily:string;edition:string;images:boolean} export interface CatalogModel extends Omit{sizes:CatalogVersion[]} -export function nativeVersionLabel(model:string){return tr(({Q2_0:'Fastest',IQ2_XS:'Compact',IQ3_XXS:'Balanced',IQ3_S:'High quality',IQ1_M:'Coding','Gyro-S':'Smallest','Gyro-M':'Small memory'} as Record)[model]??model);} +export function nativeVersionLabel(model:string){const nv=nvfp4Version(model);if(nv)return tr(nv.name);return tr(({Q2_0:'Fastest',IQ2_XS:'Compact',IQ3_XXS:'Balanced',IQ3_S:'High quality',IQ1_M:'Coding','Gyro-S':'Smallest','Gyro-M':'Small memory'} as Record)[model]??model);} export const catalogVersionLabel=(version:CatalogVersion)=>{const label=nativeVersionLabel(version.model);return [tr(version.edition),label===version.model&&version.edition?'':label].filter(Boolean).join(' · ');}; +/** The one line that says how a version differs from its neighbours (the three NVFP4 versions); empty for the rest. */ +export const versionNote=(model:string)=>{const nv=nvfp4Version(model);return nv?tr(nv.note):'';}; /** Display groups are distinct from the engine's installation family IDs. */ export function nativeCatalogModels(families:NativeFamily[]):CatalogModel[]{ if(!families.length)return[]; diff --git a/apps/host/src/lib/native-fit.ts b/apps/host/src/lib/native-fit.ts index 32250cc7..8a72c105 100644 --- a/apps/host/src/lib/native-fit.ts +++ b/apps/host/src/lib/native-fit.ts @@ -61,3 +61,8 @@ export const RECOMMENDED: { family: string; model: string; note: string }[] = [ /** Is a group of the version list open? What the person chose wins; until they touch it, only the group holding the selected version is open * (the running version's group used to stay open whatever was clicked). */ export const groupOpen = (opened: Record, id: string, containsSelected: boolean): boolean => opened[id] ?? containsSelected; + +/** The recommended four, found in a version list (a version the catalog does not offer is skipped). */ +export function recommendedVersions(versions: V[]): { r: typeof RECOMMENDED[number]; v: V }[] { + return RECOMMENDED.map(r => ({ r, v: versions.find(v => v.sourceFamily === r.family && v.model === r.model) })).filter((x): x is { r: typeof RECOMMENDED[number]; v: V } => !!x.v); +} diff --git a/apps/host/src/lib/native-names.ts b/apps/host/src/lib/native-names.ts index de2ef322..db71ff0f 100644 --- a/apps/host/src/lib/native-names.ts +++ b/apps/host/src/lib/native-names.ts @@ -4,12 +4,27 @@ */ const FAMILIES: [string, string][] = [['swift-', 'Swift'], ['coder-', 'Coder'], ['unsloth-', 'Unsloth'], ['gyro-gyro-', 'Gyro'], ['gyro-', 'Gyro'], ['nvfp4-', 'NVFP4'], ['qwen36-', 'Qwen3.6']]; +/** + * The three NVFP4 versions, named by who made the weights (the plain model names NVFP4 / NVFP4-NVIDIA / NVFP4-QAD looked like the same thing): + * - NVFP4: Strata's own GPTQ conversion of Qwen's weights, the best quality of the three; + * - NVFP4-NVIDIA: NVIDIA's own NVFP4 checkpoint (plain rounding), converted for Strata, the same size and speed; + * - NVFP4-QAD: NVIDIA's FP4 checkpoint that was trained for FP4 (quantization-aware distillation), slightly faster on short prompts. + * `note` is the one line that says how they differ. + */ +export const NVFP4_VERSIONS: Record = { + 'NVFP4': { name: 'NVFP4 (Strata’s version)', note: 'Strata’s own conversion. The best quality of the NVFP4 versions.' }, + 'NVFP4-NVIDIA': { name: 'NVFP4 (NVIDIA’s version)', note: 'NVIDIA’s own NVFP4 checkpoint, converted for Strata. Same size and speed.' }, + 'NVFP4-QAD': { name: 'NVFP4 (NVIDIA, trained for FP4)', note: 'NVIDIA’s FP4 checkpoint, trained for FP4. Slightly faster on short prompts.' }, +}; +export const nvfp4Version = (model: string) => NVFP4_VERSIONS[String(model ?? '').toUpperCase()]; + export function nativeShortName(id: string): string { const lower = String(id ?? '').toLowerCase(); for (const [prefix, label] of FAMILIES) { if (!lower.startsWith(prefix)) continue; const rest = lower.slice(prefix.length).toUpperCase(); if (!rest) return label; + if (label === 'NVFP4') return nvfp4Version(rest)?.name ?? `${label} ${rest}`; return label === 'Gyro' ? `Gyro-${rest.replace(/^GYRO-/, '')}` : `${label} ${rest}`; } return lower.toUpperCase() || String(id); diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.ts index 509bef23..2d0f5c2d 100644 --- a/apps/host/src/lib/native.ts +++ b/apps/host/src/lib/native.ts @@ -6,17 +6,60 @@ export interface GpuChoice {options:GpuChoiceOption[];recommended:string|null;ig export interface NativeSize {/** The first engine that reads this size's files (the catalog), and whether the installed engine is older: the screen then says "needs a newer engine" and offers the update. */engine_min?:string|null;needsNewerEngine?:boolean;id:string;model:string;about:string;download_gb:number;ram_needed_gb:number;experts_gb:number;on_this_pc:string|null;installed:boolean;gpu_options?:GpuChoice|null;images?:boolean;imagesCapable?:boolean} export interface NativeFamily {family:string;title:string;about:string;experimental:boolean;images:boolean;sizes:NativeSize[]} export 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|null;progress?:Record|null} +export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string;family?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;details?:string;result:Record|null;progress?:Record|null} export interface NativeInstance {id:string;apiModelId:string;model:string;label:string;aliases?:string[];vision?:boolean;resourceProfile?:'work'|'performance'|null;context?:number;port:number;gpus:number[];status:'loading'|'ready'|'unloading'|'error';phase:string;loadedAt:string;error:string|null;metrics:Record|null} export interface NativeState { /** The picture reader (strata-vision) is installed with the engine, so models marked for pictures can read them here. */ - visionReader?: boolean;available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;/** The picture-reading files are on this computer (notes-split-agent8.md, item 8). */visionPrepared?:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;diskGb?:number;diskBytes?:number;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;componentUpdates?:boolean}} -let state:NativeState|null=null,timer:ReturnType|null=null,reading:Promise|null=null; + /** Strata Control's view of the engine for this computer (the app): usable false = none found or recognised; `notice` says why in plain words. */ + engine?:{usable:boolean;notice?:string|null;version?:string|null}; + visionReader?: boolean;available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;/** The picture-reading files are on this computer (notes-split-agent8.md, item 8). */visionPrepared?:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;diskGb?:number;diskBytes?:number;/** Files this model shares with another (the picture reader, the draft layer): counted once, in `usage`. */sharedBytes?:number;/** What Delete frees: files in Strata's own folders that no other model uses. */removableGb?:number;missing_files?:string[]}[];/** What all models take on disk, from their real files, shared files counted once. */usage?:{total_bytes:number;total_gb:number;shared_bytes:number;shared_gb:number;models:Record}|null;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;componentUpdates?:boolean}} +let state:NativeState|null=null; const listeners=new Set<()=>void>(); -let again=false; +function put(value:NativeState){if(state&&JSON.stringify(state)===JSON.stringify(value))return;state=value;listeners.forEach(fn=>fn());} +/** The host pushes its whole native state (jobs included) at every progress step: the page shows it at once, without waiting for the next poll. */ +export function applyNativeEvent(value:unknown){if(value&&typeof value==='object'&&'available' in value&&'jobs' in value)put(value as NativeState);} +const READ_LIMIT_MS=60000; +function read(force:boolean):Promise{ + const request=api.get(`/api/native${force?'?refresh=1':''}`); + // A read that never answers must not freeze the page: after the limit the next poll starts a fresh one. + let stop:ReturnType|undefined; + const limit=new Promise((_,reject)=>{stop=setTimeout(()=>reject(new Error('The host did not answer in time.')),READ_LIMIT_MS);}); + return Promise.race([request,limit]).then(put).catch(error=>{if(state){state={...state,error:error.message,instances:state.instances.map(i=>({...i,metrics:null,phase:'unavailable'}))};listeners.forEach(fn=>fn());}}).finally(()=>clearTimeout(stop)); +} +/* Two kinds of read that never wait for each other: the light poll (the host answers at once with the jobs it holds) and the forced read after an action (the host + re-reads the installation, which can take many seconds while a download is writing). A slow forced read used to hold every later poll, so a running download looked stuck. */ +let light:Promise|null=null,forced:Promise|null=null,again=false; /** A forced refresh (after an action) never joins a read that began before the action: that read cannot know about the new job. It waits for it, then reads again. */ -export function refreshNative(force=false):Promise{if(reading){if(!force)return reading;if(again)return reading;again=true;return reading.then(()=>{again=false;return refreshNative(true);});}reading=api.get(`/api/native${force?'?refresh=1':''}`).then(value=>{if(state&&JSON.stringify(state)===JSON.stringify(value))return;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;} -export function useNative(){const value=useSyncExternalStore(fn=>{listeners.add(fn);return()=>listeners.delete(fn);},()=>state);useEffect(()=>{void refreshNative();if(!timer)timer=setInterval(()=>void refreshNative(),2500);return()=>{if(!listeners.size&&timer){clearInterval(timer);timer=null;}};},[]);return value;} +export function refreshNative(force=false):Promise{ + if(!force){if(light)return light;light=read(false).finally(()=>{light=null;});return light;} + if(forced){if(again)return forced;again=true;return forced.then(()=>{again=false;return refreshNative(true);});} + forced=read(true).finally(()=>{forced=null;});return forced; +} +const POLL_MS=2500,RUNNING_POLL_MS=1000; +let users=0,timeout:ReturnType|null=null,watching=false; +const hidden=()=>typeof document!=='undefined'&&document.visibilityState==='hidden'; +/** How long until the next poll: quicker while a download or load is running, none while the window is hidden (it reads again the moment it is shown). */ +export const nativePollDelay=(value:NativeState|null,isHidden=false):number|null=>isHidden?null:value?.jobs?.some(j=>j.state==='running')?RUNNING_POLL_MS:POLL_MS; +function schedule(){ + if(timeout){clearTimeout(timeout);timeout=null;} + if(!users)return; + const wait=nativePollDelay(state,hidden()); + if(wait===null)return; + timeout=setTimeout(()=>{timeout=null;void refreshNative().finally(schedule);},wait); +} +const shown=()=>{if(!hidden()&&users){void refreshNative();schedule();}}; +export function useNative(){ + const value=useSyncExternalStore(fn=>{listeners.add(fn);return()=>listeners.delete(fn);},()=>state); + useEffect(()=>{ + users++;void refreshNative().finally(schedule); + if(!watching&&typeof document!=='undefined'){watching=true;document.addEventListener('visibilitychange',shown);window.addEventListener('focus',shown);} + return()=>{users--;if(!users){if(timeout){clearTimeout(timeout);timeout=null;}if(watching&&typeof document!=='undefined'){watching=false;document.removeEventListener('visibilitychange',shown);window.removeEventListener('focus',shown);}}}; + },[]); + // a new job (or its end) changes how fast the next poll should come + const running=value?.jobs?.some(j=>j.state==='running')??false; + useEffect(()=>{schedule();},[running]); + return value; +} export const nativeState=()=>state; /** Connection-list projection only; memory reservations are not inferred. */ export function nativeRouting(native:NativeState|null,hardware:Hardware|null):RuntimeModels|null{ diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts index 079afaaa..6e147451 100644 --- a/apps/host/src/lib/store.ts +++ b/apps/host/src/lib/store.ts @@ -13,7 +13,7 @@ import { PREVIEW_EXAMPLES, type PreviewArtifact } from './artifacts'; import { lifecyclePolicy } from './lifecycle'; import { newestServingState } from './serving-state'; import { photoData, uploadChatPhotos, photoHistorySlots, pendingChatPhotos, takeChatPhotos } from './chat-photos'; -import { nativeState } from './native'; +import { applyNativeEvent, nativeState } from './native'; import { pictureStatus } from './pictures'; import { taskHandoverMessage, taskHandoverTitle } from './task-handover'; import type { Task } from './tasks'; @@ -643,6 +643,9 @@ function applyEvent(e: StreamEvent) { case 'runtime': set({runtime:data as unknown as RuntimeModels}); break; + case 'native': + applyNativeEvent(data); + break; case 'image-models': if (Array.isArray(data.variants)) set({ imageModels: data as unknown as ImageModelLibrary }); break; diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.json index 2778b793..4e4671f2 100644 --- a/apps/host/src/locales/de.json +++ b/apps/host/src/locales/de.json @@ -3248,5 +3248,26 @@ "s3235": "Versuche es noch einmal oder mache stattdessen einen Screenshot dieses Fensters.", "s3236": "Das Ordnerfenster hat sich nicht geöffnet. Gib stattdessen den Ordnerpfad ein.", "s3237": "Die Datei wurde nicht hinzugefügt", - "s3238": "Versuche, sie noch einmal abzulegen." + "s3238": "Versuche, sie noch einmal abzulegen.", + "s3260": "NVFP4 (Strata-Version)", + "s3261": "NVFP4 (NVIDIA-Version)", + "s3262": "NVFP4 (NVIDIA, für FP4 trainiert)", + "s3263": "Strata-eigene Umwandlung. Die beste Qualität unter den NVFP4-Versionen.", + "s3264": "NVIDIAs eigener NVFP4-Checkpoint, für Strata umgewandelt. Gleiche Größe und Geschwindigkeit.", + "s3265": "NVIDIAs für FP4 trainierter Checkpoint. Bei kurzen Eingaben etwas schneller.", + "s3266": "Alle anderen Versionen", + "s3267": "Weitere Versionen", + "s3268": "Modelldateien werden heruntergeladen · Teil {0} von {1}", + "s3269": "Die Bildleser-Dateien werden heruntergeladen…", + "s3270": "Die Engine für diesen PC wird heruntergeladen…", + "s3271": "{0} wird vorbereitet", + "s3272": "Teile des Downloads", + "s3273": "Bildleser", + "s3274": "Gemeinsame Dateien", + "s3275": "Von mehr als einem Modell genutzt", + "s3276": "Diese Dateien liegen in deinem eigenen Ordner und bleiben dort. Nur der Eintrag in Strata wird entfernt.", + "s3277": "Das laufende Modell wird entladen.", + "s3278": "Lokal", + "s3279": "Strata hat für diesen Computer keine passende Engine erkannt. Das Modell wird trotzdem heruntergeladen, läuft aber möglicherweise erst, wenn die richtige Engine installiert ist (Einstellungen → Engine).", + "s3280": "Strata hat für diesen Computer keine passende Engine erkannt. Das Modell ist heruntergeladen, läuft aber erst, wenn die richtige Engine installiert ist. Öffne Einstellungen → Engine." } diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.json index d699c0dc..29408335 100644 --- a/apps/host/src/locales/en.json +++ b/apps/host/src/locales/en.json @@ -3248,5 +3248,26 @@ "s3235": "Try again, or take a screenshot of this window instead.", "s3236": "The folder window did not open. Type the folder path instead.", "s3237": "The file was not added", - "s3238": "Try dropping it again." + "s3238": "Try dropping it again.", + "s3260": "NVFP4 (Strata’s version)", + "s3261": "NVFP4 (NVIDIA’s version)", + "s3262": "NVFP4 (NVIDIA, trained for FP4)", + "s3263": "Strata’s own conversion. The best quality of the NVFP4 versions.", + "s3264": "NVIDIA’s own NVFP4 checkpoint, converted for Strata. Same size and speed.", + "s3265": "NVIDIA’s FP4 checkpoint, trained for FP4. Slightly faster on short prompts.", + "s3266": "All other versions", + "s3267": "More versions", + "s3268": "Downloading model files · part {0} of {1}", + "s3269": "Downloading the picture reader…", + "s3270": "Downloading the engine for this PC…", + "s3271": "Preparing {0}", + "s3272": "Download parts", + "s3273": "Picture reader", + "s3274": "Shared files", + "s3275": "Used by more than one model", + "s3276": "These files are in your own folder, so they stay there. Only the entry in Strata is removed.", + "s3277": "The running model will be unloaded.", + "s3278": "Local", + "s3279": "Strata didn’t recognise an engine for this computer. The model will download, but it may not run until the right engine is installed (Settings → Engine).", + "s3280": "Strata didn’t recognise an engine for this computer. The model is downloaded, but it can’t run until the right engine is installed. Open Settings → Engine." } diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.json index f14cafba..675d6b0f 100644 --- a/apps/host/src/locales/es.json +++ b/apps/host/src/locales/es.json @@ -3248,5 +3248,26 @@ "s3235": "Inténtalo de nuevo o haz una captura de esta ventana.", "s3236": "La ventana de carpetas no se abrió. Escribe la ruta de la carpeta.", "s3237": "No se añadió el archivo", - "s3238": "Inténtalo de nuevo soltándolo otra vez." + "s3238": "Inténtalo de nuevo soltándolo otra vez.", + "s3260": "NVFP4 (versión de Strata)", + "s3261": "NVFP4 (versión de NVIDIA)", + "s3262": "NVFP4 (NVIDIA, entrenada para FP4)", + "s3263": "Conversión propia de Strata. La mejor calidad de las versiones NVFP4.", + "s3264": "El punto de control NVFP4 propio de NVIDIA, convertido para Strata. Mismo tamaño y velocidad.", + "s3265": "El punto de control de NVIDIA entrenado para FP4. Algo más rápido con mensajes cortos.", + "s3266": "Todas las demás versiones", + "s3267": "Más versiones", + "s3268": "Descargando los archivos del modelo · parte {0} de {1}", + "s3269": "Descargando el lector de imágenes…", + "s3270": "Descargando el motor para este PC…", + "s3271": "Preparando {0}", + "s3272": "Partes de la descarga", + "s3273": "Lector de imágenes", + "s3274": "Archivos compartidos", + "s3275": "Los usa más de un modelo", + "s3276": "Estos archivos están en tu propia carpeta y se quedan allí. Solo se quita la entrada en Strata.", + "s3277": "El modelo en ejecución se descargará de la memoria.", + "s3278": "Local", + "s3279": "Strata no reconoció un motor para este equipo. El modelo se descargará, pero puede que no funcione hasta que se instale el motor adecuado (Ajustes → Motor).", + "s3280": "Strata no reconoció un motor para este equipo. El modelo está descargado, pero no podrá funcionar hasta que se instale el motor adecuado. Abre Ajustes → Motor." } diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.json index f5aa833f..167dd1b3 100644 --- a/apps/host/src/locales/ja.json +++ b/apps/host/src/locales/ja.json @@ -3248,5 +3248,26 @@ "s3235": "もう一度試すか、このウィンドウのスクリーンショットを撮ってください。", "s3236": "フォルダーの画面が開きませんでした。代わりにフォルダーのパスを入力してください。", "s3237": "ファイルを追加できませんでした", - "s3238": "もう一度ドロップしてみてください。" + "s3238": "もう一度ドロップしてみてください。", + "s3260": "NVFP4(Strata 版)", + "s3261": "NVFP4(NVIDIA 版)", + "s3262": "NVFP4(NVIDIA、FP4 向けに学習)", + "s3263": "Strata 独自の変換版です。NVFP4 の中で最も高品質です。", + "s3264": "NVIDIA 自身の NVFP4 チェックポイントを Strata 用に変換したものです。サイズと速度は同じです。", + "s3265": "NVIDIA が FP4 向けに学習したチェックポイントです。短いプロンプトでは少し高速です。", + "s3266": "その他のすべてのバージョン", + "s3267": "その他のバージョン", + "s3268": "モデルファイルをダウンロード中 · {1} 個中 {0} 個目", + "s3269": "画像読み取りファイルをダウンロード中…", + "s3270": "このパソコン用のエンジンをダウンロード中…", + "s3271": "{0} を準備中", + "s3272": "ダウンロードの内訳", + "s3273": "画像読み取り", + "s3274": "共有ファイル", + "s3275": "複数のモデルで使われています", + "s3276": "これらのファイルはあなた自身のフォルダーにあるため、そのまま残ります。Strata 上の項目だけが削除されます。", + "s3277": "動作中のモデルの読み込みを解除します。", + "s3278": "ローカル", + "s3279": "Strata がこのパソコン用のエンジンを認識できませんでした。モデルはダウンロードされますが、適切なエンジンをインストールするまで動作しない場合があります(設定 → エンジン)。", + "s3280": "Strata がこのパソコン用のエンジンを認識できませんでした。モデルはダウンロード済みですが、適切なエンジンをインストールするまで動作しません。設定 → エンジン を開いてください。" } diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.json index 80d7dcf1..575ff778 100644 --- a/apps/host/src/locales/ko.json +++ b/apps/host/src/locales/ko.json @@ -3248,5 +3248,26 @@ "s3235": "다시 시도하거나 이 창을 직접 캡처하세요.", "s3236": "폴더 창이 열리지 않았습니다. 대신 폴더 경로를 입력하세요.", "s3237": "파일을 추가하지 못했습니다", - "s3238": "다시 끌어다 놓아 보세요." + "s3238": "다시 끌어다 놓아 보세요.", + "s3260": "NVFP4 (Strata 버전)", + "s3261": "NVFP4 (NVIDIA 버전)", + "s3262": "NVFP4 (NVIDIA, FP4용으로 학습)", + "s3263": "Strata가 직접 변환한 버전입니다. NVFP4 버전 중 품질이 가장 좋습니다.", + "s3264": "NVIDIA가 직접 만든 NVFP4 체크포인트를 Strata용으로 변환했습니다. 크기와 속도는 같습니다.", + "s3265": "NVIDIA가 FP4용으로 학습한 체크포인트입니다. 짧은 입력에서 조금 더 빠릅니다.", + "s3266": "다른 모든 버전", + "s3267": "더 많은 버전", + "s3268": "모델 파일 다운로드 중 · {1}개 중 {0}번째", + "s3269": "이미지 읽기 파일 다운로드 중…", + "s3270": "이 PC용 엔진 다운로드 중…", + "s3271": "{0} 준비 중", + "s3272": "다운로드 구성", + "s3273": "이미지 읽기", + "s3274": "공유 파일", + "s3275": "여러 모델에서 함께 사용", + "s3276": "이 파일들은 내 폴더에 있으므로 그대로 남습니다. Strata의 항목만 삭제됩니다.", + "s3277": "실행 중인 모델을 해제합니다.", + "s3278": "로컬", + "s3279": "Strata가 이 컴퓨터용 엔진을 인식하지 못했습니다. 모델은 다운로드되지만 올바른 엔진을 설치하기 전에는 실행되지 않을 수 있습니다(설정 → 엔진).", + "s3280": "Strata가 이 컴퓨터용 엔진을 인식하지 못했습니다. 모델은 다운로드되었지만 올바른 엔진을 설치하기 전에는 실행할 수 없습니다. 설정 → 엔진을 열어 주세요." } diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.json index 23816cc6..ff1d233e 100644 --- a/apps/host/src/locales/pt.json +++ b/apps/host/src/locales/pt.json @@ -3248,5 +3248,26 @@ "s3235": "Tente de novo ou tire uma captura desta janela.", "s3236": "A janela de pastas não abriu. Digite o caminho da pasta.", "s3237": "O arquivo não foi adicionado", - "s3238": "Tente soltá-lo de novo." + "s3238": "Tente soltá-lo de novo.", + "s3260": "NVFP4 (versão da Strata)", + "s3261": "NVFP4 (versão da NVIDIA)", + "s3262": "NVFP4 (NVIDIA, treinada para FP4)", + "s3263": "Conversão própria da Strata. A melhor qualidade entre as versões NVFP4.", + "s3264": "O checkpoint NVFP4 da própria NVIDIA, convertido para a Strata. Mesmo tamanho e velocidade.", + "s3265": "O checkpoint da NVIDIA treinado para FP4. Um pouco mais rápido com mensagens curtas.", + "s3266": "Todas as outras versões", + "s3267": "Mais versões", + "s3268": "Baixando arquivos do modelo · parte {0} de {1}", + "s3269": "Baixando o leitor de imagens…", + "s3270": "Baixando o mecanismo para este PC…", + "s3271": "Preparando {0}", + "s3272": "Partes do download", + "s3273": "Leitor de imagens", + "s3274": "Arquivos compartilhados", + "s3275": "Usados por mais de um modelo", + "s3276": "Esses arquivos estão na sua própria pasta e continuam lá. Só a entrada no Strata é removida.", + "s3277": "O modelo em execução será descarregado.", + "s3278": "Local", + "s3279": "A Strata não reconheceu um mecanismo para este computador. O modelo será baixado, mas pode não funcionar até que o mecanismo certo seja instalado (Configurações → Mecanismo).", + "s3280": "A Strata não reconheceu um mecanismo para este computador. O modelo foi baixado, mas não vai funcionar até que o mecanismo certo seja instalado. Abra Configurações → Mecanismo." } diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.json index a4188cee..ef580114 100644 --- a/apps/host/src/locales/ru.json +++ b/apps/host/src/locales/ru.json @@ -3248,5 +3248,26 @@ "s3235": "Попробуйте ещё раз или сделайте снимок этого окна.", "s3236": "Окно выбора папки не открылось. Введите путь к папке вручную.", "s3237": "Файл не добавлен", - "s3238": "Попробуйте перетащить его ещё раз." + "s3238": "Попробуйте перетащить его ещё раз.", + "s3260": "NVFP4 (версия Strata)", + "s3261": "NVFP4 (версия NVIDIA)", + "s3262": "NVFP4 (NVIDIA, обучена для FP4)", + "s3263": "Собственная конвертация Strata. Лучшее качество среди версий NVFP4.", + "s3264": "Собственный NVFP4-чекпойнт NVIDIA, конвертированный для Strata. Тот же размер и скорость.", + "s3265": "Чекпойнт NVIDIA, обученный для FP4. Немного быстрее на коротких запросах.", + "s3266": "Все остальные версии", + "s3267": "Другие версии", + "s3268": "Скачивание файлов модели · часть {0} из {1}", + "s3269": "Скачивание модуля чтения изображений…", + "s3270": "Скачивание движка для этого компьютера…", + "s3271": "Подготовка: {0}", + "s3272": "Части загрузки", + "s3273": "Чтение изображений", + "s3274": "Общие файлы", + "s3275": "Используются несколькими моделями", + "s3276": "Эти файлы лежат в вашей папке и останутся там. Из Strata удаляется только запись.", + "s3277": "Работающая модель будет выгружена.", + "s3278": "Локальная", + "s3279": "Strata не распознала движок для этого компьютера. Модель всё равно скачается, но может не запуститься, пока не будет установлен нужный движок (Настройки → Движок).", + "s3280": "Strata не распознала движок для этого компьютера. Модель скачана, но не запустится, пока не будет установлен нужный движок. Откройте Настройки → Движок." } diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.json index 40736978..a2ad8321 100644 --- a/apps/host/src/locales/zh.json +++ b/apps/host/src/locales/zh.json @@ -3248,5 +3248,26 @@ "s3235": "请重试,或改为对此窗口截屏。", "s3236": "文件夹窗口没有打开。请改为输入文件夹路径。", "s3237": "文件未能添加", - "s3238": "请再拖放一次。" + "s3238": "请再拖放一次。", + "s3260": "NVFP4(Strata 版本)", + "s3261": "NVFP4(NVIDIA 版本)", + "s3262": "NVFP4(NVIDIA,为 FP4 训练)", + "s3263": "Strata 自己的转换版本,是 NVFP4 各版本中质量最好的。", + "s3264": "NVIDIA 自己的 NVFP4 检查点,已为 Strata 转换。大小和速度相同。", + "s3265": "NVIDIA 为 FP4 训练的检查点。短提示下速度略快。", + "s3266": "其他所有版本", + "s3267": "更多版本", + "s3268": "正在下载模型文件 · 第 {0} 部分,共 {1} 部分", + "s3269": "正在下载图片读取组件…", + "s3270": "正在下载适用于此电脑的引擎…", + "s3271": "正在准备 {0}", + "s3272": "下载分段", + "s3273": "图片读取组件", + "s3274": "共享文件", + "s3275": "被多个模型共用", + "s3276": "这些文件在你自己的文件夹中,会保留在原处,只会从 Strata 中移除该条目。", + "s3277": "将卸载运行中的模型。", + "s3278": "本地", + "s3279": "Strata 没有识别出适用于这台电脑的引擎。模型仍会下载,但在安装正确的引擎之前可能无法运行(设置 → 引擎)。", + "s3280": "Strata 没有识别出适用于这台电脑的引擎。模型已下载,但在安装正确的引擎之前无法运行。请打开 设置 → 引擎。" } diff --git a/apps/host/src/screens/Settings.tsx b/apps/host/src/screens/Settings.tsx index d608f2d9..a14854f2 100644 --- a/apps/host/src/screens/Settings.tsx +++ b/apps/host/src/screens/Settings.tsx @@ -7,7 +7,7 @@ import { SettingsModels } from '../components/SettingsModels'; import { SettingsTools } from '../components/SettingsTools'; import { SettingsStorage } from '../components/SettingsStorage'; import { PrivacyNotes } from '../components/PrivacyNotes'; -import { SettingsUpdates } from '../components/SettingsUpdates'; +import { AboutVersions, SettingsUpdates } from '../components/SettingsUpdates'; import { NativeOperations } from '../components/NativeOperations'; import { FontChoice } from '../components/FontChoice'; import { LANGUAGES } from '../lib/i18n'; @@ -58,7 +58,7 @@ export function SettingsScreen() { {tr(panel.sections.map(section =>

{tr(section)}

- {tr(section === 'About' ?
: null)} + {tr(section === 'About' ?
: null)} {tr(section === 'Storage' ? : null)} {tr(section === 'Privacy' ? : null)} {tr(section === 'Update' ? : null)} diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index a8421950..f1db727c 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -5653,7 +5653,8 @@ textarea.config-editor.st-input { .key-input .st-input { min-width: 0; flex: 1; } .dialog-feature-icon { display: grid; place-items: center; width: 52px; height: 52px; border: 1px solid var(--st-line); border-radius: 16px; background: var(--st-surface-2); color: var(--st-accent); } .key-url { overflow-wrap: anywhere; padding: 14px; background: var(--st-surface-2); border-radius: 10px; } -.settings-about-brand { display: flex; padding: 22px 20px 0; } +.settings-about-brand { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 18px; padding: 22px 20px 0; } +.settings-about-version { margin: 0; font-size: var(--st-fs-base); } .prompt-progress { display: flex; align-items: center; gap: 16px; } .prompt-progress > .st-bar { flex: 1; } .hardware-section { display: flex; flex-direction: column; gap: 20px; } @@ -7021,14 +7022,17 @@ textarea { .version-menu { display: flex; flex-direction: column; max-height: min(70vh, 640px); overflow: auto; padding: 4px 0; min-width: min(620px, calc(100vw - 24px)); } .version-head { display: grid; grid-template-columns: 1fr 84px 84px; gap: 10px; padding: 8px 18px 4px; font-size: var(--st-fs-xs); font-weight: 700; letter-spacing: .06em; text-transform: uppercase; color: var(--st-ink-muted); } .version-head span:nth-child(n+2) { text-align: right; } -.version-row { display: grid; grid-template-columns: 1fr 84px 84px; gap: 10px; align-items: baseline; width: calc(100% - 12px); margin: 0 6px; padding: 8px 12px; border: 0; border-radius: var(--st-r-sm); background: transparent; color: var(--st-ink); font: inherit; text-align: left; cursor: pointer; } +.version-row { display: grid; grid-template-columns: 1fr 84px 84px; gap: 10px; align-items: baseline; width: calc(100% - 12px); margin: 0 6px; padding: 6px 12px; border: 0; border-radius: var(--st-r-sm); background: transparent; color: var(--st-ink); font: inherit; font-size: var(--st-fs-md); text-align: left; cursor: pointer; } .version-row:hover, .version-row:focus-visible { background: var(--st-surface-2); } .version-row.is-on { background: var(--st-surface-2); } .version-row__name { min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .version-row__name svg { color: var(--st-accent-text); margin-right: 6px; vertical-align: -2px; } +.version-row__title { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.version-row__note { display: block; margin-top: 1px; font-size: var(--st-fs-xs); white-space: normal; line-height: 1.35; } +.version-row__have, .version-trigger .version-row__have { margin-left: 8px; padding: 1px 8px; border-radius: var(--st-r-pill); background: var(--st-accent-tint); color: var(--st-accent-text); font-size: var(--st-fs-xs); font-weight: 700; white-space: nowrap; } .version-row__ssd { margin-left: 10px; font-size: var(--st-fs-xs); color: var(--st-warn-text); } .version-row__ram { text-align: right; font-weight: 700; font-variant-numeric: tabular-nums; } -.version-row__dl { text-align: right; font-size: var(--st-fs-sm); color: var(--st-ink-muted); font-variant-numeric: tabular-nums; } +.version-row__dl { text-align: right; font-size: var(--st-fs-xs); color: var(--st-ink-muted); font-variant-numeric: tabular-nums; } .version-group { border-top: 1px solid var(--st-line-soft); margin-top: 4px; } .version-group[data-open] { background: var(--st-surface-2); padding-bottom: 6px; } .version-group[data-open] .version-row:hover { background: var(--st-surface); } @@ -7497,3 +7501,5 @@ textarea { .st-btn.btn-neutral { background: var(--st-surface); color: var(--st-ink); border: 1px solid var(--st-line); box-shadow: none; } .st-btn.btn-neutral:hover:not(:disabled) { background: var(--st-surface-2); } .native-vision-missing { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-top: 8px; font-size: var(--st-fs-sm); color: var(--st-ink-soft); } +.storage-model--shared { background: var(--st-surface-2); } +.storage-model--shared small { font-size: var(--st-fs-xs); } diff --git a/apps/host/src/styles/onboarding.css b/apps/host/src/styles/onboarding.css index 84e885c6..4a189170 100644 --- a/apps/host/src/styles/onboarding.css +++ b/apps/host/src/styles/onboarding.css @@ -243,3 +243,15 @@ @media(max-width:700px){.onboard-sharing{grid-template-columns:1fr;gap:20px;padding:22px}.onboard-sharing-computer{width:min(300px,100%);justify-self:center}.onboard-sharing-caption{font-size:14px}.onboard-sharing-numbers{justify-content:space-between;gap:20px}.onboard-sharing-headroom{padding-left:20px}.guided-onboarding .onboard-resource-options>button{padding:16px;grid-template-columns:1fr;gap:7px}.guided-onboarding .onboard-resource-options small{grid-column:1;grid-row:4;justify-self:start}.guided-onboarding .onboard-resource-options strong{font-size:13px}.guided-onboarding .onboard-resource-options p{font-size:11px}.guided-onboarding .onboard-load-vision,.guided-onboarding .onboard-calibration{padding:14px}.guided-onboarding .onboard-load-vision strong,.guided-onboarding .onboard-calibration strong{font-size:12px}} .onboard-progress-actions{display:flex;align-items:center;gap:10px} .onboard-tune-stage:has(.error-notice) .onboard-sharing{display:none} + +/* ---- QA 2026-10-18: more versions, download parts ---- */ +.onboard-more-versions { margin-top: 12px; } +.onboard-more-versions .version-trigger { background: var(--st-surface); } +.native-parts { list-style: none; margin: 10px 0 0; padding: 0; display: flex; flex-direction: column; gap: 4px; font-size: var(--st-fs-sm); } +.native-parts li { display: flex; justify-content: space-between; gap: 12px; padding: 4px 0; border-top: 1px solid var(--st-line-soft); } +.native-parts li[data-state="done"] > span::before { content: "\2713\00a0"; color: var(--st-accent-text); } +.native-parts li[data-state="downloading"] > span { font-weight: 700; } +.engine-warning { display: flex; gap: 10px; align-items: flex-start; margin: 12px 0; padding: 12px 14px; border-radius: var(--st-r-md); background: var(--st-warn-tint); color: var(--st-warn-text); font-size: var(--st-fs-sm); } +.engine-warning p { margin: 0; } +.engine-warning svg { flex: none; margin-top: 1px; } +.engine-warning small { display: block; margin-top: 4px; } diff --git a/apps/host/tests/native-onboarding.test.mjs b/apps/host/tests/native-onboarding.test.mjs index 1357756a..5db0a676 100644 --- a/apps/host/tests/native-onboarding.test.mjs +++ b/apps/host/tests/native-onboarding.test.mjs @@ -145,6 +145,10 @@ test('runtime vision checks prepared files, validates mode, and leaves the sourc assert.equal(runtimeVision(config,'cpu').gpu,false); assert.equal(runtimeVision(config,'yes').mmproj,config.vision.mmproj); assert.deepEqual(config,before); + const amd={vision:{exe:'/e/strata-vision-hip',cpu_exe:'/e/strata-vision',mmproj:'/m.gguf',gpu:true}}; + assert.deepEqual(runtimeVision(amd,'cpu'),{exe:'/e/strata-vision',mmproj:'/m.gguf',gpu:false}); + assert.equal(runtimeVision(amd,'gpu').exe,'/e/strata-vision-hip');assert.equal(runtimeVision(amd,'gpu').cpu_exe,'/e/strata-vision'); + assert.equal(runtimeVision(amd,'yes').gpu,true); assert.throws(()=>runtimeVision({},'yes'),/Prepare/); assert.throws(()=>runtimeVision(config,'invalid'),/picture reading/); }); diff --git a/apps/host/tests/qa1-downloads.test.mjs b/apps/host/tests/qa1-downloads.test.mjs new file mode 100644 index 00000000..4c0b7f9f --- /dev/null +++ b/apps/host/tests/qa1-downloads.test.mjs @@ -0,0 +1,165 @@ +import test from 'node:test'; +import { readFileSync as readSource } from 'node:fs'; +import assert from 'node:assert/strict'; +import { build } from 'esbuild'; +import { createEngineStep } from '../server/engine-step.mjs'; + +const compiled = await build({ + stdin: { + contents: "export * from './src/lib/native'; export * from './src/lib/download-eta'; export * from './src/lib/native-fit'; export * from './src/lib/native-names'; export * from './src/lib/native-catalog'; export * from './src/lib/i18n';", + resolveDir: process.cwd(), + }, + bundle: true, write: false, platform: 'node', format: 'esm', +}); +const lib = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`); + +const job = (progress, state = 'running') => ({ id: 'j1', kind: 'install', state, startedAt: '', summary: '', error: null, result: { install: progress } }); +const stateWith = (jobs, extra = {}) => ({ available: true, repo: '', summary: '', error: null, catalog: null, installed: null, hardware: null, instances: [], jobs, ...extra }); +const answer = body => ({ ok: true, status: 200, statusText: 'OK', text: async () => JSON.stringify(body) }); + +test('a slow forced read never holds the light poll: a running download keeps moving', async () => { + const seen = []; + globalThis.fetch = async url => { + seen.push(url); + if (String(url).includes('refresh=1')) { await new Promise(r => setTimeout(r, 400)); return answer(stateWith([job({ download: { done_gb: 1, total_gb: 10 } })])); } + return answer(stateWith([job({ download: { done_gb: 5, total_gb: 10 } })])); + }; + const slow = lib.refreshNative(true); + const t0 = Date.now(); + await lib.refreshNative(); + assert.ok(Date.now() - t0 < 200, 'the light read answered while the forced one was still running'); + assert.equal(lib.nativeState().jobs[0].result.install.download.done_gb, 5); + await slow; + assert.ok(seen.some(u => String(u).includes('refresh=1')) && seen.some(u => !String(u).includes('refresh=1'))); +}); + +test('a second forced read waits for the first and then reads again (it never joins a read that began before the action)', async () => { + let calls = 0; + globalThis.fetch = async () => { calls += 1; await new Promise(r => setTimeout(r, 50)); return answer(stateWith([], { summary: `read ${calls}` })); }; + const a = lib.refreshNative(true), b = lib.refreshNative(true), c = lib.refreshNative(true); + await Promise.all([a, b, c]); + assert.equal(calls, 2, 'one read for the first, one more for everything asked meanwhile'); + assert.equal(lib.nativeState().summary, 'read 2'); +}); + +test('the host pushes its native state and the page takes it at once', () => { + lib.applyNativeEvent(stateWith([job({ download: { done_gb: 7, total_gb: 10 } })], { summary: 'pushed' })); + assert.equal(lib.nativeState().summary, 'pushed'); + lib.applyNativeEvent({ nonsense: true }); + lib.applyNativeEvent(null); + assert.equal(lib.nativeState().summary, 'pushed', 'a frame that is not a native state changes nothing'); +}); + +test('the poll is quick while a job runs, normal otherwise, and stops while the window is hidden', () => { + assert.equal(lib.nativePollDelay(null), 2500); + assert.equal(lib.nativePollDelay(stateWith([job({})], {})), 1000); + assert.equal(lib.nativePollDelay(stateWith([job({}, 'done')])), 2500); + assert.equal(lib.nativePollDelay(stateWith([job({})]), true), null); +}); + +const parts = (model, vision, engine = { kind: 'engine', name: 'Engine', state: 'done', done_gb: 0.4, total_gb: 0.4 }) => [model, vision, engine]; +const modelPart = (state, done, total, files_done, files_total) => ({ kind: 'model', name: 'Model files', state, done_gb: done, total_gb: total, files_done, files_total }); +const visionPart = (state, done = 0) => ({ kind: 'vision', name: 'Picture reader', state, done_gb: done, total_gb: 0.9 }); + +test('a model in parts says which part is under way, then the picture reader', () => { + lib.setTranslationLanguage('en'); + const second = { parts: parts(modelPart('downloading', 20, 66, 1, 2), visionPart('waiting')) }; + assert.deepEqual(lib.installStage(second), { kind: 'model', index: 2, count: 2 }); + assert.equal(lib.stageText(lib.installStage(second)), 'Downloading model files · part 2 of 2'); + const reader = { parts: parts(modelPart('done', 66, 66, 2, 2), visionPart('downloading', 0.3)) }; + assert.deepEqual(lib.installStage(reader), { kind: 'vision' }); + assert.equal(lib.stageText(lib.installStage(reader)), 'Downloading the picture reader…'); + assert.equal(lib.stageText(lib.installStage(undefined)), 'Downloading model files…'); + const single = { parts: [modelPart('downloading', 1, 20, 0, 1), visionPart('waiting')] }; + assert.equal(lib.stageText(lib.installStage(single)), 'Downloading model files…', 'one file is not "part 1 of 1"'); +}); + +test('the figure counts every part: the model whole but the picture reader not yet is not finished', () => { + const p = lib.installProgress({ parts: parts(modelPart('done', 10, 10, 2, 2), visionPart('downloading', 0.3)) }); + assert.equal(p.percent, 94, 'the bar is not at its end while the picture reader is still coming'); + assert.ok(Math.abs(p.total_gb - 11.3) < 0.01, `total ${p.total_gb}`); + assert.ok(p.remaining_gb > 0.5); + const half = lib.installProgress({ parts: parts(modelPart('downloading', 33, 66, 1, 2), visionPart('waiting')) }); + assert.equal(half.percent, Math.floor(100 * (33 + 0.4) / (66 + 0.9 + 0.4))); +}); + +test('the engine step keeps the install job\'s own parts (model parts, picture reader) and adds the engine', () => { + const step = createEngineStep({ control: null }); + const install = { running: true, step: '5/7: downloading', download: { file: 'picture reader', done_gb: 66.3, total_gb: 66.9, remaining_gb: 0.6, percent: 99 }, + parts: [modelPart('done', 66, 66, 2, 2), visionPart('downloading', 0.3)] }; + const merged = step.merge(install); + assert.deepEqual(merged.parts.map(p => p.kind), ['model', 'vision', 'engine']); + assert.equal(merged.parts[0].files_total, 2); + const bare = step.merge({ running: true, download: { file: 'model files', done_gb: 1, remaining_gb: 9 } }); + assert.deepEqual(bare.parts.map(p => p.kind), ['model', 'engine'], 'an install without part information keeps the old two-part list'); +}); + +test('the recommended four come first; the others are what the "More versions" list holds', () => { + const v = (sourceFamily, model) => ({ sourceFamily, model, id: `${sourceFamily}-${model}` }); + const all = [v('qwen', 'Q2_0'), v('gyro', 'Gyro-S'), v('swift', 'IQ2_XS'), v('qwen', 'IQ3_S'), v('unsloth', 'UD-Q4_K_XL'), v('nvfp4', 'NVFP4')]; + const rec = lib.recommendedVersions(all).map(x => x.v.model); + assert.deepEqual(rec, ['Gyro-S', 'IQ2_XS', 'IQ3_S', 'UD-Q4_K_XL']); + assert.deepEqual(all.filter(x => !rec.includes(x.model)).map(x => x.model), ['Q2_0', 'NVFP4']); + assert.deepEqual(lib.recommendedVersions([v('qwen36', 'UD-Q4_K_XL')]), [], 'Qwen3.6 has no recommended set: its versions are all shown'); +}); + +test('the three NVFP4 versions have clear names and one line that tells them apart', () => { + lib.setTranslationLanguage('en'); + const names = ['NVFP4', 'NVFP4-NVIDIA', 'NVFP4-QAD'].map(m => lib.nativeVersionLabel(m)); + assert.deepEqual(names, ['NVFP4 (Strata’s version)', 'NVFP4 (NVIDIA’s version)', 'NVFP4 (NVIDIA, trained for FP4)']); + assert.equal(new Set(names).size, 3); + const lines = ['NVFP4', 'NVFP4-NVIDIA', 'NVFP4-QAD'].map(m => lib.versionNote(m)); + assert.match(lines[0], /best quality/i); + assert.match(lines[1], /NVIDIA’s own NVFP4 checkpoint/); + assert.match(lines[2], /trained for FP4/); + assert.match(lines[2], /faster on short prompts/); + assert.equal(lib.versionNote('IQ3_S'), ''); + assert.equal(lib.nativeShortName('nvfp4-nvfp4-nvidia'), 'NVFP4 (NVIDIA’s version)'); + for (const language of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']) { + lib.setTranslationLanguage(language); + const local = ['NVFP4', 'NVFP4-NVIDIA', 'NVFP4-QAD'].map(m => lib.nativeVersionLabel(m)); + assert.equal(new Set(local).size, 3, `${language}: three different names`); + assert.ok(local.every((n, i) => n !== names[i]), `${language}: translated`); + assert.ok(['NVFP4', 'NVFP4-NVIDIA', 'NVFP4-QAD'].every((m, i) => lib.versionNote(m) !== lines[i]), `${language}: the line is translated`); + } + lib.setTranslationLanguage('en'); +}); + +test('4d: picture reading is on unless the person turned it off (no saved choice is not "off")', async () => { + const { nativeFixture } = await import('./helpers/native-fixture.mjs'); + const { readFileSync, writeFileSync } = await import('node:fs'); + const { join } = await import('node:path'); + const f = nativeFixture(); + try { + await f.control.refresh(true); + const first = () => f.control.state().installed.models.find(m => m.model === 'iq2_xs'); + assert.equal(first().visionEnabled, undefined, 'a model never loaded and never turned off'); + const path = join(f.repo, 'strata-iq2_xs.json'); + const cfg = JSON.parse(readFileSync(path, 'utf8')); + writeFileSync(path, JSON.stringify({ ...cfg, ui_vision_enabled: false })); + await f.control.refresh(true); + assert.equal(first().visionEnabled, false, 'turned off by the person: stays off'); + writeFileSync(path, JSON.stringify({ ...cfg, ui_vision_enabled: true, ui_vision_device: 'cpu' })); + await f.control.refresh(true); + assert.equal(first().visionEnabled, true); + } finally { await f.cleanup(); } + const screen = readSource(new URL('../src/components/NativeModels.tsx', import.meta.url), 'utf8'); + assert.match(screen, /setVision\(installed\.visionEnabled === false \? 'no'/); + assert.match(screen, /else\s+setVision\('yes'\)/, 'a version that is not downloaded starts with Read pictures on'); +}); + +test('no recognised engine: the app still downloads, warns in the card, and loading says it with the next step', async () => { + const { ENGINE_NOT_RECOGNISED } = await import('../server/native-control.mjs'); + assert.match(ENGINE_NOT_RECOGNISED, /Settings → Engine/); + assert.match(ENGINE_NOT_RECOGNISED, /didn’t recognise an engine/); + const source = readSource(new URL('../server/native-control.mjs', import.meta.url), 'utf8'); + assert.equal((source.match(/ENGINE_NOT_RECOGNISED\+/g) ?? []).length, 2, 'both load paths use it'); + const models = readSource(new URL('../src/components/NativeModels.tsx', import.meta.url), 'utf8'); + const guided = readSource(new URL('../src/components/GuidedSetup.tsx', import.meta.url), 'utf8'); + assert.match(models, //); + assert.match(guided, //); + const warn = readSource(new URL('../src/components/EngineWarning.tsx', import.meta.url), 'utf8'); + assert.match(warn, /The model will download, but it may not run until the right engine is installed \(Settings → Engine\)\./); + // the install is not refused for a missing engine (only the engine-minimum refusal for a version that is too old stays) + assert.doesNotMatch(source.slice(source.indexOf('async function install(job,args)'), source.indexOf('function terminate')), /engine\.usable/); +}); diff --git a/apps/host/tests/qa1-storage.test.mjs b/apps/host/tests/qa1-storage.test.mjs new file mode 100644 index 00000000..62884816 --- /dev/null +++ b/apps/host/tests/qa1-storage.test.mjs @@ -0,0 +1,61 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { nativeUnloadPlan } from '../server/storage-check.mjs'; + +const loaded = [{ id: 'a', model: 'gyro-gyro-s' }, { id: 'b', model: 'iq3_s' }]; + +test('O01: checking the same folder unloads nothing', () => { + assert.deepEqual(nativeUnloadPlan({ changed: false, unload: true, instances: loaded }), { refuse: null, ids: [] }); + assert.deepEqual(nativeUnloadPlan({ changed: false, unload: undefined, instances: loaded }), { refuse: null, ids: [] }); +}); + +test('O01: changing the folder unloads the loaded models only when the person agreed', () => { + assert.match(nativeUnloadPlan({ changed: true, unload: false, instances: loaded }).refuse, /Unload native models/); + assert.deepEqual(nativeUnloadPlan({ changed: true, unload: true, instances: loaded }), { refuse: null, ids: ['a', 'b'] }); + assert.deepEqual(nativeUnloadPlan({ changed: true, unload: false, instances: [] }), { refuse: null, ids: [] }); + assert.deepEqual(nativeUnloadPlan({ changed: true, unload: true, instances: undefined }), { refuse: null, ids: [] }); +}); + +test('O01: the route uses that plan and the screen asks for an unload only when the folder differs', async () => { + const route = await readFile(new URL('../server/index.mjs', import.meta.url), 'utf8'); + assert.match(route, /nativeUnloadPlan\(\{changed,unload:body\.unload,instances:native\.state\(\)\.instances\}\)/); + assert.doesNotMatch(route, /for\(const instance of native\.state\(\)\.instances\)await native\.unload\(instance\.id\);\}\s*\n\s*storageChanging = true/); + const screen = await readFile(new URL('../src/components/SettingsStorage.tsx', import.meta.url), 'utf8'); + assert.match(screen, /changeModelDirectory\(path, path\.trim\(\) !== currentDirectory\)/); +}); + +test('F02: Settings -> Storage has ONE Downloaded models list and one total, with the shared files as a line of their own', async () => { + const screen = await readFile(new URL('../src/components/SettingsStorage.tsx', import.meta.url), 'utf8'); + assert.equal((screen.match(/ { + const { appVersionToShow } = await import('../server/app-version.mjs'); + assert.equal(appVersionToShow('0.2.0-beta', '0.1.45'), '0.2.0-beta'); + assert.equal(appVersionToShow('dev', '0.1.45'), '0.1.45', 'a source checkout has no app version: the next best number'); + assert.equal(appVersionToShow(undefined, null), null); + assert.equal(appVersionToShow('dev', null), 'dev'); + const { build } = await import('esbuild'); + const out = await build({ stdin: { contents: "export * from './src/lib/app-version';", resolveDir: process.cwd() }, bundle: true, write: false, platform: 'node', format: 'esm' }); + const { appVersionLabel } = await import(`data:text/javascript;base64,${Buffer.from(out.outputFiles[0].text).toString('base64')}`); + assert.equal(appVersionLabel('0.2.0-beta', '0.1.45'), '0.2.0-beta'); + assert.equal(appVersionLabel('dev', '0.1.45'), '0.1.45'); + assert.equal(appVersionLabel(undefined, undefined), undefined); + const route = await readFile(new URL('../server/index.mjs', import.meta.url), 'utf8'); + assert.match(route, /appVersion:appVersionToShow\(setupState\(\)\.app\.version,native\.state\(\)\.version\)/); + const updates = await readFile(new URL('../src/components/SettingsUpdates.tsx', import.meta.url), 'utf8'); + assert.doesNotMatch(updates, /native\?\.version \?\? appVersion/, 'the Strata row no longer prefers Control\'s version'); + assert.match(updates, /AboutVersions/); +}); + +test('Cargo.toml, tauri.conf.json and the desktop package agree on the app version the host reports', async () => { + const root = new URL('../../desktop/', import.meta.url); + const cargo = /^version\s*=\s*"([^"]+)"/m.exec(await readFile(new URL('src-tauri/Cargo.toml', root), 'utf8'))[1]; + const pkg = JSON.parse(await readFile(new URL('package.json', root), 'utf8')).version; + assert.equal(cargo, pkg); + assert.equal(cargo, '0.2.0-beta'); +}); diff --git a/apps/host/tests/split-qa2c-export.test.mjs b/apps/host/tests/split-qa2c-export.test.mjs new file mode 100644 index 00000000..4896141e --- /dev/null +++ b/apps/host/tests/split-qa2c-export.test.mjs @@ -0,0 +1,29 @@ +// The saved Monitor picture when a model is loaded (the normal case) starts with the Strata logo alone and the models/time line. +// (QA follow-up: it was checked with a loaded model through the real page; the picture is the one of the Monitor screen, which shows the +// loaded models. NativeMonitor.tsx is not used by any screen, so it needs no header.) +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { readdir } from 'node:fs/promises'; + +const read = path => readFile(new URL(path, import.meta.url), 'utf8').then(s => s.replace(/\r\n/g, '\n')); + +test('with a model loaded the picture is headed by the logo and the line " ·