From bc9058a8d47732647a16668980acbc8705ddfe64 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 17:14:01 +0200 Subject: [PATCH 01/16] host UI: the first screen no longer crashes on an empty or failed model catalog GuidedSetup read catalog.recommendation.family without checking that a catalog has a recommendation; the packaged host's catalog had none and the app showed 'couldn't show this screen'. GuidedSetup and NativeModels now tolerate no catalog, no recommendation, no families and families without sizes. A test renders both components with each of those shapes. --- apps/host/src/components/GuidedSetup.tsx | 6 +- apps/host/src/components/NativeModels.tsx | 4 +- .../tests/guided-setup-empty-catalog.test.mjs | 84 +++++++++++++++++++ 3 files changed, 89 insertions(+), 5 deletions(-) create mode 100644 apps/host/tests/guided-setup-empty-catalog.test.mjs diff --git a/apps/host/src/components/GuidedSetup.tsx b/apps/host/src/components/GuidedSetup.tsx index bd0777b8..130566e0 100644 --- a/apps/host/src/components/GuidedSetup.tsx +++ b/apps/host/src/components/GuidedSetup.tsx @@ -22,10 +22,10 @@ export function GuidedSetup() { const families = nativeCatalogModels(native?.catalog?.families ?? []); const saved = !setup?.complete && !setup?.choices?.onboarding?.manual ? setup?.choices?.onboarding : undefined; const [step, setStep] = useState(saved?.manual || setup?.complete ? 1 : saved?.step ?? 1); - const [family, setFamily] = useState(saved?.family ?? native?.catalog?.recommendation.family ?? native?.catalog?.families[0]?.family ?? ''); + const [family, setFamily] = useState(saved?.family ?? native?.catalog?.recommendation?.family ?? native?.catalog?.families?.[0]?.family ?? ''); const initialFamily = families.find(f => f.family === family || f.sizes.some(size => size.sourceFamily === family)); - const [size, setSize] = useState(saved?.size ?? initialFamily?.sizes.find(s => s.model === native?.catalog?.recommendation.model)?.id ?? initialFamily?.sizes[0]?.id ?? ''); - const [context, setContext] = useState(saved?.context ?? native?.catalog?.recommendation.context ?? 32768); + const [size, setSize] = useState(saved?.size ?? initialFamily?.sizes.find(s => s.model === native?.catalog?.recommendation?.model)?.id ?? initialFamily?.sizes[0]?.id ?? ''); + const [context, setContext] = useState(saved?.context ?? native?.catalog?.recommendation?.context ?? 32768); const [vision, setVision] = useState(saved?.vision ?? false), [directory, setDirectory] = useState(saved?.directory ?? ''); const [profile, setProfile] = useState<'work' | 'performance'>(saved?.profile ?? 'work'); const [installJobId, setInstallJobId] = useState(saved?.installJobId ?? ''), [tuneJobId, setTuneJobId] = useState(saved?.tuneJobId ?? ''); diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index fdc6a953..6b0d60cb 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -36,10 +36,10 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine 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(',') } : {}), loadAfter: true, multiple: expert && multiple }), [selectedSize?.sourceFamily, selectedSize?.model, context, vision, kv, lowRam, resourceProfile, gpus.join(','), expert, multiple]); const downloadValues = { ...values, vision: selectedSize?.images ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no' }; useEffect(() => { if (!native?.catalog || family) - return; const current = native.instances.find(i => i.id === native.defaultId); const rec = native.catalog.recommendation; const loadedFamily = families.find(f => f.sizes.some(s => s.id === current?.model)); const f = loadedFamily ?? families.find(f => f.family === rec.family || f.sizes.some(s => s.sourceFamily === rec.family)) ?? families[0]; if (f) { + return; const current = native.instances.find(i => i.id === native.defaultId); const rec = native.catalog.recommendation ?? { family: null, model: null }; const loadedFamily = families.find(f => f.sizes.some(s => s.id === current?.model)); const f = loadedFamily ?? families.find(f => f.family === rec.family || f.sizes.some(s => s.sourceFamily === rec.family)) ?? families[0]; if (f) { setFamily(f.family); setSize(f.sizes.find(s => s.id === current?.model || s.model === rec.model)?.id ?? f.sizes[0]?.id ?? ''); - setContext(rec.context ?? 32768); + setContext(('context' in rec ? rec.context : undefined) ?? 32768); } }, [native?.catalog]); useEffect(() => { if (presetPending.current) { presetPending.current = false; diff --git a/apps/host/tests/guided-setup-empty-catalog.test.mjs b/apps/host/tests/guided-setup-empty-catalog.test.mjs new file mode 100644 index 00000000..17c87ca6 --- /dev/null +++ b/apps/host/tests/guided-setup-empty-catalog.test.mjs @@ -0,0 +1,84 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {mkdtempSync,readFileSync,rmSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join,resolve} from 'node:path'; +import {createRequire} from 'node:module'; +import {build} from 'esbuild'; + +/* The installed app crashed on its first screen ("Cannot read properties of undefined (reading 'family')") when the + catalog it was given had no `recommendation` and no families. Render the real GuidedSetup and NativeModels components + (react-dom/server) with the state libraries replaced by fixed values, for every shape of an empty or failed catalog. */ +const root=resolve(import.meta.dirname,'..'); +/** Every export of the real module becomes a harmless no-op, except the few that carry the fixed state. */ +function stubFor(file,overrides){ + const source=readFileSync(resolve(root,'src/lib',file),'utf8'); + const names=new Set([...source.matchAll(/export\s+(?:async\s+)?(?:function\*?|const|let|var|class)\s+([A-Za-z_$][\w$]*)/g)].map(m=>m[1])); + for(const m of source.matchAll(/export\s*\{([^}]*)\}/g))for(const part of m[1].split(','))names.add(part.split(/\s+as\s+/).pop().trim()); + names.delete(''); + const lines=[...names].filter(n=>!(n in overrides)).map(n=>`export const ${n}=(...a)=>Promise.resolve({});`); + for(const [n,v] of Object.entries(overrides))lines.push(`export const ${n}=${v};`); + return lines.join(String.fromCharCode(10)); +} +const stubs={ + native:stubFor('native.ts',{useNative:'()=>globalThis.__native',nativeState:'()=>globalThis.__native'}), + store:stubFor('store.ts',{useStore:'sel=>sel(globalThis.__store)'}), + client:stubFor('client.ts',{}), + router:stubFor('router.ts',{}), +}; + +let dir,mod; +async function load(){ + if(mod)return mod; + dir=mkdtempSync(join(tmpdir(),'strata-gs-')); + const stubPlugin={name:'stubs',setup(b){ + b.onResolve({filter:/\/lib\/(native|store|client|router)$/},args=>({path:args.path.split('/').pop(),namespace:'stub'})); + b.onLoad({filter:/.*/,namespace:'stub'},args=>({contents:stubs[args.path],loader:'js',resolveDir:root})); + }}; + const entry=join(dir,'entry.tsx'); + const out=join(dir,'out.cjs'); + await build({ + stdin:{contents:`export {GuidedSetup} from ${JSON.stringify(resolve(root,'src/components/GuidedSetup.tsx'))}; + export {NativeModels} from ${JSON.stringify(resolve(root,'src/components/NativeModels.tsx'))}; + export {renderToString} from 'react-dom/server'; export {createElement} from 'react';`,resolveDir:root,sourcefile:'entry.tsx',loader:'tsx'}, + bundle:true,format:'cjs',platform:'node',outfile:out,jsx:'automatic',logLevel:'silent',plugins:[stubPlugin], + loader:{'.svg':'dataurl','.png':'dataurl','.css':'empty'}, + }); + globalThis.window??=globalThis;globalThis.matchMedia??=()=>({matches:false,addEventListener(){},removeEventListener(){}}); + mod=createRequire(import.meta.url)(out); + return mod; +} +test.after(()=>{if(dir)rmSync(dir,{recursive:true,force:true});}); + +const store=(complete=false)=>({setup:{complete,choices:{},app:{modelsDir:''}},hardware:null}); +const base={available:true,repo:'',summary:'',error:null,installed:{models:[],data_folder:'',engine:{version:null}},hardware:null,instances:[],jobs:[],defaultId:null,fields:[],capabilities:{}}; +const catalogs={ + 'no catalog at all':null, + 'the packaged host before it had a catalog':{families:[],sizes:[]}, + 'no recommendation':{families:[],contexts:[32768]}, + 'recommendation with nothing in it':{families:[],contexts:[],recommendation:{family:null,model:null}}, + 'no families key':{contexts:[]}, + 'a family without sizes':{families:[{family:'qwen',title:'Qwen3.8-Flash-Next',sizes:[]}],contexts:[32768]}, +}; + +for(const [name,catalog] of Object.entries(catalogs)){ + for(const component of ['GuidedSetup','NativeModels']){ + test(`${component} renders with ${name}`,async()=>{ + const m=await load(); + globalThis.__native={...base,catalog};globalThis.__store=store(); + let html; + assert.doesNotThrow(()=>{html=m.renderToString(m.createElement(m[component]));}); + assert.equal(typeof html,'string'); + }); + } +} + +test('GuidedSetup lists the real catalog when it has one',async()=>{ + const m=await load(); + globalThis.__native={...base,catalog:{families:[{family:'qwen',title:'Qwen3.8-Flash-Next',about:'',images:true,experimental:false,sizes:[ + {id:'iq3_xxs',model:'IQ3_XXS',download_gb:75.8,ram_gb:60,about:'',on_this_pc:'fits',installed:false}]}],contexts:[32768], + recommendation:{family:'qwen',model:'IQ3_XXS',context:32768},context_note:''}}; + globalThis.__store={...store(),setup:{complete:false,choices:{onboarding:{step:2,manual:false}},app:{modelsDir:''}}}; + const html=m.renderToString(m.createElement(m.GuidedSetup)); + assert.match(html,/IQ3_XXS/); +}); From ec42c93947470d1a1c92a47899ef01b45f5b5032 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 17:36:32 +0200 Subject: [PATCH 02/16] installer: setup.py and strata_mcp.py run under Control (STRATA_CONTROL_INSTALL) for the desktop app In the app's mode the install downloads the model the user chose, prepares it with the bundled tools, installs no Python package, fetches no engine and compiles nothing, and writes a run config naming component:strata-engine into a per-user folder (STRATA_INSTALL_DIR). Only bundled tools run (run() refuses pip, git, cmake and anything else). The engine component is looked up if present; a model can be downloaded before an engine is installed. stage-control.py adds setup.py, the preparation tools (static import closure), ref/load.py and data/ to the staged Control. --- apps/desktop/scripts/stage-control.py | 64 +++++++++++++++- setup.py | 103 ++++++++++++++++++++------ tools/strata_mcp.py | 38 +++++++--- 3 files changed, 170 insertions(+), 35 deletions(-) diff --git a/apps/desktop/scripts/stage-control.py b/apps/desktop/scripts/stage-control.py index 33b00560..bf570076 100644 --- a/apps/desktop/scripts/stage-control.py +++ b/apps/desktop/scripts/stage-control.py @@ -73,6 +73,55 @@ def extract(archive: Path, destination: Path) -> Path: return inner +#: What the app's installer needs on top of the Terminal bundle: the model catalog and GPU probe (tools/strata_mcp.py reads +#: setup.py's tables), and the install job, which downloads a model the user chose, prepares it with the bundled tools and +#: writes a run config naming "component:strata-engine". setup.py runs in its CONTROL mode there (no pip, no engine fetch, +#: no compiler). Entry points; their local imports under tools/ come with them. +INSTALLER_FILES = ("setup.py", "ref/load.py") # ref/load.py: strata_pack.py (the Q2_0 AVX-512 repack) imports it +INSTALLER_TOOLS = ("strata_mcp", "iq_pack", "strata_pack", "pack_index", "mtp_fetch", "mtp_pack", "mtp_rt", "draft_vocab", + "strata_tokenizer", "gguf_reader") +INSTALLER_DATA = "data" # draft vocabularies, expert profiles: 2 MB + + +def local_imports(folder: Path, entry: tuple[str, ...]) -> list[str]: + """The tools/ modules `entry` imports, transitively (static: import and from-import statements).""" + import ast + seen: set[str] = set() + todo = list(entry) + while todo: + name = todo.pop() + if name in seen: + continue + seen.add(name) + source = folder / "tools" / f"{name}.py" + if not source.exists(): + raise SystemExit(f"installer tool missing: tools/{name}.py") + for node in ast.walk(ast.parse(source.read_text(encoding="utf-8-sig"))): + names = [a.name.split(".")[0] for a in node.names] if isinstance(node, ast.Import) else \ + [node.module.split(".")[0]] if isinstance(node, ast.ImportFrom) and node.module and node.level == 0 else [] + todo += [m for m in names if (folder / "tools" / f"{m}.py").exists() and m not in seen] + return sorted(seen) + + +def add_installer(folder: Path) -> dict: + """Copy the installer's files from the source tree into the staged Control (after the Terminal bundle is in place).""" + tools = local_imports(ROOT, INSTALLER_TOOLS) + copied = [] + for name in INSTALLER_FILES: + (folder / name).parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(ROOT / name, folder / name) + copied.append(name) + (folder / "tools").mkdir(exist_ok=True) + for name in tools: + shutil.copy2(ROOT / "tools" / f"{name}.py", folder / "tools" / f"{name}.py") + copied.append(f"tools/{name}.py") + if (folder / INSTALLER_DATA).exists(): + shutil.rmtree(folder / INSTALLER_DATA) + shutil.copytree(ROOT / INSTALLER_DATA, folder / INSTALLER_DATA, ignore=shutil.ignore_patterns("__pycache__")) + return {"files": copied, "data": INSTALLER_DATA, "setup_sha256": sha256(folder / "setup.py"), + "mode": "STRATA_CONTROL_INSTALL=1: downloads the chosen model, prepares it, installs no package and no engine"} + + def write_bundle_record(folder: Path, archive: Path) -> dict: manifest_path = archive.with_name(archive.name.rsplit(".", 2 if archive.name.endswith(".tar.gz") else 1)[0] + ".manifest.json") manifest = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest_path.exists() else {} @@ -86,6 +135,7 @@ def write_bundle_record(folder: Path, archive: Path) -> dict: "installed": manifest.get("installed"), "archive": {"name": archive.name, "sha256": sha256(archive), "bytes": archive.stat().st_size}, "acquires_at_runtime": False, + "installer": add_installer(folder), } (folder / "BUNDLE.json").write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8") return record @@ -95,7 +145,8 @@ def check(folder: Path) -> int: target = pt.host_target() python = folder / pt.PYTHON_PINS[target]["python"] problems = [] - for need in (python, folder / "strata.py", folder / "strata_control", folder / "serve" / "server.py", folder / "BUNDLE.json"): + for need in (python, folder / "strata.py", folder / "strata_control", folder / "serve" / "server.py", folder / "BUNDLE.json", + folder / "setup.py", folder / "tools" / "strata_mcp.py", folder / "tools" / "iq_pack.py", folder / "data" / "draft_vocab.bin"): if not need.exists(): problems.append(f"missing {need}") if problems: @@ -105,7 +156,16 @@ def check(folder: Path) -> int: done = subprocess.run([str(python), str(folder / "strata.py"), "--version"], capture_output=True, text=True, env=env, cwd=str(folder), timeout=60) print(done.stdout.strip() or done.stderr.strip()) - return done.returncode + if done.returncode: + return done.returncode + # the installer: its catalog, a GPU probe and its imports work on the bundled Python alone (nothing is installed or fetched) + probe = ("import sys; sys.path.insert(0, %r); import importlib.util as u; s = u.spec_from_file_location('s', %r); m = u.module_from_spec(s); " + "s.loader.exec_module(m); import iq_pack, strata_pack, pack_index, mtp_fetch; " + "print('installer ok: %%d models, %%d families' %% (len(m.MODELS), len(m.FAMILIES)))") % (str(folder / "tools"), str(folder / "setup.py")) + env["STRATA_CONTROL_INSTALL"] = "1" + again = subprocess.run([str(python), "-c", probe], capture_output=True, text=True, env=env, cwd=str(folder), timeout=120) + print(again.stdout.strip() or again.stderr.strip()[-600:]) + return again.returncode def main() -> int: diff --git a/setup.py b/setup.py index c9b5fe0d..4f9812d7 100644 --- a/setup.py +++ b/setup.py @@ -61,6 +61,13 @@ from pathlib import Path from strata_control import acquisition ROOT = Path(__file__).resolve().parent +# The desktop app runs this installer under Strata Control (its bundled Python, STRATA_CONTROL_INSTALL=1). The source +# (tools/, data/, serve/) stays in ROOT, inside the app; everything the install writes (run configs, logs, third_party, +# the data folder beside it) goes to HOME, a per-user folder (STRATA_INSTALL_DIR). In that mode it installs no Python +# package and no engine and compiles nothing: it downloads the model files, prepares them with the bundled tools and +# writes a run config whose engine is "component:strata-engine". Outside that mode HOME is ROOT and nothing changes. +CONTROL = os.environ.get("STRATA_CONTROL_INSTALL") == "1" +HOME = Path(os.environ["STRATA_INSTALL_DIR"]).resolve() if CONTROL and os.environ.get("STRATA_INSTALL_DIR") else ROOT WIN = os.name == "nt" # #214: every Hugging Face file comes from a fixed commit of its repository (the `sha` of # https://huggingface.co/api/models/ when this was pinned), so a checkout installs the same files on any @@ -548,6 +555,12 @@ def _urlopen(req, timeout=None): def run(cmd, cwd=None, env=None, check=True, quiet=False): """An install, build or preparation step (pip, cmake, a package manager, tools/*.py): never part of a start.""" acquisition.require("an install or build step (" + Path(str(cmd[0])).name + ")") + if CONTROL: # the app: only this Python running a bundled tool + argv = [str(c) for c in cmd] + if len(argv) < 2 or os.path.normcase(argv[0]) != os.path.normcase(sys.executable) or argv[1] == "-m" or \ + Path(argv[1]).resolve().parent != (ROOT / "tools").resolve(): + raise acquisition.AcquisitionRefused("the desktop app's installer only runs its bundled preparation tools; " + + " ".join(argv[:2])) say(" > " + " ".join(str(c) for c in cmd)) r = subprocess.run([str(c) for c in cmd], cwd=cwd, env=env, stdout=subprocess.PIPE if quiet else None, stderr=subprocess.STDOUT if quiet else None, @@ -2018,12 +2031,12 @@ def check_shards(shards): def get_llama_cpp(): """llama.cpp at the pinned commit (ggml for the build, gguf-py for the tools, mtmd for images), as a zip: no git.""" - llama = ROOT / "third_party" / "llama.cpp" + llama = HOME / "third_party" / "llama.cpp" if (llama / "ggml" / "CMakeLists.txt").exists() and (llama / "gguf-py").is_dir(): return llama - z = ROOT / "third_party" / f"llama.cpp-{LLAMA_CPP_COMMIT[:7]}.zip" + z = HOME / "third_party" / f"llama.cpp-{LLAMA_CPP_COMMIT[:7]}.zip" download(LLAMA_CPP_ZIP, z, "llama.cpp source") - tmp = ROOT / "third_party" / "_unpack" + tmp = HOME / "third_party" / "_unpack" shutil.rmtree(tmp, ignore_errors=True) try: with zipfile.ZipFile(z) as f: @@ -2081,10 +2094,23 @@ def _installed(name: str) -> bool: return False +def control_missing_packages() -> list: + """The Python packages the preparation tools need that this interpreter does not have (the app bundle has them all).""" + import importlib.util + return [m for m in ("numpy", "jinja2", "regex", "yaml", "tqdm", "requests", "PIL", "psutil") + if importlib.util.find_spec(m) is None] + + def pip_install(packages, what): """pip install into .venv, skipped when the same list was installed before. An install from before the pinned requirements (#214) recorded bare names: those packages are kept as they are (nothing is reinstalled), and the pinned dependencies it already has count as installed.""" + if CONTROL: # the app ships these (hash-locked); nothing is installed here + missing = control_missing_packages() + if missing: + fail("this copy of Strata Control lacks " + ", ".join(missing), "reinstall the Strata app") + ok(f"{what}: bundled with the app") + return stamp = Path(sys.prefix) / ".strata-pip.json" have = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else [] bare = {p.lower() for p in have if req_name(p) == p.lower()} @@ -4388,7 +4414,7 @@ def other_installs(settings: dict) -> list: """Strata folders besides this one that may hold model files: the ones this user ran before, and Strata* folders next to this one (a zip unpacked again lands in e.g. `Strata-main (1)\\Strata-main`).""" cands = [Path(p) for p in settings.get("installs", [])] - for base in dict.fromkeys((ROOT.parent, ROOT.parent.parent)): + for base in dict.fromkeys((HOME.parent, HOME.parent.parent)): try: for d in base.iterdir(): if d.is_dir() and d.name.lower().startswith("strata"): @@ -4400,7 +4426,7 @@ def other_installs(settings: dict) -> list: for d in cands: try: d = d.resolve() - if d != ROOT and d not in found and (d / "setup.py").is_file(): + if d != HOME and d not in found and (d / "setup.py").is_file(): found.append(d) except OSError: pass @@ -4468,16 +4494,16 @@ def data_folder(requested: str | None) -> tuple: and of earlier Strata folders on the same drive into the data folder, and points their configs there.""" settings = load_settings() dest = Path(requested).expanduser().resolve() if requested else \ - Path(settings["data_dir"]) if settings.get("data_dir") else ROOT.parent / "Strata-data" + Path(settings["data_dir"]) if settings.get("data_dir") else HOME.parent / "Strata-data" try: dest.mkdir(parents=True, exist_ok=True) except OSError as e: # e.g. no write access next to the Strata folder - warn(f"cannot use {dest} for the model files ({e}): keeping them in {ROOT}") - dest = ROOT + warn(f"cannot use {dest} for the model files ({e}): keeping them in {HOME}") + dest = HOME elsewhere = [] # #198: the data folder remembered before (a --data-dir to a new place) is a source too, and so is a Strata-data # folder nested in any of them (an install that kept its models one level down) - sources = [ROOT, *other_installs(settings)] + sources = [HOME, *other_installs(settings)] if settings.get("data_dir") and Path(settings["data_dir"]) != dest: sources.append(Path(settings["data_dir"])) sources += [f / "Strata-data" for f in list(sources) if (f / "Strata-data") != dest] @@ -4512,7 +4538,7 @@ def data_folder(requested: str | None) -> tuple: warn(f"some model files are still in {folder} (in use, or already in {dest})") else: ok(f"model files from {folder} moved to {dest} (a new copy of Strata finds them there)") - installs = [str(ROOT)] + [p for p in settings.get("installs", []) if p != str(ROOT) and Path(p).is_dir()] + installs = [str(HOME)] + [p for p in settings.get("installs", []) if p != str(HOME) and Path(p).is_dir()] save_settings({**settings, "data_dir": str(dest), "installs": installs[:20]}) return dest, elsewhere @@ -4522,7 +4548,7 @@ def data_folder_in_place() -> tuple: the settings and nothing else: no folder is created, nothing is moved or copied, no setting is saved. The run configs name their model files, so an install made by an earlier Strata starts from where it is.""" settings = load_settings() - dest = Path(settings["data_dir"]) if settings.get("data_dir") else ROOT.parent / "Strata-data" + dest = Path(settings["data_dir"]) if settings.get("data_dir") else HOME.parent / "Strata-data" return dest, [] @@ -4616,6 +4642,11 @@ def args_dropped(old: dict, cfg: dict) -> list[str]: return list(dict.fromkeys(f for f in flags(old) if f not in new)) +def engine_exe(eng: Path) -> str: + """The `exe` of a run config: the engine component in the app, else the engine binary's path.""" + return "component:strata-engine" if CONTROL else str(eng / EXE) + + def write_setup_config(cfg_path: Path, cfg: dict, source: Path | None = None) -> None: """#629: setup's run config, written over an earlier one for the same model without losing what the user added to it: the keys setup does not write are carried over (carry_over), and the earlier file is kept as @@ -4765,7 +4796,7 @@ def model_config(path: Path) -> bool: def installed_configs(): - return [p for p in sorted(model_config_files(ROOT), key=lambda p: p.stat().st_mtime, reverse=True) + return [p for p in sorted(model_config_files(HOME), key=lambda p: p.stat().st_mtime, reverse=True) if model_config(p)] @@ -5529,11 +5560,11 @@ def write_run_script(model, cfg_path, port, open_browser=True): serve = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), "--port", str(port)] + (["--open"] if open_browser else []) if WIN: - script = ROOT / f"run-{model.lower()}.bat" + script = HOME / f"run-{model.lower()}.bat" script.write_text("@echo off\r\ntitle Strata " + model + "\r\ncd /d \"" + str(ROOT) + "\"\r\n" + " ".join(f'"{x}"' for x in serve) + "\r\nif errorlevel 1 pause\r\n", encoding="utf-8") else: - script = ROOT / f"run-{model.lower()}.sh" + script = HOME / f"run-{model.lower()}.sh" script.write_text("#!/bin/sh\ncd \"" + str(ROOT) + "\"\nexec " + " ".join(f'"{x}"' for x in serve) + "\n", encoding="utf-8") script.chmod(0o755) @@ -5611,9 +5642,33 @@ def sycl_setup(argv) -> int: return subprocess.call([sys.executable, str(script), *rest]) +def control_engine_step(gpu, vision): + """Step 4 in the app: the engine is the component folder's package (strata_control/engine_component.py), found if it is + there and never fetched or built. A model can be downloaded and prepared before the engine is installed; the run config + names "component:strata-engine" and the engine is looked up when the model is loaded. llama.cpp's source zip is fetched + for gguf-py only (the preparation tools), as setup always did: no git, no compiler.""" + from strata_control import engine_component as EC + llama = get_llama_cpp() + ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py for the preparation tools)") + try: + found = EC.resolve(full=False) + eng, meta = Path(found.root), {"version": found.version, "backend": found.backend, "source": "local"} + ok(f"engine component: {found.version} ({found.platform}-{found.backend}) in {eng}") + except EC.EngineMissing as e: + eng = HOME / "engine" + meta = {"version": "99.0.0", "source": "local", "component": "missing"} # its version is checked when it loads + warn(f"no engine is installed for this PC yet ({e}). The model is downloaded and prepared now; install the engine " + "component for your GPU (a later step of the app, or the Terminal) before loading it") + if vision != "none": + warn("images are not part of the app's first release: images off for this model") + return llama, eng, meta, [], gpu, "none" + + def engine_step(a, gpu, hip, amd, cuda_tk, vision): """Step 4: llama.cpp's sources and the engine (ready-made, or compiled here). Returns (llama, engine folder, its BUILD.json, its library folders, the GPU (AMD on Windows: as the engine sees it), the image-encoder choice).""" + if CONTROL: + return control_engine_step(gpu, vision) llama = get_llama_cpp() ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py, ggml, mtmd)") if hip and WIN: # AMD on Windows: the ready-made HIP engine (no compiler) @@ -5866,7 +5921,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte if fam["arch"] not in engine_families(eng): fail(f"this engine ({meta.get('version')}) does not run {fam['title']} yet", "update Strata, or compile the engine with --build, and run setup again") - ok(f"engine: {eng / EXE}") + ok("engine: the engine component (looked up when the model loads)" if CONTROL else f"engine: {eng / EXE}") step(5, f"downloading {fam['title']} {model}") if gguf.exists() and done(gguf): @@ -5903,9 +5958,9 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte if vram > 0: args += ["--expert-vram", f"{max(vram - 3.0 - a.vram_reserve_mib / 1024, 0):.1f}"] ok(f"VRAM kept free for other programs: about {a.vram_reserve_mib} MiB (the experts' share is set lower)") - cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), + cfg = {"exe": engine_exe(eng), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), "model_name": f"{fam['name']}-{model.lower()}", "arch": fam["arch"], - "log": str(ROOT / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port} + "log": str(HOME / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port} if cuda_tk == 12: cfg["cuda"] = 12 if hip: @@ -5920,7 +5975,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte if a.browser is not None: cfg["open_browser"] = a.browser cfg["args"] = recommend_pool_workers(cfg["args"]) # --pool-workers: this engine path's CPU expert threads too - cfg_path = ROOT / f"strata-{tag.lower()}.json" + cfg_path = HOME / f"strata-{tag.lower()}.json" if vision != "none": old_cfg = cfg_path if cfg_path.is_file() else adopted vt = vision_tokens(getattr(a, "vision_tokens", None), vision, old_cfg) @@ -6762,7 +6817,7 @@ def main() -> int: if MODELS[model].get("budget") and engine_ver < need_engine: fail(f"{model} needs engine {'.'.join(map(str, need_engine))} or newer; this one is {meta.get('version')}", "update Strata (or compile the engine with --build) and run setup again") - ok(f"engine: {eng / EXE}") + ok("engine: the engine component (looked up when the model loads)" if CONTROL else f"engine: {eng / EXE}") # ---- 5. the model files step(5, f"downloading {fam['title']} {model}") @@ -6862,7 +6917,7 @@ def main() -> int: run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)], env=env) # a setup run again without --draft-vocab keeps the subset this model's config chose before (cyrillic, fr, en) - draft_vocab = a.draft_vocab or saved_draft_vocab(ROOT / f"strata-{tag.lower()}.json") + draft_vocab = a.draft_vocab or saved_draft_vocab(HOME / f"strata-{tag.lower()}.json") refresh_draft_vocab(rt, draft_vocab or "cjk") ok(f"MTP draft layer: {rt}") for line in draft_vocab_note(gpu.get("vram_gb", 0.0), draft_vocab): # #474: a recommendation, nothing changes @@ -7043,8 +7098,8 @@ def main() -> int: # the package's profile, with llama.cpp's flags (the engine takes the same ones) args += ["--control-vector-scaled", f"{esp}:1.0", "--control-vector-layer-range", "4", "44", "--cvec-mode", "project", "--cvec-dir", "per-layer"] - cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), - "model_name": f"{fam['name']}-{model.lower()}", "log": str(ROOT / f"strata-{tag.lower()}.log"), + cfg = {"exe": engine_exe(eng), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), + "model_name": f"{fam['name']}-{model.lower()}", "log": str(HOME / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port} if cuda_tk == 12: # the experimental CUDA 12 engine (engine-cuda12/) cfg["cuda"] = 12 @@ -7105,7 +7160,7 @@ def main() -> int: cfg["parallel"] = 1 ok("parallel requests: one at a time (--parallel 1)") if vision != "none": - old_cfg = ROOT / f"strata-{tag.lower()}.json" + old_cfg = HOME / f"strata-{tag.lower()}.json" vt = vision_tokens(a.vision_tokens, vision, old_cfg if old_cfg.is_file() else adopted) cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), # the text model, opened vocab-only: "model": str(ready_paths(model, models_dir)["dense"] if ready else shards[0]), @@ -7116,7 +7171,7 @@ def main() -> int: warn("--vision-tokens: images are off for this model, so it is not used") if a.images: # only when given: else an earlier "images" is carried over cfg["images"] = setup_images(a, gpu, hip, Path(a.models_dir)) - cfg_path = ROOT / f"strata-{tag.lower()}.json" + cfg_path = HOME / f"strata-{tag.lower()}.json" cal = setup_calibration(cfg, hip) # #566: Linux HIP too; the tuning is offered on NVIDIA only if cal is not None: sys.path.insert(0, str(ROOT / "tools")) diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 72895893..fad2c349 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -43,6 +43,9 @@ PROTOCOLS = ("2025-06-18", "2025-03-26", "2024-11-05") # the revisions this se VERSION = "0.1.0" WIN = os.name == "nt" DEFAULT_ROOT = Path(__file__).resolve().parent.parent +# The desktop app runs this under Strata Control's Python (STRATA_CONTROL_INSTALL=1): the install runs on that Python, makes no +# .venv and installs no package (setup.py's own CONTROL mode). +CONTROL = os.environ.get("STRATA_CONTROL_INSTALL") == "1" DEFAULT_PORT = 8080 STATE_DIR = ".strata-mcp" # in the Strata folder (git-ignored) @@ -404,15 +407,18 @@ def system_folders() -> list[Path]: class Strata: """One Strata folder: what is installed there, the PC, and the processes this server started.""" - def __init__(self, root: Path | str = DEFAULT_ROOT): + def __init__(self, root: Path | str = DEFAULT_ROOT, src: Path | str | None = None): self.root = Path(root).resolve() + # where setup.py, tools/ and serve/ are (the app: inside Strata Control); `root` is where the installs live + self.src = Path(src).resolve() if src else self.root self.state_dir = self.root / STATE_DIR self.lock = threading.Lock() # install / start / stop one at a time self.children: list[subprocess.Popen] = [] # reaped now and then (no zombies on POSIX) self._setup = None self._setup_tried = False self._hw_cache = None - self.python_override: str | None = None # tests: the interpreter that runs setup / the server + # tests: the interpreter that runs setup / the server. The app's Control runs the installer on its own Python. + self.python_override: str | None = sys.executable if CONTROL else None self.health_timeout = 2.0 # ---- setup.py's own tables and logic @@ -422,7 +428,9 @@ class Strata: if not self._setup_tried: self._setup_tried = True try: - spec = importlib.util.spec_from_file_location("strata_setup_for_mcp", self.root / "setup.py") + if str(self.src) not in sys.path: + sys.path.insert(0, str(self.src)) # setup.py imports strata_control + spec = importlib.util.spec_from_file_location("strata_setup_for_mcp", self.src / "setup.py") mod = importlib.util.module_from_spec(spec) real = sys.stdout sys.stdout = sys.stderr # nothing it prints may reach the protocol stream @@ -1318,7 +1326,8 @@ class Tools: log_path = s.state_dir / "setup.log" with open(log_path, "a", encoding="utf-8") as f: f.write(f"\n===== strata-mcp: install {plan['title']} at {time.strftime('%Y-%m-%d %H:%M:%S')} =====\n") - spec = {"job": job_id, "root": str(s.root), "python": s.run_python(), "base_python": sys.executable, + spec = {"job": job_id, "root": str(s.root), "src": str(s.src), "control": CONTROL, + "python": s.run_python(), "base_python": sys.executable, "create_venv": s.python_override is None and not s.venv_python().exists(), "args": args, "result": str(s.state_dir / "install-result.json")} spec_path = s.state_dir / "install-job.json" @@ -1712,6 +1721,7 @@ def install_job(spec_path: str) -> int: os.replace(tmp, result) py = Path(spec["python"]) + src = Path(spec.get("src") or root) try: if spec.get("create_venv"): venv = root / ".venv" @@ -1727,10 +1737,18 @@ def install_job(spec_path: str) -> int: "once in a terminal", flush=True) record(exit_code=1, ended=time.strftime("%Y-%m-%d %H:%M:%S")) return 1 - cmd = [str(py), str(root / "setup.py"), *spec["args"]] + cmd = [str(py), str(src / "setup.py"), *spec["args"]] print("strata-mcp: running " + " ".join(cmd), flush=True) env = dict(os.environ, PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8") - p = subprocess.Popen(cmd, cwd=str(root), stdin=subprocess.DEVNULL, env=env) + if spec.get("control"): # the app: the installer's own mode, writing to `root` + env.update(STRATA_CONTROL_INSTALL="1", STRATA_INSTALL_DIR=str(root), PYTHONNOUSERSITE="1") + for key in ("PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV"): + env.pop(key, None) + # This job is the explicit install the user asked for (it downloads model files and the preparation sources). The + # server that started it, and every start or serve, keep STRATA_NO_ACQUIRE; setup.py's CONTROL mode still runs + # no pip, git, compiler or engine fetch. + env.pop("STRATA_NO_ACQUIRE", None) + p = subprocess.Popen(cmd, cwd=str(src if spec.get("control") else root), stdin=subprocess.DEVNULL, env=env) record(child_pid=p.pid, child_ident=proc_identity(p.pid)) rc = p.wait() except Exception as e: # noqa: BLE001 @@ -1745,6 +1763,7 @@ def main(argv=None) -> int: ap = argparse.ArgumentParser(description="Strata's MCP server (stdio): install, start, check and stop Strata " "from an AI assistant. See docs/MCP_SERVER.md.") ap.add_argument("--root", help="the Strata folder (default: the one this file is in)") + ap.add_argument("--src", help="where setup.py, tools/ and serve/ are, when that is not the Strata folder (the app)") ap.add_argument("--install-job", help=argparse.SUPPRESS) a = ap.parse_args(argv) if a.install_job: @@ -1753,12 +1772,13 @@ def main(argv=None) -> int: log("Python 3.10 or newer is needed") return 2 root = Path(a.root).expanduser().resolve() if a.root else DEFAULT_ROOT - if not (root / "setup.py").is_file() or not (root / "serve" / "server.py").is_file(): - log(f"{root} is not a Strata folder (no setup.py / serve/server.py)") + src = Path(a.src).expanduser().resolve() if a.src else root + if not (src / "setup.py").is_file() or not (src / "serve" / "server.py").is_file(): + log(f"{src} is not a Strata folder (no setup.py / serve/server.py)") return 2 out = sys.stdout.buffer sys.stdout = sys.stderr # stray prints must never corrupt the protocol stream - server = McpServer(Strata(root), out) + server = McpServer(Strata(root, src), out) log(f"ready (Strata folder {root})") try: server.serve(sys.stdin.buffer) From 11bf85d8a85f223016f703dda82e4b32bfd6be21 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 17:36:32 +0200 Subject: [PATCH 03/16] host: the packaged app gets the model catalog, the GPUs and the install job from Control's bundled installer native-control runs Control's tools/strata_mcp.py on Control's Python (installerEnvironment: STRATA_NO_ACQUIRE stays for the process; only the install job the user starts may fetch model files), in a writable per-user install folder. The catalog, hardware (nvidia-smi) and recommendation come from it, the install plan and job go through it, and a failed catalog is an empty one. Calibration stays off in the packaged app. packaged-control tests adjusted and extended. --- apps/host/server/control-runtime.mjs | 8 ++ apps/host/server/native-control.mjs | 33 +++++--- apps/host/tests/packaged-control.test.mjs | 91 ++++++++++++++++++++--- 3 files changed, 113 insertions(+), 19 deletions(-) diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjs index dc8a7a17..51fa30d9 100644 --- a/apps/host/server/control-runtime.mjs +++ b/apps/host/server/control-runtime.mjs @@ -59,6 +59,14 @@ export function controlEnvironment(control, { env = process.env, components = co }; } +/** + * The environment of the installer process (tools/strata_mcp.py): Control's, with acquiring still forbidden for the process + * itself. Only the install job it starts when the user asks to download a model lifts that for its own children. + */ +export function installerEnvironment(control, { env = process.env, installDir, components = componentsDirectory({ env }) } = {}) { + return { ...controlEnvironment(control, { env, components }), STRATA_CONTROL_INSTALL: '1', ...(installDir ? { STRATA_INSTALL_DIR: installDir } : {}) }; +} + export class ControlError extends Error { constructor(message, { code = 'control_failed', exitCode = null, output = null } = {}) { super(message); diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 0b7c7c5a..0c574aba 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -10,6 +10,7 @@ import { resourceSettings } from './native-resources.mjs'; import { resolvePython, venvPython } from './python-resolver.mjs'; import os from 'node:os'; import { runtimeVision } from './native-vision.mjs'; +import { componentsDirectory, installerEnvironment } from './control-runtime.mjs'; const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'..'); const safeId=value=>typeof value==='string'&&/^[a-z0-9_-]{1,80}$/i.test(value); @@ -28,22 +29,30 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp comes from the component folder, and a start is `strata runtime start` under the owner runtime. Nothing is installed, updated or fetched from here. Without `control` (a source checkout) every path below is the original one. */ const packaged=!!control; + /* In the packaged app the model catalog, the GPU probe and the install job are Control's bundled tools/strata_mcp.py and + setup.py, run on Control's own Python in the installer's mode (STRATA_CONTROL_INSTALL: no pip, no engine, no compiler). + The install only runs when the user clicks Download; starting and serving (control.start) keep STRATA_NO_ACQUIRE. */ + const defaultInstall=()=>join(dirname(componentsDirectory()),'install'); + let packagedInstall=null; const NO_INSTALL='Installing, updating, tuning with calibration or rolling back model files and engines happens from the Terminal (strata install), never while the app runs.'; let defaultId=null,timer=null,closing=false,polling=false; const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);}; const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();}; - function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};} + function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};} function sourceText(){try{return readFileSync(join(packaged?control.control.dir:preferences.repo,'serve/server.py'),'utf8');}catch{return '';}} function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));} function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} - function repo(){if(packaged){const base=[preferences.installDir,snapshot.installDir].find(d=>d&&existsSync(d))??control.control.dir;return realpathSync(base);}const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;} + function installRoot(){const found=[preferences.installDir,packagedInstall,snapshot.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());} + function repo(){if(packaged)return installRoot();const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;} function python(){return resolvePython({repo:preferences.repo});} function send(method,params,timeout=30000){return new Promise((resolve,reject)=>{const id=++seq;const alarm=setTimeout(()=>{pending.delete(id);reject(new Error('The native engine did not respond in time. Check engine logs.'));},timeout);pending.set(id,{resolve,reject,alarm});child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');});} function disconnect(){child?.kill();child=null;definitions=[];for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Native control connection closed.'));}pending.clear();} async function connect(){if(closing)throw new Error("The host is shutting down.");if(child&&definitions.length)return;if(!connecting)connecting=startClient().finally(()=>{connecting=null;});return connecting;} async function startClient(){ const folder=repo(); - buffer='';const py0=python();const client=child=spawnProcess(py0.command,[...py0.args,join(folder,'tools/strata_mcp.py')],{cwd:folder,windowsHide:true,stdio:['pipe','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8'}}); + buffer='';const py0=packaged?{command:control.control.python,args:[]}:python(); + const script=packaged?join(control.control.dir,'tools/strata_mcp.py'):join(folder,'tools/strata_mcp.py'); + const client=child=spawnProcess(py0.command,[...py0.args,script,...(packaged?['--root',folder,'--src',control.control.dir]:[])],{cwd:packaged?control.control.dir:folder,windowsHide:true,stdio:['pipe','pipe','pipe'],env:packaged?installerEnvironment(control.control,{installDir:folder}):{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8'}}); client.stdout.on('data',chunk=>{if(child!==client)return;buffer+=chunk.toString();let end;while((end=buffer.indexOf('\n'))>=0){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);let message;try{message=JSON.parse(line);}catch{continue;}const p=pending.get(message.id);if(p){clearTimeout(p.alarm);pending.delete(message.id);message.error?p.reject(new Error(message.error.message)):p.resolve(message.result);}}}); child.stderr.on('data',chunk=>append('control',chunk.toString())); client.on('error',error=>{if(child===client){snapshot.error=error.message;disconnect();}}); @@ -53,26 +62,30 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp definitions=(await send('tools/list',{})).tools??[]; } async function controlTool(name){ - if(name==='strata_models')return {families:[],sizes:[],note:'Model files are installed from the Terminal; the app fetches nothing while it runs.'}; if(name==='strata_status'){ - const [list,engine]=await Promise.all([control.installedModels({installDir:preferences.installDir}),control.engine()]); + let list=await control.installedModels({installDir:preferences.installDir&&existsSync(preferences.installDir)?preferences.installDir:null}); + if(!preferences.installDir&&!(list.models??[]).length){const own=installRoot();if(realpathSync(list.install_dir)!==own)list=await control.installedModels({installDir:own});} + packagedInstall=list.install_dir; + const engine=await control.engine(); + const installer=await mcpCall('strata_status',{hardware:true}).catch(error=>({error:error.message})); const models=(list.models??[]).filter(m=>m.component_status!=='invalid'&&m.source_config).map(m=>({model:m.id,config:basename(m.source_config),configPath:m.source_config,model_name:m.name,context:m.context_tokens??0,backend:m.backend,ready:m.component_status==='present',images:'off',port:undefined,last_used:null})); const cores=os.cpus().length; return {summary:engine.usable?`Strata Control is ready; engine ${engine.engine.version} (${engine.engine.platform}-${engine.engine.backend}).`:(engine.notice??'No engine for this PC was found.'), installDir:list.install_dir,engine:{usable:engine.usable,notice:engine.notice,version:engine.engine?.version??null,backend:engine.backend,componentsDir:engine.components_dir}, installed:{strata_folder:list.install_dir,data_folder:null,engine:engine.engine?{version:engine.engine.version,backend:engine.engine.backend,folder:engine.engine.root}:{folder:null,version:null},models}, - hardware:{cpu:{cores},ram_gb:Math.round(os.totalmem()/1024**3),gpus:[]},install:null,running:null}; + 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}; } - if(name==='strata_install')throw new Error(NO_INSTALL); throw new Error(`Strata Control has no ${name}.`); } - async function tool(name,args={}){if(packaged)return controlTool(name,args);await connect();if(!definitions.some(d=>d.name===name))throw new Error(`This Strata installation does not support ${name}. Update the installation first.`);const result=await send('tools/call',{name,arguments:args},120000);let value=result.structuredContent;if(!value){const text=result.content?.find(c=>c.type==='text')?.text;try{value=JSON.parse(text);}catch{value={summary:text};}}if(result.isError)throw new Error(value?.error??value?.summary??'Native operation failed.');return value;} + async function tool(name,args={}){if(packaged&&name==='strata_status')return controlTool(name,args);return mcpCall(name,args);} + async function mcpCall(name,args={}){await connect();if(!definitions.some(d=>d.name===name))throw new Error(`This Strata installation does not support ${name}. Update the installation first.`);const result=await send('tools/call',{name,arguments:args},120000);let value=result.structuredContent;if(!value){const text=result.content?.find(c=>c.type==='text')?.text;try{value=JSON.parse(text);}catch{value={summary:text};}}if(result.isError)throw new Error(value?.error??value?.summary??'Native operation failed.');return value;} async function refresh(force=false){ if(closing)return state(); if(refreshing)return refreshing;if(!force&&Date.now()-lastRead<15000)return state(); - refreshing=(async()=>{try{const [catalog,status]=await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing; + refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing; } - function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);} + function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};packagedInstall=null;disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);} function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();} function record(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path,config:readJson(path)};} function settings(model){const {config}=record(model);const values=Object.fromEntries(NATIVE_FIELDS.map(f=>[f.id,config[f.id]??null]));if(typeof values.aliases==='string')values.aliases=values.aliases.split(',').map(v=>v.trim()).filter(Boolean);values.sampling=config.sampling??{};values.args=config.args??[];values.env=publicNativeEnv(config.env??{});return {model,values,mcp:publicMcpServers(config.mcp_servers??config.mcpServers??{}),restartNeeded:true};} diff --git a/apps/host/tests/packaged-control.test.mjs b/apps/host/tests/packaged-control.test.mjs index ed357ad7..86c45634 100644 --- a/apps/host/tests/packaged-control.test.mjs +++ b/apps/host/tests/packaged-control.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { EventEmitter } from 'node:events'; +import { existsSync } from 'node:fs'; import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'node:fs'; import { join, basename } from 'node:path'; import { tmpdir } from 'node:os'; @@ -95,8 +96,9 @@ function packagedFixture({ engineUsable = true } = {}) { }); const calls = []; const spawned = []; + const rpc = []; const control = { - control: { dir: join(root, 'control') }, version: '0.1.45', + control: { dir: join(root, 'control'), python: join(root, 'control', 'python', 'python.exe') }, version: '0.1.45', async installedModels(options) { calls.push(['installedModels', options?.installDir ?? null]); return { install_dir: install, models: configs.map(c => ({ id: c.id, name: `Qwen ${c.id}`, source_config: c.path, component_status: 'present', context_tokens: 32768, backend: 'cuda' })) }; }, async engine() { calls.push(['engine']); @@ -110,8 +112,37 @@ function packagedFixture({ engineUsable = true } = {}) { }; const requests = []; const fetcher = async url => { calls.push(['fetch', url.replace(/:\d+/, ':PORT')]); return Response.json({ status: 'ok' }); }; - const native = createNativeControl({ control, directory: data, spawnProcess: (...args) => { spawned.push(args); throw new Error('no process may be started by the host in packaged mode'); }, fetcher, requests: () => requests }); - return { native, calls, spawned, install, root, cleanup: () => { rmSync(root, { recursive: true, force: true }); } }; + // The only process the host may start is Control's installer (its bundled tools/strata_mcp.py on Control's Python); the fake + // answers like it: the catalog, the hardware with the GPUs, and an install plan or job. + const catalog = { families: [{ family: 'qwen', title: 'Qwen3.8-Flash-Next', about: 'x', images: true, experimental: false, sizes: [ + { id: 'q2_0', model: 'Q2_0', download_gb: 66.4, ram_needed_gb: 48, about: 'fast', on_this_pc: 'fits', installed: false, images: true, experimental: false }, + { id: 'iq3_xxs', model: 'IQ3_XXS', download_gb: 75.8, ram_needed_gb: 60, about: 'balanced', on_this_pc: 'fits', installed: false, images: true, experimental: false }] }], + contexts: [8192, 32768], recommendation: { family: 'qwen', model: 'IQ3_XXS', context: 32768 }, context_note: '' }; + const hardware = { ram_gb: 63, cpu: { name: 'cpu', cores: 12 }, gpus: [{ index: 0, name: 'NVIDIA GeForce RTX 5070', vram_gb: 11.9, usable: true }] }; + let installJob = null; + const spawnProcess = (command, args, options) => { + spawned.push({ command, args, options }); + if (!String(args[0]).endsWith('strata_mcp.py')) throw new Error('no process but the installer may be started by the host in packaged mode: ' + command + ' ' + args.join(' ')); + const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.exitCode = null; + child.kill = () => { child.exitCode = 0; queueMicrotask(() => child.emit('exit', 0)); return true; }; + child.stdin = { write(line) { + const message = JSON.parse(line); if (!message.id) return; + if (message.method === 'tools/call') rpc.push(message.params); + let result; + if (message.method === 'initialize') result = { protocolVersion: '2024-11-05' }; + else if (message.method === 'tools/list') result = { tools: ['strata_models', 'strata_status', 'strata_install'].map(name => ({ name })) }; + else if (message.params.name === 'strata_models') result = { structuredContent: catalog }; + else if (message.params.name === 'strata_status') result = { structuredContent: { hardware, recommendation: catalog.recommendation, install: installJob, running: [], summary: 'x' } }; + else if (message.params.arguments?.confirm) { installJob = { running: false, exit_code: 0 }; result = { structuredContent: { summary: 'Install started', plan: { download_gb: 66.4 }, install: { running: true, step: 'downloading' } } }; } + else if (message.params.arguments?.cancel === undefined && message.params.arguments?.confirm === undefined) result = { structuredContent: { summary: 'Install finished', install: { running: false, exit_code: 0 } } }; + else result = { structuredContent: { summary: 'Plan', plan: { title: 'Qwen3.8-Flash-Next Q2_0', download_gb: 66.4, disk_short: null } } }; + queueMicrotask(() => child.stdout.emit('data', Buffer.from(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }) + String.fromCharCode(10)))); + } }; + return child; + }; + const native = createNativeControl({ control, directory: data, spawnProcess, fetcher, requests: () => requests }); + const others = () => spawned.filter(s => !String(s.args[0]).endsWith('strata_mcp.py')); + return { native, calls, spawned, others, rpc, catalog, hardware, install, root, cleanup: () => { rmSync(root, { recursive: true, force: true }); } }; } const finish = async (native, id) => { for (let i = 0; i < 400; i++) { const job = native.state().jobs.find(j => j.id === id); if (job.state !== 'running') return job; await new Promise(r => setTimeout(r, 10)); } throw new Error('job did not finish'); }; @@ -125,7 +156,19 @@ test('packaged: models come from Control, no python, git or engine process is st assert.equal(state.packaged, true); assert.match(state.summary, /engine 0\.1\.45/); assert.equal(state.version, '0.1.45'); - assert.equal(f.spawned.length, 0); + assert.equal(f.others().length, 0, 'nothing but the installer is started'); + // the catalog, the GPUs and the recommendation come from the bundled installer, run on Control's own Python + assert.equal(state.catalog.families[0].sizes.length, 2); + assert.equal(state.catalog.recommendation.model, 'IQ3_XXS'); + assert.equal(state.hardware.gpus[0].name, 'NVIDIA GeForce RTX 5070'); + assert.equal(state.hardware.ram_gb, 63); + const installer = f.spawned[0]; + assert.equal(installer.command, join(f.root, 'control', 'python', 'python.exe')); + assert.deepEqual(installer.args.slice(1), ['--root', f.install, '--src', join(f.root, 'control')]); + assert.equal(installer.options.env.STRATA_CONTROL_INSTALL, '1'); + assert.equal(installer.options.env.STRATA_NO_ACQUIRE, '1', 'the installer process itself may not acquire; only its explicit install job does'); + assert.equal(installer.options.env.STRATA_INSTALL_DIR, f.install); + assert.equal(installer.options.env.PYTHONNOUSERSITE, '1'); } finally { await f.native.close(); f.cleanup(); } }); @@ -146,7 +189,7 @@ test('packaged: load = saved profile + runtime start under Control; unload = run await f.native.unload(first.id); assert.deepEqual(f.calls.filter(c => c[0] === 'stop').at(-1), ['stop', 'app-1']); assert.equal(f.native.state().instances.length, 1); - assert.equal(f.spawned.length, 0, 'the host never spawned anything itself'); + assert.equal(f.others().length, 0, 'the host never spawned anything itself'); } finally { await f.native.close(); f.cleanup(); } }); @@ -159,20 +202,50 @@ test('packaged: no engine for this PC is the notice, and nothing is started', as assert.match(job.error, /No engine for this PC/); assert.match(job.error, /never downloads an engine/); assert.equal(f.calls.some(c => ['saveProfile', 'start'].includes(c[0])), false); - assert.equal(f.spawned.length, 0); + assert.equal(f.others().length, 0); } finally { await f.native.close(); f.cleanup(); } }); -test('packaged: install, update, rollback and calibration are refused with the Terminal notice and start nothing', async () => { +test('packaged: the user can download and prepare a model: the plan and the install job go to the bundled installer, the engine is not touched', async () => { const f = packagedFixture(); try { await f.native.refresh(true); - for (const [kind, args] of [['install', { family: 'qwen', model: 'IQ2_XS' }], ['update-engine', {}], ['update-strata', {}], ['rollback', {}], ['calibrate', { model: 'iq3_s' }]]) { + const plan = await f.native.plan({ family: 'qwen', model: 'Q2_0' }); + assert.equal(plan.plan.title, 'Qwen3.8-Flash-Next Q2_0'); + const planned = f.rpc.at(-1); + assert.equal(planned.name, 'strata_install'); + assert.equal(planned.arguments.confirm, false, 'a plan changes nothing'); + const job = await finish(f.native, f.native.operation('install', { family: 'qwen', model: 'Q2_0' }).id); + assert.equal(job.state, 'done', job.error); + const started = f.rpc.filter(c => c.name === 'strata_install' && c.arguments.confirm); + assert.equal(started.length, 1); + assert.equal(started[0].arguments.family, 'qwen'); + assert.equal(started[0].arguments.model, 'Q2_0'); + assert.equal(f.others().length, 0, 'the host starts no pip, git, python of its own or engine'); + assert.equal(f.calls.filter(c => ['saveProfile', 'start'].includes(c[0])).length, 0, 'installing does not start an engine'); + } finally { await f.native.close(); f.cleanup(); } +}); + +test('packaged: the installer works in a folder the app can write, never in the read-only bundle', async () => { + const f = packagedFixture(); + try { + await f.native.refresh(true); + assert.equal(existsSync(f.install), true); + assert.notEqual(f.native.state().installDir, join(f.root, 'control')); + assert.equal(f.spawned[0].args.at(-3), f.install); + } finally { await f.native.close(); f.cleanup(); } +}); + +test('packaged: update, rollback and calibration are refused with the Terminal notice and start nothing', async () => { + const f = packagedFixture(); + try { + await f.native.refresh(true); + for (const [kind, args] of [['update-engine', {}], ['update-strata', {}], ['rollback', {}], ['calibrate', { model: 'iq3_s' }]]) { const job = await finish(f.native, f.native.operation(kind, args).id); assert.equal(job.state, 'error', kind); assert.match(job.error, /Terminal|calibrates NVIDIA|No saved previous engine/, `${kind}: ${job.error}`); } - assert.equal(f.spawned.length, 0); + assert.equal(f.others().length, 0); assert.equal(f.calls.filter(c => ['saveProfile', 'start'].includes(c[0])).length, 0); } finally { await f.native.close(); f.cleanup(); } }); From 2bd0cdc4f9b16b5455b800c83148aabca0408453 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 17:46:28 +0200 Subject: [PATCH 04/16] installer: home() instead of a constant (callers can still move ROOT); close cancels a running install; tests for the app's install mode --- apps/host/server/native-control.mjs | 2 +- setup.py | 55 +++--- tests/desktop/test_control_install.py | 231 ++++++++++++++++++++++++++ 3 files changed, 263 insertions(+), 25 deletions(-) create mode 100644 tests/desktop/test_control_install.py diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 0c574aba..b455c1f8 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -187,7 +187,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp } function operation(kind,args={}){if(!['install','load','benchmark','tune','calibrate','update-engine','update-strata','rollback'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):program(job,args),{guided:args.guided===true,model:args.model});} async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install')await tool('strata_install',{cancel:true});else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} - async function close(){closing=true;clearInterval(timer);const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();} + async function close(){closing=true;clearInterval(timer);const installing=packaged&&child&&[...jobs.values()].some(j=>j.kind==='install'&&j.state==='running');if(installing)await send('tools/call',{name:'strata_install',arguments:{cancel:true}},15000).catch(()=>{});const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();} // Remove nonserializable process references from public jobs. const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,...job})=>job);return value;}; return {state:publicState,refresh,configure,setDownloadDirectory,plan,settings,save,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; diff --git a/setup.py b/setup.py index 4f9812d7..b6e2a571 100644 --- a/setup.py +++ b/setup.py @@ -63,11 +63,18 @@ from strata_control import acquisition ROOT = Path(__file__).resolve().parent # The desktop app runs this installer under Strata Control (its bundled Python, STRATA_CONTROL_INSTALL=1). The source # (tools/, data/, serve/) stays in ROOT, inside the app; everything the install writes (run configs, logs, third_party, -# the data folder beside it) goes to HOME, a per-user folder (STRATA_INSTALL_DIR). In that mode it installs no Python +# the data folder beside it) goes to home(), a per-user folder (STRATA_INSTALL_DIR). In that mode it installs no Python # package and no engine and compiles nothing: it downloads the model files, prepares them with the bundled tools and -# writes a run config whose engine is "component:strata-engine". Outside that mode HOME is ROOT and nothing changes. +# writes a run config whose engine is "component:strata-engine". Outside that mode home() is ROOT and nothing changes. CONTROL = os.environ.get("STRATA_CONTROL_INSTALL") == "1" -HOME = Path(os.environ["STRATA_INSTALL_DIR"]).resolve() if CONTROL and os.environ.get("STRATA_INSTALL_DIR") else ROOT +_CONTROL_HOME = Path(os.environ["STRATA_INSTALL_DIR"]).resolve() if CONTROL and os.environ.get("STRATA_INSTALL_DIR") else None + + +def home() -> Path: + """Where an install writes (see above). A function, not a constant, so ROOT stays the one thing a caller can point elsewhere.""" + return _CONTROL_HOME or ROOT + + WIN = os.name == "nt" # #214: every Hugging Face file comes from a fixed commit of its repository (the `sha` of # https://huggingface.co/api/models/ when this was pinned), so a checkout installs the same files on any @@ -2031,12 +2038,12 @@ def check_shards(shards): def get_llama_cpp(): """llama.cpp at the pinned commit (ggml for the build, gguf-py for the tools, mtmd for images), as a zip: no git.""" - llama = HOME / "third_party" / "llama.cpp" + llama = home() / "third_party" / "llama.cpp" if (llama / "ggml" / "CMakeLists.txt").exists() and (llama / "gguf-py").is_dir(): return llama - z = HOME / "third_party" / f"llama.cpp-{LLAMA_CPP_COMMIT[:7]}.zip" + z = home() / "third_party" / f"llama.cpp-{LLAMA_CPP_COMMIT[:7]}.zip" download(LLAMA_CPP_ZIP, z, "llama.cpp source") - tmp = HOME / "third_party" / "_unpack" + tmp = home() / "third_party" / "_unpack" shutil.rmtree(tmp, ignore_errors=True) try: with zipfile.ZipFile(z) as f: @@ -4414,7 +4421,7 @@ def other_installs(settings: dict) -> list: """Strata folders besides this one that may hold model files: the ones this user ran before, and Strata* folders next to this one (a zip unpacked again lands in e.g. `Strata-main (1)\\Strata-main`).""" cands = [Path(p) for p in settings.get("installs", [])] - for base in dict.fromkeys((HOME.parent, HOME.parent.parent)): + for base in dict.fromkeys((home().parent, home().parent.parent)): try: for d in base.iterdir(): if d.is_dir() and d.name.lower().startswith("strata"): @@ -4426,7 +4433,7 @@ def other_installs(settings: dict) -> list: for d in cands: try: d = d.resolve() - if d != HOME and d not in found and (d / "setup.py").is_file(): + if d != home() and d not in found and (d / "setup.py").is_file(): found.append(d) except OSError: pass @@ -4494,16 +4501,16 @@ def data_folder(requested: str | None) -> tuple: and of earlier Strata folders on the same drive into the data folder, and points their configs there.""" settings = load_settings() dest = Path(requested).expanduser().resolve() if requested else \ - Path(settings["data_dir"]) if settings.get("data_dir") else HOME.parent / "Strata-data" + Path(settings["data_dir"]) if settings.get("data_dir") else home().parent / "Strata-data" try: dest.mkdir(parents=True, exist_ok=True) except OSError as e: # e.g. no write access next to the Strata folder - warn(f"cannot use {dest} for the model files ({e}): keeping them in {HOME}") - dest = HOME + warn(f"cannot use {dest} for the model files ({e}): keeping them in {home()}") + dest = home() elsewhere = [] # #198: the data folder remembered before (a --data-dir to a new place) is a source too, and so is a Strata-data # folder nested in any of them (an install that kept its models one level down) - sources = [HOME, *other_installs(settings)] + sources = [home(), *other_installs(settings)] if settings.get("data_dir") and Path(settings["data_dir"]) != dest: sources.append(Path(settings["data_dir"])) sources += [f / "Strata-data" for f in list(sources) if (f / "Strata-data") != dest] @@ -4538,7 +4545,7 @@ def data_folder(requested: str | None) -> tuple: warn(f"some model files are still in {folder} (in use, or already in {dest})") else: ok(f"model files from {folder} moved to {dest} (a new copy of Strata finds them there)") - installs = [str(HOME)] + [p for p in settings.get("installs", []) if p != str(HOME) and Path(p).is_dir()] + installs = [str(home())] + [p for p in settings.get("installs", []) if p != str(home()) and Path(p).is_dir()] save_settings({**settings, "data_dir": str(dest), "installs": installs[:20]}) return dest, elsewhere @@ -4548,7 +4555,7 @@ def data_folder_in_place() -> tuple: the settings and nothing else: no folder is created, nothing is moved or copied, no setting is saved. The run configs name their model files, so an install made by an earlier Strata starts from where it is.""" settings = load_settings() - dest = Path(settings["data_dir"]) if settings.get("data_dir") else HOME.parent / "Strata-data" + dest = Path(settings["data_dir"]) if settings.get("data_dir") else home().parent / "Strata-data" return dest, [] @@ -4796,7 +4803,7 @@ def model_config(path: Path) -> bool: def installed_configs(): - return [p for p in sorted(model_config_files(HOME), key=lambda p: p.stat().st_mtime, reverse=True) + return [p for p in sorted(model_config_files(home()), key=lambda p: p.stat().st_mtime, reverse=True) if model_config(p)] @@ -5560,11 +5567,11 @@ def write_run_script(model, cfg_path, port, open_browser=True): serve = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), "--port", str(port)] + (["--open"] if open_browser else []) if WIN: - script = HOME / f"run-{model.lower()}.bat" + script = home() / f"run-{model.lower()}.bat" script.write_text("@echo off\r\ntitle Strata " + model + "\r\ncd /d \"" + str(ROOT) + "\"\r\n" + " ".join(f'"{x}"' for x in serve) + "\r\nif errorlevel 1 pause\r\n", encoding="utf-8") else: - script = HOME / f"run-{model.lower()}.sh" + script = home() / f"run-{model.lower()}.sh" script.write_text("#!/bin/sh\ncd \"" + str(ROOT) + "\"\nexec " + " ".join(f'"{x}"' for x in serve) + "\n", encoding="utf-8") script.chmod(0o755) @@ -5655,7 +5662,7 @@ def control_engine_step(gpu, vision): eng, meta = Path(found.root), {"version": found.version, "backend": found.backend, "source": "local"} ok(f"engine component: {found.version} ({found.platform}-{found.backend}) in {eng}") except EC.EngineMissing as e: - eng = HOME / "engine" + eng = home() / "engine" meta = {"version": "99.0.0", "source": "local", "component": "missing"} # its version is checked when it loads warn(f"no engine is installed for this PC yet ({e}). The model is downloaded and prepared now; install the engine " "component for your GPU (a later step of the app, or the Terminal) before loading it") @@ -5960,7 +5967,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte ok(f"VRAM kept free for other programs: about {a.vram_reserve_mib} MiB (the experts' share is set lower)") cfg = {"exe": engine_exe(eng), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), "model_name": f"{fam['name']}-{model.lower()}", "arch": fam["arch"], - "log": str(HOME / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port} + "log": str(home() / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port} if cuda_tk == 12: cfg["cuda"] = 12 if hip: @@ -5975,7 +5982,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte if a.browser is not None: cfg["open_browser"] = a.browser cfg["args"] = recommend_pool_workers(cfg["args"]) # --pool-workers: this engine path's CPU expert threads too - cfg_path = HOME / f"strata-{tag.lower()}.json" + cfg_path = home() / f"strata-{tag.lower()}.json" if vision != "none": old_cfg = cfg_path if cfg_path.is_file() else adopted vt = vision_tokens(getattr(a, "vision_tokens", None), vision, old_cfg) @@ -6917,7 +6924,7 @@ def main() -> int: run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)], env=env) # a setup run again without --draft-vocab keeps the subset this model's config chose before (cyrillic, fr, en) - draft_vocab = a.draft_vocab or saved_draft_vocab(HOME / f"strata-{tag.lower()}.json") + draft_vocab = a.draft_vocab or saved_draft_vocab(home() / f"strata-{tag.lower()}.json") refresh_draft_vocab(rt, draft_vocab or "cjk") ok(f"MTP draft layer: {rt}") for line in draft_vocab_note(gpu.get("vram_gb", 0.0), draft_vocab): # #474: a recommendation, nothing changes @@ -7099,7 +7106,7 @@ def main() -> int: args += ["--control-vector-scaled", f"{esp}:1.0", "--control-vector-layer-range", "4", "44", "--cvec-mode", "project", "--cvec-dir", "per-layer"] cfg = {"exe": engine_exe(eng), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), - "model_name": f"{fam['name']}-{model.lower()}", "log": str(HOME / f"strata-{tag.lower()}.log"), + "model_name": f"{fam['name']}-{model.lower()}", "log": str(home() / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port} if cuda_tk == 12: # the experimental CUDA 12 engine (engine-cuda12/) cfg["cuda"] = 12 @@ -7160,7 +7167,7 @@ def main() -> int: cfg["parallel"] = 1 ok("parallel requests: one at a time (--parallel 1)") if vision != "none": - old_cfg = HOME / f"strata-{tag.lower()}.json" + old_cfg = home() / f"strata-{tag.lower()}.json" vt = vision_tokens(a.vision_tokens, vision, old_cfg if old_cfg.is_file() else adopted) cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), # the text model, opened vocab-only: "model": str(ready_paths(model, models_dir)["dense"] if ready else shards[0]), @@ -7171,7 +7178,7 @@ def main() -> int: warn("--vision-tokens: images are off for this model, so it is not used") if a.images: # only when given: else an earlier "images" is carried over cfg["images"] = setup_images(a, gpu, hip, Path(a.models_dir)) - cfg_path = HOME / f"strata-{tag.lower()}.json" + cfg_path = home() / f"strata-{tag.lower()}.json" cal = setup_calibration(cfg, hip) # #566: Linux HIP too; the tuning is offered on NVIDIA only if cal is not None: sys.path.insert(0, str(ROOT / "tools")) diff --git a/tests/desktop/test_control_install.py b/tests/desktop/test_control_install.py new file mode 100644 index 00000000..96cd3f33 --- /dev/null +++ b/tests/desktop/test_control_install.py @@ -0,0 +1,231 @@ +"""The desktop app's installer: tools/strata_mcp.py and setup.py run on Control's Python in STRATA_CONTROL_INSTALL mode. + +What the owner asked for: a user installs the app, picks a model in it and downloads and prepares it, like any normal user. +What must stay true: a start or a serve never acquires anything (tests/terminal/test_no_acquisition.py), and the install +itself downloads model files only - no pip, no git, no compiler, no engine fetch, only the bundled preparation tools. +""" + +from __future__ import annotations + +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) + + +def load_setup(home: Path, name: str = "setup_control_mode"): + """setup.py imported as the app's installer: the mode is read when the module loads.""" + env = {"STRATA_CONTROL_INSTALL": "1", "STRATA_INSTALL_DIR": str(home)} + with mock.patch.dict(os.environ, env): + spec = importlib.util.spec_from_file_location(name, ROOT / "setup.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class ControlModeTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.home = Path(self.tmp.name) / "install" + self.home.mkdir() + self.S = load_setup(self.home) + + def test_the_folder_everything_is_written_to_is_the_install_folder_not_the_bundle(self): + S = self.S + self.assertTrue(S.CONTROL) + self.assertEqual(S.home(), self.home.resolve()) + self.assertEqual(S.ROOT, ROOT) + # without the mode nothing moves: HOME is the source folder, as it always was + spec = importlib.util.spec_from_file_location("setup_plain_mode", ROOT / "setup.py") + plain = importlib.util.module_from_spec(spec) + with mock.patch.dict(os.environ, {"STRATA_CONTROL_INSTALL": "0"}): + spec.loader.exec_module(plain) + self.assertFalse(plain.CONTROL) + self.assertEqual(plain.home(), plain.ROOT) + + def test_only_this_python_running_a_bundled_tool_may_run(self): + S = self.S + tool = ROOT / "tools" / "pack_index.py" + for refused in ( + [sys.executable, "-m", "pip", "install", "numpy"], + ["pip", "install", "numpy"], + ["git", "clone", "https://example.invalid/x.git"], + ["cmake", "--build", "."], + ["winget", "install", "Nvidia.CUDA"], + [sys.executable, str(self.home / "evil.py")], # a script outside the bundled tools + [sys.executable, str(ROOT / "setup.py"), "--build"], + [sys.executable], + ): + with self.subTest(refused=refused), mock.patch.object(S.subprocess, "run", side_effect=AssertionError("ran")): + with self.assertRaises(S.acquisition.AcquisitionRefused): + S.run(refused) + done = subprocess.CompletedProcess([], 0) + with mock.patch.object(S.subprocess, "run", return_value=done) as runner: + S.run([sys.executable, str(tool), "--help"], check=False) + runner.assert_called_once() + + def test_no_package_is_installed(self): + S = self.S + with mock.patch.object(S, "run", side_effect=AssertionError("pip")), \ + mock.patch.object(S, "control_missing_packages", return_value=[]): + S.pip_install(["numpy==1"], "the packages") # the app ships them; nothing runs + with mock.patch.object(S, "control_missing_packages", return_value=["numpy"]), \ + self.assertRaises(SystemExit): + S.pip_install(["numpy==1"], "the packages") + + def test_the_engine_is_the_component_and_a_missing_one_does_not_stop_the_download(self): + S = self.S + llama = self.home / "third_party" / "llama.cpp" + (llama / "ggml").mkdir(parents=True) + (llama / "ggml" / "CMakeLists.txt").write_text("", encoding="utf-8") + (llama / "gguf-py").mkdir() + empty = Path(self.tmp.name) / "components" + empty.mkdir() + gpu = {"index": 0, "vram_gb": 12.0} + with mock.patch.dict(os.environ, {"STRATA_COMPONENTS_DIR": str(empty)}), \ + mock.patch.object(S, "download", side_effect=AssertionError("fetched")), \ + mock.patch.object(S, "build_engine", side_effect=AssertionError("built")), \ + mock.patch.object(S, "get_prebuilt", side_effect=AssertionError("fetched an engine")): + found, eng, meta, libs, chosen, vision = S.engine_step(mock.Mock(build=False, prebuilt=None), gpu, False, [], 13, "gpu") + self.assertEqual(found.resolve(), llama.resolve()) + self.assertEqual(libs, []) + self.assertEqual(vision, "none") # images are not in the first app release + self.assertEqual(meta["source"], "local") + self.assertEqual(S.engine_exe(eng), "component:strata-engine") + + def test_the_run_config_goes_to_the_install_folder_and_the_data_folder_sits_beside_it(self): + S = self.S + self.assertEqual(S.installed_configs(), []) + (self.home / "strata-q2_0.json").write_text(json.dumps({"exe": "component:strata-engine", "args": ["--native", "x.gguf"], + "tokenizer": "t"}), encoding="utf-8") + with mock.patch.object(S, "model_config", return_value=True): + self.assertEqual([p.name for p in S.installed_configs()], ["strata-q2_0.json"]) + with mock.patch.dict(os.environ, {"APPDATA": self.tmp.name, "XDG_CONFIG_HOME": self.tmp.name}): + data, _ = S.data_folder_in_place() + self.assertEqual(data, self.home.resolve().parent / "Strata-data") + + def test_the_bundle_lists_everything_the_install_imports(self): + sys.path.insert(0, str(ROOT / "apps" / "desktop" / "scripts")) + try: + spec = importlib.util.spec_from_file_location("stage_control_for_test", ROOT / "apps" / "desktop" / "scripts" / "stage-control.py") + stage = importlib.util.module_from_spec(spec) + spec.loader.exec_module(stage) + finally: + sys.path.pop(0) + tools = stage.local_imports(ROOT, stage.INSTALLER_TOOLS) + for need in ("strata_mcp", "iq_pack", "strata_pack", "canonical_xcheck", "pack_layer", "gguf_reader", "gguf_writer", "_paths"): + self.assertIn(need, tools) + out = Path(self.tmp.name) / "control" + out.mkdir() + record = stage.add_installer(out) + for name in ("setup.py", "ref/load.py", "tools/strata_mcp.py", "tools/iq_pack.py", "data/draft_vocab.bin"): + self.assertTrue((out / name).is_file(), name) + self.assertIn("tools/strata_pack.py", record["files"]) + # every module setup.py's preparation steps run exists in the bundle + for tool in ("iq_pack", "strata_pack", "pack_index", "strata_tokenizer", "mtp_fetch", "mtp_pack", "mtp_rt"): + self.assertTrue((out / "tools" / f"{tool}.py").is_file(), tool) + + +class InstallerServerTests(unittest.TestCase): + """tools/strata_mcp.py with its source (setup.py, serve/) apart from the install folder, as the app runs it.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) / "install" + self.root.mkdir() + spec = importlib.util.spec_from_file_location("strata_mcp_for_test", ROOT / "tools" / "strata_mcp.py") + self.mcp = importlib.util.module_from_spec(spec) + with mock.patch.dict(os.environ, {"STRATA_CONTROL_INSTALL": "1", "STRATA_INSTALL_DIR": str(self.root)}): + spec.loader.exec_module(self.mcp) + + def test_the_catalog_comes_from_setup_py_in_the_bundle(self): + s = self.mcp.Strata(self.root, ROOT) + self.assertEqual(s.root, self.root.resolve()) + self.assertEqual(s.src, ROOT) + models, families, contexts, source = s.tables() + self.assertEqual(source, "setup.py") + self.assertIn("qwen", families) + self.assertIn("IQ3_XXS", models) + self.assertEqual(s.python_override, sys.executable) # Control's own Python runs the install + + def test_the_install_job_runs_on_control_python_without_a_venv_and_may_fetch_only_for_itself(self): + s = self.mcp.Strata(self.root, ROOT) + spec_path = self.root / "job.json" + spec = {"job": "j1", "root": str(self.root), "src": str(ROOT), "control": True, "python": sys.executable, + "base_python": sys.executable, "create_venv": False, "args": ["--yes", "--no-start"], + "result": str(self.root / "result.json")} + spec_path.write_text(json.dumps(spec), encoding="utf-8") + seen = {} + + class FakePopen: + pid = 4242 + + def __init__(self, cmd, **kw): + seen["cmd"], seen["kw"] = cmd, kw + + def wait(self): + return 0 + + with mock.patch.dict(os.environ, {"STRATA_NO_ACQUIRE": "1", "PYTHONPATH": "x", "PYTHONHOME": "y"}), \ + mock.patch.object(self.mcp.subprocess, "Popen", FakePopen), \ + mock.patch.object(self.mcp, "proc_identity", return_value=None): + self.assertEqual(self.mcp.install_job(str(spec_path)), 0) + self.assertEqual(os.environ["STRATA_NO_ACQUIRE"], "1", "this process keeps the switch") + self.assertEqual(seen["cmd"][:2], [sys.executable, str(ROOT / "setup.py")]) + env = seen["kw"]["env"] + self.assertEqual(env["STRATA_CONTROL_INSTALL"], "1") + self.assertEqual(env["STRATA_INSTALL_DIR"], str(self.root)) + self.assertNotIn("STRATA_NO_ACQUIRE", env, "the explicit install job may fetch the chosen model's files") + self.assertNotIn("PYTHONPATH", env) + self.assertNotIn("PYTHONHOME", env) + self.assertFalse((self.root / ".venv").exists(), "no virtual environment, no pip") + self.assertIsNotNone(s) + + @unittest.skipUnless(os.name == "nt" or sys.platform.startswith("linux"), "a PC with a GPU probe") + def test_a_real_install_reaches_the_model_download_with_nothing_else_acquired(self): + """setup.py in the app's mode, as the install job runs it: steps 1-4 pass (PC check, packages bundled, engine component + optional, llama.cpp source already present) and step 5 asks for the model file. The model host is a folder that does + not exist, so nothing is downloaded; pip, git, cmake and winget shims that record any call must stay unused.""" + import setup as plain + if not plain.gpus(): + self.skipTest("no NVIDIA GPU here: setup stops at step 1") + home = Path(self.tmp.name) / "home" + shims = Path(self.tmp.name) / "shims" + for p in (home / "third_party" / "llama.cpp" / "ggml", home / "third_party" / "llama.cpp" / "gguf-py", shims): + p.mkdir(parents=True) + (home / "third_party" / "llama.cpp" / "ggml" / "CMakeLists.txt").write_text("", encoding="utf-8") + log = Path(self.tmp.name) / "shim.log" + for tool in ("pip", "pip3", "git", "cmake", "ninja", "winget", "curl", "wget", "cl", "make"): + if os.name == "nt": + (shims / f"{tool}.cmd").write_text(f"@echo {tool} %* >> \"{log}\"\r\n", encoding="utf-8") + else: + (shims / tool).write_text(f"#!/bin/sh\necho {tool} \"$@\" >> '{log}'\n", encoding="utf-8") + (shims / tool).chmod(0o755) + env = {k: v for k, v in os.environ.items() if k not in ("STRATA_NO_ACQUIRE", "PYTHONPATH", "VIRTUAL_ENV")} + env.update(STRATA_CONTROL_INSTALL="1", STRATA_INSTALL_DIR=str(home), APPDATA=str(Path(self.tmp.name) / "appdata"), + XDG_CONFIG_HOME=str(Path(self.tmp.name) / "xdg"), STRATA_COMPONENTS_DIR=str(Path(self.tmp.name) / "components"), + HF_ENDPOINT=(Path(self.tmp.name) / "no-such-hf").as_uri(), PATH=str(shims) + os.pathsep + env.get("PATH", ""), + PYTHONIOENCODING="utf-8") + done = subprocess.run([sys.executable, str(ROOT / "setup.py"), "--yes", "--no-start", "--family", "qwen", "--model", "Q2_0", + "--context", "32768", "--vision", "no", "--experimental-speed-projection", "off"], + capture_output=True, text=True, env=env, cwd=str(ROOT), stdin=subprocess.DEVNULL, timeout=300) + out = done.stdout + done.stderr + self.assertNotEqual(done.returncode, 0) + self.assertIn("bundled with the app", out) + self.assertIn("Step 5: downloading", out) + self.assertIn("Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", out) + self.assertFalse(log.exists(), "something ran pip, git, cmake or a package manager: " + (log.read_text() if log.exists() else "")) + + +if __name__ == "__main__": + unittest.main() From 1b6ed0898d8af53a5435503aeee8bbe5ae141b49 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 17:50:11 +0200 Subject: [PATCH 05/16] desktop: first-run-ui.mjs, headless Chrome on the packaged host's onboarding with the real catalog --- apps/desktop/scripts/first-run-ui.mjs | 121 ++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 apps/desktop/scripts/first-run-ui.mjs diff --git a/apps/desktop/scripts/first-run-ui.mjs b/apps/desktop/scripts/first-run-ui.mjs new file mode 100644 index 00000000..757905cd --- /dev/null +++ b/apps/desktop/scripts/first-run-ui.mjs @@ -0,0 +1,121 @@ +#!/usr/bin/env node +/** + * The first run of the installed app, headless: the host as the Tauri shell starts it (STRATA_PACKAGED=1, STRATA_NO_ACQUIRE=1, + * the staged Control, nothing installed, nothing in the per-user folders) and Chrome on its onboarding. + * + * node apps/desktop/scripts/first-run-ui.mjs [--control ] [--node ] [--work ] [--shots ] + * + * Checks, one line each (exit 1 if any fails): + * the host answers; /api/native has a real catalog (families with sizes), a recommendation and the GPUs of this PC + * (from Control's bundled installer on Control's Python); the page shows "Let's get started", and after it the model + * list with sizes (no "couldn't show this screen"); no page error; the install plan for the recommended model is a + * plan (nothing is downloaded or started: a plan changes nothing); the spy sees no pip/git/compiler/engine fetch. + * Per-user folders (STRATA_HOME, APPDATA, LOCALAPPDATA, the components and install folders) are all under --work. + * No model is downloaded and no engine runs. + */ +import { spawn } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') ? true : all[i + 1]]] : acc), [])); +const here = dirname(fileURLToPath(import.meta.url)); +const repoHost = resolve(here, '../../host'); +const staged = resolve(here, '../src-tauri/resources'); +const control = resolve(args.control ?? join(staged, 'control')); +const nodeExe = resolve(args.node ?? join(staged, 'node', process.platform === 'win32' ? 'node.exe' : 'node')); +const work = resolve(args.work ?? mkdtempSync(join(tmpdir(), 'strata-first-run-'))); +const shots = resolve(args.shots ?? join(work, 'shots')); +mkdirSync(work, { recursive: true }); mkdirSync(shots, { recursive: true }); +const spy = pathToFileURL(join(repoHost, 'tests/helpers/acquire-spy.mjs')).href; +const spyLog = join(work, 'spy.log'); writeFileSync(spyLog, ''); + +const { chromium } = await import(pathToFileURL(join(repoHost, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); +const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'].find(existsSync); + +let failed = false; +const check = (ok, label, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${detail ? ' ' + detail : ''}`); if (!ok) failed = true; }; +const delay = ms => new Promise(r => setTimeout(r, ms)); +const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }; + +for (const need of [nodeExe, join(control, 'strata.py'), join(repoHost, 'dist', 'index.html')]) if (!existsSync(need)) { console.error(`missing ${need} (run stage-control.py, fetch-node and "npm run build" in apps/host first)`); process.exit(2); } + +const dirs = { home: join(work, 'home'), appdata: join(work, 'appdata'), local: join(work, 'local'), components: join(work, 'local', 'Strata', 'components') }; +for (const d of Object.values(dirs)) mkdirSync(d, { recursive: true }); +const port = await freePort(); +const env = { + ...process.env, + STRATA_PORT: String(port), STRATA_DIST: join(repoHost, 'dist'), STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', + STRATA_CONTROL_DIR: control, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(work, 'models'), STRATA_COMPONENTS_DIR: dirs.components, + APPDATA: dirs.appdata, LOCALAPPDATA: dirs.local, XDG_CONFIG_HOME: join(work, 'xdg'), XDG_DATA_HOME: join(work, 'xdgdata'), + STRATA_PROFILE_DIR: join(work, 'profiles'), STRATA_RUNTIME_DIR: join(work, 'runtime'), ACQUIRE_SPY_LOG: spyLog, +}; +delete env.STRATA_INSTALL_DIR; +mkdirSync(env.STRATA_MODELS_DIR, { recursive: true }); +const host = spawn(nodeExe, [...(args['no-spy'] === undefined ? ['--import', spy] : []), join(repoHost, 'server', 'index.mjs')], { cwd: repoHost, env, stdio: ['ignore', 'pipe', 'pipe'] }); +let hostLog = ''; +host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; }); +const base = `http://127.0.0.1:${port}`; +const api = async (path, init) => { const r = await fetch(base + path, init); return { status: r.status, body: await r.json().catch(() => null) }; }; + +let browser; +try { + let up = false; + for (let i = 0; i < 150 && !up; i++) { try { up = (await api('/api/health')).status === 200; } catch { await delay(200); } } + check(up, 'the packaged host starts', `port ${port}`); + if (!up) throw new Error(hostLog.slice(-2000)); + + const native = await api('/api/native?refresh=1'); + const state = native.body; + check(native.status === 200 && state?.available === true, 'the host reads Control', state?.error ?? ''); + const sizes = (state?.catalog?.families ?? []).reduce((n, f) => n + (f.sizes?.length ?? 0), 0); + check((state?.catalog?.families?.length ?? 0) > 0 && sizes >= 3, 'the catalog has real families and sizes', `${state?.catalog?.families?.length} families, ${sizes} sizes`); + check(!!state?.catalog?.recommendation, 'the catalog has a recommendation', JSON.stringify(state?.catalog?.recommendation ?? null).slice(0, 120)); + check(Array.isArray(state?.hardware?.gpus), 'the hardware lists GPUs', (state?.hardware?.gpus ?? []).map(g => `${g.name} ${g.vram_gb} GB`).join('; ') || 'none on this PC'); + check(state?.installDir && realpathSync.native(state.installDir).toLowerCase().startsWith(realpathSync.native(work).toLowerCase()), 'models go to a writable per-user folder, not the bundle', state?.installDir); + const hw = (await api('/api/hardware')).body; + console.log('info host hardware probe:', JSON.stringify((hw?.gpus ?? []).map(g => ({ name: g.name, backend: g.backend, vramGb: g.vramGb, unified: g.unified })))); + check(!state?.installerError, 'the bundled installer answers', state?.installerError ?? ''); + + browser = await chromium.launch({ executablePath: CHROME, headless: true }); + const page = await browser.newPage({ viewport: { width: 1400, height: 950 } }); + const problems = []; + page.on('pageerror', e => problems.push(`pageerror: ${e.message}`)); + await page.goto(base, { waitUntil: 'domcontentloaded' }); + await page.waitForSelector('text=/Let.s get started|Choose a version|Connect your Strata/i', { timeout: 30000 }).catch(() => {}); + await page.screenshot({ path: join(shots, '1-welcome.png') }); + const broken = await page.locator('text=/couldn.t show this screen/i').count(); + check(broken === 0, 'the first screen renders (not "Strata couldn\'t show this screen")'); + const start = page.getByRole('button', { name: /get started/i }); + check(await start.count() > 0, 'the welcome step offers "Let\'s get started"'); + if (await start.count()) await start.first().click(); + await page.waitForSelector('text=/Choose a version/i', { timeout: 30000 }).catch(() => {}); + await delay(1200); + await page.screenshot({ path: join(shots, '2-models.png') }); + check(await page.locator('text=/couldn.t show this screen/i').count() === 0, 'the model step renders'); + check(await page.getByText(/Choose a version/i).count() > 0, 'the model step lists the versions'); + const labels = await page.locator('[role=radio]').allInnerTexts(); + check(labels.length >= 3, 'the versions are the real catalog\'s sizes', labels.map(l => l.replace(/\s+/g, ' ').slice(0, 40)).join(' | ')); + check(labels.some(l => /\d+\.\d\s*GB/.test(l)), 'each version shows its download size'); + check(problems.length === 0, 'no page error', problems.join('; ')); + + const recommended = state?.catalog?.recommendation; + if (recommended?.model) { + const plan = await api('/api/native/plan', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ family: recommended.family, model: recommended.model, context: recommended.context, data_dir: join(work, 'Strata-data') }) }); + check(plan.status === 200 && !!plan.body?.plan, 'the install plan for the recommended model is a plan (nothing downloaded)', plan.body?.summary?.slice(0, 100) ?? JSON.stringify(plan.body).slice(0, 150)); + check(!existsSync(join(work, 'Strata-data', 'models')), 'a plan wrote no model files'); + } +} catch (error) { + check(false, 'the run', String(error?.message ?? error).slice(0, 600)); +} finally { + await browser?.close().catch(() => {}); + host.kill(); + await new Promise(r => host.once('exit', r)); // only the PID this script started + const attempts = readFileSync(spyLog, 'utf8').split('\n').filter(Boolean); + check(attempts.length === 0, 'the spy saw no pip, git, compiler, engine or internet access', attempts.slice(0, 3).join(' ')); + console.log(`shots in ${shots}`); + if (!args.work) rmSync(work, { recursive: true, force: true, maxRetries: 3 }); +} +process.exit(failed ? 1 : 0); From 8a9d724e6e3a588422f90c17aac09d7bf19907f4 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 17:53:22 +0200 Subject: [PATCH 06/16] host: look for the Harness in the user's component folder too, not only when STRATA_COMPONENTS_DIR is set --- apps/host/server/index.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index ebd1313e..3756bc7f 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -86,7 +86,7 @@ const native=createNativeControl({control,directory:store.DATA_DIR,modelsDirecto state and the chat falls back to the direct path with a notice, never silently to another model. */ const agent = createAgentBridge({ dataDir: store.DATA_DIR, - componentsDir: process.env.STRATA_COMPONENTS_DIR ?? null, + componentsDir: componentsDirectory(), localInstances: () => native.readyInstances().map(i => ({ id: i.id, label: i.label, baseUrl: `http://127.0.0.1:${i.port}/v1`, modelId: i.apiModelId, context: i.metrics?.engine?.max_context ?? i.context ?? undefined, key: i.key, vision: i.vision, From 7b2082dbb0b05c827dc28ce84326dbcc08aea9a5 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 19:10:22 +0200 Subject: [PATCH 07/16] first-run feedback: combined download progress with an ETA, catalog without pictures for app installs, RAM budget for the 20% profile, human engine-start errors, installed model preferred in Models, system theme default, NSIS ignores a remembered temp install folder --- apps/desktop/src-tauri/nsis/installer.nsi | 1044 +++++++++++++++++++++ apps/desktop/src-tauri/tauri.conf.json | 1 + apps/host/index.html | 3 +- apps/host/server/native-control.mjs | 22 +- apps/host/server/native-resources.mjs | 12 +- apps/host/src/components/GuidedSetup.tsx | 6 +- apps/host/src/components/NativeModels.tsx | 17 +- apps/host/src/lib/download-eta.ts | 36 + apps/host/src/lib/store.ts | 2 +- apps/host/src/screens/Settings.tsx | 2 +- apps/host/src/styles/onboarding.css | 1 + apps/host/tests/packaged-control.test.mjs | 32 +- apps/host/tests/resource-ram.test.mjs | 31 + strata_control/runtime.py | 13 +- tests/desktop/test_control_install.py | 26 + tools/strata_mcp.py | 32 +- 16 files changed, 1256 insertions(+), 24 deletions(-) create mode 100644 apps/desktop/src-tauri/nsis/installer.nsi create mode 100644 apps/host/src/lib/download-eta.ts create mode 100644 apps/host/tests/resource-ram.test.mjs diff --git a/apps/desktop/src-tauri/nsis/installer.nsi b/apps/desktop/src-tauri/nsis/installer.nsi new file mode 100644 index 00000000..bcbb52d2 --- /dev/null +++ b/apps/desktop/src-tauri/nsis/installer.nsi @@ -0,0 +1,1044 @@ +Unicode true +ManifestDPIAware true +; Add in `dpiAwareness` `PerMonitorV2` to manifest for Windows 10 1607+ (note this should not affect lower versions since they should be able to ignore this and pick up `dpiAware` `true` set by `ManifestDPIAware true`) +; Currently undocumented on NSIS's website but is in the Docs folder of source tree, see +; https://github.com/kichik/nsis/blob/5fc0b87b819a9eec006df4967d08e522ddd651c9/Docs/src/attributes.but#L286-L300 +; https://github.com/tauri-apps/tauri/pull/10106 +ManifestDPIAwareness PerMonitorV2 + +!if "{{compression}}" == "none" + SetCompress off +!else + ; Set the compression algorithm. We default to LZMA. + SetCompressor /SOLID "{{compression}}" +!endif + +; Keep above !include to stay ahead of any plugin command +; see https://github.com/tauri-apps/tauri/pull/15422#discussion_r3289239624 +{{#if signed_plugins_path}} +!addplugindir "{{signed_plugins_path}}" +{{/if}} + +!include MUI2.nsh +!include FileFunc.nsh +!include x64.nsh +!include WordFunc.nsh +!include "utils.nsh" +!include "FileAssociation.nsh" +!include "Win\COM.nsh" +!include "Win\Propkey.nsh" +!include "Win\RestartManager.nsh" +!include "StrFunc.nsh" +${StrCase} +${StrLoc} + +{{#if installer_hooks}} +!include "{{installer_hooks}}" +{{/if}} + +!define WEBVIEW2APPGUID "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" + +!define MANUFACTURER "{{manufacturer}}" +!define PRODUCTNAME "{{product_name}}" +!define VERSION "{{version}}" +!define VERSIONWITHBUILD "{{version_with_build}}" +!define HOMEPAGE "{{homepage}}" +!define INSTALLMODE "{{install_mode}}" +!define LICENSE "{{license}}" +!define INSTALLERICON "{{installer_icon}}" +!define SIDEBARIMAGE "{{sidebar_image}}" +!define HEADERIMAGE "{{header_image}}" +!define UNINSTALLERICON "{{uninstaller_icon}}" +!define UNINSTALLERHEADERIMAGE "{{uninstaller_header_image}}" +!define MAINBINARYNAME "{{main_binary_name}}" +!define MAINBINARYSRCPATH "{{main_binary_path}}" +!define BUNDLEID "{{bundle_id}}" +!define COPYRIGHT "{{copyright}}" +!define OUTFILE "{{out_file}}" +!define ARCH "{{arch}}" +!define ADDITIONALPLUGINSPATH "{{additional_plugins_path}}" +!define ALLOWDOWNGRADES "{{allow_downgrades}}" +!define DISPLAYLANGUAGESELECTOR "{{display_language_selector}}" +!define INSTALLWEBVIEW2MODE "{{install_webview2_mode}}" +!define WEBVIEW2INSTALLERARGS "{{webview2_installer_args}}" +!define WEBVIEW2BOOTSTRAPPERPATH "{{webview2_bootstrapper_path}}" +!define WEBVIEW2INSTALLERPATH "{{webview2_installer_path}}" +!define MINIMUMWEBVIEW2VERSION "{{minimum_webview2_version}}" +!define UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCTNAME}" +!define MANUKEY "Software\${MANUFACTURER}" +!define MANUPRODUCTKEY "${MANUKEY}\${PRODUCTNAME}" +!define UNINSTALLERSIGNCOMMAND "{{uninstaller_sign_cmd}}" +!define ESTIMATEDSIZE "{{estimated_size}}" +!define STARTMENUFOLDER "{{start_menu_folder}}" + +Var PassiveMode +Var UpdateMode +Var NoShortcutMode +Var WixMode +Var OldMainBinaryName + +Name "${PRODUCTNAME}" +BrandingText "${COPYRIGHT}" +OutFile "${OUTFILE}" + +; We don't actually use this value as default install path, +; it's just for nsis to append the product name folder in the directory selector +; https://nsis.sourceforge.io/Reference/InstallDir +!define PLACEHOLDER_INSTALL_DIR "placeholder\${PRODUCTNAME}" +InstallDir "${PLACEHOLDER_INSTALL_DIR}" + +VIProductVersion "${VERSIONWITHBUILD}" +VIAddVersionKey "ProductName" "${PRODUCTNAME}" +VIAddVersionKey "FileDescription" "${PRODUCTNAME}" +VIAddVersionKey "LegalCopyright" "${COPYRIGHT}" +VIAddVersionKey "FileVersion" "${VERSION}" +VIAddVersionKey "ProductVersion" "${VERSION}" + +# additional plugins +!addplugindir "${ADDITIONALPLUGINSPATH}" + +; Uninstaller signing command +!if "${UNINSTALLERSIGNCOMMAND}" != "" + !uninstfinalize '${UNINSTALLERSIGNCOMMAND}' +!endif + +; Handle install mode, `perUser`, `perMachine` or `both` +!if "${INSTALLMODE}" == "perMachine" + RequestExecutionLevel admin +!endif + +!if "${INSTALLMODE}" == "currentUser" + RequestExecutionLevel user +!endif + +!if "${INSTALLMODE}" == "both" + !define MULTIUSER_MUI + !define MULTIUSER_INSTALLMODE_INSTDIR "${PRODUCTNAME}" + !define MULTIUSER_INSTALLMODE_COMMANDLINE + !if "${ARCH}" == "x64" + !define MULTIUSER_USE_PROGRAMFILES64 + !else if "${ARCH}" == "arm64" + !define MULTIUSER_USE_PROGRAMFILES64 + !endif + !define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_KEY "${UNINSTKEY}" + !define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_VALUENAME "CurrentUser" + !define MULTIUSER_INSTALLMODEPAGE_SHOWUSERNAME + !define MULTIUSER_INSTALLMODE_FUNCTION RestorePreviousInstallLocation + !define MULTIUSER_EXECUTIONLEVEL Highest + !include MultiUser.nsh +!endif + +; Installer icon +!if "${INSTALLERICON}" != "" + !define MUI_ICON "${INSTALLERICON}" +!endif + +; Installer sidebar image +!if "${SIDEBARIMAGE}" != "" + !define MUI_WELCOMEFINISHPAGE_BITMAP "${SIDEBARIMAGE}" +!endif + +; Enable header images for installer and uninstaller pages when either image is configured. +!if "${HEADERIMAGE}" != "" + !define MUI_HEADERIMAGE +!else if "${UNINSTALLERHEADERIMAGE}" != "" + !define MUI_HEADERIMAGE +!endif + +; Installer header image +!if "${HEADERIMAGE}" != "" + !define MUI_HEADERIMAGE_BITMAP "${HEADERIMAGE}" +!endif + +; Uninstaller header image +!if "${UNINSTALLERHEADERIMAGE}" != "" + !define MUI_HEADERIMAGE_UNBITMAP "${UNINSTALLERHEADERIMAGE}" +!endif + +; Uninstaller icon +!if "${UNINSTALLERICON}" != "" + !define MUI_UNICON "${UNINSTALLERICON}" +!endif + +; Define registry key to store installer language +!define MUI_LANGDLL_REGISTRY_ROOT "HKCU" +!define MUI_LANGDLL_REGISTRY_KEY "${MANUPRODUCTKEY}" +!define MUI_LANGDLL_REGISTRY_VALUENAME "Installer Language" + +; Installer pages, must be ordered as they appear +; 1. Welcome Page +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MUI_PAGE_WELCOME + +; 2. License Page (if defined) +!if "${LICENSE}" != "" + !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive + !insertmacro MUI_PAGE_LICENSE "${LICENSE}" +!endif + +; 3. Install mode (if it is set to `both`) +!if "${INSTALLMODE}" == "both" + !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive + !insertmacro MULTIUSER_PAGE_INSTALLMODE +!endif + +; 4. Custom page to ask user if he wants to reinstall/uninstall +; only if a previous installation was detected +Var ReinstallPageCheck +Page custom PageReinstall PageLeaveReinstall +Function PageReinstall + ; Uninstall previous WiX installation if exists. + ; + ; A WiX installer stores the installation info in registry + ; using a UUID and so we have to loop through all keys under + ; `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall` + ; and check if `DisplayName` and `Publisher` keys match ${PRODUCTNAME} and ${MANUFACTURER} + ; + ; This has a potential issue that there maybe another installation that matches + ; our ${PRODUCTNAME} and ${MANUFACTURER} but wasn't installed by our WiX installer, + ; however, this should be fine since the user will have to confirm the uninstallation + ; and they can chose to abort it if doesn't make sense. + StrCpy $0 0 + wix_loop: + EnumRegKey $1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" $0 + StrCmp $1 "" wix_loop_done ; Exit loop if there is no more keys to loop on + IntOp $0 $0 + 1 + ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "DisplayName" + ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "Publisher" + StrCmp "$R0$R1" "${PRODUCTNAME}${MANUFACTURER}" 0 wix_loop + ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "UninstallString" + ${StrCase} $R1 $R0 "L" + ${StrLoc} $R0 $R1 "msiexec" ">" + StrCmp $R0 0 0 wix_loop_done + StrCpy $WixMode 1 + StrCpy $R6 "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" + Goto compare_version + wix_loop_done: + + ; Check if there is an existing installation, if not, abort the reinstall page + ReadRegStr $R0 SHCTX "${UNINSTKEY}" "" + ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString" + ${IfThen} "$R0$R1" == "" ${|} Abort ${|} + + ; Compare this installar version with the existing installation + ; and modify the messages presented to the user accordingly + compare_version: + StrCpy $R4 "$(older)" + ${If} $WixMode = 1 + ReadRegStr $R0 HKLM "$R6" "DisplayVersion" + ${Else} + ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion" + ${EndIf} + ${IfThen} $R0 == "" ${|} StrCpy $R4 "$(unknown)" ${|} + + nsis_tauri_utils::SemverCompare "${VERSION}" $R0 + Pop $R0 + ; Reinstalling the same version + ${If} $R0 = 0 + StrCpy $R1 "$(alreadyInstalledLong)" + StrCpy $R2 "$(addOrReinstall)" + StrCpy $R3 "$(uninstallApp)" + !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(chooseMaintenanceOption)" + ; Upgrading + ${ElseIf} $R0 = 1 + StrCpy $R1 "$(olderOrUnknownVersionInstalled)" + StrCpy $R2 "$(uninstallBeforeInstalling)" + StrCpy $R3 "$(dontUninstall)" + !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)" + ; Downgrading + ${ElseIf} $R0 = -1 + StrCpy $R1 "$(newerVersionInstalled)" + StrCpy $R2 "$(uninstallBeforeInstalling)" + !if "${ALLOWDOWNGRADES}" == "true" + StrCpy $R3 "$(dontUninstall)" + !else + StrCpy $R3 "$(dontUninstallDowngrade)" + !endif + !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)" + ${Else} + Abort + ${EndIf} + + ; Skip showing the page if passive + ; + ; Note that we don't call this earlier at the beginning + ; of this function because we need to populate some variables + ; related to current installed version if detected and whether + ; we are downgrading or not. + ${If} $PassiveMode = 1 + Call PageLeaveReinstall + ${Else} + nsDialogs::Create 1018 + Pop $R4 + ${IfThen} $(^RTL) = 1 ${|} nsDialogs::SetRTL $(^RTL) ${|} + + ${NSD_CreateLabel} 0 0 100% 24u $R1 + Pop $R1 + + ${NSD_CreateRadioButton} 30u 50u -30u 8u $R2 + Pop $R2 + ${NSD_OnClick} $R2 PageReinstallUpdateSelection + + ${NSD_CreateRadioButton} 30u 70u -30u 8u $R3 + Pop $R3 + ; Disable this radio button if downgrading and downgrades are disabled + !if "${ALLOWDOWNGRADES}" == "false" + ${IfThen} $R0 = -1 ${|} EnableWindow $R3 0 ${|} + !endif + ${NSD_OnClick} $R3 PageReinstallUpdateSelection + + ; Check the first radio button if this the first time + ; we enter this page or if the second button wasn't + ; selected the last time we were on this page + ${If} $ReinstallPageCheck <> 2 + SendMessage $R2 ${BM_SETCHECK} ${BST_CHECKED} 0 + ${Else} + SendMessage $R3 ${BM_SETCHECK} ${BST_CHECKED} 0 + ${EndIf} + + ${NSD_SetFocus} $R2 + nsDialogs::Show + ${EndIf} +FunctionEnd +Function PageReinstallUpdateSelection + ${NSD_GetState} $R2 $R1 + ${If} $R1 == ${BST_CHECKED} + StrCpy $ReinstallPageCheck 1 + ${Else} + StrCpy $ReinstallPageCheck 2 + ${EndIf} +FunctionEnd +Function PageLeaveReinstall + ${NSD_GetState} $R2 $R1 + + ; If migrating from Wix, always uninstall + ${If} $WixMode = 1 + Goto reinst_uninstall + ${EndIf} + + ; In update mode, always proceeds without uninstalling + ${If} $UpdateMode = 1 + Goto reinst_done + ${EndIf} + + ; $R0 holds whether same(0)/upgrading(1)/downgrading(-1) version + ; $R1 holds the radio buttons state: + ; 1 => first choice was selected + ; 0 => second choice was selected + ${If} $R0 = 0 ; Same version, proceed + ${If} $R1 = 1 ; User chose to add/reinstall + Goto reinst_done + ${Else} ; User chose to uninstall + Goto reinst_uninstall + ${EndIf} + ${ElseIf} $R0 = 1 ; Upgrading + ${If} $R1 = 1 ; User chose to uninstall + Goto reinst_uninstall + ${Else} + Goto reinst_done ; User chose NOT to uninstall + ${EndIf} + ${ElseIf} $R0 = -1 ; Downgrading + ${If} $R1 = 1 ; User chose to uninstall + Goto reinst_uninstall + ${Else} + Goto reinst_done ; User chose NOT to uninstall + ${EndIf} + ${EndIf} + + reinst_uninstall: + HideWindow + ClearErrors + + ${If} $WixMode = 1 + ReadRegStr $R1 HKLM "$R6" "UninstallString" + ExecWait '$R1' $0 + ${Else} + ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" "" + ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString" + ${IfThen} $UpdateMode = 1 ${|} StrCpy $R1 "$R1 /UPDATE" ${|} ; append /UPDATE + ${IfThen} $PassiveMode = 1 ${|} StrCpy $R1 "$R1 /P" ${|} ; append /P + StrCpy $R1 "$R1 _?=$4" ; append uninstall directory + ExecWait '$R1' $0 + ${EndIf} + + BringToFront + + ${IfThen} ${Errors} ${|} StrCpy $0 2 ${|} ; ExecWait failed, set fake exit code + + ${If} $0 <> 0 + ${OrIf} ${FileExists} "$INSTDIR\${MAINBINARYNAME}.exe" + ; User cancelled wix uninstaller? return to select un/reinstall page + ${If} $WixMode = 1 + ${AndIf} $0 = 1602 + Abort + ${EndIf} + + ; User cancelled NSIS uninstaller? return to select un/reinstall page + ${If} $0 = 1 + Abort + ${EndIf} + + ; Other errors? show generic error message and return to select un/reinstall page + MessageBox MB_ICONEXCLAMATION "$(unableToUninstall)" + Abort + ${EndIf} + + ; The NSIS uninstaller was run in place (`_?=`), so it cannot delete itself + ; and the install directory, clean them up here once the uninstall succeeded + ; https://nsis.sourceforge.io/Docs/Chapter3.html#:~:text=path%20contains%20spaces.-,3.2.3%20Examples,-installer.exe%20/NCRC + ${If} $WixMode = 0 + ${AndIf} $4 != "" + Delete "$4\uninstall.exe" + RMDir "$4" + ${EndIf} + reinst_done: +FunctionEnd + +; 5. Choose install directory page +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MUI_PAGE_DIRECTORY + +; 6. Start menu shortcut page +Var AppStartMenuFolder +!if "${STARTMENUFOLDER}" != "" + !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive + !define MUI_STARTMENUPAGE_DEFAULTFOLDER "${STARTMENUFOLDER}" +!else + !define MUI_PAGE_CUSTOMFUNCTION_PRE Skip +!endif +!insertmacro MUI_PAGE_STARTMENU Application $AppStartMenuFolder + +; 7. Installation page +!insertmacro MUI_PAGE_INSTFILES + +; 8. Finish page +; +; Don't auto jump to finish page after installation page, +; because the installation page has useful info that can be used debug any issues with the installer. +!define MUI_FINISHPAGE_NOAUTOCLOSE +; Use show readme button in the finish page as a button create a desktop shortcut +!define MUI_FINISHPAGE_SHOWREADME +!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(createDesktop)" +!define MUI_FINISHPAGE_SHOWREADME_FUNCTION CreateOrUpdateDesktopShortcut +; Show run app after installation. +!define MUI_FINISHPAGE_RUN +!define MUI_FINISHPAGE_RUN_FUNCTION RunMainBinary +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MUI_PAGE_FINISH + +Function RunMainBinary + nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" "" +FunctionEnd + +; Uninstaller Pages +; 1. Confirm uninstall page +Var DeleteAppDataCheckbox +Var DeleteAppDataCheckboxState +!define /ifndef WS_EX_LAYOUTRTL 0x00400000 +!define MUI_PAGE_CUSTOMFUNCTION_SHOW un.ConfirmShow +Function un.ConfirmShow ; Add add a `Delete app data` check box + ; $1 inner dialog HWND + ; $2 window DPI + ; $3 style + ; $4 x + ; $5 y + ; $6 width + ; $7 height + FindWindow $1 "#32770" "" $HWNDPARENT ; Find inner dialog + System::Call "user32::GetDpiForWindow(p r1) i .r2" + ${If} $(^RTL) = 1 + StrCpy $3 "${__NSD_CheckBox_EXSTYLE} | ${WS_EX_LAYOUTRTL}" + IntOp $4 50 * $2 + ${Else} + StrCpy $3 "${__NSD_CheckBox_EXSTYLE}" + IntOp $4 0 * $2 + ${EndIf} + IntOp $5 100 * $2 + IntOp $6 400 * $2 + IntOp $7 25 * $2 + IntOp $4 $4 / 96 + IntOp $5 $5 / 96 + IntOp $6 $6 / 96 + IntOp $7 $7 / 96 + System::Call 'user32::CreateWindowEx(i r3, w "${__NSD_CheckBox_CLASS}", w "$(deleteAppData)", i ${__NSD_CheckBox_STYLE}, i r4, i r5, i r6, i r7, p r1, i0, i0, i0) i .s' + Pop $DeleteAppDataCheckbox + SendMessage $HWNDPARENT ${WM_GETFONT} 0 0 $1 + SendMessage $DeleteAppDataCheckbox ${WM_SETFONT} $1 1 +FunctionEnd +!define MUI_PAGE_CUSTOMFUNCTION_LEAVE un.ConfirmLeave +Function un.ConfirmLeave + SendMessage $DeleteAppDataCheckbox ${BM_GETCHECK} 0 0 $DeleteAppDataCheckboxState +FunctionEnd +!define MUI_PAGE_CUSTOMFUNCTION_PRE un.SkipIfPassive +!insertmacro MUI_UNPAGE_CONFIRM + +; 2. Uninstalling Page +!insertmacro MUI_UNPAGE_INSTFILES + +;Languages +{{#each languages}} +!insertmacro MUI_LANGUAGE "{{this}}" +{{/each}} +!insertmacro MUI_RESERVEFILE_LANGDLL +{{#each language_files}} + !include "{{this}}" +{{/each}} + +Function .onInit + ${GetOptions} $CMDLINE "/P" $PassiveMode + ${IfNot} ${Errors} + StrCpy $PassiveMode 1 + ${EndIf} + + ${GetOptions} $CMDLINE "/NS" $NoShortcutMode + ${IfNot} ${Errors} + StrCpy $NoShortcutMode 1 + ${EndIf} + + ${GetOptions} $CMDLINE "/UPDATE" $UpdateMode + ${IfNot} ${Errors} + StrCpy $UpdateMode 1 + ${EndIf} + + !if "${DISPLAYLANGUAGESELECTOR}" == "true" + !insertmacro MUI_LANGDLL_DISPLAY + !endif + + !insertmacro SetContext + + ${If} $INSTDIR == "${PLACEHOLDER_INSTALL_DIR}" + ; Set default install location + !if "${INSTALLMODE}" == "perMachine" + ${If} ${RunningX64} + !if "${ARCH}" == "x64" + StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}" + !else if "${ARCH}" == "arm64" + StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}" + !else + StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}" + !endif + ${Else} + StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}" + ${EndIf} + !else if "${INSTALLMODE}" == "currentUser" + StrCpy $INSTDIR "$LOCALAPPDATA\${PRODUCTNAME}" + !endif + + Call RestorePreviousInstallLocation + ${EndIf} + + + !if "${INSTALLMODE}" == "both" + !insertmacro MULTIUSER_INIT + !endif + + ; Abort downgrades if they are disabled, in the modes that skip the reinstall page choice: + ; silent, passive and update + !if "${ALLOWDOWNGRADES}" == "false" + ${If} ${Silent} + ${OrIf} $PassiveMode = 1 + ${OrIf} $UpdateMode = 1 + ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion" + nsis_tauri_utils::SemverCompare "${VERSION}" $R0 + Pop $R0 + ; If downgrading + ${If} $R0 = -1 + ${If} ${Silent} + System::Call 'kernel32::AttachConsole(i -1)i.r0' + ${If} $0 <> 0 + System::Call 'kernel32::GetStdHandle(i -11)i.r0' + System::call 'kernel32::SetConsoleTextAttribute(i r0, i 0x0004)' ; set red color + FileWrite $0 "$(silentDowngrades)" + ${EndIf} + ${Else} + MessageBox MB_ICONSTOP "$(silentDowngrades)" + ${EndIf} + Abort + ${EndIf} + ${EndIf} + !endif +FunctionEnd + +Section WebView2 + ; Check if Webview2 is already installed and skip this section + ${If} ${RunningX64} + ReadRegStr $4 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${Else} + ReadRegStr $4 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${EndIf} + ${If} $4 == "" + ReadRegStr $4 HKCU "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${EndIf} + + ${If} $4 == "" + ; Webview2 installation + ; + ; Skip if updating + ${If} $UpdateMode <> 1 + !if "${INSTALLWEBVIEW2MODE}" == "downloadBootstrapper" + Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe" + DetailPrint "$(webview2Downloading)" + NSISdl::download "https://go.microsoft.com/fwlink/p/?LinkId=2124703" "$TEMP\MicrosoftEdgeWebview2Setup.exe" + Pop $0 + ${If} $0 == "success" + DetailPrint "$(webview2DownloadSuccess)" + ${Else} + DetailPrint "$(webview2DownloadError)" + Abort "$(webview2AbortError)" + ${EndIf} + StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe" + Goto install_webview2 + !endif + + !if "${INSTALLWEBVIEW2MODE}" == "embedBootstrapper" + Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe" + File "/oname=$TEMP\MicrosoftEdgeWebview2Setup.exe" "${WEBVIEW2BOOTSTRAPPERPATH}" + DetailPrint "$(installingWebview2)" + StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe" + Goto install_webview2 + !endif + + !if "${INSTALLWEBVIEW2MODE}" == "offlineInstaller" + Delete "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" + File "/oname=$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" "${WEBVIEW2INSTALLERPATH}" + DetailPrint "$(installingWebview2)" + StrCpy $6 "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" + Goto install_webview2 + !endif + + Goto webview2_done + + install_webview2: + DetailPrint "$(installingWebview2)" + ; $6 holds the path to the webview2 installer + ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $1 + ${If} $1 = 0 + DetailPrint "$(webview2InstallSuccess)" + ${Else} + DetailPrint "$(webview2InstallError)" + Abort "$(webview2AbortError)" + ${EndIf} + webview2_done: + ${EndIf} + ${Else} + !if "${MINIMUMWEBVIEW2VERSION}" != "" + ${VersionCompare} "${MINIMUMWEBVIEW2VERSION}" "$4" $R0 + ${If} $R0 = 1 + update_webview: + DetailPrint "$(installingWebview2)" + ${If} ${RunningX64} + ReadRegStr $R1 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate" "path" + ${Else} + ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\EdgeUpdate" "path" + ${EndIf} + ${If} $R1 == "" + ReadRegStr $R1 HKCU "SOFTWARE\Microsoft\EdgeUpdate" "path" + ${EndIf} + ${If} $R1 != "" + ; Chromium updater docs: https://source.chromium.org/chromium/chromium/src/+/main:docs/updater/user_manual.md + ; Modified from "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft EdgeWebView\ModifyPath" + ExecWait `"$R1" /install appguid=${WEBVIEW2APPGUID}&needsadmin=true` $1 + ${If} $1 = 0 + DetailPrint "$(webview2InstallSuccess)" + ${Else} + MessageBox MB_ICONEXCLAMATION|MB_ABORTRETRYIGNORE "$(webview2InstallError)" IDIGNORE ignore IDRETRY update_webview + Quit + ignore: + ${EndIf} + ${EndIf} + ${EndIf} + !endif + ${EndIf} +SectionEnd + +Section Install + SetOutPath $INSTDIR + + !ifmacrodef NSIS_HOOK_PREINSTALL + !insertmacro NSIS_HOOK_PREINSTALL + !endif + + !insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}" + + ; Copy main executable + File "${MAINBINARYSRCPATH}" + + ; Copy resources + {{#each resources_dirs}} + CreateDirectory "$INSTDIR\\{{this}}" + {{/each}} + {{#each resources}} + File /a "/oname={{this.[1]}}" "{{no-escape @key}}" + {{/each}} + + ; Copy external binaries + {{#each binaries}} + File /a "/oname={{this}}" "{{no-escape @key}}" + {{/each}} + + ; Create file associations + {{#each file_associations as |association| ~}} + {{#each association.ext as |ext| ~}} + !insertmacro APP_ASSOCIATE "{{ext}}" "{{or association.name ext}}" "{{association-description association.description ext}}" "$INSTDIR\${MAINBINARYNAME}.exe,0" "Open with ${PRODUCTNAME}" "$INSTDIR\${MAINBINARYNAME}.exe $\"%1$\"" + {{/each}} + {{/each}} + + ; Register deep links + {{#each deep_link_protocols as |protocol| ~}} + WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "URL Protocol" "" + WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "" "URL:${BUNDLEID} protocol" + WriteRegStr SHCTX "Software\Classes\\{{protocol}}\DefaultIcon" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\",0" + WriteRegStr SHCTX "Software\Classes\\{{protocol}}\shell\open\command" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\"" + {{/each}} + + ; Create uninstaller + WriteUninstaller "$INSTDIR\uninstall.exe" + + ; Save $INSTDIR in registry for future installations + WriteRegStr SHCTX "${MANUPRODUCTKEY}" "" $INSTDIR + + !if "${INSTALLMODE}" == "both" + ; Save install mode to be selected by default for the next installation such as updating + ; or when uninstalling + WriteRegStr SHCTX "${UNINSTKEY}" $MultiUser.InstallMode 1 + !endif + + ; Remove old main binary if it doesn't match new main binary name + ReadRegStr $OldMainBinaryName SHCTX "${UNINSTKEY}" "MainBinaryName" + ${If} $OldMainBinaryName != "" + ${AndIf} $OldMainBinaryName != "${MAINBINARYNAME}.exe" + Delete "$INSTDIR\$OldMainBinaryName" + ${EndIf} + + ; Save current MAINBINARYNAME for future updates + WriteRegStr SHCTX "${UNINSTKEY}" "MainBinaryName" "${MAINBINARYNAME}.exe" + + ; Registry information for add/remove programs + WriteRegStr SHCTX "${UNINSTKEY}" "DisplayName" "${PRODUCTNAME}" + WriteRegStr SHCTX "${UNINSTKEY}" "DisplayIcon" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\"" + WriteRegStr SHCTX "${UNINSTKEY}" "DisplayVersion" "${VERSION}" + WriteRegStr SHCTX "${UNINSTKEY}" "Publisher" "${MANUFACTURER}" + WriteRegStr SHCTX "${UNINSTKEY}" "InstallLocation" "$\"$INSTDIR$\"" + WriteRegStr SHCTX "${UNINSTKEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\"" + WriteRegDWORD SHCTX "${UNINSTKEY}" "NoModify" "1" + WriteRegDWORD SHCTX "${UNINSTKEY}" "NoRepair" "1" + + ${GetSize} "$INSTDIR" "/M=uninstall.exe /S=0K /G=0" $0 $1 $2 + IntOp $0 $0 + ${ESTIMATEDSIZE} + IntFmt $0 "0x%08X" $0 + WriteRegDWORD SHCTX "${UNINSTKEY}" "EstimatedSize" "$0" + + !if "${HOMEPAGE}" != "" + WriteRegStr SHCTX "${UNINSTKEY}" "URLInfoAbout" "${HOMEPAGE}" + WriteRegStr SHCTX "${UNINSTKEY}" "URLUpdateInfo" "${HOMEPAGE}" + WriteRegStr SHCTX "${UNINSTKEY}" "HelpLink" "${HOMEPAGE}" + !endif + + ; Create start menu shortcut + !insertmacro MUI_STARTMENU_WRITE_BEGIN Application + Call CreateOrUpdateStartMenuShortcut + !insertmacro MUI_STARTMENU_WRITE_END + + ; Create desktop shortcut for silent and passive installers + ; because finish page will be skipped + ${If} $PassiveMode = 1 + ${OrIf} ${Silent} + Call CreateOrUpdateDesktopShortcut + ${EndIf} + + !ifmacrodef NSIS_HOOK_POSTINSTALL + !insertmacro NSIS_HOOK_POSTINSTALL + !endif + + ; Auto close this page for passive mode + ${If} $PassiveMode = 1 + SetAutoClose true + ${EndIf} +SectionEnd + +Function .onInstSuccess + ; Check for `/R` flag only in silent and passive installers because + ; GUI installer has a toggle for the user to (re)start the app + ${If} $PassiveMode = 1 + ${OrIf} ${Silent} + ${GetOptions} $CMDLINE "/R" $R0 + ${IfNot} ${Errors} + ${GetOptions} $CMDLINE "/ARGS" $R0 + nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" "$R0" + ${EndIf} + ${EndIf} +FunctionEnd + +Function un.onInit + !insertmacro SetContext + + !if "${INSTALLMODE}" == "both" + !insertmacro MULTIUSER_UNINIT + !endif + + !insertmacro MUI_UNGETLANGUAGE + + ${GetOptions} $CMDLINE "/P" $PassiveMode + ${IfNot} ${Errors} + StrCpy $PassiveMode 1 + ${EndIf} + + ${GetOptions} $CMDLINE "/UPDATE" $UpdateMode + ${IfNot} ${Errors} + StrCpy $UpdateMode 1 + ${EndIf} +FunctionEnd + +Section Uninstall + + !ifmacrodef NSIS_HOOK_PREUNINSTALL + !insertmacro NSIS_HOOK_PREUNINSTALL + !endif + + !insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}" + + ; Delete the app directory and its content from disk + ; Copy main executable + Delete "$INSTDIR\${MAINBINARYNAME}.exe" + + ; Delete resources + {{#each resources}} + Delete "$INSTDIR\\{{this.[1]}}" + {{/each}} + + ; Delete external binaries + {{#each binaries}} + Delete "$INSTDIR\\{{this}}" + {{/each}} + + ; Delete app associations + {{#each file_associations as |association| ~}} + {{#each association.ext as |ext| ~}} + !insertmacro APP_UNASSOCIATE "{{ext}}" "{{or association.name ext}}" + {{/each}} + {{/each}} + + ; Delete deep links + {{#each deep_link_protocols as |protocol| ~}} + ReadRegStr $R7 SHCTX "Software\Classes\\{{protocol}}\shell\open\command" "" + ${If} $R7 == "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\"" + DeleteRegKey SHCTX "Software\Classes\\{{protocol}}" + ${EndIf} + {{/each}} + + + ; Delete uninstaller + Delete "$INSTDIR\uninstall.exe" + + {{#each resources_ancestors}} + RMDir /REBOOTOK "$INSTDIR\\{{this}}" + {{/each}} + RMDir "$INSTDIR" + + ; Remove shortcuts if not updating + ${If} $UpdateMode <> 1 + !insertmacro DeleteAppUserModelId + + ; Remove start menu shortcut + !insertmacro MUI_STARTMENU_GETFOLDER Application $AppStartMenuFolder + !insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + Pop $0 + ${If} $0 = 1 + !insertmacro UnpinShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" + Delete "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" + RMDir "$SMPROGRAMS\$AppStartMenuFolder" + ${EndIf} + !insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + Pop $0 + ${If} $0 = 1 + !insertmacro UnpinShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk" + Delete "$SMPROGRAMS\${PRODUCTNAME}.lnk" + ${EndIf} + + ; Remove desktop shortcuts + !insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + Pop $0 + ${If} $0 = 1 + !insertmacro UnpinShortcut "$DESKTOP\${PRODUCTNAME}.lnk" + Delete "$DESKTOP\${PRODUCTNAME}.lnk" + ${EndIf} + ${EndIf} + + ; Remove registry information for add/remove programs + !if "${INSTALLMODE}" == "both" + DeleteRegKey SHCTX "${UNINSTKEY}" + !else if "${INSTALLMODE}" == "perMachine" + DeleteRegKey HKLM "${UNINSTKEY}" + !else + DeleteRegKey HKCU "${UNINSTKEY}" + !endif + + ; Removes the Autostart entry for ${PRODUCTNAME} from the HKCU Run key if it exists. + ; This ensures the program does not launch automatically after uninstallation if it exists. + ; If it doesn't exist, it does nothing. + ; We do this when not updating (to preserve the registry value on updates) + ${If} $UpdateMode <> 1 + DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}" + ${EndIf} + + ; Delete app data if the checkbox is selected + ; and if not updating + ${If} $DeleteAppDataCheckboxState = 1 + ${AndIf} $UpdateMode <> 1 + ; Clear the install location $INSTDIR from registry + DeleteRegKey SHCTX "${MANUPRODUCTKEY}" + DeleteRegKey /ifempty SHCTX "${MANUKEY}" + + ; Clear the install language from registry + DeleteRegValue HKCU "${MANUPRODUCTKEY}" "Installer Language" + DeleteRegKey /ifempty HKCU "${MANUPRODUCTKEY}" + DeleteRegKey /ifempty HKCU "${MANUKEY}" + + SetShellVarContext current + RmDir /r "$APPDATA\${BUNDLEID}" + RmDir /r "$LOCALAPPDATA\${BUNDLEID}" + ${EndIf} + + !ifmacrodef NSIS_HOOK_POSTUNINSTALL + !insertmacro NSIS_HOOK_POSTUNINSTALL + !endif + + ; Auto close if passive mode or updating + ${If} $PassiveMode = 1 + ${OrIf} $UpdateMode = 1 + SetAutoClose true + ${EndIf} +SectionEnd + +; StrIsUnder: Push path, Push folder, Call StrIsUnder, Pop result ("1" when path is the folder or inside it; case-insensitive, +; whole path segments only). +Function StrIsUnder + Exch $1 ; folder + Exch + Exch $0 ; path + Push $2 + Push $3 + StrCpy $R9 0 + StrCmp $1 "" under_done 0 + StrLen $2 $1 + StrCpy $3 $0 $2 + StrCmp $3 $1 0 under_done + StrCpy $3 $0 1 $2 + StrCmp $3 "" under_yes 0 + StrCmp $3 "\" under_yes under_done + under_yes: + StrCpy $R9 1 + under_done: + Pop $3 + Pop $2 + Pop $0 + Pop $1 + Push $R9 +FunctionEnd + +; Strata: the install folder remembered in the registry is only reused when it is a real place for an app. A location under the +; temp folders (a test install, a build machine's scratch run) is ignored and the default per-user folder is used instead. +Function RestorePreviousInstallLocation + ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" "" + StrCmp $4 "" restore_done 0 + Push $4 + Push "$LOCALAPPDATA\Temp" + Call StrIsUnder + Pop $5 + StrCmp $5 1 restore_done 0 + Push $4 + Push "$TEMP" + Call StrIsUnder + Pop $5 + StrCmp $5 1 restore_done 0 + ReadEnvStr $6 TMP + Push $4 + Push $6 + Call StrIsUnder + Pop $5 + StrCmp $5 1 restore_done 0 + ReadEnvStr $6 TEMP + Push $4 + Push $6 + Call StrIsUnder + Pop $5 + StrCmp $5 1 restore_done 0 + StrCpy $INSTDIR $4 + restore_done: +FunctionEnd + +Function Skip + Abort +FunctionEnd + +Function SkipIfPassive + ${IfThen} $PassiveMode = 1 ${|} Abort ${|} +FunctionEnd +Function un.SkipIfPassive + ${IfThen} $PassiveMode = 1 ${|} Abort ${|} +FunctionEnd + +Function CreateOrUpdateStartMenuShortcut + ; We used to use product name as MAINBINARYNAME + ; migrate old shortcuts to target the new MAINBINARYNAME + StrCpy $R0 0 + + !insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName" + Pop $0 + ${If} $0 = 1 + !insertmacro SetShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + StrCpy $R0 1 + ${EndIf} + + !insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName" + Pop $0 + ${If} $0 = 1 + !insertmacro SetShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + StrCpy $R0 1 + ${EndIf} + + ${If} $R0 = 1 + Return + ${EndIf} + + ; Skip creating shortcut if in update mode or no shortcut mode + ; but always create if migrating from wix + ${If} $WixMode = 0 + ${If} $UpdateMode = 1 + ${OrIf} $NoShortcutMode = 1 + Return + ${EndIf} + ${EndIf} + + !if "${STARTMENUFOLDER}" != "" + CreateDirectory "$SMPROGRAMS\$AppStartMenuFolder" + CreateShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + !insertmacro SetLnkAppUserModelId "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" + !else + CreateShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + !insertmacro SetLnkAppUserModelId "$SMPROGRAMS\${PRODUCTNAME}.lnk" + !endif +FunctionEnd + +Function CreateOrUpdateDesktopShortcut + ; We used to use product name as MAINBINARYNAME + ; migrate old shortcuts to target the new MAINBINARYNAME + !insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName" + Pop $0 + ${If} $0 = 1 + !insertmacro SetShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + Return + ${EndIf} + + ; Skip creating shortcut if in update mode or no shortcut mode + ; but always create if migrating from wix + ${If} $WixMode = 0 + ${If} $UpdateMode = 1 + ${OrIf} $NoShortcutMode = 1 + Return + ${EndIf} + ${EndIf} + + CreateShortcut "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + !insertmacro SetLnkAppUserModelId "$DESKTOP\${PRODUCTNAME}.lnk" +FunctionEnd diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 0977bf52..585c61cb 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -44,6 +44,7 @@ "windows": { "nsis": { "installMode": "currentUser", + "template": "nsis/installer.nsi", "compression": "lzma", "languages": [ "English" diff --git a/apps/host/index.html b/apps/host/index.html index 437d8143..7f7aae75 100644 --- a/apps/host/index.html +++ b/apps/host/index.html @@ -11,7 +11,8 @@ // Set the saved appearance before CSS and logo images are painted. try { const saved = JSON.parse(localStorage.getItem('strata.prefs.v2') || localStorage.getItem('strata.prefs.v1') || '{}'); - const theme = saved.theme === 'dark' || (saved.theme === 'system' && matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light'; + const choice = saved.theme ?? 'system'; + const theme = choice === 'dark' || (choice === 'system' && matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light'; document.documentElement.dataset.theme = theme; document.querySelector('meta[name="theme-color"]').content = theme === 'dark' ? '#0e1113' : '#f9fafb'; } catch { document.documentElement.dataset.theme = 'light'; } diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index b455c1f8..515c95fd 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -41,6 +41,12 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};} function sourceText(){try{return readFileSync(join(packaged?control.control.dir:preferences.repo,'serve/server.py'),'utf8');}catch{return '';}} function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));} + const modelArena=id=>({arenaGb:(snapshot.catalog?.families??[]).flatMap(f=>f.sizes??[]).find(s=>s.id===id)?.experts_gb}); + /* A start that ends with `server_exited` says nothing a person can act on. The usual cause is the PC running low on memory + (the engine's own guard, or the OS); say that, what to try, and the last thing the engine wrote. */ + function humanStartError(error){const text=String(error?.message??error),tail=error?.output?.log_tail; + if(!/server_exited|exited|memory|killed|oom/i.test(text)&&!/memory|alloc|guard|killed/i.test(tail??''))return text; + return `The engine stopped before it was ready, most likely because the PC ran low on memory. Close other programs and try again, choose “Leave 20% for my work”, or turn on the low-RAM option so part of the model is read from the SSD instead of kept in memory.${tail?` Last engine message: ${tail}`:''}`;} function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} function installRoot(){const found=[preferences.installDir,packagedInstall,snapshot.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());} function repo(){if(packaged)return installRoot();const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;} @@ -83,7 +89,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp async function refresh(force=false){ if(closing)return state(); if(refreshing)return refreshing;if(!force&&Date.now()-lastRead<15000)return state(); - refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing; + refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);const noImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,images:false,sizes:(f.sizes??[]).map(s=>({...s,images:false}))}))}:c;snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:packaged?noImages(catalog):catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing; } function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};packagedInstall=null;disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);} function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();} @@ -92,7 +98,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);} function previousEngine(){try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}} async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);return tool('strata_install',installArgs(args,false));} - function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),confirm};} + function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),...(packaged?{vision:'no'}:{}),confirm};} function begin(kind,run,metadata={}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or cancel the current engine operation first.');const job={id:randomUUID(),kind,state:'running',startedAt:new Date().toISOString(),summary:'Starting…',result:null,error:null,...metadata};for(const [id,old] of jobs)if(jobs.size>=12&&old.state!=='running')jobs.delete(id);jobs.set(job.id,job);emit();void run(job).then(result=>{if(job.state==='running'){Object.assign(job,{state:'done',summary:result?.summary??'Complete',result,finishedAt:new Date().toISOString()});}}).catch(error=>{if(job.state==='running')Object.assign(job,{state:'error',error:error.message,summary:error.message,finishedAt:new Date().toISOString()});}).finally(()=>{if(job.kind.startsWith('update')||job.kind==='rollback')disconnect();lastRead=0;emit();void refresh(true);});return state().jobs.find(j=>j.id===job.id);} async function watchInstall(job,current){job.summary=current.step??'Resuming preparation status…';job.result={install:current};while(job.state==='running'){await new Promise(r=>setTimeout(r,1500));const result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(!result.install?.running){if(result.install?.exit_code!==0)throw new Error(result.install?.error??'Preparation did not finish. Retry to reuse completed files.');return {summary:'Model preparation complete. Load it from Models.'};}}} @@ -107,7 +113,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.'); const vision=runtimeVision(config,args.vision); const visionPreferences=args.vision!==undefined?{ui_vision_enabled:args.vision!=='no',ui_vision_device:args.vision==='no'?config.ui_vision_device??'yes':args.vision}:{}; - const resources=args.resourceProfile?resourceSettings({...config,vision},snapshot.hardware,args.resourceProfile):null; + const resources=args.resourceProfile?resourceSettings({...config,vision},snapshot.hardware,args.resourceProfile,modelArena(args.model)):null; const cfg={...config,...visionPreferences,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),host:'127.0.0.1',open_browser:false,...validateNativeSettings(args.values??{}),vision}; if(args.gpus!==undefined){const detected=new Set((snapshot.hardware?.gpus??[]).map(g=>g.index));if(!Array.isArray(args.gpus)||!args.gpus.length||new Set(args.gpus).size!==args.gpus.length||args.gpus.some(g=>!Number.isInteger(g)||!detected.has(g)))throw new Error('Choose distinct detected GPUs. CPU-only text inference is not supported by this native adapter.');cfg.gpu=args.gpus.length===1?args.gpus[0]:args.gpus;cfg.layer_split=args.gpus.length>1?validateNativeSettings({layer_split:args.layerSplit??'auto'}).layer_split:'auto';if(cfg.layer_split!=='auto'&&cfg.layer_split.split(',').length!==args.gpus.length-1)throw new Error('Choose one layer split point between each pair of GPUs.');} if(cfg.vram_reserve_mib!==undefined&&cfg.vram_reserve_mib!==null){cfg.args=[...(cfg.args??[])];const at=cfg.args.indexOf('--vram-reserve-mib');if(at>=0)cfg.args.splice(at,2);cfg.args.push('--vram-reserve-mib',String(cfg.vram_reserve_mib));}if(cfg.vision){if(cfg.vision_tokens!=null)cfg.vision={...cfg.vision,max_tokens:cfg.vision_tokens};if(cfg.vision_min_tokens!=null)cfg.vision={...cfg.vision,min_tokens:cfg.vision_min_tokens};}cfg.mcp={...(cfg.mcp??{}),...(cfg.mcp_timeout_s!=null?{timeout_s:cfg.mcp_timeout_s}:{}),...(cfg.mcp_max_rounds!=null?{max_rounds:cfg.mcp_max_rounds}:{}),...(cfg.mcp_max_result_chars!=null?{max_result_chars:cfg.mcp_max_result_chars}:{})}; @@ -134,7 +140,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp instances.set(id,instance);if(!defaultId||!args.multiple||wasDefault)defaultId=id;emit(); started=control.stop(instance.profile).catch(()=>{}).then(()=>control.saveProfile(instance.profile,configPath)).then(()=>control.start(instance.profile,{waitSeconds:300})); started.then(()=>append(id,'Strata Control reports the engine is ready.'),error=>{append(id,error.message);}); - try{await started;}catch(error){instance.status='error';instance.error=error.message;emit();throw error;} + try{await started;}catch(error){const said=humanStartError(error);instance.status='error';instance.error=said;emit();throw new Error(said);} } else { proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8',STRATA_API_KEY:''}}); instances.set(id,instance);processes.set(id,proc);if(!defaultId||!args.multiple||wasDefault)defaultId=id; @@ -166,20 +172,20 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp function writeModelConfig(path,next){copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);} async function tune(job,args){ await refresh(true);if(job.state!=='running')return; - const chosen=record(args.model);resourceSettings(chosen.config,snapshot.hardware,args.profile); + const chosen=record(args.model);resourceSettings(chosen.config,snapshot.hardware,args.profile,modelArena(args.model)); if(!chosen.entry.ready)throw new Error('Prepare the model before tuning.'); if(externalRunning().length)throw new Error('Stop the native server outside this UI before tuning.'); if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish requests before tuning.'); for(const id of [...instances.keys()])await unload(id); if(job.state!=='running')return; - const initialValues=resourceSettings(chosen.config,snapshot.hardware,args.profile);writeModelConfig(chosen.path,{...chosen.config,...initialValues,ui_resource_profile:args.profile}); + const initialValues=resourceSettings(chosen.config,snapshot.hardware,args.profile,modelArena(args.model));writeModelConfig(chosen.path,{...chosen.config,...initialValues,ui_resource_profile:args.profile}); if(args.calibrate!==false&&state().capabilities.calibration){job.summary='Measuring the best engine settings for this computer…';emit();await program(job,args);} if(job.state!=='running')return; - const current=record(args.model),values=resourceSettings(current.config,snapshot.hardware,args.profile); + const current=record(args.model),values=resourceSettings(current.config,snapshot.hardware,args.profile,modelArena(args.model)); const next={...current.config,...values,ui_resource_profile:args.profile}; writeModelConfig(current.path,next); job.summary='Applying your resource preference and loading the model…';emit(); - const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:args.vision}); + const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:current.config.vision?args.vision:'no'}); if(job.state!=='running'||!loaded?.instanceId)return; job.summary='Checking your model’s speed…';emit(); const measured=await benchmark(job,{instanceId:loaded.instanceId}); diff --git a/apps/host/server/native-resources.mjs b/apps/host/server/native-resources.mjs index fb5ace4e..10f9dcc6 100644 --- a/apps/host/server/native-resources.mjs +++ b/apps/host/server/native-resources.mjs @@ -1,5 +1,5 @@ /** Headroom is a worker/memory budget, not a hard utilisation throttle. */ -export function resourceSettings(config,hardware,profile){ +export function resourceSettings(config,hardware,profile,model={}){ if(!['work','performance'].includes(profile))throw new Error('Choose a resource preference.'); const args=[...(config.args??[])]; const remove=flag=>{for(let at=args.indexOf(flag);at>=0;at=args.indexOf(flag))args.splice(at,2);}; @@ -20,5 +20,13 @@ export function resourceSettings(config,hardware,profile){ const gpuMemory=(hardware?.gpus??[]).filter(g=>placement.includes(g.index)).map(g=>g.vram_gb).filter(n=>Number.isFinite(n)&&n>0); const reserve=profile==='work'&&gpuMemory.length?Math.max(safety,Math.floor(Math.min(...gpuMemory)*1024*.2)):safety; remove('--vram-reserve-mib');args.push('--vram-reserve-mib',String(reserve)); - return {args,vram_reserve_mib:reserve,ui_resource_baseline:baseline}; + // RAM: "leave 20% for my work" keeps the model's RAM within 80% of the PC. A model whose experts do not fit there (the + // setup rule: experts plus 10 GB) keeps only that many GiB of them in RAM and reads the rest from the model files + // (--resident-budget-gib, which implies --mmap-experts). Full performance takes the budget out again. + if(baseline.ramBudget)remove('--resident-budget-gib'); + const ram=Number(hardware?.ram_gb)||0,arena=Number(model?.arenaGb)||0;let ramBudget=false; + if(profile==='work'&&ram>0&&arena>0&&!['--resident-experts','--mmap-experts','--resident-budget-gib'].some(f=>args.includes(f))&&ram*.8['onboarding']>; function radioKeys(event: KeyboardEvent) { if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) @@ -66,7 +67,7 @@ export function GuidedSetup() { navigate('chat', undefined, { settings: '1' }); } else - go(manual ? 'models' : 'chat'); + go(manual || preparing ? 'models' : 'chat'); } catch (e) { leaving.current = false; @@ -161,6 +162,7 @@ export function GuidedSetup() { return () => { cancelled = true; }; }, [step, plan, preparing, native?.available, version?.id, context, directory]); 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?'; function changeDownloadFolder() { void perform(async () => { await advance(2); setFolderOpen(true); }); } return
@@ -183,7 +185,7 @@ export function GuidedSetup() { :
{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}% of this file` : 'Getting files ready…')}
: <>{tr(stopped ? : null)}{tr(plan?.plan?.disk_short ? : null)})} + {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("Save to")}{tr(modelFolderLabel(folder))}{tr(!preparing ? : null)}
:
diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 6b0d60cb..2501f5ca 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -2,6 +2,7 @@ import { tr } from '../lib/i18n'; import { useEffect, useMemo, useRef, useState } from 'react'; import { Screen } from './layout'; import { Btn, Dialog, ErrorNotice, Icon, Select } from './ui'; +import { useDownloadEta } from '../lib/download-eta'; import { api } from '../lib/client'; import { go, setSettingsSection, selectRemoteModel, pushToast } from '../lib/store'; import { nativeAction, useNative, type NativeJob } from '../lib/native'; @@ -30,15 +31,23 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine expertSection.current?.scrollIntoView({ block: 'start', behavior: 'smooth' }); }, [expert]); const selectedFamily = families.find(f => f.family === family || f.sizes.some(size => size.sourceFamily === family)) ?? families[0], selectedSize = selectedFamily?.sizes.find(s => s.id === size) ?? selectedFamily?.sizes[0]; const installed = native?.installed?.models.find(m => m.model === selectedSize?.id); + // 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]); const active = native?.jobs.find(j => j.state === 'running'); const job = native?.jobs.find(j => j.id === jobId) ?? (!jobId ? native?.jobs.filter(j => ['load', 'install'].includes(j.kind)).at(-1) : undefined); const noFit = selectedSize?.on_this_pc === 'does not fit'; 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(',') } : {}), loadAfter: true, multiple: expert && multiple }), [selectedSize?.sourceFamily, selectedSize?.model, context, vision, kv, lowRam, resourceProfile, gpus.join(','), expert, multiple]); const downloadValues = { ...values, vision: selectedSize?.images ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no' }; useEffect(() => { if (!native?.catalog || family) - return; const current = native.instances.find(i => i.id === native.defaultId); const rec = native.catalog.recommendation ?? { family: null, model: null }; const loadedFamily = families.find(f => f.sizes.some(s => s.id === current?.model)); const f = loadedFamily ?? families.find(f => f.family === rec.family || f.sizes.some(s => s.sourceFamily === rec.family)) ?? families[0]; if (f) { + return; const current = native.instances.find(i => i.id === native.defaultId); const rec = native.catalog.recommendation ?? { family: null, model: null }; const loadedFamily = families.find(f => f.sizes.some(s => s.id === current?.model)); const have = new Set((native.installed?.models ?? []).filter(m => m.ready).map(m => m.model)); const installedFamily = families.find(f => f.sizes.some(s => have.has(s.id))); const f = loadedFamily ?? installedFamily ?? families.find(f => f.family === rec.family || f.sizes.some(s => s.sourceFamily === rec.family)) ?? families[0]; if (f) { setFamily(f.family); - setSize(f.sizes.find(s => s.id === current?.model || s.model === rec.model)?.id ?? f.sizes[0]?.id ?? ''); + 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) { @@ -102,7 +111,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine } export function NativeProgress({ job }: { job: NativeJob; -}) { const download = job.result?.install?.download; const [stopping, setStopping] = useState(false), [error, setError] = useState(''); async function stop() { setStopping(true); setError(''); try { +}) { const download = job.result?.install?.download; const eta = useDownloadEta(job.kind === 'install' ? download : undefined, job.id); const [stopping, setStopping] = useState(false), [error, setError] = useState(''); async function stop() { setStopping(true); setError(''); try { await nativeAction(`operations/${job.id}/cancel`); } catch (e) { @@ -110,4 +119,4 @@ catch (e) { } finally { setStopping(false); -} } return

{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : 'Engine operation')}

{tr(job.kind === 'install' || job.kind === 'load' ? void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')} : null)}

{tr(job.kind === 'install' ? (job.result?.install?.step ?? 'Downloading and preparing model files…') : job.summary)}

{tr(download ? <>

{tr(download.file)} · {tr(download.percent ?? 0)}%

: null)}
{tr("Details")}

{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}

{tr(error ? : null)}
; } +} } return

{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : 'Engine operation')}

{tr(job.kind === 'install' || job.kind === 'load' ?
{tr(eta ? {eta} : null)} void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}
: null)}

{tr(job.kind === 'install' ? (job.result?.install?.step ?? 'Downloading and preparing model files…') : job.summary)}

{tr(download ? <>

{tr(download.file)} · {tr(download.percent ?? 0)}%{tr(Number.isFinite(download.done_gb) && Number.isFinite(download.total_gb) ? ` · ${download.done_gb!.toFixed(1)} / ${download.total_gb!.toFixed(1)} GB` : '')}

: null)}
{tr("Details")}

{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}

{tr(error ? : null)}
; } diff --git a/apps/host/src/lib/download-eta.ts b/apps/host/src/lib/download-eta.ts new file mode 100644 index 00000000..6cb46670 --- /dev/null +++ b/apps/host/src/lib/download-eta.ts @@ -0,0 +1,36 @@ +import { useEffect, useRef, useState } from 'react'; +import { tr } from './i18n'; + +/** Minutes left from recent samples of "GB done": the rate over the last minute and a half, so a stall or a burst does not + * swing the estimate. Null until there is enough to say (about 10 s of samples) or when nothing is moving. */ +export function etaMinutes(samples: { at: number; done: number }[], remainingGb: number | undefined): number | null { + if (!Number.isFinite(remainingGb) || samples.length < 2) return null; + const first = samples[0], last = samples[samples.length - 1]; + const seconds = (last.at - first.at) / 1000, gained = last.done - first.done; + if (seconds < 10 || gained <= 0) return null; + return Math.max(1, Math.ceil((remainingGb! / (gained / seconds)) / 60)); +} + +export function etaLabel(minutes: number | null): string { + if (minutes === null) return ''; + if (minutes >= 90) { const h = Math.floor(minutes / 60), m = minutes % 60; return `${tr('About')} ${h} ${tr('h')}${m ? ` ${m} ${tr('min')}` : ''} ${tr('left')}`; } + return `${tr('About')} ${minutes} ${tr('min left')}`; +} + +/** The approximate time left of a running download, for the progress bar. `key` restarts the estimate for another job. */ +export function useDownloadEta(download: { done_gb?: number; remaining_gb?: number } | undefined, key: string | undefined): string { + const samples = useRef<{ at: number; done: number }[]>([]); + const owner = useRef(undefined); + const [label, setLabel] = useState(''); + const done = download?.done_gb, remaining = download?.remaining_gb; + useEffect(() => { + if (owner.current !== key) { owner.current = key; samples.current = []; } + if (!Number.isFinite(done)) { setLabel(''); return; } + const now = Date.now(); + const list = samples.current; + if (!list.length || list[list.length - 1].done !== done) list.push({ at: now, done: done! }); + while (list.length > 2 && now - list[0].at > 90_000) list.shift(); + setLabel(etaLabel(etaMinutes(list, remaining))); + }, [done, remaining, key]); + return label; +} diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts index 10cda11a..24901631 100644 --- a/apps/host/src/lib/store.ts +++ b/apps/host/src/lib/store.ts @@ -136,7 +136,7 @@ export interface Prefs { const PREFS_DEFAULTS: Prefs = { language: 'en', fontFamily: '', - theme: 'light', + theme: 'system', contrast: 'standard', rail: false, focus: false, diff --git a/apps/host/src/screens/Settings.tsx b/apps/host/src/screens/Settings.tsx index 4e9a0a3e..002cd961 100644 --- a/apps/host/src/screens/Settings.tsx +++ b/apps/host/src/screens/Settings.tsx @@ -26,7 +26,7 @@ export function SettingsScreen() { { section: 'General', label: 'Language', hint: 'Choose the language used throughout Strata.', control: }, + { section: 'Reading & focus', label: 'Appearance', hint: 'System follows your computer by default.', aliases: 'theme light dark system automatic', control: setContentFontSize(Number(e.target.value))}/>{tr(prefs.contentFontSize)}{tr(" px")} }, { section: 'Reading & focus', label: 'Interface size', hint: 'Scale navigation and controls.', aliases: 'zoom scale 90% 100% 110% 125%', control: }, diff --git a/apps/host/src/styles/onboarding.css b/apps/host/src/styles/onboarding.css index 80fb60ab..cc88ad03 100644 --- a/apps/host/src/styles/onboarding.css +++ b/apps/host/src/styles/onboarding.css @@ -241,3 +241,4 @@ @keyframes onboard-sharing-app{0%,100%{transform:translateY(0)}50%{transform:translateY(-3px)}} @keyframes onboard-sharing-flow{to{transform:translateX(100%)}} @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} diff --git a/apps/host/tests/packaged-control.test.mjs b/apps/host/tests/packaged-control.test.mjs index 746e170d..579907d5 100644 --- a/apps/host/tests/packaged-control.test.mjs +++ b/apps/host/tests/packaged-control.test.mjs @@ -97,6 +97,7 @@ function packagedFixture({ engineUsable = true } = {}) { const calls = []; const spawned = []; const rpc = []; + let startFailure = null; const control = { control: { dir: join(root, 'control'), python: join(root, 'control', 'python', 'python.exe') }, version: '0.1.45', async installedModels(options) { calls.push(['installedModels', options?.installDir ?? null]); return { install_dir: install, models: configs.map(c => ({ id: c.id, name: `Qwen ${c.id}`, source_config: c.path, component_status: 'present', context_tokens: 32768, backend: 'cuda' })) }; }, @@ -107,7 +108,7 @@ function packagedFixture({ engineUsable = true } = {}) { : { usable: false, notice: 'No engine for this PC was found in E:\\c: the component folder holds no engine package. The app never downloads an engine while it starts or serves.', backend: 'cuda', engine: null, components_dir: 'E:\\c' }; }, async saveProfile(name, path) { calls.push(['saveProfile', name, basename(path)]); return {}; }, - async start(name, options) { calls.push(['start', name, options?.waitSeconds]); return { ok: true, state: 'ready' }; }, + async start(name, options) { calls.push(['start', name, options?.waitSeconds]); if (startFailure) { const e = new Error(startFailure.message); e.output = startFailure.output; throw e; } return { ok: true, state: 'ready' }; }, async stop(name) { calls.push(['stop', name]); return { ok: true, state: 'stopped' }; }, }; const requests = []; @@ -142,7 +143,7 @@ function packagedFixture({ engineUsable = true } = {}) { }; const native = createNativeControl({ control, directory: data, spawnProcess, fetcher, requests: () => requests }); const others = () => spawned.filter(s => !String(s.args[0]).endsWith('strata_mcp.py')); - return { native, calls, spawned, others, rpc, catalog, hardware, install, root, cleanup: () => { rmSync(root, { recursive: true, force: true }); } }; + return { native, calls, spawned, others, rpc, failStart: v => { startFailure = v; }, catalog, hardware, install, root, cleanup: () => { rmSync(root, { recursive: true, force: true }); } }; } const finish = async (native, id) => { for (let i = 0; i < 400; i++) { const job = native.state().jobs.find(j => j.id === id); if (job.state !== 'running') return job; await new Promise(r => setTimeout(r, 10)); } throw new Error('job did not finish'); }; @@ -283,3 +284,30 @@ test('createControl asks the CLI for the engine, models and runtime and reads th ]); assert.equal(createControl({ control: null }), null); }); + +test('packaged: the catalog offers no picture reading (app installs have none), and an install asks for none', async () => { + const f = packagedFixture(); + try { + const state = await f.native.refresh(true); + assert.ok(state.catalog.families[0].sizes.every(s => s.images === false)); + assert.ok(state.catalog.families.every(fam => fam.images === false)); + await f.native.plan({ family: 'qwen', model: 'Q2_0', vision: 'yes' }); + assert.equal(f.rpc.at(-1).arguments.vision, 'no'); + } finally { await f.native.close(); f.cleanup(); } +}); + +test('packaged: an engine that stops while loading is explained in words, with the engine\'s last line', async () => { + const f = packagedFixture(); + try { + await f.native.refresh(true); + const control = f.native; + // the fixture's Control starts fine; make start fail the way Control reports a dead engine + f.failStart({ message: 'server_exited', output: { log_tail: 'memory guard: 5.1 GiB free is under the 6 GiB limit' } }); + const job = await finish(control, control.operation('load', { model: 'iq2_xs' }).id); + assert.equal(job.state, 'error'); + assert.match(job.error, /ran low on memory/); + assert.match(job.error, /Leave 20% for my work/); + assert.match(job.error, /memory guard: 5\.1 GiB free/); + assert.doesNotMatch(job.error, /^server_exited$/); + } finally { await f.native.close(); f.cleanup(); } +}); diff --git a/apps/host/tests/resource-ram.test.mjs b/apps/host/tests/resource-ram.test.mjs new file mode 100644 index 00000000..bac52b5d --- /dev/null +++ b/apps/host/tests/resource-ram.test.mjs @@ -0,0 +1,31 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { resourceSettings } from '../server/native-resources.mjs'; + +const pc64 = { cpu: { cores: 12 }, ram_gb: 63, gpus: [{ index: 0, name: 'NVIDIA GeForce RTX 5070', vram_gb: 11.9 }] }; +const iq3s = { arenaGb: 50.3 }; +const config = { gpu: 0, args: ['--native', 'x.gguf', '--max-context', '32768', '--pool-workers', '12'] }; +const flag = (args, name) => args[args.indexOf(name) + 1]; + +test('"leave 20% for my work" keeps the model within 80% of the RAM: a RAM budget for the experts', () => { + const work = resourceSettings(config, pc64, 'work', iq3s); + assert.ok(work.args.includes('--resident-budget-gib'), 'a model whose experts do not fit 80% of 63 GB gets a RAM budget'); + const gib = Number(flag(work.args, '--resident-budget-gib')); + assert.ok(gib + 10 <= 63 * 0.8, `${gib} GiB plus the 10 GB the rest needs stays inside 80% of the RAM`); + assert.equal(work.ui_resource_baseline.ramBudget, true); +}); + +test('full performance takes that budget out again and keeps what the installation had', () => { + const work = resourceSettings(config, pc64, 'work', iq3s); + const back = resourceSettings({ ...config, args: work.args, ui_resource_profile: 'work', ui_resource_baseline: work.ui_resource_baseline }, pc64, 'performance', iq3s); + assert.equal(back.args.includes('--resident-budget-gib'), false); + assert.equal(flag(back.args, '--pool-workers'), '12'); +}); + +test('a model that fits, or one that already has a RAM mode, is left alone', () => { + assert.equal(resourceSettings(config, { ...pc64, ram_gb: 128 }, 'work', iq3s).args.includes('--resident-budget-gib'), false); + assert.equal(resourceSettings(config, pc64, 'work', { arenaGb: 34 }).args.includes('--resident-budget-gib'), false, 'Q2_0 fits 80% of 63 GB with 10 to spare'); + const own = { ...config, args: [...config.args, '--mmap-experts'] }; + assert.equal(resourceSettings(own, pc64, 'work', iq3s).args.includes('--resident-budget-gib'), false); + assert.equal(resourceSettings(config, pc64, 'work').args.includes('--resident-budget-gib'), false, 'no model size, no change'); +}); diff --git a/strata_control/runtime.py b/strata_control/runtime.py index 0ce7222d..1f477451 100644 --- a/strata_control/runtime.py +++ b/strata_control/runtime.py @@ -797,6 +797,17 @@ class Host: if "error" in result: self.last_error = result["error"] + def _log_tail(self, limit: int = 4096) -> str | None: + """The last line the server wrote (a failed start is explained by it), or None. Bounded read, never raises.""" + try: + with open(self.state_path.parent / f"{self.name}.server.log", "rb") as stream: + stream.seek(0, os.SEEK_END) + stream.seek(max(0, stream.tell() - limit)) + lines = [x.strip() for x in stream.read().decode("utf-8", "replace").splitlines() if x.strip()] + except OSError: + return None + return lines[-1][:300] if lines else None + def _status(self) -> dict: child = self.child base = {"ok": True, "profile": self.name, "host_pid": os.getpid(), @@ -809,7 +820,7 @@ class Host: return {**base, "state": "stopped"} if child.poll() is not None: return {**base, "ok": False, "state": "failed", "exit_code": child.returncode, - "error": self.last_error or "server_exited"} + "error": self.last_error or "server_exited", "log_tail": self._log_tail()} if self.ready_path is not None: try: ready = json.loads(self.ready_path.read_text(encoding="utf-8")) diff --git a/tests/desktop/test_control_install.py b/tests/desktop/test_control_install.py index 96cd3f33..c8449cc8 100644 --- a/tests/desktop/test_control_install.py +++ b/tests/desktop/test_control_install.py @@ -191,6 +191,32 @@ class InstallerServerTests(unittest.TestCase): self.assertFalse((self.root / ".venv").exists(), "no virtual environment, no pip") self.assertIsNotNone(s) + def test_a_two_file_model_has_one_combined_progress(self): + """The bar went 70 GB -> 0 -> up again because each file reported its own total. One total for the whole model now.""" + folder = self.root / "Strata-data" / "models" / "IQ3_S" + folder.mkdir(parents=True) + job = {"folder": str(folder), "total_gb": 0.004} + step5 = {"step": "5/7: downloading Qwen3.8-Flash-Next IQ3_S"} + seen = [] + # file 1 downloading, then complete, then file 2 starts: the combined figure only goes up + for name, size in (("a.gguf.part", 400_000), ("a.gguf.part", 1_500_000)): + (folder / name).write_bytes(b"x" * size) + seen.append(self.mcp.combined_progress(dict(step5), job)["download"]) + (folder / "a.gguf.part").rename(folder / "a.gguf") + (folder / "b.gguf.part").write_bytes(b"x" * 100_000) + seen.append(self.mcp.combined_progress(dict(step5), job)["download"]) + (folder / "b.gguf.part").write_bytes(b"x" * 1_000_000) + seen.append(self.mcp.combined_progress(dict(step5), job)["download"]) + done = [d["done_gb"] for d in seen] + self.assertEqual(done, sorted(done), done) + self.assertEqual(seen[-1]["total_gb"], 0.004) + self.assertAlmostEqual(seen[-1]["remaining_gb"], 0.004 - seen[-1]["done_gb"], places=2) + self.assertTrue(all(d["file"] == "model files" for d in seen)) + # not a download any more once setup is preparing the files + self.assertNotIn("download", self.mcp.combined_progress({"step": "6/7: preparing the model for Strata", "download": {"x": 1}}, job)) + # a resumed install counts what is already on disk + self.assertGreater(self.mcp.combined_progress(dict(step5), job)["download"]["done_gb"], 0) + @unittest.skipUnless(os.name == "nt" or sys.platform.startswith("linux"), "a PC with a GPU probe") def test_a_real_install_reaches_the_model_download_with_nothing_else_acquired(self): """setup.py in the app's mode, as the install job runs it: steps 1-4 pass (PC check, packages bundled, engine component diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index fad2c349..8abd108a 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -847,6 +847,7 @@ class Strata: log_path = Path(j.get("log", "")) tail = read_tail(log_path, 400) if log_path.name else [] prog = install_progress(tail) + prog = combined_progress(prog, j) out = {"running": running, "started": j.get("started"), "model": j.get("model"), "family": j.get("family"), "log": str(log_path), **prog} if not running: @@ -862,6 +863,31 @@ class Strata: return out +def combined_progress(prog: dict, job: dict) -> dict: + """One total for the whole model: the bytes of all its files (finished, partial and the one in flight, read from the + model's folder) over the download size, instead of each file's own 0-100% (a two-file model went 70 GB -> 0 -> up + again). Only while the download step runs; later steps are not a download.""" + folder, total = job.get("folder"), job.get("total_gb") + step = str(prog.get("step") or "") + if not folder or not total or not step.startswith("5/"): + prog.pop("download", None) + return prog + done = 0 + try: + for entry in os.scandir(folder): + if entry.is_file() and (entry.name.endswith(".gguf") or entry.name.endswith(".part")): + done += entry.stat().st_size + except OSError: + pass + if not done: # nothing on disk yet: the log's own line is all there is + return prog + done_gb = min(done / 1e9, float(total)) + prog["download"] = {"file": "model files", "done_gb": round(done_gb, 3), "total_gb": float(total), + "remaining_gb": round(max(0.0, float(total) - done_gb), 3), + "percent": min(99, int(100 * done_gb / float(total))) if total else 0} + return prog + + def install_progress(lines: list[str]) -> dict: """setup's progress from its output: the step, a download's percentage, a failure.""" step, title, dl, err = None, None, None, None @@ -1305,7 +1331,8 @@ class Tools: installed = (s.root / f"strata-{tag.lower()}.json").exists() plan = {"title": f"{families[family]['title']} {model}", "family": family, "model": model, "context": context, "images": vision or "no", "download_gb": models[model]["download_gb"], - "partly_downloaded": partly, "ram": fit, "data_folder": str(target), "disk_free_gb": free, + "partly_downloaded": partly, "ram": fit, "data_folder": str(target), "model_folder": str(have_dir), + "disk_free_gb": free, "disk_needed_gb": round(need), "disk_short": short, "already_installed": installed, "setup_command": ("START-HERE.bat " if WIN else "./setup.sh ") + " ".join(args), "takes": "about 20-90 minutes, mostly the download; the PC stays usable", @@ -1342,7 +1369,8 @@ class Tools: if ident is None and p.poll() and s.state("install-result").get("job") != job_id: raise ToolError("setup did not start: " + " | ".join(read_tail(log_path, 5))) s.save_state("install", {"job": job_id, "pid": p.pid, "ident": ident, "log": str(log_path), - "model": plan["model"], "family": plan["family"], + "model": plan["model"], "family": plan["family"], "folder": plan.get("model_folder"), + "total_gb": plan.get("download_gb"), "started": time.strftime("%Y-%m-%d %H:%M:%S"), "args": args}) return {"summary": f"Install of {plan['title']} started in the background (about 20-90 minutes, mostly the " f"{plan['download_gb']:.0f} GB download). Call strata_install again to see the progress; " From 5df75b1d4d2ac9a1aeec3690f51549967a499e31 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 19:42:08 +0200 Subject: [PATCH 08/16] first-run feedback 2: plain words for failures with Details, parts-based download progress, reading size reaches all conversation text, tuning pop-up fits its error, headless UI flows, installer mock-ups ErrorNotice and toasts map known failures (server_exited, engine missing, network, integrity, Harness missing, Control) to a sentence and a next step with the original text under Details. The install progress sums a list of parts (model files, engine) into one count with a time left. The Read pictures block is hidden when the catalog has no pictures. Control reports the last server log lines of a failed start. Reading size scales headings, code, tables and reasoning. All eight locales. --- apps/desktop/scripts/installer-mockups.mjs | 73 +++++ apps/desktop/scripts/ui-flows.mjs | 353 +++++++++++++++++++++ apps/host/server/native-control.mjs | 8 +- apps/host/src/components/GuidedSetup.tsx | 4 +- apps/host/src/components/NativeModels.tsx | 11 +- apps/host/src/components/ui.tsx | 11 +- apps/host/src/lib/download-eta.ts | 23 +- apps/host/src/lib/native.ts | 2 +- apps/host/src/lib/plain-errors.ts | 44 +++ apps/host/src/lib/store.ts | 5 +- apps/host/src/locales/de.json | 24 +- apps/host/src/locales/en.json | 24 +- apps/host/src/locales/es.json | 24 +- apps/host/src/locales/ja.json | 24 +- apps/host/src/locales/ko.json | 24 +- apps/host/src/locales/pt.json | 24 +- apps/host/src/locales/ru.json | 24 +- apps/host/src/locales/zh.json | 24 +- apps/host/src/styles/app.css | 12 + apps/host/src/styles/onboarding.css | 1 + apps/host/tests/download-eta.test.mjs | 39 +++ apps/host/tests/packaged-control.test.mjs | 11 +- apps/host/tests/plain-errors.test.mjs | 57 ++++ strata_control/runtime.py | 9 +- tests/desktop/test_control_install.py | 17 + tools/strata_mcp.py | 4 + 26 files changed, 838 insertions(+), 38 deletions(-) create mode 100644 apps/desktop/scripts/installer-mockups.mjs create mode 100644 apps/desktop/scripts/ui-flows.mjs create mode 100644 apps/host/src/lib/plain-errors.ts create mode 100644 apps/host/tests/download-eta.test.mjs create mode 100644 apps/host/tests/plain-errors.test.mjs diff --git a/apps/desktop/scripts/installer-mockups.mjs b/apps/desktop/scripts/installer-mockups.mjs new file mode 100644 index 00000000..cc7a3c8f --- /dev/null +++ b/apps/desktop/scripts/installer-mockups.mjs @@ -0,0 +1,73 @@ +#!/usr/bin/env node +/** + * Mock-ups of the Windows installer in Strata's own look: four screens (welcome, where, installing, done), light and dark, drawn with + * the app's built CSS (apps/host/dist) and brand files, then photographed with Chrome. Nothing here is built or shipped: it is what + * the owner is shown before an installer is chosen. + * + * node apps/desktop/scripts/installer-mockups.mjs [--out ] + */ +import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); +const here = dirname(fileURLToPath(import.meta.url)); +const host = resolve(here, '../../host'); +const out = resolve(args.out ?? join(here, '../installer-mockups')); +mkdirSync(out, { recursive: true }); +const dist = join(host, 'dist'); +const css = readdirSync(join(dist, 'assets')).filter(f => f.endsWith('.css')).map(f => readFileSync(join(dist, 'assets', f), 'utf8')).join('\n'); +const logo = theme => readFileSync(join(dist, 'brand', `strata-lockup-${theme}.svg`), 'utf8'); +const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); +const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); + +const check = ''; +const folder = ''; + +const screens = { + welcome: theme => `
+

State of the art. At home.

Strata runs AI on your own computer.
Setting it up takes a few minutes.

+
${check}Private${check}Fast${check}Easy to use
+
Installs for you only. No administrator needed.
`, + where: theme => `
+

Where should Strata go?

This is the right place for most people.

+
${folder}
Your Strata folderC:\\Users\\Alex\\AppData\\Local\\Strata
+

About 310 MB. Your models and chats are kept somewhere else and are never removed by an update.

+
`, + installing: theme => `
+

Installing Strata…

Copying the app and its engine room. You can keep working meanwhile.

+
+
62% · 190 / 310 MB
About 1 min left
+
Next: choose your first model inside Strata.
`, + done: theme => `
+

Strata is ready.

Open it to pick your first model. Strata downloads it for you and gets it ready.

+
A shortcut was added to your Start menu and desktop.
`, +}; + +const page = (name, theme) => `
Strata setup– ☐ ✕
+
${screens[name](theme)}
`; + +const browser = await chromium.launch({ executablePath: CHROME, headless: true }); +const written = []; +for (const theme of ['light', 'dark']) { + for (const name of Object.keys(screens)) { + const tab = await browser.newPage({ viewport: { width: 860, height: 620 }, deviceScaleFactor: 1 }); + await tab.setContent(page(name, theme)); + await tab.waitForTimeout(250); + const file = join(out, `${name}-${theme}.png`); + await tab.screenshot({ path: file }); + written.push(file); + await tab.close(); + } +} +await browser.close(); +console.log(written.join('\n')); diff --git a/apps/desktop/scripts/ui-flows.mjs b/apps/desktop/scripts/ui-flows.mjs new file mode 100644 index 00000000..a25fb40c --- /dev/null +++ b/apps/desktop/scripts/ui-flows.mjs @@ -0,0 +1,353 @@ +#!/usr/bin/env node +/** + * Headless UI flows of the installed app against a packaged host with a FAKE installer and a FAKE engine (nothing is + * downloaded, no real engine runs; the real Control starts the fake engine through the owner runtime): + * + * node apps/desktop/scripts/ui-flows.mjs [--control ] [--node ] [--shots ] [--only download,models,tune,fail,theme] + * + * download the onboarding download: ONE combined bar over both files, an ETA in minutes left of Stop, Finish later closes the + * pop-up with the download still running, the Models screen shows the same progress, Stop stops it + * models an installed model is the one Models selects and loads, without a download pop-up + * tune the tuning step offers no picture reading, tunes, writes a RAM budget for "leave 20%", opens chat; reading size + * fail an engine that stops while loading: the error is in words and the pop-up does not scroll + * theme the app follows the system light/dark setting + * Per-user folders are all under a scratch folder. Exit 1 if a check fails. + */ +import { spawn, spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, rmdirSync, symlinkSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') ? true : all[i + 1]]] : acc), [])); +const here = dirname(fileURLToPath(import.meta.url)); +const repoHost = resolve(here, '../../host'); +const staged = resolve(here, '../src-tauri/resources'); +const stagedControl = resolve(args.control ?? join(staged, 'control')); +const nodeExe = resolve(args.node ?? join(staged, 'node', process.platform === 'win32' ? 'node.exe' : 'node')); +const work = mkdtempSync(join(tmpdir(), 'strata-ui-flows-')); +const shots = resolve(args.shots ?? join(work, 'shots')); +mkdirSync(shots, { recursive: true }); +const only = new Set(String(args.only ?? 'download,models,tune,fail,theme').split(',')); +const isWin = process.platform === 'win32'; +const { chromium } = await import(pathToFileURL(join(repoHost, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); +const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); +const delay = ms => new Promise(r => setTimeout(r, ms)); +const sha = buf => createHash('sha256').update(buf).digest('hex'); +const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }; +let failed = false; +const check = (ok, label, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${detail ? ' ' + detail : ''}`); if (!ok) failed = true; }; + +// ------------------------------------------------------------------ the app folder: the real Control with a fake installer +const control = join(work, 'control'); +mkdirSync(control, { recursive: true }); +for (const name of ['python', 'strata_control', 'strata_cli', 'serve']) symlinkSync(join(stagedControl, name), join(control, name), 'junction'); +for (const name of ['strata.py', 'VERSION', 'BUNDLE.json', 'requirements.txt']) copyFileSync(join(stagedControl, name), join(control, name)); +cpSync(join(stagedControl, 'tools'), join(control, 'tools'), { recursive: true }); +const python = isWin ? join(control, 'python', 'python.exe') : join(control, 'python', 'bin', 'python3'); + +const FAKE_INSTALLER = String.raw` +import json, os, sys, time +from pathlib import Path +STATE = Path(os.environ['FAKE_STATE']); STATE.mkdir(parents=True, exist_ok=True) +RATE = float(os.environ.get('FAKE_RATE_GB_S', '0.5')) +def size(model, gb, ram, mid): + return {'model': model, 'about': model, 'download_gb': gb, 'ram_needed_gb': ram, 'experts_gb': ram - 8, 'on_this_pc': 'fits', 'installed': False, 'images': True, 'experimental': False, 'id': mid} +CATALOG = {'summary': 'fake', 'families': [{'family': 'qwen', 'title': 'Qwen3.8-Flash-Next', 'about': 'x', 'experimental': False, 'images': True, 'sizes': [ + size('Q2_0', 66.4, 48, 'q2_0'), size('IQ3_XXS', 75.8, 60, 'iq3_xxs'), size('IQ3_S', 83.6, 62, 'iq3_s')]}], + 'contexts': [8192, 32768, 65536], 'recommendation': {'family': 'qwen', 'model': 'IQ3_XXS', 'title': 'Qwen3.8-Flash-Next IQ3_XXS', 'context': 32768}, 'context_note': ''} +HARDWARE = {'ram_gb': 63.1, 'cpu': {'name': 'cpu', 'cores': 12}, 'gpus': [{'index': 0, 'name': 'NVIDIA GeForce RTX 5070', 'vram_gb': 11.9, 'usable': True}]} +TOTAL = 83.6 +def job(): + f = STATE / 'job.json' + if not f.exists(): return None + j = json.loads(f.read_text()) + if j.get('cancelled'): + return {'running': False, 'exit_code': 1, 'error': 'stopped', 'result': 'failed'} + done = min(TOTAL, RATE * (time.time() - j['start'])) + return {'running': True, 'step': '5/7: downloading Qwen3.8-Flash-Next IQ3_S', 'model': 'IQ3_S', + 'download': {'file': 'model files', 'done_gb': round(done, 3), 'total_gb': TOTAL, 'remaining_gb': round(TOTAL - done, 3), 'percent': int(100 * done / TOTAL)}} +def call(name, a): + if name == 'strata_models': return CATALOG + if name == 'strata_status': return {'summary': 'fake', 'hardware': HARDWARE, 'recommendation': CATALOG['recommendation'], 'install': job(), 'running': []} + if name == 'strata_install': + if a.get('cancel'): + f = STATE / 'job.json' + if f.exists(): j = json.loads(f.read_text()); j['cancelled'] = True; f.write_text(json.dumps(j)) + return {'summary': 'stopped', 'install': job()} + if a.get('confirm'): + (STATE / 'job.json').write_text(json.dumps({'start': time.time()})) + return {'summary': 'started', 'plan': {'download_gb': TOTAL}, 'install': job()} + if not a: return {'summary': 'progress', 'install': job()} + return {'summary': 'Plan', 'plan': {'title': 'Qwen3.8-Flash-Next IQ3_S', 'download_gb': TOTAL, 'disk_short': None}} + raise Exception('unknown tool ' + name) +for line in sys.stdin: + line = line.strip() + if not line: continue + m = json.loads(line) + if 'id' not in m: continue + method = m.get('method') + if method == 'initialize': res = {'protocolVersion': '2024-11-05'} + elif method == 'tools/list': res = {'tools': [{'name': n} for n in ('strata_models', 'strata_status', 'strata_install')]} + else: + p = m['params'] + res = {'structuredContent': call(p['name'], p.get('arguments') or {})} + sys.stdout.write(json.dumps({'jsonrpc': '2.0', 'id': m['id'], 'result': res}) + '\n'); sys.stdout.flush() +`; +writeFileSync(join(control, 'tools', 'strata_mcp.py'), FAKE_INSTALLER); + +const FAKE_ENGINE = `import os, sys, json +from pathlib import Path +if os.environ.get('FAKE_ENGINE_FAIL'): + print('memory guard: 5.1 GiB of RAM free is under the 6 GiB limit (limit 63.1 GiB)', flush=True) + sys.exit(3) +print('READY 4096 stop', flush=True) +for line in sys.stdin: + if line.strip() == 'QUIT': break + if line.startswith(('GEN ', 'BGEN ')): + slot = int(line.split()[1]) if line.startswith('BGEN ') else None + for ch in os.environ.get('FAKE_REPLY', 'a'): + print('T %d' % ord(ch), flush=True) + print('DONE 1 1 1.0 1.0 length 0 0 0', flush=True) + if slot is not None: print(f'BADM {slot} 0', flush=True) +`; + +// one scenario = one fresh host with its own per-user folders +async function scenario(name, { installed = false, env = {} } = {}, body) { + if (!only.has(name)) return; + console.log(`--- ${name}`); + const dir = join(work, name); + const dirs = { home: join(dir, 'home'), appdata: join(dir, 'appdata'), local: join(dir, 'local'), components: join(dir, 'local', 'Strata', 'components'), install: join(dir, 'local', 'Strata', 'install'), state: join(dir, 'fake-state'), profiles: join(dir, 'profiles'), runtime: join(dir, 'runtime') }; + for (const d of [dirs.home, dirs.appdata, dirs.local, dirs.components, dirs.install, dirs.state, join(dir, 'models')]) mkdirSync(d, { recursive: true }); + const baseEnv = { ...process.env, STRATA_COMPONENTS_DIR: dirs.components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(dir, 'models'), APPDATA: dirs.appdata, LOCALAPPDATA: dirs.local, XDG_CONFIG_HOME: join(dir, 'xdg'), XDG_DATA_HOME: join(dir, 'xdgdata'), PYTHONDONTWRITEBYTECODE: '1', STRATA_ENGINE_BACKEND: 'cuda', FAKE_STATE: dirs.state, ...env }; + delete baseEnv.STRATA_API_KEY; delete baseEnv.STRATA_INSTALL_DIR; + if (installed) { + const platform = isWin ? 'windows-x86_64' : 'linux-x86_64'; + const folder = join(dirs.components, 'engine', `0.1.45-${platform}-cuda`); + mkdirSync(folder, { recursive: true }); + writeFileSync(join(folder, 'engine_main.py'), FAKE_ENGINE); + const entry = isWin ? 'engine.cmd' : 'engine'; + writeFileSync(join(folder, entry), isWin ? `@echo off\r\n"${python}" "%~dp0engine_main.py" %*\r\n` : `#!/bin/sh\nexec "${python}" "$(dirname "$0")/engine_main.py" "$@"\n`); + const files = [entry, 'engine_main.py'].map(p => { const b = readFileSync(join(folder, p)); return { path: p, sha256: sha(b), bytes: b.length }; }); + writeFileSync(join(folder, 'engine-component.json'), JSON.stringify({ schema_version: 1, id: 'strata-engine', version: '0.1.45', platform, backend: 'cuda', entrypoint: entry, files })); + const tok = join(dirs.install, 'tokenizer'); + mkdirSync(tok, { recursive: true }); + const script = `import json, sys\nfrom tools.strata_tokenizer import BYTE_TO_UNICODE\ntok = sys.argv[1]\ntokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ['ab', '<|im_start|>', '<|im_end|>', '<|endoftext|>']\njson.dump({t: i for i, t in enumerate(tokens)}, open(tok + '/vocab.json', 'w'))\nopen(tok + '/merges.txt', 'w').write('a b')\njson.dump([0] * 257 + [3, 3, 3], open(tok + '/token_type.json', 'w'))\n`; + const made = spawnSync(python, ['-c', script, tok], { cwd: control, env: { ...baseEnv, PYTHONNOUSERSITE: '1' }, encoding: 'utf8' }); + if (made.status !== 0) throw new Error('tokenizer fixture: ' + made.stderr); + writeFileSync(join(dirs.install, 'strata-iq3_s.json'), JSON.stringify({ exe: 'component:strata-engine', backend: 'cuda', tokenizer: tok, args: ['--max-context', '32768', '--pool-workers', '12'], cwd: dir, model_name: 'stub', host: '127.0.0.1', port: 0, kv: 'int8' })); + } + const port = await freePort(), base = `http://127.0.0.1:${port}`; + const host = spawn(nodeExe, [join(repoHost, 'server', 'index.mjs')], { cwd: repoHost, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, + env: { ...baseEnv, STRATA_PORT: String(port), STRATA_DIST: join(repoHost, 'dist'), STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', STRATA_CONTROL_DIR: control, STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()) } }); + let log = ''; host.stdout.on('data', c => { log += c; }); host.stderr.on('data', c => { log += c; }); + const api = async (path, init) => { const r = await fetch(base + path, init); return { status: r.status, body: await r.json().catch(() => null) }; }; + const browser = await chromium.launch({ executablePath: CHROME, headless: true }); + try { + let up = false; + for (let i = 0; i < 200 && !up; i++) { try { up = (await api('/api/health')).status === 200; } catch { await delay(150); } } + check(up, `${name}: the packaged host starts`); + await api('/api/native?refresh=1'); + await body({ base, api, browser, dirs, shot: (page, n) => page.screenshot({ path: join(shots, `${name}-${n}.png`) }), log: () => log }); + } catch (error) { + check(false, `${name}: the flow`, String(error?.stack ?? error).slice(0, 700) + '\n' + log.slice(-600)); + } finally { + await browser.close().catch(() => {}); + host.kill(); await new Promise(r => host.once('exit', r)); + } +} +const newPage = async (browser, base, options = {}) => { + const context = await browser.newContext({ viewport: { width: 1400, height: 950 }, ...options }); + const page = await context.newPage(); + const problems = []; + page.on('pageerror', e => problems.push(e.message)); + page.problems = problems; + await page.goto(base, { waitUntil: 'domcontentloaded' }); + return page; +}; +const clickText = async (page, re, timeout = 30000) => { const b = page.getByRole('button', { name: re }).first(); await b.waitFor({ timeout }); await b.click(); }; +const noScroll = async page => page.evaluate(() => { + const root = document.querySelector('.guided-onboarding'); + const bad = []; + for (let el = document.querySelector('.onboard-tune-stage, .onboard-prepare-stage, .onboard-model-stage') ?? root; el && el !== document.body; el = el.parentElement) { + const style = getComputedStyle(el); + if (/(auto|scroll)/.test(style.overflowY) && el.scrollHeight > el.clientHeight + 1) bad.push(`${el.className || el.tagName}: ${el.scrollHeight} > ${el.clientHeight}`); + } + return bad; +}); + +// ------------------------------------------------------------------------------------------------ download +await scenario('download', {}, async ({ base, api, browser, shot }) => { + const page = await newPage(browser, base); + await clickText(page, /get started/i); + await page.getByText(/Choose a version/i).waitFor({ timeout: 30000 }); + await page.locator('[role=radio]').filter({ hasText: 'IQ3_S' }).first().click(); + await clickText(page, /^Continue/); + await clickText(page, /Download model/i, 60000); + await page.locator('.onboard-progress progress').waitFor({ timeout: 30000 }); + // ONE bar: sample the percent while it runs, it only goes up + const samples = []; + let eta = ''; + for (let i = 0; i < 40 && !eta; i++) { + const state = (await api('/api/native')).body; + const d = state.jobs.at(-1)?.result?.install?.download; + if (d) samples.push(d.done_gb); + eta = (await page.locator('.onboard-progress-actions span').first().textContent({ timeout: 1000 }).catch(() => '')) ?? ''; + await delay(1000); + } + await shot(page, '1-wizard-progress'); + check(/About \d+ (min left|h)/.test(eta), 'the wizard shows about how many minutes are left', eta.trim()); + const order = await page.evaluate(() => { const a = document.querySelector('.onboard-progress-actions'); const kids = a ? [...a.children].map(k => k.tagName + ':' + Math.round(k.getBoundingClientRect().left)) : []; return kids; }); + check(order.length === 2 && order[0].startsWith('SPAN') && order[1].startsWith('BUTTON') && Number(order[0].split(':')[1]) < Number(order[1].split(':')[1]), 'the time left sits left of Stop', order.join(' ')); + check(samples.length >= 3 && samples.every((v, i) => i === 0 || v >= samples[i - 1]), 'one combined count that only goes up', samples.map(v => v.toFixed(1)).join(', ')); + const meta = await page.locator('.onboard-progress-meta span').first().textContent(); + check(/GB/.test(meta ?? '') && /83\.6/.test(meta ?? ''), 'the bar says done / total over the whole model', meta); + // close the pop-up while it downloads + await clickText(page, /Finish later/i); + await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {}); + await page.getByText(/Preparing your model/i).waitFor({ timeout: 15000 }).catch(() => {}); + await delay(1500); + await shot(page, '2-models-progress'); + await page.locator('.native-progress').first().screenshot({ path: join(shots, 'download-3-models-progress-card.png') }).catch(() => {}); + check(await page.locator('.guided-onboarding').count() === 0, 'the setup pop-up closed'); + check(await page.getByText(/Preparing your model/i).count() > 0, 'the Models screen shows the running download'); + const still = (await api('/api/native')).body.jobs.at(-1); + check(still?.state === 'running', 'the download keeps running in the background', still?.state); + const modelsEta = await page.locator('.native-progress .onboard-progress-actions span').first().textContent({ timeout: 15000 }).catch(() => ''); + check(/About \d+ (min left|h)/.test(modelsEta ?? ''), 'the Models screen shows the time left too', (modelsEta ?? '').trim()); + await clickText(page, /^Stop$/); + await delay(2500); + check((await api('/api/native')).body.jobs.at(-1)?.state !== 'running', 'Stop stops it'); + check(page.problems.length === 0, 'no page error', page.problems.join('; ')); +}); + +// ------------------------------------------------------------------------------------------------ models +await scenario('models', { installed: true }, async ({ base, api, browser, shot }) => { + const page = await newPage(browser, base); + await clickText(page, /Go straight to the app/i); + await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {}); + await page.getByText(/Conversation context/i).first().waitFor({ timeout: 30000 }); + await delay(1500); + await shot(page, '1-models'); + await page.locator('.native-toolbar-summary').first().waitFor({ timeout: 20000 }).catch(async () => { await shot(page, '0-models-missing-summary'); console.log('info page text:', JSON.stringify((await page.locator('body').innerText()).slice(0, 500))); }); + const summary = await page.locator('.native-toolbar-summary').first().textContent({ timeout: 5000 }).catch(() => ''); + check(/IQ3_S|High quality/.test(summary ?? ''), 'Models selects the model that is on this PC, not the recommendation', (summary ?? '').replace(/\s+/g, ' ').trim()); + check(!/IQ3_XXS|Balanced/.test(summary ?? ''), 'the recommendation (IQ3_XXS) is not what is selected'); + const load = page.getByRole('button', { name: /^Load model$/ }).first(); + await load.click(); + await delay(1200); + check(await page.getByRole('dialog').filter({ hasText: /Download and prepare/i }).count() === 0, 'loading an installed model opens no download pop-up'); + let ready = false; + for (let i = 0; i < 90 && !ready; i++) { const s = (await api('/api/native')).body; ready = s.instances.some(x => x.status === 'ready'); const err = s.instances.find(x => x.status === 'error'); if (err) throw new Error('load failed: ' + err.error); await delay(1000); } + if (!ready) { const st = (await api('/api/native')).body; console.log('info jobs', JSON.stringify(st.jobs.map(j => [j.kind, j.state, j.error ?? j.summary])), 'instances', JSON.stringify(st.instances.map(i => [i.status, i.error]))); await shot(page, '2-models-after-click'); } + check(ready, 'the model loads (a fake engine under the real Control)'); + check(page.problems.length === 0, 'no page error', page.problems.join('; ')); +}); + +// ------------------------------------------------------------------------------------------------ tune + reading size +await scenario('tune', { installed: true, env: { FAKE_REPLY: ['I am thinking about it.', '', '', 'Here is a list:', '', '- one', '- two', '', '## Heading', '', 'Some `code` and **bold** text.', '', '| a | b |', '|---|---|', '| 1 | 2 |', '', '```', 'code line', '```', ''].join(String.fromCharCode(10)) } }, async ({ base, api, browser, dirs, shot }) => { + const page = await newPage(browser, base); + await clickText(page, /get started/i); + await page.getByText(/Choose a version/i).waitFor({ timeout: 30000 }); + await page.locator('[role=radio]').filter({ hasText: 'IQ3_S' }).first().click(); + await clickText(page, /^Continue/); + await page.getByText(/Leave 20% for my work/i).waitFor({ timeout: 30000 }); + await delay(800); + await shot(page, '1-tune-step'); + check(await page.getByText(/Read pictures when this model loads/i).count() === 0, 'the tuning step offers no picture reading for an app install'); + await clickText(page, /Tune & start chatting/i); + let done = false, job = null; + for (let i = 0; i < 120 && !done; i++) { job = (await api('/api/native')).body.jobs.findLast?.(j => j.kind === 'tune') ?? null; done = !!job && job.state !== 'running'; await delay(1000); } + check(job?.state === 'done', 'tuning finishes without a vision error', job?.error ?? job?.state); + const cfg = JSON.parse(readFileSync(join(dirs.install, 'strata-iq3_s.json'), 'utf8')); + check(cfg.args.includes('--resident-budget-gib'), '"leave 20%" wrote a RAM budget for the experts', cfg.args.join(' ')); + const gib = Number(cfg.args[cfg.args.indexOf('--resident-budget-gib') + 1]); + check(gib + 10 <= 63.1 * 0.8, 'the budget keeps the model within 80% of the PC RAM', `${gib} GiB`); + // chat + reading size + await page.getByRole('textbox', { name: /Message Strata/i }).waitFor({ timeout: 60000 }); + await page.getByRole('textbox', { name: /Message Strata/i }).fill('hello'); + await page.keyboard.press('Enter'); + await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 60000 }); + await page.locator('.st-msg--assistant .st-bubble p').first().waitFor({ timeout: 60000 }).catch(async () => console.log('info reply so far:', JSON.stringify(await page.locator('.st-msg--assistant').first().innerText()).slice(0, 300))); + await page.waitForFunction(() => !document.querySelector('.st-msg--assistant .caret'), null, { timeout: 90000 }).catch(() => {}); + const sizes = []; + for (const px of [12, 16, 22]) { + await page.evaluate(v => { const k = 'strata.prefs.v2'; const cur = JSON.parse(localStorage.getItem(k) || '{}'); localStorage.setItem(k, JSON.stringify({ ...cur, contentFontSize: v })); }, px); + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 30000 }); + sizes.push(await page.evaluate(() => { const b = document.querySelector('.st-msg--assistant .st-bubble'); const t = b.querySelector('p, .md-li, span') ?? b; const u = document.querySelector('.st-msg--user .st-bubble'); const all = {}; for (const el of b.querySelectorAll('*')) { if (!el.childNodes.length || ![...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim())) continue; all[el.tagName.toLowerCase() + (el.className ? '.' + String(el.className).split(' ')[0] : '')] = parseFloat(getComputedStyle(el).fontSize); } const extra = {}; for (const [k, q] of Object.entries({ reasoning: '.st-msg--assistant .st-collapse__body', codeblock: '.st-msg--assistant .st-code pre', codehead: '.st-msg--assistant .st-code__head' })) { const e = document.querySelector(q); if (e) extra[k] = parseFloat(getComputedStyle(e).fontSize); } Object.assign(all, extra); const chain = []; for (let e = b.querySelector('p'); e && e !== b; e = e.parentElement) chain.push(e.tagName + '.' + String(e.className).split(' ')[0] + '=' + getComputedStyle(e).fontSize); all.chain = chain; globalThis.__all = all; return [parseFloat(getComputedStyle(b).fontSize), parseFloat(getComputedStyle(t).fontSize), parseFloat(getComputedStyle(u).fontSize), all]; })); + } + console.log('info chain', JSON.stringify(await page.evaluate(() => { const el = document.querySelector('.st-msg--assistant .st-bubble p'); const out = []; for (let e = el; e && !e.classList.contains('st-msg'); e = e.parentElement) out.push(e.tagName + '.' + String(e.className).split(' ')[0] + '=' + getComputedStyle(e).fontSize); return out; }))); + await shot(page, '2-chat-22px'); + console.log('info sizes', JSON.stringify(sizes), JSON.stringify(await page.locator('.st-msg--assistant .st-bubble').first().innerHTML()).slice(0, 400)); + check(sizes[0][1] === 12 && sizes[1][1] === 16 && sizes[2][1] === 22 && sizes[0][2] === 12 && sizes[2][2] === 22, 'the reading size changes the text size of the conversation', JSON.stringify(sizes)); + // the slider itself + await page.evaluate(() => { location.hash = '#/chat?settings=1'; }); + const slider = page.getByLabel('Reading text size'); + if (await slider.count()) { + await slider.first().focus(); + for (let i = 0; i < 4; i++) await page.keyboard.press('ArrowLeft'); + await delay(500); + const now = await page.evaluate(() => getComputedStyle(document.querySelector('.st-msg--assistant .st-bubble') ?? document.body).fontSize); + check(parseFloat(now) === 18, 'moving the slider changes the conversation text at once', now); + const box = await slider.first().boundingBox(); + await page.mouse.click(box.x + box.width * 0.9, box.y + box.height / 2); + await delay(400); + const dragged = await page.evaluate(() => [getComputedStyle(document.querySelector('.st-msg--assistant .st-bubble') ?? document.body).fontSize, getComputedStyle(document.documentElement).getPropertyValue('--st-content-fs'), JSON.parse(localStorage.getItem('strata.prefs.v2') || '{}').contentFontSize]); + check(parseFloat(dragged[0]) >= 20 && parseFloat(dragged[2]) >= 20, 'clicking the slider with the mouse changes it too, and it is saved', dragged.join(' ')); + } else console.log('info the settings slider was not reachable by hash here; the stored size was checked above'); + check(page.problems.length === 0, 'no page error', page.problems.join('; ')); +}); + +// ------------------------------------------------------------------------------------------------ fail +await scenario('fail', { installed: true, env: { FAKE_ENGINE_FAIL: '1' } }, async ({ base, api, browser, shot }) => { + const page = await newPage(browser, base); + await clickText(page, /get started/i); + await page.getByText(/Choose a version/i).waitFor({ timeout: 30000 }); + await page.locator('[role=radio]').filter({ hasText: 'IQ3_S' }).first().click(); + await clickText(page, /^Continue/); + await clickText(page, /Tune & start chatting/i, 30000); + await page.getByText(/ran low on memory/i).first().waitFor({ timeout: 120000 }); + await delay(1000); + await shot(page, '1-tune-error'); + const text = await page.locator('.guided-onboarding').innerText(); + check(/ran low on memory/.test(text), 'the error says in words that the PC ran low on memory'); + check(/Leave 20% for my work/.test(text) && /low-RAM/.test(text), 'and what to try'); + check(!/server_exited|memory guard/.test(text), 'no code or log line in the main text'); + check(!/vision files/i.test(text), 'no picture-reading error'); + const bad = await noScroll(page); + check(bad.length === 0, 'the tuning pop-up does not scroll when an error shows', bad.join('; ')); + await page.locator('.error-notice summary').first().click(); + await delay(500); + await shot(page, '2-tune-error-details'); + const details = await page.locator('.error-notice pre').first().innerText(); + check(/server_exited/.test(details) && /memory guard: 5\.1 GiB/.test(details), 'Details holds the code and the last engine line', details.replace(/\s+/g, ' ').slice(0, 120)); + const badOpen = await noScroll(page); + check(badOpen.length === 0, 'and the pop-up still does not scroll with Details open', badOpen.join('; ')); + await page.setViewportSize({ width: 1280, height: 700 }); + await delay(600); + const small = await noScroll(page); + check(small.length === 0, 'nor in a small window (1280x700), Details open', small.join('; ')); + await shot(page, '3-tune-error-small-window'); + void api; +}); + +// ------------------------------------------------------------------------------------------------ theme +await scenario('theme', {}, async ({ base, browser, shot }) => { + for (const scheme of ['dark', 'light']) { + const page = await newPage(browser, base, { colorScheme: scheme }); + await delay(1500); + const theme = await page.evaluate(() => document.documentElement.dataset.theme); + check(theme === scheme, `a fresh app follows the system (${scheme})`, theme); + await shot(page, `1-${scheme}`); + await page.context().close(); + } +}); + +// the junctions into the staged Control go first (rmdir on a junction removes only the link) +for (const name of ['python', 'strata_control', 'strata_cli', 'serve']) { try { rmdirSync(join(control, name)); } catch { /* already gone */ } } +try { rmSync(work, { recursive: true, force: true, maxRetries: 3 }); } catch (e) { console.log('info scratch folder left behind:', work); } +console.log(`shots in ${shots}`); +process.exit(failed ? 1 : 0); diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 515c95fd..a71519ca 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -42,11 +42,9 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp function sourceText(){try{return readFileSync(join(packaged?control.control.dir:preferences.repo,'serve/server.py'),'utf8');}catch{return '';}} function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));} const modelArena=id=>({arenaGb:(snapshot.catalog?.families??[]).flatMap(f=>f.sizes??[]).find(s=>s.id===id)?.experts_gb}); - /* A start that ends with `server_exited` says nothing a person can act on. The usual cause is the PC running low on memory - (the engine's own guard, or the OS); say that, what to try, and the last thing the engine wrote. */ - function humanStartError(error){const text=String(error?.message??error),tail=error?.output?.log_tail; - if(!/server_exited|exited|memory|killed|oom/i.test(text)&&!/memory|alloc|guard|killed/i.test(tail??''))return text; - return `The engine stopped before it was ready, most likely because the PC ran low on memory. Close other programs and try again, choose “Leave 20% for my work”, or turn on the low-RAM option so part of the model is read from the SSD instead of kept in memory.${tail?` Last engine message: ${tail}`:''}`;} + /* A start that ends with `server_exited` carries the engine's last log line with it; the app turns the code into words and + keeps this text under "Details" (src/lib/plain-errors.ts). */ + function humanStartError(error){const text=String(error?.message??error),tail=error?.output?.log_tail;return tail&&!text.includes(tail)?`${text}: ${tail}`:text;} function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} function installRoot(){const found=[preferences.installDir,packagedInstall,snapshot.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());} function repo(){if(packaged)return installRoot();const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;} diff --git a/apps/host/src/components/GuidedSetup.tsx b/apps/host/src/components/GuidedSetup.tsx index 1e71c64c..4bbe713e 100644 --- a/apps/host/src/components/GuidedSetup.tsx +++ b/apps/host/src/components/GuidedSetup.tsx @@ -12,7 +12,7 @@ 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 { useDownloadEta } from '../lib/download-eta'; +import { installProgress, useDownloadEta } from '../lib/download-eta'; 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)) @@ -142,7 +142,7 @@ export function GuidedSetup() { await persist(4, { tuneJobId: result.id }); }); } - const progress = installJob?.result?.install?.download; + const progress = installProgress(installJob?.result?.install); const preparing = installJob?.state === 'running'; const stopped = installJob && ['error', 'cancelled'].includes(installJob.state); useEffect(() => { diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 2501f5ca..3de86f6c 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -2,7 +2,8 @@ import { tr } from '../lib/i18n'; import { useEffect, useMemo, useRef, useState } from 'react'; import { Screen } from './layout'; import { Btn, Dialog, ErrorNotice, Icon, Select } from './ui'; -import { useDownloadEta } from '../lib/download-eta'; +import { installProgress, useDownloadEta } from '../lib/download-eta'; +import { plainFailureText } from '../lib/plain-errors'; import { api } from '../lib/client'; import { go, setSettingsSection, selectRemoteModel, pushToast } from '../lib/store'; import { nativeAction, useNative, type NativeJob } from '../lib/native'; @@ -86,11 +87,11 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine 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")}
: null)}
- {tr(native?.instances.length && expert ?

{tr(native.instances.length === 1 ? 'Loaded model' : 'Loaded models')}

{tr(native.instances.map(i =>
{tr(i.label)}{tr(i.gpus.length ? i.gpus.map(g => `GPU ${g + 1}`).join(' + ') : 'Automatic GPU')} · {tr(i.status === 'ready' ? i.phase : i.status)}{tr(native.defaultId === i.id ? ' · Chat default' : '')}{tr(i.error ? {tr(i.error)} : null)}{tr(expert && multiple && native.defaultId !== i.id ? void perform(() => nativeAction(`instances/${i.id}/default`))}>{tr("Use in chat")} : null)} void perform(() => nativeAction(`instances/${i.id}/unload`))}>{tr("Unload")}
))}
: null)} + {tr(native?.instances.length && expert ?

{tr(native.instances.length === 1 ? 'Loaded model' : 'Loaded models')}

{tr(native.instances.map(i =>
{tr(i.label)}{tr(i.gpus.length ? i.gpus.map(g => `GPU ${g + 1}`).join(' + ') : 'Automatic GPU')} · {tr(i.status === 'ready' ? i.phase : i.status)}{tr(native.defaultId === i.id ? ' · Chat default' : '')}{tr(i.error ? {tr(plainFailureText(i.error).message)} : null)}{tr(expert && multiple && native.defaultId !== i.id ? void perform(() => nativeAction(`instances/${i.id}/default`))}>{tr("Use in chat")} : null)} void perform(() => nativeAction(`instances/${i.id}/unload`))}>{tr("Unload")}
))}
: null)}
{tr(selectedFamily && !selectedSize ? <>

{tr("This model needs a newer engine.")}

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

{ setSettingsSection('Engine'); go('settings'); }}>{tr("Update engine")}{tr("Use a local GGUF\u2026")} : null)}{tr(!selectedFamily ? <>

{tr("Set up Strata")}

{tr("Connect your local installation to choose an optimized model.")}

{ setSettingsSection('Engine'); go('settings'); })}>{tr("Connect engine")}{tr(native?.error ?

{tr(native.error)}

: null)}{tr("Other local models")} : null)} {tr(selectedSize ? <>{tr(expert && vision !== 'no' ? setVision(e.target.checked ? 'yes' : 'no')}/>{tr("Read pictures ")}{tr("Optional")}{tr("Understand photos, screenshots and charts. Vision files download automatically. Enable them when loading this model.")}{tr(expert && vision !== 'no' ? ({ value: String(n), label: `${n / 1024}K` }))} onChange={n => setContext(Number(n))}/>
: null)} @@ -111,7 +112,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine } export function NativeProgress({ job }: { job: NativeJob; -}) { const download = job.result?.install?.download; const eta = useDownloadEta(job.kind === 'install' ? download : undefined, job.id); const [stopping, setStopping] = useState(false), [error, setError] = useState(''); async function stop() { setStopping(true); setError(''); try { +}) { const download = installProgress(job.result?.install); const detailsText = [job.details, job.result?.install?.engine?.details].filter(Boolean).join('\n'); const eta = useDownloadEta(job.kind === 'install' ? download : undefined, job.id); const [stopping, setStopping] = useState(false), [error, setError] = useState(''); async function stop() { setStopping(true); setError(''); try { await nativeAction(`operations/${job.id}/cancel`); } catch (e) { @@ -119,4 +120,4 @@ catch (e) { } finally { setStopping(false); -} } return

{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : 'Engine operation')}

{tr(job.kind === 'install' || job.kind === 'load' ?
{tr(eta ? {eta} : null)} void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}
: null)}

{tr(job.kind === 'install' ? (job.result?.install?.step ?? 'Downloading and preparing model files…') : job.summary)}

{tr(download ? <>

{tr(download.file)} · {tr(download.percent ?? 0)}%{tr(Number.isFinite(download.done_gb) && Number.isFinite(download.total_gb) ? ` · ${download.done_gb!.toFixed(1)} / ${download.total_gb!.toFixed(1)} GB` : '')}

: null)}
{tr("Details")}

{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}

{tr(error ? : null)}
; } +} } return

{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : 'Engine operation')}

{tr(job.kind === 'install' || job.kind === 'load' ?
{tr(eta ? {eta} : null)} void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}
: null)}

{tr(job.kind === 'install' ? (job.result?.install?.step ?? 'Downloading and preparing model files…') : job.summary)}

{tr(download ? <>

{tr(download.file)} · {tr(download.percent ?? 0)}%{tr(Number.isFinite(download.done_gb) && Number.isFinite(download.total_gb) ? ` · ${download.done_gb!.toFixed(1)} / ${download.total_gb!.toFixed(1)} GB` : '')}

: null)}
{tr("Details")}

{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}

{tr(detailsText ?
{detailsText}
: null)}
{tr(error ? : null)}
; } diff --git a/apps/host/src/components/ui.tsx b/apps/host/src/components/ui.tsx index 7b4c27f3..b7b3da7d 100644 --- a/apps/host/src/components/ui.tsx +++ b/apps/host/src/components/ui.tsx @@ -10,6 +10,7 @@ import { tr } from '../lib/i18n'; import { createContext, useContext, useCallback, useEffect, useId, useRef, useState, type AriaAttributes, type CSSProperties, type ReactNode } from 'react'; import { createPortal } from 'react-dom'; import { cx, userError } from '../lib/format'; +import { plainFailure } from '../lib/plain-errors'; import { dismissActionError, dismissToast, holdToast, releaseToast, useStore } from '../lib/store'; import { isTopSurface, useSurfaceFocus } from '../lib/focus'; /* -------------------------------------------------------------------- icon */ @@ -514,12 +515,18 @@ export function MetricGrid({ children, min = 200 }: {
); } /** Shared, announced error with a cause and a concrete recovery action. */ -export function ErrorNotice({ message, next, action, onRetry }: { +export function ErrorNotice({ message, next, action, onRetry, detail }: { message: string; next?: string; action?: string; onRetry?: () => void; + detail?: string; }) { - return
{tr(userError(message))}{tr(next ?

{tr(next)}

: null)}
{tr(onRetry ? {tr(action ?? 'Try again')} : null)}
; + // A known failure is shown as a sentence and a next step; the original text stays under Details for experts. + const plain = plainFailure(message); + const known = plain.kind !== 'plain'; + const nextStep = known ? (plain.next ? tr(plain.next) : next) : next; + const raw = detail ?? (known ? plain.detail : undefined); + return
{tr(known ? plain.message : userError(message))}{tr(nextStep ?

{tr(nextStep)}

: null)}{tr(raw ?
{tr("Details")}
{raw}
: null)}
{tr(onRetry ? {tr(action ?? 'Try again')} : null)}
; } export function PreviewBadge() { const demo = useStore(s => s.library?.mode === 'simulated'); return demo ? {tr("Preview build")} : null; } diff --git a/apps/host/src/lib/download-eta.ts b/apps/host/src/lib/download-eta.ts index 6cb46670..64b5c556 100644 --- a/apps/host/src/lib/download-eta.ts +++ b/apps/host/src/lib/download-eta.ts @@ -13,8 +13,11 @@ export function etaMinutes(samples: { at: number; done: number }[], remainingGb: export function etaLabel(minutes: number | null): string { if (minutes === null) return ''; - if (minutes >= 90) { const h = Math.floor(minutes / 60), m = minutes % 60; return `${tr('About')} ${h} ${tr('h')}${m ? ` ${m} ${tr('min')}` : ''} ${tr('left')}`; } - return `${tr('About')} ${minutes} ${tr('min left')}`; + if (minutes >= 90) { + const h = Math.floor(minutes / 60), m = minutes % 60; + return m ? tr('About {0} h {1} min left', [h, m]) : tr('About {0} h left', [h]); + } + return tr('About {0} min left', [minutes]); } /** The approximate time left of a running download, for the progress bar. `key` restarts the estimate for another job. */ @@ -34,3 +37,19 @@ export function useDownloadEta(download: { done_gb?: number; remaining_gb?: numb }, [done, remaining, key]); return label; } + +/** What the progress UI reads from an install job's `install` object: the parts it is downloading (the model's files and, + * when the job adds it, the engine) summed into ONE count. A part is {kind, name, done_gb, total_gb, state}. Without `parts` + * the job's combined `download` fields ({done_gb, total_gb, remaining_gb, percent}) are used as they are. */ +export interface InstallParts { parts?: { done_gb?: number; total_gb?: number; state?: string }[]; download?: { done_gb?: number; total_gb?: number; remaining_gb?: number; percent?: number; file?: string } } +export function installProgress(install: InstallParts | undefined): { done_gb: number; total_gb: number; remaining_gb: number; percent: number; file?: string } | undefined { + const parts = (install?.parts ?? []).filter(p => Number.isFinite(p.total_gb) && (p.total_gb ?? 0) > 0 && p.state !== 'skipped' && p.state !== 'current'); + if (parts.length) { + const total = parts.reduce((n, p) => n + (p.total_gb ?? 0), 0); + const done = Math.min(total, parts.reduce((n, p) => n + Math.min(p.done_gb ?? 0, p.total_gb ?? 0), 0)); + return { done_gb: done, total_gb: total, remaining_gb: Math.max(0, total - done), percent: Math.min(99, Math.floor(100 * done / total)), file: install?.download?.file }; + } + const d = install?.download; + 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; +} diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.ts index b4fb4df8..fbdd66e2 100644 --- a/apps/host/src/lib/native.ts +++ b/apps/host/src/lib/native.ts @@ -4,7 +4,7 @@ import type { Hardware, RuntimeModels } from './types'; export interface NativeSize {id:string;model:string;about:string;download_gb:number;ram_needed_gb:number;experts_gb:number;on_this_pc:string|null;installed: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;result:Record|null} +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} export interface NativeInstance {id:string;apiModelId:string;model:string;label:string;aliases?:string[];vision?:boolean;context?:number;port:number;gpus:number[];status:'loading'|'ready'|'unloading'|'error';phase:string;loadedAt:string;error:string|null;metrics:Record|null} export interface NativeState {available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;missing_files?:string[]}[];data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;gpus:{index:number;name:string;vram_gb:number;usable:boolean}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean}} let state:NativeState|null=null,timer:ReturnType|null=null,reading:Promise|null=null; diff --git a/apps/host/src/lib/plain-errors.ts b/apps/host/src/lib/plain-errors.ts new file mode 100644 index 00000000..23f30561 --- /dev/null +++ b/apps/host/src/lib/plain-errors.ts @@ -0,0 +1,44 @@ +/** + * Plain words for failures. The host and Control speak in codes and log lines (`server_exited`, exit codes, "component-missing", + * a Python message); a person needs what happened and what to do next. Every message the UI shows through ErrorNotice or a toast + * passes through here: a known failure becomes a sentence and a next step, and the original text stays one click away under + * "Details" for experts. Strings are fixed so every language has them. + */ +import { tr } from './i18n'; + +export interface PlainFailure { message: string; next?: string; detail?: string; kind: string } + +interface Rule { kind: string; match: RegExp; message: string; next?: string; detail?: (m: RegExpMatchArray, raw: string) => string | undefined } + +const MEMORY = 'The model stopped while starting, most likely because the PC ran low on memory.'; +const MEMORY_NEXT = 'Close other programs and try again, or choose “Leave 20% for my work”. In Expert mode you can also turn on the low-RAM option, so part of the model is read from the SSD.'; + +/** Order matters: the first rule that matches wins. */ +const RULES: Rule[] = [ + { kind: 'picture-reading', match: /vision files|picture reading/i, message: 'Picture reading isn’t available for this model.', next: 'Turn off picture reading and try again.' }, + { kind: 'memory', match: /server_exited|engine stopped|exited before|died before|out of memory|memory guard|\boom\b|killed/i, message: MEMORY, next: MEMORY_NEXT }, + { kind: 'slow-load', match: /loading took more than/i, message: 'Loading is taking too long.', next: 'The PC may be short on memory. Close other programs and try again.' }, + { kind: 'engine-missing', match: /no engine for this pc|engine component|never downloads an engine|engine .*not installed|no strata engine/i, message: 'Strata’s engine for this computer isn’t installed yet.', next: 'It is added when you download a model. Download your model again to add it.' }, + { kind: 'network', match: /cannot reach|could not reach|can't reach|timed out|econn|enotfound|getaddrinfo|urlopen|connection (?:reset|refused|aborted)|network is unreachable/i, message: 'The download couldn’t reach the internet.', next: 'Check your connection, then press Resume download.' }, + { kind: 'integrity', match: /sha-?256|checksum|does not match|did not match|hash mismatch|safety check/i, message: 'A downloaded file didn’t pass Strata’s safety check.', next: 'Press Resume download and Strata will fetch it again.' }, + { kind: 'assistant-missing', match: /agent component|deepseek harness|component-missing|harness .*not (?:installed|found)/i, message: 'The coding assistant isn’t installed on this computer yet.', next: 'Chat works without it.' }, + { kind: 'control', match: /strata control (?:could not start|did not answer|stopped)|control did not answer/i, message: 'Strata couldn’t read its own components.', next: 'Close and reopen Strata. If this keeps happening, reinstall the app.' }, + { kind: 'technical', match: /traceback|\bexit(?:ed)?(?: code)? \d+|errno|ERR_[A-Z_]+|\bat \S+:\d+|\[X\]|\bENOENT\b|\bEPERM\b|\bEACCES\b/i, message: 'Something went wrong.', next: 'Try again. If it keeps happening, open Details and share them when you ask for help.' }, +]; + +/** The message as a person should read it, its next step, and the original text for the Details disclosure. */ +export function plainFailure(raw: string | null | undefined): PlainFailure { + const text = String(raw ?? '').replace(/^\s*Fixture:\s*/i, '').trim(); + for (const rule of RULES) { + const m = text.match(rule.match); + if (!m) continue; + return { kind: rule.kind, message: rule.message, next: rule.next, detail: rule.detail ? rule.detail(m, text) : text }; + } + return { kind: 'plain', message: text.replace(/^./, c => c.toUpperCase()) }; +} + +/** Translated copy of a failure, ready to show. */ +export function plainFailureText(raw: string | null | undefined) { + const f = plainFailure(raw); + return { ...f, message: tr(f.message), next: f.next ? tr(f.next) : undefined }; +} diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts index 24901631..18703366 100644 --- a/apps/host/src/lib/store.ts +++ b/apps/host/src/lib/store.ts @@ -1,3 +1,4 @@ +import { plainFailure, plainFailureText } from './plain-errors'; import { showcaseMessages, SHOWCASE_AGENTS } from './chat-showcase'; import { updateAgent } from './agents'; import { TIME_SKIP_DURATION, timeSkipPrompt, timeSkipTabId, withTimeSkipResult, type TimeSkipRun, type TimeSkipVersion } from './time-skip'; @@ -1341,7 +1342,7 @@ export async function sendMessage(text: string) { } else if (type === 'notice') { // The host says why this chat is not using the agent. One toast per reason per page load. const code = String(frame.code ?? 'notice'); - if (!noticed.has(code)) { noticed.add(code); pushToast('info', 'Agent', String(frame.message ?? '')); } + if (!noticed.has(code)) { noticed.add(code); pushToast('info', 'Agent', plainFailureText(String(frame.message ?? '')).message); } } else if (type === 'agent-tool') { const tool = frame.tool as ToolCall; patchAssistant(m => { @@ -1368,7 +1369,7 @@ export async function sendMessage(text: string) { tps: typeof frame.tps === 'number' ? frame.tps : m.tps, })); } else if (type === 'error') { - patchAssistant((m) => ({ ...m, error: String(frame.message ?? 'Engine error'), streaming: false })); + patchAssistant((m) => ({ ...m, error: plainFailure(String(frame.message ?? 'Engine error')).message, streaming: false })); } else if (type === 'done') { patchSession(sessionId, (sess) => ({ ...sess, diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.json index 0c48de2e..5ade6d0d 100644 --- a/apps/host/src/locales/de.json +++ b/apps/host/src/locales/de.json @@ -2568,5 +2568,27 @@ "s2567": "Prüfe, ob die Engine verbunden und dieses Modell installiert ist, und versuche es erneut.", "s2568": "Ausgeführt", "s2569": "In diesem Modus nicht erlaubt. Es wurde nichts ausgeführt.", - "s2570": "Vorschau erneut abspielen" + "s2570": "Vorschau erneut abspielen", + "s2571": "Noch etwa {0} Min.", + "s2572": "Noch etwa {0} Std. {1} Min.", + "s2573": "Noch etwa {0} Std.", + "s2574": "Standardmäßig folgt es den Einstellungen Ihres Computers.", + "s2575": "Für dieses Modell ist das Lesen von Bildern nicht verfügbar.", + "s2576": "Schalten Sie das Lesen von Bildern aus und versuchen Sie es erneut.", + "s2577": "Das Modell wurde beim Start beendet, wahrscheinlich weil dem PC der Arbeitsspeicher ausging.", + "s2578": "Schließen Sie andere Programme und versuchen Sie es erneut, oder wählen Sie „20 % für meine Arbeit frei lassen“. Im Expertenmodus können Sie außerdem die Option für wenig Arbeitsspeicher aktivieren, damit ein Teil des Modells von der SSD gelesen wird.", + "s2579": "Das Laden dauert zu lange.", + "s2580": "Dem PC fehlt möglicherweise Arbeitsspeicher. Schließen Sie andere Programme und versuchen Sie es erneut.", + "s2581": "Die Strata-Engine für diesen Computer ist noch nicht installiert.", + "s2582": "Sie wird beim Herunterladen eines Modells hinzugefügt. Laden Sie Ihr Modell erneut herunter, um sie hinzuzufügen.", + "s2583": "Der Download konnte das Internet nicht erreichen.", + "s2584": "Prüfen Sie Ihre Verbindung und drücken Sie dann „Download fortsetzen“.", + "s2585": "Eine heruntergeladene Datei hat die Sicherheitsprüfung von Strata nicht bestanden.", + "s2586": "Drücken Sie „Download fortsetzen“, dann lädt Strata sie erneut herunter.", + "s2587": "Der Coding-Assistent ist auf diesem Computer noch nicht installiert.", + "s2588": "Der Chat funktioniert auch ohne ihn.", + "s2589": "Strata konnte seine eigenen Komponenten nicht lesen.", + "s2590": "Schließen Sie Strata und öffnen Sie es erneut. Tritt das Problem weiterhin auf, installieren Sie die App neu.", + "s2591": "Etwas ist schiefgelaufen.", + "s2592": "Versuchen Sie es erneut. Tritt das Problem weiterhin auf, öffnen Sie „Details“ und geben Sie diese bei einer Supportanfrage an." } diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.json index 7ce504b5..de1c65cd 100644 --- a/apps/host/src/locales/en.json +++ b/apps/host/src/locales/en.json @@ -2568,5 +2568,27 @@ "s2567": "Check that the engine is connected and this model is installed, then try again.", "s2568": "Ran", "s2569": "Not allowed in this mode. Nothing ran.", - "s2570": "Replay preview" + "s2570": "Replay preview", + "s2571": "About {0} min left", + "s2572": "About {0} h {1} min left", + "s2573": "About {0} h left", + "s2574": "System follows your computer by default.", + "s2575": "Picture reading isn’t available for this model.", + "s2576": "Turn off picture reading and try again.", + "s2577": "The model stopped while starting, most likely because the PC ran low on memory.", + "s2578": "Close other programs and try again, or choose “Leave 20% for my work”. In Expert mode you can also turn on the low-RAM option, so part of the model is read from the SSD.", + "s2579": "Loading is taking too long.", + "s2580": "The PC may be short on memory. Close other programs and try again.", + "s2581": "Strata’s engine for this computer isn’t installed yet.", + "s2582": "It is added when you download a model. Download your model again to add it.", + "s2583": "The download couldn’t reach the internet.", + "s2584": "Check your connection, then press Resume download.", + "s2585": "A downloaded file didn’t pass Strata’s safety check.", + "s2586": "Press Resume download and Strata will fetch it again.", + "s2587": "The coding assistant isn’t installed on this computer yet.", + "s2588": "Chat works without it.", + "s2589": "Strata couldn’t read its own components.", + "s2590": "Close and reopen Strata. If this keeps happening, reinstall the app.", + "s2591": "Something went wrong.", + "s2592": "Try again. If it keeps happening, open Details and share them when you ask for help." } diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.json index 9ebba966..9be5f93d 100644 --- a/apps/host/src/locales/es.json +++ b/apps/host/src/locales/es.json @@ -2568,5 +2568,27 @@ "s2567": "Comprueba que el motor esté conectado y este modelo esté instalado. Después, inténtalo de nuevo.", "s2568": "Ejecutado", "s2569": "No se permite en este modo. No se ejecutó nada.", - "s2570": "Repetir vista previa" + "s2570": "Repetir vista previa", + "s2571": "Quedan unos {0} min", + "s2572": "Quedan unas {0} h {1} min", + "s2573": "Quedan unas {0} h", + "s2574": "De forma predeterminada sigue el ajuste de tu equipo.", + "s2575": "La lectura de imágenes no está disponible para este modelo.", + "s2576": "Desactiva la lectura de imágenes e inténtalo de nuevo.", + "s2577": "El modelo se detuvo al iniciarse, probablemente porque el equipo se quedó sin memoria.", + "s2578": "Cierra otros programas e inténtalo de nuevo, o elige «Dejar el 20 % para mi trabajo». En el modo experto también puedes activar la opción de poca RAM para que una parte del modelo se lea desde el SSD.", + "s2579": "La carga está tardando demasiado.", + "s2580": "Puede que al equipo le falte memoria. Cierra otros programas e inténtalo de nuevo.", + "s2581": "El motor de Strata para este equipo aún no está instalado.", + "s2582": "Se añade al descargar un modelo. Vuelve a descargar tu modelo para añadirlo.", + "s2583": "La descarga no pudo conectarse a internet.", + "s2584": "Revisa tu conexión y pulsa «Reanudar descarga».", + "s2585": "Un archivo descargado no superó la comprobación de seguridad de Strata.", + "s2586": "Pulsa «Reanudar descarga» y Strata la obtendrá de nuevo.", + "s2587": "El asistente de programación aún no está instalado en este equipo.", + "s2588": "El chat funciona sin él.", + "s2589": "Strata no pudo leer sus propios componentes.", + "s2590": "Cierra y vuelve a abrir Strata. Si sigue ocurriendo, reinstala la aplicación.", + "s2591": "Algo salió mal.", + "s2592": "Inténtalo de nuevo. Si sigue ocurriendo, abre «Detalles» y compártelos cuando pidas ayuda." } diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.json index 0a8afb22..7a9adc0f 100644 --- a/apps/host/src/locales/ja.json +++ b/apps/host/src/locales/ja.json @@ -2568,5 +2568,27 @@ "s2567": "エンジンが接続され、このモデルがインストールされていることを確認してから、もう一度お試しください。", "s2568": "実行済み", "s2569": "このモードでは許可されていません。何も実行していません。", - "s2570": "プレビューを再生" + "s2570": "プレビューを再生", + "s2571": "あと約 {0} 分", + "s2572": "あと約 {0} 時間 {1} 分", + "s2573": "あと約 {0} 時間", + "s2574": "既定ではお使いのコンピューターの設定に従います。", + "s2575": "このモデルでは画像の読み取りを使えません。", + "s2576": "画像の読み取りをオフにして、もう一度お試しください。", + "s2577": "モデルの起動中に停止しました。パソコンのメモリ不足が原因と考えられます。", + "s2578": "他のプログラムを閉じてもう一度お試しいただくか、「作業用に 20% を残す」を選んでください。エキスパートモードでは、低メモリのオプションをオンにして、モデルの一部を SSD から読み込むこともできます。", + "s2579": "読み込みに時間がかかっています。", + "s2580": "パソコンのメモリが足りない可能性があります。他のプログラムを閉じて、もう一度お試しください。", + "s2581": "このコンピューター用の Strata エンジンはまだインストールされていません。", + "s2582": "モデルをダウンロードするときに一緒に追加されます。もう一度モデルをダウンロードして追加してください。", + "s2583": "ダウンロードがインターネットに接続できませんでした。", + "s2584": "接続を確認してから、「ダウンロードを再開」を押してください。", + "s2585": "ダウンロードしたファイルが Strata の安全性チェックに合格しませんでした。", + "s2586": "「ダウンロードを再開」を押すと、Strata がもう一度取得します。", + "s2587": "このコンピューターにはコーディングアシスタントがまだインストールされていません。", + "s2588": "これがなくてもチャットは使えます。", + "s2589": "Strata が自身のコンポーネントを読み取れませんでした。", + "s2590": "Strata を閉じて開き直してください。それでも改善しない場合は、アプリを再インストールしてください。", + "s2591": "問題が発生しました。", + "s2592": "もう一度お試しください。それでも解決しない場合は「詳細」を開き、サポートに問い合わせる際に共有してください。" } diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.json index b5f36565..5f683a47 100644 --- a/apps/host/src/locales/ko.json +++ b/apps/host/src/locales/ko.json @@ -2568,5 +2568,27 @@ "s2567": "엔진이 연결되어 있고 이 모델이 설치되어 있는지 확인한 후 다시 시도하세요.", "s2568": "실행됨", "s2569": "이 모드에서는 허용되지 않습니다. 실행된 항목이 없습니다.", - "s2570": "미리보기 다시 재생" + "s2570": "미리보기 다시 재생", + "s2571": "약 {0}분 남음", + "s2572": "약 {0}시간 {1}분 남음", + "s2573": "약 {0}시간 남음", + "s2574": "기본적으로 컴퓨터 설정을 따릅니다.", + "s2575": "이 모델에서는 이미지 읽기를 사용할 수 없습니다.", + "s2576": "이미지 읽기를 끄고 다시 시도하세요.", + "s2577": "모델이 시작 중에 멈췄습니다. 컴퓨터의 메모리가 부족했을 가능성이 큽니다.", + "s2578": "다른 프로그램을 닫고 다시 시도하거나 “작업용으로 20% 남기기”를 선택하세요. 전문가 모드에서는 저메모리 옵션을 켜서 모델의 일부를 SSD에서 읽게 할 수도 있습니다.", + "s2579": "불러오는 데 시간이 너무 오래 걸립니다.", + "s2580": "컴퓨터의 메모리가 부족할 수 있습니다. 다른 프로그램을 닫고 다시 시도하세요.", + "s2581": "이 컴퓨터용 Strata 엔진이 아직 설치되지 않았습니다.", + "s2582": "모델을 다운로드할 때 함께 추가됩니다. 모델을 다시 다운로드하여 추가하세요.", + "s2583": "다운로드가 인터넷에 연결되지 않았습니다.", + "s2584": "연결을 확인한 다음 “다운로드 재개”를 누르세요.", + "s2585": "다운로드한 파일이 Strata의 안전 검사를 통과하지 못했습니다.", + "s2586": "“다운로드 재개”를 누르면 Strata가 다시 받아옵니다.", + "s2587": "이 컴퓨터에는 코딩 어시스턴트가 아직 설치되지 않았습니다.", + "s2588": "없어도 채팅은 사용할 수 있습니다.", + "s2589": "Strata가 자체 구성 요소를 읽지 못했습니다.", + "s2590": "Strata를 닫았다가 다시 여세요. 계속되면 앱을 다시 설치하세요.", + "s2591": "문제가 발생했습니다.", + "s2592": "다시 시도하세요. 계속되면 “세부 정보”를 열어 도움을 요청할 때 함께 알려 주세요." } diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.json index 41853a9d..8b5e6180 100644 --- a/apps/host/src/locales/pt.json +++ b/apps/host/src/locales/pt.json @@ -2568,5 +2568,27 @@ "s2567": "Verifique se o mecanismo está conectado e este modelo está instalado. Depois, tente novamente.", "s2568": "Executado", "s2569": "Não permitido neste modo. Nada foi executado.", - "s2570": "Repetir prévia" + "s2570": "Repetir prévia", + "s2571": "Faltam cerca de {0} min", + "s2572": "Faltam cerca de {0} h {1} min", + "s2573": "Faltam cerca de {0} h", + "s2574": "Por padrão, segue a configuração do seu computador.", + "s2575": "A leitura de imagens não está disponível para este modelo.", + "s2576": "Desative a leitura de imagens e tente novamente.", + "s2577": "O modelo parou ao iniciar, provavelmente porque o computador ficou sem memória.", + "s2578": "Feche outros programas e tente novamente, ou escolha “Deixar 20% para o meu trabalho”. No modo especialista, você também pode ativar a opção de pouca RAM, para que parte do modelo seja lida do SSD.", + "s2579": "O carregamento está levando tempo demais.", + "s2580": "O computador pode estar com pouca memória. Feche outros programas e tente novamente.", + "s2581": "O motor do Strata para este computador ainda não está instalado.", + "s2582": "Ele é adicionado ao baixar um modelo. Baixe seu modelo novamente para adicioná-lo.", + "s2583": "O download não conseguiu acessar a internet.", + "s2584": "Verifique sua conexão e pressione “Retomar download”.", + "s2585": "Um arquivo baixado não passou na verificação de segurança do Strata.", + "s2586": "Pressione “Retomar download” e o Strata o baixará novamente.", + "s2587": "O assistente de programação ainda não está instalado neste computador.", + "s2588": "O chat funciona sem ele.", + "s2589": "O Strata não conseguiu ler seus próprios componentes.", + "s2590": "Feche e abra o Strata novamente. Se o problema continuar, reinstale o aplicativo.", + "s2591": "Algo deu errado.", + "s2592": "Tente novamente. Se o problema continuar, abra “Detalhes” e compartilhe-os ao pedir ajuda." } diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.json index af230036..466e4908 100644 --- a/apps/host/src/locales/ru.json +++ b/apps/host/src/locales/ru.json @@ -2568,5 +2568,27 @@ "s2567": "Убедитесь, что движок подключён и эта модель установлена, затем повторите попытку.", "s2568": "Выполнено", "s2569": "В этом режиме не разрешено. Ничего не запущено.", - "s2570": "Повторить просмотр" + "s2570": "Повторить просмотр", + "s2571": "Осталось около {0} мин", + "s2572": "Осталось около {0} ч {1} мин", + "s2573": "Осталось около {0} ч", + "s2574": "По умолчанию используется настройка вашего компьютера.", + "s2575": "Чтение изображений недоступно для этой модели.", + "s2576": "Отключите чтение изображений и повторите попытку.", + "s2577": "Модель остановилась при запуске, скорее всего из-за нехватки памяти на компьютере.", + "s2578": "Закройте другие программы и повторите попытку или выберите «Оставить 20% для моей работы». В режиме эксперта можно также включить режим малого объёма ОЗУ: часть модели будет читаться с SSD.", + "s2579": "Загрузка занимает слишком много времени.", + "s2580": "Возможно, на компьютере не хватает памяти. Закройте другие программы и повторите попытку.", + "s2581": "Движок Strata для этого компьютера ещё не установлен.", + "s2582": "Он добавляется при загрузке модели. Загрузите модель ещё раз, чтобы добавить его.", + "s2583": "Не удалось подключиться к интернету для загрузки.", + "s2584": "Проверьте подключение и нажмите «Возобновить загрузку».", + "s2585": "Загруженный файл не прошёл проверку безопасности Strata.", + "s2586": "Нажмите «Возобновить загрузку», и Strata загрузит файл заново.", + "s2587": "Помощник по программированию ещё не установлен на этом компьютере.", + "s2588": "Чат работает и без него.", + "s2589": "Strata не удалось прочитать собственные компоненты.", + "s2590": "Закройте и снова откройте Strata. Если проблема повторяется, переустановите приложение.", + "s2591": "Что-то пошло не так.", + "s2592": "Повторите попытку. Если проблема остаётся, откройте «Подробности» и приложите их, когда будете обращаться за помощью." } diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.json index 83e2e3e5..72468802 100644 --- a/apps/host/src/locales/zh.json +++ b/apps/host/src/locales/zh.json @@ -2568,5 +2568,27 @@ "s2567": "请确认引擎已连接且此模型已安装,然后重试。", "s2568": "已运行", "s2569": "此模式下不允许,未执行任何操作。", - "s2570": "重播预览" + "s2570": "重播预览", + "s2571": "大约还需 {0} 分钟", + "s2572": "大约还需 {0} 小时 {1} 分钟", + "s2573": "大约还需 {0} 小时", + "s2574": "默认跟随你的电脑设置。", + "s2575": "此模型暂不支持读取图片。", + "s2576": "请关闭图片读取后重试。", + "s2577": "模型在启动时停止了,很可能是因为电脑内存不足。", + "s2578": "请关闭其他程序后重试,或选择“为我的工作留出 20%”。在专家模式中,你还可以开启低内存选项,让模型的一部分从固态硬盘读取。", + "s2579": "加载时间过长。", + "s2580": "电脑内存可能不足。请关闭其他程序后重试。", + "s2581": "这台电脑还没有安装 Strata 引擎。", + "s2582": "下载模型时会一并添加。请重新下载你的模型来添加它。", + "s2583": "下载无法连接到互联网。", + "s2584": "请检查网络连接,然后点击“继续下载”。", + "s2585": "有一个下载的文件未通过 Strata 的安全检查。", + "s2586": "点击“继续下载”,Strata 会重新获取该文件。", + "s2587": "这台电脑还没有安装编程助手。", + "s2588": "没有它也可以正常聊天。", + "s2589": "Strata 无法读取自身的组件。", + "s2590": "请关闭并重新打开 Strata。如果问题持续出现,请重新安装该应用。", + "s2591": "出了点问题。", + "s2592": "请重试。如果问题持续出现,请展开“详情”,并在求助时一并提供。" } diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index b00cdf8c..b37f74af 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -6993,3 +6993,15 @@ textarea { white-space: normal; padding: 8px; } + +/* The reading size reaches everything in a conversation, not only paragraphs: headings, inline code, tables, code blocks and the + model's reasoning keep their usual proportion (18px, 13px, 13px at the 16px default) at any size. */ +.st-bubble h2, .st-bubble h3, .st-bubble h4 { font-size: 1.125em; } +.st-bubble .md-code { font-size: .8125em; } +.st-bubble .md-table { font-size: calc(var(--st-content-fs, 16px) * .8125); } +.st-bubble .md-table th, .st-bubble .md-table td { font-size: inherit; } +.st-bubble .st-code pre, .st-bubble .st-code pre code, .st-bubble .st-code .syntax-text { font-size: calc(var(--st-content-fs, 16px) * .8125); } +.st-msg--assistant .st-collapse__body { font-size: calc(var(--st-content-fs, 16px) * .8125); } +.error-notice .error-detail { margin-top: 6px; } +.error-notice .error-detail pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: 6px 0 0; font-family: var(--st-font-mono); } +.error-detail-text { white-space: pre-wrap; overflow-wrap: anywhere; margin: 6px 0 0; font-family: var(--st-font-mono); } diff --git a/apps/host/src/styles/onboarding.css b/apps/host/src/styles/onboarding.css index cc88ad03..84e885c6 100644 --- a/apps/host/src/styles/onboarding.css +++ b/apps/host/src/styles/onboarding.css @@ -242,3 +242,4 @@ @keyframes onboard-sharing-flow{to{transform:translateX(100%)}} @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} diff --git a/apps/host/tests/download-eta.test.mjs b/apps/host/tests/download-eta.test.mjs new file mode 100644 index 00000000..70ee005b --- /dev/null +++ b/apps/host/tests/download-eta.test.mjs @@ -0,0 +1,39 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { build } from 'esbuild'; + +const built = await build({ stdin: { contents: "export * from './src/lib/download-eta';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' }, external: ['react'] }); +const src = built.outputFiles[0].text.replace(/from\s*["']react["']/, 'from "data:text/javascript,export const useRef=()=>({current:null}),useEffect=()=>{},useState=v=>[v,()=>{}]"'); +const { etaMinutes, etaLabel, installProgress } = await import(`data:text/javascript;base64,${Buffer.from(src).toString('base64')}`); + +test('the time left comes from the recent rate, and says nothing until there is one', () => { + assert.equal(etaMinutes([{ at: 0, done: 1 }], 50), null); + assert.equal(etaMinutes([{ at: 0, done: 1 }, { at: 5000, done: 3 }], 50), null, 'under ten seconds of samples'); + assert.equal(etaMinutes([{ at: 0, done: 1 }, { at: 20000, done: 1 }], 50), null, 'nothing moved'); + assert.equal(etaMinutes([{ at: 0, done: 0 }, { at: 20000, done: 10 }], 60), 2, '0.5 GB/s, 60 GB left: 120 s'); + assert.equal(etaMinutes([{ at: 0, done: 0 }, { at: 60000, done: 1 }], 0.1), 1, 'never below one minute'); +}); + +test('the label is minutes, and hours past an hour and a half', () => { + assert.equal(etaLabel(null), ''); + assert.equal(etaLabel(3), 'About 3 min left'); + assert.equal(etaLabel(125), 'About 2 h 5 min left'); + assert.equal(etaLabel(120), 'About 2 h left'); +}); + +test('one count over all the parts of the job: the model files and, when there is one, the engine', () => { + const model = { kind: 'model', done_gb: 30, total_gb: 60, state: 'downloading' }; + const engine = { kind: 'engine', done_gb: 0.3, total_gb: 0.7, state: 'downloading' }; + const both = installProgress({ parts: [model, engine], download: { done_gb: 0, total_gb: 1 } }); + assert.equal(both.total_gb, 60.7); + assert.ok(Math.abs(both.done_gb - 30.3) < 1e-9); + assert.equal(both.percent, 49); + assert.ok(Math.abs(both.remaining_gb - 30.4) < 1e-9); + const modelOnly = installProgress({ parts: [model] }); + assert.equal(modelOnly.total_gb, 60); + assert.equal(installProgress({ parts: [model, { ...engine, state: 'skipped' }, { kind: 'engine', state: 'current', total_gb: 1, done_gb: 1 }] }).total_gb, 60, 'a part that is skipped or already current is not downloaded'); + // no parts: the job's own combined figures + assert.deepEqual(installProgress({ download: { done_gb: 5, total_gb: 50, percent: 10 } }), { done_gb: 5, total_gb: 50, remaining_gb: 45, percent: 10, file: undefined }); + assert.equal(installProgress({}), undefined); + assert.equal(installProgress(undefined), undefined); +}); diff --git a/apps/host/tests/packaged-control.test.mjs b/apps/host/tests/packaged-control.test.mjs index 579907d5..f6ce53cc 100644 --- a/apps/host/tests/packaged-control.test.mjs +++ b/apps/host/tests/packaged-control.test.mjs @@ -296,18 +296,13 @@ test('packaged: the catalog offers no picture reading (app installs have none), } finally { await f.native.close(); f.cleanup(); } }); -test('packaged: an engine that stops while loading is explained in words, with the engine\'s last line', async () => { +test('packaged: an engine that stops while loading keeps the code and the last engine line for the Details disclosure', async () => { const f = packagedFixture(); try { await f.native.refresh(true); - const control = f.native; - // the fixture's Control starts fine; make start fail the way Control reports a dead engine f.failStart({ message: 'server_exited', output: { log_tail: 'memory guard: 5.1 GiB free is under the 6 GiB limit' } }); - const job = await finish(control, control.operation('load', { model: 'iq2_xs' }).id); + const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id); assert.equal(job.state, 'error'); - assert.match(job.error, /ran low on memory/); - assert.match(job.error, /Leave 20% for my work/); - assert.match(job.error, /memory guard: 5\.1 GiB free/); - assert.doesNotMatch(job.error, /^server_exited$/); + assert.match(job.error, /^server_exited: memory guard: 5\.1 GiB free/); } finally { await f.native.close(); f.cleanup(); } }); diff --git a/apps/host/tests/plain-errors.test.mjs b/apps/host/tests/plain-errors.test.mjs new file mode 100644 index 00000000..fbb9c840 --- /dev/null +++ b/apps/host/tests/plain-errors.test.mjs @@ -0,0 +1,57 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { build } from 'esbuild'; + +const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +const catalogs = Object.fromEntries(await Promise.all(languages.map(async l => [l, JSON.parse(await readFile(`src/locales/${l}.json`, 'utf8'))]))); +const built = await build({ stdin: { contents: "export * from './src/lib/plain-errors'; export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } }); +const { plainFailure, plainFailureText, setTranslationLanguage } = await import(`data:text/javascript;base64,${Buffer.from(built.outputFiles[0].text).toString('base64')}`); + +const cases = [ + ['server_exited', 'memory', /ran low on memory/], + ['server_exited: memory guard: 5.1 GiB of RAM free is under the 6 GiB limit', 'memory', /ran low on memory/], + ['Engine stopped (exit 3). Open diagnostics or reload.', 'memory', /ran low on memory/], + ['Loading took more than five minutes. Check the engine log and free memory.', 'slow-load', /taking too long/], + ['No engine for this PC was found in C:/x/components: the component folder holds no engine package. The app never downloads an engine while it starts or serves.', 'engine-missing', /engine for this computer isn’t installed yet/], + ['cannot reach huggingface.co ()', 'network', /couldn’t reach the internet/], + ['sha256 mismatch for Qwen3.8-Flash-Next-00001-of-00002.gguf', 'integrity', /safety check/], + ['The agent component (DeepSeek Harness) is not installed.', 'assistant-missing', /coding assistant isn’t installed/], + ['component-missing', 'assistant-missing', /coding assistant/], + ['Strata Control did not answer within 60 s (models list).', 'control', /couldn’t read its own components/], + ['Prepare this model’s vision files before enabling picture reading.', 'picture-reading', /Picture reading isn’t available/], + ['Traceback (most recent call last):\n File "x.py", line 3', 'technical', /Something went wrong/], +]; + +for (const [raw, kind, message] of cases) { + test(`plain words for: ${raw.slice(0, 60)}`, () => { + const f = plainFailure(raw); + assert.equal(f.kind, kind); + assert.match(f.message, message); + assert.ok(f.next, 'a next step'); + assert.equal(f.detail, raw.trim(), 'the original text stays for Details'); + assert.doesNotMatch(f.message, /server_exited|exit \d|component-missing|Traceback/); + }); +} + +test('an ordinary sentence is left as it is and gets no Details', () => { + const f = plainFailure('Some model files are missing. Use Download / repair to restore them.'); + assert.equal(f.kind, 'plain'); + assert.equal(f.detail, undefined); +}); + +test('every plain message and next step is translated in all eight languages', () => { + const en = catalogs.en; + const ids = Object.fromEntries(Object.entries(en).map(([id, text]) => [text, id])); + for (const [raw] of cases) { + const f = plainFailure(raw); + for (const text of [f.message, f.next]) { + const id = ids[text]; + assert.ok(id, `"${text}" is in the catalog`); + for (const l of languages) if (l !== 'en') assert.notEqual(catalogs[l][id], text, `${l}: "${text}" is translated`); + } + } + setTranslationLanguage('de'); + assert.notEqual(plainFailureText('server_exited').message, plainFailure('server_exited').message); + setTranslationLanguage('en'); +}); diff --git a/strata_control/runtime.py b/strata_control/runtime.py index 1f477451..5ec301a9 100644 --- a/strata_control/runtime.py +++ b/strata_control/runtime.py @@ -798,15 +798,18 @@ class Host: self.last_error = result["error"] def _log_tail(self, limit: int = 4096) -> str | None: - """The last line the server wrote (a failed start is explained by it), or None. Bounded read, never raises.""" + """The last lines the server wrote (a failed start is explained by them), or None. Bounded read, never raises.""" try: with open(self.state_path.parent / f"{self.name}.server.log", "rb") as stream: stream.seek(0, os.SEEK_END) stream.seek(max(0, stream.tell() - limit)) - lines = [x.strip() for x in stream.read().decode("utf-8", "replace").splitlines() if x.strip()] + lines = [x.rstrip() for x in stream.read().decode("utf-8", "replace").splitlines() if x.strip()] except OSError: return None - return lines[-1][:300] if lines else None + # not the indented frames of a Python traceback: the engine's own lines and the final exception line say why + plain = [x for x in lines if not x[0].isspace() and not x.startswith("Traceback")] + chosen = plain[-3:] or lines[-1:] + return " | ".join(x[:200] for x in chosen) if chosen else None def _status(self) -> dict: child = self.child diff --git a/tests/desktop/test_control_install.py b/tests/desktop/test_control_install.py index c8449cc8..d1650f06 100644 --- a/tests/desktop/test_control_install.py +++ b/tests/desktop/test_control_install.py @@ -255,3 +255,20 @@ class InstallerServerTests(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class FailedStartTests(unittest.TestCase): + def test_a_failed_start_carries_the_last_lines_the_server_wrote(self): + """The app turns `server_exited` into words and keeps the reason under Details: Control reports the log's last lines.""" + from strata_control import runtime + owner = [c for _, c in vars(runtime).items() if isinstance(c, type) and hasattr(c, "_log_tail")][0] + with tempfile.TemporaryDirectory() as directory: + fake = mock.Mock() + fake.state_path = Path(directory) / "app-1.json" + fake.name = "app-1" + self.assertIsNone(owner._log_tail(fake)) # no log: nothing, no exception + (Path(directory) / "app-1.server.log").write_text("loading\n\nmemory guard: 5.1 GiB free is under 6 GiB\nthe engine process ended: exit code 3\n", encoding="utf-8") + tail = owner._log_tail(fake) + self.assertIn("memory guard: 5.1 GiB free", tail) + self.assertTrue(tail.endswith("exit code 3")) + self.assertNotIn("loading", tail.split(" | ")[0] if tail.count(" | ") > 2 else "") diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 8abd108a..64fc3e29 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -885,6 +885,10 @@ def combined_progress(prog: dict, job: dict) -> dict: prog["download"] = {"file": "model files", "done_gb": round(done_gb, 3), "total_gb": float(total), "remaining_gb": round(max(0.0, float(total) - done_gb), 3), "percent": min(99, int(100 * done_gb / float(total))) if total else 0} + # The parts of the whole job, for a progress bar that sums them (the job that fetches the engine adds its own part): + # {kind, name, done_gb, total_gb, state} + prog["parts"] = [{"kind": "model", "name": "Model files", "done_gb": prog["download"]["done_gb"], + "total_gb": float(total), "state": "downloading"}] return prog From bfe0798660adcae75bf2e85114d532b9e8d02cba Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 19:51:52 +0200 Subject: [PATCH 09/16] install progress step as a sentence; Model files label; ui-flows details check --- apps/desktop/scripts/ui-flows.mjs | 2 +- apps/host/src/components/NativeModels.tsx | 9 ++++++++- apps/host/src/locales/de.json | 6 +++++- apps/host/src/locales/en.json | 6 +++++- apps/host/src/locales/es.json | 6 +++++- apps/host/src/locales/ja.json | 6 +++++- apps/host/src/locales/ko.json | 6 +++++- apps/host/src/locales/pt.json | 6 +++++- apps/host/src/locales/ru.json | 6 +++++- apps/host/src/locales/zh.json | 6 +++++- 10 files changed, 49 insertions(+), 10 deletions(-) diff --git a/apps/desktop/scripts/ui-flows.mjs b/apps/desktop/scripts/ui-flows.mjs index a25fb40c..cdb47b53 100644 --- a/apps/desktop/scripts/ui-flows.mjs +++ b/apps/desktop/scripts/ui-flows.mjs @@ -323,7 +323,7 @@ await scenario('fail', { installed: true, env: { FAKE_ENGINE_FAIL: '1' } }, asyn await delay(500); await shot(page, '2-tune-error-details'); const details = await page.locator('.error-notice pre').first().innerText(); - check(/server_exited/.test(details) && /memory guard: 5\.1 GiB/.test(details), 'Details holds the code and the last engine line', details.replace(/\s+/g, ' ').slice(0, 120)); + check(/server_exited/.test(details) && /exited before/.test(details), 'Details holds the code and the reason the server logged', details.replace(/\s+/g, ' ').slice(0, 120)); const badOpen = await noScroll(page); check(badOpen.length === 0, 'and the pop-up still does not scroll with Details open', badOpen.join('; ')); await page.setViewportSize({ width: 1280, height: 700 }); diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 3de86f6c..f635d82b 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -110,6 +110,13 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine setBenchmark(false)}/> ; } +/** setup's "5/7: downloading …" as a sentence a person can read. */ +function installStepLabel(step?: string): string { + const n = Number(step?.match(/^(\d+)\//)?.[1]); + if (!n) + return step ? 'Getting things ready…' : 'Downloading and preparing model files…'; + return n <= 2 ? 'Checking your computer…' : n <= 4 ? 'Getting things ready…' : n === 5 ? 'Downloading your model…' : n === 6 ? 'Preparing your model for Strata…' : 'Finishing up…'; +} export function NativeProgress({ job }: { job: NativeJob; }) { const download = installProgress(job.result?.install); const detailsText = [job.details, job.result?.install?.engine?.details].filter(Boolean).join('\n'); const eta = useDownloadEta(job.kind === 'install' ? download : undefined, job.id); const [stopping, setStopping] = useState(false), [error, setError] = useState(''); async function stop() { setStopping(true); setError(''); try { @@ -120,4 +127,4 @@ catch (e) { } finally { setStopping(false); -} } return

{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : 'Engine operation')}

{tr(job.kind === 'install' || job.kind === 'load' ?
{tr(eta ? {eta} : null)} void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}
: null)}

{tr(job.kind === 'install' ? (job.result?.install?.step ?? 'Downloading and preparing model files…') : job.summary)}

{tr(download ? <>

{tr(download.file)} · {tr(download.percent ?? 0)}%{tr(Number.isFinite(download.done_gb) && Number.isFinite(download.total_gb) ? ` · ${download.done_gb!.toFixed(1)} / ${download.total_gb!.toFixed(1)} GB` : '')}

: null)}
{tr("Details")}

{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}

{tr(detailsText ?
{detailsText}
: null)}
{tr(error ? : null)}
; } +} } return

{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : 'Engine operation')}

{tr(job.kind === 'install' || job.kind === 'load' ?
{tr(eta ? {eta} : null)} void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}
: null)}

{tr(job.kind === 'install' ? installStepLabel(job.result?.install?.step) : job.summary)}

{tr(download ? <>

{tr(download.file === 'model files' ? 'Model files' : download.file)} · {tr(download.percent ?? 0)}%{tr(Number.isFinite(download.done_gb) && Number.isFinite(download.total_gb) ? ` · ${download.done_gb!.toFixed(1)} / ${download.total_gb!.toFixed(1)} GB` : '')}

: null)}
{tr("Details")}

{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}

{tr(detailsText ?
{detailsText}
: null)}
{tr(error ? : null)}
; } diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.json index 5ade6d0d..a794146f 100644 --- a/apps/host/src/locales/de.json +++ b/apps/host/src/locales/de.json @@ -2590,5 +2590,9 @@ "s2589": "Strata konnte seine eigenen Komponenten nicht lesen.", "s2590": "Schließen Sie Strata und öffnen Sie es erneut. Tritt das Problem weiterhin auf, installieren Sie die App neu.", "s2591": "Etwas ist schiefgelaufen.", - "s2592": "Versuchen Sie es erneut. Tritt das Problem weiterhin auf, öffnen Sie „Details“ und geben Sie diese bei einer Supportanfrage an." + "s2592": "Versuchen Sie es erneut. Tritt das Problem weiterhin auf, öffnen Sie „Details“ und geben Sie diese bei einer Supportanfrage an.", + "s2593": "Ihr Computer wird geprüft …", + "s2594": "Alles wird vorbereitet …", + "s2595": "Ihr Modell wird heruntergeladen …", + "s2596": "Ihr Modell wird für Strata vorbereitet …" } diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.json index de1c65cd..349372d5 100644 --- a/apps/host/src/locales/en.json +++ b/apps/host/src/locales/en.json @@ -2590,5 +2590,9 @@ "s2589": "Strata couldn’t read its own components.", "s2590": "Close and reopen Strata. If this keeps happening, reinstall the app.", "s2591": "Something went wrong.", - "s2592": "Try again. If it keeps happening, open Details and share them when you ask for help." + "s2592": "Try again. If it keeps happening, open Details and share them when you ask for help.", + "s2593": "Checking your computer…", + "s2594": "Getting things ready…", + "s2595": "Downloading your model…", + "s2596": "Preparing your model for Strata…" } diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.json index 9be5f93d..55cffb0d 100644 --- a/apps/host/src/locales/es.json +++ b/apps/host/src/locales/es.json @@ -2590,5 +2590,9 @@ "s2589": "Strata no pudo leer sus propios componentes.", "s2590": "Cierra y vuelve a abrir Strata. Si sigue ocurriendo, reinstala la aplicación.", "s2591": "Algo salió mal.", - "s2592": "Inténtalo de nuevo. Si sigue ocurriendo, abre «Detalles» y compártelos cuando pidas ayuda." + "s2592": "Inténtalo de nuevo. Si sigue ocurriendo, abre «Detalles» y compártelos cuando pidas ayuda.", + "s2593": "Revisando tu equipo…", + "s2594": "Preparando todo…", + "s2595": "Descargando tu modelo…", + "s2596": "Preparando tu modelo para Strata…" } diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.json index 7a9adc0f..b2b582ed 100644 --- a/apps/host/src/locales/ja.json +++ b/apps/host/src/locales/ja.json @@ -2590,5 +2590,9 @@ "s2589": "Strata が自身のコンポーネントを読み取れませんでした。", "s2590": "Strata を閉じて開き直してください。それでも改善しない場合は、アプリを再インストールしてください。", "s2591": "問題が発生しました。", - "s2592": "もう一度お試しください。それでも解決しない場合は「詳細」を開き、サポートに問い合わせる際に共有してください。" + "s2592": "もう一度お試しください。それでも解決しない場合は「詳細」を開き、サポートに問い合わせる際に共有してください。", + "s2593": "お使いのコンピューターを確認しています…", + "s2594": "準備をしています…", + "s2595": "モデルをダウンロードしています…", + "s2596": "Strata 用にモデルを準備しています…" } diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.json index 5f683a47..f305210a 100644 --- a/apps/host/src/locales/ko.json +++ b/apps/host/src/locales/ko.json @@ -2590,5 +2590,9 @@ "s2589": "Strata가 자체 구성 요소를 읽지 못했습니다.", "s2590": "Strata를 닫았다가 다시 여세요. 계속되면 앱을 다시 설치하세요.", "s2591": "문제가 발생했습니다.", - "s2592": "다시 시도하세요. 계속되면 “세부 정보”를 열어 도움을 요청할 때 함께 알려 주세요." + "s2592": "다시 시도하세요. 계속되면 “세부 정보”를 열어 도움을 요청할 때 함께 알려 주세요.", + "s2593": "컴퓨터를 확인하는 중…", + "s2594": "준비하는 중…", + "s2595": "모델을 다운로드하는 중…", + "s2596": "Strata용으로 모델을 준비하는 중…" } diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.json index 8b5e6180..bed56fe3 100644 --- a/apps/host/src/locales/pt.json +++ b/apps/host/src/locales/pt.json @@ -2590,5 +2590,9 @@ "s2589": "O Strata não conseguiu ler seus próprios componentes.", "s2590": "Feche e abra o Strata novamente. Se o problema continuar, reinstale o aplicativo.", "s2591": "Algo deu errado.", - "s2592": "Tente novamente. Se o problema continuar, abra “Detalhes” e compartilhe-os ao pedir ajuda." + "s2592": "Tente novamente. Se o problema continuar, abra “Detalhes” e compartilhe-os ao pedir ajuda.", + "s2593": "Verificando seu computador…", + "s2594": "Preparando tudo…", + "s2595": "Baixando seu modelo…", + "s2596": "Preparando seu modelo para o Strata…" } diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.json index 466e4908..7690de78 100644 --- a/apps/host/src/locales/ru.json +++ b/apps/host/src/locales/ru.json @@ -2590,5 +2590,9 @@ "s2589": "Strata не удалось прочитать собственные компоненты.", "s2590": "Закройте и снова откройте Strata. Если проблема повторяется, переустановите приложение.", "s2591": "Что-то пошло не так.", - "s2592": "Повторите попытку. Если проблема остаётся, откройте «Подробности» и приложите их, когда будете обращаться за помощью." + "s2592": "Повторите попытку. Если проблема остаётся, откройте «Подробности» и приложите их, когда будете обращаться за помощью.", + "s2593": "Проверяем ваш компьютер…", + "s2594": "Подготовка…", + "s2595": "Загружаем вашу модель…", + "s2596": "Готовим вашу модель для Strata…" } diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.json index 72468802..b99805b7 100644 --- a/apps/host/src/locales/zh.json +++ b/apps/host/src/locales/zh.json @@ -2590,5 +2590,9 @@ "s2589": "Strata 无法读取自身的组件。", "s2590": "请关闭并重新打开 Strata。如果问题持续出现,请重新安装该应用。", "s2591": "出了点问题。", - "s2592": "请重试。如果问题持续出现,请展开“详情”,并在求助时一并提供。" + "s2592": "请重试。如果问题持续出现,请展开“详情”,并在求助时一并提供。", + "s2593": "正在检查你的电脑…", + "s2594": "正在做准备…", + "s2595": "正在下载你的模型…", + "s2596": "正在为 Strata 准备你的模型…" } From 42ffb279513dba9b736047e2e42a1075591d037a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 20:10:06 +0200 Subject: [PATCH 10/16] stable window origin (fixed port with fallback), run configs repaired when Control moves, app installs to Programs\Strata and migrates an old install out of the data folder --- apps/desktop/scripts/ui-flows.mjs | 32 +- apps/desktop/src-tauri/nsis/installer.nsi | 21 +- apps/desktop/src-tauri/src/main.rs | 33 +- apps/host/server/native-control.mjs | 402 +++++++++++----------- apps/host/tests/packaged-control.test.mjs | 22 ++ tests/desktop/test_nsis_layout.py | 101 ++++++ 6 files changed, 412 insertions(+), 199 deletions(-) create mode 100644 tests/desktop/test_nsis_layout.py diff --git a/apps/desktop/scripts/ui-flows.mjs b/apps/desktop/scripts/ui-flows.mjs index cdb47b53..3fc3f0e8 100644 --- a/apps/desktop/scripts/ui-flows.mjs +++ b/apps/desktop/scripts/ui-flows.mjs @@ -30,7 +30,7 @@ const nodeExe = resolve(args.node ?? join(staged, 'node', process.platform === ' const work = mkdtempSync(join(tmpdir(), 'strata-ui-flows-')); const shots = resolve(args.shots ?? join(work, 'shots')); mkdirSync(shots, { recursive: true }); -const only = new Set(String(args.only ?? 'download,models,tune,fail,theme').split(',')); +const only = new Set(String(args.only ?? 'download,models,tune,fail,theme,restart').split(',')); const isWin = process.platform === 'win32'; const { chromium } = await import(pathToFileURL(join(repoHost, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); @@ -139,7 +139,7 @@ async function scenario(name, { installed = false, env = {} } = {}, body) { if (made.status !== 0) throw new Error('tokenizer fixture: ' + made.stderr); writeFileSync(join(dirs.install, 'strata-iq3_s.json'), JSON.stringify({ exe: 'component:strata-engine', backend: 'cuda', tokenizer: tok, args: ['--max-context', '32768', '--pool-workers', '12'], cwd: dir, model_name: 'stub', host: '127.0.0.1', port: 0, kv: 'int8' })); } - const port = await freePort(), base = `http://127.0.0.1:${port}`; + const port = env.FIXED_PORT ? Number(env.FIXED_PORT) : await freePort(), base = `http://127.0.0.1:${port}`; const host = spawn(nodeExe, [join(repoHost, 'server', 'index.mjs')], { cwd: repoHost, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, env: { ...baseEnv, STRATA_PORT: String(port), STRATA_DIST: join(repoHost, 'dist'), STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', STRATA_CONTROL_DIR: control, STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()) } }); let log = ''; host.stdout.on('data', c => { log += c; }); host.stderr.on('data', c => { log += c; }); @@ -334,6 +334,34 @@ await scenario('fail', { installed: true, env: { FAKE_ENGINE_FAIL: '1' } }, asyn void api; }); +// ------------------------------------------------------------------------------------------------ restart +// The app keeps its theme, text size, language and chat list in the browser's storage, which belongs to the window's origin +// (127.0.0.1:). The shell now uses the same port every launch: stop the host, start it again on that port, reopen the +// window with the same browser profile, and everything is still there. +if (only.has('restart')) { + console.log('--- restart'); + const fixed = await freePort(); + const profile = join(work, 'browser-profile'); + const run = async (body) => scenario('restart', { env: { FIXED_PORT: String(fixed) } }, async ctx => { + const context = await chromium.launchPersistentContext(profile, { executablePath: CHROME, headless: true, viewport: { width: 1200, height: 800 } }); + try { await body(context, ctx); } finally { await context.close(); } + }); + only.add('restart'); + await run(async (context, { base }) => { + const page = context.pages()[0] ?? await context.newPage(); + await page.goto(base, { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => { localStorage.setItem('strata.prefs.v2', JSON.stringify({ theme: 'dark', contentFontSize: 19, language: 'de' })); localStorage.setItem('strata.sessions.v1', JSON.stringify([{ id: 'chat-1', title: 'My chat' }])); }); + }); + await run(async (context, { base }) => { + const page = context.pages()[0] ?? await context.newPage(); + await page.goto(base, { waitUntil: 'domcontentloaded' }); + const saved = await page.evaluate(() => ({ prefs: JSON.parse(localStorage.getItem('strata.prefs.v2') || '{}'), chats: localStorage.getItem('strata.sessions.v1'), theme: document.documentElement.dataset.theme })); + check(saved.prefs.contentFontSize === 19 && saved.prefs.language === 'de', 'text size and language survive a restart on the same port', JSON.stringify(saved.prefs)); + check(saved.theme === 'dark', 'the theme survives too', saved.theme); + check(/My chat/.test(saved.chats ?? ''), 'and the chat list', saved.chats); + }); +} + // ------------------------------------------------------------------------------------------------ theme await scenario('theme', {}, async ({ base, browser, shot }) => { for (const scheme of ['dark', 'light']) { diff --git a/apps/desktop/src-tauri/nsis/installer.nsi b/apps/desktop/src-tauri/nsis/installer.nsi index bcbb52d2..cca93d5d 100644 --- a/apps/desktop/src-tauri/nsis/installer.nsi +++ b/apps/desktop/src-tauri/nsis/installer.nsi @@ -521,7 +521,7 @@ Function .onInit StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}" ${EndIf} !else if "${INSTALLMODE}" == "currentUser" - StrCpy $INSTDIR "$LOCALAPPDATA\${PRODUCTNAME}" + StrCpy $INSTDIR "$LOCALAPPDATA\Programs\${PRODUCTNAME}" !endif Call RestorePreviousInstallLocation @@ -651,6 +651,21 @@ Section WebView2 ${EndIf} SectionEnd +; STRATA-MIGRATE-BEGIN +; An earlier build installed the app into %LOCALAPPDATA%\Strata, the folder that also holds the user's data (components, install, +; procs, runtime, time-skip). Remove only the app files that build put there; everything else stays. +!macro StrataMigrateOldInstall OLDDIR NEWDIR + StrCmp "${OLDDIR}" "${NEWDIR}" +8 + IfFileExists "${OLDDIR}\strata-desktop.exe" 0 +7 + Delete "${OLDDIR}\strata-desktop.exe" + Delete "${OLDDIR}\uninstall.exe" + RMDir /r "${OLDDIR}\host" + RMDir /r "${OLDDIR}\node" + RMDir /r "${OLDDIR}\control" + RMDir "${OLDDIR}" +!macroend +; STRATA-MIGRATE-END + Section Install SetOutPath $INSTDIR @@ -658,6 +673,8 @@ Section Install !insertmacro NSIS_HOOK_PREINSTALL !endif + !insertmacro StrataMigrateOldInstall "$LOCALAPPDATA\${PRODUCTNAME}" "$INSTDIR" + !insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}" ; Copy main executable @@ -941,6 +958,8 @@ FunctionEnd Function RestorePreviousInstallLocation ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" "" StrCmp $4 "" restore_done 0 + ; %LOCALAPPDATA%\Strata holds the user's engines, model configs and tuning: never an app folder + StrCmp $4 "$LOCALAPPDATA\${PRODUCTNAME}" restore_done 0 Push $4 Push "$LOCALAPPDATA\Temp" Call StrIsUnder diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 51cd861c..4f2c8e5b 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -234,6 +234,22 @@ fn pick_port() -> Result { Ok(port) } +/// The port the app prefers. The window's origin is `http://127.0.0.1:`, and the browser storage that holds the +/// theme, text size, language and the chat list belongs to that origin, so a port that changed on every launch lost all +/// of it. The preferred port is fixed; only when something else holds it does the app fall back to a free one (and that +/// launch starts with empty storage, as before). +const PREFERRED_PORT: u16 = 47831; + +fn pick_stable_port() -> Result { + match TcpListener::bind(("127.0.0.1", PREFERRED_PORT)) { + Ok(listener) => { + drop(listener); + Ok(PREFERRED_PORT) + } + Err(_) => pick_port(), + } +} + /// Locate a bundled resource. /// /// In a packaged `.app` Tauri places `bundle.resources` under `Contents/Resources`. During @@ -413,7 +429,7 @@ fn start_host(app: &tauri::AppHandle) -> Result { } let node = node_binary(&res)?; - let port = pick_port()?; + let port = pick_stable_port()?; let mut cmd = Command::new(&node); cmd.arg(&entry) @@ -806,6 +822,21 @@ fn main() { mod tests { use super::*; + #[test] + fn the_window_origin_is_stable_unless_the_port_is_taken() { + // free (or already ours from a previous run): the same port every launch, so browser storage survives a restart + let first = pick_stable_port().unwrap(); + let second = pick_stable_port().unwrap(); + assert_eq!(first, second); + // held by another program: a different free port, not a failure + if first == PREFERRED_PORT { + let held = TcpListener::bind(("127.0.0.1", PREFERRED_PORT)).unwrap(); + let fallback = pick_stable_port().unwrap(); + assert_ne!(fallback, PREFERRED_PORT); + drop(held); + } + } + fn scratch(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("strata-desktop-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index a71519ca..e4511e7d 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -1,198 +1,210 @@ -/** Native Strata control plane. All user actions are explicit; opening the UI only reads state. */ -import { spawn } from 'node:child_process'; -import { randomBytes, randomUUID, createHash } from 'node:crypto'; -import { existsSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs'; -import { join, resolve, dirname, basename } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { createServer } from 'node:net'; -import { NATIVE_FIELDS, validateNativeSettings, validateMcpServers, publicMcpServers, publicNativeEnv, restoreNativeEnv } from './native-settings.mjs'; -import { resourceSettings } from './native-resources.mjs'; -import { resolvePython, venvPython } from './python-resolver.mjs'; -import os from 'node:os'; -import { runtimeVision } from './native-vision.mjs'; -import { componentsDirectory, installerEnvironment } from './control-runtime.mjs'; - -const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'..'); -const safeId=value=>typeof value==='string'&&/^[a-z0-9_-]{1,80}$/i.test(value); -const busy=requests=>requests.some(r=>['queued','generating'].includes(r.state)); -function readJson(path,fallback={}){try{return JSON.parse(readFileSync(path,'utf8').replace(/^\uFEFF/,''));}catch{return fallback;}} - -export function createNativeControl({directory,requests=()=>[],changed=()=>{},spawnProcess=spawn,fetcher=fetch,modelsDirectory,nativeDataDirectory=value=>value,beforeLoad=async()=>{},control=null,defaultRepo=process.env.STRATA_NATIVE_REPO??resolve(ROOT,'../../Strata')}={}){ - mkdirSync(directory,{recursive:true}); - const settingsPath=join(directory,'native-host.json'); - let preferences=readJson(settingsPath,{repo:defaultRepo}); - let child=null,seq=0,buffer='',pending=new Map(),definitions=[],refreshing=null,lastRead=0,connecting=null; - let snapshot={available:false,repo:preferences.repo,summary:'Connect a local Strata installation.',catalog:null,installed:null,hardware:null,error:null}; - const instances=new Map(),processes=new Map(),jobs=new Map(),logs=[]; - const savedJobs=readJson(join(directory,'native-jobs.json'),[]);for(const j of (Array.isArray(savedJobs)?savedJobs:[]).slice(-12))jobs.set(j.id,{...j,...(j.state==='running'?{state:'error',error:'The host restarted before completion. Check diagnostics, then retry; completed files are kept.',summary:'Interrupted operation'}:{})}); - /* Packaged mode: the app ships Strata Control (control-runtime.mjs). Models are run configs in an install folder, the engine - comes from the component folder, and a start is `strata runtime start` under the owner runtime. Nothing is installed, - updated or fetched from here. Without `control` (a source checkout) every path below is the original one. */ - const packaged=!!control; - /* In the packaged app the model catalog, the GPU probe and the install job are Control's bundled tools/strata_mcp.py and - setup.py, run on Control's own Python in the installer's mode (STRATA_CONTROL_INSTALL: no pip, no engine, no compiler). - The install only runs when the user clicks Download; starting and serving (control.start) keep STRATA_NO_ACQUIRE. */ - const defaultInstall=()=>join(dirname(componentsDirectory()),'install'); - let packagedInstall=null; - const NO_INSTALL='Installing, updating, tuning with calibration or rolling back model files and engines happens from the Terminal (strata install), never while the app runs.'; - let defaultId=null,timer=null,closing=false,polling=false; - const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);}; - const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();}; - function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};} - function sourceText(){try{return readFileSync(join(packaged?control.control.dir:preferences.repo,'serve/server.py'),'utf8');}catch{return '';}} - function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));} - const modelArena=id=>({arenaGb:(snapshot.catalog?.families??[]).flatMap(f=>f.sizes??[]).find(s=>s.id===id)?.experts_gb}); +/** Native Strata control plane. All user actions are explicit; opening the UI only reads state. */ +import { spawn } from 'node:child_process'; +import { randomBytes, randomUUID, createHash } from 'node:crypto'; +import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs'; +import { join, resolve, dirname, basename } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createServer } from 'node:net'; +import { NATIVE_FIELDS, validateNativeSettings, validateMcpServers, publicMcpServers, publicNativeEnv, restoreNativeEnv } from './native-settings.mjs'; +import { resourceSettings } from './native-resources.mjs'; +import { resolvePython, venvPython } from './python-resolver.mjs'; +import os from 'node:os'; +import { runtimeVision } from './native-vision.mjs'; +import { componentsDirectory, installerEnvironment } from './control-runtime.mjs'; + +const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'..'); +const safeId=value=>typeof value==='string'&&/^[a-z0-9_-]{1,80}$/i.test(value); +const busy=requests=>requests.some(r=>['queued','generating'].includes(r.state)); +function readJson(path,fallback={}){try{return JSON.parse(readFileSync(path,'utf8').replace(/^\uFEFF/,''));}catch{return fallback;}} + +export function createNativeControl({directory,requests=()=>[],changed=()=>{},spawnProcess=spawn,fetcher=fetch,modelsDirectory,nativeDataDirectory=value=>value,beforeLoad=async()=>{},control=null,defaultRepo=process.env.STRATA_NATIVE_REPO??resolve(ROOT,'../../Strata')}={}){ + mkdirSync(directory,{recursive:true}); + const settingsPath=join(directory,'native-host.json'); + let preferences=readJson(settingsPath,{repo:defaultRepo}); + let child=null,seq=0,buffer='',pending=new Map(),definitions=[],refreshing=null,lastRead=0,connecting=null; + let snapshot={available:false,repo:preferences.repo,summary:'Connect a local Strata installation.',catalog:null,installed:null,hardware:null,error:null}; + const instances=new Map(),processes=new Map(),jobs=new Map(),logs=[]; + const savedJobs=readJson(join(directory,'native-jobs.json'),[]);for(const j of (Array.isArray(savedJobs)?savedJobs:[]).slice(-12))jobs.set(j.id,{...j,...(j.state==='running'?{state:'error',error:'The host restarted before completion. Check diagnostics, then retry; completed files are kept.',summary:'Interrupted operation'}:{})}); + /* Packaged mode: the app ships Strata Control (control-runtime.mjs). Models are run configs in an install folder, the engine + comes from the component folder, and a start is `strata runtime start` under the owner runtime. Nothing is installed, + updated or fetched from here. Without `control` (a source checkout) every path below is the original one. */ + const packaged=!!control; + /* In the packaged app the model catalog, the GPU probe and the install job are Control's bundled tools/strata_mcp.py and + setup.py, run on Control's own Python in the installer's mode (STRATA_CONTROL_INSTALL: no pip, no engine, no compiler). + The install only runs when the user clicks Download; starting and serving (control.start) keep STRATA_NO_ACQUIRE. */ + const defaultInstall=()=>join(dirname(componentsDirectory()),'install'); + let packagedInstall=null; + const NO_INSTALL='Installing, updating, tuning with calibration or rolling back model files and engines happens from the Terminal (strata install), never while the app runs.'; + let defaultId=null,timer=null,closing=false,polling=false; + const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);}; + const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();}; + function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};} + function sourceText(){try{return readFileSync(join(packaged?control.control.dir:preferences.repo,'serve/server.py'),'utf8');}catch{return '';}} + function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));} + const modelArena=id=>({arenaGb:(snapshot.catalog?.families??[]).flatMap(f=>f.sizes??[]).find(s=>s.id===id)?.experts_gb}); /* A start that ends with `server_exited` carries the engine's last log line with it; the app turns the code into words and keeps this text under "Details" (src/lib/plain-errors.ts). */ function humanStartError(error){const text=String(error?.message??error),tail=error?.output?.log_tail;return tail&&!text.includes(tail)?`${text}: ${tail}`:text;} - function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} - function installRoot(){const found=[preferences.installDir,packagedInstall,snapshot.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());} - function repo(){if(packaged)return installRoot();const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;} - function python(){return resolvePython({repo:preferences.repo});} - function send(method,params,timeout=30000){return new Promise((resolve,reject)=>{const id=++seq;const alarm=setTimeout(()=>{pending.delete(id);reject(new Error('The native engine did not respond in time. Check engine logs.'));},timeout);pending.set(id,{resolve,reject,alarm});child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');});} - function disconnect(){child?.kill();child=null;definitions=[];for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Native control connection closed.'));}pending.clear();} - async function connect(){if(closing)throw new Error("The host is shutting down.");if(child&&definitions.length)return;if(!connecting)connecting=startClient().finally(()=>{connecting=null;});return connecting;} - async function startClient(){ - const folder=repo(); - buffer='';const py0=packaged?{command:control.control.python,args:[]}:python(); - const script=packaged?join(control.control.dir,'tools/strata_mcp.py'):join(folder,'tools/strata_mcp.py'); - const client=child=spawnProcess(py0.command,[...py0.args,script,...(packaged?['--root',folder,'--src',control.control.dir]:[])],{cwd:packaged?control.control.dir:folder,windowsHide:true,stdio:['pipe','pipe','pipe'],env:packaged?installerEnvironment(control.control,{installDir:folder}):{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8'}}); - client.stdout.on('data',chunk=>{if(child!==client)return;buffer+=chunk.toString();let end;while((end=buffer.indexOf('\n'))>=0){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);let message;try{message=JSON.parse(line);}catch{continue;}const p=pending.get(message.id);if(p){clearTimeout(p.alarm);pending.delete(message.id);message.error?p.reject(new Error(message.error.message)):p.resolve(message.result);}}}); - child.stderr.on('data',chunk=>append('control',chunk.toString())); - client.on('error',error=>{if(child===client){snapshot.error=error.message;disconnect();}}); - client.on('exit',()=>{if(child===client){child=null;for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Strata control stopped. Python 3.10 or newer is required.'));}pending.clear();}}); - await send('initialize',{protocolVersion:'2024-11-05',capabilities:{},clientInfo:{name:'Strata UI',version:'0.1.0'}}); - child.stdin.write(JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})+'\n'); - definitions=(await send('tools/list',{})).tools??[]; - } - async function controlTool(name){ - if(name==='strata_status'){ - let list=await control.installedModels({installDir:preferences.installDir&&existsSync(preferences.installDir)?preferences.installDir:null}); - if(!preferences.installDir&&!(list.models??[]).length){const own=installRoot();if(realpathSync(list.install_dir)!==own)list=await control.installedModels({installDir:own});} - packagedInstall=list.install_dir; - const engine=await control.engine(); - const installer=await mcpCall('strata_status',{hardware:true}).catch(error=>({error:error.message})); - const models=(list.models??[]).filter(m=>m.component_status!=='invalid'&&m.source_config).map(m=>({model:m.id,config:basename(m.source_config),configPath:m.source_config,model_name:m.name,context:m.context_tokens??0,backend:m.backend,ready:m.component_status==='present',images:'off',port:undefined,last_used:null})); - const cores=os.cpus().length; - return {summary:engine.usable?`Strata Control is ready; engine ${engine.engine.version} (${engine.engine.platform}-${engine.engine.backend}).`:(engine.notice??'No engine for this PC was found.'), - installDir:list.install_dir,engine:{usable:engine.usable,notice:engine.notice,version:engine.engine?.version??null,backend:engine.backend,componentsDir:engine.components_dir}, - installed:{strata_folder:list.install_dir,data_folder:null,engine:engine.engine?{version:engine.engine.version,backend:engine.engine.backend,folder:engine.engine.root}:{folder:null,version:null},models}, - hardware:installer.hardware?{...installer.hardware,cpu:{...(installer.hardware.cpu??{}),cores:installer.hardware.cpu?.cores??cores},gpus:installer.hardware.gpus??[]}:{cpu:{cores},ram_gb:Math.round(os.totalmem()/1024**3),gpus:[]}, - recommendation:installer.recommendation??null,installerError:installer.error??null,install:installer.install??null,running:null}; - } - throw new Error(`Strata Control has no ${name}.`); - } - async function tool(name,args={}){if(packaged&&name==='strata_status')return controlTool(name,args);return mcpCall(name,args);} - async function mcpCall(name,args={}){await connect();if(!definitions.some(d=>d.name===name))throw new Error(`This Strata installation does not support ${name}. Update the installation first.`);const result=await send('tools/call',{name,arguments:args},120000);let value=result.structuredContent;if(!value){const text=result.content?.find(c=>c.type==='text')?.text;try{value=JSON.parse(text);}catch{value={summary:text};}}if(result.isError)throw new Error(value?.error??value?.summary??'Native operation failed.');return value;} - async function refresh(force=false){ - if(closing)return state(); - if(refreshing)return refreshing;if(!force&&Date.now()-lastRead<15000)return state(); - refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);const noImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,images:false,sizes:(f.sizes??[]).map(s=>({...s,images:false}))}))}:c;snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:packaged?noImages(catalog):catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing; - } - function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};packagedInstall=null;disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);} - function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();} - function record(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path,config:readJson(path)};} - function settings(model){const {config}=record(model);const values=Object.fromEntries(NATIVE_FIELDS.map(f=>[f.id,config[f.id]??null]));if(typeof values.aliases==='string')values.aliases=values.aliases.split(',').map(v=>v.trim()).filter(Boolean);values.sampling=config.sampling??{};values.args=config.args??[];values.env=publicNativeEnv(config.env??{});return {model,values,mcp:publicMcpServers(config.mcp_servers??config.mcpServers??{}),restartNeeded:true};} - function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);} - function previousEngine(){try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}} - async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);return tool('strata_install',installArgs(args,false));} - function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),...(packaged?{vision:'no'}:{}),confirm};} - - function begin(kind,run,metadata={}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or cancel the current engine operation first.');const job={id:randomUUID(),kind,state:'running',startedAt:new Date().toISOString(),summary:'Starting…',result:null,error:null,...metadata};for(const [id,old] of jobs)if(jobs.size>=12&&old.state!=='running')jobs.delete(id);jobs.set(job.id,job);emit();void run(job).then(result=>{if(job.state==='running'){Object.assign(job,{state:'done',summary:result?.summary??'Complete',result,finishedAt:new Date().toISOString()});}}).catch(error=>{if(job.state==='running')Object.assign(job,{state:'error',error:error.message,summary:error.message,finishedAt:new Date().toISOString()});}).finally(()=>{if(job.kind.startsWith('update')||job.kind==='rollback')disconnect();lastRead=0;emit();void refresh(true);});return state().jobs.find(j=>j.id===job.id);} - async function watchInstall(job,current){job.summary=current.step??'Resuming preparation status…';job.result={install:current};while(job.state==='running'){await new Promise(r=>setTimeout(r,1500));const result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(!result.install?.running){if(result.install?.exit_code!==0)throw new Error(result.install?.error??'Preparation did not finish. Retry to reuse completed files.');return {summary:'Model preparation complete. Load it from Models.'};}}} - function externalRunning(){return Array.isArray(snapshot.external)?snapshot.external.filter(s=>![...instances.values()].some(i=>i.port===s.port)):[];} - async function install(job,args){if(job.state!=='running')return;if(externalRunning().length)throw new Error('Stop the native server running outside this UI before preparing files.');if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel requests before preparing model files.');for(const id of [...instances.keys()])await unload(id);if(job.state!=='running')return;let result=await tool('strata_install',installArgs(args,true));job.summary=result.summary;job.result=result;emit();for(;;){if(job.state!=='running')return;await new Promise(resolve=>setTimeout(resolve,1500));result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(result.install&&!result.install.running){if(result.install.exit_code!==0)throw new Error(result.install.error??result.summary);await refresh(true);if(args.loadAfter){const model=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;return loadEngine(job,{model,multiple:!!args.multiple,resourceProfile:args.resourceProfile,vision:args.loadVision});}return result;}}} - function terminate(proc,signal='SIGTERM'){if(!proc)return;if(process.platform!=='win32'&&proc.pid){try{process.kill(-proc.pid,signal);return;}catch{}}proc.kill(signal);} - async function stopProcess(proc){if(!proc||proc.exitCode!=null)return;await new Promise(resolve=>{const timeout=setTimeout(()=>{terminate(proc,'SIGKILL');resolve();},8000);proc.once('exit',()=>{clearTimeout(timeout);resolve();});terminate(proc);});} - async function unload(id,force=false){const instance=instances.get(id);if(!instance)throw new Error('This model is no longer loaded.');if(!force&&[...jobs.values()].some(j=>j.kind==='benchmark'&&j.state==='running'&&j.instanceId===id))throw new Error('Stop the benchmark before unloading this model.');if(!force&&busy(requests().filter(r=>r.instanceId===id)))throw new Error('Finish or cancel this model’s requests first.');instance.status='unloading';if(instance.profile){try{await control.stop(instance.profile);}catch(error){if(!force){instance.status='error';instance.error=error.message;emit();throw error;}}}else await stopProcess(processes.get(id));processes.delete(id);instances.delete(id);try{unlinkSync(instance.configPath);}catch{}if(defaultId===id)defaultId=instances.keys().next().value??null;emit();return state();} - async function loadEngine(job,args){ - await refresh(true);if(job.state!=='running')return;const {config,entry}=record(args.model);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');}if(!entry.ready)throw new Error('Some model files are missing. Use Download / repair to restore them.'); - if(externalRunning().length)throw new Error('A Strata server is already running outside this UI. Stop it before loading here, or connect its API in Settings → Models.'); - if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.'); - const vision=runtimeVision(config,args.vision); - const visionPreferences=args.vision!==undefined?{ui_vision_enabled:args.vision!=='no',ui_vision_device:args.vision==='no'?config.ui_vision_device??'yes':args.vision}:{}; - const resources=args.resourceProfile?resourceSettings({...config,vision},snapshot.hardware,args.resourceProfile,modelArena(args.model)):null; - const cfg={...config,...visionPreferences,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),host:'127.0.0.1',open_browser:false,...validateNativeSettings(args.values??{}),vision}; - if(args.gpus!==undefined){const detected=new Set((snapshot.hardware?.gpus??[]).map(g=>g.index));if(!Array.isArray(args.gpus)||!args.gpus.length||new Set(args.gpus).size!==args.gpus.length||args.gpus.some(g=>!Number.isInteger(g)||!detected.has(g)))throw new Error('Choose distinct detected GPUs. CPU-only text inference is not supported by this native adapter.');cfg.gpu=args.gpus.length===1?args.gpus[0]:args.gpus;cfg.layer_split=args.gpus.length>1?validateNativeSettings({layer_split:args.layerSplit??'auto'}).layer_split:'auto';if(cfg.layer_split!=='auto'&&cfg.layer_split.split(',').length!==args.gpus.length-1)throw new Error('Choose one layer split point between each pair of GPUs.');} - if(cfg.vram_reserve_mib!==undefined&&cfg.vram_reserve_mib!==null){cfg.args=[...(cfg.args??[])];const at=cfg.args.indexOf('--vram-reserve-mib');if(at>=0)cfg.args.splice(at,2);cfg.args.push('--vram-reserve-mib',String(cfg.vram_reserve_mib));}if(cfg.vision){if(cfg.vision_tokens!=null)cfg.vision={...cfg.vision,max_tokens:cfg.vision_tokens};if(cfg.vision_min_tokens!=null)cfg.vision={...cfg.vision,min_tokens:cfg.vision_min_tokens};}cfg.mcp={...(cfg.mcp??{}),...(cfg.mcp_timeout_s!=null?{timeout_s:cfg.mcp_timeout_s}:{}),...(cfg.mcp_max_rounds!=null?{max_rounds:cfg.mcp_max_rounds}:{}),...(cfg.mcp_max_result_chars!=null?{max_result_chars:cfg.mcp_max_result_chars}:{})}; - for(const arg of cfg.args??[])if(arg.endsWith('.gguf')&&!existsSync(resolve(repo(),arg)))throw new Error('An engine argument names a missing GGUF. Restore the saved arguments or repair the files.'); - const fingerprint=createHash('sha256').update(JSON.stringify({...cfg,api_key:undefined,port:undefined})).digest('hex'); - const placement=Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu];const matching=[...instances.values()].find(i=>i.model===args.model&&JSON.stringify(i.gpus)===JSON.stringify(placement)); - if(matching?.status==='ready'&&matching.fingerprint===fingerprint&&(args.multiple||instances.size===1))return {summary:`${matching.label} is already ready.`,instanceId:matching.id}; - const wasDefault=matching?.id===defaultId; - const id=matching?.id??randomUUID();let apiModelId=matching?.apiModelId??args.model,suffix=1;while(!matching&&[...instances.values()].some(i=>i.apiModelId===apiModelId))apiModelId=`${args.model}--${++suffix}`; - cfg.aliases=[...new Set([...(Array.isArray(cfg.aliases)?cfg.aliases:typeof cfg.aliases==='string'?cfg.aliases.split(',').map(s=>s.trim()).filter(Boolean):[]),apiModelId])]; - const key=randomBytes(32).toString('hex');cfg.api_key=key;cfg.port=await freePort(args.port); - const work=join(directory,'native-instances');mkdirSync(work,{recursive:true});const configPath=join(work,`${id}.json`); - const py=packaged?null:venvPython(repo());if(!packaged&&!existsSync(py))throw new Error('The Strata Python environment is missing. Use Download / repair first.'); - if(job.state!=='running')return; - await beforeLoad();if(job.state!=='running')return; - if(!args.multiple){if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel native requests before switching models.');for(const id of [...instances.keys()])await unload(id);}else if(matching)await unload(matching.id); - if(job.state!=='running')return; - writeFileSync(configPath,JSON.stringify(cfg,null,2),{mode:0o600}); - const instance={id,apiModelId,fingerprint,context:entry.context??0,aliases:cfg.aliases??[],vision:!!cfg.vision,model:args.model,label:entry.model_name??args.model,port:cfg.port,gpus:Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu],status:'loading',phase:'loading',key,configPath,loadedAt:new Date().toISOString(),metrics:null,error:null}; - let proc=null,started=null; - if(packaged){ - /* The engine starts under Control's owner runtime, not as our child: a saved profile per slot, then `runtime start`. */ - const used=new Set([...instances.values()].map(i=>i.profile));let slot=1;while(used.has('app-'+slot))slot++;instance.profile='app-'+slot; - instances.set(id,instance);if(!defaultId||!args.multiple||wasDefault)defaultId=id;emit(); - started=control.stop(instance.profile).catch(()=>{}).then(()=>control.saveProfile(instance.profile,configPath)).then(()=>control.start(instance.profile,{waitSeconds:300})); - started.then(()=>append(id,'Strata Control reports the engine is ready.'),error=>{append(id,error.message);}); - try{await started;}catch(error){const said=humanStartError(error);instance.status='error';instance.error=said;emit();throw new Error(said);} - } else { - proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8',STRATA_API_KEY:''}}); - instances.set(id,instance);processes.set(id,proc);if(!defaultId||!args.multiple||wasDefault)defaultId=id; - for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{const lines=chunk.toString().split('\n').filter(Boolean);lines.forEach(line=>append(id,line.replaceAll(key,'[redacted]')));job.summary=lines.at(-1)??job.summary;emit();}); - proc.on('error',error=>{instance.status='error';instance.error=error.message;emit();});proc.on('exit',code=>{if(instances.has(id)&&instance.status!=='unloading'){instance.status='error';instance.error=`Engine stopped${code===null?'':` (exit ${code})`}. Open diagnostics or reload.`;emit();}});emit(); - } - const deadline=Date.now()+300000;while(Date.now()setTimeout(resolve,1200)); - } - if(job.state!=='running'){await unload(id);return;} - if(instance.profile)await control.stop(instance.profile).catch(()=>{});else await stopProcess(proc);instance.status='error';instance.error='Loading took more than five minutes. Check the engine log and free memory.';throw new Error(instance.error); - } - async function freePort(requested){for(let port=Number(requested??18500);port<=Number(requested??18500)+20;port++){if(!Number.isInteger(port)||port<1024||port>65535)throw new Error('Choose a port from 1024 to 65535.');if([...instances.values()].some(i=>i.port===port)){if(requested)throw new Error('This private engine port is already in use.');continue;}const available=await new Promise(resolve=>{const probe=createServer();probe.once('error',()=>resolve(false));probe.listen(port,'127.0.0.1',()=>probe.close(()=>resolve(true)));});if(available)return port;if(requested)throw new Error('This private engine port is already in use.');}throw new Error('No free private engine port was found.');} - async function poll(){if(polling||closing)return;polling=true;try{await Promise.all([...instances.values()].map(async instance=>{if(instance.status!=='ready')return;try{const response=await fetcher(`http://127.0.0.1:${instance.port}/metrics?requests=all`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(!response.ok)throw new Error('Metrics unavailable');instance.metrics=await response.json();const tools=await fetcher(`http://127.0.0.1:${instance.port}/mcp`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(tools.ok)instance.metrics.mcp=await tools.json();instance.phase=instance.metrics.live?.state??'idle';}catch{instance.metrics=null;instance.phase='unavailable';}}));emit();}finally{polling=false;}} - function ensurePoll(){if(!timer){timer=setInterval(()=>void poll(),2000);timer.unref?.();}void poll();} - async function benchmark(job,args){const instance=resolveInstance(args.instanceId);job.instanceId=instance.id;if(busy(requests().filter(r=>r.instanceId===instance.id)))throw new Error('Wait for this model to finish before benchmarking.');const started=Date.now();job.abort=new AbortController();const response=await fetcher(`http://127.0.0.1:${instance.port}/v1/chat/completions`,{method:'POST',headers:{'content-type':'application/json',authorization:`Bearer ${instance.key}`},signal:AbortSignal.any([job.abort.signal,AbortSignal.timeout(180000)]),body:JSON.stringify({model:instance.apiModelId,messages:[{role:'user',content:'Explain how a rainbow forms in clear, simple language.'}],temperature:0,reasoning_effort:'none',max_tokens:200,stream:false})});const body=await response.json();if(!response.ok)throw new Error(body.error?.message??'Benchmark failed.');if(job.state!=='running')return;const result={summary:'Measured benchmark complete.',at:new Date().toISOString(),model:instance.apiModelId,durationMs:Date.now()-started,tokensIn:body.usage?.prompt_tokens??null,tokensOut:body.usage?.completion_tokens??null,outputTps:body.timings?.predicted_per_second??null,promptTps:body.timings?.prompt_per_second??null,source:'engine',settings:'Greedy · thinking off · up to 200 output tokens'};writeFileSync(join(directory,'native-benchmark.json'),JSON.stringify(result,null,2),{mode:0o600});return result;} - function resolveInstance(id){const aliases=[...instances.values()].filter(i=>i.aliases?.includes(id));if(aliases.length>1&&!instances.has(id)&&![...instances.values()].some(i=>i.apiModelId===id))throw new Error('This alias matches more than one instance. Choose its exact model ID.');const i=instances.get(id)??[...instances.values()].find(i=>i.apiModelId===id)??aliases[0]??(!id&&instances.size===1?[...instances.values()][0]:undefined);if(!i)throw new Error('Choose a loaded model ID.');if(i.status!=='ready')throw new Error('This model is not ready.');return i;} - async function program(job,args){if(packaged)throw new Error(NO_INSTALL);if(externalRunning().length)throw new Error('Stop the native server running outside this UI before changing engine files.');if(instances.size)throw new Error('Unload native models before changing engine files.');const folder=repo();let {command,args:prefix}=python(),argv; - if(job.kind==='calibrate'||job.kind==='tune'){if(!state().capabilities.calibration)throw new Error('This installation calibrates NVIDIA GPUs only. Use the short benchmark on other devices.');const model=args.model??snapshot.installed?.models?.[0]?.model;const chosen=record(model);if(!chosen.entry.ready)throw new Error('Prepare this model before calibrating.');command=venvPython(folder);prefix=[];if(!existsSync(command))throw new Error('Prepare the Python environment first.');argv=['-c','import sys; from pathlib import Path; import setup; sys.exit(0 if setup.calibrate_config(Path(sys.argv[1])) else 1)',chosen.path];} - else if(job.kind==='rollback'){if(!previousEngine())throw new Error('No saved previous engine is available.');argv=[join(folder,'setup.py'),'--rollback-engine'];} - else if(job.kind==='update-engine'){if(!snapshot.installed?.models?.length)throw new Error('Prepare a model first. Its installer downloads the matching engine.');argv=[join(folder,'setup.py'),'--update'];} - else if(job.kind==='update-strata'){const status=await execute('git',['status','--porcelain'],folder);if(status.trim())throw new Error('This Strata checkout has local edits. Save or commit them before updating.');const remote=await execute('git',['remote','get-url','origin'],folder);if(!/^https:\/\/github\.com\/Niko1221\/Strata(?:\.git)?\s*$/.test(remote))throw new Error('The native installation must use the official Strata repository to update here.');await execute('git',['pull','--ff-only'],folder);argv=[join(folder,'setup.py'),'--update'];} - else throw new Error('Unsupported native operation.'); - return new Promise((resolve,reject)=>{const proc=spawnProcess(command,[...prefix,...argv],{cwd:folder,windowsHide:true,detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1'}});job.process=proc;for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{chunk.toString().split('\n').filter(Boolean).forEach(line=>append(job.id,line));job.summary=chunk.toString().trim().slice(-500);emit();});proc.on('error',reject);proc.on('exit',code=>{delete job.process;code===0?resolve({summary:job.kind==='calibrate'?'Calibration complete. Native settings were saved.':'Native installation updated.'}):reject(new Error(`Operation stopped (exit ${code}). Open diagnostics for details.`));});}); - } - function execute(cmd,args,cwd){return new Promise((resolve,reject)=>{let output='';const process=spawnProcess(cmd,args,{cwd,stdio:['ignore','pipe','pipe']});process.stdout.on('data',c=>{output+=c;if(output.length>100000)process.kill();});process.stderr.on('data',c=>append('update',c.toString()));process.on('error',reject);process.on('exit',code=>code===0?resolve(output):reject(new Error('Git could not update this installation. Open diagnostics.')));});} - function writeModelConfig(path,next){copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);} - async function tune(job,args){ - await refresh(true);if(job.state!=='running')return; - const chosen=record(args.model);resourceSettings(chosen.config,snapshot.hardware,args.profile,modelArena(args.model)); - if(!chosen.entry.ready)throw new Error('Prepare the model before tuning.'); - if(externalRunning().length)throw new Error('Stop the native server outside this UI before tuning.'); - if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish requests before tuning.'); - for(const id of [...instances.keys()])await unload(id); - if(job.state!=='running')return; - const initialValues=resourceSettings(chosen.config,snapshot.hardware,args.profile,modelArena(args.model));writeModelConfig(chosen.path,{...chosen.config,...initialValues,ui_resource_profile:args.profile}); - if(args.calibrate!==false&&state().capabilities.calibration){job.summary='Measuring the best engine settings for this computer…';emit();await program(job,args);} - if(job.state!=='running')return; - const current=record(args.model),values=resourceSettings(current.config,snapshot.hardware,args.profile,modelArena(args.model)); - const next={...current.config,...values,ui_resource_profile:args.profile}; - writeModelConfig(current.path,next); - job.summary='Applying your resource preference and loading the model…';emit(); - const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:current.config.vision?args.vision:'no'}); - if(job.state!=='running'||!loaded?.instanceId)return; - job.summary='Checking your model’s speed…';emit(); - const measured=await benchmark(job,{instanceId:loaded.instanceId}); - return {...loaded,...measured,summary:'Your model is tuned and ready.',profile:args.profile}; - } - function operation(kind,args={}){if(!['install','load','benchmark','tune','calibrate','update-engine','update-strata','rollback'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):program(job,args),{guided:args.guided===true,model:args.model});} - async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install')await tool('strata_install',{cancel:true});else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} - async function close(){closing=true;clearInterval(timer);const installing=packaged&&child&&[...jobs.values()].some(j=>j.kind==='install'&&j.state==='running');if(installing)await send('tools/call',{name:'strata_install',arguments:{cancel:true}},15000).catch(()=>{});const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();} - // Remove nonserializable process references from public jobs. - const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,...job})=>job);return value;}; - return {state:publicState,refresh,configure,setDownloadDirectory,plan,settings,save,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; -} + /* A run config the app's install job wrote names files inside the app's own Control folder (`cwd`, `--expert-profile`). When the + app is reinstalled to another folder, or an update moves Control, those absolute paths point at nothing and every installed + model breaks. At every read of the installed models, a path that ends up inside a folder called `control` that no longer + exists is pointed at the Control this app has now, when the file is there. The config is saved (with a .bak) only then. */ + function repairControlPaths(dir){if(!packaged||!dir||!existsSync(dir))return;let names=[];try{names=readdirSync(dir).filter(n=>/^strata-[a-z0-9_-]+\.json$/i.test(n));}catch{return;} + const here=control.control.dir,inside=/^(.+?[\/]control)(?=[\/]|$)(.*)$/i; + const fix=value=>{if(typeof value!=='string')return value;const m=value.match(inside);if(!m||existsSync(value)||resolve(m[1]).toLowerCase()===resolve(here).toLowerCase())return value;const candidate=join(here,m[2]);return existsSync(candidate)?candidate:value;}; + for(const name of names){const path=join(dir,name),config=readJson(path,null);if(!config||typeof config!=='object')continue; + const next={...config,...(config.cwd!==undefined?{cwd:fix(config.cwd)}:{}),...(Array.isArray(config.args)?{args:config.args.map(fix)}:{})}; + if(JSON.stringify(next)!==JSON.stringify(config)){try{writeModelConfig(path,next);}catch{/* read-only folder: the load reports it */}}}} + function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} + function installRoot(){const found=[preferences.installDir,packagedInstall,snapshot.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());} + function repo(){if(packaged)return installRoot();const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;} + function python(){return resolvePython({repo:preferences.repo});} + function send(method,params,timeout=30000){return new Promise((resolve,reject)=>{const id=++seq;const alarm=setTimeout(()=>{pending.delete(id);reject(new Error('The native engine did not respond in time. Check engine logs.'));},timeout);pending.set(id,{resolve,reject,alarm});child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');});} + function disconnect(){child?.kill();child=null;definitions=[];for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Native control connection closed.'));}pending.clear();} + async function connect(){if(closing)throw new Error("The host is shutting down.");if(child&&definitions.length)return;if(!connecting)connecting=startClient().finally(()=>{connecting=null;});return connecting;} + async function startClient(){ + const folder=repo(); + buffer='';const py0=packaged?{command:control.control.python,args:[]}:python(); + const script=packaged?join(control.control.dir,'tools/strata_mcp.py'):join(folder,'tools/strata_mcp.py'); + const client=child=spawnProcess(py0.command,[...py0.args,script,...(packaged?['--root',folder,'--src',control.control.dir]:[])],{cwd:packaged?control.control.dir:folder,windowsHide:true,stdio:['pipe','pipe','pipe'],env:packaged?installerEnvironment(control.control,{installDir:folder}):{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8'}}); + client.stdout.on('data',chunk=>{if(child!==client)return;buffer+=chunk.toString();let end;while((end=buffer.indexOf('\n'))>=0){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);let message;try{message=JSON.parse(line);}catch{continue;}const p=pending.get(message.id);if(p){clearTimeout(p.alarm);pending.delete(message.id);message.error?p.reject(new Error(message.error.message)):p.resolve(message.result);}}}); + child.stderr.on('data',chunk=>append('control',chunk.toString())); + client.on('error',error=>{if(child===client){snapshot.error=error.message;disconnect();}}); + client.on('exit',()=>{if(child===client){child=null;for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Strata control stopped. Python 3.10 or newer is required.'));}pending.clear();}}); + await send('initialize',{protocolVersion:'2024-11-05',capabilities:{},clientInfo:{name:'Strata UI',version:'0.1.0'}}); + child.stdin.write(JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})+'\n'); + definitions=(await send('tools/list',{})).tools??[]; + } + async function controlTool(name){ + if(name==='strata_status'){ + for(const dir of [preferences.installDir,packagedInstall,installRoot()])repairControlPaths(dir); + let list=await control.installedModels({installDir:preferences.installDir&&existsSync(preferences.installDir)?preferences.installDir:null}); + if(!preferences.installDir&&!(list.models??[]).length){const own=installRoot();if(realpathSync(list.install_dir)!==own)list=await control.installedModels({installDir:own});} + if(!preferences.installDir&&list.install_dir&&![preferences.installDir,packagedInstall,installRoot()].some(d=>d&&resolve(d).toLowerCase()===resolve(list.install_dir).toLowerCase())){repairControlPaths(list.install_dir);list=await control.installedModels({installDir:list.install_dir});} + packagedInstall=list.install_dir; + const engine=await control.engine(); + const installer=await mcpCall('strata_status',{hardware:true}).catch(error=>({error:error.message})); + const models=(list.models??[]).filter(m=>m.component_status!=='invalid'&&m.source_config).map(m=>({model:m.id,config:basename(m.source_config),configPath:m.source_config,model_name:m.name,context:m.context_tokens??0,backend:m.backend,ready:m.component_status==='present',images:'off',port:undefined,last_used:null})); + const cores=os.cpus().length; + return {summary:engine.usable?`Strata Control is ready; engine ${engine.engine.version} (${engine.engine.platform}-${engine.engine.backend}).`:(engine.notice??'No engine for this PC was found.'), + installDir:list.install_dir,engine:{usable:engine.usable,notice:engine.notice,version:engine.engine?.version??null,backend:engine.backend,componentsDir:engine.components_dir}, + installed:{strata_folder:list.install_dir,data_folder:null,engine:engine.engine?{version:engine.engine.version,backend:engine.engine.backend,folder:engine.engine.root}:{folder:null,version:null},models}, + hardware:installer.hardware?{...installer.hardware,cpu:{...(installer.hardware.cpu??{}),cores:installer.hardware.cpu?.cores??cores},gpus:installer.hardware.gpus??[]}:{cpu:{cores},ram_gb:Math.round(os.totalmem()/1024**3),gpus:[]}, + recommendation:installer.recommendation??null,installerError:installer.error??null,install:installer.install??null,running:null}; + } + throw new Error(`Strata Control has no ${name}.`); + } + async function tool(name,args={}){if(packaged&&name==='strata_status')return controlTool(name,args);return mcpCall(name,args);} + async function mcpCall(name,args={}){await connect();if(!definitions.some(d=>d.name===name))throw new Error(`This Strata installation does not support ${name}. Update the installation first.`);const result=await send('tools/call',{name,arguments:args},120000);let value=result.structuredContent;if(!value){const text=result.content?.find(c=>c.type==='text')?.text;try{value=JSON.parse(text);}catch{value={summary:text};}}if(result.isError)throw new Error(value?.error??value?.summary??'Native operation failed.');return value;} + async function refresh(force=false){ + if(closing)return state(); + if(refreshing)return refreshing;if(!force&&Date.now()-lastRead<15000)return state(); + refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);const noImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,images:false,sizes:(f.sizes??[]).map(s=>({...s,images:false}))}))}:c;snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:packaged?noImages(catalog):catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing; + } + function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};packagedInstall=null;disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);} + function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();} + function record(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path,config:readJson(path)};} + function settings(model){const {config}=record(model);const values=Object.fromEntries(NATIVE_FIELDS.map(f=>[f.id,config[f.id]??null]));if(typeof values.aliases==='string')values.aliases=values.aliases.split(',').map(v=>v.trim()).filter(Boolean);values.sampling=config.sampling??{};values.args=config.args??[];values.env=publicNativeEnv(config.env??{});return {model,values,mcp:publicMcpServers(config.mcp_servers??config.mcpServers??{}),restartNeeded:true};} + function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);} + function previousEngine(){try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}} + async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);return tool('strata_install',installArgs(args,false));} + function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),...(packaged?{vision:'no'}:{}),confirm};} + + function begin(kind,run,metadata={}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or cancel the current engine operation first.');const job={id:randomUUID(),kind,state:'running',startedAt:new Date().toISOString(),summary:'Starting…',result:null,error:null,...metadata};for(const [id,old] of jobs)if(jobs.size>=12&&old.state!=='running')jobs.delete(id);jobs.set(job.id,job);emit();void run(job).then(result=>{if(job.state==='running'){Object.assign(job,{state:'done',summary:result?.summary??'Complete',result,finishedAt:new Date().toISOString()});}}).catch(error=>{if(job.state==='running')Object.assign(job,{state:'error',error:error.message,summary:error.message,finishedAt:new Date().toISOString()});}).finally(()=>{if(job.kind.startsWith('update')||job.kind==='rollback')disconnect();lastRead=0;emit();void refresh(true);});return state().jobs.find(j=>j.id===job.id);} + async function watchInstall(job,current){job.summary=current.step??'Resuming preparation status…';job.result={install:current};while(job.state==='running'){await new Promise(r=>setTimeout(r,1500));const result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(!result.install?.running){if(result.install?.exit_code!==0)throw new Error(result.install?.error??'Preparation did not finish. Retry to reuse completed files.');return {summary:'Model preparation complete. Load it from Models.'};}}} + function externalRunning(){return Array.isArray(snapshot.external)?snapshot.external.filter(s=>![...instances.values()].some(i=>i.port===s.port)):[];} + async function install(job,args){if(job.state!=='running')return;if(externalRunning().length)throw new Error('Stop the native server running outside this UI before preparing files.');if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel requests before preparing model files.');for(const id of [...instances.keys()])await unload(id);if(job.state!=='running')return;let result=await tool('strata_install',installArgs(args,true));job.summary=result.summary;job.result=result;emit();for(;;){if(job.state!=='running')return;await new Promise(resolve=>setTimeout(resolve,1500));result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(result.install&&!result.install.running){if(result.install.exit_code!==0)throw new Error(result.install.error??result.summary);await refresh(true);if(args.loadAfter){const model=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;return loadEngine(job,{model,multiple:!!args.multiple,resourceProfile:args.resourceProfile,vision:args.loadVision});}return result;}}} + function terminate(proc,signal='SIGTERM'){if(!proc)return;if(process.platform!=='win32'&&proc.pid){try{process.kill(-proc.pid,signal);return;}catch{}}proc.kill(signal);} + async function stopProcess(proc){if(!proc||proc.exitCode!=null)return;await new Promise(resolve=>{const timeout=setTimeout(()=>{terminate(proc,'SIGKILL');resolve();},8000);proc.once('exit',()=>{clearTimeout(timeout);resolve();});terminate(proc);});} + async function unload(id,force=false){const instance=instances.get(id);if(!instance)throw new Error('This model is no longer loaded.');if(!force&&[...jobs.values()].some(j=>j.kind==='benchmark'&&j.state==='running'&&j.instanceId===id))throw new Error('Stop the benchmark before unloading this model.');if(!force&&busy(requests().filter(r=>r.instanceId===id)))throw new Error('Finish or cancel this model’s requests first.');instance.status='unloading';if(instance.profile){try{await control.stop(instance.profile);}catch(error){if(!force){instance.status='error';instance.error=error.message;emit();throw error;}}}else await stopProcess(processes.get(id));processes.delete(id);instances.delete(id);try{unlinkSync(instance.configPath);}catch{}if(defaultId===id)defaultId=instances.keys().next().value??null;emit();return state();} + async function loadEngine(job,args){ + await refresh(true);if(job.state!=='running')return;const {config,entry}=record(args.model);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');}if(!entry.ready)throw new Error('Some model files are missing. Use Download / repair to restore them.'); + if(externalRunning().length)throw new Error('A Strata server is already running outside this UI. Stop it before loading here, or connect its API in Settings → Models.'); + if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.'); + const vision=runtimeVision(config,args.vision); + const visionPreferences=args.vision!==undefined?{ui_vision_enabled:args.vision!=='no',ui_vision_device:args.vision==='no'?config.ui_vision_device??'yes':args.vision}:{}; + const resources=args.resourceProfile?resourceSettings({...config,vision},snapshot.hardware,args.resourceProfile,modelArena(args.model)):null; + const cfg={...config,...visionPreferences,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),host:'127.0.0.1',open_browser:false,...validateNativeSettings(args.values??{}),vision}; + if(args.gpus!==undefined){const detected=new Set((snapshot.hardware?.gpus??[]).map(g=>g.index));if(!Array.isArray(args.gpus)||!args.gpus.length||new Set(args.gpus).size!==args.gpus.length||args.gpus.some(g=>!Number.isInteger(g)||!detected.has(g)))throw new Error('Choose distinct detected GPUs. CPU-only text inference is not supported by this native adapter.');cfg.gpu=args.gpus.length===1?args.gpus[0]:args.gpus;cfg.layer_split=args.gpus.length>1?validateNativeSettings({layer_split:args.layerSplit??'auto'}).layer_split:'auto';if(cfg.layer_split!=='auto'&&cfg.layer_split.split(',').length!==args.gpus.length-1)throw new Error('Choose one layer split point between each pair of GPUs.');} + if(cfg.vram_reserve_mib!==undefined&&cfg.vram_reserve_mib!==null){cfg.args=[...(cfg.args??[])];const at=cfg.args.indexOf('--vram-reserve-mib');if(at>=0)cfg.args.splice(at,2);cfg.args.push('--vram-reserve-mib',String(cfg.vram_reserve_mib));}if(cfg.vision){if(cfg.vision_tokens!=null)cfg.vision={...cfg.vision,max_tokens:cfg.vision_tokens};if(cfg.vision_min_tokens!=null)cfg.vision={...cfg.vision,min_tokens:cfg.vision_min_tokens};}cfg.mcp={...(cfg.mcp??{}),...(cfg.mcp_timeout_s!=null?{timeout_s:cfg.mcp_timeout_s}:{}),...(cfg.mcp_max_rounds!=null?{max_rounds:cfg.mcp_max_rounds}:{}),...(cfg.mcp_max_result_chars!=null?{max_result_chars:cfg.mcp_max_result_chars}:{})}; + for(const arg of cfg.args??[])if(arg.endsWith('.gguf')&&!existsSync(resolve(repo(),arg)))throw new Error('An engine argument names a missing GGUF. Restore the saved arguments or repair the files.'); + const fingerprint=createHash('sha256').update(JSON.stringify({...cfg,api_key:undefined,port:undefined})).digest('hex'); + const placement=Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu];const matching=[...instances.values()].find(i=>i.model===args.model&&JSON.stringify(i.gpus)===JSON.stringify(placement)); + if(matching?.status==='ready'&&matching.fingerprint===fingerprint&&(args.multiple||instances.size===1))return {summary:`${matching.label} is already ready.`,instanceId:matching.id}; + const wasDefault=matching?.id===defaultId; + const id=matching?.id??randomUUID();let apiModelId=matching?.apiModelId??args.model,suffix=1;while(!matching&&[...instances.values()].some(i=>i.apiModelId===apiModelId))apiModelId=`${args.model}--${++suffix}`; + cfg.aliases=[...new Set([...(Array.isArray(cfg.aliases)?cfg.aliases:typeof cfg.aliases==='string'?cfg.aliases.split(',').map(s=>s.trim()).filter(Boolean):[]),apiModelId])]; + const key=randomBytes(32).toString('hex');cfg.api_key=key;cfg.port=await freePort(args.port); + const work=join(directory,'native-instances');mkdirSync(work,{recursive:true});const configPath=join(work,`${id}.json`); + const py=packaged?null:venvPython(repo());if(!packaged&&!existsSync(py))throw new Error('The Strata Python environment is missing. Use Download / repair first.'); + if(job.state!=='running')return; + await beforeLoad();if(job.state!=='running')return; + if(!args.multiple){if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel native requests before switching models.');for(const id of [...instances.keys()])await unload(id);}else if(matching)await unload(matching.id); + if(job.state!=='running')return; + writeFileSync(configPath,JSON.stringify(cfg,null,2),{mode:0o600}); + const instance={id,apiModelId,fingerprint,context:entry.context??0,aliases:cfg.aliases??[],vision:!!cfg.vision,model:args.model,label:entry.model_name??args.model,port:cfg.port,gpus:Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu],status:'loading',phase:'loading',key,configPath,loadedAt:new Date().toISOString(),metrics:null,error:null}; + let proc=null,started=null; + if(packaged){ + /* The engine starts under Control's owner runtime, not as our child: a saved profile per slot, then `runtime start`. */ + const used=new Set([...instances.values()].map(i=>i.profile));let slot=1;while(used.has('app-'+slot))slot++;instance.profile='app-'+slot; + instances.set(id,instance);if(!defaultId||!args.multiple||wasDefault)defaultId=id;emit(); + started=control.stop(instance.profile).catch(()=>{}).then(()=>control.saveProfile(instance.profile,configPath)).then(()=>control.start(instance.profile,{waitSeconds:300})); + started.then(()=>append(id,'Strata Control reports the engine is ready.'),error=>{append(id,error.message);}); + try{await started;}catch(error){const said=humanStartError(error);instance.status='error';instance.error=said;emit();throw new Error(said);} + } else { + proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8',STRATA_API_KEY:''}}); + instances.set(id,instance);processes.set(id,proc);if(!defaultId||!args.multiple||wasDefault)defaultId=id; + for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{const lines=chunk.toString().split('\n').filter(Boolean);lines.forEach(line=>append(id,line.replaceAll(key,'[redacted]')));job.summary=lines.at(-1)??job.summary;emit();}); + proc.on('error',error=>{instance.status='error';instance.error=error.message;emit();});proc.on('exit',code=>{if(instances.has(id)&&instance.status!=='unloading'){instance.status='error';instance.error=`Engine stopped${code===null?'':` (exit ${code})`}. Open diagnostics or reload.`;emit();}});emit(); + } + const deadline=Date.now()+300000;while(Date.now()setTimeout(resolve,1200)); + } + if(job.state!=='running'){await unload(id);return;} + if(instance.profile)await control.stop(instance.profile).catch(()=>{});else await stopProcess(proc);instance.status='error';instance.error='Loading took more than five minutes. Check the engine log and free memory.';throw new Error(instance.error); + } + async function freePort(requested){for(let port=Number(requested??18500);port<=Number(requested??18500)+20;port++){if(!Number.isInteger(port)||port<1024||port>65535)throw new Error('Choose a port from 1024 to 65535.');if([...instances.values()].some(i=>i.port===port)){if(requested)throw new Error('This private engine port is already in use.');continue;}const available=await new Promise(resolve=>{const probe=createServer();probe.once('error',()=>resolve(false));probe.listen(port,'127.0.0.1',()=>probe.close(()=>resolve(true)));});if(available)return port;if(requested)throw new Error('This private engine port is already in use.');}throw new Error('No free private engine port was found.');} + async function poll(){if(polling||closing)return;polling=true;try{await Promise.all([...instances.values()].map(async instance=>{if(instance.status!=='ready')return;try{const response=await fetcher(`http://127.0.0.1:${instance.port}/metrics?requests=all`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(!response.ok)throw new Error('Metrics unavailable');instance.metrics=await response.json();const tools=await fetcher(`http://127.0.0.1:${instance.port}/mcp`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(tools.ok)instance.metrics.mcp=await tools.json();instance.phase=instance.metrics.live?.state??'idle';}catch{instance.metrics=null;instance.phase='unavailable';}}));emit();}finally{polling=false;}} + function ensurePoll(){if(!timer){timer=setInterval(()=>void poll(),2000);timer.unref?.();}void poll();} + async function benchmark(job,args){const instance=resolveInstance(args.instanceId);job.instanceId=instance.id;if(busy(requests().filter(r=>r.instanceId===instance.id)))throw new Error('Wait for this model to finish before benchmarking.');const started=Date.now();job.abort=new AbortController();const response=await fetcher(`http://127.0.0.1:${instance.port}/v1/chat/completions`,{method:'POST',headers:{'content-type':'application/json',authorization:`Bearer ${instance.key}`},signal:AbortSignal.any([job.abort.signal,AbortSignal.timeout(180000)]),body:JSON.stringify({model:instance.apiModelId,messages:[{role:'user',content:'Explain how a rainbow forms in clear, simple language.'}],temperature:0,reasoning_effort:'none',max_tokens:200,stream:false})});const body=await response.json();if(!response.ok)throw new Error(body.error?.message??'Benchmark failed.');if(job.state!=='running')return;const result={summary:'Measured benchmark complete.',at:new Date().toISOString(),model:instance.apiModelId,durationMs:Date.now()-started,tokensIn:body.usage?.prompt_tokens??null,tokensOut:body.usage?.completion_tokens??null,outputTps:body.timings?.predicted_per_second??null,promptTps:body.timings?.prompt_per_second??null,source:'engine',settings:'Greedy · thinking off · up to 200 output tokens'};writeFileSync(join(directory,'native-benchmark.json'),JSON.stringify(result,null,2),{mode:0o600});return result;} + function resolveInstance(id){const aliases=[...instances.values()].filter(i=>i.aliases?.includes(id));if(aliases.length>1&&!instances.has(id)&&![...instances.values()].some(i=>i.apiModelId===id))throw new Error('This alias matches more than one instance. Choose its exact model ID.');const i=instances.get(id)??[...instances.values()].find(i=>i.apiModelId===id)??aliases[0]??(!id&&instances.size===1?[...instances.values()][0]:undefined);if(!i)throw new Error('Choose a loaded model ID.');if(i.status!=='ready')throw new Error('This model is not ready.');return i;} + async function program(job,args){if(packaged)throw new Error(NO_INSTALL);if(externalRunning().length)throw new Error('Stop the native server running outside this UI before changing engine files.');if(instances.size)throw new Error('Unload native models before changing engine files.');const folder=repo();let {command,args:prefix}=python(),argv; + if(job.kind==='calibrate'||job.kind==='tune'){if(!state().capabilities.calibration)throw new Error('This installation calibrates NVIDIA GPUs only. Use the short benchmark on other devices.');const model=args.model??snapshot.installed?.models?.[0]?.model;const chosen=record(model);if(!chosen.entry.ready)throw new Error('Prepare this model before calibrating.');command=venvPython(folder);prefix=[];if(!existsSync(command))throw new Error('Prepare the Python environment first.');argv=['-c','import sys; from pathlib import Path; import setup; sys.exit(0 if setup.calibrate_config(Path(sys.argv[1])) else 1)',chosen.path];} + else if(job.kind==='rollback'){if(!previousEngine())throw new Error('No saved previous engine is available.');argv=[join(folder,'setup.py'),'--rollback-engine'];} + else if(job.kind==='update-engine'){if(!snapshot.installed?.models?.length)throw new Error('Prepare a model first. Its installer downloads the matching engine.');argv=[join(folder,'setup.py'),'--update'];} + else if(job.kind==='update-strata'){const status=await execute('git',['status','--porcelain'],folder);if(status.trim())throw new Error('This Strata checkout has local edits. Save or commit them before updating.');const remote=await execute('git',['remote','get-url','origin'],folder);if(!/^https:\/\/github\.com\/Niko1221\/Strata(?:\.git)?\s*$/.test(remote))throw new Error('The native installation must use the official Strata repository to update here.');await execute('git',['pull','--ff-only'],folder);argv=[join(folder,'setup.py'),'--update'];} + else throw new Error('Unsupported native operation.'); + return new Promise((resolve,reject)=>{const proc=spawnProcess(command,[...prefix,...argv],{cwd:folder,windowsHide:true,detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1'}});job.process=proc;for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{chunk.toString().split('\n').filter(Boolean).forEach(line=>append(job.id,line));job.summary=chunk.toString().trim().slice(-500);emit();});proc.on('error',reject);proc.on('exit',code=>{delete job.process;code===0?resolve({summary:job.kind==='calibrate'?'Calibration complete. Native settings were saved.':'Native installation updated.'}):reject(new Error(`Operation stopped (exit ${code}). Open diagnostics for details.`));});}); + } + function execute(cmd,args,cwd){return new Promise((resolve,reject)=>{let output='';const process=spawnProcess(cmd,args,{cwd,stdio:['ignore','pipe','pipe']});process.stdout.on('data',c=>{output+=c;if(output.length>100000)process.kill();});process.stderr.on('data',c=>append('update',c.toString()));process.on('error',reject);process.on('exit',code=>code===0?resolve(output):reject(new Error('Git could not update this installation. Open diagnostics.')));});} + function writeModelConfig(path,next){copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);} + async function tune(job,args){ + await refresh(true);if(job.state!=='running')return; + const chosen=record(args.model);resourceSettings(chosen.config,snapshot.hardware,args.profile,modelArena(args.model)); + if(!chosen.entry.ready)throw new Error('Prepare the model before tuning.'); + if(externalRunning().length)throw new Error('Stop the native server outside this UI before tuning.'); + if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish requests before tuning.'); + for(const id of [...instances.keys()])await unload(id); + if(job.state!=='running')return; + const initialValues=resourceSettings(chosen.config,snapshot.hardware,args.profile,modelArena(args.model));writeModelConfig(chosen.path,{...chosen.config,...initialValues,ui_resource_profile:args.profile}); + if(args.calibrate!==false&&state().capabilities.calibration){job.summary='Measuring the best engine settings for this computer…';emit();await program(job,args);} + if(job.state!=='running')return; + const current=record(args.model),values=resourceSettings(current.config,snapshot.hardware,args.profile,modelArena(args.model)); + const next={...current.config,...values,ui_resource_profile:args.profile}; + writeModelConfig(current.path,next); + job.summary='Applying your resource preference and loading the model…';emit(); + const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:current.config.vision?args.vision:'no'}); + if(job.state!=='running'||!loaded?.instanceId)return; + job.summary='Checking your model’s speed…';emit(); + const measured=await benchmark(job,{instanceId:loaded.instanceId}); + return {...loaded,...measured,summary:'Your model is tuned and ready.',profile:args.profile}; + } + function operation(kind,args={}){if(!['install','load','benchmark','tune','calibrate','update-engine','update-strata','rollback'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):program(job,args),{guided:args.guided===true,model:args.model});} + async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install')await tool('strata_install',{cancel:true});else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} + async function close(){closing=true;clearInterval(timer);const installing=packaged&&child&&[...jobs.values()].some(j=>j.kind==='install'&&j.state==='running');if(installing)await send('tools/call',{name:'strata_install',arguments:{cancel:true}},15000).catch(()=>{});const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();} + // Remove nonserializable process references from public jobs. + const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,...job})=>job);return value;}; + return {state:publicState,refresh,configure,setDownloadDirectory,plan,settings,save,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; +} diff --git a/apps/host/tests/packaged-control.test.mjs b/apps/host/tests/packaged-control.test.mjs index f6ce53cc..6e701882 100644 --- a/apps/host/tests/packaged-control.test.mjs +++ b/apps/host/tests/packaged-control.test.mjs @@ -306,3 +306,25 @@ test('packaged: an engine that stops while loading keeps the code and the last e assert.match(job.error, /^server_exited: memory guard: 5\.1 GiB free/); } finally { await f.native.close(); f.cleanup(); } }); + +test('packaged: a run config that points into an old Control folder is repaired to this Control (a reinstall or an update moved it)', async () => { + const f = packagedFixture(); + try { + const here = join(f.root, 'control'); + mkdirSync(join(here, 'data'), { recursive: true }); + writeFileSync(join(here, 'data', 'expert-profile.bin'), 'profile'); + const path = join(f.install, 'strata-iq2_xs.json'); + const old = 'C:/Users/Alex/AppData/Local/Temp/strata-life-install/control'; + writeFileSync(path, JSON.stringify({ exe: 'component:strata-engine', cwd: old, args: ['--pack', 'D:/Strata/packs/x', '--expert-profile', old + '/data/expert-profile.bin', '--max-context', '32768'], model_name: 'x', port: 8080 })); + await f.native.refresh(true); + const repaired = JSON.parse(readFileSync(path, 'utf8')); + assert.equal(repaired.cwd.toLowerCase(), here.toLowerCase()); + assert.equal(repaired.args[repaired.args.indexOf('--expert-profile') + 1].toLowerCase(), join(here, 'data', 'expert-profile.bin').toLowerCase()); + assert.equal(repaired.args[1], 'D:/Strata/packs/x', 'paths outside Control are left alone'); + assert.ok(existsSync(path + '.bak'), 'the old config is kept'); + // a config that is already right, or whose new target is not there, is not touched + const before = readFileSync(path, 'utf8'); + await f.native.refresh(true); + assert.equal(readFileSync(path, 'utf8'), before); + } finally { await f.native.close(); f.cleanup(); } +}); diff --git a/tests/desktop/test_nsis_layout.py b/tests/desktop/test_nsis_layout.py new file mode 100644 index 00000000..9fbf228f --- /dev/null +++ b/tests/desktop/test_nsis_layout.py @@ -0,0 +1,101 @@ +r"""The Windows installer must never touch the user's data. The app lives in %LOCALAPPDATA%\Programs\Strata; %LOCALAPPDATA%\Strata +holds engines, model run configs, tuning. A build that installed the app into the data folder is migrated by removing only its app +files. Exercised with makensis on a temp layout (the template's own migration macro, extracted and run); skipped without NSIS.""" + +import os +import re +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +TEMPLATE = ROOT / "apps" / "desktop" / "src-tauri" / "nsis" / "installer.nsi" +MAKENSIS = Path(os.environ.get("LOCALAPPDATA", "")) / "tauri" / "NSIS" / "makensis.exe" +DATA = ["components/engine/0.1.45/strata.exe", "install/strata-iq3_s.json", "procs/p.json", "runtime/r.json", "time-skip/t.json", + "presets/p.json"] +APP = ["strata-desktop.exe", "uninstall.exe", "host/server/index.mjs", "node/node.exe", "control/python/python.exe"] +BS = "\\" + + +def touch(base: Path, names): + for name in names: + path = base / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("x", encoding="utf-8") + + +class TemplateTests(unittest.TestCase): + text = TEMPLATE.read_text(encoding="utf-8") + + def test_the_default_folder_is_programs_strata_and_the_data_folder_is_never_remembered_as_the_app(self): + self.assertIn(r'StrCpy $INSTDIR "$LOCALAPPDATA\Programs\${PRODUCTNAME}"', self.text) + self.assertIn(r'StrCmp $4 "$LOCALAPPDATA\${PRODUCTNAME}" restore_done 0', self.text) + self.assertIn("StrIsUnder", self.text) # a remembered folder under Temp is ignored too + + def test_the_uninstaller_removes_files_one_by_one_and_only_empty_folders(self): + uninstall = self.text[self.text.index("Section Uninstall"):] + self.assertNotRegex(uninstall, r'RMDir /r "\$INSTDIR"') + self.assertNotIn(r'RmDir /r "$LOCALAPPDATA\${PRODUCTNAME}"', self.text) + self.assertIn(r'RmDir /r "$LOCALAPPDATA\${BUNDLEID}"', self.text) + + +@unittest.skipUnless(MAKENSIS.is_file(), "NSIS (the Tauri bundler's copy) is not installed here") +class MigrationTests(unittest.TestCase): + def run_nsis(self, body: str, work: Path): + block = re.search(r"; STRATA-MIGRATE-BEGIN.*?; STRATA-MIGRATE-END", TEMPLATE.read_text(encoding="utf-8"), re.S).group(0) + script = work / "t.nsi" + script.write_text('Unicode true\nOutFile "t.exe"\nRequestExecutionLevel user\nSilentInstall silent\n' + block + "\nSection\n" + body + "\nSectionEnd\n", encoding="utf-8") + done = subprocess.run([str(MAKENSIS), "/V1", str(script)], cwd=work, capture_output=True, text=True) + self.assertEqual(done.returncode, 0, done.stdout + done.stderr) + subprocess.run([str(work / "t.exe")], cwd=work, check=True, timeout=60) + + def layout(self, base: Path) -> Path: + old = base / "Strata" + touch(old, DATA + APP) + return old + + def test_migration_removes_only_the_old_app_files_and_keeps_every_bit_of_data(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + old = self.layout(base) + new = base / "Programs" / "Strata" + self.run_nsis(f'!insertmacro StrataMigrateOldInstall "{old}" "{new}"', base) + for name in DATA: + self.assertTrue((old / name).is_file(), f"data kept: {name}") + for name in APP: + self.assertFalse((old / name).exists(), f"app file removed: {name}") + for folder in ("host", "node", "control"): + self.assertFalse((old / folder).exists()) + + def test_migration_does_nothing_when_old_and_new_are_the_same_or_there_is_no_old_app(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + old = self.layout(base) + self.run_nsis(f'!insertmacro StrataMigrateOldInstall "{old}" "{old}"', base) + for name in DATA + APP: + self.assertTrue((old / name).is_file(), name) + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + touch(base / "Strata", DATA) # data only: no strata-desktop.exe + self.run_nsis(f'!insertmacro StrataMigrateOldInstall "{base / "Strata"}" "{base / "Programs" / "Strata"}"', base) + for name in DATA: + self.assertTrue((base / "Strata" / name).is_file(), name) + + def test_an_uninstall_of_the_template_kind_leaves_data_in_a_shared_folder(self): + """The uninstaller deletes named files and uses non-recursive RMDir: in a folder that also holds data (a legacy install) the + data and so the folder stay.""" + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + old = self.layout(base) + lines = [f'Delete "{old}{BS}{n.replace("/", BS)}"' for n in APP] + lines += [f'RMDir "{old}{BS}{d}"' for d in ("host" + BS + "server", "host", "node", "control" + BS + "python", "control")] + lines += [f'RMDir "{old}"'] + self.run_nsis("\n".join(lines), base) + for name in DATA: + self.assertTrue((old / name).is_file(), name) + self.assertFalse((old / "strata-desktop.exe").exists()) + + +if __name__ == "__main__": + unittest.main() From 0db5d17102adc67a01b38ef5465f59ab428f2b0e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 20:25:35 +0200 Subject: [PATCH 11/16] chat speed is decode speed with reasoning, context shown is the running model's, Models shows Unload while loaded, VRAM reserve floor, default text size 14, installer branding, icon --- apps/desktop/scripts/make-icons.mjs | 78 ++++++++++++++++++ .../desktop/scripts/make-installer-images.mjs | 66 +++++++++++++++ apps/desktop/scripts/ui-flows.mjs | 59 +++++++++++-- apps/desktop/src-tauri/icons/128x128.png | Bin 3576 -> 2052 bytes apps/desktop/src-tauri/icons/128x128@2x.png | Bin 7686 -> 4314 bytes apps/desktop/src-tauri/icons/32x32.png | Bin 882 -> 433 bytes apps/desktop/src-tauri/icons/64x64.png | Bin 1687 -> 1004 bytes apps/desktop/src-tauri/icons/icon.ico | Bin 13777 -> 11409 bytes apps/desktop/src-tauri/icons/icon.png | Bin 16378 -> 9537 bytes apps/desktop/src-tauri/nsis/header.bmp | Bin 0 -> 25818 bytes apps/desktop/src-tauri/nsis/installer.nsi | 14 +++- apps/desktop/src-tauri/nsis/sidebar.bmp | Bin 0 -> 154542 bytes apps/desktop/src-tauri/tauri.conf.json | 6 +- apps/host/server/inference.mjs | 10 +++ apps/host/server/native-resources.mjs | 5 +- apps/host/src/components/NativeModels.tsx | 4 +- apps/host/src/components/TelemetryPopover.tsx | 7 +- apps/host/src/lib/store.ts | 6 +- apps/host/src/styles/app.css | 17 ++-- apps/host/tests/agent-host.test.mjs | 2 +- apps/host/tests/resource-ram.test.mjs | 14 ++++ apps/host/tests/stream-speed.test.mjs | 40 +++++++++ 22 files changed, 303 insertions(+), 25 deletions(-) create mode 100644 apps/desktop/scripts/make-icons.mjs create mode 100644 apps/desktop/scripts/make-installer-images.mjs create mode 100644 apps/desktop/src-tauri/nsis/header.bmp create mode 100644 apps/desktop/src-tauri/nsis/sidebar.bmp create mode 100644 apps/host/tests/stream-speed.test.mjs diff --git a/apps/desktop/scripts/make-icons.mjs b/apps/desktop/scripts/make-icons.mjs new file mode 100644 index 00000000..411e4b97 --- /dev/null +++ b/apps/desktop/scripts/make-icons.mjs @@ -0,0 +1,78 @@ +#!/usr/bin/env node +/** + * The app and installer icon, refined from the existing Strata mark (apps/host/public/brand/strata-mark-*.svg and the current + * icons/icon.png): the same three rounded bars on the same dark tile, in the same colours. Nothing is redrawn. What changes is + * how it is cut for small sizes: at 16-48 px the bars are snapped to whole pixels and made a little bolder and wider so they + * stay crisp instead of blurring; from 64 px up the geometry is the mark's own proportions. + * + * node apps/desktop/scripts/make-icons.mjs [--out ] writes icon-.png for every size and icon.ico + */ +import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); +const here = dirname(fileURLToPath(import.meta.url)); +const host = resolve(here, '../../host'); +const out = resolve(args.out ?? join(here, '../src-tauri/icons')); +mkdirSync(out, { recursive: true }); +const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); +const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); + +const TILE = '#161a1d', LIGHT = '#eef1f3', GREEN = '#34d399'; // the colours of the current icon.png + +/** Integer geometry for the small sizes: bars on whole pixels, centred. Returns [{x,y,w,h,fill}]. */ +function hinted(size) { + const bar = Math.max(2, Math.round(size * 0.14)), gap = Math.max(2, Math.round(size * 0.1)), mid = bar + 1; + const total = 2 * bar + mid + 2 * gap, top = Math.floor((size - total) / 2); + const even = w => (w % 2 === size % 2 ? w : w + 1); + const wide = even(Math.round(size * 0.5)), long = even(Math.round(size * 0.76)); + return [ + { x: (size - wide) / 2, y: top, w: wide, h: bar, fill: LIGHT }, + { x: (size - long) / 2, y: top + bar + gap, w: long, h: mid, fill: GREEN }, + { x: (size - wide) / 2, y: top + bar + gap + mid + gap, w: wide, h: bar, fill: LIGHT }, + ]; +} +/** The mark's own proportions (from icon.png at 512): bars 34% / 50% / 34% wide, 9% high, on a tile with 21.5% corners. */ +function proportional(size) { + const k = size / 512; + return [ + { x: 170 * k, y: 156 * k, w: 173 * k, h: 46 * k, fill: LIGHT }, + { x: 128 * k, y: 232 * k, w: 256 * k, h: 48 * k, fill: GREEN }, + { x: 170 * k, y: 309 * k, w: 173 * k, h: 46 * k, fill: LIGHT }, + ]; +} +function svg(size) { + const small = size <= 48; + const bars = (small ? hinted(size) : proportional(size)); + const radius = small ? Math.round(size * 0.22) : size * 0.215; + const rects = bars.map(b => ``).join(''); + return `${rects}`; +} + +const SIZES = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256, 512, 1024]; +const browser = await chromium.launch({ executablePath: CHROME, headless: true }); +const png = {}; +for (const size of SIZES) { + const page = await browser.newPage({ viewport: { width: size, height: size }, deviceScaleFactor: 1 }); + await page.setContent(`${svg(size)}`); + png[size] = await page.screenshot({ omitBackground: true, clip: { x: 0, y: 0, width: size, height: size } }); + await page.close(); + writeFileSync(join(out, `icon-${size}.png`), png[size]); +} +await browser.close(); + +// The .ico: one PNG image per size (16-256), the sizes Windows asks for at 100-250% scaling. +const ICO = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256]; +const head = Buffer.alloc(6); head.writeUInt16LE(0, 0); head.writeUInt16LE(1, 2); head.writeUInt16LE(ICO.length, 4); +let offset = 6 + 16 * ICO.length; +const entries = [], blobs = []; +for (const size of ICO) { + const data = png[size], e = Buffer.alloc(16); + e.writeUInt8(size === 256 ? 0 : size, 0); e.writeUInt8(size === 256 ? 0 : size, 1); e.writeUInt8(0, 2); e.writeUInt8(0, 3); + e.writeUInt16LE(1, 4); e.writeUInt16LE(32, 6); e.writeUInt32LE(data.length, 8); e.writeUInt32LE(offset, 12); + offset += data.length; entries.push(e); blobs.push(data); +} +writeFileSync(join(out, 'icon.ico'), Buffer.concat([head, ...entries, ...blobs])); +writeFileSync(join(out, 'icon.png'), png[512]); +console.log('icons in', out, ICO.join(',')); diff --git a/apps/desktop/scripts/make-installer-images.mjs b/apps/desktop/scripts/make-installer-images.mjs new file mode 100644 index 00000000..f12d6cc1 --- /dev/null +++ b/apps/desktop/scripts/make-installer-images.mjs @@ -0,0 +1,66 @@ +#!/usr/bin/env node +/** + * The installer's pictures, drawn from the app's own design: the light surface and ink colours of the app (src/styles tokens), the + * brand lockup and mark files, GT Walsheim Bold for the words (baked into the pictures, because NSIS cannot use a web font). + * + * node apps/desktop/scripts/make-installer-images.mjs [--out ] [--preview ] + * + * Writes sidebar.bmp (164x314, the welcome and finish pages) and header.bmp (150x57, the other pages) as 24-bit BMPs, and with + * --preview the same as PNGs at 3x. + */ +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { tmpdir } from 'node:os'; + +const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); +const here = dirname(fileURLToPath(import.meta.url)); +const host = resolve(here, '../../host'); +const out = resolve(args.out ?? join(here, '../src-tauri/nsis')); +mkdirSync(out, { recursive: true }); +const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); +const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); +const font = pathToFileURL(join(host, 'public/fonts/GTWalsheimPro-Bold.woff2')).href; +const fontMedium = pathToFileURL(join(host, 'public/fonts/GTWalsheimPro-Medium.woff2')).href; +const lockup = readFileSync(join(host, 'public/brand/strata-lockup-light.svg'), 'utf8'); +const mark = readFileSync(join(host, 'public/brand/strata-mark-light.svg'), 'utf8'); + +// the app's light tokens +const SURFACE = '#f9fafb', INK = '#171b1e', MUTED = '#5b646b', ACCENT = '#10b981', LINE = '#e3e8ea'; +const css = `@font-face{font-family:GT;font-weight:700;src:url(${font})}@font-face{font-family:GT;font-weight:500;src:url(${fontMedium})} +*{box-sizing:border-box}body{margin:0;font-family:GT,'Segoe UI',sans-serif;color:${INK};background:${SURFACE}}`; + +const pages = { + sidebar: { w: 164, h: 314, html: `
+
${lockup.replace(' +
+
State of
the art.
At home.
+
AI on your own computer.
Private. Fast. Easy.
+
+
` }, + header: { w: 150, h: 57, html: `
${lockup.replace('` }, +}; + +const browser = await chromium.launch({ executablePath: CHROME, headless: true }); +const work = join(tmpdir(), 'strata-installer-images'); mkdirSync(work, { recursive: true }); +for (const [name, page] of Object.entries(pages)) { + for (const scale of [1, 3]) { + const file = join(work, `${name}.html`); + writeFileSync(file, `${page.html}`); + const tab = await browser.newPage({ viewport: { width: page.w, height: page.h }, deviceScaleFactor: scale }); + await tab.goto(pathToFileURL(file).href); + await tab.evaluate(() => document.fonts.ready); + await tab.waitForTimeout(200); + const png = join(work, `${name}@${scale}.png`); + await tab.screenshot({ path: png, clip: { x: 0, y: 0, width: page.w, height: page.h } }); + await tab.close(); + if (scale === 3 && args.preview) { mkdirSync(resolve(args.preview), { recursive: true }); writeFileSync(join(resolve(args.preview), `${name}.png`), readFileSync(png)); } + } +} +await browser.close(); +// 24-bit BMP, the format NSIS wants: render at 3x, shrink with a good filter +const py = `import sys\nfrom PIL import Image\nfor name in ('sidebar','header'):\n im = Image.open(sys.argv[1] + '/' + name + '@3.png').convert('RGB')\n w, h = im.width // 3, im.height // 3\n im.resize((w, h), Image.LANCZOS).save(sys.argv[2] + '/' + name + '.bmp', 'BMP')\n`; +const done = spawnSync('python', ['-c', py, work, out], { encoding: 'utf8' }); +if (done.status !== 0) { console.error(done.stderr); process.exit(1); } +console.log('wrote', join(out, 'sidebar.bmp'), join(out, 'header.bmp')); diff --git a/apps/desktop/scripts/ui-flows.mjs b/apps/desktop/scripts/ui-flows.mjs index 3fc3f0e8..69e261a8 100644 --- a/apps/desktop/scripts/ui-flows.mjs +++ b/apps/desktop/scripts/ui-flows.mjs @@ -98,19 +98,23 @@ for line in sys.stdin: `; writeFileSync(join(control, 'tools', 'strata_mcp.py'), FAKE_INSTALLER); -const FAKE_ENGINE = `import os, sys, json +const FAKE_ENGINE = `import os, sys, json, time from pathlib import Path if os.environ.get('FAKE_ENGINE_FAIL'): print('memory guard: 5.1 GiB of RAM free is under the 6 GiB limit (limit 63.1 GiB)', flush=True) sys.exit(3) -print('READY 4096 stop', flush=True) +ctx = '4096' +if '--max-context' in sys.argv: ctx = sys.argv[sys.argv.index('--max-context') + 1] +print('READY %s stop' % ctx, flush=True) for line in sys.stdin: if line.strip() == 'QUIT': break if line.startswith(('GEN ', 'BGEN ')): slot = int(line.split()[1]) if line.startswith('BGEN ') else None + t0 = time.time(); n = 0 for ch in os.environ.get('FAKE_REPLY', 'a'): - print('T %d' % ord(ch), flush=True) - print('DONE 1 1 1.0 1.0 length 0 0 0', flush=True) + print('T %d' % ord(ch), flush=True); n += 1 + if os.environ.get('FAKE_TOKEN_DELAY'): time.sleep(float(os.environ['FAKE_TOKEN_DELAY'])) + print('DONE %d 12 300.0 %.1f length 0 0 0' % (n, max(1.0, (time.time() - t0) * 1000)), flush=True) if slot is not None: print(f'BADM {slot} 0', flush=True) `; @@ -243,11 +247,22 @@ await scenario('models', { installed: true }, async ({ base, api, browser, shot for (let i = 0; i < 90 && !ready; i++) { const s = (await api('/api/native')).body; ready = s.instances.some(x => x.status === 'ready'); const err = s.instances.find(x => x.status === 'error'); if (err) throw new Error('load failed: ' + err.error); await delay(1000); } if (!ready) { const st = (await api('/api/native')).body; console.log('info jobs', JSON.stringify(st.jobs.map(j => [j.kind, j.state, j.error ?? j.summary])), 'instances', JSON.stringify(st.instances.map(i => [i.status, i.error]))); await shot(page, '2-models-after-click'); } check(ready, 'the model loads (a fake engine under the real Control)'); + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.getByRole('button', { name: /^Unload$/ }).first().waitFor({ timeout: 30000 }).catch(() => {}); + await shot(page, '3-models-loaded'); + check(await page.getByRole('button', { name: /^Unload$/ }).count() > 0, 'after a reload the Models screen shows the model as loaded, with Unload'); + check(await page.getByRole('button', { name: /^Load model$/ }).count() === 0, 'and no longer offers Load model'); + await page.getByRole('button', { name: /^Unload$/ }).first().click(); + let gone = false; + for (let i = 0; i < 40 && !gone; i++) { gone = (await api('/api/native')).body.instances.length === 0; await delay(500); } + check(gone, 'Unload stops the engine'); + await page.getByRole('button', { name: /^Load model$/ }).first().waitFor({ timeout: 15000 }).catch(() => {}); + check(await page.getByRole('button', { name: /^Load model$/ }).count() > 0, 'and Load model is back'); check(page.problems.length === 0, 'no page error', page.problems.join('; ')); }); // ------------------------------------------------------------------------------------------------ tune + reading size -await scenario('tune', { installed: true, env: { FAKE_REPLY: ['I am thinking about it.', '', '', 'Here is a list:', '', '- one', '- two', '', '## Heading', '', 'Some `code` and **bold** text.', '', '| a | b |', '|---|---|', '| 1 | 2 |', '', '```', 'code line', '```', ''].join(String.fromCharCode(10)) } }, async ({ base, api, browser, dirs, shot }) => { +await scenario('tune', { installed: true, env: { FAKE_TOKEN_DELAY: '0.02', FAKE_REPLY: ['I am thinking about it.', '', '', 'Here is a list:', '', '- one', '- two', '', '## Heading', '', 'Some `code` and **bold** text.', '', '| a | b |', '|---|---|', '| 1 | 2 |', '', '```', 'code line', '```', ''].join(String.fromCharCode(10)) } }, async ({ base, api, browser, dirs, shot }) => { const page = await newPage(browser, base); await clickText(page, /get started/i); await page.getByText(/Choose a version/i).waitFor({ timeout: 30000 }); @@ -272,23 +287,51 @@ await scenario('tune', { installed: true, env: { FAKE_REPLY: ['I am thinking abo await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 60000 }); await page.locator('.st-msg--assistant .st-bubble p').first().waitFor({ timeout: 60000 }).catch(async () => console.log('info reply so far:', JSON.stringify(await page.locator('.st-msg--assistant').first().innerText()).slice(0, 300))); await page.waitForFunction(() => !document.querySelector('.st-msg--assistant .caret'), null, { timeout: 90000 }).catch(() => {}); + // the chat's telemetry chips: speed and context + const chips = page.locator('.telemetry__chip'); + const chipTexts = await chips.allInnerTexts(); + console.log('info chips', JSON.stringify(chipTexts)); + let speedText = '', contextText = ''; + for (let i = 0; i < await chips.count(); i++) { + await chips.nth(i).click(); + await delay(400); + const pop = await page.locator('.telepop').last().innerText().catch(() => ''); + if (/tok\/s|speed/i.test(pop) && !speedText) speedText = pop; + if (/context/i.test(pop) && !contextText) contextText = pop; + await page.keyboard.press('Escape'); + } + const tps = Number(speedText.match(/([\d.]+)\s*tok(?:ens)?\/s/)?.[1] ?? NaN); + check(tps > 15 && tps < 120, 'the speed shown is the decode speed (the engine paced at ~50 tokens a second)', speedText.replace(/\s+/g, ' ').slice(0, 160)); + check(/32\.8K|32K|32,768|32768/.test(contextText) && !/128K/.test(contextText), 'the context shown is the one the model runs with (32K), not 128K', contextText.replace(/\s+/g, ' ').slice(0, 160)); const sizes = []; - for (const px of [12, 16, 22]) { + for (const px of [12, 14, 16, 22]) { await page.evaluate(v => { const k = 'strata.prefs.v2'; const cur = JSON.parse(localStorage.getItem(k) || '{}'); localStorage.setItem(k, JSON.stringify({ ...cur, contentFontSize: v })); }, px); await page.reload({ waitUntil: 'domcontentloaded' }); await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 30000 }); + await page.screenshot({ path: join(shots, `tune-3-chat-${px}px.png`) }); sizes.push(await page.evaluate(() => { const b = document.querySelector('.st-msg--assistant .st-bubble'); const t = b.querySelector('p, .md-li, span') ?? b; const u = document.querySelector('.st-msg--user .st-bubble'); const all = {}; for (const el of b.querySelectorAll('*')) { if (!el.childNodes.length || ![...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim())) continue; all[el.tagName.toLowerCase() + (el.className ? '.' + String(el.className).split(' ')[0] : '')] = parseFloat(getComputedStyle(el).fontSize); } const extra = {}; for (const [k, q] of Object.entries({ reasoning: '.st-msg--assistant .st-collapse__body', codeblock: '.st-msg--assistant .st-code pre', codehead: '.st-msg--assistant .st-code__head' })) { const e = document.querySelector(q); if (e) extra[k] = parseFloat(getComputedStyle(e).fontSize); } Object.assign(all, extra); const chain = []; for (let e = b.querySelector('p'); e && e !== b; e = e.parentElement) chain.push(e.tagName + '.' + String(e.className).split(' ')[0] + '=' + getComputedStyle(e).fontSize); all.chain = chain; globalThis.__all = all; return [parseFloat(getComputedStyle(b).fontSize), parseFloat(getComputedStyle(t).fontSize), parseFloat(getComputedStyle(u).fontSize), all]; })); } console.log('info chain', JSON.stringify(await page.evaluate(() => { const el = document.querySelector('.st-msg--assistant .st-bubble p'); const out = []; for (let e = el; e && !e.classList.contains('st-msg'); e = e.parentElement) out.push(e.tagName + '.' + String(e.className).split(' ')[0] + '=' + getComputedStyle(e).fontSize); return out; }))); + // which visible text does NOT follow the reading size? (same elements at 12 and 22) + const survey = async px => { await page.evaluate(v => { const k = 'strata.prefs.v2'; const cur = JSON.parse(localStorage.getItem(k) || '{}'); localStorage.setItem(k, JSON.stringify({ ...cur, contentFontSize: v })); }, px); await page.reload({ waitUntil: 'domcontentloaded' }); await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 30000 }); await delay(600); + return page.evaluate(() => { const out = {}; for (const el of document.querySelectorAll('main *, .chat *, textarea')) { if (![...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim()) && el.tagName !== 'TEXTAREA') continue; const r = el.getBoundingClientRect(); if (!r.width || !r.height) continue; const key = el.tagName.toLowerCase() + '.' + String(el.className).split(' ')[0] + ' <' + (el.parentElement?.className ?? '').toString().split(' ')[0] + '>'; out[key] = parseFloat(getComputedStyle(el).fontSize); } return out; }); }; + const a = await survey(12), b = await survey(22); + // a fresh app (nothing saved) uses 14 px + await page.evaluate(() => localStorage.removeItem('strata.prefs.v2')); + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 30000 }); + check(await page.evaluate(() => getComputedStyle(document.querySelector('.st-msg--assistant .st-bubble')).fontSize) === '14px', 'the default reading size is 14 px'); + const fixed = Object.keys(a).filter(k => k in b && a[k] === b[k]); + console.log('info text that does not follow the reading size:', JSON.stringify(fixed.map(k => k + '=' + a[k]))); await shot(page, '2-chat-22px'); console.log('info sizes', JSON.stringify(sizes), JSON.stringify(await page.locator('.st-msg--assistant .st-bubble').first().innerHTML()).slice(0, 400)); - check(sizes[0][1] === 12 && sizes[1][1] === 16 && sizes[2][1] === 22 && sizes[0][2] === 12 && sizes[2][2] === 22, 'the reading size changes the text size of the conversation', JSON.stringify(sizes)); + check(sizes[0][1] === 12 && sizes[1][1] === 14 && sizes[2][1] === 16 && sizes[3][1] === 22 && sizes[0][2] === 12 && sizes[3][2] === 22, 'the reading size changes the text size of the conversation', JSON.stringify(sizes)); // the slider itself await page.evaluate(() => { location.hash = '#/chat?settings=1'; }); const slider = page.getByLabel('Reading text size'); if (await slider.count()) { await slider.first().focus(); - for (let i = 0; i < 4; i++) await page.keyboard.press('ArrowLeft'); + for (let i = 0; i < 4; i++) await page.keyboard.press('ArrowRight'); await delay(500); const now = await page.evaluate(() => getComputedStyle(document.querySelector('.st-msg--assistant .st-bubble') ?? document.body).fontSize); check(parseFloat(now) === 18, 'moving the slider changes the conversation text at once', now); diff --git a/apps/desktop/src-tauri/icons/128x128.png b/apps/desktop/src-tauri/icons/128x128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POXKN7UGv;_B_M>xEqvC$aYTHCAu-;OqM z=v`M-ROoi>t!;0>^0Uv>KyMMVA{*?`V0ttNT$xj`^o_qdz30Rm9`feI> zq5dUeo)Jp6%iiA3L->OO#t~!!6n_8#4Avj?_8vYcO=;6U^FyEKC-&m&2mmpMFcau0 z`K&3daCm-VFHUgjwcH&NKpyWoydUe?+C`uS_(sO~ibog|)`iP64o$zQQxU1JJl=d4@w~$QAPN?Q54J7@A$rY|5#7@Lde+-RAF(bP=D|y5RYe_)_Nv^mEgA`_{~!>ol8-u zADRdH0Adk+AbFGQ7ewCS%WAdnd3$rfcc#P5nPuCM-d7_-1Ai_ltAD6MXX0{95(z^D zP83Bf)FZsmd6#%I*`r5$x^BwBc-r*7Gnc(%`aV23urFC&@n2Lg*CNBHD?>KteU|*L zde6l9bJ{8#d*&_B~VxA>3m zdxt26k1GH9sTeKP{lzjz^+3&v`Wx^PtZis|n!;{grnbO01I{G_lj6+k_EpXt$^df_ zwx(;RUA?~Uu3e|YWic+Wc8%kqrK)b##kkYF1=&cs<}ad&NO0tao!rR-&bV$rH*`03 zn+K?RiwbzChGRM`7W)SCFts?zyxQ7TtCjGZ@CR#gz~>|MDf~l~_!eCZ$hm}Bj%(qU xQGH+s>-MQ^pDMShc-Pc#=4xU&S6e@w{14il=kn%&?)?A&002ovPDHLkV1oLo)|mhR diff --git a/apps/desktop/src-tauri/icons/128x128@2x.png b/apps/desktop/src-tauri/icons/128x128@2x.png index 3417d3529e849b1d2412067fd837d1480c3f4430..3bea2d8ffe4ccf76b924c9efc11e67400383c2b9 100644 GIT binary patch literal 4314 zcmbtY`9IX(_rEj7T4}PUVx%3REJZTOmbG_66eAH?LTIeh2x%dCXUQ@YN>T<{XD~=q zvhV9yVq_S^m>J8=cl7xOzTeOHr`LU*bMASZdmraK&-2_Tmo1ET2}uh90Crt6*1rM( zgu8?Q0Y2{M#=ZBq0f2)``WLPSWz3I;`u0xanwQ)CE%g261P>;>fWZykU%l*SkE53a zP#@m?^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MTKX2g!^wj8xf zSRu0jEY%>nisMgaf3P`0T7QTXpb=(bmT`+(CdWebgK5)dz>N`hg<3Fv-7ek9P?$e4 z$&gOx9D^D$Cx}``>?$G{6)$v|BaDRA<`Qb$S#{#oA+>Cg*i}R@Dnj&%IY#t3!s=Y) zHl0)_78PTnOHs>^T~$<;AZ^B&MVsrg8Do?O2`3a*WGUj)F%6!@Qh#JG81P;*+IFcEM^=@6t%E0yM&Vu%rS z7P*3ZgvmpxvxkwV>n|!s*|8>1^Xuf~AC)})F#7x@#VOe<9KU diff --git a/apps/desktop/src-tauri/icons/icon.ico b/apps/desktop/src-tauri/icons/icon.ico index a052e27f4b0de2ba405fb78ae443fe6010201b86..e38a27ec33add6238f2989416e5d6cab18aaf84f 100644 GIT binary patch literal 11409 zcmbt)1yodDwD+B1=o%X7P(Y9r1PK`$X`}?CL!^=J0Z9=-=|(_0r8^`A>F$v3Zsr^P z``-7~dT;&L7qjl%d-mRE&N{n(XP+|{06+j10EGg`C*AKGkPQF;G4Ve%-ESKCB`5!f zmPNKZ!2m$_rz;&$hNSTz0KmfXk9-eFH=_ao7uP>D1F~-sIsm|6|Ij-q05E_F0EUMD z&=<(Q^|$~4hyO!EFaV&O2>A2)J)ddhys9YyAXG(31{aG03n{>TE-U#0`9w+pC=ONyzxCHF;ffc{~j%%Z9T9-X+0m<;m^>K}Aqo-2`qKR} zKCS%V^liW5DY}G}L<&i^jh3;kOWk{6jBX+$#fmgFg3mo$qSS6=EJILsRMLmru+Ks- z1`Kf@Kj42d-=*&UZ12s>g8lfsz%Cl~Thf3kjDeG<%}9G85a#;D-ADz{ek*_iPzLc9 zaO`MkAUVKuDJ98baYO(AL4Tx&0OCLThlf%lO$dzrqyK138CDw?G>Eg38vIotB*Rco zV>VgO`Gmv^nsP$zg{vp2m!daTD^ErymiW^R#7@tV{S;kPpoVI8K=0!#FBt1-%|7>2 z3D=O$Ry@BdU)d+k**%{c+wo8Xo&~5nsbFPVga*^p5OJaLY1;5U=E|>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ps/desktop/src-tauri/nsis/installer.nsi index cca93d5d..0c6fe9aa 100644 --- a/apps/desktop/src-tauri/nsis/installer.nsi +++ b/apps/desktop/src-tauri/nsis/installer.nsi @@ -165,6 +165,16 @@ VIAddVersionKey "ProductVersion" "${VERSION}" !define MUI_LANGDLL_REGISTRY_KEY "${MANUPRODUCTKEY}" !define MUI_LANGDLL_REGISTRY_VALUENAME "Installer Language" +; Strata's look and words: the app's light surface and ink, short copy, no directory page, straight on to the progress. +!define MUI_BGCOLOR "F9FAFB" +!define MUI_TEXTCOLOR "171B1E" +!define MUI_INSTFILESPAGE_PROGRESSBAR "smooth" +!define MUI_WELCOMEPAGE_TITLE "State of the art. At home." +!define MUI_WELCOMEPAGE_TEXT "Strata runs AI on your own computer.$\r$\n$\r$\nThis takes about a minute and needs no administrator. You choose your first model inside Strata." +!define MUI_FINISHPAGE_TITLE "Strata is ready." +!define MUI_FINISHPAGE_TEXT "Open it to pick your first model. Strata downloads it for you and gets it ready." +!define MUI_FINISHPAGE_RUN_TEXT "Open Strata" + ; Installer pages, must be ordered as they appear ; 1. Welcome Page !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive @@ -395,7 +405,7 @@ Function PageLeaveReinstall FunctionEnd ; 5. Choose install directory page -!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!define MUI_PAGE_CUSTOMFUNCTION_PRE Skip !insertmacro MUI_PAGE_DIRECTORY ; 6. Start menu shortcut page @@ -415,7 +425,7 @@ Var AppStartMenuFolder ; ; Don't auto jump to finish page after installation page, ; because the installation page has useful info that can be used debug any issues with the installer. -!define MUI_FINISHPAGE_NOAUTOCLOSE +; (no NOAUTOCLOSE: welcome, progress, finish) ; Use show readme button in the finish page as a button create a desktop shortcut !define MUI_FINISHPAGE_SHOWREADME !define MUI_FINISHPAGE_SHOWREADME_TEXT "$(createDesktop)" diff --git a/apps/desktop/src-tauri/nsis/sidebar.bmp b/apps/desktop/src-tauri/nsis/sidebar.bmp new file mode 100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NkV!u6>(Jc7GiZM$a3y84LTkhLM}>cfHR(^CW2)lJs_57=<})Bpeg literal 0 HcmV?d00001 diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 585c61cb..daf8c621 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -24,7 +24,8 @@ "deb" ], "icon": [ - "icons/icon.png" + "icons/icon.png", + "icons/icon.ico" ], "category": "DeveloperTool", "shortDescription": "Local AI, tuned to one model.", @@ -45,6 +46,9 @@ "nsis": { "installMode": "currentUser", "template": "nsis/installer.nsi", + "headerImage": "nsis/header.bmp", + "sidebarImage": "nsis/sidebar.bmp", + "installerIcon": "icons/icon.ico", "compression": "lzma", "languages": [ "English" diff --git a/apps/host/server/inference.mjs b/apps/host/server/inference.mjs index 1c2fbde1..c3735863 100644 --- a/apps/host/server/inference.mjs +++ b/apps/host/server/inference.mjs @@ -278,6 +278,12 @@ export async function proxyCompletion({ baseUrl, message, history = [], systemPr let streaming = true; let writing = false; let timings=null,finishReason=null; + /* The speed shown while it streams is the decode speed of everything generated, reasoning included, from the first token: tokens + (one per streamed chunk, or characters / 4 when the server batches) over the time since the first token, never the visible + answer over the whole wall time. The engine's own numbers replace it when the answer is done. */ + let chunks=0,chars=0,lastStats=0; + const liveStats=()=>{if(supervised||firstTokenAt===null)return;const now=Date.now();if(now-lastStats<400)return;const seconds=(now-firstTokenAt)/1000;if(seconds<.5)return;lastStats=now; + const tokens=chars/Math.max(1,chunks)<8?chunks:Math.ceil(chars/4);onFrame({type:'stats',tokensOut:tokens,tps:Number((tokens/seconds).toFixed(1)),source:'stream'});}; const metricsTicker = supervised ? setInterval(() => { @@ -325,12 +331,16 @@ export async function proxyCompletion({ baseUrl, message, history = [], systemPr if (delta.reasoning_content) { if (firstTokenAt === null) engine?.beginThinking(); if (firstTokenAt === null) firstTokenAt = Date.now(); + chunks++; chars+=delta.reasoning_content.length; onFrame({ type: 'reasoning', text: delta.reasoning_content }); + liveStats(); } if (delta.content) { if (!writing) { engine?.beginGenerating(); writing = true; } if (firstTokenAt === null) firstTokenAt = Date.now(); + chunks++; chars+=delta.content.length; onFrame({ type: 'delta', text: delta.content }); + liveStats(); } } if (done) break; diff --git a/apps/host/server/native-resources.mjs b/apps/host/server/native-resources.mjs index 10f9dcc6..eda84f7f 100644 --- a/apps/host/server/native-resources.mjs +++ b/apps/host/server/native-resources.mjs @@ -15,9 +15,12 @@ export function resourceSettings(config,hardware,profile,model={}){ args.push('--pool-workers',String(previous>0?Math.min(previous,workers):workers)); } // Preserve calibrated worker counts and the installation's safety/vision reserve. - const safety=Math.max(config.vision?2048:700,baseline.reserve); const placement=Array.isArray(config.gpu)?config.gpu:[config.gpu??0]; const gpuMemory=(hardware?.gpus??[]).filter(g=>placement.includes(g.index)).map(g=>g.vram_gb).filter(n=>Number.isFinite(n)&&n>0); + /* The engine warns below ~1-1.5 GiB of free VRAM (the driver then pages GPU memory to system RAM and decoding falls to a few tokens a + second, #2065), so neither profile may reserve less: 1536 MiB on a card of 16 GB or less, 1024 above; with pictures 2048. */ + const floor=gpuMemory.length&&Math.min(...gpuMemory)>16?1024:1536; + const safety=Math.max(config.vision?2048:floor,baseline.reserve); const reserve=profile==='work'&&gpuMemory.length?Math.max(safety,Math.floor(Math.min(...gpuMemory)*1024*.2)):safety; remove('--vram-reserve-mib');args.push('--vram-reserve-mib',String(reserve)); // RAM: "leave 20% for my work" keeps the model's RAM within 80% of the PC. A model whose experts do not fit there (the diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index f635d82b..e728b927 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -32,6 +32,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine expertSection.current?.scrollIntoView({ block: 'start', behavior: 'smooth' }); }, [expert]); const selectedFamily = families.find(f => f.family === family || f.sizes.some(size => size.sourceFamily === family)) ?? families[0], selectedSize = selectedFamily?.sizes.find(s => s.id === size) ?? selectedFamily?.sizes[0]; const installed = native?.installed?.models.find(m => m.model === selectedSize?.id); + // The model that is running is shown as running, with Unload: not offered for loading again. + 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) @@ -101,7 +103,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(active ? : null)} {tr(job?.state === 'error' ? void load()}/> : null)} {tr(error ? : null)} -

{tr(onReady && native?.instances.some(i => i.status === 'ready') ? {tr("Start chatting")} : <> i.status === 'ready') || !!active} onClick={() => setBenchmark(true)}>{tr("Tune model")} void load()}>{tr(pending ? 'Checking…' : installed?.ready ? 'Load model' : 'Download & load')})}
+
{tr(loadedSelected ? <> setBenchmark(true)}>{tr("Tune model")} void perform(() => nativeAction(`instances/${loadedSelected.id}/unload`))}>{tr("Unload")}{tr(onReady ? {tr("Start chatting")} : {tr("Ready")})} : onReady && native?.instances.some(i => i.status === 'ready') ? {tr("Start chatting")} : <> i.status === 'ready') || !!active} onClick={() => setBenchmark(true)}>{tr("Tune model")} void load()}>{tr(pending ? 'Checking…' : installed?.ready ? 'Load model' : 'Download & load')})}
diff --git a/apps/host/src/components/TelemetryPopover.tsx b/apps/host/src/components/TelemetryPopover.tsx index 15522f8a..f44e1ccf 100644 --- a/apps/host/src/components/TelemetryPopover.tsx +++ b/apps/host/src/components/TelemetryPopover.tsx @@ -6,6 +6,7 @@ import { ContextRing } from './ContextRing'; import { Popover } from './Popover'; import { chatMetrics, compactTokens, elapsed } from '../lib/chat-metrics'; import { useStore } from '../lib/store'; +import { useNative } from '../lib/native'; import type { Session } from '../lib/types'; function Chip({ icon, visual, label, title, children }: { icon?: IconName; @@ -46,7 +47,11 @@ export function ChatTelemetry({ session }: { }) { const monitor = useStore(s => s.monitor); const engine = useStore(s => s.engine); - const m = chatMetrics(session, monitor, engine ? contextTokens(engine.beginner.contextLength) : undefined); + // The context shown is the one the loaded model runs with (the engine's own --max-context), not a catalog or settings default. + const native = useNative(); + const running = native?.instances.find(i => i.id === native.defaultId && i.status === 'ready') ?? native?.instances.find(i => i.status === 'ready'); + const runningContext = running ? Number(running.metrics?.engine?.max_context) || running.context || undefined : undefined; + const m = chatMetrics(session, monitor, runningContext ?? (engine ? contextTokens(engine.beginner.contextLength) : undefined)); const speed = useCalmSpeed(m.speed, session?.id ?? null, m.streaming); if (!m.hasReplies) return null; diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts index 18703366..f2ae0307 100644 --- a/apps/host/src/lib/store.ts +++ b/apps/host/src/lib/store.ts @@ -141,7 +141,7 @@ const PREFS_DEFAULTS: Prefs = { contrast: 'standard', rail: false, focus: false, - contentFontSize: 16, + contentFontSize: 14, density: 'comfortable', motion: 'system', transparency: 'translucent', @@ -188,7 +188,7 @@ function loadPrefs(): Prefs { ...parsed, language: validLanguage(parsed.language) ? parsed.language : 'en', fontFamily: typeof parsed.fontFamily === 'string' ? parsed.fontFamily.slice(0,128).replace(/[\x00-\x1f]/g,'') : '', - contentFontSize: Math.min(CONTENT_FS_MAX, Math.max(CONTENT_FS_MIN, Number(parsed.contentFontSize) || 16)), + contentFontSize: Math.min(CONTENT_FS_MAX, Math.max(CONTENT_FS_MIN, Number(parsed.contentFontSize) || 14)), }; } catch { /* fall through to the next key */ @@ -1353,7 +1353,7 @@ export async function sendMessage(text: string) { } else if (type === 'agent') { patchSession(sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], frame.agent) })); } else if (type === 'delta') { - patchAssistant((m) => { const content=m.content+String(frame.text??''); const count=Math.max(1,Math.ceil(content.length/4)); const seconds=Math.max(.1,(performance.now()-started)/1000); return {...m,content,tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),tps:count/seconds,usageSource:'estimated'}; }); + patchAssistant((m) => { const content=m.content+String(frame.text??''); const count=Math.max(1,Math.ceil((content.length+(m.reasoning?.length??0))/4)); return {...m,content,tokens:m.usageSource==='estimated'&&m.tps?m.tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),usageSource:'estimated'}; }); } else if (type === 'artifacts' && Array.isArray(frame.artifacts)) { patchAssistant(m => ({ ...m, artifacts: frame.artifacts as PreviewArtifact[] })); } else if(type==='native-tool'){ diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index b37f74af..0c7c1f2b 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -452,11 +452,11 @@ the text size — a fixed px allowance drifts at the extremes. */ .app[data-focus='true'] .slashmenu, .app[data-focus='true'] .chat__inner { - font-size: var(--st-content-fs, 16px); + font-size: var(--st-content-fs, 14px); max-width: calc(var(--st-measure) + 2.5em); } .app[data-focus='true'] .composer__inner { - font-size: var(--st-content-fs, 16px); + font-size: var(--st-content-fs, 14px); /* the same column, less the transcript's 28px padding on each side */ max-width: calc(var(--st-measure) + 2.5em - 56px); } @@ -474,8 +474,8 @@ — the same scoping DSH uses for its 10–22px content setting. */ .st-msg--assistant .st-bubble, .st-msg--user .st-bubble { - font-size: var(--st-content-fs, 16px); - line-height: calc(var(--st-content-fs, 16px) * 1.62); + font-size: var(--st-content-fs, 14px); + line-height: calc(var(--st-content-fs, 14px) * 1.62); } /* Density — the difference between scanning data and reading it. */ @@ -6998,10 +6998,13 @@ textarea { model's reasoning keep their usual proportion (18px, 13px, 13px at the 16px default) at any size. */ .st-bubble h2, .st-bubble h3, .st-bubble h4 { font-size: 1.125em; } .st-bubble .md-code { font-size: .8125em; } -.st-bubble .md-table { font-size: calc(var(--st-content-fs, 16px) * .8125); } +.st-bubble .md-table { font-size: calc(var(--st-content-fs, 14px) * .8125); } .st-bubble .md-table th, .st-bubble .md-table td { font-size: inherit; } -.st-bubble .st-code pre, .st-bubble .st-code pre code, .st-bubble .st-code .syntax-text { font-size: calc(var(--st-content-fs, 16px) * .8125); } -.st-msg--assistant .st-collapse__body { font-size: calc(var(--st-content-fs, 16px) * .8125); } +.st-bubble .st-code pre, .st-bubble .st-code pre code, .st-bubble .st-code .syntax-text { font-size: calc(var(--st-content-fs, 14px) * .8125); } +.st-msg--assistant .st-collapse__body { font-size: calc(var(--st-content-fs, 14px) * .8125); } .error-notice .error-detail { margin-top: 6px; } .error-notice .error-detail pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: 6px 0 0; font-family: var(--st-font-mono); } .error-detail-text { white-space: pre-wrap; overflow-wrap: anywhere; margin: 6px 0 0; font-family: var(--st-font-mono); } +/* What you type and the small print under each message follow the reading size too, so the whole conversation changes together. */ +.st-composer textarea { font-size: var(--st-content-fs, 14px); } +.st-msg__meta, .st-msg__meta time { font-size: calc(var(--st-content-fs, 14px) * .8125); } diff --git a/apps/host/tests/agent-host.test.mjs b/apps/host/tests/agent-host.test.mjs index 7335f89f..1fabf699 100644 --- a/apps/host/tests/agent-host.test.mjs +++ b/apps/host/tests/agent-host.test.mjs @@ -26,7 +26,7 @@ const sleep = ms => new Promise(r => setTimeout(r, ms)); async function startHost(t, { home, ws, harness = HARNESS } = {}) { const port = await freePort(); - const env = { ...process.env, STRATA_HOME: home, STRATA_PORT: String(port), STRATA_WORKSPACE: ws, STRATA_REAL_ENGINE: '0' }; + const env = { ...process.env, STRATA_HOME: home, STRATA_PORT: String(port), STRATA_WORKSPACE: ws, STRATA_REAL_ENGINE: '0', STRATA_COMPONENTS_DIR: join(home, 'components') }; if (harness) env.STRATA_HARNESS_DIR = harness; else delete env.STRATA_HARNESS_DIR; const child = spawn(process.execPath, [HOST], { env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true }); let log = ''; diff --git a/apps/host/tests/resource-ram.test.mjs b/apps/host/tests/resource-ram.test.mjs index bac52b5d..3965ea47 100644 --- a/apps/host/tests/resource-ram.test.mjs +++ b/apps/host/tests/resource-ram.test.mjs @@ -29,3 +29,17 @@ test('a model that fits, or one that already has a RAM mode, is left alone', () assert.equal(resourceSettings(own, pc64, 'work', iq3s).args.includes('--resident-budget-gib'), false); assert.equal(resourceSettings(config, pc64, 'work').args.includes('--resident-budget-gib'), false, 'no model size, no change'); }); + +test('neither profile reserves less VRAM than the engine\'s safe floor (the driver pages GPU memory below it and decoding collapses)', () => { + const card12 = { cpu: { cores: 12 }, ram_gb: 63, gpus: [{ index: 0, vram_gb: 11.9 }] }; + const card24 = { cpu: { cores: 12 }, ram_gb: 63, gpus: [{ index: 0, vram_gb: 24 }] }; + for (const profile of ['work', 'performance']) { + const lowConfig = { gpu: 0, args: ['--max-context', '32768', '--vram-reserve-mib', '700'] }; + assert.ok(resourceSettings(lowConfig, card12, profile).vram_reserve_mib >= 1536, `${profile} on 12 GB`); + assert.ok(resourceSettings({ gpu: 0, args: [] }, card12, profile).vram_reserve_mib >= 1536, `${profile}, nothing configured`); + assert.ok(resourceSettings(lowConfig, card24, profile).vram_reserve_mib >= 1024, `${profile} on 24 GB`); + } + assert.equal(resourceSettings({ gpu: 0, args: [] }, card12, 'performance').vram_reserve_mib, 1536); + assert.equal(resourceSettings({ gpu: 0, args: [] }, card24, 'performance').vram_reserve_mib, 1024); + assert.equal(resourceSettings({ gpu: 0, args: [], vram_reserve_mib: 2437 }, card12, 'performance').vram_reserve_mib, 2437, 'a larger reserve of the installation is kept'); +}); diff --git a/apps/host/tests/stream-speed.test.mjs b/apps/host/tests/stream-speed.test.mjs new file mode 100644 index 00000000..309fedc7 --- /dev/null +++ b/apps/host/tests/stream-speed.test.mjs @@ -0,0 +1,40 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { proxyCompletion } from '../server/inference.mjs'; + +/* The speed shown while an answer streams must be the decode speed of everything generated, reasoning included, from the first + token (the owner saw 4-5 tok/s in chat while the engine log said 48-57): the stand-in engine streams 90 reasoning tokens at about + 40 a second, a 4 s "prompt" before the first one, then a short answer. */ +function engine({ promptMs, reasoning, answer, perSecond }) { + return createServer((req, res) => { + res.writeHead(200, { 'content-type': 'text/event-stream' }); + const send = obj => res.write(`data: ${JSON.stringify(obj)}\n\n`); + let sent = 0; + setTimeout(function tick() { + if (sent < reasoning + answer) { + send({ choices: [{ delta: sent < reasoning ? { reasoning_content: 'tok ' } : { content: 'ans ' } }] }); + sent++; + return setTimeout(tick, 1000 / perSecond); + } + send({ choices: [], usage: { prompt_tokens: 20, completion_tokens: reasoning + answer } }); + res.write('data: [DONE]\n\n'); res.end(); + }, promptMs); + }); +} + +test('live speed counts reasoning tokens over decode time, not the answer over the whole wait', async () => { + const server = engine({ promptMs: 4000, reasoning: 90, answer: 10, perSecond: 40 }); + await new Promise(r => server.listen(0, '127.0.0.1', r)); + const frames = []; + try { + const result = await proxyCompletion({ baseUrl: `http://127.0.0.1:${server.address().port}/v1`, message: 'hi', onFrame: f => frames.push(f), engine: { beginReading() {}, beginThinking() {}, beginGenerating() {} } }); + const stats = frames.filter(f => f.type === 'stats'); + assert.ok(stats.length >= 2, 'live frames while it streams'); + const last = stats.at(-1); + assert.ok(last.tps > 22 && last.tps < 80, `live tok/s ${last.tps} is the decode rate, not tokens over the wait including the prompt (~14)`); + assert.ok(last.tokensOut >= 50, 'reasoning tokens are counted'); + assert.equal(result.tokensOut, 100); + assert.ok(result.tps > 22 && result.tps < 80, `final tok/s ${result.tps}`); + } finally { server.close(); } +}); From 1696b5c959acb4ee8b9f52e7ddc421ffbd34333a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 20:29:43 +0200 Subject: [PATCH 12/16] installer: header text, branding line, no details pane --- apps/desktop/src-tauri/nsis/installer.nsi | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/apps/desktop/src-tauri/nsis/installer.nsi b/apps/desktop/src-tauri/nsis/installer.nsi index 0c6fe9aa..375d5238 100644 --- a/apps/desktop/src-tauri/nsis/installer.nsi +++ b/apps/desktop/src-tauri/nsis/installer.nsi @@ -174,6 +174,10 @@ VIAddVersionKey "ProductVersion" "${VERSION}" !define MUI_FINISHPAGE_TITLE "Strata is ready." !define MUI_FINISHPAGE_TEXT "Open it to pick your first model. Strata downloads it for you and gets it ready." !define MUI_FINISHPAGE_RUN_TEXT "Open Strata" +!define MUI_PAGE_HEADER_TEXT "Installing Strata" +!define MUI_PAGE_HEADER_SUBTEXT "Copying the app. You can keep working meanwhile." +BrandingText "Strata" +ShowInstDetails nevershow ; Installer pages, must be ordered as they appear ; 1. Welcome Page From ffbc606682368e450a45021aef316f2c34f865f4 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 21:48:51 +0200 Subject: [PATCH 13/16] delete a downloaded native model: strata_remove (own files and run config, shared files kept), Delete in Models and Storage, real disk use per model --- apps/desktop/scripts/ui-flows.mjs | 36 +++++- apps/host/server/native-control.mjs | 16 ++- apps/host/src/components/NativeDelete.tsx | 43 ++++++++ apps/host/src/components/NativeModels.tsx | 5 +- apps/host/src/components/SettingsStorage.tsx | 6 + apps/host/src/lib/native.ts | 2 +- apps/host/tests/packaged-control.test.mjs | 23 +++- tests/desktop/test_control_install.py | 78 +++++++++++++ tools/strata_mcp.py | 110 +++++++++++++++++++ tools/test_strata_mcp.py | 4 +- 10 files changed, 312 insertions(+), 11 deletions(-) create mode 100644 apps/host/src/components/NativeDelete.tsx diff --git a/apps/desktop/scripts/ui-flows.mjs b/apps/desktop/scripts/ui-flows.mjs index 69e261a8..0edb6534 100644 --- a/apps/desktop/scripts/ui-flows.mjs +++ b/apps/desktop/scripts/ui-flows.mjs @@ -30,7 +30,7 @@ const nodeExe = resolve(args.node ?? join(staged, 'node', process.platform === ' const work = mkdtempSync(join(tmpdir(), 'strata-ui-flows-')); const shots = resolve(args.shots ?? join(work, 'shots')); mkdirSync(shots, { recursive: true }); -const only = new Set(String(args.only ?? 'download,models,tune,fail,theme,restart').split(',')); +const only = new Set(String(args.only ?? 'download,models,tune,fail,delete,theme,restart').split(',')); const isWin = process.platform === 'win32'; const { chromium } = await import(pathToFileURL(join(repoHost, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); @@ -51,6 +51,7 @@ const python = isWin ? join(control, 'python', 'python.exe') : join(control, 'py const FAKE_INSTALLER = String.raw` import json, os, sys, time from pathlib import Path +ROOT = Path(sys.argv[sys.argv.index('--root') + 1]) if '--root' in sys.argv else Path('.') STATE = Path(os.environ['FAKE_STATE']); STATE.mkdir(parents=True, exist_ok=True) RATE = float(os.environ.get('FAKE_RATE_GB_S', '0.5')) def size(model, gb, ram, mid): @@ -71,7 +72,11 @@ def job(): 'download': {'file': 'model files', 'done_gb': round(done, 3), 'total_gb': TOTAL, 'remaining_gb': round(TOTAL - done, 3), 'percent': int(100 * done / TOTAL)}} def call(name, a): if name == 'strata_models': return CATALOG - if name == 'strata_status': return {'summary': 'fake', 'hardware': HARDWARE, 'recommendation': CATALOG['recommendation'], 'install': job(), 'running': []} + if name == 'strata_remove': + cfg = ROOT / ('strata-%s.json' % a['model']) + if a.get('confirm') and cfg.exists(): cfg.unlink() + return {'summary': 'Deleted', 'plan': {'gb': 83.6}, 'failed': []} + if name == 'strata_status': return {'summary': 'fake', 'installed': {'models': [{'model': 'iq3_s', 'disk_gb': 83.6, 'disk_bytes': 83600000000}]}, 'hardware': HARDWARE, 'recommendation': CATALOG['recommendation'], 'install': job(), 'running': []} if name == 'strata_install': if a.get('cancel'): f = STATE / 'job.json' @@ -90,7 +95,7 @@ for line in sys.stdin: if 'id' not in m: continue method = m.get('method') if method == 'initialize': res = {'protocolVersion': '2024-11-05'} - elif method == 'tools/list': res = {'tools': [{'name': n} for n in ('strata_models', 'strata_status', 'strata_install')]} + elif method == 'tools/list': res = {'tools': [{'name': n} for n in ('strata_models', 'strata_status', 'strata_install', 'strata_remove')]} else: p = m['params'] res = {'structuredContent': call(p['name'], p.get('arguments') or {})} @@ -344,6 +349,31 @@ await scenario('tune', { installed: true, env: { FAKE_TOKEN_DELAY: '0.02', FAKE_ check(page.problems.length === 0, 'no page error', page.problems.join('; ')); }); +// ------------------------------------------------------------------------------------------------ delete +await scenario('delete', { installed: true }, async ({ base, api, browser, dirs, shot }) => { + const page = await newPage(browser, base); + await clickText(page, /Go straight to the app/i); + await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {}); + await page.getByRole('button', { name: /^Load model$/ }).first().click(); + let ready = false; + for (let i = 0; i < 90 && !ready; i++) { ready = (await api('/api/native')).body.instances.some(x => x.status === 'ready'); await delay(1000); } + check(ready, 'a model is loaded'); + await clickText(page, /Manage models/i); + await page.getByRole('button', { name: /^Delete$/ }).first().click(); + await delay(600); + await shot(page, '1-delete-confirm'); + const dialog = await page.getByRole('dialog').last().innerText(); + check(/Delete this version\?/.test(dialog) && /Remove 83\.6 GB of downloaded files\. You can download this version again\./.test(dialog), 'the confirm dialog uses the existing words and the real size', dialog.replace(/\s+/g, ' ').slice(0, 200)); + check(/running model will be unloaded/i.test(dialog), 'and says the loaded model is unloaded first'); + await page.getByRole('button', { name: /^Delete version$/ }).click(); + let state = null; + for (let i = 0; i < 40; i++) { state = (await api('/api/native')).body; if (state.instances.length === 0 && !state.installed?.models?.some(m => m.model === 'iq3_s')) break; await delay(500); } + check(state.instances.length === 0, 'the loaded model was unloaded'); + check(!existsSync(join(dirs.install, 'strata-iq3_s.json')), 'the installer removed the run config of the model'); + check(!state.installed?.models?.some(m => m.model === 'iq3_s'), 'the model is no longer listed as downloaded'); + await shot(page, '2-after-delete'); +}); + // ------------------------------------------------------------------------------------------------ fail await scenario('fail', { installed: true, env: { FAKE_ENGINE_FAIL: '1' } }, async ({ base, api, browser, shot }) => { const page = await newPage(browser, base); diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index e4511e7d..02e0bf1f 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -55,7 +55,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},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,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} + function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,diskGb:entry.diskGb??entry.disk_gb,diskBytes:entry.diskBytes??entry.disk_bytes,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} function installRoot(){const found=[preferences.installDir,packagedInstall,snapshot.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());} function repo(){if(packaged)return installRoot();const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;} function python(){return resolvePython({repo:preferences.repo});} @@ -84,7 +84,8 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp packagedInstall=list.install_dir; const engine=await control.engine(); const installer=await mcpCall('strata_status',{hardware:true}).catch(error=>({error:error.message})); - const models=(list.models??[]).filter(m=>m.component_status!=='invalid'&&m.source_config).map(m=>({model:m.id,config:basename(m.source_config),configPath:m.source_config,model_name:m.name,context:m.context_tokens??0,backend:m.backend,ready:m.component_status==='present',images:'off',port:undefined,last_used:null})); + const disk=Object.fromEntries((installer.installed?.models??[]).map(m=>[m.model,{diskGb:m.disk_gb,diskBytes:m.disk_bytes}])); + const models=(list.models??[]).filter(m=>m.component_status!=='invalid'&&m.source_config).map(m=>({...(disk[m.id]??{}),model:m.id,config:basename(m.source_config),configPath:m.source_config,model_name:m.name,context:m.context_tokens??0,backend:m.backend,ready:m.component_status==='present',images:'off',port:undefined,last_used:null})); const cores=os.cpus().length; return {summary:engine.usable?`Strata Control is ready; engine ${engine.engine.version} (${engine.engine.platform}-${engine.engine.backend}).`:(engine.notice??'No engine for this PC was found.'), installDir:list.install_dir,engine:{usable:engine.usable,notice:engine.notice,version:engine.engine?.version??null,backend:engine.backend,componentsDir:engine.components_dir}, @@ -117,6 +118,15 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp function terminate(proc,signal='SIGTERM'){if(!proc)return;if(process.platform!=='win32'&&proc.pid){try{process.kill(-proc.pid,signal);return;}catch{}}proc.kill(signal);} async function stopProcess(proc){if(!proc||proc.exitCode!=null)return;await new Promise(resolve=>{const timeout=setTimeout(()=>{terminate(proc,'SIGKILL');resolve();},8000);proc.once('exit',()=>{clearTimeout(timeout);resolve();});terminate(proc);});} async function unload(id,force=false){const instance=instances.get(id);if(!instance)throw new Error('This model is no longer loaded.');if(!force&&[...jobs.values()].some(j=>j.kind==='benchmark'&&j.state==='running'&&j.instanceId===id))throw new Error('Stop the benchmark before unloading this model.');if(!force&&busy(requests().filter(r=>r.instanceId===id)))throw new Error('Finish or cancel this model’s requests first.');instance.status='unloading';if(instance.profile){try{await control.stop(instance.profile);}catch(error){if(!force){instance.status='error';instance.error=error.message;emit();throw error;}}}else await stopProcess(processes.get(id));processes.delete(id);instances.delete(id);try{unlinkSync(instance.configPath);}catch{}if(defaultId===id)defaultId=instances.keys().next().value??null;emit();return state();} + /* Delete a downloaded model: stop it first, then the installer removes the model's own files and its run config and keeps + whatever another installed model still uses (shared MTP draft, shared PLE shard). */ + async function removeModel(job,args){if(!safeId(args.model))throw new Error('Choose an installed model.'); + if(externalRunning().length)throw new Error('Stop the native server running outside this UI before deleting a model.'); + for(const instance of [...instances.values()].filter(i=>i.model===args.model)){if(busy(requests().filter(r=>r.instanceId===instance.id)))throw new Error('Finish or cancel requests before deleting this model.');await unload(instance.id);} + job.summary='Deleting downloaded files…';emit(); + const result=await tool('strata_remove',{model:args.model,confirm:true}); + if(result.failed?.length)throw new Error(`Some files could not be removed: ${result.failed.slice(0,3).join('; ')}`); + await refresh(true);return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} async function loadEngine(job,args){ await refresh(true);if(job.state!=='running')return;const {config,entry}=record(args.model);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');}if(!entry.ready)throw new Error('Some model files are missing. Use Download / repair to restore them.'); if(externalRunning().length)throw new Error('A Strata server is already running outside this UI. Stop it before loading here, or connect its API in Settings → Models.'); @@ -201,7 +211,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp const measured=await benchmark(job,{instanceId:loaded.instanceId}); return {...loaded,...measured,summary:'Your model is tuned and ready.',profile:args.profile}; } - function operation(kind,args={}){if(!['install','load','benchmark','tune','calibrate','update-engine','update-strata','rollback'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):program(job,args),{guided:args.guided===true,model:args.model});} + function operation(kind,args={}){if(!['install','load','benchmark','tune','calibrate','update-engine','update-strata','rollback','remove'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):kind==='remove'?removeModel(job,args):program(job,args),{guided:args.guided===true,model:args.model});} async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install')await tool('strata_install',{cancel:true});else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} async function close(){closing=true;clearInterval(timer);const installing=packaged&&child&&[...jobs.values()].some(j=>j.kind==='install'&&j.state==='running');if(installing)await send('tools/call',{name:'strata_install',arguments:{cancel:true}},15000).catch(()=>{});const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();} // Remove nonserializable process references from public jobs. diff --git a/apps/host/src/components/NativeDelete.tsx b/apps/host/src/components/NativeDelete.tsx new file mode 100644 index 00000000..07e9ba62 --- /dev/null +++ b/apps/host/src/components/NativeDelete.tsx @@ -0,0 +1,43 @@ +import { tr } from '../lib/i18n'; +import { useState } from 'react'; +import { Btn, Dialog, ErrorNotice } from './ui'; +import { nativeAction, nativeState, refreshNative, useNative, type NativeJob } from '../lib/native'; +import { catalogVersionLabel, nativeCatalogModels } from '../lib/native-catalog'; +import { sizeGb } from '../lib/format'; + +/** Delete a downloaded (native) model: its own files and run config. What another installed model still uses stays. A loaded model + * is unloaded first by the host. Same dialog and words as deleting a version of the managed library. */ +export function NativeDeleteDialog({ id, onClose }: { id: string | null; onClose: () => void }) { + const native = useNative(); + const [pending, setPending] = useState(false), [error, setError] = useState(''); + const entry = native?.installed?.models.find(m => m.model === id); + const label = (() => { const sizes = nativeCatalogModels(native?.catalog?.families ?? []).flatMap(f => f.sizes); const v = sizes.find(s => s.id === id); return v ? `${catalogVersionLabel(v)} · ${v.model}` : entry?.model_name ?? id ?? ''; })(); + const running = !!native?.instances.some(i => i.model === id); + const busy = !!native?.jobs.some(j => j.state === 'running'); + const gb = entry?.diskGb ?? 0; + function close() { if (!pending) { onClose(); setError(''); } } + async function remove() { + setPending(true); + setError(''); + try { + const job = await nativeAction('operations', { kind: 'remove', args: { model: id } }); + for (let i = 0; i < 600; i++) { + await new Promise(r => setTimeout(r, 500)); + await refreshNative(true).catch(() => undefined); + const current = nativeState()?.jobs.find(j => j.id === job.id); + if (current && current.state !== 'running') { + if (current.state === 'error') throw new Error(current.error ?? 'Could not delete this version.'); + break; + } + } + onClose(); + } + catch (e) { setError(e instanceof Error ? e.message : String(e)); } + finally { setPending(false); } + } + return {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(error ? : null)} +
; +} diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index e728b927..a251f073 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -3,6 +3,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { Screen } from './layout'; import { Btn, Dialog, ErrorNotice, Icon, Select } from './ui'; import { installProgress, useDownloadEta } from '../lib/download-eta'; +import { NativeDeleteDialog } from './NativeDelete'; import { plainFailureText } from '../lib/plain-errors'; import { api } from '../lib/client'; import { go, setSettingsSection, selectRemoteModel, pushToast } from '../lib/store'; @@ -26,6 +27,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const [resourceProfile, setResourceProfile] = useState<'work' | 'performance'>('work'); const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState | null>(null), [benchmark, setBenchmark] = useState(false), [jobId, setJobId] = useState(''), [manage, setManage] = useState(false); const presetPending = useRef(false); + const [deleting, setDeleting] = useState(null); const families = nativeCatalogModels(native?.catalog?.families ?? []); const expertSection = useRef(null); useEffect(() => { if (expert) @@ -108,7 +110,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
!pending && setPlan(null)} actions={<> setPlan(null)}>{tr("Cancel")} void download()}>{tr("Download & load")}}>

{tr(plan?.plan?.title ?? selectedFamily?.title)}{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")}

{tr(plan?.plan?.disk_short ? : null)}

{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}

{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}

{tr(selectedSize?.images ?

{tr("Vision encoder files are included. Picture reading loads only when enabled.")}

: null)}
- setManage(false)} actions={ setManage(false)}>{tr("Done")}}>

{tr(selectedFamily?.title)}

{tr(selectedFamily?.sizes.map(v => ))}
{tr("Version")}{tr("Download")}{tr("Status")}
{tr(catalogVersionLabel(v))}{tr(v.model)} · {tr(v.about)}{tr(v.download_gb.toFixed(1))}{tr(" GB")}{tr(native?.instances.some(i => i.model === v.id) ? 'Loaded' : v.installed ? 'Downloaded' : 'Available')} { setSize(v.id); setManage(false); }}>{tr(selectedSize?.id === v.id ? 'Selected' : 'Use version')}
{ setManage(false); (onImport ?? onOtherModels)(); }}>{tr("Use a local GGUF\u2026")}

{tr("Choose a version, then load it from Models. Shared native files are kept together in Storage.")}

+ setDeleting(null)}/> + setManage(false)} actions={ setManage(false)}>{tr("Done")}}>

{tr(selectedFamily?.title)}

{tr(selectedFamily?.sizes.map(v => ))}
{tr("Version")}{tr("Download")}{tr("Status")}
{tr(catalogVersionLabel(v))}{tr(v.model)} · {tr(v.about)}{tr(v.download_gb.toFixed(1))}{tr(" GB")}{tr(native?.instances.some(i => i.model === v.id) ? 'Loaded' : v.installed ? 'Downloaded' : 'Available')} { setSize(v.id); setManage(false); }}>{tr(selectedSize?.id === v.id ? 'Selected' : 'Use version')}{tr(native?.installed?.models.some(m => m.model === v.id) ? <> setDeleting(v.id)}>{tr("Delete")} : null)}
{ setManage(false); (onImport ?? onOtherModels)(); }}>{tr("Use a local GGUF\u2026")}

{tr("Choose a version, then load it from Models. Shared native files are kept together in Storage.")}

setBenchmark(false)}/> ; } diff --git a/apps/host/src/components/SettingsStorage.tsx b/apps/host/src/components/SettingsStorage.tsx index 439eb489..a78520bf 100644 --- a/apps/host/src/components/SettingsStorage.tsx +++ b/apps/host/src/components/SettingsStorage.tsx @@ -5,10 +5,12 @@ import { changeModelDirectory, getState, lifecycleStatus, removeVariant, runtime import { pickerGroups, pickerVersionState } from '../lib/model-picker'; import { sizeGb } from '../lib/format'; import { useNative } from '../lib/native'; +import { NativeDeleteDialog } from './NativeDelete'; export function SettingsStorage() { const state = useStore(s => s); const native = useNative(); const [selected, setSelected] = useState(null); + const [nativeDeleting, setNativeDeleting] = useState(null); const [pending, setPending] = useState(false), [error, setError] = useState(''); const [editing, setEditing] = useState(false), [directory, setDirectory] = useState(''); const [directoryPending, setDirectoryPending] = useState(false), [directoryError, setDirectoryError] = useState(''), [notice, setNotice] = useState(''); @@ -95,6 +97,10 @@ export function SettingsStorage() { ...versions.map(v => ({ value: v.id, label: `${v.local ? v.name : v.family} · ${v.quant} · ${sizeGb(v.diskGb)}${v.local ? ' · Local' : ''}`, disabled: pickerVersionState(v, library?.loaded ?? null).busy })), ]} onChange={id => { setError(''); setSelected(id); }}/> + {tr(native?.installed?.models.length ? n + (m.diskGb ?? 0), 0))])}> +
{tr(native.installed.models.map(m =>
{tr(m.model_name || m.model)} {tr(m.model)} · {tr(sizeGb(m.diskGb ?? 0))}{tr(native.instances.some(i => i.model === m.model) ? <> · {tr('Loaded')} : null)} 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.')}

{tr(version ?

{tr(version.local ? `${running ? 'The model will be unloaded and removed from Strata.' : 'The model will be removed from Strata.'} Your original GGUF files stay in their folder.` : `${running ? 'The running model will be unloaded and its files deleted.' : 'Its files will be deleted from this computer.'} You can download it again in Models.`)}

: null)} diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.ts index fbdd66e2..58da20c1 100644 --- a/apps/host/src/lib/native.ts +++ b/apps/host/src/lib/native.ts @@ -6,7 +6,7 @@ export interface NativeFamily {family:string;title:string;about:string;experimen 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} export interface NativeInstance {id:string;apiModelId:string;model:string;label:string;aliases?:string[];vision?:boolean;context?:number;port:number;gpus:number[];status:'loading'|'ready'|'unloading'|'error';phase:string;loadedAt:string;error:string|null;metrics:Record|null} -export interface NativeState {available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;missing_files?:string[]}[];data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;gpus:{index:number;name:string;vram_gb:number;usable:boolean}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean}} +export interface NativeState {available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;diskGb?:number;diskBytes?:number;missing_files?:string[]}[];data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;gpus:{index:number;name:string;vram_gb:number;usable:boolean}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean}} let state:NativeState|null=null,timer:ReturnType|null=null,reading:Promise|null=null; const listeners=new Set<()=>void>(); export function refreshNative(force=false){if(reading)return reading;reading=api.get(`/api/native${force?'?refresh=1':''}`).then(value=>{state=value;listeners.forEach(fn=>fn());}).catch(error=>{if(state){state={...state,error:error.message,instances:state.instances.map(i=>({...i,metrics:null,phase:'unavailable'}))};listeners.forEach(fn=>fn());}}).finally(()=>{reading=null;});return reading;} diff --git a/apps/host/tests/packaged-control.test.mjs b/apps/host/tests/packaged-control.test.mjs index 6e701882..f4dd41b6 100644 --- a/apps/host/tests/packaged-control.test.mjs +++ b/apps/host/tests/packaged-control.test.mjs @@ -131,8 +131,9 @@ function packagedFixture({ engineUsable = true } = {}) { if (message.method === 'tools/call') rpc.push(message.params); let result; if (message.method === 'initialize') result = { protocolVersion: '2024-11-05' }; - else if (message.method === 'tools/list') result = { tools: ['strata_models', 'strata_status', 'strata_install'].map(name => ({ name })) }; + else if (message.method === 'tools/list') result = { tools: ['strata_models', 'strata_status', 'strata_install', 'strata_remove'].map(name => ({ name })) }; else if (message.params.name === 'strata_models') result = { structuredContent: catalog }; + else if (message.params.name === 'strata_remove') result = { structuredContent: { summary: 'Deleted', plan: { gb: 1.2 }, failed: [] } }; else if (message.params.name === 'strata_status') result = { structuredContent: { hardware, recommendation: catalog.recommendation, install: installJob, running: [], summary: 'x' } }; else if (message.params.arguments?.confirm) { installJob = { running: false, exit_code: 0 }; result = { structuredContent: { summary: 'Install started', plan: { download_gb: 66.4 }, install: { running: true, step: 'downloading' } } }; } else if (message.params.arguments?.cancel === undefined && message.params.arguments?.confirm === undefined) result = { structuredContent: { summary: 'Install finished', install: { running: false, exit_code: 0 } } }; @@ -328,3 +329,23 @@ test('packaged: a run config that points into an old Control folder is repaired assert.equal(readFileSync(path, 'utf8'), before); } finally { await f.native.close(); f.cleanup(); } }); + +test('packaged: deleting a downloaded model unloads it first, then the installer removes its files', async () => { + const f = packagedFixture(); + try { + await f.native.refresh(true); + const load = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id); + assert.equal(load.state, 'done', load.error); + assert.equal(f.native.state().instances.length, 1); + const job = await finish(f.native, f.native.operation('remove', { model: 'iq2_xs' }).id); + assert.equal(job.state, 'done', job.error); + assert.equal(f.native.state().instances.length, 0, 'the loaded model was unloaded first'); + assert.deepEqual(f.calls.filter(c => c[0] === 'stop').at(-1), ['stop', 'app-1']); + const removed = f.rpc.filter(c => c.name === 'strata_remove'); + assert.equal(removed.length, 1); + assert.deepEqual(removed[0].arguments, { model: 'iq2_xs', confirm: true }); + assert.equal(f.others().length, 0); + const bad = await finish(f.native, f.native.operation('remove', { model: '../x' }).id); + assert.equal(bad.state, 'error', 'an id that is not an installed model is refused'); + } finally { await f.native.close(); f.cleanup(); } +}); diff --git a/tests/desktop/test_control_install.py b/tests/desktop/test_control_install.py index d1650f06..5a251ec9 100644 --- a/tests/desktop/test_control_install.py +++ b/tests/desktop/test_control_install.py @@ -272,3 +272,81 @@ class FailedStartTests(unittest.TestCase): self.assertIn("memory guard: 5.1 GiB free", tail) self.assertTrue(tail.endswith("exit code 3")) self.assertNotIn("loading", tail.split(" | ")[0] if tail.count(" | ") > 2 else "") + + +class DeleteModelTests(unittest.TestCase): + """Deleting a downloaded model removes its own files and run config, never what another installed model still uses.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + base = Path(self.tmp.name) + self.root = base / "install" + self.root.mkdir() + self.data = base / "Strata-data" + spec = importlib.util.spec_from_file_location("strata_mcp_for_delete", ROOT / "tools" / "strata_mcp.py") + self.mcp = importlib.util.module_from_spec(spec) + with mock.patch.dict(os.environ, {"STRATA_CONTROL_INSTALL": "1", "STRATA_INSTALL_DIR": str(self.root)}): + spec.loader.exec_module(self.mcp) + self.s = self.mcp.Strata(self.root, ROOT) + self.tools = self.mcp.Tools(self.s) + + def make(path: Path, size: int): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"x" * size) + return path + self.make = make + mtp = self.data / "mtp" / "rt" + make(mtp / "experts.bin", 3000) + shared_ple = make(self.data / "models" / "Q2_0" / "shard-2.gguf", 2000) # the same second shard in both models + for tag, size in (("iq3_s", 10000), ("q2_0", 4000)): + folder = self.data / "models" / tag + first = make(folder / "shard-1.gguf", size) + make(first.with_name(first.name + ".done"), 1) + pack = self.data / "packs" / tag + make(pack / "tokenizer" / "vocab.json", 500) + (self.root / f"strata-{tag}.json").write_text(json.dumps({"exe": "component:strata-engine", "args": [ + "--pack", str(pack), "--native", str(first), "--ple-gguf", str(shared_ple), "--mtp", str(mtp), "--max-context", "32768"]}), encoding="utf-8") + (self.root / f"strata-{tag}.log").write_text("log", encoding="utf-8") + + def test_the_plan_names_what_goes_and_what_stays(self): + plan = self.tools.strata_remove(model="iq3_s")["plan"] + removed = {Path(x["path"]).name for x in plan["remove"]} + kept = {Path(x["path"]).name for x in plan["keep"]} + self.assertIn("shard-1.gguf", removed) + self.assertIn("iq3_s", removed) # its pack folder + self.assertIn("strata-iq3_s.json", removed) + self.assertEqual(kept, {"shard-2.gguf", "rt"}) # the shared PLE shard and the shared MTP draft + self.assertEqual(plan["bytes"], 10000 + 1 + 500 + 3 + (self.root / "strata-iq3_s.json").stat().st_size) + + def test_confirm_deletes_only_that_model_and_the_other_still_has_everything(self): + result = self.tools.strata_remove(model="iq3_s", confirm=True) + self.assertEqual(result["failed"], []) + self.assertFalse((self.data / "models" / "iq3_s").exists()) # its folder is gone with its file + self.assertFalse((self.data / "packs" / "iq3_s").exists()) + self.assertFalse((self.root / "strata-iq3_s.json").exists()) + self.assertTrue((self.data / "models" / "Q2_0" / "shard-2.gguf").is_file()) + self.assertTrue((self.data / "mtp" / "rt" / "experts.bin").is_file()) + self.assertTrue((self.data / "models" / "q2_0" / "shard-1.gguf").is_file()) + self.assertTrue((self.data / "packs" / "q2_0" / "tokenizer" / "vocab.json").is_file()) + self.assertTrue((self.root / "strata-q2_0.json").is_file()) + + def test_the_last_model_takes_its_shared_files_with_it(self): + self.tools.strata_remove(model="iq3_s", confirm=True) + self.tools.strata_remove(model="q2_0", confirm=True) + self.assertFalse((self.data / "mtp" / "rt").exists()) + self.assertFalse((self.data / "models" / "Q2_0" / "shard-2.gguf").exists()) + + def test_nothing_outside_strata_s_folders_is_touched_and_each_model_reports_its_own_disk_use(self): + outside = Path(self.tmp.name) / "elsewhere" / "mine.gguf" + self.make(outside, 777) + cfg = self.root / "strata-q2_0.json" + data = json.loads(cfg.read_text()) + data["args"] += ["--ple-gguf", str(outside)] + cfg.write_text(json.dumps(data), encoding="utf-8") + plan = self.tools.strata_remove(model="q2_0")["plan"] + self.assertIn("mine.gguf", {Path(x["path"]).name for x in plan["keep"]}) + self.tools.strata_remove(model="q2_0", confirm=True) + self.assertTrue(outside.is_file()) + described = self.s.describe_config(self.root / "strata-iq3_s.json") + self.assertGreater(described["disk_bytes"], 10000) diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 64fc3e29..476e932a 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -536,8 +536,78 @@ class Strata: "low_ram": "--resident-experts" in a or "--mmap-experts" in a, "start_script": script.name if script.exists() else None, "ready": not missing and bool(cfg), "missing_files": missing[:3], + "disk_gb": self.removal_plan(path)["gb"], "disk_bytes": self.removal_plan(path)["bytes"], "last_used": time.strftime("%Y-%m-%d %H:%M", time.localtime(path.stat().st_mtime))} + # ---- what a model owns on disk (Delete, and the per-model disk usage in Storage) + FILE_FLAGS = ("--native", "--ple-gguf", "--embd-gguf", "--native-dense-gguf") + DIR_FLAGS = ("--pack", "--mtp") + + def model_paths(self, cfg: dict) -> tuple[list, list]: + """(the GGUF files, the folders) a run config names: --native/--ple-gguf/... and --pack/--mtp, plus any other .gguf.""" + a = [x for x in (cfg.get("args") or []) if isinstance(x, str)] + files = [Path(a[i + 1]) for i, x in enumerate(a[:-1]) if x in self.FILE_FLAGS] + files += [Path(x) for x in a if x.lower().endswith(".gguf") and Path(x) not in files] + dirs = [Path(a[i + 1]) for i, x in enumerate(a[:-1]) if x in self.DIR_FLAGS] + return files, dirs + + @staticmethod + def tree_bytes(path: Path) -> int: + if path.is_file(): + try: + return path.stat().st_size + except OSError: + return 0 + total = 0 + for base, _d, names in os.walk(path): + for n in names: + try: + total += os.stat(os.path.join(base, n)).st_size + except OSError: + pass + return total + + def removal_plan(self, config: Path) -> dict: + """What deleting this model removes and what it keeps. A file or folder another installed model's config still names + (the shared MTP draft, a shared PLE shard) is kept; so is anything outside Strata's own folders.""" + cfg = self.read_config(config) + files, dirs = self.model_paths(cfg) + used_files, used_dirs = set(), set() + for other in self.configs(): + if norm(other) == norm(config): + continue + f, d = self.model_paths(self.read_config(other)) + used_files |= {norm(x) for x in f} + used_dirs |= {norm(x) for x in d} + remove, keep = [], [] + + def shared(p: Path, is_dir: bool) -> bool: + n = norm(p) + if n in used_files or n in used_dirs or any(is_inside(u, n) for u in used_files | used_dirs) and is_dir: + return True + return any(is_inside(n, u) for u in used_dirs) + + for p, is_dir in [(x, False) for x in files] + [(x, True) for x in dirs]: + if not p.exists(): + continue + if not self.allowed(p): + keep.append({"path": str(p), "reason": "outside Strata's folders"}) + elif shared(p, is_dir): + keep.append({"path": str(p), "reason": "another installed model still uses it"}) + else: + remove.append({"path": str(p), "kind": "folder" if is_dir else "file", "bytes": self.tree_bytes(p)}) + if not is_dir: + for extra in (p.with_name(p.name + ".done"), p.with_name(p.name + ".part")): + if extra.exists(): + remove.append({"path": str(extra), "kind": "file", "bytes": self.tree_bytes(extra)}) + tag = config.stem[len("strata-"):] + for extra in (config, config.with_name(config.name + ".bak"), config.with_name(f"strata-{tag}.log"), + self.root / f"run-{tag}.bat", self.root / f"run-{tag}.sh"): + if extra.exists(): + remove.append({"path": str(extra), "kind": "file", "bytes": self.tree_bytes(extra)}) + total = sum(x["bytes"] for x in remove) + return {"model": tag, "remove": remove, "keep": keep, "bytes": total, "gb": round(total / 1e9, 2)} + def find_config(self, model: str | None) -> Path: have = self.configs() if not have: @@ -1008,6 +1078,13 @@ def tool_defs(models: dict, families: dict, contexts: list) -> list: "Read-only.", "inputSchema": {"type": "object", "additionalProperties": False, "properties": {}}, "annotations": ro}, + {"name": "strata_remove", "title": "Delete an installed model", + "description": "Delete an installed model's own files (its model GGUFs, its pack folder, its run config) and nothing " + "another installed model still uses (a shared MTP draft or PLE file). Without confirm=true it only " + "returns the plan (what would be removed and how big, what is kept). Stop the model first.", + "inputSchema": {"type": "object", "additionalProperties": False, "required": ["model"], + "properties": {"model": installed_model, "confirm": {"type": "boolean"}}}, + "annotations": {"readOnlyHint": False, "destructiveHint": True}}, {"name": "strata_install", "title": "Install Strata", "description": "Install a Strata model on this PC by running Strata's setup non-interactively in the " "background (Python packages, the engine, a 58-111 GB model download, preparation, start " @@ -1187,6 +1264,39 @@ class Tools: "gpus": [{k: g.get(k) for k in ("index", "name", "vram_gb", "usable")} for g in hw.get("gpus", [])]}} + # ---- strata_remove + def strata_remove(self, model=None, confirm=False) -> dict: + s = self.s + config = s.find_config(model) + plan = s.removal_plan(config) + if not confirm: + return {"summary": f"Plan: delete {plan['model']} ({plan['gb']:.1f} GB). Nothing was done yet.", "plan": plan} + with s.lock: + job = s.install_job() + if job and job["running"]: + raise ToolError("an install is running: wait for it to finish or stop it first") + tracked = s.tracked_server() + if tracked and not tracked.get("ended") and tracked.get("model") == plan["model"]: + raise ToolError("this model is running: stop it first") + failed = [] + for item in sorted(plan["remove"], key=lambda x: (x["path"] == str(config), x["path"])): + p = Path(item["path"]) + try: + if p.is_dir(): + shutil.rmtree(p) + else: + p.unlink() + except OSError as e: + failed.append(f"{p.name}: {e}") + files, dirs = s.model_paths(s.read_config(config)) if config.exists() else ([], []) + for p in {x.parent for x in [Path(i["path"]) for i in plan["remove"]] if x.suffix == ".gguf"}: + try: + p.rmdir() # the model's own folder, when nothing else is in it + except OSError: + pass + return {"summary": f"Deleted {plan['model']} ({plan['gb']:.1f} GB)" + (f"; could not remove {len(failed)} item(s)" if failed else ""), + "plan": plan, "failed": failed} + # ---- strata_install def check_data_dir(self, raw: str) -> Path: s = self.s diff --git a/tools/test_strata_mcp.py b/tools/test_strata_mcp.py index ab1e4608..9dd2210a 100644 --- a/tools/test_strata_mcp.py +++ b/tools/test_strata_mcp.py @@ -233,7 +233,7 @@ class Protocol(FakeRoot): self.assertIn("tools", init["capabilities"]) self.assertEqual(init["serverInfo"]["name"], "strata") names = [t["name"] for t in r[2]["result"]["tools"]] - self.assertEqual(names, ["strata_status", "strata_models", "strata_install", "strata_start", "strata_stop", + self.assertEqual(names, ["strata_status", "strata_models", "strata_remove", "strata_install", "strata_start", "strata_stop", "strata_logs", "strata_benchmark", "strata_connect_info"]) for t in r[2]["result"]["tools"]: self.assertEqual(t["inputSchema"]["type"], "object") @@ -272,7 +272,7 @@ class Protocol(FakeRoot): timeout=60, env=dict(os.environ)) lines = [json.loads(x) for x in p.stdout.splitlines()] self.assertEqual(sorted(m["id"] for m in lines), [1, 2, 3]) - self.assertEqual(len(next(m for m in lines if m["id"] == 2)["result"]["tools"]), 8) + self.assertEqual(len(next(m for m in lines if m["id"] == 2)["result"]["tools"]), 9) self.assertIn("ready", p.stderr) def test_not_a_strata_folder(self): From 8e2460d18c234d11b889a8006a51ef2e17ee9d97 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 00:53:05 +0200 Subject: [PATCH 14/16] owner feedback round: unified local-GGUF page and Manage models, no Tune model, Engine settings reduced with working Save logs, update buttons only when available, GPU data in Monitor with no model, thinking dots stop, Latest spacing, calmer native status reads, local GGUF adoption via --gguf-dir, no Contrast option or request-log button --- apps/desktop/scripts/ui-flows.mjs | 130 +++++++++++++++++- apps/host/server/control-runtime.mjs | 6 + apps/host/server/index.mjs | 21 ++- apps/host/server/native-control.mjs | 19 ++- apps/host/src/components/NativeLocalModel.tsx | 85 ++++++++++++ apps/host/src/components/NativeModels.tsx | 17 ++- apps/host/src/components/NativeOperations.tsx | 74 +++++----- apps/host/src/components/SettingsUpdates.tsx | 3 +- apps/host/src/lib/native-monitor.ts | 12 ++ apps/host/src/locales/de.json | 18 ++- apps/host/src/locales/en.json | 18 ++- apps/host/src/locales/es.json | 18 ++- apps/host/src/locales/ja.json | 18 ++- apps/host/src/locales/ko.json | 18 ++- apps/host/src/locales/pt.json | 18 ++- apps/host/src/locales/ru.json | 18 ++- apps/host/src/locales/zh.json | 18 ++- apps/host/src/screens/Chat.tsx | 2 +- apps/host/src/screens/ModelRun.tsx | 3 + apps/host/src/screens/Monitor.tsx | 7 +- apps/host/src/screens/Settings.tsx | 5 +- apps/host/src/styles/annotation-fixes.css | 12 ++ apps/host/src/styles/app.css | 5 +- apps/host/tests/monitor-host-sensors.test.mjs | 31 +++++ apps/host/tests/packaged-control.test.mjs | 14 ++ tests/desktop/test_control_install.py | 20 +++ tools/strata_mcp.py | 17 ++- 27 files changed, 553 insertions(+), 74 deletions(-) create mode 100644 apps/host/src/components/NativeLocalModel.tsx create mode 100644 apps/host/tests/monitor-host-sensors.test.mjs diff --git a/apps/desktop/scripts/ui-flows.mjs b/apps/desktop/scripts/ui-flows.mjs index 0edb6534..87235e51 100644 --- a/apps/desktop/scripts/ui-flows.mjs +++ b/apps/desktop/scripts/ui-flows.mjs @@ -30,7 +30,7 @@ const nodeExe = resolve(args.node ?? join(staged, 'node', process.platform === ' const work = mkdtempSync(join(tmpdir(), 'strata-ui-flows-')); const shots = resolve(args.shots ?? join(work, 'shots')); mkdirSync(shots, { recursive: true }); -const only = new Set(String(args.only ?? 'download,models,tune,fail,delete,theme,restart').split(',')); +const only = new Set(String(args.only ?? 'download,models,tune,fail,delete,theme,restart,perf,polish,stop,latest').split(',')); const isWin = process.platform === 'win32'; const { chromium } = await import(pathToFileURL(join(repoHost, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); @@ -130,7 +130,7 @@ async function scenario(name, { installed = false, env = {} } = {}, body) { const dir = join(work, name); const dirs = { home: join(dir, 'home'), appdata: join(dir, 'appdata'), local: join(dir, 'local'), components: join(dir, 'local', 'Strata', 'components'), install: join(dir, 'local', 'Strata', 'install'), state: join(dir, 'fake-state'), profiles: join(dir, 'profiles'), runtime: join(dir, 'runtime') }; for (const d of [dirs.home, dirs.appdata, dirs.local, dirs.components, dirs.install, dirs.state, join(dir, 'models')]) mkdirSync(d, { recursive: true }); - const baseEnv = { ...process.env, STRATA_COMPONENTS_DIR: dirs.components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(dir, 'models'), APPDATA: dirs.appdata, LOCALAPPDATA: dirs.local, XDG_CONFIG_HOME: join(dir, 'xdg'), XDG_DATA_HOME: join(dir, 'xdgdata'), PYTHONDONTWRITEBYTECODE: '1', STRATA_ENGINE_BACKEND: 'cuda', FAKE_STATE: dirs.state, ...env }; + const baseEnv = { ...process.env, STRATA_COMPONENTS_DIR: dirs.components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(dir, 'models'), APPDATA: dirs.appdata, LOCALAPPDATA: dirs.local, USERPROFILE: dirs.home, XDG_CONFIG_HOME: join(dir, 'xdg'), XDG_DATA_HOME: join(dir, 'xdgdata'), PYTHONDONTWRITEBYTECODE: '1', STRATA_ENGINE_BACKEND: 'cuda', FAKE_STATE: dirs.state, ...env }; delete baseEnv.STRATA_API_KEY; delete baseEnv.STRATA_INSTALL_DIR; if (installed) { const platform = isWin ? 'windows-x86_64' : 'linux-x86_64'; @@ -168,7 +168,7 @@ async function scenario(name, { installed = false, env = {} } = {}, body) { } } const newPage = async (browser, base, options = {}) => { - const context = await browser.newContext({ viewport: { width: 1400, height: 950 }, ...options }); + const context = await browser.newContext({ viewport: { width: 1400, height: 950 }, ...(process.env.SCHEME ? { colorScheme: process.env.SCHEME } : {}), ...options }); const page = await context.newPage(); const problems = []; page.on('pageerror', e => problems.push(e.message)); @@ -374,6 +374,130 @@ await scenario('delete', { installed: true }, async ({ base, api, browser, dirs, await shot(page, '2-after-delete'); }); +// ------------------------------------------------------------------------------------------------ perf +await scenario('perf', { installed: true }, async ({ base, api, browser, shot }) => { + const page = await newPage(browser, base); + await clickText(page, /Go straight to the app/i); + await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {}); + await page.getByRole('button', { name: /^Load model$/ }).first().click(); + let ready = false; + for (let i = 0; i < 90 && !ready; i++) { ready = (await api('/api/native')).body.instances.some(x => x.status === 'ready'); await delay(1000); } + check(ready, 'a model is loaded'); + await delay(2500); + const requests = []; + const started = new Map(); + page.on('request', r => started.set(r, Date.now())); + page.on('requestfinished', r => requests.push([r.url().replace(base, '').slice(0, 60), Date.now() - (started.get(r) ?? Date.now())])); + await page.evaluate(() => { window.__long = []; new PerformanceObserver(l => { for (const e of l.getEntries()) window.__long.push(Math.round(e.duration)); }).observe({ entryTypes: ['longtask'] }); }); + const t0 = Date.now(); + await page.evaluate(() => { location.hash = '#/chat'; }); + await page.getByRole('textbox', { name: /Message Strata/i }).waitFor({ timeout: 30000 }); + const open = Date.now() - t0; + await delay(1500); + const long = await page.evaluate(() => window.__long); + console.log('info chat opened in', open, 'ms; long tasks', JSON.stringify(long), 'requests', JSON.stringify(requests.filter(r => r[1] > 100)), 'all', requests.length); + check(open < 1500 && Math.max(0, ...long) < 300, 'Models to Chat opens at once, with no long block', open + ' ms, longest task ' + Math.max(0, ...long) + ' ms'); +}); + +// ------------------------------------------------------------------------------------------------ polish +await scenario('polish', { installed: true }, async ({ base, api, browser, dirs, shot }) => { + const page = await newPage(browser, base); + await clickText(page, /Go straight to the app/i); + await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {}); + await page.getByText(/Conversation context/i).first().waitFor({ timeout: 30000 }); + check(await page.getByRole('button', { name: /Tune model/i }).count() === 0, 'the Models tab has no "Tune model" button'); + await clickText(page, /Manage models/i); + await delay(500); + const rows = await page.locator('.native-manage-row').count(); + check(rows === 1, 'Manage models lists only the downloaded model, not the catalog', rows + ' row(s)'); + await shot(page, '1-manage-models'); + await page.getByRole('button', { name: /^Done$/ }).click(); + await page.getByRole('button', { name: /Other local models/i }).click().catch(async () => { await clickText(page, /Manage models/i); await clickText(page, /Use a local GGUF/i); }); + await page.getByText(/Folder with the GGUF files/i).first().waitFor({ timeout: 15000 }).catch(() => {}); + await shot(page, '2-local-gguf'); + check(await page.getByText(/Folder with the GGUF files/i).count() > 0, 'the local GGUF page opens in the same design as Models'); + await page.getByPlaceholder(/Full path to the folder/i).fill(join(dirs.install, 'does-not-exist')); + await page.getByRole('button', { name: /^Check files$/ }).click(); + await delay(3000); + check(await page.locator('.error-notice').count() > 0, 'a folder that cannot be used says so in words'); + await shot(page, '2b-local-gguf-problem'); + await page.evaluate(() => { location.hash = '#/chat?settings=1'; }); + await delay(1500); + const text = await page.locator('body').innerText(); + check(!/Contrast/.test(text), 'Settings has no Contrast option'); + check(!/View request log/.test(text), 'and no "View request log" button'); + await page.getByText(/^Engine$/).first().click().catch(() => {}); + await delay(1500); + await shot(page, '3-settings-engine'); + const engine = await page.locator('body').innerText(); + check(/Update component/.test(engine) && /Diagnostics/.test(engine), 'Settings > Engine has Update component and Diagnostics'); + check(!/Performance|Model settings|Calibrate|Engine installation/.test(engine), 'and nothing else'); + await page.getByRole('button', { name: /^Save logs$/ }).click(); + await page.getByText(/Saved to/).first().waitFor({ timeout: 15000 }).catch(() => {}); + const savedText = await page.getByText(/Saved to/).first().innerText().catch(() => ''); + const savedPath = savedText.replace(/^Saved to\s*/, '').trim(); + check(!!savedPath && existsSync(savedPath), 'Save logs writes a file to Downloads and says where', savedPath); + await shot(page, '4-logs-saved'); + await page.evaluate(() => { location.hash = '#/monitor'; }); + await delay(6000); + await shot(page, '5-monitor'); + const mon = await page.locator('body').innerText(); + check(/°C/.test(mon), 'the Monitor shows GPU data with no model loaded', (mon.match(/.{0,30}°C.{0,20}/)?.[0] ?? 'no temperature text').replace(/\s+/g, ' ')); +}); + +// ------------------------------------------------------------------------------------------------ stop +await scenario('stop', { installed: true, env: { FAKE_TOKEN_DELAY: '0.1', FAKE_REPLY: 'thinking '.repeat(30) } }, async ({ base, api, browser, shot }) => { + const page = await newPage(browser, base); + await clickText(page, /Go straight to the app/i); + await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {}); + await page.getByRole('button', { name: /^Load model$/ }).first().click(); + let ready = false; + for (let i = 0; i < 90 && !ready; i++) { ready = (await api('/api/native')).body.instances.some(x => x.status === 'ready'); await delay(1000); } + if (!ready) { const st = (await api('/api/native')).body; console.log('info jobs', JSON.stringify(st.jobs.map(j => [j.kind, j.state, j.error ?? j.summary])), JSON.stringify(st.instances.map(i => [i.status, i.error]))); await shot(page, '0-stop-notloaded'); } + check(ready, 'a model is loaded'); + await page.evaluate(() => { location.hash = '#/chat'; }); + const box = page.getByRole('textbox', { name: /Message Strata/i }); + await box.waitFor({ timeout: 30000 }); + await box.fill('hello'); + await page.keyboard.press('Enter'); + await page.locator('.typing').first().waitFor({ timeout: 30000 }); + await delay(1500); + await page.getByRole('button', { name: /^Stop/i }).first().click().catch(async () => { await page.keyboard.press('Escape'); }); + await delay(4000); + const dots = await page.locator('.typing').count(); + await shot(page, '1-after-stop'); + check(dots === 0, 'after Stop in the middle of thinking the three dots are gone', dots + ' left'); +}); + +// ------------------------------------------------------------------------------------------------ latest +await scenario('latest', {}, async ({ base, browser, shot }) => { + const page = await newPage(browser, base); + const now = Date.now(); + await page.evaluate(now => { + const messages = []; + for (let i = 0; i < 40; i++) { messages.push({ id: 'u' + i, role: 'user', content: 'question ' + i, at: now }, { id: 'a' + i, role: 'assistant', content: 'answer number ' + i + ' with some text to fill the line and more of it.', at: now, tokens: 20, inputTokens: 5 }); } + localStorage.setItem('strata.sessions.v1', JSON.stringify([{ id: 's_latest', title: 'long', updatedAt: now, createdAt: now, messages }])); + localStorage.setItem('strata.active-session.v1', 's_latest'); + }, now); + await page.reload({ waitUntil: 'domcontentloaded' }); + await delay(1500); + if (await page.getByRole('button', { name: /Go straight to the app/i }).count()) { await clickText(page, /Go straight to the app/i); await delay(1500); } + await page.goto(base + '/#/chat', { waitUntil: 'domcontentloaded' }); + await page.getByRole('textbox', { name: /Message Strata/i }).waitFor({ timeout: 30000 }); + await delay(800); + await page.locator('.main__body.chat').first().waitFor({ timeout: 15000 }).catch(async () => { await shot(page, '0-latest-missing'); console.log('info body', JSON.stringify((await page.locator('body').innerText()).slice(0, 300))); }); + await page.locator('.main__body.chat').first().evaluate(el => { el.scrollTop = 3000; }); + await delay(600); + await page.mouse.wheel(0, -400); + await delay(600); + await page.locator('.main__body.chat').first().evaluate(el => { el.scrollTop = 0; }); + await delay(800); + const gaps = await page.evaluate(() => { const b = document.querySelector('.jumplatest'), c = document.querySelector('.main__body.chat'); if (!b || !c) return null; const r = b.getBoundingClientRect(), cr = c.getBoundingClientRect(); return { top: Math.round(r.top - cr.top), bottom: Math.round(cr.bottom - r.bottom) }; }); + console.log('info chat dom', JSON.stringify(await page.evaluate(() => { const c = document.querySelector('.main__body.chat'); return { msgs: document.querySelectorAll('.st-msg').length, scrollH: c?.scrollHeight, clientH: c?.clientHeight, top: c?.scrollTop, jump: document.querySelectorAll('.jumplatest').length }; }))); + await shot(page, '1-latest-button'); + check(!!gaps && gaps.top >= 12 && gaps.bottom >= 12, 'the Latest button keeps a gap from the top navigation and from the bottom', JSON.stringify(gaps)); +}); + // ------------------------------------------------------------------------------------------------ fail await scenario('fail', { installed: true, env: { FAKE_ENGINE_FAIL: '1' } }, async ({ base, api, browser, shot }) => { const page = await newPage(browser, base); diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjs index d163f928..e07da9af 100644 --- a/apps/host/server/control-runtime.mjs +++ b/apps/host/server/control-runtime.mjs @@ -123,6 +123,12 @@ export function createControl({ control = findControl(), env = process.env, run if (result.code !== 0 || !result.json) throw failure(result, 'The installed models could not be read.'); return result.json; }, + /** What a local GGUF folder or file holds, without touching it: the model it is, and why it cannot be used when it cannot. */ + async importPlan(path) { + const result = await call(['models', 'import', path, '--plan', '--output', 'json'], { timeoutMs: 120_000 }); + if (result.json && result.code === 0) return result.json.plan ?? result.json; + throw failure(result, 'The files could not be checked.'); + }, async saveProfile(name, configPath) { const listed = await call(['profile', 'list', '--output', 'json'], { timeoutMs: 20_000 }); const known = (listed.json?.profiles ?? []).some(p => p.id === name); diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 3756bc7f..a84b0f40 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -22,11 +22,12 @@ import { createAgentBridge } from './agent/agent-bridge.mjs'; * live metrics and the local inference API. No runtime dependencies. */ import http from 'node:http'; +import { homedir } from 'node:os'; import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'; import { spawn } from 'node:child_process'; import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; -import { basename, extname, isAbsolute, join, normalize, resolve } from 'node:path'; +import { basename, dirname, extname, isAbsolute, join, normalize, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import * as hardware from './hardware.mjs'; @@ -772,6 +773,24 @@ async function api(req, res, path, method, url) { if(path==='/api/native/plan'&&method==='POST')return json(res,200,await native.plan(await readBody(req))); if(path==='/api/native/operations'&&method==='POST'){if(storageChanging)return error(res,409,'Wait for the model folder check to finish.');const body=await readBody(req);return json(res,202,native.operation(body.kind,body.args));} if(path==='/api/native/logs'&&method==='GET')return json(res,200,{logs:native.logs()}); + if(path==='/api/native/logs/save'&&method==='POST'){ + /* Diagnostics to a file: the engine messages the app kept, failed operations, and the tail of each model's server log under Control. + Written to the user's Downloads folder (the window cannot save a download); the path is returned to show. */ + const NL=String.fromCharCode(10); + const lines=[`Strata diagnostics ${new Date().toISOString()}`,`Version ${native.state().version??'unknown'}`,'','== Engine messages ==']; + for(const l of native.logs())lines.push(`${l.at} ${l.instanceId}: ${l.line}`); + lines.push('','== Operations ==');for(const j of native.state().jobs)lines.push(`${j.startedAt} ${j.kind} ${j.state}${j.error?`: ${j.error}`:''}${j.details?`${NL} ${j.details}`:''}`); + try{const runtime=process.env.STRATA_RUNTIME_DIR??join(dirname(componentsDirectory()),'runtime');for(const name of readdirSync(runtime).filter(n=>n.endsWith('.server.log'))){lines.push('',`== ${name} (last lines) ==`,...readFileSync(join(runtime,name),'utf8').split(NL).slice(-200));}}catch{/* no server logs yet */} + const folder=join(process.env.USERPROFILE??process.env.HOME??homedir(),'Downloads');mkdirSync(folder,{recursive:true}); + const file=join(folder,`strata-diagnostics-${new Date().toISOString().replace(/[:.]/g,'-').slice(0,19)}.txt`);writeFileSync(file,lines.join(NL),'utf8'); + return json(res,200,{path:file});} + if(path==='/api/native/local/preview'&&method==='POST'){ + /* "Use a local GGUF": pick (or type) the folder, and Control says what is in it. Nothing is copied or changed. */ + const typed=await typedFolder((await readBody(req)).path,{isAbsolute}); + const picked=typed?{path:typed}:await chooseFolder('Choose the folder that holds your GGUF files'); + if(picked.unavailable)return error(res,501,`${TYPE_A_PATH} ${picked.reason}`); + if(picked.cancelled)return json(res,200,{cancelled:true}); + return json(res,200,{path:picked.path,preview:await native.localPreview(picked.path)});} if(path==='/api/native/benchmark'&&method==='GET')return json(res,200,native.benchmarkReport()); const nativeOperation=/^\/api\/native\/operations\/([a-z0-9-]+)\/cancel$/.exec(path); if(nativeOperation&&method==='POST')return json(res,200,await native.cancel(nativeOperation[1])); diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 02e0bf1f..1a4afeb8 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -39,7 +39,8 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);}; const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();}; function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};} - function sourceText(){try{return readFileSync(join(packaged?control.control.dir:preferences.repo,'serve/server.py'),'utf8');}catch{return '';}} + let sourceCache={path:'',time:0,text:''}; + function sourceText(){try{const path=join(packaged?control.control.dir:preferences.repo,'serve/server.py'),time=statSync(path).mtimeMs;if(sourceCache.path===path&&sourceCache.time===time)return sourceCache.text;sourceCache={path,time,text:readFileSync(path,'utf8')};return sourceCache.text;}catch{return '';}} function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));} const modelArena=id=>({arenaGb:(snapshot.catalog?.families??[]).flatMap(f=>f.sizes??[]).find(s=>s.id===id)?.experts_gb}); /* A start that ends with `server_exited` carries the engine's last log line with it; the app turns the code into words and @@ -99,8 +100,10 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp async function mcpCall(name,args={}){await connect();if(!definitions.some(d=>d.name===name))throw new Error(`This Strata installation does not support ${name}. Update the installation first.`);const result=await send('tools/call',{name,arguments:args},120000);let value=result.structuredContent;if(!value){const text=result.content?.find(c=>c.type==='text')?.text;try{value=JSON.parse(text);}catch{value={summary:text};}}if(result.isError)throw new Error(value?.error??value?.summary??'Native operation failed.');return value;} async function refresh(force=false){ if(closing)return state(); - if(refreshing)return refreshing;if(!force&&Date.now()-lastRead<15000)return state(); - refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);const noImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,images:false,sizes:(f.sizes??[]).map(s=>({...s,images:false}))}))}:c;snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:packaged?noImages(catalog):catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing; + /* A read that is not forced never makes the window wait for the (slow) status of Control: it gets the last state at once, and a stale one + is refreshed in the background. Only the first read, and a forced one after an operation, waits. */ + if(refreshing)return !force&&snapshot.available?state():refreshing;if(!force&&Date.now()-lastRead<45000)return state(); + refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);const noImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,images:false,sizes:(f.sizes??[]).map(s=>({...s,images:false}))}))}:c;snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:packaged?noImages(catalog):catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});const run=refreshing;if(!force&&snapshot.available){run.catch(()=>{});return state();}return run; } function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};packagedInstall=null;disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);} function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();} @@ -109,7 +112,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);} function previousEngine(){try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}} async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);return tool('strata_install',installArgs(args,false));} - function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),...(packaged?{vision:'no'}:{}),confirm};} + function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port','gguf_dir'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),...(packaged?{vision:'no'}:{}),confirm};} function begin(kind,run,metadata={}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or cancel the current engine operation first.');const job={id:randomUUID(),kind,state:'running',startedAt:new Date().toISOString(),summary:'Starting…',result:null,error:null,...metadata};for(const [id,old] of jobs)if(jobs.size>=12&&old.state!=='running')jobs.delete(id);jobs.set(job.id,job);emit();void run(job).then(result=>{if(job.state==='running'){Object.assign(job,{state:'done',summary:result?.summary??'Complete',result,finishedAt:new Date().toISOString()});}}).catch(error=>{if(job.state==='running')Object.assign(job,{state:'error',error:error.message,summary:error.message,finishedAt:new Date().toISOString()});}).finally(()=>{if(job.kind.startsWith('update')||job.kind==='rollback')disconnect();lastRead=0;emit();void refresh(true);});return state().jobs.find(j=>j.id===job.id);} async function watchInstall(job,current){job.summary=current.step??'Resuming preparation status…';job.result={install:current};while(job.state==='running'){await new Promise(r=>setTimeout(r,1500));const result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(!result.install?.running){if(result.install?.exit_code!==0)throw new Error(result.install?.error??'Preparation did not finish. Retry to reuse completed files.');return {summary:'Model preparation complete. Load it from Models.'};}}} @@ -176,7 +179,10 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp if(instance.profile)await control.stop(instance.profile).catch(()=>{});else await stopProcess(proc);instance.status='error';instance.error='Loading took more than five minutes. Check the engine log and free memory.';throw new Error(instance.error); } async function freePort(requested){for(let port=Number(requested??18500);port<=Number(requested??18500)+20;port++){if(!Number.isInteger(port)||port<1024||port>65535)throw new Error('Choose a port from 1024 to 65535.');if([...instances.values()].some(i=>i.port===port)){if(requested)throw new Error('This private engine port is already in use.');continue;}const available=await new Promise(resolve=>{const probe=createServer();probe.once('error',()=>resolve(false));probe.listen(port,'127.0.0.1',()=>probe.close(()=>resolve(true)));});if(available)return port;if(requested)throw new Error('This private engine port is already in use.');}throw new Error('No free private engine port was found.');} - async function poll(){if(polling||closing)return;polling=true;try{await Promise.all([...instances.values()].map(async instance=>{if(instance.status!=='ready')return;try{const response=await fetcher(`http://127.0.0.1:${instance.port}/metrics?requests=all`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(!response.ok)throw new Error('Metrics unavailable');instance.metrics=await response.json();const tools=await fetcher(`http://127.0.0.1:${instance.port}/mcp`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(tools.ok)instance.metrics.mcp=await tools.json();instance.phase=instance.metrics.live?.state??'idle';}catch{instance.metrics=null;instance.phase='unavailable';}}));emit();}finally{polling=false;}} + let pollCount=0; + /* The engine's metrics carry every finished request with `?requests=all`: a long session makes that a large JSON that the host parses and + pushes to the window every 2 s. The last dozen is what the app shows live; the full list is refreshed every tenth poll. */ + async function poll(){if(polling||closing)return;polling=true;const full=pollCount++%10===0;try{await Promise.all([...instances.values()].map(async instance=>{if(instance.status!=='ready')return;try{const response=await fetcher(`http://127.0.0.1:${instance.port}/metrics${full?'?requests=all':''}`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(!response.ok)throw new Error('Metrics unavailable');const fresh=await response.json();const older=instance.metrics?.requests,recent=fresh.requests;instance.metrics=full||!Array.isArray(older)||!Array.isArray(recent)||!recent.length?fresh:{...fresh,requests:[...recent,...older.filter(r=>Number(r.time)Number(x.time))))]};const tools=await fetcher(`http://127.0.0.1:${instance.port}/mcp`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(tools.ok)instance.metrics.mcp=await tools.json();instance.phase=instance.metrics.live?.state??'idle';}catch{instance.metrics=null;instance.phase='unavailable';}}));emit();}finally{polling=false;}} function ensurePoll(){if(!timer){timer=setInterval(()=>void poll(),2000);timer.unref?.();}void poll();} async function benchmark(job,args){const instance=resolveInstance(args.instanceId);job.instanceId=instance.id;if(busy(requests().filter(r=>r.instanceId===instance.id)))throw new Error('Wait for this model to finish before benchmarking.');const started=Date.now();job.abort=new AbortController();const response=await fetcher(`http://127.0.0.1:${instance.port}/v1/chat/completions`,{method:'POST',headers:{'content-type':'application/json',authorization:`Bearer ${instance.key}`},signal:AbortSignal.any([job.abort.signal,AbortSignal.timeout(180000)]),body:JSON.stringify({model:instance.apiModelId,messages:[{role:'user',content:'Explain how a rainbow forms in clear, simple language.'}],temperature:0,reasoning_effort:'none',max_tokens:200,stream:false})});const body=await response.json();if(!response.ok)throw new Error(body.error?.message??'Benchmark failed.');if(job.state!=='running')return;const result={summary:'Measured benchmark complete.',at:new Date().toISOString(),model:instance.apiModelId,durationMs:Date.now()-started,tokensIn:body.usage?.prompt_tokens??null,tokensOut:body.usage?.completion_tokens??null,outputTps:body.timings?.predicted_per_second??null,promptTps:body.timings?.prompt_per_second??null,source:'engine',settings:'Greedy · thinking off · up to 200 output tokens'};writeFileSync(join(directory,'native-benchmark.json'),JSON.stringify(result,null,2),{mode:0o600});return result;} function resolveInstance(id){const aliases=[...instances.values()].filter(i=>i.aliases?.includes(id));if(aliases.length>1&&!instances.has(id)&&![...instances.values()].some(i=>i.apiModelId===id))throw new Error('This alias matches more than one instance. Choose its exact model ID.');const i=instances.get(id)??[...instances.values()].find(i=>i.apiModelId===id)??aliases[0]??(!id&&instances.size===1?[...instances.values()][0]:undefined);if(!i)throw new Error('Choose a loaded model ID.');if(i.status!=='ready')throw new Error('This model is not ready.');return i;} @@ -216,5 +222,6 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp async function close(){closing=true;clearInterval(timer);const installing=packaged&&child&&[...jobs.values()].some(j=>j.kind==='install'&&j.state==='running');if(installing)await send('tools/call',{name:'strata_install',arguments:{cancel:true}},15000).catch(()=>{});const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();} // Remove nonserializable process references from public jobs. const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,...job})=>job);return value;}; - return {state:publicState,refresh,configure,setDownloadDirectory,plan,settings,save,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; + async function localPreview(path){if(!packaged)throw new Error('Checking local model files is part of the Strata app.');if(typeof path!=='string'||!path.trim()||[...path].some(c=>c.charCodeAt(0)<32))throw new Error('Choose a folder.');return control.importPlan(path.trim());} + return {state:publicState,refresh,localPreview,configure,setDownloadDirectory,plan,settings,save,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; } diff --git a/apps/host/src/components/NativeLocalModel.tsx b/apps/host/src/components/NativeLocalModel.tsx new file mode 100644 index 00000000..f2d05aaa --- /dev/null +++ b/apps/host/src/components/NativeLocalModel.tsx @@ -0,0 +1,85 @@ +import { tr } from '../lib/i18n'; +import { useState } from 'react'; +import { Screen } from './layout'; +import { Btn, ErrorNotice, Icon } from './ui'; +import { api } from '../lib/client'; +import { nativeAction, useNative, type NativeJob } from '../lib/native'; +import { nativeCatalogModels, catalogVersionLabel } from '../lib/native-catalog'; +import { sizeGb } from '../lib/format'; +import { NativeProgress } from './NativeModels'; + +interface Preview { path: string; preview: { file_count: number; total_bytes: number; file_set_status: string; issues: string[]; candidate_selection: { family: string; model: string } | null } } + +/** The words for why a folder of GGUF files cannot be used: a sentence and what to do, the checker's own codes under Details. */ +function problem(issues: string[]): { message: string; next: string } { + const has = (re: RegExp) => issues.some(i => re.test(i)); + if (has(/incomplete_or_invalid_shard_set|multiple_model_groups/)) + return { message: 'Some parts of this model are missing, or the folder holds more than one model.', next: 'Put every part of one model in one folder, then check again.' }; + if (has(/unrecognized_or_unsupported_model_variant|unsupported_architecture|unsupported_or_missing_architecture|expert_quantization|tokenizer/)) + return { message: 'Strata can’t run these files yet.', next: 'Strata runs the Qwen3.8-Flash-Next models. Download one from Models, or choose a folder with its files.' }; + return { message: 'These files could not be checked.', next: 'Check that the folder holds complete GGUF files, then try again.' }; +} + +/** "Use a local GGUF": choose the folder of a model you already have, Strata checks it, and prepares and loads it without copying + * or downloading the model files. The same page layout and cards as the optimized models page. */ +export function NativeLocalModel({ onBack }: { onBack: () => void }) { + const native = useNative(); + const [typed, setTyped] = useState(''), [checked, setChecked] = useState(null), [pending, setPending] = useState(false), [error, setError] = useState(''), [jobId, setJobId] = useState(''); + const job = native?.jobs.find(j => j.id === jobId); + const active = native?.jobs.find(j => j.state === 'running'); + const selection = checked?.preview.candidate_selection; + const usable = !!checked && checked.preview.file_set_status === 'plausible' && !!selection; + const version = selection ? nativeCatalogModels(native?.catalog?.families ?? []).flatMap(f => f.sizes).find(s => s.sourceFamily === selection.family && s.model === selection.model) : undefined; + const family = selection ? nativeCatalogModels(native?.catalog?.families ?? []).find(f => f.sizes.some(s => s.sourceFamily === selection.family && s.model === selection.model)) : undefined; + async function check(path: string) { + setPending(true); + setError(''); + setChecked(null); + try { + const result = await api.post('/api/native/local/preview', { path }); + if (!result.cancelled) { + setChecked(result); + setTyped(result.path); + } + } + catch (e) { setError(e instanceof Error ? e.message : String(e)); } + finally { setPending(false); } + } + async function prepare() { + if (!usable || !selection || !checked) + return; + setPending(true); + setError(''); + try { + const result = await nativeAction('operations', { kind: 'install', args: { family: selection.family, model: selection.model, gguf_dir: checked.path, context: native?.catalog?.recommendation?.context ?? 32768, vision: 'no', kv: 'int8', loadAfter: true } }); + setJobId(result.id); + } + catch (e) { setError(e instanceof Error ? e.message : String(e)); } + finally { setPending(false); } + } + const found = checked ? problem(checked.preview.issues) : null; + return {tr("Strata optimized models")}}> +
+
+

{tr("Use a local GGUF…")}

+

{tr("Already have a supported model on this computer? Choose the folder that holds its files. Strata checks them, prepares the model and loads it. Nothing is copied or downloaded.")}

+ +
void check('')}>{tr("Choose folder")} void check(typed)}>{tr(pending && !jobId ? 'Checking…' : 'Check files')}
+
+ {tr(checked ?
{tr(usable ? <> +

{tr(family ? family.title : 'Model found')}

+

{tr(version ? catalogVersionLabel(version) : selection?.model ?? '')} · {tr(selection?.model ?? '')}

+

{tr("{0} files · {1}", [checked.preview.file_count, sizeGb(checked.preview.total_bytes / 1024 ** 3)])}

+
void prepare()}>{tr(pending ? 'Checking…' : 'Prepare and load')}
+ : <> +

{tr(found!.message)}

+

{tr(found!.next)}

+ {tr(checked.preview.issues.length ?
{tr("Details")}
{checked.preview.issues.join(String.fromCharCode(10))}
: null)} + )}
: null)} + {tr(active ? : job?.state === 'error' ? : job?.state === 'done' ?

{tr(job.summary)}

: null)} + {tr(error ? : null)} +
+ +
+
; +} diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index a251f073..07625d16 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -3,6 +3,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { Screen } from './layout'; import { Btn, Dialog, ErrorNotice, Icon, Select } from './ui'; import { installProgress, useDownloadEta } from '../lib/download-eta'; +import { sizeGb } from '../lib/format'; import { NativeDeleteDialog } from './NativeDelete'; import { plainFailureText } from '../lib/plain-errors'; import { api } from '../lib/client'; @@ -12,7 +13,6 @@ import { NativeSettings } from './NativeSettings'; import { RunImageModel } from './RunImageModel'; import { useStore } from '../lib/store'; import { NativePresets } from './NativePresets'; -import { NativeBenchmark } from './NativeOperations'; import { nativeCatalogModels, catalogVersionLabel } from '../lib/native-catalog'; export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine }: { onOtherModels: () => void; @@ -25,7 +25,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine 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 [resourceProfile, setResourceProfile] = useState<'work' | 'performance'>('work'); - const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState | null>(null), [benchmark, setBenchmark] = useState(false), [jobId, setJobId] = useState(''), [manage, setManage] = useState(false); + const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState | null>(null), [jobId, setJobId] = useState(''), [manage, setManage] = useState(false); const presetPending = useRef(false); const [deleting, setDeleting] = useState(null); const families = nativeCatalogModels(native?.catalog?.families ?? []); @@ -35,6 +35,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const selectedFamily = families.find(f => f.family === family || f.sizes.some(size => size.sourceFamily === family)) ?? families[0], selectedSize = selectedFamily?.sizes.find(s => s.id === size) ?? selectedFamily?.sizes[0]; const installed = native?.installed?.models.find(m => m.model === selectedSize?.id); // The model that is running is shown as running, with Unload: not offered for loading again. + const downloaded = native?.installed?.models ?? [], allSizes = families.flatMap(f => f.sizes); 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) { @@ -105,14 +106,20 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(active ? : null)} {tr(job?.state === 'error' ? void load()}/> : null)} {tr(error ? : null)} -
{tr(loadedSelected ? <> setBenchmark(true)}>{tr("Tune model")} void perform(() => nativeAction(`instances/${loadedSelected.id}/unload`))}>{tr("Unload")}{tr(onReady ? {tr("Start chatting")} : {tr("Ready")})} : onReady && native?.instances.some(i => i.status === 'ready') ? {tr("Start chatting")} : <> i.status === 'ready') || !!active} onClick={() => setBenchmark(true)}>{tr("Tune model")} void load()}>{tr(pending ? 'Checking…' : installed?.ready ? 'Load model' : 'Download & load')})}
+
{tr(loadedSelected ? <> void perform(() => nativeAction(`instances/${loadedSelected.id}/unload`))}>{tr("Unload")}{tr(onReady ? {tr("Start chatting")} : {tr("Ready")})} : onReady && native?.instances.some(i => i.status === 'ready') ? {tr("Start chatting")} : <> void load()}>{tr(pending ? 'Checking…' : installed?.ready ? 'Load model' : 'Download & load')})}
!pending && setPlan(null)} actions={<> setPlan(null)}>{tr("Cancel")} void download()}>{tr("Download & load")}}>

{tr(plan?.plan?.title ?? selectedFamily?.title)}{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")}

{tr(plan?.plan?.disk_short ? : null)}

{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}

{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}

{tr(selectedSize?.images ?

{tr("Vision encoder files are included. Picture reading loads only when enabled.")}

: null)}
setDeleting(null)}/> - setManage(false)} actions={ setManage(false)}>{tr("Done")}}>

{tr(selectedFamily?.title)}

{tr(selectedFamily?.sizes.map(v => ))}
{tr("Version")}{tr("Download")}{tr("Status")}
{tr(catalogVersionLabel(v))}{tr(v.model)} · {tr(v.about)}{tr(v.download_gb.toFixed(1))}{tr(" GB")}{tr(native?.instances.some(i => i.model === v.id) ? 'Loaded' : v.installed ? 'Downloaded' : 'Available')} { setSize(v.id); setManage(false); }}>{tr(selectedSize?.id === v.id ? 'Selected' : 'Use version')}{tr(native?.installed?.models.some(m => m.model === v.id) ? <> setDeleting(v.id)}>{tr("Delete")} : null)}
{ setManage(false); (onImport ?? onOtherModels)(); }}>{tr("Use a local GGUF\u2026")}

{tr("Choose a version, then load it from Models. Shared native files are kept together in Storage.")}

- setBenchmark(false)}/> + setManage(false)} actions={ setManage(false)}>{tr("Done")}}>
+ {tr(downloaded.length ?
{tr(downloaded.map(m => { const v = allSizes.find(x => x.id === m.model), loaded = native?.instances.some(i => i.model === m.model && i.status === 'ready'); return
+ {tr(v ? `${catalogVersionLabel(v)}` : m.model_name ?? m.model)}{tr(v ? v.model : m.model)}{tr(m.diskGb ? ` · ${sizeGb(m.diskGb)}` : '')} + {tr(loaded ? 'Loaded' : 'Downloaded')} + { if (v) setSize(v.id); setManage(false); }}>{tr(selectedSize?.id === m.model ? 'Selected' : 'Use version')} setDeleting(m.model)}>{tr("Delete")} +
; }))}
:

{tr("No downloaded models")}

)} +
{ setManage(false); (onImport ?? onOtherModels)(); }}>{tr("Use a local GGUF…")}
+
; } /** setup's "5/7: downloading …" as a sentence a person can read. */ diff --git a/apps/host/src/components/NativeOperations.tsx b/apps/host/src/components/NativeOperations.tsx index 1857b747..f058becc 100644 --- a/apps/host/src/components/NativeOperations.tsx +++ b/apps/host/src/components/NativeOperations.tsx @@ -2,8 +2,7 @@ import {localeTag} from '../lib/i18n'; import { tr } from '../lib/i18n'; import { useEffect, useState } from 'react'; import { api } from '../lib/client'; -import { nativeAction, refreshNative, useNative, type NativeJob } from '../lib/native'; -import { NativeSettings } from './NativeSettings'; +import { nativeAction, useNative, type NativeJob } from '../lib/native'; import { Btn, Dialog, ErrorNotice, Select } from './ui'; import { NativeProgress } from './NativeModels'; export function NativeBenchmark({ open, onClose }: { @@ -48,57 +47,60 @@ export function NativeBenchmark({ open, onClose }: { } export function NativeOperations() { const native = useNative(); - const [repository, setRepository] = useState(''), [model, setModel] = useState(''), [error, setError] = useState(''), [pending, setPending] = useState(false), [benchmark, setBenchmark] = useState(false), [logs, setLogs] = useState<{ + const [error, setError] = useState(''), [saved, setSaved] = useState(''), [saving, setSaving] = useState(false); + const [logs, setLogs] = useState<{ at: string; instanceId: string; line: string; - }[]>([]), [showLogs, setShowLogs] = useState(false), [confirm, setConfirm] = useState(''); - const installed = native?.installed?.models ?? [], selected = installed.find(i => i.model === model) ?? installed[0], active = native?.jobs.find(j => j.state === 'running'); - useEffect(() => { setRepository(native?.repo ?? ''); }, [native?.repo]); + }[]>([]), [showLogs, setShowLogs] = useState(false), [confirm, setConfirm] = useState(false); + const [update, setUpdate] = useState<'checking' | 'available' | 'current' | 'unknown'>('checking'); + const active = native?.jobs.find(j => j.state === 'running'); + // The engine's update is offered only when the update check says there is one. + useEffect(() => { + let alive = true; + void api.get<{ engine?: { status?: string } }>('/api/updates/check').then(r => { if (alive) setUpdate(r.engine?.status === 'available' ? 'available' : r.engine?.status === 'current' ? 'current' : 'unknown'); }).catch(() => { if (alive) setUpdate('unknown'); }); + return () => { alive = false; }; + }, []); useEffect(() => { if (!showLogs) return; - let current = true; - const load = () => void api.get<{ + const read = () => void api.get<{ logs: typeof logs; - }>('/api/native/logs').then(value => { - if (current) - setLogs(value.logs); - }).catch(e => setError(e.message)); - load(); - const timer = setInterval(load, 2500); - return () => { current = false; clearInterval(timer); }; + }>('/api/native/logs').then(value => { setLogs(value.logs); }).catch(() => { }); + read(); + const timer = setInterval(read, 2000); + return () => clearInterval(timer); }, [showLogs]); - async function connect() { - setPending(true); + async function updateEngine() { setError(''); try { - await api.patch('/api/native', { repository }); - await refreshNative(true); + await nativeAction('operations', { kind: 'update-engine' }); + setConfirm(false); + } + catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } + } + // The window cannot save a download, so the host writes the file to Downloads and says where. + async function saveLogs() { + setSaving(true); + setSaved(''); + setError(''); + try { + const result = await api.post<{ path: string }>('/api/native/logs/save', {}); + setSaved(result.path); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { - setPending(false); + setSaving(false); } } - async function operate(kind: string) { - setError(''); - try { - await nativeAction('operations', { kind, args: { model: selected?.model } }); - setConfirm(''); - } - catch (e) { - setError(e instanceof Error ? e.message : String(e)); - } - } - function exportLogs() { const url = URL.createObjectURL(new Blob([logs.map(l => `${l.at} ${l.instanceId}: ${l.line}`).join('\n')], { type: 'text/plain' })); const a = document.createElement('a'); a.href = url; a.download = 'strata-engine.log'; a.click(); URL.revokeObjectURL(url); } - return

{tr("Engine installation")}

{tr(native?.available ? 'Connected' : 'Setup needed')}

{tr("Your local Strata installation handles optimized models, companion files and engine updates.")}

{tr("Installation folder")}
void connect()}>{tr(pending ? 'Connecting…' : 'Connect installation')} void refreshNative(true)}>{tr("Check again")}{tr("Get Strata")}
{tr(native?.error ?

{tr(native.error)}

:

{tr(native?.summary)}

)}
- {tr(installed.length ?

{tr("Model settings & tools")}

}, { section: 'Reading & focus', label: 'Motion', hint: 'Reduced motion also disables smooth scrolling.', aliases: 'animation system full reduced', control: }, - { section: 'Reading & focus', label: 'Contrast', hint: 'Increase text and boundary contrast.', aliases: 'accessibility standard increased', control: