okami.mom/strata

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

Niko1221Merge f-0213-qafix into f-0213-int64b48c0d0

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