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
49.2 KiB915 linesraw
1"""Rich, read-only overview for the interactive monitor.
2
3The layout follows YASD's one-screen dashboard idea while using Strata's
4bounded telemetry contract and theme. No server text is treated as markup.
5"""
6
7from __future__ import annotations
8
9import math
10import time
11from collections import deque
12from typing import Any
13
14from rich import box
15from rich.align import Align
16from rich.console import Group
17from rich.panel import Panel
18from rich.table import Table
19from rich.text import Text
20
21from strata_cli import nav
22from strata_cli.client import complete_slots
23from strata_cli.render import (_queue_wait, activity_continuity_notice, activity_label, display_width,
24                               field, group_occupancy, number, safe)
25
26
27WORK_SAMPLE_MAX_AGE_S = 5.0
28
29
30_ASCII_BOXES = False
31
32
33def _rounded():
34    """Panel corners: rounded where the font has them, square (Consolas has these) in the classic Windows console."""
35    return box.SQUARE if _ASCII_BOXES else box.ROUNDED
36
37
38def set_ascii_boxes(on: bool) -> None:
39    global _ASCII_BOXES
40    _ASCII_BOXES = bool(on)
41
42
43def _current_sample(row: dict, age_key: str) -> bool:
44    """A retained engine sample stops representing current work after five seconds."""
45    age = row.get(age_key)
46    return (isinstance(age, (int, float)) and not isinstance(age, bool) and
47            math.isfinite(age) and 0 <= age <= WORK_SAMPLE_MAX_AGE_S)
48
49
50def _current_batch_value(row: dict, key: str) -> Any:
51    return row.get(key) if _current_sample(row, "batch_sample_age_s") else None
52
53
54class MonitorHistory:
55    """Small display-only device history, reset when the server changes."""
56
57    def __init__(self, limit: int = 32):
58        self.limit = limit
59        self.instance: tuple[str, str] | None = None
60        self.device_util: dict[int, deque[float | None]] = {}
61        self.device_vram: dict[int, deque[float | None]] = {}
62        self.output_rate: deque[float | None] = deque(maxlen=limit)
63        self.prefill_rate: deque[float | None] = deque(maxlen=limit)
64        self.answer_rate: deque[float | None] = deque(maxlen=limit)
65        self.batch_rows: deque[float | None] = deque(maxlen=limit)
66        self.pre_admit: deque[float | None] = deque(maxlen=limit)
67        self.replica_batch_rows: dict[int, deque[float | None]] = {}
68
69    @staticmethod
70    def _sample(value: Any) -> float | None:
71        return (float(value) if isinstance(value, (int, float)) and not isinstance(value, bool)
72                and math.isfinite(value) and 0 <= value <= 1_000_000_000 else None)
73
74    def gap(self) -> None:
75        """Keep an outage visible between samples from the same instance."""
76        self.output_rate.append(None)
77        self.prefill_rate.append(None)
78        self.answer_rate.append(None)
79        self.batch_rows.append(None)
80        self.pre_admit.append(None)
81        for series in (*self.device_util.values(), *self.device_vram.values(),
82                       *self.replica_batch_rows.values()):
83            series.append(None)
84
85    def add(self, snapshot: dict, instance: tuple[str, str] | None) -> None:
86        if instance != self.instance:
87            self.device_util.clear()
88            self.device_vram.clear()
89            self.output_rate.clear()
90            self.prefill_rate.clear()
91            self.answer_rate.clear()
92            self.batch_rows.clear()
93            self.pre_admit.clear()
94            self.replica_batch_rows.clear()
95            self.instance = instance
96        value = (snapshot.get("rates") or {}).get("aggregate_output_tok_s")
97        self.output_rate.append(self._sample(value))
98        self.prefill_rate.append(self._sample((snapshot.get("rates") or {}).get("prefill_tok_s")))
99        self.answer_rate.append(self._sample((snapshot.get("rates") or {}).get("answer_tok_s")))
100        work = snapshot.get("work") or {}
101        self.batch_rows.append(self._sample(_current_batch_value(work, "effective_rows_window")))
102        self.pre_admit.append(self._sample(work.get("queued")))
103        replica_rows = work.get("replica_batches") or []
104        reported: dict[int, dict] = {}
105        ambiguous: set[int] = set()
106        for row in (replica_rows if isinstance(replica_rows, list) else [])[:16]:
107            if not isinstance(row, dict):
108                continue
109            replica = row.get("replica")
110            if type(replica) is not int or not 0 <= replica < 16:
111                continue
112            if replica in reported:
113                ambiguous.add(replica)
114            reported[replica] = row
115        topology = snapshot.get("topology") or {}
116        configured = {row.get("replica") for row in (topology.get("replica_devices") or [])[:16]
117                      if isinstance(row, dict) and type(row.get("replica")) is int and
118                      0 <= row["replica"] < 16}
119        current_replicas = configured or set(reported)
120        self.replica_batch_rows = {
121            replica: self.replica_batch_rows.get(replica, deque(maxlen=self.limit))
122            for replica in current_replicas
123        }
124        for replica, series in self.replica_batch_rows.items():
125            row = reported.get(replica, {}) if replica not in ambiguous else {}
126            series.append(self._sample(_current_batch_value(row, "effective_rows_window")))
127        reported: dict[int, dict] = {}
128        ambiguous: set[int] = set()
129        devices = snapshot.get("devices")
130        for row in (devices if isinstance(devices, list) else [])[:16]:
131            if not isinstance(row, dict):
132                continue
133            index = row.get("index")
134            if type(index) is not int or not 0 <= index <= 65535:
135                continue
136            if index in reported:
137                ambiguous.add(index)
138            reported[index] = row
139        topology = snapshot.get("topology") or {}
140        selected = topology.get("selected_devices")
141        selected = selected if isinstance(selected, list) else []
142        indices = list(dict.fromkeys(index for index in selected[:16]
143                                     if type(index) is int and 0 <= index <= 65535))
144        if not indices:
145            indices = list(reported)
146        self.device_util = {index: self.device_util.get(index, deque(maxlen=self.limit))
147                            for index in indices}
148        self.device_vram = {index: self.device_vram.get(index, deque(maxlen=self.limit))
149                            for index in indices}
150        for index in indices:
151            row = reported.get(index) if index not in ambiguous else None
152            value = row.get("util") if row else None
153            if not isinstance(value, (int, float)) or isinstance(value, bool) or not math.isfinite(value):
154                value = None
155            self.device_util[index].append(value)
156            used, total = (row.get("mem_used"), row.get("mem_total")) if row else (None, None)
157            if (not all(isinstance(item, (int, float)) and not isinstance(item, bool) and
158                        math.isfinite(item) for item in (used, total)) or
159                    total <= 0 or used < 0 or used > total):
160                vram = None
161            else:
162                vram = 100.0 * (used / total)
163            self.device_vram[index].append(vram)
164
165
166def _spark(values: Any, glyphs: str, width: int = 8) -> str:
167    samples = list(values or [])[-(width * 2 if glyphs == "braille" else width):]
168    if not samples or all(value is None for value in samples):
169        return "--"
170    if glyphs != "braille":
171        ramp = ".:-=+*#@" if glyphs == "ascii" else "▁▂▃▄▅▆▇█"
172        return "".join(" " if value is None else ramp[min(7, max(0, int(value / 100 * 7)))]
173                       for value in samples)
174    # Braille has two columns and four rows per cell. A cell represents two
175    # consecutive utilization samples, with the newest sample at the right.
176    left, right = (0x40, 0x04, 0x02, 0x01), (0x80, 0x20, 0x10, 0x08)
177    if len(samples) % 2:
178        samples.insert(0, None)
179    graph = []
180    for first, second in zip(samples[::2], samples[1::2]):
181        bits = 0
182        for value, dots in ((first, left), (second, right)):
183            if value is not None:
184                level = max(1, min(4, round(value / 100 * 4)))
185                bits |= sum(dots[:level])
186        graph.append(chr(0x2800 + bits) if bits else " ")
187    return "".join(graph)
188
189
190def _output_trend(values: Any, glyphs: str, compact: bool) -> str:
191    width = 6 if compact else 8
192    samples = list(values or [])[-width * (2 if glyphs == "braille" else 1):]
193    valid = [value for value in samples if value is not None]
194    label = "Output" if compact else "Output trend"
195    if len(valid) < 2 or samples[-1] is None:
196        return f"{label}  --"
197    low, high = min(valid), max(valid)
198    scaled = [None if value is None else
199              0 if high == 0 else 50 if high == low else 100 * (value - low) / (high - low)
200              for value in samples]
201    graph = _spark(scaled, glyphs, width)
202    span = f"{low:.3g}" if high == low else f"{low:.3g}-{high:.3g}"
203    return f"{label}  {graph}  {span} tok/s"
204
205
206def _work_trend(values: Any, glyphs: str, label: str, unit: str, digits: int = 0) -> str | None:
207    """Show the range of displayed samples; never turn missing work into zero."""
208    width = 8
209    samples = list(values or [])[-width * (2 if glyphs == "braille" else 1):]
210    valid = [value for value in samples if value is not None]
211    if len(valid) < 2 or samples[-1] is None:
212        return None
213    low, high = min(valid), max(valid)
214    scaled = [None if value is None else
215              0 if high == 0 else 50 if high == low else 100 * (value - low) / (high - low)
216              for value in samples]
217    span = number(low, "", digits)
218    if high != low:
219        span += "-" + number(high, "", digits)
220    return f"{label}  {_spark(scaled, glyphs, width)}  {span}{unit}"
221
222
223def _panel(lines: list[str], title: str, accent: str, *, color: bool) -> Panel:
224    body = Text("\n".join(lines), no_wrap=True, overflow="crop")
225    if color:
226        body.highlight_regex(r"\b(?:READY|LIVE|GENERATING|READING)\b", accent)
227        body.highlight_regex(r"\b(?:STALE|FROZEN|QUEUED|DRAINING)\b", "yellow")
228        body.highlight_regex(r"\b(?:DISCONNECTED|INCOMPATIBLE|REJECTED|AUTH REQUIRED)\b", "red")
229        body.highlight_regex(r"[\u2800-\u28ff▁▂▃▄▅▆▇█]+", accent)
230    return Panel(body, title=Text(title, style=f"bold {accent}" if color else "bold"),
231                 border_style="dim" if color else "", box=_rounded(), padding=(0, 1))
232
233
234def _columns(left: list[Panel], right: list[Panel]) -> Table:
235    """Keep the YASD-style metric stack beside hardware and request activity."""
236    grid = Table.grid(expand=True, padding=(0, 1))
237    grid.add_column(ratio=3)
238    grid.add_column(ratio=4)
239    grid.add_row(Group(*left), Group(*right))
240    return grid
241
242
243def _state(snapshot: dict, connection_state: str, frozen: bool) -> tuple[str, bool]:
244    age = _age(snapshot)
245    telemetry = (snapshot.get("quality") or {}).get("telemetry")
246    state = ("NO TELEMETRY" if telemetry == "unavailable" and connection_state == "connected" else
247             {"connected": "LIVE", "connecting": "CONNECTING", "stale": "STALE",
248              "disconnected": "DISCONNECTED", "auth_required": "AUTH REQUIRED",
249              "incompatible": "INCOMPATIBLE", "telemetry_unavailable": "NO TELEMETRY"}
250             .get(connection_state, "STALE"))
251    if state == "LIVE" and (age is None or age > 5 or age < -5):
252        state = "STALE"
253    if state == "LIVE" and (snapshot.get("model") or {}).get("loaded") is False:
254        state = "SLEEPING"
255    return (f"FROZEN / {state}" if frozen else state), state == "LIVE"
256
257
258def _prompt_progress(work: dict, compact: bool, glyphs: str) -> str | None:
259    for row in work.get("requests") or []:
260        if row.get("state") != "reading":
261            continue
262        done, total = row.get("prompt_read"), row.get("prompt_tokens")
263        if any(not isinstance(value, (int, float)) or isinstance(value, bool) or
264               not math.isfinite(value) for value in (done, total)) or total <= 0 or done < 0:
265            continue
266        size = 6 if compact else 8
267        filled = min(size, max(0, round(done / total * size)))
268        full, empty = ("#", ".") if glyphs == "ascii" else ("█", "░")
269        prefix = "Read" if compact else f"Reading {safe(row.get('id'), 11)}"
270        return f"{prefix}  {number(done)}/{number(total)}  [{full * filled}{empty * (size - filled)}]"
271    return None
272
273
274def _age(snapshot: dict) -> float | None:
275    sampled = snapshot.get("sampled_at")
276    if not isinstance(sampled, (int, float)) or isinstance(sampled, bool) or not math.isfinite(sampled):
277        return None
278    return time.time() - sampled
279
280
281def _gib(value: Any) -> str:
282    if not isinstance(value, (int, float)) or isinstance(value, bool):
283        return "--"
284    return number(value / 2**30, "", 1)
285
286
287def _groups(work: dict, compact: bool, glyphs: str) -> list[str]:
288    occupancy = group_occupancy(work)
289    if occupancy is None:
290        return ["Group occupancy --"]
291    owner_sets: dict[int, set[int | None]] = {}
292    for row in complete_slots(work) or []:
293        group = row.get("group")
294        if type(group) is int:
295            replica = row.get("replica")
296            owner_sets.setdefault(group, set()).add(replica if type(replica) is int else None)
297    owners = {group: next(iter(values)) for group, values in owner_sets.items() if len(values) == 1}
298    def label(group: int) -> str:
299        replica = owners.get(group)
300        return f"R{replica} G{group}" if replica is not None else f"G{group}"
301    labels = [f"{label(group)} {busy}/{total}"
302              for group, (busy, total) in sorted(occupancy.items())]
303    if compact:
304        lines = ["  ".join(labels[:2]), "  ".join(labels[2:4])] if len(labels) > 2 else ["  ".join(labels)]
305        if len(labels) > 4:
306            lines.append(f"+{len(labels) - 4} groups; press 2")
307        return lines
308    full, empty = ("#", ".") if glyphs == "ascii" else ("█", "░")
309    lines = ["Pipeline groups · occupied slots" if glyphs != "ascii" else "Pipeline groups / occupied slots"]
310    for group, (busy, total) in sorted(occupancy.items())[:5]:
311        bar = full * min(busy, 8) + empty * min(max(0, total - busy), 8)
312        lines.append(f"{label(group):<6} {bar}  {busy}/{total} slots")
313    if len(occupancy) > 5:
314        lines.append(f"+{len(occupancy) - 5} groups; press 2")
315    return lines
316
317
318def _replica_batch_line(work: dict, compact: bool) -> str:
319    """Each replica reports its own batch window; there is no cross-replica average."""
320    rows = sorted(work.get("replica_batches") or [], key=lambda row: row["replica"])
321    if not rows:
322        return "Batch rows -- across replicas" if compact else "Rows/window -- across replicas"
323    shown = rows[:2]
324    if compact:
325        text = "Proc/win " + " ".join(
326            f"R{row['replica']} {number(_current_batch_value(row, 'effective_rows_window'), '', 1)}" for row in shown)
327    else:
328        text = "Rows/win p/a " + "  ".join(
329            f"R{row['replica']} {number(_current_batch_value(row, 'effective_rows_window'), '', 1)}/"
330            f"{number(_current_batch_value(row, 'batch_active_rows_window'), '', 1)}" for row in shown)
331    return text + (f" +{len(rows) - 2}" if len(rows) > 2 else "")
332
333
334def _slot_phases(work: dict, compact: bool) -> str | None:
335    """Summarize slot states only when the complete effective slot set is present."""
336    slots = complete_slots(work)
337    if slots is None:
338        return None
339    counts = {"reading": 0, "decoding": 0, "idle": 0}
340    for row in slots:
341        counts[row["state"]] += 1
342    prefix = "Slot phases" if not compact else "Phases"
343    return (f"{prefix}  read {counts['reading']}  decode {counts['decoding']}  "
344            f"idle {counts['idle']}")
345
346
347def _hardware(snapshot: dict, history: MonitorHistory, glyphs: str, compact: bool) -> list[str]:
348    devices = snapshot.get("devices") or []
349    topology = snapshot.get("topology") or {}
350    selected = [index for index in topology.get("selected_devices") or []
351                if type(index) is int and index >= 0]
352    selected = list(dict.fromkeys(selected))
353    if selected:
354        reported = {}
355        ambiguous = set()
356        for row in devices:
357            index = row.get("index")
358            if type(index) is not int or index < 0:
359                continue
360            if index in reported:
361                ambiguous.add(index)
362            reported[index] = row
363        rows = [(reported[index], True) if index in reported and index not in ambiguous
364                else ({"index": index}, False) for index in selected]
365    else:
366        rows = [(row, True) for row in devices]
367    if not rows:
368        return ["Per-device readings unavailable"]
369    stages = (topology.get("stages") or []) if topology.get("resolved") is True else []
370    mapped = {row.get("device_index"): row.get("stage") for row in stages}
371    replica_map = {device: row.get("replica") for row in topology.get("replica_devices") or []
372                   for device in row.get("devices") or []}
373    replica_stages: dict[int, list[tuple[int, int]]] = {}
374    for entry in topology.get("replica_stages") or []:
375        replica = entry.get("replica")
376        for stage in entry.get("stages") or []:
377            device = stage.get("device_index")
378            stage_id = stage.get("stage")
379            if (type(device) is int and type(replica) is int and type(stage_id) is int and
380                    0 <= replica < 16 and 0 <= stage_id < 16 and replica_map.get(device) == replica):
381                replica_stages.setdefault(device, []).append((replica, stage_id))
382    lines = []
383    for row, sensor_present in rows[:4]:
384        index = row.get("index")
385        label = f"GPU {number(index)}"
386        local_stages = replica_stages.get(index) or []
387        stage = (f"R{local_stages[0][0]}/S{local_stages[0][1]}" if len(local_stages) == 1 else
388                 f"R{number(replica_map[index])}" if index in replica_map else
389                 f"S{number(mapped[index])}" if index in mapped else "S--")
390        memory = field(f"{_gib(row.get('mem_used'))}/{_gib(row.get('mem_total'))}G", 13)
391        graph = (_spark(history.device_util.get(index), glyphs, 6 if compact else 8)
392                 if sensor_present else "--")
393        vram_graph = (_spark(history.device_vram.get(index), glyphs, 6)
394                      if sensor_present else "--")
395        if compact:
396            lines.append(f"{label:<5} {stage:<5} {memory:<11} {number(row.get('util'), '%'):>4} {graph}")
397        else:
398            lines.append(f"{label:<5} {stage:<5} {field(row.get('name'), 18)} {memory}  vram {vram_graph}")
399            lines.append(f"      load {number(row.get('util'), '%'):>4}  temp {number(row.get('temp'), 'C'):>4}  "
400                         f"power {number(row.get('power'), 'W'):>5}  {graph}")
401    if len(rows) > 4:
402        lines.append(f"+{len(rows) - 4} {'selected ' if selected else ''}devices; press 5 for all")
403    return lines
404
405
406def _request_lines(snapshot: dict, compact: bool, filter_text: str, *, tall: bool = False) -> list[str]:
407    work = snapshot.get("work") or {}
408    needle = filter_text.lower()
409    live = [row for row in (work.get("requests") or []) if not needle or
410            needle in (safe(row.get("id")) + safe(row.get("state"))).lower()]
411    lines = []
412    limit = 2 if compact else 12 if tall else 4
413    queued = [row for row in live if row.get("state") == "queued"]
414    admitted = [row for row in live if row.get("slot") is None and row.get("state") != "queued"]
415    running = [row for row in live if row.get("slot") is not None]
416    preferred = ((queued[:1] + running[:1]) if compact else
417                 (queued[:2] + admitted[:1] + running[:1]))
418    chosen = []
419    seen = set()
420    for row in preferred + live:
421        if id(row) not in seen:
422            chosen.append(row)
423            seen.add(id(row))
424        if len(chosen) == limit:
425            break
426    for row in chosen:
427        wait = _queue_wait(row, snapshot.get("sampled_at"))
428        state = safe(row.get("state"), 9)
429        state_column = field(row.get("state"), 7 if compact else 9)
430        work_label = (f"wait {number(wait, 's', 1)}" if state == "queued" else
431                      "awaiting slot" if row.get("slot") is None else
432                      f"read {number(row.get('prompt_read'))}" if state == "reading" else
433                      f"out {number(row.get('generated'))}")
434        replica = f"r{row['replica']} " if type(row.get("replica")) is int else ""
435        if compact:
436            if state == "queued":
437                lines.append(f"{field(row.get('id'), 9)} {state_column} {work_label}")
438            else:
439                lines.append(f"{field(row.get('id'), 9)} {state_column} "
440                             f"{replica}s{number(row.get('slot'))} g{number(row.get('group'))} {work_label}")
441        else:
442            lines.append(f"{field(row.get('id'), 12)} {state_column} "
443                         f"{replica}s{number(row.get('slot'))} g{number(row.get('group'))}  {work_label}")
444    if len(live) > limit:
445        lines.append(f"+{len(live) - limit} more; press 3 for all")
446    if not lines:
447        slots = [row for row in work.get("slots") or [] if row.get("state") != "idle"]
448        if slots:
449            lines = [f"{('R' + str(row['replica']) + '  ') if type(row.get('replica')) is int else ''}"
450                     f"Slot {number(row.get('slot'))}  G{number(row.get('group'))}  "
451                     f"{safe(row.get('state'), 12)}  {number(row.get('generated'))} out"
452                     for row in slots[:limit]]
453            lines.insert(0, "Request identities unavailable")
454        else:
455            lines = ["No active requests"]
456    return lines
457
458
459def _activity(snapshot: dict, compact: bool, filter_text: str) -> list[str]:
460    activity = snapshot.get("activity") or {}
461    if not activity.get("available"):
462        return ["Request activity unavailable"]
463    notice = activity_continuity_notice(snapshot)
464    needle = filter_text.lower()
465    rows = [row for row in activity.get("events") or [] if isinstance(row, dict) and
466            (not needle or needle in (safe(row.get("event")) + safe(row.get("request_id"))).lower())]
467    if not rows:
468        return ([notice] if notice else []) + ["No matching transitions" if needle else "No recent transitions"]
469    if compact:
470        return ([notice] if notice else []) + [f"{field(row.get('request_id'), 10)} "
471                f"{safe(row.get('event'), 18)}" for row in rows[-(1 if notice else 2):]]
472    return ([notice] if notice else []) + [activity_label(row, 48) for row in rows[-(3 if notice else 4):]]
473
474
475_DIGITS = {
476    "0": (" ███ ", "█   █", "█   █", "█   █", " ███ "),
477    "1": ("  █  ", " ██  ", "  █  ", "  █  ", " ███ "),
478    "2": (" ███ ", "█   █", "   █ ", "  █  ", "█████"),
479    "3": ("████ ", "    █", " ███ ", "    █", "████ "),
480    "4": ("█   █", "█   █", "█████", "    █", "    █"),
481    "5": ("█████", "█    ", "████ ", "    █", "████ "),
482    "6": (" ███ ", "█    ", "████ ", "█   █", " ███ "),
483    "7": ("█████", "    █", "   █ ", "  █  ", " █   "),
484    "8": (" ███ ", "█   █", " ███ ", "█   █", " ███ "),
485    "9": (" ███ ", "█   █", " ████", "    █", " ███ "),
486    ".": ("  ", "  ", "  ", "██", "██"),
487    ",": ("   ", "   ", "   ", " ██", " █ "),
488    "-": ("     ", "     ", "█████", "     ", "     "),
489}
490
491
492def _big_rate(value: Any, color: str, glyphs: str) -> list[Text]:
493    """Legible five-row numerals; the exact value is repeated in plain text."""
494    label = number(value, "", 1) if value is not None else "--"
495    if glyphs == "ascii":
496        return [Text(label + " tok/s", style=f"bold {color}")]
497    if len(label) > 9:
498        return [Text(label + " tok/s", style=f"bold {color}")]
499    return [Text(" ".join(_DIGITS.get(char, ("     ",) * 5)[row]
500                          for char in label), style=f"bold {color}", no_wrap=True)
501            for row in range(5)]
502
503
504def _meter(value: Any, total: Any, size: int, glyphs: str) -> str:
505    valid = (all(isinstance(item, (int, float)) and not isinstance(item, bool) and
506                 math.isfinite(item) for item in (value, total)) and total > 0 and 0 <= value <= total)
507    if not valid:
508        return "[" + ("?" * size) + "]"
509    filled = max(0, min(size, round(value / total * size)))
510    on, off = ("#", ".") if glyphs == "ascii" else ("█", "░")
511    return "[" + on * filled + off * (size - filled) + "]"
512
513
514def _visual_panel(lines: list[Text], title: str, accent: str, color: bool,
515                  height: int | None = None) -> Panel:
516    return Panel(Group(*lines), title=Text(title, style=f"bold {accent}" if color else "bold"),
517                 border_style="dim" if color else "", box=box.SQUARE, padding=(0, 1),
518                 height=height)
519
520
521def _visual_pair(left: Panel, right: Panel, left_ratio: int = 3, right_ratio: int = 4) -> Table:
522    grid = Table.grid(expand=True, padding=(0, 1))
523    grid.add_column(ratio=left_ratio)
524    grid.add_column(ratio=right_ratio)
525    grid.add_row(left, right)
526    return grid
527
528
529def _visual_overview(snapshot: dict, history: MonitorHistory, *, width: int, height: int,
530                     header: Panel, footer: Text, live: bool, glyphs: str, color: bool,
531                     theme: str, filter_text: str) -> Group:
532    """Wide monitor: rate, cards, context, slot concurrency and live requests."""
533    cyan = ("#087b9a" if theme == "light" else "#22d3ee") if color else "default"
534    green = ("#0c8a60" if theme == "light" else "#34d399") if color else "default"
535    amber = ("#946000" if theme == "light" else "#fbbf24") if color else "default"
536    violet = ("#7842af" if theme == "light" else "#a78bfa") if color else "default"
537    dim = "dim" if color else ""
538    model, work, rates = (snapshot.get("model") or {}, snapshot.get("work") or {},
539                          snapshot.get("rates") or {})
540    topology = snapshot.get("topology") or {}
541    slots = complete_slots(work)
542    output = rates.get("aggregate_output_tok_s") if live else None
543    prefill = rates.get("prefill_tok_s") if live else None
544    answer = rates.get("answer_tok_s") if live else None
545    hero = [Text(f"{safe(model.get('id'), 35)}   "
546                 f"{number(work.get('active'))} active  ·  {number(work.get('queued'))} pre-admit",
547                 style=dim, no_wrap=True)]
548    hero.extend(_big_rate(output, cyan, glyphs))
549    hero.append(Text(f"{number(output, '', 1)} tok/s  ·  ALL REQUESTS",
550                     style=f"bold {cyan}" if color else "bold"))
551    hero.append(Text(f"PROMPT {number(prefill, '', 1)} tok/s     "
552                     f"ANSWER {number(answer, '', 1)} tok/s", no_wrap=True))
553    hero.append(Text(_output_trend(history.output_rate if live else (), glyphs, False), style=dim))
554    hero.append(Text(f"Prefill  {_rate_spark(history.prefill_rate if live else (), glyphs)}     "
555                     f"Answer  {_rate_spark(history.answer_rate if live else (), glyphs)}", style=dim))
556    while len(hero) < 9:
557        hero.append(Text(""))
558
559    devices = snapshot.get("devices") or []
560    selected = [index for index in topology.get("selected_devices") or [] if type(index) is int and index >= 0]
561    selected = list(dict.fromkeys(selected))
562    reported: dict[int, dict] = {}
563    ambiguous: set[int] = set()
564    for row in devices:
565        index = row.get("index")
566        if type(index) is int and index >= 0:
567            if index in reported:
568                ambiguous.add(index)
569            reported[index] = row
570    indices = selected or list(reported)
571    gpu_lines: list[Text] = []
572    for index in indices[:4]:
573        row = reported.get(index, {}) if index not in ambiguous else {}
574        stage = _device_role(index, topology)
575        util = row.get("util") if live else None
576        used = row.get("mem_used") if live else None
577        total = row.get("mem_total") if live else None
578        gpu_lines.append(Text(f"GPU {index} {stage:<5} {field(row.get('name'), 19)} "
579                              f"load {number(util, '%'):>4}  "
580                              f"{number(row.get('power') if live else None, 'W'):>5}  "
581                              f"{number(row.get('temp') if live else None, 'C'):>4}", no_wrap=True))
582        gpu_lines.append(Text(f"   {_meter(util, 100, 16, glyphs)}  "
583                              f"VRAM {_meter(used, total, 12, glyphs)} "
584                              f"{_gib(used)}/{_gib(total)}G  "
585                              f"{_spark(history.device_util.get(index) if live else (), glyphs, 6)}",
586                              style=green if color else "", no_wrap=True))
587    if not gpu_lines:
588        gpu_lines.append(Text("Per-device sensors unavailable", style=dim))
589    if len(indices) > 4:
590        gpu_lines.append(Text(f"+{len(indices) - 4} selected cards · press 5", style=dim))
591    while len(gpu_lines) < 9:
592        gpu_lines.append(Text(""))
593
594    context = model.get("context")
595    held = [row.get("held_tokens") for row in (slots or []) if live
596            if row.get("state") != "idle" and
597            isinstance(row.get("held_tokens"), (int, float)) and
598            not isinstance(row.get("held_tokens"), bool) and
599            math.isfinite(row["held_tokens"]) and row["held_tokens"] >= 0]
600    # A complete all-idle slot map establishes zero active context. An active
601    # slot with a missing held-token reading still remains unavailable.
602    max_held = (max(held) if held else
603                0 if live and slots is not None and all(row.get("state") == "idle" for row in slots)
604                else None)
605    context_lines = [Text(f"CAPACITY {number(context)} tokens / slot     "
606                          f"MAX ACTIVE HELD {number(max_held)}", no_wrap=True),
607                     Text(_meter(max_held, context, max(12, min(80, width - 8)), glyphs),
608                          style=violet if color else "", no_wrap=True),
609                     Text(f"Slots {number(work.get('occupied_slots'))}/{number(work.get('slots_effective'))} "
610                          f"occupied  ·  wait {number(work.get('waiting'))}  ·  "
611                          f"queue {number(work.get('queued'))}  ·  "
612                          f"rows/window {number(_current_batch_value(work, 'effective_rows_window'), '', 1)} "
613                          f"processed / {number(_current_batch_value(work, 'batch_active_rows_window'), '', 1)} active",
614                          no_wrap=True)]
615    if work.get("replica_batches"):
616        context_lines.append(Text(_replica_batch_line(work, False), style=dim))
617    else:
618        context_lines.append(Text("Held is the largest active slot cache; groups are not GPU lanes.", style=dim))
619
620    slot_lines: list[Text] = []
621    if slots is None:
622        slot_lines.append(Text("Complete slot map unavailable", style=dim))
623    else:
624        grouped: dict[tuple[int | None, int | None], list[dict]] = {}
625        for row in slots:
626            key = (row.get("replica") if type(row.get("replica")) is int else None,
627                   row.get("group") if type(row.get("group")) is int else None)
628            grouped.setdefault(key, []).append(row)
629        for (replica, group), rows in sorted(grouped.items(), key=lambda item: (
630                -1 if item[0][0] is None else item[0][0],
631                -1 if item[0][1] is None else item[0][1]))[:10]:
632            label = f"R{replica} " if replica is not None else ""
633            label += f"G{group}" if group is not None else "G--"
634            line = Text(f"{label:<7} ", no_wrap=True)
635            for row in rows[:8]:
636                state = {"reading": "P", "decoding": "D", "idle": "·"}.get(row.get("state"), "?")
637                tint = (amber if state == "P" else green if state == "D" else dim)
638                line.append(f"[{number(row.get('slot')):>2} {state}] ", style=tint if color else "")
639            if len(rows) > 8:
640                line.append(f"+{len(rows) - 8}", style=dim)
641            slot_lines.append(line)
642        if len(grouped) > 10:
643            slot_lines.append(Text(f"+{len(grouped) - 10} groups · press 2", style=dim))
644    slot_lines.insert(0, Text("P prefill   D decode   · idle   |   engine slots", style=dim))
645    slot_lines.append(Text(f"{_slot_phases(work, False) or 'Slot phases unavailable'}", style=dim))
646    slot_lines.append(Text(_replica_batch_line(work, False) if work.get("replica_batches") else
647                           f"Oldest queue {number(work.get('oldest_queue_s'), 's', 1)}  ·  "
648                           f"admission {number(work.get('admission_reserved'))}/"
649                           f"{number(work.get('admission_limit'))}", style=dim))
650    active_slots = [row for row in slots or [] if row.get("state") != "idle"]
651    if active_slots:
652        slot_lines.append(Text("ACTIVE CONTEXTS  ·  held / capacity", style=dim))
653        for row in active_slots[:max(1, min(8, height - 32))]:
654            held_tokens = row.get("held_tokens") if live else None
655            slot_lines.append(Text(f"S{number(row.get('slot')):<3} "
656                                   f"{_meter(held_tokens, context, 10, glyphs)}  "
657                                   f"{number(held_tokens)}/{number(context)} tokens  "
658                                   f"{number(row.get('tok_s') if live else None, '', 1)} t/s",
659                                   style=green if color else "", no_wrap=True))
660        if len(active_slots) > max(1, min(8, height - 32)):
661            slot_lines.append(Text(f"+{len(active_slots) - max(1, min(8, height - 32))} slots · press 2",
662                                   style=dim))
663
664    needle = filter_text.lower()
665    requests = [row for row in work.get("requests") or [] if not needle or
666                needle in (safe(row.get("id")) + safe(row.get("state"))).lower()]
667    requests.sort(key=lambda row: (row.get("state") != "queued", row.get("slot") is None,
668                                   row.get("slot") if type(row.get("slot")) is int else 999))
669    slot_rates = {(row.get("slot"), row.get("request_id")): row.get("tok_s")
670                  for row in slots or [] if row.get("request_id") is not None}
671    narrow_requests = width < 138
672    req_lines = [Text("ID         STATE    SLOT   PROMPT    OUT    t/s   1ST ENGINE" if narrow_requests else
673                      "ID           STATE      ROUTE     PROMPT      OUT  SLOT t/s  1ST ENGINE",
674                      style=dim)]
675    limit = max(5, min(15, height - 28))
676    for row in requests[:limit]:
677        route = (f"R{row['replica']}/" if type(row.get("replica")) is int else "")
678        route += (f"S{row['slot']}" if type(row.get("slot")) is int else "--")
679        prompt_read = row.get("prompt_read")
680        prompt_total = row.get("prompt_tokens")
681        prompt_label = (f"{number(prompt_read)}/{number(prompt_total)}" if row.get("state") == "reading" else
682                        number(prompt_total))
683        first = number(row.get("first_engine_token_s"), "s", 2)
684        if row.get("state") == "queued":
685            first = f"wait {number(_queue_wait(row, snapshot.get('sampled_at')), 's', 1)}"
686        slot_rate = slot_rates.get((row.get("slot"), row.get("id"))) if live else None
687        state = safe(row.get("state"), 10)
688        tint = amber if state == "reading" else green if state == "decoding" else violet
689        if narrow_requests:
690            request_text = (f"{field(row.get('id'), 10)} {state:<8} {route:<6} "
691                            f"{prompt_label:<9} {number(row.get('generated')):>4}  "
692                            f"{number(slot_rate, '', 1):>5}  {first}")
693        else:
694            request_text = (f"{field(row.get('id'), 12)} {state:<10} {route:<9} "
695                            f"{prompt_label:<11} {number(row.get('generated')):>4}  "
696                            f"{number(slot_rate, '', 1):>7}   {first}")
697        req_lines.append(Text(request_text, style=tint if color else "", no_wrap=True))
698    if len(requests) > limit:
699        req_lines.append(Text(f"+{len(requests) - limit} more · press 3", style=dim))
700    if not requests:
701        req_lines.append(Text("No active requests" if work.get("requests") is not None else
702                              "Request identities unavailable", style=dim))
703    if work.get("requests_omitted"):
704        req_lines.append(Text(f"{number(work.get('requests_omitted'))} additional rows omitted by server", style=dim))
705    lower_rows = max(len(slot_lines), len(req_lines))
706    slot_lines.extend(Text("") for _ in range(lower_rows - len(slot_lines)))
707    req_lines.extend(Text("") for _ in range(lower_rows - len(req_lines)))
708
709    top = _visual_pair(_visual_panel(hero, "THROUGHPUT", cyan, color),
710                       _visual_panel(gpu_lines, f"GPUS · {len(indices)} "
711                                     f"{'selected' if selected else 'reported'}", green, color))
712    middle = _visual_panel(context_lines, "CONTEXT / BATCHING", violet, color)
713    lower_height = max(lower_rows + 2, height - 23)
714    lower = _visual_pair(_visual_panel(slot_lines, "PARALLEL SLOTS", amber, color,
715                                      height=lower_height),
716                         _visual_panel(req_lines, f"REQUESTS · {len(requests)} visible", green, color,
717                                       height=lower_height), 3, 4)
718    return Group(header, top, middle, lower, footer)
719
720
721def _rate_spark(values: Any, glyphs: str) -> str:
722    samples = list(values or [])[-(16 if glyphs == "braille" else 8):]
723    valid = [value for value in samples if value is not None]
724    if len(valid) < 2 or samples[-1] is None:
725        return "--"
726    low, high = min(valid), max(valid)
727    scaled = [None if value is None else (50 if high == low else 100 * (value - low) / (high - low))
728              for value in samples]
729    return _spark(scaled, glyphs, 8)
730
731
732def _device_role(index: int, topology: dict) -> str:
733    for replica in topology.get("replica_devices") or []:
734        if index in replica.get("devices", []):
735            return f"R{number(replica.get('replica'))}"
736    if topology.get("resolved"):
737        for stage in topology.get("stages") or []:
738            if stage.get("device_index") == index:
739                return f"S{number(stage.get('stage'))}"
740    return ""
741
742
743def render_dashboard(snapshot: dict, *, width: int, height: int, history: MonitorHistory,
744                     connection: str = "", connection_state: str = "connected", frozen: bool = False,
745                     filter_text: str = "", glyphs: str = "ascii", color: bool = True,
746                     theme: str = "dark", connect: bool = False) -> Group:
747    """Compose the primary one-screen monitor at standard terminal sizes.
748
749    Smaller terminals retain the existing compact text renderer in MonitorApp.
750    """
751    set_ascii_boxes(glyphs == "ascii")
752    compact = width < 100 or height < 27
753    accent = ("#0c8a60" if theme == "light" else "#34d399") if color else "default"
754    danger = ("#b01a2e" if theme == "light" else "#ff8a98") if color else "default"
755    danger_border = ("#e0283f" if theme == "light" else "#ff5a6e") if color else "default"
756    model, instance = snapshot.get("model") or {}, snapshot.get("instance") or {}
757    work, rates = snapshot.get("work") or {}, snapshot.get("rates") or {}
758    topology = snapshot.get("topology") or {}
759    recent = snapshot.get("recent") or []
760    state, live = _state(snapshot, connection_state, frozen)
761    model_state = ("DRAINING" if instance.get("state") == "draining" else
762                   "READY" if model.get("loaded") is True else
763                   "NO MODEL LOADED" if model.get("loaded") is False else "UNKNOWN")
764    heading = Text()
765    heading.append("STRATA  /  MONITOR", style=f"bold {accent}")
766    heading.append("   ")
767    heading.append(state, style=(f"bold {accent}" if state == "LIVE" else
768                                 "bold yellow" if state in ("SLEEPING", "STALE", "CONNECTING") else
769                                 f"bold {danger}" if state in ("DISCONNECTED", "AUTH REQUIRED", "INCOMPATIBLE") else
770                                 "bold"))
771    heading.append(f"   {safe(connection, max(0, width - 45))}")
772    blocked = connection_state in ("disconnected", "auth_required", "incompatible")
773    header = Panel(heading, box=_rounded(),
774                   border_style=danger_border if blocked else accent, padding=(0, 1))
775
776    if connection_state in ("connecting", "disconnected", "auth_required", "incompatible"):
777        title, message, action = {
778            "connecting": ("CONNECTING", "Waiting for the first Strata telemetry snapshot.",
779                           "The monitor will update automatically."),
780            "disconnected": ("CONNECTION LOST", "The Strata server is not responding.",
781                             "Retrying automatically; press r to retry now."),
782            "auth_required": ("AUTHORIZATION REQUIRED", "The telemetry credential was rejected.",
783                              "Update the saved monitor connection, then press r."),
784            "incompatible": ("INCOMPATIBLE SERVER", "This telemetry schema is unsupported.",
785                             "Connect to a compatible Strata server, then press r."),
786        }[connection_state]
787        age = _age(snapshot)
788        last_seen = (f"Last snapshot {number(age, 's', 1)} ago" if age is not None and age >= 0 else
789                     "No telemetry snapshot available")
790        lines = Group(Text(title, style=f"bold {danger}" if blocked else f"bold {accent}"),
791                      Text(message), Text(action, style="dim"), Text(last_seen, style="dim"))
792        panel = Panel(Align.center(lines, vertical="middle"),
793                      title=Text("CONNECTION", style=f"bold {danger}" if blocked else f"bold {accent}"),
794                      border_style=danger_border if blocked else "dim", box=_rounded(),
795                      height=max(8, height - 4))
796        return Group(header, panel, Text(f"r Retry   q Detach   {nav.keys(connect)} Views", style="dim"))
797
798    model_name = safe(model.get("id"), 80)
799    if compact and display_width(model_name) > 19:
800        model_name = safe(model_name, 18) + "…"
801    else:
802        model_name = safe(model_name, 19 if compact else 35)
803    serving = [f"Model  {model_name}",
804               (f"State  {model_state}  {number(work.get('active'))} active" if compact else
805                f"State  {model_state}  |  {number(work.get('active'))} in flight"),
806               (f"Queue  {number(work.get('waiting'))} engine  {number(work.get('queued'))} pre-admit" if compact else
807                f"Queue  {number(work.get('waiting'))} engine  /  {number(work.get('queued'))} pre-admit")]
808    progress = _prompt_progress(work, compact, glyphs) if live else None
809    if progress:
810        serving.append(progress)
811    telemetry_unavailable = (snapshot.get("quality") or {}).get("telemetry") == "unavailable"
812    answer = number(rates.get('answer_tok_s') if live else None, '', 1)
813    prompt = number(rates.get('prefill_tok_s') if live else None, '', 1)
814    aggregate = number(rates.get('aggregate_output_tok_s') if live else None, ' tok/s', 1)
815    performance = ([f"P {prompt}  A {answer} tok/s", f"All {aggregate} server"] if compact else
816                   [f"Prompt {prompt}  Answer {answer} tok/s", f"Aggregate {aggregate} server"])
817    performance.append(_output_trend(history.output_rate if live else (), glyphs, compact))
818
819    batch = [f"Slots {number(work.get('occupied_slots'))}/{number(work.get('slots_effective'))}  "
820             f"req {number(work.get('slots_requested'))}  groups {number(work.get('groups'))}",
821             f"Rows/win {number(_current_batch_value(work, 'effective_rows_window'), '', 1)} processed  "
822             f"{number(_current_batch_value(work, 'batch_active_rows_window'), '', 1)} active",
823             f"Admit {number(work.get('admission_reserved'))}/{number(work.get('admission_limit'))}  "
824             f"oldest {number(work.get('oldest_queue_s'), 's', 1)}  "
825             f"reject {number(work.get('admission_rejected'))}"]
826    replica_ids = {row.get("replica") for row in complete_slots(work) or []
827                   if type(row.get("replica")) is int}
828    replica_count = max(len(replica_ids), len(topology.get("replica_devices") or []),
829                        len(work.get("replica_batches") or []))
830    if replica_count:
831        batch[0] = (f"Slots {number(work.get('occupied_slots'))}/{number(work.get('slots_effective'))}  "
832                    f"| requested {number(work.get('slots_requested'))}  | replicas {replica_count}")
833        batch[1] = _replica_batch_line(work, compact=False)
834    if compact:
835        batch[0] = (f"Slots {number(work.get('occupied_slots'))}/{number(work.get('slots_effective'))}  "
836                    f"{'replicas ' + str(replica_count) if replica_count else 'groups ' + number(work.get('groups'))}")
837        batch[1] = (_replica_batch_line(work, compact=True) if replica_count else
838                    f"Batch rows {number(_current_batch_value(work, 'effective_rows_window'), '', 1)}  "
839                    f"active {number(_current_batch_value(work, 'batch_active_rows_window'), '', 1)}")
840        batch[2] = (f"Admit {number(work.get('admission_reserved'))}/{number(work.get('admission_limit'))}  "
841                    f"oldest {number(work.get('oldest_queue_s'), 's', 1)}")
842    phases = _slot_phases(work, compact)
843    if phases:
844        batch.append(phases.replace("Phases  ", "") if compact else phases)
845    batch += _groups(work, compact, glyphs)
846    if not compact:
847        stages = (work.get("stage_in_flight") or []) if _current_sample(work, "stage_sample_age_s") else []
848        replica_samples = work.get("replica_stage_samples") or []
849        if replica_samples:
850            for row in replica_samples[:2]:
851                samples = (row.get("stage_in_flight") or []) if _current_sample(row, "stage_sample_age_s") else []
852                batch.append(f"Host span R{row['replica']} " + ("  ".join(
853                    f"S{number(stage.get('stage'))} {number(stage.get('percent'), '%')}"
854                    for stage in samples) + f"  age {number(row.get('stage_sample_age_s'), 's', 1)}"
855                    if samples else "--"))
856            if len(replica_samples) > 2:
857                batch.append(f"+{len(replica_samples) - 2} replicas; see Engine")
858        else:
859            batch.append(("Host span " + "  ".join(f"S{number(row.get('stage'))}/"
860                          f"{number(row.get('percent'), '%')}" for row in stages)) if stages else
861                         "Stage host span --")
862        if live:
863            if replica_count:
864                trends = [_work_trend(history.replica_batch_rows.get(replica), glyphs,
865                                      f"R{replica} rows", "/win", 1)
866                          for replica in sorted(history.replica_batch_rows)[:2]]
867            else:
868                trends = [_work_trend(history.batch_rows, glyphs, "Rows trend", "/win", 1),
869                          _work_trend(history.pre_admit, glyphs, "Pre-admit", " req")]
870            detail_rows = 10 if width >= 100 and height >= 40 else 0
871            used_rows = (3 + 1 + len(serving) + 2 + len(performance) + 2 +
872                         len(batch) + 2 + detail_rows)
873            batch.extend([trend for trend in trends if trend][:max(0, height + 1 - used_rows)])
874
875    hardware = _hardware(snapshot, history, glyphs, compact)
876    ram = snapshot.get("ram") or {}
877    if isinstance(ram.get("used"), (int, float)) and isinstance(ram.get("total"), (int, float)):
878        hardware.append(f"RAM {_gib(ram['used'])}/{_gib(ram['total'])} GiB")
879    hardware.append(("Each request stays in one replica" if replica_count else "Groups are not GPU lanes") if compact else
880                    ("Per-card sensors; replicas serve independently" if replica_count else
881                     "Per-card sensors; requests cross all stages"))
882    requests = _request_lines(snapshot, compact, filter_text, tall=height >= 40)
883    activity = _activity(snapshot, compact, filter_text)
884    age = _age(snapshot)
885    age_text = f"age {number(age, 's', 1)}"
886    footer = Text(nav.plain(0, max(20, width - len(age_text) - 4), connect) + "    " + age_text, style="dim")
887    if width >= 126 and height >= 34:
888        return _visual_overview(snapshot, history, width=width, height=height,
889                                header=header, footer=footer, live=live, glyphs=glyphs,
890                                color=color, theme=theme, filter_text=filter_text)
891    left_sections = [(serving, "SERVING"), (performance, "PERFORMANCE"),
892                     (batch, "BATCHING / PARALLEL")]
893    if width >= 100 and height >= 40:
894        totals = snapshot.get("totals") or {}
895        left_sections.extend([
896            ([f"Completed {number(totals.get('requests'))}  [server lifetime]",
897              f"Prompt {number(totals.get('prompt_tokens'))} tokens",
898              f"Output {number(totals.get('output_tokens'))} tokens"], "SESSION"),
899            ([f"Context {number(model.get('context'))} tokens",
900              f"Topology {safe(topology.get('mode'), 26)}",
901              f"Last engine token {number(recent[0].get('first_engine_token_s') if recent else None, 's', 3)}"],
902             "ENGINE"),
903        ])
904    right_sections = [(hardware, "HARDWARE"), (requests, "REQUESTS"),
905                      (activity, "ACTIVITY")]
906    panel_rows = max(sum(len(lines) + 2 for lines, _ in left_sections),
907                     sum(len(lines) + 2 for lines, _ in right_sections))
908    # Textual reserves its final row for the read-only message. Keep this
909    # navigation row next to it when a tall terminal has spare space.
910    filler = max(0, min(200, height + 1 - (3 + int(telemetry_unavailable) + panel_rows + 1)))
911    return Group(header, *([Text("Telemetry unavailable; status only", style="yellow" if color else "")]
912                           if telemetry_unavailable else []),
913                 _columns([_panel(lines, title, accent, color=color) for lines, title in left_sections],
914                          [_panel(lines, title, accent, color=color) for lines, title in right_sections]),
915                 *[Text(" ") for _ in range(filler)], footer)