diff --git a/meshterm/ui/livefeed_screen.py b/meshterm/ui/livefeed_screen.py index 0564444..0f86365 100644 --- a/meshterm/ui/livefeed_screen.py +++ b/meshterm/ui/livefeed_screen.py @@ -71,6 +71,7 @@ from ..core.models import Observation, utcnow from .menus import fit_cells from .packet_viewer import ( KIND_STYLES, + MessageScopeOf, PacketEntry, PacketViewer, ScopeOf, @@ -297,6 +298,7 @@ class LiveFeedScreen(Screen): type_of: TypeOf | None = None, key_of: NameKeyResolver | None = None, scope_of: ScopeOf | None = None, + message_scope: MessageScopeOf | None = None, ) -> None: """Create the feed over its data feeds. @@ -322,9 +324,12 @@ class LiveFeedScreen(Screen): 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 + each opened viewer for its ``scope`` 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`). + message_scope: Reads a decoded channel message's scope off its copies in the + packet log (:func:`message_scope_reader`), handed to each opened viewer so + a message's card has a ``scope`` row too. ``None``: no row for messages. """ super().__init__() self.title = "Live feed" @@ -337,6 +342,7 @@ class LiveFeedScreen(Screen): self._type_of = type_of self._key_of: NameKeyResolver = key_of or (lambda name: None) self._scope_of: ScopeOf = scope_of or unnamed_scope + self._message_scope = message_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) @@ -547,6 +553,7 @@ class LiveFeedScreen(Screen): type_of=self._type_of, key_of=self._key_of, scope_of=self._scope_of, + message_scope=self._message_scope, # 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), @@ -944,6 +951,7 @@ async def open_livefeed(ctx: AppContext) -> None: self_name: str | None = None channels: list[tuple[str, bytes]] = [] channel_names: dict[int, str] = {} + slots_by_idx: dict[int, tuple[str, bytes]] = {} try: if ctx.is_connected or ctx.settings.connect_on_start: # Through the session cache: contacts and the channel-slot probe are the two @@ -954,6 +962,7 @@ async def open_livefeed(ctx: AppContext) -> None: slots = await ctx.devstate.channel_slots() channels = [(s.name, s.secret) for s in slots] channel_names = {s.idx: s.name for s in slots} + slots_by_idx = {s.idx: (s.name, s.secret) for s in slots} except Exception: # noqa: BLE001 - the feed renders fine without contact names contacts = [] # Contacts first, every name the recorder ever overheard as the fallback — the @@ -978,6 +987,7 @@ async def open_livefeed(ctx: AppContext) -> None: type_of=type_of, key_of=key_of, scope_of=ctx.region_store.scope_of, + message_scope=message_scope_reader(ctx, slots_by_idx), ) unsubscribe = ctx.events.subscribe(screen.on_event) @@ -1000,3 +1010,60 @@ async def open_livefeed(ctx: AppContext) -> None: pass except Exception: # noqa: BLE001 - teardown must never surface a tick hiccup pass + + +def message_scope_reader( + ctx: AppContext, slots_by_idx: Mapping[int, tuple[str, bytes]] +) -> MessageScopeOf: + """A reader for a decoded channel message's scope, off its copies in the packet log. + + The radio hands a received message over as text, not as the frame it arrived in, so a + ``message`` row carries no transport code. Its flooded copies are in the packet log, + though, and the message paths dialog already finds them by decrypting and matching + the text (:func:`~meshterm.services.message_paths.channel_arrivals`); every copy + carries the sender's one code, so their scope is the message's + (:func:`~meshterm.services.message_paths.message_scope`). + + The copies found are kept per entry — a card repaints every second and the lookup is a + windowed query plus a decrypt per frame — but only once some were found: a message + can be told to the feed a beat before its frame is written to the log, and a miss + cached then would be a miss for good. The region is resolved on every call, against + the store's memo, so a name learned while the card is open still names it. + + A direct message has no reader: its copies are encrypted end to end and a routed one + has no scope anyway. + + Args: + ctx: The application context (its repository and region store). + slots_by_idx: The device's channels by slot, as ``(name, secret)``. + + Returns: + The reader, answering ``None`` for anything it can't place. + """ + from ..core.models import ChatMessage + from ..services.message_paths import channel_arrivals, message_scope + + found: dict[int, list] = {} + + def read(entry: PacketEntry) -> Scope | None: + if entry.kind != "message" or entry.channel is None: + return None + channel = slots_by_idx.get(entry.channel) + if channel is None or not entry.text: + return None + arrivals = found.get(id(entry)) + if arrivals is None: + message = ChatMessage( + text=entry.text, outbound=False, is_channel=True, created_at=entry.when + ) + try: + arrivals = channel_arrivals( + ctx.repo, message, channel_name=channel[0], secret=channel[1] + ) + except Exception: # noqa: BLE001 - a card without a scope row, never a crash + return None + if arrivals: + found[id(entry)] = arrivals + return message_scope(arrivals, ctx.region_store.scope_of) + + return read diff --git a/meshterm/ui/packet_viewer.py b/meshterm/ui/packet_viewer.py index 48ef884..d75238a 100644 --- a/meshterm/ui/packet_viewer.py +++ b/meshterm/ui/packet_viewer.py @@ -80,6 +80,10 @@ from .widgets import ( #: ``None`` for a frame with no scope to state (direct, or a route type never kept). ScopeOf = Callable[[dict | None], Scope | None] +#: Reads a decoded message entry's scope off the flooded copies the packet log holds of it +#: (see :func:`~meshterm.ui.livefeed_screen.message_scope_reader`). +MessageScopeOf = Callable[["PacketEntry"], 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. @@ -432,6 +436,7 @@ class PacketViewer(Screen): type_of: TypeOf | None = None, key_of: NameKeyResolver | None = None, scope_of: ScopeOf | None = None, + message_scope: MessageScopeOf | None = None, ) -> None: """Open the viewer over a packet list. @@ -463,10 +468,14 @@ class PacketViewer(Screen): 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 + by name (``ctx.region_store.scope_of``), so the ``scope`` 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. + message_scope: Reads a decoded ``message`` entry's scope, which its own raw + payload cannot carry, off the flooded copies of it in the packet log (see + :func:`~meshterm.ui.livefeed_screen.message_scope_reader`). ``None``: a + message's card has no ``scope`` row. """ super().__init__() self._entries = list(entries) @@ -483,6 +492,7 @@ class PacketViewer(Screen): self._type_of = type_of self._key_of = key_of self._scope_of: ScopeOf = scope_of or unnamed_scope + self._message_scope = message_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 @@ -782,6 +792,12 @@ class PacketViewer(Screen): if entry.kind == "packet": rows.extend(self._packet_rows(entry)) + elif entry.kind == "message": + # A decoded message carries no routing of its own; its scope is read off the + # flooded copies of it the packet log holds (see :meth:`_entry_scope`). + scope = self._entry_scope(entry) + if scope is not None: + rows.append(("scope", self._scope_text(scope))) return rows def _node_marker(self, entry: PacketEntry, style: str) -> tuple[str, str]: @@ -989,9 +1005,14 @@ class PacketViewer(Screen): 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. + A raw ``packet`` frame carries the route type and transport codes a scope is read + from. A decoded ``message`` carries neither — the radio hands over the text, not + the frame — so its scope is read off the flooded copies of it in the packet log, + where a ``message_scope`` reader was given (the live feed gives one for channel + messages). Every other kind answers ``None`` and draws nothing. """ + if entry.kind == "message" and self._message_scope is not None: + return self._message_scope(entry) if entry.kind != "packet" or not isinstance(entry.raw, dict): return None return self._scope_of(entry.raw) diff --git a/tests/test_scope_display.py b/tests/test_scope_display.py index dcf12e1..2004d82 100644 --- a/tests/test_scope_display.py +++ b/tests/test_scope_display.py @@ -410,3 +410,46 @@ def test_the_channel_list_draws_scope_only_when_a_channel_has_one() -> None: "MSGS", "ACTIVITY", ] + + +# -- a decoded message's card -------------------------------------------------------------- + + +def test_a_decoded_messages_card_reads_its_scope_off_its_logged_copies(tmp_path: Path) -> None: + """A 💬 row carries no frame; its card finds the flooded copy in the log and names it.""" + from types import SimpleNamespace + + from meshterm.persistence.repository import Repository + from meshterm.ui.livefeed_screen import message_scope_reader + + text = "Alice: road closed" + raw = _grp_txt_raw(SECRET, text) + payload = bytes.fromhex(raw["chan_hash"] + raw["cipher_mac"] + raw["crypted"]) + code = transport_code(region_key("harbour"), scope_body(5, payload)) + raw.update( + route_typename="TC_FLOOD", + payload_type=5, + pkt_payload=payload, + transport_code=code.to_bytes(2, "little").hex() + "0000", + ) + repo = Repository(tmp_path / "log.db") + when = utcnow() + repo.record_observation( + repo.start_run("monitor", {}), + Observation(node=None, kind="packet", path="3d", observed_at=when, raw=raw), + ) + store = RegionStore(tmp_path / "regions.json") + ctx = SimpleNamespace(repo=repo, region_store=store) + read = message_scope_reader(ctx, {1: ("#general", SECRET)}) + + entry = PacketEntry(when=when, kind="message", channel=1, text=text) + assert read(entry).state == "unknown" # the copy is found; its region not yet named + store.learn("harbour", "typed") + assert read(entry).region == "harbour" # named the moment the region is known + + viewer = PacketViewer([entry], 0, resolve=lambda h: "", message_scope=read) + assert _has_scope_row(_plain(viewer.render_body(80)), "harbour") + other = PacketEntry(when=when, kind="message", channel=1, text="Bob: something else") + assert read(other) is None # no copy of it in the log: no scope row, no guess + assert read(PacketEntry(when=when, kind="message", channel=9, text=text)) is None + repo.close()