Outbound paths start the suggested routes, for each site and fixed device

The user names the ways out of their node, one or more hops long, in order.
Each site of this computer (Home, Foulab) has its own list, one site is
active, and a fixed device keeps its own list.

- Explore > Outbound paths: the sites with the active mark, the fixed
  devices, and a staged editor for each list. Each path shows how well its
  first hop hears us (out) and how well we hear it (in). Measure sends one
  trace out along a path and back, after the cooldown.
- The path composer has an outbound mode, and puts the active paths first
  while the insertion slot is at our node (trace target, trace path, the
  TX sweep route).
- MeshTopology.outbound_scenarios: one route through each path. It scores
  from the link after the path, lets the user's order win a near tie, and
  skips a path whose first hop was silent for outbound_silent_hours. These
  routes lead Explore paths, the node page's Routes tab, and the trace auto
  route, ahead of a device route that starts on another hop.
- A first link out of our node is scored from what the far end measured,
  when a trace gave such readings.
- The site suggestion: when the radio hears the first hop of another site
  three times, the main menu asks to use that site and says what it heard.
  "Never suggest" sets the new suggest_site preference off.
- CLI: meshterm outbound [show|sites|use|set|remove|fix|unfix], plain and
  --json.

Refs: #35

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5.5 committed 2026-11-07 14:21:46 -05:00
1 parent c50656c586
commit ec64076d44
19 files changed
+2468 -55

No files matched your search

