Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
installer: home() instead of a constant (callers can still move ROOT); close cancels a running install; tests for the app's install mode
Niko12212bd0cdc4f9b1
diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjsindex 0c574abad..b455c1f86 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.pyindex 4f9812d76..b6e2a571f 100644--- a/setup.py+++ b/setup.py@@ -63,11 +63,18 @@ from strata_control import acquisitionROOT = 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/<repo> 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* foldersnext 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 runconfigs 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 loadswarn(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, adopteok(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"] = 12if hip:@@ -5975,7 +5982,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopteif a.browser is not None:cfg["open_browser"] = a.browsercfg["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 adoptedvt = 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"] = 1ok("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 overcfg["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 onlyif 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.pynew file mode 100644index 000000000..96cd3f336--- /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()