okami.mom/strata

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

Niko1221Terminal Overview: the ASCII look has no U+00B7 (a redirected stdout in cp852, cp874, cp932 or ascii raised UnicodeEncodeError); test_speed_average decodes node's output as UTF-8 instead of the locale code page568127b7a

main
25.1 KiB460 linesraw
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:
38    if isinstance(v, bool) or not isinstance(v, (int, float)):
39        return None
40    if v != v or v in (float("inf"), float("-inf")):
41        return None
42    return float(v)
43
44
45def _gib(v: Any) -> float | None:
46    n = _num(v)
47    return None if n is None else n / GIB
48
49
50def _series(history: dict, key: str, scale: float = 1.0) -> list[float | None]:
51    raw = history.get(key) if isinstance(history, dict) else None
52    if not isinstance(raw, list):
53        return []
54    return [(None if _num(x) is None else _num(x) / scale) for x in raw[-60:]]
55
56
57def request_speed(r: dict) -> float | None:
58    out, ms = _num(r.get("output_tokens")), _num(r.get("decode_ms"))
59    if r.get("decode_tok_s") is not None and _num(r.get("decode_tok_s")) is not None:
60        return _num(r.get("decode_tok_s"))
61    return 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
66    decode time (the server's `totals`, the same token-weighted figure the engine's DONE lines and Prometheus use).
67    Not the last request's speed - a single request is noisy; this is the average over everything since the start.
68    None when the server reported no totals (never an invented zero)."""
69    totals = metrics.get("totals") or {}
70    out, ms = _num(totals.get("output_tokens")), _num(totals.get("decode_ms"))
71    return 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
76    draws exactly what it always drew."""
77    raw = hw.get("gpus") if isinstance(hw.get("gpus"), list) else []
78    cards = [{"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)]
81    return cards if len(cards) >= 2 else []
82
83
84def _total(values: list) -> float | None:
85    present = [v for v in values if v is not None]
86    return sum(present) if present else None
87
88
89def _most(values: list) -> float | None:
90    present = [v for v in values if v is not None]
91    return 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)."""
96    if not isinstance(metrics, dict) or not isinstance(metrics.get("live"), dict):
97        return None
98    live, engine = metrics["live"], metrics.get("engine") if isinstance(metrics.get("engine"), dict) else {}
99    hw = metrics.get("hardware") if isinstance(metrics.get("hardware"), dict) else {}
100    static = metrics.get("hardware_static") if isinstance(metrics.get("hardware_static"), dict) else {}
101    history = metrics.get("history") if isinstance(metrics.get("history"), dict) else {}
102    recent = [r for r in (metrics.get("requests") or []) if isinstance(r, dict)]
103    state_raw = str(live.get("state") or "idle")
104    queued = _num(live.get("queued")) or 0
105    err = bool(engine.get("error")) or state_raw == "error"
106    if err:
107        state = "Error"
108    elif state_raw == "reading":
109        state = "Reading"
110    elif state_raw == "generating":
111        state = "Generating"
112    elif queued > 0 and state_raw not in ("reading", "generating"):
113        state = "Queued"
114    else:
115        state = "Idle"
116    active = state in ("Reading", "Generating")
117    prompt_read, prompt_total = _num(live.get("prompt_read")), _num(live.get("prompt_total"))
118    generated, max_tokens = _num(live.get("generated")), _num(live.get("max_tokens"))
119    if state == "Reading" and prompt_total:
120        done, total = prompt_read or 0.0, prompt_total
121    elif state == "Generating" and max_tokens:
122        done, total = generated or 0.0, max_tokens
123    else:
124        done, total = None, None
125    last = recent[0] if recent else None
126    max_ctx = _num(engine.get("max_context"))
127    if active and _num(live.get("prompt_tokens")) is not None and generated is not None:
128        used = _num(live.get("prompt_tokens")) + generated
129    elif last and _num(last.get("prompt_tokens")) is not None and _num(last.get("output_tokens")) is not None:
130        used = _num(last["prompt_tokens"]) + _num(last["output_tokens"])
131    else:
132        used = None
133    if state == "Generating" and _num(live.get("tok_s")) is not None:
134        speed, speed_note = _num(live.get("tok_s")), "now"
135    elif state == "Reading" and _num(live.get("prefill_tok_s_mean")) is not None:
136        speed, speed_note = _num(live.get("prefill_tok_s_mean")), "reading the prompt"
137    else:
138        # Idle: not the last request's speed (one request is noisy) but the run's average, from the server's totals.
139        speed, speed_note = run_average_speed(metrics), "average of the run"
140        if speed is None:
141            speed, speed_note = (request_speed(last) if last else None), "last request"
142    slots, total_slots = _num(engine.get("expert_slots")), _num(engine.get("experts"))
143    cache_mib = _num(engine.get("expert_cache_mib"))
144    gen, genmax, width = _num(hw.get("gpu_pcie_gen")), _num(hw.get("gpu_pcie_gen_max")), _num(hw.get("gpu_pcie_width"))
145    model = {
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")
168                                                           if (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    }
173    cards = model["gpu"]["cards"]
174    if cards:                                  # two or more cards: the tiles say it for the whole computer, the Cards strip says it per card
175        g = model["gpu"]
176        g["util"] = _most([c["util"] for c in cards])                          # the busiest card
177        g["vram_used"] = _total([c["mem_used"] for c in cards])                # all cards together
178        g["vram_total"] = _total([c["mem_total"] for c in cards])
179        g["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
180        g["temp"] = _most([c["temp"] for c in cards])                          # the hottest card
181        g["power"] = _total([c["power"] for c in cards])
182        g["power_limit"] = _total([c["power_limit"] for c in cards])
183        g["count"] = float(len(cards))
184    return 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):
191    a thin dim ▄ for the lowest quarter, ▄ for the middle, █ for the top."""
192    vals = values[-width:]
193    present = [v for v in vals if v is not None]
194    if not present:
195        return Text(" " * width)
196    out = Text(" " * (width - len(vals)))
197    low = min(present) if lo is None else lo
198    high = max(present) if hi is None else hi
199    if high - low < 1e-9:
200        high = low + 1.0
201    for v in vals:
202        if v is None:
203            out.append(" ")
204            continue
205        f = (v - low) / (high - low)
206        if f < 0.25:
207            out.append("▄", style=SOLID_TRACK)
208        elif f < 0.6:
209            out.append("▄")
210        else:
211            out.append("█")
212    return 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,
217    solid blocks (a Text) in the classic console's solid look."""
218    if glyphs == "solid":
219        return solid_spark(values, width, lo, hi)
220    ramp = ".:-=+*#@" if glyphs == "ascii" else "▁▂▃▄▅▆▇█"
221    vals = values[-width:]
222    present = [v for v in vals if v is not None]
223    if not present:
224        return " " * width
225    low = min(present) if lo is None else lo
226    high = max(present) if hi is None else hi
227    if high - low < 1e-9:
228        high = low + 1.0
229    cells = []
230    for v in vals:
231        if v is None:
232            cells.append(" ")
233        else:
234            cells.append(ramp[min(7, max(0, int((v - low) / (high - low) * 7.999)))])
235    return " " * (width - len(cells)) + "".join(cells)
236
237
238def bar(frac: float | None, width: int, glyphs: str, color: str, empty: str = GREY) -> Text:
239    t = Text(no_wrap=True)
240    if glyphs == "solid":                       # solid █ and a thin ▄ track: no dithered shades in the classic console
241        n = 0 if frac is None else int(round(max(0.0, min(1.0, frac)) * width))
242        t.append("█" * n, style=color)
243        t.append("▄" * (width - n), style=SOLID_TRACK)
244        return t
245    full, hollow = ("#", ".") if glyphs == "ascii" else ("█", "░")
246    if frac is None:
247        t.append(hollow * width, style=GREY)
248        return t
249    n = int(round(max(0.0, min(1.0, frac)) * width))
250    t.append(full * n, style=color)
251    t.append(hollow * (width - n), style=empty)
252    return 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")."""
257    if not name:
258        return "graphics card"
259    for prefix in ("NVIDIA GeForce ", "NVIDIA ", "AMD Radeon ", "AMD ", "Intel(R) ", "Intel "):
260        if name.startswith(prefix):
261            name = name[len(prefix):]
262    return name
263
264
265def fmt(v: float | None, digits: int = 0, unit: str = "") -> str:
266    if v is None:
267        return "--"
268    return f"{v:,.{digits}f}{unit}"
269
270
271def tokens(v: float | None) -> str:
272    return "--" if v is None else f"{v:,.0f}"
273
274
275def k(v: float | None) -> str:
276    if v is None:
277        return "--"
278    return 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:
282    body = Text(no_wrap=True, overflow="crop")
283    body.append(big + "\n", style=big_style)
284    body.append(sub + "\n", style="dim")
285    if isinstance(series, Text):                # the solid look's sparkline carries its own styles
286        styled = Text(style=accent)
287        styled.append_text(series)
288        body.append_text(styled)
289    else:
290        body.append(series, style=accent)
291    return Panel(body, title=Text(title, style="dim"), title_align="left", box=box_style, padding=(0, 1), width=width,
292                 border_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."""
297    t = Text(no_wrap=True, overflow="crop")
298    t.append("Cards" + chr(10), style=f"bold {accent}")
299    shown = cards[:4]
300    names = [short_gpu(c.get("name")) for c in shown]
301    pad = min(16, max(len(n) for n in names))
302    for c, name in zip(shown, names):
303        util = c["util"]
304        used, total = c["mem_used"], c["mem_total"]
305        t.append(f"GPU {c['index'] if c['index'] is not None else '?'}  {name[:pad]:<{pad}}  ")
306        t.append_text(bar((util / 100.0) if util is not None else None, 10, glyphs, accent))
307        mem = f"{fmt(used, 1)} / {fmt(total, 0)} GB" if used is not None and total is not None else "-- GB"
308        temp = f"{fmt(c['temp'])} {'C' if ascii_mode else '°C'}"
309        t.append(f"  {fmt(util):>3} %   {mem:<14}  {temp:>6}   {fmt(c['power']):>4} W" + chr(10))
310    if len(cards) > 4:
311        t.append(f"+ {len(cards) - 4} more cards: press 5" + chr(10), style="dim")
312    return t
313
314
315def render(model: dict, *, width: int, height: int, connection: str, connection_state: str = "connected", frozen: bool = False,
316           glyphs: str = "unicode", color: bool = True, theme: str = "dark", connect: bool = False, view_label: str = "Overview",
317           now: float | None = None, bullet: str = "●") -> Group:
318    now = time.time() if now is None else now
319    ascii_mode = glyphs == "ascii"
320    dot = "-" if ascii_mode else "·"             # the ASCII look is pure ASCII: a stdout that cannot encode U+00B7 (cp852, cp874, cp932, ascii) must not raise
321    solid = glyphs == "solid"                   # the classic Windows console without Cascadia Mono: solid blocks, square boxes, palette colours
322    box_style = box.SQUARE if (ascii_mode or solid) else box.ROUNDED
323    accent = ("#0c8a60" if theme == "light" else ACCENT) if color else "default"
324    blue, amber, red = BLUE, AMBER, RED
325    if solid and color:
326        accent, blue, amber, red = SOLID_ACCENT, SOLID_BLUE, SOLID_AMBER, SOLID_RED
327    plain = (lambda s: "default") if not color else (lambda s: {BLUE: blue, AMBER: amber, RED: red}.get(s, s))
328    state = model["state"]
329    state_color = plain({"Idle": "default", "Reading": BLUE, "Generating": accent, "Queued": AMBER, "Error": RED}[state])
330    age = None if model.get("sampled_at") is None else now - model["sampled_at"]
331    marker = ("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"))
334    if marker == "LIVE" and age is not None and age > 6:
335        marker = "STALE"
336    ctx_used, ctx_max = model["context"]
337    done, total = model["progress"]
338    pct = int(round(100 * done / total)) if done is not None and total else None
339
340    # ---- heading, tabs, rule
341    head = Text(no_wrap=True, overflow="crop")
342    head.append(f"STRATA  {view_label}   ", style=f"bold {accent}")
343    head.append(connection + "   ", style=f"bold {accent}")
344    label = f"{model.get('model') or ''} {k(ctx_max) if ctx_max else ''}".strip()
345    head.append(label, style="bold")
346    right = Text()
347    right.append((bullet + " " if not ascii_mode else "* ") + model["phase_text"] + (f" {dot} {pct}%" if pct is not None and state in ("Reading", "Generating") else ""),
348                 style=state_color if state != "Idle" else "dim")
349    right.append("   ")
350    right.append(f"[{marker}]", style=f"bold {accent}" if marker == "LIVE" else "bold yellow")
351    pad = max(2, width - len(head.plain) - len(right.plain))
352    head.append(" " * pad)
353    head.append_text(right)
354    tabs = nav.styled(0, min(width, 110), connect, accent=accent, color=color)
355    rule = Text(("-" if ascii_mode else "─") * min(width, 110), style="dim")
356
357    # ---- model state bar
358    bar_w = max(20, min(width, 110) - 2)
359    st = Text(no_wrap=True, overflow="crop")
360    st.append("Model state  ", style=f"bold {accent}")
361    for n in STATES:
362        txt = f"[{n}]" if n == state else n
363        st.append(txt + "  ", style=(state_color if n == state and state != "Idle" else "bold" if n == state else "dim"))
364    if done is not None and total:
365        right_txt = f"{tokens(done)} / {tokens(total)} tokens {dot} {pct}%"
366    elif model["queued"]:
367        right_txt = f"{model['queued']} queued"
368    else:
369        right_txt = ""
370    st.append(" " * max(2, min(width, 110) - len(st.plain) - len(right_txt)) + right_txt, style="dim")
371    state_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
374    g = model["gpu"]
375    cards = g.get("cards") or []
376    ncards = len(cards)
377    tile_w = max(18, (min(width, 110) - 3) // 4)
378    inner = tile_w - 4
379    spd, spd_note, spd_hist = model["speed"]
380    util_scale = dict(lo=0, hi=100)
381    tiles1 = [
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
384              short_gpu(g["name"]) if g["count"] in (None, 1) else f"{short_gpu(g['name'])} +{int(g['count']) - 1}",
385              spark(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
388               f"{int(model['experts']['slots']):,} experts cached" if model["experts"]["slots"] is not None else "graphics memory"),
389              spark(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 "",
391              spark(g["temp_hist"], inner, glyphs, lo=20, hi=100), tile_w, accent=plain(AMBER) if color else "default", box_style=box_style),
392    ]
393    c, d = model["cpu"], model["disk"]
394    gen = f"Gen{int(g['pcie_gen'])}" if g["pcie_gen"] else "PCIe"
395    link = f"{gen} x{int(g['pcie_width'])}" if g["pcie_width"] else gen
396    cpu_sub = (f"{int(c['sockets'])} CPUs {dot} {int(c['cores'])} cores" if c.get("sockets") and c["sockets"] > 1 and c["cores"] else
397               f"{int(c['cores'])} cores {dot} {int(c['threads'])} threads" if c["cores"] and c["threads"] else
398               f"{int(c['threads'])} threads" if c["threads"] else "")
399    tiles2 = [
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),
401              tile_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,
403              accent=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 --",
406              spark(d["hist"], inner, glyphs, lo=0), tile_w, accent=accent, box_style=box_style),
407    ]
408
409    def row(tiles: list[Panel]) -> Table:
410        t = Table.grid(padding=(0, 1))
411        for _ in tiles:
412            t.add_column(width=tile_w)
413        t.add_row(*tiles)
414        return t
415
416    # ---- bars and requests
417    left_w = max(24, min(width, 110) * 2 // 5)
418    used_ctx = (ctx_used / ctx_max) if ctx_used is not None and ctx_max else None
419    e = model["experts"]
420    e_frac = (e["slots"] / e["total"]) if e["slots"] is not None and e["total"] else None
421    ram_used, ram_total = model["ram"]
422    ram_frac = (ram_used / ram_total) if ram_used is not None and ram_total else None
423    lines: list[Text] = []
424    t = Text(no_wrap=True, overflow="crop")
425    t.append("Context fill  ", style=f"bold {accent}")
426    t.append(f"{k(ctx_used)} / {k(ctx_max)}" + (f"  {used_ctx * 100:.0f}%" if used_ctx is not None else ""))
427    lines += [t, bar(used_ctx, left_w, glyphs, accent)]
428    t = Text(no_wrap=True, overflow="crop")
429    t.append("Experts in VRAM   ")
430    t.append(f"{fmt(e['slots'])}" + (f" {dot} {e['gb']:.1f} GB" if e["gb"] is not None else ""), style="dim")
431    lines += [t, bar(e_frac, left_w, glyphs, accent)]
432    t = Text(no_wrap=True, overflow="crop")
433    t.append("System RAM        ")
434    t.append(f"{fmt(ram_used, 1)} / {fmt(ram_total, 0)} GB", style="dim")
435    lines += [t, bar(ram_frac, left_w, glyphs, plain(RED) if ram_frac is not None and ram_frac > 0.9 else accent)]
436
437    req = Table(box=None, padding=(0, 1), show_header=True, header_style="dim", pad_edge=False)
438    for col, just in (("TIME", "left"), ("STATUS", "left"), ("PROMPT", "right"), ("REUSED", "right"), ("OUTPUT", "right"), ("TOK/S", "right"),
439                      ("DURATION", "right")):
440        req.add_column(col, justify=just, no_wrap=True)
441    strip_rows = (1 + min(ncards, 4) + (1 if ncards > 4 else 0) + 1) if ncards else 0
442    show = max(2, min(6, height - 20 - strip_rows))
443    for r in model["recent"][:show]:
444        stamp = time.strftime("%H:%M:%S", time.localtime(r["time"])) if r["time"] else "--"
445        req.add_row(stamp, Text(r["state"], style=plain(accent) if r["state"] == "Done" else plain(RED if r["state"] == "Error" else AMBER)),
446                    tokens(r["prompt"]), tokens(r["reused"]), tokens(r["output"]), fmt(r["tps"], 1), fmt(r["duration"], 1, " s"))
447    if not model["recent"]:
448        req.add_row("No requests yet", "", "", "", "", "", "")
449    bottom = Table.grid(padding=(0, 3))
450    bottom.add_column(width=left_w)
451    bottom.add_column()
452    right = Group(Text("Recent requests", style=f"bold {accent}"), req)
453    bottom.add_row(Group(*lines), right)
454
455    hint = Text(f"{nav.keys(connect)} views" + "   / filter   Space freeze   r refresh   t theme   b open in browser   ? help   q quit", style="dim")
456    parts: list[Any] = [head, tabs, rule, st, state_bar, Text(""), row(tiles1), row(tiles2)]
457    if ncards:
458        parts += [Text(""), _cards_strip(cards, glyphs, accent, ascii_mode)]
459    parts += [bottom, Text(""), hint]
460    return Group(*parts)