okami.mom/strata

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

Niko1221Merge f-split-tuiqa (95f380769) into f-split-int: TUI QA fixes (launch with flags, discovery, monitor menu, connect checks, layouts, no browser, warnings), picture reader CPU under 24 GB / GPU from 24 GBfd0e3766a

main
45.3 KiB744 linesraw
1"""Width-aware, color-free monitor content. The UI applies presentation styles."""
2
3from __future__ import annotations
4
5import math
6import time
7import unicodedata
8from typing import Any
9
10from strata_cli import nav
11from strata_cli.client import complete_slots
12
13
14VIEWS = ("overview", "serving", "requests", "engine", "hardware", "logs")
15
16
17def activity_continuity_notice(snapshot: dict) -> str | None:
18    """Label missing transitions observed by this monitor, separate from server events."""
19    state = snapshot.get("activity_continuity") or {}
20    if not isinstance(state, dict):
21        return None
22    if state.get("regressed") is True:
23        return "Activity sequence reset without an instance change"
24    gap = state.get("gap") or {}
25    if not isinstance(gap, dict):
26        return None
27    start, end = gap.get("from_seq"), gap.get("to_seq")
28    if type(start) is int and type(end) is int and 0 < start <= end:
29        return f"Missed activity #{start}-{end} (retention gap)"
30    if state.get("restarted") is True:
31        return "Serving restarted; activity sequence reset"
32    return None
33
34
35def group_occupancy(work: dict) -> dict[int, tuple[int, int]] | None:
36    """Do not publish exact group counts from truncated or ambiguous slots."""
37    slots = complete_slots(work)
38    if slots is None:
39        return None
40    groups: dict[int, tuple[int, int]] = {}
41    reported_count = work.get("groups")
42    for row in slots:
43        group = row.get("group")
44        if (not isinstance(group, int) or isinstance(group, bool) or group < 0 or
45                isinstance(reported_count, int) and not isinstance(reported_count, bool) and
46                reported_count > 0 and group >= reported_count):
47            return None
48        busy, total = groups.get(group, (0, 0))
49        groups[group] = (busy + (row["state"] != "idle"), total + 1)
50    return groups
51
52
53def _emoji(char: str) -> bool:
54    code = ord(char)
55    return 0x1F000 <= code <= 0x1FAFF or 0x2600 <= code <= 0x27BF
56
57
58def _regional_indicator(char: str) -> bool:
59    return 0x1F1E6 <= ord(char) <= 0x1F1FF
60
61
62def _clusters(value: Any):
63    """Yield printable clusters without terminal controls or bidi formatters."""
64    current = ""
65    join_emoji = False
66    for char in unicodedata.normalize("NFC", str(value) if value is not None else "--"):
67        category = unicodedata.category(char)
68        if char == "\u200d":
69            if current and any(_emoji(piece) for piece in current):
70                current += char
71                join_emoji = True
72            continue
73        if not char.isprintable() or category in ("Cf", "Cc", "Cs"):
74            continue
75        mark = category in ("Mn", "Mc", "Me") or 0x1F3FB <= ord(char) <= 0x1F3FF
76        if mark:
77            if current:
78                current += char
79            continue
80        if join_emoji:
81            join_emoji = False
82            if _emoji(char):
83                current += char
84                continue
85            yield current.rstrip("\u200d")
86            current = char
87            continue
88        if _regional_indicator(char) and len(current) == 1 and _regional_indicator(current):
89            current += char
90            continue
91        if current:
92            yield current
93        current = char
94    if current:
95        yield current.rstrip("\u200d")
96
97
98def _cluster_width(cluster: str) -> int:
99    if "\u200d" in cluster or "\ufe0f" in cluster:
100        return 2
101    if len(cluster) == 2 and all(_regional_indicator(char) for char in cluster):
102        return 2
103    width = 0
104    for char in cluster:
105        if unicodedata.category(char) in ("Mn", "Mc", "Me") or 0x1F3FB <= ord(char) <= 0x1F3FF:
106            continue
107        width += 2 if unicodedata.east_asian_width(char) in ("W", "F") or \
108                      0x1F000 <= ord(char) <= 0x1FAFF else 1
109    return width
110
111
112def display_width(value: str) -> int:
113    return sum(_cluster_width(cluster) for cluster in _clusters(value))
114
115
116def safe(value: Any, width: int = 80) -> str:
117    cells = 0
118    out = []
119    for cluster in _clusters(value):
120        needed = _cluster_width(cluster)
121        if cells + needed > max(0, width):
122            break
123        out.append(cluster)
124        cells += needed
125    return "".join(out)
126
127
128def field(value: Any, width: int) -> str:
129    text = safe(value, width)
130    return text + " " * max(0, width - display_width(text))
131
132
133def number(value: Any, unit: str = "", digits: int = 0) -> str:
134    if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
135        return "--"
136    return f"{value:,.{digits}f}{unit}" if digits else f"{value:,.0f}{unit}"
137
138
139def _line(text: str, width: int) -> str:
140    return safe(text, width)
141
142
143def _queue_wait(row: dict, sampled_at: Any) -> float | None:
144    queued = row.get("queued_at")
145    if not isinstance(queued, (int, float)) or isinstance(queued, bool) or not math.isfinite(queued):
146        return None
147    admitted = row.get("admitted_at")
148    end = admitted if isinstance(admitted, (int, float)) and not isinstance(admitted, bool) and math.isfinite(admitted) else sampled_at
149    if not isinstance(end, (int, float)) or isinstance(end, bool) or not math.isfinite(end):
150        return None
151    return max(0.0, end - queued)
152
153
154def _request_work(row: dict) -> str:
155    read = row.get("prompt_read")
156    if row.get("state") == "reading":
157        return f"read {number(read)} new" if read is not None else "read --"
158    return f"out {number(row.get('generated'))}"
159
160
161def _replica_prefix(row: dict) -> str:
162    replica = row.get("replica")
163    return f"Replica {replica}   " if type(replica) is int and 0 <= replica < 16 else ""
164
165
166def _replica_short(row: dict) -> str:
167    replica = row.get("replica")
168    return f"r{replica} " if type(replica) is int and 0 <= replica < 16 else ""
169
170
171def _request_detail(row: dict, sampled_at: Any, width: int) -> list[str]:
172    """Only fields from the bounded, redacted telemetry contract."""
173    return ["", "REQUEST DETAIL  (read only)",
174            _line(f"ID {safe(row.get('id'), 24)}   State {safe(row.get('state'), 16)}", width),
175            _line(f"{_replica_prefix(row)}Slot {number(row.get('slot'))}   Group {number(row.get('group'))}   Queue wait {number(_queue_wait(row, sampled_at), ' s', 1)}", width),
176            _line(f"Prompt {number(row.get('prompt_tokens'))} tokens   {_request_work(row)}", width),
177            _line(f"First engine token {number(row.get('first_engine_token_s'), ' s', 3)} [since queue entry]  |  No prompt text", width)]
178
179
180def _recent_detail(row: dict, width: int) -> list[str]:
181    """Completed-request fields from the bounded telemetry contract."""
182    return ["", "RECENT REQUEST DETAIL  (read only)",
183            _line(f"ID {safe(row.get('id'), 24)}   Finish {safe(row.get('finish'), 16)}", width),
184            _line(f"Prompt {number(row.get('prompt_tokens'))}   Cached {number(row.get('reused'))}   Output {number(row.get('output_tokens'))} tokens", width),
185            _line(f"Duration {number(row.get('duration_s'), ' s', 2)}   Prompt {number(row.get('prompt_ms'), ' ms', 1)}   Decode {number(row.get('decode_ms'), ' ms', 1)}", width),
186            _line(f"First engine token {number(row.get('first_engine_token_s'), ' s', 3)} [since queue entry]  |  No prompt text", width)]
187
188
189def request_rows(snapshot: dict, filter_text: str = "", *, limit: int | None = None) -> tuple[list[dict], list[dict]]:
190    """One selection order for the interactive shell and all renderer widths."""
191    work = snapshot.get("work") or {}
192    live = (work.get("requests") or [])[:limit]
193    recent = (snapshot.get("recent") or [])[:limit]
194    needle = filter_text.lower()
195    if needle:
196        # what the screen calls the row counts too: LIVE for a request in flight, DONE for a finished one
197        live = [row for row in live if needle in (safe(row.get("id")) + " " + safe(row.get("state")) + " live").lower()]
198        recent = [row for row in recent if needle in (safe(row.get("id")) + " " + safe(row.get("finish")) + " done").lower()]
199    return live, recent
200
201
202def no_requests_text(filter_text: str = "") -> str:
203    """The empty-list sentence: with a filter on it says so and names the filter, so an empty page is never a mystery."""
204    if not filter_text:
205        return "No request summaries"
206    return f"No requests match this filter ({safe(filter_text, 30)}). It looks at the id, the state, and live or done. Esc clears it."
207
208
209def activity_rows(snapshot: dict, filter_text: str = "") -> list[dict]:
210    rows = (snapshot.get("activity") or {}).get("events") or []
211    needle = filter_text.lower()
212    return [row for row in rows if isinstance(row, dict) and
213            (not needle or needle in (safe(row.get("request_id")) + " " + safe(row.get("event")) +
214                                      " " + safe(row.get("outcome"))).lower())]
215
216
217def activity_label(row: dict, width: int) -> str:
218    at = row.get("at")
219    try:
220        clock = time.strftime("%H:%M:%S", time.localtime(at)) if isinstance(at, (int, float)) else "--:--:--"
221    except (OverflowError, OSError, ValueError):
222        clock = "--:--:--"
223    event = safe(row.get("event"), 16)
224    outcome = row.get("outcome")
225    label = f"{event} ({safe(outcome, 12)})" if outcome else event
226    return _line(f"#{number(row.get('seq')):<6} {clock}  {field(row.get('request_id'), 12)}  {label}", width)
227
228
229def _device(row: dict, width: int) -> str:
230    idx = row.get("index")
231    label = f"GPU {idx if idx is not None else '?'}"
232    used, total = row.get("mem_used"), row.get("mem_total")
233    mem = f"{number(used / 2**30 if isinstance(used, (int, float)) else None, '', 1)}/{number(total / 2**30 if isinstance(total, (int, float)) else None, ' GiB', 1)}"
234    if width < 80:
235        return _line(f"{label:<7} {mem:<17} util {number(row.get('util'), '%')}", width)
236    from strata_cli.overview import short_gpu              # "NVIDIA GeForce RTX 3090" -> "RTX 3090": the maker's prefix used to cut the model off
237    name = short_gpu(row.get("name")) if row.get("name") else None
238    return _line(f"{label:<7} {field(name, 20)} {mem:<17} {number(row.get('util'), '%'):>5}  {number(row.get('temp'), ' C'):>6}  {number(row.get('power'), ' W'):>7}", width)
239
240
241def _device_stage(topology: dict, index: Any, width: int) -> str:
242    if str(topology.get("mode") or "").startswith("replicas"):
243        for row in topology.get("replica_devices") or []:
244            if index in row.get("devices", []):
245                replica = row["replica"]
246                plan = next((entry for entry in topology.get("replica_stages") or []
247                             if entry["replica"] == replica), None)
248                assigned = [stage for stage in plan["stages"] if stage.get("device_index") == index] if plan else []
249                if assigned:
250                    ranges = ", ".join(f"{stage['stage']}:{stage['layer_start']}-{stage['layer_end']}"
251                                       for stage in assigned)
252                    return _line(f"Replica R{replica} stage/layers {ranges} [engine log]", width)
253                cards = ",".join(str(device) for device in row["devices"])
254                return _line(f"Replica R{replica} [configured cards {cards}; stage map unavailable]", width)
255        return "Replica card assignment unavailable"
256    stages = topology.get("stages") or []
257    if topology.get("resolved") is True and stages:
258        assigned = [row for row in stages if row.get("device_index") == index]
259        if assigned:
260            ranges = ", ".join(f"{number(row.get('stage'))}:{number(row.get('layer_start'))}-{number(row.get('layer_end'))}"
261                               for row in assigned)
262            return _line(f"Stage/layers {ranges} [engine log]", width)
263        return "Selected card is not an engine stage"
264    return ("Engine stage ranges reported; card mapping unavailable" if stages else
265            "Stage/layer mapping unavailable")
266
267
268def _batch_window(work: dict, width: int) -> str:
269    replica_batches = work.get("replica_batches") or []
270    if replica_batches:
271        shown = sorted(replica_batches, key=lambda row: row["replica"])[:2]
272        parts = [f"R{row['replica']} {number(row.get('effective_rows_window'), '', 1)}/"
273                 f"{number(row.get('batch_active_rows_window'), '', 1)}"
274                 + (f" age {number(row.get('batch_sample_age_s'), 's', 1)}" if width >= 80 else "")
275                 for row in shown]
276        extra = max(0, len(replica_batches) - len(shown))
277        return _line("Batch rows/window processed/active " + "  ".join(parts)
278                     + (f" +{extra} replicas" if extra else ""), width)
279    rows = work.get("effective_rows_window")
280    if not isinstance(rows, (int, float)):
281        return _line("Batch rows/window --" if width < 60 else
282                     "Batch rows/window -- [no engine batch sample]", width)
283    active = work.get("batch_active_rows_window")
284    if width < 60:
285        return _line(f"Batch {number(rows, '', 1)} processed / {number(active, '', 1)} active", width)
286    windows = work.get("batch_sample_windows")
287    span = work.get("batch_sample_span_s")
288    age = work.get("batch_sample_age_s")
289    return _line(f"Batch rows/window {number(rows, '', 1)} processed / {number(active, '', 1)} active "
290                 f"[{number(windows)} windows/{number(span, 's', 1)}, {number(age, 's', 1)} old]", width)
291
292
293def _stage_in_flight(work: dict, width: int) -> str:
294    replica_samples = work.get("replica_stage_samples") or []
295    if replica_samples:
296        parts = []
297        for row in replica_samples[:2]:
298            stages = row.get("stage_in_flight") or []
299            values = " ".join(f"S{stage['stage']} {number(stage['percent'], '%', 0)}"
300                              for stage in stages)
301            parts.append(f"R{row['replica']} {values or '--'}")
302        extra = max(0, len(replica_samples) - 2)
303        return _line("Replica host span " + "  ".join(parts)
304                     + (f" +{extra} see Engine" if extra else "") + " [not GPU util]", width)
305    stages = work.get("stage_in_flight") or []
306    if not stages:
307        return _line("Stage in-flight -- [no pipeline sample]", width)
308    values = " ".join(f"S{row['stage']} {number(row['percent'], '%', 0)}" for row in stages)
309    if width < 60:
310        compact = "/".join(number(row["percent"], "", 0) for row in stages)
311        return _line(f"Stages {compact}% in-flight [host]", width)
312    span, age = work.get("stage_sample_span_s"), work.get("stage_sample_age_s")
313    return _line(f"Stage in-flight {values} [host, {number(span, 's', 1)}, {number(age, 's', 1)} old]", width)
314
315
316def _device_detail(row: dict, topology: dict, width: int) -> list[str]:
317    used, total = row.get("mem_used"), row.get("mem_total")
318    used_gib = used / 2**30 if isinstance(used, (int, float)) else None
319    total_gib = total / 2**30 if isinstance(total, (int, float)) else None
320    return ["DEVICE DETAIL  (read only)",
321            _line(f"GPU {number(row.get('index'))}   {safe(row.get('name'), 30)}", width),
322            _line(f"VRAM {number(used_gib, ' GiB', 1)} / {number(total_gib, ' GiB', 1)}   Util {number(row.get('util'), '%')}", width),
323            _line(f"Temperature {number(row.get('temp'), ' C')}   Power {number(row.get('power'), ' W')}", width),
324            _line(f"Placement {safe(topology.get('mode'), 24)}; split {safe(topology.get('configured_split'), 24)}", width),
325            _device_stage(topology, row.get("index"), width)]
326
327
328def _slot_detail(row: dict, width: int) -> list[str]:
329    return ["", "SLOT DETAIL  (read only)",
330            _line(f"{_replica_prefix(row)}Slot {number(row.get('slot'))}   Group {number(row.get('group'))}   State {safe(row.get('state'), 16)}", width),
331            _line(f"Request {safe(row.get('request_id'), 24)}   Held {number(row.get('held_tokens'))} tokens", width),
332            _line(f"Prompt {number(row.get('prompt_tokens'))}   New read {number(row.get('prompt_read'))}   Output {number(row.get('generated'))}", width),
333            _line(f"Elapsed {number(row.get('elapsed_s'), ' s', 1)}   Slot rate {number(row.get('tok_s'), ' tok/s', 1)}", width),
334            "Group is a pipeline batch group, not a GPU assignment"]
335
336
337def _row_window(rows: list[dict], selected: int, capacity: int) -> tuple[int, int, int]:
338    index = min(max(0, selected), max(0, len(rows) - 1))
339    start = min(max(0, index - capacity // 2), max(0, len(rows) - capacity))
340    return index, start, min(start + capacity, len(rows))
341
342
343def _wide_serving(lines: list[str], snapshot: dict, width: int, height: int,
344                  filter_text: str, selected: int, connect: bool = False) -> str:
345    work, rates = snapshot.get("work") or {}, snapshot.get("rates") or {}
346    topology, devices = snapshot.get("topology") or {}, snapshot.get("devices") or []
347    recent = snapshot.get("recent") or []
348    lines += [f"Topology {safe(topology.get('mode'))}  |  Requested {number(work.get('slots_requested'))} / effective {number(work.get('slots_effective'))} slots  |  Groups {number(work.get('groups'))}",
349              f"Outside slots {number(work.get('outside_slots'))}    Total output {number(rates.get('aggregate_output_tok_s'), ' tok/s', 1)} [common sample]    Disconnect cancels {number(work.get('client_disconnect_cancels'))}",
350              f"Admission {number(work.get('admission_reserved'))}/{number(work.get('admission_limit'))} reserved/limit    Queue cap {number(work.get('max_queue'))}    Rejected {number(work.get('admission_rejected'))}    Timed out {number(work.get('queue_timeouts'))}",
351              f"Wait limit {number(work.get('queue_timeout_s'), 's', 1)}    Oldest wait {number(work.get('oldest_queue_s'), 's', 1)}",
352              f"First engine token {number(recent[0].get('first_engine_token_s') if recent else None, ' s', 3)} [last completed, since queue entry]",
353              _batch_window(work, width),
354              _stage_in_flight(work, width),
355              "-" * min(width, 110)]
356    left_width = max(56, width - 47)
357    left = ["REQUEST FLOW  (no-slot first; wait = queue time)"]
358    # When height is scarce, preserve pressure outside the batch window; slot rows remain in the Groups pane.
359    all_requests = work.get("requests") or []
360    requests = sorted((row for row in all_requests if not filter_text or
361                       filter_text.lower() in (safe(row.get("id")) + " " + safe(row.get("state")) + " live").lower()),
362                      key=lambda row: row.get("slot") is not None)
363    if requests:
364        for row in requests:
365            wait = _queue_wait(row, snapshot.get("sampled_at"))
366            left.append(_line(f"{field(row.get('id'), 12)} {_replica_short(row)}s{number(row.get('slot')):<2} g{number(row.get('group')):<2} {field(row.get('state'), 9)} wait {number(wait, 's', 1):<6} {_request_work(row)}", left_width))
367    elif all_requests:
368        left.append(no_requests_text(filter_text) if filter_text else "No matching request summaries")
369    else:
370        left.append("Request identity unavailable; showing engine slots")
371        for row in work.get("slots") or []:
372            left.append(_line(f"{_replica_short(row)}slot {number(row.get('slot')):<2} group {number(row.get('group')):<2} {field(row.get('state'), 10)} in {number(row.get('prompt_tokens')):<7} {_request_work(row)}", left_width))
373    # Reserve space for group occupancy, mapping provenance and the footer at standard 30-row terminals.
374    count = min(max(len(left), len(devices) + 1), max(1, height - len(lines) - 8))
375    right = ["GPU SENSORS  (per card)"]
376    if devices:
377        capacity = max(1, count - 1)
378        _, start, end = _row_window(devices, selected, capacity)
379        if start:
380            right[0] = f"GPU SENSORS  ({start + 1}-{end}/{len(devices)})"
381        for i in range(start, end):
382            row = devices[i]
383            used, total = row.get("mem_used"), row.get("mem_total")
384            memory = f"{number(used / 2**30 if isinstance(used, (int, float)) else None, '', 1)}/{number(total / 2**30 if isinstance(total, (int, float)) else None, '', 1)}G"
385            right.append(_line(f"{'>' if i == selected else ' '} GPU {number(row.get('index')):<2} {field(row.get('name'), 8)} {memory:<11} {number(row.get('util'), '%'):>4} {number(row.get('temp'), 'C'):>4} {number(row.get('power'), 'W'):>5}", width-left_width-2))
386    else:
387        right.append("Per-device sensors unavailable")
388    lines += [f"{field(left[i] if i < len(left) else '', left_width)}  {_line(right[i] if i < len(right) else '', width-left_width-2)}".rstrip()
389              for i in range(count)]
390    if len(left) > count:
391        lines.append(f"+{len(left) - count} more requests; use Requests view")
392    groups = group_occupancy(work)
393    lines += ["", ("Occupied slots by group  " +
394                   "   ".join(f"G{g} {busy}/{total}" for g, (busy, total) in sorted(groups.items()))
395                   if groups is not None else "Occupied slots by group -- (slot report incomplete)")]
396    if topology.get("resolved") is True:
397        ranges = "  ".join(f"GPU {number(row.get('device_index'))}: {number(row.get('layer_start'))}-{number(row.get('layer_end'))}"
398                           for row in topology.get("stages") or [])
399        lines += [_line(f"Engine stage layers [start log]  {ranges}", width)]
400    elif any(entry.get("stages") for entry in topology.get("replica_stages") or []):
401        ranges = "  ".join(
402            f"R{entry['replica']} GPU {number(stage.get('device_index'))}: "
403            f"{number(stage.get('layer_start'))}-{number(stage.get('layer_end'))}"
404            for entry in topology["replica_stages"] for stage in entry["stages"])
405        lines += [_line(f"Replica stage layers [start log]  {ranges}", width)]
406    elif topology.get("stages"):
407        lines += ["Engine stage ranges reported; card mapping unavailable"]
408    else:
409        lines += ["Stage/layer mapping unavailable; groups are not GPU assignments"]
410    age = time.time() - snapshot["sampled_at"] if isinstance(snapshot.get("sampled_at"), (int, float)) else None
411    lines += ["", f"Sample age {number(age, ' s', 1)}  |  Source {safe(snapshot.get('source'))}",
412              f"{nav.keys(connect)} views   / filter   Space freeze   r refresh   t theme   ? help   q quit"]
413    return "\n".join(_line(x, width) for x in lines[:height])
414
415
416def render_view(snapshot: dict, view: str, width: int = 80, height: int = 24,
417                selected: int = 0, frozen: bool = False, filter_text: str = "",
418                glyphs: str = "ascii", connection: str = "", serving_pane: str = "devices",
419                detail: bool = False, connection_state: str | None = None, connect: bool = False) -> str:
420    """Render the six views (seven with Connect, when `strata launch` opened the monitor) with explicit unavailable markers and no fake rates."""
421    width, height = max(width, 30), max(height, 8)
422    tiny = width < 60 or height < 14
423    view = view if view in VIEWS else "overview"
424    model = snapshot.get("model") or {}
425    instance = snapshot.get("instance") or {}
426    model_state = ("DRAINING" if instance.get("state") == "draining" else
427                   "READY" if model.get("loaded") is True else
428                   "NO MODEL LOADED" if model.get("loaded") is False else "UNKNOWN")
429    work = snapshot.get("work") or {}
430    rates = snapshot.get("rates") or {}
431    topology = snapshot.get("topology") or {}
432    devices = snapshot.get("devices") or []
433    recent = snapshot.get("recent") or []
434    totals = snapshot.get("totals") or {}
435    sampled = snapshot.get("sampled_at")
436    age = time.time() - sampled if isinstance(sampled, (int, float)) else None
437    if (snapshot.get("quality") or {}).get("telemetry") == "unavailable":
438        connection_state = "telemetry_unavailable" if connection_state in (None, "connected") else connection_state
439    if connection_state is None:
440        marker = "[FROZEN]" if frozen else ("[STALE]" if age is not None and age > 5 else "[LIVE]")
441    else:
442        labels = {"connecting": "CONNECTING", "connected": "LIVE", "stale": "STALE",
443                  "auth_required": "AUTH REQUIRED", "incompatible": "INCOMPATIBLE",
444                  "disconnected": "DISCONNECTED", "telemetry_unavailable": "NO TELEMETRY"}
445        state = connection_state if connection_state in labels else "stale"
446        if state == "connected" and (age is None or age > 5 or age < -5):
447            state = "stale"
448        if state != "connected":
449            rates = {**rates, "answer_tok_s": None, "prefill_tok_s": None,
450                     "aggregate_output_tok_s": None, "answer_window_s": None,
451                     "aggregate_window_s": None}
452            snapshot = {**snapshot, "rates": rates}
453        if frozen:
454            short = {"connecting": "CONNECT", "connected": "", "stale": "STALE",
455                     "auth_required": "AUTH", "incompatible": "SCHEMA",
456                     "disconnected": "OFFLINE", "telemetry_unavailable": "NO METRICS"}[state]
457            marker = f"[FROZEN/{short}]" if short else "[FROZEN]"
458        else:
459            marker = f"[{labels[state]}]"
460    lines = [f"STRATA  {view.title():<10} {safe(connection, max(0, width - 42))} {marker}"]
461    if tiny:       # a small window: the tabs (names kept, the selected one marked) and, under them, the keys that matter
462        lines += [nav.plain(VIEWS.index(view), width, connect), f"{nav.keys(connect)} views  q quit  ? help"[:width]]
463    else:
464        quit_hint = "  q quit"
465        tab_line = nav.plain(VIEWS.index(view), width - len(quit_hint), connect) if width < 80 else nav.plain(VIEWS.index(view), width, connect)
466        lines += [tab_line + (quit_hint if width < 80 else ""), "-" * min(width, 100)]
467    if connection_state in ("connecting", "disconnected", "auth_required", "incompatible"):
468        title, message, action = {
469            "connecting": ("CONNECTING", "Waiting for the first telemetry snapshot.",
470                           "The monitor will update automatically."),
471            "disconnected": ("CONNECTION LOST", "Strata is not responding.",
472                             "Retrying automatically; press r now."),
473            "auth_required": ("AUTHORIZATION REQUIRED", "The telemetry credential was rejected.",
474                              "Update the saved connection; press r."),
475            "incompatible": ("INCOMPATIBLE SERVER", "This telemetry schema is unsupported.",
476                             "Connect to a compatible server; press r."),
477        }[connection_state]
478        last_seen = (f"Last snapshot {number(age, ' s', 1)} ago" if age is not None and age >= 0
479                     else "No telemetry snapshot available")
480        lines += [title, message, action, last_seen]
481        if tiny:
482            lines = lines[:height - 1] + ["More: strata status --json"]
483        return "\n".join(_line(line, width) for line in lines[:height])
484    if connection_state is not None and (state != "connected" or frozen):
485        lines.append(f"Sample age {number(age, ' s', 1)}  |  Source {safe(snapshot.get('source'))}")
486    if (snapshot.get("quality") or {}).get("telemetry") == "unavailable":
487        lines.append("Telemetry unavailable; status only")
488    if width < 70 or height < 20:
489        lines += [_line(f"Model {safe(model.get('id'), width-17)} {model_state}", width),
490                  f"In flight {number(work.get('active'))}  Slots {number(work.get('occupied_slots'))}/{number(work.get('slots_effective'))}",
491                  f"Engine waiting {number(work.get('waiting'))}  Pre-admit {number(work.get('queued'))}"]
492        if not tiny:
493            lines.append(f"Answer {number(rates.get('answer_tok_s'), ' tok/s', 1)}  GPUs {len(devices) or '--'}")
494        if view == "requests":
495            live, done = request_rows(snapshot, filter_text)
496            rows = [("LIVE", row) for row in live] + [("DONE", row) for row in done]
497            if rows:
498                index = min(max(0, selected), len(rows) - 1)
499                kind, row = rows[index]
500                label = row.get("id") or (f"#{index - len(live) + 1}" if kind == "DONE" else None)
501                lines.append(f"{index + 1}/{len(rows)} {kind} {safe(label, 12)}")
502                if kind == "DONE":
503                    lines += [f"{safe(row.get('finish'), 10)} out {number(row.get('output_tokens'))}  {number(row.get('duration_s'), ' s', 1)}"]
504                    if detail:
505                        lines += [f"Prompt {number(row.get('prompt_tokens'))}  cached {number(row.get('reused'))}",
506                                  f"Engine first {number(row.get('first_engine_token_s'), ' s', 2)}"]
507                else:
508                    lines += [f"slot {number(row.get('slot'))} group {number(row.get('group'))} {_request_work(row)}"]
509                    if detail:
510                        lines += [f"Prompt {number(row.get('prompt_tokens'))} tokens",
511                                  f"Wait {number(_queue_wait(row, sampled), ' s', 1)}  Engine first {number(row.get('first_engine_token_s'), ' s', 2)}"]
512            else:
513                lines += [no_requests_text(filter_text)]
514        elif view == "serving":
515            optional = [_batch_window(work, width), _stage_in_flight(work, width)]
516            if not tiny:
517                lines += optional
518            live, _ = request_rows(snapshot, filter_text)
519            rows = (work.get("slots") or []) if serving_pane == "groups" else \
520                   devices if serving_pane == "devices" else live
521            if rows:
522                index = min(max(0, selected), len(rows) - 1)
523                row = rows[index]
524                lines.append(f"{serving_pane.title()} {index + 1}/{len(rows)}")
525                if serving_pane == "devices":
526                    lines.append(_device(row, width))
527                    if detail:
528                        lines += [f"VRAM {number(row.get('mem_used') / 2**30 if isinstance(row.get('mem_used'), (int, float)) else None, ' GiB', 1)}",
529                                  f"Util {number(row.get('util'), '%')}  Temp {number(row.get('temp'), ' C')}  Power {number(row.get('power'), ' W')}",
530                                  _device_stage(topology, row.get("index"), width)]
531                else:
532                    lines += [f"{safe(row.get('id') or row.get('request_id'), 12)} {safe(row.get('state'), 10)}",
533                              f"slot {number(row.get('slot'))} group {number(row.get('group'))} {_request_work(row)}"]
534                    if detail and serving_pane == "requests":
535                        lines += [f"Prompt {number(row.get('prompt_tokens'))} tokens",
536                                  f"Wait {number(_queue_wait(row, sampled), ' s', 1)}  Engine first {number(row.get('first_engine_token_s'), ' s', 2)}"]
537                    elif detail and serving_pane == "groups":
538                        lines += [f"Held {number(row.get('held_tokens'))}  Read {number(row.get('prompt_read'))}  Out {number(row.get('generated'))}",
539                                  f"Elapsed {number(row.get('elapsed_s'), ' s', 1)}  Rate {number(row.get('tok_s'), ' tok/s', 1)}"]
540            else:
541                lines += [f"{serving_pane.title()} unavailable"]
542            if tiny:
543                lines += optional
544        elif view == "hardware":
545            if devices:
546                index = min(max(0, selected), len(devices) - 1)
547                row = devices[index]
548                lines += [f"Device {index + 1}/{len(devices)}", _device(row, width)]
549                if detail:
550                    lines += [f"Temp {number(row.get('temp'), ' C')}  Power {number(row.get('power'), ' W')}",
551                              _device_stage(topology, row.get("index"), width)]
552            else:
553                lines.append("Per-device sensors unavailable")
554        elif view == "engine":
555            lines += [_batch_window(work, width), _stage_in_flight(work, width)]
556        elif view == "logs":
557            activity = snapshot.get("activity") or {}
558            if not activity.get("available"):
559                lines += ["Request activity unavailable on this server"]
560            else:
561                events = activity_rows(snapshot, filter_text)
562                lines += ["Recent request activity (redacted)"]
563                notice = activity_continuity_notice(snapshot)
564                if notice:
565                    lines.append(notice)
566                lines += [activity_label(row, width) for row in events[-max(1, height - len(lines) - 1):]] \
567                    if events else ["No request transitions retained"]
568        else:
569            if not tiny:
570                lines += ["More: strata status --json"]
571        if tiny:
572            lines = lines[:height - 1] + ["More: strata status --json"]
573        return "\n".join(_line(x, width) for x in lines[:height])
574    lines += [f"Model {safe(model.get('id'), max(10, width-30))}  {model_state}",
575              f"In flight {number(work.get('active'))}   Slots occupied {number(work.get('occupied_slots'))}/{number(work.get('slots_effective'))}   Engine waiting {number(work.get('waiting'))}   Pre-admit {number(work.get('queued'))}"]
576    if view == "serving" and width >= 100 and height >= 24 and serving_pane == "devices" and not detail:
577        return _wide_serving(lines, snapshot, width, height, filter_text, selected, connect)
578    if view == "overview":
579        lines += [f"Answer speed  {number(rates.get('answer_tok_s'), ' tok/s', 1)} [engine, {number(rates.get('answer_window_s'), ' s', 1)} window]",
580                  f"Prompt reading {number(rates.get('prefill_tok_s'), ' tok/s', 1)} [reported mean]",
581                  f"First engine token {number(recent[0].get('first_engine_token_s') if recent else None, ' s', 3)} [last completed, since queue entry]",
582                  f"Completed     {number(totals.get('requests'))} [server lifetime]",
583                  "", "Hardware"]
584        lines += [_device(d, width) for d in devices[:4]] or ["Per-device readings unavailable"]
585        lines += ["", "Recent requests (finished; identities unavailable in legacy telemetry)"]
586        for i, r in enumerate(recent[:max(1, height-len(lines)-3)]):
587            lines.append(_line(f"#{i+1:<3} {field(r.get('finish'), 13)} in {number(r.get('prompt_tokens')):<8} out {number(r.get('output_tokens')):<8} {number(r.get('duration_s'), ' s', 1)}", width))
588    elif view == "serving":
589        lines += [f"Topology {safe(topology.get('mode'))}  Devices {number(len(devices))}  Groups {number(work.get('groups'))}",
590                  f"Slots requested {number(work.get('slots_requested'))} / effective {number(work.get('slots_effective'))}",
591                  f"Admission {number(work.get('admission_reserved'))}/{number(work.get('admission_limit'))}  Cap {number(work.get('max_queue'))}  Rejected {number(work.get('admission_rejected'))}",
592                  f"Wait limit {number(work.get('queue_timeout_s'), 's', 1)}  Timed out {number(work.get('queue_timeouts'))}  Oldest {number(work.get('oldest_queue_s'), 's', 1)}",
593                  f"Disconnect cancels {number(work.get('client_disconnect_cancels'))}  Output {number(rates.get('aggregate_output_tok_s'), ' tok/s', 1)} [common sample]",
594                  _batch_window(work, width)]
595        if work.get("stage_in_flight") or work.get("replica_stage_samples"):
596            lines.append(_stage_in_flight(work, width))
597        lines.append(f"Pane: {serving_pane.title()}   Tab switches Devices / Requests / Groups")
598        if not detail and serving_pane == "requests":
599            lines.insert(-1, f"First engine token {number(recent[0].get('first_engine_token_s') if recent else None, ' s', 3)} [last completed, since queue entry]")
600        if not work.get("stage_in_flight") and not (detail and serving_pane == "requests"):
601            lines.append("")
602        if serving_pane == "requests":
603            rows = [r for r in (work.get("requests") or []) if not filter_text or
604                    filter_text.lower() in (safe(r.get("id")) + " " + safe(r.get("state")) + " live").lower()]
605            capacity = max(1, height - len(lines) - (10 if detail and rows else 4))
606            start = min(max(0, selected - capacity // 2), max(0, len(rows) - capacity))
607            lines += [f"Requests {start + 1 if rows else 0}-{min(start + capacity, len(rows))} of {len(rows)}  (Up/Down scroll; wait is queue time)"]
608            for i, row in enumerate(rows[start:start + capacity], start):
609                wait = _queue_wait(row, sampled)
610                cursor = ">" if i == selected else " "
611                lines.append(_line(f"{cursor}{field(row.get('id'), 12)} {_replica_short(row)}s{number(row.get('slot')):<3} g{number(row.get('group')):<3} {field(row.get('state'), 9)} wait {number(wait, ' s', 1):<8} {_request_work(row)}", width))
612            if not rows:
613                lines.append("Request correlation unavailable")
614            elif detail:
615                lines += _request_detail(rows[min(selected, len(rows) - 1)], sampled, width)
616        elif serving_pane == "groups":
617            rows = work.get("slots") or []
618            capacity = max(1, height - len(lines) - (10 if detail else 4))
619            start = min(max(0, selected - capacity // 2), max(0, len(rows) - capacity))
620            scope = "replica / pipeline group" if str(topology.get("mode") or "").startswith("replicas") else "pipeline group"
621            lines += [f"Slot / {scope} {start + 1 if rows else 0}-{min(start + capacity, len(rows))} of {len(rows)}  (occupancy is not rows/window)"]
622            for i, row in enumerate(rows[start:start + capacity], start):
623                cursor = ">" if i == selected else " "
624                lines.append(_line(f"{cursor}{_replica_short(row)}slot {number(row.get('slot')):<3} group {number(row.get('group')):<3} {field(row.get('state'), 11)} req {field(row.get('request_id'), 12)} in {number(row.get('prompt_tokens')):<7} {_request_work(row)} {number(row.get('tok_s'), ' tok/s', 1)}", width))
625            if not rows:
626                lines.append("Slot detail unavailable")
627            elif detail:
628                lines += _slot_detail(rows[min(max(0, selected), len(rows) - 1)], width)
629        else:
630            lines += ["Per-card sensors; each request stays within one replica" if
631                      str(topology.get("mode") or "").startswith("replicas") else
632                      "Per-card sensors; requests traverse all stages" if topology.get("resolved") is True
633                      else "Stage/layer mapping unavailable; groups are not GPU assignments"]
634            if devices:
635                capacity = max(1, height - len(lines) - (11 if detail else 4))
636                index, start, end = _row_window(devices, selected, capacity)
637                lines.append(f"Devices {start + 1}-{end} of {len(devices)}  (Up/Down scroll; Enter detail)")
638                for i in range(start, end):
639                    lines.append(_line(("> " if i == index else "  ") + _device(devices[i], width - 2), width))
640                if detail:
641                    lines += _device_detail(devices[index], topology, width)
642            else:
643                lines.append("Per-device readings unavailable")
644    elif view == "requests":
645        active, shown = request_rows(snapshot, filter_text)
646        rows = [("LIVE", row) for row in active] + [("DONE", row) for row in shown]
647        lines += [f"Live {len(active)}  /  recent {len(shown)}   No prompt bodies" + (f"   Filter: {safe(filter_text, 20)}  (Esc clears)" if filter_text else ""), ""]
648        if rows:
649            index = min(max(0, selected), len(rows) - 1)
650            capacity = max(1, height - len(lines) - (10 if detail else 4))
651            start = min(max(0, index - capacity // 2), max(0, len(rows) - capacity))
652            lines.append(f"Requests {start + 1}-{min(start + capacity, len(rows))} of {len(rows)}  (Up/Down scroll; Enter detail)")
653            for i in range(start, min(start + capacity, len(rows))):
654                kind, row = rows[i]
655                cursor = ">" if i == index else " "
656                if kind == "LIVE":
657                    summary = f"{field(row.get('id'), 12)} {field(row.get('state'), 11)} s{number(row.get('slot')):<3} g{number(row.get('group')):<3} in {number(row.get('prompt_tokens')):<7} {_request_work(row)}"
658                else:
659                    summary = f"{field(row.get('id') or f'#{i - len(active) + 1}', 12)} {field(row.get('finish'), 11)} in {number(row.get('prompt_tokens')):<7} cached {number(row.get('reused')):<7} out {number(row.get('output_tokens')):<7} {number(row.get('duration_s'), ' s', 1)}"
660                lines.append(_line(f"{cursor} {kind:<4} {summary}", width))
661            if detail:
662                kind, row = rows[index]
663                lines += (_request_detail(row, sampled, width) if kind == "LIVE" else _recent_detail(row, width))
664        else:
665            lines.append(no_requests_text(filter_text))
666    elif view == "engine":
667        lines += [f"Context capacity {number(model.get('context'), ' tokens')}",
668                  f"Batch groups {number(work.get('groups'))}",
669                  _batch_window(work, width)]
670        if work.get("stage_in_flight") or work.get("replica_stage_samples"):
671            lines.append(_stage_in_flight(work, width))
672        lines += [f"Answer rate {number(rates.get('answer_tok_s'), ' tok/s', 1)} [engine window]",
673                  f"Prompt rate {number(rates.get('prefill_tok_s'), ' tok/s', 1)} [engine reported]", ""]
674        if topology.get("replica_stages"):
675            lines.append("Replica layers [engine log]; in-flight [host span]; groups are not GPU assignments")
676            sampled_replicas = {row["replica"]: {stage["stage"]: stage
677                                for stage in row.get("stage_in_flight") or []}
678                                for row in work.get("replica_stage_samples") or []}
679            sample_meta = {row["replica"]: row for row in work.get("replica_stage_samples") or []}
680            for entry in topology["replica_stages"]:
681                meta = sample_meta.get(entry["replica"], {})
682                if meta.get("stage_in_flight"):
683                    lines.append(_line(f"R{entry['replica']} host sample "
684                                       f"{number(meta.get('stage_sample_span_s'), 's', 1)} span, "
685                                       f"{number(meta.get('stage_sample_age_s'), 's', 1)} old", width))
686                if not entry["stages"]:
687                    lines.append(f"R{entry['replica']} stage ranges unavailable")
688                for stage in entry["stages"]:
689                    sample = sampled_replicas.get(entry["replica"], {}).get(stage["stage"])
690                    lines.append(_line(f"R{entry['replica']} Stage {number(stage.get('stage'))}  "
691                                       f"Device {number(stage.get('device_index'))}  "
692                                       f"Layers {number(stage.get('layer_start'))}-{number(stage.get('layer_end'))}  "
693                                       f"In-flight {number(sample.get('percent') if sample else None, '%', 0)}", width))
694        elif topology.get("stages"):
695            lines.append("Layer allocation [engine start log]; stage in-flight [host scheduling]")
696            sampled = {row["stage"]: row for row in work.get("stage_in_flight") or []}
697            for stage in topology["stages"]:
698                row = sampled.get(stage.get("stage"))
699                lines.append(_line(f"Stage {number(stage.get('stage'))}  Engine GPU {number(stage.get('engine_ordinal'))}  Device {number(stage.get('device_index'))}  Layers {number(stage.get('layer_start'))}-{number(stage.get('layer_end'))}  In-flight {number(row.get('percent') if row else None, '%', 0)}", width))
700        else:
701            lines.append("Stage/layer mapping unavailable")
702        lines.append("In-flight includes host poll delay; GPU kernel occupancy unavailable" if
703                     work.get("stage_in_flight") or any(row.get("stage_in_flight") for row in
704                     work.get("replica_stage_samples") or [])
705                     else "Live stage in-flight and GPU kernel occupancy unavailable")
706    elif view == "hardware":
707        lines += ["Device sensors; missing measurements are shown as --", ""]
708        if devices:
709            capacity = max(1, height - len(lines) - (10 if detail else 6))
710            index, start, end = _row_window(devices, selected, capacity)
711            lines.append(f"Devices {start + 1}-{end} of {len(devices)}  (Up/Down scroll; Enter detail)")
712            for i in range(start, end):
713                lines.append(_line(("> " if i == index else "  ") + _device(devices[i], width - 2), width))
714            if detail:
715                lines += _device_detail(devices[index], topology, width)
716        else:
717            lines.append("No per-device sensor readings")
718        ram = snapshot.get("ram") or {}
719        used, total = ram.get("used"), ram.get("total")
720        lines += ["", f"RAM {number(used / 2**30 if isinstance(used, (int, float)) else None, ' GiB', 1)} / {number(total / 2**30 if isinstance(total, (int, float)) else None, ' GiB', 1)}"]
721    else:
722        activity = snapshot.get("activity") or {}
723        lines += ["Recent request activity (redacted; no prompt or tool content)", ""]
724        if not activity.get("available"):
725            lines.append("Request activity unavailable on this server")
726        else:
727            events = activity_rows(snapshot, filter_text)
728            last_seq = activity.get("last_seq")
729            retained = len(activity.get("events") or [])
730            older = " | older omitted" if isinstance(last_seq, int) and last_seq > retained else ""
731            lines.append(f"Recent {len(events)}/{retained} retained | sequence {number(last_seq)}{older}")
732            notice = activity_continuity_notice(snapshot)
733            if notice:
734                lines.append(notice)
735            if events:
736                capacity = max(1, height - len(lines) - 4)
737                lines += [activity_label(row, width) for row in events[-capacity:]]
738            else:
739                lines.append("No matching request transitions" if filter_text else "No request transitions retained")
740    if not detail:
741        lines.append("")
742    lines += [f"Sample age {number(age, ' s', 1)}   Source {safe(snapshot.get('source'))}",
743              f"{nav.keys(connect)} views  / filter  Space freeze  r refresh  t theme  ? help  q quit"]
744    return "\n".join(_line(x, width) for x in lines[:height])