+43
View File
@@ -1622,6 +1622,49 @@ $ meshterm trace-path --path "a1,d4" --json | jq -r '.edges | min_by(.snr_db) |
a1 -> d4 2.0 dB
```
#### `meshterm outbound`
Show and change the outbound paths: the ways out of your node that the trace features
start their routes on. A path is a spec, the same as `--path` (`3d63,f2c2`), from your
node outward. Each site of this computer has its own paths, and one site is active. A
fixed device keeps its own paths, and the active site does not apply to it.
| Command | What it does |
| --- | --- |
| `outbound` or `outbound show` | The paths that apply to the connected device now, and where they come from. |
| `outbound sites` | Each site, whether it is active, and its paths. |
| `outbound use SITE` | Make a site active. `outbound use --none` makes no site active. |
| `outbound set SITE PATH…` | Make a site, or replace its paths, in your order. When no site is active, the new site becomes active. |
| `outbound remove SITE --yes` | Delete a site and its paths. |
| `outbound fix [PATH…]` | Give the connected device its own paths. With no path, it starts with the paths of the active site. |
| `outbound unfix --yes` | The connected device follows the active site again. |
```console
$ meshterm outbound set Home 3d63c6429436 27d4,f2c2
✓ site Home: 2 outbound path(s)
$ meshterm outbound sites
SITE ACTIVE PATHS
Home yes 3d63c6429436 27d4,f2c2
Foulab no a100
$ meshterm outbound
SOURCE site
NAME Home
RANK PATH HOPS
1 3d63c6429436 3d63c6429436
2 27d4,f2c2 27d4 → f2c2
```
`sites`, `use`, `set`, and `remove` do not open the device. `show`, `fix`, and `unfix`
open it, because the fixed devices are known by their public key. `show` returns `5` when
no list applies. `sites` returns `5` when there is no site. A path with a node two times,
or a hop that is not whole bytes of hex, is a usage error (`2`).
**`--json`** gives `show` as one object, `{"source": …, "name": …, "paths": [{"rank": …,
"path": …, "hops": […]}]}`. `source` is `site`, `device`, or `null`. `sites` is an array of
`{"site", "active", "paths"}`. Each change prints the object that it wrote, for example
`{"active": "Foulab"}`.
#### `meshterm tx-optimize`
Sweep the transmit power of a remote node against a target. Then select the lowest level
+1
View File
@@ -40,6 +40,7 @@ This page lists each interactive screen with its scripted equivalent, where one
| **🌐 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 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 …` |
| **🏆 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
+18
View File
@@ -50,6 +50,7 @@ if TYPE_CHECKING:
from .services.monitor_service import MonitorService
from .services.places import PlaceService
from .services.rooms import RoomService
from .services.site_suggest import SiteSuggester
from .services.watchtower import WatchtowerService
from .ui.surface import Ui
@@ -201,6 +202,7 @@ class AppContext:
_courier: CourierService | None = field(default=None, init=False, repr=False)
_battery: BatteryService | None = field(default=None, init=False, repr=False)
_places: PlaceService | None = field(default=None, init=False, repr=False)
_site_suggest: SiteSuggester | None = field(default=None, init=False, repr=False)
_devstate: DeviceState | None = field(default=None, init=False, repr=False)
_basemap_source: BasemapSource | None = field(default=None, init=False, repr=False)
_ui: Ui | None = field(default=None, init=False, repr=False)
@@ -511,6 +513,20 @@ class AppContext:
self._places = PlaceService(self)
return self._places
@property
def site_suggest(self) -> SiteSuggester:
"""Return the site suggestion of the session, and create it at first use.
The property creates it idle. The interactive session starts it with the other
always-on services. It only listens, and the menu asks the user. Scripted CLI runs
never start it.
"""
if self._site_suggest is None:
from .services.site_suggest import SiteSuggester
self._site_suggest = SiteSuggester(self)
return self._site_suggest
@property
def battery(self) -> BatteryService:
"""Return the battery poller of the session, and create it at first use.
@@ -1079,6 +1095,8 @@ class AppContext:
await self._battery.aclose()
if self._places is not None:
await self._places.aclose()
if self._site_suggest is not None:
await self._site_suggest.aclose()
if self._watchtower is not None:
await self._watchtower.aclose()
if self._clock_sync is not None:
+26
View File
@@ -261,6 +261,17 @@ PREFERENCES: tuple[PrefSpec, ...] = (
# connection. Refer to :mod:`meshterm.services.clock_sync`.
default=False,
),
PrefSpec(
key="suggest_site",
label="Suggest a site",
help="Offer the site whose outbound paths your radio hears",
group="Device",
value_type="bool",
# On: the offer only asks, and it says what it heard. It never changes the active
# site by itself. Its dialog has a choice that sets this preference off. Refer to
# meshterm.services.site_suggest.
default=True,
),
# --- Sending -----------------------------------------------------------------
PrefSpec(
key="trace_cooldown_s",
@@ -331,6 +342,21 @@ PREFERENCES: tuple[PrefSpec, ...] = (
maximum=1440,
unit="min",
),
PrefSpec(
key="outbound_silent_hours",
label="Silent path",
help="Skip an outbound path whose first hop is this quiet",
group="Sending",
value_type="int",
# A repeater that relayed nothing that our node heard for a day is probably off, or
# out of reach from where the radio is now. A route through it fails, so the route
# suggestions skip it. A first hop with no evidence at all is not silent: it is
# unknown, and the user named it. Refer to meshterm.services.topology.
default=24,
minimum=1,
maximum=720,
unit="h",
),
# --- TX optimize -------------------------------------------------------------
PrefSpec(
key="tx_opt_min",
+140
View File
@@ -0,0 +1,140 @@
# SPDX-License-Identifier: Apache-2.0
"""Outbound paths in use: the list that applies to the connected device, and its evidence.
The store (:mod:`meshterm.core.outbound_store`) keeps the sites, the active site, and the
fixed devices. This module joins the store to the live session. It finds the public key
of the connected companion, so that the store can give the list that applies to it. It
also builds the evidence graph and reads the two directions of the first link of a path
(refer to :meth:`~meshterm.services.topology.MeshTopology.readings`). The pages show this
evidence beside each path, because a radio link is not symmetric: the user must see how
well a repeater hears our node, and not only how well our node hears the repeater.
"""
from __future__ import annotations
import statistics
from dataclasses import dataclass
from datetime import datetime
from typing import TYPE_CHECKING
from ..core.outbound_store import OutboundChoice, OutboundPath
from .topology import MeshTopology, build_topology
if TYPE_CHECKING: # pragma: no cover - typing only
from ..context import AppContext
from ..core.models import Contact
@dataclass(frozen=True, slots=True)
class DeviceIdentity:
"""The connected companion as the Outbound paths features know it.
Attributes:
key: The public key of the companion in lowercase hex, or ``""`` when it is not
known (no device is connected).
name: The name of the companion, or ``""``.
"""
key: str = ""
name: str = ""
@dataclass(frozen=True, slots=True)
class FirstLink:
"""The evidence for the first link of an outbound path, one direction at a time.
Attributes:
out_snr: The median SNR (dB) at which the first hop received our node, or ``None``
when no reading exists. Only traces give these readings.
out_count: How many readings ``out_snr`` comes from.
in_snr: The median SNR (dB) at which our node received the first hop, or
``None``.
in_count: How many readings ``in_snr`` comes from.
last_heard: The most recent time that the link carried a packet, from any source,
or ``None`` when the graph has no such link.
"""
out_snr: float | None = None
out_count: int = 0
in_snr: float | None = None
in_count: int = 0
last_heard: datetime | None = None
async def device_identity(ctx: AppContext) -> DeviceIdentity:
"""The key and the name of the connected companion, from the session cache.
A page about outbound paths works also with no device. The sites belong to the
computer, and the user can prepare them anywhere. Thus a failed read gives an empty
identity, and not an error.
"""
try:
info = await ctx.devstate.self_info()
except Exception: # noqa: BLE001 - an optional read. With no device, only sites apply.
return DeviceIdentity()
key = str(info.get("public_key") or "").lower().removeprefix("0x")
return DeviceIdentity(key=key, name=str(info.get("name") or ""))
async def session_contacts(ctx: AppContext) -> list[Contact]:
"""The contacts of the connected companion, or an empty list when there is no device."""
try:
return list(await ctx.devstate.contacts())
except Exception: # noqa: BLE001 - an optional read. The pages still work without it.
return []
async def current_choice(ctx: AppContext) -> OutboundChoice:
"""The outbound paths that apply to the connected companion now.
Refer to :meth:`~meshterm.core.outbound_store.OutboundStore.lookup` for the order.
"""
identity = await device_identity(ctx)
return ctx.outbound_store.lookup(identity.key or None)
def session_topology(ctx: AppContext, self_key: str, contacts: list[Contact]) -> MeshTopology:
"""Build the evidence graph from the stored data, around our node.
Args:
ctx: The shared application context (for the repository).
self_key: The public key of our node, or ``""`` when it is not known.
contacts: The contacts of the companion, for the names and the canonical ids.
Returns:
The populated graph.
"""
return build_topology(
self_id=self_key or "local",
contacts=contacts,
trace_paths=ctx.repo.trace_paths(),
packet_paths=ctx.repo.packet_paths(),
neighbour_links=ctx.repo.neighbour_links(),
)
def first_link(topo: MeshTopology, path: OutboundPath) -> FirstLink:
"""The evidence for the link from our node to the first hop of ``path``.
Args:
topo: The evidence graph around our node.
path: The outbound path.
Returns:
The two directions of the first link. Each field is empty when the graph has no
evidence for it.
"""
if not path:
return FirstLink()
hop = topo.canonical(path[0]) or path[0]
us = topo.self_id
out = topo.readings(us, hop)
heard = topo.readings(hop, us)
link = topo.link(us, hop)
return FirstLink(
out_snr=statistics.median(out) if out else None,
out_count=len(out),
in_snr=statistics.median(heard) if heard else None,
in_count=len(heard),
last_heard=link.last_seen if link is not None else None,
)
+201
View File
@@ -0,0 +1,201 @@
# SPDX-License-Identifier: Apache-2.0
"""The site suggestion: notice that the radio hears the way out of another site, and offer it.
The outbound paths of a site apply while the site is active (refer to
:mod:`meshterm.core.outbound_store`). The user takes the computer from site to site, and can
forget to change the active site. This service listens to what our node hears after the
session starts. A packet that arrives through a repeater names that repeater: the last hop
of its relay path, or the node itself for a packet with no relay. When the first hop of an
outbound path of another site is heard :data:`HEARD_TO_SUGGEST` times, and no first hop of
the active site was heard, the service has a suggestion. The menu then asks the user, and
says what MeshTerm heard (refer to :func:`meshterm.ui.outbound_screen.offer_site`). The
service never changes the active site by itself.
It asks at most one time in a session. When the radio hears a first hop of the active site
first, the question is settled: the user is where the active site says. It does not ask
for a fixed device, which keeps its own paths, or when the ``suggest_site`` preference is
off.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from ..core.events import EventKind, MeshEvent
from ..core.models import Observation
from ..core.outbound_store import Site
from ..persistence.logging import get_logger
if TYPE_CHECKING: # pragma: no cover - typing only
from collections.abc import Callable
from ..context import AppContext
#: How many packets from the first hop of another site make a suggestion. One packet can be
#: a hash that two nodes share. Three are a node that is really near.
HEARD_TO_SUGGEST = 3
@dataclass(frozen=True, slots=True)
class SiteSuggestion:
"""A site that the radio seems to be at.
Attributes:
site: The name of the site.
hop: The first hop of its outbound path that the radio heard, as the store keeps it.
heard: How many packets came through that hop.
"""
site: str
hop: str
heard: int
def heard_hop(obs: Observation) -> str | None:
"""The node that our node heard transmit this packet, as a hex hash, or ``None``.
For a packet with relays, it is the last relay. For a packet with no relay, it is the
node that sent it. Other classes of observation do not say who transmitted the packet
that our node received, so they give ``None``.
"""
if obs.kind != "packet" or obs.path is None:
return None
hops = [hop for hop in obs.path.split(",") if hop]
if hops:
return hops[-1].lower()
return obs.node.lower() if obs.node else None
def _matches(heard: str, hop: str) -> bool:
"""Whether a heard hash can be the stored hop: one is a prefix of the other."""
return bool(heard) and (hop.startswith(heard) or heard.startswith(hop))
class SiteWatch:
"""The decision of the service, with no I/O: count what is heard, and find a suggestion.
Args:
sites: The sites of this computer.
active: The name of the active site, or ``None``.
threshold: How many packets from one first hop make a suggestion.
"""
def __init__(
self, sites: list[Site], active: str | None, *, threshold: int = HEARD_TO_SUGGEST
) -> None:
"""Index the first hops of each site."""
self._active = active.casefold() if active else None
self._threshold = threshold
self._own = [
path[0] for site in sites if site.name.casefold() == self._active for path in site.paths
]
self._others = [
(site.name, path[0])
for site in sites
if site.name.casefold() != self._active
for path in site.paths
]
self._counts: dict[tuple[str, str], int] = {}
self.settled = not self._others
def note(self, heard: str) -> SiteSuggestion | None:
"""Count one heard hash. Return a suggestion when one is due, else ``None``.
After a suggestion, or after a first hop of the active site is heard, the watch is
settled, and it returns nothing more.
"""
if self.settled or not heard:
return None
if any(_matches(heard, hop) for hop in self._own):
self.settled = True
return None
for name, hop in self._others:
if _matches(heard, hop):
count = self._counts.get((name, hop), 0) + 1
self._counts[(name, hop)] = count
if count >= self._threshold:
self.settled = True
return SiteSuggestion(name, hop, count)
return None
return None
class SiteSuggester:
"""The session service: it listens to the hub and keeps one pending suggestion.
The interactive session starts it with the other always-on services. The menu takes
the pending suggestion (:meth:`take`) and asks the user. :attr:`on_ready` lets the menu
ask at once when it is on the screen.
"""
def __init__(self, ctx: AppContext) -> None:
"""Make the service idle."""
self._ctx = ctx
self._watch: SiteWatch | None = None
self._unsubscribe: Callable[[], None] | None = None
self._pending: SiteSuggestion | None = None
#: A callback that the menu sets. The service calls it when a suggestion is ready.
self.on_ready: Callable[[], None] | None = None
async def start(self) -> None:
"""Start to listen, unless the preference is off or there is nothing to suggest."""
if self._unsubscribe is not None or not self._ctx.preferences.suggest_site:
return
store = self._ctx.outbound_store
active = store.active_site()
self._watch = SiteWatch(store.sites(), active.name if active else None)
if self._watch.settled:
return
self._unsubscribe = self._ctx.events.subscribe(self._on_event, EventKind.OBSERVATION)
def _on_event(self, event: MeshEvent) -> None:
"""Count the hop that transmitted one packet. This runs on each packet, so it is cheap."""
obs = event.observation
if obs is None or self._watch is None:
return None
hop = heard_hop(obs)
if hop is None:
return None
suggestion = self._watch.note(hop)
if self._watch.settled:
self._stop()
if suggestion is not None:
return self._decide(suggestion) # the hub runs the coroutine as a task
return None
async def _decide(self, suggestion: SiteSuggestion) -> None:
"""Keep the suggestion, unless the connected device is fixed or the user said never."""
if not self._ctx.preferences.suggest_site:
return
try:
info = await self._ctx.devstate.self_info()
except Exception: # noqa: BLE001 - with no device identity, only the sites apply
info = {}
key = str(info.get("public_key") or "")
if key and self._ctx.outbound_store.fixed_device(key) is not None:
return # a fixed device keeps its own paths: the active site does not apply
get_logger().info(
"heard %s %d times: it is a first hop of site %s",
suggestion.hop,
suggestion.heard,
suggestion.site,
)
self._pending = suggestion
if self.on_ready is not None:
self.on_ready()
def take(self) -> SiteSuggestion | None:
"""Return the pending suggestion one time, and forget it."""
suggestion, self._pending = self._pending, None
return suggestion
def _stop(self) -> None:
"""Stop listening."""
if self._unsubscribe is not None:
self._unsubscribe()
self._unsubscribe = None
async def aclose(self) -> None:
"""Stop listening at the end of the session."""
self._stop()
+248 -36
View File
@@ -39,6 +39,7 @@ import bisect
import heapq
import math
import statistics
from collections.abc import Sequence
from dataclasses import dataclass, field
from datetime import datetime
from itertools import chain, pairwise
@@ -73,6 +74,17 @@ _HOP_PENALTY = 0.35
_MAX_SCENARIOS = 5
_MAX_SCENARIO_HOPS = 5
#: How close two outbound routes must score to be a tie, as a fraction of the higher score.
#: In a tie, the outbound path that the user put first wins (refer to
#: :meth:`MeshTopology.outbound_scenarios`). A strength is a noisy estimate, so a small
#: difference must not override the knowledge of the user.
_NEAR_TIE = 0.15
#: The strength that a route gets for a part that the user vouches for: a target that is a
#: hop of an outbound path. No link of the route is left to score, and the user trusts
#: each link of the path. Thus the route ranks above each route that the evidence scores.
_TRUSTED_STRENGTH = 1e6
#: The test that an ambiguous short hash must pass before it merges into one of the nodes
#: that it can name (refer to :meth:`MeshTopology._corroborated_owner`). The first value is
#: how many discriminating neighbours (neighbours that link to exactly one candidate) must
@@ -225,7 +237,7 @@ class Link:
"""
return self.heard_at.get(node, [])
def strength(self, now: datetime | None = None) -> float:
def strength(self, now: datetime | None = None, *, snrs: list[float] | None = None) -> float:
"""Score the observed reliability of the link, for the ranking (higher is stronger).
Three factors multiply:
@@ -241,6 +253,10 @@ class Link:
Args:
now: The reference time for recency (the default is the current time).
snrs: The readings for the quality factor, in place of the pooled readings of
the two directions. The graph gives the readings of one direction here for
the first link of a route out of our node (refer to
:meth:`MeshTopology.outward_strength`).
Returns:
The strength score of the link, ``> 0``.
@@ -251,7 +267,7 @@ class Link:
if self.last_seen is not None and getattr(self.last_seen, "tzinfo", None):
age_days = max(0.0, (now - self.last_seen).total_seconds() / 86400.0)
recency = 0.5 ** (age_days / _EVIDENCE_HALF_LIFE_DAYS)
snr = self.median_snr
snr = self.median_snr if snrs is None else (statistics.median(snrs) if snrs else None)
quality = 1.0
if snr is not None:
span = _SNR_CEIL_DB - _SNR_FLOOR_DB
@@ -291,8 +307,8 @@ class PathScenario:
label: A short description for the user, of where the route came from.
hops: The canonical ids of the intermediate repeaters, in order from our node
outward, without the two endpoints (empty means to trace the target directly).
source: The evidence class that proposed the route (``device``, ``direct``,
``observed``).
source: The evidence class that proposed the route (``device``, ``outbound``,
``direct``, ``observed``).
score: The ranking score (higher first): the strength of the weakest link of the
path, with a penalty for the hop count. Direct and device scenarios with no
observed evidence score 0.
@@ -300,6 +316,8 @@ class PathScenario:
is the bottleneck that the trace will probably measure.
samples: The total of the readings on the links of the route (an approximate
measure of confidence).
rank: For an ``outbound`` scenario, the place of its outbound path in the list of
the user, from 1. It is 0 for each other source.
"""
label: str
@@ -308,6 +326,7 @@ class PathScenario:
score: float
weakest_snr: float | None = None
samples: int = 0
rank: int = 0
def spec(self, target_hash: str, width_bytes: int) -> str:
"""Render the scenario as a forced-path spec, with the return leg.
@@ -363,7 +382,7 @@ class MeshTopology:
# target two times when a screen opens (suggested() and scenarios() both run the
# search). The search is the most costly part of an open that uses the topology.
self._graph_version = 0
self._routes_memo: dict[tuple[str, int, int], list[tuple[str, ...]]] = {}
self._routes_memo: dict[tuple, list[tuple[str, ...]]] = {}
# --- identity ----------------------------------------------------------------
@@ -763,6 +782,31 @@ class MeshTopology:
"""The evidence for the undirected link between ``a`` and ``b``, if there is any."""
return self._links.get((a, b) if a < b else (b, a))
def outward_strength(self, a: str, b: str, link: Link) -> float:
"""The strength of ``link`` for a packet that goes from ``a`` to ``b``.
A link that leaves our node is scored from what the far end measured from our node
(the first hop of a trace reports it), when such readings exist. The pooled readings
are mostly what our node *heard*: each received packet adds one, and only a trace
adds a reading of the other direction. A repeater that our node hears well can
hear our node badly, and a route out of our node depends on the second fact. Each
other link keeps its pooled strength: the graph knows both directions of those
links only from the same few traces.
Args:
a: The canonical id of the node that transmits.
b: The canonical id of the node that receives.
link: The link between them.
Returns:
The strength score of the link, in that direction.
"""
if a == self.self_id:
outward = link.heard_by(b)
if outward:
return link.strength(self._now, snrs=outward)
return link.strength(self._now)
def readings(self, sender: str, receiver: str) -> list[float]:
"""The SNR readings of one direction of a link: what ``receiver`` measured from ``sender``.
@@ -807,21 +851,32 @@ class MeshTopology:
other = b if a == tail else a if b == tail else None
if other is None or other in exclude:
continue
out.append(HopSuggestion(node=other, link=link, strength=link.strength(self._now)))
strength = self.outward_strength(tail, other, link)
out.append(HopSuggestion(node=other, link=link, strength=strength))
out.sort(key=lambda s: (-s.strength, s.node))
return out
def scenarios(
self, target: str, *, device_route: tuple[str, ...] | None = None
self,
target: str,
*,
device_route: tuple[str, ...] | None = None,
outbound: Sequence[tuple[str, ...]] = (),
silent_before: datetime | None = None,
) -> list[PathScenario]:
"""Rank the candidate outbound routes to ``target``.
Three families, without duplicates, in this order of priority:
Four families, without duplicates, in this order of priority:
1. **device**: the route that the firmware itself learned from received floods
(the route that an auto-routed trace walks), when the caller supplies one.
2. **direct**: no repeaters at all. MeshTerm always offers it as the baseline.
3. **observed**: the strongest simple paths through the evidence graph (the score
2. **outbound**: one route through each outbound path of the user (refer to
:meth:`outbound_scenarios`). When the user has outbound paths and the device
route does not start with one of them, this family comes first. The firmware
learns its route from floods that our node *received*, and a radio link is not
symmetric. The user knows the way out, and the received floods do not.
3. **direct**: no repeaters at all. MeshTerm always offers it as the baseline.
4. **observed**: the strongest simple paths through the evidence graph (the score
is the weakest link, with a penalty for each hop). This family gives the paths
that the device never learned, but that the data supports.
@@ -834,12 +889,18 @@ class MeshTopology:
target: The canonical id of the target.
device_route: The learned route of the firmware (canonical intermediate
hops), if the contact has one.
outbound: The outbound paths of the user, in order, as canonical ids.
silent_before: Skip an outbound path whose first hop was last heard before
this time (refer to :meth:`outbound_scenarios`).
Returns:
Scenarios ranked with the best evidence first. The device route, when there
is one, is always first, whatever its score, because it is what "auto" does.
is one, is first, whatever its score, because it is what "auto" does. The one
exception is a device route that does not start with an outbound path of the
user: then the outbound routes are first.
"""
seen: set[tuple[str, ...]] = set()
first = self.outbound_scenarios(target, outbound, silent_before=silent_before)
seen: set[tuple[str, ...]] = {s.hops for s in first}
out: list[PathScenario] = []
def add(label: str, hops: tuple[str, ...], source: str) -> None:
@@ -858,22 +919,133 @@ class MeshTopology:
)
)
device: list[PathScenario] = []
if device_route is not None:
add("device route", device_route, "device")
if device_route in seen: # the device learned one of the outbound routes
device = [s for s in first if s.hops == device_route]
first = [s for s in first if s.hops != device_route]
else:
add("device route", device_route, "device")
device = [s for s in out if s.source == "device"]
out = [s for s in out if s.source != "device"]
add("direct", (), "direct")
for hops in self._best_routes(target, k=_MAX_SCENARIOS):
add("observed path", hops, "observed")
# Rank the observed evidence, but keep the device route pinned at the top. It is
# the reference point for the comparison of each alternative.
head = [s for s in out if s.source == "device"]
rest = sorted(
(s for s in out if s.source != "device"),
key=lambda s: (-s.score, len(s.hops)),
# the reference point for the comparison of each alternative. The outbound routes
# go in front of a device route that starts on a path the user did not name.
rest = sorted(out, key=lambda s: (-s.score, len(s.hops)))
starts_outbound = bool(device) and any(
device[0].hops[: len(path)] == path for path in outbound
)
return (head + rest)[:_MAX_SCENARIOS]
head = device + first if (starts_outbound or not first) else first + device
return (head + rest)[: max(_MAX_SCENARIOS, len(head))]
def suggested(self, target: str) -> PathScenario | None:
def outbound_scenarios(
self,
target: str,
outbound: Sequence[tuple[str, ...]],
*,
silent_before: datetime | None = None,
) -> list[PathScenario]:
"""One route to ``target`` through each outbound path of the user, the best first.
The route through an outbound path is the path, then the cheapest continuation
from its last hop to the target (a node of the path is never used again). When
the target is a hop of the path, the route is the part of the path before it.
The score is the weakest link of the continuation only, with the penalty for each
hop of the full route. The user vouches for the links of the outbound path, and
the evidence for these links is mostly what our node *heard*, which says little
about how well a repeater hears our node. A route that ends inside its path has no
link to score, and gets :data:`_TRUSTED_STRENGTH`.
The best score is first. When two scores are within :data:`_NEAR_TIE`, the path
that the user put first wins. A path whose first hop was last heard before
``silent_before`` is skipped: that repeater is probably off, or out of reach from
here. A first hop with no evidence at all is not silent, because nothing says so.
Args:
target: The canonical id of the target.
outbound: The outbound paths, in the order of the user, as canonical ids.
silent_before: The time before which a first hop counts as silent, or
``None`` to keep each path.
Returns:
The scenarios (source ``outbound``, with the rank of their path), the best
first. A path that cannot reach the target is not in the list.
"""
found: list[PathScenario] = []
for rank, path in enumerate(outbound, start=1):
if not path or self.self_id in path:
continue
first_link = self.link(self.self_id, path[0])
if (
silent_before is not None
and first_link is not None
and first_link.last_seen is not None
and getattr(first_link.last_seen, "tzinfo", None) is not None
and first_link.last_seen < silent_before
):
continue
if target in path:
hops = path[: path.index(target)]
score = _TRUSTED_STRENGTH / (1.0 + _HOP_PENALTY * len(hops))
found.append(
PathScenario(f"outbound path {rank}", hops, "outbound", score, rank=rank)
)
continue
# The search gives its candidates by cost, and the score is the weakest link.
# The two orders differ (one weak direct link costs less than two strong links),
# so the best continuation is the best score among a few candidates.
best: PathScenario | None = None
for tail in self._best_routes(
target,
k=_MAX_SCENARIOS,
source=path[-1],
banned=frozenset({self.self_id, *path[:-1]}),
max_hops=_MAX_SCENARIO_HOPS - len(path),
):
hops = (*path, *tail)
strength, weakest, samples = self._weakest([path[-1], *tail, target])
score = strength / (1.0 + _HOP_PENALTY * len(hops))
if best is None or score > best.score:
best = PathScenario(
label=f"outbound path {rank}",
hops=hops,
source="outbound",
score=score,
weakest_snr=weakest,
samples=samples,
rank=rank,
)
if best is not None:
found.append(best)
found.sort(key=lambda s: -s.score)
# A near tie goes to the path that the user put first. The list is short (one
# entry for each outbound path), so a bubble pass is enough.
moved = True
while moved:
moved = False
for i in range(len(found) - 1):
ahead, behind = found[i], found[i + 1]
if behind.rank < ahead.rank and behind.score * (1.0 + _NEAR_TIE) >= ahead.score:
found[i], found[i + 1] = behind, ahead
moved = True
unique: list[PathScenario] = []
for scenario in found:
if all(scenario.hops != kept.hops for kept in unique):
unique.append(scenario)
return unique
def suggested(
self,
target: str,
*,
outbound: Sequence[tuple[str, ...]] = (),
silent_before: datetime | None = None,
) -> PathScenario | None:
"""The one best outbound route to ``target`` that has evidence, if one exists.
This is the answer from the data to "what is the best way to reach this node?".
@@ -888,14 +1060,24 @@ class MeshTopology:
For a node that the evidence can only reach directly (or not at all), the method
returns ``None``. Thus the caller keeps the default that it uses otherwise.
When the user has outbound paths, the best route through one of them comes first
(refer to :meth:`outbound_scenarios`). The user knows the way out of our node,
and the evidence about it is mostly what our node heard.
Args:
target: The canonical id of the target.
outbound: The outbound paths of the user, in order, as canonical ids.
silent_before: Skip an outbound path whose first hop was last heard before
this time.
Returns:
The best observed :class:`PathScenario` (always with at least one intermediate
hop, and a positive score from evidence), or ``None`` when the observations
support nothing better than a direct route.
The best outbound :class:`PathScenario`, else the best observed one (always
with at least one intermediate hop, and a positive score from evidence), or
``None`` when nothing is better than a direct route.
"""
through = self.outbound_scenarios(target, outbound, silent_before=silent_before)
if through:
return through[0]
for scenario in self.scenarios(target):
if scenario.source == "observed" and scenario.hops and scenario.score > 0:
return scenario
@@ -918,7 +1100,19 @@ class MeshTopology:
Returns:
``(score, weakest_median_snr, total_samples)``.
"""
chain = [self.self_id, *hops, target]
strength, weakest_snr, samples = self._weakest([self.self_id, *hops, target])
return strength / (1.0 + _HOP_PENALTY * len(hops)), weakest_snr, samples
def _weakest(self, chain: list[str]) -> tuple[float, float | None, int]:
"""The weakest link of a chain of nodes: its strength, the lowest SNR, the readings.
Args:
chain: The canonical ids of the nodes, in order.
Returns:
``(weakest_strength, weakest_median_snr, total_samples)``. The strength is 0
when a link of the chain has no evidence.
"""
weakest_strength: float | None = None
weakest_snr: float | None = None
samples = 0
@@ -926,17 +1120,24 @@ class MeshTopology:
link = self.link(a, b)
if link is None:
return 0.0, None, samples
strength = link.strength(self._now)
strength = self.outward_strength(a, b, link)
samples += link.samples
if weakest_strength is None or strength < weakest_strength:
weakest_strength = strength
snr = link.median_snr
if snr is not None and (weakest_snr is None or snr < weakest_snr):
weakest_snr = snr
score = (weakest_strength or 0.0) / (1.0 + _HOP_PENALTY * len(hops))
return score, weakest_snr, samples
return weakest_strength or 0.0, weakest_snr, samples
def _best_routes(self, target: str, *, k: int) -> list[tuple[str, ...]]:
def _best_routes(
self,
target: str,
*,
k: int,
source: str | None = None,
banned: frozenset[str] = frozenset(),
max_hops: int = _MAX_SCENARIO_HOPS,
) -> list[tuple[str, ...]]:
"""Find up to ``k`` strong simple paths from our node to ``target``, lowest cost first.
This is Yen's k-shortest-loopless-paths over the evidence graph. Each link costs
@@ -962,6 +1163,11 @@ class MeshTopology:
Args:
target: The canonical id of the destination.
k: The maximum number of routes to return.
source: The canonical id where the routes start. The default is our node. An
outbound route continues from the last hop of its outbound path with it.
banned: The ids that a route must not go through (the hops of an outbound
path before ``source``, and our node).
max_hops: The most intermediate hops that a route can have.
Returns:
The intermediate-hop tuples of the routes that the method found (without the
@@ -969,15 +1175,21 @@ class MeshTopology:
version (refer to ``_routes_memo``). Callers must use the list as read-only,
and they do (both consumers only iterate it).
"""
memo_key = (target, k, self._graph_version)
start = self.self_id if source is None else source
memo_key = (target, k, self._graph_version, start, banned, max_hops)
memoized = self._routes_memo.get(memo_key)
if memoized is not None:
return memoized
neighbors: dict[str, list[tuple[str, float]]] = {}
for (a, b), link in self._links.items():
cost = 1.0 / max(link.strength(self._now), 1e-6) + _HOP_PENALTY
neighbors.setdefault(a, []).append((b, cost))
neighbors.setdefault(b, []).append((a, cost))
# Each direction has its own cost: a link out of our node is scored from what
# the far end measured from us (refer to outward_strength).
neighbors.setdefault(a, []).append(
(b, 1.0 / max(self.outward_strength(a, b, link), 1e-6) + _HOP_PENALTY)
)
neighbors.setdefault(b, []).append(
(a, 1.0 / max(self.outward_strength(b, a, link), 1e-6) + _HOP_PENALTY)
)
def shortest(
source: str, banned_nodes: set[str], banned_edges: set[tuple[str, str]]
@@ -995,7 +1207,7 @@ class MeshTopology:
if u == target:
break
for v, cost in neighbors.get(u, ()):
if v in banned_nodes or (u, v) in banned_edges:
if v in banned_nodes or v in banned or (u, v) in banned_edges:
continue
nd = d + cost
if nd < dist.get(v, math.inf):
@@ -1016,8 +1228,8 @@ class MeshTopology:
total += min((c for v, c in neighbors.get(a, ()) if v == b), default=math.inf)
return total
first = shortest(self.self_id, set(), set())
if first is None or len(first[1]) - 2 > _MAX_SCENARIO_HOPS:
first = shortest(start, set(), set())
if first is None or len(first[1]) - 2 > max_hops:
self._routes_memo[memo_key] = []
return []
accepted: list[list[str]] = [first[1]]
@@ -1044,7 +1256,7 @@ class MeshTopology:
if spur_result is None:
continue
full = root[:-1] + spur_result[1]
if len(full) - 2 > _MAX_SCENARIO_HOPS:
if len(full) - 2 > max_hops:
continue
key = tuple(full)
if key in seen:
+353
View File
@@ -0,0 +1,353 @@
# SPDX-License-Identifier: Apache-2.0
"""The ``outbound`` tool: the outbound paths of the sites of this computer and of fixed devices.
An outbound path is a path out of our node into the mesh, one or more hops long, that the
user trusts for the first hops of a route (refer to :mod:`meshterm.core.outbound_store`).
The route suggestions of the trace features start on one of them.
In the menu, the tool opens the Outbound paths page (:mod:`meshterm.ui.outbound_screen`),
in the Explore section, after Trace target and Trace path, which start their routes on
these paths. The paths belong to the computer, and the page works also with no device
connected.
On the CLI:
* ``outbound`` (or ``outbound show``): the paths that apply to the connected device now,
and where they come from. The exit status is ``5`` when no list applies.
* ``outbound sites``: each site, whether it is active, and its paths.
* ``outbound use SITE`` and ``outbound use --none``: make a site active, or no site.
* ``outbound set SITE PATH…``: make a site, or replace its paths. A path is a spec, the
same as ``--path`` of a trace (``3d63,f2c2``). When no site is active, the new site
becomes active, the same as in the menu.
* ``outbound remove SITE --yes``: delete a site.
* ``outbound fix [PATH…]``: make the connected device a fixed device. With no path, it
starts with the paths of the active site.
* ``outbound unfix --yes``: the connected device follows the active site again.
The commands that delete data need ``--yes``, as each such command in MeshTerm does.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import typer
from ..context import AppContext
from ..core import exitcodes
from ..core.outbound_store import OutboundPath, clean_path
from .base import Tool, ToolResult, register
if TYPE_CHECKING: # pragma: no cover - typing only
from ..ui.report import Block
@register
class OutboundTool(Tool):
"""Show and change the outbound paths of the sites and of the fixed devices."""
name = "outbound"
title = "Outbound paths"
icon = "🧭"
help = "The ways out of your node, for each site and fixed device"
category = "Explore"
order = 34 # after the two trace tools, which start their routes on these paths
async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None:
"""Open the Outbound paths page. The page writes its own changes.
Args:
ctx: The shared application context.
Returns:
``None``: nothing is left for :meth:`run` to do.
"""
from ..ui.outbound_screen import manage_outbound
await manage_outbound(ctx)
return None
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
"""Do one CLI operation on the store of outbound paths.
Args:
ctx: The shared application context.
params: ``op``: one of ``show``, ``sites``, ``use``, ``set``, ``remove``,
``fix``, and ``unfix``, with ``site`` and ``paths`` where the operation
takes them.
Returns:
A :class:`ToolResult` with the report of the operation.
Raises:
typer.BadParameter: If a site name or a path is not valid.
"""
op = params.get("op", "show")
store = ctx.outbound_store
if op == "show":
return await _show(ctx)
if op == "sites":
sites = store.sites()
active = store.active_site()
return ToolResult(
summary={"sites": len(sites)},
report=(_sites_listing(sites, active.name if active else None),),
exit_code=exitcodes.OK if sites else exitcodes.NO_RESULT,
)
if op == "use":
name = params.get("site")
if name is not None and store.site(name) is None:
raise typer.BadParameter(
f"no site is named {name!r}; see `meshterm outbound sites`"
)
store.set_active(name)
active = store.active_site()
shown = active.name if active else None
return _ack(
{"active": shown},
f"[ok]✓[/ok] active site: [brand]{shown}[/brand]"
if shown
else "[ok]✓[/ok] no site is active",
)
if op == "set":
name = str(params.get("site") or "").strip()
paths = _parse_paths(params.get("paths") or [])
try:
site = store.put_site(name, paths)
except ValueError as exc:
raise typer.BadParameter(str(exc)) from exc
if store.active_site() is None:
store.set_active(site.name)
active = store.active_site()
return _ack(
{
"site": site.name,
"active": active is not None and active.name == site.name,
"paths": [",".join(path) for path in site.paths],
},
f"[ok]✓[/ok] site [brand]{site.name}[/brand]: {len(site.paths)} outbound path(s)",
)
if op == "remove":
name = str(params.get("site") or "")
if not store.remove_site(name):
raise typer.BadParameter(
f"no site is named {name!r}; see `meshterm outbound sites`"
)
return _ack({"removed": name}, f"[ok]✓[/ok] deleted the site [brand]{name}[/brand]")
if op == "fix":
# A fixed device is the connected companion, so this needs the device: a read
# that fails here is the "no device" exit, and not an empty identity.
info = await ctx.devstate.self_info()
key = str(info.get("public_key") or "").lower()
name = str(info.get("name") or "")
given = params.get("paths")
if given:
paths = _parse_paths(given)
else:
active = store.active_site()
paths = list(active.paths) if active else []
device = store.fix_device(key, name, paths)
return _ack(
{"device": name or None, "paths": [",".join(path) for path in device.paths]},
f"[ok]✓[/ok] fixed [brand]{name or key[:12]}[/brand]: "
f"{len(device.paths)} outbound path(s)",
)
if op == "unfix":
info = await ctx.devstate.self_info()
key = str(info.get("public_key") or "").lower()
done = store.unfix_device(key)
return ToolResult(
summary={"unfixed": done},
message="[ok]✓[/ok] the device follows the active site again" if done else None,
report=(_facts({"unfixed": done}),),
exit_code=exitcodes.OK if done else exitcodes.NO_RESULT,
)
raise typer.BadParameter(f"unknown operation {op!r}") # pragma: no cover - the CLI sets it
# -- CLI --------------------------------------------------------------------
def register_cli(self, app: typer.Typer) -> None:
"""Register the ``outbound`` subcommand group.
Args:
app: The Typer application.
"""
from ..cli import run_tool_command
group = typer.Typer(help=self.help, no_args_is_help=False, rich_markup_mode=None)
@group.callback(invoke_without_command=True)
def _root(ctx: typer.Context) -> None:
"""Show the outbound paths that apply now when no subcommand is given."""
if ctx.invoked_subcommand is None:
run_tool_command(self, {"op": "show"})
@group.command("show", help="Show the outbound paths that apply to the device now")
def _show_cmd() -> None:
run_tool_command(self, {"op": "show"})
@group.command("sites", help="List the sites and their outbound paths")
def _sites_cmd() -> None:
run_tool_command(self, {"op": "sites"})
@group.command("use", help="Make a site active (or no site, with --none)")
def _use_cmd(
site: str | None = typer.Argument(None, help="The site to make active"),
none: bool = typer.Option(False, "--none", help="Make no site active"),
) -> None:
if (site is None) == (not none):
raise typer.BadParameter("give a site, or --none")
run_tool_command(self, {"op": "use", "site": site})
@group.command("set", help="Make a site, or replace its outbound paths")
def _set_cmd(
site: str = typer.Argument(..., help="The name of the site"),
paths: list[str] = typer.Argument(
None, help="Outbound paths in order, each a hop spec like 3d63,f2c2"
),
) -> None:
run_tool_command(self, {"op": "set", "site": site, "paths": paths or []})
@group.command("remove", help="Delete a site and its outbound paths")
def _remove_cmd(
site: str = typer.Argument(..., help="The site to delete"),
yes: bool = typer.Option(False, "--yes", help="Confirm this destructive action"),
) -> None:
if not yes:
raise typer.BadParameter(
"this deletes the site and its outbound paths; re-run with --yes to confirm"
)
run_tool_command(self, {"op": "remove", "site": site})
@group.command("fix", help="Give the connected device its own outbound paths")
def _fix_cmd(
paths: list[str] = typer.Argument(
None, help="Outbound paths in order (default: those of the active site)"
),
) -> None:
run_tool_command(self, {"op": "fix", "paths": paths or []})
@group.command("unfix", help="Let the connected device follow the active site again")
def _unfix_cmd(
yes: bool = typer.Option(False, "--yes", help="Confirm this destructive action"),
) -> None:
if not yes:
raise typer.BadParameter(
"this forgets the device's own outbound paths; re-run with --yes to confirm"
)
run_tool_command(self, {"op": "unfix"})
app.add_typer(group, name=self.name)
async def _show(ctx: AppContext) -> ToolResult:
"""The paths that apply to the connected device now, with the source of the list."""
from ..services.outbound import current_choice, session_contacts
choice = await current_choice(ctx)
contacts = await session_contacts(ctx)
blocks: list[Block] = [
_facts({"source": choice.source or None, "name": choice.name or None}, shape="pairs"),
_paths_listing(choice.paths, contacts),
]
return ToolResult(
summary={"source": choice.source, "paths": len(choice.paths)},
report=tuple(blocks),
exit_code=exitcodes.OK if choice.paths else exitcodes.NO_RESULT,
)
def _parse_paths(specs: list[str]) -> list[OutboundPath]:
"""The paths that the user typed, each checked. A bad one is a usage error."""
paths: list[OutboundPath] = []
for spec in specs:
path = clean_path(spec)
if path is None:
raise typer.BadParameter(
f"{spec!r} is not an outbound path: give hops in hex, separated by commas "
"(3d63,f2c2), each node only one time"
)
paths.append(path)
return paths
def _ack(values: dict[str, Any], message: str) -> ToolResult:
"""A change that worked: its facts for the machine face, and a line on stderr."""
return ToolResult(summary=dict(values), message=message, report=(_facts(values),))
def _facts(values: dict[str, Any], *, shape: str = "silent") -> Block:
"""One set of facts. Each value is a word, a flag, or a list of specs."""
from ..ui import fields
from ..ui.report import Column, Facts, Lane
columns = []
for key, value in values.items():
if isinstance(value, bool):
columns.append(fields.flag(key, key.upper()))
elif isinstance(value, list):
columns.append(
Column(
key=key,
lanes=(Lane(header=key.upper(), render=lambda v: " ".join(v) or "-"),),
json=list,
)
)
else:
columns.append(fields.word(key, key.upper()))
return Facts(key="outbound", fields=tuple(columns), values=values, shape=shape)
def _paths_listing(paths: tuple[OutboundPath, ...], contacts: list) -> Block:
"""The outbound paths in order: the rank, the hops with their names, and the spec."""
from ..ui import fields
from ..ui.report import Listing
def ref(hop: str) -> fields.NodeRef:
for contact in contacts:
key = (contact.public_key or contact.key_prefix or "").lower()
if key and key.startswith(hop):
return fields.NodeRef(
name=contact.name or None, key=contact.public_key or None, hash=hop
)
return fields.NodeRef(hash=hop)
return Listing(
key="paths",
columns=(
fields.integer("rank", "RANK"),
fields.spec("path", "PATH"),
fields.route("hops", "HOPS"),
),
rows=[
{"rank": i + 1, "path": ",".join(path), "hops": [ref(hop) for hop in path]}
for i, path in enumerate(paths)
],
)
def _sites_listing(sites: list, active: str | None) -> Block:
"""Each site: its name, whether it is active, and its paths as specs."""
from ..ui import fields
from ..ui.report import Column, Lane, Listing
return Listing(
key="sites",
columns=(
fields.name("site", "SITE"),
fields.flag("active", "ACTIVE"),
Column(
key="paths",
lanes=(Lane(header="PATHS", render=lambda v: " ".join(v) or "-"),),
json=list,
),
),
rows=[
{
"site": site.name,
"active": site.name == active,
"paths": [",".join(path) for path in site.paths],
}
for site in sites
],
)
+26
View File
@@ -849,6 +849,18 @@ async def _menu_loop(ctx: AppContext, session: TuiSession) -> None:
)
session.set_root(menu)
loop = asyncio.get_running_loop()
def offer_site_now() -> None:
"""Ask about a suggested site at once, but only over the main menu.
The suggestion arrives while the user does something. Over a screen, it waits for
the next round of the menu, so that it never interrupts a screen.
"""
if session.top is menu:
session.run_detached(_offer_pending_site(ctx))
if getattr(ctx, "site_suggest", None) is not None:
ctx.site_suggest.on_ready = offer_site_now
while True:
try:
await _menu_round(ctx, session, menu, tools, loop)
@@ -861,6 +873,16 @@ async def _menu_loop(ctx: AppContext, session: TuiSession) -> None:
session.unwound()
async def _offer_pending_site(ctx: AppContext) -> None:
"""Ask the user about the site that the radio seems to be at, if a suggestion waits."""
service = getattr(ctx, "site_suggest", None) # a stub context of a test has none
suggestion = service.take() if service is not None else None
if suggestion is not None:
from .outbound_screen import offer_site
await offer_site(ctx, suggestion)
class _Quit(Exception):
"""The user confirmed the quit dialog from the Quit row of the menu.
@@ -901,6 +923,7 @@ async def _menu_round(
session.push(menu)
ran_over_menu = False
try:
await _offer_pending_site(ctx) # a suggestion that waited for the menu
selection = await menu.future
# The Quit row asks first, in a dialog over the menu (which is still pushed). Cancel
# ends the round and paints the menu again, and its highlight is still on the row.
@@ -1089,6 +1112,9 @@ async def _resume_monitor(ctx: AppContext) -> Exception | None:
# The place finder reads only stored locations and the network (tiles, Nominatim), never
# the device. Its first read waits some seconds, so it does not slow the start.
await ctx.places.start()
# The site suggestion only counts what the hub hears, and the menu asks the user. It
# never opens the device (refer to meshterm.services.site_suggest).
await ctx.site_suggest.start()
if not ctx.settings.connect_on_start:
return None
failure: Exception | None = None
+33 -4
View File
@@ -103,7 +103,7 @@ import re
import time
from collections.abc import Callable
from dataclasses import dataclass, field, replace
from datetime import datetime
from datetime import datetime, timedelta
from itertools import pairwise
from typing import TYPE_CHECKING
@@ -1618,9 +1618,33 @@ async def open_node_detail(
if not you and contact is not None and contact.route_hops is not None:
device_route = tuple(topo.canonical(h) or h for h in contact.route_hops)
canonical_target = (topo.canonical(target_hash) or target_hash[:12]) if target_hash else None
suggested = topo.suggested(canonical_target) if canonical_target else None
# The outbound paths of the user lead the suggestions, as on the trace screen (refer to
# MeshTopology.scenarios). A stub context of a test has no store, and gets none.
outbound_store = getattr(ctx, "outbound_store", None)
choice = outbound_store.lookup(self_key or None) if outbound_store is not None else None
outbound = (
tuple(tuple(topo.canonical(h) or h for h in path) for path in choice.paths)
if choice is not None
else ()
)
prefs = getattr(ctx, "preferences", None)
silent_before = (
utcnow() - timedelta(hours=prefs.outbound_silent_hours) if prefs is not None else None
)
suggested = (
topo.suggested(canonical_target, outbound=outbound, silent_before=silent_before)
if canonical_target
else None
)
scenarios = (
topo.scenarios(canonical_target, device_route=device_route) if canonical_target else []
topo.scenarios(
canonical_target,
device_route=device_route,
outbound=outbound,
silent_before=silent_before,
)
if canonical_target
else []
)
# -- the info block (the identity, how the node was heard, and where it is). The routes
@@ -2727,7 +2751,7 @@ def _routes_view(
return _RoutesView(note="no key to route to")
has_evidence = (
device_route is not None
or any(s.source == "observed" for s in scenarios)
or any(s.source in ("observed", "outbound") for s in scenarios)
or topo.link(topo.self_id, canonical_target) is not None
)
if not has_evidence:
@@ -2764,6 +2788,11 @@ def _routes_view(
add(best_hops, "best", None, 0)
if device_route is not None:
add(device_route, "device", None, 0)
# Each route through an outbound path of the user: the user named the way out, so the
# route gets a line also where the evidence is thin.
for scenario in scenarios:
if scenario.source == "outbound":
add(scenario.hops, "", scenario.weakest_snr, scenario.samples)
for scenario in _good_alternatives(topo, scenarios, canonical_target):
add(scenario.hops, "", scenario.weakest_snr, scenario.samples)
+774
View File
@@ -0,0 +1,774 @@
# SPDX-License-Identifier: Apache-2.0
"""The Outbound paths pages: the sites of this computer, the fixed devices, and their paths.
An outbound path is a path out of our node into the mesh, which the user trusts for the
first hops of a route (refer to :mod:`meshterm.core.outbound_store`). The pages have three
levels, each a place on the stack:
* **Outbound paths** (the tool page). The summary line says which list applies now: the
list of a fixed device, the list of the active site, or none. Below it are the sites,
with a ``✓`` on the active site, and the fixed devices. Enter opens one of them. Two
action rows make a new site, or make the connected device a fixed device.
* ``Site — name`` and ``Device — name``. One editor for a list of outbound paths, in
order. Each path is a row: its rank and its route, with the evidence for its first
link under it. ``out`` is how well the first hop hears our node, and ``in`` is how well
our node hears it. A radio link is not symmetric, and the evidence of MeshTerm comes
mostly from what our node hears. Thus the two directions show apart (refer to
:func:`~meshterm.services.outbound.first_link`). Enter on a path floats a small dialog:
edit it in the composer, move it up or down, or remove it. Del removes it too. The
changes are staged, and Apply writes them (the ``exit_rows`` shape of the app). Below
the list are the actions of the site or the device, which act at once: use the site,
rename it, delete it, or unfix the device.
An outbound path is composed in the path composer, in its outbound mode (refer to
:class:`~meshterm.ui.path_composer.PathComposerScreen`). The suggestions come from the
evidence graph, the same as for a trace.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
from rich.cells import cell_len
from rich.text import Text
from ..core.outbound_store import (
SOURCE_DEVICE,
SOURCE_SITE,
OutboundPath,
OutboundStore,
clean_path,
)
from ..services import trace_runner
from ..services.outbound import (
DeviceIdentity,
FirstLink,
device_identity,
first_link,
session_contacts,
session_topology,
)
from ..services.topology import MeshTopology
from .menus import (
confirm_discard,
exit_rows,
fit_cells,
icon_lane,
marked_label,
menu_rows,
section_heading,
)
from .path_composer import PathComposerScreen
from .pathline import cut_to, path_line
from .theme import snr_style
from .tui.screen import CANCEL
from .tui.select import Choice, DeleteRequest, SelectScreen, Separator
from .widgets import age_seconds, format_age
if TYPE_CHECKING: # pragma: no cover - typing only
from ..context import AppContext
from ..core.models import Contact
from ..services.site_suggest import SiteSuggestion
#: The hint of the tool page: each row opens a page.
_PAGE_HINT = "↑↓ move · Enter open · Esc back"
#: The hint of an editor page.
_EDIT_HINT = "↑↓ move · Enter select · Esc back"
#: The limits of the name lane of the sites and the fixed devices, in cells. The lane fits
#: the longest name between the two, the same as the Rooms page.
_NAME_MIN = 8
_NAME_MAX = 16
#: The longest name that the user can give a site, in characters. A longer name only makes
#: the rows of the tool page longer, and a site needs a short name.
SITE_NAME_MAX = 24
_NEW = ("new",)
_FIX = ("fix",)
_ADD = ("add",)
_APPLY = ("apply",)
_BACK = ("back",)
_USE = ("use",)
_UNUSE = ("unuse",)
_RENAME = ("rename",)
_DELETE = ("delete",)
_UNFIX = ("unfix",)
@dataclass(slots=True)
class _Env:
"""What each page needs from the session, read one time for the visit.
Attributes:
identity: The connected companion (empty with no device).
contacts: Its contacts, for the names of the hops.
topology: The evidence graph around our node.
width_bytes: The path-hash width at which a hop with no name shows its hash.
"""
identity: DeviceIdentity
contacts: list[Contact]
topology: MeshTopology
width_bytes: int
_resolve: Any = field(init=False, repr=False)
def __post_init__(self) -> None:
"""Build the fallback resolver one time (it scans the contacts)."""
self._resolve = trace_runner.make_node_resolver(self.contacts)
def name(self, hop: str | None) -> str | None:
"""The name of a hop: the name in the graph, else the first contact that matches."""
if hop is None:
return None
return self.topology.display_name(hop) or self._resolve(hop) or hop
async def _env(ctx: AppContext) -> _Env:
"""Read the session for a visit: the device, its contacts, the graph, and the width."""
identity = await device_identity(ctx)
contacts = await session_contacts(ctx)
try:
from .trace_screen import collapse_trace_width
width_bytes = collapse_trace_width(int(await ctx.devstate.path_hash_mode()))
except Exception: # noqa: BLE001 - an optional read. One byte is the protocol default.
width_bytes = 1
return _Env(identity, contacts, session_topology(ctx, identity.key, contacts), width_bytes)
# --- the tool page --------------------------------------------------------------------
async def manage_outbound(ctx: AppContext) -> None:
"""Run the Outbound paths page until the user backs out.
Args:
ctx: The shared application context (which runs the interactive TUI surface).
"""
env = await _env(ctx)
store = ctx.outbound_store
title, prompt, items = _page(store, env)
menu = SelectScreen(title, items, prompt=prompt, footer_hint=_PAGE_HINT, filterable=False)
async with ctx.ui.session.stay(menu) as visit:
while True:
choice = await visit.result()
if choice is CANCEL or choice is None:
return
if choice == _NEW:
name = await _ask_site_name(ctx)
if name is not None:
store.put_site(name, [])
if store.active_site() is None:
store.set_active(name) # the first site is where the user is
await _site_page(ctx, env, name)
elif choice == _FIX and env.identity.key:
active = store.active_site()
store.fix_device(
env.identity.key, env.identity.name, list(active.paths) if active else []
)
await _device_page(ctx, env, env.identity.key)
elif choice[0] == "site":
await _site_page(ctx, env, choice[1])
elif choice[0] == "device":
await _device_page(ctx, env, choice[1])
title, prompt, items = _page(store, env)
menu.replace_items(items, title=title, prompt=prompt)
def _page(store: OutboundStore, env: _Env) -> tuple[str, str, list]:
"""The title, the summary line, and the rows of the tool page."""
sites = store.sites()
active = store.active_site()
devices = store.fixed_devices()
choice = store.lookup(env.identity.key or None)
if choice.source == SOURCE_DEVICE:
prompt = f"Now: {choice.name or 'this device'}'s own paths (a fixed device)"
elif choice.source == SOURCE_SITE:
prompt = f"Now: site {choice.name}"
else:
prompt = "Now: no site — routes come from what MeshTerm heard"
lane = icon_lane(("✎",))
labels = [site.name for site in sites] + [d.name or k[:12] for k, d in devices.items()]
name_w = max(_NAME_MIN, min(_NAME_MAX, max((cell_len(n) for n in labels), default=0)))
items: list = [section_heading("Sites")]
for site in sites:
is_active = active is not None and site.name == active.name
items.append(_list_row(env, ("site", site.name), site.name, site.paths, is_active, name_w))
if not sites:
items.append(
Separator(" no sites yet — a site holds the paths for where you are", style="muted")
)
items += menu_rows(
[(marked_label("✎", "New site…", "", lane=lane), "Name it, then add its paths", _NEW)]
)
items.append(section_heading("Fixed devices"))
for key, device in devices.items():
label = device.name or key[:12]
items.append(_list_row(env, ("device", key), label, device.paths, False, name_w))
if not devices:
items.append(Separator(" none — a fixed device keeps its own paths", style="muted"))
if env.identity.key and env.identity.key not in devices:
name = env.identity.name or "this device"
items += menu_rows(
[
(
marked_label("✎", f"Fix {name}…", "", lane=lane),
"It never moves: give it its own paths",
_FIX,
)
]
)
return "Outbound paths", prompt, items
def _list_row(env: _Env, value: tuple, name: str, paths: list, active: bool, name_w: int) -> Choice:
"""One site or fixed device: the active mark, the name, the path count, the first path."""
def title(width: int) -> Text:
text = Text(no_wrap=True)
text.append("✓ " if active else " ", style="ok")
text.append(fit_cells(name, name_w))
count = len(paths)
counted = f"{count} path{'' if count == 1 else 's'}"
text.append(f" {counted:<8} ", style="muted")
if paths:
text.append_text(_route(env, paths[0]))
return cut_to(text, width)
return Choice(title=title, value=value, fitted=True)
def _route(env: _Env, path: OutboundPath) -> Text:
"""An outbound path as a path line: our ``★``, then its hops, with an open end."""
return path_line(
[None, *path],
env.name,
prefix_bytes=env.width_bytes,
hash_bytes=env.width_bytes,
bare_self=True,
dim_self=False,
to_destination=False,
).text()
async def _ask_site_name(ctx: AppContext, *, current: str = "") -> str | None:
"""Ask for the name of a site. A name that another site has is refused."""
store = ctx.outbound_store
def valid(text: str) -> bool | str:
name = text.strip()
if not name:
return "a site needs a name"
if len(name) > SITE_NAME_MAX:
return f"at most {SITE_NAME_MAX} characters"
other = store.site(name)
if other is not None and other.name.casefold() != current.casefold():
return f"a site named {other.name} already exists"
return True
answer = await ctx.ui.session.text(
"Rename site" if current else "New site",
prompt="Site name (where you are: Home, Work, …):",
default=current,
validate=valid,
floating=True,
)
return answer.strip() if answer is not None else None
# --- the editor pages -------------------------------------------------------------------
async def _site_page(ctx: AppContext, env: _Env, name: str) -> None:
"""The page of one site: its outbound paths, then the actions of the site."""
store = ctx.outbound_store
site = store.site(name)
if site is None: # pragma: no cover - the row came from this store
return
state = {"name": site.name}
def actions() -> list:
return _site_actions(store, state["name"])
def summary(paths: list[OutboundPath]) -> str:
return _site_summary(store, state["name"], paths)
async def act(value: Any) -> bool:
"""Run one action of the site. Return ``True`` when the page must close."""
if value == _USE:
store.set_active(state["name"])
elif value == _UNUSE:
store.set_active(None)
elif value == _RENAME:
new = await _ask_site_name(ctx, current=state["name"])
if new is not None and new != state["name"]:
current = store.site(state["name"])
store.put_site(new, list(current.paths) if current else [], old_name=state["name"])
state["name"] = new
elif value == _DELETE:
if await ctx.ui.dialog(
f"Delete the site {state['name']} and its outbound paths?",
[("Cancel", False), ("Delete", True)],
title=f"Delete — {state['name']}",
default=1,
destructive=True,
):
store.remove_site(state["name"])
return True
return False
def save(paths: list[OutboundPath]) -> None:
store.put_site(state["name"], paths)
await _paths_page(
ctx,
env,
title=lambda: f"Site — {state['name']}",
summary=summary,
paths=list(site.paths),
actions=actions,
act=act,
save=save,
)
async def _device_page(ctx: AppContext, env: _Env, key: str) -> None:
"""The page of one fixed device: its outbound paths, then the action that unfixes it."""
store = ctx.outbound_store
device = store.fixed_device(key)
if device is None: # pragma: no cover - the row came from this store
return
label = device.name or key[:12]
def actions() -> list:
return _device_actions()
def summary(paths: list[OutboundPath]) -> str:
return _device_summary(key == env.identity.key, paths)
async def act(value: Any) -> bool:
if value == _UNFIX and await ctx.ui.dialog(
f"Unfix {label}? Its own outbound paths are forgotten, and the active site "
"applies to it again.",
[("Cancel", False), ("Unfix", True)],
title=f"Unfix — {label}",
default=1,
destructive=True,
):
store.unfix_device(key)
return True
return False
def save(paths: list[OutboundPath]) -> None:
store.fix_device(key, device.name, paths)
await _paths_page(
ctx,
env,
title=lambda: f"Device — {label}",
summary=summary,
paths=list(device.paths),
actions=actions,
act=act,
save=save,
)
def _paths_phrase(count: int) -> str:
"""``"no outbound paths"``, ``"1 outbound path"``, ``"3 outbound paths"``."""
if not count:
return "no outbound paths"
return f"{count} outbound path{'' if count == 1 else 's'}"
def _site_summary(store: OutboundStore, name: str, paths: list[OutboundPath]) -> str:
"""The summary line of a site page: whether the site is active, and its path count."""
active = store.active_site()
word = "active" if active is not None and active.name == name else "not active"
return f"{word} · {_paths_phrase(len(paths))}"
def _device_summary(connected: bool, paths: list[OutboundPath]) -> str:
"""The summary line of a device page."""
here = " · connected" if connected else ""
return f"fixed{here} · {_paths_phrase(len(paths))} · the active site does not apply"
def _site_actions(store: OutboundStore, name: str) -> list:
"""The actions of a site, which act at once: use it (or stop), rename it, delete it."""
lane = icon_lane(("✓", "✎", "🗑"))
active = store.active_site()
rows: list = []
if active is None or active.name != name:
rows.append(
(
marked_label("✓", "Use this site", "ok", lane=lane),
"Its paths apply to each device that is not fixed",
_USE,
)
)
else:
rows.append(
(
marked_label("○", "Stop using this site", "muted", lane=lane),
"Routes then come from what MeshTerm heard",
_UNUSE,
)
)
rows.append((marked_label("✎", "Rename…", "", lane=lane), "Give the site a new name", _RENAME))
rows.append(
(
marked_label("🗑", "Delete this site…", "err", lane=lane),
"Forget the site and its paths",
_DELETE,
)
)
return [section_heading("Site"), *menu_rows(rows)]
def _device_actions() -> list:
"""The one action of a fixed device: unfix it."""
lane = icon_lane(("🗑",))
return [
section_heading("Device"),
*menu_rows(
[
(
marked_label("🗑", "Unfix this device…", "err", lane=lane),
"Forget its paths: it follows the active site",
_UNFIX,
)
]
),
]
def _editor_items(env: _Env, staged: list[OutboundPath], owner: list, changes: int) -> list:
"""The rows of an editor page: the paths, the Add row, the owner's actions, the exit pair."""
lane = icon_lane(("✎",))
rows: list = [section_heading("Outbound paths")]
rows.append(Separator(" out: its first hop hears you · in: you hear it", style="muted"))
for index, path in enumerate(staged):
rows.append(_path_row(env, index, path))
if not staged:
rows.append(Separator(" none yet — add the way out that works from here", style="muted"))
rows += menu_rows(
[
(
marked_label("✎", "Add an outbound path…", "", lane=lane),
"Compose it hop by hop",
_ADD,
)
]
)
rows += owner
rows += exit_rows(changes, apply_value=_APPLY, back_value=_BACK)
return rows
async def _paths_page(
ctx: AppContext,
env: _Env,
*,
title: Any,
summary: Any,
paths: list[OutboundPath],
actions: Any,
act: Any,
save: Any,
) -> None:
"""The editor of one list of outbound paths, with the actions of its owner below it.
The changes to the list are staged. Apply writes them with ``save``, and Esc or Back
with staged changes asks first (:func:`~meshterm.ui.menus.confirm_discard`). The
actions of the owner act at once, through ``act``.
Args:
ctx: The shared application context.
env: The session values of the visit.
title: A callable that gives the title (a rename changes it).
summary: A callable that gives the summary line for the staged list.
paths: The stored list, the preferred path first.
actions: A callable that gives the rows of the actions of the owner.
act: An async callable that runs one action. It returns ``True`` when the page
must close (the owner was deleted).
save: A callable that writes a list.
"""
stored = list(paths)
staged = list(paths)
edits = 0
def changes() -> int:
return 0 if staged == stored else max(1, edits)
def items() -> list:
return _editor_items(env, staged, actions(), changes())
menu = SelectScreen(
title(),
items(),
prompt=summary(staged),
footer_hint=_EDIT_HINT,
filterable=False,
delete_hint="Del remove",
)
async with ctx.ui.session.stay(menu) as visit:
while True:
choice = await visit.result()
if choice is CANCEL or choice is None or choice == _BACK:
if changes() and not await confirm_discard(ctx, changes()):
continue
return
if isinstance(choice, DeleteRequest):
index = choice.value[1]
del staged[index]
edits += 1
elif choice == _APPLY:
save(list(staged))
stored = list(staged)
edits = 0
elif choice == _ADD:
added = await _compose(ctx, env, ())
if added is not None and added not in staged:
staged.append(added)
edits += 1
elif isinstance(choice, tuple) and choice[0] == "path":
edits += await _path_actions(ctx, env, staged, choice[1])
elif await act(choice):
return
menu.replace_items(items(), title=title(), prompt=summary(staged))
def _path_row(env: _Env, index: int, path: OutboundPath) -> Choice:
"""One outbound path: its rank and route, with the evidence of its first link below."""
def title(width: int) -> Text:
text = Text(f"{index + 1} ", style="accent", no_wrap=True)
text.append_text(_route(env, path))
return cut_to(text, width)
return Choice(
title=title,
value=("path", index),
detail=_evidence(first_link(env.topology, path)),
deletable=True,
)
def _evidence(link: FirstLink) -> Text:
"""The two directions of a first link: ``out +9 dB ×12 · in +11 dB ×2.1k · 3m``."""
if not link.out_count and not link.in_count:
return Text(" no readings of its first hop yet", style="muted")
text = Text(" ")
for word, snr, count in (
("out", link.out_snr, link.out_count),
("in", link.in_snr, link.in_count),
):
if word == "in":
text.append(" · ", style="muted")
text.append(f"{word} ", style="muted")
if snr is None:
text.append("-", style="muted")
else:
text.append(f"{snr:+.0f} dB", style=snr_style(snr))
text.append(f" ×{_count(count)}", style="muted")
if link.last_heard is not None:
text.append(f" · {format_age(age_seconds(link.last_heard))}", style="muted")
return text
def _count(count: int) -> str:
"""A reading count in at most four cells: ``12``, ``980``, ``2.1k``, ``14k``."""
if count < 1000:
return str(count)
if count < 10_000:
return f"{count / 1000:.1f}k"
return f"{count // 1000}k"
async def _path_actions(ctx: AppContext, env: _Env, staged: list[OutboundPath], index: int) -> int:
"""Float the actions of one path, and apply the selected one to the staged list.
Returns:
``1`` when the list changed, else ``0``.
"""
lane = icon_lane(("✎", "⚡", "↕", "🗑"))
rows: list = [(marked_label("✎", "Edit…", "", lane=lane), "Change its hops", "edit")]
if env.identity.key: # a measure transmits, so it needs the device
rows.append(
(
marked_label("⚡", "Measure", "", lane=lane),
"One trace out along it and back",
"measure",
)
)
if index > 0:
rows.append(
(marked_label("↕", "Move up", "", lane=lane), "Prefer it to the path above", "up")
)
if index < len(staged) - 1:
rows.append(
(marked_label("↕", "Move down", "", lane=lane), "Prefer the path below", "down")
)
rows.append((marked_label("🗑", "Remove", "err", lane=lane), "Take it off the list", "remove"))
picked = await ctx.ui.session.select(
f"Outbound path {index + 1}",
menu_rows(rows),
filterable=False,
footer_hint="↑↓ move · Enter select · Esc cancel",
floating=True,
)
if picked == "edit":
changed = await _compose(ctx, env, staged[index])
if changed is None or changed == staged[index]:
return 0
if changed in staged: # the same path is already on the list: keep one copy
del staged[index]
else:
staged[index] = changed
return 1
if picked == "measure":
await _measure(ctx, env, staged[index])
return 0
if picked == "up":
staged[index - 1], staged[index] = staged[index], staged[index - 1]
return 1
if picked == "down":
staged[index + 1], staged[index] = staged[index], staged[index + 1]
return 1
if picked == "remove":
del staged[index]
return 1
return 0
async def offer_site(ctx: AppContext, suggestion: SiteSuggestion) -> None:
"""Ask the user to use the site whose way out the radio hears, and say why.
The dialog names the node that the radio heard, how many times, and the site whose
outbound path starts on it. It never changes the site without an answer. "Never
suggest" sets the ``suggest_site`` preference off, so the user can stop the question
where it asks (refer to :mod:`meshterm.services.site_suggest`).
"""
store = ctx.outbound_store
site = store.site(suggestion.site)
if site is None: # deleted since the radio heard it
return
contacts = await session_contacts(ctx)
named = trace_runner.make_node_resolver(contacts)(suggestion.hop)
label = named if named and named != suggestion.hop else suggestion.hop
active = store.active_site()
unheard = (
f"no first hop of site {active.name} was heard"
if active is not None
else "no site is active now"
)
prompt = (
f"Your radio heard {label} {suggestion.heard} times since MeshTerm started. It is the "
f"first hop of an outbound path of site {site.name}, and {unheard}.\n\n"
f"Use site {site.name}?"
)
answer = await ctx.ui.dialog(
prompt,
[("Not now", None), ("Never suggest", "never"), (f"Use {site.name}", "use")],
title="Site",
default=2,
)
if answer == "use":
store.set_active(site.name)
elif answer == "never":
ctx.preferences.set("suggest_site", False)
ctx.preferences.save()
def measure_walk(path: OutboundPath) -> tuple[str, ...]:
"""The walk that measures an outbound path: out along it, and back the same way.
The last hop of the path is the turning point, so it is in the walk one time
(``A, B, C`` walks ``A, B, C, B, A``). The trace protocol has no return field, and the
reply comes home from the last hop of the walk. Thus each link of the path is measured
in both directions. The first hop reports how well it heard our node, and our node
measures the last step home.
"""
return (*path, *reversed(path[:-1]))
async def _measure(ctx: AppContext, env: _Env, path: OutboundPath) -> None:
"""Send one trace along ``path`` and back, store it, and show what each hop measured.
One press sends one trace, after the shared transmit cooldown (refer to
:func:`~meshterm.ui.cooldown.wait_for_cooldown`). Repeaters penalize a node that sends
bursts. The trace is stored as a path walk, exactly as a Trace path run stores it.
Thus its readings go into the evidence graph, and the evidence line of the path
changes when the dialog closes.
"""
from ..core.models import PATH_TRACE_TARGET
from ..services.topology import render_custom_spec
from .cooldown import wait_for_cooldown
walk = measure_walk(path)
spec = render_custom_spec(walk, env.width_bytes)
if not await wait_for_cooldown(ctx, action="Measure"):
return
device = await ctx.device()
hex_path = trace_runner.parse_trace_path(spec, env.contacts)
run_id = ctx.repo.start_run(
"trace", {"target": PATH_TRACE_TARGET, "path": hex_path}, ctx.profile_name
)
try:
async with ctx.ui.busy_dialog("tracing out and back…", title="Measure"):
result = await device.run_trace(PATH_TRACE_TARGET, path=hex_path)
except BaseException as exc:
ctx.repo.finish_run(run_id, "error", {"error": str(exc) or type(exc).__name__})
raise
ctx.repo.record_trace(run_id, result)
ctx.repo.finish_run(
run_id,
"ok",
{"target": PATH_TRACE_TARGET, "success": result.success, "min_snr": result.min_snr},
)
env.topology = session_topology(ctx, env.identity.key, env.contacts)
await ctx.ui.session.message_dialog(_measured(env, walk, result), title="Measure")
def _measured(env: _Env, walk: tuple[str, ...], result: Any) -> Text:
"""What one measure found: who heard whom, at what SNR, or why it did not come back."""
if not result.success:
return Text("✗ no reply — a hop did not hear the trace, or did not relay it", style="err")
text = Text("✓ ", style="ok")
text.append("the trace came back")
if result.round_trip_ms is not None:
text.append(f" in {result.round_trip_ms / 1000:.1f} s", style="muted")
senders = [None, *walk]
receivers = [*walk, None]
for hop, sender, receiver in zip(result.hops, senders, receivers, strict=False):
text.append("\n")
text.append(env.name(receiver) or "you" if receiver else "you")
text.append(" heard ", style="muted")
text.append(env.name(sender) or "you" if sender else "you")
text.append(" at ", style="muted")
text.append(f"{hop.snr:+.1f} dB", style=snr_style(hop.snr))
return text
async def _compose(ctx: AppContext, env: _Env, path: OutboundPath) -> OutboundPath | None:
"""Open the composer in outbound mode. Return the composed path, or ``None``."""
topo = env.topology
screen = PathComposerScreen(
device_label=env.identity.name or "you",
device_hash=env.identity.key or None,
topology=topo,
width_bytes=env.width_bytes,
hops=[topo.canonical(hop) or hop for hop in path],
resolve=env.name,
outbound=True,
)
result = await ctx.ui.session.run_screen(screen)
if result is CANCEL or not isinstance(result, str):
return None
return clean_path(result)
__all__ = ["SITE_NAME_MAX", "manage_outbound"]
+76 -3
View File
@@ -23,6 +23,12 @@ node can hear it.)
dims) only the last step back to our node. The preview starts as ``★ → + → ★`` only.
There is no "Auto" action, because with no destination, the device has nothing to
route to.
* **Outbound mode** (the Outbound paths pages, ``outbound=True``): the user composes an
outbound path, the way out of our node into the mesh (refer to
:mod:`meshterm.core.outbound_store`). It has no target and no return. The preview is
``★ → hop → …`` and its end is open, because the route goes on from there. A node can
be in the path only one time. The composer returns the canonical ids of the hops, at
full width, because a stored path must not depend on the path-hash width of a session.
Interaction, which follows the pattern of the reorder screen (a highlight that moves over
rows and actions):
@@ -39,6 +45,10 @@ rows and actions):
* Typed text filters the suggestions by name or by hash. When the typed text is hex with
an even length, a row appears that adds it as a custom hop. Thus the user can force a
node that MeshTerm never observed (or a bare hash from another tool) into the route.
* While the insertion slot is at our node, the outbound paths of the user (refer to
:mod:`meshterm.core.outbound_store`) come first, in the order of the user, before the
suggestions. Enter on one inserts all of its hops. The user knows which way out of our
node works, and the evidence of the graph is mostly what our node heard.
* Backspace (⌫) removes the filter text first. When the filter is empty, it removes the
hop to the left of the slot.
* When the slot is after a repeater for which we have admin credentials, a "Fetch
@@ -217,6 +227,8 @@ class PathComposerScreen(Screen):
cursor: int | None = None,
fetch_nodes: frozenset[str] = frozenset(),
resolve: NodeResolver = identity_label,
outbound: bool = False,
outbound_paths: tuple[tuple[str, ...], ...] = (),
) -> None:
"""Build the composer.
@@ -224,7 +236,8 @@ class PathComposerScreen(Screen):
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,
the composer is in path mode: the user composes the full walk by hand, and the
composer returns it exactly.
composer returns it exactly. ``outbound`` selects outbound mode, which also has no
target.
Args:
device_label: The name of our node, at the start and at the end of the route
@@ -251,9 +264,19 @@ class PathComposerScreen(Screen):
names a hop that the topology cannot name (refer to
:meth:`_resolve_entry`). Thus the composer shows the same names as the
screen that opened it.
outbound: Compose an outbound path: no target, no return, and the canonical
ids of the hops as the result (refer to the module docstring).
outbound_paths: The outbound paths that apply now, in the order of the user,
as canonical ids. They lead the rows while the insertion slot is at our
node. Outbound mode ignores them, because it composes such a path.
"""
super().__init__()
self.title = f"Compose path — {target_label}" if target_label else "Compose path"
if outbound:
self.title = "Compose outbound path"
else:
self.title = f"Compose path — {target_label}" if target_label else "Compose path"
self._outbound = outbound and target_id is None
self._outbound_paths = () if outbound else tuple(p for p in outbound_paths if p)
self._target_id = target_id
self._target_hash = (target_hash or "").lower().removeprefix("0x")
self._target_label = target_label
@@ -416,6 +439,8 @@ class PathComposerScreen(Screen):
"""
if self._mirrored:
exclude = frozenset({self._topology.self_id, self._target_id, *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:
after = self._hops[self._cursor] if self._cursor < len(self._hops) else None
exclude = frozenset(
@@ -444,6 +469,22 @@ class PathComposerScreen(Screen):
]
return merged[:_MAX_SUGGESTIONS]
def _usable_outbound(self) -> list[tuple[int, tuple[str, ...]]]:
"""The outbound paths to offer now, each with its rank: only at our node, unfiltered.
A path is offered only where it can go: while the insertion slot is at our node,
with no typed entry, and when none of its nodes is already in the route or is the
target.
"""
if self._cursor or self._entry or not self._outbound_paths:
return []
taken = {*self._hops, self._target_id} if self._target_id else set(self._hops)
return [
(rank, path)
for rank, path in enumerate(self._outbound_paths, start=1)
if not taken & set(path)
]
def _custom_hex(self) -> str | None:
"""The typed entry as a hex hop that the user can add, or ``None`` if it is not one."""
needle = self._entry.strip().lower().removeprefix("0x")
@@ -455,6 +496,7 @@ class PathComposerScreen(Screen):
custom = self._custom_hex()
if custom:
rows.append(("custom", custom))
rows.extend(("outbound", entry) for entry in self._usable_outbound())
rows.extend(("hop", s) for s in self._suggestions())
# When the slot is after a repeater for which we have credentials, its live
# neighbour table is one key press away. The row goes with the suggestions,
@@ -479,6 +521,8 @@ class PathComposerScreen(Screen):
"""
if self._mirrored:
return render_forced_spec(tuple(self._hops), self._target_hash, self._width_bytes)
if self._outbound: # the stored form: each hop at its full width
return ",".join(self._hops)
return render_custom_spec(tuple(self._hops), self._width_bytes)
def _walk_nodes(self) -> list[str]:
@@ -596,6 +640,23 @@ class PathComposerScreen(Screen):
if self._mirrored:
entries.append(self._path_entry(self._target_id))
entries.extend(self._path_entry(hop) for hop in reversed(self._hops))
if self._outbound:
# An outbound path has no way home: the route goes on from its last hop. Thus
# the line ends open (refer to ``to_destination`` of PathLine).
line = path_line(
entries,
self._resolve_entry,
prefix_bytes=self._width_bytes,
self_name=self._device_label,
hash_bytes=self._width_bytes,
device_hash=self._device_hash or None,
bare_self=True,
cursor=self._cursor + 1,
to_destination=False,
)
if self._places.on:
line = placed(line, places_of_session(), node_of(self._resolve))
return line
entries.append(None)
line = path_line(
entries,
@@ -639,6 +700,14 @@ class PathComposerScreen(Screen):
return text
if kind == "hop":
return self._suggestion_text(payload)
if kind == "outbound":
rank, path = payload # type: ignore[misc]
text = Text(f"outbound path {rank} ", style="accent")
for i, hop in enumerate(path):
if i:
text.append(" → ", style="muted")
text.append_text(self._node_text(hop))
return text
if kind == "fetch":
text = Text("⇣ Fetch neighbours from ", style="")
text.append_text(self._node_text(str(payload))) # named like each other row
@@ -696,7 +765,8 @@ class PathComposerScreen(Screen):
else:
heading = Text("Next hop from ", style="muted")
heading.append_text(self._node_text(self._anchor()))
heading.append(" — strongest first", style="muted")
first = "your paths first" if self._usable_outbound() else "strongest first"
heading.append(f" — {first}", style="muted")
lines.extend(render_lines(heading, width))
# Each entry of the list window is one rendered line, tagged with its row index
@@ -772,6 +842,9 @@ class PathComposerScreen(Screen):
self._insert_hop(str(payload))
elif kind == "hop":
self._insert_hop(payload.node) # type: ignore[union-attr]
elif kind == "outbound":
for hop in payload[1]: # type: ignore[index]
self._insert_hop(hop)
elif kind == "fetch":
self.resolve(FetchNeighbours(node=str(payload)))
elif payload == _USE:
+80 -9
View File
@@ -107,13 +107,14 @@ from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable, Sequence
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any
from rich.cells import cell_len
from rich.console import Group, RenderableType
from rich.text import Text
from ..core.models import PATH_TRACE_TARGET, HopAggregate, TraceResult, TraceStats
from ..core.models import PATH_TRACE_TARGET, HopAggregate, TraceResult, TraceStats, utcnow
from ..services import trace_runner
from ..services.records import first_repeated_edge
from ..services.topology import render_forced_spec
@@ -1584,6 +1585,47 @@ def _best_observed(topo: Any, target_hash: str) -> tuple[tuple[str, ...], str] |
return scenario.hops, source
def _best_outbound(
topo: Any,
target_hash: str,
outbound: tuple[tuple[str, ...], ...],
silent_before: datetime,
choice: Any,
) -> tuple[tuple[str, ...], str] | None:
"""The best route to ``target_hash`` through an outbound path of the user, if one exists.
The ranking is :meth:`~meshterm.services.topology.MeshTopology.outbound_scenarios`:
the best score from the link after the path, the order of the user in a near tie, and
no path whose first hop went silent. The source line names the path and where the list
came from (``outbound path 1 · Foulab · 3× · −7 dB``).
Args:
topo: The newly built evidence graph.
target_hash: The hex hash of the target (any width ≥ 1 byte).
outbound: The outbound paths that apply, as canonical ids.
silent_before: The time before which a first hop counts as silent.
choice: The :class:`~meshterm.core.outbound_store.OutboundChoice` that gave the
paths, for the name of the site or the fixed device.
Returns:
``(outbound_hops, provenance)``, or ``None`` when no outbound path reaches the
target.
"""
target_id = topo.canonical(target_hash) or target_hash[:12]
found = topo.outbound_scenarios(target_id, outbound, silent_before=silent_before)
if not found:
return None
best = found[0]
source = f"outbound path {best.rank}"
if choice is not None and choice.name:
source += f" · {choice.name}"
if best.samples:
source += f" · {best.samples}×"
if best.weakest_snr is not None:
source += f" · {best.weakest_snr:+.0f} dB"
return best.hops, source
def _scenario_path(
scenario: Any,
topo: Any,
@@ -1637,7 +1679,9 @@ def _scenario_detail(scenario: Any) -> Text:
``unobserved`` when the evidence graph has no information about the route yet.
"""
atoms: list[Text] = [hops_atom(len(scenario.hops))]
if scenario.source == "device":
if scenario.source in ("device", "outbound"):
# An outbound route is a claim about where its first hops came from, the same as
# the device route: the user named them (refer to MeshTopology.outbound_scenarios).
atoms.append(Text(scenario.label, style="accent"))
if scenario.weakest_snr is not None:
snr = Text("weakest ", style="muted")
@@ -1834,18 +1878,42 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st
# that the device learned, when it really has one. If not, the outbound leg of the
# last successful stored walk (the route that the screen shows). If not, the bare
# destination: a direct attempt, which says clearly that it is one.
#
# The outbound paths of the user come before all of these, with one exception: a
# device route that starts with one of them. The firmware learns its route from floods
# that our node received, and a radio link is not symmetric (refer to
# meshterm.core.outbound_store).
# To make hop hashes canonical, only the contact index is necessary. Thus an *empty*
# graph does it. The full evidence build of fresh_topology() (stored traces, packet
# paths, neighbour tables) is necessary only for a suggestion from the evidence.
ident = MeshTopology(device_hash or "local", contacts)
store = getattr(ctx, "outbound_store", None)
choice = store.lookup(device_hash) if store is not None else None
outbound = (
tuple(tuple(ident.canonical(h) or h for h in path) for path in choice.paths)
if choice is not None
else ()
)
silent_before = utcnow() - timedelta(hours=ctx.preferences.outbound_silent_hours)
device_route: tuple[str, ...] | None = None
if target_contact is not None and target_contact.route_hops is not None:
# To make hop hashes canonical, only the contact index is necessary. Thus an
# *empty* graph does it. The full evidence build of fresh_topology() (stored
# traces, packet paths, neighbour tables) is not necessary, because this
# branch does not read it.
ident = MeshTopology(device_hash or "local", contacts)
device_route = tuple(ident.canonical(h) or h for h in target_contact.route_hops)
device_first = device_route is not None and (
not outbound or any(device_route[: len(path)] == path for path in outbound)
)
auto_hops: tuple[str, ...] | None = None
auto_source = ""
if target_hash is not None:
if device_route is not None:
through = (
None
if device_first or not outbound
else _best_outbound(fresh_topology(), target_hash, outbound, silent_before, choice)
)
if device_first:
auto_hops, auto_source = device_route, "device route"
elif through is not None:
auto_hops, auto_source = through
elif device_route is not None:
auto_hops, auto_source = device_route, "device route"
elif (observed := _best_observed(fresh_topology(), target_hash)) is not None:
# The firmware has no route, but the evidence of the recorder gives one: the
@@ -2062,6 +2130,7 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st
cursor=seed_cursor,
fetch_nodes=frozenset(fetchable),
resolve=resolve, # name a hop that the topology left ambiguous, as we do
outbound_paths=outbound, # the user's ways out lead the first slot
)
result = await session.run_screen(screen)
if result is CANCEL:
@@ -2291,7 +2360,9 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st
return None
topo = fresh_topology()
target_id = topo.canonical(target_hash) or target_hash[:12]
scenarios = topo.scenarios(target_id, device_route=device_route)
scenarios = topo.scenarios(
target_id, device_route=device_route, outbound=outbound, silent_before=silent_before
)
if not scenarios:
await session.message_dialog(
Text(
+7
View File
@@ -723,6 +723,12 @@ async def open_tx_optimize(
neighbour_links=ctx.repo.neighbour_links(),
)
admin_id = topo.canonical(admin_hash) or admin_hash[:12]
# The user's ways out lead the first slot, as on the trace screens.
store = getattr(ctx, "outbound_store", None)
choice = store.lookup(device_hash) if store is not None else None
outbound = tuple(
tuple(topo.canonical(h) or h for h in path) for path in (choice.paths if choice else ())
)
composer = PathComposerScreen(
device_label=device_label,
device_hash=device_hash,
@@ -733,6 +739,7 @@ async def open_tx_optimize(
target_label=admin_node.name,
hops=[topo.canonical(h) or h for h in screen.route_hops],
resolve=resolve, # name a hop that the topology left ambiguous, as we do
outbound_paths=outbound,
)
result = await session.run_screen(composer)
if result is CANCEL or not isinstance(result, str):
+77
View File
@@ -1292,6 +1292,80 @@ def _path_composer(cols: int, rows: int) -> Screen:
)
def _outbound_env(): # noqa: ANN202 - a private type of the module under test
"""The session values of the Outbound paths pages: two nodes, and one trace through both."""
from meshterm.persistence.repository import TracedPath
from meshterm.services.outbound import DeviceIdentity
from meshterm.ui.outbound_screen import _Env
hub = Contact(name="Hilltop-Repeater", public_key=_HUB_KEY, key_prefix="3d63c6429436")
far = Contact(name="Alice", public_key=_FAR_KEY, key_prefix="f2c24f54551e")
self_key = "aaaaaaaaaaaa" + "0" * 52
walk = TracedPath(when=utcnow(), hops=[("3d", 9.5), ("f2", -4.0), ("3d", -3.5), (None, 11.0)])
topo = build_topology(
self_id=self_key,
contacts=[hub, far],
trace_paths=[walk] * 1200, # a count of four digits, the widest that the lane draws
packet_paths=[],
neighbour_links=[],
)
return _Env(DeviceIdentity(self_key, "Homestead"), [hub, far], topo, 1)
def _outbound_store(): # noqa: ANN202
"""Two sites (one with a name of the longest length) and a fixed device."""
from meshterm.core.outbound_store import OutboundStore
store = OutboundStore(Path(tempfile.mkdtemp(prefix="meshterm-gallery-outbound-")) / "o.json")
store.put_site("Home", [("3d63c6429436",), ("3d63c6429436", "f2c24f54551e", "9a9a")])
store.put_site("A-site-named-24-chars-xx", [("f2c24f54551e",)])
store.set_active("Home")
store.fix_device("bb" * 32, "Rooftop-Companion-Unit", [("3d63c6429436",)])
return store
def _outbound_page(cols: int, rows: int) -> Screen:
"""The Outbound paths page: sites, the active mark, and a fixed device."""
from meshterm.ui.outbound_screen import _PAGE_HINT, _page
title, prompt, items = _page(_outbound_store(), _outbound_env())
return SelectScreen(title, items, prompt=prompt, footer_hint=_PAGE_HINT, filterable=False)
def _outbound_site(cols: int, rows: int) -> Screen:
"""The page of the active site with staged changes: paths, evidence, actions, Apply."""
from meshterm.ui.outbound_screen import (
_EDIT_HINT,
_editor_items,
_site_actions,
_site_summary,
)
store = _outbound_store()
paths = store.site("Home").paths
return SelectScreen(
"Site — Home",
_editor_items(_outbound_env(), paths, _site_actions(store, "Home"), 2),
prompt=_site_summary(store, "Home", paths),
footer_hint=_EDIT_HINT,
filterable=False,
delete_hint="Del remove",
)
def _outbound_composer(cols: int, rows: int) -> Screen:
"""The composer in outbound mode: an open path of two hops."""
env = _outbound_env()
return PathComposerScreen(
device_label="Homestead",
device_hash=env.identity.key,
topology=env.topology,
width_bytes=1,
hops=["3d63c6429436", "f2c24f54551e"],
outbound=True,
)
class _CourierStubDevice:
async def get_contacts(self) -> list:
return []
@@ -1878,6 +1952,9 @@ _ENTRIES: list[_Entry] = [
_Entry("message_paths_sent_scope", _message_paths_sent_scope),
_Entry("remote_cli", _remote_cli),
_Entry("path_composer", _path_composer),
_Entry("outbound_composer", _outbound_composer),
_Entry("outbound_page", _outbound_page),
_Entry("outbound_site", _outbound_site),
_Entry("courier_outbox", _courier_outbox),
_Entry("record_dialog", _record_dialog),
_Entry("record_route", _record_route),
+4 -3
View File
@@ -182,8 +182,9 @@ def test_main_menu_sections_answer_the_menus_own_question() -> None:
The menu asks "What would you like to do?". Thus the groups are by verb and not by
subject. The address book is with the features that send messages from it. The recorded
history is with the live views, because it is their past tense. The two walks are with
the topology that they walk over. A setting goes in the section that says whose it is:
this radio, the radio of another node over the mesh, or MeshTerm itself.
the topology that they walk over. The outbound paths are with the two trace tools that
start their routes on them. A setting goes in the section that says whose it is: this
radio, the radio of another node over the mesh, or MeshTerm itself.
This app is the last of these three sections, and this is the reason that it sorts last.
It holds the preferences that change the program, the diagnostics that state what the
@@ -203,7 +204,7 @@ def test_main_menu_sections_answer_the_menus_own_question() -> None:
assert sections == {
"Message": ["chat", "channels", "rooms", "courier", "contacts"],
"Watch": ["dashboard", "livefeed", "watchtower", "clocks", "timemachine"],
"Explore": ["map", "walk", "trace", "trace-path", "records"],
"Explore": ["map", "walk", "trace", "trace-path", "outbound", "records"],
"This node": ["info", "config", "advert"],
"Managed nodes": ["repeater-admin", "tx-optimize", "forget-admin-passwords"],
"This app": [
+119
View File
@@ -0,0 +1,119 @@
# SPDX-License-Identifier: Apache-2.0
"""Tests for the Outbound paths pages: the rows, the evidence line, and the measure walk."""
from __future__ import annotations
from pathlib import Path
from meshterm.core.models import Contact, Hop, TraceResult, utcnow
from meshterm.core.outbound_store import OutboundStore
from meshterm.persistence.repository import TracedPath
from meshterm.services.outbound import DeviceIdentity, FirstLink, first_link
from meshterm.services.topology import build_topology
from meshterm.ui.outbound_screen import (
_count,
_editor_items,
_Env,
_evidence,
_measured,
_page,
_site_actions,
measure_walk,
)
from meshterm.ui.tui.select import Choice
US = "aaaaaaaaaaaa" + "0" * 52
HUB = Contact(name="Hub", public_key="3d63c6429436" + "0" * 52, key_prefix="3d63c6429436")
FAR = Contact(name="Far", public_key="f2c24f54551e" + "0" * 52, key_prefix="f2c24f54551e")
def _env(walks: int = 3) -> _Env:
"""A session with one trace walk through Hub to Far, repeated."""
walk = TracedPath(when=utcnow(), hops=[("3d", 9.0), ("f2", -4.0), ("3d", -3.0), (None, 11.0)])
topo = build_topology(
self_id=US, contacts=[HUB, FAR], trace_paths=[walk] * walks, packet_paths=[]
)
return _Env(DeviceIdentity(US, "Me"), [HUB, FAR], topo, 1)
def _plain(items: list) -> list[str]:
"""The text of each row and separator, as the user reads it."""
out = []
for item in items:
if isinstance(item, Choice):
text = item.text(200)
else:
text = item.title(200) if callable(item.title) else item.title
out.append(text if isinstance(text, str) else text.plain)
return out
def test_measure_walk_turns_at_the_last_hop() -> None:
"""Out along the path and back the same way: each link in both directions."""
assert measure_walk(("a1",)) == ("a1",)
assert measure_walk(("a1", "b2", "c3")) == ("a1", "b2", "c3", "b2", "a1")
def test_first_link_keeps_the_two_directions_apart() -> None:
"""OUT is what the first hop measured from us. IN is what we measured from it."""
link = first_link(_env().topology, ("3d63c6429436", "f2c24f54551e"))
assert (link.out_snr, link.out_count, link.in_snr, link.in_count) == (9.0, 3, 11.0, 3)
assert first_link(_env().topology, ("9a9a",)) == FirstLink()
def test_the_evidence_line_names_both_directions_or_says_there_is_none() -> None:
"""The line under a path reads ``out … · in … · age``, or says that nothing is known."""
line = _evidence(FirstLink(9.0, 12, None, 0, utcnow())).plain
assert line.strip().startswith("out +9 dB ×12 · in -")
assert "no readings" in _evidence(FirstLink()).plain
assert [_count(n) for n in (12, 980, 2140, 14600)] == ["12", "980", "2.1k", "14k"]
def test_the_tool_page_marks_the_active_site_and_offers_to_fix_the_device(tmp_path: Path) -> None:
"""Sites first, with ✓ on the active one, then the fixed devices and the fix row."""
store = OutboundStore(tmp_path / "o.json")
store.put_site("Home", [("3d63c6429436",)])
store.put_site("Lab", [])
store.set_active("Home")
title, prompt, items = _page(store, _env())
rows = _plain(items)
assert (title, prompt) == ("Outbound paths", "Now: site Home")
assert any(row.startswith("✓ Home") and "1 path" in row for row in rows)
assert any("Fix Me…" in row for row in rows)
store.fix_device(US, "Me", [])
_, prompt, items = _page(store, _env())
assert prompt.startswith("Now: Me's own paths")
assert not any("Fix Me…" in row for row in _plain(items))
def test_the_editor_shows_apply_only_with_staged_changes(tmp_path: Path) -> None:
"""An editor ends on its last action until a change is staged, then on Apply over Back."""
store = OutboundStore(tmp_path / "o.json")
store.put_site("Home", [("3d63c6429436",)])
clean = _plain(_editor_items(_env(), [("3d63c6429436",)], _site_actions(store, "Home"), 0))
assert not any("Apply" in row for row in clean)
assert any("Use this site" in row for row in clean)
staged = _plain(_editor_items(_env(), [], _site_actions(store, "Home"), 1))
assert any("Apply 1 staged change" in row for row in staged)
assert any("none yet" in row for row in staged)
def test_a_measure_says_who_heard_whom() -> None:
"""Each hop of the reply is one line: the receiver, the sender, and the SNR."""
walk = measure_walk(("3d63c6429436", "f2c24f54551e"))
result = TraceResult(
target="(path)",
success=True,
hops=[Hop(0, None, 9.0), Hop(1, None, -4.0), Hop(2, None, -3.0), Hop(3, None, 11.0)],
round_trip_ms=1500.0,
)
lines = _measured(_env(), walk, result).plain.splitlines()
assert lines == [
"✓ the trace came back in 1.5 s",
"Hub heard you at +9.0 dB",
"Far heard Hub at -4.0 dB",
"Hub heard Far at -3.0 dB",
"you heard Hub at +11.0 dB",
]
failed = TraceResult(target="(path)", success=False)
assert _measured(_env(), walk, failed).plain.startswith("✗ no reply")
+97
View File
@@ -0,0 +1,97 @@
# SPDX-License-Identifier: Apache-2.0
"""Tests for the site suggestion: what counts as heard, and when a suggestion is due."""
from __future__ import annotations
from meshterm.core.models import Observation
from meshterm.core.outbound_store import Site
from meshterm.services.site_suggest import HEARD_TO_SUGGEST, SiteSuggestion, SiteWatch, heard_hop
HOME = Site("Home", [("3d63c6429436",), ("27d4396a2967", "f2c24f54551e")])
LAB = Site("Foulab", [("a100008dc55e", "b2b2")])
def test_the_heard_node_is_the_last_relay_or_the_sender() -> None:
"""A relayed packet names its last relay. A direct packet names its sender."""
assert heard_hop(Observation(node="aa", kind="packet", path="11,22,A1")) == "a1"
assert heard_hop(Observation(node="BB", kind="packet", path="")) == "bb"
assert heard_hop(Observation(node="cc", kind="advert", path=None)) is None
assert heard_hop(Observation(node=None, kind="packet", path="")) is None
def test_three_packets_from_another_sites_first_hop_make_a_suggestion() -> None:
"""The first hop of the Foulab path, heard three times, suggests Foulab."""
watch = SiteWatch([HOME, LAB], "Home")
for _ in range(HEARD_TO_SUGGEST - 1):
assert watch.note("a1") is None # a 1-byte hash matches the stored key prefix
assert watch.note("a100") == SiteSuggestion("Foulab", "a100008dc55e", HEARD_TO_SUGGEST)
assert watch.settled
assert watch.note("a1") is None # one question for each session
def test_a_first_hop_of_the_active_site_settles_the_question() -> None:
"""Once the radio hears the way out of the active site, there is nothing to suggest."""
watch = SiteWatch([HOME, LAB], "home")
watch.note("a1")
assert watch.note("27d4") is None
assert watch.settled
assert all(watch.note("a1") is None for _ in range(5))
def test_a_hop_that_is_not_a_first_hop_counts_for_nothing() -> None:
"""Only the first hop of a path says where the radio is: the second hop is far away."""
watch = SiteWatch([HOME, LAB], "Home")
assert all(watch.note("b2b2") is None for _ in range(5))
assert not watch.settled
async def test_the_service_keeps_one_suggestion_for_the_menu(tmp_path) -> None: # noqa: ANN001
"""Packets from the hub make a pending suggestion, unless the connected device is fixed."""
from types import SimpleNamespace
from meshterm.core.events import MeshEvent
from meshterm.core.outbound_store import OutboundStore
from meshterm.services.site_suggest import SiteSuggester
store = OutboundStore(tmp_path / "o.json")
store.put_site("Home", list(HOME.paths))
store.put_site("Foulab", list(LAB.paths))
store.set_active("Home")
handlers: list = []
async def self_info() -> dict:
return {"public_key": "c0" * 32}
ctx = SimpleNamespace(
preferences=SimpleNamespace(suggest_site=True),
outbound_store=store,
events=SimpleNamespace(subscribe=lambda handler, *kinds: handlers.append(handler) or None),
devstate=SimpleNamespace(self_info=self_info),
)
service = SiteSuggester(ctx)
ready: list = []
service.on_ready = lambda: ready.append(True)
await service.start()
packet = MeshEvent.observation_event(Observation(node="99", kind="packet", path="77,a1"))
pending = [handlers[0](packet) for _ in range(HEARD_TO_SUGGEST)]
assert pending[:-1] == [None, None]
await pending[-1]
assert ready == [True]
assert service.take() == SiteSuggestion("Foulab", "a100008dc55e", HEARD_TO_SUGGEST)
assert service.take() is None # one time only
store.fix_device("c0" * 32, "Roof", [])
fixed = SiteSuggester(ctx)
handlers.clear()
await fixed.start()
last = [handlers[0](packet) for _ in range(HEARD_TO_SUGGEST)][-1]
await last
assert fixed.take() is None # the active site does not apply to a fixed device
def test_with_no_active_site_any_site_can_be_suggested_and_one_site_needs_no_watch() -> None:
"""No active site: the first site heard is suggested. A single active site settles at once."""
watch = SiteWatch([HOME, LAB], None)
suggestions = [watch.note("3d") for _ in range(HEARD_TO_SUGGEST)]
assert suggestions[-1] == SiteSuggestion("Home", "3d63c6429436", HEARD_TO_SUGGEST)
assert SiteWatch([HOME], "Home").settled
+145
View File
@@ -247,6 +247,101 @@ def test_coalesce_keeps_the_direction_of_the_readings_of_a_stub() -> None:
assert sorted(topo.readings(far, leaf)) == [-4.5, -3.5]
# --- outbound paths -----------------------------------------------------------------
HUB, LEAF_ID, FAR_ID = "3d63c6429436", "27d4396a2967", "f2c24f54551e"
def _two_ways(strong: int = 5, weak: int = 1, weak_age_hours: float = 0.0): # noqa: ANN202
"""Two ways to Far: through Hub (strong, often heard) and through Leaf (weak)."""
return _topo(
trace_paths=[
*[_traced(("3d", 12.0), ("f2", 10.0), ("3d", 10.0), (None, 12.0))] * strong,
*[_traced(("27", 2.0), ("f2", 0.0), ("27", 0.0), (None, 2.0), age_hours=weak_age_hours)]
* weak,
]
)
def test_an_outbound_path_starts_the_routes_although_the_evidence_prefers_another() -> None:
"""The user knows the way out. The graph ranks a first hop by what our node heard."""
topo = _two_ways()
assert topo.scenarios(FAR_ID)[0].hops != (LEAF_ID,) # the evidence alone prefers Hub
first = topo.scenarios(FAR_ID, outbound=[(LEAF_ID,)])[0]
assert (first.source, first.hops, first.rank) == ("outbound", (LEAF_ID,), 1)
assert topo.suggested(FAR_ID, outbound=[(LEAF_ID,)]).hops == (LEAF_ID,)
def test_a_target_inside_an_outbound_path_is_reached_along_the_path() -> None:
"""A route to a hop of the path is the part of the path before it, and it is trusted."""
topo = _two_ways()
(scenario,) = topo.outbound_scenarios(FAR_ID, [(LEAF_ID, FAR_ID, HUB)])
assert scenario.hops == (LEAF_ID,)
assert scenario.score > topo.scenarios(FAR_ID)[0].score
def test_the_best_score_wins_and_the_order_of_the_user_breaks_a_near_tie() -> None:
"""A much better second path wins. Two paths that score the same keep the user's order."""
topo = _two_ways(strong=5, weak=1)
ranked = topo.outbound_scenarios(FAR_ID, [(LEAF_ID,), (HUB,)])
assert [s.hops for s in ranked] == [(HUB,), (LEAF_ID,)] # Hub is far stronger
even = _topo(
trace_paths=[
_traced(("3d", 5.0), ("f2", 5.0), ("3d", 5.0), (None, 5.0)),
_traced(("27", 5.0), ("f2", 5.0), ("27", 5.0), (None, 5.0)),
]
)
assert [s.hops for s in even.outbound_scenarios(FAR_ID, [(LEAF_ID,), (HUB,)])] == [
(LEAF_ID,),
(HUB,),
]
assert [s.hops for s in even.outbound_scenarios(FAR_ID, [(HUB,), (LEAF_ID,)])] == [
(HUB,),
(LEAF_ID,),
]
def test_an_outbound_path_whose_first_hop_went_silent_is_skipped() -> None:
"""A first hop that our node did not hear for too long is probably off, or out of reach."""
topo = _two_ways(weak_age_hours=48.0)
quiet_since = utcnow() - timedelta(hours=24)
assert topo.outbound_scenarios(FAR_ID, [(LEAF_ID,)], silent_before=quiet_since) == []
assert topo.outbound_scenarios(FAR_ID, [(LEAF_ID,)]) # with no window, it stays
unknown = topo.outbound_scenarios(FAR_ID, [("9a9a",)], silent_before=quiet_since)
assert unknown == [] # no evidence at all is not silence, but no route continues from it
def test_outbound_routes_go_before_a_device_route_that_starts_elsewhere() -> None:
"""The firmware learns its route from what our node received. The user's way out wins."""
topo = _two_ways()
elsewhere = topo.scenarios(FAR_ID, device_route=(HUB,), outbound=[(LEAF_ID,)])
assert [s.source for s in elsewhere[:2]] == ["outbound", "device"]
agreed = topo.scenarios(FAR_ID, device_route=(LEAF_ID,), outbound=[(LEAF_ID,)])
assert agreed[0].hops == (LEAF_ID,) # the device learned the user's way out
assert [s.hops for s in agreed].count((LEAF_ID,)) == 1
def test_a_first_link_is_scored_by_how_well_the_far_end_hears_us() -> None:
"""Our node hears Hub well, but Hub hears our node badly. Leaf is the better way out."""
packets = [
*[PacketPath(when=utcnow(), origin=None, snr=10.0, hops=[HUB])] * 20,
*[PacketPath(when=utcnow(), origin=None, snr=2.0, hops=[LEAF_ID])] * 20,
]
walks = [
_traced(("3d", -12.0), ("f2", 5.0), ("3d", 5.0), (None, 10.0)),
_traced(("27", 8.0), ("f2", 5.0), ("27", 5.0), (None, 2.0)),
]
topo = _topo(trace_paths=walks, packet_paths=packets)
us = topo.self_id
assert topo.link(us, HUB).median_snr > topo.link(us, LEAF_ID).median_snr # the pool
assert [s.node for s in topo.next_hops(us)][:2] == [LEAF_ID, HUB]
assert topo.scenarios(FAR_ID)[0].hops == (LEAF_ID,)
# Away from our node, the pooled strength is unchanged.
assert topo.outward_strength(HUB, FAR_ID, topo.link(HUB, FAR_ID)) == topo.link(
HUB, FAR_ID
).strength(topo._now)
# --- suggestions and scenarios ----------------------------------------------------
@@ -797,6 +892,56 @@ def test_composer_path_mode_opens_star_to_star_without_auto(monkeypatch) -> None
assert "Auto" not in _rows_plain(screen)
async def test_composer_outbound_mode_returns_full_ids_and_keeps_its_end_open(
monkeypatch, # noqa: ANN001
) -> None:
"""An outbound path has no return, no node two times, and the full id of each hop."""
import asyncio
monkeypatch.setattr(pathline, "powerline_enabled", lambda: False) # assert the words
walks = [_traced(("3d", 12.0), ("f2", 5.0), ("3d", 5.0), (None, 12.0))]
topo = _topo(trace_paths=walks)
screen = PathComposerScreen(
device_label="Me", topology=topo, width_bytes=1, hops=["3d63c6429436"], outbound=True
)
assert screen.title == "Compose outbound path"
preview = screen._route_preview().text().plain
assert preview.endswith(f"{CURSOR_GLYPH} →") # open: the route goes on from here
assert SELF_GLYPH not in preview[1:] # our node only at the start
suggested = [s.node for s in screen._suggestions()]
assert "3d63c6429436" not in suggested and "f2c24f54551e" in suggested
screen.future = asyncio.get_running_loop().create_future()
screen.handle("enter") # the top suggestion: Far
screen.handle("end")
screen.handle("enter") # Use this path
assert screen.future.result() == "3d63c6429436,f2c24f54551e"
def test_composer_offers_the_outbound_paths_first_at_our_node_only() -> None:
"""At our node, the user's ways out lead the rows. Enter inserts the whole path."""
walks = [_traced(("3d", 12.0), ("f2", 5.0), ("3d", 5.0), (None, 12.0))]
topo = _topo(trace_paths=walks)
screen = PathComposerScreen(
device_label="Me",
topology=topo,
width_bytes=1,
outbound_paths=((LEAF_ID, HUB), (FAR_ID,)),
)
kinds = [kind for kind, _ in screen._rows()]
assert kinds[:2] == ["outbound", "outbound"]
assert "your paths first" in _rows_plain(screen)
screen.handle("enter") # outbound path 1: Leaf → Hub
assert screen.hops == [LEAF_ID, HUB]
assert "outbound" not in [kind for kind, _ in screen._rows()] # the slot left our node
screen.handle("left")
screen.handle("left") # back at our node, but path 1 is in the route already
assert [p for kind, p in screen._rows() if kind == "outbound"] == [(2, (FAR_ID,))]
outbound_mode = PathComposerScreen(
device_label="Me", topology=topo, width_bytes=1, outbound=True, outbound_paths=((HUB,),)
)
assert "outbound" not in [kind for kind, _ in outbound_mode._rows()]
def test_composer_names_an_ambiguous_hop_through_the_owning_screens_resolver() -> None:
"""A short hop that the topology does not name still shows a name, with its hash beside it.