okami.mom/strata

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

Niko1221Merge f-0215-accesskey: launch: a key that only the Access step's highlight made goes again on "This computer only" (#5812)3235191e2

main
82.7 KiB1811 linesraw
1"""The screens of `strata launch`: the saved-preset start screen, the nine setup steps, the confirm pop-up and the progress screen.
2
3One decision per screen. Every screen has a short plain explanation under the content (what it means, what to do next) and a line
4of key hints. Esc goes back, Enter goes on, q leaves (and says what is kept). Choices are written into `app.ctx.settings`
5(strata_cli/launch/settings.py); nothing is installed or started until the last screen.
6"""
7
8from __future__ import annotations
9
10import os
11from pathlib import Path
12
13from rich.text import Text
14from textual.app import ComposeResult
15from textual.binding import Binding
16from textual.containers import Vertical, VerticalScroll
17from textual.screen import ModalScreen, Screen
18from textual.widgets import Input, Static
19
20from strata_cli.launch import access as acc
21from strata_cli.launch import params as P
22from strata_cli.launch import settings as S
23from strata_cli.launch import store
24from strata_cli.launch.widgets import (ACCENT, BAD, DARK, FG, LIGHT, MUTE, WARN, Cell, Item, Menu, bar)
25
26STEPS = (("model", "Model"), ("cards", "Cards"), ("folder", "Folder"), ("context", "Context"), ("pictures", "Pictures"),
27         ("parallel", "Parallel"), ("tuning", "Tuning"), ("advanced", "Advanced"), ("access", "Access"), ("save", "Save"))
28
29
30STEP_LABELS = {**dict(STEPS), "drafting": "Drafting"}
31
32
33def middle_shorten(text: str, width: int, dots: str = "…") -> str:
34    """`text` in at most `width` terminal cells: when longer, its start and its end with `dots` between them (the drive and the folder's own
35    name stay readable). Unchanged when it fits; at least the dots and one character on each side."""
36    from rich.cells import cell_len
37    if cell_len(text) <= width:
38        return text
39    room = max(2, width - cell_len(dots))
40    head_n = max(1, room * 2 // 5)
41    tail_n = max(1, room - head_n)
42    head, tail = "", ""
43    for ch in text:                                  # by cells, so wide characters count twice
44        if cell_len(head + ch) > head_n:
45            break
46        head += ch
47    for ch in reversed(text):
48        if cell_len(ch + tail) > tail_n:
49            break
50        tail = ch + tail
51    return head + dots + tail
52
53
54def drafting_choice_available(ctx) -> bool:
55    """The Drafting step exists only where there is something to choose: Qwen3.8-Flash-Next (qwen, gyro) on a computer whose engine can run DFlash2
56    (CUDA or HIP, strata_control/drafting.py). Every other model has no step: the rest have only the MTP."""
57    from strata_control import drafting
58    if getattr(getattr(ctx, "settings", None), "family", None) not in drafting.SUPPORTED_FAMILIES or not drafting.ENGINE_SERVES_DFLASH2:
59        return False
60    backend, archs = drafting.detect_hardware()
61    return drafting.hardware_support(backend, archs).can_run
62
63
64def flow_for(ctx) -> list[str]:
65    """The steps of this computer: the Cards step exists only when two or more graphics cards can be used; the Drafting step only for
66    Qwen3.8-Flash-Next on a computer that can run DFlash2."""
67    ids = [sid for sid, _ in STEPS]
68    if len(ctx.computer.usable_gpus) < 2:
69        ids.remove("cards")
70    if drafting_choice_available(ctx):
71        ids.insert(ids.index("pictures") + 1, "drafting")
72    return ids
73
74
75def _t(*parts: tuple[str, str] | str) -> Text:
76    out = Text(no_wrap=False)
77    for p in parts:
78        if isinstance(p, tuple):
79            out.append(p[0], style=p[1])
80        else:
81            out.append(p)
82    return out
83
84
85class Base(Screen):
86    """Shared frame: heading line, rule, content, rule, explanation, key hints, message."""
87
88    BINDINGS = [
89        Binding("escape", "back", "Back", show=False), Binding("q", "quit_app", "Quit", show=False),
90        Binding("question_mark", "help", "Help", show=False), Binding("f1", "help", "Help", show=False),
91        Binding("down", "move(1)", show=False), Binding("up", "move(-1)", show=False),
92        Binding("pagedown", "page(1)", show=False), Binding("pageup", "page(-1)", show=False),
93        Binding("enter", "next", "Next", show=False),
94        Binding("home", "edge(0)", show=False), Binding("end", "edge(1)", show=False),
95    ]
96
97    AUTO_FOCUS = ""
98    step_id = ""
99    title_line = "Set up"
100    hints = "↑↓ choose   Enter next   Esc back   ? help   q quit"
101    help_text = "Up/Down choose, Enter next, Esc back, q quit. Nothing is installed or started until the last screen."
102
103    def __init__(self) -> None:
104        super().__init__()
105        self.message = ""
106
107    # ---- frame
108    @property
109    def ctx(self):
110        return self.app.ctx           # type: ignore[attr-defined]
111
112    @property
113    def g(self):
114        return self.ctx.glyphs
115
116    def compose(self) -> ComposeResult:
117        with Vertical(id="shell"):
118            yield Static("", id="head", markup=False)
119            yield Static("", id="rule1", markup=False)
120            with Vertical(id="body"):
121                yield from self.body()
122            yield Static("", id="rule2", markup=False)
123            yield Static("", id="explain", markup=False)
124            yield Static("", id="hints", markup=False)
125            yield Static("", id="message", markup=False)
126
127    def body(self) -> ComposeResult:
128        yield from ()
129
130    def on_mount(self) -> None:
131        self.paint()
132
133    def on_resize(self, _e) -> None:
134        self.paint()
135
136    def width(self) -> int:
137        return max(40, (self.size.width or 100) - 2)
138
139    def rule(self) -> str:
140        return self.g.rule * self.width()
141
142    def head_text(self) -> Text:
143        flow = flow_for(self.ctx)
144        out = Text(no_wrap=True, overflow="crop")
145        out.append("STRATA  ", style=f"bold {ACCENT}")
146        out.append(f"{self.title_line}", style=f"bold {ACCENT}")
147        if self.step_id in flow:
148            labels = STEP_LABELS
149            n = flow.index(self.step_id)
150            if self.width() >= 118:
151                out.append("   ")
152                for i, sid in enumerate(flow):
153                    mark = f"[{i + 1} {labels[sid]}]" if i == n else f"{i + 1} {labels[sid]}"
154                    out.append(mark + "  ", style=f"bold {ACCENT}" if i == n else "")
155            else:
156                out.append(f"   Step {n + 1} of {len(flow)}: {labels[self.step_id]}", style="")
157        return out
158
159    def paint(self) -> None:
160        try:
161            self.query_one("#head", Static).update(self.head_text())
162            self.query_one("#rule1", Static).update(Text(self.rule(), style=MUTE))
163            self.query_one("#rule2", Static).update(Text(self.rule(), style=MUTE))
164            explanation = self.explain()
165            self.query_one("#explain", Static).update(explanation)
166            self.query_one("#explain", Static).display = bool(explanation.plain.strip())     # no empty row where there is nothing to say
167            self.query_one("#hints", Static).update(Text(self.hints_text(), style=MUTE))
168            self.query_one("#message", Static).update(Text(self.message, style=WARN if self.message.startswith("!") else MUTE))
169        except Exception:                                    # noqa: BLE001 - a screen that is closing
170            return
171        self.refresh_body()
172
173    def hints_text(self) -> str:
174        return self.hints.replace("↑↓", self.g.updown)
175
176    def explain(self) -> Text:
177        return Text("")
178
179    def refresh_body(self) -> None:
180        pass
181
182    def say(self, text: str, warn: bool = False) -> None:
183        self.message = ("! " if warn else "") + text
184        self.paint()
185
186    # ---- actions
187    def menu(self) -> Menu | None:
188        try:
189            return self.query_one(Menu)
190        except Exception:                                    # noqa: BLE001
191            return None
192
193    def action_move(self, step: int) -> None:
194        m = self.menu()
195        if m is not None and not self.input_open():
196            m.move(step)
197            self.on_cursor()
198            self.paint()
199
200    def action_edge(self, last: int) -> None:
201        m = self.menu()
202        if m is not None and not self.input_open() and m.items:
203            m.index = len(m.items) - 1 if last else 0
204            m._refresh()
205            self.on_cursor()
206            self.paint()
207
208    def action_page(self, step: int) -> None:
209        m = self.menu()
210        if m is not None:
211            m.page(step)
212            self.on_cursor()
213            self.paint()
214
215    def on_cursor(self) -> None:
216        pass
217
218    def input_open(self) -> bool:
219        return any(i.has_class("open") and not i.has_class("always") for i in self.query(".field"))
220
221    def action_help(self) -> None:
222        self.say(self.help_text)
223
224    def action_quit_app(self) -> None:
225        self.app.exit(None)
226
227    def action_back(self) -> None:
228        self.app.back()          # type: ignore[attr-defined]
229
230    def action_next(self) -> None:
231        self.commit()
232        self.app.advance()       # type: ignore[attr-defined]
233
234    def commit(self) -> None:
235        pass
236
237    # ---- text input helper
238    def open_field(self, field_id: str, value: str = "", placeholder: str = "") -> None:
239        f = self.query_one(f"#{field_id}", Input)
240        f.disabled = False
241        f.add_class("open")
242        f.value = value
243        f.placeholder = placeholder
244        f.focus()
245
246    def close_field(self, field_id: str) -> None:
247        f = self.query_one(f"#{field_id}", Input)
248        f.remove_class("open")
249        f.disabled = True
250        self.set_focus(None)
251
252
253# ------------------------------------------------------------------------------------------------ start
254
255class StartScreen(Base):
256    step_id = "start"
257    title_line = "Launch"
258    hints = "↑↓ choose   Enter launch   e edit preset   d delete   ? help   q quit"
259    help_text = ("Pick a saved preset to start it at once, or set up from the beginning. A preset remembers the model, "
260                 "context size, parallel requests, tuned settings and who can reach it.")
261
262    BINDINGS = Base.BINDINGS + [Binding("e", "edit", "Edit", show=False), Binding("d", "delete", "Delete", show=False)]
263
264    def body(self) -> ComposeResult:
265        yield Static("", id="intro", markup=False)
266        yield Menu([("", 34), ("", 14), ("", 8), ("", 14), ("", 16)], id="menu")
267
268    def on_mount(self) -> None:
269        self.reload()
270        self.paint()
271
272    def reload(self) -> None:
273        self.presets = store.list_presets()
274        items: list[Item] = []
275        for p in self.presets:
276            sm = store.summary(p)
277            req = (f"{p.parallel} request" + ("s" if p.parallel != 1 else "")) if p.parallel else "fit to card"
278            tuned = f"tuned {p.tuned_at[5:]}" if p.is_tuned and p.tuned_at else "not tuned"
279            used = f"last used {p.last_used[5:10]}" if p.last_used else "not used yet"
280            items.append(Item([p.name or "?", str(sm["model"]), S.context_label(p.context), req, Cell(tuned, MUTE if not p.is_tuned else ""),
281                               Cell(used, MUTE)], key=("preset", p.name)))
282        items.append(Item([Cell("Set up from the beginning", "")], key=("new", None)))
283        items.append(Item([Cell("Use model files I already have", "")], key=("own", None)))
284        m = self.query_one(Menu)
285        m.columns = [("", 34), ("", 14), ("", 8), ("", 14), ("", 14)]
286        m.show_header = False
287        m.set_items(items, 0)
288
289    def refresh_body(self) -> None:
290        intro = Text()
291        if self.presets:
292            intro.append("Start from a saved preset\n", style=f"bold {ACCENT}")
293        else:
294            intro.append("No saved presets yet\n", style=f"bold {ACCENT}")
295            intro.append("A preset remembers all your choices so next time you start with one key.\n", style=MUTE)
296        try:                                                      # one quiet line when the last check found a newer engine (a local file; no network)
297            from strata_control import engine_update
298            line = engine_update.notice_line()
299        except Exception:                                         # noqa: BLE001
300            line = None
301        if line:
302            intro.append(line + "\n", style=MUTE)
303        self.query_one("#intro", Static).update(intro)
304
305    def explain(self) -> Text:
306        c = self.ctx.computer
307        return Text(f"This computer: {c.line()}.  " + ("Preset: model, context, parallel requests, tuned settings, access. "
308                    "Shared with the Strata app." if self.presets else "Choose how to begin."), style=MUTE)
309
310    def head_text(self) -> Text:
311        out = Text(no_wrap=True, overflow="crop")
312        out.append("STRATA  Launch", style=f"bold {ACCENT}")
313        info = self.ctx.computer.line()
314        gap = max(2, self.width() - len("STRATA  Launch") - len(info))
315        out.append(" " * gap + info, style=MUTE)
316        return out
317
318    def action_next(self) -> None:
319        it = self.query_one(Menu).current
320        if it is None:
321            return
322        kind, name = it.key
323        if kind == "preset":
324            self.app.start_preset(name)          # type: ignore[attr-defined]
325        elif kind == "new":
326            self.app.begin_setup()               # type: ignore[attr-defined]
327        else:
328            self.app.begin_setup(own_files=True)   # type: ignore[attr-defined]
329
330    def action_edit(self) -> None:
331        it = self.query_one(Menu).current
332        if it and it.key[0] == "preset":
333            self.app.begin_setup(preset=it.key[1])   # type: ignore[attr-defined]
334
335    def action_delete(self) -> None:
336        it = self.query_one(Menu).current
337        if not it or it.key[0] != "preset":
338            return
339        name = it.key[1]
340
341        def done(choice: str | None) -> None:
342            if choice == "yes":
343                try:
344                    store.delete(name)
345                except store.PresetError as e:
346                    self.say(str(e), True)
347                self.reload()
348                self.say(f"Deleted '{name}'. Models and tuning results were not touched.")
349
350        self.app.push_screen(ConfirmScreen(f"Delete the preset '{name}'?",
351                                           "Only the saved choices go. The model files and tuning results stay.",
352                                           [("yes", "Delete it"), ("no", "Keep it")]), done)
353
354    def action_back(self) -> None:
355        self.app.exit(None)
356
357
358# ------------------------------------------------------------------------------------------------ confirm pop-up
359
360class ConfirmScreen(ModalScreen):
361    BINDINGS = [Binding("up", "move(-1)", show=False), Binding("down", "move(1)", show=False),
362                Binding("enter", "pick", show=False), Binding("escape", "cancel", show=False)]
363    DEFAULT_CSS = f"""
364    ConfirmScreen {{ align: center middle; background: #0e1113 80%; }}
365    #dialog {{ width: 70; max-width: 100%; height: auto; max-height: 100%; background: #161a1d; border: solid {ACCENT}; padding: 1 2; }}
366    """
367
368    def __init__(self, question: str, detail: str, options: list[tuple[str, str]]):
369        super().__init__()
370        self.question, self.detail, self.options = question, detail, options
371
372    def compose(self) -> ComposeResult:
373        pal = LIGHT if self.app.has_class("theme-light") else DARK          # the monitor's light theme reaches its pop-ups
374        with Vertical(id="dialog"):
375            yield Static(Text(self.question, style=f"bold {pal.accent}"), markup=False)
376            yield Static(Text(self.detail, style=pal.mute), markup=False)
377            yield Static("", markup=False)
378            yield Menu(id="confirm-menu", palette=pal)
379            yield Static(Text("Up/Down choose   Enter confirm   Esc cancel", style=pal.mute), markup=False)
380
381    def on_mount(self) -> None:
382        m = self.query_one(Menu)
383        m.set_items([Item([label], key=key) for key, label in self.options], 0)
384        if self.app.has_class("theme-light"):          # the monitor's light theme: a white dialog with dark text (the dark one is the default)
385            dialog = self.query_one("#dialog")
386            dialog.styles.background = LIGHT.panel
387            dialog.styles.border = ("solid", LIGHT.accent)
388            dialog.styles.color = LIGHT.fg
389            self.styles.background = "#f9fafb 70%"
390            for static in dialog.query(Static):
391                static.styles.background = LIGHT.panel
392
393    def action_move(self, step: int) -> None:
394        self.query_one(Menu).move(step)
395
396    def action_pick(self) -> None:
397        self.dismiss(self.query_one(Menu).current.key)
398
399    def action_cancel(self) -> None:
400        self.dismiss(None)
401
402
403# ------------------------------------------------------------------------------------------------ 1 model
404
405class ModelScreen(Base):
406    step_id = "model"
407    hints = "↑↓ choose   Enter next   o use my own files   Esc back   ? help"
408    help_text = ("Pick the model. 'Needs' is the RAM + graphics memory the model's files take (the app's figure; the n-gram table stays on your SSD and is not counted). 'fits' means they fit the RAM and "
409                 "the graphics memory together; 'may run slower' means they do not, so part is read from the SSD while it answers. Neither is a block: you can still try it.")
410
411    BINDINGS = Base.BINDINGS + [Binding("o", "own", "Own files", show=False)]
412
413    def body(self) -> ComposeResult:
414        yield Static("", id="question", markup=False)
415        yield Menu(id="menu")
416        yield Input(placeholder="Folder with the model files, or one .gguf file", id="own", classes="field", disabled=True)
417
418    def on_mount(self) -> None:
419        self.rows = self.ctx.rows
420        s = self.ctx.settings
421        self.build_menu(initial=True)
422        self.paint()
423        if self.ctx.start_own_files and not s.model_path:
424            self.ctx.start_own_files = False
425            self.action_own()
426
427    def widths(self) -> list[tuple[str, int]]:
428        w = self.width()
429        if w >= 100:
430            return [("Model", 42), ("Download", 10), ("Needs (RAM + VRAM)", 20), ("On this computer", 0)]
431        return [("Model", 41), ("Size", 8), ("Needs", 7), ("Fits?", 0)]      # 80 columns: the verdict column keeps room (the long words are below the list)
432
433    def build_menu(self, initial: bool = False) -> None:
434        s = self.ctx.settings
435        if not (s.family and s.model) and not s.model_path:
436            rec = next((r for r in self.rows if r.recommended), None) or next((r for r in self.rows if r.verdict == "fits"), None)
437            if rec is not None:
438                s.family, s.model = rec.family, rec.model
439        items: list[Item] = []
440        sel = 0
441        for i, r in enumerate(self.rows):
442            col = {"fits": "", "slower": WARN, "tight": WARN, "no": BAD}[r.verdict]
443            tag = (" (recommended)" if r.recommended else "") + (" (installed)" if r.installed else "") + (" [experimental]" if r.experimental else "")
444            need = f"{r.fit_gb:.0f} GB" if r.fit_gb else "-"
445            verdict = r.words + tag
446            if self.width() < 100:                           # a short verdict that fits the column; the full sentence is shown under the list
447                extra = " (recommended)" if r.recommended else " (installed)" if r.installed else " [experimental]" if r.experimental else ""
448                verdict = {"fits": "fits", "slower": "may run slower", "tight": "tight", "no": "too big"}[r.verdict] + extra
449            items.append(Item([r.title, f"{r.download_gb:.0f} GB", need, Cell(verdict, col)], key=(r.family, r.model)))
450            if (s.family, s.model) == (r.family, r.model):
451                sel = i
452        m = self.query_one(Menu)
453        m.columns = self.widths()
454        m.show_header = True
455        m.window = max(4, (self.size.height or 30) - 12)
456        m.set_items(items, sel if (initial or not m.items) else None)
457
458    def on_resize(self, _e) -> None:
459        if hasattr(self, "rows"):
460            self.build_menu()
461        self.paint()
462
463    def refresh_body(self) -> None:
464        q = Text()
465        q.append("Which model?", style=f"bold {ACCENT}")
466        s = self.ctx.settings
467        if s.model_path:
468            q.append(f"   your files: {s.model_path}", style=MUTE)
469        else:
470            info = "This computer: " + self.ctx.computer.line()
471            if len("Which model?") + len(info) + 3 <= self.width():
472                q.append(" " * (self.width() - len("Which model?") - len(info)) + info, style=MUTE)
473        self.query_one("#question", Static).update(q)
474
475    def explain(self) -> Text:
476        m = self.menu()
477        cur = m.current if m else None
478        out = Text()
479        if cur is not None and hasattr(self, "rows"):
480            r = next((x for x in self.rows if (x.family, x.model) == cur.key), None)
481            if r:
482                out.append(f"{r.title}: {r.about}.\n", style=FG)
483                if r.verdict != "fits":
484                    out.append(f"{r.words}. ", style=BAD if r.verdict == "no" else WARN)
485        out.append("The n-gram table stays on your SSD and is not counted above.", style=MUTE)
486        for title, why in self.unavailable_lines():
487            out.append(f"\n{title}: {why}", style=MUTE)
488        note = self.ctx.computer.other_vendor_note
489        if note:
490            out.append(" " + note, style=WARN)
491        return out
492
493    def unavailable_lines(self) -> list:
494        """Models of the signed feed this engine does not run (none for a feed without any): listed under the models, never in the list."""
495        if not hasattr(self, "_unavailable"):
496            self._unavailable = self.ctx.catalog.unavailable(self.ctx.computer.raw)
497        return self._unavailable
498
499    def on_cursor(self) -> None:
500        pass
501
502    def commit(self) -> None:
503        if self.input_open():
504            return
505        cur = self.menu().current
506        if cur is not None:
507            s = self.ctx.settings
508            fam, model = cur.key
509            if (s.family, s.model) != (fam, model) or s.model_path:
510                s.model_path = None
511            s.family, s.model = fam, model
512            from strata_cli.launch import modelstate
513            s.drafting = modelstate.drafting_for_family(s.drafting, fam)         # the other families have no Drafting choice: back to Auto
514            r = next(x for x in self.rows if (x.family, x.model) == (fam, model))
515            if r.verdict == "no":
516                self.ctx.notes.append(f"{r.title} does not fit this computer; it may be slow or run out of memory.")
517
518    def action_next(self) -> None:
519        if self.input_open():
520            return
521        if self.ctx.settings.model_path and not self.ctx.picked_in_list:
522            self.app.advance()           # type: ignore[attr-defined]
523            return
524        super().action_next()
525
526    def action_move(self, step: int) -> None:
527        if self.input_open():
528            return
529        self.ctx.picked_in_list = True
530        super().action_move(step)
531
532    # ---- own files
533    def action_own(self) -> None:
534        self.open_field("own", self.ctx.settings.model_path or "", "Folder with the model files, or one .gguf file")
535        self.say("Type or paste the folder (or the first .gguf file), then press Enter.")
536
537    def on_input_submitted(self, event: Input.Submitted) -> None:
538        if event.input.id != "own":
539            return
540        path = event.value.strip().strip('"')
541        if not path:
542            self.close_field("own")
543            return
544        self.check_own(path)
545
546    def check_own(self, path: str) -> None:
547        from strata_control import models
548        problem = models.own_path_problem(path)
549        if problem:
550            self.say(f"{problem[0]} {problem[1]}", True)
551            return
552        from strata_control import retired
553        if retired.folder_reason(models.absolute(path)):   # DeepSeek files: named, never used (strata_control/retired.py)
554            self.say(retired.own_files(models.absolute(path)), True)
555            return
556        try:
557            plan = models.plan_import(models.absolute(path))
558        except Exception as e:                               # noqa: BLE001
559            self.say(f"These files cannot be used: {e}. Pick the folder with every shard of one model, or a .gguf file of it.", True)
560            return
561        sel = plan.get("candidate_selection") or {}
562        if sel.get("family") and sel.get("model") and not plan.get("issues"):
563            s = self.ctx.settings
564            s.model_path, s.family, s.model = models.import_target(path, plan), sel["family"], sel["model"]
565            from strata_cli.launch import modelstate
566            s.drafting = modelstate.drafting_for_family(s.drafting, s.family)
567            self.ctx.picked_in_list = False
568            self.close_field("own")
569            gb = plan.get("total_bytes", 0) / 1e9
570            self.say(f"These files are {sel['family']} {sel['model']} ({plan['file_count']} file(s), {gb:.0f} GB). Press Enter to use them.")
571            self.menu().select((sel["family"], sel["model"]))
572            self.paint()
573        else:
574            why = models.problem_words(plan.get("issues") or [], missing=plan.get("missing_shards")) or "they are not a model Strata knows"
575            holds = next((m for m in plan.get("messages") or [] if "holds" in m), "")
576            self.say(f"These files cannot be used as they are ({why}). " + (holds + " " if holds else "") +
577                     "Check that every shard is in the folder, or pick a model from the list.", True)
578
579    def action_back(self) -> None:
580        if self.input_open():
581            self.close_field("own")
582            self.say("")
583            return
584        super().action_back()
585
586
587# ------------------------------------------------------------------------------------------------ 2 cards (only with 2+ cards)
588
589class CardsScreen(Base):
590    """Main / Helper / Off for every card (strata_control/gpu_roles.py). The recommendation is already selected; M H O set the role of the
591    card under the cursor, R goes back to the recommendation, D shows what the roles mean."""
592
593    step_id = "cards"
594    help_text = ("Main does the last steps of every answer; Helper holds part of the model; Off leaves the card alone. "
595                 "Keys: M Main, H Helper, O Off, R back to recommended, D details.")
596    hints = "↑↓ choose card   M Main   H Helper   O Off   R recommended   D details   Enter next   Esc back   ? help"
597    BINDINGS = Base.BINDINGS + [Binding("m", "role('main')", show=False), Binding("h", "role('helper')", show=False),
598                                Binding("o", "role('off')", show=False), Binding("r", "recommended", show=False),
599                                Binding("d", "details", show=False), Binding("right", "cycle(1)", show=False),
600                                Binding("left", "cycle(-1)", show=False)]
601
602    def body(self) -> ComposeResult:
603        yield Static(Text("Which graphics cards should it use?", style=f"bold {ACCENT}"), markup=False)
604        yield Static("", id="reco", markup=False)
605        yield Menu([("", 0)], id="menu")
606        yield Static("", id="cardnotes", markup=False)
607
608    def model_memory(self) -> float:
609        s = self.ctx.settings
610        r = next((x for x in self.ctx.rows if (x.family, x.model) == (s.family, s.model)), None)
611        return float(r.memory_gb) if r is not None and r.memory_gb else 44.0
612
613    def installed(self) -> list[int] | None:
614        """The cards the installed model was set to by a person's choice (kept unless this launch names others)."""
615        from strata_cli.launch.runner import installed_cards
616        try:
617            return installed_cards(self.ctx.base_config(), self.ctx.computer.usable_gpus)
618        except Exception:                                    # noqa: BLE001
619            return None
620
621    def cards(self) -> list[dict]:
622        from strata_control import gpu_roles
623        c = self.ctx.computer
624        return gpu_roles.rows(c.gpus, c.engine_vendor)
625
626    def start_roles(self) -> dict[int, str]:
627        """The roles the screen opens with: this launch's own, else the installed model's own choice, else the recommendation."""
628        from strata_control import gpu_roles
629        s, cards = self.ctx.settings, self.cards()
630        if s.gpu_roles:
631            return gpu_roles.normalize({int(k): v for k, v in s.gpu_roles.items()}, cards)
632        if s.gpus:
633            return gpu_roles.from_legacy(list(s.gpus), cards, "as_given")
634        return self.baseline()
635
636    def baseline(self) -> dict[int, str]:
637        """What "no choice made here" means: the installed model's own cards, else the recommendation."""
638        from strata_control import gpu_roles
639        inst = self.installed()
640        cards = self.cards()
641        if inst:
642            return gpu_roles.from_legacy(inst, cards, "as_given")
643        return dict(gpu_roles.recommend(cards, self.ctx.computer.engine_vendor)["roles"])
644
645    def on_mount(self) -> None:
646        from strata_control import gpu_roles
647        self.detail = False
648        self.note = ""
649        self.cardlist = self.cards()
650        self.roles = self.start_roles()
651        self.rec = gpu_roles.recommend(self.cardlist, self.ctx.computer.engine_vendor)
652        wide = max((len(gpu_roles.short_name(c)) for c in self.cardlist), default=20)
653        self.query_one(Menu).columns = [("", 8), ("", min(wide + 2, 34)), ("", 10), ("", 32), ("", 0)]
654        self.fill(0)
655        self.paint()
656
657    def role_cell(self, role: str) -> str:
658        words = [("main", "Main"), ("helper", "Helper"), ("off", "Off")]
659        return "".join(f"[ {w} ] " if r == role else f"  {w}   " for r, w in words)
660
661    def fill(self, index: int = 0) -> None:
662        from strata_control import gpu_roles
663        items = []
664        for c in self.cardlist:
665            i = int(c.get("index", 0))
666            role = self.roles.get(i, "off")
667            rec = self.rec["roles"].get(i)
668            tag = "recommended" if rec == role else f"recommended: {rec}"
669            mem = "built-in" if gpu_roles._shares(c) else f"{float(c.get('vram_gb') or 0):.0f} GB"
670            items.append(Item([gpu_roles.gpu_label(c), gpu_roles.short_name(c), mem, self.role_cell(role), Cell(tag, "" if rec == role else MUTE)], key=i))
671        self.query_one(Menu).set_items(items, index)
672
673    def current_card(self) -> int | None:
674        cur = self.menu().current if self.menu() else None
675        return None if cur is None else int(cur.key)
676
677    def action_role(self, role: str) -> None:
678        from strata_control import gpu_roles
679        i = self.current_card()
680        if i is None:
681            return
682        self.roles, code = gpu_roles.set_role(self.roles, self.cardlist, i, role)
683        self.note = gpu_roles.note_text(code, self.cardlist)
684        self.fill(self.menu().index)
685        self.paint()
686
687    def action_cycle(self, step: int) -> None:
688        order = ["main", "helper", "off"]
689        i = self.current_card()
690        if i is None:
691            return
692        self.action_role(order[(order.index(self.roles.get(i, "off")) + step) % 3])
693
694    def action_recommended(self) -> None:
695        self.roles = dict(self.rec["roles"])
696        self.note = ""
697        self.fill(self.menu().index)
698        self.paint()
699
700    def action_details(self) -> None:
701        self.detail = not self.detail
702        self.paint()
703
704    def is_cpu_engine(self) -> bool:
705        try:
706            return (self.ctx.catalog.installed_backend() or "") in ("cpu", "metal")
707        except Exception:                                    # noqa: BLE001
708            return False
709
710    def refresh_body(self) -> None:
711        if not hasattr(self, "roles"):
712            return
713        from strata_control import gpu_fit, gpu_roles
714        c = self.ctx.computer
715        try:
716            self.query_one("#reco", Static).update(Text(gpu_roles.sentence(self.cardlist, c.engine_vendor), style=MUTE))
717        except Exception:                                    # noqa: BLE001
718            return
719        lines = Text()
720        if self.note:
721            lines.append(f"  {self.note}\n", style=MUTE)
722        spill = gpu_roles.spill_for(self.roles, self.cardlist, self.model_memory(), c.ram_gb)
723        for w in gpu_roles.warnings(self.roles, self.cardlist, spill_gb=spill, engine_runs_cpu_only=self.is_cpu_engine()):
724            fix = ""
725            if w["fix"]:
726                n = gpu_roles.gpu_label(next(x for x in self.cardlist if int(x.get("index", 0)) == w["fix"]["card"]))
727                fix = f"   (select {n} and press {w['fix']['role'][0].upper()})"
728            lines.append(f"  ! {w['text']}{fix}\n", style=WARN)
729        if self.detail:
730            for word, text in (("Main", "does the last steps of every answer and keeps the conversation. Only one."),
731                               ("Helper", "holds a share of the model, so more of it fits on graphics cards."),
732                               ("Off", "Strata does not touch the card.")):
733                lines.append(f"  {word}: {text}\n", style=MUTE)
734        for g in gpu_fit.for_vendor(c.gpus, c.engine_vendor)[1]:
735            lines.append(f"  Not used: {g.get('name')} (another make of card than this engine drives).\n", style=MUTE)
736        try:
737            self.query_one("#cardnotes", Static).update(lines)
738        except Exception:                                    # noqa: BLE001
739            pass
740
741    def explain(self) -> Text:
742        return Text("Strata recommends the roles shown. A Helper holds part of the model; Off leaves a card alone (for a game or the screen). "
743                    "Any card is one key away; the choice is yours.", style=MUTE)
744
745    def commit(self) -> None:
746        if not hasattr(self, "roles"):
747            return
748        s = self.ctx.settings
749        if self.roles == self.baseline():
750            s.gpu_roles, s.gpus = None, None                 # the recommendation (or the installed choice) stays "not set": a card added later is re-recommended
751        else:
752            s.gpu_roles, s.gpus = {str(i): r for i, r in sorted(self.roles.items())}, None
753
754
755# ------------------------------------------------------------------------------------------------ 3 folder
756
757class FolderScreen(Base):
758    step_id = "folder"
759    hints = "Type to change the folder   Enter next   Esc back   ? help"
760    help_text = "Models are big. Pick a drive with free space. The default is where Strata keeps its data."
761
762    BINDINGS = [b for b in Base.BINDINGS if b.key not in ("q", "up", "down")] + [Binding("down", "noop", show=False)]
763
764    def body(self) -> ComposeResult:
765        yield Static(Text("Where should the model files be stored?", style=f"bold {ACCENT}"), markup=False)
766        yield Static("", id="folderinfo", markup=False)
767        yield Input(id="folderpath", classes="field open always")
768
769    def on_mount(self) -> None:
770        s = self.ctx.settings
771        f = self.query_one("#folderpath", Input)
772        f.value = s.data_dir or str(self.ctx.default_folder())
773        f.focus()
774        self.paint()
775
776    def action_noop(self) -> None:
777        pass
778
779    def on_input_changed(self, event: Input.Changed) -> None:
780        self.paint()
781
782    def on_input_submitted(self, event: Input.Submitted) -> None:
783        self.action_next()
784
785    def state(self, value: str | None = None):
786        return self.ctx.model_state(value or None)
787
788    def need_gb(self, st=None) -> float:
789        """The room to ask for: what is still to download plus working room (a little when the model is already there)."""
790        st = st or self.state()
791        return st.remaining_gb + (2.0 if (st.installed or st.own_files) else 8.0)
792
793    def refresh_body(self) -> None:
794        try:
795            value = self.query_one("#folderpath", Input).value.strip()
796        except Exception:                                    # noqa: BLE001
797            return
798        free = self.ctx.catalog.disk_free(value or self.ctx.default_folder())
799        st = self.state(value)
800        need = self.need_gb(st)
801        s = self.ctx.settings
802        out = Text()
803        if s.model_path:
804            out.append(f"Your model files stay where they are: {s.model_path}\n", style=FG)
805            out.append("Strata only writes its prepared data here (packs, a small draft layer).\n", style=MUTE)
806        out.append(st.headline(), style=FG)
807        out.append("\n")
808        if st.installed and st.folder is not None:
809            out.append(f"It is stored in {st.folder}\n", style=MUTE)
810        if st.parts and (st.installed or st.own_files):
811            for p in st.parts:
812                out.append(f"  - missing: {p.label}, about {p.gb:.1f} GB\n", style=WARN)
813        if free is not None:
814            warn = free < need
815            out.append(f"Free space in that folder's drive: {free:,.0f} GB", style=WARN if warn else FG)
816            if warn:
817                out.append(f"   Not enough for the {need:.0f} GB needed. You can still go on, but the download is likely to stop; pick a bigger drive.", style=WARN)
818        else:
819            out.append("The free space of that folder could not be read.", style=MUTE)
820        moving = self.models_that_would_move(value)
821        if moving:
822            out.append(f"\nModel files Strata already keeps in {moving} stay there and keep working. This folder is used for new downloads. "
823                       "To move them here, use: strata models move.", style=MUTE)
824        self.query_one("#folderinfo", Static).update(out)
825
826    def models_that_would_move(self, value: str) -> str | None:
827        """The folder holding model files today when a different one is typed (setup gathers the model files into the data folder), else None."""
828        try:
829            old = Path(self.ctx.default_folder())
830            new = Path(value).expanduser() if value else old
831            if os.path.normcase(str(new.resolve())) == os.path.normcase(str(old.resolve())):
832                return None
833            models = old / "models"
834            if models.is_dir() and any(models.iterdir()):
835                return str(old)
836        except OSError:
837            pass
838        return None
839
840    def explain(self) -> Text:
841        if self.state().installed:
842            return Text("This model is already on this computer, so the folder starts where it is. Press Enter to keep it. "
843                        "Another folder only matters for files that still have to be downloaded.", style=MUTE)
844        return Text("Models are large files. Strata keeps them in one folder; the default is Strata's own data folder. "
845                    "Press Enter to keep it, or type another folder (it is created if it does not exist). Models you already have stay where "
846                    "they are and stay usable; the new folder is for new downloads.", style=MUTE)
847
848    def typed(self) -> str:
849        return self.query_one("#folderpath", Input).value.strip().strip('"')
850
851    def action_next(self) -> None:
852        """The folder is checked before going on (B05): a path that cannot hold the models is said here, in plain words, and not saved."""
853        from strata_control import folders
854        found = folders.problem(self.typed())
855        if found:
856            self.say(folders.words(found), True)
857            return
858        super().action_next()
859
860    def commit(self) -> None:
861        value = self.typed()
862        default = str(self.ctx.default_folder())
863        self.ctx.settings.data_dir = None if (not value or value == default) else value
864
865
866# ------------------------------------------------------------------------------------------------ 4 context
867
868class ContextScreen(Base):
869    step_id = "context"
870    hints = "↑↓ choose   Enter next   m memory format   Esc back   ? help"
871    help_text = ("Context is how much text the model can see at once (your chat, files, tool output). A longer one lets agents read "
872                 "bigger projects, uses more memory, and makes the first reply of a long chat slower.")
873
874    BINDINGS = Base.BINDINGS + [Binding("m", "memory", "Memory format", show=False), Binding("c", "custom", "Custom", show=False)]
875
876    def body(self) -> ComposeResult:
877        yield Static(Text("How much text should it remember at once?", style=f"bold {ACCENT}"), markup=False)
878        yield Menu([("", 7), ("", 24), ("", 12), ("", 0)], id="menu")
879        yield Static("", id="kvline", markup=False)
880        yield Input(placeholder="a size like 100k, or a number of tokens", id="custom", classes="field", disabled=True)
881
882    def kv(self) -> str:
883        s = self.ctx.settings
884        return s.kv or "int8"
885
886    def on_mount(self) -> None:
887        s = self.ctx.settings
888        cat = self.ctx.catalog
889        fam, model = s.family, s.model
890        self.rec = cat.max_context(fam, model, self.ctx.computer.raw) if fam and model else 32768
891        if s.context is None:
892            s.context = self.rec
893        self.build()
894        self.paint()
895
896    def build(self) -> None:
897        s, cat = self.ctx.settings, self.ctx.catalog
898        items = []
899        sel = 0
900        sizes = cat.contexts_for(s.family, s.model)
901        for i, c in enumerate(sizes):
902            kvgb = cat.kv_gb(c, self.kv())
903            note, style = "", ""
904            if c == self.rec:
905                note = "recommended"
906            elif c > max(self.rec * 2, 131072) and c <= 262144:
907                note, style = "tight on this computer", WARN
908            elif c > 262144:
909                note, style = "experimental: rope scaling", WARN
910            items.append(Item([S.context_label(c), S.words_for(c), f"+{kvgb:.1f} GB", Cell(note, style)], key=c))
911            if c == s.context:
912                sel = i
913        if s.context and s.context not in sizes:
914            items.append(Item([S.context_label(s.context), S.words_for(s.context), f"+{cat.kv_gb(s.context, self.kv()):.1f} GB",
915                               Cell("your own size", "")], key=s.context))
916            sel = len(items) - 1
917        items.append(Item(["Custom…"], key="custom"))
918        self.query_one(Menu).set_items(items, sel)
919
920    def refresh_body(self) -> None:
921        s = self.ctx.settings
922        kv = self.kv()
923        label = {"int8": "8-bit (recommended: what the published numbers were measured with)",
924                 "q4_0": "4-bit (half the memory, a little less precise on long documents)",
925                 "k8v4": "mixed 8-bit and 4-bit", "fp16": "full precision"}.get(kv, kv)
926        small = (s.context or 0) <= 8192
927        self.query_one("#kvline", Static).update(Text(
928            f"Conversation memory: {label}" + ("" if not small else " (small contexts always use full precision)") + "   press m to change",
929            style=MUTE))
930
931    def explain(self) -> Text:
932        cur = self.menu().current if self.menu() else None
933        out = Text("More context lets agents read bigger projects. It uses more memory and the first reply of a long chat is slower. "
934                   "The memory shown is only the extra for the conversation itself.", style=MUTE)
935        if cur is not None and isinstance(cur.key, int) and cur.key > 262144:
936            out.append("\nThis is past what the model was trained on; setup adds rope scaling and answers may get less reliable.", style=WARN)
937        return out
938
939    def action_memory(self) -> None:
940        s = self.ctx.settings
941        order = ["int8", "q4_0"]
942        cur = s.kv or "int8"
943        s.kv = order[(order.index(cur) + 1) % len(order)] if cur in order else "int8"
944        self.build()
945        self.paint()
946
947    def action_custom(self) -> None:
948        self.open_field("custom", "", "a size like 100k, or a number of tokens")
949        self.say("Type a size and press Enter.")
950
951    def on_input_submitted(self, event: Input.Submitted) -> None:
952        if event.input.id != "custom":
953            return
954        try:
955            n = S.parse_context(event.value)
956        except ValueError as e:
957            self.say(str(e), True)
958            return
959        self.ctx.settings.context = n
960        self.close_field("custom")
961        self.build()
962        self.say(f"{S.context_label(n)} chosen.")
963        self.paint()
964
965    def action_back(self) -> None:
966        if self.input_open():
967            self.close_field("custom")
968            return
969        super().action_back()
970
971    def commit(self) -> None:
972        cur = self.menu().current
973        if cur is None:
974            return
975        if cur.key == "custom":
976            return
977        self.ctx.settings.context = int(cur.key)
978
979    def action_next(self) -> None:
980        if self.input_open():
981            return
982        cur = self.menu().current
983        if cur is not None and cur.key == "custom":
984            self.action_custom()
985            return
986        super().action_next()
987
988
989# ------------------------------------------------------------------------------------------------ 5 pictures
990
991class PicturesScreen(Base):
992    step_id = "pictures"
993    help_text = "Pictures let the model read screenshots, photos and scanned pages. It is a small extra download and a little graphics memory."
994
995    def body(self) -> ComposeResult:
996        yield Static(Text("Should the model read pictures?", style=f"bold {ACCENT}"), markup=False)
997        yield Menu(id="menu")
998
999    def row(self):
1000        s = self.ctx.settings
1001        return next((x for x in self.ctx.rows if (x.family, x.model) == (s.family, s.model)), None)
1002
1003    def reader(self) -> str:
1004        """"present" when the installed engine carries the picture reader (strata-vision), "missing" when an engine is installed without it,
1005        "unknown" before any engine is installed (the first launch fetches it)."""
1006        return self.ctx.catalog.reader_state()
1007
1008    def on_mount(self) -> None:
1009        s = self.ctx.settings
1010        r = self.row()
1011        self.supported = True if r is None else r.images
1012        items = [Item(["No pictures"], key="off")]
1013        if self.supported:
1014            items.append(Item(["Yes, read pictures" + ("  (this engine has no picture reader)" if self.reader() == "missing" else "")], key="on"))
1015        else:
1016            items.append(Item([Cell("Yes, read pictures: not available for this model yet", MUTE)], key="on", enabled=False))
1017        sel = 1 if s.vision != "off" and self.supported and self.reader() != "missing" else 0       # pictures are on unless someone said off
1018        self.query_one(Menu).set_items(items, sel)
1019        self.paint()
1020
1021    def explain(self) -> Text:
1022        amd = any(str(g.get("vendor")) == "amd" for g in self.ctx.computer.usable_gpus)
1023        on_card = self.ctx.catalog.picture_default(True) == "gpu"
1024        extra = ("a 0.9 GB download (if it is not on this computer yet). On your AMD card the picture reader runs on the graphics card "
1025                 "(about 1 GB of its memory, under a second per picture) and starts on the processor by itself if it cannot."
1026                 if amd and on_card and self.reader() != "missing" else
1027                 "a 0.9 GB download (if it is not on this computer yet), and about 1.4 GB of graphics memory kept free for the picture reader "
1028                 "(text is a few % slower)." if on_card else
1029                 "a 0.9 GB download (if it is not on this computer yet). The picture reader runs on the CPU: a few seconds per picture, nothing "
1030                 "taken from the graphics card.")
1031        if not self.supported:
1032            return Text("This model cannot read pictures yet, so pictures stay off. Pick another model if you need them.", style=WARN)
1033        out = Text("Pictures are on by default. They add " + extra + " Say No if you only chat in text.", style=MUTE)
1034        if self.reader() == "missing":
1035            out.append("\nHeads up: the engine installed here does not carry the picture reader, so the model would answer text only. "
1036                       "Update the engine, or say No.", style=WARN)
1037        return out
1038        return out
1039
1040    def commit(self) -> None:
1041        key = self.menu().current.key
1042        if key == "on":                                      # yes: the reader on the card (NVIDIA, AMD) or the CPU, as the default says
1043            device = self.ctx.catalog.picture_default(True)
1044            key = device if device != "off" else "on"
1045        self.ctx.settings.vision = key
1046
1047
1048# ------------------------------------------------------------------------------------------------ drafting
1049
1050def drafting_launch_word(ctx) -> str | None:
1051    """The Drafting word this launch was given last time (its own run config): a chosen drafter stays chosen at a start with no word (Runner.keep_saved_word,
1052    keep_saved_off), so the Drafting step shows it and an Auto picked there is written to replace it."""
1053    try:
1054        from strata_cli.launch import runner
1055        return runner.saved_launch_word(runner.launch_name_of(ctx.settings))
1056    except Exception:                                        # noqa: BLE001 - no readable file, no word
1057        return None
1058
1059
1060def drafting_saved_choice(ctx, choices) -> str:
1061    """The Drafting row a start with no new choice runs, in the order the start reads them: the model's own saved choice (the app's Models screen), the draft
1062    layer switched off with no choice (Off), the word this launch was given last time, else Auto."""
1063    from strata_cli.launch import modelstate
1064    base = ctx.base_config() or {}
1065    own = str(base.get("drafting") or "").strip().lower()
1066    if own in choices:
1067        return own
1068    if modelstate.layer_off_without_choice(base):
1069        return "off"
1070    word = drafting_launch_word(ctx)
1071    return word if word in choices and modelstate.drafting_for_family(word, ctx.settings.family) is not None else "auto"
1072
1073
1074class DraftingScreen(Base):
1075    step_id = "drafting"
1076    help_text = "Drafting is how the model guesses the next words ahead to make answers faster. One drafter runs at a time."
1077
1078    CHOICES = (("auto", "Auto (recommended)"), ("mtp", "MTP"), ("dflash2", "DFlash2"), ("off", "Off"))
1079
1080    def body(self) -> ComposeResult:
1081        yield Static(Text("How should the model guess ahead?", style=f"bold {ACCENT}"), markup=False)
1082        yield Menu(id="menu")
1083
1084    def on_mount(self) -> None:
1085        s = self.ctx.settings
1086        from strata_cli.launch import modelstate
1087        now = {"dflash2": "DFlash2", "mtp": "MTP", "off": "Off"}[modelstate.resolved_drafting(None, s.family)]
1088        items = [Item([label, Cell(now, "") if key == "auto" else Cell("", "")], key=key) for key, label in self.CHOICES]
1089        shown = s.drafting if s.drafting in dict(self.CHOICES) else drafting_saved_choice(self.ctx, dict(self.CHOICES))
1090        sel = [key for key, _ in self.CHOICES].index(shown)
1091        self.query_one(Menu).columns = [("", 24), ("", 0)]
1092        self.query_one(Menu).set_items(items, sel)
1093        self.paint()
1094
1095    def explain(self) -> Text:
1096        return Text("")
1097
1098    def commit(self) -> None:
1099        key = self.menu().current.key
1100        from strata_cli.launch import modelstate
1101        # Auto stays "nobody chose" (a saved preset writes nothing) unless the model's file or this launch holds another choice: then Auto is written, so it wins
1102        base = self.ctx.base_config() or {}
1103        layer_off = modelstate.layer_off_without_choice(base)  # the draft layer is off and nothing else is saved: the step showed Off
1104        if layer_off and key == "off" and self.ctx.settings.drafting is None:
1105            return                                            # Off left as it is: nothing new is written, the draft layer's "mtp": false keeps it
1106        saved = "off" if layer_off else base.get("drafting") if base.get("drafting") is not None else drafting_launch_word(self.ctx)
1107        self.ctx.settings.drafting = modelstate.drafting_to_save(key, saved)
1108
1109
1110# ------------------------------------------------------------------------------------------------ 6 parallel
1111
1112class ParallelScreen(Base):
1113    step_id = "parallel"
1114    help_text = ("Parallel requests: how many people or apps are answered at the same time. More at once makes each answer a bit slower "
1115                 "and needs graphics memory the model could use otherwise.")
1116
1117    def body(self) -> ComposeResult:
1118        yield Static(Text("How many requests at the same time?", style=f"bold {ACCENT}"), markup=False)
1119        yield Menu(id="menu")
1120
1121    def on_mount(self) -> None:
1122        vram = self.ctx.computer.main_vram_gb
1123        self.fit = S.fit_parallel(vram) if vram else 1
1124        s = self.ctx.settings
1125        items = [Item([f"Fit to my graphics card ({self.fit})", Cell("recommended", "")], key=None)]
1126        for n in (1, 2, 3, 4):
1127            note, style = "", ""
1128            if n > self.fit:
1129                note, style = "may not fit: slower answers", WARN
1130            items.append(Item([f"{n} request" + ("s" if n != 1 else ""), Cell(note, style)], key=n))
1131        sel = 0 if s.parallel is None else min(4, max(1, s.parallel))
1132        self.query_one(Menu).columns = [("", 36), ("", 0)]
1133        self.query_one(Menu).set_items(items, sel)
1134        self.paint()
1135
1136    def explain(self) -> Text:
1137        vram = self.ctx.computer.main_vram_gb
1138        return Text(f"Your card has {vram:.0f} GB of graphics memory, which fits {self.fit} at once by Strata's rule "
1139                    "(12 GB: 1, 20 GB: 2, 24 GB: 3, 32 GB or more: 4). One person: pick 1. A team or several coding agents: more. "
1140                    "More than fits still starts, only slower." if vram else
1141                    "No graphics card was found, so Strata cannot say how many fit. 1 is the safe choice.", style=MUTE)
1142
1143    def commit(self) -> None:
1144        self.ctx.settings.parallel = self.menu().current.key
1145
1146
1147# ------------------------------------------------------------------------------------------------ 7 tuning
1148
1149class TuningScreen(Base):
1150    step_id = "tuning"
1151    hints = "↑↓ choose   Enter next   a answer-changing settings on/off   Esc back   ? help"
1152    help_text = ("Tuning measures a few settings on this computer and keeps only real gains. It runs after the model is downloaded, "
1153                 "before serving starts. You can stop it at any time: nothing changes until it is done.")
1154
1155    BINDINGS = Base.BINDINGS + [Binding("a", "allow", "Allow", show=False)]
1156
1157    def body(self) -> ComposeResult:
1158        yield Static(Text("Tune for the best speed on this computer?", style=f"bold {ACCENT}"), markup=False)
1159        yield Menu([("", 12), ("", 22), ("", 0)], id="menu")
1160        yield Static("", id="allowline", markup=False)
1161
1162    def on_mount(self) -> None:
1163        s = self.ctx.settings
1164        first = self.ctx.fresh_setup and not s.is_tuned
1165        items = [Item(["Quick", "about 20 minutes", "checks the most likely gains" + ("; suggested the first time" if first else "")], key="quick"),
1166                 Item(["Thorough", "up to 2 hours", "tries more settings, measures each one several times"], key="thorough"),
1167                 Item(["Skip", "", "use the default settings (already good on most computers)"], key="skip")]
1168        if not self.ctx.tune_chosen and s.tune == "skip" and not s.is_tuned and self.ctx.fresh_setup:
1169            s.tune = "quick"
1170        self.query_one(Menu).set_items(items, {"quick": 0, "thorough": 1, "skip": 2}.get(s.tune, 0))
1171        self.paint()
1172
1173    def refresh_body(self) -> None:
1174        on = self.ctx.settings.tune_allow_small
1175        self.query_one("#allowline", Static).update(Text(
1176            f"\n  [{'x' if on else ' '}] Allow settings that change answers very slightly (same quality)   press a to change", style=MUTE))
1177
1178    def explain(self) -> Text:
1179        return Text("Tuning is optional: it keeps only real gains, and the result is a preset the Strata app can use too. Close other heavy "
1180                    "programs while it measures. The command line skips tuning unless you add --tune.", style=MUTE)
1181
1182    def action_allow(self) -> None:
1183        self.ctx.settings.tune_allow_small = not self.ctx.settings.tune_allow_small
1184        self.paint()
1185
1186    def commit(self) -> None:
1187        self.ctx.settings.tune = self.menu().current.key
1188        self.ctx.tune_chosen = True
1189
1190
1191# ------------------------------------------------------------------------------------------------ 8 advanced
1192
1193class AdvancedScreen(Base):
1194    step_id = "advanced"
1195    hints = "n next   ↑↓ choose   Enter edit   Esc back   Del reset   x experimental   / filter   a add by name   c copy command   Tab scroll command"
1196    help_text = ("Every engine setting with its default, the value the tuner chose and your own value. You never have to touch this. "
1197                 "A name the engine does not list gets a warning, not a refusal.")
1198
1199    BINDINGS = [b for b in Base.BINDINGS if b.key != "enter"] + [
1200        Binding("enter", "edit", show=False), Binding("delete", "reset", show=False), Binding("backspace", "reset", show=False),
1201        Binding("x", "experimental", show=False), Binding("slash", "filter", show=False), Binding("a", "add", show=False),
1202        Binding("c", "copy", show=False), Binding("n", "go_next", show=False), Binding("right", "go_next", show=False),
1203        Binding("tab", "scroll_command", show=False)]
1204
1205    def body(self) -> ComposeResult:
1206        yield Static("", id="advhead", markup=False)
1207        yield Menu([("Setting", 24), ("Default", 11), ("Tuned", 13), ("Yours", 10), ("What it does", 0)], id="menu", window=8)
1208        with VerticalScroll(id="cmdbox"):                    # the long command has its own scroll area (Tab, then the arrows) instead of running off the screen
1209            yield Static("", id="cmdline", markup=False)
1210        yield Input(id="edit", classes="field", disabled=True)
1211
1212    def on_mount(self) -> None:
1213        self.only_experimental = False
1214        self.filter = ""
1215        self.mode = ""         # "", "edit", "filter", "add"
1216        self.rows: list[P.Row] = []
1217        self.load_rows()
1218        self.paint()
1219
1220    def load_rows(self) -> None:
1221        self.rows = self.ctx.advanced_rows()
1222        self.build()
1223
1224    def build(self) -> None:
1225        items = []
1226        for r in self.rows:
1227            if self.only_experimental and not r.experimental:
1228                continue
1229            if self.filter and self.filter.lower() not in r.name.lower() and self.filter.lower() not in r.description.lower():
1230                continue
1231            d, t, y = r.cells()[1:]
1232            desc = ("[experimental] " if r.experimental else "") + r.description
1233            items.append(Item([r.name, d, t, Cell(y, ACCENT if y != "-" else ""), Cell(desc, WARN if r.experimental else (BAD if not r.known else ""))],
1234                              key=r.name))
1235        items.append(Item([Cell("+ Add a setting by name…", ""), "", "", "", Cell("for flags of newer engine versions", MUTE)], key="__add__"))
1236        m = self.query_one(Menu)
1237        body_h = self.query_one("#body").size.height or max(6, (self.size.height or 30) - 8)
1238        box_h = max(3, min(8, body_h // 3))
1239        self.query_one("#cmdbox").styles.height = box_h
1240        m.window = max(3, body_h - box_h - 4)                # the heading, the column titles, the "n of m" line and the box's rule
1241        m.set_items(items, min(m.index, len(items) - 1))
1242
1243    def on_resize(self, _e) -> None:
1244        if hasattr(self, "rows"):
1245            self.build()
1246        self.paint()
1247
1248    def refresh_body(self) -> None:
1249        eng = self.ctx.engine_note
1250        t = Text(no_wrap=True, overflow="ellipsis")
1251        t.append("All settings", style=f"bold {ACCENT}")
1252        if self.width() >= 70:
1253            t.append("   (optional · for tinkerers)", style=MUTE)
1254            extra = "   / filter" + (f": {self.filter}" if self.filter else "") + "   x show experimental only" + (" (on)" if self.only_experimental else "")
1255        else:
1256            extra = "  (optional)" + (f"  filter: {self.filter}" if self.filter else "") + ("  experimental only" if self.only_experimental else "")
1257        t.append(extra, style=MUTE)
1258        self.query_one("#advhead", Static).update(t)
1259        s = self.ctx.settings
1260        cmd = self.ctx.command_text()
1261        out = Text()
1262        out.append("Command that will run (your choices above are in it)\n", style=f"bold {ACCENT}")
1263        out.append("  " + cmd + "\n")
1264        out.append("  Same as: " + S.flags_text(s) + "\n", style=MUTE)
1265        if eng:
1266            out.append("  " + eng, style=WARN)
1267        self.query_one("#cmdline", Static).update(out)
1268
1269    def hints_text(self) -> str:
1270        if (self.size.width or 80) < 60:
1271            return "n next  Enter edit  Esc back  Tab command"
1272        return super().hints_text()
1273
1274    def explain(self) -> Text:
1275        if (self.size.height or 30) < 20:
1276            return Text("")                                  # a small window: the list and the command matter more than the sentence under them
1277        m = self.menu()
1278        cur = m.current if m else None
1279        if cur is not None and cur.key not in (None, "__add__"):
1280            r = next((x for x in self.rows if x.name == cur.key), None)
1281            if r:
1282                return Text(f"{r.name}: {r.description}" + (" This one is experimental: it may change answers or not work on every card." if r.experimental else ""), style=MUTE)
1283        return Text("Press Enter on a row to set your own value; Del puts the tuned value back. You can go on without touching anything: n.", style=MUTE)
1284
1285    # ---- editing
1286    def action_edit(self) -> None:
1287        if self.mode:
1288            return
1289        cur = self.menu().current
1290        if cur is None:
1291            return
1292        if cur.key == "__add__":
1293            return self.action_add()
1294        self.mode = "edit"
1295        self.edit_name = cur.key
1296        r = next(x for x in self.rows if x.name == cur.key)
1297        self.open_field("edit", r.yours or (r.tuned if r.tuned != "-" else r.default) or "", f"value for {cur.key} (empty = on, 'off' removes it)")
1298        self.say(f"Type the value for {cur.key} and press Enter. Esc cancels.")
1299
1300    def action_add(self) -> None:
1301        if self.mode:
1302            return
1303        self.mode = "add"
1304        self.open_field("edit", "", "name=value, e.g. prefill=65536 or STRATA_PIN_BY_NEED=1")
1305        self.say("Type the setting as name=value (the name of a newer engine's flag is fine).")
1306
1307    def action_filter(self) -> None:
1308        if self.mode:
1309            return
1310        self.mode = "filter"
1311        self.open_field("edit", self.filter, "part of a name or description")
1312
1313    def on_input_submitted(self, event: Input.Submitted) -> None:
1314        if event.input.id != "edit":
1315            return
1316        text = event.value.strip()
1317        mode = self.mode
1318        self.mode = ""
1319        self.close_field("edit")
1320        if mode == "filter":
1321            self.filter = text
1322        elif mode == "edit":
1323            self.set_value(self.edit_name, text)
1324        elif mode == "add" and text:
1325            try:
1326                key, value = S.split_setting(text)
1327            except ValueError as e:
1328                self.say(str(e), True)
1329                return
1330            self.set_value(key, value)
1331        self.build()
1332        self.paint()
1333
1334    def set_value(self, key: str, value: str) -> None:
1335        s = self.ctx.settings
1336        s.extra[key] = value
1337        warn = P.check_name(key, self.ctx.engine_flags)
1338        self.ctx.invalidate_rows()
1339        self.rows = self.ctx.advanced_rows()
1340        self.say(warn or f"{key} set to {value or 'on'}. It is used for this launch.", bool(warn))
1341
1342    def action_reset(self) -> None:
1343        if self.mode:
1344            return
1345        cur = self.menu().current
1346        if cur is None or cur.key in (None, "__add__"):
1347            return
1348        if self.ctx.settings.extra.pop(cur.key, None) is not None:
1349            self.ctx.invalidate_rows()
1350            self.rows = self.ctx.advanced_rows()
1351            self.build()
1352            self.say(f"{cur.key} is back to the tuned value.")
1353            self.paint()
1354
1355    def action_experimental(self) -> None:
1356        if self.mode:
1357            return
1358        self.only_experimental = not self.only_experimental
1359        self.build()
1360        self.paint()
1361
1362    def action_copy(self) -> None:
1363        if self.mode:
1364            return
1365        text = self.ctx.command_text() + "\n" + S.flags_text(self.ctx.settings)
1366        try:
1367            self.app.copy_to_clipboard(text)
1368            self.say("Copied the command to the clipboard (if your terminal allows it).")
1369        except Exception:                                    # noqa: BLE001
1370            self.say("Your terminal does not allow copying; select the lines above with the mouse.", True)
1371
1372    def action_scroll_command(self) -> None:
1373        box = self.query_one("#cmdbox")
1374        if box.has_focus:
1375            self.set_focus(None)
1376            self.say("")
1377        else:
1378            box.focus()
1379            self.say("Up/Down/PageUp/PageDown scroll the command; Tab or Esc goes back to the list.")
1380
1381    def action_go_next(self) -> None:
1382        if self.mode:
1383            return
1384        self.app.advance()           # type: ignore[attr-defined]
1385
1386    def action_next(self) -> None:
1387        self.action_edit()
1388
1389    def action_back(self) -> None:
1390        if self.mode:
1391            self.mode = ""
1392            self.close_field("edit")
1393            self.say("")
1394            return
1395        if self.query_one("#cmdbox").has_focus:
1396            self.set_focus(None)
1397            self.say("")
1398            return
1399        super().action_back()
1400
1401    def action_move(self, step: int) -> None:
1402        if self.mode:
1403            return
1404        super().action_move(step)
1405
1406
1407# ------------------------------------------------------------------------------------------------ 9 access
1408
1409class AccessScreen(Base):
1410    step_id = "access"
1411    hints = "↑↓ choose   Enter next   p port   k new key   t key on/off   Esc back   ? help"
1412    help_text = ("Who can use the model. 'This computer only' is the safe default and never needs a key. Beyond it Strata makes an API key "
1413                 "for you (recommended); press t if you would rather have no key: it still starts, but anyone who can reach it can use it. "
1414                 "To see the key later: strata launch --show-key. To use a key of your own: strata launch --api-key YOUR-KEY (or --api-key-env NAME).")
1415
1416    BINDINGS = Base.BINDINGS + [Binding("p", "port", show=False), Binding("k", "newkey", show=False), Binding("t", "keytoggle", show=False)]
1417
1418    def body(self) -> ComposeResult:
1419        yield Static(Text("Who can use it?", style=f"bold {ACCENT}"), markup=False)
1420        yield Menu([("", 22), ("", 46), ("", 0)], id="menu")
1421        yield Static("", id="portkey", markup=False)
1422        yield Input(id="portfield", classes="field", disabled=True)
1423
1424    def on_mount(self) -> None:
1425        # #5812: the key this launch had when the step opened, and the one moving the highlight made (None: none made)
1426        self._entry_key, self._cursor_key = self.ctx.settings.api_key, None
1427        self.build()
1428        self.paint()
1429
1430    def drop_cursor_key(self) -> bool:
1431        """Back on 'This computer only': a key that only moving the highlight made goes again, so a local launch keeps none (#5812).
1432        A key the person made (k, t), gave (--api-key) or had before this step stays."""
1433        s = self.ctx.settings
1434        made = getattr(self, "_cursor_key", None)
1435        if made is None or s.api_key != made:
1436            return False
1437        s.api_key, self._cursor_key = getattr(self, "_entry_key", None), None
1438        return True
1439
1440    def build(self) -> None:
1441        s = self.ctx.settings
1442        opts = acc.options(s.port)
1443        items = []
1444        sel = 0
1445        for i, o in enumerate(opts):
1446            note = o.note
1447            style = WARN if o.warn else ""
1448            items.append(Item([o.label, o.url, Cell(note, style)], key=o.kind))
1449            if o.kind == s.access:
1450                sel = i
1451        self.opts = {o.kind: o for o in opts}
1452        self.query_one(Menu).set_items(items, sel)
1453
1454    def refresh_body(self) -> None:
1455        s = self.ctx.settings
1456        on = bool(s.api_key)
1457        beyond = s.access != "local"
1458        t = Text()
1459        t.append(f"\n   Port      [ {s.port} ]   press p to change\n")
1460        t.append(f"   API key   [ {'on' if on else 'off'} ]   {acc.mask_key(s.api_key)}  ", style=FG if on else WARN)
1461        t.append(("(recommended for anything beyond this computer; t = no key)" if on else "(t = make a key)") if beyond else "(not needed on this computer)", style=MUTE)
1462        self.query_one("#portkey", Static).update(t)
1463
1464    def explain(self) -> Text:
1465        cur = self.menu().current if self.menu() else None
1466        out = Text()
1467        if cur is not None:
1468            missing = acc.missing_helper(cur.key)
1469            if missing:
1470                out.append(missing + "\n", style=WARN)
1471            fw = acc.firewall_note(cur.key)
1472            if fw:
1473                out.append(fw + "\n", style=WARN)
1474            if cur.key == "cloudflare":
1475                out.append("A Cloudflare quick tunnel gives a temporary public address; anyone with it can try to use the server, so an API key keeps others out.", style=MUTE)
1476            elif cur.key == "lan":
1477                out.append("Other computers on your network can use it at the address shown. An API key is recommended.", style=MUTE)
1478            elif cur.key == "tailscale":
1479                out.append("Only devices signed in to your Tailscale network can reach it.", style=MUTE)
1480            else:
1481                out.append("Only programs on this computer can reach it, so no key is needed.", style=MUTE)
1482        return out
1483
1484    def on_cursor(self) -> None:
1485        kind = self.menu().current.key
1486        s = self.ctx.settings
1487        s.access = kind
1488        if kind == "local" and self.drop_cursor_key():
1489            self.say("")
1490        elif kind != "local" and not s.api_key and not s.no_key:
1491            s.api_key = acc.kept_key() or acc.new_key()
1492            self._cursor_key = s.api_key
1493            self.say("An API key was made for you (recommended beyond this computer). Press t if you want no key.")
1494        elif kind != "local" and s.no_key:
1495            self.say(S.NO_KEY_PUBLIC if kind == "cloudflare" else S.NO_KEY_NETWORK, True)
1496
1497    def action_port(self) -> None:
1498        self.open_field("portfield", str(self.ctx.settings.port), "port number")
1499        self.say("Type a port from 1 to 65535 and press Enter.")
1500
1501    def on_input_submitted(self, event: Input.Submitted) -> None:
1502        if event.input.id != "portfield":
1503            return
1504        n = S.check_port(event.value.strip())
1505        if n and n.level == "error":
1506            self.say(n.line(), True)
1507            return
1508        self.ctx.settings.port = int(event.value.strip())
1509        self.close_field("portfield")
1510        self.build()
1511        self.say(n.line() if n else f"Port {self.ctx.settings.port}.", bool(n))
1512        self.paint()
1513
1514    def action_newkey(self) -> None:
1515        self.ctx.settings.api_key = acc.new_key()
1516        self.ctx.settings.no_key = False
1517        self.say("A new API key was made. Apps that used the old one need the new one (strata connect shows it).")
1518        self.paint()
1519
1520    def action_keytoggle(self) -> None:
1521        s = self.ctx.settings
1522        if s.api_key:
1523            s.api_key = None
1524            s.no_key = s.access != "local"
1525            self.say("The API key is off." + ((" " + (S.NO_KEY_PUBLIC if s.access == "cloudflare" else S.NO_KEY_NETWORK)) if s.access != "local" else ""), s.access != "local")
1526        else:
1527            s.api_key, s.no_key = acc.new_key(), False
1528            self.say("The API key is on.")
1529        self.paint()
1530
1531    def action_next(self) -> None:
1532        if self.input_open():
1533            return
1534        self.commit()
1535        self.app.advance()           # type: ignore[attr-defined]
1536
1537    def commit(self) -> None:
1538        s = self.ctx.settings
1539        s.access = self.menu().current.key
1540        if s.access == "local":
1541            self.drop_cursor_key()
1542        elif not s.api_key and not s.no_key:
1543            s.api_key = acc.kept_key() or acc.new_key()
1544
1545    def action_back(self) -> None:
1546        if self.input_open():
1547            self.close_field("portfield")
1548            return
1549        super().action_back()
1550
1551
1552# ------------------------------------------------------------------------------------------------ 10 save + launch
1553
1554class SaveScreen(Base):
1555    step_id = "save"
1556    hints = "↑↓ choose   Enter do it   Tab rename   Esc back   ? help"
1557    BINDINGS = Base.BINDINGS + [Binding("tab", "rename", show=False)]
1558    help_text = "Save remembers all your choices under a name so next time you start with one key. Launch downloads what is missing, tunes if you asked, and starts serving."
1559
1560    def body(self) -> ComposeResult:
1561        yield Static("", id="summary", markup=False)
1562        yield Input(id="name", classes="field open always")
1563        yield Menu(id="menu")
1564
1565    def on_mount(self) -> None:
1566        s = self.ctx.settings
1567        f = self.query_one("#name", Input)
1568        f.value = s.name or self.ctx.default_name()
1569        items = [Item(["Save as a preset and launch"], key="save_launch"), Item(["Launch without saving"], key="launch"),
1570                 Item(["Save the preset and stop here"], key="save")]
1571        self.query_one(Menu).set_items(items, 0)
1572        self.paint()
1573
1574    def hints_text(self) -> str:
1575        cur = self.menu().current if self.menu() else None
1576        label = (cur.cells[0] if isinstance(cur.cells[0], str) else cur.cells[0].text) if cur is not None else "do it"
1577        if (self.size.width or 80) < 60:
1578            return f"Enter: {label}  Esc back"
1579        return f"{self.g.updown} choose  Enter: {label}  Tab rename  Esc back  ? help"
1580
1581    def on_cursor(self) -> None:
1582        self.paint()
1583
1584    def summary_lines(self) -> list[tuple[str, str]]:
1585        s = self.ctx.settings
1586        from strata_cli.launch import modelstate
1587        r = next((x for x in self.ctx.rows if (x.family, x.model) == (s.family, s.model)), None)
1588        lines = [("Model", (r.title if r else (s.model or "?")) + (" (your files)" if s.model_path else "")),
1589                 ("Context", S.context_label(s.context) + f", memory {s.kv or 'int8'}"),
1590                 ("Pictures", "on" if s.vision != "off" else "off"),
1591                 *([("Drafting", dict(DraftingScreen.CHOICES).get(s.drafting or ("off" if modelstate.layer_off_without_choice(self.ctx.base_config()) else "auto"), "Auto (recommended)"))] if drafting_choice_available(self.ctx) else []),
1592                 ("Parallel", f"{s.parallel} at a time" if s.parallel else f"fit to your card ({S.fit_parallel(self.ctx.computer.main_vram_gb)})"),
1593                 ("Tuning", {"quick": "quick (about 20 min)", "thorough": "thorough (up to 2 h)", "skip": "skipped"}[s.tune]),
1594                 ("Access", f"{S.ACCESS_WORDS[s.access]}, port {s.port}" + (", API key on" if s.api_key else ", no API key")),
1595                 ("Storage", s.data_dir or str(self.ctx.default_folder()))]
1596        if s.extra:
1597            lines.append(("Advanced", ", ".join(f"{k}={v}" for k, v in s.extra.items())))
1598        return lines
1599
1600    def refresh_body(self) -> None:
1601        """The summary, the name and the three choices. When the body is too short for all of it (a small window), the summary shrinks to a
1602        few short lines and the name field to one row, so the three choices stay on screen and Enter never acts on something you cannot see."""
1603        s = self.ctx.settings
1604        lines = self.summary_lines()
1605        warnings = self.ctx.warnings()
1606        body_h = self.query_one("#body").size.height
1607        full_need = 2 + len(lines) + len(warnings) + 3 + 3
1608        compact = bool(body_h) and full_need > body_h
1609        name = self.query_one("#name", Input)
1610        name.set_class(compact, "slim")
1611        if compact:
1612            t = Text(no_wrap=True, overflow="ellipsis")
1613            tiny = body_h < 9
1614            model = dict(lines)["Model"].replace("Qwen3.8-Flash-Next ", "")
1615            rows = [f"{model} \u00b7 {S.context_label(s.context)} \u00b7 memory {s.kv or 'int8'}",
1616                    f"Pictures {'on' if s.vision != 'off' else 'off'} \u00b7 Parallel {s.parallel or 'auto'} \u00b7 Tuning {s.tune}",
1617                    f"Access {s.access}, port {s.port}" + (f" \u00b7 Storage {s.data_dir}" if s.data_dir else "")]
1618            t.append("Save, then launch   name:\n" if tiny else "Save as preset, then launch   name:\n", style=f"bold {ACCENT}")
1619            for ln in rows[:2 if tiny else 3]:
1620                t.append("  " + ln + "\n")
1621            if warnings and not tiny:
1622                t.append(f"  ! {warnings[0]}" + (f"  (+{len(warnings) - 1} more)" if len(warnings) > 1 else "") + "\n", style=WARN)
1623            t.rstrip()
1624        else:
1625            t = Text()
1626            t.append("Save as preset, then launch\n", style=f"bold {ACCENT}")
1627            t.append("  Name   ")
1628            t.append("(type below)\n", style=MUTE)
1629            for k, v in lines:
1630                if k == "Storage":   # one row: a long folder wrapped and pushed the last choice off an 80x24 screen
1631                    v = middle_shorten(v, self.width() - 14, "…" if self.g.unicode else "...")
1632                t.append(f"  {k:<10}{v}\n")
1633            for n in warnings:
1634                t.append(f"  ! {n}\n", style=WARN)
1635            t.rstrip()
1636        self.query_one("#summary", Static).update(t)
1637        if getattr(self, "_compact", None) != compact:       # the body's height changes with it: look again once the layout has settled
1638            self._compact = compact
1639            self.call_after_refresh(self.paint)
1640
1641    def explain(self) -> Text:
1642        if (self.size.height or 30) < 20:
1643            return Text("")                                  # a small window: the choices matter more than the sentence
1644        st = self.ctx.model_state()
1645        if st.remaining_gb < 0.05:
1646            fetch = "Nothing needs to be downloaded."
1647        elif st.only_helpers:
1648            fetch = "The model is already downloaded; Strata fetches " + st._names() + "."        # noqa: SLF001
1649        else:
1650            fetch = f"Strata downloads about {st.remaining_gb:.0f} GB first."
1651        tune = " It tunes first." if self.ctx.settings.tune != "skip" else ""
1652        return Text(f"Press Enter on the first choice to save and start. {fetch}{tune} The Strata monitor opens in this window when it is serving; "
1653                    "no web page opens by itself.", style=MUTE)
1654
1655    def action_rename(self) -> None:
1656        self.query_one("#name", Input).focus()
1657        self.say("Type the preset's name and press Enter.")
1658
1659    def on_input_submitted(self, event: Input.Submitted) -> None:
1660        if event.input.id == "name":
1661            self.set_focus(None)
1662            self.say("")
1663
1664    def action_next(self) -> None:
1665        name = self.query_one("#name", Input).value.strip() or self.ctx.default_name()
1666        choice = self.menu().current.key
1667        s = self.ctx.settings
1668        s.name = name
1669        if choice in ("save", "save_launch"):
1670            try:
1671                if choice == "save":
1672                    store.save(s, name)
1673                else:
1674                    store.check_name(name)                   # saved by the run once the restart question (if any) is answered "Restart"
1675            except store.PresetError as e:
1676                self.say(str(e), True)
1677                return
1678            if choice == "save_launch":
1679                self.ctx.pending_save = name
1680        if choice == "save":
1681            self.app.exit(None)
1682            self.app.stopped_after_save = True       # type: ignore[attr-defined]
1683            return
1684        self.app.run_launch()                        # type: ignore[attr-defined]
1685
1686    def action_quit_app(self) -> None:
1687        pass
1688
1689
1690# ------------------------------------------------------------------------------------------------ progress
1691
1692class RunScreen(Base):
1693    step_id = "run"
1694    title_line = "Launch"
1695    hints = "s stop   q quit"
1696    BINDINGS = [Binding("s", "stop_run", show=False), Binding("q", "stop_run", show=False), Binding("escape", "stop_run", show=False),
1697                Binding("r", "retry", show=False)]
1698
1699    STAGE_WORDS = (("engine", "Engine"), ("model", "Model"), ("config", "Settings"), ("tune", "Tuning"), ("start", "Starting"),
1700                   ("access", "Access"))
1701
1702    def body(self) -> ComposeResult:
1703        yield Static("", id="stages", markup=False)
1704        yield Static("", id="tunepanel", markup=False)
1705
1706    def __init__(self) -> None:
1707        super().__init__()
1708        self.state: dict[str, dict] = {k: {"text": "", "pct": None, "status": "wait"} for k, _ in self.STAGE_WORDS}
1709        self.failed: str | None = None
1710        self.tune_info: dict = {}
1711
1712    def on_mount(self) -> None:
1713        self.paint()
1714
1715    def head_text(self) -> Text:
1716        out = Text(no_wrap=True, overflow="crop")
1717        out.append("STRATA  Launch", style=f"bold {ACCENT}")
1718        s = self.ctx.settings
1719        out.append(f"   {s.name or ''}", style=MUTE)
1720        return out
1721
1722    def handle_event(self, ev) -> None:
1723        if ev.stage == "done":
1724            return
1725        st = self.state.get(ev.stage)
1726        if st is None:
1727            return
1728        for k, _ in self.STAGE_WORDS:           # earlier stages are finished
1729            if k == ev.stage:
1730                break
1731            if self.state[k]["status"] in ("wait", "run"):
1732                self.state[k]["status"] = "done" if self.state[k]["text"] else "skip"
1733        st["text"] = ev.text
1734        st["pct"] = ev.pct
1735        st["level"] = ev.level
1736        st["status"] = "done" if (ev.pct is not None and ev.pct >= 100) else "run"
1737        if ev.stage == "tune":
1738            self.tune_info = ev.data or {}
1739        self.paint()
1740
1741    def on_failure(self, text: str) -> None:
1742        self.failed = text
1743        self.paint()
1744
1745    def on_finished(self) -> None:
1746        for k, st in self.state.items():
1747            if st["status"] in ("wait", "run"):
1748                st["status"] = "done" if st["text"] else "skip"
1749        self.paint()
1750
1751    def refresh_body(self) -> None:
1752        t = Text()
1753        g = self.g
1754        width = max(20, min(40, self.width() - 50))
1755        for k, label in self.STAGE_WORDS:
1756            st = self.state.get(k) if hasattr(self, "state") else None
1757            if st is None:
1758                continue
1759            mark = {"wait": "  ", "run": "> ", "done": g.tick + " ", "skip": "- "}[st["status"]]
1760            style = ACCENT if st["status"] in ("run", "done") else MUTE
1761            if st.get("level") == "warn" and st["status"] != "run":
1762                style = WARN
1763            t.append(f"  {mark}{label:<10}", style=f"bold {style}")
1764            if st["pct"] is not None and st["status"] == "run":
1765                t.append(bar(st["pct"] / 100.0, width, g) + f" {st['pct']:.0f}%  ", style=ACCENT)
1766            t.append((st["text"] or "") + "\n", style=FG if st["status"] == "run" else MUTE)
1767        if self.failed:
1768            t.append("\n  " + self.failed + "\n", style=BAD)
1769            t.append("  Press r to try again, Esc to go back to the screens, q to quit.\n", style=MUTE)
1770        try:
1771            self.query_one("#stages", Static).update(t)
1772            self.query_one("#tunepanel", Static).update(self.tune_panel())
1773        except Exception:                                    # noqa: BLE001
1774            pass
1775
1776    def tune_panel(self) -> Text:
1777        t = Text()
1778        info = self.tune_info
1779        if not info or self.state["tune"]["status"] == "wait":
1780            return t
1781        t.append("\n  Tuning", style=f"bold {ACCENT}")
1782        rnd = info.get("round")
1783        if rnd and rnd[1]:
1784            t.append(f"   measurement {rnd[0]} of {rnd[1]}")
1785        if info.get("minutes_left"):
1786            t.append(f"   about {info['minutes_left']} min left")
1787        t.append("\n")
1788        for sp in (info.get("speeds") or [])[-6:]:
1789            label = {"base": "Default settings", "base_aa": "Default settings, measured again"}.get(sp.get("label") or sp.get("id"),
1790                                                                                                 sp.get("label") or sp.get("id") or "?")
1791            val = sp.get("decode_tok_s") or sp.get("value") or sp.get("tok_s")
1792            t.append(f"    {str(label)[:34]:<36}{val if val is not None else '-'}" + (" tokens/s" if val is not None else "") + "\n")
1793        t.append("  Close other heavy programs while it measures. You can stop it any time: nothing changes until it is done.\n", style=MUTE)
1794        return t
1795
1796    def explain(self) -> Text:
1797        return Text("Strata is getting everything ready. This can take a while the first time (the model is large). "
1798                    "Stopping is safe: files already downloaded are kept and a download continues where it stopped.", style=MUTE)
1799
1800    def action_stop_run(self) -> None:
1801        self.app.stop_run(self)            # type: ignore[attr-defined]
1802
1803    def action_retry(self) -> None:
1804        if self.failed:
1805            self.app.run_launch()          # type: ignore[attr-defined]
1806
1807    def action_move(self, step: int) -> None:
1808        pass
1809
1810    def action_next(self) -> None:
1811        pass