From 0f9a15fe1cd14daefbe1f7ab26bdb2f69833e198 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sun, 8 Nov 2026 01:05:40 -0500 Subject: [PATCH] Trace target offers the route that just came home as the radio's route MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Trace target gets a Device route row after Explore paths, for a target that the radio has as a contact. It says what the radio holds now, and Enter opens the node page's Device route popup. A trace that came home walked its route out and back, the best proof that MeshTerm can have for a route. When its route out is not the radio's route, the row turns green: "Use this route for DMs and admin — 4/5 came home…". Nothing interrupts the session. The popup then shows the traced route with its proof, and offers "Use the traced route" and, with a site, "Use and keep it" before the usual rows. The popup changes no path of the trace screen, so its traces and medians stay. The gallery's Trace specimen draws the green row at both widths, and the features guide says what it does. Refs: #34 Co-Authored-By: Claude Opus 5.5 --- docs/guide/features.md | 2 +- meshterm/ui/device_route_screen.py | 177 ++++++++++++++++++++++++++--- meshterm/ui/trace_screen.py | 120 ++++++++++++++++++- tests/test_device_route_screen.py | 113 ++++++++++++++++++ tests/test_gallery.py | 11 ++ tests/test_live_screens.py | 15 ++- 6 files changed, 418 insertions(+), 20 deletions(-) diff --git a/docs/guide/features.md b/docs/guide/features.md index 79a7344..58cb306 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -38,7 +38,7 @@ This page lists each interactive screen with its scripted equivalent, where one | --- | --- | --- | | **🌍 Map** | The nodes that have a position, plotted on a real OpenStreetMap street map. The map is drawn as Unicode braille (streets, rivers, and place names). You can pan and zoom. Repeaters are highlighted and drawn on top. When you are offline, the map shows a blank grid. | none (a map is a picture, but `meshterm contacts` lists the same nodes) | | **🌐 Mesh walk** | The observed shape of the mesh, which you walk one node at a time. It is a graph of evidence from trace walks, firmware routes, overheard relay chains, and the neighbour tables of repeaters. It has braille edges that are coloured by SNR, and quality bars. Press Enter to walk to a node. Press ⌫ to go back. Type to find any node. The map shows where the nodes are. The walk shows how the nodes connect. | none | -| **🎯 Trace target** | A live trace screen. Select a target, and each trace streams in, hop by hop. The screen shows the running median and the reliability of each hop. You can compose a route through specific repeaters, or force one. A trace transmits **exactly once**, because repeaters can blacklist nodes that send bursts. To get more samples, run the trace again. | `meshterm trace --target …` | +| **🎯 Trace target** | A live trace screen. Select a target, and each trace streams in, hop by hop. The screen shows the running median and the reliability of each hop. You can compose a route through specific repeaters, or force one. A trace transmits **exactly once**, because repeaters can blacklist nodes that send bursts. To get more samples, run the trace again. A trace that came home proves its route out and back. Thus, when the radio uses another route to the target, the Device route row turns green and offers the traced route for direct messages and admin. | `meshterm trace --target …` | | **👣 Trace path** | The other half of tracing. You compose the whole circuit by hand, out and back, by the way that you choose. Then you walk it. The path composer suggests each next hop from the links that MeshTerm observed, strongest first. If you have the admin password of a repeater, the composer can also get the neighbour table of that repeater over the mesh. | `meshterm trace-path --path …` | | **🧭 Outbound paths** | The ways out of your node that you trust, in your order. A radio link is not the same in the two directions: a repeater that your node hears well can hear your node badly, and most of what MeshTerm knows comes from what your node hears. Thus you name the way out, one or more hops long. Each site where you take the computer (Home, Work) has its own list, and one site is active. A companion that never moves can keep its own list. The trace features then start their suggested routes on your paths. Each path shows how well its first hop hears you (`out`) and how well you hear it (`in`). Measure sends one trace out along a path and back. When your radio hears the way out of another site, the menu asks if you want to use that site. | `meshterm outbound …` | | **🧭 Device route** | The route that your radio holds for each contact, on the Routes tab of the node page. The radio keeps one route for each contact and replaces it with each new one that it learns, good or bad. A route that stopped to work loses each message on it, with no error. Here you see the route and how the radio got it. You can set it (your suggested route comes first), forget it so that the next message floods, or keep it: MeshTerm then writes it back each time that the radio replaces it. A kept route belongs to the site where you are. When you change site, MeshTerm saves the routes that the radio learned at the old site, and writes them back when you return. Discover routes sends one request and shows the route in each direction. When a direct message or an admin login gets no answer on a route, its retry can go by flood. | `meshterm route …` | diff --git a/meshterm/ui/device_route_screen.py b/meshterm/ui/device_route_screen.py index 4644e1f..16bb46a 100644 --- a/meshterm/ui/device_route_screen.py +++ b/meshterm/ui/device_route_screen.py @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 -"""The Device route popup of the node page: see, set, keep, forget, and discover the route. +"""The Device route popup: see, set, keep, forget, and discover the radio's route to a contact. The radio holds one *device route* for each contact: the relays that it sends to the contact through (refer to :mod:`meshterm.services.device_routes`). The Routes tab of the @@ -22,6 +22,11 @@ Enter on the row opens this popup. Its first page shows the route and how the ra The popup asks and then closes (a popup is not a place). The node page then shows the new state on its row. + +Trace target has the same row (:class:`RouteRow`). A trace that came home walked its route +out and back, which is the best proof that MeshTerm can have for a route. Thus, after such +a trace, the row offers the route that the trace walked (a :class:`ProvenRoute`), and the +popup gets two rows before the others: **Use the traced route** and **Use and keep it**. """ from __future__ import annotations @@ -63,6 +68,8 @@ _FORGET = "forget" _DISCOVER = "discover" _NEED_SITE = "site" _COMPOSE = "compose" +_USE_TRACED = "traced" +_KEEP_TRACED = "traced+keep" #: How many heard routes the picker lists after the suggested route. _PICKER_ROUTES = 6 @@ -130,6 +137,31 @@ class RouteEnv: return tuple(self.topology.canonical(hop) or hop for hop in hops) +@dataclass(frozen=True, slots=True) +class ProvenRoute: + """A route out to a contact that traces walked, and on which they came home. + + Attributes: + hops: The relays from our node to the contact, as canonical ids. Empty means no + relay. + home: How many traces came home on the route. + sent: How many traces went out on it. + worst_snr: The median bottleneck SNR (dB) of the traces that came home, if known. + """ + + hops: tuple[str, ...] + home: int + sent: int + worst_snr: float | None = None + + def evidence(self) -> str: + """The proof in words: ``came home 5 of 5 · worst +3.5 dB``.""" + text = f"came home {self.home} of {self.sent}" + if self.worst_snr is not None: + text += f" · worst {self.worst_snr:+.1f} dB" + return text + + def _hops_text(hops: tuple[str, ...]) -> str: count = len(hops) if count == 0: @@ -137,8 +169,15 @@ def _hops_text(hops: tuple[str, ...]) -> str: return "1 hop" if count == 1 else f"{count} hops" -def row_label(status: RouteStatus) -> str: - """The label of the row on the node page: the route that the radio holds, in short.""" +def row_label(status: RouteStatus, *, sep: str = " · ") -> str: + """The label of the row: the route that the radio holds, in short. + + Args: + status: The device route now. + sep: The text between the name of the row and its value. The node page uses a + middle dot. The action list of Trace target uses a dash, because each of its + rows has that shape. + """ if status.hops is None: now = "none, it floods" elif status.origin == ORIGIN_KEPT and status.owner is not None: @@ -149,7 +188,7 @@ def row_label(status: RouteStatus) -> str: now = f"{_hops_text(status.hops)}, learned" if status.skipped_since is not None: now += " · kept route skipped" - return f"Device route · {now}…" + return f"Device route{sep}{now}…" def _where(status: RouteStatus) -> str: @@ -181,8 +220,14 @@ def _route_note(line: Text) -> Separator: return Separator(title) -def _status_rows(env: RouteEnv, status: RouteStatus) -> list[Any]: - """The lines above the actions: the route now, how the radio got it, and the kept route.""" +def _status_rows( + env: RouteEnv, status: RouteStatus, proven: ProvenRoute | None = None +) -> list[Any]: + """The lines above the actions: the route now and its origin, then any other route. + + The other routes are the kept route (when the radio holds another one) and the route + that the traces walked (when it is a change). + """ rows: list[Any] = [] if status.hops is None: rows.append(_note("none — the radio floods, then learns a route")) @@ -208,18 +253,40 @@ def _status_rows(env: RouteEnv, status: RouteStatus) -> list[Any]: "warn", ) ) + if _offers_traced(status, proven): + assert proven is not None + rows.append(_note(f"the trace {proven.evidence()} on:")) + rows.append(_route_note(env.line(proven.hops))) return rows -def _action_rows(status: RouteStatus) -> list[Any]: - """The actions of the first page, for the state of the route.""" - rows: list[tuple[str, str, str]] = [ +def _offers_traced(status: RouteStatus, proven: ProvenRoute | None) -> bool: + """Whether the traced route is a change: it came home, and the radio holds another.""" + return proven is not None and proven.home > 0 and not same_route(status.hops, proven.hops) + + +def _action_rows(status: RouteStatus, proven: ProvenRoute | None = None) -> list[Any]: + """The actions of the first page, for the state of the route and a traced route.""" + rows: list[tuple[str, str, str]] = [] + if _offers_traced(status, proven): + rows.append( + ( + "Use the traced route", + "the kept route changes too" if status.kept is not None else "set it now", + _USE_TRACED, + ) + ) + if status.kept is None and status.owner is not None: + rows.append( + ("Use and keep it", f"write it back here at {_where(status)}", _KEEP_TRACED) + ) + rows.append( ( "Set the route…", "the kept route changes too" if status.kept is not None else "choose its relays", _SET, ) - ] + ) if status.kept is not None: rows.append(("Stop keeping it", "the radio keeps what it holds", _UNKEEP)) elif status.hops is not None: @@ -273,9 +340,17 @@ def _picker_rows(env: RouteEnv, status: RouteStatus) -> list[Any]: return rows -async def open_device_route(ctx: AppContext, env: RouteEnv) -> bool: +async def open_device_route( + ctx: AppContext, env: RouteEnv, *, proven: ProvenRoute | None = None +) -> bool: """Run the Device route popup for one contact. + Args: + ctx: The shared application context. + env: What the popup needs from the page that opened it. + proven: The route that traces walked and came home on, from Trace target. When + it is not the radio's route, the popup offers it first. + Returns: Whether the route or the kept route changed, so that the page shows it again. """ @@ -288,8 +363,13 @@ async def open_device_route(ctx: AppContext, env: RouteEnv) -> bool: title = f"Device route — {env.label}" def first(_values: list) -> WizardPage: - items = [*_status_rows(env, status), Separator(" "), *_action_rows(status)] - return WizardPage(title=title, items=items, default=_SET) + items = [ + *_status_rows(env, status, proven), + Separator(" "), + *_action_rows(status, proven), + ] + default = _USE_TRACED if _offers_traced(status, proven) else _SET + return WizardPage(title=title, items=items, default=default) def second(values: list): # type: ignore[no-untyped-def] - a page, or an awaitable if values[0] != _SET: @@ -304,6 +384,10 @@ async def open_device_route(ctx: AppContext, env: RouteEnv) -> bool: if answers is None: return False action, picked = answers[0], answers[1] + if action in (_USE_TRACED, _KEEP_TRACED) and proven is not None: + if action == _KEEP_TRACED: + return await _guard(ctx, env, ctx.routes.keep(env.contact, proven.hops)) + return await _apply(ctx, env, status, proven.hops) if action == _SET: if picked == _COMPOSE: hops = await _compose(ctx, env, status) @@ -441,3 +525,70 @@ async def _discover(ctx: AppContext, env: RouteEnv, status: RouteStatus) -> bool if answer != "use": return False return await _apply(ctx, env, status, out) + + +class RouteRow: + """The Device route row of Trace target, and the popup that it opens. + + The trace screen reads :meth:`text` at each paint, so the row says what the radio + holds now. After a trace comes home on another route, the row offers that route + instead, and Enter opens the popup with it first. + + Args: + ctx: The shared application context. + contact: The target, as the radio reported it. + device_key: The public key of the connected companion, or ``""``. + build_env: Builds what the popup needs, for the contact as it is now. It runs + when the popup opens, because it reads all the evidence. + """ + + def __init__( + self, + ctx: AppContext, + contact: Contact, + *, + device_key: str, + build_env: Callable[[Contact], RouteEnv], + ) -> None: + """Read the route that the radio holds now.""" + self._ctx = ctx + self._contact = contact + self._device_key = device_key + self._build_env = build_env + self._status = self._read() + + def _read(self) -> RouteStatus: + return self._ctx.routes.status(self._contact, device_key=self._device_key) + + @property + def contact(self) -> Contact: + """The target, as the radio reported it the last time.""" + return self._contact + + def text(self, proven: ProvenRoute | None) -> tuple[str, bool]: + """The label of the row, and whether it is lit: a traced route to offer. + + Args: + proven: The route that the traces of the screen came home on, or ``None``. + """ + if _offers_traced(self._status, proven): + assert proven is not None + came = f"{proven.home}/{proven.sent} came home" + return f"Use this route for DMs and admin — {came}…", True + label = row_label(self._status, sep=" — ") + if proven is not None and proven.home > 0: + label = label.removesuffix("…") + " · same as the trace…" + return label, False + + async def open(self, proven: ProvenRoute | None) -> None: + """Open the popup, then read the contact and its route again after a change.""" + env = self._build_env(self._contact) + if not await open_device_route(self._ctx, env, proven=proven): + return + try: + contacts = await self._ctx.devstate.contacts() + except Exception: # noqa: BLE001 - keep the old snapshot, the row still opens + contacts = [] + wanted = self._contact.public_key.lower() + self._contact = next((c for c in contacts if c.public_key.lower() == wanted), self._contact) + self._status = self._read() diff --git a/meshterm/ui/trace_screen.py b/meshterm/ui/trace_screen.py index fa27a4a..16d5b1b 100644 --- a/meshterm/ui/trace_screen.py +++ b/meshterm/ui/trace_screen.py @@ -46,6 +46,13 @@ it to. An action list controls the screen: ↑/↓ select a row, and Enter runs winner for adoption. The evidence proposes, the measurement decides, and the user makes the choice. When the user adopts a route, the highlight moves to Trace, the same as after the composer. +* **Device route** (Trace target only, for a contact that the radio has) says which route + the radio holds for the target, and opens the Device route popup of the node page + (refer to :mod:`~meshterm.ui.device_route_screen`). A trace that came home walked its + route out and back. Thus, when the route out of such a trace is not the radio's route, + the row turns green and offers it: ``Use this route for DMs and admin``. The popup then + has *Use the traced route* and *Use and keep it* first. Nothing interrupts the session: + only the row changes. * **Path width** opens a small dialog, where the user selects the path-hash width for each hop: 1, 2, or 4 bytes. A forced hop is addressed by this number of bytes from the start of its key. The first value is the routing width of the device. When the @@ -119,6 +126,8 @@ from ..services import trace_runner from ..services.records import first_repeated_edge from ..services.topology import render_forced_spec from .braillechart import meter +from .device_route_screen import ICON as ROUTE_ICON +from .device_route_screen import ProvenRoute, RouteRow from .menus import icon_lane, icon_mark, marked_label, section_heading from .pathline import ( ELIDE_HEAD, @@ -209,7 +218,7 @@ _PATH_LANE = "path " #: are one cell. Thus with a fixed ``"icon "`` prefix, the label of Explore starts one #: column to the right of the labels of all the other actions. Refer to #: :func:`_icon_lane`. -_ACTION_ICONS = ("✎", "⇄", "⚡", "⚙", "#", "▶") +_ACTION_ICONS = ("✎", "⇄", "⚡", ROUTE_ICON, "⚙", "#", "▶") def _icon_lane() -> int: @@ -491,6 +500,8 @@ class TraceScreen(Screen): auto_source: str = "", initial_spec: str = "", open_trophy_case: Callable[[], Awaitable[None]] | None = None, + route_row: RouteRow | None = None, + prove: Callable[[list[TraceResult]], ProvenRoute | None] | None = None, ) -> None: """Create the screen (nothing transmits until the user runs Trace). @@ -548,6 +559,10 @@ class TraceScreen(Screen): open_trophy_case: Opens the trophy case over this screen. The left button of the new-record dialog does this. ``None`` leaves only *Close* in the dialog, which is what a screen that runs outside the menu gets. + route_row: The Device route row (target mode, for a contact that the radio + has), or ``None`` for no row. + prove: Finds the route out that the traces of the screen came home on, for + the Device route row. ``None`` offers no traced route. """ super().__init__() self.title = f"Trace — {target}" if mode == "target" else "Trace path" @@ -571,6 +586,8 @@ class TraceScreen(Screen): self._auto_source = auto_source self._path_spec = initial_spec.strip() self._open_trophy_case = open_trophy_case + self._route_row = route_row if mode == "target" else None + self._prove = prove #: The trophy case disciplines that the current run placed in. The key is the #: title of the discipline, so that a run with more than one sample that #: improves keeps only its latest ``"Title — score"`` label for each board. @@ -614,6 +631,8 @@ class TraceScreen(Screen): # 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"] + if self._route_row is not None: + actions.append("route") actions += ["width", "samples", "trace"] self._actions: tuple[str, ...] = tuple(actions) ready = mode == "target" or bool(self._effective_spec()[0]) @@ -897,6 +916,35 @@ class TraceScreen(Screen): # The same as Compose: when the user adopts a route, the highlight moves to # Trace, so Enter walks it (GitHub #29). self._open_flow(self._explore, focus_trace=True) + elif key == "route": + self._open_route() + + def proven(self) -> ProvenRoute | None: + """The route out that the traces of this route came home on, or ``None``.""" + if self._prove is None or not self._traces: + return None + return self._prove(self._traces) + + def _open_route(self) -> None: + """Open the Device route popup over the screen, with the traced route to offer. + + The popup changes no path of this screen: the route of the radio is a different + thing from the route that Trace walks. Thus the traces and the medians stay. + """ + row = self._route_row + if row is None or self._dialog_open or self._running: + return + self._dialog_open = True + proven = self.proven() + + async def run() -> None: + try: + await row.open(proven) + finally: + self._dialog_open = False + self._session.invalidate() + + self._session.run_detached(run()) def _open_flow( self, flow: PathFlow, seed: str | None = None, focus_trace: bool = False @@ -1008,10 +1056,11 @@ 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 (Explore in - # target mode, Reverse in path mode, whichever is last) and after the - # trace-settings group. - if key in ("explore", "reverse", "samples"): + # 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"): 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 @@ -1078,6 +1127,10 @@ class TraceScreen(Screen): elif key == "explore": _icon(text, "⚡", "warn") text.append("Explore paths") + elif key == "route" and self._route_row is not None: + label, lit = self._route_row.text(self.proven()) + _icon(text, ROUTE_ICON, "ok" if lit else "accent") + text.append(label, style="ok" if lit else "") elif key == "width": w = self._width_bytes() _icon(text, "⚙", "accent") @@ -2570,6 +2623,61 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st }, ) + # The Device route row: only for a target that the radio has as a contact, because the + # radio holds a route only for its own contacts (refer to device_route_screen). + route_row: RouteRow | None = None + prove = None + target_key = (target_contact.public_key if target_contact else "").lower() + if mode == "target" and target_contact is not None and len(target_key) == 64: + from .device_route_screen import RouteEnv + + def build_route_env(current: Contact) -> RouteEnv: + """What the popup needs, from all the evidence that is stored now.""" + topo = fresh_topology() + canonical = topo.canonical(target_key) or target_key[:12] + radio = ( + tuple(topo.canonical(h) or h for h in current.route_hops) + if current.route_hops is not None + else None + ) + return RouteEnv( + contact=current, + label=target_label or current.name, + target=canonical, + topology=topo, + self_key=(device_hash or "").lower(), + width_bytes=width_bytes, + resolve=resolve, + scenarios=topo.scenarios( + canonical, device_route=radio, outbound=outbound, silent_before=silent_before + ), + suggested=topo.suggested(canonical, outbound=outbound, silent_before=silent_before), + outbound=outbound, + ) + + def prove(traces: list[TraceResult]) -> ProvenRoute | None: + """The route out of the newest trace that came home, with the proof of the run.""" + home = [t for t in traces if t.success] + if not home: + return None + hops = _previous_outbound(home[-1], target_key) + if hops is None: + return None + stats = TraceStats.from_traces(record_target, traces) + return ProvenRoute( + hops=tuple(ident.canonical(h) or h for h in hops), + home=len(home), + sent=len(traces), + worst_snr=stats.median_min_snr, + ) + + route_row = RouteRow( + ctx, + target_contact, + device_key=(device_hash or "").lower(), + build_env=build_route_env, + ) + screen = TraceScreen( record_target, mode=mode, @@ -2594,6 +2702,8 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st # path must end at a real hash. initial_spec=initial_spec if (mode == "path" or target_hash is not None) else "", open_trophy_case=_trophy_case_opener(ctx), + route_row=route_row, + prove=prove, ) try: await session.run_screen(screen) diff --git a/tests/test_device_route_screen.py b/tests/test_device_route_screen.py index cd6b6b5..1e100f3 100644 --- a/tests/test_device_route_screen.py +++ b/tests/test_device_route_screen.py @@ -179,3 +179,116 @@ def test_the_route_row_follows_the_routes_on_the_node_page() -> None: newer = _Action("device_route", "🧭", "", "Device route · 1 hop, set by you…") screen.replace_routes(view, route_action=newer, trace_action=trace) assert screen._focusables()[screen._row_index][1] is newer + + +# -- Trace target ---------------------------------------------------------------------- + + +def _row(hops: tuple[str, ...] | None, opened: list | None = None): # noqa: ANN202 + """A RouteRow over a route service that reports ``hops``, and records each open.""" + from meshterm.ui.device_route_screen import RouteRow + + routes = SimpleNamespace( + status=lambda contact, device_key: RouteStatus(hops, ORIGIN_LEARNED), + ) + + class _Row(RouteRow): + async def open(self, proven): # noqa: ANN001, ANN201 + if opened is not None: + opened.append(proven) + + return _Row( + SimpleNamespace(routes=routes), + Contact(name="Alice", public_key=ALICE_KEY), + device_key="", + build_env=lambda contact: _env(), + ) + + +def test_the_trace_row_lights_only_for_a_route_that_is_a_change() -> None: + """A traced route that the radio lacks is offered. The same route says so, quietly.""" + from meshterm.ui.device_route_screen import ProvenRoute + + proven = ProvenRoute(hops=("27d4",), home=4, sent=5, worst_snr=2.5) + assert proven.evidence() == "came home 4 of 5 · worst +2.5 dB" + text, lit = _row(("3d",)).text(proven) + assert lit + assert text == "Use this route for DMs and admin — 4/5 came home…" + text, lit = _row(("27",)).text(proven) + assert not lit + assert text == "Device route — 1 hop, learned · same as the trace…" + text, lit = _row(None).text(None) + assert (text, lit) == ("Device route — none, it floods…", False) + failed = ProvenRoute(hops=("27d4",), home=0, sent=2) + assert not _row(("3d",)).text(failed)[1] + + +def test_the_popup_offers_the_traced_route_first() -> None: + """Use the traced route, then Use and keep it (with a site), then the usual rows.""" + from meshterm.ui.device_route_screen import ProvenRoute + + proven = ProvenRoute(hops=("27d4",), home=3, sent=3) + learned = RouteStatus(("3d",), ORIGIN_LEARNED, owner=HOME) + assert _values(_action_rows(learned, proven)) == [ + "traced", + "traced+keep", + "set", + "keep", + "forget", + "discover", + ] + same = RouteStatus(("27",), ORIGIN_LEARNED, owner=HOME) + assert _values(_action_rows(same, proven))[0] == "set" + + +async def test_trace_target_has_the_row_and_hands_it_the_traced_route() -> None: + """The row follows Explore paths, turns green after a trace home, and opens with it.""" + import asyncio + + from meshterm.ui.device_route_screen import ProvenRoute + from meshterm.ui.trace_screen import TraceScreen + from tests.conftest import plain + from tests.test_live_screens import _FakeSession, _trace + + opened: list = [] + session = _FakeSession() + + async def flow(current): # noqa: ANN001, ANN202 + return current + + async def trace(spec, on_trace): # noqa: ANN001, ANN202 + on_trace(_trace(5.0, 2.0)) + + def prove(traces: list) -> ProvenRoute | None: + home = [t for t in traces if t.success] + return ProvenRoute(("27d4",), len(home), len(traces), 2.0) if home else None + + screen = TraceScreen( + "Alice", + device_label="Us", + device_hash="aabb" + "00" * 30, + resolve=lambda label: label, + session=session, + trace=trace, + compose_path=flow, + explore=flow, + pick_width=flow, + pick_samples=flow, + width_bytes=lambda: 1, + sample_count=lambda: 1, + pace_s=0.0, + route_row=_row(("3d",), opened), + prove=prove, + ) + screen.note_viewport(40) + assert screen._actions == ("compose", "explore", "route", "width", "samples", "trace") + before = "\n".join(plain(line) for line in screen.render_body(72)) + assert "Device route — 1 hop, learned…" in before + screen._on_trace(_trace(5.0, 2.0)) + after = "\n".join(plain(line) for line in screen.render_body(72)) + assert "Use this route for DMs and admin — 1/1 came home…" in after + screen._index = screen._actions.index("route") + screen.handle("enter") + await asyncio.sleep(0) + assert opened == [ProvenRoute(("27d4",), 1, 1, 2.0)] + assert len(screen._traces) == 1 # the popup changes no path of the screen diff --git a/tests/test_gallery.py b/tests/test_gallery.py index c3a1611..4198725 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -1566,6 +1566,16 @@ def _packet_viewer_unknown_scope(cols: int, rows: int) -> Screen: return _packet_viewer_scoped(cols, rows, region="elsewhere") +class _LitRouteRow: + """The Device route row of Trace target after a trace came home on another route.""" + + def text(self, proven): # noqa: ANN001, ANN201 + return "Use this route for DMs and admin — 1/1 came home…", True + + async def open(self, proven): # noqa: ANN001, ANN201 + return None + + def _trace(cols: int, rows: int) -> Screen: async def _noop_flow(current): # noqa: ANN001 return current @@ -1591,6 +1601,7 @@ def _trace(cols: int, rows: int) -> Screen: previous=None, auto_spec=lambda: "", auto_source="", + route_row=_LitRouteRow(), ) screen._on_trace( TraceResult( diff --git a/tests/test_live_screens.py b/tests/test_live_screens.py index 191ca04..7137c1a 100644 --- a/tests/test_live_screens.py +++ b/tests/test_live_screens.py @@ -233,6 +233,7 @@ def _trace_screen( auto_spec=None, auto_source="", open_trophy_case=None, + route_row=None, ) -> tuple[TraceScreen, _FakeSession]: session = _FakeSession() @@ -261,11 +262,22 @@ def _trace_screen( auto_spec=auto_spec or (lambda: ""), auto_source=auto_source, open_trophy_case=open_trophy_case, + route_row=route_row, ) screen.note_viewport(40) # the frame records this before each real paint return screen, session +class _RouteRowStub: + """The Device route row of Trace target, as the screen reads it (refer to RouteRow).""" + + def text(self, proven): # noqa: ANN001, ANN201 + return "Device route — none, it floods…", False + + async def open(self, proven): # noqa: ANN001, ANN201 + return None + + async def test_trace_screen_one_trace_per_enter_accumulates() -> None: """At the default sample count, each Enter key press transmits exactly one trace. @@ -635,7 +647,8 @@ def test_every_action_row_starts_its_words_in_one_cell_in_both_modes(platform_na starts: set[int] = set() marks: set[str] = set() for mode in ("target", "path"): - screen, _ = _trace_screen(mode=mode) + # Target mode with the Device route row, so that each declared mark is drawn. + screen, _ = _trace_screen(mode=mode, route_row=_RouteRowStub()) for key in screen._actions: for selected in (False, True): row = screen._action_text(key, selected).plain