okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
64b48c0d0
main
1"""Optional Textual shell around the read-only terminal renderer.""" 2 3from __future__import annotations 4 5import asyncio 6import math 7import os 8import random 9import sys 10import time 11 12from rich .text import Text 13from textual .app import App ,ComposeResult 14from textual .binding import Binding 15from textual .containers import Vertical 16from textual .widgets import Input ,Static 17 18from strata_cli import nav 19from strata_cli .client import ClientError ,Endpoint 20from strata_cli .dashboard import MonitorHistory ,render_dashboard 21from strata_cli .detail_dashboard import render_detail_dashboard 22from strata_cli .logs import ActivityContinuity 23from strata_cli .render import VIEWS ,render_view ,request_rows ,safe 24 25 26def choose_glyphs (requested :str ,encoding :str | None ,term :str | None )-> str : 27"""Prefer readable Unicode when the output stream can encode its graph cells.""" 28if requested != "auto" : 29return requested 30from strata_cli import consoleinfo 31if term == "dumb" or not encoding : 32return "ascii" 33if consoleinfo .legacy_console (): 34forced = os .environ .get ("STRATA_GLYPHS" ,"" ).strip ().lower () 35if forced in ("ascii" ,"legacy" ): 36return "ascii" 37if forced == "solid" : 38return "solid" 39# the classic Windows console: the full Unicode look when the window's font could be switched to Cascadia Mono, else solid blocks 40return "unicode" if consoleinfo .classic_style ()["mode" ]== "full" else "solid" 41try : 42"▁█░" .encode (encoding ) 43except (LookupError ,UnicodeEncodeError ): 44return "ascii" 45return "unicode" 46 47 48def with_aggregate_rate (previous :dict ,current :dict )-> dict : 49"""One common interval across all requests; reset on a new server instance.""" 50old_id = (previous .get ("instance" )or {}).get ("id" ) 51new_id = (current .get ("instance" )or {}).get ("id" ) 52old = (previous .get ("rates" )or {}).get ("output_tokens_server_counter" ) 53new = (current .get ("rates" )or {}).get ("output_tokens_server_counter" ) 54old_at ,new_at = previous .get ("sampled_at" ),current .get ("sampled_at" ) 55rates = current .setdefault ("rates" , {}) 56rates ["aggregate_output_tok_s" ]= None 57rates ["aggregate_window_s" ]= None 58if not old_id or old_id != new_id or not all (isinstance (v , (int ,float ))and 59not isinstance (v ,bool )and math .isfinite (v ) 60for v in (old ,new ,old_at ,new_at ))or old < 0 : 61return current 62dt = new_at - old_at 63if 0 < dt <= 30 and new >= old : 64rates ["aggregate_output_tok_s" ]= round ((new - old )/ dt ,1 ) 65rates ["aggregate_window_s" ]= round (dt ,2 ) 66return current 67 68 69def _fresh_rate_sample (snapshot :dict )-> bool : 70sampled = snapshot .get ("sampled_at" ) 71return (isinstance (sampled , (int ,float ))and not isinstance (sampled ,bool )and 72math .isfinite (sampled )and abs (time .time ()- sampled )<= 5 ) 73 74 75class MonitorApp (App ): 76TITLE = "Strata Monitor" 77CSS = """ 78Screen { background: #0e1113; color: #eef1f3; } 79#shell { width: 100%; height: 100%; background: #161a1d; padding: 0 1; } 80#content { width: 100%; height: 1fr; color: #eef1f3; } 81#filter { height: 3; display: none; border: solid #34d399; } 82#message { height: 1; color: #8e979f; } 83""" 84BINDINGS = [ 85Binding (str (i + 1 ),f"view_ { i } " ,f" { name . title () } view" ,show = False ) 86for i ,name in enumerate (VIEWS ) 87 ]+ [ 88Binding ("q" ,"quit" ,"Detach" ),Binding ("ctrl+c" ,"quit" ,"Detach" ,show = False ), 89Binding ("space" ,"freeze" ,"Freeze" ),Binding ("r" ,"refresh" ,"Refresh" ), 90Binding ("tab" ,"cycle_serving_pane" ,"Next pane" ,priority = True ), 91Binding ("shift+tab" ,"previous_serving_pane" ,"Previous pane" ,show = False ,priority = True ), 92Binding ("t" ,"theme_cycle" ,"Theme" ),Binding ("slash" ,"filter_open" ,"Filter" ), 93Binding ("escape" ,"filter_clear" ,"Clear filter" ,show = False ), 94Binding ("down" ,"next_row" ,"Next" ,show = False ), 95Binding ("up" ,"previous_row" ,"Previous" ,show = False ), 96Binding ("pagedown" ,"page_down" ,"Next page" ,show = False ), 97Binding ("pageup" ,"page_up" ,"Previous page" ,show = False ), 98Binding ("home" ,"first_row" ,"First row" ,show = False ), 99Binding ("end" ,"last_row" ,"Last row" ,show = False ), 100Binding ("left" ,"previous_view" ,"Previous view" ,show = False ), 101Binding ("right" ,"next_view" ,"Next view" ,show = False ), 102Binding ("enter" ,"request_detail" ,"Row detail" ,show = False ), 103Binding ("question_mark" ,"help" ,"Help" ),Binding ("f1" ,"help" ,"Help" ,show = False ), 104Binding ("b" ,"browser" ,"Open in browser" ,show = False ), 105Binding ("7" ,"view_6" ,"Connect view" ,show = False ), 106 ] 107 108def __init__ (self ,endpoint :Endpoint ,snapshot :dict | None ,* ,interval :float = 1.0 , 109requests :int = 12 ,theme :str = "auto" ,color :str = "auto" ,glyphs :str = "auto" ): 110super ().__init__ () 111self .endpoint = endpoint 112self .latest = snapshot if snapshot is not None else {"source" :"pending" } 113self .rate_previous = snapshot if snapshot is not None and _fresh_rate_sample (snapshot )else None 114self .displayed = self .latest 115self .has_snapshot = snapshot is not None 116self .displayed_has_snapshot = self .has_snapshot 117self .connection_state = ("telemetry_unavailable" if self .has_snapshot and 118 (self .latest .get ("quality" )or {}).get ("telemetry" )== "unavailable" else 119"connected" if self .has_snapshot else "connecting" ) 120self .metrics_model = None # the Overview's numbers, from /metrics (None: an older server; the earlier Overview is drawn) 121self .connect_enabled = False # launch's monitor adds a Connect view (key 7) 122self .interval = interval 123self .requests = requests 124self .view = 0 125self .serving_pane = "devices" 126self .selected = 0 127self .selected_identity :tuple [str ,str ]| None = None 128self .detail = False 129self .selection_notice :str | None = None 130self .frozen = False 131self .filter_text = "" 132self .polling = False 133self .closing = False 134self .error :str | None = None 135self .help_until = 0.0 # the key list from `?` stays up to HELP_SECONDS (a poll no longer wipes it on any view) 136self .failures = 0 137self .next_poll_at = 0.0 138self .next_age_repaint = 0.0 139self .theme_choice = "terminal" if theme == "auto" else theme 140self .color_choice = "never" if os .environ .get ("NO_COLOR" )is not None else color 141self .glyph_choice = choose_glyphs (glyphs ,sys .stdout .encoding ,os .environ .get ("TERM" )) 142from strata_cli import consoleinfo 143self .classic = consoleinfo .classic_style ()if consoleinfo .legacy_console ()else None 144self .margin = 3 if self .classic else 2 # one more column of room in the classic Windows console (its scroll bar) 145self .history = MonitorHistory () 146self .activity_continuity = ActivityContinuity () 147self .displayed_activity_continuity = self .activity_continuity .status () 148if snapshot is not None : 149self .history .add (snapshot ,self ._instance_key (snapshot )) 150self .activity_continuity .add (snapshot ) 151self .displayed_activity_continuity = self .activity_continuity .status () 152 153def compose (self )-> ComposeResult : 154with Vertical (id = "shell" ): 155yield Static ("" ,id = "content" ,markup = False ) 156yield Input (placeholder = "Filter by request id, state, live or done, then Enter" ,max_length = 80 ,id = "filter" ) 157yield Static ("Read only | q detaches without stopping Strata" ,id = "message" ,markup = False ) 158 159def on_mount (self )-> None : 160self ._apply_theme () 161self ._paint () 162self .query_one ("#filter" ,Input ).disabled = True 163self .set_focus (None ) 164self .set_interval (self .interval ,self ._schedule_poll ) 165if not self .has_snapshot : 166self ._schedule_poll (force = True ) 167 168def _apply_theme (self )-> None : 169bg ,panel ,fg ,mute = { 170"dark" : ("#0e1113" ,"#161a1d" ,"#eef1f3" ,"#8e979f" ), 171"light" : ("#f9fafb" ,"#ffffff" ,"#221e1f" ,"#6f6f6f" ), 172"terminal" : ("transparent" ,"transparent" ,"ansi_default" ,"ansi_default" ), 173 }[self .theme_choice ] 174if self .color_choice == "never" : 175bg ,panel ,fg ,mute = "transparent" ,"transparent" ,"ansi_default" ,"ansi_default" 176self .set_class (self .theme_choice == "light" and self .color_choice != "never" ,"theme-light" )# pop-ups and the Connect view follow it 177self .screen .styles .background = bg 178self .query_one ("#shell" ).styles .background = panel 179self .query_one ("#content" ).styles .color = fg 180self .query_one ("#message" ).styles .color = mute 181 182@property 183def text_glyphs (self )-> str : 184"""The glyph set of the text views (2-6): the Overview's solid look is not theirs, they keep the plain ASCII fallback.""" 185return "ascii" if self .glyph_choice == "solid" else self .glyph_choice 186 187def _view_count (self )-> int : 188"""Six views, and a seventh (Connect) when `strata launch` opened the monitor: arrows, number keys and the tab line all use this.""" 189return nav .count (self .connect_enabled ) 190 191def _paint (self ,size = None )-> None : 192size = self .screen .size if size is None else size 193if self .view >= len (VIEWS ):# the Connect view belongs to the launch-aware monitor (strata_cli/launch/monitor_ext.py) 194return 195help_lines = self ._help_wrapped (size .width )if self ._help_open ()else [] 196extra = max (0 ,len (help_lines )- 1 )# the key list wraps over more lines than the one-line message row 197snapshot = {** self .displayed ,"recent" : (self .displayed .get ("recent" )or [])[:self .requests ]} 198snapshot ["activity_continuity" ]= self .displayed_activity_continuity 199snapshot ["work" ]= {** (self .displayed .get ("work" )or {}), 200"requests" : ((self .displayed .get ("work" )or {}).get ("requests" )or [])[:self .requests ]} 201if self .view == 0 and size .width >= 78 and size .height >= 23 and self .metrics_model is not None and self .connection_state in ("connected" ,"stale" ,"telemetry_unavailable" ): 202from strata_cli import overview 203display = overview .render ( 204self .metrics_model ,width = max (30 ,min (size .width - self .margin ,100 if self .margin > 2 else 1000 )),height = max (8 ,size .height - 2 - extra ), 205connection = getattr (self .endpoint ,"base_url" ,getattr (self .endpoint ,"root" ,"" )), 206connection_state = self .connection_state ,frozen = self .frozen ,glyphs = self .glyph_choice , 207color = self .color_choice != "never" ,theme = self .theme_choice ,connect = self .connect_enabled , 208bullet = (self .classic or {}).get ("bullet" ,"●" )) 209elif self .view == 0 and size .width >= 78 and size .height >= 23 : 210display = render_dashboard ( 211snapshot ,width = max (30 ,size .width - self .margin ),height = max (8 ,size .height - 2 - extra ), 212history = self .history ,connection = getattr (self .endpoint ,"base_url" ,getattr (self .endpoint ,"root" ,"" )), 213connection_state = self .connection_state ,frozen = self .frozen , 214filter_text = self .filter_text ,glyphs = self .text_glyphs , 215color = self .color_choice != "never" ,theme = self .theme_choice ,connect = self .connect_enabled ) 216elif self .view != 0 and size .width >= 128 and size .height >= 36 and self .connection_state not in ( 217"connecting" ,"disconnected" ,"auth_required" ,"incompatible" ): 218display = render_detail_dashboard ( 219snapshot ,VIEWS [self .view ],width = max (30 ,size .width - self .margin ), 220height = max (8 ,size .height - 2 - extra ),history = self .history , 221connection = getattr (self .endpoint ,"base_url" ,getattr (self .endpoint ,"root" ,"" )), 222connection_state = self .connection_state ,frozen = self .frozen , 223filter_text = self .filter_text ,glyphs = self .text_glyphs , 224color = self .color_choice != "never" ,theme = self .theme_choice , 225selected = self .selected ,detail = self .detail ,serving_pane = self .serving_pane ,connect = self .connect_enabled ) 226else : 227content = render_view (snapshot ,VIEWS [self .view ], 228width = max (30 ,size .width - self .margin ),height = max (8 ,size .height - 2 - extra ), 229selected = self .selected ,frozen = self .frozen , 230filter_text = self .filter_text ,glyphs = self .text_glyphs , 231connection = getattr (self .endpoint ,"base_url" ,getattr (self .endpoint ,"root" ,"" )), 232serving_pane = self .serving_pane , 233detail = self .detail ,connection_state = self .connection_state ,connect = self .connect_enabled ) 234display = Text (content ,no_wrap = True ,overflow = "crop" ) 235if self .color_choice != "never" : 236accent = "#0c8a60" if self .theme_choice == "light" else "#34d399" 237muted = "#6f6f6f" if self .theme_choice == "light" else "#8e979f" 238offset = 0 239for line in content .splitlines (keepends = True ): 240stripped = line .strip () 241if stripped .startswith ("STRATA" )or stripped .startswith (("REQUEST FLOW" ,"GPU SENSORS" ,"Hardware" ,"Recent requests" ,"Slots / groups" ,"Occupied slots by group" )): 242display .stylize (f"bold { accent } " ,offset ,offset + len (line .rstrip ("\n" ))) 243elif stripped .startswith (("---" ,"Sample age" ,"1-6 views" ,"1-7 views" ,"Read only" )): 244display .stylize (muted ,offset ,offset + len (line .rstrip ("\n" ))) 245offset += len (line ) 246display .highlight_regex (r"\[LIVE\]|\[\d [^\]]+\]" ,f"bold { accent } " ) 247display .highlight_regex (r"\[(?:STALE|FROZEN(?:/[^\]]+)?|CONNECTING)\]" ,"bold yellow" ) 248display .highlight_regex (r"\[(?:AUTH REQUIRED|INCOMPATIBLE|DISCONNECTED|NO TELEMETRY)\]" ,"bold red" ) 249display .highlight_regex (r"GPU \d+" ,f"bold { accent } " ) 250self .query_one ("#content" ,Static ).update (display ) 251idle_message = ("Read only | q keeps server on" if size .width < 60 else 252"Read only | q detaches without stopping Strata" ) 253if self .classic and self .classic .get ("tip" ):# the classic Windows console: one line about the full look 254idle_message = ("Read only | q detaches | " if size .width >= 100 else "" )+ self .classic ["tip" ] 255note = getattr (self ,"quiet_note" ,None )# one quiet line (an engine update is available), only where the screen has room for it 256if note and self .connection_state in ("connected" ,"stale" ,"telemetry_unavailable" )and not self .frozen : 257idle_message = note if size .width < 100 else f" { note } | q detaches without stopping Strata" 258msg = ("\n" .join (help_lines )if help_lines else None )or self .error or self .selection_notice or ("Connecting to Strata" if self .connection_state == "connecting" else 259"Telemetry unavailable; status only" if self .connection_state == "telemetry_unavailable" else 260"Frozen display; collection continues" if self .frozen else 261idle_message ) 262self .query_one ("#message" ,Static ).styles .height = max (1 ,len (help_lines )) 263self .query_one ("#message" ,Static ).update (msg ) 264 265def _schedule_poll (self ,force :bool = False )-> None : 266now = time .monotonic () 267if not self .closing and not self .polling and (force or now >= self .next_poll_at ): 268self .polling = True # claim the cycle before create_task can be called again 269asyncio .create_task (self ._poll ()) 270elif not self .closing and self .is_mounted and self .connection_state != "connected" and now >= self .next_age_repaint : 271self .next_age_repaint = now + 1.0 272self ._paint () 273 274async def _poll (self )-> None : 275try : 276fresh = with_aggregate_rate (self .rate_previous or {}, 277await asyncio .to_thread (self .endpoint .snapshot )) 278self .latest = fresh 279await self ._poll_metrics () 280self .rate_previous = fresh if _fresh_rate_sample (fresh )else None 281self .activity_continuity .add (fresh ) 282if not self .frozen : 283self ._show_snapshot (fresh ) 284self .has_snapshot = True 285self .connection_state = ("telemetry_unavailable" if 286 (fresh .get ("quality" )or {}).get ("telemetry" )== "unavailable" else 287"connected" ) 288self .error = None 289self .failures = 0 290self .next_poll_at = 0.0 291except ClientError as e : 292self .rate_previous = None 293if not self .frozen : 294self .history .gap () 295self .error = str (e ) 296self .failures += 1 297self .connection_state = ("auth_required" if e .exit_code == 4 else 298"incompatible" if e .exit_code == 5 else 299"stale" if self .has_snapshot and self .failures < 3 else "disconnected" ) 300self .next_poll_at = (float ("inf" )if e .exit_code in (4 ,5 )else 301time .monotonic ()+ min (30.0 ,2.0 ** min (self .failures ,5 )* 302random .uniform (0.8 ,1.2 ))) 303except Exception : 304self .rate_previous = None 305if not self .frozen : 306self .history .gap () 307self .error = "Telemetry collection failed" 308self .failures += 1 309self .connection_state = "stale" if self .has_snapshot and self .failures < 3 else "disconnected" 310self .next_poll_at = (time .monotonic ()+ min (30.0 ,2.0 ** min (self .failures ,5 )* 311random .uniform (0.8 ,1.2 ))) 312finally : 313self .polling = False 314if not self .closing and self .is_mounted : 315self ._paint () 316 317async def _poll_metrics (self )-> None : 318"""The browser Monitor's own data (/metrics: live state, engine facts, hardware with a minute of history, last requests).""" 319getter = getattr (self .endpoint ,"get" ,None ) 320if getter is None : 321self .metrics_model = None 322return 323try : 324from strata_cli import overview 325self .metrics_model = overview .build (await asyncio .to_thread (getter ,"/metrics" )) 326except Exception :# noqa: BLE001 - an older server has no /metrics: keep the earlier Overview 327self .metrics_model = None 328 329def action_browser (self )-> None : 330import webbrowser 331url = getattr (self .endpoint ,"base_url" ,None )or getattr (self .endpoint ,"root" ,"" ) 332try : 333opened = webbrowser .open (url )if url else False 334except Exception :# noqa: BLE001 335opened = False 336self .error = f"Opened { url } in your browser" if opened else f"Open { url } in a browser (none could be started here)" 337self ._paint () 338 339def on_resize (self ,event )-> None : 340self ._paint (event .size ) 341 342def action_quit (self )-> None : 343self .closing = True 344self .exit () 345 346def action_freeze (self )-> None : 347self .frozen = not self .frozen 348if not self .frozen : 349self ._show_snapshot (self .latest ) 350self ._paint () 351 352@staticmethod 353def _instance_key (snapshot :dict )-> tuple [str ,str ]| None : 354instance = snapshot .get ("instance" )or {} 355identity = instance .get ("id" ) 356if isinstance (identity ,str )and identity : 357return ("id" ,identity ) 358boot = instance .get ("boot_time" ) 359if isinstance (boot , (int ,float ))and not isinstance (boot ,bool ): 360return ("boot" ,str (boot )) 361return None 362 363def _show_snapshot (self ,fresh :dict )-> None : 364self .activity_continuity .add (fresh ) 365self .displayed_activity_continuity = self .activity_continuity .status () 366prior = self ._instance_key (self .displayed ) 367current = self ._instance_key (fresh ) 368self .displayed = fresh 369self .history .add (fresh ,current ) 370was_displayed = self .displayed_has_snapshot 371self .displayed_has_snapshot = True 372if was_displayed and prior != current and (prior is not None or current is not None ): 373self .selected = 0 374self .selected_identity = None 375self .detail = False 376self .selection_notice = "Server instance changed; selection cleared" 377else : 378self ._restore_selection () 379 380def action_refresh (self )-> None : 381self ._schedule_poll (force = True ) 382 383def action_cycle_serving_pane (self )-> None : 384if self .view == 1 : 385panes = ("devices" ,"requests" ,"groups" ) 386self .serving_pane = panes [(panes .index (self .serving_pane )+ 1 )% len (panes )] 387self .selected = 0 388self .selected_identity = None 389self .detail = False 390self .selection_notice = None 391self ._paint () 392 393def action_previous_serving_pane (self )-> None : 394if self .view == 1 : 395panes = ("devices" ,"requests" ,"groups" ) 396self .serving_pane = panes [(panes .index (self .serving_pane )- 1 )% len (panes )] 397self .selected = 0 398self .selected_identity = None 399self .detail = False 400self .selection_notice = None 401self ._paint () 402 403def action_theme_cycle (self )-> None : 404choices = ("terminal" ,"dark" ,"light" ) 405self .theme_choice = choices [(choices .index (self .theme_choice )+ 1 )% len (choices )] 406self ._apply_theme () 407self ._paint () 408 409def action_filter_open (self )-> None : 410field = self .query_one ("#filter" ,Input ) 411field .disabled = False 412field .styles .display = "block" 413field .value = self .filter_text 414field .focus () 415 416def on_input_changed (self ,event :Input .Changed )-> None : 417cleaned = safe (event .value ,80 ) 418if event .value != cleaned : 419event .input .value = cleaned 420 421def on_input_submitted (self ,event :Input .Submitted )-> None : 422self .filter_text = safe (event .value ,80 ) 423event .input .styles .display = "none" 424event .input .disabled = True 425self .set_focus (None ) 426self .selected = 0 427self .selected_identity = None 428self .detail = False 429self .selection_notice = None 430self ._paint () 431 432def action_filter_clear (self )-> None : 433self .help_until = 0.0 434self .filter_text = "" 435self .selected = 0 436self .selected_identity = None 437self .detail = False 438self .selection_notice = None 439field = self .query_one ("#filter" ,Input ) 440field .styles .display = "none" 441field .disabled = True 442self .set_focus (None ) 443self ._paint () 444 445def action_next_row (self )-> None : 446self ._move_row (1 ) 447 448def action_previous_row (self )-> None : 449self ._move_row (- 1 ) 450 451def action_page_down (self )-> None : 452self ._move_row (max (1 ,self .screen .size .height - 12 )) 453 454def action_page_up (self )-> None : 455self ._move_row (- max (1 ,self .screen .size .height - 12 )) 456 457def action_first_row (self )-> None : 458self ._move_row (- self .selected ) 459 460def action_last_row (self )-> None : 461self ._move_row (len (self ._selectable_rows ())) 462 463def action_previous_view (self )-> None : 464self ._set_view ((self .view - 1 )% self ._view_count ()) 465 466def action_next_view (self )-> None : 467self ._set_view ((self .view + 1 )% self ._view_count ()) 468 469def _move_row (self ,amount :int )-> None : 470rows = self ._selectable_rows () 471if rows : 472self .selected = min (max (0 ,self .selected + amount ),len (rows )- 1 ) 473self ._remember_selection () 474self ._paint () 475 476HELP_SECONDS = 15.0 477 478def _help_open (self )-> bool : 479return time .monotonic ()< self .help_until 480 481def _help_line (self )-> str : 482return f" { nav . keys ( self . connect_enabled ) } /Left/Right views Tab pane Up/Down/PgUp/PgDn/Home/End rows Enter detail Space freeze r refresh t theme q detach" 483 484def _help_wrapped (self ,width :int )-> list [str ]: 485"""The key list cut at the separators between keys (two spaces), never inside a key, into lines that fit `width` (less the shell's padding).""" 486room = max (20 ,width - 2 ) 487lines :list [str ]= [] 488for item in self ._help_line ().split (" " ): 489if lines and len (lines [- 1 ])+ 2 + len (item )<= room : 490lines [- 1 ]+= " " + item 491else : 492lines .append (item ) 493return lines 494 495def action_help (self )-> None : 496"""`?`: the key list on the message line, on every view. The next poll (every second) used to wipe it, so it flashed by on the Overview; 497now it stays until `?` again, Esc, another view or HELP_SECONDS.""" 498self .help_until = 0.0 if self ._help_open ()else time .monotonic ()+ self .HELP_SECONDS 499self ._paint () 500 501def action_request_detail (self )-> None : 502if self ._selected_entry ()is not None : 503self .detail = not self .detail 504self ._remember_selection () 505self ._paint () 506 507def _selectable_rows (self )-> list [tuple [str ,dict ]]: 508live ,recent = request_rows (self .displayed ,self .filter_text ,limit = self .requests ) 509if self .view == 1 : 510if self .serving_pane == "requests" : 511return [("live" ,row )for row in live ] 512if self .serving_pane == "groups" : 513return [("slot" ,row )for row in (self .displayed .get ("work" )or {}).get ("slots" )or []] 514return [("device" ,row )for row in self .displayed .get ("devices" )or []] 515if self .view == 2 : 516return [("live" ,row )for row in live ]+ [("recent" ,row )for row in recent ] 517if self .view == 4 : 518return [("device" ,row )for row in self .displayed .get ("devices" )or []] 519return [] 520 521def _selected_entry (self )-> tuple [str ,dict ]| None : 522rows = self ._selectable_rows () 523return rows [self .selected ]if 0 <= self .selected < len (rows )else None 524 525@staticmethod 526def _identity (kind :str ,row :dict )-> tuple [str ,str ]| None : 527key = "index" if kind == "device" else "slot" if kind == "slot" else "id" 528value = row .get (key ) 529if kind in ("device" ,"slot" ): 530return (kind ,str (value ))if isinstance (value ,int )and not isinstance (value ,bool )and value >= 0 else None 531return (kind ,value )if isinstance (value ,str )and value else None 532 533def _remember_selection (self )-> None : 534selected = self ._selected_entry () 535self .selected_identity = self ._identity (* selected )if selected is not None else None 536self .selection_notice = None 537 538def _restore_selection (self )-> None : 539rows = self ._selectable_rows () 540if self .selected_identity is None : 541if self .detail : 542self .detail = False 543self .selected = min (self .selected ,max (0 ,len (rows )- 1 )) 544return 545matches = [i for i , (kind ,row )in enumerate (rows ) 546if self ._identity (kind ,row )== self .selected_identity ] 547if not matches and self .view == 2 and self .selected_identity [0 ]in ("live" ,"recent" ): 548# A live request can finish between polls. Follow its unique ID into recent history. 549matches = [i for i , (_ ,row )in enumerate (rows ) 550if row .get ("id" )== self .selected_identity [1 ]] 551if len (matches )== 1 : 552self .selected = matches [0 ] 553self .selected_identity = self ._identity (* rows [self .selected ]) 554self .selection_notice = None 555else : 556self .selected_identity = None 557self .detail = False 558self .selection_notice = "No longer retained; select another row" 559self .selected = min (self .selected ,max (0 ,len (rows )- 1 )) 560 561def _set_view (self ,index :int )-> None : 562self .view = index 563self .selected = 0 564self .selected_identity = None 565self .detail = False 566self .selection_notice = None 567self .help_until = 0.0 568self ._paint () 569 570def action_view_0 (self )-> None : 571self ._set_view (0 ) 572 573def action_view_1 (self )-> None : 574self ._set_view (1 ) 575 576def action_view_2 (self )-> None : 577self ._set_view (2 ) 578 579def action_view_3 (self )-> None : 580self ._set_view (3 ) 581 582def action_view_4 (self )-> None : 583self ._set_view (4 ) 584 585def action_view_5 (self )-> None : 586self ._set_view (5 ) 587 588def action_view_6 (self )-> None : 589if self .connect_enabled : 590self ._set_view (6 )