diff --git a/meshterm/tools/dashboard.py b/meshterm/tools/dashboard.py index 551af1c..f06b63c 100644 --- a/meshterm/tools/dashboard.py +++ b/meshterm/tools/dashboard.py @@ -2,9 +2,10 @@ Opens the full-screen dashboard (see :mod:`meshterm.ui.dashboard_screen`): the two-hour all-packet activity chart with its pulse line, the session's traffic tallies by packet -class, the window's RF health beside the radio's own live numbers, and the streaming -packet feed. It leads the Mesh section because it answers the section's first question — -*what's going on out there?* — before any specific tool is reached for. +class, and the window's RF health beside the radio's own live numbers. (The per-packet +stream is the Live feed tool, right below.) It leads the Mesh section because it answers +the section's first question — *what's going on out there?* — before any specific tool +is reached for. Menu-only: the dashboard is inherently live (it rides the event hub and repaints every second), so there is no scripted one-shot to register — the ``monitor`` and ``nodes`` @@ -23,12 +24,12 @@ from .base import Tool, ToolResult, register @register class DashboardTool(Tool): - """Watch everything going on on the mesh: activity, traffic, RF health, feed.""" + """Watch everything going on on the mesh: activity, traffic, RF health.""" name = "dashboard" title = "Dashboard" icon = "📊" - help = "Watch the mesh live — activity, traffic, RF health, packet feed" + help = "Watch the mesh live — activity, traffic, RF health" category = "Mesh" order = 5 # the section's overview, above the tools it summarizes diff --git a/meshterm/tools/livefeed.py b/meshterm/tools/livefeed.py new file mode 100644 index 0000000..3530da3 --- /dev/null +++ b/meshterm/tools/livefeed.py @@ -0,0 +1,71 @@ +"""The ``livefeed`` tool: every packet as it arrives, right under the dashboard. + +Opens the full-screen live feed (see :mod:`meshterm.ui.livefeed_screen`): the +streaming packet list that used to be the dashboard's bottom panel, promoted to its +own menu entry — newest first, every class, Enter opening any row in the shared +packet viewer. It sits directly under the dashboard because the two split one +question between them: the dashboard summarizes *what's going on out there*, the +feed shows every individual packet behind those numbers. + +Menu-only: the feed is inherently live (it rides the event hub and repaints every +second), so there is no scripted one-shot to register — the ``monitor`` subcommand +covers scripted packet-watching. +""" + +from __future__ import annotations + +from typing import Any, Optional + +import typer + +from ..context import AppContext +from .base import Tool, ToolResult, register + + +@register +class LiveFeedTool(Tool): + """Watch every packet stream in, newest first, and open any in the viewer.""" + + name = "livefeed" + title = "Live feed" + icon = "📰" + help = "Every packet as it arrives, newest first — open any in the viewer" + category = "Mesh" + order = 6 # right under the dashboard it was promoted out of + + async def prompt_params(self, ctx: AppContext) -> Optional[dict[str, Any]]: + """Run the live feed; there are never parameters to collect. + + The screen presents everything itself and returns when dismissed, so + returning ``None`` tells the menu the invocation is complete (the same + pattern as the ``dashboard`` tool). + + Args: + ctx: Shared application context. + + Returns: + Always ``None``. + """ + from ..ui.livefeed_screen import open_livefeed + + await open_livefeed(ctx) + return None + + async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: + """Nothing runs here: the feed lives inside :meth:`prompt_params`. + + Args: + ctx: Shared application context. + params: Unused. + + Returns: + An empty :class:`ToolResult` (only reachable from a scripted call). + """ + return ToolResult(summary={}) + + def register_cli(self, app: typer.Typer) -> None: + """Register no CLI command — the feed is a live, menu-only screen. + + Args: + app: The Typer application (untouched). + """ diff --git a/meshterm/ui/dashboard_screen.py b/meshterm/ui/dashboard_screen.py index 7711b0d..17a518f 100644 --- a/meshterm/ui/dashboard_screen.py +++ b/meshterm/ui/dashboard_screen.py @@ -1,7 +1,7 @@ """The live mesh dashboard: everything going on around this node, on one screen. The interactive face of the ``dashboard`` tool. One full-screen, always-repainting view -stacks four reads of the mesh, coarsest first: +stacks three reads of the mesh, coarsest first: * **Activity** — a tall braille bar chart of *every* packet the hub hears (adverts, telemetry, RX-logged packets, messages, acks), one dot column per minute — braille's @@ -17,20 +17,14 @@ stacks four reads of the mesh, coarsest first: tool's quality bar) and RSSI from stored observations, plus the radio's own live numbers — noise floor, last RSSI/SNR, airtime, battery — polled from the device the way Device info reads them. -* **Feed** — the latest packets, newest first: time, class (icon + label, icon alone - on a narrow terminal), node, SNR/RSSI. Seeded from stored history so the screen - opens full, then streamed live off the event hub. The feed scrolls *within* the - screen — the charts above hold still, faint ``↑/↓ n more`` markers bracket its - window — with ``↑``/``↓`` walking the rows and Enter opening the highlighted - packet in the shared :class:`~meshterm.ui.packet_viewer.PacketViewer` — which - then pages through the feed itself with the same ``↑``/``↓``, and, for an - overheard channel-text packet naming a channel we hold the key for, decrypts it. + +The per-packet stream that used to close this screen is now its own tool — the Live +feed (see :mod:`meshterm.ui.livefeed_screen`), right under the dashboard in the menu — +so this screen is pure overview: it scrolls as one body under the arrow/page keys. The screen holds no subscriptions of its own — the opener (:func:`open_dashboard`) wires the hub subscription, the device-stats poll, and the once-a-second repaint, and -tears them all down when the screen resolves. The newest packet is highlighted from the -moment the screen opens; PgUp/PgDn/Home/End walk that highlight, and Esc backs out -directly. +tears them all down when the screen resolves. Esc backs out directly. """ from __future__ import annotations @@ -38,31 +32,21 @@ from __future__ import annotations import asyncio from collections import Counter, deque from statistics import median -from typing import TYPE_CHECKING, Any, Optional, Sequence +from typing import TYPE_CHECKING, Any, Optional from rich.console import Group, RenderableType from rich.table import Table from rich.text import Text -from ..core.channels import split_channel_sender -from ..core.events import EventKind, MeshEvent +from ..core.events import MeshEvent from ..core.models import NODE_TYPE_REPEATER, Observation, utcnow from ..persistence.repository import OBSERVATION_WINDOW from .braillechart import axis_chart, meter, timeline_rows -from .menus import fit_cells -from .widgets import TypeOf, path_text -from .packet_viewer import ( - KIND_STYLES, - PacketEntry, - PacketViewer, - kind_icon, - node_label, - payload_class, -) -from .theme import name_style, snr_style +from .packet_viewer import KIND_STYLES +from .theme import snr_style from .trace_screen import snr_bar -from .tui.render import render_lines, render_to_ansi -from .tui.screen import ListWindow, Screen +from .tui.render import render_lines +from .tui.screen import Screen if TYPE_CHECKING: from ..context import AppContext @@ -73,13 +57,6 @@ _REFRESH_S = 1.0 #: Seconds between polls of the device's own statistics (noise floor, airtime, battery). _STATS_POLL_S = 10.0 -#: How many feed rows are kept (the feed windows within the screen, so this is -#: history depth, not layout). -_FEED_CAP = 100 - -#: The feed's fixed node-name lane width; longer names ellipsize so the columns hold. -_FEED_NAME_WIDTH = 18 - #: How many braille rows tall the activity chart draws (each row is four dot rows). _CHART_ROWS = 3 @@ -89,26 +66,11 @@ _KIND_ORDER = ("advert", "telemetry", "packet", "message", "ack") #: How many character cells a traffic lane's meter spans (48 half-step levels). _TRAFFIC_METER_CELLS = 24 -#: Terminal width below which the feed drops the textual kind label and keeps only -#: the two-cell icon, buying the name and reception lanes room (≤72-col care). -_FEED_LABEL_MIN_WIDTH = 76 - #: The label column every hanging-indent section grid reserves (the ``snr `` / #: ``radio `` lane), so wrapped values align with their own block, never column 0. _GRID_LABEL_W = 9 -def _channel_sender(text: Optional[str]) -> Optional[str]: - """The sender named by a channel message's ``Name: `` prefix, or ``None`` if absent. - - The shared protocol-layer parse (see - :func:`~meshterm.core.channels.split_channel_sender`), so the feed's node lane names - exactly the sender the chat transcript would. - """ - name, _body = split_channel_sender(text or "") - return name - - def _span_label(minutes: int) -> str: """A compact duration — ``45 min`` under two hours, else ``2.5 h`` / ``3 h``.""" if minutes < 120: @@ -121,7 +83,7 @@ class DashboardScreen(Screen): """The live mesh overview. Renders state and scrolls; the opener feeds it.""" floating = False - footer_hint = "↑↓ packets · Enter open · PgUp/PgDn/Home/End scroll · Esc back" + footer_hint = "↑↓ PgUp/PgDn scroll · Esc back" def __init__( self, @@ -132,30 +94,17 @@ class DashboardScreen(Screen): activity: Any, activity_flags: Any, kind_counts: Any, - hub_active: Any, - prefix_bytes: int = 0, - self_name: Optional[str] = None, - channels: Sequence[tuple[str, bytes]] = (), - type_of: Optional[TypeOf] = None, ) -> None: """Create the dashboard over its data feeds. Args: - session: The running TUI session (for repaints and the packet viewer). + session: The running TUI session (for repaints). resolve: Maps a node hash to a friendly contact name when known. window: The stored observations seeding the trailing window (oldest first). activity: Zero-arg callable returning the monitor's all-packet histogram. activity_flags: Zero-arg callable returning the histogram's per-bucket this-session flags (seeded history draws grey, live traffic green). kind_counts: Zero-arg callable returning the monitor's kind tallies. - hub_active: Zero-arg callable: whether the event hub is pumping. - prefix_bytes: Path-hash width to light in the packet viewer's hashes. - self_name: Our own node's name, drawn white wherever it appears. - channels: The device's configured channels, as ``(name, secret)`` pairs, - handed to each opened :class:`~meshterm.ui.packet_viewer.PacketViewer` - so it can attempt to decrypt an overheard channel-text packet. - type_of: Maps a relay hash to its node type, handed to the packet viewer so a - relayed packet's route graph marks a repeater ``▲`` (etc.) over a dot. """ super().__init__() self.title = "Dashboard — mesh overview" @@ -164,56 +113,22 @@ class DashboardScreen(Screen): self._activity = activity self._activity_flags = activity_flags self._kind_counts = kind_counts - self._hub_active = hub_active - self._prefix_bytes = prefix_bytes - self._self_name = self_name - self._channels = channels - self._type_of = type_of #: The trailing window of observations (stored seed + live), oldest first. self._window: deque[Observation] = deque(window, maxlen=4000) - #: The feed: latest events of every class as data, newest first — rendered - #: fresh each paint (rows adapt to width) and handed whole to the viewer. - self._feed: deque[PacketEntry] = deque(maxlen=_FEED_CAP) - for obs in list(self._window)[-_FEED_CAP:][::-1]: - self._feed.append(PacketEntry.from_observation(obs)) - #: The highlighted feed row. Starts on the newest packet (``None`` only when - #: the feed is empty) so a lone Esc always backs straight out of the screen. - self._selected: Optional[int] = 0 if self._feed else None - #: The feed's window within the fixed screen (only its rows scroll). - self._feed_window = ListWindow() #: The device's own numbers, refreshed by the opener's poll (Device info's #: dynamic rows): ``stats`` from get_stats, ``battery`` from get_battery. self.stats: dict = {} self.battery: dict = {} - # --- live feed ----------------------------------------------------------------- + # --- live window ----------------------------------------------------------------- def on_event(self, event: MeshEvent) -> None: - """Fold one hub event into the window and the feed, and repaint.""" - entry: Optional[PacketEntry] = None + """Fold one hub observation into the trailing window, and repaint.""" obs = event.observation if obs is not None: self._window.append(obs) - entry = PacketEntry.from_observation(obs) - elif event.kind == EventKind.MESSAGE and event.message is not None: - msg = event.message - entry = PacketEntry( - when=utcnow(), kind="message", node=msg.sender, snr=msg.snr, - where=f"ch {msg.channel}" if msg.is_channel else "direct", - text=msg.text, raw=msg.raw, - ) - elif event.kind == EventKind.ACK and event.ack is not None: - entry = PacketEntry( - when=utcnow(), kind="ack", - where=event.ack.code or "delivery confirmed", - ) - if entry is not None: - self._feed.appendleft(entry) - # Keep the highlight on the same packet as new rows push it down. - if self._selected is not None: - self._selected = min(self._selected + 1, len(self._feed) - 1) - self._prune() - self._session.invalidate() + self._prune() + self._session.invalidate() def _prune(self) -> None: """Drop window observations that aged past the trailing window.""" @@ -224,111 +139,35 @@ class DashboardScreen(Screen): # --- input ----------------------------------------------------------------------- def handle(self, action: str, data: str = "") -> None: - """Walk the feed, open the highlighted packet, scroll, or dismiss.""" + """Scroll the overview body, or dismiss.""" if action == "up": - self._move_selection(-1) + self.scroll_lines(-1) elif action == "down": - self._move_selection(1) - elif action == "enter": - self._open_packet() + self.scroll_lines(1) elif action == "pageup": - # With a feed row highlighted the page keys walk the selection (a - # windowful at a time), so the highlight travels with the window; with - # none, they slide the feed window itself under the pinned charts. - if self._selected is not None: - self._select_index(self._selected - self._feed_window.page) - else: - self._feed_window.top -= self._feed_window.page - self._session.invalidate() + self.scroll_pages(-1) elif action in ("pagedown", "space"): - if self._selected is not None: - self._select_index(self._selected + self._feed_window.page) - else: - self._feed_window.top += self._feed_window.page - self._session.invalidate() + self.scroll_pages(1) elif action in ("home", "ctrl_home"): - # With the feed highlight active, Home jumps to the newest packet; - # otherwise it slides the window to the feed's newest end (End mirrors). - if self._selected is not None: - self._select_index(0) - else: - self._feed_window.top = 0 - self._session.invalidate() + self.scroll_to_top() elif action in ("end", "ctrl_end"): - if self._selected is not None: - self._select_index(len(self._feed) - 1) - else: - self._feed_window.to_end() - self._session.invalidate() + self.scroll_to_bottom() elif action == "escape": self.resolve(None) - def _move_selection(self, delta: int) -> None: - """Move the feed highlight (the first press lands on the newest packet).""" - if not self._feed: - return - if self._selected is None: - self._select_index(0) - else: - self._select_index(self._selected + delta) - - def _select_index(self, index: int) -> None: - """Highlight one feed row (clamped) and repaint.""" - self._selected = max(0, min(index, len(self._feed) - 1)) - self._session.invalidate() - - def _open_packet(self) -> None: - """Float the packet viewer over the highlighted feed row. - - Paging inside the viewer walks the feed highlight in step (via - ``on_navigate``), so closing it lands back on the packet last viewed. - """ - if self._selected is None or not self._feed: - return - - def follow(entry: PacketEntry) -> None: - # The feed may have grown since the snapshot; find the entry itself. - for i, candidate in enumerate(self._feed): - if candidate is entry: - self._select_index(i) - return - - viewer = PacketViewer( - list(self._feed), self._selected, - resolve=self._resolve, prefix_bytes=self._prefix_bytes, - self_name=self._self_name, on_navigate=follow, - channels=self._channels, type_of=self._type_of, - # The live feed itself (newest first), so the viewer keeps up with packets - # that arrive while it is open instead of freezing at this snapshot. - source=lambda: list(self._feed), - ) - asyncio.ensure_future(self._session.run_screen(viewer)) - # --- rendering --------------------------------------------------------------------- def render_body(self, width: int) -> list[str]: - """Render the pinned overview sections, then the feed's window beneath. - - The charts, traffic, and RF sections size the fixed chrome; whatever the - frame's viewport has left is the feed's window — only its rows scroll (see - :class:`~meshterm.ui.tui.screen.ListWindow`), so the overview stays - glanceable however deep the reader digs into the feed. - """ + """Render the overview sections as one scrolling body.""" self._prune() - if self._selected is not None and self._feed: - self._selected = min(self._selected, len(self._feed) - 1) - chrome: list[RenderableType] = [ + body: list[RenderableType] = [ *self._activity_section(width), Text(), *self._traffic_section(), Text(), *self._rf_section(), - Text(), - self._feed_heading(), ] - lines = render_lines(Group(*chrome), width) - win = max(1, self._scroll_viewport - len(lines)) - lines.extend(self._feed_lines(width, win)) + lines = render_lines(Group(*body), width) self._scroll_total = max(1, len(lines)) return lines @@ -534,115 +373,6 @@ class DashboardScreen(Screen): return [heading, Text("no receptions in the window yet", style="muted")] return [heading, self._grid(rows)] - # -- feed -- - - def _feed_heading(self) -> Text: - """The feed's pinned heading, with a live-light for the hub.""" - heading = Text("Feed", style="accent") - heading.append(" · newest first · Enter opens a packet ", style="muted") - if self._hub_active(): - heading.append("● live", style="ok") - else: - heading.append("○ waiting for a device", style="muted") - return heading - - def _feed_lines(self, width: int, win: int) -> list[str]: - """The feed's windowed rows: newest first, ``↑/↓ n more`` at the edges.""" - if not self._feed: - return [render_to_ansi(Text("nothing heard yet", style="muted"), width)] - show_label = width >= _FEED_LABEL_MIN_WIDTH - entries = list(self._feed) - top, count = self._feed_window.fit(len(entries), win, self._selected) - out: list[str] = [] - if top > 0: - out.append(render_to_ansi(ListWindow.marker(top, "above"), width)) - for i in range(top, top + count): - row = self._feed_row(entries[i], i == self._selected, show_label) - out.append(render_to_ansi(row, width, no_wrap=True)) - below = len(entries) - top - count - if below > 0: - out.append(render_to_ansi(ListWindow.marker(below, "below"), width)) - return out - - def _feed_row(self, entry: PacketEntry, selected: bool, show_label: bool) -> Text: - """Lay one feed row out in fixed lanes: time, class, node, reception, detail. - - The class lane leads with its two-cell icon; the textual label beside it is - dropped wholesale on a narrow terminal (``show_label``), keeping the lanes - aligned either way. The node name takes the app-wide palette hue (our own - node white, a bare hash muted). Never wraps — a long relay path ellipsizes - at the right edge instead of spilling a lone ``dBm`` onto its own line. - """ - row = Text(no_wrap=True, overflow="ellipsis") - row.append("▸ " if selected else " ", style="accent") - row.append(entry.when.astimezone().strftime("%H:%M:%S") + " ", style="muted") - row.append(kind_icon(entry.kind) + " ") - if show_label: - row.append(entry.kind.ljust(10), style=KIND_STYLES.get(entry.kind, "brand")) - label, style = node_label(entry, self._resolve, self._self_name) - if label == "?": - label, style = self._feed_subject(entry) # no node identity: name what we can - row.append(fit_cells(label, _FEED_NAME_WIDTH), style=style) - row.append(" ") - row.append( - f"{entry.snr:+5.1f} dB" if entry.snr is not None else " " * 8, - style=snr_style(entry.snr) if entry.snr is not None else "muted", - ) - row.append( - f" {entry.rssi:5.0f} dBm" if entry.rssi is not None else " " * 10, - style="muted", - ) - note = self._feed_note(entry) - if note is not None: - row.append(" ") - row.append_text(note) - return row - - def _feed_subject(self, entry: PacketEntry) -> tuple[str, str]: - """Name the node lane when an entry carries no resolvable node identity. - - The fallback the vast majority of rows hit — a relayed ``packet`` naming no - origin, or a channel message with no sender field. Rather than a useless ``?`` - (or the bare ``ch 3`` that only repeats the note), it reads the most identifying - thing the entry does carry: the sender a channel message named itself with, or - what *kind* of frame a relayed packet is (``channel text`` / ``trace`` / …). An - ack falls back to its code; nothing else, to a dash. - """ - if entry.kind == "message": - sender = _channel_sender(entry.text) - if sender: - ours = self._self_name and sender == self._self_name - return sender, ("you" if ours else name_style(sender)) - return "channel", "muted" - if entry.kind == "packet": - cls = payload_class(entry.raw) - if cls: - return cls, "muted" - if entry.where: - return entry.where, "muted" # an ack's code, or any other stray context - return "—", "muted" - - def _feed_note(self, entry: PacketEntry) -> Optional[Text]: - """The row's trailing detail: a packet's relay path, a message's conversation. - - The path renders through the shared compact path widget, so a relayed frame's - ``via`` chain reads the same here as in the packet viewer and the chat paths. - """ - if entry.kind == "packet" and entry.path is not None: - note = Text("via ", style="muted") - note.append_text( - path_text( - entry.path.split(","), - self._resolve, - prefix_bytes=self._prefix_bytes, - self_name=self._self_name, - ) - ) - return note - if entry.kind == "message" and entry.where: - return Text(entry.where, style="muted") - return None - def _name(self, node: Optional[str]) -> str: """A node's friendly name when known, else its raw hash (never ``None``).""" if not node: @@ -667,30 +397,23 @@ async def open_dashboard(ctx: "AppContext") -> None: """ from ..services import trace_runner from .surface import TuiUi - from .timemachine_screen import _routing_prefix_bytes if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller raise RuntimeError("the dashboard is only available in the menu") session = ctx.ui.session contacts = [] - self_name: Optional[str] = None - channels: list[tuple[str, bytes]] = [] try: if ctx.is_connected or ctx.settings.connect_on_start: - # Through the session cache: contacts and the channel-slot probe are the two - # slowest reads on a screen open, so reading them once (not per dashboard open) - # is what keeps navigation snappy over Bluetooth. + # Through the session cache: contacts are one of the slowest reads on a + # screen open, so reading them once (not per dashboard open) is what keeps + # navigation snappy over Bluetooth. contacts = await ctx.devstate.contacts() - self_name = (await ctx.devstate.self_info()).get("name") or None - channels = [(s.name, s.secret) for s in await ctx.devstate.channel_slots()] except Exception: # noqa: BLE001 - the dashboard renders fine without contact names contacts = [] # Contacts first, every name the recorder ever overheard as the fallback — the # app-wide rule that a node we can name never renders as a bare hash. resolve = trace_runner.make_node_resolver(contacts, ctx.repo.node_names()) - type_of = trace_runner.make_node_type_resolver(contacts) - prefix_bytes = await _routing_prefix_bytes(ctx) window = ctx.repo.recent_observations(since=utcnow() - OBSERVATION_WINDOW) screen = DashboardScreen( @@ -700,11 +423,6 @@ async def open_dashboard(ctx: "AppContext") -> None: activity=ctx.monitor.activity_histogram, activity_flags=ctx.monitor.activity_session_flags, kind_counts=ctx.monitor.kind_counts, - hub_active=lambda: ctx.events.active, - prefix_bytes=prefix_bytes, - self_name=self_name, - channels=channels, - type_of=type_of, ) unsubscribe = ctx.events.subscribe(screen.on_event) diff --git a/meshterm/ui/livefeed_screen.py b/meshterm/ui/livefeed_screen.py new file mode 100644 index 0000000..6730e19 --- /dev/null +++ b/meshterm/ui/livefeed_screen.py @@ -0,0 +1,430 @@ +"""The Live feed: every packet as it arrives, full-screen and newest first. + +The interactive face of the ``livefeed`` tool — the dashboard's old feed panel, +promoted to a first-class screen. One always-repainting list streams the latest +packets, newest first: time, class (icon + label, icon alone on a narrow terminal), +node, SNR/RSSI, and the trailing detail (a relayed frame's ``via`` chain, a message's +conversation). Seeded from stored history so the screen opens full, then streamed +live off the event hub. ``↑``/``↓`` walk the rows, PgUp/PgDn/Home/End page and jump +them, and Enter opens the highlighted packet in the shared +:class:`~meshterm.ui.packet_viewer.PacketViewer` — which then pages through the feed +itself with the same ``↑``/``↓``, and, for an overheard channel-text packet naming a +channel we hold the key for, decrypts it. + +The screen holds no subscriptions of its own — the opener (:func:`open_livefeed`) +wires the hub subscription and the once-a-second repaint, and tears them down when +the screen resolves. The newest packet is highlighted from the moment the screen +opens; Esc backs out directly. +""" + +from __future__ import annotations + +import asyncio +from collections import deque +from typing import TYPE_CHECKING, Any, Optional, Sequence + +from rich.text import Text + +from ..core.channels import split_channel_sender +from ..core.events import EventKind, MeshEvent +from ..core.models import Observation, utcnow +from ..persistence.repository import OBSERVATION_WINDOW +from .menus import fit_cells +from .packet_viewer import ( + KIND_STYLES, + PacketEntry, + PacketViewer, + kind_icon, + node_label, + payload_class, +) +from .theme import name_style, snr_style +from .tui.render import render_to_ansi +from .tui.screen import ListWindow, Screen +from .widgets import TypeOf, path_text + +if TYPE_CHECKING: + from ..context import AppContext + +#: Seconds between full repaints while the feed is open (keeps the live-light and any +#: age-sensitive chrome honest even between hub events). +_REFRESH_S = 1.0 + +#: How many feed rows are kept (the feed windows within the screen, so this is +#: history depth, not layout). +_FEED_CAP = 100 + +#: The feed's fixed node-name lane width; longer names ellipsize so the columns hold. +_FEED_NAME_WIDTH = 18 + +#: Terminal width below which the feed drops the textual kind label and keeps only +#: the two-cell icon, buying the name and reception lanes room (≤72-col care). +_FEED_LABEL_MIN_WIDTH = 76 + + +def _channel_sender(text: Optional[str]) -> Optional[str]: + """The sender named by a channel message's ``Name: `` prefix, or ``None`` if absent. + + The shared protocol-layer parse (see + :func:`~meshterm.core.channels.split_channel_sender`), so the feed's node lane names + exactly the sender the chat transcript would. + """ + name, _body = split_channel_sender(text or "") + return name + + +class LiveFeedScreen(Screen): + """The full-screen packet stream. Renders state; the opener feeds it.""" + + floating = False + footer_hint = "↑↓ packets · Enter open · PgUp/PgDn/Home/End scroll · Esc back" + + def __init__( + self, + *, + session: Any, + resolve: Any, + seed: list[Observation], + hub_active: Any, + prefix_bytes: int = 0, + self_name: Optional[str] = None, + channels: Sequence[tuple[str, bytes]] = (), + type_of: Optional[TypeOf] = None, + ) -> None: + """Create the feed over its data feeds. + + Args: + session: The running TUI session (for repaints and the packet viewer). + resolve: Maps a node hash to a friendly contact name when known. + seed: Stored observations to open with (oldest first, as the repository + returns them); the newest :data:`_FEED_CAP` become the opening feed. + hub_active: Zero-arg callable: whether the event hub is pumping. + prefix_bytes: The hash width to light in the packet viewer's keys. + self_name: Our own node's name, drawn white wherever it appears. + channels: The device's configured channels, as ``(name, secret)`` pairs, + handed to each opened :class:`~meshterm.ui.packet_viewer.PacketViewer` + so it can attempt to decrypt an overheard channel-text packet. + type_of: Maps a relay hash to its node type, handed to the packet viewer so a + relayed packet's route graph marks a repeater ``▲`` (etc.) over a dot. + """ + super().__init__() + self.title = "Live feed" + self._session = session + self._resolve = resolve + self._hub_active = hub_active + self._prefix_bytes = prefix_bytes + self._self_name = self_name + self._channels = channels + self._type_of = type_of + #: The feed: latest events of every class as data, newest first — rendered + #: fresh each paint (rows adapt to width) and handed whole to the viewer. + self._feed: deque[PacketEntry] = deque(maxlen=_FEED_CAP) + for obs in list(seed)[-_FEED_CAP:][::-1]: + self._feed.append(PacketEntry.from_observation(obs)) + #: The highlighted feed row. Starts on the newest packet (``None`` only when + #: the feed is empty) so a lone Esc always backs straight out of the screen. + self._selected: Optional[int] = 0 if self._feed else None + #: The feed's window within the fixed screen (its rows scroll under the heading). + self._feed_window = ListWindow() + + # --- live feed ----------------------------------------------------------------- + + def on_event(self, event: MeshEvent) -> None: + """Fold one hub event into the feed and repaint.""" + entry: Optional[PacketEntry] = None + obs = event.observation + if obs is not None: + entry = PacketEntry.from_observation(obs) + elif event.kind == EventKind.MESSAGE and event.message is not None: + msg = event.message + entry = PacketEntry( + when=utcnow(), kind="message", node=msg.sender, snr=msg.snr, + where=f"ch {msg.channel}" if msg.is_channel else "direct", + text=msg.text, raw=msg.raw, + ) + elif event.kind == EventKind.ACK and event.ack is not None: + entry = PacketEntry( + when=utcnow(), kind="ack", + where=event.ack.code or "delivery confirmed", + ) + if entry is not None: + self._feed.appendleft(entry) + # Keep the highlight on the same packet as new rows push it down. + if self._selected is not None: + self._selected = min(self._selected + 1, len(self._feed) - 1) + self._session.invalidate() + + # --- input ----------------------------------------------------------------------- + + def handle(self, action: str, data: str = "") -> None: + """Walk the feed, open the highlighted packet, scroll, or dismiss.""" + if action == "up": + self._move_selection(-1) + elif action == "down": + self._move_selection(1) + elif action == "enter": + self._open_packet() + elif action == "pageup": + # With a feed row highlighted the page keys walk the selection (a + # windowful at a time), so the highlight travels with the window; with + # none, they slide the feed window itself under the pinned heading. + if self._selected is not None: + self._select_index(self._selected - self._feed_window.page) + else: + self._feed_window.top -= self._feed_window.page + self._session.invalidate() + elif action in ("pagedown", "space"): + if self._selected is not None: + self._select_index(self._selected + self._feed_window.page) + else: + self._feed_window.top += self._feed_window.page + self._session.invalidate() + elif action in ("home", "ctrl_home"): + # With the feed highlight active, Home jumps to the newest packet; + # otherwise it slides the window to the feed's newest end (End mirrors). + if self._selected is not None: + self._select_index(0) + else: + self._feed_window.top = 0 + self._session.invalidate() + elif action in ("end", "ctrl_end"): + if self._selected is not None: + self._select_index(len(self._feed) - 1) + else: + self._feed_window.to_end() + self._session.invalidate() + elif action == "escape": + self.resolve(None) + + def _move_selection(self, delta: int) -> None: + """Move the feed highlight (the first press lands on the newest packet).""" + if not self._feed: + return + if self._selected is None: + self._select_index(0) + else: + self._select_index(self._selected + delta) + + def _select_index(self, index: int) -> None: + """Highlight one feed row (clamped) and repaint.""" + self._selected = max(0, min(index, len(self._feed) - 1)) + self._session.invalidate() + + def _open_packet(self) -> None: + """Float the packet viewer over the highlighted feed row. + + Paging inside the viewer walks the feed highlight in step (via + ``on_navigate``), so closing it lands back on the packet last viewed. + """ + if self._selected is None or not self._feed: + return + + def follow(entry: PacketEntry) -> None: + # The feed may have grown since the snapshot; find the entry itself. + for i, candidate in enumerate(self._feed): + if candidate is entry: + self._select_index(i) + return + + viewer = PacketViewer( + list(self._feed), self._selected, + resolve=self._resolve, prefix_bytes=self._prefix_bytes, + self_name=self._self_name, on_navigate=follow, + channels=self._channels, type_of=self._type_of, + # The live feed itself (newest first), so the viewer keeps up with packets + # that arrive while it is open instead of freezing at this snapshot. + source=lambda: list(self._feed), + ) + asyncio.ensure_future(self._session.run_screen(viewer)) + + # --- rendering --------------------------------------------------------------------- + + def render_body(self, width: int) -> list[str]: + """The pinned heading, then the feed's window filling the viewport.""" + if self._selected is not None and self._feed: + self._selected = min(self._selected, len(self._feed) - 1) + lines = [render_to_ansi(self._heading(), width, no_wrap=True)] + win = max(1, self._scroll_viewport - len(lines)) + lines.extend(self._feed_lines(width, win)) + self._scroll_total = max(1, len(lines)) + return lines + + def _heading(self) -> Text: + """The feed's pinned status line, with a live-light for the hub.""" + heading = Text("newest first · Enter opens a packet ", style="muted") + if self._hub_active(): + heading.append("● live", style="ok") + else: + heading.append("○ waiting for a device", style="muted") + return heading + + def _feed_lines(self, width: int, win: int) -> list[str]: + """The feed's windowed rows: newest first, ``↑/↓ n more`` at the edges.""" + if not self._feed: + return [render_to_ansi(Text("nothing heard yet", style="muted"), width)] + show_label = width >= _FEED_LABEL_MIN_WIDTH + entries = list(self._feed) + top, count = self._feed_window.fit(len(entries), win, self._selected) + out: list[str] = [] + if top > 0: + out.append(render_to_ansi(ListWindow.marker(top, "above"), width)) + for i in range(top, top + count): + row = self._feed_row(entries[i], i == self._selected, show_label) + out.append(render_to_ansi(row, width, no_wrap=True)) + below = len(entries) - top - count + if below > 0: + out.append(render_to_ansi(ListWindow.marker(below, "below"), width)) + return out + + def _feed_row(self, entry: PacketEntry, selected: bool, show_label: bool) -> Text: + """Lay one feed row out in fixed lanes: time, class, node, reception, detail. + + The class lane leads with its two-cell icon; the textual label beside it is + dropped wholesale on a narrow terminal (``show_label``), keeping the lanes + aligned either way. The node name takes the app-wide palette hue (our own + node white, a bare hash muted). Never wraps — a long relay path ellipsizes + at the right edge instead of spilling a lone ``dBm`` onto its own line. + """ + row = Text(no_wrap=True, overflow="ellipsis") + row.append("▸ " if selected else " ", style="accent") + row.append(entry.when.astimezone().strftime("%H:%M:%S") + " ", style="muted") + row.append(kind_icon(entry.kind) + " ") + if show_label: + row.append(entry.kind.ljust(10), style=KIND_STYLES.get(entry.kind, "brand")) + label, style = node_label(entry, self._resolve, self._self_name) + if label == "?": + label, style = self._feed_subject(entry) # no node identity: name what we can + row.append(fit_cells(label, _FEED_NAME_WIDTH), style=style) + row.append(" ") + row.append( + f"{entry.snr:+5.1f} dB" if entry.snr is not None else " " * 8, + style=snr_style(entry.snr) if entry.snr is not None else "muted", + ) + row.append( + f" {entry.rssi:5.0f} dBm" if entry.rssi is not None else " " * 10, + style="muted", + ) + note = self._feed_note(entry) + if note is not None: + row.append(" ") + row.append_text(note) + return row + + def _feed_subject(self, entry: PacketEntry) -> tuple[str, str]: + """Name the node lane when an entry carries no resolvable node identity. + + The fallback the vast majority of rows hit — a relayed ``packet`` naming no + origin, or a channel message with no sender field. Rather than a useless ``?`` + (or the bare ``ch 3`` that only repeats the note), it reads the most identifying + thing the entry does carry: the sender a channel message named itself with, or + what *kind* of frame a relayed packet is (``channel text`` / ``trace`` / …). An + ack falls back to its code; nothing else, to a dash. + """ + if entry.kind == "message": + sender = _channel_sender(entry.text) + if sender: + ours = self._self_name and sender == self._self_name + return sender, ("you" if ours else name_style(sender)) + return "channel", "muted" + if entry.kind == "packet": + cls = payload_class(entry.raw) + if cls: + return cls, "muted" + if entry.where: + return entry.where, "muted" # an ack's code, or any other stray context + return "—", "muted" + + def _feed_note(self, entry: PacketEntry) -> Optional[Text]: + """The row's trailing detail: a packet's relay path, a message's conversation. + + The path renders through the shared compact path widget, so a relayed frame's + ``via`` chain reads the same here as in the packet viewer and the chat paths. + """ + if entry.kind == "packet" and entry.path is not None: + note = Text("via ", style="muted") + note.append_text( + path_text( + entry.path.split(","), + self._resolve, + prefix_bytes=self._prefix_bytes, + self_name=self._self_name, + ) + ) + return note + if entry.kind == "message" and entry.where: + return Text(entry.where, style="muted") + return None + + +async def open_livefeed(ctx: "AppContext") -> None: + """Open the live feed and run it until dismissed. + + Wires the screen to its feeds: stored recent observations seed it, a hub + subscription streams every new packet in, and a once-a-second ticker keeps the + live-light honest. Everything is torn down when the screen closes. + + Args: + ctx: The shared application context (must be running the interactive TUI surface). + + Raises: + RuntimeError: If called outside the interactive menu (no full-screen session). + """ + from ..services import trace_runner + from .surface import TuiUi + from .timemachine_screen import _routing_prefix_bytes + + if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller + raise RuntimeError("the live feed is only available in the menu") + session = ctx.ui.session + + contacts = [] + self_name: Optional[str] = None + channels: list[tuple[str, bytes]] = [] + try: + if ctx.is_connected or ctx.settings.connect_on_start: + # Through the session cache: contacts and the channel-slot probe are the two + # slowest reads on a screen open, so reading them once (not per feed open) + # is what keeps navigation snappy over Bluetooth. + contacts = await ctx.devstate.contacts() + self_name = (await ctx.devstate.self_info()).get("name") or None + channels = [(s.name, s.secret) for s in await ctx.devstate.channel_slots()] + except Exception: # noqa: BLE001 - the feed renders fine without contact names + contacts = [] + # Contacts first, every name the recorder ever overheard as the fallback — the + # app-wide rule that a node we can name never renders as a bare hash. + resolve = trace_runner.make_node_resolver(contacts, ctx.repo.node_names()) + type_of = trace_runner.make_node_type_resolver(contacts) + prefix_bytes = await _routing_prefix_bytes(ctx) + + seed = ctx.repo.recent_observations(since=utcnow() - OBSERVATION_WINDOW) + screen = LiveFeedScreen( + session=session, + resolve=resolve, + seed=seed, + hub_active=lambda: ctx.events.active, + prefix_bytes=prefix_bytes, + self_name=self_name, + channels=channels, + type_of=type_of, + ) + + unsubscribe = ctx.events.subscribe(screen.on_event) + + async def tick() -> None: + """Repaint once a second so the live-light and clock-sensitive rows stay honest.""" + while True: + await asyncio.sleep(_REFRESH_S) + session.invalidate() + + ticker = asyncio.ensure_future(tick()) + try: + await session.run_screen(screen) + finally: + unsubscribe() + ticker.cancel() + try: + await ticker + except asyncio.CancelledError: + pass + except Exception: # noqa: BLE001 - teardown must never surface a tick hiccup + pass diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index d66d4ce..0b2f5ee 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -12,7 +12,7 @@ from datetime import datetime, timedelta from pathlib import Path from meshterm.core.events import MeshEvent -from meshterm.core.models import Ack, Message, Observation, utcnow +from meshterm.core.models import Observation, utcnow from meshterm.persistence.repository import Repository from meshterm.services.monitor_service import ACTIVITY_BUCKETS from meshterm.ui.dashboard_screen import DashboardScreen @@ -26,7 +26,7 @@ class _FakeSession: self.repaints += 1 -def _screen(window=None, histogram=None, kinds=None, active=True) -> DashboardScreen: +def _screen(window=None, histogram=None, kinds=None) -> DashboardScreen: screen = DashboardScreen( session=_FakeSession(), resolve=lambda h: {"a1b2": "Alice", "3d63": "YUL"}.get(h, ""), @@ -34,7 +34,6 @@ def _screen(window=None, histogram=None, kinds=None, active=True) -> DashboardSc activity=lambda: tuple(histogram or (0,) * ACTIVITY_BUCKETS), activity_flags=lambda: (True,) * ACTIVITY_BUCKETS, kind_counts=lambda: dict(kinds or {}), - hub_active=lambda: active, ) screen.note_viewport(48) # the frame records this before every real paint return screen @@ -59,19 +58,21 @@ def _stripped(lines: list[str]) -> list[str]: # --- the screen ---------------------------------------------------------------------- -def test_dashboard_renders_all_four_sections() -> None: - """Activity, Traffic, RF health, and Feed all render from a seeded window.""" +def test_dashboard_renders_all_three_sections() -> None: + """Activity, Traffic, and RF health all render from a seeded window. + + (The feed panel moved out to the Live feed tool — see ``test_livefeed``.) + """ screen = _screen( window=[_obs(), _obs(node="3d63", node_type=2, snr=-2.0)], histogram=[3] + [0] * (ACTIVITY_BUCKETS - 1), kinds={"advert": 5, "ack": 1}, ) body = _plain(screen.render_body(100)) - assert "Activity" in body and "Traffic" in body - assert "RF health" in body and "Feed" in body - assert "● live" in body + assert "Activity" in body and "Traffic" in body and "RF health" in body + assert "Feed" not in body # the packet stream lives in the Live feed tool now assert "nodes heard" in body and "(1 repeater)" in body - assert "advert" in body and "Alice" in body and "YUL" in body + assert "advert" in body and "Alice" in body # traffic class + the busiest node def test_dashboard_activity_chart_reads_newest_right_with_mirrored_scale() -> None: @@ -124,60 +125,16 @@ def test_dashboard_pulse_drops_heard_only_when_it_wont_fit() -> None: assert "heard" not in tight and "nodes" in tight -def test_dashboard_live_events_land_in_the_feed_and_window() -> None: - """Observations, messages, and acks each fold into the feed as they arrive.""" +def test_dashboard_live_observations_land_in_the_window() -> None: + """A hub observation folds into the trailing window and repaints the charts.""" screen = _screen() screen.on_event(MeshEvent.observation_event(_obs(snr=7.5))) - screen.on_event(MeshEvent.message_event(Message(text="hi", sender="a1b2"))) - screen.on_event(MeshEvent.ack_event(Ack(code="01c3"))) body = _plain(screen.render_body(100)) - assert "+7.5 dB" in body - assert "message" in body and "ack" in body - # Newest first: the ack row sits above the message row, which sits above the advert. - assert body.index("ack") < body.index("message") < body.index("advert") + assert "+7.5 dB median" in body # the RF section now has a reception to describe + assert screen._session.repaints >= 1 -def test_dashboard_packet_rows_show_their_relay_path() -> None: - """An RX-log packet reads as its relay path, resolved to names where known. - - The path renders through the shared compact path widget, so each name carries its - own hue — assert on the stripped text, not the raw ANSI. - """ - screen = _screen() - screen.on_event( - MeshEvent.observation_event(_obs(kind="packet", path="3d63,a1b2", snr=1.0)) - ) - assert "via YUL → Alice" in "\n".join(_stripped(screen.render_body(100))) - - -def test_dashboard_feed_names_a_relayed_packet_by_its_payload_class() -> None: - """A relayed packet naming no origin reads as its payload class, never a bare '?'.""" - screen = _screen() - raw = {"payload_typename": "TRACE", "route_typename": "FLOOD"} - screen.on_event( - MeshEvent.observation_event( - _obs(node="", kind="packet", snr=1.0, path="3d63,a1b2", raw=raw) - ) - ) - feed = _plain(screen.render_body(100)).split("Feed")[1] - assert "trace" in feed # the payload-class gloss stands in for the missing identity - assert "?" not in feed # …instead of the useless placeholder - - -def test_dashboard_feed_names_a_channel_message_by_its_sender() -> None: - """A channel message's ``Name:`` prefix names the node lane, not the bare channel.""" - from meshterm.core.models import Message - - screen = _screen() - screen.on_event( - MeshEvent.message_event(Message(text="Alice: hi all", channel=3, is_channel=True)) - ) - feed = _plain(screen.render_body(100)).split("Feed")[1] - assert "Alice" in feed # the parsed sender leads the row - assert "ch 3" in feed # …with the channel kept as the trailing context - - -def test_dashboard_prunes_the_window_but_keeps_the_feed() -> None: +def test_dashboard_prunes_the_window() -> None: """Observations older than the window drop out of the statistics.""" stale = _obs(age_s=3 * 3600, snr=-12.0) screen = _screen(window=[stale]) @@ -185,41 +142,6 @@ def test_dashboard_prunes_the_window_but_keeps_the_feed() -> None: assert "no receptions in the window yet" in body # stats pruned the stale row -def test_dashboard_page_keys_move_the_feed_selection() -> None: - """With a feed row highlighted, PgUp/PgDn walk the selection a windowful at a time.""" - window = [_obs(node=f"n{i}", age_s=i) for i in range(20)] - screen = _screen(window=window) - screen._feed_window.page = 5 # as if the last paint settled a five-row window - assert screen._selected == 0 # the newest packet is highlighted from the start - screen.handle("pagedown") - assert screen._selected == 5 # the selection travelled down a page, not just the view - screen.handle("pageup") - assert screen._selected == 0 - - # With nothing highlighted, the page keys slide the feed window instead. - screen._selected = None - screen.handle("pagedown") - assert screen._feed_window.top > 0 and screen._selected is None - - -def test_dashboard_feed_windows_inside_the_fixed_screen() -> None: - """The charts stay pinned: the body fits the viewport and the feed rows window.""" - window = [_obs(node=f"n{i}", age_s=i) for i in range(40)] - screen = _screen(window=window) - screen.note_viewport(24) - lines = screen.render_body(100) - assert len(lines) <= 24 # charts + feed window == the viewport, never more - body = _plain(_stripped(lines)) - assert "Activity" in body and "Feed" in body # the chrome is all still there - assert "↓" in body and "more" in body # hidden feed rows are counted below - - -def test_dashboard_without_a_device_reads_as_waiting() -> None: - """With the hub idle the feed heading says so instead of pretending to be live.""" - screen = _screen(active=False) - assert "○ waiting for a device" in _plain(screen.render_body(100)) - - def test_dashboard_radio_rows_render_device_stats() -> None: """The Device-info dynamic numbers (noise floor, airtime, battery) fold in.""" screen = _screen(window=[_obs()]) diff --git a/tests/test_livefeed.py b/tests/test_livefeed.py new file mode 100644 index 0000000..2374df5 --- /dev/null +++ b/tests/test_livefeed.py @@ -0,0 +1,147 @@ +"""Live feed tests: the promoted feed screen's state, rows, and windowing. + +The screen is driven headless against fake sessions and canned observations — the +same approach as the dashboard tests, whose feed panel this screen grew out of. +""" + +from __future__ import annotations + +import re +from datetime import timedelta + +from meshterm.core.events import MeshEvent +from meshterm.core.models import Ack, Message, Observation, utcnow +from meshterm.ui.livefeed_screen import LiveFeedScreen + + +class _FakeSession: + def __init__(self) -> None: + self.repaints = 0 + + def invalidate(self) -> None: + self.repaints += 1 + + +def _screen(seed=None, active=True) -> LiveFeedScreen: + screen = LiveFeedScreen( + session=_FakeSession(), + resolve=lambda h: {"a1b2": "Alice", "3d63": "YUL"}.get(h, ""), + seed=list(seed or []), + hub_active=lambda: active, + ) + screen.note_viewport(48) # the frame records this before every real paint + return screen + + +def _obs(node="a1b2", kind="advert", snr=5.0, rssi=-90.0, age_s=0, **extra) -> Observation: + return Observation( + node=node, name=node, kind=kind, snr=snr, rssi=rssi, + observed_at=utcnow() - timedelta(seconds=age_s), **extra, + ) + + +def _plain(lines: list[str]) -> str: + return "\n".join(lines) + + +def _stripped(lines: list[str]) -> list[str]: + """The rendered lines with ANSI escapes removed, for structural assertions.""" + return [re.sub(r"\x1b\[[0-9;]*m", "", line) for line in lines] + + +def test_livefeed_tool_registers_under_the_dashboard() -> None: + """The livefeed tool lands in the Mesh section, right below the dashboard.""" + from meshterm.tools import load_all_tools + from meshterm.tools.base import all_tools + + load_all_tools() + tools = {t.name: t for t in all_tools()} + tool = tools["livefeed"] + assert tool.title == "Live feed" and tool.category == "Mesh" + assert tools["dashboard"].order < tool.order < tools["nodes"].order + + +def test_livefeed_live_events_land_in_the_feed() -> None: + """Observations, messages, and acks each fold into the feed as they arrive.""" + screen = _screen() + screen.on_event(MeshEvent.observation_event(_obs(snr=7.5))) + screen.on_event(MeshEvent.message_event(Message(text="hi", sender="a1b2"))) + screen.on_event(MeshEvent.ack_event(Ack(code="01c3"))) + body = _plain(screen.render_body(100)) + assert "+7.5 dB" in body + assert "message" in body and "ack" in body + # Newest first: the ack row sits above the message row, which sits above the advert. + assert body.index("ack") < body.index("message") < body.index("advert") + + +def test_livefeed_packet_rows_show_their_relay_path() -> None: + """An RX-log packet reads as its relay path, resolved to names where known. + + The path renders through the shared compact path widget, so each name carries its + own hue — assert on the stripped text, not the raw ANSI. + """ + screen = _screen() + screen.on_event( + MeshEvent.observation_event(_obs(kind="packet", path="3d63,a1b2", snr=1.0)) + ) + assert "via YUL → Alice" in "\n".join(_stripped(screen.render_body(100))) + + +def test_livefeed_names_a_relayed_packet_by_its_payload_class() -> None: + """A relayed packet naming no origin reads as its payload class, never a bare '?'.""" + screen = _screen() + raw = {"payload_typename": "TRACE", "route_typename": "FLOOD"} + screen.on_event( + MeshEvent.observation_event( + _obs(node="", kind="packet", snr=1.0, path="3d63,a1b2", raw=raw) + ) + ) + body = _plain(screen.render_body(100)) + assert "trace" in body # the payload-class gloss stands in for the missing identity + assert "?" not in body # …instead of the useless placeholder + + +def test_livefeed_names_a_channel_message_by_its_sender() -> None: + """A channel message's ``Name:`` prefix names the node lane, not the bare channel.""" + screen = _screen() + screen.on_event( + MeshEvent.message_event(Message(text="Alice: hi all", channel=3, is_channel=True)) + ) + body = _plain(screen.render_body(100)) + assert "Alice" in body # the parsed sender leads the row + assert "ch 3" in body # …with the channel kept as the trailing context + + +def test_livefeed_page_keys_move_the_feed_selection() -> None: + """With a feed row highlighted, PgUp/PgDn walk the selection a windowful at a time.""" + seed = [_obs(node=f"n{i}", age_s=i) for i in range(20)] + screen = _screen(seed=seed) + screen._feed_window.page = 5 # as if the last paint settled a five-row window + assert screen._selected == 0 # the newest packet is highlighted from the start + screen.handle("pagedown") + assert screen._selected == 5 # the selection travelled down a page, not just the view + screen.handle("pageup") + assert screen._selected == 0 + + # With nothing highlighted, the page keys slide the feed window instead. + screen._selected = None + screen.handle("pagedown") + assert screen._feed_window.top > 0 and screen._selected is None + + +def test_livefeed_windows_inside_the_fixed_screen() -> None: + """The heading stays pinned: the body fits the viewport and the feed rows window.""" + seed = [_obs(node=f"n{i}", age_s=i) for i in range(40)] + screen = _screen(seed=seed) + screen.note_viewport(24) + lines = screen.render_body(100) + assert len(lines) <= 24 # heading + feed window == the viewport, never more + body = _plain(_stripped(lines)) + assert "newest first" in body # the pinned status line is still there + assert "↓" in body and "more" in body # hidden feed rows are counted below + + +def test_livefeed_without_a_device_reads_as_waiting() -> None: + """With the hub idle the heading says so instead of pretending to be live.""" + screen = _screen(active=False) + assert "○ waiting for a device" in _plain(screen.render_body(100))