Forced traces walk the return leg too: no auto reflection
The trace protocol has no separate return-path field, so a forced path (from the composer or an adopted scenario) has to spell out the whole boomerang itself: outbound hops, the target, then those hops mirrored back. We were only sending the outbound half — repeaters never saw the return leg, so a forced multi-hop trace couldn't rely on the destination reflecting it. render_forced_spec() in topology.py is now the one place that builds a forced-path spec; PathScenario.spec() and the composer's _spec() both call it. The composer's live preview already showed the mirrored return dimmed alongside the outbound hops - that display code stays, but the trace screen's planned-route preview now splits the *actual* wire spec at its midpoint instead of assuming it was outbound-only, and the composer's reopen-with-current-path reseeding drops the whole return leg instead of just the spec's last token. Also normalized node-hash display in the composer to the spec's path-hash width (matching the planned/completed route views) instead of a hardcoded 6-hex-digit slice. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a65ce0ccf7
commit
fbcf13baf5
5 files changed
+134
-65
No files matched your search
@@ -71,6 +71,32 @@ def _is_hex(value: str) -> bool:
|
||||
return bool(value) and len(value) % 2 == 0 and all(c in _HEX_DIGITS for c in value)
|
||||
|
||||
|
||||
def render_forced_spec(hops: tuple[str, ...], target_hash: str, width_bytes: int) -> str:
|
||||
"""Render a forced-path spec: outbound hops, the target, then the return leg.
|
||||
|
||||
The MeshCore trace protocol has no separate "return path" field — the whole
|
||||
boomerang (out to the target, back to us) is one path the repeaters walk in
|
||||
order, so the spec must spell out the return hops explicitly, not just the
|
||||
outbound ones. The return leg is always the outbound hops in reverse (the
|
||||
trace protocol doesn't support asymmetric routing), so it's appended here
|
||||
rather than asked of the caller.
|
||||
|
||||
Args:
|
||||
hops: Intermediate repeaters, in order from us outward, excluding both
|
||||
endpoints (empty = trace the target directly, no forced hops).
|
||||
target_hash: The target's hex hash (any width ≥ 1 byte).
|
||||
width_bytes: Preferred per-hop path-hash width in bytes (1, 2, 4, or 8);
|
||||
shrunk via :func:`collapse_width` when a hop's known hash is narrower.
|
||||
|
||||
Returns:
|
||||
A comma-separated hex spec, e.g. ``"3d,f2,3d"`` for one forced hop.
|
||||
"""
|
||||
width = collapse_width(*hops, target_hash, ceiling=width_bytes)
|
||||
outbound = [h[: width * 2] for h in (*hops, target_hash)]
|
||||
outbound.extend(h[: width * 2] for h in reversed(hops))
|
||||
return ",".join(outbound)
|
||||
|
||||
|
||||
def collapse_width(*hashes: str, ceiling: int) -> int:
|
||||
"""The widest representable per-hop hash width every given hash can honour.
|
||||
|
||||
@@ -166,9 +192,10 @@ class HopSuggestion:
|
||||
class PathScenario:
|
||||
"""One candidate outbound route to a target, ready to trace.
|
||||
|
||||
A scenario describes only the *outbound* leg, ending at the target: the trace
|
||||
protocol replies along the reversed path automatically, so the return is always the
|
||||
symmetric mirror and is never part of the spec.
|
||||
A scenario stores only the *outbound* leg — the return is always the symmetric
|
||||
mirror, so there's nothing to choose there — but :meth:`spec` renders the full
|
||||
boomerang, since the trace protocol has no separate return-path field: the whole
|
||||
out-and-back route is one spec the repeaters walk in order.
|
||||
|
||||
Attributes:
|
||||
label: Short human description of where the route came from.
|
||||
@@ -191,23 +218,18 @@ class PathScenario:
|
||||
samples: int = 0
|
||||
|
||||
def spec(self, target_hash: str, width_bytes: int) -> str:
|
||||
"""Render the scenario as a forced-path spec ending at the target.
|
||||
"""Render the scenario as a forced-path spec, return leg included.
|
||||
|
||||
Every hop (and the target's own hash, always the final hop so the destination
|
||||
recognizes the trace and replies) is truncated to one uniform per-hop width —
|
||||
``width_bytes``, shrunk via :func:`collapse_width` when a hop's known hash is
|
||||
narrower, since a trace transmits every hop at the same width (see
|
||||
:func:`~meshterm.services.trace_runner.parse_trace_path`).
|
||||
See :func:`render_forced_spec` for the width-collapsing and return-leg rules.
|
||||
|
||||
Args:
|
||||
target_hash: The target's hex hash (any width ≥ 1 byte).
|
||||
width_bytes: Preferred per-hop path-hash width in bytes (1, 2, 4, or 8).
|
||||
|
||||
Returns:
|
||||
A comma-separated hex spec, e.g. ``"3d,f2"``.
|
||||
A comma-separated hex spec, e.g. ``"3d,f2,3d"``.
|
||||
"""
|
||||
width = collapse_width(*self.hops, target_hash, ceiling=width_bytes)
|
||||
return ",".join(h[: width * 2] for h in (*self.hops, target_hash))
|
||||
return render_forced_spec(self.hops, target_hash, width_bytes)
|
||||
|
||||
|
||||
class MeshTopology:
|
||||
@@ -365,8 +387,9 @@ class MeshTopology:
|
||||
(weakest-link scoring with a per-hop penalty), which is where a path the
|
||||
device never learned — but the data supports — comes from.
|
||||
|
||||
Every scenario is an *outbound* leg only: the trace reply retraces it in
|
||||
reverse automatically, so intermediate links are implicitly crossed twice.
|
||||
Every scenario stores an *outbound* leg only — the return is always those hops
|
||||
mirrored, so there's nothing to rank there — but :meth:`PathScenario.spec`
|
||||
renders the full boomerang; intermediate links are implicitly crossed twice.
|
||||
|
||||
Args:
|
||||
target: The target's canonical id.
|
||||
|
||||
@@ -23,8 +23,11 @@ Interaction, following the reorder screen's cursor-over-rows-and-actions pattern
|
||||
* Enter on **Use this path** commits the composed spec; **Auto** hands routing back to
|
||||
the device; Esc cancels with no change.
|
||||
|
||||
The return leg is never composed: the trace protocol replies along the reversed path
|
||||
automatically, so the dialog shows the outbound route only and says so.
|
||||
The return leg is never composed — it's always the outbound hops in reverse, so
|
||||
there's nothing to choose there — but it isn't optional either: the trace protocol has
|
||||
no separate return-path field, so the spec sent to the device must spell out the whole
|
||||
boomerang, out and back. The preview resolves and shows that return leg dimmed,
|
||||
right alongside the hops you're actually choosing, rather than leaving it to a footnote.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -35,11 +38,11 @@ from typing import Optional
|
||||
from rich.cells import cell_len
|
||||
from rich.text import Text
|
||||
|
||||
from ..services.topology import MeshTopology, _is_hex, collapse_width
|
||||
from ..services.topology import MeshTopology, _is_hex, render_forced_spec
|
||||
from .theme import snr_style
|
||||
from .tui.render import render_lines, render_to_ansi
|
||||
from .tui.screen import Screen
|
||||
from .widgets import _age_seconds, _format_age
|
||||
from .widgets import _age_seconds, _format_age, _shorten_hash
|
||||
|
||||
#: Sentinel spec meaning "no forced path — let the device route" (the trace screen's
|
||||
#: empty-spec convention).
|
||||
@@ -78,8 +81,9 @@ class FetchNeighbours:
|
||||
class PathComposerScreen(Screen):
|
||||
"""Compose a forced outbound trace path step by step.
|
||||
|
||||
Resolves with the finished spec (comma-separated hex, ending at the target),
|
||||
:data:`AUTO_SPEC` for device routing, or :data:`~meshterm.ui.tui.screen.CANCEL`.
|
||||
Resolves with the finished spec (comma-separated hex: outbound hops, the target,
|
||||
then the return leg), :data:`AUTO_SPEC` for device routing, or
|
||||
:data:`~meshterm.ui.tui.screen.CANCEL`.
|
||||
"""
|
||||
|
||||
footer_hint = (
|
||||
@@ -183,35 +187,54 @@ class PathComposerScreen(Screen):
|
||||
return rows
|
||||
|
||||
def _spec(self) -> str:
|
||||
"""Render the composed route as the forced-path spec, target hash appended.
|
||||
"""Render the composed route as the forced-path spec, return leg included.
|
||||
|
||||
The width shrinks below the preferred one only when a composed hop's known hash
|
||||
is narrower (see :func:`collapse_width`), keeping every hop representable.
|
||||
See :func:`~meshterm.services.topology.render_forced_spec` for the
|
||||
width-collapsing and return-leg rules.
|
||||
"""
|
||||
width = collapse_width(*self._hops, self._target_hash, ceiling=self._width_bytes)
|
||||
return ",".join(h[: width * 2] for h in (*self._hops, self._target_hash))
|
||||
return render_forced_spec(tuple(self._hops), self._target_hash, self._width_bytes)
|
||||
|
||||
# --- rendering ---------------------------------------------------------------
|
||||
|
||||
def _node_text(self, node: str) -> Text:
|
||||
"""A node as ``Name (hash)`` when known, else its bare hash, brand-tinted."""
|
||||
def _node_text(self, node: str, *, dim: bool = False) -> Text:
|
||||
"""A node as ``Name (hash)`` when known, else its bare hash.
|
||||
|
||||
The hash is shown at the spec's preferred path-hash width — the same width
|
||||
every other trace-feature view (planned route, completed route, hop table)
|
||||
truncates to — so a node reads the same length everywhere instead of the
|
||||
fixed, arbitrary slice a naive ``node[:n]`` would give it.
|
||||
|
||||
Args:
|
||||
node: The node's canonical id (or ``self_id`` for our own device).
|
||||
dim: Whether to render in the resolved-return-leg's faint style rather
|
||||
than the outbound leg's normal accent/brand styling.
|
||||
"""
|
||||
if node == self._topology.self_id:
|
||||
return Text(self._device_label, style="accent")
|
||||
return Text(self._device_label, style="faint" if dim else "accent")
|
||||
name = self._topology.display_name(node)
|
||||
style = "faint" if dim else "brand"
|
||||
shown = _shorten_hash(node, self._width_bytes)
|
||||
if name:
|
||||
text = Text(name, style="brand")
|
||||
text.append(f" ({node[:6]})", style="muted")
|
||||
text = Text(name, style=style)
|
||||
text.append(f" ({shown})", style="faint")
|
||||
return text
|
||||
return Text(node, style="brand")
|
||||
return Text(shown, style=style)
|
||||
|
||||
def _route_preview(self) -> Text:
|
||||
"""The outbound route under construction, target pinned as the final hop."""
|
||||
"""The route under construction: outbound in full color, the mirrored
|
||||
return leg resolved and dimmed right alongside it.
|
||||
"""
|
||||
text = Text(self._device_label, style="accent")
|
||||
for hop in self._hops:
|
||||
text.append(" → ", style="muted")
|
||||
text.append_text(self._node_text(hop))
|
||||
text.append(" → ", style="muted")
|
||||
text.append(self._target_label, style="ok")
|
||||
for hop in reversed(self._hops):
|
||||
text.append(" → ", style="faint")
|
||||
text.append_text(self._node_text(hop, dim=True))
|
||||
text.append(" → ", style="faint")
|
||||
text.append(self._device_label, style="faint")
|
||||
return text
|
||||
|
||||
def _suggestion_text(self, suggestion) -> Text: # noqa: ANN001
|
||||
@@ -268,12 +291,6 @@ class PathComposerScreen(Screen):
|
||||
self._index = max(0, min(self._index, len(rows) - 1))
|
||||
|
||||
lines = render_lines(self._route_preview(), width)
|
||||
lines.extend(
|
||||
render_lines(
|
||||
Text("return: automatic — the reply retraces the path in reverse", style="faint"),
|
||||
width,
|
||||
)
|
||||
)
|
||||
lines.append("")
|
||||
if self._entry:
|
||||
lines.append(render_to_ansi(Text(f"/{self._entry}", style="warn"), width))
|
||||
|
||||
+45
-18
@@ -18,7 +18,9 @@ whatever you make it, and nothing transmits until you say so. Three verbs drive
|
||||
admin credentials for, the composer can also *fetch that repeater's neighbour table*
|
||||
over the mesh (login required; firmware ignores guests): second-vantage evidence,
|
||||
persisted and folded straight back into the suggestions. Only the outbound leg is
|
||||
composed: the trace protocol replies back along the reversed path automatically.
|
||||
composed — the return is always those hops in reverse — but the spec sent to the
|
||||
device spells out the whole boomerang, since the trace protocol has no separate
|
||||
return-path field.
|
||||
* **x** explores scenarios: ranked candidate routes to the target straight from the
|
||||
topology evidence (the device's own learned route, the direct shot, and the strongest
|
||||
observed alternatives). Adopt one directly — or probe them all, one measured trace per
|
||||
@@ -409,24 +411,46 @@ class TraceScreen(Screen):
|
||||
return line
|
||||
|
||||
def _planned_route(self) -> Optional[Text]:
|
||||
"""The composed outbound path as a route preview, or ``None`` without one.
|
||||
"""The composed path as a route preview, or ``None`` without one.
|
||||
|
||||
Only the outbound leg exists in the spec; the reply retraces it in reverse, so
|
||||
the preview says so instead of drawing a mirrored (and redundant) return chain.
|
||||
``_path_spec`` is the literal wire spec: outbound hops, the target, then the
|
||||
return leg (those hops mirrored) — the trace protocol has no separate
|
||||
return-path field, so the composer already baked the return leg in. The
|
||||
preview splits it back at its midpoint (the target) to dim the return half,
|
||||
reading as "this part isn't yours to compose."
|
||||
"""
|
||||
hops = [h.strip() for h in self._path_spec.split(",") if h.strip()]
|
||||
if not hops:
|
||||
tokens = [h.strip() for h in self._path_spec.split(",") if h.strip()]
|
||||
if not tokens:
|
||||
return None
|
||||
mid = len(tokens) // 2 # outbound hops + target = first half, inclusive
|
||||
outbound, return_leg = tokens[: mid + 1], tokens[mid + 1 :]
|
||||
text = Text(self._device_label, style="accent")
|
||||
for hop in hops:
|
||||
for hop in outbound:
|
||||
text.append(" → ", style="muted")
|
||||
named = self._resolve(hop)
|
||||
if named and named != hop:
|
||||
text.append(named, style="brand")
|
||||
text.append(f" ({hop})", style="muted")
|
||||
else:
|
||||
text.append(hop, style="brand")
|
||||
text.append(" ⟲ auto return (planned)", style="faint")
|
||||
text.append_text(self._planned_hop_text(hop, dim=False))
|
||||
for hop in return_leg:
|
||||
text.append(" → ", style="faint")
|
||||
text.append_text(self._planned_hop_text(hop, dim=True))
|
||||
text.append(" → ", style="faint")
|
||||
text.append(self._device_label, style="faint")
|
||||
return text
|
||||
|
||||
def _planned_hop_text(self, hop: str, *, dim: bool) -> Text:
|
||||
"""One planned-path node: resolved name (with hash) or bare hash.
|
||||
|
||||
Args:
|
||||
hop: The hop's raw hex key prefix.
|
||||
dim: Whether to render in the return leg's faint style rather than the
|
||||
outbound leg's normal brand/muted styling.
|
||||
"""
|
||||
style = "faint" if dim else "brand"
|
||||
text = Text()
|
||||
named = self._resolve(hop)
|
||||
if named and named != hop:
|
||||
text.append(named, style=style)
|
||||
text.append(f" ({hop})", style="faint" if dim else "muted")
|
||||
else:
|
||||
text.append(hop, style=style)
|
||||
return text
|
||||
|
||||
def _summary(self, stats: TraceStats) -> Text:
|
||||
@@ -728,11 +752,14 @@ async def open_trace(ctx: "AppContext", target: str) -> int:
|
||||
return None
|
||||
topo = fresh_topology()
|
||||
target_id = topo.canonical(target_hash) or target_hash[:12]
|
||||
# Re-seed from the current spec, dropping its final hop (the target itself).
|
||||
# Re-seed from the current spec's outbound half only: it reads as hops, the
|
||||
# target, then the target's own hops mirrored back — drop the target and
|
||||
# that whole return leg, keeping just the intermediate hops the user chose.
|
||||
tokens = [p.strip() for p in current.split(",") if p.strip()]
|
||||
seed = [
|
||||
cid
|
||||
for h in [p for p in current.split(",") if p.strip()][:-1]
|
||||
if (cid := topo.canonical(h.strip())) is not None
|
||||
for h in tokens[: len(tokens) // 2]
|
||||
if (cid := topo.canonical(h)) is not None
|
||||
]
|
||||
while True:
|
||||
# Nodes whose neighbour table can be asked for: repeater contacts with a
|
||||
@@ -944,7 +971,7 @@ async def open_trace(ctx: "AppContext", target: str) -> int:
|
||||
SelectScreen(
|
||||
f"reach {target_label} · scenarios",
|
||||
items,
|
||||
prompt="Outbound path only — the reply always retraces it in reverse.",
|
||||
prompt="Choose the outbound leg — the return is always those hops mirrored.",
|
||||
footer_hint="↑↓ move · Enter adopt/probe · Esc back",
|
||||
wrap=False,
|
||||
)
|
||||
|
||||
@@ -164,16 +164,18 @@ async def test_trace_screen_composer_updates_the_spec() -> None:
|
||||
|
||||
async def compose(current: str): # noqa: ANN001
|
||||
asked.append(current)
|
||||
return "3d,f2"
|
||||
return "3d,f2,3d" # one forced hop: outbound, target, then the mirrored return
|
||||
|
||||
screen, _ = _trace_screen(compose_path=compose)
|
||||
screen.handle("text", "p")
|
||||
await asyncio.sleep(0)
|
||||
assert asked == [""]
|
||||
assert screen._path_spec == "3d,f2"
|
||||
assert screen._path_spec == "3d,f2,3d"
|
||||
body = _plain(screen.render_body(100))
|
||||
assert "3d,f2" in body
|
||||
assert "auto return" in body # the planned route previews the outbound leg
|
||||
assert "3d,f2,3d" in body
|
||||
# the planned route previews outbound *and* the resolved, dimmed return leg
|
||||
assert body.count("Us") >= 2
|
||||
assert body.count("3d") >= 2
|
||||
|
||||
|
||||
async def test_trace_screen_explore_adopts_a_scenario_path() -> None:
|
||||
|
||||
@@ -140,13 +140,13 @@ def test_scenarios_rank_observed_route_and_pin_device_route_first() -> None:
|
||||
|
||||
|
||||
def test_scenario_spec_ends_at_target_and_collapses_width() -> None:
|
||||
"""Specs are outbound-only, target-terminated, at a width every hash can honour."""
|
||||
"""Specs walk out to the target then mirror the hops back, at a uniform width."""
|
||||
walks = [_traced(("3d", 12.0), ("f2", -5.0), ("3d", -5.5), (None, 12.0))]
|
||||
topo = _topo(trace_paths=walks)
|
||||
scenario = next(
|
||||
s for s in topo.scenarios("f2c24f54551e") if s.hops == ("3d63c6429436",)
|
||||
)
|
||||
assert scenario.spec("f2c24f54551e", 2) == "3d63,f2c2"
|
||||
assert scenario.spec("f2c24f54551e", 2) == "3d63,f2c2,3d63"
|
||||
assert collapse_width("3d", "f2c24f54551e", ceiling=2) == 1 # narrowest hash rules
|
||||
|
||||
|
||||
@@ -303,7 +303,7 @@ def test_composer_suggests_from_tail_and_appends_on_enter() -> None:
|
||||
walks = [_traced(("3d", 12.0), ("f2", -5.0), ("3d", -5.5), (None, 12.0))]
|
||||
screen = _composer(_topo(trace_paths=walks))
|
||||
body = _rows_plain(screen)
|
||||
assert "Hub" in body and "auto" in body.lower() # suggestion + symmetric-return note
|
||||
assert "Hub" in body and "auto" in body.lower() # suggestion + the "Auto" action row
|
||||
screen.handle("enter") # top row: the Hub suggestion
|
||||
assert screen._hops == ["3d63c6429436"]
|
||||
# From the new tail the target is excluded, so Far never appears as a hop.
|
||||
@@ -344,7 +344,7 @@ def test_composer_hides_fetch_row_off_fetchable_tails() -> None:
|
||||
|
||||
|
||||
async def test_composer_commits_spec_auto_and_cancel() -> None:
|
||||
"""Use resolves the target-terminated spec; Auto resolves the empty spec; Esc cancels."""
|
||||
"""Use resolves the spec with its mirrored return leg; Auto resolves empty; Esc cancels."""
|
||||
import asyncio
|
||||
|
||||
walks = [_traced(("3d", 12.0), (None, 12.0))]
|
||||
@@ -355,7 +355,7 @@ async def test_composer_commits_spec_auto_and_cancel() -> None:
|
||||
screen.handle("up")
|
||||
screen.handle("up") # …then back up to "Use this path"
|
||||
screen.handle("enter")
|
||||
assert screen.future.result() == "3d,f2"
|
||||
assert screen.future.result() == "3d,f2,3d"
|
||||
|
||||
auto = _composer(_topo(trace_paths=walks))
|
||||
auto.future = asyncio.get_running_loop().create_future()
|
||||
|
||||
Reference in new issue
Block a user