okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
84.3 KiB1393 linesraw
1"""`strata launch` without screens: the settings rules, the catalog, presets, parameters, access, connect, and every flag."""
2
3from __future__ import annotations
4
5import io
6import json
7import os
8import shutil
9import sys
10import unittest
11from pathlib import Path
12from unittest import mock
13
14from strata_cli.launch import access, harness, params, settings as S, store
15from strata_cli.launch.catalog import Catalog, CatalogUnavailable, fit_on, verdict
16from strata_cli.launch.runner import Result, Runner, derive_config, desc_matches, tune_words
17from tests.terminal.launch_support import HW_12, HW_24, HW_2X16, Home, catalog, run_cli
18
19
20class SettingsRules(unittest.TestCase):
21    def test_parse_context(self):
22        self.assertEqual(S.parse_context("128k"), 131072)
23        self.assertEqual(S.parse_context("128K"), 131072)
24        self.assertEqual(S.parse_context("32 k"), 32768)
25        self.assertEqual(S.parse_context("65536"), 65536)
26        with self.assertRaises(ValueError):
27            S.parse_context("lots")
28        with self.assertRaises(ValueError):
29            S.parse_context("100")
30
31    def test_fit_parallel_follows_the_spec(self):
32        self.assertEqual([S.fit_parallel(v) for v in (8, 12, 16, 20, 24, 32, 48)], [1, 1, 1, 2, 3, 4, 4])
33        self.assertEqual(S.fit_parallel(None), 1)
34
35    def test_words_and_labels(self):
36        self.assertEqual(S.context_label(131072), "128K")
37        self.assertEqual(S.words_for(131072), "about 98,000 words")
38
39    def test_parallel_warning_is_a_warning_not_an_error(self):
40        notes = S.check_parallel(S.LaunchSettings(parallel=4), vram_gb=12)
41        self.assertEqual([n.level for n in notes], ["warn"])
42        self.assertIn("still start", notes[0].line())
43        self.assertEqual(S.check_parallel(S.LaunchSettings(parallel=9), vram_gb=12)[0].level, "error")
44        self.assertEqual(S.check_parallel(S.LaunchSettings(parallel=2), vram_gb=24), [])
45
46    def test_no_key_warnings_are_plain_and_stronger_in_public(self):
47        lan = S.check_access(S.LaunchSettings(access="lan", no_key=True))
48        self.assertEqual([n.level for n in lan], ["warn"])
49        self.assertIn("anyone who can reach this port can use the model and its tools", lan[0].line())
50        pub = S.check_access(S.LaunchSettings(access="cloudflare", no_key=True))
51        self.assertEqual([n.level for n in pub], ["warn"])
52        self.assertIn("public address", pub[0].line())
53        self.assertIn("anyone on the internet", pub[0].line())
54        self.assertEqual(S.check_access(S.LaunchSettings(access="lan", api_key="k")), [])
55        self.assertEqual(S.check_access(S.LaunchSettings(access="local", no_key=True)), [])
56
57    def test_access_notes(self):
58        self.assertEqual(S.check_access(S.LaunchSettings(access="local")), [])
59        lan = S.check_access(S.LaunchSettings(access="lan"))
60        self.assertEqual([n.level for n in lan], ["warn"])
61        self.assertIn("API key", lan[0].line())
62        bad = S.check_access(S.LaunchSettings(access="lann"))
63        self.assertEqual(bad[0].level, "error")
64        self.assertIn("lan", bad[0].line())
65        self.assertEqual(S.check_port("abc").level, "error")
66        self.assertEqual(S.check_port(70000).level, "error")
67        self.assertEqual(S.check_port(80).level, "warn")
68        self.assertIsNone(S.check_port(8080))
69
70    def test_split_setting(self):
71        self.assertEqual(S.split_setting("prefill=65536"), ("--prefill", "65536"))
72        self.assertEqual(S.split_setting("--kv-grow"), ("--kv-grow", ""))
73        self.assertEqual(S.split_setting("STRATA_PIN_BY_NEED=1"), ("STRATA_PIN_BY_NEED", "1"))
74        self.assertEqual(S.split_setting("expert_cache=auto"), ("--expert-cache", "auto"))
75        self.assertEqual(S.split_setting("IGC_EnableDPEmulation=1"), ("IGC_EnableDPEmulation", "1"))        # environment names keep their case
76        self.assertEqual(S.split_setting("ONEAPI_DEVICE_SELECTOR=level_zero:gpu"), ("ONEAPI_DEVICE_SELECTOR", "level_zero:gpu"))
77        self.assertEqual(S.split_setting("--prefill=4096"), ("--prefill", "4096"))
78        with self.assertRaises(ValueError):
79            S.split_setting("no spaces allowed=1")
80
81    def test_flags_text_round_trips_to_the_same_choices(self):
82        s = S.LaunchSettings(family="qwen", model="IQ3_XXS", context=131072, parallel=2, tune="quick", access="lan", port=9000,
83                             extra={"--prefill": "65536", "STRATA_PIN_BY_NEED": "1"})
84        text = S.flags_text(s)
85        for part in ("--model iq3_xxs", "--context 128k", "--parallel 2", "--tune quick", "--access lan", "--port 9000",
86                     "--set prefill=65536", "--set STRATA_PIN_BY_NEED=1"):
87            self.assertIn(part, text)
88        self.assertIn('--preset "Fast"', S.flags_text(s, preset="Fast"))
89
90    def test_slug(self):
91        self.assertEqual(S.slug("IQ3_XXS 128K - Full speed"), "iq3_xxs-128k-full-speed")
92        self.assertTrue(S.slug("123 go")[0].isalpha())
93
94    def test_roundtrip_dict(self):
95        s = S.LaunchSettings(name="a", model="Q2_0", family="qwen", context=32768, extra={"--spec": "3"}, tuned_preset="abc")
96        again = S.LaunchSettings.from_dict(json.loads(json.dumps(s.to_dict())))
97        self.assertEqual(again, s)
98        self.assertEqual(s.to_dict(with_key=False)["api_key"], None)
99        self.assertEqual(S.LaunchSettings(api_key="sk-x").to_dict(with_key=False)["api_key"], "set")
100
101
102class CatalogRules(unittest.TestCase):
103    def test_one_source_of_truth_and_fit_numbers(self):
104        with Home():
105            cat = catalog(HW_12)
106            rows = cat.rows()
107            ids = {(r.family, r.model) for r in rows}
108            self.assertIn(("qwen", "IQ3_XXS"), ids)
109            models, families, contexts, source = cat.tables()
110            self.assertEqual(source, "setup.py")                       # the same tables setup.py and the app read
111            for r in rows:
112                self.assertAlmostEqual(r.download_gb, models[r.model]["download_gb"])
113            rec = [r for r in rows if r.recommended]
114            self.assertEqual([(r.family, r.model) for r in rec], [("qwen", "IQ3_S")])      # 64 + 12 GB: the 64 GB tier
115
116    def test_the_recommendation_follows_the_memory_tiers(self):
117        # the owner's tiers count RAM + VRAM: 44 GB is the 40 GB tier (Swift 1.5 IQ2_XS, Gyro-M named), 60 GB the 48 GB tier
118        from tests.terminal.launch_support import HW_32GB_RAM
119        with Home():
120            rec = catalog(HW_32GB_RAM).recommendation(HW_32GB_RAM)
121            self.assertEqual((rec["family"], rec["model"]), ("swift", "IQ2_XS"))
122            self.assertIn("Gyro-M", rec["why"])
123            hw = {**HW_32GB_RAM, "ram_gb": 48.0}
124            rec = catalog(hw).recommendation(hw)
125            self.assertEqual((rec["family"], rec["model"]), ("qwen", "IQ3_XXS"))
126
127    def test_fit_on_matches_native_fit_ts(self):
128        # apps/host/src/lib/native-fit.ts: memory = experts + 1; GPU holds experts up to vram - 5; RAM holds up to ram - 10; the rest spills
129        f = fit_on({"experts_gb": 42.9, "ram_needed_gb": 60}, 64.0, 12.0)
130        self.assertEqual((f["memoryGb"], f["vramUseGb"], f["spillGb"]), (43.9, 12.0, 0.0))
131        self.assertAlmostEqual(f["ramUseGb"], 35.9, places=1)
132        spill = fit_on({"experts_gb": 98.4, "ram_needed_gb": 108}, 64.0, 12.0)
133        self.assertGreater(spill["spillGb"], 30)
134        self.assertFalse(fit_on({"experts_gb": 10}, None, 12)["known"])
135        gyro = fit_on({"mem_total": True, "ram_needed_gb": 27.6}, 64, 12)
136        self.assertEqual(gyro["memoryGb"], 27.6)
137
138    def test_a_mac_is_judged_by_unified_memory_and_the_words_follow(self):
139        hw = {"ram_gb": 32.0, "disk_free_gb": 5000.0, "os": "Darwin", "cpu": {"avx2": None, "name": "Apple M4"}, "mac": {"chip": "Apple M4", "macos": "27.2", "unified_gb": 32.0},
140              "gpus": [{"index": 0, "name": "Apple M4", "vendor": "apple", "vram_gb": 0.0, "unified_gb": 32.0, "usable": True}]}
141        with Home():
142            cat = catalog(hw)
143            rows = {r.model: r for r in cat.rows()}
144            self.assertEqual(set(rows), {"Q2_0", "IQ3_XXS", "IQ3_S", "Gyro-S", "Gyro-M", "UD-IQ1_M",
145                                "UD-Q2_0", "UD-IQ2_XS", "UD-Q2_K_XL", "UD-IQ3_XXS", "UD-Q3_K_XL", "UD-IQ4_XS-v31", "UD-Q4_K_XL", "UD-Q5_K_XL", "UD-Q6_K_XL"})   # Unsloth's sets (round 0214: the Mac app repacks them)
146            self.assertEqual([r.model for r in rows.values() if r.recommended], ["Q2_0"])
147            self.assertEqual((rows["Q2_0"].verdict, rows["Q2_0"].words), ("slower", "may run slower"))
148            self.assertEqual(rows["IQ3_S"].verdict, "slower")
149            self.assertGreater(rows["IQ3_S"].spill_gb, 10)
150            self.assertEqual(cat.max_context("qwen", "Q2_0", hw), 32768)
151            self.assertEqual(cat.computer().line(), "Apple M4 · 32 GB unified memory · " + cat.computer().line().split(" · ")[-1])
152            # no "0 GB" of video memory in the card part of the line (the free-disk figure after it may end in a zero: "60 GB free")
153            self.assertNotIn("0 GB", " · ".join(cat.computer().line().split(" · ")[:2]))
154
155    def test_verdict_words_never_block(self):
156        self.assertEqual(verdict("fits")[0], "fits")
157        self.assertEqual(verdict("does not fit"), ("slower", "may run slower"))              # an older Control's words, read as the one label
158        self.assertEqual(verdict("tight")[0], "tight")
159        self.assertEqual(verdict("fits"), ("fits", "fits"))
160        self.assertEqual(verdict("may run slower"), ("slower", "may run slower"))
161
162    def test_resolve_names_and_closest(self):
163        with Home():
164            cat = catalog()
165            self.assertEqual(cat.resolve("iq3_xxs"), ("qwen", "IQ3_XXS"))
166            self.assertEqual(cat.resolve("IQ1_M"), ("coder", "IQ1_M"))
167            self.assertEqual(cat.resolve("iq3_xxs", "swift"), ("swift", "IQ3_XXS"))
168            with self.assertRaises(ValueError) as e:
169                cat.resolve("iq3xxs")
170            self.assertIn("Did you mean 'IQ3_XXS'", str(e.exception))
171            with self.assertRaises(ValueError) as e:
172                cat.resolve("q2_0", "swiift")
173            self.assertIn("swift", str(e.exception))
174            with self.assertRaises(ValueError) as e:
175                cat.resolve("IQ1_M", "swift")
176            self.assertIn("has no size", str(e.exception))
177
178    def test_small_computer_gets_warnings_not_blocks(self):
179        with Home():
180            rows = catalog({**HW_12, "ram_gb": 32.0}).rows()
181            big = [r for r in rows if r.model == "IQ3_S" and r.family == "qwen"][0]
182            self.assertEqual((big.verdict, big.words), ("slower", "may run slower"))          # 51 GB of weights against 32 GB of RAM + a 12 GB card
183
184    def test_kv_figures(self):
185        with Home():
186            cat = catalog()
187            self.assertAlmostEqual(cat.kv_gb(131072, "int8"), 1.799, places=2)
188            self.assertLess(cat.kv_gb(131072, "q4_0"), cat.kv_gb(131072, "int8"))
189            self.assertEqual(cat.max_context("qwen", "IQ3_XXS", HW_12), 131072)      # 128K on every card (owner, 2026-11-01)
190            self.assertEqual(cat.max_context("qwen", "IQ3_XXS", HW_24), 131072)
191
192    def test_missing_installer_files_are_said_in_words(self):
193        with Home():
194            with self.assertRaises(CatalogUnavailable) as e:
195                Catalog(src="/nonexistent-folder", hardware=HW_12)
196            self.assertIn("one-line installer", str(e.exception))
197
198
199class PresetStore(unittest.TestCase):
200    def test_save_load_list_delete(self):
201        # Windows' clock moves in ~15.6 ms ticks: on a fast PC (a CI runner) the save and touch_used can read the same time, a tie in the order
202        ticks = iter(f"2026-01-01 00:00:{s:02d}.000000" for s in range(60))
203        with Home(), mock.patch.object(store, "now_text", lambda: next(ticks)):
204            s = S.LaunchSettings(name="IQ3_XXS 128K", family="qwen", model="IQ3_XXS", context=131072, api_key="sk-secret")
205            store.save(s)
206            store.save(S.LaunchSettings(name="Coder 64K", family="coder", model="IQ1_M", context=65536))
207            names = [p.name for p in store.list_presets()]
208            self.assertEqual(sorted(names), ["Coder 64K", "IQ3_XXS 128K"])
209            back = store.load("IQ3_XXS 128K")
210            self.assertEqual((back.model, back.context, back.api_key), ("IQ3_XXS", 131072, "sk-secret"))
211            store.touch_used("IQ3_XXS 128K")
212            self.assertTrue(store.load("IQ3_XXS 128K").last_used)
213            self.assertEqual(store.list_presets()[0].name, "IQ3_XXS 128K")          # most recently used first
214            store.delete("Coder 64K")
215            self.assertEqual([p.name for p in store.list_presets()], ["IQ3_XXS 128K"])
216            with self.assertRaises(store.PresetError) as e:
217                store.load("IQ3 XXS 128")
218            self.assertIn("Did you mean", str(e.exception))
219            with self.assertRaises(store.PresetError):
220                store.delete("nope")
221
222    def test_key_is_not_world_readable_on_posix(self):
223        if os.name == "nt":
224            self.skipTest("POSIX modes")
225        with Home():
226            store.save(S.LaunchSettings(name="k", api_key="sk-secret"))
227            path = next(store.preset_dir().glob("*.json"))
228            self.assertEqual(path.stat().st_mode & 0o077, 0)
229
230
231class Advanced(unittest.TestCase):
232    HELP = """strata generate --pack DIR [options]
233
234  --pack DIR           the pack directory (default pack/full)
235  --kv fp16|int8       KV storage (plan v0.3 P7): int8 codes, half the
236                       VRAM; default fp16 until the gate accepts int8
237  --kv q4_0            4-bit K/V after a Hadamard rotation
238  --kv-grow            the K/V takes VRAM only for the cells the requests reach
239  --native-rope        experimental pinned text-only CUDA rotary arithmetic
240  --prefill N          prompt chunk size (default 2048)
241"""
242
243    def test_parse_help(self):
244        ps = {p.name: p for p in params.parse_help(self.HELP)}
245        self.assertEqual(set(ps), {"--pack", "--kv", "--kv-grow", "--native-rope", "--prefill"})
246        self.assertEqual(ps["--pack"].metavar, "DIR")
247        self.assertEqual(ps["--pack"].help_default, "pack/full")
248        self.assertEqual(ps["--kv"].values, ["fp16", "int8"])
249        self.assertIn("4-bit", ps["--kv"].description)               # a flag listed twice keeps both texts
250        self.assertTrue(ps["--native-rope"].experimental)
251        self.assertFalse(ps["--prefill"].experimental)
252        self.assertEqual(ps["--kv-grow"].metavar, "")
253        self.assertLessEqual(len(ps["--prefill"].short), 70)
254
255    def test_rows_show_default_tuned_and_yours(self):
256        rows = {r.name: r for r in params.build_rows(self.HELP, ["--kv", "int8", "--prefill", "auto"], ["--kv", "int8", "--prefill", "auto:32768"],
257                                                     {}, {}, {"--prefill": "65536"})}
258        self.assertEqual((rows["--prefill"].default, rows["--prefill"].tuned, rows["--prefill"].yours), ("auto", "auto:32768", "65536"))
259        self.assertEqual(rows["--kv"].yours, "")
260        self.assertIn("--native-rope", rows)
261        names = list(rows)
262        self.assertEqual(names[:2], ["--kv", "--prefill"])             # what this launch uses comes first
263
264    def test_unknown_names_warn_and_are_kept(self):
265        rows = params.build_rows(self.HELP, [], None, {}, {}, {"--prefil": "1"})
266        r = next(x for x in rows if x.name == "--prefil")
267        self.assertFalse(r.known)
268        warn = params.check_name("--prefil", ["--prefill", "--kv"])
269        self.assertIn("Did you mean --prefill", warn)
270        self.assertIsNone(params.check_name("--prefill", ["--prefill"]))
271        self.assertIsNone(params.check_name("--prefil", None))        # no list to check against: no warning
272
273    def test_extra_becomes_argv_and_env(self):
274        a, e = S.as_argv_changes({"--prefill": "65536", "--kv-grow": "", "--spec": "off", "STRATA_PIN_BY_NEED": "1"}, frozenset({"--kv-grow"}))
275        self.assertEqual(a, {"--prefill": "65536", "--kv-grow": True, "--spec": None})
276        self.assertEqual(e, {"STRATA_PIN_BY_NEED": "1"})
277
278
279class RunConfig(unittest.TestCase):
280    BASE = {"exe": "component:strata-engine", "args": ["--native", "x.gguf", "--max-context", "32768", "--kv", "int8", "--prefill", "auto"],
281            "port": 8095, "model_name": "m", "env": {}}
282
283    def test_derive_applies_access_key_and_advanced(self):
284        s = S.LaunchSettings(access="lan", port=9001, api_key="sk-k", extra={"--prefill": "65536", "--kv-grow": "", "STRATA_PIN_BY_NEED": "1"})
285        cfg = derive_config(self.BASE, s, bool_flags=frozenset({"--kv-grow"}))
286        self.assertEqual((cfg["host"], cfg["port"], cfg["api_key"]), ("0.0.0.0", 9001, "sk-k"))
287        args = cfg["args"]
288        self.assertEqual(args[args.index("--prefill") + 1], "65536")
289        self.assertIn("--kv-grow", args)
290        self.assertEqual(cfg["env"], {"STRATA_PIN_BY_NEED": "1"})
291        self.assertEqual(self.BASE["args"][-1], "auto")               # the installed config is never edited
292
293    def test_mtp_off_leaves_the_draft_layer_out_of_this_launch_only(self):
294        base = {**self.BASE, "args": [*self.BASE["args"], "--spec", "4", "--spec-min-p", "0.5", "--mtp", "/m/rt"]}
295        cfg = derive_config(base, S.LaunchSettings(mtp="off"), bool_flags=frozenset())
296        self.assertIs(cfg["mtp"], False)
297        for flag in ("--mtp", "--spec-min-p", "--batch-mtp"):
298            self.assertNotIn(flag, cfg["args"])
299        self.assertEqual(cfg["args"][cfg["args"].index("--spec") + 1], "4")      # prompt lookup keeps its windows
300        self.assertIn("--mtp", base["args"])                                      # the installed config is never edited
301        on = derive_config({**base, "mtp": False}, S.LaunchSettings(mtp="on"), bool_flags=frozenset())
302        self.assertIs(on["mtp"], True)                                            # an explicit on beats an installed off
303        self.assertEqual(derive_config(base, S.LaunchSettings(), bool_flags=frozenset())["args"], base["args"])
304
305    def test_local_and_cloudflare_stay_on_loopback_without_a_key(self):
306        for kind in ("local", "cloudflare"):
307            cfg = derive_config(self.BASE, S.LaunchSettings(access=kind), bool_flags=frozenset())
308            self.assertEqual(cfg["host"], "127.0.0.1")
309            self.assertNotIn("api_key", cfg)
310
311    def test_no_key_is_written_as_none_and_a_key_wins(self):
312        cfg = derive_config(self.BASE, S.LaunchSettings(access="lan", no_key=True), bool_flags=frozenset())
313        self.assertEqual((cfg["host"], cfg["api_key"]), ("0.0.0.0", "none"))
314        cfg = derive_config(self.BASE, S.LaunchSettings(access="lan", no_key=True, api_key="sk-x"), bool_flags=frozenset())
315        self.assertEqual(cfg["api_key"], "sk-x")
316        cfg = derive_config(self.BASE, S.LaunchSettings(access="local", no_key=True), bool_flags=frozenset())
317        self.assertNotIn("api_key", cfg)
318
319    def test_installed_config_matching(self):
320        d = {"context": 32768, "kv": "int8", "images": "off"}
321        self.assertTrue(desc_matches(d, S.LaunchSettings(context=32768)))
322        self.assertFalse(desc_matches(d, S.LaunchSettings(context=65536)))
323        self.assertFalse(desc_matches(d, S.LaunchSettings(context=32768, vision="on")))
324        self.assertFalse(desc_matches({**d, "images": "cpu"}, S.LaunchSettings(context=32768, vision="off")))
325        self.assertFalse(desc_matches(d, S.LaunchSettings(context=32768, kv="q4_0")))
326
327    def test_tune_words(self):
328        self.assertEqual(tune_words({"outcome": "improved", "gain_pct": 4.2})[0], "faster")
329        self.assertEqual(tune_words({"outcome": "default_confirmed"})[0], "already fastest")
330        self.assertEqual(tune_words({"outcome": "inconclusive", "reason_code": "noisy"})[0], "busy PC")
331        self.assertEqual(tune_words({"outcome": "base_failed", "message": "Not tuned: no memory"})[0], "failed")
332        self.assertEqual(tune_words(None)[0], "failed")
333        self.assertEqual(tune_words({"outcome": "cancelled"})[0], "stopped")
334
335
336class SetupArgs(unittest.TestCase):
337    def runner(self, **kw):
338        with Home():
339            cat = catalog(HW_12)
340            kw.setdefault("vision", "off")
341            s = S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, kv="q4_0", **kw)
342            return Runner(s, catalog=cat).setup_args()
343
344    def args_for(self, **kw):
345        values = dict(family="qwen", model="IQ3_XXS", context=32768, kv="q4_0", vision="off")
346        values.update(kw)
347        with Home():
348            return Runner(S.LaunchSettings(**values), catalog=catalog(HW_12)).setup_args()
349
350    def test_a_lower_case_tag_from_a_saved_preset_reaches_setup_as_its_key(self):
351        """#4209: a preset keeps "model": "iq3_xxs", and setup's --model choices are the table's own keys
352        ("IQ3_XXS"). Starting such a preset with any changed choice reruns setup, which then refused it."""
353        args = self.args_for(model="iq3_xxs")
354        self.assertEqual(args[args.index("--model") + 1], "IQ3_XXS")
355        self.assertEqual(args[args.index("--family") + 1], "qwen")
356        for fam, model, want in (("coder", "iq1_m", "IQ1_M"), ("gyro", "gyro-s", "Gyro-S"), ("qwen", "IQ3_S", "IQ3_S")):
357            args = self.args_for(family=fam, model=model)
358            self.assertEqual(args[args.index("--family") + 1], fam)
359            self.assertEqual(args[args.index("--model") + 1], want)
360
361    def test_an_unknown_model_is_still_setup_to_report(self):
362        args = self.args_for(model="not-a-model")
363        self.assertEqual(args[args.index("--model") + 1], "not-a-model")
364
365    def test_a_model_list_that_cannot_be_read_leaves_the_values_alone(self):
366        """The resolver is an improvement, never a new way for the launch to fail: when it cannot answer, the
367        preset's own values go to setup as they did before #4209."""
368        with Home():
369            cat = catalog(HW_12)
370            r = Runner(S.LaunchSettings(family="qwen", model="iq3_xxs", context=32768, vision="off"), catalog=cat)
371            with mock.patch.object(cat, "resolve", side_effect=RuntimeError("the model list cannot be read")):
372                args = r.setup_args()
373        self.assertEqual(args[args.index("--model") + 1], "iq3_xxs")
374        self.assertEqual(args[args.index("--family") + 1], "qwen")
375
376    def test_pictures_default_on_the_cpu_reader_under_24_gb_and_the_gpu_reader_from_24_gb_on_every_make(self):
377        from tests.terminal.launch_support import HW_12 as NV
378        card = lambda name, gb, vendor: {**NV, "gpus": [{"index": 0, "name": name, "vram_gb": gb, "usable": True, "vendor": vendor}]}   # noqa: E731
379        amd = card("AMD Radeon RX 9070 XT", 16.0, "amd")
380        intel = card("Intel Arc B580", 12.0, "intel")
381        with Home():
382            for hw, want in ((NV, "cpu"), (amd, "cpu"), (intel, "cpu"), (card("NVIDIA GeForce RTX 4090", 24.0, "nvidia"), "gpu"),
383                             (card("AMD Radeon AI PRO R9700", 32.0, "amd"), "gpu")):
384                cat = catalog(hw)
385                r = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768), catalog=cat)
386                self.assertEqual(r.setup_args()[r.setup_args().index("--vision") + 1], want, hw["gpus"][0]["vendor"])
387                self.assertEqual(r.s.vision, want)
388            off = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, vision="off"), catalog=catalog(NV))
389            self.assertEqual(off.setup_args()[off.setup_args().index("--vision") + 1], "no")
390
391    def test_an_arc_b_series_card_is_allowed_with_pictures_on_the_cpu_reader_and_one_plain_line(self):
392        """Owner decision 2026-10-22: Arc B-series (Battlemage) runs like any Arc. An Arc Pro B70 (32 GB) gets pictures on, with the CPU reader (the GPU
393        reader has not run on a 24 GB+ Arc), and a warn-level note that it is new and how to report a problem. An A-series card gets no such note."""
394        from strata_cli.launch import cmd
395        for name, vram, note in (("Intel Arc Pro B70", 32.0, True), ("Intel Arc B580", 12.0, True), ("Intel Arc A750", 8.0, False)):
396            hw = {"ram_gb": 64.0, "os": "Linux", "cpu": {"avx2": True, "name": "x"},
397                  "gpus": [{"index": 0, "name": name, "vendor": "intel", "vram_gb": vram, "usable": True}]}
398            with Home():
399                from strata_cli.launch.catalog import Computer
400                cat = catalog(hw)
401                comp = Computer(ram_gb=64.0, gpus=hw["gpus"], disk_free_gb=500.0, os="Linux", avx2=True, raw=hw, engine_vendor="intel")
402                with mock.patch.object(type(cat), "reader_state", lambda self: "present"), mock.patch.object(type(cat), "computer", lambda self, fresh=False: comp):
403                    self.assertEqual(cat.picture_default(True), "cpu", name)
404                self.assertEqual(bool(comp.new_card_note), note, name)
405                if note:
406                    text, nxt = comp.new_card_note
407                    self.assertIn("new to Strata", text)
408                    self.assertIn("--vision off", nxt)
409                    self.assertIn("github.com/Niko1221/Strata/issues", nxt)
410
411    def test_a_mac_defaults_pictures_to_the_metal_reader_whatever_its_memory(self):
412        for gb in (16.0, 32.0, 128.0):
413            hw = {"ram_gb": gb, "os": "Darwin", "cpu": {"avx2": None, "name": "Apple M4"},
414                  "mac": {"chip": "Apple M4", "macos": "27.2", "unified_gb": gb},
415                  "gpus": [{"index": 0, "name": "Apple M4", "vendor": "apple", "vram_gb": 0.0, "unified_gb": gb, "usable": True}]}
416            with Home():
417                cat = catalog(hw)
418                with mock.patch.object(type(cat), "reader_state", lambda self: "present"):
419                    self.assertTrue(cat.is_mac())
420                    self.assertEqual(cat.picture_default(True), "gpu", gb)
421                    r = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768), catalog=cat)
422                    with mock.patch.object(sys, "platform", "darwin"):
423                        args = r.setup_args()
424                    self.assertEqual(args[args.index("--vision") + 1], "gpu", gb)
425                with mock.patch.object(type(cat), "reader_state", lambda self: "missing"):
426                    self.assertEqual(cat.picture_default(True), "off")
427
428    def test_a_model_that_cannot_read_pictures_stays_off_without_a_question(self):
429        import dataclasses
430        with Home():
431            cat = catalog(HW_12)
432            real = cat.rows()
433            rows = [dataclasses.replace(r, images=False) for r in real]
434            with mock.patch.object(type(cat), "rows", lambda self, *a, **k: rows):
435                r = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768), catalog=cat)
436                self.assertEqual(r.resolved_vision(), "off")
437
438    def test_an_engine_without_the_reader_defaults_to_off(self):
439        with Home():
440            cat = catalog(HW_12)
441            with mock.patch.object(type(cat), "reader_state", lambda self: "missing"):
442                self.assertEqual(cat.picture_default(True), "off")
443
444    def test_the_command_defaults_pictures_on_and_off_still_turns_them_off(self):
445        from strata_cli.launch.cmd import apply_defaults
446        with Home():
447            cat = catalog(HW_12)
448            s, _ = apply_defaults(S.LaunchSettings(family="qwen", model="IQ3_XXS"), cat)
449            self.assertEqual(s.vision, "cpu")                                 # a 12 GB card: pictures ON, read on the CPU
450            s, _ = apply_defaults(S.LaunchSettings(family="qwen", model="IQ3_XXS", vision="gpu"), cat)
451            self.assertEqual(s.vision, "gpu")                                 # what was asked for is kept
452            s, _ = apply_defaults(S.LaunchSettings(family="qwen", model="IQ3_XXS", vision="off"), cat)
453            self.assertEqual(s.vision, "off")
454
455    def test_a_disk_warning_is_not_shown_for_files_used_where_they_are_and_reads_once(self):
456        import dataclasses
457        from strata_cli.launch.cmd import apply_defaults
458        with Home():
459            cat = catalog(HW_12)
460            real = cat.rows()
461            rows = [dataclasses.replace(r, verdict="tight", words="tight: needs more disk space") for r in real]
462            with mock.patch.object(type(cat), "rows", lambda self, *a, **k: rows):
463                _, notes = apply_defaults(S.LaunchSettings(family="qwen", model="IQ3_XXS", model_path="/x"), cat)
464                self.assertFalse([n for n in notes if "tight" in n.text], notes)
465                _, notes = apply_defaults(S.LaunchSettings(family="qwen", model="IQ3_XXS"), cat)
466                text = " ".join(n.text for n in notes)
467                self.assertIn("is a tight fit: needs more disk space.", text)
468                self.assertNotIn("tight: tight", text)
469
470    def test_the_apps_own_installer_arguments(self):
471        import tempfile
472        own = tempfile.mkdtemp()
473        self.addCleanup(shutil.rmtree, own, True)
474        a = self.runner(data_dir="/d", model_path=own, gpus=[1])
475        self.assertEqual(a[:8], ["--yes", "--no-start", "--family", "qwen", "--model", "IQ3_XXS", "--context", "32768"])
476        for pair in (["--vision", "no"], ["--kv", "q4_0"], ["--experimental-speed-projection", "off"], ["--data-dir", "/d"], ["--gguf-dir", own],
477                     ["--gpu", "1"]):
478            self.assertIn(pair[0], a)
479            self.assertEqual(a[a.index(pair[0]) + 1], pair[1])
480        self.assertIn("--set-default-data-dir", a)             # a folder the person chose is the remembered one (the app and the next start use it)
481
482    def test_a_mac_gets_only_the_options_its_setup_knows(self):
483        with mock.patch.object(sys, "platform", "darwin"):
484            a = self.runner(data_dir="/d", gpus=[0])
485        self.assertEqual(a, ["--yes", "--no-start", "--family", "qwen", "--model", "IQ3_XXS", "--context", "32768", "--vision", "no", "--data-dir", "/d",
486                             "--set-default-data-dir"])
487
488
489class AdoptRules(unittest.TestCase):
490    def setUp(self):
491        from tests.terminal.launch_support import not_intel
492        not_intel(self)
493
494    def files(self, root: Path, shards=2, pack=True, tokenizer=True, mtp=True):
495        d = root / "Strata-data"
496        m = d / "models" / "IQ3_XXS"
497        m.mkdir(parents=True)
498        for i in range(1, shards + 1):
499            (m / f"Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-0000{i}-of-0000{shards}.gguf").write_bytes(b"GGUF")
500        p = d / "packs" / "iq3_xxs"
501        p.mkdir(parents=True)
502        if pack:
503            (p / "experts.bin").write_bytes(b"x")
504        if tokenizer:
505            (p / "tokenizer").mkdir()
506        if mtp:
507            (d / "mtp" / "rt").mkdir(parents=True)
508        return d, m
509
510    def test_setup_detection(self):
511        from strata_cli.launch import adopt
512        self.assertTrue(adopt.setup_cannot_handle_this_card("no NVIDIA GPU found (nvidia-smi did not answer)"))
513        self.assertTrue(adopt.setup_cannot_handle_this_card("no AMD GPU Strata can use"))
514        self.assertFalse(adopt.setup_cannot_handle_this_card("not enough free disk space in /x"))
515
516    def test_find_shards_needs_the_whole_set(self):
517        from strata_cli.launch import adopt
518        with Home() as h:
519            d, m = self.files(h.base)
520            self.assertEqual(len(adopt.find_shards(m)), 2)
521            (m / "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf").unlink()
522            self.assertEqual(adopt.find_shards(m), [])
523
524    def test_plan_writes_the_settings_setup_would(self):
525        from strata_cli.launch import adopt
526        with Home() as h:
527            d, m = self.files(h.base)
528            src = Path(__file__).resolve().parents[2]
529            cfg, problems = adopt.plan(family="qwen", model="IQ3_XXS", model_dir=m, data_dir=d, src=src, context=32768, kv=None,
530                                       model_name="qwen3.8-flash-next-iq3_xxs", family_def={}, log=h.base / "x.log", backend="sycl")
531            self.assertEqual(problems, [])
532            a = cfg["args"]
533            self.assertEqual(a[a.index("--max-context") + 1], "32768")
534            self.assertEqual(a[a.index("--kv") + 1], "int8")
535            self.assertIn("--ple-gguf", a)
536            self.assertIn("--mtp", a)
537            self.assertEqual((cfg["exe"], cfg["backend"]), ("component:strata-engine", "sycl"))
538            self.assertTrue(cfg["tokenizer"].endswith("tokenizer"))
539
540    def test_plan_intel_flags_follow_the_driver(self):
541        from unittest import mock
542        from strata_cli.launch import adopt
543        for driver, want, other in (("i915", ["--ple-io", "ram"], "--stream-experts"), ("xe", ["--stream-experts"], "--ple-io")):
544            with Home() as h, mock.patch.object(adopt, "intel_driver", return_value=driver):
545                d, m = self.files(h.base)
546                for ctx, reserve in ((32768, "1024"), (65536, "2048")):
547                    cfg, problems = adopt.plan(family="qwen", model="IQ3_XXS", model_dir=m, data_dir=d, src=Path(__file__).resolve().parents[2],
548                                               context=ctx, kv=None, model_name="x", family_def={}, log=h.base / "x.log", backend="sycl")
549                    self.assertEqual(problems, [])
550                    a = cfg["args"]
551                    for w in want:
552                        self.assertIn(w, a)
553                    self.assertNotIn(other, a)
554                    self.assertEqual(a[a.index("--vram-reserve-mib") + 1], reserve)
555
556    def test_intel_arc_is_read_from_the_kernel_and_gets_a_small_context(self):
557        from strata_cli.launch import catalog as C
558        with Home() as h:
559            card = h.base / "drm" / "card0" / "device"
560            card.mkdir(parents=True)
561            (card / "vendor").write_text("0x8086")
562            (card / "device").write_text("0x56a1")
563            cards = C.intel_arc_cards(str(h.base / "drm"))
564            self.assertEqual([(c["name"], c["vram_gb"]) for c in cards], [("Intel Arc A750", 8.0)])
565            self.assertEqual(C.intel_arc_cards(str(h.base / "nothing")), [])
566            hw = dict(HW_12)
567            hw["gpus"] = cards
568            cat = catalog(hw)
569            self.assertEqual(cat.computer().line().split(" 8 GB")[0], "Arc A750".replace("Arc", "Intel Arc"))
570            self.assertEqual(cat.max_context("qwen", "IQ3_XXS", hw), 131072)      # an 8 GB Arc too: warned about, never lowered
571            hw["gpus"] = [{"vendor": "intel", "name": "Intel Arc Pro B70", "vram_gb": 32.0, "usable": True}]
572            self.assertEqual(cat.max_context("qwen", "IQ3_XXS", hw), 131072)
573
574    def test_plan_names_what_is_missing(self):
575        from strata_cli.launch import adopt
576        with Home() as h:
577            d, m = self.files(h.base, pack=False, tokenizer=False)
578            cfg, problems = adopt.plan(family="qwen", model="IQ3_XXS", model_dir=m, data_dir=d, src=Path(__file__).resolve().parents[2], context=8192,
579                                       kv=None, model_name="x", family_def={}, log=h.base / "x.log", backend=None)
580            self.assertIsNone(cfg)
581            self.assertTrue(any("prepared pack" in p for p in problems))
582            self.assertTrue(any("tokenizer" in p for p in problems))
583            cfg, problems = adopt.plan(family="nvfp4", model="NVFP4", model_dir=m, data_dir=d, src=Path("."), context=8192, kv=None, model_name="x",
584                                       family_def={}, log=h.base / "x.log", backend=None)
585            self.assertIn("only for the Qwen3.8-Flash-Next", problems[0])
586            self.assertNotIn("..", problems[0] + ".")                           # round 8, N11: the caller adds the full stop
587
588    def test_pictures_on_is_setups_yes_and_setup_picks_the_encoder(self):
589        with Home() as h:
590            cat = catalog(HW_12)
591            for vision, want in (("on", "yes"), ("off", "no"), ("gpu", "gpu"), ("cpu", "cpu")):
592                r = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", vision=vision), catalog=cat)
593                self.assertEqual(r.vision_word(), want, vision)
594            argv = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", vision="on"), catalog=cat).setup_args()
595            self.assertEqual(argv[argv.index("--vision") + 1], "yes")
596
597    def test_setup_control_mode_keeps_pictures_when_the_engine_carries_the_reader(self):
598        from types import SimpleNamespace
599        with Home() as h:
600            mod = catalog(HW_12).strata.setup_module()
601            if mod is None or not hasattr(mod, "control_engine_step"):
602                self.skipTest("no setup.py in this checkout")
603            engine = h.base / "engine"
604            engine.mkdir()
605            found = SimpleNamespace(root=engine, version="0.1.45", backend="cuda", platform="linux-x86_64")
606            with mock.patch.object(mod, "get_llama_cpp", return_value=engine), mock.patch("strata_control.engine_component.resolve", return_value=found):
607                self.assertEqual(mod.control_engine_step({}, "cpu")[5], "none")           # no strata-vision beside the engine: off, with a note
608                (engine / mod.VEXE).write_text("x")
609                self.assertEqual(mod.control_engine_step({}, "cpu")[5], "cpu")            # the component carries it: the choice is kept
610                self.assertEqual(mod.control_engine_step({}, "none")[5], "none")
611
612    def test_turning_pictures_on_for_an_installed_model_downloads_only_the_reader(self):
613        with Home() as h:
614            cat = catalog(HW_12)
615            cfgfile = h.base / "strata-x.json"
616            cfgfile.write_text("{}")
617            for vision, images, ctx, want in (("on", "off", 32768, 0.9), ("on", "cpu", 32768, 0.0), ("off", "off", 32768, 0.0), ("off", "off", 65536, 0.0)):
618                r = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", vision=vision, context=ctx), catalog=cat)
619                desc = {"context": 32768, "kv": "int8", "images": images}
620                with mock.patch.object(r, "installed_state", return_value=(cfgfile, desc)):
621                    self.assertAlmostEqual(r.download_gb(), want, msg=(vision, images, ctx))
622
623    def test_a_missing_picture_reader_file_is_fetched_again(self):
624        from strata_cli.launch.runner import files_present
625        with Home() as h:
626            mm = h.base / "mmproj-x.gguf"
627            cfg = {"args": [], "vision": {"mmproj": str(mm)}}
628            self.assertEqual(files_present(cfg), [str(mm)])
629            mm.write_text("x")
630            self.assertEqual(files_present(cfg), [])
631            mm.unlink()
632            cat = catalog(HW_12)
633            cfgfile = h.base / "strata-x.json"
634            cfgfile.write_text(json.dumps(cfg))
635            r = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", vision="on", context=32768), catalog=cat)
636            with mock.patch.object(r, "installed_state", return_value=(cfgfile, {"context": 32768, "kv": "int8", "images": "cpu"})):
637                self.assertAlmostEqual(r.download_gb(), 0.9)
638
639    def test_the_cards_of_this_launch_go_into_its_config_without_reinstalling(self):
640        from tests.terminal.launch_support import HW_2X16
641        from strata_cli.launch.runner import apply_cards, cards_for_launch
642        from strata_control import tune_knobs
643        base = {"exe": "component:strata-engine", "args": ["--max-context", "32768"], "gpu": 0, "port": 8080}
644        with Home() as h:
645            # an installed single-card config, then the split chosen now
646            cfg = derive_config(base, S.LaunchSettings(), bool_flags=tune_knobs.BOOL_FLAGS, gpus=[0, 1])
647            self.assertEqual((cfg["gpu"], cfg["layer_split"]), ([0, 1], "auto"))
648            self.assertTrue(cfg["gpus_asked"])
649            # an installed split config, then one named card now
650            split_base = {**base, "gpu": [0, 1], "layer_split": "auto"}
651            cfg = derive_config(split_base, S.LaunchSettings(), bool_flags=tune_knobs.BOOL_FLAGS, gpus=[1])
652            self.assertEqual(cfg["gpu"], 1)
653            self.assertNotIn("layer_split", cfg)
654            # nothing chosen and nothing to recommend: the installed choice stays
655            cfg = derive_config(split_base, S.LaunchSettings(), bool_flags=tune_knobs.BOOL_FLAGS)
656            self.assertEqual(cfg["gpu"], [0, 1])
657            self.assertEqual(base["gpu"], 0)                                   # the installed config itself is never changed
658            aged = derive_config({**base, "backend": "hip", "hip_ordinal": 1}, S.LaunchSettings(), bool_flags=tune_knobs.BOOL_FLAGS, gpus=[0])
659            self.assertNotIn("hip_ordinal", aged)                              # a card named now is not overruled by an old config's ordinal
660            # which cards: named ones win (one card too: --gpu 1 on a box that has them), else the fit rule on a box with several cards
661            two = catalog(HW_2X16)
662            self.assertEqual(cards_for_launch(S.LaunchSettings(family="qwen", model="IQ3_XXS", gpus=[1, 0]), two), [1, 0])
663            self.assertEqual(cards_for_launch(S.LaunchSettings(family="qwen", model="IQ3_XXS"), two), [0, 1])     # roles: card 0 Main (last), card 1 Helper
664            one = catalog(HW_12)
665            self.assertEqual(cards_for_launch(S.LaunchSettings(family="qwen", model="IQ3_XXS", gpus=[1]), one), [1])
666            self.assertIsNone(cards_for_launch(S.LaunchSettings(family="qwen", model="IQ3_XXS"), one))
667            # the launch's own config is written with them (Runner.build_config), the installed file is untouched
668            import json
669            installed = h.base / "strata-iq3_xxs.json"
670            installed.write_text(json.dumps(base))
671            r = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", name="cards", gpus=[1]), catalog=two)
672            out = r.build_config(installed)
673            self.assertEqual(json.loads(out.read_text())["gpu"], 1)
674            self.assertEqual(json.loads(installed.read_text())["gpu"], 0)
675
676    def test_a_card_the_installed_model_was_set_to_is_not_replaced_by_the_automatic_pick(self):
677        """Two equal cards: the fit rule recommends card 0, so a person's earlier choice (setup --gpu 1, the app's card pick: "gpus_asked")
678        must survive a `strata launch` that names no cards - in its order, with "gpu_order": "as_given" too."""
679        import json
680        from tests.terminal.launch_support import HW_2X16
681        from strata_cli.launch.runner import cards_for_launch, installed_cards
682        with Home() as h:
683            two = catalog(HW_2X16)
684            plain = S.LaunchSettings(family="qwen", model="IQ3_XXS")
685            chosen = {"exe": "component:strata-engine", "args": ["--max-context", "32768"], "gpu": 1, "gpus_asked": True, "port": 8080}
686            self.assertEqual(installed_cards(chosen), [1])
687            self.assertEqual(installed_cards({**chosen, "gpu": [1, 0], "gpu_order": "as_given"}), [1, 0])
688            self.assertEqual(installed_cards({**chosen, "gpu": "1,0"}), [1, 0])
689            self.assertIsNone(installed_cards({**chosen, "gpus_asked": False}))               # never asked: setup's default, not a choice
690            self.assertIsNone(installed_cards({"gpu": 1}))
691            self.assertIsNone(cards_for_launch(plain, two, base=chosen))                      # the installed choice stays
692            self.assertEqual(cards_for_launch(plain, two, base={**chosen, "gpus_asked": False}), [0, 1])    # no choice recorded: the recommended roles
693            self.assertEqual(cards_for_launch(S.LaunchSettings(family="qwen", model="IQ3_XXS", gpus=[0]), two, base=chosen), [0])   # --gpu 0 wins
694            if True:
695                installed = h.base / "strata-iq3_xxs.json"
696                for gpu, extra in ((1, {}), ([1, 0], {"gpu_order": "as_given", "layer_split": "auto"})):
697                    base = {**chosen, "gpu": gpu, **extra}
698                    installed.write_text(json.dumps(base))
699                    r = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", name="keep"), catalog=two)
700                    cfg = json.loads(r.build_config(installed).read_text())
701                    self.assertEqual(cfg["gpu"], gpu)
702                    self.assertEqual(cfg.get("gpu_order"), extra.get("gpu_order"))
703
704    def test_pictures_asked_but_still_off_is_said_in_plain_words(self):
705        with Home() as h:
706            cat = catalog(HW_12)
707            seen = []
708            r = Runner(S.LaunchSettings(family="qwen", model="IQ3_XXS", vision="on"), catalog=cat, emit=seen.append)
709            path = h.base / "cfg.json"
710            path.write_text("{}")
711            with mock.patch.object(cat.strata, "describe_config", return_value={"images": "off"}):
712                r.check_pictures(path)
713            self.assertTrue(any("Pictures could not be switched on" in e.text and e.level == "warn" for e in seen))
714            seen.clear()
715            with mock.patch.object(cat.strata, "describe_config", return_value={"images": "cpu"}):
716                r.check_pictures(path)
717            self.assertEqual(seen, [])
718
719    def test_tuning_that_found_the_standard_settings_fastest_is_not_run_again(self):
720        # "already fastest" saves no tuning preset, only tuned_at: the next start (a container restart with TUNE=quick) must not measure for 20 minutes again
721        with Home():
722            seen = []
723            s = S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, tune="quick", tuned_at="2026-10-20")
724            self.assertTrue(s.is_tuned)
725            r = Runner(s, catalog=catalog(HW_12), emit=seen.append)
726            with mock.patch.object(r, "_spawn", side_effect=AssertionError("tuned again")):
727                r.tune()
728            self.assertTrue(any("Already tuned on 2026-10-20" in e.text for e in seen))
729            self.assertFalse(S.LaunchSettings(tune="quick").is_tuned)
730            store.save(s, "Fastest")
731            self.assertTrue(store.summary(store.load("Fastest"))["tuned"])
732
733    def test_runner_adopts_when_setup_cannot_handle_the_card(self):
734        # the engine make is read from the machine (adopt_prepared_files asks engine_component.detect_backend); on a box with an Intel Arc the
735        # second launch below would be refused as an Intel one. This case is the "no NVIDIA driver" one.
736        with Home() as h, mock.patch("strata_control.engine_component.detect_backend", lambda environ=None: ("cuda", "test")):
737            d, m = self.files(h.base)
738            cat = catalog(HW_12)
739            s = S.LaunchSettings(family="qwen", model="IQ3_XXS", context=32768, data_dir=str(d))
740            r = Runner(s, catalog=cat)
741            path = r.adopt_prepared_files("no NVIDIA GPU found (nvidia-smi did not answer)")
742            self.assertTrue(path.is_file())
743            self.assertTrue(r.notices and "wrote the run settings itself" in r.notices[0])
744            self.assertIsNone(r.adopt_prepared_files("not enough free disk space"))
745            from strata_cli.launch.runner import LaunchError
746            r2 = Runner(S.LaunchSettings(family="qwen", model="IQ3_S", context=32768, data_dir=str(d)), catalog=cat)
747            with self.assertRaises(LaunchError) as e:
748                r2.adopt_prepared_files("no NVIDIA GPU found")
749            self.assertIn("cannot set up this graphics card yet", e.exception.text)
750
751
752class AccessRules(unittest.TestCase):
753    def test_hosts_and_keys(self):
754        self.assertEqual(access.host_for("local"), "127.0.0.1")
755        self.assertEqual(access.host_for("cloudflare"), "127.0.0.1")
756        self.assertEqual(access.host_for("lan"), "0.0.0.0")
757        self.assertTrue(access.new_key().startswith("sk-strata-"))
758        self.assertNotIn(access.new_key(), access.mask_key(access.new_key()))
759        self.assertEqual(access.mask_key(None), "off")
760
761    def test_private_ranges(self):
762        for ip in ("10.1.2.3", "192.168.88.21", "172.16.0.9", "100.101.1.1"):
763            self.assertTrue(access._is_private(ip), ip)
764        for ip in ("8.8.8.8", "172.32.0.1", "1.2.3.4"):
765            self.assertFalse(access._is_private(ip), ip)
766
767    def test_missing_helpers_say_how_to_install(self):
768        with mock.patch.object(access, "find_cloudflared", return_value=None):
769            msg = access.missing_helper("cloudflare")
770            self.assertIn("cloudflared is not installed", msg)
771            self.assertIn("quick tunnel", msg)
772        with mock.patch.object(access, "find_tailscale", return_value=None):
773            self.assertIn("Tailscale is not installed", access.missing_helper("tailscale"))
774        with mock.patch.object(access, "tailscale_status", return_value={"installed": True, "running": False, "ip": None, "name": None}):
775            self.assertIn("tailscale up", access.missing_helper("tailscale"))
776        self.assertIsNone(access.missing_helper("local"))
777
778    def test_options_and_urls(self):
779        with mock.patch.object(access, "lan_ips", return_value=["192.168.1.5"]), \
780                mock.patch.object(access, "find_cloudflared", return_value="/bin/cloudflared"), \
781                mock.patch.object(access, "tailscale_status", return_value={"installed": True, "running": True, "ip": "100.64.0.1", "name": "pc.tail.ts.net"}):
782            opts = {o.kind: o for o in access.options(8080)}
783            self.assertEqual(opts["lan"].url, "http://192.168.1.5:8080")
784            self.assertTrue(opts["cloudflare"].ready)
785            self.assertEqual(opts["tailscale"].url, "http://pc.tail.ts.net:8080")
786            urls = access.urls_for(S.LaunchSettings(access="lan", port=8080))
787            self.assertEqual(urls, ["http://127.0.0.1:8080", "http://192.168.1.5:8080"])
788            self.assertEqual(access.urls_for(S.LaunchSettings(access="cloudflare", port=8080), tunnel_url="https://a.trycloudflare.com")[0],
789                             "https://a.trycloudflare.com")
790
791    def test_the_windows_firewall_question_is_announced_before_it_happens(self):
792        with mock.patch.object(access, "WINDOWS", True):
793            self.assertIn("choose Allow for private networks", access.firewall_note("lan"))
794            self.assertIn("still works on this computer", access.firewall_note("tailscale"))
795            self.assertIsNone(access.firewall_note("local"))
796            self.assertIsNone(access.firewall_note("cloudflare"))
797        with mock.patch.object(access, "WINDOWS", False):
798            self.assertIsNone(access.firewall_note("lan"))
799
800    def test_helper_output_filter_drops_login_lines(self):
801        self.assertEqual(access.filter_line("Please open this URL to login: https://dash.cloudflare.com/argotunnel?token=abc"), "")
802        self.assertEqual(access.filter_line("Your quick Tunnel has been created: https://x.trycloudflare.com"),
803                         "Your quick Tunnel has been created: https://x.trycloudflare.com")
804        self.assertEqual(access.TUNNEL_URL.search("| https://calm-river-1234.trycloudflare.com |").group(0),
805                         "https://calm-river-1234.trycloudflare.com")
806
807
808# a person at Git Bash: no CI variable (a CI runner sets one, and strata launch then never asks) and no STRATA_NO_PROMPT
809GIT_BASH_ENV = {"MSYSTEM": "MINGW64", "CI": "", "STRATA_NO_PROMPT": ""}
810
811
812class FlagsCommand(unittest.TestCase):
813    """Every `strata launch` flag, run through the real parser with the computer faked and nothing installed."""
814
815    def setUp(self):
816        self.home = Home().__enter__()
817        self.addCleanup(self.home.__exit__, None, None, None)
818        p = mock.patch.object(Catalog, "hardware", lambda self, fresh=False: dict(HW_12, disk_free_gb=500.0))
819        p.start()
820        self.addCleanup(p.stop)
821
822    def plan(self, *args):
823        code, out, err = run_cli(["launch", "--plan", "--output", "json", *args])
824        self.assertEqual(code, 0, err or out)
825        return json.loads(out)["plan"]
826
827    def test_help_lists_everything_with_examples(self):
828        code, out, err = run_cli(["launch", "--help"])
829        self.assertEqual(code, 0)
830        for flag in ("--preset", "--model", "--family", "--model-path", "--data-dir", "--context", "--kv", "--vision", "--parallel", "--gpu",
831                     "--tune", "--tune-allow-small", "--set", "--access", "--port", "--api-key", "--api-key-env", "--new-key", "--save-preset",
832                     "--no-tui", "--plan", "--feed", "--list-presets", "--delete-preset", "--status", "--stop", "--show-key", "examples:"):
833            self.assertIn(flag, out)
834        code, out, _ = run_cli(["--help"])
835        self.assertIn("launch", out)
836        self.assertIn("connect", out)
837
838    def test_mtp_flag_is_listed_planned_and_copyable(self):
839        code, out, err = run_cli(["launch", "--help"])
840        self.assertIn("--mtp", out)
841        p = self.plan("--model", "q2_0", "--context", "32k", "--vision", "off", "--mtp", "off")
842        self.assertEqual(p["settings"]["mtp"], "off")
843        self.assertIn("--mtp off", p["flags"])
844        code, out, err = run_cli(["launch", "--plan", "--mtp", "maybe"])
845        self.assertNotEqual(code, 0)
846
847    def test_vision_help_says_the_picture_rule(self):
848        code, out, err = run_cli(["launch", "--help"])
849        text = " ".join(out.split())
850        self.assertIn("CPU reader under 24 GB", text)
851        self.assertIn("GPU reader from 24 GB", text)
852        self.assertIn("off turns pictures off", text)
853        self.assertNotIn("for NVIDIA and AMD", text)
854
855    def test_model_context_parallel_vision_tune_access_port(self):
856        p = self.plan("--model", "iq3_xxs", "--context", "128k", "--parallel", "2", "--vision", "off", "--tune", "quick", "--access", "lan",
857                      "--port", "9090")
858        s = p["settings"]
859        self.assertEqual((s["family"], s["model"], s["context"], s["parallel"], s["vision"], s["tune"], s["access"], s["port"]),
860                         ("qwen", "IQ3_XXS", 131072, 2, "off", "quick", "lan", 9090))
861        self.assertEqual(s["api_key"], "set")                               # shared beyond this computer: a key was made
862        self.assertTrue(any("2 requests" in w and "12 GB" in w for w in p["warnings"]))
863
864    def test_defaults_come_from_the_recommendation(self):
865        p = self.plan()
866        s = p["settings"]
867        self.assertEqual((s["family"], s["model"], s["context"], s["access"], s["tune"]), ("qwen", "IQ3_S", 131072, "local", "skip"))
868        self.assertTrue(any("picked" in w for w in p["warnings"]))
869
870    def test_family_and_kv_and_gpu_and_data_dir_and_set(self):
871        p = self.plan("--model", "iq3_xxs", "--family", "swift", "--kv", "q4_0", "--gpu", "0,1", "--data-dir", str(self.home.base / "data-x"),
872                      "--set", "prefill=65536", "--set", "STRATA_PIN_BY_NEED=1", "--tune-allow-small")
873        s = p["settings"]
874        self.assertEqual((s["family"], s["kv"], s["gpus"], s["data_dir"], s["tune_allow_small"]), ("swift", "q4_0", [0, 1], str(self.home.base / "data-x"), True))
875        self.assertEqual(s["extra"], {"--prefill": "65536", "STRATA_PIN_BY_NEED": "1"})
876        self.assertIn("--set prefill=65536", p["flags"])
877
878    def test_pool_cores_is_an_experimental_advanced_setting(self):
879        code, out, err = run_cli(["launch", "--help"])
880        self.assertIn("--pool-cores", out)
881        p = self.plan("--model", "q2_0", "--pool-cores", "2,4, 6,8")
882        self.assertEqual(p["settings"]["extra"], {"--pool-cores": "2,4,6,8"})
883        self.assertIn("--set pool-cores=2,4,6,8", p["flags"])                # the copyable line says the same
884        p = self.plan("--model", "q2_0", "--pool-cores", "2-14:2")
885        self.assertEqual(p["settings"]["extra"], {"--pool-cores": "2-14:2"})
886        p = self.plan("--model", "q2_0")                                    # off by default: nothing is added
887        self.assertNotIn("--pool-cores", p["settings"]["extra"])
888        p = self.plan("--model", "q2_0", "--pool-cores", "two,four")        # a list that cannot be read: a warning, never a refusal
889        self.assertNotIn("--pool-cores", p["settings"]["extra"])
890        self.assertTrue(any("pool-cores" in w for w in p["warnings"]))
891
892    def test_api_key_flags(self):
893        p = self.plan("--model", "q2_0", "--access", "lan", "--api-key", "sk-mine")
894        self.assertEqual(p["settings"]["api_key"], "set")
895        self.assertFalse(any("new API key was made" in w for w in p["warnings"]))
896        with mock.patch.dict(os.environ, {"MY_KEY": "sk-env"}):
897            p = self.plan("--model", "q2_0", "--api-key-env", "MY_KEY")
898            self.assertEqual(p["settings"]["api_key"], "set")
899        code, out, err = run_cli(["launch", "--plan", "--api-key-env", "NOT_SET_ANYWHERE"])
900        self.assertEqual(code, 2)
901        self.assertIn("NOT_SET_ANYWHERE", err)
902        p = self.plan("--model", "q2_0", "--new-key")
903        self.assertEqual(p["settings"]["api_key"], "set")
904
905    def test_no_api_key_flag(self):
906        p = self.plan("--model", "q2_0", "--access", "lan", "--no-api-key")
907        self.assertIsNone(p["settings"]["api_key"])
908        self.assertFalse(any("new API key was made" in w for w in p["warnings"]))
909        self.assertTrue(any("anyone who can reach this port can use the model and its tools" in w for w in p["warnings"]))
910        p = self.plan("--model", "q2_0", "--access", "cloudflare", "--no-api-key")
911        self.assertTrue(any("public address" in w and "anyone on the internet" in w for w in p["warnings"]))
912        p = self.plan("--model", "q2_0", "--access", "local", "--no-api-key")
913        self.assertEqual([w for w in p["warnings"] if "API key" in w], [])
914        # scripts that name LAN without a key flag keep getting a key, as before
915        p = self.plan("--model", "q2_0", "--access", "lan", "--yes")
916        self.assertEqual(p["settings"]["api_key"], "set")
917        self.assertFalse(any("new API key was made" in w for w in p["warnings"]))      # the plan writes nothing: the launch says it when the key is on disk (QATUI, 11-04)
918        # a key given as well wins over --no-api-key, with a note
919        p = self.plan("--model", "q2_0", "--access", "lan", "--api-key", "sk-a", "--no-api-key")
920        self.assertEqual(p["settings"]["api_key"], "set")
921
922    def test_model_path_is_used_instead_of_a_catalog_model(self):
923        import tempfile
924        from tests.terminal.test_own_files import IQ3XXS, gguf_bytes
925        with tempfile.TemporaryDirectory() as tmp:
926            folder = Path(tmp) / "IQ3_XXS"
927            folder.mkdir()
928            for n in IQ3XXS:
929                (folder / n).write_bytes(gguf_bytes(["IQ3_XXS"]))
930            s = self.plan("--model-path", str(folder))["settings"]
931        self.assertEqual(s["model_path"], str(folder))
932        self.assertEqual((s["family"], s["model"]), ("qwen", "IQ3_XXS"))      # the files say which model they are
933
934    def test_no_choices_and_no_terminal_does_not_start_anything(self):
935        with mock.patch.dict(os.environ, {"CI": "1"}), mock.patch.object(Runner, "run", side_effect=AssertionError("must not run")):
936            code, out, err = run_cli(["launch"])
937        self.assertEqual(code, 2)
938        self.assertIn("not a terminal", err)
939        self.assertIn("--preset NAME", err)
940
941    def test_git_bash_without_a_tty_goes_on_in_plain_questions(self):
942        fake = Result("launch-x", ["http://127.0.0.1:8080"], None, None, [], "/x")
943        with mock.patch.dict(os.environ, GIT_BASH_ENV), mock.patch("builtins.input", return_value="y"),                 mock.patch.object(Runner, "run", return_value=fake) as run:
944            code, out, err = run_cli(["launch"])
945        self.assertEqual(code, 0, err)
946        run.assert_called_once()
947        self.assertIn("cannot show Strata's screens", out + err)
948        self.assertIn("winpty strata launch", out + err)
949
950    def test_git_bash_answering_no_changes_nothing(self):
951        with mock.patch.dict(os.environ, GIT_BASH_ENV), mock.patch("builtins.input", return_value="n"),                 mock.patch.object(Runner, "run", side_effect=AssertionError("must not run")):
952            code, out, err = run_cli(["launch"])
953        self.assertEqual(code, 0, err)
954        self.assertIn("Nothing was changed", out + err)
955
956    def test_a_pipe_with_nobody_to_answer_still_says_what_to_name(self):
957        with mock.patch.dict(os.environ, GIT_BASH_ENV), mock.patch("builtins.input", side_effect=EOFError),                 mock.patch.object(Runner, "run", side_effect=AssertionError("must not run")):
958            code, out, err = run_cli(["launch"])
959        self.assertEqual(code, 2)
960        self.assertIn("--preset NAME", err)
961
962    def test_unknown_model_names_the_closest_one(self):
963        code, out, err = run_cli(["launch", "--plan", "--model", "iq3xxs"])
964        self.assertEqual(code, 2)
965        self.assertIn("Did you mean 'IQ3_XXS'", err)
966        self.assertNotIn("Traceback", err)
967
968    def test_unknown_flag_names_the_closest_one(self):
969        code, out, err = run_cli(["launch", "--modle", "iq3_xxs"])
970        self.assertEqual(code, 2)
971        self.assertIn("Did you mean '--model'", err)
972
973    def test_bad_values_are_plain_sentences(self):
974        for argv, word in ((["--tune", "quik"], "quick"), (["--access", "lann"], "lan"), (["--context", "huge"], "context"),
975                           (["--port", "99999"], "1 to 65535"), (["--parallel", "12"], "1 to 8"), (["--vision", "maybe"], "off")):
976            code, out, err = run_cli(["launch", "--plan", *argv])
977            self.assertEqual(code, 2, argv)
978            self.assertIn(word, err, argv)
979
980    def test_preset_with_flags_on_top(self):
981        store.save(S.LaunchSettings(name="Office", family="qwen", model="IQ3_XXS", context=65536, parallel=2, access="local"))
982        p = self.plan("--preset", "Office", "--context", "128k")
983        s = p["settings"]
984        self.assertEqual((s["name"], s["context"], s["parallel"]), ("Office", 131072, 2))
985        code, out, err = run_cli(["launch", "--plan", "--preset", "Offce"])
986        self.assertEqual(code, 2)
987        self.assertIn("Did you mean 'Office'", err)
988
989    def test_vision_is_turned_off_for_a_model_without_pictures(self):
990        # every catalog model reads pictures now (Gyro and NVFP4-QAD too): a row that does not stands in for a future one
991        import dataclasses
992        real_rows = Catalog.rows
993
994        def rows(self, *args, **kwargs):
995            return [dataclasses.replace(r, images=False) if r.model == "Gyro-S" else r for r in real_rows(self, *args, **kwargs)]
996
997        with mock.patch.object(Catalog, "rows", rows):
998            p = self.plan("--model", "gyro-s", "--vision", "on")
999        self.assertEqual(p["settings"]["vision"], "off")
1000        self.assertTrue(any("cannot read pictures" in w for w in p["warnings"]))
1001
1002    def test_does_not_fit_is_a_warning_with_the_reason(self):
1003        p = self.plan("--model", "q8_0")                                  # 129 GB of weights against 64 GB of RAM + a 12 GB card
1004        self.assertTrue(any(w.endswith(": may run slower.") for w in p["warnings"]), p["warnings"])
1005        p = self.plan("--model", "iq3_s")                                 # 54.8 GB: fits
1006        self.assertFalse(any("may run slower" in w for w in p["warnings"]))
1007
1008    def test_human_plan_changes_nothing(self):
1009        code, out, err = run_cli(["launch", "--plan", "--model", "q2_0", "--save-preset", "X"])
1010        self.assertEqual(code, 0)
1011        self.assertIn("Nothing was changed.", out)
1012        self.assertEqual(store.list_presets(), [])
1013
1014    def test_the_access_help_names_the_flags_for_showing_and_setting_a_key(self):             # #3713 #3951
1015        from strata_cli.launch import screens
1016        self.assertIn("strata launch --show-key", screens.AccessScreen.help_text)
1017        self.assertIn("--api-key YOUR-KEY", screens.AccessScreen.help_text)
1018
1019    def test_the_summary_says_where_the_engine_log_is(self):                                  # #3656
1020        import tempfile
1021        with tempfile.TemporaryDirectory() as d:
1022            cfg = Path(d) / "x.json"
1023            cfg.write_text(json.dumps({"log": str(Path(d) / "office.engine.log"), "args": []}), encoding="utf-8")
1024            fake = Result(profile="launch-office", urls=["http://127.0.0.1:8080"], key=None, tune_word=None, notices=[], config=str(cfg))
1025            with mock.patch.object(Runner, "run", return_value=fake):
1026                code, out, err = run_cli(["launch", "--no-tui", "--model", "q2_0"])
1027        self.assertEqual(code, 0, err)
1028        self.assertIn("Engine log", out)
1029        self.assertIn("office.engine.log", out)
1030        self.assertIn("strata logs --follow", out)
1031
1032    def test_run_without_screens_prints_the_address_and_saves_the_preset(self):
1033        fake = Result(profile="launch-office", urls=["http://127.0.0.1:8080", "http://192.168.1.5:8080"], key="sk-strata-abcdefghijkl",
1034                      tune_word=None, notices=[], config="/x")
1035        with mock.patch.object(Runner, "run", return_value=fake):
1036            code, out, err = run_cli(["launch", "--no-tui", "--model", "q2_0", "--access", "lan", "--save-preset", "Office"])
1037        self.assertEqual(code, 0, err)
1038        self.assertIn("Strata is serving.", out)
1039        self.assertIn("http://127.0.0.1:8080/v1", out)
1040        self.assertIn("http://192.168.1.5:8080/v1", out)
1041        self.assertNotIn("sk-strata-abcdefghijkl", out)                      # the key is masked
1042        self.assertIn("strata connect", out)
1043        self.assertEqual([p.name for p in store.list_presets()], ["Office"])
1044        code, out, err = run_cli(["launch", "--list-presets"])
1045        self.assertIn("Office", out)
1046        code, out, _ = run_cli(["launch", "--show-key", "--preset", "Office"])
1047        self.assertEqual(code, 0)                                              # the preset's own key
1048        self.assertTrue(out.strip().startswith("sk-strata-"))
1049
1050    def test_a_setup_line_joined_after_the_model_could_not_be_installed_starts_with_a_capital(self):
1051        from strata_cli.launch.runner import setup_failure
1052        e = setup_failure([], "the model does not answer sensibly after the preparation: no answer", "", None, False)
1053        self.assertTrue(e.text.startswith("The model could not be installed. The model does not answer sensibly"), e.text)
1054
1055    def test_a_reason_joined_after_a_sentence_starts_with_a_capital(self):
1056        from strata_cli.launch.runner import capital
1057        self.assertEqual(capital("the update feed could not be read: no route"), "The update feed could not be read: no route")
1058        self.assertEqual(capital("Already fine."), "Already fine.")
1059        self.assertEqual(capital(""), "")
1060
1061    def test_launch_error_is_one_plain_sentence(self):
1062        from strata_cli.launch.runner import LaunchError
1063        with mock.patch.object(Runner, "run", side_effect=LaunchError("The engine could not be installed.", "Check your internet.", 6)):
1064            code, out, err = run_cli(["launch", "--no-tui", "--model", "q2_0"])
1065        self.assertEqual(code, 6)
1066        self.assertIn("The engine could not be installed. Check your internet.", err)
1067        self.assertNotIn("Traceback", err)
1068
1069    def test_list_delete_status_stop_without_anything_running(self):
1070        store.save(S.LaunchSettings(name="A", family="qwen", model="Q2_0", context=32768))
1071        code, out, _ = run_cli(["launch", "--list-presets"])
1072        self.assertIn("A", out)
1073        code, out, _ = run_cli(["launch", "--delete-preset", "A"])
1074        self.assertEqual(code, 0)
1075        self.assertIn("Models and tuning results were not touched", out)
1076        code, out, _ = run_cli(["launch", "--list-presets"])
1077        self.assertIn("No saved presets", out)
1078        code, out, _ = run_cli(["launch", "--status"])
1079        self.assertEqual(code, 0)
1080        self.assertIn("Nothing from `strata launch` is running.", out)
1081        code, out, _ = run_cli(["launch", "--stop"])
1082        self.assertEqual(code, 0)
1083        self.assertIn("Nothing", out)
1084        code, out, err = run_cli(["launch", "--delete-preset", "gone"])
1085        self.assertEqual(code, 2)
1086        self.assertIn("no saved preset", err)
1087
1088    def test_feed_flag_reaches_the_runner(self):
1089        seen = {}
1090
1091        def fake(self, *a, **k):
1092            seen["feed"] = self.feed
1093            return Result("launch-x", ["http://127.0.0.1:8080"], None, None, [], "/x")
1094
1095        with mock.patch.object(Runner, "run", fake):
1096            code, _, err = run_cli(["launch", "--no-tui", "--model", "q2_0", "--feed", "http://127.0.0.1:9/feed"])
1097        self.assertEqual(code, 0, err)
1098        self.assertEqual(seen["feed"], "http://127.0.0.1:9/feed")
1099
1100    def test_output_json_for_scripts(self):
1101        fake = Result("launch-x", ["http://127.0.0.1:8080"], "sk-k", "faster", ["a note"], "/x")
1102        with mock.patch.object(Runner, "run", return_value=fake):
1103            code, out, err = run_cli(["launch", "--no-tui", "--output", "json", "--model", "q2_0"])
1104        data = json.loads(out)
1105        self.assertTrue(data["ok"])
1106        self.assertEqual(data["urls"], ["http://127.0.0.1:8080"])
1107        self.assertEqual(data["api_key"], "set")                                # never the key itself
1108        self.assertEqual(data["tuned"], "faster")
1109
1110
1111class ConnectCommand(unittest.TestCase):
1112    def setUp(self):
1113        self.home = Home().__enter__()
1114        self.addCleanup(self.home.__exit__, None, None, None)
1115
1116    def test_list_and_unknown_names(self):
1117        code, out, _ = run_cli(["connect"])
1118        self.assertEqual(code, 0)
1119        for h in ("opencode", "codex", "claude-code", "omp", "pi", "hermes", "openclaw", "deepseek-harness"):
1120            self.assertIn(h, out)
1121        code, out, err = run_cli(["connect", "opncode"])
1122        self.assertEqual(code, 2)
1123        self.assertIn("Did you mean 'opencode'", err)
1124        code, out, _ = run_cli(["connect", "--output", "json"])
1125        self.assertEqual(len(json.loads(out)["harnesses"]), 8)
1126
1127    def test_prints_the_config_with_a_masked_key(self):
1128        code, out, err = run_cli(["connect", "opencode", "--url", "http://127.0.0.1:8123", "--key", "sk-strata-abcdefghij1234", "--model", "m1"])
1129        self.assertEqual(code, 0, err)
1130        self.assertIn("http://127.0.0.1:8123/v1", out)
1131        self.assertIn("opencode.json", out)
1132        self.assertIn("limit", out)
1133        self.assertNotIn("abcdefghij1234", out)
1134        code, out, _ = run_cli(["connect", "opencode", "--url", "http://127.0.0.1:8123", "--key", "sk-strata-abcdefghij1234", "--show-key"])
1135        self.assertIn("sk-strata-abcdefghij1234", out)
1136
1137    def test_claude_code_uses_the_anthropic_variables_without_a_login(self):
1138        code, out, _ = run_cli(["connect", "claude-code", "--url", "http://127.0.0.1:8080", "--key", "sk-x1234567890abc", "--show-key"])
1139        self.assertIn("ANTHROPIC_BASE_URL", out)
1140        self.assertIn("ANTHROPIC_AUTH_TOKEN", out)
1141        self.assertNotIn("/v1", out.split("ANTHROPIC_BASE_URL")[1].splitlines()[0])      # the Anthropic client adds /v1 itself
1142
1143    def test_a_pasted_v1_address_is_cut_back_to_the_server_root(self):
1144        """The Anthropic client adds /v1/messages itself, so ANTHROPIC_BASE_URL must never end in /v1 (that gave /v1/v1/messages, a 404);
1145        the OpenAI-style apps get exactly one /v1."""
1146        code, out, _ = run_cli(["connect", "claude-code", "--url", "http://127.0.0.1:8080/v1/", "--key", "sk-x1234567890abc", "--show-key", "--output", "json"])
1147        data = json.loads(out)
1148        self.assertEqual(data["env"]["ANTHROPIC_BASE_URL"], "http://127.0.0.1:8080")
1149        self.assertIn('"ANTHROPIC_BASE_URL": "http://127.0.0.1:8080"', data["files"][0]["text"])
1150        code, out, _ = run_cli(["connect", "opencode", "--url", "http://127.0.0.1:8080/v1", "--output", "json"])
1151        text = json.loads(out)["files"][0]["text"]
1152        self.assertIn("http://127.0.0.1:8080/v1", text)
1153        self.assertNotIn("/v1/v1", text)
1154        code, out, _ = run_cli(["connect", "claude-code", "--url", "http://127.0.0.1:8080"])
1155        self.assertIn("without /v1", out)
1156
1157    def test_write_keeps_a_backup_and_merges(self):
1158        target = Path(os.environ["HOME"]) / ".config" / "opencode" / "opencode.json"
1159        target.parent.mkdir(parents=True)
1160        target.write_text(json.dumps({"theme": "dark", "provider": {"other": {"a": 1}}}))
1161        code, out, err = run_cli(["connect", "opencode", "--url", "http://127.0.0.1:8080", "--key", "sk-x1234567890abc", "--write", "--yes"])
1162        self.assertEqual(code, 0, err)
1163        data = json.loads(target.read_text())
1164        self.assertEqual(data["theme"], "dark")
1165        self.assertIn("other", data["provider"])
1166        self.assertIn("strata", data["provider"])
1167        backups = list(target.parent.glob("opencode.json.strata-bak-*"))
1168        self.assertEqual(len(backups), 1)
1169        self.assertEqual(json.loads(backups[0].read_text())["theme"], "dark")
1170        self.assertIn("backup", out)
1171
1172    def test_write_asks_first_without_yes(self):
1173        # no keyboard: stdin is a pipe whatever the shell that runs the tests is; input() must never be reached
1174        pipe = io.StringIO("")
1175        with mock.patch.object(sys, "stdin", pipe), mock.patch("builtins.input", side_effect=AssertionError("asked on a pipe")):
1176            code, out, err = run_cli(["connect", "opencode", "--write"])
1177        self.assertEqual(code, 2)
1178        self.assertIn("asks first", err)
1179
1180    def test_write_answered_by_nobody_writes_nothing(self):
1181        # a terminal whose input ends (Ctrl-D, a closed console) is "no", not a traceback
1182        with mock.patch.object(sys.stdin, "isatty", return_value=True), mock.patch("builtins.input", side_effect=EOFError):
1183            code, out, err = run_cli(["connect", "opencode", "--write"])
1184        self.assertEqual(code, 0)
1185        self.assertIn("Nothing was written", out)
1186
1187    def test_built_in_harness_has_nothing_to_write(self):
1188        code, out, _ = run_cli(["connect", "deepseek-harness", "--write", "--yes"])
1189        self.assertEqual(code, 0)
1190        self.assertIn("Nothing to write", out)
1191
1192    def render(self, name, **kw):
1193        h = harness.find(name)
1194        t = harness.target(kw.get("url", "http://127.0.0.1:18900"), kw.get("key"), "qwen3.8-flash-next-q2_0", kw.get("context", 32768))
1195        return harness.render(h, t)
1196
1197    def test_all_eight_are_tested_configs(self):
1198        self.assertEqual([h.id for h in harness.HARNESSES],
1199                         ["opencode", "codex", "claude-code", "omp", "pi", "hermes", "openclaw", "deepseek-harness"])
1200        for h in harness.HARNESSES:
1201            self.assertTrue(h.tested, h.id)
1202            self.assertIn("tested", h.status)
1203
1204    def test_opencode_has_limit_input_and_the_15k_compaction_buffer(self):
1205        cfg = json.loads(self.render("opencode")["files"][0]["text"])
1206        m = cfg["provider"]["strata"]["models"]["qwen3.8-flash-next-q2_0"]
1207        self.assertEqual(m["limit"], {"context": 32768, "input": 28672, "output": 4096})
1208        self.assertEqual(cfg["compaction"]["buffer"], 13672)                  # 28672 - 15000
1209        self.assertEqual(cfg["provider"]["strata"]["options"]["baseURL"], "http://127.0.0.1:18900/v1")
1210        self.assertEqual(cfg["provider"]["strata"]["options"]["apiKey"], "strata-local")
1211
1212    def test_codex_uses_responses_and_the_key_variable(self):
1213        out = self.render("codex", key="sk-real")
1214        text = out["files"][0]["text"]
1215        self.assertIn('wire_api = "responses"', text)
1216        self.assertIn("model_auto_compact_token_limit = 15000", text)
1217        self.assertIn('base_url = "http://127.0.0.1:18900/v1"', text)
1218        self.assertEqual(out["env"], {"STRATA_API_KEY": "sk-real"})
1219
1220    def test_claude_code_sets_window_and_output_cap_and_has_no_login(self):
1221        out = self.render("claude-code")
1222        env = out["env"]
1223        self.assertEqual(env["ANTHROPIC_BASE_URL"], "http://127.0.0.1:18900")
1224        self.assertEqual(env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"], "32768")
1225        self.assertEqual(env["CLAUDE_CODE_MAX_OUTPUT_TOKENS"], "4096")
1226        self.assertEqual(env["CLAUDE_CODE_SIMPLE"], "1")                      # the full prompt is 15.6K tokens
1227        self.assertEqual(json.loads(out["files"][0]["text"])["env"], env)
1228        big = self.render("claude-code", context=131072)["env"]
1229        self.assertEqual(big["CLAUDE_CODE_MAX_CONTEXT_TOKENS"], "131072")
1230        self.assertNotIn("CLAUDE_CODE_SIMPLE", big)
1231        self.assertTrue(any("CLAUDE_CODE_MAX_OUTPUT_TOKENS" in n for n in out["limits"]))
1232
1233    def test_pi_omp_hermes_openclaw_numbers(self):
1234        pi = self.render("pi")["files"]
1235        self.assertEqual(json.loads(pi[1]["text"])["compaction"]["reserveTokens"], 17768)       # 32768 - 15000
1236        self.assertEqual(json.loads(pi[0]["text"])["providers"]["strata"]["models"][0]["contextWindow"], 32768)
1237        omp = self.render("omp")["files"]
1238        self.assertIn("thresholdTokens: 15000", omp[1]["text"])
1239        self.assertIn("contextWindow: 32768", omp[0]["text"])
1240        hermes = self.render("hermes")
1241        self.assertIn("provider: lmstudio", hermes["files"][0]["text"])
1242        self.assertIn("context_length: 65536", hermes["files"][0]["text"])
1243        self.assertTrue(any("WARNING" in n and "64K" in n for n in hermes["limits"]))
1244        self.assertFalse(any("WARNING" in n for n in self.render("hermes", context=131072)["limits"]))
1245        oc = json.loads(self.render("openclaw")["files"][0]["text"])
1246        self.assertEqual(oc["models"]["providers"]["strata"]["models"][0]["contextTokens"], 23192)
1247        self.assertTrue(any("Node 24.16" in n for n in self.render("openclaw")["limits"]))
1248
1249    def test_limits_are_in_plain_words_for_every_app(self):
1250        for h in harness.HARNESSES:
1251            self.assertTrue(self.render(h.id)["limits"], h.id)
1252
1253    def test_deepseek_harness_is_the_app(self):
1254        out = self.render("deepseek-harness")
1255        self.assertEqual(out["files"], [])
1256        self.assertIn("Strata app", " ".join(out["limits"]))
1257
1258    def test_check_sends_the_apps_own_wire_format_and_reports_pass_or_fail(self):
1259        from strata_cli.launch import check
1260        seen = []
1261
1262        def good(url, key, body, headers=None, timeout=0):
1263            seen.append(url)
1264            if url.endswith("/v1/responses"):
1265                if "tools" in body:
1266                    return {"output": [{"type": "function_call", "name": "get_weather", "arguments": json.dumps({"city": "Paris"})}]}
1267                return {"output_text": "pong"}
1268            if url.endswith("/v1/messages"):
1269                if "tools" in body:
1270                    return {"content": [{"type": "tool_use", "name": "get_weather", "input": {"city": "Paris"}}]}
1271                return {"content": [{"type": "text", "text": "pong"}]}
1272            if "tools" in body:
1273                return {"choices": [{"message": {"content": None, "tool_calls": [{"function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"}}]}}]}
1274            return {"choices": [{"message": {"content": "Pong."}}]}
1275
1276        for h, ending in (("opencode", "/v1/chat/completions"), ("codex", "/v1/responses"), ("claude-code", "/v1/messages")):
1277            seen.clear()
1278            res = check.run_checks(h, "http://127.0.0.1:1", "k", "m", poster=good)
1279            self.assertEqual([r.ok for r in res], [True, True], h)
1280            self.assertTrue(all(u.endswith(ending) for u in seen), (h, seen))
1281
1282        def wrong(url, key, body, headers=None, timeout=0):
1283            if "tools" in body:
1284                return {"choices": [{"message": {"content": "It is sunny.", "tool_calls": None}}]}
1285            return {"choices": [{"message": {"content": "hello there"}}]}
1286
1287        res = check.run_checks("pi", "http://127.0.0.1:1", "k", "m", poster=wrong)
1288        self.assertEqual([r.ok for r in res], [False, False])
1289        self.assertIn("not the word asked for", res[0].detail)
1290        self.assertIn("did not call the tool", res[1].detail)
1291
1292        import urllib.error
1293
1294        def refused(url, key, body, headers=None, timeout=0):
1295            raise urllib.error.HTTPError(url, 401, "no", None, None)
1296        res = check.run_checks("pi", "http://127.0.0.1:1", "", "m", poster=refused)
1297        self.assertIn("refused the key", res[0].detail)
1298
1299    def test_connect_check_flag_prints_pass_lines(self):
1300        from strata_cli.launch import check
1301        ok = [check.Check("prompt", True, "It answered: 'pong'.", 1.0), check.Check("tool call", True, "It called get_weather with {}.", 2.0)]
1302        with mock.patch.object(check, "run_checks", return_value=ok):
1303            code, out, err = run_cli(["connect", "opencode", "--url", "http://127.0.0.1:1", "--check"])
1304        self.assertEqual(code, 0, err)
1305        self.assertIn("PASS prompt", out)
1306        self.assertIn("PASS tool call", out)
1307        bad = [check.Check("prompt", False, "x", 1.0), ok[1]]
1308        with mock.patch.object(check, "run_checks", return_value=bad):
1309            code, out, err = run_cli(["connect", "opencode", "--url", "http://127.0.0.1:1", "--check"])
1310        self.assertEqual(code, 1)
1311        self.assertIn("FAIL prompt", out)
1312
1313    def test_context_flag_reaches_the_config(self):
1314        code, out, _ = run_cli(["connect", "pi", "--url", "http://127.0.0.1:8080", "--context", "64k", "--show-key"])
1315        self.assertIn('"contextWindow": 65536', out)
1316        self.assertIn('"reserveTokens": 33394', out)             # 65536 - 32142: the tested 52.3% share, not a flat 15K
1317
1318    def test_the_compaction_point_scales_with_the_window(self):
1319        """A wider server must not be summarised every 15,000 tokens: the share the tested 32K configs used carries over."""
1320        wide = harness.target("http://127.0.0.1:18900", None, "qwen3.8-flash-next-q2_0", 262144)
1321        self.assertEqual(harness.compact_at(wide), 135000)                     # 52.3% of the 258048 input limit
1322        cfg = json.loads(self.render("opencode", context=262144)["files"][0]["text"])
1323        self.assertEqual(wide.input_limit - cfg["compaction"]["buffer"], 135000)
1324        self.assertIn("model_auto_compact_token_limit = 135000", self.render("codex", context=262144)["files"][0]["text"])
1325        self.assertIn("thresholdTokens: 135000", self.render("omp", context=262144)["files"][1]["text"])
1326        # the window every config was tested on keeps exactly the value it was tested at
1327        tested = harness.target("http://127.0.0.1:18900", None, "qwen3.8-flash-next-q2_0", 32768)
1328        self.assertEqual(harness.compact_at(tested), 15000)
1329
1330
1331class GpuRolesFlag(unittest.TestCase):
1332    """--gpu-roles: a role for each card (strata_control/gpu_roles.py); unnamed cards are Off."""
1333
1334    def setUp(self):
1335        self.home = Home().__enter__()
1336        self.addCleanup(self.home.__exit__, None, None, None)
1337        p = mock.patch.object(Catalog, "hardware", lambda self, fresh=False: dict(HW_2X16, disk_free_gb=500.0))
1338        p.start()
1339        self.addCleanup(p.stop)
1340
1341    def test_roles_reach_the_settings_and_the_plan_says_who_does_what(self):
1342        code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "iq3_xxs", "--gpu-roles", "1=main,0=helper"])
1343        self.assertEqual(code, 0, err or out)
1344        s = json.loads(out)["plan"]["settings"]
1345        self.assertEqual(s["gpu_roles"], {"1": "main", "0": "helper"})
1346        self.assertIsNone(s["gpus"])
1347        code, out, err = run_cli(["launch", "--plan", "--model", "iq3_xxs", "--gpu-roles", "1=main,0=helper"])
1348        self.assertEqual(code, 0, err or out)
1349        self.assertIn("cards     Main: GPU 2 (--gpu 1) RTX A4000. Helper: GPU 1 (--gpu 0) RTX A4000.", out)      # counted from 1 like the screens, and the number --gpu takes
1350        self.assertIn("--gpu-roles 0=helper,1=main", out)                 # the copyable line says the same
1351
1352    def test_one_card_named_leaves_the_other_off(self):
1353        code, out, err = run_cli(["launch", "--plan", "--model", "iq3_xxs", "--gpu-roles", "1=main"])
1354        self.assertEqual(code, 0, err or out)
1355        self.assertIn("Main: GPU 2 (--gpu 1) RTX A4000. Off: GPU 1 (--gpu 0) RTX A4000.", out)
1356
1357    def test_bad_roles_are_plain_sentences(self):
1358        for argv, word in ((["--gpu-roles", "1=boss"], "main, helper, off"), (["--gpu-roles", "0=main,1=main"], "only one card can be Main"),
1359                           (["--gpu-roles", "1"], "number=role"), (["--gpu", "0", "--gpu-roles", "1=main"], "not both")):
1360            code, out, err = run_cli(["launch", "--plan", *argv])
1361            self.assertEqual(code, 2, argv)
1362            self.assertIn(word, err, argv)
1363        code, out, err = run_cli(["launch", "--plan", "--model", "iq3_xxs", "--gpu-roles", "7=main"])
1364        self.assertIn("There is no card 7", out + err)
1365
1366    def test_the_launch_config_gets_the_roles_and_the_mirror_with_main_last(self):
1367        from strata_cli.launch.runner import cards_for_launch
1368        two = catalog(HW_2X16)
1369        mirror = cards_for_launch(S.LaunchSettings(family="qwen", model="IQ3_XXS", gpu_roles={"1": "main", "0": "helper"}), two)
1370        self.assertEqual((mirror["gpu"], mirror["gpu_order"]), ([0, 1], "as_given"))
1371        self.assertEqual(mirror["gpu_roles"], {"0": "helper", "1": "main"})
1372        base = {"exe": "x", "args": [], "gpu": 1, "gpus_asked": True, "hip_ordinal": 0, "gpu_roles": {"0": "off", "1": "main"}}
1373        cfg = derive_config(base, S.LaunchSettings(family="qwen", model="IQ3_XXS"), bool_flags=frozenset(), gpus=mirror)
1374        self.assertEqual((cfg["gpu"], cfg["layer_split"], cfg["gpu_order"]), ([0, 1], "auto", "as_given"))
1375        self.assertNotIn("hip_ordinal", cfg)
1376        one = cards_for_launch(S.LaunchSettings(family="qwen", model="IQ3_XXS", gpu_roles={"0": "main"}), two)
1377        cfg = derive_config(base, S.LaunchSettings(family="qwen", model="IQ3_XXS"), bool_flags=frozenset(), gpus=one)
1378        self.assertEqual((cfg["gpu"], cfg["gpu_roles"], "layer_split" in cfg), (0, {"0": "main", "1": "off"}, False))
1379        none = cards_for_launch(S.LaunchSettings(family="qwen", model="IQ3_XXS", gpu_roles={"0": "off", "1": "off"}), two)
1380        self.assertEqual((none["gpu"], none["gpu_none"]), ([], True))
1381
1382    def test_a_plain_card_list_replaces_an_earlier_roles_choice_and_the_installed_roles_are_kept(self):
1383        from strata_cli.launch.runner import apply_cards, cards_for_launch, installed_cards
1384        cfg = {"gpu": 1, "gpu_roles": {"0": "off", "1": "main"}, "gpu_cards": {}, "gpus_asked": True}
1385        apply_cards(cfg, [0, 1])
1386        self.assertEqual((cfg["gpu"], "gpu_roles" in cfg), ([0, 1], False))
1387        saved = {"gpu": [0, 1], "gpu_order": "as_given", "gpu_roles": {"0": "helper", "1": "main"}}
1388        self.assertEqual(installed_cards(saved), [0, 1])
1389        self.assertIsNone(cards_for_launch(S.LaunchSettings(family="qwen", model="IQ3_XXS"), catalog(HW_2X16), base=saved))
1390
1391
1392if __name__ == "__main__":
1393    unittest.main()