okami.mom/strata

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

Niko1221launch: Auto tells setup the drafter the start runs (12 GB card, IQ3_S)68a2916b7

main
21.5 KiB479 linesraw
1"""The `strata launch` application: the screens in order, the run, and the hand-over to the monitor.
2
3`run_tui` opens the screens (or, with settings already chosen, goes straight to the run), then the Strata Monitor with the
4launch-aware extras: a Connect view (key 7) and a quit question (keep serving in the background, or stop).
5"""
6
7from __future__ import annotations
8
9import sys
10import threading
11from dataclasses import dataclass, field
12from pathlib import Path
13from typing import Any
14
15from textual.app import App
16from textual.binding import Binding
17
18from strata_cli.launch import access as acc
19from strata_cli.launch import params as P
20from strata_cli.launch import settings as S
21from strata_cli.launch import store
22from strata_cli.launch.catalog import Catalog
23from strata_cli.launch.runner import Cancelled, Event, LaunchError, Result, Runner, auto_signals, read_config
24from strata_cli.launch.screens import (AccessScreen, AdvancedScreen, CardsScreen, ConfirmScreen, ContextScreen, DraftingScreen, FolderScreen,
25                                       ModelScreen, ParallelScreen, PicturesScreen, RunScreen, SaveScreen, StartScreen,
26                                       TuningScreen, flow_for)
27from strata_cli.launch.widgets import CSS, Glyphs
28
29SCREENS = {"model": ModelScreen, "cards": CardsScreen, "folder": FolderScreen, "context": ContextScreen, "pictures": PicturesScreen, "drafting": DraftingScreen,
30           "parallel": ParallelScreen, "tuning": TuningScreen, "advanced": AdvancedScreen, "access": AccessScreen, "save": SaveScreen}
31
32
33@dataclass
34class Ctx:
35    """Everything the screens share: the catalog, this computer, the choices so far."""
36
37    catalog: Catalog
38    computer: Any
39    rows: list
40    settings: S.LaunchSettings
41    glyphs: Glyphs = field(default_factory=Glyphs)
42    feed: str | None = None
43    move_data: bool = False
44    retune: bool = False
45    restart: bool = False
46    pending_save: str | None = None          # the preset name "Save as a preset and launch" saves once nothing blocks the launch
47    notes: list[str] = field(default_factory=list)
48    start_own_files: bool = False
49    picked_in_list: bool = False
50    tune_chosen: bool = False
51    fresh_setup: bool = True
52    engine_note: str = ""
53    engine_flags: list[str] | None = None
54    _adv: list | None = None
55    _help: str | None = None
56
57    # ---- names and warnings
58    def default_name(self) -> str:
59        s = self.settings
60        base = f"{s.model or 'my model'} {S.context_label(s.context)}"
61        names = {p.name for p in store.list_presets()}
62        if base not in names:
63            return base
64        n = 2
65        while f"{base} ({n})" in names:
66            n += 1
67        return f"{base} ({n})"
68
69    def warnings(self) -> list[str]:
70        s = self.settings
71        out = [n.line() for n in S.check_access(s)]
72        out += [n.line() for n in S.check_parallel(s, vram_gb=self.computer.main_vram_gb or None)]
73        out += [n.line() for n in S.check_context(s)]
74        r = next((x for x in self.rows if (x.family, x.model) == (s.family, s.model)), None)
75        if r is not None and r.verdict != "fits":
76            out.append(f"{r.title}: {r.words}.")
77        if self.computer.other_vendor_note:
78            out.append(self.computer.other_vendor_note)
79        missing = acc.missing_helper(s.access)
80        if missing:
81            out.append(missing)
82        return out
83
84    # ---- the installed model's configuration (for the Advanced table and the command)
85    def base_config(self) -> dict | None:
86        s = self.settings
87        if not (s.family and s.model):
88            return None
89        path = self.catalog.installed_config(self.catalog.tag_of(s.family, s.model))
90        if path is None:
91            return None
92        try:
93            return read_config(path)
94        except (OSError, ValueError):
95            return None
96
97    def engine_exe(self) -> str | None:
98        try:
99            from strata_control import engine_component as ec
100            rep = ec.status()
101            return (rep.get("engine") or {}).get("exe") if rep.get("usable") else None
102        except Exception:                                    # noqa: BLE001
103            return None
104
105    # ---- where the model is and what it still needs
106    def model_state(self, data_dir: str | None = None):
107        """The chosen model's state (installed, what helper files are missing, sizes) for these choices."""
108        from strata_cli.launch import modelstate
109        s = self.settings
110        return modelstate.assess(self.catalog, s.family, s.model, vision=s.vision, model_path=s.model_path,
111                                 data_dir=data_dir if data_dir is not None else s.data_dir, rows=self.rows, mtp=s.mtp,
112                                 drafting=modelstate.resolved_drafting(s.drafting, s.family, **auto_signals(self.catalog, s, s.family)))
113
114    def default_folder(self) -> Path:
115        """The folder the Folder step starts with: where the chosen model already is (installed, or the person's own files with their
116        prepared data), else the data folder every command agrees on."""
117        s = self.settings
118        if s.model_path:
119            try:
120                from strata_control import discovery
121                p = Path(s.model_path).expanduser()
122                first = p if p.is_file() else next(iter(sorted(p.glob("*.gguf"))), None)
123                found = discovery.writable_beside(first) if first else None     # not a folder Strata cannot write to, nor a Hugging Face cache
124                if found:
125                    return Path(found)
126            except OSError:
127                pass
128            return self.catalog.data_dir()
129        return self.catalog.data_dir_for(s.family, s.model)
130
131    def invalidate_rows(self) -> None:
132        self._adv = None
133
134    def advanced_rows(self) -> list[P.Row]:
135        if self._adv is not None:
136            return self._adv
137        s = self.settings
138        cfg = self.base_config()
139        base_args = list((cfg or {}).get("args") or [])
140        base_env = dict((cfg or {}).get("env") or {})
141        tuned_args, tuned_env = None, None
142        if cfg:
143            try:
144                from strata_control import presets
145                merged, info = presets.overlay(cfg)
146                if info.get("applied"):
147                    tuned_args, tuned_env = list(merged.get("args") or []), dict(merged.get("env") or {})
148            except Exception:                                # noqa: BLE001
149                pass
150        exe = self.engine_exe()
151        text = P.engine_help_text(exe) if exe else None
152        if exe and text:
153            self.engine_flags = sorted({p.name for p in P.parse_help(text)})
154            self.engine_note = ""
155        else:
156            self.engine_flags = None
157            self.engine_note = ("The engine is not installed yet, so this list shows only what this launch uses. The full list "
158                                "appears after the first launch installs it.") if not exe else \
159                               "The engine's own list could not be read here; names are not checked."
160        if not cfg and not s.extra:
161            self.engine_note = self.engine_note or "The model is not installed yet; the defaults and tuned values appear after it is."
162        from strata_control import speed_switches
163        gpus = list(getattr(self.computer, "gpus", None) or [])
164        switches = P.switch_params(speed_switches.applicable(cfg, gpus, self.catalog.installed_backend()))
165        self._adv = P.build_rows(text, base_args, tuned_args, base_env, tuned_env, s.extra, switches)
166        return self._adv
167
168    def command_text(self) -> str:
169        s = self.settings
170        name = "launch-" + S.slug(s.name or self.default_name())
171        cfg = self.base_config()
172        line = f"strata runtime start --profile {name}"
173        if cfg is None:
174            return line + "   (the engine command is shown once the model is installed)"
175        try:
176            from strata_control import tune_knobs
177            from strata_cli.launch.runner import apply_choices, cards_for_launch, derive_config
178            from serve.server import engine_args
179            import contextlib
180            import io
181            d = derive_config(apply_choices(cfg, s), s, bool_flags=tune_knobs.BOOL_FLAGS, gpus=cards_for_launch(s, self.catalog, base=cfg))
182            if s.parallel:
183                d["parallel"] = s.parallel
184            with contextlib.redirect_stdout(io.StringIO()):
185                argv = engine_args(d)
186            argv = ["***" if (i and argv[i - 1] in ("--api-key",)) else a for i, a in enumerate(argv)]
187            return f"{Path(str(d.get('exe', 'engine'))).name} {' '.join(str(a) for a in argv)}"
188        except Exception:                                    # noqa: BLE001
189            return line
190
191
192class LaunchApp(App):
193    TITLE = "strata launch"
194    CSS = CSS
195    # Textual's own ctrl+c only shows a "Do you want to quit?" note, and Escape pressed next also went Back (B13): ctrl+c quits like ctrl+q and q
196    BINDINGS = [Binding("ctrl+c", "quit", "Quit", show=False, priority=True)]
197
198    def __init__(self, ctx: Ctx, *, auto_run: bool = False) -> None:
199        super().__init__()
200        self.ctx = ctx
201        self.history: list[str] = []
202        self.result: Result | None = None
203        self.stopped_after_save = False
204        self.cancel = threading.Event()
205        self.auto_run = auto_run
206        self.runner: Runner | None = None
207        self.run_screen: RunScreen | None = None
208        self.running = False
209        self.current = "start"
210
211    def action_quit(self) -> None:
212        """ctrl+q and ctrl+c, as q on the screens: leave at once. Only a running download or tuning asks first ("Stop now?"), because work would be lost."""
213        if self.running and self.run_screen is not None:
214            self.stop_run(self.run_screen)
215        else:
216            self.exit(None)
217
218    def on_mount(self) -> None:
219        if self.auto_run:
220            self.run_launch()
221        else:
222            self.push_screen(StartScreen())
223
224    # ---- navigation
225    def flow(self) -> list[str]:
226        return flow_for(self.ctx)
227
228    def goto(self, step_id: str) -> None:
229        self.current = step_id
230        self.show(SCREENS[step_id]())
231
232    def begin_setup(self, *, preset: str | None = None, own_files: bool = False) -> None:
233        self.ctx.tune_chosen = False
234        self.ctx.fresh_setup = not preset
235        if preset:
236            s = store.load(preset)
237            self.ctx.settings = s
238        else:
239            self.ctx.settings = S.LaunchSettings()
240        self.ctx.start_own_files = own_files
241        self.ctx.picked_in_list = False
242        self.ctx.invalidate_rows()
243        self.current = "model"
244        self.show(ModelScreen())
245
246    def advance(self) -> None:
247        flow = self.flow()
248        i = flow.index(self.current) if self.current in flow else -1
249        if i + 1 < len(flow):
250            self.goto(flow[i + 1])
251
252    def back(self) -> None:
253        flow = self.flow()
254        i = flow.index(self.current) if self.current in flow else 0
255        if i > 0:
256            self.goto(flow[i - 1])
257        else:
258            self.current = "start"
259            self.show(StartScreen())
260
261    # ---- starting
262    def start_preset(self, name: str) -> None:
263        s = store.load(name)
264        self.ctx.settings = s
265        self.run_launch()
266
267    def show(self, screen) -> None:
268        """Put `screen` in front. The first screen of a run that skips the questions has nothing to replace (the app starts with only its
269        empty base screen), so it is pushed; every later one replaces the one on top. (switch_screen on the base screen raised
270        IndexError: pop from empty list, tester report T02.)"""
271        if len(self.screen_stack) <= 1:
272            self.push_screen(screen)
273        else:
274            self.switch_screen(screen)
275
276    def run_launch(self, confirmed: bool = False) -> None:
277        s = self.ctx.settings
278        self.cancel = threading.Event()
279        self.runner = Runner(s, catalog=self.ctx.catalog, emit=self._emit, cancel=self.cancel, feed=self.ctx.feed, confirm=self._ask_from_run,
280                             move_data=self.ctx.move_data, retune=self.ctx.retune, restart=self.ctx.restart,
281                             confirm_restart=self._ask_restart, after_check=self._save_pending)
282        gb = getattr(self.runner, "download_gb", lambda: 0.0)() if not confirmed else 0.0
283        if gb >= 1.0:
284            free = self.ctx.catalog.disk_free(s.data_dir or self.ctx.catalog.data_dir())
285            room = (f" There is {free:,.0f} GB free in the folder." if free is not None else "")
286            warn = (" That is less than the download needs; it will probably stop part way." if free is not None and free < gb + 8 else "")
287
288            def done(choice: str | None) -> None:
289                if choice == "go":
290                    self.run_launch(confirmed=True)
291
292            asker = getattr(self.runner, "download_question", None)
293            title, text = asker() if asker else (f"Download about {gb:.0f} GB?",
294                                                 f"This model is not on this computer yet. Strata will download about {gb:.0f} GB now; "
295                                                 "an interrupted download continues where it stopped.")
296            self.push_screen(ConfirmScreen(title, text + room + warn, [("go", "Download and start"), ("no", "Not now")]), done)
297            return
298        screen = RunScreen()
299        self.run_screen = screen
300        self.current = "run"
301        self.show(screen)
302        self.running = True
303        threading.Thread(target=self._work, daemon=True).start()
304
305    def _save_pending(self) -> None:
306        name, self.ctx.pending_save = self.ctx.pending_save, None
307        if name:
308            try:
309                store.save(self.ctx.settings, name)
310            except store.PresetError:
311                pass
312
313    def _ask_restart(self, title: str, text: str) -> bool:
314        """Another model is serving other choices: ask once, in the same pop-up, whether to restart it. Cancel leaves it running."""
315        return self._ask_from_run(title, text, [("go", "Restart"), ("no", "Cancel")], default=False)
316
317    def _ask_from_run(self, title: str, text: str, options: list[tuple[str, str]] | None = None, default: bool = True) -> bool:
318        """A question from the run (a worker thread): show it on the screen and wait for the answer. Enter means yes."""
319        box: dict[str, bool] = {"go": default}
320        answered = threading.Event()
321
322        def done(choice: str | None) -> None:
323            box["go"] = choice == "go"
324            answered.set()
325
326        def show() -> None:
327            self.push_screen(ConfirmScreen(title, text, options or [("go", "Download anyway"), ("no", "Not now")]), done)
328
329        if not self._call(show):                             # the app is closing
330            return False
331        while not answered.wait(0.2):
332            if self.cancel.is_set():
333                return False
334        return box["go"]
335
336    def _emit(self, ev: Event) -> None:
337        screen = self.run_screen
338        if screen is not None:
339            self._call(screen.handle_event, ev)
340
341    def _call(self, fn, *args) -> bool:
342        """call_from_thread from a worker thread, False when it could not be made: after a quit the app's loop is closed and
343        the call raises ("Event loop is closed"); the screen is gone then, so there is nothing to tell.  A loop already closed is not
344        asked at all: Textual makes the call's coroutine before it finds the loop closed, and that left a "coroutine was
345        never awaited" warning on the terminal."""
346        loop = getattr(self, "_loop", None)
347        if loop is not None and loop.is_closed():
348            return False
349        try:
350            self.call_from_thread(fn, *args)
351        except Exception:                                    # noqa: BLE001 - the app is closing
352            return False
353        return True
354
355    def _work(self) -> None:
356        screen = self.run_screen
357        try:
358            result = self.runner.run()               # type: ignore[union-attr]
359        except Cancelled:
360            self.running = False
361            self._call(self._after_cancel)
362            return
363        except LaunchError as e:
364            self.running = False
365            self._call(screen.on_failure, f"{e.text} {e.next}".strip())
366            return
367        except Exception as e:                           # noqa: BLE001
368            self.running = False
369            self._call(screen.on_failure, f"Something unexpected went wrong: {type(e).__name__}: {e}")
370            return
371        self.running = False
372        self._save_pending()                         # a runner that never asked (nothing was running) still saves what was chosen
373        s = self.ctx.settings
374        try:
375            if s.name and store.load(s.name, missing_ok=True) is not None:
376                store.save(s, s.name)
377                store.touch_used(s.name)
378        except Exception:                                # noqa: BLE001
379            pass
380        self.result = result
381        self._call(screen.on_finished)
382        self._call(self.exit, result)
383
384    def _after_cancel(self) -> None:
385        self.run_screen.on_failure("Stopped. Nothing was started.")     # type: ignore[union-attr]
386
387    def stop_run(self, screen) -> None:
388        if not self.running:
389            if screen.failed:
390                self.back_to_start()
391            else:
392                self.exit(None)
393            return
394
395        def done(choice: str | None) -> None:
396            if choice == "stop":
397                self.cancel.set()
398
399        self.push_screen(ConfirmScreen("Stop now?", "Files already downloaded are kept; a download continues where it stopped next time. "
400                                       "Nothing is started.", [("stop", "Stop"), ("go", "Keep going")]), done)
401
402    def back_to_start(self) -> None:
403        self.current = "start"
404        self.show(StartScreen())
405
406
407# ------------------------------------------------------------------------------------------------ the monitor
408
409def _info_for(result: Result, s: S.LaunchSettings) -> dict:
410    cfg = {}
411    try:
412        cfg = read_config(Path(result.config))
413    except (OSError, ValueError):
414        pass
415    return {"url": result.urls[0] if result.urls else f"http://127.0.0.1:{s.port}", "urls": result.urls, "key": result.key,
416            "model": cfg.get("model_name") or "strata", "context": s.context, "name": s.name, "profile": result.profile, "running": True,
417            "tunnel": result.tunnel}
418
419
420def run_monitor(info: dict, *, keep_default: bool = True, color: str = "auto") -> int:
421    """Open the monitor for a running launch. q asks whether to keep serving or stop."""
422    from strata_cli.client import Endpoint
423    from strata_cli.launch.monitor_ext import LaunchMonitor
424    local = next((u for u in info.get("urls", []) if "127.0.0.1" in u), None) or f"http://127.0.0.1:{info.get('port', S.DEFAULT_PORT)}"
425    endpoint = Endpoint(local, info.get("key"), 3.0, "")
426    app = LaunchMonitor(endpoint, None, info={**info, "daily_check": True}, color=color)     # (the quiet once-a-day check for a newer engine: this monitor only)
427    app.run()
428    if app.stop_requested:
429        from strata_control import runtime
430        try:
431            runtime.stop(info["profile"], timeout=180)
432        except Exception as e:                               # noqa: BLE001
433            print(f"strata: could not stop the server: {e}", file=sys.stderr)
434            return 6
435        acc.stop_tunnel(info["profile"])
436        print("Stopped. The model is unloaded and the graphics memory is free.")
437    else:
438        print(f"Still serving at {info['url']}. Watch it again: strata monitor --url {info['url']}   Stop: strata launch --stop")
439    return 0
440
441
442def run_tui(settings: S.LaunchSettings | None, *, catalog: Catalog | None = None, feed: str | None = None, auto_run: bool = False,
443            save: bool = False, open_page: bool = False, move_data: bool = False, retune: bool = False,
444            restart: bool = False) -> int:
445    """Open the launch screens. `settings` given and `auto_run`: skip the questions and go straight to the run."""
446    catalog = catalog or Catalog()
447    print("Looking at this computer…", flush=True)
448    computer = catalog.computer()
449    rows = catalog.rows(computer.raw)
450    from strata_cli.launch.cmd import apply_defaults
451    s = settings or S.LaunchSettings()
452    notes: list[S.Notice] = []
453    if settings is not None:
454        s, notes = apply_defaults(s, catalog)
455        if not s.name:
456            s.name = f"{s.model or 'model'} {S.context_label(s.context)}"
457        if save:
458            store.save(s, s.name)
459    ctx = Ctx(catalog=catalog, computer=computer, rows=rows, settings=s, glyphs=Glyphs(), feed=feed, move_data=move_data, retune=retune, restart=restart)
460    app = LaunchApp(ctx, auto_run=auto_run)
461    result = app.run()
462    if getattr(app, "return_code", 0) not in (0, None) or getattr(app, "_exception", None) is not None:
463        # The screens stopped on an error of their own (not a launch failure, which the run screen shows). Never end quietly with exit 0.
464        print("strata: The launch screens stopped because of an unexpected problem, and nothing was started. "
465              "Run the same command with --no-tui to see the steps as plain lines, and send the output if you ask for help.", file=sys.stderr)
466        return 1
467    if app.stopped_after_save:
468        print(f"Saved the preset '{ctx.settings.name}'. Start it with: strata launch --preset \"{ctx.settings.name}\"")
469        return 0
470    if result is None:
471        return 0
472    if not result.serving:
473        print(result.final_text)
474        return 0
475    info = _info_for(result, ctx.settings)
476    if open_page:                                            # only with an explicit --open: nothing else opens a browser
477        from strata_cli.launch.cmd import open_page as open_in_browser
478        open_in_browser(info["url"])
479    return run_monitor(info)