From fe8a70d51621691f48a42cddb3d2b17e1d3b9138 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sun, 8 Nov 2026 02:30:02 -0500 Subject: [PATCH] Message paths traces the selected route Enter on an arrival in the Message paths dialog (^P in a chat) opens a trace of the route that the row draws, walked from our node: - A received message is traced back to its sender: the relays in reverse, out to the sender, and back on the mirror (Trace target). - A sent direct message is traced out to its recipient on the relays in order (Trace target). - A sent channel message came back to our node, so its relays are the full walk (Trace path). - A sender with no key turns the trace at the first relay (Trace path). - A direct-routed copy carries only the rest of its route, so it offers no trace, and the hint does not show Enter there. The trace screen opens idle and armed. Nothing transmits until the user starts a trace. The dialog stays pushed under it as a hub, so Esc from the trace comes back to the same dialog and highlight. In Trace target, a trace that comes home lights the Device route row, so the route a message took can become the radio's route to that contact. A sender that is not a contact opens on its key, and open_trace takes a label so that the screen shows its name instead of the hex. Refs: #34 Co-Authored-By: Claude Opus 5.5 --- docs/guide/features.md | 2 +- meshterm/services/message_paths.py | 69 +++++++++++++++++ meshterm/ui/chat.py | 116 ++++++++++++++++++++++++---- meshterm/ui/message_paths_screen.py | 53 +++++++++++-- meshterm/ui/trace_screen.py | 22 ++++-- tests/test_chat.py | 66 ++++++++++++++++ tests/test_gallery.py | 2 + tests/test_message_paths.py | 53 +++++++++++++ tests/test_message_paths_screen.py | 65 ++++++++++++++++ 9 files changed, 419 insertions(+), 29 deletions(-) diff --git a/docs/guide/features.md b/docs/guide/features.md index 8fd663a..1d7873e 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -15,7 +15,7 @@ This page lists each interactive screen with its scripted equivalent, where one | Feature | What it does | Scripted | | --- | --- | --- | -| **๐Ÿ’ฌ Chat** | Live full-screen messages on channels and to contacts. The transcript scrolls, the input line stays at the bottom, and sent and received messages appear together. The rooms that you joined are also here. Each post shows under the name of its author. MeshTerm stores each message. Unread counts show in the menu header. | `meshterm chat send / history / list / listen` | +| **๐Ÿ’ฌ Chat** | Live full-screen messages on channels and to contacts. The transcript scrolls, the input line stays at the bottom, and sent and received messages appear together. The rooms that you joined are also here. Each post shows under the name of its author. MeshTerm stores each message. Unread counts show in the menu header. To see each path on which a message reached your node, select the message and press ^P. Enter on a path opens a trace of that route: back to the sender of a received message, or out to the contact of a sent direct message. When the trace comes home, the Device route row can make that route the radio's route to the contact. | `meshterm chat send / history / list / listen` | | **๐Ÿ“ป Channels** | Create, join, reorder, mute, and share mesh channels. You can share a channel with a QR code or a `meshcore://` link. If you give a channel a **send scope**, its messages are flooded into one region. Only the repeaters that carry that region relay them. When you change to a new device, export all the channels to a file, then import the file on the new device. The **channel guide** lists the public channels that MeshTerm heard, also the channels that are not on your device, and adds one with Enter. | `meshterm channels list / add / join / import / share / clear / scope / export / guide` | | **๐Ÿ“Œ Rooms** | Each room server that your radio knows. A room server is a message board on a radio. It keeps the latest posts and sends you the posts that you missed. Join a room with its password. If a room does not answer, MeshTerm tells you what it knows and offers the next step to try. For example, it can send again by flood when the route that your radio learned is no longer good. When the clock of a room goes back (often after a reboot), the room sends you no new post, because each new post looks older than the ones that you have. The node page of the room then says so and offers to ask for all its posts again. | `meshterm rooms list / join / forget` | | **๐Ÿ“จ Courier** | A store-and-forward outbox for contacts that you cannot reach yet. Queue a message. MeshTerm sends it when the contact is next heard, or at a time that you set. It tracks the acks, and it waits longer between each try (exponential backoff). | `meshterm courier queue / list / send / cancel / clear` | diff --git a/meshterm/services/message_paths.py b/meshterm/services/message_paths.py index 79257b9..ddcbaaf 100644 --- a/meshterm/services/message_paths.py +++ b/meshterm/services/message_paths.py @@ -470,3 +470,72 @@ def message_scope( def distinct_paths(arrivals: list[Arrival]) -> int: """The number of distinct relay paths that a set of arrivals covers.""" return len({a.hops for a in arrivals}) + + +@dataclass(frozen=True, slots=True) +class TraceWalk: + """The trace that walks the route of one arrival again, from our node. + + Attributes: + target: The key of the node at which the trace turns back home (a *Trace target* + session), or ``None`` for a walk with no target (a *Trace path* session). + hops: With a target: the leg from our node out to the target, without the two + ends. The trace comes back on the mirror of this leg. With no target: the full + walk, which ends at a node that our node heard. + """ + + target: str | None + hops: tuple[str, ...] + + +def trace_walk( + arrival: Arrival, + *, + outbound: bool, + origin_key: str | None, + far_key: str | None, +) -> TraceWalk | None: + """The trace that walks the route of an arrival, as the Message paths dialog draws it. + + The dialog draws each arrival as a route from the origin of the message, through its + relays, to the node that the message was addressed to. A trace always starts at our + node. Thus it walks that same route from our end: + + * **A message that our node sent** starts at our node. The trace walks the relays in + the same order. A direct message goes on to its recipient, and the trace turns back + there (``far_key``). A channel message came back to our node, and the relays are the + full walk: the last relay is a node that our node heard. + * **A message that our node received** ends at our node. The trace walks the relays + in the reverse order, back to the sender (``origin_key``), and turns back there. + When no key names the sender, the trace turns back at the first relay, the last + node of the route that MeshTerm can address. + + A direct-routed copy gives no trace. Its hops are the part of a route that the packet + still had to go through, not where it went. Thus a trace on them starts at a node that + our node possibly cannot reach. + + Args: + arrival: The arrival whose route the trace walks. + outbound: Whether our node sent the message. + origin_key: The key (or a key prefix) of the sender of a received message, or + ``None`` when it is unknown. + far_key: The key (or a key prefix) of the recipient of a sent direct message, or + ``None`` for a channel message, which comes back to our node. + + Returns: + The walk, or ``None`` when the arrival has no route that a trace can walk. + """ + if arrival.routed or not arrival.route_known: + return None + hops = arrival.hops + if outbound: + if far_key: + return TraceWalk(far_key, hops) + return TraceWalk(None, hops) if hops else None + back = tuple(reversed(hops)) + if origin_key: + return TraceWalk(origin_key, back) + if not hops: + return None + # Out to the first relay, and back on the same relays (refer to render_forced_spec). + return TraceWalk(None, back + hops[1:]) diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py index e8a02e9..2623e08 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -65,6 +65,7 @@ from .widgets import ( if TYPE_CHECKING: from ..context import AppContext + from ..services.message_paths import TraceWalk from .map_render import MapMarker from .map_screen import Locator from .node_detail_screen import ContactPages @@ -2100,6 +2101,57 @@ def _sent_scope_line(ctx: AppContext, message: ChatMessage, *, relayed: bool) -> return line +async def _trace_walk( + ctx: AppContext, + walk: TraceWalk, + *, + contacts: list[Contact], + label: str | None, +) -> None: + """Open the trace screen armed on the walk of one arrival, and run it until the user leaves. + + The screen opens idle, armed on the route. Nothing transmits until the user starts a + trace there. A walk with a target opens *Trace target*. The spec is the leg out to the + target, the target, and the mirror of the leg back + (:func:`~meshterm.services.topology.render_forced_spec`). A walk with no target opens + *Trace path* on the walk as given. The width of each hop is the routing width of the + device, collapsed to what a trace can encode, the same as the trace screen uses. + + Args: + ctx: The shared application context. + walk: The walk of the arrival (refer to + :func:`~meshterm.services.message_paths.trace_walk`). + contacts: The contacts of the device. A target that is a contact opens under the + name of that contact, the same as from its node page. Thus the history of its + traces stays in one place. + label: The name of the target node, for a target that is not a contact. + """ + from ..services.topology import render_custom_spec, render_forced_spec + from .trace_screen import collapse_trace_width, open_trace, open_trace_path + + try: + width = collapse_trace_width(int(await ctx.devstate.path_hash_mode())) + except Exception: # noqa: BLE001 - an optional read. The 1-byte default always works. + width = 1 + if walk.target is None: + await open_trace_path(ctx, render_custom_spec(walk.hops, width)) + return + key = walk.target.lower() + + def holds(contact: Contact) -> bool: + # A key prefix and a full key name the same node, in either order. + own = (contact.public_key or contact.key_prefix or "").lower() + return bool(own) and (own.startswith(key) or key.startswith(own)) + + contact = next((c for c in contacts if holds(c)), None) + await open_trace( + ctx, + contact.name if contact is not None else key, + initial_spec=render_forced_spec(walk.hops, key, width), + label=label, + ) + + async def _make_paths_presenter( ctx: AppContext, conversation: Conversation, @@ -2123,16 +2175,22 @@ async def _make_paths_presenter( conversation: The conversation that the chat screen opens. device: The connected device (the caller already awaited it). + The window stays pushed while the user traces a route from it (Enter on an arrival). + The trace screen opens above it, and Esc from the trace comes back to the same window, + with its highlight. + Returns: An async callable that shows the paths of one message in a floating window. """ from ..services import trace_runner from ..services.message_paths import ( + Arrival, channel_arrivals, collapse, direct_arrivals, distinct_paths, message_scope, + trace_walk, ) from .message_paths_screen import MessagePathsScreen @@ -2158,6 +2216,7 @@ async def _make_paths_presenter( secret = None async def present(message: ChatMessage) -> None: + peer_key: str | None = None if conversation.is_channel and secret: arrivals = channel_arrivals( ctx.repo, message, channel_name=conversation.label, secret=secret @@ -2224,22 +2283,49 @@ async def _make_paths_presenter( source, _body = split_channel_sender(message.text) else: source = conversation.label - await session.run_screen( - MessagePathsScreen( - message, - arrivals, - matched=matched, - resolve=resolve, - prefix_bytes=prefix_bytes, - self_name=self_name, - summary=summary, - source=source or None, - destination=destination or None, - type_of=type_of, - key_of=key_of, - scope=message_scope(arrivals, ctx.region_store.scope_of), - sent_scope=_sent_scope_line(ctx, message, relayed=bool(arrivals)), + # The keys of the two ends, for a trace of a route (refer to trace_walk). The peer + # of a direct chat is the recipient of our sends and the sender of what we receive. + # A channel message names its sender only by name, and the key comes from that name. + if message.outbound: + origin_key = None + far_key = None if conversation.is_channel else peer_key + elif conversation.is_channel: + origin_key = key_of(source) if source else None + far_key = None + else: + origin_key, far_key = peer_key, None + + def walk_of(arrival: Arrival) -> TraceWalk | None: + return trace_walk( + arrival, outbound=message.outbound, origin_key=origin_key, far_key=far_key ) + + screen = MessagePathsScreen( + message, + arrivals, + matched=matched, + resolve=resolve, + prefix_bytes=prefix_bytes, + self_name=self_name, + summary=summary, + source=source or None, + destination=destination or None, + type_of=type_of, + key_of=key_of, + scope=message_scope(arrivals, ctx.region_store.scope_of), + sent_scope=_sent_scope_line(ctx, message, relayed=bool(arrivals)), + can_trace=lambda arrival: walk_of(arrival) is not None, ) + # A hub, not a one-time dialog: each Enter traces one route above the window, and + # the window stays with its highlight for the next one. + async with session.stay(screen) as visit: + while True: + chosen = await visit.result() + if not isinstance(chosen, Arrival): + return + walk = walk_of(chosen) + if walk is not None: + label = destination if message.outbound else source + await _trace_walk(ctx, walk, contacts=contacts, label=label or None) return present diff --git a/meshterm/ui/message_paths_screen.py b/meshterm/ui/message_paths_screen.py index 8f8c53d..0908dc8 100644 --- a/meshterm/ui/message_paths_screen.py +++ b/meshterm/ui/message_paths_screen.py @@ -48,18 +48,31 @@ atom in the title (``Message paths ยท scope harbour``). The title states it one the message, not for each arrival, because each copy carries the transport code of its sender unchanged (refer to :func:`~meshterm.services.message_paths.message_scope`). +**Enter traces the selected route.** The dialog returns the selected arrival, and the +caller opens a trace screen above the dialog, armed on the same route as walked from our +node (:func:`~meshterm.services.message_paths.trace_walk`). A received message is traced +back to its sender, and a sent direct message out to its recipient, in *Trace target*. +Thus a trace that comes home can become the route of the radio to that contact, through +the *Device route* row of that screen. A sent channel message is walked again in *Trace +path*. The dialog stays pushed below the trace screen, with its highlight, and Esc from +the trace comes back to it. A direct-routed copy has no route that a trace can walk, and +then the hint does not show Enter. + Nothing in this module transmits. Like the service below it, this dialog is a read-model -over the packets that the radio already heard. +over the packets that the radio already heard. The trace screen transmits only when the +user starts a trace there. """ from __future__ import annotations +from collections.abc import Callable from typing import TYPE_CHECKING from rich.text import Text from ..core.models import ChatMessage, clock_tolerance_s from ..services.message_paths import Arrival +from .menus import HINT_CELLS from .pathgraph import PathLayer, render_path_graph, revisited_hops from .pathline import ( ELIDE_HEAD, @@ -75,6 +88,7 @@ from .pathline import ( from .placemode import ACTION as PLACES_ACTION from .placemode import PlaceToggle, node_of, placed, places_of_session from .theme import snr_style +from .tui.frame import fit_hint from .tui.render import crop_cells, render_lines, render_to_ansi from .tui.screen import ListWindow, Screen from .widgets import ( @@ -135,6 +149,7 @@ class MessagePathsScreen(Screen): key_of: NameKeyResolver | None = None, scope: Scope | None = None, sent_scope: Text | None = None, + can_trace: Callable[[Arrival], bool] | None = None, ) -> None: """Build the dialog for the matched arrivals of one message. @@ -174,6 +189,9 @@ class MessagePathsScreen(Screen): that the message was flooded under (``sent under scope yul``), and why no node relayed it, when that is known. The dialog draws this line under the summary. ``None`` draws nothing. + can_trace: Whether a trace can walk the route of an arrival. When it can, + Enter on that arrival resolves the dialog with it, and the caller opens + the trace. ``None`` offers no trace. """ super().__init__() self.title = self.titled(scope) @@ -191,6 +209,7 @@ class MessagePathsScreen(Screen): self._type_of = type_of self._key_of = key_of self._sent_scope = sent_scope + self._can_trace = can_trace self._index = 0 #: The number of cells by which the selected row is moved left (set to zero each #: time โ†‘ or โ†“ moves the highlight), and the maximum move, measured against the @@ -226,20 +245,35 @@ class MessagePathsScreen(Screen): # --- input --------------------------------------------------------------- + #: The atoms that go first when the hint is longer than the limit. The pager atom goes + #: first, because โ†‘โ†“ already move through the same rows. The scroll of the line goes + #: next. ``Enter trace`` stays, because no other place says that a route can be traced. + spare_hint_atoms = ("PgUp/PgDn scroll", "โ†โ†’ scroll line") + @property def footer_hint(self) -> str: # type: ignore[override] """The keys for the rows while there are rows. If there are no rows, only the close hint. - The paging atom shows only while the list window hides arrivals. This is the rule of - the whole app: a hint never shows a key that does nothing. + The paging atom shows only while the list window hides arrivals, and ``Enter trace`` + only while a trace can walk the selected route. This is the rule of the whole app: a + hint never shows a key that does nothing. """ if not self._arrivals: return "Esc close" parts = ["โ†‘โ†“ move"] if self._list_hidden: parts.append("PgUp/PgDn scroll") - parts.extend(("โ†โ†’ scroll line", self._places.hint, "Esc close")) - return " ยท ".join(parts) + parts.append("โ†โ†’ scroll line") + if self._traceable(): + parts.append("Enter trace") + parts.extend((self._places.hint, "Esc close")) + return fit_hint(" ยท ".join(parts), HINT_CELLS, shed_first=self.spare_hint_atoms) + + def _traceable(self) -> bool: + """Whether Enter can trace the route of the selected arrival.""" + if self._can_trace is None or not self._arrivals: + return False + return self._can_trace(self._arrivals[self._index]) @property def picocalc_lyra_lane(self): @@ -257,7 +291,7 @@ class MessagePathsScreen(Screen): return tuple(lane) def handle(self, action: str, data: str = "") -> None: - """Move the highlight, move the selected line to the side, or close the dialog.""" + """Move the highlight, move the selected line to the side, trace it, or close the dialog.""" rows = len(self._arrivals) # Both ends clamp. The highlight does not go around to the other end, because the # arrivals scroll in a list window (refer to ListWindow). If the highlight jumps @@ -288,7 +322,12 @@ class MessagePathsScreen(Screen): self._hshift = min(self._hmax, self._hshift + _HSTEP) elif action == PLACES_ACTION: self._places.flip() - elif action in ("escape", "enter"): + elif action == "enter": + # The caller opens the trace above the dialog, and the dialog stays. Enter on a + # route that a trace cannot walk does nothing, and the hint does not show it. + if self._traceable(): + self.resolve(self._arrivals[self._index]) + elif action == "escape": self.resolve(None) def cursor_line(self) -> int | None: diff --git a/meshterm/ui/trace_screen.py b/meshterm/ui/trace_screen.py index 7673cf0..2a4ccb5 100644 --- a/meshterm/ui/trace_screen.py +++ b/meshterm/ui/trace_screen.py @@ -1763,7 +1763,9 @@ def _scenario_detail(scenario: Any) -> Text: return detail -async def open_trace(ctx: AppContext, target: str, *, initial_spec: str = "") -> int: +async def open_trace( + ctx: AppContext, target: str, *, initial_spec: str = "", label: str | None = None +) -> int: """Open the live *Trace target* screen for ``target``, and run it until the user leaves. This is the symmetric feature: can I reach this node? Routes turn at the target and @@ -1779,6 +1781,9 @@ async def open_trace(ctx: AppContext, target: str, *, initial_spec: str = "") -> suggested best path, so that the trace opens ready to walk that path. Empty (the default) opens on the automatic route (learned by the device, best observed, last trace, or direct, refer to :func:`_open_session`). + label: The name that the screen shows for a target that is not a contact (the + Message paths dialog gives the name of the sender with its key). ``None`` + shows the target as given. A contact always shows its own name. Returns: The number of traces that ran while the screen was open. @@ -1786,7 +1791,7 @@ async def open_trace(ctx: AppContext, target: str, *, initial_spec: str = "") -> Raises: RuntimeError: If called outside the interactive menu (no full-screen session). """ - return await _open_session(ctx, target, initial_spec=initial_spec) + return await _open_session(ctx, target, initial_spec=initial_spec, label=label) async def open_trace_path(ctx: AppContext, spec: str = "") -> int: @@ -1814,7 +1819,9 @@ async def open_trace_path(ctx: AppContext, spec: str = "") -> int: return await _open_session(ctx, None, initial_spec=spec) -async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: str = "") -> int: +async def _open_session( + ctx: AppContext, target: str | None, *, initial_spec: str = "", label: str | None = None +) -> int: """Connect and run one live trace session (the two features share this code). This function connects the screen to the radio, the database, and the @@ -1835,8 +1842,11 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st a path walk with no target. initial_spec: A forced path (hex hops separated by commas) on which the path screen opens armed, instead of idle on the history. *Trace this path* in the - trophy case gives it. Ignored in target mode (only path walks arm on a bare - spec). + trophy case gives it. In target mode, it arms only when the target can be + addressed (a contact or a hex key), because a forced path must turn at a real + hash. The Node detail screen and the Message paths dialog give it there. + label: The name to show for a target that is not a contact. ``None`` shows the + target as given. Returns: The number of traces that ran while the screen was open. @@ -1917,7 +1927,7 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st .removeprefix("0x") ) target_hash = raw_hash if is_path_hash(raw_hash) else None - target_label = target_contact.name if target_contact else target + target_label = target_contact.name if target_contact else (label or target) def fresh_topology() -> MeshTopology: """Build the evidence graph from all the data that is stored now and on the device.""" diff --git a/tests/test_chat.py b/tests/test_chat.py index c25b3df..b7a2430 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -3716,3 +3716,69 @@ def test_chat_reply_hint_with_every_key_of_a_selection_fits_in_72_cells() -> Non assert cell_len(hint) <= 72 for atom in ("Enter reply", "^P paths", "^U QR", "^L map", "^O author", "Esc cancel"): assert atom in hint + + +# -- Message paths: Enter traces a route ------------------------------------------------ + + +def _trace_ctx(mode: int = 0): # noqa: ANN202 + """A context with only what the trace opener reads: the path-hash mode of the device.""" + from types import SimpleNamespace + + async def path_hash_mode() -> int: + return mode + + return SimpleNamespace(devstate=SimpleNamespace(path_hash_mode=path_hash_mode)) + + +def _capture_traces(monkeypatch) -> list: # noqa: ANN001 + """Replace the two trace openers. Each call is recorded, and nothing opens.""" + import meshterm.ui.trace_screen as trace_screen + + calls: list = [] + + async def open_trace(ctx, target, *, initial_spec="", label=None): # noqa: ANN001, ANN202 + calls.append(("target", target, initial_spec, label)) + return 0 + + async def open_trace_path(ctx, spec=""): # noqa: ANN001, ANN202 + calls.append(("path", spec)) + return 0 + + monkeypatch.setattr(trace_screen, "open_trace", open_trace) + monkeypatch.setattr(trace_screen, "open_trace_path", open_trace_path) + return calls + + +def test_a_traced_route_opens_trace_target_under_the_contacts_name(monkeypatch) -> None: # noqa: ANN001 + """A contact opens under its own name, armed on the leg, the contact, and the mirror.""" + from meshterm.services.message_paths import TraceWalk + from meshterm.ui.chat import _trace_walk + + calls = _capture_traces(monkeypatch) + alice = Contact(name="Alice", public_key="d4e5f6a7" + "0" * 56, key_prefix="d4e5f6a7") + walk = TraceWalk("d4e5f6a7", ("cc", "bb")) + asyncio.run(_trace_walk(_trace_ctx(), walk, contacts=[alice], label="Alice")) + assert calls == [("target", "Alice", "cc,bb,d4,bb,cc", "Alice")] + + +def test_a_traced_route_to_a_stranger_opens_on_its_key_with_its_name(monkeypatch) -> None: # noqa: ANN001 + """A sender that is not a contact opens on its key, and the screen shows its name.""" + from meshterm.services.message_paths import TraceWalk + from meshterm.ui.chat import _trace_walk + + calls = _capture_traces(monkeypatch) + walk = TraceWalk("A3A3A3A3", ("cc",)) + asyncio.run(_trace_walk(_trace_ctx(), walk, contacts=[], label="bob_caribou")) + assert calls == [("target", "a3a3a3a3", "cc,a3,cc", "bob_caribou")] + + +def test_a_walk_with_no_target_opens_trace_path(monkeypatch) -> None: # noqa: ANN001 + """A channel message that came back to our node walks its relays again in Trace path.""" + from meshterm.services.message_paths import TraceWalk + from meshterm.ui.chat import _trace_walk + + calls = _capture_traces(monkeypatch) + walk = TraceWalk(None, ("aabb", "ccdd")) + asyncio.run(_trace_walk(_trace_ctx(mode=1), walk, contacts=[], label=None)) + assert calls == [("path", "aabb,ccdd")] diff --git a/tests/test_gallery.py b/tests/test_gallery.py index 4198725..88ea7a6 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -1201,6 +1201,8 @@ def _message_paths(cols: int, rows: int) -> Screen: self_name="Homestead", summary="heard twice", source="Alice", + # As the chat opens it: Enter traces the selected route (the hint shows it). + can_trace=lambda arrival: True, ) diff --git a/tests/test_message_paths.py b/tests/test_message_paths.py index f149a67..d2643df 100644 --- a/tests/test_message_paths.py +++ b/tests/test_message_paths.py @@ -19,10 +19,13 @@ from meshterm.core.channels import channel_hash, derive_secret from meshterm.core.models import ChatMessage, Observation, utcnow from meshterm.persistence.repository import Repository from meshterm.services.message_paths import ( + Arrival, + TraceWalk, channel_arrivals, collapse, direct_arrivals, distinct_paths, + trace_walk, ) SECRET = derive_secret("#general") @@ -410,3 +413,53 @@ def test_collapse_keeps_a_routed_path_apart_from_the_same_hops_flooded(tmp_path: ) assert len(folded) == 2, "a route travelled is not a route intended" assert [a.routed for a in folded] == [False, True] + + +# -- trace_walk: the route of an arrival, walked from our node -------------------------- + + +def test_a_received_message_is_traced_back_to_its_sender() -> None: + """The relays reversed, out to the sender, and the trace turns back there.""" + arrival = Arrival(when=utcnow(), hops=("aa", "bb", "cc"), snr=1.0) + walk = trace_walk(arrival, outbound=False, origin_key="5e", far_key=None) + assert walk == TraceWalk("5e", ("cc", "bb", "aa")) + + +def test_a_sender_with_no_key_is_traced_to_the_first_relay_and_back() -> None: + """With no key for the sender, the trace turns back at the first relay.""" + arrival = Arrival(when=utcnow(), hops=("aa", "bb", "cc"), snr=1.0) + walk = trace_walk(arrival, outbound=False, origin_key=None, far_key=None) + assert walk == TraceWalk(None, ("cc", "bb", "aa", "bb", "cc")) + direct = Arrival(when=utcnow(), hops=(), snr=1.0) + assert trace_walk(direct, outbound=False, origin_key=None, far_key=None) is None + # A sender that we heard direct and that has a key: a trace with no relays. + assert trace_walk(direct, outbound=False, origin_key="5e", far_key=None) == TraceWalk("5e", ()) + + +def test_a_sent_direct_message_is_traced_out_to_its_recipient() -> None: + """Our send walks its relays in order, then turns back at the recipient.""" + arrival = Arrival(when=utcnow(), hops=("aa", "bb"), snr=1.0) + walk = trace_walk(arrival, outbound=True, origin_key=None, far_key="77") + assert walk == TraceWalk("77", ("aa", "bb")) + + +def test_a_sent_channel_message_walks_its_loop_again() -> None: + """Our broadcast came back to our node, so its relays are the full walk.""" + arrival = Arrival(when=utcnow(), hops=("aa", "bb"), snr=1.0) + assert trace_walk(arrival, outbound=True, origin_key=None, far_key=None) == TraceWalk( + None, ("aa", "bb") + ) + + +def test_a_direct_routed_copy_gives_no_trace() -> None: + """The hops of a routed copy are what it still had to walk, so no trace starts there.""" + routed = Arrival(when=utcnow(), hops=("bb",), snr=1.0, routed=True) + consumed = Arrival(when=utcnow(), hops=(), snr=1.0, routed=True) + for arrival in (routed, consumed): + assert trace_walk(arrival, outbound=True, origin_key=None, far_key="77") is None + assert trace_walk(arrival, outbound=False, origin_key="5e", far_key=None) is None + # History from before MeshTerm kept the route type reads as a flood, as the dialog draws it. + old = Arrival(when=utcnow(), hops=("aa",), snr=1.0, routed=None) + assert trace_walk(old, outbound=False, origin_key="5e", far_key=None) == TraceWalk( + "5e", ("aa",) + ) diff --git a/tests/test_message_paths_screen.py b/tests/test_message_paths_screen.py index a54988a..f7b2d70 100644 --- a/tests/test_message_paths_screen.py +++ b/tests/test_message_paths_screen.py @@ -453,3 +453,68 @@ def test_the_selection_clamps_at_both_ends() -> None: for _ in range(10): screen.handle("down") assert screen._index == 5 + + +# -- Enter traces the selected route ---------------------------------------------------- + + +class _Fut: + """A minimal replacement for a future, so that the dialog can resolve with no event loop.""" + + def __init__(self) -> None: + self.value: object = None + self._done = False + + def done(self) -> bool: + return self._done + + def set_result(self, value: object) -> None: + self.value = value + self._done = True + + +def test_enter_returns_the_selected_arrival_for_the_trace() -> None: + """Enter resolves the dialog with the highlighted arrival, and the caller traces it.""" + arrivals = _arrivals() + screen = _screen(arrivals, can_trace=lambda arrival: True) + screen.future = _Fut() + screen.handle("down") + screen.handle("enter") + assert screen.future.done() + assert screen.future.value is arrivals[1] + + +def test_enter_does_nothing_on_a_route_that_no_trace_can_walk() -> None: + """A row with no trace keeps the dialog open, and its hint does not show Enter.""" + arrivals = _arrivals() + screen = _screen(arrivals, can_trace=lambda arrival: arrival is arrivals[0]) + screen.render_body(72) + assert "Enter trace" in screen.footer_hint + screen.handle("down") + assert "Enter trace" not in screen.footer_hint + screen.future = _Fut() + screen.handle("enter") + assert not screen.future.done() + screen.handle("escape") + assert screen.future.done() and screen.future.value is None + + +def test_a_dialog_with_no_trace_offers_no_enter() -> None: + """The dialog opened with no trace (``can_trace`` is ``None``) does not show Enter.""" + screen = _screen(_arrivals()) + screen.render_body(72) + assert "Enter" not in screen.footer_hint + screen.future = _Fut() + screen.handle("enter") + assert not screen.future.done() + + +def test_the_trace_hint_fits_by_shedding_the_pager_first() -> None: + """With paging and the trace, the hint is too long. The pager atom goes, Enter stays.""" + screen = _screen(_many(12), can_trace=lambda arrival: True) + screen.note_viewport(24) + screen.render_body(72) + hint = screen.footer_hint + assert len(hint) <= 72 + assert "Enter trace" in hint and hint.endswith("Esc close") + assert "PgUp/PgDn" not in hint