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