From a3398bebf548e2271220e5610d0740a0fabb7cad Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sat, 11 Jul 2026 22:47:36 -0400 Subject: [PATCH] UI punch-list: dashboard feed, chart axes, chat counter, popups MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two rounds of interactive-polish fixes across the dashboard, Time Machine, chat, and the menu popups. Dashboard - Feed name lane names what a row actually is: a channel message's parsed sender, or a relayed packet's payload class (channel text / trace / …), instead of a bare "?" or a redundant "ch N". The class is persisted so history-seeded rows carry it too (observations.payload_typename, schema v10). - PgUp/PgDn walk the feed selection so the highlight travels with the view. Packet viewer - Takes a live source and re-locates the viewed packet by identity, so packets arriving after it opens become reachable; the n/total title stays current. - Decrypts overheard channel text straight from stored history (crypto fields persisted: chan_hash/cipher_mac/crypted, schema v9). Time Machine - Day charts label their bars with column ticks: each date sits under its own bar with a ┬ notch, shortens (month only on the first tick and on rollover), and thins to fit. axis_chart grows an optional ticks path for columnar charts. - Node history charts render through the shared axis_chart widget; the mesh Rhythm is 96 fifteen-minute slices at 4x width, "now/newest" hints dropped. Chat - The byte counter pins to the right edge of the input's last line, so it stays bottom-right when the compose wraps instead of trailing the cursor. Menu popups - The per-node Rules popover gets an explicit Close row. - The Send advert popup drops the emoji from its floating title (a terminal that paints it narrow left the content-sized dialog's border short, bleeding the backdrop through); the menu row keeps its icon. 625 tests pass. Co-Authored-By: Claude Opus 4.8 --- meshterm/persistence/db.py | 23 +++- meshterm/persistence/repository.py | 94 +++++++++++++- meshterm/ui/braillechart.py | 100 ++++++++++++--- meshterm/ui/chat.py | 15 +-- meshterm/ui/config_editor.py | 6 +- meshterm/ui/dashboard_screen.py | 71 ++++++++++- meshterm/ui/packet_viewer.py | 83 +++++++++++-- meshterm/ui/timemachine_screen.py | 189 ++++++++++++++++++----------- meshterm/ui/tui/render.py | 37 ++++++ meshterm/ui/watchtower_screen.py | 3 +- tests/test_braillechart.py | 37 ++++++ tests/test_chat.py | 28 ++++- tests/test_dashboard.py | 127 ++++++++++++++++++- tests/test_packet_viewer.py | 30 +++++ tests/test_timemachine.py | 78 +++++++++++- 15 files changed, 802 insertions(+), 119 deletions(-) diff --git a/meshterm/persistence/db.py b/meshterm/persistence/db.py index f2b0a74..46d054b 100644 --- a/meshterm/persistence/db.py +++ b/meshterm/persistence/db.py @@ -10,7 +10,7 @@ from __future__ import annotations import sqlite3 from pathlib import Path -SCHEMA_VERSION = 8 +SCHEMA_VERSION = 10 _SCHEMA = """ CREATE TABLE IF NOT EXISTS schema_meta ( @@ -109,7 +109,11 @@ CREATE TABLE IF NOT EXISTS observations ( lat REAL, lon REAL, path TEXT, -- 'packet' rows: comma-separated relay-hop hex hashes - observed_at TEXT NOT NULL + observed_at TEXT NOT NULL, + chan_hash TEXT, -- overheard GRP_TXT frames: channel-hash fingerprint (hex) + cipher_mac TEXT, -- …its 2-byte MAC (hex) + crypted TEXT, -- …its ciphertext (hex), so a stored channel text still decrypts + payload_typename TEXT -- 'packet' rows: the frame's payload class (GRP_TXT/TRACE/…) ); -- One chat message, sent or received, on a channel or with a contact. Unlike the other @@ -191,3 +195,18 @@ def _migrate(conn: sqlite3.Connection) -> None: # v6 -> v7: observations gained the relay path of RX-logged packets, the passive # evidence the mesh topology graph is built from. Older rows carry NULL (no path). conn.execute("ALTER TABLE observations ADD COLUMN path TEXT") + if "chan_hash" not in observation_cols: + # v8 -> v9: overheard channel-text (GRP_TXT) frames keep the fields the packet + # viewer needs to decrypt them — the channel-hash fingerprint, the 2-byte MAC, and + # the ciphertext — so a channel we hold the key for stays readable even when the feed + # is seeded from stored history (a live frame carries them in its raw payload; a + # replayed one had nowhere to keep them). Older rows carry NULL (never decryptable). + conn.execute("ALTER TABLE observations ADD COLUMN chan_hash TEXT") + conn.execute("ALTER TABLE observations ADD COLUMN cipher_mac TEXT") + conn.execute("ALTER TABLE observations ADD COLUMN crypted TEXT") + if "payload_typename" not in observation_cols: + # v9 -> v10: 'packet' RX-log rows keep their payload class (GRP_TXT, TRACE, PATH, + # ACK, …), the one identifying thing a relayed flood carries when it names no + # origin node — so the dashboard feed can read "channel text" / "trace" instead of + # a bare "?" even when seeded from history. Older rows carry NULL (class unknown). + conn.execute("ALTER TABLE observations ADD COLUMN payload_typename TEXT") diff --git a/meshterm/persistence/repository.py b/meshterm/persistence/repository.py index cafad60..393c037 100644 --- a/meshterm/persistence/repository.py +++ b/meshterm/persistence/repository.py @@ -38,6 +38,39 @@ ACTIVITY_WINDOW = timedelta(hours=2) ACTIVITY_BUCKETS = 24 +def _packet_raw(row: sqlite3.Row) -> Optional[dict]: + """Rebuild the minimal raw payload a stored ``packet`` observation is read back with. + + Two things a live RX-log event carried in its raw payload are kept per row: the + frame's payload class (``payload_typename``), so a list can name what the packet is, + and — for an overheard ``GRP_TXT`` frame — the three crypto fields it decrypts from + (fingerprint, MAC, ciphertext), so a channel we hold the key for stays readable + straight from history via the same code path a fresh frame takes. A row that stored + neither carries no raw (``None``), exactly as before. + """ + typename = _row_value(row, "payload_typename") + chan_hash = row["chan_hash"] + if not typename and not chan_hash: + return None + raw: dict = {} + if typename: + raw["payload_typename"] = typename + if chan_hash: + raw.setdefault("payload_typename", "GRP_TXT") + raw["chan_hash"] = chan_hash + raw["cipher_mac"] = row["cipher_mac"] + raw["crypted"] = row["crypted"] + return raw + + +def _row_value(row: sqlite3.Row, key: str) -> Any: + """Read ``key`` from a row, tolerating a query that didn't select it (returns ``None``).""" + try: + return row[key] + except (IndexError, KeyError): + return None + + def _hops_hash_bytes(hops: list[Hop]) -> Optional[int]: """Recover a stored trace's per-hop path-hash width from its hop hashes. @@ -613,14 +646,29 @@ class Repository: path the packet traversed — the raw material of the topology graph (see :meth:`packet_paths`). + An overheard channel-text (``GRP_TXT``) frame also keeps the three fields the + packet viewer decrypts from — the channel-hash fingerprint, the 2-byte MAC, and + the ciphertext — lifted out of the raw payload so a channel we hold the key for + is still readable when the feed is later seeded from stored history. + Args: run_id: The owning run. obs: The observation to store. """ + chan_hash = cipher_mac = crypted = None + raw = obs.raw if isinstance(obs.raw, dict) else {} + # The payload class identifies a relayed 'packet' that names no origin node — kept + # for every packet, not only channel text; the crypto trio is kept for GRP_TXT alone. + typename = raw.get("payload_typename") if obs.kind == "packet" else None + if raw.get("payload_typename") == "GRP_TXT": + chan_hash = raw.get("chan_hash") + cipher_mac = raw.get("cipher_mac") + crypted = raw.get("crypted") self._conn.execute( "INSERT INTO observations " - "(run_id, node, name, kind, node_type, snr, rssi, lat, lon, path, observed_at) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "(run_id, node, name, kind, node_type, snr, rssi, lat, lon, path, observed_at, " + "chan_hash, cipher_mac, crypted, payload_typename) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ( run_id, obs.node, @@ -633,6 +681,10 @@ class Repository: obs.lon, obs.path, obs.observed_at.isoformat(), + chan_hash, + cipher_mac, + crypted, + typename, ), ) self._conn.commit() @@ -669,7 +721,8 @@ class Repository: The window's observations, oldest first (ready to append live events to). """ rows = self._conn.execute( - "SELECT node, name, kind, node_type, snr, rssi, lat, lon, path, observed_at " + "SELECT node, name, kind, node_type, snr, rssi, lat, lon, path, observed_at, " + "chan_hash, cipher_mac, crypted, payload_typename " "FROM observations WHERE observed_at >= ? ORDER BY observed_at DESC LIMIT ?", (since.isoformat(), limit), ).fetchall() @@ -691,6 +744,7 @@ class Repository: lon=row["lon"], path=row["path"], observed_at=observed_at, + raw=_packet_raw(row), ) ) return observations @@ -793,6 +847,40 @@ class Repository: continue # a malformed stray timestamp simply isn't counted return counts + def quarter_hour_activity(self, *, since: Optional[datetime] = None) -> list[int]: + """Observation counts by UTC quarter-hour of day (0–95) across the history. + + The finer sibling of :meth:`hourly_activity` — four slices an hour instead of + one — feeding the whole-mesh Rhythm chart at its full 15-minute resolution. The + slice index is ``HH * 4 + MM // 15``, computed in SQL off the same cheap ISO-8601 + substrings (``HH`` at position 12, ``MM`` at position 15), so the cost stays 96 + rows however deep the history grows. The caller rotates the histogram into local + time (one current-offset rotation, in 15-minute units). + + Args: + since: Only observations at or after this time, if given. + + Returns: + 96 counts, index = UTC quarter-hour slice of the day. + """ + sql = ( + "SELECT CAST(substr(observed_at, 12, 2) AS INTEGER) * 4 " + "+ CAST(substr(observed_at, 15, 2) AS INTEGER) / 15 AS slot, COUNT(*) AS n " + "FROM observations" + ) + params: list[Any] = [] + if since is not None: + sql += " WHERE observed_at >= ?" + params.append(since.isoformat()) + sql += " GROUP BY slot" + counts = [0] * 96 + for row in self._conn.execute(sql, params).fetchall(): + try: + counts[int(row["slot"])] += int(row["n"]) + except (TypeError, ValueError, IndexError): + continue # a malformed stray timestamp simply isn't counted + return counts + def first_seen( self, *, since: Optional[datetime] = None ) -> list[tuple[str, Optional[str], datetime]]: diff --git a/meshterm/ui/braillechart.py b/meshterm/ui/braillechart.py index 7cff982..a4dbcaa 100644 --- a/meshterm/ui/braillechart.py +++ b/meshterm/ui/braillechart.py @@ -318,19 +318,22 @@ def axis_caption( return Text(label.ljust(chars), style=style) -def y_axis_labels(peak: float, rows: int) -> list[str]: +def y_axis_labels(peak: float, rows: int, *, lo: float = 0.0) -> list[str]: """Each chart row's top-edge value, top row first, dupes and zeros blanked. The top row always reads the peak; lower rows read the proportional values at their upper edges, but a mark that would repeat the one above (a low peak makes neighbouring rows round to the same value) or read zero is left blank, so the - scale never shows the same number twice. + scale never shows the same number twice. A signed chart passes its floor as + ``lo`` (``< 0``): the marks then run linearly from ``peak`` at the top down + through the grey zero line to ``lo`` at the bottom, so the gutter quotes both + extremes (an SNR band's ``+5 … −10 dB``) instead of only the positive peak. """ labels: list[str] = [] seen: set[int] = set() for i in range(rows): - value = round(peak * (rows - i) / rows) - if peak and value and value not in seen: + value = round(peak - (peak - lo) * i / rows) + if peak != lo and value and value not in seen: labels.append(str(value)) seen.add(value) else: @@ -338,37 +341,99 @@ def y_axis_labels(peak: float, rows: int) -> list[str]: return labels +#: Minimum blank cells kept between two column-axis labels, so a thinned tick row +#: reads as separate marks rather than a run of touching text. +_TICK_GAP = 2 + + +def _tick_axis( + chars: int, + label_w: int, + ticks: Sequence[tuple[int, str]], + style: str, +) -> tuple[Text, str]: + """Build the boxed border and its caption for a column chart with explicit ticks. + + Each tick is a ``(cell, label)`` pointing at a chart column: the border draws a + ``┬`` at that column and the label sits centred beneath it. Labels are placed + left to right and any that would land within :data:`_TICK_GAP` cells of the one + before it is dropped — tick and all — so a crowded axis thins to what fits + instead of overprinting. Callers pre-thin to roughly the right count (see the + Time Machine's ``_day_ticks``); this is the collision backstop. + + Args: + chars: The chart's width in character cells. + label_w: The y-axis gutter width the border and caption indent past. + ticks: ``(cell, label)`` marks, any order; ``cell`` is a 0-based chart column. + style: Style for the border (and its ticks). + + Returns: + ``(border, caption_text)`` — the border :class:`Text` and the plain caption + string, ready to indent under the gutter. + """ + cells = [" "] * chars + marked: set[int] = set() + last_end = -_TICK_GAP + for cell, label in sorted(ticks): + cell = max(0, min(chars - 1, cell)) + start = max(0, min(chars - len(label), cell - len(label) // 2)) + if start < last_end + _TICK_GAP: + continue # would crowd the label before it — drop this mark + cells[start : start + len(label)] = list(label) + marked.add(cell) + last_end = start + len(label) + bar = "".join("┬" if i in marked else "─" for i in range(chars)) + border = Text(" " * label_w + " └" + bar + "┘", style=style) + return border, "".join(cells) + + def axis_chart( chart_rows: list[Text], peak: float, chars: int, - label_at: Callable[[float], str], + label_at: Optional[Callable[[float], str]] = None, *, label_w: Optional[int] = None, style: str = "muted", + floor: float = 0.0, + ticks: Optional[Sequence[tuple[int, str]]] = None, ) -> list[Text]: """Frame :func:`timeline_rows` output with a mirrored y-axis and x-axis caption. Each row's top-edge value is mirrored on both gutters (blank where it would repeat the mark above or read zero), closed with a boxed bottom border, and - followed by :func:`axis_caption`, indented to clear the gutter. + followed by an x-axis caption indented to clear the gutter. + + The caption comes one of two ways. A *continuous* chart passes ``label_at`` and + the ends-plus-quarters marks of :func:`axis_caption` fill in whatever fits. A + *columnar* chart — bars of a fixed width apiece, a day or a slot each — instead + passes ``ticks``: explicit ``(cell, label)`` marks that centre a label under its + own column and notch the border with a ``┬`` beneath it (see :func:`_tick_axis`), + so a date sits under the bar it names rather than at an arbitrary fraction. Args: chart_rows: The chart's rows, as returned by :func:`timeline_rows`. peak: The value the top row's mark reads (the chart's tallest bar). chars: The chart's width in character cells. - label_at: Maps a position fraction to the x-axis caption at that point. + label_at: Maps a position fraction to the x-axis caption at that point + (a continuous chart); ignored when ``ticks`` is given. label_w: The gutter's digit width, when several stacked charts must - share one width so their gutters line up; sized from ``peak`` alone - by default. + share one width so their gutters line up; sized from ``peak`` (and + ``floor``) by default. style: Style for the gutters, ticks, marks, and border. + floor: The value the bottom edge reads on a signed chart (``< 0``), so + the gutter quotes both extremes of a zero-crossing series (the Time + Machine's SNR band). Defaults to ``0`` — an all-positive chart whose + baseline sits on the floor, the common case. + ticks: Explicit ``(cell, label)`` column marks for a columnar chart; when + given they drive the border and caption instead of ``label_at``. Returns: ``len(chart_rows) + 2`` :class:`Text` lines: the decorated rows, the bottom border, and the caption. """ - label_w = label_w or max(1, len(str(round(peak)))) - marks = y_axis_labels(peak, len(chart_rows)) + label_w = label_w or max(1, len(str(round(peak))), len(str(round(floor)))) + marks = y_axis_labels(peak, len(chart_rows), lo=floor) out: list[Text] = [] for mark, row in zip(marks, chart_rows): line = Text(f"{mark:>{label_w}} " + ("┤" if mark else "│"), style=style) @@ -377,9 +442,16 @@ def axis_chart( if mark: line.append(f" {mark}", style=style) out.append(line) - out.append(Text(" " * label_w + " └" + "─" * chars + "┘", style=style)) - caption = Text(" " * (label_w + 2)) - caption.append_text(axis_caption(chars, label_at)) + if ticks is not None: + border, caption_text = _tick_axis(chars, label_w, ticks, style) + out.append(border) + caption = Text(" " * (label_w + 2)) + caption.append(caption_text, style="faint") + else: + assert label_at is not None, "axis_chart needs label_at or ticks" + out.append(Text(" " * label_w + " └" + "─" * chars + "┘", style=style)) + caption = Text(" " * (label_w + 2)) + caption.append_text(axis_caption(chars, label_at)) out.append(caption) return out diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py index a40fc5d..6f924e8 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -26,7 +26,7 @@ from ..core.events import EventKind, MeshEvent from ..core.models import ChatMessage, Contact, Conversation, Message, utcnow from .theme import name_style, snr_style from .tui.prompt import _LineEditor -from .tui.render import render_hanging, render_lines +from .tui.render import render_hanging, render_lines, right_aligned_tail from .tui.screen import CANCEL, Screen from .tui.spinner import Spinner @@ -200,15 +200,16 @@ class ChatScreen(Screen): lines = self._render_grouped(width) limit = self._byte_limit() - # The byte budget rides the input line itself (no row of its own): it trails - # the cursor and wraps along with a long compose, so it is exactly as visible - # as the input — never the one line a full transcript pushes off the bottom. + # The byte budget is pinned to the right edge of the input's *last* line — so a + # compose that wraps onto a second line keeps the counter in the bottom-right + # corner rather than letting it trail the cursor down the wrap. Only a last line + # already full to the edge pushes it onto a right-aligned line of its own. input_line = self._editor.render(overflow_at=self._overflow_at(limit)) - input_line.append(" ") - input_line.append_text(self._byte_counter(limit)) + counter = self._byte_counter(limit) + compose = right_aligned_tail(input_line, counter, width) footer_parts: list[RenderableType] = [ Text("─" * width, style="muted"), - input_line, + compose, ] if self._is_channel and self._selected is not None: footer_parts.append(self._reply_banner()) diff --git a/meshterm/ui/config_editor.py b/meshterm/ui/config_editor.py index 997c97e..3046188 100644 --- a/meshterm/ui/config_editor.py +++ b/meshterm/ui/config_editor.py @@ -781,8 +781,12 @@ async def send_advert(ctx: "AppContext") -> None: """ device = await ctx.device() snapshot = dict(await device.get_self_info()) + # No emoji in this floating dialog's title: a terminal that paints an emoji a cell + # narrower than Rich measures it leaves the content-sized popup's title border short, + # bleeding the backdrop through the frame. The menu row keeps its 📡 icon (drawn in the + # full-width base, where the miscount has nowhere to show). choice = await ctx.ui.select( - "📡 Send advert", + "Send advert", [ Choice(title="Zero-hop — Announce directly to neighbours in range", value="zero"), Choice(title="Flood — Repeaters rebroadcast it across the mesh", value="flood"), diff --git a/meshterm/ui/dashboard_screen.py b/meshterm/ui/dashboard_screen.py index e2cfdf9..dce95c5 100644 --- a/meshterm/ui/dashboard_screen.py +++ b/meshterm/ui/dashboard_screen.py @@ -34,6 +34,7 @@ drops the feed highlight, then backs out. from __future__ import annotations import asyncio +import re from collections import Counter, deque from statistics import median from typing import TYPE_CHECKING, Any, Optional, Sequence @@ -46,8 +47,15 @@ from ..core.events import EventKind, MeshEvent from ..core.models import NODE_TYPE_REPEATER, Observation, utcnow from ..persistence.repository import ACTIVITY_WINDOW from .braillechart import axis_chart, meter, timeline_rows -from .packet_viewer import KIND_STYLES, PacketEntry, PacketViewer, kind_icon, node_label -from .theme import snr_style +from .packet_viewer import ( + KIND_STYLES, + PacketEntry, + PacketViewer, + kind_icon, + node_label, + payload_class, +) +from .theme import name_style, snr_style from .trace_screen import snr_bar from .tui.render import render_lines from .tui.screen import Screen @@ -85,6 +93,21 @@ _FEED_LABEL_MIN_WIDTH = 76 _GRID_LABEL_W = 9 +#: A channel message carries no sender field on the wire, so senders self-identify by +#: prefixing ``Name: `` (mirrors the chat transcript's own parse). Lifting the name out +#: lets the feed's node lane show *who* sent it rather than the bare channel it came in on. +_SENDER_PREFIX = re.compile(r"^([^\s:][^:]{0,19}):[ \t]+\S") + + +def _channel_sender(text: Optional[str]) -> Optional[str]: + """The sender named by a channel message's ``Name: `` prefix, or ``None`` if absent.""" + match = _SENDER_PREFIX.match(text or "") + if match is None: + return None + name = match.group(1).strip() + return name if name and not name.isdigit() else None + + def _fit(text: str, width: int) -> str: """Left-justify ``text`` to ``width`` columns, ellipsizing anything longer.""" if len(text) > width: @@ -210,9 +233,18 @@ class DashboardScreen(Screen): elif action == "enter": self._open_packet() elif action == "pageup": - self.scroll_pages(-1) + # With a feed row highlighted the page keys walk the selection (a screenful + # at a time), so the highlight travels with the view instead of the view + # scrolling out from under a pinned selection; with none, they free-scroll. + if self._selected is not None: + self._select_index(self._selected - self._page_step) + else: + self.scroll_pages(-1) elif action in ("pagedown", "space"): - self.scroll_pages(1) + if self._selected is not None: + self._select_index(self._selected + self._page_step) + else: + self.scroll_pages(1) elif action in ("home", "ctrl_home"): # With the feed highlight active, Home jumps to the newest packet; # otherwise it keeps its plain scroll-to-top meaning (End mirrors it). @@ -267,6 +299,9 @@ class DashboardScreen(Screen): resolve=self._resolve, prefix_bytes=self._prefix_bytes, self_name=self._self_name, on_navigate=follow, channels=self._channels, + # 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)) @@ -535,8 +570,8 @@ class DashboardScreen(Screen): 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 + if label == "?": + label, style = self._feed_subject(entry) # no node identity: name what we can row.append(_fit(label, _FEED_NAME_WIDTH), style=style) row.append(" ") row.append( @@ -552,6 +587,30 @@ class DashboardScreen(Screen): row.append(f" {note}", style="muted") 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[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: diff --git a/meshterm/ui/packet_viewer.py b/meshterm/ui/packet_viewer.py index 11f9005..3cf846e 100644 --- a/meshterm/ui/packet_viewer.py +++ b/meshterm/ui/packet_viewer.py @@ -157,6 +157,22 @@ def kind_icon(kind: str) -> str: return KIND_ICONS.get(kind, DEFAULT_ICON) +def payload_class(raw: Optional[dict]) -> Optional[str]: + """The friendly payload-class label for a raw ``packet`` frame, or ``None`` if unknown. + + Maps the frame's ``payload_typename`` (``GRP_TXT``, ``TRACE``, …) through + :data:`_PAYLOAD_GLOSS` — the one identifying thing a relayed flood carries when it + names no origin node, so a packet list can read "channel text" / "trace" instead of a + bare ``?``. Shared by the viewer's "class" row and the dashboard feed's node lane. + """ + if not isinstance(raw, dict): + return None + typename = raw.get("payload_typename") + if not typename: + return None + return _PAYLOAD_GLOSS.get(typename, typename.lower()) + + def node_label( entry: PacketEntry, resolve: NodeResolver, self_name: Optional[str] = None ) -> tuple[str, str]: @@ -211,12 +227,12 @@ class PacketViewer(Screen): self_name: Optional[str] = None, on_navigate: Optional[Callable[[PacketEntry], None]] = None, channels: Sequence[tuple[str, bytes]] = (), + source: Optional[Callable[[], Sequence[PacketEntry]]] = 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). + entries: The list's packets, newest first — the opening snapshot. 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). @@ -227,19 +243,64 @@ class PacketViewer(Screen): tried against an overheard ``packet`` entry's channel-text frame (see :func:`~meshterm.core.channels.decrypt_channel_text`), so a raw frame the radio never decoded for us can still be read when we hold the key. + source: Optional zero-arg callable returning the list's *current* packets + (newest first). When given, the viewer re-reads it every repaint and + keypress and re-locates the packet being viewed by identity, so packets + that arrive while the dialog is open become reachable (``↑`` walks up + into them) instead of the view being frozen at its opening snapshot. """ super().__init__() - self._entries = entries - self._index = max(0, min(index, len(entries) - 1)) + self._entries = list(entries) + self._index = max(0, min(index, len(self._entries) - 1)) self._resolve = resolve self._prefix_bytes = prefix_bytes self._self_name = self_name self._on_navigate = on_navigate self._channels = channels - if len(entries) > 1: + self._source = source + #: The packet currently shown, tracked by identity so a live prepend to the + #: source (which shifts every index) never slides the view onto another packet. + self._current: Optional[PacketEntry] = ( + self._entries[self._index] if self._entries else None + ) + self._update_footer() + self._set_title() + + def _update_footer(self) -> None: + """Set the footer hint to match whether the list currently has more than one entry.""" + if len(self._entries) > 1: self.footer_hint = "↑↓ newer/older · PgUp/PgDn scroll · Home/End ends · Esc close" else: self.footer_hint = "Esc close" + + def _sync(self) -> None: + """Refresh the entries from the live source, re-finding the viewed packet by identity. + + A no-op without a ``source``. Otherwise the list is re-read (picking up any + packets that arrived since the last paint) and the view stays on the *same* + packet object — its index simply moves as newer packets prepend ahead of it — + so paging keys measure against the current list and newly arrived packets sit + reachable above the one being read. A packet that has since aged out of the + list drops the view to the nearest surviving index. + """ + if self._source is None: + return + entries = list(self._source()) + if not entries: + return + self._entries = entries + if self._current is not None: + for i, candidate in enumerate(entries): + if candidate is self._current: + self._index = i + break + else: + self._index = min(self._index, len(entries) - 1) + self._current = entries[self._index] + else: + self._index = min(self._index, len(entries) - 1) + self._current = entries[self._index] + self._update_footer() self._set_title() def _set_title(self) -> None: @@ -253,6 +314,10 @@ class PacketViewer(Screen): def handle(self, action: str, data: str = "") -> None: """Page through the list, scroll a tall entry, or dismiss.""" + if action in ("up", "down", "home", "ctrl_home", "end", "ctrl_end"): + # Re-read the live list first so newly arrived packets are in range before we + # step — otherwise the first ``↑`` off the newest could never reach them. + self._sync() if action == "up": self._jump(self._index - 1) elif action == "down": @@ -273,15 +338,19 @@ class PacketViewer(Screen): index = max(0, min(index, len(self._entries) - 1)) if index != self._index: self._index = index + self._current = self._entries[index] self.scroll = 0 self._set_title() if self._on_navigate is not None: - self._on_navigate(self._entries[index]) + self._on_navigate(self._current) # --- rendering ------------------------------------------------------------- def render_body(self, width: int) -> list[str]: """Lay the current entry out as labelled rows, flavoured by its kind.""" + # Fold in any packets that arrived since the last paint, keeping the view on the + # same packet, so the title's ``n/total`` and the reachable range stay current. + self._sync() entry = self._entries[self._index] grid = Table( box=None, show_header=False, show_edge=False, pad_edge=False, @@ -373,7 +442,7 @@ class PacketViewer(Screen): rows: list[tuple[str, RenderableType]] = [] typename = raw.get("payload_typename") if typename: - rows.append(("class", Text(_PAYLOAD_GLOSS.get(typename, typename.lower())))) + rows.append(("class", Text(payload_class(raw) or typename.lower()))) route = raw.get("route_typename") if route: rows.append(("route", Text(route.replace("_", " ").lower()))) diff --git a/meshterm/ui/timemachine_screen.py b/meshterm/ui/timemachine_screen.py index 9730a6d..b55dc53 100644 --- a/meshterm/ui/timemachine_screen.py +++ b/meshterm/ui/timemachine_screen.py @@ -30,7 +30,7 @@ from rich.console import Group, RenderableType from rich.text import Text from ..core.models import utcnow -from .braillechart import GAP, axis_caption, axis_chart, chart_span, timeline_rows +from .braillechart import GAP, axis_chart, chart_span, timeline_rows from .theme import snr_style from .tui.render import render_lines from .tui.screen import Screen @@ -59,9 +59,6 @@ _WINDOWS: tuple[tuple[str, Optional[timedelta]], ...] = ( #: Picker sentinel for the whole-mesh overview page. MESH = ("mesh",) -#: Character cells the charts keep clear for their side gutters. -_GUTTER = 4 - #: How many braille rows tall the volume/rhythm charts draw. _CHART_ROWS = 2 @@ -98,25 +95,6 @@ def _snr_cell_style(values: list[float]) -> str: return snr_style(sum(values) / len(values)) -def _chart_block( - rows: list[Text], label_at: Callable[[float], str], chars: int -) -> list[RenderableType]: - """Indent chart rows into the gutter and add the oldest→now caption line. - - The caption is the shared :func:`~meshterm.ui.braillechart.axis_caption`, so a - wide chart gains intermediate time marks between its two edge labels for free. - """ - out: list[RenderableType] = [] - for row in rows: - line = Text(" ") - line.append_text(row) - out.append(line) - caption = Text(" ") - caption.append_text(axis_caption(chars, label_at)) - out.append(caption) - return out - - def _time_axis(start: datetime, end: datetime) -> Callable[[float], str]: """An axis labeller over a real time span: timestamps left of the closing ``now``.""" def label_at(frac: float) -> str: @@ -127,10 +105,20 @@ def _time_axis(start: datetime, end: datetime) -> Callable[[float], str]: def _hour_axis(frac: float) -> str: - """The rhythm charts' labeller: the local hour of day at ``frac`` of the sweep.""" + """The node rhythm's labeller: the local hour of day at ``frac`` of the 24-slot sweep.""" return f"{round(frac * 23)} h" +def _quarter_axis(frac: float) -> str: + """The mesh rhythm's labeller: the local hour at ``frac`` of a full-day quarter-hour sweep. + + The 96 fifteen-minute slices span midnight to midnight, so the fraction maps onto the + whole ``0 → 24 h`` day (the right edge closing on ``24 h``), landing the intermediate + marks on clean six-hour boundaries. + """ + return f"{round(frac * 24)} h" + + def _heading(title: str, note: str) -> Text: """A section heading in the dashboard's voice: accent title, muted note.""" text = Text(title, style="accent") @@ -228,43 +216,53 @@ def _node_sections( Text("Press w to widen it.", style="muted"), ] start = since or observations[0].observed_at - chars = max(20, width - 2 * _GUTTER) - buckets = chars * 2 - - out: list[RenderableType] = [] stamps = [o.observed_at for o in observations] - out.append( - _heading("Volume", f"{len(observations)} receptions · now at the right") - ) - out.extend( - _chart_block( - timeline_rows(bucketize(stamps, start, now, buckets), rows=_CHART_ROWS), - _time_axis(start, now), chars, - ) - ) - snr_pairs = [ (o.observed_at, float(o.snr)) for o in observations if o.snr is not None ] + + # Volume and SNR share one y-axis gutter width (like the mesh page's day pair) so + # their axes line up; a provisional width finds the peaks that size the gutter, then + # the real width re-buckets the bars flush with it. The rhythm below is its own + # narrow chart, so it keeps its own gutter. + def _layout(label_w: int) -> tuple[int, int]: + chars = max(20, width - 2 * (label_w + 2)) + return chars, chars * 2 + + chars, buckets = _layout(1) + volume = bucketize(stamps, start, now, buckets) + lo, hi = chart_span(bucket_medians(snr_pairs, start, now, buckets)) if snr_pairs else (0.0, 0.0) + label_w = max(1, len(str(max(volume))), len(str(round(hi))), len(str(round(lo)))) + chars, buckets = _layout(label_w) + volume = bucketize(stamps, start, now, buckets) + + out: list[RenderableType] = [] + out.append(_heading("Volume", f"{len(observations)} receptions")) + out.extend( + axis_chart( + timeline_rows(volume, rows=_CHART_ROWS), + max(volume), chars, _time_axis(start, now), label_w=label_w, + ) + ) + if snr_pairs: medians = bucket_medians(snr_pairs, start, now, buckets) lo, hi = chart_span(medians) rows = timeline_rows(medians, rows=_SNR_ROWS, style=_snr_cell_style) out.append(Text()) - out.append( - _heading( - "SNR", - f"median per slice · grey line = 0 · scale {lo:+.1f} → {hi:+.1f} dB", + out.append(_heading("SNR", "median dB per slice · grey line = 0")) + out.extend( + axis_chart( + rows, hi, chars, _time_axis(start, now), label_w=label_w, floor=lo, ) ) - out.extend(_chart_block(rows, _time_axis(start, now), chars)) hours = [0] * 24 for stamp in stamps: hours[stamp.astimezone().hour] += 1 out.append(Text()) out.append(_heading("Rhythm", "receptions by local hour of day")) - out.extend(_chart_block(timeline_rows(hours, rows=_CHART_ROWS), _hour_axis, 12)) + out.extend(axis_chart(timeline_rows(hours, rows=_CHART_ROWS), max(hours), 12, _hour_axis)) out.append(Text()) out.append(_heading("Record", "this window")) @@ -299,24 +297,75 @@ def _node_sections( # --- the mesh page ----------------------------------------------------------------------- -def _day_axis(shown: list) -> Callable[[float], str]: - """An axis labeller over the day charts: compact dates, ``today`` at the right. +def _day_centers(days: int, chars: int) -> list[int]: + """The chart cell each day's bar is centred on, mirroring :func:`_day_columns`. - Dates render in the caption style the rest of the app speaks (``Jul 05``, not - raw ISO), and the right edge reads ``today`` when the newest charted day is - today — mirroring the node page's closing ``now``. + Replays the same even split ``_day_columns`` uses to spread ``days`` bars across + ``2 × chars`` dot columns, so a tick placed at ``centers[i]`` lands under day + ``i``'s bar rather than at an arbitrary fraction of the axis. + + Args: + days: How many day bars the chart draws. + chars: The chart's width in character cells. + + Returns: + One centre cell (``0 .. chars - 1``) per day, oldest first. """ - today = utcnow().strftime("%Y-%m-%d") + n = max(1, days) + centers: list[int] = [] + dot = 0 # running dot-column offset, two per character cell + base, extra = divmod(chars, n) if n <= chars else divmod(chars * 2, n) + for i in range(n): + span = (base + (1 if i < extra else 0)) * (2 if n <= chars else 1) + centers.append(min(chars - 1, (dot + span // 2) // 2)) + dot += span + return centers - def label_at(frac: float) -> str: - iso = shown[min(len(shown) - 1, round(frac * (len(shown) - 1)))][0] - if frac >= 1.0 and iso == today: - return "today" + +def _day_ticks(shown: list, chars: int) -> list[tuple[int, str]]: + """``(cell, label)`` axis ticks under the day bars: short dates, thinned to fit. + + One tick per day where they all fit, else an evenly spaced subset keeping both + ends; each label sits under its own bar (see :func:`_day_centers`). Dates are + kept compact — the month is shown only on the first tick and whenever it rolls + over, so most ticks read as a bare day number — and the newest bar reads + ``today`` when it is, mirroring the node page's closing ``now``. + + Args: + shown: The charted days, oldest first, each ``(iso_date, ...)``. + chars: The chart's width in character cells. + + Returns: + The ticks to pass to :func:`~meshterm.ui.braillechart.axis_chart`. + """ + n = len(shown) + centers = _day_centers(n, chars) + today = utcnow().strftime("%Y-%m-%d") + # A dated label is at most "Jul 12" (6 cells); keep a couple of cells between them. + fit = max(2, chars // 8) + if n <= fit: + picks = list(range(n)) + else: + picks = sorted({round(i * (n - 1) / (fit - 1)) for i in range(fit)}) + ticks: list[tuple[int, str]] = [] + prev_month: Optional[str] = None + for i in picks: + iso = shown[i][0] try: - return datetime.strptime(iso, "%Y-%m-%d").strftime("%b %d") + day = datetime.strptime(iso, "%Y-%m-%d") except ValueError: - return iso - return label_at + ticks.append((centers[i], iso)) + continue + month = day.strftime("%b") + if i == n - 1 and iso == today: + label = "today" + elif month != prev_month: + label = f"{month} {day.day}" + else: + label = str(day.day) + prev_month = month + ticks.append((centers[i], label)) + return ticks def _day_columns(values: list[int], chars: int) -> list: @@ -406,11 +455,12 @@ def _mesh_sections( shown = days[-chars * 2 :] out: list[RenderableType] = [] packets = [d[1] for d in shown] - out.append(_heading("Packets per day", "UTC days · newest at the right")) + day_ticks = _day_ticks(shown, chars) + out.append(_heading("Packets per day", "UTC days")) out.extend( axis_chart( timeline_rows(_day_columns(packets, chars), rows=_CHART_ROWS), - max(packets), chars, _day_axis(shown), label_w=label_w, + max(packets), chars, label_w=label_w, ticks=day_ticks, ) ) @@ -420,21 +470,22 @@ def _mesh_sections( out.extend( axis_chart( timeline_rows(_day_columns(nodes, chars), rows=_CHART_ROWS), - max(nodes), chars, _day_axis(shown), label_w=label_w, + max(nodes), chars, label_w=label_w, ticks=day_ticks, ) ) - # The node page's rhythm chart, mesh-wide: when does this *mesh* talk? Hours are - # grouped by UTC in SQL and rotated here by the current local offset (see - # Repository.hourly_activity for why one rotation is honest enough). - offset = round( - (datetime.now().astimezone().utcoffset() or timedelta()).total_seconds() / 3600 + # The node page's rhythm chart, mesh-wide and four times finer: when does this *mesh* + # talk? 15-minute slices are grouped by UTC in SQL and rotated here into local time by + # the current offset in quarter-hour units (see Repository.quarter_hour_activity for why + # one rotation is honest enough). The wider chart earns the finer resolution its width. + offset_slots = round( + (datetime.now().astimezone().utcoffset() or timedelta()).total_seconds() / 900 ) - utc_hours = ctx.repo.hourly_activity(since=since) - hours = [utc_hours[(h - offset) % 24] for h in range(24)] + utc_slots = ctx.repo.quarter_hour_activity(since=since) + slots = [utc_slots[(s - offset_slots) % 96] for s in range(96)] out.append(Text()) - out.append(_heading("Rhythm", "packets by local hour of day")) - out.extend(axis_chart(timeline_rows(hours, rows=_CHART_ROWS), max(hours), 12, _hour_axis)) + out.append(_heading("Rhythm", "packets by local time of day · 15-min slices")) + out.extend(axis_chart(timeline_rows(slots, rows=_CHART_ROWS), max(slots), 48, _quarter_axis)) arrivals = ctx.repo.first_seen(since=since) out.append(Text()) diff --git a/meshterm/ui/tui/render.py b/meshterm/ui/tui/render.py index 1ecd951..acbcb1c 100644 --- a/meshterm/ui/tui/render.py +++ b/meshterm/ui/tui/render.py @@ -93,6 +93,43 @@ def render_lines(renderable: RenderableType, width: int, *, no_wrap: bool = Fals return lines +def right_aligned_tail(body: Text, tail: Text, width: int) -> Text: + """Lay ``body`` out with ``tail`` pinned to the right edge of its last line. + + ``body`` wraps at ``width`` as usual; ``tail`` — a short status such as the chat + compose bar's byte counter — is right-aligned on ``body``'s final wrapped line when + it still fits there (after at least one blank cell), otherwise on a new line of its + own, also right-aligned. So the tail reads as a steady gauge in the corner rather + than trailing the cursor and wrapping along with the text. + + Args: + body: The wrappable leading content (e.g. the input line, cursor block included). + tail: The short run to pin to the right edge. + width: Total render width in columns. + + Returns: + A single :class:`Text` with embedded newlines, ready for :func:`render_lines`. + """ + width = max(1, width) + console = _console(width) + lines = list(body.wrap(console, width)) or [Text("")] + combined = Text() + for line in lines[:-1]: + combined.append_text(line) + combined.append("\n") + last = lines[-1] + gap = width - last.cell_len - tail.cell_len + if gap >= 1: + combined.append_text(last) + combined.append(" " * gap) + else: + combined.append_text(last) + combined.append("\n") + combined.append(" " * max(0, width - tail.cell_len)) + combined.append_text(tail) + return combined + + def render_hanging(prefix: Text, body: Text, width: int, *, indent: int) -> list[str]: """Render ``prefix + body`` at ``width``, wrapping the body with a hanging indent. diff --git a/meshterm/ui/watchtower_screen.py b/meshterm/ui/watchtower_screen.py index f5a9b4d..9323eb7 100644 --- a/meshterm/ui/watchtower_screen.py +++ b/meshterm/ui/watchtower_screen.py @@ -242,12 +242,13 @@ async def _node_rules(ctx: "AppContext", key: str) -> None: Choice("📶 SNR watch " + ("on" if entry.snr_watch else "off"), "snr"), Separator(""), Choice("✖ Stop watching this node", "unwatch"), + Choice("← Close", None), ] picked = await session.select( f"Rules — {entry.name}", items, filterable=False, footer_hint="↑↓ move · Enter change · Esc back", ) - if picked is None: + if picked is None: # Close, or Esc return if picked == "silence": await _pick_silence(ctx, key, entry) diff --git a/tests/test_braillechart.py b/tests/test_braillechart.py index 115244c..d7bbe00 100644 --- a/tests/test_braillechart.py +++ b/tests/test_braillechart.py @@ -215,6 +215,22 @@ def test_axis_chart_mirrors_marks_on_both_gutters() -> None: assert out[2].plain.startswith(" └") and out[2].plain.endswith("┘") +def test_y_axis_labels_signed_span_quotes_both_extremes() -> None: + """A signed chart's marks run from the peak down through zero toward the floor.""" + # rows=3 over +8..-4: top edge 8, middle 4, then 0 (blanked — it is the grey line). + assert y_axis_labels(8, 3, lo=-4) == ["8", "4", ""] + # A wider signed span surfaces a negative mark on the bottom row. + assert y_axis_labels(6, 3, lo=-6) == ["6", "2", "-2"] + + +def test_axis_chart_floor_frames_a_signed_chart_and_widens_the_gutter() -> None: + """A signed floor draws negative marks and sizes the gutter for the widest one.""" + rows = timeline_rows([5, -5], rows=3, span=(-5, 5)) + out = axis_chart(rows, 5, 1, lambda f: "x", floor=-5) + assert out[0].plain.startswith(" 5 ┤") # peak on top, gutter widened to two cells + assert out[2].plain.startswith("-2 ┤") # a negative mark near the floor + + def test_axis_chart_honours_a_shared_label_width() -> None: """An explicit label_w widens the gutter past the peak's own digit count. @@ -224,3 +240,24 @@ def test_axis_chart_honours_a_shared_label_width() -> None: rows = timeline_rows([9] * 8, rows=1) out = axis_chart(rows, 9, 4, lambda f: "x", label_w=3) assert out[0].plain.startswith(" 9 ┤") + + +# --- axis_chart column ticks ---------------------------------------------------------- + + +def test_axis_chart_ticks_notch_the_border_and_centre_labels() -> None: + """Explicit column ticks draw a ``┬`` on the border with the label centred beneath.""" + rows = timeline_rows([9] * 8, rows=1) + out = axis_chart(rows, 9, 4, ticks=[(0, "A"), (3, "D")]) + assert out[1].plain == " └┬──┬┘" # ticks at chart cells 0 and 3 + assert out[2].plain == " A D" # labels centred under their ticks + + +def test_axis_chart_ticks_thin_a_label_that_would_collide() -> None: + """A tick whose label would overprint the one before it is dropped, tick and all.""" + rows = timeline_rows([9] * 16, rows=1) + out = axis_chart(rows, 9, 8, ticks=[(0, "aaaa"), (2, "aaaa"), (7, "b")]) + border, caption = out[1].plain, out[2].plain + assert caption.count("aaaa") == 1 # the crowded twin was skipped + assert "b" in caption + assert border.count("┬") == 2 # …and its tick with it (only two survive) diff --git a/tests/test_chat.py b/tests/test_chat.py index 08d4239..aeee0c6 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -560,12 +560,15 @@ def test_byte_counter_shows_used_over_limit_and_colors_only_used() -> None: counter = screen._byte_counter(screen._byte_limit()) assert isinstance(counter, Text) assert counter.plain.strip() == "5/150" # 5 bytes used of the 150-byte direct-message cap - # The budget rides the input line itself, right after the compose text, so it can - # never be the one row a full transcript pushes off the bottom of the viewport. + # The budget is pinned to the input line's right edge (padded out from the compose text, + # not trailing the cursor), while still sharing the input's own row so a full transcript + # can never push it off the bottom of the viewport. import re body = re.sub(r"\x1b\[[0-9;]*m", "", "\n".join(screen.render_body(80))) - assert re.search(r"› hello.*5/150", body) + input_row = next(line for line in body.splitlines() if "5/150" in line) + assert re.search(r"› hello +5/150$", input_row.rstrip()) # a gap of padding, flush right + assert len(input_row.rstrip()) == 80 # the counter reaches the right edge of the width # Only the "5" carries a color; the "/150" tail stays muted (it never changes). used_at = counter.plain.index("5") slash_at = counter.plain.index("/") @@ -575,6 +578,25 @@ def test_byte_counter_shows_used_over_limit_and_colors_only_used() -> None: assert tail_spans and tail_spans[0].style == "muted" +def test_byte_counter_stays_bottom_right_when_the_compose_wraps() -> None: + """A compose line long enough to wrap keeps the counter pinned to the last line's + right edge — not trailing the cursor down onto the second row.""" + import re + + screen = _screen(_StubSession(), send=None) + text = "this is a long compose line that certainly wraps onto several rows here ok" + for ch in text: + screen.handle("text", ch) + counter = f"{len(text)}/150" + body = re.sub(r"\x1b\[[0-9;]*m", "", "\n".join(screen.render_body(40))) + counter_rows = [line for line in body.splitlines() if counter in line] + assert len(counter_rows) == 1 + row = counter_rows[0] + assert row.rstrip().endswith(counter) # flush right, not mid-line after the text + assert len(row.rstrip()) == 40 # reaches the render width's right edge + assert not row.lstrip().startswith("›") # on a wrapped row, not the first input row + + def test_byte_style_escalates_as_budget_runs_out() -> None: """The used-byte color steps green → yellow → orange → red as fewer bytes remain.""" from meshterm.ui.chat import _BYTES_ORANGE, _BYTES_YELLOW diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 8ca8144..3f692c9 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -8,7 +8,7 @@ covered in ``test_braillechart``.) from __future__ import annotations import re -from datetime import timedelta +from datetime import datetime, timedelta, timezone from pathlib import Path from meshterm.core.events import MeshEvent @@ -140,6 +140,33 @@ def test_dashboard_packet_rows_show_their_relay_path() -> None: assert "via YUL → Alice" in _plain(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: """Observations older than the window drop out of the statistics.""" stale = _obs(age_s=3 * 3600, snr=-12.0) @@ -148,6 +175,25 @@ 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 screenful at a time.""" + window = [_obs(node=f"n{i}", age_s=i) for i in range(20)] + screen = _screen(window=window) + screen.note_metrics(total=40, viewport=6) # a screenful is _page_step = 5 rows + screen.handle("down") # first press lands the highlight on the newest feed row + assert screen._selected == 0 + 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 free-scroll the body as before. + screen._selected = None + screen.scroll = 0 + screen.handle("pagedown") + assert screen.scroll > 0 and screen._selected is None + + 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) @@ -183,3 +229,82 @@ def test_recent_observations_windows_and_orders(tmp_path: Path) -> None: assert [o.node for o in window] == ["mid", "new"] assert window[0].kind == "packet" and window[0].path == "3d63" repo.close() + + +def test_recent_observations_rehydrate_channel_text_for_decryption(tmp_path: Path) -> None: + """A stored GRP_TXT frame comes back with the fields the packet viewer decrypts from.""" + from Crypto.Cipher import AES + from Crypto.Hash import HMAC, SHA256 + + from meshterm.core.channels import channel_hash, derive_secret + from meshterm.ui.packet_viewer import PacketEntry, PacketViewer + + name, secret = "#general", derive_secret("#general") + plain = (0).to_bytes(4, "little") + bytes([0]) + b"hi from history" + plain += b"\x00" * (-len(plain) % 16) + crypted = AES.new(secret, AES.MODE_ECB).encrypt(plain) + mac = HMAC.new(secret, digestmod=SHA256) + mac.update(crypted) + raw = { + "payload_typename": "GRP_TXT", + "chan_hash": channel_hash(secret), + "cipher_mac": mac.digest()[:2].hex(), + "crypted": crypted.hex(), + } + + repo = Repository(tmp_path / "chan.db") + run = repo.start_run("monitor", {}, None) + repo.record_observation(run, _obs(node="src", kind="packet", path="3d63", raw=raw)) + repo.record_observation(run, _obs(node="adv", kind="advert")) # a plain advert nearby + + window = {o.node: o for o in repo.recent_observations(since=utcnow() - timedelta(hours=2))} + stored = window["src"] + assert stored.raw is not None and stored.raw["chan_hash"] == channel_hash(secret) + assert window["adv"].raw is None # nothing to rebuild from → no raw, as before + + # The stored frame decrypts straight out of history — the whole point of persisting it. + viewer = PacketViewer( + [PacketEntry.from_observation(stored)], 0, + resolve=lambda h: "", channels=[(name, secret)], + ) + body = "\n".join(re.sub(r"\x1b\[[0-9;]*m", "", ln) for ln in viewer.render_body(80)) + assert "#general" in body and "hi from history" in body + repo.close() + + +def test_recent_observations_rehydrate_the_packet_payload_class(tmp_path: Path) -> None: + """A stored ``packet`` comes back carrying its payload class, so a list can name it.""" + repo = Repository(tmp_path / "cls.db") + run = repo.start_run("monitor", {}, None) + repo.record_observation( + run, + _obs(node="", kind="packet", path="3d63", raw={"payload_typename": "TRACE"}), + ) + repo.record_observation(run, _obs(node="a1b2", kind="advert")) # a plain advert nearby + + window = {o.node or "": o for o in repo.recent_observations(since=utcnow() - timedelta(hours=2))} + assert window[""].raw is not None and window[""].raw["payload_typename"] == "TRACE" + assert window["a1b2"].raw is None # an advert keeps no packet raw, as before + repo.close() + + +def test_quarter_hour_activity_buckets_by_15_minute_slice(tmp_path: Path) -> None: + """Observations fall into 96 quarter-hour-of-day slots (``HH * 4 + MM // 15``).""" + repo = Repository(tmp_path / "q.db") + run = repo.start_run("monitor", {}, None) + + def at(hh: int, mm: int) -> Observation: + return Observation( + node="n", name="n", kind="advert", + observed_at=datetime(2026, 7, 8, hh, mm, tzinfo=timezone.utc), + ) + + for hh, mm in [(0, 0), (0, 44), (17, 55), (17, 59)]: + repo.record_observation(run, at(hh, mm)) + slots = repo.quarter_hour_activity() + assert len(slots) == 96 + assert slots[0] == 1 # 00:00 → slot 0 + assert slots[2] == 1 # 00:44 → slot 2 (44 // 15) + assert slots[71] == 2 # 17:55 and 17:59 → slot 17*4 + 3 + assert sum(slots) == 4 + repo.close() diff --git a/tests/test_packet_viewer.py b/tests/test_packet_viewer.py index 447242d..6ce7de3 100644 --- a/tests/test_packet_viewer.py +++ b/tests/test_packet_viewer.py @@ -68,6 +68,36 @@ def test_packet_viewer_reports_an_unknown_channel() -> None: assert "unknown" in body and "can't decrypt" in body +def test_packet_viewer_reaches_packets_that_arrive_after_open() -> None: + """A live source lets the viewer page up into packets that arrive after it opens.""" + old = PacketEntry(when=utcnow(), kind="advert", node="aa") + feed = [old] + viewer = PacketViewer(list(feed), 0, resolve=lambda h: "", source=lambda: list(feed)) + assert viewer._entries[viewer._index] is old + + # A newer packet is prepended (the feed is newest-first) while the dialog sits on the + # old one; a repaint folds it in and the view stays put on `old` (now at index 1). + newer = PacketEntry(when=utcnow(), kind="message", node="bb", text="new!") + feed.insert(0, newer) + viewer.render_body(80) + assert viewer._entries[viewer._index] is old + assert "2/2" in viewer.title + + # ↑ (newer) now reaches the packet that arrived after the dialog opened. + viewer.handle("up") + assert viewer._entries[viewer._index] is newer + assert "1/2" in viewer.title + + +def test_packet_viewer_without_a_source_stays_a_snapshot() -> None: + """With no live source the viewer is frozen on its opening list (unchanged behaviour).""" + entry = PacketEntry(when=utcnow(), kind="advert", node="aa") + viewer = PacketViewer([entry], 0, resolve=lambda h: "") + viewer.render_body(80) + assert viewer._entries == [entry] + assert viewer.footer_hint == "Esc close" + + def test_packet_viewer_raw_dump_skips_fields_folded_into_flavoured_rows() -> None: """Fields already shown as class/route/via/channel rows don't also dump generically.""" entry = _grp_txt_entry({ diff --git a/tests/test_timemachine.py b/tests/test_timemachine.py index 7d911c9..14cd2db 100644 --- a/tests/test_timemachine.py +++ b/tests/test_timemachine.py @@ -16,7 +16,9 @@ from meshterm.persistence.repository import Repository from meshterm.ui.braillechart import GAP from meshterm.ui.timemachine_screen import ( TimeMachineScreen, + _day_centers, _day_columns, + _day_ticks, _mesh_sections, _node_sections, _snr_cell_style, @@ -168,6 +170,47 @@ def test_day_columns_always_hits_the_exact_width() -> None: assert len(cols) == chars * 2, (n, chars) +def test_day_centers_land_under_each_bar() -> None: + """A day's centre cell sits within its own bar's span (so a tick points at it).""" + chars = 60 + n = 7 + centers = _day_centers(n, chars) + assert len(centers) == n + base = chars / n + for i, cell in enumerate(centers): + assert i * base <= cell <= (i + 1) * base # inside day i's character span + assert centers == sorted(centers) and centers[-1] <= chars - 1 + + +def test_day_ticks_shorten_dates_and_align_to_bars() -> None: + """One tick per day when they fit: month only on the first, bare day numbers after.""" + days = [(f"2026-07-{d:02d}", 10, 3) for d in range(1, 8)] # Jul 1..7 + chars = 60 + ticks = _day_ticks(days, chars) + assert [cell for cell, _ in ticks] == _day_centers(len(days), chars) # under the bars + labels = [label for _, label in ticks] + assert labels[0] == "Jul 1" # month printed once, on the first tick + assert labels[1:] == ["2", "3", "4", "5", "6", "7"] # bare day numbers after it + + +def test_day_ticks_reprint_the_month_on_a_rollover() -> None: + """The month reappears the first time a new one starts, so a boundary reads clearly.""" + days = [(iso, 1, 1) for iso in ("2026-06-29", "2026-06-30", "2026-07-01", "2026-07-02")] + labels = [label for _, label in _day_ticks(days, 60)] + assert labels == ["Jun 29", "30", "Jul 1", "2"] + + +def test_day_ticks_thin_to_fit_keeping_both_ends() -> None: + """More days than labels fit: an evenly spaced subset is kept, first and last included.""" + days = [(f"2026-06-{d:02d}", 1, 1) for d in range(1, 31)] # 30 days + chars = 40 # ~5 dated labels fit (chars // 8) + ticks = _day_ticks(days, chars) + centers = _day_centers(len(days), chars) + assert 2 <= len(ticks) <= 6 + cols = [cell for cell, _ in ticks] + assert cols[0] == centers[0] and cols[-1] == centers[-1] # both ends survive the thinning + + def test_day_columns_notches_the_first_dot_of_a_multi_character_day() -> None: """A day wide enough to span several characters opens with a GAP dot column.""" cols = _day_columns([2, 8, 4], 12) # 3 days, 12 chars -> 4 chars (8 dots) each @@ -243,7 +286,7 @@ def test_mesh_page_renders_days_rhythm_arrivals_and_ledger(tmp_path: Path) -> No ctx = SimpleNamespace(repo=repo) body = _plain(_mesh_sections(ctx, None, 90, prefix_bytes=2)) assert "Packets per day" in body and "Nodes per day" in body - assert "Rhythm" in body and "local hour" in body + assert "Rhythm" in body and "15-min" in body # 15-minute slices, four per hour assert "Arrivals" in body and "Newcomer" in body # Arrivals are aligned lanes: the hash sits in its own column and the old # per-row "first heard" prefix now lives once, in the column header. @@ -258,16 +301,41 @@ def test_mesh_page_day_chart_axis_matches_the_bar_width(tmp_path: Path) -> None: A rounding mismatch here (the old ``_day_columns``) leaves the border and caption sized for a wider chart than the bars actually drawn — the bars - reading as shifted left of an axis drawn for more columns than exist. + reading as shifted left of an axis drawn for more columns than exist. The + border now carries ``┬`` tick marks under the dated columns, so its interior + is counted as dashes *and* ticks together. """ repo = _seeded_repo(tmp_path) ctx = SimpleNamespace(repo=repo) lines = _plain(_mesh_sections(ctx, None, 90), width=90).split("\n") - border_idx = next(i for i, line in enumerate(lines) if re.fullmatch(r"\s*└─+┘", line)) - border_dashes = lines[border_idx].count("─") + heading_idx = next(i for i, line in enumerate(lines) if "Packets per day" in line) + border_idx = next( + i for i, line in enumerate(lines[heading_idx:], heading_idx) + if re.fullmatch(r"\s*└[─┬]+┘", line) + ) + border_interior = len(re.search(r"└([─┬]+)┘", lines[border_idx]).group(1)) row_line = lines[border_idx - 1] content = re.search(r"[┤│](.*?)[├│]", row_line).group(1) - assert len(content) == border_dashes + assert len(content) == border_interior + repo.close() + + +def test_mesh_page_day_axis_ticks_sit_under_dated_columns(tmp_path: Path) -> None: + """The day chart notches its border with ``┬`` and labels the ticks with dates.""" + repo = _seeded_repo(tmp_path) + ctx = SimpleNamespace(repo=repo) + lines = _plain(_mesh_sections(ctx, None, 90), width=90).split("\n") + heading_idx = next(i for i, line in enumerate(lines) if "Packets per day" in line) + border = next( + line for line in lines[heading_idx:] if re.fullmatch(r"\s*└[─┬]+┘", line) + ) + caption = lines[lines.index(border) + 1] + tick_cols = [i for i, ch in enumerate(border) if ch == "┬"] + assert tick_cols, "the day axis should carry tick marks" + # The seeded history ends today, so the newest bar's tick reads 'today'. + assert "today" in caption + # Every tick has a non-blank label somewhere near it (labels centre on their tick). + assert any(not caption[max(0, c - 3):c + 4].isspace() for c in tick_cols) repo.close()