okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
568127b7a
main
1"""The monitor's Overview (view 1): the browser Monitor's page redone for the terminal. 2 3A model-state bar, eight tiles with sparklines (speed, GPU load, VRAM, GPU temperature, power, PCIe, CPU, disk), bars for context fill, 4experts in VRAM and system RAM, and the recent requests. It reads what the browser Monitor reads: the server's `/metrics` 5(live state, engine facts, the hardware sample and a minute of history per series, the last requests) as the app's 6apps/host/src/lib/native-monitor.ts maps it: the context used is the current request's prompt + generated tokens while one runs, else the 7last request's; the speed is the live rate while generating, else the last request's. 8 9`build(metrics)` turns the raw metrics into plain numbers (None where the server did not report one: never a made-up zero); 10`render(...)` draws them. Neither needs Textual. 11""" 12 13from __future__import annotations 14 15import time 16from typing import Any 17 18from rich import box 19from rich .console import Group 20from rich .panel import Panel 21from rich .table import Table 22from rich .text import Text 23 24from strata_cli import nav 25 26GIB = 2 ** 30 27BLUE = "#5aa9ff" 28AMBER = "#f5c56b" 29RED = "#f28b82" 30ACCENT = "#34d399" 31GREY = "#59636b" 32STATES = ("Idle" ,"Reading" ,"Generating" ,"Queued" ,"Error" ) 33# the classic Windows console draws with its 16 palette colours; these are the names that map onto them (glyphs="solid") 34SOLID_ACCENT ,SOLID_BLUE ,SOLID_AMBER ,SOLID_RED ,SOLID_TRACK = "bright_green" ,"bright_blue" ,"yellow" ,"red" ,"bright_black" 35 36 37def _num (v :Any )-> float | None : 38if isinstance (v ,bool )or not isinstance (v , (int ,float )): 39return None 40if v != v or v in (float ("inf" ),float ("-inf" )): 41return None 42return float (v ) 43 44 45def _gib (v :Any )-> float | None : 46n = _num (v ) 47return None if n is None else n / GIB 48 49 50def _series (history :dict ,key :str ,scale :float = 1.0 )-> list [float | None ]: 51raw = history .get (key )if isinstance (history ,dict )else None 52if not isinstance (raw ,list ): 53return [] 54return [(None if _num (x )is None else _num (x )/ scale )for x in raw [- 60 :]] 55 56 57def request_speed (r :dict )-> float | None : 58out ,ms = _num (r .get ("output_tokens" )),_num (r .get ("decode_ms" )) 59if r .get ("decode_tok_s" )is not None and _num (r .get ("decode_tok_s" ))is not None : 60return _num (r .get ("decode_tok_s" )) 61return round (out / (ms / 1000.0 ),1 )if out and out >= 2 and ms and ms > 0 else None # one token has no decode span (a probe showed 1,250 tok/s) 62 63 64def run_average_speed (metrics :dict )-> float | None : 65"""The run's average decode speed: every token the server produced over the whole run divided by the run's 66decode time (the server's `totals`, the same token-weighted figure the engine's DONE lines and Prometheus use). 67Not the last request's speed - a single request is noisy; this is the average over everything since the start. 68None when the server reported no totals (never an invented zero).""" 69totals = metrics .get ("totals" )or {} 70out ,ms = _num (totals .get ("output_tokens" )),_num (totals .get ("decode_ms" )) 71return round (out / (ms / 1000.0 ),1 )if out and out >= 2 and ms and ms > 0 else None 72 73 74def _cards (hw :dict ,static :dict )-> list [dict ]: 75"""Each graphics card's own readings when the server lists two or more (hardware.gpus); [] for one card or none: the Overview then 76draws exactly what it always drew.""" 77raw = hw .get ("gpus" )if isinstance (hw .get ("gpus" ),list )else [] 78cards = [{"index" :c .get ("index" ),"name" :c .get ("name" ),"util" :_num (c .get ("util" )),"mem_used" :_gib (c .get ("mem_used" )), 79"mem_total" :_gib (c .get ("mem_total" )),"temp" :_num (c .get ("temp" )),"power" :_num (c .get ("power" )), 80"power_limit" :_num (c .get ("power_limit" ))}for c in raw [:16 ]if isinstance (c ,dict )] 81return cards if len (cards )>= 2 else [] 82 83 84def _total (values :list )-> float | None : 85present = [v for v in values if v is not None ] 86return sum (present )if present else None 87 88 89def _most (values :list )-> float | None : 90present = [v for v in values if v is not None ] 91return max (present )if present else None 92 93 94def build (metrics :dict | None )-> dict | None : 95"""The numbers the Overview draws, or None when the server does not serve /metrics (an old server: the caller falls back).""" 96if not isinstance (metrics ,dict )or not isinstance (metrics .get ("live" ),dict ): 97return None 98live ,engine = metrics ["live" ],metrics .get ("engine" )if isinstance (metrics .get ("engine" ),dict )else {} 99hw = metrics .get ("hardware" )if isinstance (metrics .get ("hardware" ),dict )else {} 100static = metrics .get ("hardware_static" )if isinstance (metrics .get ("hardware_static" ),dict )else {} 101history = metrics .get ("history" )if isinstance (metrics .get ("history" ),dict )else {} 102recent = [r for r in (metrics .get ("requests" )or [])if isinstance (r ,dict )] 103state_raw = str (live .get ("state" )or "idle" ) 104queued = _num (live .get ("queued" ))or 0 105err = bool (engine .get ("error" ))or state_raw == "error" 106if err : 107state = "Error" 108elif state_raw == "reading" : 109state = "Reading" 110elif state_raw == "generating" : 111state = "Generating" 112elif queued > 0 and state_raw not in ("reading" ,"generating" ): 113state = "Queued" 114else : 115state = "Idle" 116active = state in ("Reading" ,"Generating" ) 117prompt_read ,prompt_total = _num (live .get ("prompt_read" )),_num (live .get ("prompt_total" )) 118generated ,max_tokens = _num (live .get ("generated" )),_num (live .get ("max_tokens" )) 119if state == "Reading" and prompt_total : 120done ,total = prompt_read or 0.0 ,prompt_total 121elif state == "Generating" and max_tokens : 122done ,total = generated or 0.0 ,max_tokens 123else : 124done ,total = None ,None 125last = recent [0 ]if recent else None 126max_ctx = _num (engine .get ("max_context" )) 127if active and _num (live .get ("prompt_tokens" ))is not None and generated is not None : 128used = _num (live .get ("prompt_tokens" ))+ generated 129elif last and _num (last .get ("prompt_tokens" ))is not None and _num (last .get ("output_tokens" ))is not None : 130used = _num (last ["prompt_tokens" ])+ _num (last ["output_tokens" ]) 131else : 132used = None 133if state == "Generating" and _num (live .get ("tok_s" ))is not None : 134speed ,speed_note = _num (live .get ("tok_s" )),"now" 135elif state == "Reading" and _num (live .get ("prefill_tok_s_mean" ))is not None : 136speed ,speed_note = _num (live .get ("prefill_tok_s_mean" )),"reading the prompt" 137else : 138# Idle: not the last request's speed (one request is noisy) but the run's average, from the server's totals. 139speed ,speed_note = run_average_speed (metrics ),"average of the run" 140if speed is None : 141speed ,speed_note = (request_speed (last )if last else None ),"last request" 142slots ,total_slots = _num (engine .get ("expert_slots" )),_num (engine .get ("experts" )) 143cache_mib = _num (engine .get ("expert_cache_mib" )) 144gen ,genmax ,width = _num (hw .get ("gpu_pcie_gen" )),_num (hw .get ("gpu_pcie_gen_max" )),_num (hw .get ("gpu_pcie_width" )) 145model = { 146"model" :engine .get ("model" ),"max_context" :max_ctx ,"state" :state ,"state_raw" :state_raw ,"queued" :int (queued ), 147"progress" : (done ,total ),"phase_text" : {"Idle" :"Waiting for a request" ,"Reading" :"Reading prompt" ,"Generating" :"Generating a reply" , 148"Queued" :"Requests are queued" ,"Error" :"Model unavailable" }[state ], 149"context" : (used ,max_ctx ), 150"speed" : (speed ,speed_note ,_series (history ,"tok_s" )if speed_note == "now" or not _series (history ,"prefill_tok_s_mean" )else 151_series (history ,"tok_s" )), 152"gpu" : {"cards" :_cards (hw ,static ), 153"name" :static .get ("gpu_name" ),"util" :_num (hw .get ("gpu_util" )),"util_hist" :_series (history ,"gpu_util" ), 154"vram_used" :_gib (hw .get ("gpu_mem_used" )),"vram_total" :_gib (hw .get ("gpu_mem_total" ))or 155 (_num (static .get ("gpu_vram_total_mib" ))/ 1024.0 if _num (static .get ("gpu_vram_total_mib" ))else None ), 156"vram_hist" :_series (history ,"gpu_mem_used" ,GIB ),"temp" :_num (hw .get ("gpu_temp" )),"temp_hist" :_series (history ,"gpu_temp" ), 157"power" :_num (hw .get ("gpu_power" )),"power_limit" :_num (hw .get ("gpu_power_limit" )),"power_hist" :_series (history ,"gpu_power" ), 158"pcie_rx" :_num (hw .get ("gpu_pcie_rx_mb" )),"pcie_hist" :_series (history ,"gpu_pcie_rx_mb" ), 159"pcie_gen" :gen if gen is not None else genmax ,"pcie_width" :width ,"count" :_num (static .get ("gpu_count" ))}, 160"cpu" : {"load" :_num (hw .get ("cpu_pct" )if hw .get ("cpu_pct" )is not None else hw .get ("cpu" )),"hist" :_series (history ,"cpu" ), 161"cores" :_num (static .get ("cores" )),"threads" :_num (static .get ("threads" )),"sockets" :_num (static .get ("sockets" )), 162"numa" :_num (static .get ("numa_nodes" ))}, 163"disk" : {"read" :_num (hw .get ("disk_read_mb" )),"write" :_num (hw .get ("disk_write_mb" )),"hist" :_series (history ,"disk_read_mb" )}, 164"ram" : (_gib (hw .get ("ram_used" )),_gib (hw .get ("ram_total" ))), 165"experts" : {"slots" :slots ,"total" :total_slots ,"gb" : (cache_mib / 1024.0 if cache_mib is not None else None )}, 166"recent" : [{"time" :_num (r .get ("time" )),"state" : ("Error" if r .get ("error" )else 167 {"stop" :"Done" ,"length" :"Done" ,"tool_calls" :"Done" }.get (r .get ("finish_reason" )or r .get ("finish" ),"Done" ) 168if (r .get ("finish_reason" )or r .get ("finish" ))not in ("cancelled" ,"error" ,"abort" )else "Stopped" ), 169"prompt" :_num (r .get ("prompt_tokens" )),"reused" :_num (r .get ("reused" )),"output" :_num (r .get ("output_tokens" )), 170"tps" :request_speed (r ),"duration" :_num (r .get ("duration_s" ))}for r in recent [:6 ]], 171"sampled_at" :_num (metrics .get ("time" )), 172 } 173cards = model ["gpu" ]["cards" ] 174if cards :# two or more cards: the tiles say it for the whole computer, the Cards strip says it per card 175g = model ["gpu" ] 176g ["util" ]= _most ([c ["util" ]for c in cards ])# the busiest card 177g ["vram_used" ]= _total ([c ["mem_used" ]for c in cards ])# all cards together 178g ["vram_total" ]= _total ([c ["mem_total" ]for c in cards ]) 179g ["vram_hist" ]= [g ["vram_used" ]]* 60 if g ["vram_used" ]is not None else []# the server keeps a history of card 0 only: a flat line, not a wrong one 180g ["temp" ]= _most ([c ["temp" ]for c in cards ])# the hottest card 181g ["power" ]= _total ([c ["power" ]for c in cards ]) 182g ["power_limit" ]= _total ([c ["power_limit" ]for c in cards ]) 183g ["count" ]= float (len (cards )) 184return model 185 186 187# ------------------------------------------------------------------------------------------------ drawing 188 189def solid_spark (values :list ,width :int ,lo :float | None ,hi :float | None )-> Text : 190"""The classic console's sparkline (glyphs="solid"): only solid blocks, no dithered shades (ClearType fringes those with colour): 191a thin dim ▄ for the lowest quarter, ▄ for the middle, █ for the top.""" 192vals = values [- width :] 193present = [v for v in vals if v is not None ] 194if not present : 195return Text (" " * width ) 196out = Text (" " * (width - len (vals ))) 197low = min (present )if lo is None else lo 198high = max (present )if hi is None else hi 199if high - low < 1e-9 : 200high = low + 1.0 201for v in vals : 202if v is None : 203out .append (" " ) 204continue 205f = (v - low )/ (high - low ) 206if f < 0.25 : 207out .append ("▄" ,style = SOLID_TRACK ) 208elif f < 0.6 : 209out .append ("▄" ) 210else : 211out .append ("█" ) 212return out 213 214 215def spark (values :list [float | None ],width :int ,glyphs :str ,lo :float | None = None ,hi :float | None = None )-> str | Text : 216"""One row of block characters for the last `width` samples; blanks where a sample is missing; ASCII ramp when `glyphs` is ascii, 217solid blocks (a Text) in the classic console's solid look.""" 218if glyphs == "solid" : 219return solid_spark (values ,width ,lo ,hi ) 220ramp = ".:-=+*#@" if glyphs == "ascii" else "▁▂▃▄▅▆▇█" 221vals = values [- width :] 222present = [v for v in vals if v is not None ] 223if not present : 224return " " * width 225low = min (present )if lo is None else lo 226high = max (present )if hi is None else hi 227if high - low < 1e-9 : 228high = low + 1.0 229cells = [] 230for v in vals : 231if v is None : 232cells .append (" " ) 233else : 234cells .append (ramp [min (7 ,max (0 ,int ((v - low )/ (high - low )* 7.999 )))]) 235return " " * (width - len (cells ))+ "" .join (cells ) 236 237 238def bar (frac :float | None ,width :int ,glyphs :str ,color :str ,empty :str = GREY )-> Text : 239t = Text (no_wrap = True ) 240if glyphs == "solid" :# solid █ and a thin ▄ track: no dithered shades in the classic console 241n = 0 if frac is None else int (round (max (0.0 ,min (1.0 ,frac ))* width )) 242t .append ("█" * n ,style = color ) 243t .append ("▄" * (width - n ),style = SOLID_TRACK ) 244return t 245full ,hollow = ("#" ,"." )if glyphs == "ascii" else ("█" ,"░" ) 246if frac is None : 247t .append (hollow * width ,style = GREY ) 248return t 249n = int (round (max (0.0 ,min (1.0 ,frac ))* width )) 250t .append (full * n ,style = color ) 251t .append (hollow * (width - n ),style = empty ) 252return t 253 254 255def short_gpu (name :str | None )-> str : 256"""The card's name without the maker prefixes that eat a tile's width ("NVIDIA GeForce RTX 5070" -> "RTX 5070").""" 257if not name : 258return "graphics card" 259for prefix in ("NVIDIA GeForce " ,"NVIDIA " ,"AMD Radeon " ,"AMD " ,"Intel(R) " ,"Intel " ): 260if name .startswith (prefix ): 261name = name [len (prefix ):] 262return name 263 264 265def fmt (v :float | None ,digits :int = 0 ,unit :str = "" )-> str : 266if v is None : 267return "--" 268return f" { v :,.{ digits }f } { unit } " 269 270 271def tokens (v :float | None )-> str : 272return "--" if v is None else f" { v :,.0f } " 273 274 275def k (v :float | None )-> str : 276if v is None : 277return "--" 278return f" { v / 1024 :.0f } K" if v >= 1024 else f" { v :.0f } " 279 280 281def _tile (title :str ,big :str ,sub :str ,series :str ,width :int ,* ,accent :str ,box_style ,big_style :str = "bold" )-> Panel : 282body = Text (no_wrap = True ,overflow = "crop" ) 283body .append (big + "\n" ,style = big_style ) 284body .append (sub + "\n" ,style = "dim" ) 285if isinstance (series ,Text ):# the solid look's sparkline carries its own styles 286styled = Text (style = accent ) 287styled .append_text (series ) 288body .append_text (styled ) 289else : 290body .append (series ,style = accent ) 291return Panel (body ,title = Text (title ,style = "dim" ),title_align = "left" ,box = box_style ,padding = (0 ,1 ),width = width , 292border_style = "dim" ) 293 294 295def _cards_strip (cards :list [dict ],glyphs :str ,accent :str ,ascii_mode :bool )-> Text : 296"""One line per card (up to 4): a small load bar, load %, memory, temperature and power; "+ N more cards" beyond that.""" 297t = Text (no_wrap = True ,overflow = "crop" ) 298t .append ("Cards" + chr (10 ),style = f"bold { accent } " ) 299shown = cards [:4 ] 300names = [short_gpu (c .get ("name" ))for c in shown ] 301pad = min (16 ,max (len (n )for n in names )) 302for c ,name in zip (shown ,names ): 303util = c ["util" ] 304used ,total = c ["mem_used" ],c ["mem_total" ] 305t .append (f"GPU { c [ 'index' ] if c [ 'index' ] is not None else '?' } { name [: pad ]:<{ pad } } " ) 306t .append_text (bar ((util / 100.0 )if util is not None else None ,10 ,glyphs ,accent )) 307mem = f" { fmt ( used , 1 ) } / { fmt ( total , 0 ) } GB" if used is not None and total is not None else "-- GB" 308temp = f" { fmt ( c [ 'temp' ]) } { 'C' if ascii_mode else '°C' } " 309t .append (f" { fmt ( util ):>3 } % { mem :<14 } { temp :>6 } { fmt ( c [ 'power' ]):>4 } W" + chr (10 )) 310if len (cards )> 4 : 311t .append (f"+ { len ( cards ) - 4 } more cards: press 5" + chr (10 ),style = "dim" ) 312return t 313 314 315def render (model :dict ,* ,width :int ,height :int ,connection :str ,connection_state :str = "connected" ,frozen :bool = False , 316glyphs :str = "unicode" ,color :bool = True ,theme :str = "dark" ,connect :bool = False ,view_label :str = "Overview" , 317now :float | None = None ,bullet :str = "●" )-> Group : 318now = time .time ()if now is None else now 319ascii_mode = glyphs == "ascii" 320dot = "-" if ascii_mode else "·" # the ASCII look is pure ASCII: a stdout that cannot encode U+00B7 (cp852, cp874, cp932, ascii) must not raise 321solid = glyphs == "solid" # the classic Windows console without Cascadia Mono: solid blocks, square boxes, palette colours 322box_style = box .SQUARE if (ascii_mode or solid )else box .ROUNDED 323accent = ("#0c8a60" if theme == "light" else ACCENT )if color else "default" 324blue ,amber ,red = BLUE ,AMBER ,RED 325if solid and color : 326accent ,blue ,amber ,red = SOLID_ACCENT ,SOLID_BLUE ,SOLID_AMBER ,SOLID_RED 327plain = (lambda s :"default" )if not color else (lambda s : {BLUE :blue ,AMBER :amber ,RED :red }.get (s ,s )) 328state = model ["state" ] 329state_color = plain ({"Idle" :"default" ,"Reading" :BLUE ,"Generating" :accent ,"Queued" :AMBER ,"Error" :RED }[state ]) 330age = None if model .get ("sampled_at" )is None else now - model ["sampled_at" ] 331marker = ("FROZEN" if frozen else {"connected" :"LIVE" ,"stale" :"STALE" ,"connecting" :"CONNECTING" ,"disconnected" :"DISCONNECTED" , 332"auth_required" :"AUTH REQUIRED" ,"incompatible" :"INCOMPATIBLE" , 333"telemetry_unavailable" :"LIVE" }.get (connection_state ,"STALE" )) 334if marker == "LIVE" and age is not None and age > 6 : 335marker = "STALE" 336ctx_used ,ctx_max = model ["context" ] 337done ,total = model ["progress" ] 338pct = int (round (100 * done / total ))if done is not None and total else None 339 340# ---- heading, tabs, rule 341head = Text (no_wrap = True ,overflow = "crop" ) 342head .append (f"STRATA { view_label } " ,style = f"bold { accent } " ) 343head .append (connection + " " ,style = f"bold { accent } " ) 344label = f" { model . get ( 'model' ) or '' } { k ( ctx_max ) if ctx_max else '' } " .strip () 345head .append (label ,style = "bold" ) 346right = Text () 347right .append ((bullet + " " if not ascii_mode else "* " )+ model ["phase_text" ]+ (f" { dot } { pct } %" if pct is not None and state in ("Reading" ,"Generating" )else "" ), 348style = state_color if state != "Idle" else "dim" ) 349right .append (" " ) 350right .append (f"[ { marker } ]" ,style = f"bold { accent } " if marker == "LIVE" else "bold yellow" ) 351pad = max (2 ,width - len (head .plain )- len (right .plain )) 352head .append (" " * pad ) 353head .append_text (right ) 354tabs = nav .styled (0 ,min (width ,110 ),connect ,accent = accent ,color = color ) 355rule = Text (("-" if ascii_mode else "─" )* min (width ,110 ),style = "dim" ) 356 357# ---- model state bar 358bar_w = max (20 ,min (width ,110 )- 2 ) 359st = Text (no_wrap = True ,overflow = "crop" ) 360st .append ("Model state " ,style = f"bold { accent } " ) 361for n in STATES : 362txt = f"[ { n } ]" if n == state else n 363st .append (txt + " " ,style = (state_color if n == state and state != "Idle" else "bold" if n == state else "dim" )) 364if done is not None and total : 365right_txt = f" { tokens ( done ) } / { tokens ( total ) } tokens { dot } { pct } %" 366elif model ["queued" ]: 367right_txt = f" { model [ 'queued' ] } queued" 368else : 369right_txt = "" 370st .append (" " * max (2 ,min (width ,110 )- len (st .plain )- len (right_txt ))+ right_txt ,style = "dim" ) 371state_bar = bar ((done / total )if done is not None and total else None ,bar_w ,glyphs ,state_color if state != "Idle" else accent ) 372 373# ---- tiles 374g = model ["gpu" ] 375cards = g .get ("cards" )or [] 376ncards = len (cards ) 377tile_w = max (18 , (min (width ,110 )- 3 )// 4 ) 378inner = tile_w - 4 379spd ,spd_note ,spd_hist = model ["speed" ] 380util_scale = dict (lo = 0 ,hi = 100 ) 381tiles1 = [ 382_tile ("Speed" ,f" { fmt ( spd , 1 ) } tok/s" if spd is not None else "-- tok/s" ,spd_note ,spark (spd_hist ,inner ,glyphs ),tile_w ,accent = accent ,box_style = box_style ), 383_tile ("GPU load" ,f" { fmt ( g [ 'util' ]) } %" ,f"busiest of { ncards } cards" if ncards else 384short_gpu (g ["name" ])if g ["count" ]in (None ,1 )else f" { short_gpu ( g [ 'name' ]) } + { int ( g [ 'count' ]) - 1 } " , 385spark (g ["util_hist" ],inner ,glyphs ,** util_scale ),tile_w ,accent = accent ,box_style = box_style ), 386_tile ("VRAM" ,f" { fmt ( g [ 'vram_used' ], 1 ) } / { fmt ( g [ 'vram_total' ], 0 ) } GB" , 387 (f"all { ncards } cards" if ncards else 388f" { int ( model [ 'experts' ][ 'slots' ]):, } experts cached" if model ["experts" ]["slots" ]is not None else "graphics memory" ), 389spark (g ["vram_hist" ],inner ,glyphs ,lo = 0 ,hi = g ["vram_total" ]),tile_w ,accent = accent ,box_style = box_style ), 390_tile ("GPU temp" ,f" { fmt ( g [ 'temp' ]) } °C" if not ascii_mode else f" { fmt ( g [ 'temp' ]) } C" ,"hottest card" if ncards else "" , 391spark (g ["temp_hist" ],inner ,glyphs ,lo = 20 ,hi = 100 ),tile_w ,accent = plain (AMBER )if color else "default" ,box_style = box_style ), 392 ] 393c ,d = model ["cpu" ],model ["disk" ] 394gen = f"Gen { int ( g [ 'pcie_gen' ]) } " if g ["pcie_gen" ]else "PCIe" 395link = f" { gen } x { int ( g [ 'pcie_width' ]) } " if g ["pcie_width" ]else gen 396cpu_sub = (f" { int ( c [ 'sockets' ]) } CPUs { dot } { int ( c [ 'cores' ]) } cores" if c .get ("sockets" )and c ["sockets" ]> 1 and c ["cores" ]else 397f" { int ( c [ 'cores' ]) } cores { dot } { int ( c [ 'threads' ]) } threads" if c ["cores" ]and c ["threads" ]else 398f" { int ( c [ 'threads' ]) } threads" if c ["threads" ]else "" ) 399tiles2 = [ 400_tile ("Power" ,f" { fmt ( g [ 'power' ]) } W" ,f"of { fmt ( g [ 'power_limit' ]) } W limit" if g ["power_limit" ]else "" ,spark (g ["power_hist" ],inner ,glyphs ,lo = 0 ), 401tile_w ,accent = accent ,box_style = box_style ), 402_tile ("PCIe" ,link ,f"to GPU { fmt ( g [ 'pcie_rx' ]) } MB/s" if g ["pcie_rx" ]is not None else "to GPU --" ,spark (g ["pcie_hist" ],inner ,glyphs ,lo = 0 ),tile_w , 403accent = accent ,box_style = box_style ), 404_tile ("CPU" ,f" { fmt ( c [ 'load' ]) } %" ,cpu_sub ,spark (c ["hist" ],inner ,glyphs ,lo = 0 ,hi = 100 ),tile_w ,accent = accent ,box_style = box_style ), 405_tile ("Disk read" ,f" { fmt ( d [ 'read' ], 1 ) } MB/s" ,f"write { fmt ( d [ 'write' ], 1 ) } MB/s" if d ["write" ]is not None else "write --" , 406spark (d ["hist" ],inner ,glyphs ,lo = 0 ),tile_w ,accent = accent ,box_style = box_style ), 407 ] 408 409def row (tiles :list [Panel ])-> Table : 410t = Table .grid (padding = (0 ,1 )) 411for _ in tiles : 412t .add_column (width = tile_w ) 413t .add_row (* tiles ) 414return t 415 416# ---- bars and requests 417left_w = max (24 ,min (width ,110 )* 2 // 5 ) 418used_ctx = (ctx_used / ctx_max )if ctx_used is not None and ctx_max else None 419e = model ["experts" ] 420e_frac = (e ["slots" ]/ e ["total" ])if e ["slots" ]is not None and e ["total" ]else None 421ram_used ,ram_total = model ["ram" ] 422ram_frac = (ram_used / ram_total )if ram_used is not None and ram_total else None 423lines :list [Text ]= [] 424t = Text (no_wrap = True ,overflow = "crop" ) 425t .append ("Context fill " ,style = f"bold { accent } " ) 426t .append (f" { k ( ctx_used ) } / { k ( ctx_max ) } " + (f" { used_ctx * 100 :.0f } %" if used_ctx is not None else "" )) 427lines += [t ,bar (used_ctx ,left_w ,glyphs ,accent )] 428t = Text (no_wrap = True ,overflow = "crop" ) 429t .append ("Experts in VRAM " ) 430t .append (f" { fmt ( e [ 'slots' ]) } " + (f" { dot } { e [ 'gb' ]:.1f } GB" if e ["gb" ]is not None else "" ),style = "dim" ) 431lines += [t ,bar (e_frac ,left_w ,glyphs ,accent )] 432t = Text (no_wrap = True ,overflow = "crop" ) 433t .append ("System RAM " ) 434t .append (f" { fmt ( ram_used , 1 ) } / { fmt ( ram_total , 0 ) } GB" ,style = "dim" ) 435lines += [t ,bar (ram_frac ,left_w ,glyphs ,plain (RED )if ram_frac is not None and ram_frac > 0.9 else accent )] 436 437req = Table (box = None ,padding = (0 ,1 ),show_header = True ,header_style = "dim" ,pad_edge = False ) 438for col ,just in (("TIME" ,"left" ), ("STATUS" ,"left" ), ("PROMPT" ,"right" ), ("REUSED" ,"right" ), ("OUTPUT" ,"right" ), ("TOK/S" ,"right" ), 439 ("DURATION" ,"right" )): 440req .add_column (col ,justify = just ,no_wrap = True ) 441strip_rows = (1 + min (ncards ,4 )+ (1 if ncards > 4 else 0 )+ 1 )if ncards else 0 442show = max (2 ,min (6 ,height - 20 - strip_rows )) 443for r in model ["recent" ][:show ]: 444stamp = time .strftime ("%H:%M:%S" ,time .localtime (r ["time" ]))if r ["time" ]else "--" 445req .add_row (stamp ,Text (r ["state" ],style = plain (accent )if r ["state" ]== "Done" else plain (RED if r ["state" ]== "Error" else AMBER )), 446tokens (r ["prompt" ]),tokens (r ["reused" ]),tokens (r ["output" ]),fmt (r ["tps" ],1 ),fmt (r ["duration" ],1 ," s" )) 447if not model ["recent" ]: 448req .add_row ("No requests yet" ,"" ,"" ,"" ,"" ,"" ,"" ) 449bottom = Table .grid (padding = (0 ,3 )) 450bottom .add_column (width = left_w ) 451bottom .add_column () 452right = Group (Text ("Recent requests" ,style = f"bold { accent } " ),req ) 453bottom .add_row (Group (* lines ),right ) 454 455hint = Text (f" { nav . keys ( connect ) } views" + " / filter Space freeze r refresh t theme b open in browser ? help q quit" ,style = "dim" ) 456parts :list [Any ]= [head ,tabs ,rule ,st ,state_bar ,Text ("" ),row (tiles1 ),row (tiles2 )] 457if ncards : 458parts += [Text ("" ),_cards_strip (cards ,glyphs ,accent ,ascii_mode )] 459parts += [bottom ,Text ("" ),hint ] 460return Group (* parts )