okami.mom/strata

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

Niko1221launch: a drafter the person chose stays chosen, the way Off does1b4018870

main
165.4 KiB2807 linesraw
1"""What `strata launch` does after the choices are made: get the engine and the model, write the run config, tune, start, open access.
2
3Every step reports plain-word events through one callback (`emit`), so the TUI (progress screen), `--no-tui` (printed lines) and the
4tests see the same thing. Nothing here prints or reads the keyboard. The steps reuse what is already in the Terminal:
5
6* the engine comes from the signed feed (`strata update`, the one explicit step that downloads);
7* the model comes from setup.py in the app's own installer mode (STRATA_CONTROL_INSTALL), the same job the desktop app runs;
8* the run config the engine uses is a private copy of the installed one with this launch's choices applied; the profile
9  `launch-<name>` (the shared profiles store) points at it, and carries host, port and parallel;
10* tuning is `strata tune auto`, its result lives in the shared presets store and is applied at every start;
11* start and stop are `strata runtime start|stop` (a background service: it keeps serving after this terminal closes).
12"""
13
14from __future__ import annotations
15
16import json
17import os
18import re
19import subprocess
20import sys
21import tempfile
22import threading
23import time
24from strata_control import vram_fit
25from strata_control.childenv import quiet_crash_env
26from strata_control import reader_room
27from strata_control import atomic as _atomic_mod
28from dataclasses import dataclass, field
29from pathlib import Path
30from typing import Any, Callable
31
32from strata_cli.launch import access as acc
33from strata_cli.launch import modelstate
34from strata_cli.launch import settings as S
35from strata_cli.launch.catalog import Catalog, CatalogUnavailable
36
37ROOT = Path(__file__).resolve().parents[2]
38WINDOWS = os.name == "nt"
39
40
41def install_isolation_words(catalog, data_dir: str | os.PathLike | None = None) -> list[str]:
42    """Round 8, N5: a clean test (a scratch data folder) silently ran an OLDER install found elsewhere (its run config and engine 0.1.41).
43    When a data folder was chosen (--data-dir, or STRATA_DATA_DIR from the installer) and the install in use is outside it, say which one is used
44    and why. Nothing is moved or switched."""
45    chosen = data_dir or os.environ.get("STRATA_DATA_DIR")
46    places = getattr(catalog, "places", None) or []
47    if not chosen or not places or places[0].source == "explicit":
48        return []
49    main = Path(places[0].path)
50    try:
51        inside = os.path.commonpath([os.path.abspath(main), os.path.abspath(chosen)]) == os.path.abspath(chosen)
52    except ValueError:
53        inside = False
54    if inside:
55        return []
56    return [f"Strata is using the earlier install in {main} ({places[0].configs} saved model setting(s) and its engine settings), not a clean one in "
57            f"{chosen}: the data folder only says where model files are kept. To test from scratch, use a new user account or remove the earlier install first."]
58
59
60#: the first engine whose Metal build reads Gyro files (round 8, M: 0.1.45.3 was reused and failed on missing TQK6/TQK7 kernels)
61GYRO_METAL_ENGINE = (0, 1, 47)
62
63
64def version_tuple(version: str | None) -> tuple[int, ...]:
65    """'0.1.45.3' -> (0, 1, 45, 3); () when it is not a dotted run of numbers (a source build says so itself)."""
66    m = re.match(r"\d+(?:\.\d+)*", str(version or "").strip())
67    return tuple(int(x) for x in m.group(0).split(".")) if m else ()
68
69
70def python_failure(lines: list[str]) -> str | None:
71    """The last line of a Python traceback in setup.py's output (ModuleNotFoundError: No module named 'calibrate'), or None when the
72    output holds no traceback. Frames are skipped; the exception line is the first unindented line after the last 'Traceback'."""
73    for i in range(len(lines) - 1, -1, -1):
74        if lines[i].startswith("Traceback (most recent call last)"):
75            for line in lines[i + 1:]:
76                if line.strip() and not line[:1].isspace():
77                    return line.strip()[:300]
78            return None
79    return None
80
81
82def argparse_failure(lines: list[str]) -> str:
83    """setup.py's own refusal of an option ("setup.py: error: argument --kv: invalid choice: ..."), which is neither an [X] line nor a
84    traceback (#3785): the words after "error:" are the cause."""
85    for line in reversed(lines):
86        found = re.match(r"\s*(?:setup|strata)(?:\.py)?: error: (.+)", line)
87        if found:
88            return found.group(1).strip()[:300]
89    return ""
90
91
92def missing_file(failure: str) -> bool:
93    """An import or file error: the install itself is short of a file, which an update of Strata brings back."""
94    return failure.startswith(("ModuleNotFoundError", "ImportError", "FileNotFoundError"))
95
96
97def capital(text: str) -> str:
98    """A reason that was written to stand alone ("the update feed could not be read: ...") starts the sentence it is joined to with a capital.
99    A host name stays as it is written ("github.com did not answer ...", strata_control/netpolicy.py)."""
100    first = text.split(" ", 1)[0]
101    if "." in first.strip(".") and re.fullmatch(r"[a-z0-9.-]+", first.rstrip(".")):
102        return text
103    return text[:1].upper() + text[1:]
104
105
106class LaunchError(RuntimeError):
107    """A step could not be done. `text` says what it means; `next` says what to do."""
108
109    def __init__(self, text: str, next: str = "", code: int = 6):
110        super().__init__((text + " " + next).strip())
111        self.text, self.next, self.code = text, next, code
112
113
114def setup_failure(lines: list[str], err: str, hint: str, details: str | None, own_files: bool) -> LaunchError:
115    """The error for a setup.py run that exited non-zero. setup.py's own `[X]` line (err) is the message when there is one; when it
116    stopped with a Python error instead, that error's last line is (#3613, #3467: a file missing from the Terminal's tools/ ended every
117    launch after a tune with only "The model could not be installed"). `details` is the file that holds the rest of its output."""
118    err = err or argparse_failure(lines)
119    crashed = python_failure(lines) if not err else None
120    if crashed:
121        where = f" The whole setup output is in {details}." if details else ""
122        if missing_file(crashed):
123            return LaunchError(f"The model could not be installed. A file that setup needs is missing from this Strata install ({crashed}).",
124                               "Update Strata (`strata update`) and run it again." + where, 6)
125        if crashed.startswith("PermissionError"):
126            folder = re.findall(r"'([^']+)'", crashed)
127            shown = folder[-1] if folder else None
128            try:                                              # the folder Strata was told to use, not a file inside it
129                shown = str(Path(shown).parent) if shown and Path(shown).name in ("models", "packs", "mtp") else shown
130            except (OSError, ValueError):
131                pass
132            return LaunchError("The model could not be installed. " + (f"Windows would not let Strata write to {shown}" if shown else
133                               "Windows would not let Strata write to a folder") + " (access denied).",
134                               "Pick a folder you own for the model files (the Folder step, or --data-dir D:\\Strata-models) and start again. "
135                               "Nothing was downloaded." + where, 6)
136        return LaunchError(f"The model could not be installed. Setup stopped with an error ({crashed}).", "Run it again." + where, 6)
137    return LaunchError("The model could not be installed." + (f" {capital(err.rstrip('.'))}." if err else ""),
138                       (hint or ("Run it again: finished steps are skipped." if own_files else
139                                 "Run it again: finished steps are skipped and a download continues where it stopped."))
140                       + (f" Details: {details}" if details else ""), 6)
141
142
143class Cancelled(LaunchError):
144    def __init__(self):
145        super().__init__("Stopped. Nothing was changed on your computer beyond files already downloaded.", "", 130)
146
147
148@dataclass
149class Event:
150    stage: str                      # engine | model | config | tune | start | access | done
151    text: str
152    pct: float | None = None
153    level: str = "info"             # info | warn | error
154    data: dict = field(default_factory=dict)
155
156
157@dataclass
158class Result:
159    profile: str
160    urls: list[str]
161    key: str | None
162    tune_word: str | None
163    notices: list[str]
164    config: str
165    tunnel: str | None = None
166    serving: bool = True                   # False: the model is ready but nothing was started (no engine yet)
167    engine_problem: str | None = None      # the plain reason there is no engine, when serving is False
168    final_text: str = ""                   # what to tell the person when serving is False
169    reused: bool = False                   # the same choices were already serving: nothing was stopped or started
170
171
172NO_ENGINE_NEXT = ("Update Strata (`strata update`) and run `strata launch` again. Nothing was downloaded, and any model files you already have are kept.")
173
174STAGES = ("engine", "model", "config", "tune", "start", "access")
175
176NO_ENGINE_STEP = ("run `strata update` to get the newest engines and start again; if this stays, your graphics card is not one Strata supports yet, "
177                  "and the model files stay on this computer for when it is")
178
179#: no graphics card Strata can use at all (an Intel UHD/Iris only, an AMD APU-only laptop, a virtual machine, Windows on ARM)
180NO_GPU_PREFIX = "no graphics card that Strata can use was found"
181NO_GPU_STEP = ("Strata needs an NVIDIA or AMD graphics card, an Intel Arc card or an Apple Silicon Mac, and there is no CPU-only engine for this "
182                "computer. Run Strata on a computer that has one; the model files stay here")
183
184
185def no_gpu_words(names: list[str] | None = None) -> str:
186    """The plain reason when nothing Strata can run on is in this computer, naming what is there when it is known."""
187    names = [n for n in (names or []) if n]
188    if names:
189        return f"{NO_GPU_PREFIX}; this computer has {', '.join(names[:3])}"
190    return NO_GPU_PREFIX
191
192
193def _step_for(reason: str) -> str:
194    return NO_GPU_STEP if reason.startswith(NO_GPU_PREFIX) else NO_ENGINE_STEP
195
196
197def no_engine_warning(reason: str) -> str:
198    """The plain warning shown before a model is downloaded on a computer with no engine to run it."""
199    reason = reason.strip().rstrip(".")
200    if reason.startswith(NO_GPU_PREFIX):
201        return (f"Strata can't run on this computer: {reason}. The model will download, but it will not run here "
202                f"(next step: {NO_GPU_STEP}).")
203    return (f"Strata couldn't find an engine for this computer ({reason}). The model will download, but it may not run until you install "
204            f"the right engine (next step: {NO_ENGINE_STEP}).")
205
206
207def no_engine_final(reason: str, name: str = "") -> str:
208    reason = reason.strip().rstrip(".")
209    if reason.startswith(NO_GPU_PREFIX):
210        return f"The model is ready, but Strata can't start it on this computer: {reason}. Next step: {NO_GPU_STEP}."
211    return (f"The model is ready, but Strata can't start it yet: it couldn't find an engine for this computer ({reason}). "
212            f"Next step: {NO_ENGINE_STEP}. The model files stay on this computer.")
213
214
215def tune_words(result: dict | None, code: int | None = None) -> tuple[str, str]:
216    """(short word, plain sentence) for a tuner result: faster / already fastest / busy PC / failed / stopped."""
217    if not result:
218        return "failed", "The tuner did not finish, so the standard settings run. Nothing was changed."
219    out = result.get("outcome")
220    if out == "improved":
221        gain = result.get("gain_pct")
222        return "faster", (f"Done: answers are about {gain:.0f}% faster with the tuned settings." if isinstance(gain, (int, float))
223                          else "Done: the tuned settings are faster.")
224    if out == "default_confirmed" and result.get("not_tried"):
225        n = int(result["not_tried"])          # some candidates were never measured: "already fastest" would be untrue (#5122)
226        return "some not tried", f"{n} setting{'s' if n != 1 else ''} could not be tried: not enough free memory"
227    if out == "default_confirmed":
228        return "already fastest", "Your computer already runs at its best with the standard settings. Nothing needed changing."
229    if out == "inconclusive":
230        return "busy PC", ("The computer was too busy to tell a real gain from noise, so the standard settings run. "
231                           "Close other programs and tune again later (strata tune auto).")
232    if out == "cancelled":
233        return "stopped", "Tuning was stopped. Your settings were not changed."
234    return "failed", (result.get("message") or "Tuning could not run here.") + " The standard settings run."
235
236
237# ----------------------------------------------------------------------------------------------- run config
238
239def runtime_max_wait() -> int:
240    from strata_control import runtime
241    return int(runtime.MAX_START_WAIT)
242
243
244def read_config(path: Path) -> dict:
245    return json.loads(Path(path).read_text(encoding="utf-8-sig"))
246
247
248def desc_matches(desc: dict, s: S.LaunchSettings) -> bool:
249    """Does the installed model's config already carry the context, memory format and picture choice of these settings?
250    (The graphics cards are not part of it: they go into each launch's own config, see apply_cards.)"""
251    if s.context and desc.get("context") != s.context:
252        return False
253    want_kv = s.kv or ("int8" if (s.context or 32768) > 8192 else "fp16")
254    if desc.get("kv") not in (None, want_kv) and (s.context or 32768) > 8192:
255        return False
256    images = desc.get("images") or "off"
257    if s.vision is None:
258        return True                                          # no preference yet: the run settles it before it compares
259    if (s.vision == "off") != (images == "off"):
260        return False
261    if s.vision in ("gpu", "cpu") and images != s.vision:
262        return False
263    return True
264
265
266def _inside(path: Path, folder: Path) -> bool:
267    a, b = os.path.normcase(str(path)), os.path.normcase(str(folder))
268    return a == b or a.startswith(b.rstrip("\\/") + os.sep)
269
270
271def files_present(cfg: dict) -> list[str]:
272    """The model files a run config names that are missing (empty list: all there)."""
273    missing = []
274    for tok in cfg.get("args") or []:
275        if isinstance(tok, str) and tok.lower().endswith(".gguf") and not Path(tok).exists():
276            missing.append(tok)
277    for flag in ("--pack", "--mtp"):
278        args = [str(a) for a in cfg.get("args") or []]
279        if flag == "--mtp" and flag in args and args.index(flag) + 1 < len(args) and args[args.index(flag) + 1].isdigit():
280            continue                                      # Qwen3.6: a number is the draft depth, not a folder (#3298)
281        if flag in args and args.index(flag) + 1 < len(args) and not Path(args[args.index(flag) + 1]).exists():
282            missing.append(args[args.index(flag) + 1])
283    vision = cfg.get("vision")
284    if isinstance(vision, dict) and vision.get("mmproj") and not Path(str(vision["mmproj"])).exists():
285        missing.append(str(vision["mmproj"]))                 # the picture reader's file: setup fetches it again
286    return missing
287
288
289def apply_choices(cfg: dict, s: S.LaunchSettings) -> dict:
290    """A copy of the installed run config with this launch's context, memory format and picture choice on its engine command, so the command
291    the Advanced step shows is the one these choices run (the installed config only holds the choices it was installed with). Only the command
292    preview and the comparison use this; the start itself goes through setup, which writes the same values."""
293    import copy
294    cfg = copy.deepcopy(cfg)
295    args = [str(a) for a in cfg.get("args") or []]
296
297    def put(flag: str, value: str) -> None:
298        if flag in args:
299            i = args.index(flag)
300            if i + 1 < len(args) and not args[i + 1].startswith("--"):
301                args[i + 1] = value
302                return
303            args.insert(i + 1, value)
304        else:
305            args.extend([flag, value])
306
307    if s.context:
308        put("--max-context", str(int(s.context)))
309    kv = s.kv or ("int8" if (s.context or 32768) > 8192 else "fp16")
310    if "--kv" in args or s.kv:
311        put("--kv", kv)
312    if s.vision == "off":
313        args = [a for a in args if a != "--vision"]
314        cfg.pop("vision", None)                              # the picture reader's own settings: the server adds --vision for them
315    elif s.vision and "--vision" not in args:
316        args.append("--vision")
317    cfg["args"] = args
318    return cfg
319
320
321def card_signals(cfg: dict, gpus: Any, want: dict) -> dict:
322    """Runner.drafting_signals for a run config and the launch's cards ``gpus``: the arguments with the person's own options over them, and the ONE card's memory."""
323    try:
324        from strata_control import drafting, user_args
325        args = [str(a) for a in cfg.get("args") or []]
326        if cfg.get("user_args"):
327            args = user_args.merge(args, cfg["user_args"])
328        run = {**cfg, "gpu": [int(g) for g in gpus] if gpus else cfg.get("gpu")}
329        return {"args": args, "vram_mib": drafting.card_vram_mib(run, want.get("backend"), want.get("archs"))}
330    except Exception:                                    # noqa: BLE001 - no signal means the tuned pack is not fetched
331        return {"args": [], "vram_mib": None}
332
333
334def auto_signals(catalog, s: S.LaunchSettings, family: str | None) -> dict:
335    """What the start's drafting decision reads besides the choice (drafting_inputs / drafting_signals): the model's set and the card signals of the installed config
336    (or none yet) with this launch's context and cards. With them, what setup is told to fetch and what the plan lists are the drafter the start runs: on the 12 GB
337    card with IQ3_S Auto is the MTP (drafting.CLASS_DEFAULTS); without them setup was told DFlash2, skipped the draft layer, and the start had no drafter (0.2.14
338    real-use run); on a Mac the set decides (Metal IQ3_S is the MTP, the other sets DFlash2). Never raises."""
339    try:
340        from strata_control import drafting
341        path = catalog.installed_config(catalog.tag_of(s.family, s.model))
342        cfg = apply_choices(read_config(path) if path is not None else {}, s)
343        backend, archs = drafting.detect_hardware()
344        return {"model_name": cfg.get("model_name") or catalog.model_name_of(family, s.model),
345                **card_signals(cfg, s.gpus, {"backend": backend, "archs": archs})}
346    except Exception:                                    # noqa: BLE001 - no signal: Auto as before
347        return {}
348
349
350def apply_cards(cfg: dict, gpus: "list[int] | dict | None") -> None:
351    """The graphics cards of THIS launch go into its run config, whatever card the model was installed with (no reinstall): one card is a number,
352    several are a list with the automatic layer split. None: the installed config's own choice stays.  A dict is the roles of every card
353    (strata_control/gpu_roles.mirror: "gpu_roles" plus the legacy "gpu" with the Main card last)."""
354    if isinstance(gpus, dict):
355        for k in ("gpu", "gpu_order", "gpu_none", "gpu_roles", "gpu_cards"):
356            cfg.pop(k, None)
357        cfg.update(gpus)
358        cfg["gpus_asked"] = True
359        cfg.pop("hip_ordinal", None)
360        on = gpus.get("gpu")
361        if isinstance(on, list) and len(on) > 1:
362            cfg["layer_split"] = cfg.get("layer_split") or "auto"
363        else:
364            cfg.pop("layer_split", None)
365        return
366    if not gpus:
367        return
368    for k in ("gpu_roles", "gpu_cards", "gpu_none", "gpu_order"):   # a plain card list replaces an earlier roles choice; the engine orders it
369        cfg.pop(k, None)
370    gpus = [int(g) for g in gpus]
371    cfg["gpu"] = gpus[0] if len(gpus) == 1 else gpus
372    cfg["gpus_asked"] = True
373    cfg.pop("hip_ordinal", None)                             # an old AMD config's ordinal of ITS card would win over the card named now
374    if len(gpus) > 1:
375        cfg["layer_split"] = cfg.get("layer_split") or "auto"
376    else:
377        cfg.pop("layer_split", None)
378
379
380def installed_cards(base: dict | None, usable: list[dict] | None = None) -> list[int] | None:
381    """The cards the installed model's own config names after a choice (setup --gpu / --gpus, the app's card pick: "gpus_asked"), in its order;
382    None when it names none or was never asked, or when setup picked them itself ("gpus_by": "setup").  `usable` is not used any more (it told a
383    DeepSeek config's own pick apart) and is kept for the callers."""
384    if not isinstance(base, dict) or not (base.get("gpus_asked") or base.get("gpu_roles")):
385        return None
386    if not base.get("gpu_roles") and base.get("gpus_by") == "setup":
387        return None
388    g = base.get("gpu")
389    if g is None or g == "":
390        return None
391    try:
392        cards = [int(str(x).strip()) for x in (g if isinstance(g, (list, tuple)) else str(g).split(",")) if str(x).strip() != ""]
393    except ValueError:
394        return None
395    return cards or None
396
397
398def cards_for_launch(s: S.LaunchSettings, catalog, ram_gb: float | None = None, base: dict | None = None) -> "list[int] | dict | None":
399    """The cards this launch uses: the ones named (--gpu / --gpus, the Cards step), else the cards the installed config was set to (a person's
400    earlier choice, "gpu": 1 or [1, 0] - never replaced by the automatic pick, which would put the first of equal cards back), else the
401    recommended ones by the shared fit rule (strata_control/gpu_fit.py) when the computer has more than one card that counts, else None."""
402    if s.gpu_roles:
403        try:
404            from strata_control import gpu_roles
405            comp = catalog.computer()
406            cards = gpu_roles.rows(comp.gpus, comp.engine_vendor)
407            named = {int(k): v for k, v in s.gpu_roles.items()}
408            roles = gpu_roles.normalize({int(c.get("index", 0)): named.get(int(c.get("index", 0)), "off") for c in cards}, cards)
409            return gpu_roles.mirror(roles, cards)
410        except Exception:                                    # noqa: BLE001 - never block a launch over the choice of cards
411            return None
412    if s.gpus:
413        return [int(g) for g in s.gpus]
414    try:
415        usable_now = catalog.computer().usable_gpus
416    except Exception:                                        # noqa: BLE001 - without the card list a saved card is kept, as before
417        usable_now = None
418    if installed_cards(base, usable_now) or (isinstance(base, dict) and base.get("gpu_roles")):
419        return None
420    try:
421        from strata_control import gpu_roles
422        comp = catalog.computer()
423        if len(comp.usable_gpus) < 2:
424            return None
425        cards = gpu_roles.rows(comp.gpus, comp.engine_vendor)
426        rec = gpu_roles.recommend(cards, comp.engine_vendor)["roles"]
427        return gpu_roles.order(rec, cards) or None
428    except Exception:                                        # noqa: BLE001 - never block a launch over the choice of cards
429        return None
430
431
432def used_cards(computer, s: "S.LaunchSettings") -> list:
433    """The cards this launch uses: the ones named (--gpu, the Cards step; a role other than off), else every card that can be used."""
434    cards = list(computer.usable_gpus)
435    chosen = None
436    if s.gpu_roles:
437        chosen = {int(k) for k, v in s.gpu_roles.items() if str(v) != "off"}
438    elif s.gpus:
439        chosen = {int(g) for g in s.gpus}
440    if chosen is not None:
441        cards = [c for c in cards if int(c.get("index", 0)) in chosen]
442    return cards
443
444
445def uses_integrated_gpu(computer, s: "S.LaunchSettings") -> bool:
446    """Does the launch run on an integrated / unified-memory GPU (Strix Halo, gfx1151, Radeon 8060S: the hardware probe marks it uma, integrated or
447    unified_memory)? A Mac is left out."""
448    for c in used_cards(computer, s):
449        if str(c.get("vendor")) == "apple" or c.get("unified_gb"):
450            continue
451        if c.get("integrated") or c.get("uma") or c.get("unified_memory"):
452            return True
453    return False
454
455
456_SETUP_LOG_NAME = re.compile(r"^strata-[A-Za-z0-9_.-]+\.log$")
457
458
459def own_log_path(base: dict) -> str | None:
460    """The log path a person wrote into the model's config themselves (#3656): setup names its own `strata-<model>.log`, so any other
461    name is theirs and a launch keeps it instead of writing its per-profile log file."""
462    value = base.get("log")
463    if not isinstance(value, str) or not value.strip():
464        return None
465    return None if _SETUP_LOG_NAME.match(Path(value.replace("\\", "/")).name) else value
466
467
468def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str], log: str | None = None, gpus: "list[int] | dict | None" = None,
469                  prev: dict | None = None) -> dict:
470    """The private run config of this launch: the installed one plus the choices that are not setup's (host, port, key, cards, advanced).
471    `prev` is the config this launch wrote last time: its calibrated values and hand edits are kept (strata_control/arg_layers.py: explicit
472    launch values, then persisted overrides, then calibrated values, then Auto)."""
473    from strata_control import arg_layers, tune_knobs
474    cfg = json.loads(json.dumps(base))
475    cfg["host"] = acc.host_for(s.access)
476    cfg["port"] = int(s.port)
477    if s.api_key:
478        cfg["api_key"] = s.api_key
479    elif s.no_key and s.access != "local":
480        cfg["api_key"] = "none"                              # served without a key on purpose (the server warns once at start)
481    else:
482        cfg.pop("api_key", None)
483    chosen = s.drafting
484    if chosen:                                               # strata_control/drafting.py: serve/server.py applies it at every start
485        cfg["drafting"] = chosen
486    if s.split_engine:                                       # strata_control/split_engine.py: read by apply_split_engine; "off" survives every update
487        cfg["split_engine"] = s.split_engine
488    cfg.setdefault("exe", "component:strata-engine")
489    cfg["open_browser"] = False                              # strata launch never opens a browser by itself (only `--open` does, after the start)
490    if isinstance(cfg.get("args"), list):
491        cfg["args"] = [a for a in cfg["args"] if a != "--open"]
492    if log and not own_log_path(base):
493        cfg["log"] = log
494    apply_cards(cfg, gpus)
495    from strata_control import drafting as _drafting
496    drafting_off = _drafting.normalize(chosen if chosen is not None else cfg.get("drafting")) == "off"
497    if s.mtp == "off" or drafting_off:                       # no draft layer for this launch (serve/server.py applies "mtp": false at every start)
498        from strata_control import draft_layer              # --drafting off: the written file carries no --mtp either (it was left in before)
499        cfg["mtp"] = False
500        draft_layer.apply(cfg)
501    elif s.mtp == "on":
502        cfg["mtp"] = True
503    if cfg.get("backend") == "sycl":                         # exactly two Arc B-series cards: --spec 2 (strata_control/intel_spec.py); the person's
504        from strata_control import intel_spec                # own choices (user_args, an extra option below) come after it and win
505        intel_spec.apply_for_launch(cfg)
506    word_flags = S.WORD_VALUE_FLAGS
507    a_changes, e_changes = S.as_argv_changes(s.extra, bool_flags, word_flags) if s.extra else ({}, {})
508    arg_layers.layer(cfg, a_changes, prev, bool_flags)       # the one place that decides which value an option has
509    if e_changes:
510        cfg["env"] = tune_knobs.apply_to_env(dict(cfg.get("env") or {}), e_changes)
511    from strata_control import draft_layer
512    draft_layer.apply(cfg)                                   # "mtp": false (from the installed config too) never sits beside --mtp in the saved args (B10)
513    return cfg
514
515
516def write_private(path: Path, data: dict) -> None:
517    path.parent.mkdir(parents=True, exist_ok=True)
518    fd, tmp = tempfile.mkstemp(prefix=".launch-cfg-", suffix=".tmp", dir=path.parent)
519    try:
520        with os.fdopen(fd, "wb") as fh:
521            fh.write((json.dumps(data, indent=1, ensure_ascii=False) + "\n").encode("utf-8"))
522        try:
523            os.chmod(tmp, 0o600)
524        except OSError:
525            pass
526        _atomic_mod.replace(tmp, path)
527    finally:
528        if os.path.exists(tmp):
529            os.unlink(tmp)
530    if WINDOWS:
531        try:
532            from strata_control import private_files
533            private_files.restrict_to_current_user(path, directory=False)
534        except Exception:                                    # noqa: BLE001
535            pass
536
537
538def launch_dir() -> Path:
539    from strata_control import paths
540    d = paths.state_base() / "launch"
541    d.mkdir(parents=True, exist_ok=True)
542    return d
543
544
545def launch_name_of(s) -> str:
546    """The name of the launch these settings make (Runner.name): its run config is launch/<name>.json."""
547    return S.slug(s.name or (s.model or "model") + "-" + S.context_label(s.context).lower())
548
549
550def saved_launch_word(name: str) -> str | None:
551    """The Drafting word the launch `name` (Runner.name) was given last time, as its own run config (launch/<name>.json) keeps it: auto | mtp | dflash2 | off,
552    or None when there is none or it cannot be read. The TUI's Drafting step and Runner.keep_saved_word read it."""
553    try:
554        from strata_control import drafting
555        prev = read_config(launch_dir() / f"{name}.json")
556        word = prev.get("drafting") if isinstance(prev, dict) else None
557        word = word.strip().lower() if isinstance(word, str) else None
558        return word if word in drafting.MODES else None
559    except Exception:                                        # noqa: BLE001 - no readable file, no word
560        return None
561
562
563# ----------------------------------------------------------------------------------------------- the runner
564
565
566def download_text(dl: dict, already: bool, label: str | None = None) -> str:
567    """The step line for a download or a check. `label` is what is being fetched, in words (strata_control/progress_words.py). A model whose
568    files were all on disk before this run says so instead of "Downloading 58.5 of 58.5 GB"."""
569    if already:
570        return f"The model files are already on this computer ({dl['total_gb']:.1f} GB); checking them"
571    return f"{label}: {dl['done_gb']:.1f} of {dl['total_gb']:.1f} GB" if label else f"Downloading {dl['done_gb']:.1f} of {dl['total_gb']:.1f} GB"
572
573
574_END = object()
575
576
577def _elapsed(seconds: float) -> str:
578    """'40 s', '3 min' (plain, rounded down)."""
579    seconds = int(seconds)
580    return f"{seconds} s" if seconds < 90 else f"{seconds // 60} min"
581
582
583class Runner:
584    def __init__(self, s: S.LaunchSettings, *, catalog: Catalog | None = None, emit: Callable[[Event], None] | None = None,
585                 cancel: threading.Event | None = None, feed: str | None = None, python: str | None = None,
586                 components_dir: str | None = None, hardware: dict | None = None,
587                 confirm: Callable[[str, str], bool] | None = None, assume_yes: bool = False, move_data: bool = False,
588                 retune: bool = False, restart: bool = False, confirm_restart: Callable[[str, str], bool] | None = None,
589                 after_check: Callable[[], None] | None = None):
590        self.s = s
591        self.after_check = after_check        # called once when nothing blocks the launch (no server, the same one, or "Restart" was answered): the screens save the preset then
592        self.restart = restart                # --restart: a server that serves other choices (or holds this port) is stopped and replaced without asking
593        self.confirm_restart = confirm_restart  # the screens: asked (question, detail) once; True = restart. None (no screens) and no --restart: refuse in one line
594        self._stop_first: list[str] = []      # other launch profiles that hold this port; stopped before the measuring and the start
595        self.retune = retune                  # --retune: measure again even when a tuning result for this model on this computer is stored
596        self.move_data = move_data            # --move-data / the answer "move": the model files already here go to the new --data-dir
597        self.confirm = confirm                # asked (title, text) before a model is downloaded with no engine; True = go on
598        self.assume_yes = assume_yes          # --yes: no questions
599        self.engine_problem: str | None = None
600        self.key_written_notice: str | None = None   # the sentence "a new API key was made", held by the command until the run config that holds the key is on disk
601        self.key_written = False
602        self._catalog = catalog
603        self.emit_cb = emit or (lambda e: None)
604        self.cancel = cancel or threading.Event()
605        self.feed = feed
606        self.python = python or sys.executable
607        self.components_dir = components_dir
608        self.hardware_override = hardware
609        self.children: list[subprocess.Popen] = []
610        self.notices: list[str] = []
611        self.identity_notes: list[str] = []
612        self.tune_result: dict | None = None
613        self.config_path: Path | None = None
614        self._own_checked = False
615
616    # ---- small helpers
617    def emit(self, stage: str, text: str, pct: float | None = None, level: str = "info", **data: Any) -> None:
618        self.emit_cb(Event(stage, text, pct, level, data))
619
620    def check_cancel(self) -> None:
621        if self.cancel.is_set():
622            raise Cancelled()
623
624    @property
625    def catalog(self) -> Catalog:
626        if self._catalog is None:
627            try:
628                self._catalog = Catalog(hardware=self.hardware_override)
629            except CatalogUnavailable as e:
630                raise LaunchError(str(e), "", 5) from None
631        return self._catalog
632
633    @property
634    def name(self) -> str:
635        return launch_name_of(self.s)
636
637    @property
638    def profile(self) -> str:
639        return "launch-" + self.name
640
641    def _env(self) -> dict[str, str]:
642        env = quiet_crash_env(dict(os.environ, PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8"))   # no debugger on a user's machine
643        env.pop("STRATA_NO_ACQUIRE", None)                  # launch is the explicit step that may download
644        if self.components_dir:
645            env["STRATA_COMPONENTS_DIR"] = self.components_dir
646        return env
647
648    def _spawn(self, argv: list[str], *, env: dict | None = None, cwd: str | None = None) -> subprocess.Popen:
649        kw = {"creationflags": subprocess.CREATE_NO_WINDOW} if WINDOWS else {}
650        p = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
651                             encoding="utf-8", errors="replace", env=env or self._env(), cwd=cwd, bufsize=1, **kw)
652        self.children.append(p)
653        return p
654
655    def _stop_children(self) -> None:
656        """End only the processes this runner started (by the handles it holds)."""
657        for p in self.children:
658            if p.poll() is None:
659                try:
660                    p.terminate()
661                    p.wait(timeout=15)
662                except Exception:                            # noqa: BLE001
663                    try:
664                        p.kill()
665                    except Exception:                        # noqa: BLE001
666                        pass
667
668    def _cli(self, *args: str) -> list[str]:
669        return [self.python, str(ROOT / "strata.py"), *args]
670
671    def warn_wsl_amd(self) -> None:
672        """Under WSL the Linux AMD engines hang (no /dev/kfd, librocdxg never completes a GPU command): say so plainly with one next step,
673        and go on (a warning, never a refusal)."""
674        try:
675            from strata_control import engine_component as ec
676            note = ec.wsl_amd_note("hip") and ec.wsl_amd_note(ec.detect_backend()[0])    # the cheap file test first: no GPU tool is run on other systems
677        except Exception:                                    # noqa: BLE001 - a nicety, never a reason to stop
678            return
679        if note:
680            self.emit("engine", note, level="warn")
681            if note not in self.notices:
682                self.notices.append(note)
683
684    # ---- 1. the engine
685    def ensure_engine(self) -> None:
686        self.warn_wsl_amd()
687        shape = self.model_shape()
688        if shape:                                            # a Qwen4 model of its own shape: its engine is a separate component (strata_control/shape_engine.py)
689            self.ensure_shape_engine(shape)
690            return
691        self.emit("engine", "Checking the engine for this computer…")
692        from strata_control import engine_component as ec
693        root = Path(self.components_dir) if self.components_dir else None
694        report = ec.status(root)
695        stale = None
696        if report.get("usable"):
697            eng = report["engine"]
698            stale = self.stale_engine(eng.get("version"))
699            if not stale:
700                self.emit("engine", f"Engine {eng['version']} ({eng['backend']}) is installed.", 100)
701                return
702        feed = self.feed or os.environ.get("STRATA_UPDATE_FEED")
703        if stale:
704            blocked = self.stale_update_blocked(stale)
705            if blocked:                                      # an engine update is the person's choice, and never beside a loaded model
706                self.notices.append(blocked)
707                self.emit("engine", blocked, 100, level="warn")
708                return
709            self.emit("engine", stale + " Looking for a newer one…", 0, level="warn")
710        else:
711            self.emit("engine", "No engine is installed yet. Getting the one for your graphics card…", 0)
712        argv = self._cli("update", "--no-control", "--output", "jsonl")
713        if feed:
714            argv += ["--feed", feed]
715        if self.components_dir:
716            argv += ["--components-dir", self.components_dir]
717        env = self._env()
718        for key, value in self.s.extra.items():              # the engine's own environment settings (device selectors, ...) apply to its test start too
719            if not key.startswith("--") and value.lower() not in ("off", "unset", "none"):
720                env[key] = value
721        p = self._spawn(argv, env=env)
722        last = None
723        tail: list[str] = []
724        for line in p.stdout:                                # type: ignore[union-attr]
725            self.check_cancel()
726            line = line.strip()
727            if not line:
728                continue
729            try:
730                ev = json.loads(line)
731            except ValueError:
732                tail.append(line)
733                continue
734            if ev.get("event") == "progress":
735                self.emit("engine", f"Downloading the engine… {ev.get('percent', 0)}%", float(ev.get("percent", 0)))
736            elif ev.get("event") in ("phase", "waiting"):
737                if ev.get("phase") == "warn":
738                    self.emit("engine", str(ev.get("message") or ""), level="warn")
739                else:
740                    self.emit("engine", str(ev.get("message") or ""))
741            last = ev
742        code = p.wait()
743        if stale:
744            # an engine is there and was too old: warn, never refuse (round 8, M: 0.1.45.3 was reused although 0.1.47 existed, and Gyro-S failed
745            # on kernels only the newer engine has). Whatever the update did, say where it stands.
746            after = ec.status(root)
747            now = (after.get("engine") or {}).get("version") if after.get("usable") else None
748            still = self.stale_engine(now) if now else stale
749            if still:
750                self.notices.append(still + " Run `strata update`, then start it again.")
751                self.emit("engine", still + (" The update did not bring a newer one." if code == 0 else " The update did not finish.") +
752                          " Run `strata update`, then start it again.", 100, level="warn")
753            else:
754                self.emit("engine", f"Engine {now} is installed.", 100)
755            return
756        if code == 0:
757            # `strata update` exits 0 when the feed simply has no engine for this PC (or only one for another card family). That is not an
758            # engine: refuse here, before the model (tens of GB) is touched.
759            after = ec.status(root)
760            if not after.get("usable"):
761                self.no_engine(self._no_engine_words(last, after))
762                return
763        if code != 0:
764            why = ""
765            if isinstance(last, dict):
766                why = str((last.get("error") or {}).get("message") or last.get("message") or "")
767                if not why:
768                    for res in last.get("results") or []:
769                        if isinstance(res, dict) and res.get("status") == "failed" and res.get("error"):
770                            why = str(res["error"])
771                            break
772            why = why or (tail[-1] if tail else "")
773            why = capital(why)                         # (joined after a sentence: "the update feed could not be read ..." starts a new one)
774            raise LaunchError("The engine could not be installed." + (f" {why}" if why else ""),
775                              "Check your internet connection, or point Strata at an update source with --feed, then try again.", 6)
776        self.emit("engine", "The engine is installed.", 100)
777
778    def stale_update_blocked(self, stale: str) -> str | None:
779        """The engine here is older than this model needs. Updating it is the person's choice (owner, 11-01: an engine update never starts by itself):
780        None when they said yes (--yes, or the answer to the question on the screens), else the one plain sentence that says why nothing was
781        updated and the next step. A model that is loaded blocks it whatever was answered. Warn, never refuse: the launch goes on."""
782        from strata_control import engine_update, updater
783        try:
784            models = engine_update.running_models(updater.serving_now())
785        except Exception:                                    # noqa: BLE001 - not knowing is not a reason to update
786            models = []
787        if models:
788            names = ", ".join(m.label for m in models)
789            return (f"{stale} {names} {'is' if len(models) == 1 else 'are'} running, so Strata did not update the engine. "
790                    "Stop it (`strata launch --stop`), run `strata update`, then start again.")
791        if self.assume_yes:
792            return None
793        if self.confirm is not None and self.confirm("Update the engine?", stale + " Update it now? Nothing else is changed; your models are kept."):
794            return None
795        return stale + " Strata did not update it. Run `strata update` (or start with --yes) and start again."
796
797    def model_shape(self) -> str | None:
798        """The model shape whose own engine runs the chosen model (a feed model of a shape other than Flash-Next's: setup's FAMILIES entry has "shape"), or None."""
799        try:
800            fam = (getattr(self.catalog.strata.setup_module(), "FAMILIES", None) or {}).get(self.s.family) or {}
801            shape = fam.get("shape")
802            return shape if isinstance(shape, str) and shape else None
803        except Exception:                                    # noqa: BLE001 - no table, no shape: the Strata engine
804            return None
805
806    def model_title(self) -> str | None:
807        """The chosen model's title ("Q4 Lite Shape"), which the lines about its engine name instead of the geometry's name; None when the table has none."""
808        try:
809            title = ((getattr(self.catalog.strata.setup_module(), "FAMILIES", None) or {}).get(self.s.family) or {}).get("title")
810            return title if isinstance(title, str) and title else None
811        except Exception:                                    # noqa: BLE001
812            return None
813
814    def ensure_shape_engine(self, shape: str) -> None:
815        """Step 1 for a model of its own shape: the engine of that shape is installed (and the feed's newer one fetched), next to the Strata engine, which is not touched."""
816        import argparse
817        from strata_cli import update_cmd
818        from strata_control import engine_component as ec, shape_engine
819        root = Path(self.components_dir) if self.components_dir else None
820        title = self.model_title()
821        name = shape_engine.shown(shape, title)
822        self.emit("engine", shape_engine.WORDS["checking"].format(model=name))
823        source = update_cmd._feed_source(argparse.Namespace(feed=self.feed or os.environ.get("STRATA_UPDATE_FEED")), root or ec.components_dir())
824        said: list[str] = []
825        exe = shape_engine.ensure(shape, source, components=root, emit=lambda m: (said.append(m), self.emit("engine", m, 0)), title=title,
826                                  automatic=True)     # with an engine installed, a check nobody asked for (netpolicy rule 4b)
827        if exe is None:
828            self.no_engine(said[-1] if said else shape_engine.WORDS["fetch_failed"].format(model=name, why="nothing was fetched"))
829            return
830        found = shape_engine.find(shape, root, full=False, title=title)
831        self.emit("engine", shape_engine.WORDS["ready"].format(model=name, version=found.version, backend=found.backend), 100)
832
833    def needed_engine(self) -> tuple[int, ...] | None:
834        """The oldest engine this model runs on, from setup.py's own tables (MIN_ENGINE for everything, GYRO_ENGINE for Gyro), or None."""
835        try:
836            mod = self.catalog.strata.setup_module()
837            need = tuple(getattr(mod, "MIN_ENGINE", ()) or ())
838            if self.s.family == "gyro":
839                need = max(need, tuple(getattr(mod, "GYRO_ENGINE", ()) or ()))
840                if sys.platform == "darwin":
841                    need = max(need, GYRO_METAL_ENGINE)      # the Metal Gyro kernels (TQK6/TQK7/TQ2_T) first shipped in 0.1.47; CUDA, HIP, SYCL had them earlier
842            return need or None
843        except Exception:                                    # noqa: BLE001 - no table, no check
844            return None
845
846    def stale_engine(self, version: str | None) -> str | None:
847        """A plain sentence when the installed engine is older than the model needs, else None."""
848        have = version_tuple(version)
849        need = self.needed_engine()
850        if not have or not need or have >= need:
851            return None
852        return f"The engine installed here ({version}) is older than this model needs ({'.'.join(map(str, need))} or newer)."
853
854    def no_engine(self, reason: str) -> None:
855        """There is no engine for this computer and none to get. This is a warning, not a refusal: the model may still be downloaded, because
856        the engine can be installed afterwards. Ask first (the answer is yes unless the person says no; --yes skips the question) when a
857        download is about to happen; otherwise just remember the problem for the final message."""
858        self.engine_problem = reason
859        warning = no_engine_warning(reason)
860        self.emit("engine", warning, 100, level="warn")
861        if self.assume_yes or self.confirm is None:
862            return
863        try:
864            gb = self.download_gb()
865        except Exception:                                    # noqa: BLE001
866            gb = 0.0
867        if gb < 0.05:
868            return                                           # nothing would be downloaded: no question, only the final message
869        if not self.confirm("No engine for this computer yet", warning + f" Download the model now (about {gb:.0f} GB)?"):
870            raise LaunchError("Stopped. Nothing was downloaded.", "Install the engine first, or run this again and answer yes.", 130)
871
872    @staticmethod
873    def _no_engine_words(last: object, report: dict) -> str:
874        """The one plain sentence for "no usable engine for this PC": the update's own note (the wrong-card-family line, or "the feed has no
875        engine package for this PC"), else the engine report's plain notice. Never the raw list of reasons."""
876        note = ""
877        if isinstance(last, dict):
878            for res in last.get("results") or []:
879                if isinstance(res, dict) and res.get("component") == "engine":
880                    note = str(res.get("note") or "").strip()
881        if not note:
882            note = str(report.get("notice") or "").strip()
883        if "backend" in report and report["backend"] is None:                    # not even a graphics card Strata knows: say that, not "the feed has nothing"
884            names = []
885            try:
886                from strata_control import engine_component as ec
887                names = [a.get("name", "") for a in ec.windows_display_adapters()] if os.name == "nt" else []
888            except Exception:                                # noqa: BLE001 - the names are a nicety
889                pass
890            return no_gpu_words(names)
891        if not note or note.startswith("No engine for this PC was found"):
892            note = "There is no engine for this computer's graphics card in the update source."
893        return note
894
895    # ---- 2. the model
896    def resolved_vision(self) -> str:
897        """The picture setting of this launch: the chosen one, or (nothing chosen) the default for this model and engine (catalog.picture_default)."""
898        s = self.s
899        if s.vision is None:
900            row = next((r for r in self.catalog.rows() if (r.family, r.model) == (s.family, s.model)), None)
901            s.vision = self.catalog.picture_default(bool(row.images) if row is not None else False)
902        return s.vision
903
904    def vision_word(self) -> str:
905        """What setup is told for the picture choice. "on" is setup's "yes": setup (Control mode) picks the CPU encoder on a card under 24 GB
906        and the GPU encoder from 24 GB (any make of card), and downloads the pinned picture-reader file (mmproj) with the model."""
907        s = self.s
908        self.resolved_vision()
909        if s.vision == "off":
910            return "no"
911        return "yes" if s.vision == "on" else s.vision
912
913    def check_pictures(self, path: Path) -> None:
914        """Pictures were asked for: say so in plain words when the installed settings still have them off."""
915        s = self.s
916        if s.vision == "off":
917            return
918        try:
919            desc = self.catalog.strata.describe_config(path)
920        except Exception:                                    # noqa: BLE001
921            return
922        if (desc or {}).get("images") in (None, "off"):
923            note = ("Pictures could not be switched on: this engine does not carry the picture reader, or this model cannot read pictures, "
924                    "so it will answer text only.")
925            self.notices.append(note)
926            self.emit("model", note, 100, level="warn")
927
928    def setup_args(self) -> list[str]:
929        cat, s = self.catalog, self.s
930        fam, model = s.family, s.model
931        try:                     # a saved preset or choices file keeps the lower-case tag ("iq3_xxs", #4209), while setup's
932            fam, model = cat.resolve(str(model), None if fam is None else str(fam))    # --model takes the table's own key
933        except Exception:        # noqa: BLE001  a name the list does not hold, or a list that cannot be read here, is setup's
934            pass                 # to report: passing the values on unchanged keeps the launch behaving as it did before
935        args = ["--yes", "--no-start", "--family", str(fam), "--model", str(model)]
936        ctx = s.context
937        if ctx:
938            args += ["--context", str(ctx)]
939        args += ["--vision", self.vision_word()]
940        if s.kv:
941            args += ["--kv", s.kv]
942        if fam in ("qwen", "coder"):
943            args += ["--experimental-speed-projection", "off"]
944        layer_fetch = getattr(self, "_layer_fetch", False)  # the start's safety net (fetch_missing_drafter): setup fetches the draft layer
945        resolved = "mtp" if layer_fetch else self.resolved_drafting(fam)
946        mtp_word = s.mtp if resolved != "off" else "off"
947        if mtp_word is None and (layer_fetch or self.layer_back()):
948            mtp_word = "on"                                  # a drafter chosen again after Off: the "mtp": false that Off's "--mtp off" left goes (REAL-USE-1)
949        if mtp_word in ("on", "off") and fam in modelstate.HELPER_FAMILIES:
950            args += ["--mtp", mtp_word]                      # round 8, N3: "--mtp off" never reached setup, which then fetched the 5.2 GB draft layer
951        if resolved == "dflash2" and fam in modelstate.HELPER_FAMILIES and mtp_word != "off":
952            args += ["--drafter", "dflash2"]                 # one drafter per run: a new install fetches DFlash2's pack (below), not the MTP layer
953        data = s.data_dir or self.existing_data_dir()
954        if data:
955            args += ["--data-dir", str(data)]
956            if self.move_data and s.data_dir:             # only when the person said so: setup moves nothing otherwise
957                args.append("--move-data")
958            if s.data_dir:                                # a folder the person chose is remembered for the next start and for the app
959                args.append("--set-default-data-dir")
960        if s.model_path:
961            p = Path(s.model_path)
962            args += ["--gguf-dir", str(p if p.is_dir() else p.parent)]
963        if self.feed:                                     # --feed / STRATA_UPDATE_FEED: setup reads the signed feed from there too
964            args += ["--feed", str(self.feed)]
965        if s.gpu_roles:
966            args += ["--gpu-roles", ",".join(f"{k}={v}" for k, v in sorted(s.gpu_roles.items(), key=lambda kv: int(kv[0])))]
967        elif s.gpus:
968            args += ["--gpus", ",".join(str(g) for g in s.gpus)] if len(s.gpus) > 1 else ["--gpu", str(s.gpus[0])]
969        else:
970            args += self.installed_card_args()
971        if sys.platform == "darwin":
972            # a Mac's setup (Control mode, strata_control/mac_fit.py) takes fewer options (no --kv, --gpu, speed projection)
973            keep = {"--yes", "--no-start", "--family", "--model", "--context", "--vision", "--data-dir", "--gguf-dir", "--move-data",
974                    "--set-default-data-dir", "--feed", "--drafter", "--mtp"}     # --drafter / --mtp: setup.py's Mac step fetches the draft layer only where the
975                                                                                  # start runs the MTP, and not after a Drafting Off (`--mtp off`)
976            flags = ("--yes", "--no-start", "--move-data", "--set-default-data-dir")
977            out, i = [], 0
978            while i < len(args):
979                if args[i] in keep:
980                    out.append(args[i])
981                    if args[i] not in flags and i + 1 < len(args):
982                        out.append(args[i + 1])
983                    i += 2 if args[i] not in flags else 1
984                else:
985                    i += 2 if i + 1 < len(args) and not args[i + 1].startswith("--") else 1
986            args = out
987        return args
988
989    def installed_card_args(self) -> list[str]:
990        """--gpu-roles / --gpus of the installed config when the launch names no cards itself. A change of context or pictures runs setup again;
991        without these it picked the cards and the Main/Helper roles afresh and reset an explicit choice (round 8, F3: 0=main,1=helper
992        came back as 0=helper,1=main). Only a choice that was made ("gpus_asked" / roles) is forwarded, never the automatic pick."""
993        try:
994            path, _desc = self.installed_state()
995            base = read_config(path) if path is not None else None
996            if not isinstance(base, dict):
997                return []
998            roles = base.get("gpu_roles")
999            if isinstance(roles, dict) and roles:
1000                return ["--gpu-roles", ",".join(f"{k}={v}" for k, v in sorted(roles.items(), key=lambda kv: int(kv[0])))]
1001            try:
1002                usable_now = self.catalog.computer().usable_gpus
1003            except Exception:                                # noqa: BLE001
1004                usable_now = None
1005            cards = installed_cards(base, usable_now)
1006            if cards:
1007                return ["--gpus", ",".join(str(g) for g in cards)] if len(cards) > 1 else ["--gpu", str(cards[0])]
1008        except Exception:                                    # noqa: BLE001 - never block a launch over remembering the cards
1009            pass
1010        return []
1011
1012    def installed_state(self) -> tuple[Path | None, dict | None]:
1013        tag = self.catalog.tag_of(self.s.family, self.s.model)
1014        path = self.catalog.installed_config(tag)
1015        if path is None:
1016            return None, None
1017        desc = self.catalog.strata.describe_config(path)
1018        return path, desc
1019
1020    def layer_back(self, path: Path | None = None) -> bool:
1021        """A drafter is named at this launch (Auto, MTP or DFlash2, not Off; no --mtp) while the installed config says "mtp": false: a Drafting Off launch hands
1022        setup "--mtp off", and setup keeps that at every later run, so Auto read it as "the draft layer is off" and started without a drafter (0.2.13.1, REAL-USE-1).
1023        Then setup runs again with "--mtp on", and the start is the one a first launch with that choice gets.  A model the feed says has no draft layer stays off."""
1024        s = self.s
1025        if s.mtp is not None or s.drafting is None or s.family not in modelstate.HELPER_FAMILIES:
1026            return False                                     # (a Mac's setup takes the --mtp word too: setup_args)
1027        from strata_control import drafting
1028        if drafting.normalize(s.drafting) == "off" or self.resolved_drafting(s.family) == "off":
1029            return False
1030        try:
1031            if path is None:
1032                path = self.catalog.installed_config(self.catalog.tag_of(s.family, s.model))
1033            return path is not None and read_config(path).get("mtp") is False
1034        except Exception:                                    # noqa: BLE001 - an unreadable config is setup's to report; nothing changes here
1035            return False
1036
1037    def installed_serves_request(self, path: Path) -> bool:
1038        """C08: the installed copy is what this launch asked for. A --model-path (or the Folder step's own files) and a --data-dir always win:
1039        when the installed config names files outside them, it is not reused (that served another copy without a word) and setup runs with
1040        the given folders, which rewrites the config so the profile follows."""
1041        s = self.s
1042        if not (s.model_path or s.data_dir):
1043            return True
1044        try:
1045            cfg = read_config(path)
1046            args = [str(a) for a in cfg.get("args") or []]
1047            if s.model_path:
1048                want = Path(s.model_path).expanduser().resolve()
1049                folder = want if want.is_dir() else want.parent
1050                ggufs = [Path(a) for a in args if a.lower().endswith(".gguf")]
1051                if not ggufs or not all(_inside(g.resolve(), folder) for g in ggufs):
1052                    return False
1053                if s.data_dir:
1054                    packs = [Path(args[i + 1]) for i, a in enumerate(args[:-1]) if a == "--pack"]
1055                    return all(_inside(pk.resolve(), Path(s.data_dir).expanduser().resolve()) for pk in packs)
1056                return True
1057            from strata_control import discovery
1058            found = discovery.footprint(cfg, path).data_dir
1059            return found is not None and os.path.normcase(str(Path(found).resolve())) == os.path.normcase(str(Path(s.data_dir).expanduser().resolve()))
1060        except Exception:                                    # noqa: BLE001 - when in doubt do what was asked: run setup with the given folders
1061            return False
1062
1063    def existing_data_dir(self) -> Path | None:
1064        """The data folder to give setup when the person chose none: the folder the model already lives in (its run config names its files),
1065        else the folder the desktop app uses, so a helper file that is missing is fetched next to the rest, never into a second folder.
1066        None: setup's own default is right."""
1067        s = self.s
1068        try:
1069            if s.model_path:
1070                from strata_control import discovery
1071                # the folder above the person's own files only when Strata may keep its files there (writable, not a Hugging Face cache);
1072                # else setup's default data folder (lane NET item 5; beside_refused() says so)
1073                found = discovery.writable_beside(self._first_own_gguf())
1074                return Path(found) if found else None
1075            if s.family and s.model:
1076                path = self.catalog.installed_config(self.catalog.tag_of(s.family, s.model))
1077                if path is not None:
1078                    from strata_control import discovery
1079                    found = discovery.footprint(read_config(path), path).data_dir
1080                    if found is not None:
1081                        return found
1082            found, source = self.catalog.data_dir_choice()
1083            return found if source != "default" else None
1084        except Exception:                                    # noqa: BLE001
1085            return None
1086
1087    def _first_own_gguf(self) -> Path | None:
1088        s = self.s
1089        if not s.model_path:
1090            return None
1091        try:
1092            p = Path(s.model_path)
1093            return next(iter(sorted(p.glob("*.gguf"))), None) if p.is_dir() else p
1094        except OSError:
1095            return None
1096
1097    def beside_refused(self) -> Path | None:
1098        """The data folder guessed from the person's own files (the folder above a `models` folder) when Strata does not use it for its own files
1099        because it cannot write there or it is inside a Hugging Face cache; None when it is used or there is none."""
1100        s = self.s
1101        if not s.model_path or s.data_dir:
1102            return None
1103        try:
1104            from strata_control import discovery
1105            first = self._first_own_gguf()
1106            found = discovery.prepared_beside(first)["data_dir"] if first else None
1107            if found is None or discovery.writable_beside(first) is not None:
1108                return None
1109            return Path(found)
1110        except Exception:                                    # noqa: BLE001
1111            return None
1112
1113    def model_state(self):
1114        """What this launch still needs for the model, in numbers and words (strata_cli/launch/modelstate.py)."""
1115        from strata_cli.launch import modelstate
1116        s = self.s
1117        self.resolved_vision()
1118        path, desc = (None, None)
1119        installed = True
1120        if s.family and s.model and not s.model_path:
1121            path, desc = self.installed_state()
1122            if path is not None and self.other_copy() is not None:
1123                # the copy that is installed is not what this launch uses (another --data-dir): the start runs setup with the given folder, so
1124                # the plan counts what setup fetches there, not the other copy (lane NET 4a)
1125                path, desc, installed = None, None, False
1126        return modelstate.assess(self.catalog, s.family, s.model, vision=s.vision, model_path=s.model_path, data_dir=s.data_dir,
1127                                 config=path, desc=desc, mtp=s.mtp, drafting=self.resolved_drafting(s.family), use_installed=installed)
1128
1129    def other_copy(self) -> Path | None:
1130        """The data folder of an installed copy of this model that this launch does not use, else None: another --data-dir was given, and the
1131        copy is not in a folder setup itself takes model files from (setup.data_folder_for keeps the remembered data folder and Strata's own
1132        folder as sources and uses complete files there where they are; any other folder it does not look at, so everything is fetched)."""
1133        s = self.s
1134        if not (s.family and s.model and s.data_dir) or s.model_path:
1135            return None
1136        try:
1137            path, _desc = self.installed_state()
1138            if path is None or self.installed_serves_request(path):
1139                return None
1140            from strata_control import discovery
1141            found = discovery.footprint(read_config(path), path).data_dir
1142            if found is None:
1143                return None
1144            here = Path(found).resolve()
1145            for source in (self.catalog.data_dir(), Path(self.catalog.root)):
1146                try:
1147                    src = Path(source).resolve()
1148                except (OSError, TypeError):
1149                    continue
1150                if here == src or here == src / "Strata-data":
1151                    return None                              # setup reuses it: the plan's installed answer is the start's
1152            return found
1153        except Exception:                                    # noqa: BLE001 - a plan line, never a reason to stop
1154            return None
1155
1156    def download_gb(self) -> float:
1157        """How much would be downloaded for this launch right now: 0 when everything is on disk (the model is installed with these choices
1158        or is the person's own files). A model whose helper files are missing counts only those files, never the whole model."""
1159        s = self.s
1160        if not (s.family and s.model) and not s.model_path:
1161            return 0.0
1162        try:
1163            return float(self.model_state().remaining_gb)
1164        except Exception:                                    # noqa: BLE001
1165            return 0.0
1166
1167    def start_wait(self) -> int:
1168        """How long the start waits for the model to be ready (#3949 #3459): 10 minutes, more for a big model, which a slow disk needs
1169        longer to read (about 8 more seconds per GB above 40 GB, at most 30 minutes). Automatic: nobody sets a variable for it."""
1170        gb = 0.0
1171        try:
1172            row = next((r for r in self.catalog.rows() if r.family == self.s.family and r.model == self.s.model), None)
1173            gb = float(getattr(row, "download_gb", 0) or 0)
1174        except Exception:                                    # noqa: BLE001
1175            gb = 0.0
1176        return int(min(runtime_max_wait(), max(600, 600 + (gb - 40.0) * 8.0)))
1177
1178    def download_question(self) -> tuple[str, str]:
1179        """(title, text) of the question before a download starts, naming exactly what is fetched."""
1180        return self.model_state().question()
1181
1182    #: seconds of silence from setup before a "still working" line (packing a 40 GB model prints nothing for minutes)
1183    HEARTBEAT_S = 30.0
1184
1185    def _read_lines(self, p: subprocess.Popen):
1186        """The lines setup prints, and None whenever a second passes with none, so a silent step can say it is still going and a cancel is
1187        seen at once."""
1188        import queue
1189        q: queue.Queue = queue.Queue()
1190
1191        def pump() -> None:
1192            try:
1193                for ln in p.stdout:                          # type: ignore[union-attr]
1194                    q.put(ln)
1195            finally:
1196                q.put(_END)
1197        threading.Thread(target=pump, daemon=True).start()
1198        while True:
1199            try:
1200                ln = q.get(timeout=min(1.0, max(0.05, self.HEARTBEAT_S / 2)))
1201            except queue.Empty:
1202                yield None
1203                continue
1204            if ln is _END:
1205                return
1206            yield ln
1207
1208    def progress_job(self) -> dict:
1209        """What the download figure is counted over: the folder setup writes the model into (the data folder it is GIVEN, which may be the
1210        person's --data-dir and not the default one) and every file of the install with the catalog's total, so a model in several shards
1211        shows 'of 66.4 GB' from the start and not the size of the file being fetched."""
1212        s, cat = self.s, self.catalog
1213        data = Path(s.data_dir) if s.data_dir else (self.existing_data_dir() or cat.data_dir())
1214        models_dir = data / "models"
1215        job = {"folder": str(cat.model_folder(data, s.family, s.model)),
1216               "total_gb": float(next((r.download_gb for r in cat.rows() if r.family == s.family and r.model == s.model), 0) or 0)}
1217        try:
1218            setup_module = cat.strata.setup_module()
1219            if setup_module is not None and not s.model_path:
1220                job["files"] = cat.mcp.expected_files(setup_module, str(s.family), str(s.model), models_dir, self.vision_word() != "no")
1221                first = next((f for f in job["files"] if f.get("role") == "model"), None)
1222                if first:                                    # the folder setup names it (Q2_0), not the lower-case run-config tag (q2_0)
1223                    job["folder"] = str(Path(first["path"]).parent)
1224        except Exception:                                    # noqa: BLE001 - progress is a convenience; the folder scan still counts
1225            pass
1226        return job
1227
1228    def ensure_model(self) -> Path:
1229        s, cat = self.s, self.catalog
1230        self.check_own_files()
1231        self.resolved_vision()
1232        if not (s.family and s.model):
1233            raise LaunchError("No model was chosen.", "Choose a model, or use --model NAME (strata launch --help lists them).", 2)
1234        path, desc = self.installed_state()
1235        if path is not None and desc is not None and desc_matches(desc, s) and not files_present(read_config(path)) and not self.layer_back(path) \
1236                and not getattr(self, "_layer_fetch", False):
1237            if self.installed_serves_request(path):
1238                self.emit("model", f"{s.family} {s.model} is already installed with these choices.", 100)
1239                return path
1240            self.emit("model", "The model already installed here is somewhere else than the folder you gave, so Strata uses the folder you gave "
1241                               "and points this launch at it.", 0)
1242        title = f"{s.family} {s.model}"
1243        try:                                                 # the name on screen
1244            title = next((r.title for r in self.catalog.rows() if r.family == s.family and r.model == s.model), title)
1245        except Exception:                                    # noqa: BLE001 - a label only
1246            pass
1247        if sys.platform == "darwin" and not (cat.src / "strata_control" / "mac_fit.py").is_file():
1248            # a Terminal from before the Mac rules moved into strata_control/mac_fit.py: setup.py cannot install a Mac model in its Control
1249            # mode (no source build, no setup_mac.py), so use model files prepared on this Mac. Every other Terminal installs through setup.py.
1250            adopted = self.adopt_prepared_files("no Mac model installer in this Terminal")
1251            if adopted is not None:
1252                return adopted
1253        if self.intel_chosen():
1254            adopted = self.adopt_prepared_files("", chosen=True)
1255            if adopted is not None:
1256                return adopted
1257        self.emit("model", f"Preparing {title} from your model files…" if s.model_path else
1258                  f"Getting {title} ready (a download may be large; it continues where it stopped if interrupted)…", 0)
1259        refused = self.beside_refused()
1260        if refused is not None:                              # lane NET item 5 (W9): the files stay, Strata's own go to the data folder
1261            from strata_control import discovery
1262            why = (f"{refused} is a Hugging Face download folder, so Strata" if discovery.in_hf_cache(refused) or discovery.in_hf_cache(refused / "models")
1263                   else f"Strata can't write in {refused}, so it")   # (W9 / W9b, owner 11-10)
1264            note = (f"Your model files are used where they are. {why} keeps its own files (the prepared data and "
1265                    f"the picture reader) in {cat.data_dir()}.")
1266            self.notices.append(note)
1267            self.emit("model", note, None)
1268        argv = [self.python, str(cat.src / "setup.py"), *self.setup_args()]
1269        env = self._env()
1270        env.update(STRATA_CONTROL_INSTALL="1", STRATA_INSTALL_DIR=str(cat.root), PYTHONNOUSERSITE="1")
1271        env.pop("STRATA_NEED_ENGINE", None)
1272        if self.engine_problem:
1273            env["STRATA_ALLOW_NO_ENGINE"] = "1"              # the person said go on: setup warns about the engine instead of stopping
1274        else:
1275            env["STRATA_NEED_ENGINE"] = "1"
1276        for k in ("PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV"):
1277            env.pop(k, None)
1278        env["PYTHONPATH"] = str(cat.src)
1279        p = self._spawn(argv, env=env, cwd=str(cat.src))
1280        lines: list[str] = []
1281        already: bool | None = None                          # all the model's files were on disk before this run wrote anything
1282        job = self.progress_job()
1283        step_seen, step_since, quiet_since, said = None, time.monotonic(), time.monotonic(), None
1284        for line in self._read_lines(p):
1285            if self.cancel.is_set():
1286                self._stop_children()
1287                self.keep_setup_output(lines + [f"(you stopped it{': ' + said[0] if said else ''})"])   # the log says where it stood
1288                raise Cancelled()
1289            if line is None:                                 # nothing printed for a while: the long steps (packing, converting) are silent
1290                if said and time.monotonic() - quiet_since >= self.HEARTBEAT_S:     # (the download phase too: a server that does not answer is silent)
1291                    quiet_since = time.monotonic()
1292                    self.emit("model", f"{said[0]} (still working, {_elapsed(time.monotonic() - step_since)} so far)", None, step=step_seen)
1293                continue
1294            quiet_since = time.monotonic()
1295            line = line.rstrip()
1296            if not line:
1297                continue
1298            lines.append(line)
1299            lines[:] = lines[-1500:]
1300            prog = cat.mcp.install_progress(lines)
1301            prog = cat.mcp.combined_progress(prog, job)
1302            dl, phase, label = prog.get("download"), prog.get("phase"), prog.get("label")
1303            if prog.get("step") != step_seen:
1304                step_seen, step_since = prog.get("step"), time.monotonic()
1305            said = (label, phase) if label else None
1306            if phase == "waiting":                           # setup is waiting for a server to answer: say which one (netpolicy's line)
1307                self.emit("model", label, None, step=prog.get("step"))
1308            elif dl and dl.get("total_gb", 0) >= 0.05 and not (s.model_path and phase == "download"):
1309                if phase == "download" and already is None:
1310                    already = float(dl["percent"]) >= 99.5
1311                text = download_text(dl, bool(already) and phase == "download", label)
1312                self.emit("model", text, float(dl["percent"]), step=prog.get("step"))
1313            elif label:
1314                self.emit("model", label, None, step=prog.get("step"))
1315            elif prog.get("step"):
1316                self.emit("model", f"Setup step {prog['step']}", None, step=prog.get("step"))
1317        code = p.wait()
1318        self.note_setup_lines(lines)
1319        if code != 0:
1320            err = ""
1321            for line in reversed(lines):
1322                if line.strip().startswith("[X]"):
1323                    err = line.strip()[3:].strip()
1324                    break
1325            hint = ""
1326            if err:
1327                for i, line in enumerate(lines):
1328                    if err in line and i + 1 < len(lines) and lines[i + 1].startswith("       "):
1329                        hint = lines[i + 1].strip()
1330            adopted = self.adopt_prepared_files(err)
1331            if adopted is not None:
1332                return adopted
1333            raise setup_failure(lines, err, hint, self.keep_setup_output(lines), bool(s.model_path))
1334        path, _desc = self.installed_state()
1335        if path is None:
1336            raise LaunchError("Setup finished but no run config was written for this model.",
1337                              "Run `strata launch` again; if it repeats, the setup output above says why.", 6)
1338        self.emit("model", f"{title} is ready.", 100)
1339        self.say_reused_data(path)
1340        self.check_pictures(path)
1341        return path
1342
1343    def say_reused_data(self, path: Path) -> None:
1344        """C08 note: your own model files are used where they are, and when the prepared pack or the draft layer are read from another data folder
1345        than the one given, one line says where from."""
1346        s = self.s
1347        if not (s.model_path and s.data_dir):
1348            return
1349        try:
1350            args = [str(a) for a in read_config(path).get("args") or []]
1351            want = Path(s.data_dir).expanduser().resolve()
1352            elsewhere = []
1353            for flag, label in (("--pack", "the prepared pack"), ("--mtp", "the draft layer")):
1354                if flag in args and args.index(flag) + 1 < len(args):
1355                    value = args[args.index(flag) + 1]
1356                    if value.isdigit():
1357                        continue
1358                    place = Path(value).expanduser().resolve()
1359                    if not _inside(place, want):
1360                        elsewhere.append((label, place))
1361            if elsewhere:
1362                folders = sorted({str(pl.parent.parent if pl.parent.name in ("packs", "mtp") else pl.parent) for _l, pl in elsewhere})
1363                text = (f"{' and '.join(l for l, _p in elsewhere).capitalize()} {'is' if len(elsewhere) == 1 else 'are'} read from "
1364                        f"{', '.join(folders)}, not from {want}; nothing was copied.")
1365                self.notices.append(text)
1366                self.emit("model", text, 100)
1367        except (OSError, ValueError):
1368            pass
1369
1370    def keep_setup_output(self, lines: list[str]) -> str | None:
1371        """The last lines setup.py printed, kept next to the launch's other logs so a failed install can be read afterwards (the message
1372        shows one line; a traceback needs the rest). Best effort: None when it cannot be written."""
1373        try:
1374            folder = launch_dir()
1375            folder.mkdir(parents=True, exist_ok=True)
1376            path = folder / f"{self.name}.setup.log"
1377            path.write_text("\n".join(lines[-400:]) + "\n", encoding="utf-8", errors="replace")
1378            return str(path)
1379        except (OSError, ValueError):
1380            return None
1381
1382    def intel_chosen(self) -> bool:
1383        """The engine for this launch is the Intel Arc one (chosen with --backend intel, saved, or the only make here), and the model is one
1384        the built-in downloader sets up for NVIDIA and AMD only: Strata prepares the model files itself instead (adopt_prepared_files)."""
1385        if sys.platform == "darwin" or WINDOWS:
1386            return False
1387        try:
1388            from strata_control import engine_component
1389            return engine_component.detect_backend()[0] == "sycl"
1390        except Exception:                                        # noqa: BLE001
1391            return False
1392
1393    def prepare_pack(self, model_dir: Path, pack: Path, shards: list) -> None:
1394        """Build the pack an Intel Arc run needs from the GGUF files (the step setup.py runs for NVIDIA and AMD cards): setup.py --prepare-pack
1395        fetches llama.cpp's gguf-py by itself and runs tools/iq_pack.py. Takes seconds to a few minutes; the draft layer is not built."""
1396        cat = self.catalog
1397        fam, model = self.s.family, self.s.model
1398        try:
1399            fam, model = cat.resolve(str(model), None if fam is None else str(fam))      # setup's own spelling (IQ2_XS, not iq2_xs)
1400        except Exception:                                    # noqa: BLE001
1401            pass
1402        self.emit("model", "Preparing the model files for this graphics card (once, a few minutes; nothing is downloaded except a small helper)…", 0)
1403        argv = [self.python, str(cat.src / "setup.py"), "--prepare-pack", str(pack), "--gguf-dir", str(model_dir),
1404                "--family", str(fam), "--model", str(model)]
1405        env = self._env()
1406        env.update(STRATA_CONTROL_INSTALL="1", STRATA_INSTALL_DIR=str(cat.root), PYTHONNOUSERSITE="1")
1407        for k in ("PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV"):
1408            env.pop(k, None)
1409        env["PYTHONPATH"] = str(cat.src)
1410        p = self._spawn(argv, env=env, cwd=str(cat.src))
1411        lines: list[str] = []
1412        for line in self._read_lines(p):
1413            if self.cancel.is_set():
1414                self._stop_children()
1415                raise Cancelled()
1416            if line is None:
1417                continue
1418            line = line.rstrip()
1419            if line:
1420                lines.append(line)
1421                lines[:] = lines[-400:]
1422        if p.wait() != 0:
1423            err = next((ln.strip()[3:].strip() for ln in reversed(lines) if ln.strip().startswith("[X]")), "")
1424            raise LaunchError("Strata could not prepare the model files for this graphics card" + (f": {err}" if err else "."),
1425                              "The last lines of the preparation are in " + (self.keep_setup_output(lines) or "the launch log")
1426                              + ". If it says the helper could not be downloaded, check the internet connection (proxy: set HTTPS_PROXY) and try again.", 5)
1427
1428    def adopt_prepared_files(self, setup_error: str, chosen: bool = False) -> Path | None:
1429        """The installer cannot set this graphics card up (Intel Arc, for one): if the model's files and prepared pack are already on disk,
1430        write the run config here (strata_cli/launch/adopt.py); else say what is missing."""
1431        from strata_cli.launch import adopt
1432        from strata_control import engine_component
1433        s, cat = self.s, self.catalog
1434        if not chosen and not adopt.setup_cannot_handle_this_card(setup_error):
1435            return None
1436        _models, families, _ctx, _src = cat.tables()
1437        fam = families.get(s.family or "", {})
1438        tag = cat.tag_of(s.family, s.model)
1439        data_dir = Path(s.data_dir) if s.data_dir else cat.data_dir()
1440        model_dir = Path(s.model_path) if s.model_path else data_dir / "models" / (fam.get("tag", "") + s.model)
1441        if model_dir.is_file():
1442            model_dir = model_dir.parent
1443        try:
1444            backend = engine_component.detect_backend()[0]
1445        except Exception:                                    # noqa: BLE001
1446            backend = None
1447        pack_dir = data_dir / "packs" / tag.lower()
1448        files = adopt.model_files(model_dir, s.family or "", fam) if fam.get("feed") else adopt.find_shards(model_dir)   # a feed model can be one GGUF
1449        if backend == "sycl" and files and not (pack_dir / "experts.bin").exists() and not (
1450                (pack_dir / "index.txt").exists() and (pack_dir / "tokenizer" / "vocab.json").exists()):
1451            self.prepare_pack(model_dir, pack_dir, files)
1452        cfg, problems = adopt.plan(family=s.family, model=s.model, model_dir=model_dir, data_dir=data_dir, src=cat.src,
1453                                   context=s.context or 32768, kv=s.kv, model_name=f"{fam.get('name', s.family)}-{s.model.lower()}", family_def=fam,
1454                                   log=cat.root / f"strata-{tag}.log", backend=backend,
1455                                   vram_gb=float(cat.computer().main_vram_gb or 0), notes=self.notices, pack_name=tag.lower())
1456        if cfg is None:
1457            if backend == "sycl":
1458                raise LaunchError("Strata cannot start this model on the Intel Arc card yet: " + "; ".join(problems) + ".",
1459                                  "Give the folder that holds the model's .gguf files with --model-path (Strata prepares them itself). "
1460                                  "Intel cards do not download models yet; see docs/INTEL_ARC.md.", 5)
1461            raise LaunchError("The installer cannot set up this graphics card yet, and the files Strata would need to write the settings itself are not all there: "
1462                              + "; ".join(problems) + ".",
1463                              "Use model files that were prepared on this computer already (folder + pack): for an Intel Arc card the steps are in docs/INTEL_ARC.md (the Terminal carries tools/iq_pack.py for the pack). Or install on a computer with an NVIDIA or AMD card.", 5)
1464        path = cat.root / f"strata-{tag}.json"
1465        adopt.write(path, cfg)
1466        self.notices.append("The downloader built into this Terminal sets up NVIDIA and AMD cards only (Intel Arc cards have a separate installer), so Strata wrote the "
1467                            f"run settings itself from the prepared model files already on this computer ({path.name}). No model files were downloaded.")
1468        self.emit("model", f"Used your prepared model files and wrote the run settings ({path.name}); this card is not one the built-in downloader sets up.", 100, level="warn")
1469        return path
1470
1471    def check_own_files(self) -> None:
1472        """The person's own model files, looked at once: a path that is not there or holds no model is said in plain words first, and the
1473        files are matched to the catalog model (resolve_own_files). Nothing else is done with a path that was already checked."""
1474        if self.s.model_path and not self._own_checked:
1475            self.resolve_own_files()
1476            self._own_checked = True
1477
1478    def resolve_own_files(self) -> None:
1479        """"Use model files I already have": the fingerprint table says which catalog model the files are, and which folder holds them (the
1480        person may have named the folder above it). When the person also named the model (--model), the files are never refused here: setup
1481        takes the files of that model out of the folder by name, as it always did (0.1.45), and says what is wrong when it cannot."""
1482        from strata_control import models
1483        s = self.s
1484        problem = models.own_path_problem(s.model_path)
1485        if problem:                                          # before the engine or setup are touched, with the path as typed
1486            raise LaunchError(problem[0], problem[1], 2)
1487        from strata_control import retired
1488        if retired.folder_reason(models.absolute(s.model_path)):   # DeepSeek files: named, never used (strata_control/retired.py)
1489            raise LaunchError(retired.own_files(models.absolute(s.model_path)), "", 2)
1490        given = bool(s.family and s.model)
1491        try:
1492            plan = models.plan_import(models.absolute(s.model_path))
1493        except Exception as e:                               # noqa: BLE001
1494            if given:
1495                return
1496            raise LaunchError(f"These model files cannot be used: {e}.", "Pick the folder with every shard of one model, or a .gguf file of it.", 5) from None
1497        if given:
1498            sel = plan.get("candidate_selection") or {}
1499            if sel.get("family") and sel.get("model") and (sel["family"], sel["model"]) != (s.family, s.model):
1500                # round 8, N8: --family swift was accepted for an IQ3_XXS file. The files are not refused (setup takes the named model's files
1501                # out of the folder by name), but the person is told what the file header says.
1502                words = (f"These files look like {sel['family']} {sel['model']} (by the file headers), not {s.family} {s.model}. "
1503                         f"Setup will look for {s.family} {s.model} files in that folder and may stop; to use these files, leave out --family and --model.")
1504                self.identity_notes.append(words)
1505                self.notices.append(words)
1506            hold = [h for h in plan.get("folder_holds") or [] if (h.get("family"), h.get("model")) == (s.family, s.model)]
1507            if len(hold) == 1 and hold[0].get("folder"):
1508                s.model_path = hold[0]["folder"]
1509            elif not plan.get("issues"):
1510                s.model_path = models.import_target(s.model_path, plan)
1511            return
1512        sel = plan.get("candidate_selection") or {}
1513        fam, model = sel.get("family"), sel.get("model")
1514        if not (fam and model) or plan.get("issues"):
1515            issues = models.problem_words(plan.get("issues") or [], missing=plan.get("missing_shards")) or "they are not a model Strata knows"
1516            more = " " + next((m for m in plan.get("messages") or [] if "holds" in m), "")
1517            raise LaunchError(f"These files cannot be used as they are ({issues}).{more.rstrip()}",
1518                              "Choose the matching model in the list, or check that every shard is in the folder.", 5)
1519        s.family, s.model = fam, model
1520        s.model_path = models.import_target(s.model_path, plan)
1521        self.emit("model", f"These files are {fam} {model}.", None)
1522
1523    # ---- 3. config and profile
1524    def resolved_drafting(self, family: str | None) -> str:
1525        """modelstate.resolved_drafting for this launch: Auto where the all-cards split engine will take the start is the MTP (it runs the model's draft layer and
1526        nothing else), so the plan and the fetch include the draft layer and not DFlash2's drafter.  A drafter the person chose is kept."""
1527        from strata_control import drafting
1528        if self.feed_without_draft_layer(family):            # the model list says this model has no draft layer: no drafter is planned or fetched for it (G14, APP-LIN 0.2.14)
1529            return "off"
1530        r = modelstate.resolved_drafting(self.s.drafting, family, **auto_signals(self.catalog, self.s, family))
1531        if r == "dflash2" and drafting.normalize(self.s.drafting) == "auto" and self.split_expected():
1532            return "mtp"
1533        return r
1534
1535    def card_probe(self):
1536        """The cards' facts for the split engine's rule: None (the engine's own probe, which counts each card's FREE memory), or, when a server of this launch's profile or on
1537        its port is running, the same probe with the free memory left out: that server is stopped before the start and gives its memory back, so it is not "busy" memory."""
1538        try:
1539            mine = any(r["profile"] == self.profile or r["port"] == int(self.s.port) for r in self.serving_launches())
1540        except Exception:                                    # noqa: BLE001 - a question asked early is never a reason to stop a launch
1541            mine = False
1542        if not mine:
1543            return None
1544        import dataclasses
1545        from strata_control import split_engine as SE
1546        return lambda indexes: [dataclasses.replace(c, free_mib=None) for c in SE.probe_cards(indexes)]
1547
1548    def split_expected(self, cfg: dict | None = None) -> bool:
1549        """Would the all-cards split engine take this launch (strata_control/split_engine.expected: the rule apply_split_engine uses, asked before anything is on disk)."""
1550        cached = getattr(self, "_split_expected", None)
1551        if cached is not None:
1552            return cached
1553        got = False
1554        try:
1555            from strata_control import split_engine as SE
1556            s = self.s
1557            if s.family in modelstate.HELPER_FAMILIES and not self.intel_chosen():
1558                base = dict(cfg or {})
1559                if s.split_engine:
1560                    base["split_engine"] = s.split_engine
1561                base["drafting"] = s.drafting if s.drafting is not None else base.get("drafting")
1562                native = None
1563                if s.model_path:
1564                    p = Path(s.model_path)
1565                    shards = sorted(p.glob("*-00001-of-*.gguf")) or sorted(p.glob("*.gguf")) if p.is_dir() else [p]
1566                    native = str(shards[0]) if shards else None
1567                else:
1568                    native = next((str(a2) for a1, a2 in zip(base.get("args") or [], (base.get("args") or [])[1:]) if a1 == "--native"), None)
1569                if native is None and s.family not in ("qwen", "unsloth"):
1570                    got = False                              # no file to look at and no reason to assume a Flash-Next shape
1571                else:
1572                    cards = [int(g) for g in s.gpus] if s.gpus else None
1573                    got = SE.expected(base, indexes=cards, native=native, context=int(s.context or SE.TESTED_CONTEXT),
1574                                      kv=next((str(a2) for a1, a2 in zip(base.get("args") or [], (base.get("args") or [])[1:]) if a1 == "--kv"), None),
1575                                      allow_untested=os.environ.get("STRATA_SPLIT_ALLOW_UNTESTED") == "1", probe=self.card_probe())
1576        except Exception:                                    # noqa: BLE001 - a question asked early is never a reason to stop a launch
1577            got = False
1578        self._split_expected = got
1579        return got
1580
1581    def drafting_inputs(self, cfg: dict) -> dict:
1582        """What strata_control/drafting.py needs to decide for this launch: the choice, the card class, the model and the data folder."""
1583        from strata_control import drafting
1584        backend, archs = drafting.detect_hardware()
1585        mode = self.s.drafting if self.s.drafting is not None else cfg.get("drafting")
1586        args = cfg.get("args") or []
1587        if cfg.get("mtp") is False and drafting.normalize(mode) == "auto":
1588            mode = "off"                                     # the Draft layer switch is off and no drafter was chosen since
1589        elif drafting.normalize(mode) == "auto" and self.split_expected(cfg):
1590            mode = "mtp"                                     # the all-cards split engine runs the MTP draft layer: the plan and the fetch are for that, not for DFlash2
1591        name = cfg.get("model_name")
1592        if not name:                                         # not installed yet (a first launch, --plan): the name setup will write, so the plan names the drafter Auto will really fetch
1593            try:
1594                name = self.catalog.model_name_of(self.s.family, self.s.model)
1595            except Exception:                                # noqa: BLE001 - an unreadable table is only the old, generic plan
1596                name = None
1597        split = bool(self.s.gpus and len(self.s.gpus) > 1)
1598        slot_drafts = False
1599        if str(backend or "").lower() == "cuda" and drafting.request_count(args, int(self.s.parallel or 0)) in drafting.SLOT_DRAFT_REQUESTS:     # (the card is only read for a start that could be in the class)
1600            sig = self.drafting_signals(cfg, {"backend": backend, "archs": archs})
1601            slot_drafts = drafting.slot_drafts_by_default(mode, backend=backend, archs=archs, vram_mib=sig["vram_mib"], args=sig["args"], slots=int(self.s.parallel or 0), split=split)   # the drafter is fetched before the start (ensure_drafter)
1602        return {"mode": mode, "klass": drafting.card_class(archs), "model_name": name, "family": self.s.family,
1603                "data_dir": drafting.data_dir_of(args) or (Path(self.s.data_dir) if self.s.data_dir else None),
1604                "backend": backend, "archs": archs, "mtp_here": drafting.mtp_ready(args) if cfg else None,
1605                "blocked": drafting.blocked_by(args, split=split, slots=int(self.s.parallel or 0), named=drafting.normalize(mode) == "dflash2", backend=backend, slot_drafts=slot_drafts),
1606                "slots_none": drafting.slots_draft_nothing(drafting.merged_args(cfg), int(self.s.parallel or 0))}
1607
1608    def drafting_signals(self, cfg: dict, want: dict) -> dict:
1609        """The two signals drafting.tuned_applies reads besides the backend and the card: the arguments (--expert-cache and the others the confidence reads, with the person's own
1610        options over them as the server merges them) and the memory of the ONE card this launch uses (None: several cards, a shared-memory chip, or not readable)."""
1611        return card_signals(cfg, self.s.gpus, want)
1612
1613    def one_request_for_dflash2(self, config: Path) -> bool:
1614        """DFlash2 chosen on purpose and the person gave no number of requests: one at a time, said once (drafting.wants_one_request)."""
1615        try:
1616            from strata_control import drafting
1617            cfg = read_config(config)
1618            want = self.drafting_inputs(cfg)
1619            sig = self.drafting_signals(cfg, want)
1620            if not drafting.wants_one_request(**want, **sig) or not drafting.drafter_ready(want["data_dir"], want["model_name"], want["backend"]):
1621                return False                                 # (no drafter file after all, e.g. no internet: the MTP runs and the slots stay)
1622        except Exception:                                    # noqa: BLE001 - a note is never a reason to stop a launch
1623            return False
1624        if not getattr(self, "_one_request_said", False):
1625            self._one_request_said = True
1626            self.notices.append(drafting.ONE_REQUEST_NOTE)
1627        return True
1628
1629    def ensure_drafter(self, base_path: Path) -> None:
1630        """Fetch the DFlash2 drafter when this launch will use it and it is not here yet. Never stops the launch: if it cannot be had, the model
1631        starts with the MTP and the person is told (recommend, never force)."""
1632        from strata_control import drafting, drafting_fetch
1633        want: dict = {}
1634        try:
1635            cfg = read_config(base_path)
1636            want = self.drafting_inputs(cfg)
1637            sig = self.drafting_signals(cfg, want)
1638            if want["data_dir"] is not None and drafting.needs_conversion(**want) and drafting.engine_has_selector_q4():
1639                drafting_fetch.convert_selector(want["data_dir"])        # Load, not a start: the smaller selector (174 MiB), made here from the checked pack, no network
1640            if want["data_dir"] is None or not (drafting.needs_pack(**want, **sig) or drafting.needs_tuned(**want, **sig)):
1641                return
1642            tuned = drafting.tuned_applies(want["backend"], want["model_name"], want["archs"], **sig)
1643            self.emit("model", f"Downloading the DFlash2 drafter ({drafting.tuned_pack(drafting.tuned_variant(want['backend'], want['model_name'])).gb if tuned else drafting.DOWNLOAD_GB:g} GB, once)…", 0)
1644
1645            def show(step: str, done: int, total: int) -> None:
1646                self.check_cancel()
1647                self.emit("model", f"{step} {done / 1e9:.2f} of {total / 1e9:.2f} GB" if total > 1 and done < total else step,
1648                          100.0 * done / total if total > 0 else None)
1649            drafting_fetch.ensure_for(want["data_dir"], model_name=want["model_name"], backend=want["backend"], progress=show, cancel=self.cancel, throttle=True,
1650                                    archs=want["archs"], **sig)
1651        except Cancelled:
1652            raise
1653        except Exception as e:                               # noqa: BLE001 - the MTP still runs
1654            then = "starts with the MTP instead" if want.get("mtp_here") is not False else "starts without a drafter"
1655            text = f"{e} The model {then}." if isinstance(e, drafting_fetch.DraftingError) else \
1656                f"The DFlash2 drafter could not be downloaded. The model {then}."
1657            self.notices.append(text)
1658            self.emit("model", text, None, level="warn")
1659
1660    def check_saved_state_readable(self) -> None:
1661        """Before anything is written: a profile or run config of THIS launch that exists but cannot be read (permissions, a damaged profile) stops the
1662        launch here. Writing the run config first replaced it with a new one holding a NEW API key (the apps set up with the old key broke without a word) and
1663        only then failed on the profile (`profile 'x' already exists`). Wording approved by the owner 11-04."""
1664        from strata_control import profiles
1665        try:
1666            profiles.load(self.profile)
1667        except profiles.ProfileError as exc:
1668            path = profiles._path(self.profile)
1669            if path.exists() or path.is_symlink():
1670                try:
1671                    path.read_bytes()
1672                    reason = str(exc)                              # readable, but not a profile: the load says why
1673                except OSError as os_error:
1674                    reason = os_error.strerror or type(os_error).__name__
1675                raise profiles.ProfileError(f"The profile of this launch ({path}) cannot be read ({reason}). "
1676                                            "Fix its permissions or move it away, then run the launch again.")
1677        existing = launch_dir() / f"{self.name}.json"
1678        try:
1679            existing.read_bytes()
1680        except FileNotFoundError:
1681            pass
1682        except OSError as exc:
1683            raise LaunchError(f"The saved settings of this launch ({existing}) cannot be read ({exc.strerror or type(exc).__name__}).",
1684                              "Fix its permissions or move it away, then run the launch again: writing a new one would drop its API key and your changes.")
1685
1686    def announce_key_written(self) -> None:
1687        """The run config (with the key in it) is on disk: now, and only now, say a new key was made."""
1688        if self.key_written_notice and not self.key_written:
1689            self.key_written = True
1690            self.emit("config", self.key_written_notice, None, level="warn")
1691
1692    def build_config(self, base_path: Path) -> Path:
1693        from strata_control import tune_knobs
1694        base = read_config(base_path)
1695        try:
1696            previous = read_config(launch_dir() / f"{self.name}.json")
1697        except (OSError, ValueError):                        # no earlier launch of this name, or an unreadable file: nothing to keep from it
1698            previous = None
1699        if not isinstance(previous, dict):
1700            previous = None
1701        cfg = derive_config(base, self.s, bool_flags=tune_knobs.BOOL_FLAGS,
1702                            log=str(launch_dir() / f"{self.name}.engine.log"), gpus=cards_for_launch(self.s, self.catalog, base=base),
1703                            prev=previous)
1704        self.say_remembered_cards(base)
1705        self.apply_four_card(cfg)
1706        self.apply_split_engine(cfg)
1707        wait = self.start_wait()
1708        if wait > 600 and not cfg.get("engine_ready_s"):     # the server's own wait for the engine (900 s) must not end before the start's
1709            cfg["engine_ready_s"] = wait + 60
1710        out = launch_dir() / f"{self.name}.json"
1711        from strata_control import arg_layers
1712        arg_layers.stamp(cfg)                                # what this launch wrote: a later change to "args" is a hand edit (kept next time)
1713        write_private(out, cfg)
1714        self.config_path = out
1715        return out
1716
1717    def apply_split_engine(self, cfg: dict) -> None:
1718        """The all-cards split engine (docs/SPLIT_ENGINE.md): by itself ("auto", the default) for a Qwen model on this PC's NVIDIA or AMD (gfx1201) cards that passes
1719        strata_control/split_engine.py's rule, never when the run config says "split_engine": "off" (`--split-engine off`, STRATA_SPLIT_ENGINE=0).
1720        In auto a "no" is silent and the config stays as it is; with "on" it gets one plain line. It never stops a launch."""
1721        from strata_control import split_engine as SE
1722        if SE.mode(cfg) == "off":
1723            return
1724        exe_for = SE.exe_finder(cfg)                         # strata-split-N beside the run config's engine (shared with the app's start)
1725
1726        # the split runs the model's own draft layer (--mtp) and refuses to start without it; the plan for Auto downloads DFlash2's drafter, not the draft layer, so
1727        # a start whose draft-layer folder is not on disk stays on the layer split (Auto: silently, with DFlash2 as the plan said; "on": one line saying how to get it)
1728        mtp_dir = next((str(cfg["args"][i + 1]) for i, a in enumerate(cfg.get("args") or []) if a == "--mtp" and i + 1 < len(cfg["args"])), None)
1729        df2_split = str(cfg.get("drafting") or "").lower() == "dflash2" and SE.mode(cfg) == "on"     # DFlash2 chosen by name and the split engine asked for: its drafter is DFlash2's pack, the layer is not loaded
1730        if mtp_dir and not df2_split and not self.draft_layer_present(mtp_dir):
1731            if SE.mode(cfg) == "on":
1732                text = ("The all-cards split engine needs the model's draft layer (the MTP), which is not downloaded. Add --drafting mtp to fetch it; "
1733                        "using the normal layer split.")
1734                self.notices.append(text)
1735                self.emit("config", text, None, level="warn")
1736            return
1737        # `--parallel N` is the split's lane count (split_config reads cfg["parallel"]); a refusal puts the run config back as it was
1738        lanes_added = bool(self.s.parallel) and not cfg.get("parallel")
1739        if lanes_added:
1740            cfg["parallel"] = int(self.s.parallel)
1741        try:
1742            decision = SE.apply_to_config(cfg, exe_for_cards=exe_for, allow_untested=os.environ.get("STRATA_SPLIT_ALLOW_UNTESTED") == "1", probe=self.card_probe())
1743        except Exception as e:                               # noqa: BLE001 - never stop a launch over an option
1744            if lanes_added:
1745                cfg.pop("parallel", None)
1746            if SE.mode(cfg) == "on":
1747                text = f"The all-cards split engine was left out ({type(e).__name__}). Using the normal layer split."
1748                self.notices.append(text)
1749                self.emit("config", text, None, level="warn")
1750            return
1751        if lanes_added and not decision.use_split:
1752            cfg.pop("parallel", None)
1753        if decision.quiet:
1754            return
1755        line = decision.line + (" Turn it off with: strata launch --split-engine off." if decision.use_split else "")
1756        self.notices.append(line)
1757        self.emit("config", line, None)
1758
1759    def say_remembered_cards(self, base: dict) -> None:
1760        """A launch that names no cards keeps the cards the person chose earlier (`--gpu 0` is remembered by the model's settings).  On a PC with more
1761        cards than that, one line says so and how to use them all, so a one-card start is never a surprise (AMD says the same when the card is named)."""
1762        s = self.s
1763        if s.gpus or s.gpu_roles:
1764            return
1765        try:
1766            usable = [int(g.get("index", 0)) for g in self.catalog.computer().usable_gpus]
1767            kept = installed_cards(base, self.catalog.computer().usable_gpus)
1768        except Exception:                                    # noqa: BLE001 - a note only: never stop a launch over it
1769            return
1770        if not kept or len(usable) <= len(set(kept) & set(usable)):
1771            return
1772        where = f"card {kept[0]}" if len(kept) == 1 else "cards " + ", ".join(str(k) for k in kept)
1773        text = (f"This model stays on {where}, the {'card' if len(kept) == 1 else 'cards'} you chose earlier; this PC has {len(usable)} usable cards. "
1774                f"To use them all: strata launch --gpu {','.join(str(u) for u in sorted(usable))} (it is remembered from then on).")
1775        self.notices.append(text)
1776        self.emit("config", text, None)
1777
1778    def apply_four_card(self, cfg: dict) -> None:
1779        """Four Radeon AI PRO R9700 cards and Qwen3.8-Flash-Next IQ3_S: the measured serving profile (strata_control/amd_four_card.py), filled
1780        in where the person chose nothing. Never stops a launch."""
1781        self.four_card_parallel = None
1782        try:
1783            from strata_control import amd_four_card
1784            picked = cfg.get("gpu")
1785            if not (isinstance(picked, list) and len(picked) == amd_four_card.CARDS):
1786                return
1787            want = {int(i) for i in picked}
1788            cards = [c for c in self.catalog.computer().usable_gpus if int(c.get("index", -1)) in want]
1789            before = cfg.get("parallel")
1790            notes = amd_four_card.apply(cards, cfg, parallel_given=bool(self.s.parallel))
1791            if notes:
1792                self.four_card_parallel = cfg.get("parallel") if before is None and cfg.get("parallel") else None   # (only a number the profile set)
1793                self.emit("model", "Four " + str(cards[0].get("name", "AMD")).replace("AMD Radeon ", "") + " cards: " + "; ".join(notes) + ".", None)
1794        except Exception:                                    # noqa: BLE001 - a profile is never a reason to stop a launch
1795            self.four_card_parallel = None
1796
1797    def ensure_profile(self, config: Path) -> None:
1798        from strata_control import profiles
1799        name = self.profile
1800        parallel = self.s.parallel if self.s.parallel else (getattr(self, "four_card_parallel", None) or self.catalog_parallel())
1801        if parallel and not self.s.parallel and self.one_request_for_dflash2(config):
1802            parallel = None                                  # the slots Strata fills in by itself would keep the MTP: DFlash2 answers one request at a time
1803        if parallel and self.run_config_owns_slots(config):
1804            parallel = None                                  # the all-cards split engine's run config carries its lanes (--batch N, from --parallel N or its default): a profile override would only collide with them
1805        sets = [f"host={acc.host_for(self.s.access)}", f"port={int(self.s.port)}"] + ([f"parallel={parallel}"] if parallel else [])
1806        try:
1807            current, _rev = profiles.load(name)
1808        except profiles.ProfileError:
1809            profiles.create(name, str(config))
1810        else:
1811            if current.get("source_config") != str(config.resolve()):
1812                proposed, rev = profiles.propose_source(name, str(config))
1813                profiles.save(name, proposed, expected_revision=rev)
1814        # the overrides are replaced as a set: a launch's host/port/parallel are exactly these
1815        cur, rev = profiles.load(name)
1816        want = {k: v for k, v in (profiles.parse_assignment(x) for x in sets)}
1817        if cur.get("overrides") != want:
1818            profiles.save(name, {**cur, "overrides": want}, expected_revision=rev)
1819
1820    @staticmethod
1821    def draft_layer_present(folder: str) -> bool:
1822        """The draft layer's folder (mtp/rt) exists and holds files."""
1823        try:
1824            return Path(folder).is_dir() and any(Path(folder).iterdir())
1825        except OSError:
1826            return False
1827
1828    @staticmethod
1829    def run_config_owns_slots(config: Path) -> bool:
1830        """The run config already names its batch slots (--batch / --slots in its args): the all-cards split engine's does, always."""
1831        try:
1832            args = [str(a) for a in read_config(config).get("args") or []]
1833        except Exception:                                    # noqa: BLE001 - a config that cannot be read is not a reason to stop a launch
1834            return False
1835        return "--batch" in args or "--slots" in args
1836
1837    def catalog_parallel(self) -> int | None:
1838        try:
1839            comp = self.catalog.computer()
1840            return S.fit_parallel(comp.main_vram_gb) if comp.usable_gpus else None
1841        except Exception:                                    # noqa: BLE001
1842            return None
1843
1844    # ---- 4. tuning
1845    def tune(self) -> None:
1846        s = self.s
1847        if s.tune == "skip":
1848            return
1849        from strata_control import presets
1850        if not self.retune:
1851            if s.tuned_preset:
1852                try:
1853                    presets.find(s.tuned_preset)
1854                    self.emit("tune", "This preset is already tuned for this computer. Add --retune to measure again.", 100)
1855                    return
1856                except presets.PresetError:
1857                    pass
1858            elif s.tuned_at:                                 # measured before: the standard settings were already the fastest, nothing was saved
1859                self.emit("tune", f"Already tuned on {s.tuned_at}: this computer runs best with the standard settings. Nothing to do; add --retune to measure again.", 100)
1860                return
1861            stored = self.stored_tuning()
1862            if stored:                                       # the same model and choices were tuned on this computer before (a run by flags, no preset)
1863                s.tuned_preset, s.tuned_at = stored["id"], stored["date"]
1864                self.emit("tune", f"This model was already tuned for this computer on {stored['date']} ('{stored['name']}'), so that result is used "
1865                                  "and nothing is measured again. Add --retune to measure again.", 100)
1866                return
1867        mode = "thorough" if s.tune == "thorough" else "quick"
1868        status_file = launch_dir() / f"{self.name}.tune.json"
1869        try:
1870            status_file.unlink()
1871        except OSError:
1872            pass
1873        argv = self._cli("tune", "auto", self.profile, "--mode", mode, "--output", "json", "--status-file", str(status_file),
1874                         "--name", (s.name or self.name))
1875        if s.tune_allow_small:
1876            argv.append("--allow-small-differences")
1877        self.stop_own_server_for_tuning()
1878        self.emit("tune", "Tuning for the best speed. Close other heavy programs while it measures.", 0)
1879        p = self._spawn(argv)
1880        out_lines: list[str] = []
1881        reader = threading.Thread(target=lambda: out_lines.extend(p.stdout.readlines()), daemon=True)   # type: ignore[union-attr]
1882        reader.start()
1883        while p.poll() is None:
1884            if self.cancel.is_set():
1885                self._stop_children()
1886                raise Cancelled()
1887            st = _read_json(status_file)
1888            if st:
1889                done, planned = st.get("runs_done") or 0, st.get("runs_planned") or 0
1890                pct = (100.0 * done / planned) if planned else None
1891                left = st.get("minutes_left")
1892                self.emit("tune", st.get("message") or "Measuring…", pct, speeds=st.get("speeds") or [],
1893                          round=(done, planned), minutes_left=left)
1894            time.sleep(1.0)
1895        reader.join(timeout=3)
1896        result = None
1897        for line in reversed(out_lines):
1898            try:
1899                result = json.loads(line).get("result")
1900                break
1901            except (ValueError, AttributeError):
1902                continue
1903        self.tune_result = result
1904        word, sentence = tune_words(result, p.returncode)
1905        self.tune_word = word
1906        preset = (result or {}).get("preset") or {}
1907        if preset.get("id"):
1908            s.tuned_preset, s.tuned_at = preset["id"], time.strftime("%Y-%m-%d")
1909        elif result and result.get("outcome") == "default_confirmed":
1910            s.tuned_at = time.strftime("%Y-%m-%d")
1911        self.emit("tune", f"Tuning result: {word}. {sentence}", 100, level="info" if word in ("faster", "already fastest") else "warn", word=word)
1912
1913    restart_after = True                                     # run(start=False) measures only: nothing starts the model again
1914
1915    def stop_own_server_for_tuning(self) -> None:
1916        """The measuring engine needs the card, so this launch's own server (the same profile) is stopped first and `start()` brings it back with
1917        the result (E07). Other engines are never touched here; the tuner says plainly when another program holds the card."""
1918        from strata_control import runtime
1919        from strata_control.profiles import ProfileError
1920        self.stop_others()
1921        try:
1922            state = runtime.status(self.profile).get("state")
1923        except Exception:                                    # noqa: BLE001 - no state to read: nothing of ours is running
1924            return
1925        if state not in LEFTOVER_STATES:
1926            return
1927        if state in ("ready", "starting"):
1928            self.emit("tune", "Stopping the model to measure; it starts again afterwards." if self.restart_after
1929                      else "Stopping the model to measure.", 0)
1930        else:
1931            # a server that already stopped but whose manager is still open (#4824): it would refuse the start that comes after the measuring
1932            self.emit("tune", "Clearing a stopped server of this preset before measuring.", 0)
1933        try:
1934            runtime.stop(self.profile, timeout=120)
1935        except ProfileError as e:
1936            raise LaunchError(f"The running model could not be stopped to measure: {e}.", "Run `strata launch --stop` first, then measure again.", 6) from None
1937
1938    def stored_tuning(self) -> dict | None:
1939        """The tuning result stored for this launch's model, choices and computer (the active preset of its slot in the shared presets store,
1940        which the start applies), or None. A result whose computer changed in a way that matters (a different card, processor or memory,
1941        another model file) is not reused: it is measured again."""
1942        if self.config_path is None:
1943            return None
1944        from strata_control import presets
1945        try:
1946            _cfg, info = presets.overlay(read_config(self.config_path))
1947            if not info.get("applied") or not info.get("preset"):
1948                return None
1949            made = str(presets.load(info["preset"]["id"]).get("created") or "")[:10]
1950            return {"id": info["preset"]["id"], "name": info["preset"]["name"], "date": made or time.strftime("%Y-%m-%d")}
1951        except Exception:                                    # noqa: BLE001 - an unreadable store means: measure
1952            return None
1953
1954    tune_word: str | None = None
1955
1956    # ---- 0. a server is already running
1957    CHOICE_SKIP = ("schema", "name", "tuned_preset", "tuned_at", "last_used", "created", "api_key")
1958
1959    def choices(self) -> dict:
1960        """The choices that make one server different from another (not the bookkeeping, and the key only as a fingerprint)."""
1961        import hashlib
1962        d = {k: v for k, v in self.s.to_dict(with_key=False).items() if k not in self.CHOICE_SKIP}
1963        d["key"] = hashlib.sha256(("none" if self.s.no_key and not self.s.api_key else self.s.api_key or "").encode("utf-8")).hexdigest()[:16]
1964        return json.loads(json.dumps(d, sort_keys=True))
1965
1966    def _choices_file(self, profile: str | None = None) -> Path:
1967        return launch_dir() / f"{(profile or self.profile)[7:]}.choices.json"
1968
1969    def save_choices(self) -> None:
1970        try:
1971            write_private(self._choices_file(), self.choices())
1972        except OSError:
1973            pass
1974
1975    def _saved_choices(self, profile: str) -> dict | None:
1976        try:
1977            return json.loads(self._choices_file(profile).read_text(encoding="utf-8"))
1978        except (OSError, ValueError):
1979            return None
1980
1981    def serving_launches(self) -> list[dict]:
1982        """Launch servers that are up now (this one included): [{profile, name, port, choices}]."""
1983        from strata_control import profiles, runtime
1984        out = []
1985        try:
1986            listing = profiles.list_profiles()
1987        except Exception:                                    # noqa: BLE001
1988            return out
1989        for row in listing:
1990            pid = row["id"]
1991            if not pid.startswith("launch-"):
1992                continue
1993            try:
1994                if runtime.status(pid).get("state") not in ("ready", "starting"):
1995                    continue
1996                prof, _rev = profiles.load(pid)
1997            except Exception:                                # noqa: BLE001
1998                continue
1999            port = int((prof.get("overrides") or {}).get("port", S.DEFAULT_PORT))
2000            out.append({"profile": pid, "name": pid[7:], "port": port, "choices": self._saved_choices(pid)})
2001        return out
2002
2003    def running_phrase(self, row: dict) -> str:
2004        """`Gyro-S is running on port 8080 with 32K` for the restart question."""
2005        c = row.get("choices") or {}
2006        title = None
2007        try:
2008            title = next((r.title for r in self.catalog.rows() if r.family == c.get("family") and r.model == c.get("model")), None)
2009        except Exception:                                    # noqa: BLE001
2010            title = None
2011        title = title or ("Your model files" if c.get("model_path") else row["name"])
2012        return f"{title} is running on port {row['port']}" + (f" with {S.context_label(c['context'])}" if c.get("context") else "")
2013
2014    @staticmethod
2015    def describe_running(row: dict) -> str:
2016        c = row.get("choices") or {}
2017        bits = []
2018        if c.get("context"):
2019            bits.append(f"context {S.context_label(c['context'])}")
2020        if c.get("vision"):
2021            bits.append(f"pictures {c['vision']}")
2022        if c.get("access"):
2023            bits.append(f"access {S.ACCESS_WORDS.get(c['access'], c['access'])}")
2024        return f"{row['name']} is serving on port {row['port']}" + (f" ({', '.join(bits)})" if bits else "")
2025
2026    def check_serving(self) -> "Result | None":
2027        """G04/E01. The same choices already serving: return that server (nothing stops or starts). Other choices on this profile, or another
2028        launch on this port: ask once on the screens, go on with --restart, else refuse in one line and change nothing. A launch on another port
2029        runs beside the others (the person asked for two), with a warning about graphics memory."""
2030        running = self.serving_launches()
2031        if not running:
2032            self.checked()
2033            return None
2034        own = next((r for r in running if r["profile"] == self.profile), None)
2035        same_port = [r for r in running if r["profile"] != self.profile and r["port"] == int(self.s.port)]
2036        beside = [r for r in running if r["profile"] != self.profile and r["port"] != int(self.s.port)]
2037        if own and not self.retune and not same_port and own["choices"] == self.choices() and own["port"] == int(self.s.port):
2038            self.checked()
2039            self.config_path = launch_dir() / f"{self.name}.json"
2040            urls = acc.urls_for(self.s, tunnel_url=(acc.tunnel_info(self.profile) or {}).get("url"))
2041            self.emit("done", "Already serving these choices; nothing was restarted.", 100, urls=urls)
2042            return Result(self.profile, urls, self.s.api_key, None, self.notices, str(self.config_path), reused=True)
2043        for r in beside:
2044            self.notices.append(f"{r['name']} is already loaded on port {r['port']}. Two models at once may not fit in the graphics memory; "
2045                                "the new one can fail to start. Stop the first with `strata launch --stop` if it does.")
2046        blocking = ([own] if own and not self.retune else []) + same_port
2047        if not blocking:
2048            self.checked()
2049            return None
2050        what = "; ".join(self.describe_running(r) for r in blocking)
2051        if not self.restart:
2052            if self.confirm_restart is not None:
2053                if not self.confirm_restart(f"{self.running_phrase(blocking[0])}. Restart it with these settings?", "Answers in progress stop."):
2054                    raise LaunchError("Left as it is: the running model keeps serving.", "", 130)
2055            else:
2056                raise LaunchError(f"A model is already running: {what}. These choices are different.",
2057                                  "Add --restart to stop it and start these, or run `strata launch --stop` first.", 6)
2058        self._stop_first = [r["profile"] for r in same_port]
2059        self.checked()
2060        return None
2061
2062    def checked(self) -> None:
2063        cb, self.after_check = self.after_check, None
2064        if cb is not None:
2065            cb()
2066
2067    def stop_others(self) -> None:
2068        """Stop the other launch servers that hold this port, so the new one gets it (no "port already in use")."""
2069        from strata_control import runtime
2070        from strata_control.profiles import ProfileError
2071        for pid in self._stop_first:
2072            self.emit("start", f"Stopping {pid[7:]} so the new choices can use port {int(self.s.port)}…", None)
2073            try:
2074                runtime.stop(pid, timeout=120)
2075                acc.stop_tunnel(pid)
2076            except ProfileError as e:
2077                raise LaunchError(f"The running server {pid[7:]} could not be stopped: {e}.", "Run `strata launch --stop` first.", 6) from None
2078        self._stop_first = []
2079
2080    # ---- 5. start
2081    def start(self) -> None:
2082        from strata_control import runtime
2083        from strata_control.profiles import ProfileError
2084        name = self.profile
2085        self.stop_others()
2086        st = runtime.status(name)
2087        if st.get("state") in LEFTOVER_STATES:
2088            if st.get("state") in ("ready", "starting"):
2089                self.emit("start", "A server for this preset is already running; restarting it with these choices…")
2090            else:
2091                self.emit("start", "A server of this preset stopped earlier and was never cleared; clearing it before the start…")
2092            try:
2093                runtime.stop(name, timeout=120)
2094            except ProfileError as e:
2095                raise LaunchError(f"The running server could not be stopped: {e}.", "Run `strata launch --stop` first.", 6) from None
2096        self.check_port_free()
2097        self._marks = self.log_marks()                       # what the logs already held: only this attempt's lines are ever quoted
2098        self.emit("start", "Starting the engine and loading the model. The first start can take a few minutes.", None)
2099        done = threading.Event()
2100        box: dict[str, Any] = {}
2101
2102        def go() -> None:
2103            try:
2104                box["r"] = runtime.start(name, wait=self.start_wait())
2105            except Exception as e:                           # noqa: BLE001
2106                box["e"] = e
2107            finally:
2108                done.set()
2109
2110        threading.Thread(target=go, daemon=True).start()
2111        t0 = time.monotonic()
2112        while not done.wait(1.0):
2113            if self.cancel.is_set():
2114                try:
2115                    runtime.stop(name, timeout=60)
2116                except Exception:                            # noqa: BLE001
2117                    pass
2118                raise Cancelled()
2119            self.emit("start", f"Loading the model… {int(time.monotonic() - t0)} s", None)
2120        if "e" in box:
2121            self.end_failed_start()
2122            raise LaunchError(f"The server could not start: {box['e']}", _log_hint(self.config_path, box["e"]), 6)
2123        r = box["r"]
2124        if not r.get("ok"):
2125            text, nxt = explain_engine_exit(r, self.config_path, marks=self._marks, server_log=self.server_log_path(),
2126                                            shared_memory=self.shares_memory())
2127            self.end_failed_start()
2128            raise LaunchError(text, nxt, 6)
2129        self.emit("start", "The model is loaded and answering.", 100)
2130        self.report_drafting()
2131
2132    _marks: dict | None = None
2133
2134    def shares_memory(self) -> bool:
2135        """Does this launch run on a graphics chip that shares the RAM (Strix Halo)?  Only used to explain a stop."""
2136        try:
2137            return uses_integrated_gpu(self.catalog.computer(), self.s)
2138        except Exception:                                    # noqa: BLE001 - an explanation only
2139            return False
2140
2141    def server_log_path(self) -> Path | None:
2142        try:
2143            from strata_control import runtime
2144            return runtime.runtime_dir() / f"{self.profile}.server.log"
2145        except Exception:                                    # noqa: BLE001
2146            return None
2147
2148    def log_marks(self) -> dict:
2149        """{log path: size now} for the engine log and the runtime's server log, so a failed start quotes only what this attempt wrote."""
2150        marks = {}
2151        paths = [self.server_log_path()]
2152        try:
2153            paths.append(Path(read_config(self.config_path).get("log"))) if self.config_path else None
2154        except (OSError, ValueError, TypeError):
2155            pass
2156        for path in paths:
2157            try:
2158                marks[str(path)] = Path(path).stat().st_size if path else 0
2159            except OSError:
2160                if path:
2161                    marks[str(path)] = 0
2162        return marks
2163
2164    def check_port_free(self) -> None:
2165        """Before the host starts: a port another program holds is said at once, in words (X01), and nothing is left running."""
2166        import socket
2167        port = int(self.s.port)
2168        busy = False
2169        for host in ("127.0.0.1",):
2170            try:
2171                with socket.create_connection((host, port), timeout=1.0):
2172                    busy = True
2173            except OSError:
2174                pass
2175        if not busy:
2176            return
2177        raise LaunchError(f"Port {port} is already in use by another program.",
2178                          f"Close it, or start with a different port (for example --port {port + 1}).", 6)
2179
2180    def end_failed_start(self) -> None:
2181        """A start that failed leaves nothing alive: the runtime host of this attempt is stopped, or ended by its recorded identity."""
2182        from strata_control import runtime
2183        try:
2184            runtime.stop(self.profile, timeout=30)
2185        except Exception:                                    # noqa: BLE001
2186            pass
2187        try:
2188            runtime.cleanup(self.profile)
2189        except Exception:                                    # noqa: BLE001
2190            pass
2191
2192    def report_drafting(self) -> None:
2193        """Say which drafter runs when the engine fell back from the one that was asked for ("Drafting: MTP (DFlash2 didn't fit)"). Best effort."""
2194        try:
2195            import urllib.request
2196            headers = {"Authorization": f"Bearer {self.s.api_key}"} if self.s.api_key else {}
2197            with urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{int(self.s.port)}/metrics", headers=headers), timeout=4) as resp:
2198                info = (json.loads(resp.read().decode("utf-8", "replace")).get("engine") or {})
2199        except Exception:                                    # noqa: BLE001 - the line is a convenience
2200            return
2201        self.report_split_fallback(info)
2202        self.report_vision(info)
2203        note = str(info.get("drafting_note") or "")
2204        if note:
2205            self.notices.append(note)
2206            self.emit("start", note, None)
2207
2208    def report_vision(self, info: dict) -> None:
2209        """The server read pictures on the processor because the card had no room for the picture reader: its /metrics carries the sentence (vision_note;
2210        strata_control/reader_room.py), and the summary shows it."""
2211        note = str(info.get("vision_note") or "")
2212        if note and note not in self.notices:
2213            self.notices.append(note)
2214            self.emit("start", note, None, level="warn")
2215
2216    def report_split_fallback(self, info: dict) -> None:
2217        """The server started the normal layer split because the all-cards split engine would not come up (its metrics say split_fallback; serve/server.py
2218        start_engine_or_fallback): the summary then says what runs, not the line written before the start ("Using the all-cards split engine on N cards")."""
2219        if not info.get("split_fallback"):
2220            return
2221        why = ""
2222        try:
2223            log = read_config(self.config_path).get("log") if self.config_path else None
2224            lines = Path(str(log) + ".split-engine").read_text(encoding="utf-8", errors="replace").splitlines() if log else []
2225            why = next((ln.strip() for ln in reversed(lines) if ln.lstrip().startswith("sfnx:")), "")
2226        except Exception:                                    # noqa: BLE001 - the reason is a convenience
2227            why = ""
2228        text = "The all-cards split engine could not start" + (f" ({why})" if why else "") + "; running the normal layer split."
2229        self.notices[:] = [n for n in self.notices if not n.startswith("Using the all-cards split engine")]
2230        self.notices.append(text)
2231        self.emit("start", text, None, level="warn")
2232
2233    # ---- 6. access
2234    def open_access(self) -> str | None:
2235        s = self.s
2236        missing = acc.missing_helper(s.access)
2237        tunnel = None
2238        if s.access == "cloudflare":
2239            if missing:
2240                self.notices.append(missing + " The server is running on this computer meanwhile.")
2241                self.emit("access", missing, level="warn")
2242            else:
2243                self.emit("access", "Opening a Cloudflare quick tunnel…")
2244                tunnel, msg = acc.start_tunnel(self.profile, int(s.port))
2245                if tunnel is None:
2246                    self.notices.append(msg)
2247                self.emit("access", msg, level="info" if tunnel else "warn", url=tunnel)
2248        elif missing:
2249            self.notices.append(missing)
2250            self.emit("access", missing, level="warn")
2251        else:
2252            self.emit("access", "Ready: " + ", ".join(acc.urls_for(s)), 100)
2253        return tunnel
2254
2255    # ---- all of it
2256    def row(self):
2257        """The catalog row of the chosen model (None for a model the list does not carry)."""
2258        s = self.s
2259        return next((r for r in self.catalog.rows() if (r.family, r.model) == (s.family, s.model)), None)
2260
2261    def download_plan(self) -> dict:
2262        """What this launch would download, in numbers and words (nothing is changed): the model's missing files, and for a model that is
2263        not on this computer yet also the draft layer and the picture reader that setup fetches after it. 0 when everything is here."""
2264        from strata_control import engine_component
2265        from strata_control import discovery
2266        from strata_control.discovery import MMPROJ_GB, MTP_FETCH_GB
2267        s = self.s
2268        st = self.model_state()
2269        parts = [{"kind": p.kind, "label": p.label, "gb": round(p.gb, 1)} for p in st.parts if p.gb >= 0.05]     # a part already on disk is not a download
2270        row = self.row()
2271        helpers = s.family in modelstate.HELPER_FAMILIES
2272        wants_pictures = s.vision not in (None, "off") and row is not None and bool(row.images)
2273        if helpers and (st.own_files or not st.installed):
2274            # a model that is not set up yet (or the person's own files) comes without the draft layer and the picture reader: setup fetches them
2275            # next to the prepared data, unless they are there already
2276            have = {p["kind"] for p in parts}
2277            try:
2278                data = Path(st.folder) if st.folder else (Path(s.data_dir) if s.data_dir else (self.existing_data_dir() or self.catalog.data_dir()))
2279                # the data folder the model sits in, then --data-dir and the remembered folder: setup writes the draft layer to <data-dir>/mtp/rt even when the model folder is elsewhere
2280                homes = [data, *[d for d in modelstate.data_places(self.catalog, Path(s.data_dir) if s.data_dir else None) if d != data]]
2281                if modelstate.mtp_choice(s.mtp, self.resolved_drafting(s.family)) != "off" and "mtp" not in have and discovery.mtp_layer_in(*homes) is None:
2282                    parts.append({"kind": "mtp", "label": "the draft layer", "gb": MTP_FETCH_GB})
2283                own = None
2284                if s.model_path:                             # setup uses a reader that sits with the person's own files (setup.py --gguf-dir)
2285                    own = Path(s.model_path)
2286                    own = own if own.is_dir() else own.parent
2287                # setup's rule, not any mmproj*.gguf: the pinned name (lane NET 4b; which file setup accepts is unchanged)
2288                has_reader = modelstate.reader_present(self.catalog, s.family, homes, own=own)
2289                if wants_pictures and "mmproj" not in have and not has_reader:
2290                    parts.append({"kind": "mmproj", "label": "the picture reader", "gb": MMPROJ_GB})
2291            except OSError:
2292                pass
2293        try:
2294            from strata_control import drafting
2295            _b, _cfg = self.installed_state()
2296            if _b is not None and self.other_copy() is not None:
2297                _cfg = None                                  # another data folder's copy: its drafter is not the one this launch uses
2298            want = self.drafting_inputs(_cfg or {})
2299            want["data_dir"] = want["data_dir"] or self.existing_data_dir() or self.catalog.data_dir()
2300            sig = self.drafting_signals(_cfg or {}, want)
2301            if drafting.needs_pack(**want, **sig) or drafting.needs_tuned(**want, **sig):            # chosen DFlash2 (or Auto picking it) and the drafter (the tuned one, where the set has it) is not here: it is part of the download
2302                parts.append({"kind": "dflash2", "label": "the DFlash2 drafter",
2303                              "gb": drafting.tuned_pack(drafting.tuned_variant(want["backend"], want["model_name"])).gb if drafting.tuned_applies(want["backend"], want["model_name"], want["archs"], **sig) else drafting.DOWNLOAD_GB})
2304        except Exception:                                    # noqa: BLE001 - the plan still shows the rest
2305            pass
2306        gap = self.ready_pack_gap() if st.own_files else None
2307        if gap:
2308            # a ready-made pack (NVFP4) is taken from setup's own models folder, not from where the person's files are (round 8, N2: the plan
2309            # said "nothing to download" and setup then asked for 129 GB): count what setup will fetch
2310            parts = [p for p in parts if p["kind"] != "weights"] + [{"kind": "weights", "label": "the ready-made pack", "gb": gap["gb"]}]
2311        intel = self.intel_chosen()
2312        if intel:                                            # the Intel route builds the pack from the files and fetches no draft layer, picture reader or drafter
2313            parts = [p for p in parts if p["kind"] not in ("mtp", "mmproj", "dflash2")]
2314        gb = round(sum(p["gb"] for p in parts), 1)
2315        engine, here = True, []
2316        try:
2317            report = engine_component.status(Path(self.components_dir) if self.components_dir else None)
2318            engine = bool(report.get("usable"))
2319            here = [str(i.get("version")) for i in report.get("installed") or [] if i.get("version")]
2320        except Exception:                                    # noqa: BLE001 - the plan must not fail on this
2321            pass
2322        if gb < 0.05:
2323            text = ("Nothing to download: your model files are used where they are." if st.own_files
2324                    else "Nothing to download: the model is already on this computer.")
2325        else:
2326            names = [f"{p['label']} ({p['gb']:.2f} GB)" if p["kind"] == "dflash2" and p["gb"] < 1 else f"{p['label']} ({p['gb']:.1f} GB)" for p in parts]       # (the tuned drafter is 0.34 / 0.52 GB: one decimal said 0.3 / 0.5)
2327            what = names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1]
2328            other = self.other_copy()
2329            text = (f"About {gb:.1f} GB to download into {Path(s.data_dir).expanduser()}: {what}." if other is not None else
2330                    f"About {gb:.1f} GB to download: {what}.")
2331            if other is not None:                            # lane NET 4a: the start uses --data-dir, not the copy installed elsewhere
2332                text += f" The copy in {other} is not used with this --data-dir."
2333            if st.on_disk_gb >= 1:
2334                text += f" {st.on_disk_gb:.0f} GB of the model is already in its folder."
2335            if st.own_files:
2336                text += " Your model files are used where they are."
2337            if gap:
2338                text += (f" This is a ready-made pack, and setup takes it from its own folder ({gap['folder']}), not from where your files are. "
2339                         "Copy or link your pack there to use it as it is" +
2340                         (f"; only {gap['free_gb']:.0f} GB are free on that drive, so choose a bigger drive with --data-dir" if gap.get("free_gb") is not None and gap["free_gb"] < gap["gb"] else "") + ".")
2341            if any(p["kind"] == "mmproj" for p in parts):
2342                text += " To skip the picture reader (the model then answers text only), add --vision off; or put its mmproj file next to your model files."
2343            if any(p["kind"] == "mtp" for p in parts):
2344                text += " To skip the draft layer (a little slower, less memory), add --mtp off."
2345            if any(p["kind"] == "dflash2" for p in parts):
2346                text += " To skip the DFlash2 drafter, add --drafting mtp."
2347        if not engine and here:
2348            # B03: an engine IS installed, but this plan cannot use it (its signature cannot be checked here, or it is for another card): not "missing"
2349            text += (f" An engine ({', '.join(here[:3])}) is installed, but it did not pass Strata's check on this computer, so Strata looks for a working one "
2350                     "first. `strata components engine` says why.")
2351        elif not engine:
2352            text += " The engine for your graphics card is downloaded first (from the update source; its size is shown when it starts)."
2353        if intel:
2354            text += (" For the Intel card Strata builds the model's pack from your files itself (once, a few minutes); the first time it fetches "
2355                     "a small helper (llama.cpp's gguf-py) from GitHub. No draft layer or picture reader is used on Intel cards yet.")
2356        return {"gb": gb, "parts": parts, "engine_missing": not engine and not here, "engine_usable": engine, "own_files": st.own_files, "text": text}
2357
2358    def ready_pack_gap(self) -> dict | None:
2359        """For a ready-made pack family (NVFP4): what setup would still fetch into its models folder for these choices, {gb, folder, free_gb}, or None."""
2360        s = self.s
2361        try:
2362            mod = self.catalog.strata.setup_module()
2363            _m, families, _c, _src = self.catalog.tables()
2364            if mod is None or not (families.get(s.family or "") or {}).get("ready") or not hasattr(mod, "ready_needed"):
2365                return None
2366            data = Path(s.data_dir) if s.data_dir else (self.existing_data_dir() or self.catalog.data_dir())
2367            models_dir = data / "models"
2368            need = 0
2369            for f in mod.ready_needed(s.model, models_dir):
2370                if not mod.ready_verified(mod.ready_where(models_dir, f), f[5]):
2371                    need += int(f[4])
2372            if need <= 0:
2373                return None
2374            probe = next((q for q in (models_dir, *models_dir.parents) if q.exists()), None)
2375            free = self.catalog.disk_free(probe) if probe is not None else None
2376            return {"gb": round(need / 1e9, 1), "folder": str(models_dir), "free_gb": free}
2377        except Exception:                                    # noqa: BLE001 - a plan that cannot work this out still shows the rest
2378            return None
2379
2380    def preflight_words(self) -> list[str]:
2381        """Plain warnings for `--plan` that the run itself would meet: an engine older than the model needs, an earlier install taking the
2382        place of a clean one, files that are not the model that was named. Nothing is changed."""
2383        out: list[str] = list(self.identity_notes)
2384        try:
2385            from strata_control import engine_component as ec
2386            report = ec.status(Path(self.components_dir) if self.components_dir else None)
2387            if report.get("usable"):
2388                stale = self.stale_engine(report["engine"].get("version"))
2389                if stale:
2390                    out.append(stale + " Strata will ask before updating it (`strata update` does it now).")
2391        except Exception:                                    # noqa: BLE001
2392            pass
2393        try:
2394            out += install_isolation_words(self.catalog, self.s.data_dir)
2395        except Exception:                                    # noqa: BLE001
2396            pass
2397        return out
2398
2399    def plan(self) -> dict:
2400        s = self.s
2401        self.keep_saved_off()                                # the plan names the drafter the start will run
2402        self.keep_saved_word()
2403        self.check_own_files()
2404        warns = [n.line() for n in (*S.check_access(s),)]
2405        warns += self.preflight_words()
2406        row = self.row()
2407        try:
2408            self.resolved_vision()
2409        except Exception:                                    # noqa: BLE001
2410            pass
2411        try:
2412            download = self.download_plan()
2413        except Exception:                                    # noqa: BLE001 - a plan that cannot count the download still shows the rest
2414            download = {"gb": None, "parts": [], "engine_missing": None, "own_files": bool(s.model_path),
2415                        "text": "How much would be downloaded could not be worked out here."}
2416        title = row.title if row is not None else (f"{s.family} {s.model}" if s.model else None)
2417        model = {"title": title, "family": s.family, "model": s.model, "model_gb": row.download_gb if row is not None else None,
2418                 "own_files": bool(s.model_path), "folder": s.model_path}
2419        out = {"profile": self.profile, "settings": s.to_dict(with_key=False), "warnings": warns,
2420               "flags": S.flags_text(s), "steps": list(STAGES), "model": model, "download": download, "drafting": self.drafting_plan_line()}
2421        return out
2422
2423    def feed_without_draft_layer(self, family: str | None = None) -> bool:
2424        """A model of the signed feed whose entry says `drafter: none` (strata_control/feed_models.py puts it on the family): nothing drafts, whatever Auto would pick for a Flash-Next model.
2425        `family`: another family than this launch's (None: this launch's)."""
2426        try:
2427            fam = self.catalog.tables()[1].get(family or self.s.family) or {}
2428            return bool(fam.get("feed")) and fam.get("drafter") == "none"
2429        except Exception:                                    # noqa: BLE001 - an unreadable table is only the generic plan line
2430            return False
2431
2432    def fetch_missing_drafter(self, base_path: Path) -> Path:
2433        """The start's safety net: a model never starts without a drafter unless the person chose Off. When the start's decision (drafting.decide on the installed
2434        config) is no drafter although Off was not chosen, the drafter it falls back to is the MTP layer and that is not here (DFlash2 blocked by several requests;
2435        a card near a class line where setup and the start read the context differently): setup runs again and fetches the layer with its own download
2436        lines, then the start decides again. Offline (setup goes on without the layer) or a server that does not answer: the start goes on without, with
2437        the start's own line. Never stops the launch."""
2438        from strata_control import drafting
2439        try:
2440            cfg = read_config(base_path)
2441            want = self.drafting_inputs(cfg)
2442            if not cfg or drafting.normalize(want["mode"]) == "off" or want.get("mtp_here") is not False or self.feed_without_draft_layer() \
2443                    or self.s.family not in modelstate.HELPER_FAMILIES or drafting.decide(**want, **self.drafting_signals(cfg, want)).drafter != "off":
2444                return base_path
2445        except Exception:                                    # noqa: BLE001 - a question asked early is never a reason to stop a launch
2446            return base_path
2447        self._layer_fetch = True
2448        try:
2449            return self.ensure_model()
2450        except Cancelled:
2451            raise
2452        except LaunchError:                                  # the layer could not be had: the start goes on without it and says so
2453            return base_path
2454        finally:
2455            self._layer_fetch = False
2456
2457    def note_setup_lines(self, lines: list[str]) -> None:
2458        """Remember that setup could not fetch the draft layer because this computer is offline: tools/mtp_fetch.py's own line (netpolicy "offline"),
2459        after which setup goes on without the layer (setup.fetch_mtp, mtp_fetch exit 5)."""
2460        from strata_control import netpolicy
2461        tail = netpolicy.WORDS["offline"].split("{host}", 1)[1].format(what="the draft layer")
2462        if any(tail in str(line) for line in lines or []):
2463            self._mtp_offline = True
2464
2465    def say_mtp_offline(self, base_path: Path) -> None:
2466        """Once per launch: the draft layer could not be downloaded offline and the start has no other drafter (drafting.MTP_OFFLINE_NOTE, shown like the
2467        DFlash2 drafter's offline line). The start's own "Drafting: off (no drafter is downloaded yet)" stays as it is."""
2468        if not getattr(self, "_mtp_offline", False) or getattr(self, "_mtp_offline_said", False):
2469            return
2470        from strata_control import drafting
2471        try:
2472            cfg = read_config(base_path)
2473            want = self.drafting_inputs(cfg)
2474            if drafting.normalize(want["mode"]) == "off" or drafting.decide(**want, **self.drafting_signals(cfg, want)).drafter != "off":
2475                return                                       # Off was chosen, or another drafter runs: nothing to say
2476        except Exception:                                    # noqa: BLE001 - a note is never a reason to stop a launch
2477            return
2478        self._mtp_offline_said = True
2479        self.notices.append(drafting.MTP_OFFLINE_NOTE)
2480        self.emit("model", drafting.MTP_OFFLINE_NOTE, None, level="warn")
2481
2482    def keep_saved_off(self) -> None:
2483        """A launch without a Drafting word keeps the Off this launch ran with last time (its own run config, launch/<name>.json), unless the model's installed
2484        config holds a Drafting choice of its own (the app's Models screen). Off is only ever the person's choice, and a chosen Off holds: where setup does not run
2485        again the Off was only in that file, and the next start ran Auto's drafter (0.2.14 real-use run, Strix T6)."""
2486        s = self.s
2487        if s.drafting is not None:
2488            return
2489        try:
2490            from strata_control import drafting
2491            prev = read_config(launch_dir() / f"{self.name}.json")
2492            if not isinstance(prev, dict) or drafting.normalize(prev.get("drafting")) != "off":
2493                return
2494            path = self.catalog.installed_config(self.catalog.tag_of(s.family, s.model))
2495            if path is not None and read_config(path).get("drafting") is not None:
2496                return
2497            s.drafting = "off"
2498        except Exception:                                    # noqa: BLE001 - an unreadable file keeps the launch as it was
2499            return
2500
2501    def keep_saved_word(self) -> None:
2502        """A launch without a Drafting word keeps the word this launch was given last time (Auto, MTP or DFlash2; Off is keep_saved_off's and is never touched here).
2503        Owner 11-15: a drafter the person chose stays chosen, the way Off does; only a new explicit choice changes it, Auto included. (boxia d3d and l620 C2,
2504        0.2.14.1: the restart with no word wrote null where "auto" was, and a chosen MTP or DFlash2 went back to Auto.) The saved word is what the person chose,
2505        never the drafter a start fell back to (drafting.decide: a chosen drafter whose file is not here starts the other one when it is on disk and safe on the
2506        card, with its note). Not carried over: when the model's installed config holds a Drafting choice of its own (the app's Models screen, a later choice)
2507        or has its draft layer switched off with no choice (also later than the launch's word), and for a model with no Drafting choice."""
2508        s = self.s
2509        if s.drafting is not None:
2510            return
2511        try:
2512            from strata_control import drafting
2513            word = saved_launch_word(self.name)
2514            if word is None or word == "off" or modelstate.drafting_for_family(word, s.family) is None:
2515                return
2516            path = self.catalog.installed_config(self.catalog.tag_of(s.family, s.model))
2517            installed = read_config(path) if path is not None else {}
2518            if isinstance(installed, dict) and (installed.get("drafting") is not None or installed.get("mtp") is False):
2519                return
2520            s.drafting = drafting.normalize(word)
2521        except Exception:                                    # noqa: BLE001 - an unreadable file keeps the launch as it was
2522            return
2523
2524    def drafting_plan_line(self) -> str:
2525        """The drafting line of --plan: what drafts, or why not what was asked for. Nothing is changed or downloaded."""
2526        from strata_control import drafting
2527        if self.feed_without_draft_layer():                  # the model list says this model has no draft layer: setup fetches none and the engine starts without a drafter
2528            return drafting.summary_line(drafting.Decision("off", "off"))
2529        try:
2530            base, cfg = self.installed_state()
2531            want = self.drafting_inputs(cfg or {})
2532            if self.split_expected(cfg) and drafting.normalize(want.get("mode")) == "mtp":
2533                from strata_control.discovery import MTP_FETCH_GB
2534                from strata_control import split_engine as SE
2535                return SE.split_plan_line(MTP_FETCH_GB)
2536            sig = self.drafting_signals(cfg or {}, want)
2537            if drafting.needs_pack(**want, **sig) or drafting.needs_tuned(**want, **sig):            # the launch fetches the drafter first (ensure_drafter), so that is what will run
2538                return "Drafting: DFlash2 (its drafter is downloaded first)"
2539            return drafting.summary_line(drafting.decide(**want, **sig))
2540        except Exception:                                    # noqa: BLE001
2541            return ""
2542
2543    def run(self, *, start: bool = True) -> Result:
2544        self.restart_after = start
2545        self.keep_saved_off()
2546        self.keep_saved_word()                               # a restart with no word keeps the saved one (it was written as null before)
2547        try:
2548            self.check_own_files()                         # a wrong --model-path is said before the engine is downloaded
2549            if start:
2550                reused = self.check_serving()                # before anything is downloaded or stopped
2551                if reused is not None:
2552                    return reused
2553            self.ensure_engine()
2554            self.check_cancel()
2555            base = self.ensure_model()
2556            self.check_cancel()
2557            self.ensure_drafter(base)
2558            base = self.fetch_missing_drafter(base)
2559            self.say_mtp_offline(base)
2560            self.check_cancel()
2561            self.check_saved_state_readable()
2562            self.emit("config", "Writing this launch's settings…")
2563            cfg = self.build_config(base)
2564            self.announce_key_written()
2565            self.ensure_profile(cfg)
2566            self.emit("config", "Settings are saved.", 100)
2567            if self.engine_problem:
2568                text = no_engine_final(self.engine_problem, self.s.name or self.name)
2569                self.emit("done", text, 100, level="warn")
2570                return Result(self.profile, [], self.s.api_key, None, self.notices + [text], str(cfg), serving=False,
2571                              engine_problem=self.engine_problem, final_text=text)
2572            self.tune()
2573            self.check_cancel()
2574            if not start:
2575                return Result(self.profile, [], self.s.api_key, self.tune_word, self.notices, str(cfg))
2576            self.start()
2577            self.save_choices()
2578            tunnel = self.open_access()
2579            urls = acc.urls_for(self.s, tunnel_url=tunnel)
2580            res = Result(self.profile, urls, self.s.api_key, self.tune_word, self.notices, str(cfg), tunnel)
2581            self.emit("done", "Strata is serving.", 100, urls=urls)
2582            return res
2583        except Cancelled:
2584            self._stop_children()
2585            raise
2586        except LaunchError:
2587            self._stop_children()
2588            raise
2589
2590    def stop(self) -> dict:
2591        from strata_control import runtime
2592        out = runtime.stop(self.profile, timeout=180)
2593        acc.stop_tunnel(self.profile)
2594        return out
2595
2596
2597from strata_control.models import ISSUE_WORDS, plain_issue   # noqa: E402,F401  (one wording for the app, the Terminal and `models import`)
2598
2599
2600def _read_json(path: Path) -> dict | None:
2601    try:
2602        return json.loads(Path(path).read_text(encoding="utf-8"))
2603    except (OSError, ValueError):
2604        return None
2605
2606
2607#: lines of an engine log that say why it stopped (the last one wins), and a plain next step for the causes we know. Recommend, never force.
2608CAUSE_LINE = re.compile(r"error|exception|failed|cannot|can't|could not|no device|not found|out of memory|unsupported|abort|invalid|missing|"
2609                        r"no kernel|illegal|denied|refus", re.I)
2610# The GPU runtime (ROCm) failed while the card was being set up, often right after another engine exited: the runtime's own text
2611# ("terminate called after throwing an instance of 'rocr::AMD::hsa_exception'") stays in the log, not in the sentence shown.
2612HSA_START = re.compile(r"hsa_exception|HSA_STATUS_ERROR", re.I)
2613HSA_START_NEXT = ("The graphics card was not ready yet; wait a few seconds and run it again. If it keeps happening, restart the PC "
2614                  "and report the log.")
2615VRAM_STOP_NEXT = ("A graphics card is too full for this start, even after Strata moved what it could to the processor and the RAM. Close other programs that use the "
2616                  "cards, or start on fewer cards (--gpu), or turn pictures off (--vision off); the context and the number of requests were not changed.")
2617KNOWN_CAUSES = (
2618    (re.compile(r"cannot run the expert kernel|needs AVX-?512", re.I),
2619     "This model folder holds the pack for CPUs with AVX-512, and this PC's CPU does not have it. Run `strata setup` again: on a CPU "
2620     "without AVX-512 it builds the pack that runs on AVX2 CPUs (Ryzen 3000-5000, Intel Core 12th-14th generation)."),
2621    (re.compile(r"no device of requested type|device not found|no (gpu|sycl|level.zero) device|permission denied.*(dri|render)", re.I),
2622     "The engine could not open the graphics card. On Linux the account must be allowed to use it: add it to the render group "
2623     "(`sudo usermod -aG render $USER`), log in again and start it again."),
2624    (re.compile(r"out of memory|not enough (gpu |video |free )?memory|cudaerrormemory|allocation failed", re.I),
2625     "The card or memory ran out. Close other programs that use the card, or choose a smaller context (`--context 16k`) and start again."),
2626    (re.compile(r"tqk\d|no kernel|unsupported (quant|type|model)|unknown (quant|tensor) type", re.I),
2627     "This engine is too old for this model. Update it with `strata update` and start again."),
2628    (re.compile(r"dll|libcu|cannot open shared object|0xc0000135", re.I),
2629     "A library the engine needs is missing. Update the engine (`strata update`) or install the graphics driver again."),
2630    # a Strix Halo with --batch N: the engine's own line after a failed start (src/program/generate.cpp); it must stay the LAST entry (explain_engine_exit reads KNOWN_CAUSES[-1])
2631    (re.compile(r"requests at once do not fit", re.I),
2632     "This PC's memory cannot hold that many requests at once. Lower Concurrent requests in the app (or `--parallel` in the Terminal) by one and start again."),
2633)
2634
2635
2636def _lines_since(path: str | os.PathLike | None, mark: int | None, limit: int = 65536) -> list[str]:
2637    """Lines written to a log after `mark` bytes (the whole tail when there is no mark); a log that got shorter was started over."""
2638    if not path:
2639        return []
2640    try:
2641        with open(path, "rb") as stream:
2642            stream.seek(0, os.SEEK_END)
2643            size = stream.tell()
2644            start = 0 if (mark is None or mark > size) else mark
2645            stream.seek(max(start, size - limit))
2646            data = stream.read().decode("utf-8", "replace")
2647    except OSError:
2648        return []
2649    return [x.rstrip() for x in data.splitlines() if x.strip()]
2650
2651
2652def engine_log_tail(config: Path | None, limit: int = 65536, since: dict | None = None) -> tuple[list[str], str | None]:
2653    """(last lines of the engine log, its path); ([], path-or-None) when it cannot be read. With `since` (log sizes before the attempt)
2654    only this attempt's lines are returned."""
2655    log = None
2656    if config:
2657        try:
2658            log = read_config(config).get("log")
2659        except (OSError, ValueError):
2660            log = None
2661    if not log:
2662        return [], None
2663    if since is not None:
2664        return _lines_since(log, since.get(str(log)), limit), str(log)
2665    try:
2666        with open(log, "rb") as stream:
2667            stream.seek(0, os.SEEK_END)
2668            stream.seek(max(0, stream.tell() - limit))
2669            data = stream.read().decode("utf-8", "replace")
2670    except OSError:
2671        return [], str(log)
2672    return [x.rstrip() for x in data.splitlines() if x.strip()], str(log)
2673
2674
2675def _reader_token_limit(config: Path | None) -> int | None:
2676    """The picture reader's image limit in the run config (vision.max_tokens; 0 = no limit); None when the config does not say (the default limit)."""
2677    try:
2678        value = (read_config(config).get("vision") or {}).get("max_tokens") if config else None
2679        return int(value) if value is not None else None
2680    except (OSError, ValueError, TypeError, AttributeError):
2681        return None
2682
2683
2684def _reader_room_facts(config: Path | None, room: reader_room.NoRoom) -> tuple[int | None, int | None]:
2685    """(the card as nvidia-smi numbers it, its free memory in MiB) for a picture reader that found no room; None for what cannot be said.  The reader counts
2686    the cards its environment shows it, so its number is looked up in the list the server gave it (the config's cards in the engine's order, or the one card
2687    named by vision.cuda_device); the free memory is read after the failure, when the reader is gone, so it is what the reader had."""
2688    card = free = None
2689    try:
2690        cfg = read_config(config) if config else {}
2691        vision = cfg.get("vision") or {}
2692        if vision.get("cuda_device") is not None:
2693            visible = [vision["cuda_device"]]
2694        else:
2695            from serve import server as _server
2696            visible = _server.hip_visible(cfg) if cfg.get("backend") == "hip" else _server.ordered_gpus(cfg)
2697        card = reader_room.physical_card(room.device, visible)
2698    except Exception:                                    # noqa: BLE001 - the figures are a convenience; the sentence is complete without them
2699        card = None
2700    if card is not None:
2701        try:
2702            from strata_control import split_engine as SE
2703            cards = SE.probe_cards([card])
2704            free = cards[0].free_mib if cards else None
2705        except Exception:                                # noqa: BLE001
2706            free = None
2707    return card, free
2708
2709
2710def explain_engine_exit(result: dict, config: Path | None, marks: dict | None = None, server_log: Path | None = None,
2711                        shared_memory: bool = False) -> tuple[str, str]:
2712    """(text, next) for a start that did not reach ready: the stage, the cause line from the engine log, the next step and the log path
2713    (round 8, L3: an Arc engine died with 'No device of requested type available' and the person saw only 'server_exited')."""
2714    server_lines = _lines_since(server_log, (marks or {}).get(str(server_log))) if (server_log and marks is not None) else []
2715    for x in server_lines:                                   # the server's own refusal (server.py: error: ...) is the cause when there is one
2716        busy = re.search(r"port (\d+) is already in use", x)
2717        if busy:
2718            return (f"Port {busy.group(1)} is already in use by another program.",
2719                    f"Close it, or start with a different port (for example --port {int(busy.group(1)) + 1}). The server's log: {server_log}")
2720    lines, log = engine_log_tail(config, since=marks)
2721    if marks is not None and not lines:
2722        own = [x for x in server_lines if re.search(r"server\.py: error:|error:", x, re.I)]
2723        if own:
2724            lines, log = own, str(server_log)
2725    lines = lines or [x.strip() for x in str(result.get("log_tail") or "").split(" | ") if x.strip()]
2726    # a card that ran out of memory: the engine's own line is the cause (the picture reader's "ggml_cuda_init: ... no CUDA-capable device", which it prints when the
2727    # cards are full and it runs on the processor, matched "failed" and used to be the last line shown)
2728    vram_cause = vram_fit.engine_stop_reason(lines)
2729    reader = None if vram_cause else reader_room.find(lines)      # the picture reader found no room on its card (ggml prints it, then aborts): not the engine's line, so a search of its own
2730    cause = vram_cause or next((x for x in reversed(lines) if CAUSE_LINE.search(x) and not x.lstrip().startswith(("strata generate: ", "strata serve: expert"))), None)
2731    cause = (cause or (lines[-1] if lines else "")).strip()
2732    cause = re.sub(r"^(\[strata\]\s*)?(\d{4}-\d\d-\d\d[ T][\d:.]+\s*)?", "", cause)[:240]
2733    state, why = result.get("state"), result.get("error") or result.get("message")
2734    if why == "startup_wait_expired":
2735        stage = "The model did not finish loading in time"
2736    elif why == "server_exited" or result.get("engine_exit_code") is not None:
2737        code = result.get("engine_exit_code")
2738        stage = "The engine stopped while it was loading the model" + (f" (exit code {code})" if code not in (None, 0) else "")
2739    else:
2740        stage = f"The server did not become ready ({state}: {why or 'see the engine log'})"
2741    hsa = HSA_START.search(" ".join(lines + [str(why or "")]))   # the runtime's own text is kept out of the sentence (it is in the log)
2742    if hsa:
2743        # a real cause in the same log (out of memory, no permission on the card ...) wins: its line is the cause shown
2744        real = next((x for x in reversed(lines) if any(p.search(x) for p, _ in KNOWN_CAUSES)), None)
2745        if real:
2746            hsa = None
2747            cause = re.sub(r"^(\[strata\]\s*)?(\d{4}-\d\d-\d\d[ T][\d:.]+\s*)?", "", real.strip())[:240]
2748        else:
2749            cause = ""
2750    if reader is not None and not hsa:                    # the plain sentence: which card, what the reader needs, what is free, and the next step
2751        card, free = _reader_room_facts(config, reader)
2752        said, nxt = reader_room.could_not_start(card, reader_room.whole_need_mib(reader.need_mib, _reader_token_limit(config)), free)
2753        return said, nxt + _log_sentence(log)
2754    text = stage + (f": {cause}" if cause else ".")
2755    if not text.endswith((".", "!")):
2756        text += "."
2757    step = HSA_START_NEXT if hsa else (VRAM_STOP_NEXT if vram_cause else next((words for pattern, words in KNOWN_CAUSES if pattern.search(" ".join([cause, str(why or "")]))), "Run it again; if it repeats, report the log."))
2758    if shared_memory and not hsa and not any(p.search(" ".join([cause, str(why or "")])) for p, _ in (*KNOWN_CAUSES[:2], KNOWN_CAUSES[-1])):
2759        # a Strix Halo: the settings fix the expert cache beside a RAM budget, and the engine ended with no error text of its own (STRIX-2Q, 11-01)
2760        try:
2761            from strata_control import uma_pool, user_args as _ua
2762            cfg = read_config(config) if config else {}
2763            effective = {"args": list(cfg.get("args") or []), _ua.USER_KEY: cfg.get(_ua.USER_KEY)}
2764            _ua.apply(effective)
2765            advice = uma_pool.stop_advice(effective["args"])
2766        except Exception:                                    # noqa: BLE001 - the plain sentence below is enough
2767            advice = None
2768        if advice:
2769            if cause and not CAUSE_LINE.search(cause):       # the last log line was a progress line ("prefill: copy stream"), not a reason
2770                text = stage + "."
2771            return text, advice + _log_sentence(log)
2772    return text, step + _log_sentence(log)
2773
2774
2775def _log_sentence(log: str | None) -> str:
2776    """The sentence that points at the engine's log. A log that does not exist is not pointed at: a start that stopped before the engine
2777    existed (a profile whose runtime is still live, a missing engine package) never wrote one (#3714)."""
2778    if log and os.path.isfile(log):
2779        return f" The engine's log: {log}"
2780    if log:
2781        return " The engine did not get as far as writing its log, so the reason is in the lines above (`strata logs` has the server's own)."
2782    return " The engine's log has the reason (strata logs, or the log named in the run config)."
2783
2784
2785#: the states of a launch's own runtime that must be ended before a new start: a server that runs, and one that stopped but whose host is still
2786#: alive ("failed", "stale"); `strata launch --stop` ends all four, and a start refuses the profile while any of them is left (#4824).
2787LEFTOVER_STATES = ("ready", "starting", "failed", "stale")
2788
2789#: what the runtime says when another host still owns the profile: the start never began, so there is no engine log to read.
2790PROFILE_BUSY = re.compile(r"already has a live managed runtime", re.I)
2791
2792
2793def _log_hint(config: Path | None, error: object = None) -> str:
2794    if PROFILE_BUSY.search(str(error or "")):
2795        return ("Another Strata server for this preset is still running or starting, or one that stopped has not been cleared, so this start never began "
2796                "and there is no engine log for it. Run `strata launch --stop`, then start again without --retune: a tuning that finished is kept and is not measured again.")
2797    log = None
2798    if config:
2799        try:
2800            log = read_config(config).get("log")
2801        except (OSError, ValueError):
2802            log = None
2803    if log and os.path.isfile(log):
2804        return f"The engine's log has the reason: {log}"
2805    if log:
2806        return "The engine did not get as far as writing its log, so the reason is the message above (`strata logs` has the server's own)."
2807    return "The engine's log has the reason (strata logs, or the log named in the run config)."