diff --git a/meshterm/persistence/db.py b/meshterm/persistence/db.py index 2aa1a44..d6c00e5 100644 --- a/meshterm/persistence/db.py +++ b/meshterm/persistence/db.py @@ -10,7 +10,7 @@ from __future__ import annotations import sqlite3 from pathlib import Path -SCHEMA_VERSION = 14 +SCHEMA_VERSION = 15 _SCHEMA = """ CREATE TABLE IF NOT EXISTS schema_meta ( @@ -138,7 +138,8 @@ CREATE TABLE IF NOT EXISTS observations ( dest TEXT, -- …the recipient's key hash, for an addressed class (hex) src TEXT, -- …the sender's key hash, or its whole key (anon request) tag TEXT, -- …the frame's own token: an ack's checksum, a trace's tag - trace_snrs TEXT -- TRACE rows: comma-separated per-hop SNR readings (dB) + trace_snrs TEXT, -- TRACE rows: comma-separated per-hop SNR readings (dB) + route TEXT -- 'packet' rows: FLOOD/DIRECT/… — what `path` MEANS here ); -- One chat message, sent or received, on a channel or with a contact. Unlike the other @@ -316,3 +317,19 @@ def _migrate(conn: sqlite3.Connection) -> None: # them a replayed row would show a trace's links blank, the same gap the crypto # trio and the addressing columns above were added to close. conn.execute("ALTER TABLE observations ADD COLUMN trace_snrs TEXT") + if "route" not in observation_cols: + # v14 -> v15: a frame's route type, which says what its `path` field *means* — and + # without it the field was being read one way for packets that meant it two. + # + # A FLOOD packet accumulates: every relay appends its hash, so the path is the route + # the packet actually travelled to reach us. A DIRECT packet is the opposite — the + # path is a routing *instruction* the sender wrote and the relays consume, so it + # describes where the packet is going, not where it has been, and an empty one means + # "route used up", not "arrived in zero hops". + # + # Reading every path as a travelled route therefore drew a direct-routed message as + # having reached us out of nowhere, and drew our own outgoing route as if it were an + # inbound one (JP, 2026-09-02). Older rows carry NULL and are read as unknown rather + # than assumed flooded; the raw headers they arrived in were never persisted, so this + # cannot be filled in from history. + conn.execute("ALTER TABLE observations ADD COLUMN route TEXT") diff --git a/meshterm/persistence/repository.py b/meshterm/persistence/repository.py index b124c03..900bd4d 100644 --- a/meshterm/persistence/repository.py +++ b/meshterm/persistence/repository.py @@ -93,7 +93,8 @@ def _packet_raw(row: sqlite3.Row) -> Optional[dict]: src = _row_value(row, "src") tag = _row_value(row, "tag") trace_snrs = _row_value(row, "trace_snrs") - if not any((typename, chan_hash, cipher_mac, dest, src, tag, trace_snrs)): + route = _row_value(row, "route") + if not any((typename, chan_hash, cipher_mac, dest, src, tag, trace_snrs, route)): return None raw: dict = {} if typename: @@ -116,6 +117,8 @@ def _packet_raw(row: sqlite3.Row) -> Optional[dict]: raw["trace_tag" if typename == "TRACE" else "ack_crc"] = tag if trace_snrs: raw["trace_snrs"] = [float(v) for v in str(trace_snrs).split(",") if v] + if route: + raw["route_typename"] = route return raw @@ -1024,12 +1027,14 @@ class Repository: # class keeps relay hashes — so they get their own column rather than `path`. readings = raw.get("trace_snrs") if typename == "TRACE" else None trace_snrs = ",".join(f"{v:g}" for v in readings) if readings else None + # What the frame's `path` means — see the v15 migration. Only a packet row has one. + route = raw.get("route_typename") if obs.kind == "packet" else None self._conn.execute( "INSERT INTO observations " "(run_id, node, public_key, name, kind, node_type, snr, rssi, lat, lon, path, " "observed_at, chan_hash, cipher_mac, crypted, payload_typename, dest, src, tag, " - "trace_snrs) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "trace_snrs, route) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ( run_id, obs.node, @@ -1051,6 +1056,7 @@ class Repository: src, tag, trace_snrs, + route, ), ) self._conn.commit() @@ -1088,7 +1094,7 @@ class Repository: """ rows = self._conn.execute( "SELECT node, name, kind, node_type, snr, rssi, lat, lon, path, observed_at, " - "chan_hash, cipher_mac, crypted, payload_typename, dest, src, tag, trace_snrs " + "chan_hash, cipher_mac, crypted, payload_typename, dest, src, tag, trace_snrs, route " "FROM observations WHERE observed_at >= ? ORDER BY observed_at DESC LIMIT ?", (since.isoformat(), limit), ).fetchall() @@ -1114,7 +1120,7 @@ class Repository: """ rows = self._conn.execute( "SELECT node, name, kind, node_type, snr, rssi, lat, lon, path, observed_at, " - "chan_hash, cipher_mac, crypted, payload_typename, dest, src, tag, trace_snrs " + "chan_hash, cipher_mac, crypted, payload_typename, dest, src, tag, trace_snrs, route " "FROM observations WHERE kind = 'packet' AND observed_at >= ? " "AND observed_at <= ? ORDER BY observed_at ASC LIMIT ?", (start.isoformat(), end.isoformat(), limit), diff --git a/meshterm/services/message_paths.py b/meshterm/services/message_paths.py index c38fd6a..55b4b57 100644 --- a/meshterm/services/message_paths.py +++ b/meshterm/services/message_paths.py @@ -61,6 +61,12 @@ _DIRECT_WINDOW = timedelta(seconds=90) #: midpoint between them would otherwise leave one of them nothing at all. _MIN_HALF_WINDOW = timedelta(seconds=2) +#: Route types whose ``path`` field is a routing *instruction* rather than a record of +#: where the packet has been — the sender writes the route and the relays consume it. The +#: library names the header's two route bits (see its ``ROUTE_TYPENAMES``); the flooded +#: ones accumulate instead, which is the reading every path here used to get. +_ROUTED_TYPES = frozenset({"DIRECT", "TC_DIRECT"}) + #: Frame classes that carry a direct (addressed) text message — the payload class the #: meshcore library names, spelled exactly as it reports it (see #: :data:`~meshterm.core.frames.ADDRESSED_CLASSES`, the packet viewer's lane, the @@ -83,6 +89,13 @@ class Arrival: snr: Reception SNR in dB — of the *last relay*, as with every packet row. resend: The sender's resend counter for this copy (0 = the original send), recovered from a decrypted channel frame; always 0 for direct frames. + routed: Whether the frame was **direct-routed** rather than flooded, which decides + what :attr:`hops` even means. A flooded packet accumulates its path — every + relay appends itself — so the hops are the route it travelled to reach us. A + direct-routed packet carries a route its sender wrote and its relays consume, + so the hops are where it was *going*, and an empty one means the route was used + up rather than that the packet arrived in a single leap. ``None`` for history + recorded before the route type was kept. copies: How many logged frames this row stands for — always ``1`` as the matchers produce them, and more once :func:`collapse` folds a path heard several times into one row. A direct send is retried, and each retry is overheard off every @@ -95,14 +108,32 @@ class Arrival: hops: tuple[str, ...] snr: Optional[float] resend: int = 0 + routed: Optional[bool] = None copies: int = 1 + @property + def route_known(self) -> bool: + """Whether :attr:`hops` says anything about how this copy actually travelled. + + False for a direct-routed frame carrying no path: its route was consumed on the way + and the field is empty because there is nothing left of it, not because the packet + crossed no relays. Drawing that as a zero-hop arrival claimed a neighbour we do not + have — the "impossible direct path" (JP, 2026-09-02). + """ + return bool(self.hops) or not self.routed + def _frame_hops(observation: Observation) -> tuple[str, ...]: - """An observation's relay path as hop hashes (empty = direct).""" + """An observation's path field as hop hashes (see :attr:`Arrival.routed` for what it means).""" return tuple(h for h in (observation.path or "").split(",") if h) +def _frame_routed(raw: dict) -> Optional[bool]: + """Whether a frame was direct-routed, or ``None`` where its route type wasn't kept.""" + name = str(raw.get("route_typename") or "").upper() + return name in _ROUTED_TYPES if name and name != "UNK" else None + + def _texts_match(wire: str, stored: str) -> bool: """Whether an on-air text and a stored chat text are the same message body. @@ -164,6 +195,7 @@ def channel_arrivals( hops=_frame_hops(frame), snr=frame.snr, resend=decrypted.attempt, + routed=_frame_routed(raw), ) ) return arrivals @@ -306,7 +338,10 @@ def direct_arrivals( src, dest = _addressed(raw) if (want_src and src != want_src) or (want_dest and dest != want_dest): continue - arrival = Arrival(when=frame.observed_at, hops=_frame_hops(frame), snr=frame.snr) + arrival = Arrival( + when=frame.observed_at, hops=_frame_hops(frame), snr=frame.snr, + routed=_frame_routed(raw), + ) mac = str(raw.get("cipher_mac") or "").lower() if mac: groups.setdefault(mac, []).append(arrival) @@ -336,16 +371,20 @@ def collapse(arrivals: Sequence[Arrival]) -> list[Arrival]: One :class:`Arrival` per distinct path, in first-heard order, each carrying its :attr:`~Arrival.copies` count. """ - folded: dict[tuple[str, ...], Arrival] = {} + # Keyed on the route type as well as the hops: the same hashes mean two different + # things under the two types, so folding them together would merge a route travelled + # with a route intended. + folded: dict[tuple, Arrival] = {} for arrival in arrivals: - seen = folded.get(arrival.hops) + key = (arrival.hops, arrival.routed) + seen = folded.get(key) if seen is None: - folded[arrival.hops] = replace(arrival, copies=1) + folded[key] = replace(arrival, copies=1) continue best = seen.snr if arrival.snr is None else ( arrival.snr if seen.snr is None else max(seen.snr, arrival.snr) ) - folded[arrival.hops] = replace(seen, snr=best, copies=seen.copies + 1) + folded[key] = replace(seen, snr=best, copies=seen.copies + 1) return list(folded.values()) diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py index 304c653..0be38d0 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -1264,11 +1264,18 @@ async def _make_paths_presenter( if peer_key and self_key else "direct frames are encrypted — matched by time alone" ) - # The graph's left endpoint: who the message set out from. Our own sends are - # us; an inbound channel message names its sender on the wire; a direct chat's - # origin is the conversation's peer (billed as time-matched by the summary). + # The path's two ends: who the message set out from, and who it was addressed to. + # Our own sends leave us for the peer; an inbound channel message names its sender + # on the wire and is addressed to everyone, so it lands on us; a direct chat's + # inbound origin is the conversation's peer. + destination: Optional[str] = self_name if message.outbound: source = self_name + # A channel broadcast is addressed to nobody in particular, and the copies we + # log are its rebroadcasts coming back — so it really does end on us. A direct + # send does not: it was going to one node, and that is where its route ends. + if not conversation.is_channel: + destination = conversation.label elif conversation.is_channel: source, _body = _split_channel_sender(message.text) else: @@ -1277,7 +1284,8 @@ async def _make_paths_presenter( MessagePathsScreen( message, arrivals, matched=matched, resolve=resolve, prefix_bytes=prefix_bytes, self_name=self_name, summary=summary, - source=source or None, type_of=type_of, key_of=key_of, + source=source or None, destination=destination or None, + type_of=type_of, key_of=key_of, ) ) diff --git a/meshterm/ui/message_paths_screen.py b/meshterm/ui/message_paths_screen.py index 8b9ba2c..74ee3d1 100644 --- a/meshterm/ui/message_paths_screen.py +++ b/meshterm/ui/message_paths_screen.py @@ -91,6 +91,7 @@ class MessagePathsScreen(Screen): self_name: Optional[str], summary: str, source: Optional[str] = None, + destination: Optional[str] = None, type_of: Optional[TypeOf] = None, key_of: Optional["NameKeyResolver"] = None, ) -> None: @@ -110,6 +111,11 @@ class MessagePathsScreen(Screen): source: Display name of the message's origin — the sender parsed from a channel message, us for an outbound one, the peer for a direct chat (``None`` reads as an unknown ``?`` origin). + destination: Display name of the node the message was *addressed to* — the far + end for a message we sent, ourselves for one we received. It closes the + path line, so an outgoing message reads ``★ ▶ … ▶ Bob`` rather than + starting and ending on our own star, which is what made every send look + like a round trip (JP, 2026-09-02). ``None`` closes on our own ``★``. type_of: Maps a relay hash to its node type, so the graph marks a repeater ``▲`` (etc.) instead of a generic dot; ``None`` keeps the plain dots. key_of: Maps the origin's display name back to its node's key, so the @@ -126,6 +132,7 @@ class MessagePathsScreen(Screen): self._self_name = self_name self._summary = summary self._source = source + self._destination = destination self._type_of = type_of self._key_of = key_of self._index = 0 @@ -207,12 +214,17 @@ class MessagePathsScreen(Screen): # No blank line above the graph: its canvas already opens with air over the # topmost lane, so a spacer here would read as two rows of margin. - lines.extend(self._graph_lines(width)) - caption = Text("origin → you · white = selected path · labels = hash byte", - style="faint") - lines.append(render_to_ansi(caption, width, no_wrap=True)) - lines.append(render_to_ansi(node_type_legend(), width, no_wrap=True)) - lines.extend(self._revisit_line(width)) + graph = self._graph_lines(width) + if graph: + lines.extend(graph) + far = "you" if not self._destination else self._destination + caption = Text( + f"origin → {far} · white = selected path · labels = hash byte", + style="faint", + ) + lines.append(render_to_ansi(caption, width, no_wrap=True)) + lines.append(render_to_ansi(node_type_legend(), width, no_wrap=True)) + lines.extend(self._revisit_line(width)) lines.append("") for i, arrival in enumerate(self._arrivals): if i == self._index: @@ -260,7 +272,25 @@ class MessagePathsScreen(Screen): prefix_bytes=self._prefix_bytes, self_name=self._self_name, hash_as_name=True, ).hops - return PathLine([self._origin_hop(), *relays, PathHop(SELF_GLYPH, you=True)]).text() + return PathLine([self._origin_hop(), *relays, self._far_hop()]).text() + + def _far_hop(self) -> PathHop: + """The node the path ends on — where the message was addressed, not always us. + + The line used to close on our own ``★`` unconditionally, which is right for a + message we *received* and wrong for one we sent: with our star opening the line too + (:meth:`_origin_hop`), every outgoing message drew ``★ ▶ … ▶ ★`` and read as a round + trip. It is the same rule the line already follows at its head — a path runs between + the nodes it went *between* — applied at last to its tail. + """ + if not self._destination: + return PathHop(SELF_GLYPH, you=True) + if self._self_name and self._destination == self._self_name: + return PathHop(SELF_GLYPH, you=True) + return PathHop( + self._destination, + key=self._key_of(self._destination) if self._key_of else None, + ) def _origin_hop(self) -> PathHop: """The node the message set out from — the route's true head. @@ -294,7 +324,17 @@ class MessagePathsScreen(Screen): fill the list with a dozen identical lines. The SNR is the best that path managed, which is what it is capable of. """ - text = hops_atom(len(arrival.hops)) + # What the hop count *is* depends on the route type, so the lane says which: a + # flooded frame's path is where it has been, a direct-routed one's is where it was + # going, and a routed frame carrying none has had its route consumed — which is not + # the same as having arrived in zero hops, however much an empty field looks like it. + if not arrival.route_known: + text = Text("routed", style="warn") + text.append(" · route not carried", style="muted") + else: + text = hops_atom(len(arrival.hops)) + if arrival.routed: + text.append(" routed", style="muted") text.append(" ") text.append(arrival.when.astimezone().strftime("%H:%M:%S"), style="muted") if arrival.copies > 1: @@ -346,7 +386,9 @@ class MessagePathsScreen(Screen): """The distinct relay paths across the arrivals, in first-heard order.""" seen: list[tuple[str, ...]] = [] for arrival in self._arrivals: - if arrival.hops not in seen: + # A frame whose route was consumed has nothing to draw: an empty lane in the fan + # would be a claim of adjacency the frame never made. + if arrival.route_known and arrival.hops not in seen: seen.append(arrival.hops) return seen @@ -369,6 +411,8 @@ class MessagePathsScreen(Screen): """ selected = self._arrivals[self._index].hops paths = self._paths() + if not paths: + return [] layers = [ PathLayer( hops=path, @@ -380,7 +424,7 @@ class MessagePathsScreen(Screen): ] glyph_of, label_of, label_rgb_of = route_graph_style( resolve=self._resolve, self_name=self._self_name, source=self._source, - type_of=self._type_of, key_of=self._key_of, + destination=self._destination, type_of=self._type_of, key_of=self._key_of, ) return render_path_graph( layers, width, diff --git a/meshterm/ui/widgets.py b/meshterm/ui/widgets.py index c3d5fa6..eb189ce 100644 --- a/meshterm/ui/widgets.py +++ b/meshterm/ui/widgets.py @@ -576,6 +576,7 @@ def route_graph_style( resolve: NodeResolver, self_name: Optional[str], source: Optional[str], + destination: Optional[str] = None, type_of: Optional[TypeOf] = None, key_of: Optional[NameKeyResolver] = None, ) -> tuple[GlyphOf, LabelOf, LabelRgbOf]: @@ -586,8 +587,13 @@ def route_graph_style( plus the first byte of its hash, and each label takes its node's own name hue (us the pure-white ``you``) so a byte reads as the mesh name it stands for. It maps the graph's two endpoint sentinels — :data:`~meshterm.ui.pathgraph.SRC_NODE` on the left, - :data:`~meshterm.ui.pathgraph.DST_NODE` (always us) on the right — plus every relay - hash, to a glyph, a label, and a label colour. + :data:`~meshterm.ui.pathgraph.DST_NODE` on the right — plus every relay hash, to a + glyph, a label, and a label colour. + + The right endpoint is *usually* us, and was once unconditionally so. That is right for + a route we walked or a message we received, and wrong for one we sent: with our own + name on both ends, every outgoing message's graph drew a round trip (JP, 2026-09-02). + ``destination`` names it when it is somebody else. Args: resolve: Maps a relay's hash to a friendly name when one is known. @@ -595,6 +601,9 @@ def route_graph_style( source: The left endpoint's display name (a message's origin, or us for a walk that starts at home — pass ``self_name`` to draw both ends as us). ``None`` reads as an unknown ``?`` origin. + destination: The right endpoint's display name, when the route does not end at us — + the recipient of a message we sent. ``None`` (the default) draws us, which is + what a walk and every received message want. type_of: Maps a relay's hash to its node type, so a relay draws its own map marker (``▲`` repeater, ``■`` room, ``◉`` sensor) in the shared palette instead of a generic dot. ``None``, or a hash whose type it can't resolve, keeps the old @@ -609,11 +618,12 @@ def route_graph_style( :func:`~meshterm.ui.pathgraph.render_path_graph`. """ src_is_self = bool(source) and source == self_name + dst_is_self = not destination or destination == self_name def glyph_of(node: str) -> tuple[str, str]: """Us a star, a typed relay its map marker, a named node a dot, else a ring.""" if node == DST_NODE: - return SELF_MARK + return SELF_MARK if dst_is_self else NODE_MARK if node == SRC_NODE: return SELF_MARK if src_is_self else (NODE_MARK if source else UNKNOWN_MARK) if type_of is not None: @@ -626,7 +636,7 @@ def route_graph_style( def label_of(node: str) -> Optional[str]: """Endpoints by name, relays by their first hash byte.""" if node == DST_NODE: - return self_name or "you" + return (self_name or "you") if dst_is_self else destination if node == SRC_NODE: return source or "?" return node[:2] @@ -639,7 +649,9 @@ def route_graph_style( resolves whatever ``glyph_of`` hands back, style name or hex alike. """ if node == DST_NODE: - return _SELF_RGB + if dst_is_self: + return _SELF_RGB + return _name_rgb(destination, key_of(destination) if key_of else None) if node == SRC_NODE: if src_is_self: return _SELF_RGB diff --git a/tests/test_message_paths.py b/tests/test_message_paths.py index 5c5c586..a644a86 100644 --- a/tests/test_message_paths.py +++ b/tests/test_message_paths.py @@ -114,7 +114,7 @@ def test_channel_arrivals_ignore_frames_outside_the_window(tmp_path: Path) -> No repo.close() -def _direct_raw(dest: str = "", src: str = "", mac: str = "") -> dict: +def _direct_raw(dest: str = "", src: str = "", mac: str = "", route: str = "") -> dict: """A direct-message frame's raw payload, spelled as the meshcore library reports it.""" raw: dict = {"payload_typename": "TEXT_MSG"} if dest: @@ -123,6 +123,8 @@ def _direct_raw(dest: str = "", src: str = "", mac: str = "") -> dict: raw["src_hash"] = src if mac: raw["cipher_mac"] = mac + if route: + raw["route_typename"] = route return raw @@ -280,3 +282,66 @@ def test_collapse_folds_a_repeated_path_into_one_counted_row(tmp_path: Path) -> assert folded[0].when == base, "the first sighting is when the path first worked" assert folded[0].snr == 13.5, "the best reading is what the path can do" + + +def test_a_routed_frames_path_is_where_it_was_going_not_where_it_has_been( + tmp_path: Path, +) -> None: + """The route type decides what ``path`` means, and an empty routed one means nothing. + + A flooded packet accumulates its path — every relay appends itself — so the hops are the + route it travelled to us. A direct-routed packet carries a route its sender wrote and + its relays consume, so an empty path means the route was used up, not that the packet + crossed no relays. Read the second as the first and a message from five hops away is + drawn as having arrived out of thin air: the "impossible direct path" (JP, 2026-09-02). + """ + repo, run = _repo(tmp_path) + now = utcnow() + _record_frame( # flooded, one relay: it really did come to us that way + repo, run, when=now + timedelta(seconds=1), path="3d63", + raw=_direct_raw(dest="a1", src="d4", mac="beef", route="FLOOD"), + ) + _record_frame( # direct-routed, route consumed: says nothing about how it got here + repo, run, when=now + timedelta(seconds=2), path="", + raw=_direct_raw(dest="a1", src="d4", mac="beef", route="DIRECT"), + ) + message = ChatMessage(text="hi", outbound=False, peer="d4e5f6a7", created_at=now) + arrivals, _exact = direct_arrivals( + repo, message, self_key="a1" + "0" * 62, peer_key="d4e5f6a7" + ) + flooded, routed = arrivals + assert flooded.routed is False and flooded.route_known is True + assert routed.routed is True and routed.route_known is False, ( + "an empty routed path is not a zero-hop arrival" + ) + repo.close() + + +def test_history_without_a_route_type_is_unknown_rather_than_assumed(tmp_path: Path) -> None: + """Frames recorded before the route type was kept read as before, not as guesses.""" + repo, run = _repo(tmp_path) + now = utcnow() + _record_frame( + repo, run, when=now + timedelta(seconds=1), path="", + raw=_direct_raw(dest="a1", src="d4", mac="beef"), + ) + message = ChatMessage(text="hi", outbound=False, peer="d4e5f6a7", created_at=now) + arrivals, _exact = direct_arrivals( + repo, message, self_key="a1" + "0" * 62, peer_key="d4e5f6a7" + ) + assert arrivals[0].routed is None + assert arrivals[0].route_known is True, "unknown falls back to the old reading" + repo.close() + + +def test_collapse_keeps_a_routed_path_apart_from_the_same_hops_flooded(tmp_path: Path) -> None: + """Identical hashes mean two different things under the two route types.""" + from meshterm.services.message_paths import Arrival + + base = utcnow() + folded = collapse([ + Arrival(when=base, hops=("3d63",), snr=1.0, routed=False), + Arrival(when=base + timedelta(seconds=1), hops=("3d63",), snr=2.0, routed=True), + ]) + assert len(folded) == 2, "a route travelled is not a route intended" + assert [a.routed for a in folded] == [False, True] diff --git a/tests/test_message_paths_screen.py b/tests/test_message_paths_screen.py index dbcc27e..a7825f5 100644 --- a/tests/test_message_paths_screen.py +++ b/tests/test_message_paths_screen.py @@ -273,3 +273,59 @@ def test_paths_screen_direct_arrival_and_empty_state() -> None: body = _plain(empty.render_body(76)) assert "No direct-message frames logged in the window." in body assert empty.footer_hint == "Esc close" + + +def test_an_outgoing_message_ends_on_its_recipient_not_on_us() -> None: + """THE round-trip fix: our own sends stopped starting and ending on our own star. + + The path line always closed on our ``★``, which is right for a message we received and + wrong for one we sent — with our star opening it too, every outgoing message drew + ``★ ▶ … ▶ ★`` and read as having gone out and come back (JP, 2026-09-02). It is the same + rule the head already followed: a path runs between the nodes it went *between*. + """ + now = utcnow() + sent = ChatMessage(text="on my way", outbound=True, peer="d4e5", created_at=now) + screen = MessagePathsScreen( + sent, [Arrival(when=now, hops=("3d63",), snr=4.0)], + matched=True, resolve=_resolve, prefix_bytes=1, self_name="Homestead", + summary="heard once", source="Homestead", destination="Bob", + ) + body = _plain(screen.render_body(72)) + assert "YUL-Cartierville" in body + assert body.count("Homestead") == 1, "our name belongs at one end of a send, not both" + assert "Bob" in body, "the far end is the recipient" + # The caption names the same far end the line ends on. + assert "origin → Bob" in body + + +def test_a_received_message_still_ends_on_us() -> None: + """The default is unchanged: what we receive does end at our own star.""" + now = utcnow() + got = ChatMessage(text="on my way", outbound=False, peer="d4e5", created_at=now) + screen = MessagePathsScreen( + got, [Arrival(when=now, hops=("3d63",), snr=4.0)], + matched=True, resolve=_resolve, prefix_bytes=1, self_name="Homestead", + summary="heard once", source="Alice", + ) + body = _plain(screen.render_body(72)) + assert "Alice" in body and "Homestead" in body + assert "origin → you" in body + + +def test_a_routed_frame_with_no_path_draws_no_graph_and_says_why() -> None: + """An empty routed path is not a zero-hop arrival, and must not be drawn as one. + + Its route was consumed on the way, so there is nothing to put in the fan — an empty lane + would be a claim of adjacency the frame never made — and the row says so in words rather + than showing a confident ``0 hops``. + """ + now = utcnow() + got = ChatMessage(text="on my way", outbound=False, peer="d4e5", created_at=now) + screen = MessagePathsScreen( + got, [Arrival(when=now, hops=(), snr=4.0, routed=True)], + matched=True, resolve=_resolve, prefix_bytes=1, self_name="Homestead", + summary="heard once", source="Alice", + ) + body = _plain(screen.render_body(72)) + assert "route not carried" in body + assert "origin →" not in body, "no graph, so nothing for the caption to label"