Message paths traces a sender with no key in Trace target

Enter on a received channel message whose sender has no known key opened
Trace path, out to the first relay and back. The sender is a companion
(only a companion sends channel text), so it is the target of the walk,
and the rules of a target that does not relay apply. The dialog now opens
Trace target under the name of the sender:

- The walk turns at the relay that heard the sender, and the line under
  the route says so.
- The composer mirrors the route at its last hop. It has no Auto row,
  because the session has no route to plan for a node with no key.
- The screen has no Explore row, because the evidence graph keeps nodes
  by key.
- A sender with a key but no stored type is also a companion now.

A sender with no key and no name, and a direct message from a peer with no
key, offer no trace.

Refs: #34

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5.5 committed 2026-11-08 23:03:27 -05:00
1 parent 1f20013d49
commit c4a7e2d69f
8 files changed
+212 -55

No files matched your search

+15 -12
View File
@@ -477,15 +477,20 @@ 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
target: The key of the node that the route goes to (a *Trace target* session), or
``None`` when no key names it. A walk to a node with no key can turn only at
the last relay of the route, because no hash can address the node.
hops: For a walk to a node: the route from our node out to the node, without the
two ends. The trace turns at the node, or at the last relay before a node that
does not relay, and comes back on the mirror of the route. For a loop: the full
walk, which ends at a node that our node heard.
loop: Whether the route comes back to our node (a sent channel message), and not to
a node (a *Trace path* session).
"""
target: str | None
hops: tuple[str, ...]
loop: bool = False
def trace_walk(
@@ -506,9 +511,9 @@ def trace_walk(
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.
in the reverse order, back to the sender (``origin_key``). When no key names the
sender, the walk still goes to the sender, and the caller names it. Such a walk can
turn only at the first relay of the message, the relay that heard the sender.
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
@@ -531,11 +536,9 @@ def trace_walk(
if outbound:
if far_key:
return TraceWalk(far_key, hops)
return TraceWalk(None, hops) if hops else None
return TraceWalk(None, hops, loop=True) 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:])
# With no key and no relay, the walk has no hop at which it can turn.
return TraceWalk(None, back) if hops else None
+42 -9
View File
@@ -30,6 +30,7 @@ from ..core.channels import MENTION, split_channel_sender
from ..core.connection import ContactNotOnDeviceError
from ..core.events import EventKind, MeshEvent
from ..core.models import (
NODE_TYPE_CHAT,
ChatMessage,
Contact,
Conversation,
@@ -2107,15 +2108,19 @@ async def _trace_walk(
*,
contacts: list[Contact],
label: str | None,
node_type: int | None = 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.
trace there. A walk to a node opens *Trace target* on that node. Thus the rules for a
target apply: a node that does not relay a trace (a companion) is not the turn of the
walk, and the walk turns at the last relay before it (refer to
:func:`~meshterm.core.models.relays_traces`). The spec is the route out, the turn, and
the mirror of the route back (:func:`~meshterm.services.topology.render_forced_spec`).
A loop 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.
@@ -2124,7 +2129,11 @@ async def _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.
label: The name of the target node, for a target that is not a contact. A walk to
a node with no key opens under this name, so it must have one.
node_type: The type of the target, when the caller knows it from the message (the
sender of channel text is a companion). The screen uses it when MeshTerm has no
stored type for the target.
"""
from ..services.topology import render_custom_spec, render_forced_spec
from .trace_screen import collapse_trace_width, open_trace, open_trace_path
@@ -2133,9 +2142,21 @@ async def _trace_walk(
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:
if walk.loop:
await open_trace_path(ctx, render_custom_spec(walk.hops, width))
return
if walk.target is None:
assert label, "a walk to a node with no key opens under its name"
# No hash addresses a node with no key, so the walk turns at the last relay of the
# route. The caller offers such a walk only for a node that does not relay.
await open_trace(
ctx,
label,
initial_spec=render_custom_spec((*walk.hops, *reversed(walk.hops[:-1])), width),
label=label,
node_type=node_type,
)
return
key = walk.target.lower()
def holds(contact: Contact) -> bool:
@@ -2149,6 +2170,7 @@ async def _trace_walk(
contact.name if contact is not None else key,
initial_spec=render_forced_spec(walk.hops, key, width),
label=label,
node_type=node_type,
)
@@ -2294,11 +2316,20 @@ async def _make_paths_presenter(
far_key = None
else:
origin_key, far_key = peer_key, None
# Only a companion sends channel text. Thus the sender of a channel message does
# not relay a trace, also when MeshTerm never heard its advert.
sender_type = NODE_TYPE_CHAT if conversation.is_channel and not message.outbound else None
def walk_of(arrival: Arrival) -> TraceWalk | None:
return trace_walk(
walk = trace_walk(
arrival, outbound=message.outbound, origin_key=origin_key, far_key=far_key
)
# A walk to a sender with no key turns at its last relay. That is correct only
# for a node that does not relay, and the screen must have a name to show.
if walk is not None and walk.target is None and not walk.loop:
if sender_type is None or not source:
return None
return walk
screen = MessagePathsScreen(
message,
@@ -2326,6 +2357,8 @@ async def _make_paths_presenter(
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)
await _trace_walk(
ctx, walk, contacts=contacts, label=label or None, node_type=sender_type
)
return present
+15 -5
View File
@@ -235,7 +235,9 @@ class PathComposerScreen(Screen):
A pinned target (all three ``target_*`` arguments) selects target mode. The
suggestions do not include the target (the path turns at it implicitly), and the
returned spec adds the target and the mirrored return at its end. With no target,
returned spec adds the target and the mirrored return at its end. A target that
does not relay also selects target mode with only its label, because its walk
turns at the last composed hop. With no target,
the composer is in path mode: the user composes the full walk by hand, and the
composer returns it exactly. ``outbound`` selects outbound mode, which also has no
target.
@@ -323,8 +325,13 @@ class PathComposerScreen(Screen):
@property
def _mirrored(self) -> bool:
"""Whether the return leg is a mirror at the pinned target (target mode)."""
return self._target_id is not None
"""Whether the return leg is a mirror of the route (target mode).
A target that does not relay is target mode also with no ``target_id`` (a node
that is known by name only), because the walk turns at the last composed hop and
never addresses the target.
"""
return self._target_id is not None or not self._target_relays
def _anchor(self) -> str:
"""The node to the left of the insertion slot (our node when the slot is at the start).
@@ -445,7 +452,8 @@ class PathComposerScreen(Screen):
:data:`_MAX_SUGGESTIONS` items.
"""
if self._mirrored:
exclude = frozenset({self._topology.self_id, self._target_id, *self._hops})
target = {self._target_id} if self._target_id is not None else set()
exclude = frozenset({self._topology.self_id, *target, *self._hops})
elif self._outbound: # a node can be in an outbound path only one time
exclude = frozenset({self._topology.self_id, *self._hops})
else:
@@ -513,7 +521,9 @@ class PathComposerScreen(Screen):
rows.append(("fetch", self._anchor()))
# Use is the last row, so End goes to it, and the user leaves with the path
# (JP, 2026-11-07). Auto comes before it.
if self._mirrored: # a path walk has no target for the device to route to
# A path walk has no target for the device to route to, and a target that is known
# by name only has no route for the session to plan.
if self._mirrored and self._target_id is not None:
rows.append(("action", _AUTO))
rows.append(("action", _USE))
return rows
+53 -19
View File
@@ -555,7 +555,8 @@ class TraceScreen(Screen):
rows and for the number of traces that one Trace action runs.
explore: Opens the scenario browser and probe flow over this screen (target
mode only). Resolves to an adopted spec, or to ``None`` to keep the
current spec.
current spec. ``None`` leaves out the Explore row (a target that is known
by name only).
pace_s: The cooldown that sleeps between the traces of a run with more than
one sample. Thus a sample session is never a burst for the repeaters.
previous: The most recent stored trace, if one exists. Its route is the
@@ -666,7 +667,12 @@ class TraceScreen(Screen):
# act in target mode (with no path, the device routes), and in path mode when a
# path is available. A path walk with no path has nothing to trace, so there the
# highlight starts on Compose (GitHub #29: Enter then opens the composer).
actions = ["compose", "explore"] if mode == "target" else ["compose", "reverse"]
# A target that is known by name only has no Explore (the session gives none).
actions = ["compose"]
if mode != "target":
actions.append("reverse")
elif explore is not None:
actions.append("explore")
if self._route_row is not None:
actions.append("route")
actions += ["width", "samples", "trace"]
@@ -1153,11 +1159,10 @@ class TraceScreen(Screen):
if selected:
self._cursor = len(lines)
lines.append(render_to_ansi(text, width))
# Put a gap before the next group: after the build-path group (the Device
# route row when there is one, else Explore in target mode or Reverse in path
# mode) and after the trace-settings group.
closes = ("route",) if self._route_row is not None else ("explore", "reverse")
if key in (*closes, "samples"):
# Put a gap before the next group: after the build-path group (its last row
# is the row before Width) and after the trace-settings group.
closes = self._actions[self._actions.index("width") - 1]
if key in (closes, "samples"):
lines.append("")
# The results are page, not a list window of their own. Nothing highlights them.
# Thus a private list window hides its rows from the arrows, and gives the frame
@@ -1754,7 +1759,12 @@ def _scenario_detail(scenario: Any) -> Text:
async def open_trace(
ctx: AppContext, target: str, *, initial_spec: str = "", label: str | None = None
ctx: AppContext,
target: str,
*,
initial_spec: str = "",
label: str | None = None,
node_type: int | None = None,
) -> int:
"""Open the live *Trace target* screen for ``target``, and run it until the user leaves.
@@ -1774,6 +1784,9 @@ async def open_trace(
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.
node_type: The type of the target, when the caller knows it and MeshTerm possibly
has no stored type (the sender of channel text is a companion). The type of a
contact, or of the last advert of the node, comes first.
Returns:
The number of traces that ran while the screen was open.
@@ -1781,7 +1794,9 @@ async def open_trace(
Raises:
RuntimeError: If called outside the interactive menu (no full-screen session).
"""
return await _open_session(ctx, target, initial_spec=initial_spec, label=label)
return await _open_session(
ctx, target, initial_spec=initial_spec, label=label, node_type=node_type
)
async def open_trace_path(ctx: AppContext, spec: str = "") -> int:
@@ -1810,7 +1825,12 @@ async def open_trace_path(ctx: AppContext, spec: str = "") -> int:
async def _open_session(
ctx: AppContext, target: str | None, *, initial_spec: str = "", label: str | None = None
ctx: AppContext,
target: str | None,
*,
initial_spec: str = "",
label: str | None = None,
node_type: int | None = None,
) -> int:
"""Connect and run one live trace session (the two features share this code).
@@ -1834,9 +1854,12 @@ async def _open_session(
screen opens armed, instead of idle on the history. *Trace this path* in the
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.
hash, or when the target does not relay, because then the walk turns at the
last relay. 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.
node_type: The type of the target, for a target with no stored type (refer to
:func:`open_trace`).
Returns:
The number of traces that ran while the screen was open.
@@ -1895,8 +1918,9 @@ async def _open_session(
# The target as a hash that can be addressed: the full key of a known contact, or
# the typed hex prefix. An unknown target that is not hex can still be traced with
# device routing. But to compose or explore, a destination hash is necessary on
# which to pin the path. A path walk has no target: each target_* stays None, and
# the composer runs with a route by hand.
# which to pin the path, except for a target that does not relay (refer to by_name
# below). A path walk has no target: each target_* stays None, and the composer runs
# with a route by hand.
target_contact: Contact | None = None
target_hash: str | None = None
target_label: str | None = None
@@ -1921,12 +1945,18 @@ async def _open_session(
# Whether the target relays a trace (refer to relays_traces). A contact gives its type.
# A node that is not a contact (the sender of a message, opened from Message paths)
# gives the type of its last advert that MeshTerm heard. A node with no known type is
# traced itself, as before.
# gives the type of its last advert that MeshTerm heard, or else the type that the
# caller knows. A node with no known type is traced itself, as before.
target_type = target_contact.node_type if target_contact is not None else None
if target_type is None and target_hash is not None and target_contact is None:
target_type = ctx.repo.node_type(target_hash[:12])
if target_type is None:
target_type = node_type
target_relays = mode == "path" or relays_traces(target_type)
# A target with no hash that does not relay (the sender of a channel message with no
# known key): each walk to it turns at the last relay, so no walk has to address it.
# Only the evidence of its route is not there, because the graph keeps nodes by key.
by_name = mode == "target" and target_hash is None and not target_relays
def fresh_topology() -> MeshTopology:
"""Build the evidence graph from all the data that is stored now and on the device."""
@@ -2141,7 +2171,7 @@ async def _open_session(
composer again exactly where the user was (the same hops and insertion slot,
with refreshed suggestions).
"""
if mode == "target" and target_hash is None:
if mode == "target" and target_hash is None and not by_name:
await unaddressable()
return None
topo = fresh_topology()
@@ -2729,7 +2759,9 @@ async def _open_session(
session=session,
trace=trace_once,
compose_path=compose,
explore=explore if mode == "target" else None,
# Explore ranks the routes to a node in the graph, which keeps nodes by key. Thus a
# target that is known by name only has no Explore row.
explore=explore if mode == "target" and not by_name else None,
pick_width=pick_width,
pick_samples=pick_samples,
width_bytes=lambda: width_bytes,
@@ -2741,8 +2773,10 @@ async def _open_session(
# A spec from the caller arms the two modes: the stored route of a path walk, or
# the suggested best path that the Node detail screen gives to a target trace. In
# target mode, it arms only when the target can be addressed, because a forced
# path must end at a real hash.
initial_spec=initial_spec if (mode == "path" or target_hash is not None) else "",
# path must end at a real hash, or when the walk turns before the target.
initial_spec=(
initial_spec if (mode == "path" or target_hash is not None or by_name) else ""
),
open_trophy_case=_trophy_case_opener(ctx),
route_row=route_row,
prove=prove,
+25 -6
View File
@@ -3737,8 +3737,8 @@ def _capture_traces(monkeypatch) -> list: # noqa: ANN001
calls: list = []
async def open_trace(ctx, target, *, initial_spec="", label=None): # noqa: ANN001, ANN202
calls.append(("target", target, initial_spec, label))
async def open_trace(ctx, target, *, initial_spec="", label=None, node_type=None): # noqa: ANN001, ANN202
calls.append(("target", target, initial_spec, label, node_type))
return 0
async def open_trace_path(ctx, spec=""): # noqa: ANN001, ANN202
@@ -3759,7 +3759,7 @@ def test_a_traced_route_opens_trace_target_under_the_contacts_name(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")]
assert calls == [("target", "Alice", "cc,bb,d4,bb,cc", "Alice", None)]
def test_a_traced_route_to_a_stranger_opens_on_its_key_with_its_name(monkeypatch) -> None: # noqa: ANN001
@@ -3770,15 +3770,34 @@ def test_a_traced_route_to_a_stranger_opens_on_its_key_with_its_name(monkeypatch
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")]
assert calls == [("target", "a3a3a3a3", "cc,a3,cc", "bob_caribou", None)]
def test_a_walk_with_no_target_opens_trace_path(monkeypatch) -> None: # noqa: ANN001
def test_a_loop_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"))
walk = TraceWalk(None, ("aabb", "ccdd"), loop=True)
asyncio.run(_trace_walk(_trace_ctx(mode=1), walk, contacts=[], label=None))
assert calls == [("path", "aabb,ccdd")]
def test_a_sender_with_no_key_opens_trace_target_under_its_name(monkeypatch) -> None: # noqa: ANN001
"""A channel sender that no key names is still the target, and the walk turns at its relay.
Only a companion sends channel text, and a companion does not relay a trace. Thus the
screen is Trace target on the name of the sender, with the companion rules: the walk
goes out to the relay that heard the sender, and back.
"""
from meshterm.core.models import NODE_TYPE_CHAT
from meshterm.services.message_paths import TraceWalk
from meshterm.ui.chat import _trace_walk
calls = _capture_traces(monkeypatch)
walk = TraceWalk(None, ("3d", "51", "1b", "40"))
asyncio.run(
_trace_walk(_trace_ctx(), walk, contacts=[], label="Lindsay", node_type=NODE_TYPE_CHAT)
)
assert calls == [("target", "Lindsay", "3d,51,1b,40,1b,51,3d", "Lindsay", NODE_TYPE_CHAT)]
+38
View File
@@ -295,6 +295,44 @@ def test_trace_screen_names_the_relay_where_a_companions_walk_turns() -> None:
assert screen._actions[screen._index] == "trace" # a turn: Enter traces at once
def test_trace_screen_for_a_sender_known_by_name_only_has_no_explore_row() -> None:
"""A target with no key has no node in the graph to rank routes to, so Explore is gone.
The screen still opens armed on the walk that turns at the relay of the sender, and the
groups of rows keep their gaps.
"""
keyed, _ = _trace_screen(initial_spec="3d63,f2c2,3d63", relays=False)
assert "explore" in keyed._actions # a target with a key keeps it
bare = TraceScreen(
"Lindsay",
mode="target",
device_label="Us",
device_hash="aabb" + "00" * 30,
resolve=lambda label: label,
session=_FakeSession(),
trace=None, # type: ignore[arg-type]
compose_path=None, # type: ignore[arg-type]
explore=None,
pick_width=None, # type: ignore[arg-type]
pick_samples=None, # type: ignore[arg-type]
width_bytes=lambda: 2,
sample_count=lambda: 1,
pace_s=0.0,
previous=None,
auto_spec=lambda: "",
initial_spec="3d63,f2c2,3d63",
relays=False,
)
bare.note_viewport(40)
assert bare.title == "Trace — Lindsay"
assert bare._actions == ("compose", "width", "samples", "trace")
assert bare._actions[bare._index] == "trace" # armed: Enter traces at once
lines = _plain(bare.render_body(72)).splitlines()
assert "Lindsay can't relay a trace, so the trace turns at f2c2" in " ".join(lines)
compose = next(i for i, line in enumerate(lines) if "Compose" in line)
assert lines[compose + 1].strip() == "" # the build group ends on Compose
def test_trace_screen_wraps_the_turn_line_under_the_route_lane() -> None:
"""The line is a sentence, so it wraps at 53 cells, and no line of the page is wider."""
from rich.cells import cell_len
+5 -4
View File
@@ -425,11 +425,12 @@ def test_a_received_message_is_traced_back_to_its_sender() -> 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."""
def test_a_sender_with_no_key_is_still_the_end_of_the_walk() -> None:
"""With no key for the sender, the walk still goes to the sender, not around a loop."""
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"))
assert walk == TraceWalk(None, ("cc", "bb", "aa"))
assert walk is not None and not walk.loop
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.
@@ -447,7 +448,7 @@ 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")
None, ("aa", "bb"), loop=True
)
+19
View File
@@ -1290,3 +1290,22 @@ def test_composer_for_a_target_that_does_not_relay_turns_at_the_last_hop() -> No
assert screen._walk_nodes() == ["3d63c6429436", "27d4396a2967", "3d63c6429436"]
assert "Far" not in screen._route_preview().text().plain
assert _composer(_topo(), relays=False)._spec() == "" # no relay: nothing to walk
def test_composer_for_a_target_known_by_name_only_still_mirrors_the_route() -> None:
"""A sender with no key is target mode by its label: the route mirrors, with no Auto row."""
screen = PathComposerScreen(
device_label="Us",
device_hash=US + "0" * 52,
topology=_topo(),
width_bytes=1,
target_label="Lindsay",
target_relays=False,
hops=["3d63c6429436", "27d4396a2967"],
)
assert screen.title == "Compose path — Lindsay"
assert screen._spec() == "3d,27,3d"
assert screen._walk_nodes() == ["3d63c6429436", "27d4396a2967", "3d63c6429436"]
actions = [payload for kind, payload in screen._rows() if kind == "action"]
assert "auto" not in actions # no key: the session has no route to plan
assert actions == ["use"]