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