diff --git a/docs/development/writing-style.md b/docs/development/writing-style.md index 9b98fad..8d57647 100644 --- a/docs/development/writing-style.md +++ b/docs/development/writing-style.md @@ -186,6 +186,10 @@ and in quoted text. | outbound path | A path that starts at our node and goes out into the mesh, one or more hops long. The user trusts it for the first hops of a route, because the user knows which way out works | outbound leg (for this: an outbound leg is the outbound half of a trace) | | site | A name for where the user takes the computer (`Home`, `Foulab`), with its outbound paths in order. One site is active | profile (for this: a profile is a connection alias in `config.toml`) | | fixed device | A companion that never moves. It keeps its own outbound paths, and the active site does not apply to it | | +| device route | The route that the radio holds for one contact: the relays that it sends to the contact through. The radio learns it from a path return, and replaces it with each new one | out path, contact path (for this) | +| kept route | A device route that the user chose and told MeshTerm to keep. MeshTerm writes it back each time that the radio replaces it. It belongs to the active site or to a fixed device | pinned route | +| saved route | A device route that the radio learned at a site. MeshTerm saves it when the user changes site, and writes it back when the user returns | | +| path discovery | One flood request to a contact. The answer tells the route in each direction, and the device route does not change | | | via | The prefix for the relay chain of a packet or a message | | | location | The coordinates (latitude and longitude) that a node advertises | coordinates (alone) | | place | The named area nearest the location of a node: a neighbourhood, a village, a town, or a peak. It has a fine part and a coarse part (`Villeray, Montréal`) | location name, locality | diff --git a/docs/guide/features.md b/docs/guide/features.md index 907e48b..79a7344 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -41,6 +41,7 @@ This page lists each interactive screen with its scripted equivalent, where one | **🎯 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 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 …` | | **🏆 Trophy case** | MeshTerm scores each trace that comes home on seven boards: longest distance, farthest node, longest single leg, most nodes (with and without revisits), weakest surviving link, and biggest enclosed loop. It keeps the records for each hash width. A record walk must be a trail, which means that no link is crossed twice in the same direction. | `meshterm records` | ## 🔧 This node: the radio in your hand diff --git a/meshterm/ui/device_route_screen.py b/meshterm/ui/device_route_screen.py new file mode 100644 index 0000000..4644e1f --- /dev/null +++ b/meshterm/ui/device_route_screen.py @@ -0,0 +1,443 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The Device route popup of the node page: see, set, keep, forget, and discover the route. + +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 +node page has one row for it, ``Device route · …``, which says what the radio holds now. +Enter on the row opens this popup. Its first page shows the route and how the radio got it +(learned, set by you, or kept), and lists the actions: + +* **Set the route…** turns the page to a picker. The suggested route comes first (an + outbound path of the user, then the best way on from it), then the other routes that + MeshTerm heard, then *no relays* (a neighbour), then ``Compose…``, which opens the path + composer. When the route is kept, a new route replaces the kept route too. +* **Keep this route** remembers the route for the active site, or for the fixed device, + and MeshTerm writes it back each time that the radio replaces it. With no site, the row + says that Keep needs a site, and opens Outbound paths. +* **Stop keeping it** forgets the choice. The radio keeps what it holds. +* **Forget the route** clears the route in the radio. The next message floods, and the + radio learns a new route from the answer. +* **Discover routes…** sends one path discovery (one flood) and shows the route in each + direction, with ``Use this route`` to set the route out. + +The popup asks and then closes (a popup is not a place). The node page then shows the new +state on its row. +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +from rich.text import Text + +from ..core.models import Contact +from ..core.outbound_store import SOURCE_DEVICE, NoRouteOwnerError +from ..services.device_routes import ( + ORIGIN_KEPT, + ORIGIN_SET, + RouteStatus, + same_route, + silent_before_now, +) +from ..services.topology import MeshTopology, PathScenario +from .cooldown import wait_for_cooldown +from .menus import WizardPage, menu_rows, run_wizard +from .pathline import cut_to, path_line +from .tui.select import Choice, Separator +from .widgets import age_seconds, format_ago + +if TYPE_CHECKING: # pragma: no cover - typing only + from ..context import AppContext + +#: The action key of the row on the node page. +ACTION = "device_route" +#: The icon of the row (the path class of the payload icons). +ICON = "🧭" + +_SET = "set" +_KEEP = "keep" +_UNKEEP = "unkeep" +_FORGET = "forget" +_DISCOVER = "discover" +_NEED_SITE = "site" +_COMPOSE = "compose" +#: How many heard routes the picker lists after the suggested route. +_PICKER_ROUTES = 6 + + +@dataclass(slots=True) +class RouteEnv: + """What the popup needs from the node page, which already read it. + + Attributes: + contact: The contact, as the radio reported it (with its route). + label: The name of the contact on the page. + target: The canonical id of the contact in the graph. + topology: The evidence graph around our node. + self_key: The public key of the connected companion, or ``""``. + width_bytes: The path-hash width at which a hop with no name shows its hash. + resolve: Names a hop that the graph cannot name. + scenarios: The suggested routes of the page, best first. + suggested: The one best route, or ``None``. + outbound: The outbound paths that apply now, as canonical ids. + """ + + contact: Contact + label: str + target: str + topology: MeshTopology + self_key: str + width_bytes: int + resolve: Callable[[str], str | None] + scenarios: list[PathScenario] + suggested: PathScenario | None + outbound: tuple[tuple[str, ...], ...] = () + + def name(self, hop: str | None) -> str | None: + """The name of a hop: the target's label, the name in the graph, or the resolver's.""" + if hop is None: + return None + if hop == self.target: + return self.label + return self.topology.display_name(hop) or self.resolve(hop) or hop + + def line(self, hops: tuple[str, ...]) -> Text: + """A route from our ``★`` through ``hops`` to the contact, as a path line.""" + return path_line( + [None, *hops, self.target], + self.name, + prefix_bytes=self.width_bytes, + hash_bytes=self.width_bytes, + bare_self=True, + dim_self=False, + ).text() + + def back_line(self, hops: tuple[str, ...]) -> Text: + """A route from the contact through ``hops`` back to our ``★``, as a path line.""" + return path_line( + [self.target, *hops, None], + self.name, + prefix_bytes=self.width_bytes, + hash_bytes=self.width_bytes, + bare_self=True, + dim_self=False, + ).text() + + def canonical(self, hops: tuple[str, ...]) -> tuple[str, ...]: + """The hops as the graph names them, where it can (a longer key prefix).""" + return tuple(self.topology.canonical(hop) or hop for hop in hops) + + +def _hops_text(hops: tuple[str, ...]) -> str: + count = len(hops) + if count == 0: + return "no relays" + 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.""" + if status.hops is None: + now = "none, it floods" + elif status.origin == ORIGIN_KEPT and status.owner is not None: + now = f"{_hops_text(status.hops)}, kept at {status.owner.name}" + elif status.origin == ORIGIN_SET: + now = f"{_hops_text(status.hops)}, set by you" + else: + now = f"{_hops_text(status.hops)}, learned" + if status.skipped_since is not None: + now += " · kept route skipped" + return f"Device route · {now}…" + + +def _where(status: RouteStatus) -> str: + """Where a kept route lives, in words.""" + owner = status.owner + if owner is None: + return "" + return f"this radio ({owner.name})" if owner.source == SOURCE_DEVICE else owner.name + + +#: The cells before the text of a status line: the pointer column of the rows below it. +#: Thus the route and the action labels start in the same cell. +_INDENT = " " + + +def _note(text: str, style: str = "muted") -> Separator: + """One status line, in the column of the row labels.""" + return Separator(Text(_INDENT + text, style)) + + +def _route_note(line: Text) -> Separator: + """One route as a status line, in the column of the row labels, cut to the width.""" + + def title(width: int) -> Text: + text = Text(_INDENT) + text.append_text(cut_to(line, max(1, width - len(_INDENT)))) + return text + + 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.""" + rows: list[Any] = [] + if status.hops is None: + rows.append(_note("none — the radio floods, then learns a route")) + else: + rows.append(_route_note(env.line(env.canonical(status.hops)))) + if status.origin == ORIGIN_KEPT: + how = f"kept at {_where(status)}" + elif status.origin == ORIGIN_SET: + how = "set by you" + else: + how = "learned from a path return" + if status.changed_at is not None: + how += f" · {format_ago(age_seconds(status.changed_at))}" + rows.append(_note(how)) + if status.kept is not None and not status.kept_in_radio: + rows.append(_note(f"you keep another route at {_where(status)}:")) + rows.append(_route_note(env.line(status.kept))) + if status.skipped_since is not None: + rows.append( + _note( + "not in the radio: its first hop was last heard " + f"{format_ago(age_seconds(status.skipped_since))}", + "warn", + ) + ) + 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]] = [ + ( + "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: + if status.owner is None: + rows.append(("Keep this route…", "Keep needs a site: open Outbound paths", _NEED_SITE)) + else: + rows.append(("Keep this route", f"write it back here at {_where(status)}", _KEEP)) + if status.hops is not None: + rows.append(("Forget the route", "the next message floods", _FORGET)) + rows.append(("Discover routes…", "one flood: the route each way", _DISCOVER)) + return menu_rows(rows) + + +def _scenario_tag(scenario: PathScenario) -> str: + """Where a suggested route came from, in words.""" + if scenario.source == "outbound": + return f"outbound path {scenario.rank}" + if scenario.source == "device": + return "the radio's route" + if scenario.samples: + return f"heard {scenario.samples}×" + return "heard" + + +def _picker_rows(env: RouteEnv, status: RouteStatus) -> list[Any]: + """The routes to set: the suggested route, the routes heard, no relays, and Compose.""" + rows: list[Any] = [] + seen: list[tuple[str, ...]] = [] + + def add(hops: tuple[str, ...], tag: str) -> None: + if hops in seen or env.target in hops: + return + seen.append(hops) + line = env.line(hops) + now = " · now in the radio" if same_route(status.hops, hops) else "" + + def title(width: int, line: Text = line) -> Text: + return cut_to(line, width) + + rows.append(Choice(title=title, value=("hops", hops), detail=Text(f"{tag}{now}", "muted"))) + + if env.suggested is not None: + add(tuple(env.suggested.hops), f"★ suggested · {_scenario_tag(env.suggested)}") + for scenario in env.scenarios: + if len(seen) > _PICKER_ROUTES: + break + if scenario.source != "direct": + add(tuple(scenario.hops), _scenario_tag(scenario)) + add((), "no relays: the contact is a neighbour") + rows.extend(menu_rows([("Compose…", "choose each hop yourself", _COMPOSE)])) + return rows + + +async def open_device_route(ctx: AppContext, env: RouteEnv) -> bool: + """Run the Device route popup for one contact. + + Returns: + Whether the route or the kept route changed, so that the page shows it again. + """ + status = ctx.routes.status( + env.contact, + device_key=env.self_key, + topo=env.topology, + silent_before=silent_before_now(ctx), + ) + 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) + + def second(values: list): # type: ignore[no-untyped-def] - a page, or an awaitable + if values[0] != _SET: + return _answer(values[0]) + return WizardPage( + title=f"Set the route — {env.label}", + items=_picker_rows(env, status), + prompt="The radio sends to the contact on this route:", + ) + + answers = await run_wizard(ctx.ui.session, [first, second]) + if answers is None: + return False + action, picked = answers[0], answers[1] + if action == _SET: + if picked == _COMPOSE: + hops = await _compose(ctx, env, status) + if hops is None: + return False + else: + hops = picked[1] + return await _apply(ctx, env, status, hops) + if action == _KEEP and status.hops is not None: + return await _guard(ctx, env, ctx.routes.keep(env.contact, env.canonical(status.hops))) + if action == _UNKEEP: + await ctx.routes.unkeep(env.contact) + return True + if action == _FORGET: + return await _guard(ctx, env, ctx.routes.forget(env.contact)) + if action == _NEED_SITE: + from .outbound_screen import manage_outbound + + await manage_outbound(ctx) + return True + if action == _DISCOVER: + return await _discover(ctx, env, status) + return False + + +async def _answer(value: Any) -> Any: + """A step of the wizard that asks nothing: it gives the first answer again at once.""" + return value + + +async def _guard(ctx: AppContext, env: RouteEnv, action: Any) -> bool: + """Run one route action, and say in a dialog why the radio refused it.""" + try: + await action + except NoRouteOwnerError: + await ctx.ui.dialog( + "Keep needs a site. Choose one on Outbound paths first.", + [("OK", None)], + title="Device route", + default=0, + ) + return False + except Exception as exc: # noqa: BLE001 - the radio refused. The page stays as it was + await ctx.ui.dialog( + f"The radio refused the change to the route to {env.label}: {exc}", + [("OK", None)], + title="Device route", + default=0, + danger=True, + ) + return False + return True + + +async def _apply(ctx: AppContext, env: RouteEnv, status: RouteStatus, hops: tuple) -> bool: + """Write a picked route. A kept route is replaced, so that the radio keeps the new one.""" + hops = tuple(hops) + if status.kept is not None: + return await _guard(ctx, env, ctx.routes.keep(env.contact, hops)) + return await _guard(ctx, env, ctx.routes.set(env.contact, hops)) + + +async def _compose(ctx: AppContext, env: RouteEnv, status: RouteStatus) -> tuple | None: + """Compose a route hop by hop in the path composer. ``None`` when the user backs out. + + The composer composes a trace to the contact, so its Auto row means "let the device + route". Here, that is to forget the route. + """ + from .path_composer import AUTO_SPEC, PathComposerScreen + from .tui.screen import CANCEL + + seed = list(env.canonical(status.hops)) if status.hops else None + screen = PathComposerScreen( + device_label="you", + device_hash=env.self_key or None, + topology=env.topology, + width_bytes=env.width_bytes, + target_id=env.target, + target_hash=(env.contact.public_key or env.target).lower(), + target_label=env.label, + hops=seed, + resolve=env.resolve, + outbound_paths=env.outbound, + ) + result = await ctx.ui.session.run_screen(screen) + if result is CANCEL or result is None: + return None + if result == AUTO_SPEC: + await _guard(ctx, env, ctx.routes.forget(env.contact)) + return None + return tuple(screen.hops) + + +async def _discover(ctx: AppContext, env: RouteEnv, status: RouteStatus) -> bool: + """Send one path discovery, show the two routes, and set the route out on request.""" + if not await wait_for_cooldown(ctx, action="Path discovery"): + return False + try: + async with ctx.ui.busy_dialog( + f"asking {env.label} for its routes…", title="Discover routes" + ): + found = await ctx.routes.discover(env.contact) + except Exception as exc: # noqa: BLE001 - say why, and keep the page + await ctx.ui.dialog( + f"The radio couldn't send the path discovery: {exc}", + [("OK", None)], + title="Discover routes", + default=0, + danger=True, + ) + return False + if found is None: + await ctx.ui.dialog( + f"No answer from {env.label}. It may be out of reach, or asleep.", + [("OK", None)], + title="Discover routes", + default=0, + ) + return False + out = env.canonical(found.out_hops) + back = env.canonical(found.in_hops) + prompt = Text() + prompt.append(f"Out, to {env.label} ({_hops_text(out)}):\n", "muted") + prompt.append_text(env.line(out)) + prompt.append(f"\n\nBack, to you ({_hops_text(back)}):\n", "muted") + prompt.append_text(env.back_line(back)) + if same_route(status.hops, out): + prompt.append("\n\nThe radio already holds the route out.", "muted") + answer = await ctx.ui.dialog( + prompt, + [("Close", None), ("Use this route", "use")], + title=f"Discover routes — {env.label}", + default=1, + ) + if answer != "use": + return False + return await _apply(ctx, env, status, out) diff --git a/meshterm/ui/node_detail_screen.py b/meshterm/ui/node_detail_screen.py index d9c7f38..bd2894b 100644 --- a/meshterm/ui/node_detail_screen.py +++ b/meshterm/ui/node_detail_screen.py @@ -117,6 +117,10 @@ from ..core.places import SOURCE_USER from ..platforms import Platform, on_platform from ..services.clock_offsets import node_offset, room_posts_blocked from . import menus +from .device_route_screen import ACTION as DEVICE_ROUTE_ACTION +from .device_route_screen import ICON as DEVICE_ROUTE_ICON +from .device_route_screen import RouteEnv, open_device_route +from .device_route_screen import row_label as device_route_label from .mapcanvas import RGB from .marks import MANAGED_ICON, SELF_MARK from .minimap import MiniMap @@ -503,6 +507,7 @@ class NodeDetailScreen(Screen): routes: _RoutesView | None = None, info_actions: list[_Action] | None = None, trace_action: _Action | None = None, + route_action: _Action | None = None, mark: Text | None = None, place_row: Callable[[], Text | None] | None = None, ) -> None: @@ -534,6 +539,9 @@ class NodeDetailScreen(Screen): trace_action: The ``Trace — auto route …`` action of the Routes tab, or ``None``. It is shown only when there are no routes to list. When routes are listed, Enter on a route row starts the trace. + route_action: The ``Device route · …`` row of the Routes tab, after the routes, + or ``None`` when the radio has no contact for the node (refer to + :mod:`meshterm.ui.device_route_screen`). place_row: Gives the value of the ``place`` vital, or ``None`` when there is no place. The page asks at each paint, because the place finder can answer after the page opened (refer to :mod:`meshterm.services.places`). @@ -553,6 +561,7 @@ class NodeDetailScreen(Screen): self._routes = routes self._info_actions = info_actions or [] self._trace_action = trace_action + self._route_action = route_action #: The width in cells of the icon lane of the action rows. It is measured one time #: over each mark that this page can draw. Thus a one-cell ``🗑`` gets padding to the #: width of its two-cell siblings, and each label starts in the same cell. It is zero @@ -708,7 +717,8 @@ class NodeDetailScreen(Screen): def _measure_icon_lane(self) -> int: """The icon lane of the action rows, measured over each mark that is now on the page.""" trace = [self._trace_action] if self._trace_action else [] - return menus.icon_lane(action.glyph for action in (*self._info_actions, *trace)) + route = [self._route_action] if self._route_action else [] + return menus.icon_lane(action.glyph for action in (*self._info_actions, *trace, *route)) def replace_info_row(self, label: str, value: Text) -> None: """Replace the value of one vital in place: the regions row, after the repeater answered. @@ -760,6 +770,33 @@ class NodeDetailScreen(Screen): self._row_index = index break + def replace_routes( + self, + routes: _RoutesView | None, + *, + route_action: _Action | None, + trace_action: _Action | None, + ) -> None: + """Replace the Routes tab in place, after the device route changed. + + The routes are data (the device route tags one of them, and it leads the + suggestions), so the list refreshes and the page stays. The highlight stays on the + ``Device route`` row, because the user comes back to the row that opened the popup. + """ + self._routes = routes + self._route_action = route_action + self._trace_action = trace_action + self._stage_memo = None + self._route_sel = 0 + self._icon_lane = self._measure_icon_lane() + focus = self._focusables() + for index, (_kind, payload) in enumerate(focus): + if payload is route_action and route_action is not None: + self._row_index = index + break + else: + self._row_index = min(self._row_index, max(0, len(focus) - 1)) + def handle(self, action: str, data: str = "") -> None: """Answer one key press on the page. @@ -879,6 +916,8 @@ class NodeDetailScreen(Screen): focus.extend(("path", i) for i in range(len(self._routes.routes))) if not self._routes.routes and self._trace_action is not None: focus.append(("action", self._trace_action)) + if self._route_action is not None: + focus.append(("action", self._route_action)) elif tab is not None and tab.kind == "info": focus.extend(("action", a) for a in self._info_actions) return focus @@ -1856,6 +1895,84 @@ async def open_node_detail( trace_action: _Action | None = None if not you and node_id and not (routes_view is not None and routes_view.routes): trace_action = _Action("trace", "🎯", "", "Trace — auto route …") + # -- the device route: the route that the radio holds for this contact, after the routes + # (refer to meshterm.ui.device_route_screen). Only a contact that the radio has gets it, + # because the radio holds a route only for its own contacts. + route_env: RouteEnv | None = None + route_action: _Action | None = None + if ( + routes_view is not None + and contact is not None + and whole_key + and canonical_target is not None + and getattr(ctx, "routes", None) is not None + and not _is_archived(ctx, contact, self_key) + ): + route_env = RouteEnv( + contact=contact, + label=label, + target=canonical_target, + topology=topo, + self_key=dev_pub, + width_bytes=width_bytes, + resolve=resolve, + scenarios=list(scenarios), + suggested=suggested, + outbound=outbound, + ) + + def device_route_row(current: Contact) -> _Action: + """The row of the device route, for what the radio holds now.""" + status = ctx.routes.status( + current, device_key=dev_pub, topo=topo, silent_before=silent_before + ) + return _Action(DEVICE_ROUTE_ACTION, DEVICE_ROUTE_ICON, "", device_route_label(status)) + + if route_env is not None: + route_action = device_route_row(route_env.contact) + + async def refresh_device_route() -> None: + """Read the contact again after a change, and draw the Routes tab again in place.""" + assert route_env is not None + try: + fresh = await ctx.devstate.contacts() + except Exception: # noqa: BLE001 - keep the old snapshot, the row still opens + fresh = [] + wanted = route_env.contact.public_key.lower() + current = next((c for c in fresh if c.public_key.lower() == wanted), route_env.contact) + route_env.contact = current + new_route = ( + tuple(topo.canonical(h) or h for h in current.route_hops) + if current.route_hops is not None + else None + ) + route_env.scenarios = topo.scenarios( + route_env.target, + device_route=new_route, + outbound=outbound, + silent_before=silent_before, + ) + view = _routes_view( + topo, + route_env.scenarios, + suggested, + new_route, + canonical_target, + target_hash, + width_bytes, + resolve=resolve, + type_of=make_node_type_resolver(contacts), + key_of=make_name_key_resolver(contacts, stored_names, heard=named_at), + style=route_graph_style, + self_name=self_name, + node_label=label, + name_key=key, + node_known=name is not None, + hash_bytes=prefix_bytes, + ) + trace = None if view.routes else _Action("trace", "🎯", "", "Trace — auto route …") + screen.replace_routes(view, route_action=device_route_row(current), trace_action=trace) + title = f"Node — {label}" if not you else f"Node — {label} (you)" # Whether the visit ended with a delete of the contact. This tells the caller to build # its list again. @@ -1878,6 +1995,7 @@ async def open_node_detail( routes=routes_view, info_actions=info_actions, trace_action=trace_action, + route_action=route_action, mark=mark, place_row=place_row, ) @@ -1888,6 +2006,10 @@ async def open_node_detail( break if action == "trace": await open_trace(ctx, name or key, initial_spec=screen.selected_spec()) + elif action == DEVICE_ROUTE_ACTION: + assert route_env is not None # offered only then + if await open_device_route(ctx, route_env): + await refresh_device_route() elif action == "map": if markers: # Open the map centred on this node (the same place that the inline diff --git a/tests/test_device_route_screen.py b/tests/test_device_route_screen.py new file mode 100644 index 0000000..cd6b6b5 --- /dev/null +++ b/tests/test_device_route_screen.py @@ -0,0 +1,181 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Tests for the Device route popup of the node page: its row, its pages, and its actions.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager +from types import SimpleNamespace + +from meshterm.core.models import Contact, DiscoveredRoute, utcnow +from meshterm.core.outbound_store import SOURCE_DEVICE, SOURCE_SITE, RouteOwner +from meshterm.services.device_routes import ( + ORIGIN_FLOOD, + ORIGIN_KEPT, + ORIGIN_LEARNED, + ORIGIN_SET, + RouteStatus, +) +from meshterm.services.topology import build_topology +from meshterm.ui.device_route_screen import ( + RouteEnv, + _action_rows, + _apply, + _discover, + _picker_rows, + row_label, +) +from meshterm.ui.tui.select import Choice + +HOME = RouteOwner(SOURCE_SITE, "Home") +HUB = "3d63c6429436" +ALICE_KEY = "f2c24f54551e" + "0" * 52 + + +def _env() -> RouteEnv: + hub = Contact(name="Hilltop", public_key=HUB + "0" * 52, key_prefix=HUB) + alice = Contact(name="Alice", public_key=ALICE_KEY, key_prefix=ALICE_KEY[:12]) + topo = build_topology( + self_id="aaaaaaaaaaaa", + contacts=[hub, alice], + trace_paths=[], + packet_paths=[], + neighbour_links=[], + ) + return RouteEnv( + contact=alice, + label="Alice", + target="f2c24f54551e", + topology=topo, + self_key="aa" * 32, + width_bytes=1, + resolve=lambda hop: None, + scenarios=[], + suggested=SimpleNamespace(hops=(HUB,), source="outbound", rank=1, samples=0), + ) + + +def _values(rows: list) -> list: + return [row.value for row in rows if isinstance(row, Choice)] + + +def test_the_row_says_what_the_radio_holds() -> None: + """Flood, learned, set by you, and kept read differently, and a skipped kept route shows.""" + assert row_label(RouteStatus(None, ORIGIN_FLOOD)) == "Device route · none, it floods…" + assert row_label(RouteStatus((), ORIGIN_LEARNED)) == "Device route · no relays, learned…" + assert row_label(RouteStatus(("3d",), ORIGIN_SET)) == "Device route · 1 hop, set by you…" + kept = RouteStatus(("3d", "27"), ORIGIN_KEPT, kept=("3d", "27"), owner=HOME) + assert row_label(kept) == "Device route · 2 hops, kept at Home…" + skipped = RouteStatus(("27",), ORIGIN_LEARNED, kept=("3d",), owner=HOME, skipped_since=utcnow()) + assert row_label(skipped).endswith("learned · kept route skipped…") + + +def test_the_actions_follow_the_state_of_the_route() -> None: + """Keep needs a site, a kept route offers Stop keeping, and a flood has nothing to forget.""" + assert _values(_action_rows(RouteStatus(None, ORIGIN_FLOOD))) == ["set", "discover"] + learned = RouteStatus(("3d",), ORIGIN_LEARNED, owner=HOME) + assert _values(_action_rows(learned)) == ["set", "keep", "forget", "discover"] + no_site = RouteStatus(("3d",), ORIGIN_LEARNED) + assert _values(_action_rows(no_site)) == ["set", "site", "forget", "discover"] + kept = RouteStatus(("3d",), ORIGIN_KEPT, kept=("3d",), owner=HOME) + assert _values(_action_rows(kept)) == ["set", "unkeep", "forget", "discover"] + fixed = RouteStatus(("3d",), ORIGIN_LEARNED, owner=RouteOwner(SOURCE_DEVICE, "Roof")) + labels = [row.title for row in _action_rows(fixed) if isinstance(row, Choice)] + assert "this radio (Roof)" in str(labels[1]) + + +def test_the_picker_puts_the_suggested_route_first_and_compose_last() -> None: + """The suggested route, no relays, then Compose. A route never repeats.""" + env = _env() + env.scenarios = [SimpleNamespace(hops=(HUB,), source="observed", rank=0, samples=4)] + values = _values(_picker_rows(env, RouteStatus(None, ORIGIN_FLOOD))) + assert values == [("hops", (HUB,)), ("hops", ()), "compose"] + + +class _Routes: + """The route service, as the popup calls it.""" + + def __init__(self, found: DiscoveredRoute | None = None) -> None: + self.calls: list[tuple[str, tuple]] = [] + self.found = found + + async def set(self, contact: Contact, hops: tuple) -> tuple: + self.calls.append(("set", tuple(hops))) + return tuple(hops) + + async def keep(self, contact: Contact, hops: tuple) -> RouteOwner: + self.calls.append(("keep", tuple(hops))) + return HOME + + async def discover(self, contact: Contact) -> DiscoveredRoute | None: + self.calls.append(("discover", ())) + return self.found + + +def _ctx(routes: _Routes, answer: object = None): # noqa: ANN202 + prompts: list = [] + + async def dialog(prompt, buttons, **kwargs): # noqa: ANN001, ANN003, ANN202 + prompts.append(prompt) + return answer + + @asynccontextmanager + async def busy_dialog(message: str = "", *, title: str = ""): # noqa: ANN202 + yield None + + ui = SimpleNamespace(dialog=dialog, busy_dialog=busy_dialog, session=None) + return SimpleNamespace(routes=routes, ui=ui), prompts + + +async def test_a_picked_route_replaces_a_kept_route() -> None: + """With a kept route, Set keeps the new route. Without one, it only sets it.""" + routes = _Routes() + ctx, _ = _ctx(routes) + kept = RouteStatus(("3d",), ORIGIN_KEPT, kept=("3d",), owner=HOME) + assert await _apply(ctx, _env(), kept, (HUB, "27d4")) + assert await _apply(ctx, _env(), RouteStatus(None, ORIGIN_FLOOD), ()) + assert routes.calls == [("keep", (HUB, "27d4")), ("set", ())] + + +async def test_discover_shows_both_routes_and_uses_the_route_out() -> None: + """One discovery, a dialog with the route each way, and Use sets the route out.""" + routes = _Routes(DiscoveredRoute(out_hops=("3d",), in_hops=("27", "3d"))) + ctx, prompts = _ctx(routes, answer="use") + assert await _discover(ctx, _env(), RouteStatus(None, ORIGIN_FLOOD)) + assert routes.calls == [("discover", ()), ("set", (HUB,))] + text = prompts[0].plain + assert "Out, to Alice (1 hop)" in text + assert "Back, to you (2 hops)" in text + + +async def test_no_answer_to_a_discovery_changes_nothing() -> None: + """With no answer, the popup says so and sets nothing.""" + routes = _Routes(None) + ctx, prompts = _ctx(routes) + assert not await _discover(ctx, _env(), RouteStatus(("3d",), ORIGIN_LEARNED)) + assert routes.calls == [("discover", ())] + assert "No answer from Alice" in prompts[0] + + +def test_the_route_row_follows_the_routes_on_the_node_page() -> None: + """The row comes after the routes, and a refresh keeps the highlight on it.""" + from rich.text import Text + + from meshterm.ui.node_detail_screen import NodeDetailScreen, _Action, _RoutesView, _Tab + + row = _Action("device_route", "🧭", "", "Device route · none, it floods…") + trace = _Action("trace", "🎯", "", "Trace — auto route …") + view = _RoutesView(routes=[], note="no route observed yet") + screen = NodeDetailScreen( + title="Node — Alice", + header=Text("Alice"), + info_rows=[], + tabs=[_Tab(name="Routes", kind="routes")], + routes=view, + trace_action=trace, + route_action=row, + ) + focus = [payload for _kind, payload in screen._focusables()] + assert focus == [trace, row] + 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 diff --git a/tests/test_gallery.py b/tests/test_gallery.py index db00ae7..c3a1611 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -1366,6 +1366,64 @@ def _outbound_composer(cols: int, rows: int) -> Screen: ) +def _device_route_env(): # noqa: ANN202 - a type of the module under test + """The Device route popup for Alice: a learned route, and a kept route that is skipped.""" + from datetime import timedelta + + from meshterm.core.outbound_store import SOURCE_SITE, RouteOwner + from meshterm.services.device_routes import ORIGIN_LEARNED, RouteStatus + from meshterm.ui.device_route_screen import RouteEnv + + env = _outbound_env() + topo = env.topology + target = "f2c24f54551e" + outbound = (("3d63c6429436",),) + route_env = RouteEnv( + contact=env.contacts[1], + label="Alice", + target=target, + topology=topo, + self_key=env.identity.key, + width_bytes=1, + resolve=lambda hop: None, + scenarios=topo.scenarios(target, device_route=("3d63c6429436",), outbound=outbound), + suggested=topo.suggested(target, outbound=outbound), + outbound=outbound, + ) + status = RouteStatus( + hops=("3d",), + origin=ORIGIN_LEARNED, + changed_at=utcnow() - timedelta(minutes=5), + kept=("3d63c6429436", "9a9a"), + owner=RouteOwner(SOURCE_SITE, "A-site-named-24-chars-xx"), + skipped_since=utcnow() - timedelta(days=2), + ) + return route_env, status + + +def _device_route_page(cols: int, rows: int) -> Screen: + """The first page of the Device route popup: the route now, the kept route, the actions.""" + from meshterm.ui.device_route_screen import _action_rows, _status_rows + from meshterm.ui.tui.select import Separator + + env, status = _device_route_env() + items = [*_status_rows(env, status), Separator(" "), *_action_rows(status)] + return SelectScreen("Device route — Alice", items, filterable=False) + + +def _device_route_picker(cols: int, rows: int) -> Screen: + """The picker page of the Device route popup: the suggested route first, then Compose.""" + from meshterm.ui.device_route_screen import _picker_rows + + env, status = _device_route_env() + return SelectScreen( + "Set the route — Alice", + _picker_rows(env, status), + prompt="The radio sends to the contact on this route:", + filterable=False, + ) + + class _CourierStubDevice: async def get_contacts(self) -> list: return [] @@ -1952,6 +2010,8 @@ _ENTRIES: list[_Entry] = [ _Entry("message_paths_sent_scope", _message_paths_sent_scope), _Entry("remote_cli", _remote_cli), _Entry("path_composer", _path_composer), + _Entry("device_route_page", _device_route_page), + _Entry("device_route_picker", _device_route_picker), _Entry("outbound_composer", _outbound_composer), _Entry("outbound_page", _outbound_page), _Entry("outbound_site", _outbound_site),