Packets say which region a flood was scoped to
The packet viewer's route row reads "flood · scope harbour" (or "scoped · 3fa1" for a region nobody here has named, or "unscoped") instead of the library's bare "tc flood"; a direct frame keeps its route word and states no scope. The live feed gains a SCOPE lane where the width holds it, 72 columns included (the subject lends it one cell); the PicoCalc's row already scrolls at 53 and leaves the scope to the viewer. The message paths dialog states a message's scope once, as a title atom, read off its arrivals' frames. monitor streams a SCOPE lane before NAME, and the scope object (or null) under --json. The viewer and the feed take the region store's scope_of by injection, falling back to reading the frame alone, and the viewer's card cache keys on the scope so a region learned while it is open renames it. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
c3c0ccf9f9
commit
2785380d6b
9 files changed
+758
-30
No files matched your search
+7
-6
@@ -880,11 +880,11 @@ the live view.
|
||||
|
||||
```console
|
||||
$ meshterm monitor --seconds 2
|
||||
TIME NODE SNR_DB RSSI_DBM LOCATION NAME
|
||||
2026-09-08T04:26:00-04:00 a1b2c3d4 +7.0 -101 45.50190,-73.56740 Yagi-Repeater
|
||||
2026-09-08T04:26:00-04:00 b2c3d4e5 +9.5 -98 45.47680,-73.59900 Local-Repeater
|
||||
2026-09-08T04:26:00-04:00 c3d4e5f6 +4.9 -93 - Observer-Bot
|
||||
2026-09-08T04:26:00-04:00 d4e5f6a7 +7.4 -86 - Alice
|
||||
TIME NODE SNR_DB RSSI_DBM LOCATION SCOPE NAME
|
||||
2026-09-08T04:26:00-04:00 a1b2c3d4 +7.0 -101 45.50190,-73.56740 - Yagi-Repeater
|
||||
2026-09-08T04:26:00-04:00 b2c3d4e5 +9.5 -98 45.47680,-73.59900 - Local-Repeater
|
||||
2026-09-08T04:26:00-04:00 c3d4e5f6 +4.9 -93 - - Observer-Bot
|
||||
2026-09-08T04:26:00-04:00 d4e5f6a7 +7.4 -86 - - Alice
|
||||
NODE NAME PKTS MEDIAN_SNR_DB BEST_SNR_DB RSSI_DBM HEARD LOCATION
|
||||
d4e5f6a7 Alice 149 +6.9 +14.1 -93 now -
|
||||
c3d4e5f6 Observer-Bot 148 +5.7 +13.0 -108 now -
|
||||
@@ -903,7 +903,7 @@ stream cannot give: a count, a median, a best per node, most recently heard firs
|
||||
same shape, and **no summary document at the end**:
|
||||
|
||||
```json
|
||||
{"observed_at":"2026-09-08T08:30:40Z","node":{"name":"Yagi-Repeater","key":"a1b2c3d400000000000000000000000000000000000000000000000000000000","hash":"a1b2c3d4","type":"repeater","self":false},"kind":"advert","snr_db":7.0,"rssi_dbm":-101.3,"position":{"lat":45.5019,"lon":-73.5674},"path":null}
|
||||
{"observed_at":"2026-09-08T08:30:40Z","node":{"name":"Yagi-Repeater","key":"a1b2c3d400000000000000000000000000000000000000000000000000000000","hash":"a1b2c3d4","type":"repeater","self":false},"kind":"advert","snr_db":7.0,"rssi_dbm":-101.3,"position":{"lat":45.5019,"lon":-73.5674},"scope":null,"path":null}
|
||||
```
|
||||
|
||||
| Field | Type | Meaning |
|
||||
@@ -914,6 +914,7 @@ same shape, and **no summary document at the end**:
|
||||
| `snr_db` | number \| null | |
|
||||
| `rssi_dbm` | number \| null | |
|
||||
| `position` | object \| null | The `position` shape. |
|
||||
| `scope` | object \| null | The region a flood was sent into: `{"state", "region", "code"}`. `state` is `"scoped"` (`region` names it), `"unknown"` (scoped, but no region known here reproduces `code`) or `"unscoped"` (a plain flood). `code` is the frame's transport code as lowercase hex, kept even when unresolved so two packets can be seen to share a region. `null` for a direct packet, or a class whose route was never reported — a repeater never region-filters those. The plain `SCOPE` lane prints the region, `unknown`, `unscoped` or `-`. |
|
||||
| `path` | array of strings \| null | The relay chain the packet arrived by, one lowercase-hex hash per hop, in propagation order. `[]` is a direct reception; `null` means the packet class carries no path at all. This is the one place `path` is an array — it is a *received* relay chain rather than a composed spec. |
|
||||
|
||||
**This is the one place a whole block appears on one face and not the other, and it is
|
||||
|
||||
@@ -36,8 +36,8 @@ Nothing here transmits; it is a read-model over the repository.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass, replace
|
||||
from collections.abc import Callable, Sequence
|
||||
from dataclasses import dataclass, field, replace
|
||||
from datetime import datetime, timedelta
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
@@ -46,6 +46,7 @@ from ..core.frames import ENDPOINT_HASH_BYTES
|
||||
from ..core.models import ChatMessage, Observation
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..core.regions import Scope
|
||||
from ..persistence.repository import Repository
|
||||
|
||||
#: How far around a channel message the log is searched. Wide, because an inbound
|
||||
@@ -104,6 +105,9 @@ class Arrival:
|
||||
repeater in earshot, so one message routinely leaves a dozen frames on two
|
||||
paths; listing them individually said "twelve arrivals" where the truth was
|
||||
"two paths, six times each".
|
||||
frame: The logged frame's raw payload — what :func:`message_scope` reads the
|
||||
message's scope from. Not part of an arrival's identity (two copies on one path
|
||||
are one row whatever else their frames carry), so it takes no part in equality.
|
||||
"""
|
||||
|
||||
when: datetime
|
||||
@@ -112,6 +116,7 @@ class Arrival:
|
||||
resend: int = 0
|
||||
routed: bool | None = None
|
||||
copies: int = 1
|
||||
frame: dict | None = field(default=None, compare=False, repr=False)
|
||||
|
||||
@property
|
||||
def route_known(self) -> bool:
|
||||
@@ -196,6 +201,7 @@ def channel_arrivals(
|
||||
snr=frame.snr,
|
||||
resend=decrypted.attempt,
|
||||
routed=_frame_routed(raw),
|
||||
frame=raw,
|
||||
)
|
||||
)
|
||||
return arrivals
|
||||
@@ -337,6 +343,7 @@ def direct_arrivals(
|
||||
hops=_frame_hops(frame),
|
||||
snr=frame.snr,
|
||||
routed=_frame_routed(raw),
|
||||
frame=raw,
|
||||
)
|
||||
mac = str(raw.get("cipher_mac") or "").lower()
|
||||
if mac:
|
||||
@@ -386,6 +393,45 @@ def collapse(arrivals: Sequence[Arrival]) -> list[Arrival]:
|
||||
return list(folded.values())
|
||||
|
||||
|
||||
def message_scope(
|
||||
arrivals: Sequence[Arrival], scope_of: Callable[[dict | None], Scope | None]
|
||||
) -> Scope | None:
|
||||
"""The one scope a message was flooded under, read off its arrivals' frames.
|
||||
|
||||
A transport code is a keyed hash of the payload alone — neither the header nor the
|
||||
path is in it (see :mod:`~meshterm.core.regions`) — so every relay's copy carries the
|
||||
sender's code unchanged, and one message has **one** scope however many ways it
|
||||
arrived. That is why the dialog states it once rather than per arrival row.
|
||||
|
||||
Which frame answers still matters, because not every copy is a flood: a direct-routed
|
||||
copy has no scope at all. So the first scoped reading wins, a *named* one over one no
|
||||
known region reproduces (they are the same code, but a name is the better answer when
|
||||
any copy yields one); failing that, any plain-flood copy makes the message
|
||||
``unscoped``; and a message heard only direct-routed has no scope to state.
|
||||
|
||||
Args:
|
||||
arrivals: The message's arrivals, as the matchers (or :func:`collapse`) return
|
||||
them — each carrying its logged frame.
|
||||
scope_of: Reads a frame's scope (``ctx.region_store.scope_of``).
|
||||
|
||||
Returns:
|
||||
The message's scope, or ``None`` where no copy was a flood.
|
||||
"""
|
||||
unscoped: Scope | None = None
|
||||
unnamed: Scope | None = None
|
||||
for arrival in arrivals:
|
||||
scope = scope_of(arrival.frame)
|
||||
if scope is None:
|
||||
continue
|
||||
if not scope.scoped:
|
||||
unscoped = unscoped or scope
|
||||
elif scope.region:
|
||||
return scope
|
||||
else:
|
||||
unnamed = unnamed or scope
|
||||
return unnamed or unscoped
|
||||
|
||||
|
||||
def distinct_paths(arrivals: list[Arrival]) -> int:
|
||||
"""How many distinct relay paths a set of arrivals covers."""
|
||||
return len({a.hops for a in arrivals})
|
||||
@@ -112,6 +112,9 @@ class MonitorTool(Tool):
|
||||
"snr_db": obs.snr,
|
||||
"rssi_dbm": obs.rssi,
|
||||
"position": _position(obs.lat, obs.lon),
|
||||
# The region a flood was sent into, resolved against the names known
|
||||
# right now; a direct frame (or a class with no route) has none.
|
||||
"scope": ctx.region_store.scope_of(obs.raw),
|
||||
"path": _relays(obs.path),
|
||||
}
|
||||
)
|
||||
@@ -188,7 +191,9 @@ def _live_packets() -> Listing:
|
||||
"""The shape the live capture streams: one record per packet, as it lands.
|
||||
|
||||
``TIME`` is absolute where a listing's times are ages, and for the reason the whole
|
||||
rule turns on: every row of a live tail would read ``now``. The **name goes last**, so
|
||||
rule turns on: every row of a live tail would read ``now``. ``SCOPE`` says which region
|
||||
a flood was sent into (:func:`~meshterm.ui.fields.scope`), ``null`` in the document for
|
||||
a frame that has none. The **name goes last**, so
|
||||
the one field with no width cannot push a lane — which is what finally let the two
|
||||
streams have columns at all, and with them the quoting could go.
|
||||
"""
|
||||
@@ -217,9 +222,13 @@ def _live_packets() -> Listing:
|
||||
pin(fields.snr("snr_db", "SNR_DB"), 6),
|
||||
pin(fields.decimal("rssi_dbm", "RSSI_DBM", ".0f"), 8),
|
||||
pin(fields.position(), 19),
|
||||
# The flood's scope — a region name, ``unknown`` or ``unscoped``, ``-`` for a
|
||||
# frame with none. Pinned to hold the two words whole; a long region name
|
||||
# overruns and pushes the row right, which is why NAME still goes last.
|
||||
pin(fields.scope(), 10),
|
||||
fields.hidden("path"),
|
||||
),
|
||||
order=("TIME", "NODE", "SNR_DB", "RSSI_DBM", "LOCATION", "NAME"),
|
||||
order=("TIME", "NODE", "SNR_DB", "RSSI_DBM", "LOCATION", "SCOPE", "NAME"),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1180,6 +1180,7 @@ async def _make_paths_presenter(
|
||||
collapse,
|
||||
direct_arrivals,
|
||||
distinct_paths,
|
||||
message_scope,
|
||||
)
|
||||
from .message_paths_screen import MessagePathsScreen
|
||||
|
||||
@@ -1289,6 +1290,7 @@ async def _make_paths_presenter(
|
||||
destination=destination or None,
|
||||
type_of=type_of,
|
||||
key_of=key_of,
|
||||
scope=message_scope(arrivals, ctx.region_store.scope_of),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
+116
-15
@@ -11,6 +11,11 @@ to the packet viewer, which has the room to draw it as a wrapped path line over
|
||||
graph. The feed's job is to say what arrived and how well it was heard; Enter says how
|
||||
it got here.
|
||||
|
||||
Where the width allows, a **scope** lane follows the readings: the region a flood was sent
|
||||
into (``harbour``), ``scoped · 3fa1`` for a region nobody here has named, ``unscoped`` for a
|
||||
plain flood, and nothing for a direct frame, which no repeater region-filters (see
|
||||
:func:`_lanes_for` for which widths hold it, and why the PicoCalc's never does).
|
||||
|
||||
The subject lane is contextual: it holds whatever the *class* of packet is about (see
|
||||
:meth:`LiveFeedScreen._feed_subject`). An advert or a telemetry frame is about the node
|
||||
that sent it, so the lane names the node — but a channel text is about its channel, a
|
||||
@@ -54,7 +59,7 @@ import asyncio
|
||||
from collections import deque
|
||||
from collections.abc import Mapping, Sequence
|
||||
from datetime import datetime, timezone
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import TYPE_CHECKING, Any, NamedTuple
|
||||
|
||||
from rich.text import Text
|
||||
|
||||
@@ -67,17 +72,20 @@ from .packet_viewer import (
|
||||
KIND_STYLES,
|
||||
PacketEntry,
|
||||
PacketViewer,
|
||||
ScopeOf,
|
||||
class_marks,
|
||||
node_label,
|
||||
unnamed_scope,
|
||||
)
|
||||
from .pathline import SELF_GLYPH, PathHop, PathLine
|
||||
from .theme import name_style, snr_style
|
||||
from .tui.render import crop_cells, render_to_ansi
|
||||
from .tui.screen import ListWindow, Screen
|
||||
from .widgets import NameKeyResolver, TypeOf
|
||||
from .widgets import NameKeyResolver, TypeOf, scope_text
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..context import AppContext
|
||||
from ..core.regions import Scope
|
||||
|
||||
#: Seconds between full repaints while the feed is open (keeps age-sensitive chrome
|
||||
#: honest even between hub events).
|
||||
@@ -152,6 +160,62 @@ _FEED_LABEL_MIN_WIDTH = (
|
||||
+ _RSSI_LANE
|
||||
)
|
||||
|
||||
#: The scope lane's width: the longest thing :func:`~meshterm.ui.widgets.scope_text` draws
|
||||
#: for an unnamed scope (``scoped · 3fa1``), so the one reading that carries a code keeps
|
||||
#: it whole. A named region longer than this ellipsizes — its whole name is on the
|
||||
#: viewer's ``route`` row, one keypress away, like everything else a lane cuts.
|
||||
_FEED_SCOPE_WIDTH = 13
|
||||
|
||||
#: The scope lane with the gap that sets it off from the RSSI reading ahead of it.
|
||||
_SCOPE_LANE = _LANE_GAP + _FEED_SCOPE_WIDTH
|
||||
|
||||
#: The most cells the subject lane lends the scope lane when the row is that close to
|
||||
#: holding it. On a 72-column terminal the framed body is 68 cells and the icon-only row
|
||||
#: 54, so the scope lane is exactly one cell short — and one cell off an 18-cell name
|
||||
#: lane (``Hilltop-Rep…`` for ``Hilltop-Repe…``) is a far better trade than no scope at
|
||||
#: all at the width the app is designed to. Never more than that: the subject is what the
|
||||
#: row is about, and a lane that shrank to make room for another would stop naming it.
|
||||
_SUBJECT_LEND = 1
|
||||
|
||||
|
||||
class _Lanes(NamedTuple):
|
||||
"""Which of the optional lanes a paint at one width carries, and the subject's width.
|
||||
|
||||
Attributes:
|
||||
label: The class lane's text label beside its icon.
|
||||
scope: The scope lane after the readings.
|
||||
subject: The subject lane's width (:data:`_FEED_SUBJECT_WIDTH`, less whatever it
|
||||
lent the scope lane).
|
||||
"""
|
||||
|
||||
label: bool
|
||||
scope: bool
|
||||
subject: int
|
||||
|
||||
|
||||
def _lanes_for(width: int) -> _Lanes:
|
||||
"""The lanes a row can carry at ``width``, most informative first.
|
||||
|
||||
The class label comes first — it says what a packet *is*, on every row — and keeps
|
||||
the threshold it always had (:data:`_FEED_LABEL_MIN_WIDTH`). The scope lane then takes
|
||||
whatever the row has left, borrowing up to :data:`_SUBJECT_LEND` cells off the subject
|
||||
to fit. That makes the scope appear at two widths with a gap between them: at 72
|
||||
columns (the label already dropped, the icon row leaving room), and again once a wide
|
||||
terminal has room for both. In between the label wins, because a scope is ``unscoped``
|
||||
on most rows and a class never is.
|
||||
|
||||
The PicoCalc's 53 columns never carry it: the icon-only row is 54 cells before any
|
||||
scope, so it already scrolls sideways there, and a lane only reachable by ``←→`` on the
|
||||
highlighted row would be a lane nobody reads. The viewer's ``route`` row states it.
|
||||
"""
|
||||
label = width >= _FEED_LABEL_MIN_WIDTH
|
||||
row = _FEED_LABEL_MIN_WIDTH - (0 if label else _FEED_CLASS_WIDTH + _LANE_GAP)
|
||||
short = row + _SCOPE_LANE - width
|
||||
if short > _SUBJECT_LEND:
|
||||
return _Lanes(label, False, _FEED_SUBJECT_WIDTH)
|
||||
return _Lanes(label, True, _FEED_SUBJECT_WIDTH - max(0, short))
|
||||
|
||||
|
||||
#: Cells one ←/→ press shifts the highlighted row by — the app-wide select list's own
|
||||
#: step (:attr:`~meshterm.ui.tui.select.SelectScreen._HSCROLL_STEP`), so a row here
|
||||
#: scrolls at the rate a row anywhere else does.
|
||||
@@ -236,6 +300,7 @@ class LiveFeedScreen(Screen):
|
||||
channel_names: Mapping[int, str] | None = None,
|
||||
type_of: TypeOf | None = None,
|
||||
key_of: NameKeyResolver | None = None,
|
||||
scope_of: ScopeOf | None = None,
|
||||
) -> None:
|
||||
"""Create the feed over its data feeds.
|
||||
|
||||
@@ -259,6 +324,11 @@ class LiveFeedScreen(Screen):
|
||||
:func:`~meshterm.services.trace_runner.make_name_key_resolver`), so a
|
||||
channel sender the contacts or the recorder know takes its key-derived
|
||||
hue; an unresolvable name stays muted.
|
||||
scope_of: Reads a flood's scope off its raw frame against the regions known by
|
||||
name (``ctx.region_store.scope_of``) — for the scope lane, and handed to
|
||||
each opened viewer for its ``route`` row. ``None`` still tells a scoped
|
||||
flood from a plain one, showing a scoped one's code where a name would go
|
||||
(:func:`~meshterm.ui.packet_viewer.unnamed_scope`).
|
||||
"""
|
||||
super().__init__()
|
||||
self.title = "Live feed"
|
||||
@@ -270,6 +340,10 @@ class LiveFeedScreen(Screen):
|
||||
self._channel_names: Mapping[int, str] = channel_names or {}
|
||||
self._type_of = type_of
|
||||
self._key_of: NameKeyResolver = key_of or (lambda name: None)
|
||||
self._scope_of: ScopeOf = scope_of or unnamed_scope
|
||||
#: The lanes the last paint carried (see :func:`_lanes_for`) — read by the subject
|
||||
#: builders, whose crowded-lane fallbacks measure against the lane actually drawn.
|
||||
self._lanes = _lanes_for(_FEED_LABEL_MIN_WIDTH)
|
||||
#: 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)
|
||||
@@ -476,6 +550,7 @@ class LiveFeedScreen(Screen):
|
||||
channels=self._channels,
|
||||
type_of=self._type_of,
|
||||
key_of=self._key_of,
|
||||
scope_of=self._scope_of,
|
||||
# The live feed itself (newest first), so the viewer keeps up with packets
|
||||
# that arrive while it is open instead of freezing at this snapshot.
|
||||
source=lambda: list(self._feed),
|
||||
@@ -497,17 +572,17 @@ class LiveFeedScreen(Screen):
|
||||
if self._selected is None:
|
||||
self._hmax = 0 # nothing highlighted scrolls, so nothing advertises ←→
|
||||
self._pinned = False # a feed with no rows has nothing to pin to
|
||||
show_label = width >= _FEED_LABEL_MIN_WIDTH
|
||||
lanes = self._lanes = _lanes_for(width)
|
||||
lines: list[str] = []
|
||||
if self._feed: # a header over nothing is noise; the empty note speaks for itself
|
||||
lines.append(render_to_ansi(self._column_header(show_label), width, no_wrap=True))
|
||||
lines.append(render_to_ansi(self._column_header(lanes), width, no_wrap=True))
|
||||
win = max(1, self._scroll_viewport - len(lines))
|
||||
lines.extend(self._feed_lines(width, win, show_label))
|
||||
lines.extend(self._feed_lines(width, win, lanes))
|
||||
self._scroll_total = max(1, len(lines))
|
||||
return lines
|
||||
|
||||
@staticmethod
|
||||
def _column_header(show_label: bool) -> Text:
|
||||
def _column_header(lanes: _Lanes) -> Text:
|
||||
"""The lane names, in the app's uppercase muted column-header voice.
|
||||
|
||||
Laid out lane for lane against :meth:`_feed_row`, the pointer column included, so
|
||||
@@ -527,10 +602,10 @@ class LiveFeedScreen(Screen):
|
||||
header.append(fit_cells("TIME", _TIME_LANE))
|
||||
header.append(
|
||||
fit_cells("CLASS", _ICON_LANE + _FEED_CLASS_WIDTH + _LANE_GAP)
|
||||
if show_label
|
||||
if lanes.label
|
||||
else " " * _ICON_LANE
|
||||
)
|
||||
header.append(fit_cells("SUBJECT", _FEED_SUBJECT_WIDTH + _LANE_GAP))
|
||||
header.append(fit_cells("SUBJECT", lanes.subject + _LANE_GAP))
|
||||
# The two readings right-align their number, so their labels do too — each sits
|
||||
# over the digits it names rather than over the sign column ahead of them.
|
||||
header.append(fit_cells("SNR", _READING_W, align="right"))
|
||||
@@ -538,9 +613,12 @@ class LiveFeedScreen(Screen):
|
||||
header.append(" " * _LANE_GAP)
|
||||
header.append(fit_cells("RSSI", _READING_W, align="right"))
|
||||
header.append(" " * (_RSSI_LANE - _LANE_GAP - _READING_W))
|
||||
if lanes.scope:
|
||||
header.append(" " * _LANE_GAP)
|
||||
header.append(fit_cells("SCOPE", _FEED_SCOPE_WIDTH))
|
||||
return header
|
||||
|
||||
def _feed_lines(self, width: int, win: int, show_label: bool) -> list[str]:
|
||||
def _feed_lines(self, width: int, win: int, lanes: _Lanes) -> list[str]:
|
||||
"""The feed's windowed rows: newest first, ``↑/↓ n more`` at the edges."""
|
||||
if not self._feed:
|
||||
return [render_to_ansi(Text("nothing heard yet", style="muted"), width)]
|
||||
@@ -550,14 +628,14 @@ class LiveFeedScreen(Screen):
|
||||
if top > 0:
|
||||
out.append(render_to_ansi(ListWindow.marker(top, "above"), width))
|
||||
for i in range(top, top + count):
|
||||
row = self._feed_row(entries[i], i == self._selected, show_label, width)
|
||||
row = self._feed_row(entries[i], i == self._selected, lanes, width)
|
||||
out.append(render_to_ansi(row, width, no_wrap=True))
|
||||
below = len(entries) - top - count
|
||||
if below > 0:
|
||||
out.append(render_to_ansi(ListWindow.marker(below, "below"), width))
|
||||
return out
|
||||
|
||||
def _feed_row(self, entry: PacketEntry, selected: bool, show_label: bool, width: int) -> Text:
|
||||
def _feed_row(self, entry: PacketEntry, selected: bool, lanes: _Lanes, width: int) -> Text:
|
||||
"""Lay one feed row out in fixed lanes: time, class, subject, reception, detail.
|
||||
|
||||
The class lane says what the packet *is*, straight from
|
||||
@@ -565,7 +643,7 @@ class LiveFeedScreen(Screen):
|
||||
``📻 channel text``, the class the viewer's card headlines, rather than the
|
||||
``📦 packet`` event family it merely arrived in. Its icon always shows; the
|
||||
textual label beside it is dropped wholesale on a narrow terminal
|
||||
(``show_label``), keeping the lanes aligned either way. The subject lane beside it
|
||||
(``lanes.label``), keeping the lanes aligned either way. The subject lane beside it
|
||||
then answers what the packet is *about*, in whatever terms its class deals in
|
||||
(:meth:`_feed_subject`). No relay path rides here — the whole row fits a
|
||||
72-column screen precisely because it doesn't try to, and the route is drawn
|
||||
@@ -600,7 +678,7 @@ class LiveFeedScreen(Screen):
|
||||
)
|
||||
icon, class_label = class_marks(entry)
|
||||
body.append(fit_cells(icon, _ICON_LANE))
|
||||
if show_label:
|
||||
if lanes.label:
|
||||
body.append(
|
||||
fit_cells(class_label, _FEED_CLASS_WIDTH),
|
||||
style=KIND_STYLES.get(entry.kind, "brand"),
|
||||
@@ -609,7 +687,7 @@ class LiveFeedScreen(Screen):
|
||||
subject = self._feed_subject(entry)
|
||||
# The lane fits like every other: cells, not characters, ellipsis on overflow —
|
||||
# but as a Text, so a subject built of several styled pieces keeps them.
|
||||
subject.truncate(_FEED_SUBJECT_WIDTH, overflow="ellipsis", pad=True)
|
||||
subject.truncate(lanes.subject, overflow="ellipsis", pad=True)
|
||||
body.append_text(subject)
|
||||
body.append(" " * _LANE_GAP)
|
||||
body.append(
|
||||
@@ -623,6 +701,14 @@ class LiveFeedScreen(Screen):
|
||||
style="muted",
|
||||
)
|
||||
note = self._feed_note(entry)
|
||||
if lanes.scope:
|
||||
scope = scope_text(self._entry_scope(entry), bare=True)
|
||||
if scope or note is not None:
|
||||
# Padded only where something follows it — a lane at the row's end needs
|
||||
# no trailing blanks, and they would only give ←→ nothing to scroll to.
|
||||
body.append(" " * _LANE_GAP)
|
||||
scope.truncate(_FEED_SCOPE_WIDTH, overflow="ellipsis", pad=note is not None)
|
||||
body.append_text(scope)
|
||||
if note is not None:
|
||||
body.append(" " * _LANE_GAP)
|
||||
body.append_text(note)
|
||||
@@ -759,7 +845,7 @@ class LiveFeedScreen(Screen):
|
||||
if not src:
|
||||
return self._token("to", dest)
|
||||
named = PathLine([self._hop(src), self._hop(dest)], mode="plain").text()
|
||||
if named.cell_len <= _FEED_SUBJECT_WIDTH:
|
||||
if named.cell_len <= self._lanes.subject:
|
||||
return named
|
||||
# Too wide: the sender drops to its hash, so the addressee keeps its name whole (or
|
||||
# as much of it as the lane holds) instead of being the half that gets amputated.
|
||||
@@ -799,6 +885,20 @@ class LiveFeedScreen(Screen):
|
||||
text.append(value, style="muted")
|
||||
return text
|
||||
|
||||
def _entry_scope(self, entry: PacketEntry) -> Scope | None:
|
||||
"""The scope of a row's frame, or ``None`` where it has none to state.
|
||||
|
||||
Only a raw ``packet`` frame carries the route type and transport codes a scope is
|
||||
read from, and only a flood has one; the lane is left blank for everything else —
|
||||
a direct frame is never region-filtered, so a word there would claim a meaning it
|
||||
lacks. The lane is drawn ``bare``: its heading already says ``SCOPE``, so a known
|
||||
region reads as its name alone, while ``unscoped`` and ``scoped · 3fa1`` stay the
|
||||
words they are everywhere (:func:`~meshterm.ui.widgets.scope_text`).
|
||||
"""
|
||||
if entry.kind != "packet" or not isinstance(entry.raw, dict):
|
||||
return None
|
||||
return self._scope_of(entry.raw)
|
||||
|
||||
def _feed_note(self, entry: PacketEntry) -> Text | None:
|
||||
"""The row's trailing detail — a message's conversation, and nothing else.
|
||||
|
||||
@@ -883,6 +983,7 @@ async def open_livefeed(ctx: AppContext) -> None:
|
||||
channel_names=channel_names,
|
||||
type_of=type_of,
|
||||
key_of=key_of,
|
||||
scope_of=ctx.region_store.scope_of,
|
||||
)
|
||||
|
||||
unsubscribe = ctx.events.subscribe(screen.on_event)
|
||||
|
||||
@@ -35,12 +35,19 @@ detail read together:
|
||||
under a cracked chip at whichever edge continues, and snaps back the moment the
|
||||
selection moves on. A row you are *not* on is cut the same way — it just cannot slide.
|
||||
|
||||
The message's **scope** — the region it was flooded into — rides the title as a status
|
||||
atom (``Message paths · scope harbour``), stated once for the message rather than per
|
||||
arrival: every copy carries its sender's transport code unchanged (see
|
||||
:func:`~meshterm.services.message_paths.message_scope`).
|
||||
|
||||
Nothing here transmits; like the service beneath it, this is a read-model over what
|
||||
the radio already heard.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from rich.text import Text
|
||||
|
||||
from ..core.models import ChatMessage
|
||||
@@ -67,8 +74,12 @@ from .widgets import (
|
||||
node_type_legend,
|
||||
revisit_note,
|
||||
route_graph_style,
|
||||
scope_text,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..core.regions import Scope
|
||||
|
||||
#: Cells one ←/→ press shifts the selected row by.
|
||||
_HSTEP = 4
|
||||
|
||||
@@ -108,6 +119,7 @@ class MessagePathsScreen(Screen):
|
||||
destination: str | None = None,
|
||||
type_of: TypeOf | None = None,
|
||||
key_of: NameKeyResolver | None = None,
|
||||
scope: Scope | None = None,
|
||||
) -> None:
|
||||
"""Build the dialog over one message's matched arrivals.
|
||||
|
||||
@@ -135,9 +147,12 @@ class MessagePathsScreen(Screen):
|
||||
key_of: Maps the origin's display name back to its node's key, so the
|
||||
graph's left endpoint takes its key-derived hue; ``None`` (or an
|
||||
unresolvable name) leaves it muted.
|
||||
scope: The region the message was flooded into, read off its arrivals'
|
||||
frames (:func:`~meshterm.services.message_paths.message_scope`); ``None``
|
||||
where no copy was a flood, and the title then states nothing.
|
||||
"""
|
||||
super().__init__()
|
||||
self.title = "Message paths"
|
||||
self.title = self.titled(scope)
|
||||
self._message = message
|
||||
self._arrivals = arrivals
|
||||
self._matched = matched
|
||||
@@ -161,6 +176,23 @@ class MessagePathsScreen(Screen):
|
||||
self._list = ListWindow()
|
||||
self._list_hidden = False
|
||||
|
||||
@staticmethod
|
||||
def titled(scope: Scope | None) -> str:
|
||||
"""The dialog's title: its name, then the message's scope as a status atom.
|
||||
|
||||
Every copy of one message carries its sender's transport code (the code is over the
|
||||
payload, which no relay touches), so the scope is a fact about the *message*, not
|
||||
about any one arrival — stated once, up here, rather than repeated down a list whose
|
||||
rows differ only by path. It rides the title because the title is where a screen's
|
||||
status atoms chain (``Message paths · scope harbour``) and it costs the body no
|
||||
line: on the PicoCalc's 26 rows a line spent here is a lane of the fan or a row of
|
||||
the list. The words are :func:`~meshterm.ui.widgets.scope_text`'s, plain — a title
|
||||
carries no styling — so ``unscoped`` and ``scoped · 3fa1`` read here exactly as they
|
||||
do on the packet viewer's ``route`` row.
|
||||
"""
|
||||
atom = scope_text(scope).plain
|
||||
return f"Message paths · {atom}" if atom else "Message paths"
|
||||
|
||||
# --- input ---------------------------------------------------------------
|
||||
|
||||
@property
|
||||
|
||||
@@ -6,7 +6,8 @@ the rows share this module's per-kind chrome — a colour and a two-cell icon pe
|
||||
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 its parsed class and route, what it was addressed to (the
|
||||
RX-logged packet shows its parsed class and route — a flood's with the region it was
|
||||
scoped to, if any (:func:`~meshterm.ui.widgets.scope_text`) — what it was addressed to (the
|
||||
recipient and sender read out of the frame body — see :mod:`~meshterm.core.frames` — or
|
||||
the token a trace or an ack stands on), plus the relay path it rode in on —
|
||||
as a ``via`` chain on THE path line (:mod:`~meshterm.ui.pathline`), wrapping at hop
|
||||
@@ -51,6 +52,7 @@ from rich.text import Text
|
||||
|
||||
from ..core.channels import decrypt_channel_text, identify_channel
|
||||
from ..core.models import Observation, node_type_label, utcnow
|
||||
from ..core.regions import Scope, frame_scope
|
||||
from ..services.trace_runner import NodeResolver
|
||||
from .marks import SELF_MARK, UNKNOWN_MARK
|
||||
from .menus import SEP_COMPACT, SEP_ROOMY
|
||||
@@ -71,8 +73,25 @@ from .widgets import (
|
||||
node_type_legend,
|
||||
revisit_note,
|
||||
route_graph_style,
|
||||
scope_text,
|
||||
)
|
||||
|
||||
#: Reads a frame's scope from its raw payload — ``ctx.region_store.scope_of`` in the app:
|
||||
#: ``None`` for a frame with no scope to state (direct, or a route type never kept).
|
||||
ScopeOf = Callable[[dict | None], Scope | None]
|
||||
|
||||
|
||||
def unnamed_scope(raw: dict | None) -> Scope | None:
|
||||
"""A frame's scope read without any region names — the fallback when none are at hand.
|
||||
|
||||
Still says everything the frame itself says: a plain flood is ``unscoped``, and a
|
||||
scoped one is ``scoped · <code>``. Only the *naming* needs the known regions (see
|
||||
:meth:`~meshterm.core.region_store.RegionStore.scope_of`), so a viewer opened without a
|
||||
store never draws less than the truth, only less than the whole of it.
|
||||
"""
|
||||
return frame_scope(raw, ()) if isinstance(raw, dict) else None
|
||||
|
||||
|
||||
#: Composed packet cards the viewer memoizes (a few pages either side of the view).
|
||||
_BODY_CACHE_MAX = 8
|
||||
|
||||
@@ -101,7 +120,7 @@ _PAYLOAD_GLOSS = {
|
||||
_RAW_ROW_SKIP = frozenset({
|
||||
"node", "name", "kind", "snr", "rssi", "lat", "lon", "path", "node_type",
|
||||
"observed_at", "text",
|
||||
"header", "payload_ver", "transport_code", "path_len", "path_hash_size",
|
||||
"header", "payload_ver", "transport_code", "scope_body", "path_len", "path_hash_size",
|
||||
"payload_type", "payload_typename", "route_type", "route_typename",
|
||||
"pkt_payload", "pkt_hash", "raw_hex", "payload", "payload_length", "recv_time",
|
||||
"chan_hash", "cipher_mac", "crypted", "message", "msg_hash", "sender_timestamp",
|
||||
@@ -412,6 +431,7 @@ class PacketViewer(Screen):
|
||||
source: Callable[[], Sequence[PacketEntry]] | None = None,
|
||||
type_of: TypeOf | None = None,
|
||||
key_of: NameKeyResolver | None = None,
|
||||
scope_of: ScopeOf | None = None,
|
||||
) -> None:
|
||||
"""Open the viewer over a packet list.
|
||||
|
||||
@@ -442,6 +462,11 @@ class PacketViewer(Screen):
|
||||
key_of: Maps an origin's display name back to its node's key, so the route
|
||||
graph's left endpoint takes its key-derived hue; ``None`` (or an
|
||||
unresolvable name) leaves it muted.
|
||||
scope_of: Reads a flood's scope off its raw frame against the regions known
|
||||
by name (``ctx.region_store.scope_of``), so the ``route`` row can say which
|
||||
region a scoped flood was sent into. ``None`` falls back to
|
||||
:func:`unnamed_scope`: the flood is still told apart as scoped or not,
|
||||
and a scoped one shows its code where a name would go.
|
||||
"""
|
||||
super().__init__()
|
||||
self._entries = list(entries)
|
||||
@@ -457,6 +482,7 @@ class PacketViewer(Screen):
|
||||
self._source = source
|
||||
self._type_of = type_of
|
||||
self._key_of = key_of
|
||||
self._scope_of: ScopeOf = scope_of or unnamed_scope
|
||||
#: 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: PacketEntry | None = self._entries[self._index] if self._entries else None
|
||||
@@ -661,7 +687,11 @@ class PacketViewer(Screen):
|
||||
# Memoize on exactly that: the repaint tick re-lays the graph only when a
|
||||
# minute boundary actually moves the visible text.
|
||||
age_minute = int(max(0.0, (utcnow() - entry.when).total_seconds()) // 60)
|
||||
key = (id(entry), width, age_minute)
|
||||
# …and of the flood's scope, which is *not* fixed at capture: a region learned
|
||||
# while the card is open (a repeater's list arriving, a name typed) names a code
|
||||
# that read as unknown a moment ago. The store memoizes the lookup, so asking it
|
||||
# every paint costs a dict hit.
|
||||
key = (id(entry), width, age_minute, self._entry_scope(entry))
|
||||
cached = self._body_cache.get(key)
|
||||
if cached is not None:
|
||||
self._body_cache.move_to_end(key)
|
||||
@@ -910,7 +940,7 @@ class PacketViewer(Screen):
|
||||
rows.extend(self._addressing_rows(raw))
|
||||
route = raw.get("route_typename")
|
||||
if route:
|
||||
rows.append(("route", Text(route.replace("_", " ").lower())))
|
||||
rows.append(("route", self._route_text(route, self._entry_scope(entry))))
|
||||
rows.append(("via", self._via_path(entry)))
|
||||
# The figure the chain above encodes but never states, hung under it as the app's
|
||||
# own hop atom — the same one the node page's routes and the trace scenarios carry
|
||||
@@ -953,6 +983,40 @@ class PacketViewer(Screen):
|
||||
)
|
||||
return rows
|
||||
|
||||
def _entry_scope(self, entry: PacketEntry) -> Scope | None:
|
||||
"""The scope of an entry's frame, or ``None`` where it has none to state.
|
||||
|
||||
Only a raw ``packet`` frame carries the route type and transport codes a scope is
|
||||
read from; every other kind answers ``None`` and draws nothing.
|
||||
"""
|
||||
if entry.kind != "packet" or not isinstance(entry.raw, dict):
|
||||
return None
|
||||
return self._scope_of(entry.raw)
|
||||
|
||||
@staticmethod
|
||||
def _route_text(route: str, scope: Scope | None) -> Text:
|
||||
"""The ``route`` row: how the frame was routed, and for a flood, where to.
|
||||
|
||||
A flood reads ``flood`` and then its scope as a chained atom
|
||||
(:func:`~meshterm.ui.widgets.scope_text`) — ``flood · scope harbour``,
|
||||
``flood · scoped · 3fa1``, ``flood · unscoped`` — rather than the library's
|
||||
``tc flood``, which named the wire mechanism (transport codes) and left the
|
||||
reader to know that it meant *scoped*, and to which region nobody could say.
|
||||
A scoped and an unscoped flood are one routing; the scope is what differs, so it
|
||||
is the scope that is spelled out.
|
||||
|
||||
A direct frame keeps its route word alone. A repeater never region-filters a
|
||||
direct packet, so it has no scope, and a ``TC_DIRECT`` frame's codes are the
|
||||
"to nowhere" pair a contact share uses, not a region — a word there would claim a
|
||||
meaning the frame does not carry.
|
||||
"""
|
||||
if scope is None:
|
||||
return Text(route.replace("_", " ").lower())
|
||||
text = Text("flood")
|
||||
text.append(" · ", style="muted")
|
||||
text.append_text(scope_text(scope))
|
||||
return text
|
||||
|
||||
def _addressing_rows(self, raw: dict) -> list[tuple[str, RenderableType]]:
|
||||
"""Who a frame was for, who it says it was from, and the token it carries.
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ from meshterm.core.models import (
|
||||
utcnow,
|
||||
)
|
||||
from meshterm.core.preferences import Preferences
|
||||
from meshterm.core.regions import frame_scope, region_key, scope_body, transport_code
|
||||
from meshterm.core.remote_store import CachedValue
|
||||
from meshterm.core.watch_store import WatchStore
|
||||
from meshterm.persistence.repository import DiscoveredPath
|
||||
@@ -602,6 +603,48 @@ def _livefeed(cols: int, rows: int) -> Screen:
|
||||
)
|
||||
|
||||
|
||||
#: The region the scope specimens resolve against, and a channel-text payload to scope.
|
||||
_REGION = "harbour"
|
||||
_SCOPED_PAYLOAD = bytes.fromhex("a71c2d00112233445566778899aabbccddeeff")
|
||||
|
||||
|
||||
def _scoped_frame(region: str) -> dict:
|
||||
"""An RX-log frame's raw payload for a channel text flooded under ``region``."""
|
||||
code = transport_code(region_key(region), scope_body(5, _SCOPED_PAYLOAD))
|
||||
return {
|
||||
"route_typename": "TC_FLOOD",
|
||||
"payload_type": 5,
|
||||
"payload_typename": "GRP_TXT",
|
||||
"chan_hash": "a7",
|
||||
"pkt_payload": _SCOPED_PAYLOAD,
|
||||
"transport_code": code.to_bytes(2, "little").hex() + "0000",
|
||||
}
|
||||
|
||||
|
||||
def _scope_of(raw: dict | None): # noqa: ANN202 - the region store's answer, standing in
|
||||
"""Resolve a frame's scope against the one region the specimens know by name."""
|
||||
return frame_scope(raw, (_REGION,)) if isinstance(raw, dict) else None
|
||||
|
||||
|
||||
def _livefeed_scopes(cols: int, rows: int) -> Screen:
|
||||
"""The feed carrying a scoped, an unknown-scoped, an unscoped and a direct frame."""
|
||||
frames = [
|
||||
_scoped_frame(_REGION),
|
||||
_scoped_frame("elsewhere"), # a region nobody here has named
|
||||
{"route_typename": "FLOOD", "payload_typename": "GRP_TXT", "chan_hash": "a7"},
|
||||
{"route_typename": "DIRECT", "payload_typename": "TEXT_MSG", "dest_hash": "a1"},
|
||||
]
|
||||
return LiveFeedScreen(
|
||||
session=_GallerySession(cols, rows),
|
||||
resolve=lambda h: {"a1": "Alice"}.get(h, ""),
|
||||
seed=[
|
||||
Observation(node="", kind="packet", snr=5.0, rssi=-90.0, observed_at=utcnow(), raw=raw)
|
||||
for raw in frames
|
||||
],
|
||||
scope_of=_scope_of,
|
||||
)
|
||||
|
||||
|
||||
def _walk_topo() -> tuple[MeshTopology, dict[str, Contact]]:
|
||||
hub = Contact(name="Hilltop-Repeater", public_key=_HUB_KEY, key_prefix="3d63c6429436")
|
||||
far = Contact(name="Alice", public_key=_FAR_KEY, key_prefix="f2c24f54551e")
|
||||
@@ -654,6 +697,38 @@ def _message_paths(cols: int, rows: int) -> Screen:
|
||||
)
|
||||
|
||||
|
||||
def _message_paths_scoped(cols: int, rows: int) -> Screen:
|
||||
"""A message flooded under a known region: its scope rides the title, stated once."""
|
||||
screen = _message_paths(cols, rows)
|
||||
return MessagePathsScreen(
|
||||
screen._message,
|
||||
screen._arrivals,
|
||||
matched=True,
|
||||
resolve=lambda h: h,
|
||||
prefix_bytes=1,
|
||||
self_name="Homestead",
|
||||
summary="heard twice",
|
||||
source="Alice",
|
||||
scope=_scope_of(_scoped_frame(_REGION)),
|
||||
)
|
||||
|
||||
|
||||
def _message_paths_unknown_scope(cols: int, rows: int) -> Screen:
|
||||
"""A message flooded under a region nobody here has named: the code stands in."""
|
||||
screen = _message_paths(cols, rows)
|
||||
return MessagePathsScreen(
|
||||
screen._message,
|
||||
screen._arrivals,
|
||||
matched=True,
|
||||
resolve=lambda h: h,
|
||||
prefix_bytes=1,
|
||||
self_name="Homestead",
|
||||
summary="heard twice",
|
||||
source="Alice",
|
||||
scope=_scope_of(_scoped_frame("elsewhere")),
|
||||
)
|
||||
|
||||
|
||||
def _remote_cli(cols: int, rows: int) -> Screen:
|
||||
return RemoteCliScreen(
|
||||
node_label="Hilltop-Repeater",
|
||||
@@ -803,6 +878,27 @@ def _packet_viewer(cols: int, rows: int) -> Screen:
|
||||
)
|
||||
|
||||
|
||||
def _packet_viewer_scoped(cols: int, rows: int, region: str = _REGION) -> Screen:
|
||||
"""A channel text flooded under a region: the route row names it."""
|
||||
entry = PacketEntry(
|
||||
when=utcnow(),
|
||||
kind="packet",
|
||||
path="3d63c6429436f2c24f54551e",
|
||||
raw=_scoped_frame(region),
|
||||
)
|
||||
return PacketViewer(
|
||||
[entry],
|
||||
0,
|
||||
resolve=lambda h: {"3d63c6429436": "Hilltop-Repeater"}.get(h, h),
|
||||
scope_of=_scope_of,
|
||||
)
|
||||
|
||||
|
||||
def _packet_viewer_unknown_scope(cols: int, rows: int) -> Screen:
|
||||
"""A channel text flooded under a region nobody here has named: its code stands in."""
|
||||
return _packet_viewer_scoped(cols, rows, region="elsewhere")
|
||||
|
||||
|
||||
def _trace(cols: int, rows: int) -> Screen:
|
||||
async def _noop_flow(current): # noqa: ANN001
|
||||
return current
|
||||
@@ -1103,9 +1199,12 @@ _ENTRIES: list[_Entry] = [
|
||||
_Entry("channels_manager", _channels_manager),
|
||||
_Entry("channel_detail", _channel_detail),
|
||||
_Entry("livefeed", _livefeed),
|
||||
_Entry("livefeed_scopes", _livefeed_scopes),
|
||||
_Entry("walk", _walk),
|
||||
_Entry("timemachine", _timemachine),
|
||||
_Entry("message_paths", _message_paths),
|
||||
_Entry("message_paths_scoped", _message_paths_scoped),
|
||||
_Entry("message_paths_unknown_scope", _message_paths_unknown_scope),
|
||||
_Entry("remote_cli", _remote_cli),
|
||||
_Entry("path_composer", _path_composer),
|
||||
_Entry("courier_outbox", _courier_outbox),
|
||||
@@ -1113,6 +1212,8 @@ _ENTRIES: list[_Entry] = [
|
||||
_Entry("record_route", _record_route),
|
||||
_Entry("record_area", _record_area),
|
||||
_Entry("packet_viewer", _packet_viewer),
|
||||
_Entry("packet_viewer_scoped", _packet_viewer_scoped),
|
||||
_Entry("packet_viewer_unknown_scope", _packet_viewer_unknown_scope),
|
||||
_Entry("trace", _trace),
|
||||
_Entry("tx_sweep", _tx_sweep),
|
||||
_Entry("device_info", _device_info),
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Where a flood's scope is shown: the packet viewer, the live feed, message paths, monitor.
|
||||
|
||||
The scope itself — the maths, the store, the history columns — is pinned in
|
||||
``test_regions.py``; these tests are about the surfaces that state it, and the one rule
|
||||
they all share: a flood says which region it was sent into (or that it was unscoped, or
|
||||
scoped to a region nobody here has named), and a direct frame says nothing at all.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from rich.cells import cell_len
|
||||
|
||||
from meshterm.core.models import ChatMessage, Observation, utcnow
|
||||
from meshterm.core.region_store import RegionStore
|
||||
from meshterm.core.regions import (
|
||||
UNSCOPED,
|
||||
Scope,
|
||||
frame_scope,
|
||||
region_key,
|
||||
scope_body,
|
||||
transport_code,
|
||||
)
|
||||
from meshterm.persistence.repository import Repository
|
||||
from meshterm.services.message_paths import (
|
||||
Arrival,
|
||||
channel_arrivals,
|
||||
collapse,
|
||||
message_scope,
|
||||
)
|
||||
from meshterm.tools.monitor import _live_packets
|
||||
from meshterm.ui import script
|
||||
from meshterm.ui.livefeed_screen import LiveFeedScreen
|
||||
from meshterm.ui.message_paths_screen import MessagePathsScreen
|
||||
from meshterm.ui.packet_viewer import PacketEntry, PacketViewer
|
||||
from meshterm.ui.renderers import JsonRenderer, PlainRenderer
|
||||
from tests.conftest import plain as _plain
|
||||
from tests.test_message_paths import SECRET, _grp_txt_raw
|
||||
|
||||
#: An arbitrary channel-text payload to scope (the code is over it, not over its meaning).
|
||||
_PAYLOAD = bytes.fromhex("a71c2d00112233445566778899aabbccddeeff")
|
||||
|
||||
|
||||
def _scoped(region: str, payload: bytes = _PAYLOAD, **extra) -> dict:
|
||||
"""An RX-log frame's raw payload for a channel text flooded under ``region``."""
|
||||
code = transport_code(region_key(region), scope_body(5, payload))
|
||||
return {
|
||||
"route_typename": "TC_FLOOD",
|
||||
"payload_type": 5,
|
||||
"payload_typename": "GRP_TXT",
|
||||
"pkt_payload": payload,
|
||||
"transport_code": code.to_bytes(2, "little").hex() + "0000",
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def _code(region: str) -> str:
|
||||
"""The 4-hex code a :func:`_scoped` frame carries."""
|
||||
return f"{transport_code(region_key(region), scope_body(5, _PAYLOAD)):04x}"
|
||||
|
||||
|
||||
_FLOOD = {"route_typename": "FLOOD", "payload_typename": "GRP_TXT", "chan_hash": "a7"}
|
||||
_DIRECT = {"route_typename": "DIRECT", "payload_typename": "TEXT_MSG", "dest_hash": "a1"}
|
||||
|
||||
|
||||
def _knows(*names: str): # noqa: ANN202 - a scope reader over a fixed set of names
|
||||
"""A ``scope_of`` that knows exactly ``names`` — the region store's answer, in small."""
|
||||
return lambda raw: frame_scope(raw, names) if isinstance(raw, dict) else None
|
||||
|
||||
|
||||
def _stripped(lines: list[str]) -> list[str]:
|
||||
return [re.sub(r"\x1b\[[0-9;]*m", "", line) for line in lines]
|
||||
|
||||
|
||||
def _col(line: str, needle: str) -> int:
|
||||
"""The display column (cells, not characters — the class icon is two) of ``needle``."""
|
||||
return cell_len(line[: line.index(needle)])
|
||||
|
||||
|
||||
# -- the packet viewer -------------------------------------------------------------------
|
||||
|
||||
|
||||
def _route_row(raw: dict, scope_of=None) -> str: # noqa: ANN001
|
||||
"""The viewer's ``route`` row for one frame, as plain text."""
|
||||
entry = PacketEntry(when=utcnow(), kind="packet", path="3d", raw=raw)
|
||||
body = _stripped(
|
||||
PacketViewer([entry], 0, resolve=lambda h: "", scope_of=scope_of).render_body(80)
|
||||
)
|
||||
return next(line for line in body if line.startswith("route")).rstrip()
|
||||
|
||||
|
||||
def test_the_viewer_names_the_region_a_flood_was_scoped_to() -> None:
|
||||
"""``tc flood`` said *how* and never *where*; the row now says flood, then the scope."""
|
||||
assert _route_row(_scoped("harbour"), _knows("harbour")).split(None, 1)[1] == (
|
||||
"flood · scope harbour"
|
||||
)
|
||||
|
||||
|
||||
def test_the_viewer_shows_an_unnamed_scopes_code_and_a_plain_flood_as_unscoped() -> None:
|
||||
"""A scope no known name reproduces keeps its code; a plain flood reads unscoped."""
|
||||
assert _route_row(_scoped("elsewhere"), _knows("harbour")).endswith(
|
||||
f"flood · scoped · {_code('elsewhere')}"
|
||||
)
|
||||
assert _route_row(_FLOOD, _knows("harbour")).endswith("flood · unscoped")
|
||||
|
||||
|
||||
def test_the_viewer_without_a_store_still_tells_scoped_from_unscoped() -> None:
|
||||
"""No names at hand is less of the truth, never a wrong one: the code stands in."""
|
||||
assert _route_row(_scoped("harbour")).endswith(f"flood · scoped · {_code('harbour')}")
|
||||
assert _route_row(_FLOOD).endswith("flood · unscoped")
|
||||
|
||||
|
||||
def test_the_viewer_never_gives_a_direct_frame_a_scope() -> None:
|
||||
"""A repeater never region-filters a direct packet, so its route row is the word alone."""
|
||||
assert _route_row(_DIRECT, _knows("harbour")).split() == ["route", "direct"]
|
||||
assert _route_row({**_DIRECT, "route_typename": "TC_DIRECT"}).split() == [
|
||||
"route",
|
||||
"tc",
|
||||
"direct",
|
||||
]
|
||||
|
||||
|
||||
def test_the_viewer_keeps_the_scope_body_out_of_the_raw_dump(tmp_path: Path) -> None:
|
||||
"""The restored HMAC input is plumbing the route row already spoke for."""
|
||||
raw = _scoped("harbour")
|
||||
restored = {k: v for k, v in raw.items() if k not in ("payload_type", "pkt_payload")}
|
||||
restored["scope_body"] = scope_body(5, _PAYLOAD).hex()
|
||||
body = _plain(
|
||||
PacketViewer(
|
||||
[PacketEntry(when=utcnow(), kind="packet", path="", raw=restored)],
|
||||
0,
|
||||
resolve=lambda h: "",
|
||||
scope_of=_knows("harbour"),
|
||||
).render_body(80)
|
||||
)
|
||||
assert "scope harbour" in body # a replayed frame resolves exactly as a live one
|
||||
assert "scope_body" not in body
|
||||
|
||||
|
||||
def test_the_viewer_renames_a_scope_the_moment_its_region_is_learned(tmp_path: Path) -> None:
|
||||
"""The card is memoized, but not past a name arriving: the scope is in the cache key."""
|
||||
store = RegionStore(tmp_path / "regions.json")
|
||||
entry = PacketEntry(when=utcnow(), kind="packet", path="", raw=_scoped("harbour"))
|
||||
viewer = PacketViewer([entry], 0, resolve=lambda h: "", scope_of=store.scope_of)
|
||||
assert "scope harbour" not in _plain(viewer.render_body(80))
|
||||
store.learn("harbour", "typed")
|
||||
assert "scope harbour" in _plain(viewer.render_body(80))
|
||||
|
||||
|
||||
# -- the live feed -----------------------------------------------------------------------
|
||||
|
||||
|
||||
class _Session:
|
||||
def invalidate(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def _feed(*raws: dict) -> LiveFeedScreen:
|
||||
"""A live feed over one packet row per frame, oldest first, knowing ``harbour``."""
|
||||
screen = LiveFeedScreen(
|
||||
session=_Session(),
|
||||
resolve=lambda h: "",
|
||||
seed=[
|
||||
Observation(node="", kind="packet", snr=5.0, rssi=-90.0, observed_at=utcnow(), raw=raw)
|
||||
for raw in raws
|
||||
],
|
||||
scope_of=_knows("harbour"),
|
||||
)
|
||||
screen.note_viewport(40)
|
||||
return screen
|
||||
|
||||
|
||||
def test_the_feed_carries_a_scope_lane_on_a_72_column_terminal() -> None:
|
||||
"""The framed body there is 68 cells: the icon-only row holds the lane, name and all."""
|
||||
screen = _feed(_DIRECT, _FLOOD, _scoped("elsewhere"), _scoped("harbour"))
|
||||
header, *rows = _stripped(screen.render_body(68))
|
||||
assert header.split()[-1] == "SCOPE"
|
||||
assert rows[0].rstrip().endswith("harbour")
|
||||
assert rows[1].rstrip().endswith(f"scoped · {_code('elsewhere')}")
|
||||
assert rows[2].rstrip().endswith("unscoped")
|
||||
assert rows[3].rstrip().endswith("dBm") # the direct frame states no scope
|
||||
for line in (header, *rows):
|
||||
assert cell_len(line.rstrip()) <= 68
|
||||
# The label sits over the values it names.
|
||||
assert _col(header, "SCOPE") == _col(rows[0], "harbour")
|
||||
|
||||
|
||||
def test_the_feed_keeps_the_class_label_ahead_of_the_scope() -> None:
|
||||
"""Between the two widths that hold it, the label wins: a class is never ``unscoped``."""
|
||||
screen = _feed(_scoped("harbour"))
|
||||
header = _stripped(screen.render_body(72))[0]
|
||||
assert "CLASS" in header and "SCOPE" not in header
|
||||
header, row = _stripped(screen.render_body(100))[:2]
|
||||
assert "CLASS" in header and "SCOPE" in header
|
||||
assert _col(header, "SCOPE") == _col(row, "harbour")
|
||||
|
||||
|
||||
def test_the_feed_leaves_the_scope_to_the_viewer_on_the_picocalc() -> None:
|
||||
"""At 53 the row already scrolls sideways; a lane only ←→ reaches is not drawn."""
|
||||
screen = _feed(_scoped("harbour"))
|
||||
body = _plain(screen.render_body(53))
|
||||
assert "SCOPE" not in body and "harbour" not in body
|
||||
|
||||
|
||||
def test_the_feed_hands_its_scope_reader_to_the_viewer() -> None:
|
||||
"""Enter opens a card that names the same region the row did."""
|
||||
screen = _feed(_scoped("harbour"))
|
||||
opened: list = []
|
||||
screen._session.run_screen = lambda viewer: opened.append(viewer) # noqa: SLF001
|
||||
screen._session.run_detached = lambda coro: None # noqa: SLF001
|
||||
screen.handle("enter")
|
||||
assert "flood · scope harbour" in _plain(opened[0].render_body(80))
|
||||
|
||||
|
||||
# -- message paths -----------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_messages_scope_is_read_once_off_its_arrivals() -> None:
|
||||
"""Every copy carries the sender's code, so the first flooded copy answers.
|
||||
|
||||
A named reading beats an unnamed one, any scope beats unscoped, and direct copies
|
||||
have nothing to say.
|
||||
"""
|
||||
scope_of = _knows("harbour")
|
||||
when = utcnow()
|
||||
|
||||
def arrival(raw): # noqa: ANN001, ANN202
|
||||
return Arrival(when=when, hops=(), snr=None, frame=raw)
|
||||
|
||||
direct, flood = arrival(_DIRECT), arrival(_FLOOD)
|
||||
named, unnamed = arrival(_scoped("harbour")), arrival(_scoped("elsewhere"))
|
||||
assert message_scope([direct, unnamed, named], scope_of) == Scope(
|
||||
"scoped", "harbour", _code("harbour")
|
||||
)
|
||||
assert message_scope([flood, unnamed], scope_of).state == "unknown"
|
||||
assert message_scope([direct, flood], scope_of) is UNSCOPED
|
||||
assert message_scope([direct], scope_of) is None
|
||||
assert message_scope([arrival(None)], scope_of) is None
|
||||
|
||||
|
||||
def test_a_stored_scoped_message_resolves_through_its_arrivals(tmp_path: Path) -> None:
|
||||
"""History keeps what resolution needs, the matcher keeps the frame, collapse keeps it."""
|
||||
repo = Repository(tmp_path / "test.db")
|
||||
run = repo.start_run("monitor", {}, None)
|
||||
now = utcnow()
|
||||
wire = "Alice: hi harbour"
|
||||
for i, path in enumerate(("3d63", "3d63", "3d63,a1b2")):
|
||||
raw = {**_grp_txt_raw(SECRET, wire), **_scoped("harbour")}
|
||||
repo.record_observation(
|
||||
run,
|
||||
Observation(
|
||||
node=None,
|
||||
kind="packet",
|
||||
path=path,
|
||||
snr=2.0,
|
||||
observed_at=now - timedelta(seconds=5 - i),
|
||||
raw=raw,
|
||||
),
|
||||
)
|
||||
message = ChatMessage(text=wire, is_channel=True, created_at=now)
|
||||
arrivals = collapse(channel_arrivals(repo, message, channel_name="#general", secret=SECRET))
|
||||
assert len(arrivals) == 2
|
||||
store = RegionStore(tmp_path / "regions.json")
|
||||
assert message_scope(arrivals, store.scope_of).state == "unknown"
|
||||
store.learn("harbour", "channel")
|
||||
assert message_scope(arrivals, store.scope_of).region == "harbour"
|
||||
repo.close()
|
||||
|
||||
|
||||
def _paths_screen(scope: Scope | None) -> MessagePathsScreen:
|
||||
message = ChatMessage(text="hi", is_channel=True, created_at=utcnow())
|
||||
return MessagePathsScreen(
|
||||
message,
|
||||
[Arrival(when=utcnow(), hops=("3d",), snr=1.0)],
|
||||
matched=True,
|
||||
resolve=lambda h: h,
|
||||
prefix_bytes=1,
|
||||
self_name="Homestead",
|
||||
summary="heard once",
|
||||
source="Alice",
|
||||
scope=scope,
|
||||
)
|
||||
|
||||
|
||||
def test_the_paths_dialog_states_the_scope_once_in_its_title() -> None:
|
||||
"""A status atom on the title, in the viewer's words — and none for a direct message."""
|
||||
assert _paths_screen(Scope("scoped", "harbour", "3fa1")).title == (
|
||||
"Message paths · scope harbour"
|
||||
)
|
||||
assert _paths_screen(Scope("unknown", None, "3fa1")).title == "Message paths · scoped · 3fa1"
|
||||
assert _paths_screen(UNSCOPED).title == "Message paths · unscoped"
|
||||
assert _paths_screen(None).title == "Message paths"
|
||||
# …and never per arrival row: the body does not repeat it.
|
||||
body = _plain(_paths_screen(Scope("scoped", "harbour", "3fa1")).render_body(72))
|
||||
assert "harbour" not in body
|
||||
|
||||
|
||||
# -- monitor -------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _capture(renderer_cls, rows: list[dict]) -> str: # noqa: ANN001
|
||||
buffer = io.StringIO()
|
||||
with renderer_cls(script.console(buffer)).stream(_live_packets()) as emit:
|
||||
for row in rows:
|
||||
emit(row)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _record(scope: Scope | None, name: str) -> dict:
|
||||
from meshterm.ui.fields import NodeRef
|
||||
|
||||
return {
|
||||
"observed_at": utcnow(),
|
||||
"node": NodeRef(name=name, hash="d4e5f6a7"),
|
||||
"kind": "packet",
|
||||
"snr_db": 1.0,
|
||||
"rssi_dbm": -90.0,
|
||||
"position": None,
|
||||
"scope": scope,
|
||||
"path": [],
|
||||
}
|
||||
|
||||
|
||||
def test_monitor_streams_the_scope_before_the_name() -> None:
|
||||
"""A pinned SCOPE lane on the plain face, and NAME still last.
|
||||
|
||||
A long region overruns its lane and pushes the row right, so the one field built to be
|
||||
pushed is the only one it can push.
|
||||
"""
|
||||
text = _capture(
|
||||
PlainRenderer,
|
||||
[
|
||||
_record(Scope("scoped", "harbour", "3fa1"), "Alice"),
|
||||
_record(Scope("unknown", None, "3fa1"), "Bob"),
|
||||
_record(UNSCOPED, "Carol"),
|
||||
_record(None, "Dave"),
|
||||
],
|
||||
)
|
||||
header, *rows = text.splitlines()
|
||||
assert header.split()[-2:] == ["SCOPE", "NAME"]
|
||||
assert [row.split()[-2:] for row in rows] == [
|
||||
["harbour", "Alice"],
|
||||
["unknown", "Bob"],
|
||||
["unscoped", "Carol"],
|
||||
["-", "Dave"],
|
||||
]
|
||||
assert (
|
||||
len(
|
||||
{
|
||||
row.index(name)
|
||||
for row, name in zip(rows, "Alice Bob Carol Dave".split(), strict=True)
|
||||
}
|
||||
)
|
||||
== 1
|
||||
)
|
||||
|
||||
|
||||
def test_monitor_json_carries_the_scope_object_or_null() -> None:
|
||||
"""The document speaks the shared scope shape; a frame with none is ``null``."""
|
||||
text = _capture(
|
||||
JsonRenderer, [_record(Scope("scoped", "harbour", "3fa1"), "Alice"), _record(None, "Bob")]
|
||||
)
|
||||
first, second = (json.loads(line) for line in text.splitlines())
|
||||
assert first["scope"] == {"state": "scoped", "region": "harbour", "code": "3fa1"}
|
||||
assert second["scope"] is None
|
||||
assert list(first)[-2:] == ["scope", "path"]
|
||||
Reference in new issue
Block a user