Dashboard rebuilt around the packet viewer: open any feed row

New packet_viewer module: per-kind icons and colours shared by every
packet list, and a floating viewer that lays any packet out in full -
advert identity/location, telemetry payload, a packet's relay path,
a message's text - pageable over its list with PgUp/PgDn/Home/End.
The feed stores packets as data and renders per paint: up/down walk
the rows, Enter opens the viewer, Esc peels the highlight; the class
lane drops to icon-only on narrow terminals. Node names take the
app-wide palette (ours white), RF health and pulse render as labelled
grids so wrapped items align with their block, traffic lanes ride the
shared braille meter, the chart caption gains intermediate time marks,
and history buckets draw grey like the header.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Fable 5 committed 2026-07-11 18:35:54 -04:00
1 parent 072a4573fe
commit 872156b388
3 files changed
+573 -110

No files matched your search

+217 -107
View File
@@ -17,12 +17,17 @@ 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, node, SNR/RSSI. Seeded
from stored history so the screen opens full, then streamed live off the event hub.
* **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. ``↑``/``↓`` walk the feed rows
and Enter opens the highlighted packet in the shared
:class:`~meshterm.ui.packet_viewer.PacketViewer` — which then pages through the
feed itself with PgUp/PgDn.
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. PgUp/PgDn/Home/End scroll, Esc backs out.
tears them all down when the screen resolves. PgUp/PgDn/Home/End scroll; Esc first
drops the feed highlight, then backs out.
"""
from __future__ import annotations
@@ -33,12 +38,14 @@ from statistics import median
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.events import EventKind, MeshEvent
from ..core.models import NODE_TYPE_REPEATER, Observation, utcnow
from ..persistence.repository import ACTIVITY_WINDOW
from .braillechart import timeline_rows
from .braillechart import axis_caption, meter, timeline_rows
from .packet_viewer import KIND_STYLES, PacketEntry, PacketViewer, kind_icon, node_label
from .theme import snr_style
from .trace_screen import snr_bar
from .tui.render import render_lines
@@ -62,18 +69,20 @@ _FEED_NAME_WIDTH = 18
#: How many braille rows tall the activity chart draws (each row is four dot rows).
_CHART_ROWS = 3
#: Display style per packet class, shared by the traffic panel and the feed.
_KIND_STYLES = {
"advert": "accent",
"telemetry": "brand",
"packet": "muted",
"message": "ok",
"ack": "faint",
}
#: The order the traffic panel lists packet classes in (heard ones not listed sort last).
_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 _fit(text: str, width: int) -> str:
"""Left-justify ``text`` to ``width`` columns, ellipsizing anything longer."""
@@ -114,7 +123,7 @@ class DashboardScreen(Screen):
"""The live mesh overview. Renders state and scrolls; the opener feeds it."""
floating = False
footer_hint = "PgUp/PgDn scroll · Esc back"
footer_hint = "↑↓ packets · Enter open · PgUp/PgDn scroll · Esc back"
def __init__(
self,
@@ -123,32 +132,47 @@ class DashboardScreen(Screen):
resolve: Any,
window: list[Observation],
activity: Any,
activity_flags: Any,
kind_counts: Any,
hub_active: Any,
prefix_bytes: int = 0,
self_name: Optional[str] = None,
) -> None:
"""Create the dashboard over its data feeds.
Args:
session: The running TUI session (for repaints).
session: The running TUI session (for repaints and the packet viewer).
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.
kind_counts: Zero-arg callable returning the monitor's session kind tallies.
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.
"""
super().__init__()
self.title = "dashboard · mesh overview"
self._session = session
self._resolve = resolve
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
#: 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, newest first.
self._feed: deque[Text] = deque(maxlen=_FEED_CAP)
#: 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(self._observation_row(obs))
self._feed.append(PacketEntry.from_observation(obs))
#: The highlighted feed row (``None`` = nothing selected, view scrolls free).
self._selected: Optional[int] = None
#: Body lines the last render produced before the feed rows began.
self._feed_first_line = 0
#: 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 = {}
@@ -158,23 +182,28 @@ class DashboardScreen(Screen):
def on_event(self, event: MeshEvent) -> None:
"""Fold one hub event into the window and the feed, and repaint."""
entry: Optional[PacketEntry] = None
obs = event.observation
if obs is not None:
self._window.append(obs)
self._feed.appendleft(self._observation_row(obs))
entry = PacketEntry.from_observation(obs)
elif event.kind == EventKind.MESSAGE and event.message is not None:
msg = event.message
where = f"ch {msg.channel}" if msg.is_channel else "direct"
row = self._feed_row(
utcnow(), "message",
self._name(msg.sender) if msg.sender else where,
note=where if not msg.is_channel else None, snr=msg.snr,
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,
)
self._feed.appendleft(row)
elif event.kind == EventKind.ACK and event.ack is not None:
self._feed.appendleft(
self._feed_row(utcnow(), "ack", event.ack.code or "delivery confirmed")
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()
@@ -187,11 +216,15 @@ class DashboardScreen(Screen):
# --- input -----------------------------------------------------------------------
def handle(self, action: str, data: str = "") -> None:
"""Scroll the body or dismiss the screen."""
if action in ("up", "pageup"):
self.scroll_pages(-1) if action == "pageup" else self.scroll_lines(-1)
"""Walk the feed, open the highlighted packet, scroll, or dismiss."""
if action == "up":
self._move_selection(-1)
elif action == "down":
self.scroll_lines(1)
self._move_selection(1)
elif action == "enter":
self._open_packet()
elif action == "pageup":
self.scroll_pages(-1)
elif action in ("pagedown", "space"):
self.scroll_pages(1)
elif action in ("home", "ctrl_home"):
@@ -199,13 +232,46 @@ class DashboardScreen(Screen):
elif action in ("end", "ctrl_end"):
self.scroll_to_bottom()
elif action == "escape":
self.resolve(None)
if self._selected is not None:
self._selected = None # first Esc peels the highlight, second leaves
self._session.invalidate()
else:
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._selected = 0
else:
self._selected = max(0, min(self._selected + delta, len(self._feed) - 1))
self._session.invalidate()
def _open_packet(self) -> None:
"""Float the packet viewer over the highlighted feed row."""
if self._selected is None or not self._feed:
return
viewer = PacketViewer(
list(self._feed), self._selected,
resolve=self._resolve, prefix_bytes=self._prefix_bytes,
self_name=self._self_name,
)
asyncio.ensure_future(self._session.run_screen(viewer))
def cursor_line(self) -> Optional[int]:
"""Keep the highlighted feed row in view (free scrolling when nothing is)."""
if self._selected is None or not self._feed:
return None
return self._feed_first_line + self._selected
# --- rendering ---------------------------------------------------------------------
def render_body(self, width: int) -> list[str]:
"""Render the four stacked sections for the current state."""
self._prune()
if self._selected is not None and self._feed:
self._selected = min(self._selected, len(self._feed) - 1)
sections: list[RenderableType] = [
*self._activity_section(width),
Text(),
@@ -213,10 +279,13 @@ class DashboardScreen(Screen):
Text(),
*self._rf_section(),
Text(),
*self._feed_section(),
*self._feed_section(width),
]
lines = render_lines(Group(*sections), width)
self._scroll_total = max(1, len(lines))
# Feed rows are the body's tail, one line each (they never wrap), so the
# highlight's body line is a plain offset from the end.
self._feed_first_line = len(lines) - len(self._feed)
return lines
# -- activity --
@@ -242,7 +311,13 @@ class DashboardScreen(Screen):
heading = Text("Activity", style="accent")
heading.append(" · every packet heard · one minute per dot column",
style="muted")
chart_rows = timeline_rows(list(reversed(shown)), rows=_CHART_ROWS)
# Buckets seeded from a previous session's stored history draw grey; only
# what this session heard itself pulses green.
flags = (tuple(self._activity_flags()) + (True,) * minutes)[:minutes]
styles = ["ok" if live else "muted" for live in reversed(flags)]
chart_rows = timeline_rows(
list(reversed(shown)), rows=_CHART_ROWS, column_styles=styles
)
marks = _axis_labels(peak, len(chart_rows))
out: list[RenderableType] = [heading]
for mark, row in zip(marks, chart_rows):
@@ -254,17 +329,38 @@ class DashboardScreen(Screen):
out.append(line)
axis = Text(" " * label_w + " └" + "─" * chars + "┘", style="muted")
out.append(axis)
span = "−" + _span_label(minutes)
def caption_at(frac: float) -> str:
if frac >= 1.0:
return "now"
return "−" + _span_label(round(minutes * (1 - frac)))
caption = Text(" " * (label_w + 2))
caption.append(span, style="faint")
caption.append(" " * max(1, chars - len(span) - len("now")))
caption.append("now", style="faint")
caption.append_text(axis_caption(chars, caption_at))
out.append(caption)
out.append(Text())
out.append(self._pulse_line(shown, width))
out.append(self._pulse_grid(shown, width))
return out
def _pulse_line(self, shown: list[int], width: int) -> Text:
def _grid(self, rows: list[tuple[str, Text]]) -> Table:
"""Labelled rows with a hanging indent: values wrap within their own block.
The app-wide alignment rule — a wrapped item's continuation lines align with
the item, never with the line start — done as a two-column frameless grid:
the label lane is fixed at :data:`_GRID_LABEL_W` cells, the value column
soaks up the rest and folds inside itself.
"""
grid = Table(
box=None, show_header=False, show_edge=False, pad_edge=False,
padding=(0, 0), expand=False,
)
grid.add_column(width=_GRID_LABEL_W, no_wrap=True)
grid.add_column(overflow="fold")
for label, value in rows:
grid.add_row(Text(label, style="muted"), value)
return grid
def _pulse_grid(self, shown: list[int], width: int) -> Table:
"""Rates, who's been heard, and the window's busiest transmitter.
``shown`` is the chart's visible slice (newest first, one bucket per minute),
@@ -283,7 +379,7 @@ class DashboardScreen(Screen):
}
def compose(heard: bool) -> Text:
line = Text("pulse ", style="muted")
line = Text()
line.append(f"{recent:.1f} pkt/min", style="brand")
line.append(f" (15 m) · {overall:.1f} ({span})", style="muted")
line.append(" · ", style="muted")
@@ -298,18 +394,19 @@ class DashboardScreen(Screen):
return line
line = compose(heard=True)
if len(line.plain) > width:
if len(line.plain) + _GRID_LABEL_W > width:
line = compose(heard=False)
rows = [("pulse", line)]
busiest = self._busiest()
if busiest is not None:
name, count = busiest
line.append("\nbusiest ", style="muted")
line.append(name, style="brand")
line.append(
value = Text(name, style="brand")
value.append(
f" {count} packet{'s' if count != 1 else ''} in the window",
style="muted",
)
return line
rows.append(("busiest", value))
return self._grid(rows)
def _busiest(self) -> Optional[tuple[str, int]]:
"""The window's most-heard attributable node, or ``None`` in silence."""
@@ -324,9 +421,9 @@ class DashboardScreen(Screen):
# -- traffic --
def _traffic_section(self) -> list[RenderableType]:
"""Session tallies by packet class, each with a proportional bar."""
"""Tallies by packet class, each with a proportional braille meter."""
heading = Text("Traffic", style="accent")
heading.append(" · this session, by packet class", style="muted")
heading.append(" · by packet class · stored history + live", style="muted")
counts = self._kind_counts()
if not counts:
return [heading, Text("nothing heard yet", style="muted")]
@@ -339,73 +436,76 @@ class DashboardScreen(Screen):
count = counts[kind]
row = Text(f"{kind.ljust(label_w)} ", style="muted")
row.append(f"{count:>{count_w}} ")
# Bars step in half characters — braille's two dot columns per cell —
# so the lane resolves 48 levels across its 24 cells.
halves = max(1, round(count / peak * 48))
style = _KIND_STYLES.get(kind, "brand")
row.append("⣿" * (halves // 2), style=style)
if halves % 2:
row.append("⡇", style=style) # a lone left dot column: the half step
# The shared braille meter, full-height with no track: the lane resolves
# 48 levels across its 24 cells (two half-steps per cell).
row.append_text(
meter(
count / peak, _TRAFFIC_METER_CELLS,
style=KIND_STYLES.get(kind, "brand"),
)
)
rows.append(row)
return rows
# -- rf health --
def _rf_section(self) -> list[RenderableType]:
"""The window's reception quality plus the radio's own live numbers."""
"""The window's reception quality plus the radio's own live numbers.
Rendered as a labelled grid so an item that wraps on a narrow terminal
aligns its continuation with its own block, not the line start.
"""
heading = Text("RF health", style="accent")
heading.append(" · reception over 2 h · radio live", style="muted")
rows: list[RenderableType] = [heading]
rows: list[tuple[str, Text]] = []
snrs = [o.snr for o in self._window if o.snr is not None and o.kind != "packet"]
rssis = [o.rssi for o in self._window if o.rssi is not None and o.kind != "packet"]
if snrs:
med = median(snrs)
line = Text("snr ", style="muted")
line.append(f"{med:+.1f} dB median ", style=snr_style(med))
line = Text(f"{med:+.1f} dB median ", style=snr_style(med))
line.append_text(snr_bar(med))
lo, hi = min(snrs), max(snrs)
line.append(f" worst {lo:+.1f} · best {hi:+.1f}", style="muted")
rows.append(line)
rows.append(("snr", line))
if rssis:
line = Text("rssi ", style="muted")
line.append(f"{median(rssis):.0f} dBm median")
line = Text(f"{median(rssis):.0f} dBm median")
line.append(f" weakest {min(rssis):.0f} · strongest {max(rssis):.0f}",
style="muted")
rows.append(line)
if not snrs and not rssis:
rows.append(Text("no receptions in the window yet", style="muted"))
rows.append(("rssi", line))
stats = self.stats
if stats.get("noise_floor") is not None:
line = Text("radio ", style="muted")
line.append(f"{stats['noise_floor']} dBm noise floor")
line = Text(f"{stats['noise_floor']} dBm noise floor")
if stats.get("last_rssi") is not None:
line.append(f" · last RSSI {stats['last_rssi']} dBm", style="muted")
if stats.get("last_snr") is not None:
line.append(f" · last SNR {stats['last_snr']:+.1f} dB", style="muted")
rows.append(line)
rows.append(("radio", line))
extras = Text()
label = "airtime"
if stats.get("tx_air_secs") is not None:
extras.append("airtime ", style="muted")
extras.append(f"TX {stats['tx_air_secs']} s · RX {stats.get('rx_air_secs', 0)} s")
level = self.battery.get("level")
if level:
if extras.plain:
extras.append(" · ", style="muted")
else:
extras.append("battery ", style="muted")
label = "battery"
extras.append(f"{int(level) / 1000:.2f} V")
if extras.plain:
rows.append(extras)
return rows
rows.append((label, extras))
if not rows:
return [heading, Text("no receptions in the window yet", style="muted")]
return [heading, self._grid(rows)]
# -- feed --
def _feed_section(self) -> list[RenderableType]:
def _feed_section(self, width: int) -> list[RenderableType]:
"""The latest packets, newest first, with a live-light in the heading."""
heading = Text("Feed", style="accent")
heading.append(" · newest first ", style="muted")
heading.append(" · newest first · Enter opens a packet ", style="muted")
if self._hub_active():
heading.append("● live", style="ok")
else:
@@ -413,52 +513,53 @@ class DashboardScreen(Screen):
rows: list[RenderableType] = [heading]
if not self._feed:
rows.append(Text("nothing heard yet", style="muted"))
rows.extend(self._feed)
show_label = width >= _FEED_LABEL_MIN_WIDTH
for i, entry in enumerate(self._feed):
rows.append(self._feed_row(entry, i == self._selected, show_label))
return rows
def _observation_row(self, obs: Observation) -> Text:
"""One observation as a feed row (packets show their relay path)."""
note = None
if obs.kind == "packet" and obs.path is not None:
hops = [h for h in obs.path.split(",") if h]
note = "via " + " → ".join(self._name(h) for h in hops) if hops else "direct"
label = self._name(obs.node) if obs.node else (obs.name or "?")
return self._feed_row(
obs.observed_at, obs.kind, label, note=note, snr=obs.snr, rssi=obs.rssi
)
def _feed_row(
self,
when: Any,
kind: str,
who: str,
*,
note: Optional[str] = None,
snr: Optional[float] = None,
rssi: Optional[float] = None,
) -> Text:
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.
Never wraps — a long relay path ellipsizes at the right edge instead of
spilling a lone ``dBm`` onto its own line — and the node lane is fixed-width
so the reception columns align down the feed.
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(when.astimezone().strftime("%H:%M:%S") + " ", style="muted")
row.append(kind.ljust(10), style=_KIND_STYLES.get(kind, "brand"))
row.append(_fit(who, _FEED_NAME_WIDTH))
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 == "?" and entry.where:
label, style = entry.where, "muted" # a senderless message/ack: its context
row.append(_fit(label, _FEED_NAME_WIDTH), style=style)
row.append(" ")
row.append(
f"{snr:+5.1f} dB" if snr is not None else " " * 8,
style=snr_style(snr) if snr is not None else "muted",
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" {rssi:5.0f} dBm" if rssi is not None else " " * 10, style="muted"
f" {entry.rssi:5.0f} dBm" if entry.rssi is not None else " " * 10,
style="muted",
)
note = self._feed_note(entry)
if note:
row.append(f" {note}", style="muted")
return row
def _feed_note(self, entry: PacketEntry) -> Optional[str]:
"""The row's trailing detail: a packet's relay path, a message's conversation."""
if entry.kind == "packet" and entry.path is not None:
hops = [h for h in entry.path.split(",") if h]
return "via " + " → ".join(self._name(h) for h in hops) if hops else "direct"
if entry.kind == "message":
return entry.where
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:
@@ -483,19 +584,25 @@ 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
try:
if ctx.is_connected or ctx.settings.connect_on_start:
device = await ctx.device()
contacts = await device.get_contacts()
self_name = (await device.get_self_info()).get("name") or None
except Exception: # noqa: BLE001 - the dashboard renders fine without contact names
contacts = []
resolve = trace_runner.make_node_resolver(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())
prefix_bytes = await _routing_prefix_bytes(ctx)
window = ctx.repo.recent_observations(since=utcnow() - ACTIVITY_WINDOW)
screen = DashboardScreen(
@@ -503,8 +610,11 @@ async def open_dashboard(ctx: "AppContext") -> None:
resolve=resolve,
window=window,
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,
)
unsubscribe = ctx.events.subscribe(screen.on_event)
+347
View File
@@ -0,0 +1,347 @@
"""The packet viewer: one floating popup that can open any packet a list shows.
Everywhere MeshTerm lists packets (the dashboard feed today; any future packet list)
the rows share this module's per-kind chrome — a colour and a two-cell icon per packet
class — and every row can open into the same viewer: a centered dialog over the list
that lays the packet out in full, flavoured by kind. An advert shows the node's
identity, type, and location; telemetry shows the node and its reported values; an
RX-logged packet shows the relay path it rode in on; a message shows the sender, the
conversation, and the text; an ack shows its code. Common to all: the timestamp, the
node (name coloured by the app-wide palette, hash in the hash widget), and reception
quality on the shared SNR bar.
When opened over a list the viewer pages through it in place — PgUp/PgDn step to the
newer/older packet, Home/End jump to the newest/oldest — so a burst can be read
packet by packet without bouncing back out to the list. ``↑``/``↓`` scroll a tall
packet inside the dialog; Esc closes it.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from typing import Optional
from rich.console import RenderableType
from rich.table import Table
from rich.text import Text
from ..core.models import NODE_TYPE_LABELS, Observation
from ..services.trace_runner import NodeResolver
from .theme import name_style, snr_style
from .trace_screen import snr_bar
from .tui.render import render_lines
from .tui.screen import Screen
from .widgets import _age_seconds, _format_age, highlighted_hash
#: Display style per packet class, shared by every packet list and the viewer.
KIND_STYLES = {
"advert": "accent",
"telemetry": "brand",
"packet": "muted",
"message": "ok",
"ack": "faint",
}
#: The two-cell icon per packet class — every icon is emoji-wide, so a list can swap
#: the textual kind label for the icon alone on a narrow terminal without the lanes
#: shifting. The fallback marks a class this table has never heard of.
KIND_ICONS = {
"advert": "📢",
"telemetry": "📊",
"packet": "📦",
"message": "💬",
"ack": "✅",
}
DEFAULT_ICON = "❔"
@dataclass(slots=True)
class PacketEntry:
"""One listed packet, in the shape every packet list stores and the viewer reads.
A deliberately flat union of what the feed's three event families carry — the
monitor's observations, chat messages, and delivery acks — so one list type can
hold them all and the viewer can flavour by :attr:`kind`.
Attributes:
when: When the packet was heard.
kind: Packet class (``advert``/``telemetry``/``packet``/``message``/``ack``).
node: The transmitting node's stored hash, when identified.
name: The name the packet itself carried (an advert's node name, a message's
sender), if any; display falls back to resolving :attr:`node`.
snr: Reception SNR in dB, if measured (for ``packet`` rows: of the *last relay*).
rssi: Reception strength in dBm, if measured.
lat: Advertised latitude, when the packet shared a location.
lon: Advertised longitude, when the packet shared one.
node_type: The advertised node type (see ``NODE_TYPE_*``), if carried.
path: A ``packet`` row's relay path: comma-separated hop hashes in propagation
order (empty = arrived direct; ``None`` = the class carries no path).
where: A message's conversation (``ch 3`` / ``direct``) or an ack's code.
text: A message's body, when it is known.
raw: The raw event payload, for the values a class-specific layout can't name.
"""
when: datetime
kind: str
node: Optional[str] = None
name: Optional[str] = None
snr: Optional[float] = None
rssi: Optional[float] = None
lat: Optional[float] = None
lon: Optional[float] = None
node_type: Optional[int] = None
path: Optional[str] = None
where: Optional[str] = None
text: Optional[str] = None
raw: Optional[dict] = None
@classmethod
def from_observation(cls, obs: Observation) -> "PacketEntry":
"""Capture an overheard observation (the monitor's event family) as an entry."""
return cls(
when=obs.observed_at,
kind=obs.kind,
node=obs.node,
name=obs.name,
snr=obs.snr,
rssi=obs.rssi,
lat=obs.lat,
lon=obs.lon,
node_type=obs.node_type,
path=obs.path,
raw=obs.raw,
)
def kind_icon(kind: str) -> str:
"""The two-cell icon for a packet class (a fallback for unknown classes)."""
return KIND_ICONS.get(kind, DEFAULT_ICON)
def node_label(
entry: PacketEntry, resolve: NodeResolver, self_name: Optional[str] = None
) -> tuple[str, str]:
"""The display name and style for an entry's node — the app-wide naming rule.
What ``resolve`` knows about the hash wins (the contact list is the canonical
identity), then the name the packet itself carried; a genuinely nameless node
shows its hash. Names take their stable palette hue
(:func:`~meshterm.ui.theme.name_style`) — except our own node, which is always
the pure-white ``you`` — and a bare hash stays muted, because colour is the
"this is a name" signal.
Args:
entry: The packet whose node to label.
resolve: Maps a node hash to a friendly name when known.
self_name: Our own node's name, to spot "us" (``None`` = never matches).
Returns:
``(label, style)``, ready to append to a row.
"""
name = None
if entry.node:
resolved = resolve(entry.node)
if resolved and resolved != entry.node:
name = resolved
if not name:
name = entry.name
if not name:
return (entry.node or "?", "muted")
if self_name and name == self_name:
return (name, "you")
return (name, name_style(name))
class PacketViewer(Screen):
"""The floating packet dialog: one entry laid out in full, pageable over its list.
A read-only popup. The opener hands it the list *as rendered* (newest first) and
the index of the row the user opened; PgUp/PgDn then walk toward newer/older
packets, Home/End jump to the ends, ``↑``/``↓`` scroll a tall body, Esc closes.
Opened over a single packet (a one-entry list) the paging keys simply do nothing.
"""
def __init__(
self,
entries: list[PacketEntry],
index: int,
*,
resolve: NodeResolver,
prefix_bytes: int = 0,
self_name: Optional[str] = None,
) -> None:
"""Open the viewer over a packet list.
Args:
entries: The list's packets, newest first (a snapshot; live inserts into
the underlying list don't shift the view).
index: Which entry to open on.
resolve: Maps a node hash to a friendly name when known.
prefix_bytes: Path-hash width to light in displayed hashes (0 = none).
self_name: Our own node's name, drawn white wherever it appears.
"""
super().__init__()
self._entries = entries
self._index = max(0, min(index, len(entries) - 1))
self._resolve = resolve
self._prefix_bytes = prefix_bytes
self._self_name = self_name
if len(entries) > 1:
self.footer_hint = "PgUp/PgDn newer/older · Home/End ends · Esc close"
else:
self.footer_hint = "Esc close"
self._set_title()
def _set_title(self) -> None:
entry = self._entries[self._index]
title = f"{kind_icon(entry.kind)} {entry.kind}"
if len(self._entries) > 1:
title += f" · {self._index + 1}/{len(self._entries)}"
self.title = title
# --- input ---------------------------------------------------------------
def handle(self, action: str, data: str = "") -> None:
"""Page through the list, scroll a tall entry, or dismiss."""
if action == "pageup":
self._jump(self._index - 1)
elif action in ("pagedown", "space"):
self._jump(self._index + 1)
elif action in ("home", "ctrl_home"):
self._jump(0)
elif action in ("end", "ctrl_end"):
self._jump(len(self._entries) - 1)
elif action == "up":
self.scroll_lines(-1)
elif action == "down":
self.scroll_lines(1)
elif action in ("escape", "enter"):
self.resolve(None)
def _jump(self, index: int) -> None:
"""Move to another entry (clamped), resetting the scroll for the new body."""
index = max(0, min(index, len(self._entries) - 1))
if index != self._index:
self._index = index
self.scroll = 0
self._set_title()
# --- rendering -------------------------------------------------------------
def render_body(self, width: int) -> list[str]:
"""Lay the current entry out as labelled rows, flavoured by its kind."""
entry = self._entries[self._index]
grid = Table(
box=None, show_header=False, show_edge=False, pad_edge=False,
padding=(0, 0), expand=False,
)
# The label lane is fixed so wrapped values align with their own block
# (the app-wide hanging-indent rule), never with column zero.
grid.add_column(width=10, no_wrap=True)
grid.add_column(overflow="fold", max_width=max(20, width - 10))
for label, value in self._rows(entry):
grid.add_row(Text(label, style="muted"), value)
lines = render_lines(grid, width)
self._scroll_total = max(1, len(lines))
return lines
def _rows(self, entry: PacketEntry) -> list[tuple[str, RenderableType]]:
"""The labelled rows for one entry: the common core plus its kind's extras."""
rows: list[tuple[str, RenderableType]] = []
secs = _age_seconds(entry.when)
heard = Text(entry.when.astimezone().strftime("%b %d %H:%M:%S"))
heard.append(f" ({_format_age(secs)} ago)", style="muted")
rows.append(("heard", heard))
if entry.node or entry.name:
who = Text()
label, style = node_label(entry, self._resolve, self._self_name)
who.append(label, style=style)
if entry.node and label != entry.node:
who.append(" ")
who.append_text(highlighted_hash(entry.node, self._prefix_bytes))
rows.append(("from", who))
if entry.node_type is not None:
label = NODE_TYPE_LABELS.get(entry.node_type, f"type {entry.node_type}")
rows.append(("type", Text(label)))
if entry.snr is not None or entry.rssi is not None:
rows.append(("snr", self._reception(entry)))
if entry.kind == "packet":
rows.append(("via", self._path_text(entry)))
rows.append((
"", Text("reception describes the last relay, not the origin",
style="faint"),
))
if entry.lat is not None and entry.lon is not None:
rows.append(("location", Text(f"{entry.lat:.5f}, {entry.lon:.5f}")))
if entry.where:
label = "code" if entry.kind == "ack" else "where"
rows.append((label, Text(entry.where)))
if entry.text:
rows.append(("text", Text(entry.text)))
rows.extend(self._raw_rows(entry))
return rows
def _reception(self, entry: PacketEntry) -> Text:
"""SNR (with the shared quality bar) and RSSI on one line."""
line = Text()
if entry.snr is not None:
line.append(f"{entry.snr:+.1f} dB ", style=snr_style(entry.snr))
line.append_text(snr_bar(entry.snr))
if entry.rssi is not None:
if entry.snr is not None:
line.append(" · ", style="muted")
line.append(f"{entry.rssi:.0f} dBm rssi", style="muted")
return line
def _path_text(self, entry: PacketEntry) -> Text:
"""A ``packet`` entry's relay path as named hops, or ``direct``."""
hops = [h for h in (entry.path or "").split(",") if h]
if not hops:
return Text("direct — no relays", style="muted")
text = Text()
for i, hop in enumerate(hops):
if i:
text.append(" → ", style="muted")
named = self._resolve(hop)
if named and named != hop:
style = "you" if self._self_name and named == self._self_name else name_style(named)
text.append(named, style=style)
text.append(f" ({hop})", style="muted")
else:
text.append(hop, style="muted")
return text
def _raw_rows(self, entry: PacketEntry) -> list[tuple[str, RenderableType]]:
"""The raw payload's leftover fields, one labelled row each (telemetry's meat).
Fields the flavoured layout already presents are skipped; the rest render as
flat ``key value`` rows so a telemetry frame's channels (or a new firmware
field the layout doesn't know yet) are still visible without a debugger.
"""
raw = entry.raw if isinstance(entry.raw, dict) else None
if not raw:
return []
shown = {
k: v
for k, v in raw.items()
if k not in ("node", "name", "kind", "snr", "rssi", "lat", "lon", "path",
"node_type", "observed_at", "text")
and v is not None
}
if not shown:
return []
rows: list[tuple[str, RenderableType]] = [("", Text())]
rows.append(("payload", Text(f"{len(shown)} raw fields", style="faint")))
for key, value in list(shown.items())[:12]:
body = str(value)
if len(body) > 200:
body = body[:199] + "…"
rows.append((f" {key[:8]}", Text(body, style="muted")))
return rows
+9 -3
View File
@@ -32,6 +32,7 @@ def _screen(window=None, histogram=None, kinds=None, active=True) -> DashboardSc
resolve=lambda h: {"a1b2": "Alice", "3d63": "YUL"}.get(h, ""),
window=list(window or []),
activity=lambda: tuple(histogram or (0,) * ACTIVITY_BUCKETS),
activity_flags=lambda: (True,) * ACTIVITY_BUCKETS,
kind_counts=lambda: dict(kinds or {}),
hub_active=lambda: active,
)
@@ -103,13 +104,18 @@ def test_dashboard_activity_chart_fills_the_width() -> None:
def test_dashboard_pulse_drops_heard_only_when_it_wont_fit() -> None:
"""The pulse line keeps ' heard' at full width and sheds it instead of wrapping."""
from meshterm.ui.tui.render import render_lines
def pulse_row(width: int) -> str:
grid = screen._pulse_grid(shown, width)
return _stripped(render_lines(grid, width))[0]
screen = _screen(window=[_obs(), _obs(node="3d63", node_type=2)])
shown = [1] * 120
roomy = screen._pulse_line(shown, 100).plain.splitlines()[0]
roomy = pulse_row(100)
assert "nodes heard" in roomy
tight = screen._pulse_line(shown, len(roomy) - 1).plain.splitlines()[0]
tight = pulse_row(len(roomy.rstrip()) - 1)
assert "heard" not in tight and "nodes" in tight
assert len(tight) <= len(roomy) - 1
def test_dashboard_live_events_land_in_the_feed_and_window() -> None: