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