Node detail: a full-screen page for each contact, reached by Enter

Pressing Enter on a contact now opens its whole story on one page instead of
a bare row: identity (name in its hue, key with the routing hash lit, type,
first/last heard, packet tally, reception SNR/RSSI), an inline location
preview centred on the node (a small static basemap via the new MiniMap), the
observed routes to it, and an action list (trace armed with the suggested best
path, open full map, time machine). Contacts owns the show/open/reshow loop;
topology.suggested answers "the best evidence-backed way to reach this node",
wired ahead of the firmware route in the trace arming precedence. Timemachine
and Trace grew the entry points the page opens.

Four fixes fell out of driving it on real hardware:

Slow open. Each located-node page built a fresh BasemapSource and resolved its
TileJSON -- a blocking HTTPS round-trip (~100ms, up to the 12s timeout on a bad
link) -- on every open. Hold one source for the session (ctx.basemap_source),
shared by the map, the picker, and the preview, and warm it behind the menu at
login, so the resolve is paid once, off the navigation path.

Black map. A companion advertising nonsense coordinates (Homestead reports
lat -97, lon -1042) flung the viewport off the world, leaving the map a screen
of empty/water fill that reads as solid black -- both from "open full map" and
from filtering to it and framing. The old guard only caught the 0/0 no-GPS
null island; the new geo.usable_fix() rejects any out-of-range fix too, applied
to the map markers and the location preview alike. Verified on-device: of 265
located contacts, only Homestead drops.

Path to node. The route/suggest rows render through THE path widget with a
1-byte hash in parentheses (a "name (3d)" tag), so they cross-read hop for hop
against the route graph's byte labels.

Route graph. Draw us on the left and the target on the right (us to target,
"how we reach it", left to right) via a local endpoint swap that leaves the
shared route_graph_style untouched for its other callers, and give the fan a
generous lane step and row budget so a well-connected node's candidate paths
spread into separate, legible tracks instead of a cramped tangle -- the height
stays adaptive, so a one- or two-route node still draws compact.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 4.8 committed 2026-07-19 23:41:52 -04:00
1 parent 198111095a
commit 62a2d76e8c
15 files changed
+1463 -48

No files matched your search

+20
View File
@@ -33,6 +33,7 @@ if TYPE_CHECKING:
from .services.courier import CourierService
from .services.monitor_service import MonitorService
from .services.watchtower import WatchtowerService
from .services.basemap import BasemapSource
from .services.battery_service import BatteryService
from .services.device_state import DeviceState
from .ui.surface import Ui
@@ -117,6 +118,7 @@ class AppContext:
_courier: "Optional[CourierService]" = field(default=None, init=False, repr=False)
_battery: "Optional[BatteryService]" = field(default=None, init=False, repr=False)
_devstate: "Optional[DeviceState]" = field(default=None, init=False, repr=False)
_basemap_source: "Optional[BasemapSource]" = field(default=None, init=False, repr=False)
_ui: "Optional[Ui]" = field(default=None, init=False, repr=False)
def __post_init__(self) -> None:
@@ -345,6 +347,24 @@ class AppContext:
self._devstate = DeviceState(self)
return self._devstate
@property
def basemap_source(self) -> "BasemapSource":
"""Return the session's shared map tile source, built once and reused.
The map, the location picker, and the Node-detail location preview all draw the
same OpenStreetMap basemap; each used to build its own :class:`BasemapSource`, so
each paid the one-off TileJSON resolve — a blocking network round-trip the first
time ``.max_zoom``/``.available`` is touched — on *every* open. Holding one source
for the session means that resolve happens once (warmed behind the menu, see
:func:`meshterm.ui.menu._warm_basemap`), and the on-disk tile cache is shared too.
Independent of the radio link, so it survives reconnects untouched.
"""
if self._basemap_source is None:
from .services.basemap import BasemapSource
self._basemap_source = BasemapSource(self.settings.config_dir / "tilecache")
return self._basemap_source
@property
def log(self): # type: ignore[no-untyped-def]
"""The application logger."""
+22
View File
@@ -112,6 +112,28 @@ def clamp_lat(lat: float) -> float:
return max(-85.05112878, min(85.05112878, lat))
def usable_fix(lat: float, lon: float) -> bool:
"""Whether an advertised ``(lat, lon)`` is a real position worth plotting.
A node's advert location is only usable if it is a genuine fix. Two ways it isn't:
* **out of range** — latitude must sit within ±90° and longitude within ±180°.
Some firmware/adverts report nonsense (a MeshCore companion has been seen
advertising ``lat -97, lon -1042``); projecting that flings the view off the
world, leaving the map a screen of empty/water fill that reads as solid black.
* **null island** — a companion with no GPS lock advertises latitude and
longitude both zero, which projects to the empty mid-Atlantic. Plotting a node
there is worse than useless: framing only it drops the whole view onto open
ocean (again, solid-water black).
Either way the fix is treated as absent, so the node simply carries no location —
the shared guard the map markers and the Node-detail location preview both apply.
"""
if not (-90.0 <= lat <= 90.0 and -180.0 <= lon <= 180.0):
return False
return not (abs(lat) < 1e-6 and abs(lon) < 1e-6)
def lonlat_to_world(lat: float, lon: float, zoom: float) -> tuple[float, float]:
"""Project ``(lat, lon)`` to Web Mercator world pixels at ``zoom``.
+27
View File
@@ -464,6 +464,33 @@ class MeshTopology:
)
return (head + rest)[:_MAX_SCENARIOS]
def suggested(self, target: str) -> Optional[PathScenario]:
"""The single best *evidence-backed* outbound route to ``target``, if one exists.
The data-driven answer to "what's the best way to reach this node?": the highest-
scoring **observed** scenario — a route through repeaters the recorder has actually
watched carry traffic (traces, overheard relay chains, fetched neighbour tables),
ranked weakest-link-first with a per-hop penalty and its links' sample counts and
median SNR behind the score. It deliberately ignores the *device* and *direct*
families :meth:`scenarios` also offers: the firmware's learned route is what an
auto-routed trace already walks (the caller prefers it when it has one), and a
direct shot is the trivial fallback — neither is a *suggestion* the observations
made. A node the evidence can only reach directly (or not at all) yields ``None``,
so the caller keeps whatever default it would have used.
Args:
target: The target's canonical id.
Returns:
The best observed :class:`PathScenario` (always with at least one intermediate
hop and a positive, evidence-backed score), or ``None`` when the observations
support nothing better than a direct route.
"""
for scenario in self.scenarios(target):
if scenario.source == "observed" and scenario.hops and scenario.score > 0:
return scenario
return None
# --- internals -----------------------------------------------------------------
def _score_route(
+5 -18
View File
@@ -22,6 +22,7 @@ from rich.table import Table
from rich.text import Text
from ..context import AppContext
from ..core.geo import usable_fix
from ..core.models import NODE_TYPE_REPEATER
from .base import Tool, ToolResult, register
@@ -195,7 +196,7 @@ async def gather_markers(ctx: AppContext) -> list["MapMarker"]:
seen: set[str] = set()
for contact in await _contacts(ctx):
if not contact.has_location or _is_null_island(contact.lat, contact.lon):
if not contact.has_location or not usable_fix(contact.lat, contact.lon):
continue
key = contact.key_prefix or (contact.public_key or "")[:12]
if key:
@@ -215,7 +216,7 @@ async def gather_markers(ctx: AppContext) -> list["MapMarker"]:
for node in observed.values():
if not node.has_location or node.node in seen:
continue
if _is_null_island(node.lat, node.lon):
if not usable_fix(node.lat, node.lon):
continue
markers.append(
MapMarker(
@@ -251,8 +252,8 @@ async def _self_marker(ctx: AppContext) -> Optional["MapMarker"]:
except Exception: # noqa: BLE001 - the map is useful without our own position
return None
lat, lon = _as_float(info.get("adv_lat")), _as_float(info.get("adv_lon"))
if lat is None or lon is None or _is_null_island(lat, lon):
return None # a device with no fix reports 0/0
if lat is None or lon is None or not usable_fix(lat, lon):
return None # a device with no fix reports 0/0 (or nonsense out-of-range)
return MapMarker(
label=str(info.get("name") or "this node"),
lat=lat,
@@ -302,20 +303,6 @@ def _signal_detail(node: object) -> str:
return detail
def _is_null_island(lat: float, lon: float) -> bool:
"""Whether a fix is the 0/0 "null island" a device reports when it has no GPS lock.
A companion without a position advertises latitude and longitude both zero, which
projects to the empty mid-Atlantic. Plotting a node there is worse than useless: the
default frame trims the far outlier away so it hides unseen, but *filtering to it and
pressing Enter* frames only that node — dropping the whole view onto open ocean, a
screen of solid water fill that reads as all black. So a both-near-zero fix counts as
no fix at all — the same guard :func:`_self_marker` applies to our own node, now shared
with the contact and heard-node markers.
"""
return abs(lat) < 1e-6 and abs(lon) < 1e-6
def _as_float(value: object) -> Optional[float]:
"""Best-effort float conversion, returning ``None`` on missing/garbage values."""
if value is None:
+33 -24
View File
@@ -3,9 +3,11 @@
The Time Machine picker's presentation pointed at the companion's contact table: the same
aligned ``NAME · HEARD · PKTS · KEY`` lanes, our own node pinned first, the same Ctrl+arrow
sort (now including the key column) and type-to-filter — one contact list app-wide, whatever
the data source (see :mod:`~meshterm.ui.contactlist`). Enter is deliberately inert for now: the
highlight is a cursor, not yet a selection — a per-contact action will land on it later. The
one-shot CLI (``meshterm contacts --sort …``) still renders the static
the data source (see :mod:`~meshterm.ui.contactlist`). Enter opens the highlighted node's
full-screen Node detail page (:mod:`~meshterm.ui.node_detail_screen`) — its identity, a
location preview, the observed routes to it, and the ways in (trace, map, time machine) —
and backing out of that page returns to the list right where it stood. The one-shot CLI
(``meshterm contacts --sort …``) still renders the static
:func:`~meshterm.ui.widgets.contacts_table`; only the menu gets the live list.
"""
@@ -14,6 +16,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from .contactlist import ContactListScreen, ContactRow
from .tui.screen import CANCEL
from .widgets import ContactsSort, _contact_pkts
if TYPE_CHECKING:
@@ -21,16 +24,17 @@ if TYPE_CHECKING:
from ..core.models import Contact
#: A stable identity for the own-node row (its lane data has no key to stand on when no
#: device answered), so a re-sort can keep the highlight on it.
#: device answered) — Enter on it opens our own node's detail page.
YOU = ("you",)
#: The Contacts list's footer: the shared list's grammar minus the Enter atom — pressing it
#: does nothing yet, so the hint doesn't advertise it.
_HINT = "↑↓ move · ^←→↑↓ sort · type filter · Esc back"
class ContactsScreen(ContactListScreen):
"""A full-screen, Ctrl+arrow-sortable list of this node and its known contacts."""
"""A full-screen, Ctrl+arrow-sortable list of this node and its known contacts.
Enter resolves the highlighted row — our own node (:data:`YOU`) or a
:class:`~meshterm.core.models.Contact` — for :func:`open_contacts` to open in the
Node detail page; the shared list handles the sort, filter, and navigation.
"""
def __init__(
self,
@@ -58,7 +62,9 @@ class ContactsScreen(ContactListScreen):
for c in contacts:
rows.append(
ContactRow(
value=c.public_key or c.name,
# The contact itself is the row's identity, so Enter hands the whole
# record straight to the detail page — no re-lookup by name/key.
value=c,
name=c.name,
key=c.public_key,
node_type=c.node_type,
@@ -71,19 +77,8 @@ class ContactsScreen(ContactListScreen):
rows=rows,
prefix_bytes=prefix_bytes,
sort=sort,
footer_hint=_HINT,
)
def handle(self, action: str, data: str = "") -> None:
"""Swallow Enter; every other key is the shared list's.
The highlight is only a cursor until per-contact actions land, so committing it
must neither act nor dismiss the screen — only Esc leaves.
"""
if action == "enter":
return
super().handle(action, data)
async def open_contacts(
ctx: "AppContext",
@@ -94,7 +89,11 @@ async def open_contacts(
counts: dict[str, int],
sort: ContactsSort,
) -> None:
"""Open the interactive, sortable contacts list and run until dismissed with Esc.
"""Open the interactive contacts list; Enter opens Node detail, Esc leaves.
Runs the show/open/reshow loop: the sortable list, then whichever node's detail page
Enter commits, then the list again (same sort, the highlight kept on its row) — until
Esc backs out of the list itself.
Args:
ctx: Shared application context (must be in the interactive menu).
@@ -103,14 +102,24 @@ async def open_contacts(
contacts: Known contacts to list under our own node.
prefix_bytes: Path-hash width in bytes to highlight in every key.
counts: Overheard-packet counts keyed by lowercased 12-hex node id.
sort: The initial sort (column + direction) over the shared list's ring.
sort: The initial sort (column + direction) over the shared list's ring — mutated
in place, so a re-sort survives visiting a detail page and coming back.
Raises:
RuntimeError: If called outside the interactive menu (no full-screen session).
"""
from .node_detail_screen import open_node_detail
from .surface import TuiUi
if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller
raise RuntimeError("the interactive contacts list is only available in the menu")
session = ctx.ui.session
# One screen for the whole visit: re-running it keeps the highlight (and any sort or
# filter) on the row the user just opened a detail for, rather than snapping to the top.
screen = ContactsScreen(self_name, self_key, contacts, prefix_bytes, counts, sort)
await ctx.ui.session.run_screen(screen)
while True:
chosen = await session.run_screen(screen)
if chosen is CANCEL or chosen is None:
return
# The own-node sentinel opens our own node's page; any other value is a Contact.
await open_node_detail(ctx, None if chosen == YOU else chosen)
+6 -2
View File
@@ -500,8 +500,12 @@ async def pick_location(
def basemap_source(ctx: "AppContext") -> BasemapSource:
"""Build the vector-tile source backed by the app's on-disk tile cache."""
return BasemapSource(ctx.settings.config_dir / "tilecache")
"""The session's shared vector-tile source (see :attr:`AppContext.basemap_source`).
Memoized on the context, so the one-off TileJSON resolve is paid once for the whole
session instead of on every map open or Node-detail location preview.
"""
return ctx.basemap_source
async def open_map(
+24
View File
@@ -620,6 +620,12 @@ async def _resume_monitor(ctx: AppContext) -> None:
await ctx.chat.start()
except Exception: # noqa: BLE001 - surface via the header, don't crash the menu
pass
# Warm the map tile source's metadata behind the menu too: the first ``.max_zoom`` touch
# resolves the TileJSON over the network, and the Map / Node-detail location preview would
# otherwise pay that round-trip on the navigation path (a stall on opening a located node's
# page). The tile source is independent of the radio link, so this runs regardless of
# connect state — offline it just fails quietly and the map falls back to a default zoom.
_warm_basemap(ctx)
# Warm the slow session caches (contacts, the channel-slot probe) behind the menu now that
# the link is up, so the first Chat/Trace/Dashboard open is served from cache instead of
# paying those round-trips in the navigation path — one quiet wait after login rather than a
@@ -629,6 +635,24 @@ async def _resume_monitor(ctx: AppContext) -> None:
ctx.devstate.prewarm()
def _warm_basemap(ctx: AppContext) -> None:
"""Resolve the shared tile source's TileJSON in the background (best-effort, once).
Fire-and-forget: the resolve is a blocking network call, so it runs in a worker thread
off the event loop, and any failure (offline, a slow source) is swallowed — the map
simply falls back to its default max zoom. Warming it here means the first Map or
Node-detail location preview opens from the already-resolved source instead of stalling
on the round-trip.
"""
async def _warm() -> None:
try:
await asyncio.to_thread(lambda: ctx.basemap_source.max_zoom)
except Exception: # noqa: BLE001 - the map works offline at a default zoom
pass
asyncio.ensure_future(_warm())
@asynccontextmanager
async def _busy_over_link(
ctx: AppContext, *, title: str = ""
+135
View File
@@ -0,0 +1,135 @@
"""A small, static, non-interactive map region embeddable inside any screen.
The full-screen :class:`~meshterm.ui.map_screen.MapScreen` is a whole layer of its own —
it pans, zooms, finds nodes, and persists its view. Some screens only want a *glance*: a
few rows of basemap fixed on one place, with the mesh's markers on it, no controls. The
Node detail screen's "Location" preview is the first such caller — it shows where a node
sits without leaving for the big map (which its *Open full map* action still reaches).
This is the map's tile plumbing distilled to that job: a fixed centre and zoom, its own
little tile cache, background fetches off the event loop (so the host screen never blocks
on the network), and a synchronous :meth:`render` that draws whatever tiles have landed —
refining in place as more arrive, exactly like the big map. With no network and no cached
tiles the basemap is simply absent and the markers plot on a blank grid, so the preview is
always *something*. It owns no keys and resolves nothing; the screen that embeds it just
calls :meth:`render` from its own ``render_body`` and forwards nothing back.
"""
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Optional
from ..core.geo import Viewport, clamp_lat
from ..core.mvt import Layer
from .map_render import MapMarker, render_map
if TYPE_CHECKING: # pragma: no cover - typing only
from ..services.basemap import BasemapSource
#: How far past the tile source's max zoom a preview may sit — the lower-zoom tiles are
#: magnified to fill it. Matches the big map's overzoom so a close preview still has a
#: (blurred) basemap rather than blank tiles.
_OVERZOOM = 2
class MiniMap:
"""A fixed, non-interactive slippy-map region drawn into a host screen's body.
Build one with the resolved tile source (as :func:`~meshterm.ui.map_screen.open_map`
resolves it) plus the centre, zoom, and markers to plot, then call :meth:`render`
from the host's ``render_body`` with the cell width and row height the region should
take. Tiles fetch in the background and the region redraws as they arrive; nothing
here transmits over the radio.
"""
def __init__(
self,
session, # noqa: ANN001 - TuiSession, untyped to avoid an import cycle
source: "BasemapSource",
max_tile_zoom: int,
*,
center_lat: float,
center_lon: float,
zoom: int,
markers: list[MapMarker],
) -> None:
"""Create the preview over a fixed view.
Args:
session: The running TUI session — used only to repaint the host screen when
a background tile lands (:meth:`_load`).
source: The vector-tile source, already resolved/warmed by the caller.
max_tile_zoom: The source's max zoom, captured off the event loop at open time
(reading it can touch the network, so the host resolves it once up front).
center_lat: Latitude the preview centres on.
center_lon: Longitude the preview centres on.
zoom: Display zoom; clamped to a sane range against the source's max.
markers: The located mesh nodes to overlay (may be empty).
"""
self._session = session
self._source = source
self._max_tile_zoom = max_tile_zoom
self._center_lat = clamp_lat(center_lat)
self._center_lon = center_lon
self._zoom = max(2, min(int(zoom), max_tile_zoom + _OVERZOOM))
self._markers = markers
# Decoded tiles keyed by (z, x, y); a stored ``None`` means "fetched, empty/absent".
self._tiles: dict[tuple[int, int, int], Optional[list[Layer]]] = {}
self._pending: set[tuple[int, int, int]] = set()
@property
def has_basemap(self) -> bool:
"""Whether the source can serve a basemap at all (network reachable, or cached)."""
return self._source.available
@property
def pending(self) -> int:
"""How many visible tiles are still in flight — for a host's loading note."""
return len(self._pending)
def render(self, width: int, rows: int) -> list[str]:
"""Render the preview at ``width`` cells by ``rows`` rows, scheduling tile loads.
Builds a :class:`~meshterm.core.geo.Viewport` sized to this region (each cell is
two braille dots wide, each row four tall) fixed on the preview's centre and zoom,
kicks off background fetches for any not-yet-loaded tiles, and draws the frame from
whatever has landed. Called every paint; the viewport is cheap to rebuild, so a
resize just re-sizes it.
Args:
width: Region width in character cells.
rows: Region height in character cells.
Returns:
One ANSI string per row (exactly ``rows`` of them, as the canvas fills its box).
"""
viewport = Viewport(
self._center_lat, self._center_lon, self._zoom, max(2, width) * 2, max(1, rows) * 4
)
self._ensure_tiles(viewport)
tiles = {t: self._tiles.get(t) for t in viewport.tiles(self._max_tile_zoom)}
return render_map(viewport, tiles, self._markers)
def _ensure_tiles(self, viewport: Viewport) -> None:
"""Schedule background fetches for any visible tiles not yet loaded or pending."""
if not self._source.available: # offline (resolved at open time) — markers only
return
for t in viewport.tiles(self._max_tile_zoom):
if t in self._tiles or t in self._pending:
continue
self._pending.add(t)
try:
asyncio.ensure_future(self._load(t))
except RuntimeError: # pragma: no cover - no running loop (non-interactive)
self._pending.discard(t)
async def _load(self, t: tuple[int, int, int]) -> None:
"""Fetch+decode one tile off the event loop, then repaint the host screen."""
try:
layers = await asyncio.to_thread(self._source.load_tile, *t)
except Exception: # noqa: BLE001 - a failed tile is just an absent one
layers = None
self._tiles[t] = layers
self._pending.discard(t)
self._session.invalidate()
+746
View File
@@ -0,0 +1,746 @@
"""The Node detail screen: one node's whole story on a single page, and the ways into it.
Reached by pressing Enter on any contact in the Contacts list (see
:mod:`~meshterm.ui.contacts_screen`). Where the list is one aligned row per node, this is
the node itself, in full:
* **who it is** — its name in the node's own hue, its key with the routing hash lit, its
type, when it was first and last heard, how many packets we've overheard, its reception
SNR (median and best) and last RSSI, and where it sits;
* **where it is** — a small static basemap preview (see :class:`~meshterm.ui.minimap.MiniMap`)
centred on the node with the rest of the mesh around it, when the node has advertised a
location;
* **how we reach it** — the observed routes drawn on the shared route graph
(:mod:`~meshterm.ui.pathgraph`), the best-evidence one lit white over the alternatives, so
the path the trace would take reads at a glance;
* **the ways in** — an action list: *Trace target* (armed with the suggested best path, so
Enter walks straight to it), *Open full map*, and *Time machine* (only when the recorder
actually holds history for the node). ↑/↓ move the cursor, Enter commits, Esc backs to the
list.
The screen is a pure read-and-route view: it renders already-resolved display data and
resolves an action token; :func:`open_node_detail` owns the data-gathering and runs the
sub-flows each action opens, then re-shows the page — the same loop the Time Machine and
Contacts list use. Nothing here transmits.
"""
from __future__ import annotations
import asyncio
import math
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Optional
from rich.text import Text
from ..core.geo import EARTH_RADIUS_KM, usable_fix
from ..core.models import NODE_TYPE_LABELS, Contact
from .minimap import MiniMap
from .pathgraph import (
DST_NODE,
SRC_NODE,
GlyphOf,
LabelOf,
LabelRgbOf,
PathLayer,
render_path_graph,
)
from .theme import name_style, snr_style
from .tui.render import render_hanging, render_lines, render_to_ansi
from .tui.screen import CANCEL, Screen
from .widgets import (
_DEFAULT_GLYPH,
_NODE_GLYPHS,
_age_seconds,
_recency_style,
format_ago,
highlighted_hash,
node_type_legend,
path_text,
)
if TYPE_CHECKING: # pragma: no cover - typing only
from ..context import AppContext
#: Our own node's marker glyph and hue, matching the map/atlas star.
_SELF_GLYPH = ("★", "#facc15")
#: How many character rows the inline location preview draws.
_MAP_ROWS = 7
#: Route-graph tuning for this page. It draws us on the left and the target on the right
#: (us → target, so the graph reads as "how we reach it", left to right). A well-connected
#: node offers several candidate paths at once, and cramming them into a short box overlaps
#: the lanes into an unreadable tangle — so this page gives the fan a generous lane step and
#: row budget, letting each path spread into its own clearly separated track. The height is
#: adaptive: it grows only with the number of distinct lanes, so a node with one or two
#: routes still draws compact while a busy one earns the room it needs. The page scrolls
#: (PgUp/PgDn), so a tall graph never crowds the action rows off-screen.
_PATH_LANE_STEP = 15
_PATH_MAX_ROWS = 22
#: Cells the labelled info rows reserve for their label lane, so the value blocks line up
#: and a wrapped value hangs under itself rather than under the label (the app-wide
#: hanging-indent rule). Sized to the widest label the block uses ("packets").
_LABEL_LANE = 9
@dataclass(slots=True)
class _Action:
"""One action row at the foot of the page.
Attributes:
key: The token the screen resolves with when this row is committed.
glyph: The leading icon.
glyph_style: The icon's style.
label: The row's text (a current value inlined, muted where it's context).
"""
key: str
glyph: str
glyph_style: str
label: str
@dataclass(slots=True)
class _PathView:
"""The route-graph layers and their shared per-node draw callbacks, or a bare note.
Attributes:
layers: The paths to draw (best-evidence one highest priority), or empty when
there is no route evidence at all — then ``note`` carries the muted stand-in.
glyph_of: Per-node marker callback for the graph.
label_of: Per-node label callback for the graph.
label_rgb_of: Per-node label-colour callback for the graph.
legend: Whether to draw the node-type key beneath the graph (a typed relay showed).
note: The muted line shown instead of a graph when there is no evidence.
"""
layers: list[PathLayer] = field(default_factory=list)
glyph_of: Optional[GlyphOf] = None
label_of: Optional[LabelOf] = None
label_rgb_of: Optional[LabelRgbOf] = None
legend: bool = False
note: str = ""
class NodeDetailScreen(Screen):
"""A full-screen page for one node: identity, location, routes, and the ways in.
A read-and-route view. It renders already-resolved display data (see
:func:`open_node_detail`, which assembles it) and, on Enter, resolves the highlighted
action's token for the opener to act on; Esc resolves :data:`CANCEL` to leave. ↑/↓ move
the action cursor (its row is kept in view while navigating); PgUp/PgDn/Home/End scroll
the whole page, so the location preview and route graph can be read on a short terminal
without losing the controls.
"""
floating = False
def __init__(
self,
*,
title: str,
header: Text,
info_rows: list[tuple[str, Text]],
actions: list[_Action],
minimap: Optional[MiniMap] = None,
map_caption: Optional[Text] = None,
path: Optional[_PathView] = None,
) -> None:
"""Build the page over resolved display data.
Args:
title: The screen heading (``Node — <name>``).
header: The identity line: type glyph, the coloured name, its type label.
info_rows: ``(label, value)`` pairs for the fixed info block; each renders as
a muted label lane with the value hanging under itself when it wraps.
actions: The action rows, in display order (a ``back`` row set apart at the end).
minimap: The inline location preview, or ``None`` when the node has no location.
map_caption: A faint line under the preview (its centre/scale), when a map shows.
path: The route-graph view (layers + callbacks, or a muted note), or ``None`` to
omit the whole "Path to node" section (our own node has no route to itself).
"""
super().__init__()
self.title = title
self._header = header
self._info_rows = info_rows
self._actions = actions
self._minimap = minimap
self._map_caption = map_caption
self._path = path
self._index = 0
self._pin_cursor = False # open showing the top; only pin once ↑/↓ are used
self._cursor: Optional[int] = None
# --- input -----------------------------------------------------------------
@property
def footer_hint(self) -> str: # type: ignore[override]
"""Navigation, commit, scroll, then Esc last."""
return "↑↓ actions · Enter open · PgUp/PgDn scroll · Esc back"
def consume_edge_scrub(self) -> int:
"""Scrub the panel's right edge while a braille map shows (the same smear the map has)."""
return 2 if self._minimap is not None else 0
def handle(self, action: str, data: str = "") -> None:
"""Move the action cursor, commit it, scroll the page, or leave."""
if action == "enter":
self.resolve(self._actions[self._index].key)
elif action == "up":
self._index = (self._index - 1) % len(self._actions)
self._pin_cursor = True
elif action == "down":
self._index = (self._index + 1) % len(self._actions)
self._pin_cursor = True
elif action == "pageup":
self._pin_cursor = False
self.scroll_pages(-1)
elif action in ("pagedown", "space"):
self._pin_cursor = False
self.scroll_pages(1)
elif action in ("home", "ctrl_home"):
self._pin_cursor = False
self.scroll_to_top()
elif action in ("end", "ctrl_end"):
self._pin_cursor = False
self.scroll_to_bottom()
elif action == "escape":
self.resolve(CANCEL)
def cursor_line(self) -> Optional[int]:
"""Keep the highlighted action visible while ↑/↓ are in use; free scroll otherwise."""
return self._cursor if self._pin_cursor else None
# --- rendering -------------------------------------------------------------
def render_body(self, width: int) -> list[str]:
"""Render the identity block, location preview, route graph, and action list."""
lines: list[str] = []
lines.extend(render_lines(self._header, width))
for label, value in self._info_rows:
lines.extend(
render_hanging(
Text(f"{label:<{_LABEL_LANE}}", style="muted"),
value,
width,
indent=_LABEL_LANE,
)
)
if self._minimap is not None:
lines.append("")
lines.extend(render_lines(Text("Location", style="accent"), width))
lines.extend(self._minimap.render(width, _MAP_ROWS))
if self._map_caption is not None:
lines.extend(render_lines(self._map_caption, width, no_wrap=True))
if self._path is not None:
lines.append("")
lines.extend(render_lines(Text("Path to node", style="accent"), width))
lines.extend(self._path_lines(width))
lines.append("")
self._cursor = None
for i, action in enumerate(self._actions):
if action.key == "back":
lines.append("") # set the exit row apart, as the menus do
selected = i == self._index
text = Text("❯ " if selected else " ", style="brand" if selected else "")
if action.glyph:
text.append(f"{action.glyph} ", style=action.glyph_style)
text.append(action.label)
if selected:
text.style = "brand"
self._cursor = len(lines)
text.no_wrap = True
text.truncate(width, overflow="ellipsis")
lines.append(render_to_ansi(text, width))
self._scroll_total = max(1, len(lines))
return lines
def _path_lines(self, width: int) -> list[str]:
"""The route graph (best-evidence path white over the rest), or the muted note."""
path = self._path
assert path is not None # only called when a path section exists
if not path.layers or path.glyph_of is None:
return render_lines(Text(path.note or "no route observed yet", style="muted"), width)
lines = render_path_graph(
path.layers,
width,
glyph_of=path.glyph_of,
label_of=path.label_of, # type: ignore[arg-type]
label_rgb_of=path.label_rgb_of, # type: ignore[arg-type]
max_rows=_PATH_MAX_ROWS,
lane_step=_PATH_LANE_STEP,
)
caption = Text("you → node · white = suggested route · labels = hash byte", style="faint")
lines.extend(render_lines(caption, width, no_wrap=True))
if path.legend:
lines.extend(render_lines(node_type_legend(), width, no_wrap=True))
return lines
# -- geographic helpers --------------------------------------------------------
_COMPASS = ("N", "NE", "E", "SE", "S", "SW", "W", "NW")
def _distance_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""Great-circle distance between two coordinates, in kilometres (haversine)."""
p1, p2 = math.radians(lat1), math.radians(lat2)
dp = math.radians(lat2 - lat1)
dl = math.radians(lon2 - lon1)
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
return 2 * EARTH_RADIUS_KM * math.asin(min(1.0, math.sqrt(a)))
def _bearing(lat1: float, lon1: float, lat2: float, lon2: float) -> str:
"""The 8-point compass direction from ``(lat1, lon1)`` toward ``(lat2, lon2)``."""
p1, p2 = math.radians(lat1), math.radians(lat2)
dl = math.radians(lon2 - lon1)
y = math.sin(dl) * math.cos(p2)
x = math.cos(p1) * math.sin(p2) - math.sin(p1) * math.cos(p2) * math.cos(dl)
deg = (math.degrees(math.atan2(y, x)) + 360) % 360
return _COMPASS[round(deg / 45) % 8]
def _range_text(
lat: float, lon: float, self_lat: Optional[float], self_lon: Optional[float]
) -> Text:
"""A location value: the coordinates, plus range + bearing from us when we're placed."""
text = Text(f"{lat:.4f}, {lon:.4f}", style="")
if self_lat is not None and self_lon is not None:
km = _distance_km(self_lat, self_lon, lat, lon)
dist = f"{km * 1000:.0f} m" if km < 1 else f"{km:.1f} km"
text.append(f" · {dist} {_bearing(self_lat, self_lon, lat, lon)}", style="muted")
return text
def _as_float(value: object) -> Optional[float]:
"""Best-effort float coercion for the raw lat/lon a device reports (``None`` on junk)."""
try:
return float(value) # type: ignore[arg-type]
except (TypeError, ValueError):
return None
def _located(lat: Optional[float], lon: Optional[float]) -> bool:
"""Whether a coordinate is a real, plottable fix (see :func:`~meshterm.core.geo.usable_fix`).
Rejects both the 0/0 null-island a no-GPS node reports and the out-of-range nonsense a
misconfigured companion sometimes advertises (``lat -97, lon -1042`` seen in the wild),
either of which would drop the location preview onto an all-black off-world view.
"""
return lat is not None and lon is not None and usable_fix(lat, lon)
# -- data gathering + the action loop -----------------------------------------
async def open_node_detail(ctx: "AppContext", contact: Optional["Contact"]) -> None:
"""Open the Node detail page for a contact (or our own node) and run its action loop.
Assembles the page from stored history, the device's contacts, and the observed
topology — identity, reception stats, a location preview, and the observed routes — then
loops: show the page, run whatever action the user commits (trace, full map, time
machine), and show it again, until Esc backs out. This is the same show/act/reshow loop
the Time Machine and Contacts list use.
Args:
ctx: The shared application context (must be running the interactive TUI).
contact: The contact to detail, or ``None`` for our own node (an identity-and-ledger
page — we never overhear ourselves, so there is no reception history to show).
Raises:
RuntimeError: If called outside the interactive menu (no full-screen session).
"""
from ..services.trace_runner import (
make_name_key_resolver,
make_node_resolver,
make_node_type_resolver,
)
from ..services.topology import build_topology, render_forced_spec, _is_hex
from ..tools.map import gather_markers
from .map_screen import basemap_source, open_map
from .surface import TuiUi
from .timemachine_screen import open_timemachine_node, open_timemachine_self
from .trace_screen import _collapse_trace_width, open_trace
from .widgets import route_graph_style
if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller
raise RuntimeError("the node detail screen is only available in the menu")
session = ctx.ui.session
you = contact is None
# -- our own node, for the "us" label, the location preview centre, and range/bearing.
try:
info = await ctx.devstate.self_info()
except Exception: # noqa: BLE001 - the page is useful without our own identity/fix
info = {}
self_name = str(info.get("name") or "this node")
self_key = str(info.get("public_key") or "")
self_lat, self_lon = _as_float(info.get("adv_lat")), _as_float(info.get("adv_lon"))
if not _located(self_lat, self_lon):
self_lat = self_lon = None
# -- the device's contacts (for name/type/key resolution) and the routing hash width.
try:
contacts = await ctx.devstate.contacts()
except Exception: # noqa: BLE001 - resolution just falls back to stored data
contacts = []
try:
mode = int(await ctx.devstate.path_hash_mode())
prefix_bytes = (mode + 1) if 0 <= mode <= 3 else 0
width_bytes = _collapse_trace_width(mode)
except Exception: # noqa: BLE001 - optional reads; sane defaults keep the page working
prefix_bytes, width_bytes = 0, 1
stored_names = ctx.repo.node_names()
# One hash→name resolver for the whole page: the route/suggest rows and the route
# graph all name their hops through it (contacts first, recorder history behind).
resolve = make_node_resolver(contacts, stored_names)
if you:
node_id = (self_key.lower().removeprefix("0x")[:12]) or ""
name: Optional[str] = self_name
key = self_key
node_type = info.get("adv_type")
lat, lon = self_lat, self_lon
else:
assert contact is not None
key = contact.public_key or contact.key_prefix or ""
node_id = key.lower().removeprefix("0x")[:12]
name = contact.name or None
node_type = contact.node_type
lat = contact.lat if _located(contact.lat, contact.lon) else None
lon = contact.lon if _located(contact.lat, contact.lon) else None
# -- reception stats + first-heard from the recorder's history.
heard = {n.node: n for n in ctx.repo.heard_nodes() if n.node}
hn = heard.get(node_id)
firsts = {n: when for n, _n, when in ctx.repo.first_seen()}
first_heard = firsts.get(node_id)
if you:
hn = None # we never overhear ourselves — no reception history to show
# A node with a fix but no observation-derived location still shows the map — but only
# when that overheard fix is itself real (a no-GPS/nonsense advert never places it).
if lat is None and hn is not None and hn.has_location and _located(hn.lat, hn.lon):
lat, lon = hn.lat, hn.lon
label = name or node_id or key or "?"
# -- identity header.
if you:
glyph, glyph_style = _SELF_GLYPH
name_hue = "you"
else:
glyph, glyph_style = _NODE_GLYPHS.get(node_type, _DEFAULT_GLYPH)
name_hue = name_style(name, key) if name else "muted"
header = Text()
header.append(f"{glyph} ", style=glyph_style)
header.append(name or "unknown", style=name_hue)
type_label = NODE_TYPE_LABELS.get(node_type) if node_type is not None else None
if you:
header.append(" your node", style="muted")
elif type_label:
header.append(f" {type_label}", style="muted")
# -- the observed topology: the suggested best path and the routes to draw.
target_hash = key.lower().removeprefix("0x")
target_hash = target_hash if (not you and _is_hex(target_hash)) else None
topo = build_topology(
self_id=(self_key.lower().removeprefix("0x")[:12]) or "local",
contacts=contacts,
trace_paths=ctx.repo.trace_paths(),
packet_paths=ctx.repo.packet_paths(),
neighbour_links=ctx.repo.neighbour_links(),
)
device_route: Optional[tuple[str, ...]] = None
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
scenarios = (
topo.scenarios(canonical_target, device_route=device_route)
if canonical_target
else []
)
# The spec the Trace action arms on: the observed best path, else the firmware's
# learned route, else nothing (let the trace screen auto-resolve).
if target_hash and suggested is not None:
suggested_spec = render_forced_spec(suggested.hops, target_hash, width_bytes)
elif target_hash and device_route is not None:
suggested_spec = render_forced_spec(device_route, target_hash, width_bytes)
else:
suggested_spec = ""
# -- the info block.
info_rows: list[tuple[str, Text]] = []
if key:
info_rows.append(("key", highlighted_hash(key, prefix_bytes)))
else:
info_rows.append(("key", Text("?", style="muted")))
if not you:
secs = _age_seconds(hn.last_seen if hn else (contact.last_seen if contact else None))
heard_val = Text(format_ago(secs), style=_recency_style(secs))
if first_heard is not None:
heard_val.append(
f" · first {first_heard.astimezone():%b %d %Y}", style="muted"
)
info_rows.append(("heard", heard_val))
# A node never overheard reads a faint em-dash, as the contact list draws it.
packets = Text(str(hn.count)) if hn else Text("—", style="faint")
info_rows.append(("packets", packets))
signal = _signal_row(hn)
if signal is not None:
info_rows.append(("signal", signal))
if lat is not None and lon is not None:
info_rows.append(("where", _range_text(lat, lon, self_lat, self_lon)))
if not you:
info_rows.append(("route", _route_row(device_route, resolve=resolve, self_name=self_name)))
info_rows.append(("suggest", _suggest_row(suggested, resolve=resolve, self_name=self_name)))
# -- the location preview (only when the node advertised a fix).
minimap: Optional[MiniMap] = None
map_caption: Optional[Text] = None
markers: list = []
if lat is not None and lon is not None:
try:
markers = await gather_markers(ctx)
except Exception: # noqa: BLE001 - a preview of just this node is still useful
markers = []
source = basemap_source(ctx)
try:
max_zoom = await asyncio.to_thread(lambda: source.max_zoom)
except Exception: # noqa: BLE001 - offline: markers on a blank grid
max_zoom = 14
minimap = MiniMap(
session, source, max_zoom,
center_lat=lat, center_lon=lon, zoom=min(13, max_zoom), markers=markers,
)
map_caption = Text(f"{label} · centred here", style="faint")
# -- the "path to node" route graph (node → us), best-evidence path white.
path: Optional[_PathView] = None
if not you:
path = _path_view(
topo, scenarios, suggested, device_route, canonical_target,
resolve=resolve,
type_of=make_node_type_resolver(contacts),
key_of=make_name_key_resolver(contacts, stored_names),
style=route_graph_style,
self_name=self_name,
node_label=label,
)
# -- the action rows.
def build_actions() -> list[_Action]:
rows: list[_Action] = []
if not you and node_id:
rows.append(_Action("trace", "🎯", "", _trace_label(suggested_spec)))
if minimap is not None:
rows.append(_Action("map", "🌍", "", "Open full map"))
if you:
rows.append(_Action("timemachine", "⏳", "", "Time machine — your activity"))
elif hn is not None:
rows.append(_Action("timemachine", "⏳", "", f"Time machine — {hn.count} receptions"))
rows.append(_Action("back", "", "", "Back"))
return rows
title = f"Node — {label}" if not you else f"Node — {label} (you)"
while True:
screen = NodeDetailScreen(
title=title,
header=header,
info_rows=info_rows,
actions=build_actions(),
minimap=minimap,
map_caption=map_caption,
path=path,
)
action = await session.run_screen(screen)
if action is CANCEL or action is None:
break
if action == "trace":
await open_trace(ctx, name or key, initial_spec=suggested_spec)
elif action == "map":
if markers:
await open_map(ctx, markers)
elif action == "timemachine":
if you:
await open_timemachine_self(ctx)
else:
await open_timemachine_node(ctx, node_id, label)
if minimap is not None:
# The preview's braille may have smeared the terminal (double-width fallback
# glyphs prompt_toolkit's diff can't see); force one clean repaint of the list
# underneath, exactly as the full map does on the way out.
session.request_full_repaint()
def _signal_row(hn) -> Optional[Text]: # noqa: ANN001 - Optional[HeardNode]
"""Median/best reception SNR and last RSSI, or ``None`` when nothing was measured."""
if hn is None:
return None
text = Text()
if hn.median_snr is not None:
text.append("median ", style="muted")
text.append(f"{hn.median_snr:+.1f} dB", style=snr_style(hn.median_snr))
if hn.best_snr is not None:
text.append(" · best ", style="muted")
text.append(f"{hn.best_snr:+.1f} dB", style=snr_style(hn.best_snr))
if hn.last_rssi is not None:
if text.plain:
text.append(" · ", style="muted")
text.append(f"RSSI {hn.last_rssi:.0f} dBm", style="muted")
return text if text.plain else None
def _route_row(
device_route: Optional[tuple[str, ...]], *, resolve, self_name: Optional[str]
) -> Text:
"""The firmware's learned route to the node, or a note that it floods.
The hops render through THE path widget (:func:`~meshterm.ui.widgets.path_text`) at a
1-byte hash width, so each reads ``name (3d)`` — the same first-byte tag the route graph
prints beside its markers, letting the row and the graph be cross-read hop for hop.
"""
if device_route is None:
return Text("no learned route — floods", style="muted")
if not device_route:
return Text("direct neighbour (zero-hop route)", style="")
text = Text("device route", style="accent")
text.append(" via ", style="muted")
text.append_text(_hop_path(device_route, resolve, self_name))
return text
def _suggest_row(suggested, *, resolve, self_name: Optional[str]) -> Text: # noqa: ANN001
"""The observed best path (the "suggest best path" answer), or a muted stand-in.
Like :func:`_route_row`, the hops render through THE path widget with a 1-byte hash in
parentheses so they match the route graph's byte labels; the bottleneck SNR and sample
count trail behind as context.
"""
if suggested is None:
return Text("none observed yet — trace to learn one", style="muted")
text = (
_hop_path(suggested.hops, resolve, self_name)
if suggested.hops
else Text("direct", style="brand")
)
if suggested.weakest_snr is not None:
text.append(" · weakest ", style="muted")
text.append(f"{suggested.weakest_snr:+.1f} dB", style=snr_style(suggested.weakest_snr))
if suggested.samples:
text.append(f" · {suggested.samples}×", style="muted")
return text
def _hop_path(hops: tuple[str, ...], resolve, self_name: Optional[str]) -> Text:
"""A hop sequence rendered through THE path widget, each hop tagged with its first byte."""
return path_text(
list(hops), resolve, prefix_bytes=1, self_name=self_name,
show_hash=True, hash_bytes=1,
)
def _trace_label(suggested_spec: str) -> str:
"""The Trace action's row label — naming whether it arms on a suggested path or auto."""
return "Trace target — suggested path" if suggested_spec else "Trace target — auto route"
def _path_view(
topo,
scenarios,
suggested,
device_route,
canonical_target,
*,
resolve,
type_of,
key_of,
style,
self_name,
node_label,
) -> _PathView:
"""Build the route-graph layers (us → node) and their draw callbacks, or a muted note.
The paths are drawn us-on-the-left to the target-on-the-right — the outbound direction
a trace walks, so the graph reads left to right as "how we reach it" and lines up with
the Path-to-node rows above. The shared :func:`~meshterm.ui.widgets.route_graph_style`
always pins us to the graph's right endpoint (it was built for the Message paths view,
where traffic arrives *at* us), so we hand it the target as its ``source`` and then swap
the two endpoint sentinels in its callbacks — putting the star on the left and the named
target on the right without disturbing the widget's other callers. The best-evidence
route (the observed suggestion, else the firmware's route) is lit white over the
alternatives' grey. With no route evidence at all — no learned route, no observed path,
not even a direct link — there is nothing honest to draw, so a muted note stands in.
"""
if canonical_target is None:
return _PathView(note="no key to route to")
has_evidence = (
device_route is not None
or any(s.source == "observed" for s in scenarios)
or topo.link(topo.self_id, canonical_target) is not None
)
if not has_evidence:
return _PathView(note="no route observed yet — trace to discover one")
white, grey = (255, 255, 255), (120, 120, 120)
best_hops = (
suggested.hops if suggested is not None
else device_route if device_route is not None
else None
)
layers: list[PathLayer] = []
seen: set[tuple[str, ...]] = set()
def add(hops: tuple[str, ...], priority: int, color: tuple[int, int, int]) -> None:
if hops in seen: # draw us → target (the outbound order the trace walks)
return
seen.add(hops)
layers.append(PathLayer(hops=hops, color=color, priority=priority))
if best_hops is not None:
add(best_hops, 3, white)
for scenario in scenarios:
add(scenario.hops, 2, grey)
glyph_of, label_of, label_rgb_of = style(
resolve=resolve, self_name=self_name, source=node_label, type_of=type_of, key_of=key_of
)
# route_graph_style pins us to DST (the right) and the target to SRC (the left); swap the
# two sentinels so the graph draws us on the left and the target on the right.
glyph_of = _flip_endpoints(glyph_of)
label_of = _flip_endpoints(label_of)
label_rgb_of = _flip_endpoints(label_rgb_of)
legend = any(type_of(h) is not None for layer in layers for h in layer.hops)
return _PathView(
layers=layers,
glyph_of=glyph_of,
label_of=label_of,
label_rgb_of=label_rgb_of,
legend=legend,
)
def _flip_endpoints(callback):
"""Wrap a pathgraph per-node callback so it swaps the two endpoint sentinels.
:func:`~meshterm.ui.widgets.route_graph_style` builds its glyph/label/colour callbacks
with us on the right (``DST_NODE``) and the far node on the left (``SRC_NODE``). Passing
each hop through here maps ``SRC_NODE`` to ``DST_NODE`` and back, so the drawn graph puts
us on the left and the target on the right — relay hops (anything else) pass through
untouched.
"""
def wrapped(node: str): # noqa: ANN202 - forwards whatever the callback returns
if node == SRC_NODE:
node = DST_NODE
elif node == DST_NODE:
node = SRC_NODE
return callback(node)
return wrapped
+6 -1
View File
@@ -101,6 +101,7 @@ def render_path_graph(
label_rgb_of: LabelRgbOf,
min_rows: int = 5,
max_rows: int = 15,
lane_step: int = _LANE_STEP_DOTS,
) -> list[str]:
"""Draw the layered route graph and return its ANSI lines.
@@ -118,6 +119,10 @@ def render_path_graph(
min_rows: The fewest canvas rows to draw, however flat the fan.
max_rows: The most canvas rows to spend; a taller fan compresses its lane
spacing to fit.
lane_step: Vertical dot separation between adjacent path lanes. A smaller step
packs the fan into a shallower band, so the segments leaving each endpoint
run closer to horizontal — flatter, less acute angles — at the cost of the
lanes sitting nearer each other. Defaults to :data:`_LANE_STEP_DOTS`.
Returns:
One ANSI string per canvas row (empty when there are no layers to draw).
@@ -165,7 +170,7 @@ def render_path_graph(
# far the fan reaches *each* way, which is rarely symmetric (lanes fan 0, −1, +1,
# −2, …). Sizing to the real up/down reach and centring the endpoints' lane-0
# line on it keeps the box off the empty half a mirrored block would leave.
step = _LANE_STEP_DOTS
step = lane_step
ups = -min([0.0, *lane_y.values()]) # lanes rising above the lane-0 line
downs = max([0.0, *lane_y.values()]) # …and dropping below it
+54
View File
@@ -1226,3 +1226,57 @@ async def open_timemachine(ctx: "AppContext") -> None:
)
screen = TimeMachineScreen(session=session, label=label, build=build)
await session.run_screen(screen)
async def open_timemachine_node(ctx: "AppContext", node_id: str, label: str) -> None:
"""Open one node's Time Machine page directly, skipping the subject picker.
The Node detail screen's *Time machine* link lands here: the same scrollable per-node
page :func:`open_timemachine` reaches through its picker (volume, SNR band, hour-of-day
rhythm, roll-up), but for a node already chosen elsewhere. Reads stored history only, so
no device is needed and nothing transmits; runs until dismissed with Esc.
Args:
ctx: The shared application context (must be running the interactive TUI).
node_id: The node's stored 12-hex key-prefix id (what observations carry).
label: The node's display name for the page heading.
Raises:
RuntimeError: If called outside the interactive menu (no full-screen session).
"""
from .surface import TuiUi
if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller
raise RuntimeError("the time machine is only available in the menu")
session = ctx.ui.session
build = ( # noqa: E731 - a tiny binding closure reads better than a def here
lambda window, width, _id=node_id, _lb=label: _node_sections(
ctx, _id, _lb, window, width
)
)
await session.run_screen(TimeMachineScreen(session=session, label=label, build=build))
async def open_timemachine_self(ctx: "AppContext") -> None:
"""Open our own node's Time Machine page directly (the outbound-activity ledger).
The Node detail screen's *Time machine* link for our own node: we never overhear
ourselves, so this page is the traces we launched and the messages we sent, not a
reception history (see :func:`_self_sections`). Reads stored history only; runs until
dismissed with Esc.
Args:
ctx: The shared application context (must be running the interactive TUI).
Raises:
RuntimeError: If called outside the interactive menu (no full-screen session).
"""
from .surface import TuiUi
if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller
raise RuntimeError("the time machine is only available in the menu")
session = ctx.ui.session
self_name, _ = await _self_identity(ctx)
label = self_name or "you"
build = lambda window, width: _self_sections(ctx, window, width) # noqa: E731
await session.run_screen(TimeMachineScreen(session=session, label=label, build=build))
+45 -3
View File
@@ -1069,7 +1069,35 @@ def _previous_walk(previous: Optional[TraceResult]) -> Optional[tuple[str, ...]]
return tokens or None
async def open_trace(ctx: "AppContext", target: str) -> int:
def _best_observed(topo: Any, target_hash: str) -> Optional[tuple[tuple[str, ...], str]]:
"""The strongest evidence-backed outbound route to ``target_hash``, if the data has one.
The observed-topology counterpart to the firmware's learned route: when the device
knows no route to a contact — the common case, since repeater contacts flood — the
recorder's own evidence (traces, overheard relay chains, fetched neighbour tables)
may still spell out a route that has demonstrably carried traffic. Delegates the
ranking to :meth:`~meshterm.services.topology.MeshTopology.suggested` and returns the
winner's canonical outbound hops with a short provenance line
(``best observed · 3× · −7 dB``) for the route line and summary, or ``None`` when
nothing beats a direct shot.
Args:
topo: The freshly built :class:`~meshterm.services.topology.MeshTopology`.
target_hash: The target's hex hash (any width ≥ 1 byte).
Returns:
``(outbound_hops, provenance)`` for the suggested route, or ``None``.
"""
scenario = topo.suggested(topo.canonical(target_hash) or target_hash[:12])
if scenario is None:
return None
source = f"best observed · {scenario.samples}×"
if scenario.weakest_snr is not None:
source += f" · {scenario.weakest_snr:+.0f} dB"
return scenario.hops, source
async def open_trace(ctx: "AppContext", target: str, *, initial_spec: str = "") -> int:
"""Open the live *Trace target* screen for ``target`` and run it until dismissed.
The symmetric feature: can I reach this node? Routes turn at the target and come
@@ -1079,6 +1107,11 @@ async def open_trace(ctx: "AppContext", target: str) -> int:
Args:
ctx: The shared application context (must be running the interactive TUI surface).
target: The trace destination (contact name or key prefix).
initial_spec: A forced path to open armed on (the full symmetric boomerang,
comma-separated hex hops), instead of idle on the auto-resolved route — how
the Node detail screen hands over its suggested best path so the trace opens
ready to walk it. Empty (the default) opens on the auto route (device-learned,
best-observed, last trace, or direct — see :func:`_open_session`).
Returns:
The number of traces run while the screen was open.
@@ -1086,7 +1119,7 @@ async def open_trace(ctx: "AppContext", target: str) -> int:
Raises:
RuntimeError: If called outside the interactive menu (no full-screen session).
"""
return await _open_session(ctx, target)
return await _open_session(ctx, target, initial_spec=initial_spec)
async def open_trace_path(ctx: "AppContext", spec: str = "") -> int:
@@ -1243,6 +1276,12 @@ async def _open_session(
if target_hash is not None:
if device_route is not None:
auto_hops, auto_source = device_route, "device route"
elif (observed := _best_observed(fresh_topology(), target_hash)) is not None:
# No firmware route, but the recorder's own evidence spells one out — the
# strongest observed path (sample counts, SNR behind the ranking). This is
# what makes Trace target *suggest* a route from the data rather than
# defaulting to a doomed path-less flood past the first neighbour.
auto_hops, auto_source = observed
else:
auto_hops = _previous_outbound(previous, target_hash)
if auto_hops is not None and previous is not None:
@@ -1873,7 +1912,10 @@ async def _open_session(
previous=previous,
auto_spec=auto_spec,
auto_source=auto_source,
initial_spec=initial_spec if mode == "path" else "",
# A caller-supplied spec arms either mode: a path walk's stored route, or the Node
# detail screen's suggested best path handed to a target trace. In target mode it
# only arms when the target is addressable — a forced path must end at a real hash.
initial_spec=initial_spec if (mode == "path" or target_hash is not None) else "",
)
try:
result = await session.run_screen(screen)
+32
View File
@@ -381,6 +381,38 @@ async def test_map_tool_static_render_plots_contacts(ctx) -> None:
assert "1 pkts" in out # the seeded observation's detail merged onto the contact
def test_usable_fix_rejects_out_of_range_and_null_island() -> None:
"""A fix is usable only in valid lat/lon range and away from the 0/0 no-GPS sentinel."""
from meshterm.core.geo import usable_fix
assert usable_fix(45.5, -73.6) is True
assert usable_fix(90.0, 180.0) is True and usable_fix(-90.0, -180.0) is True # extremes
assert usable_fix(0.0, 0.0) is False # null island (a no-GPS companion reports this)
assert usable_fix(-97.0, -1041.97) is False # out of range (a real advert seen in the wild)
assert usable_fix(45.0, 181.0) is False and usable_fix(-91.0, -73.0) is False
async def test_gather_markers_drops_out_of_range_fix(ctx) -> None:
"""A node advertising nonsense coordinates is never plotted, only the real one is.
Some firmware reports an out-of-range fix (a companion has advertised ``lat -97,
lon -1042``); projecting it flings the view off the world, leaving the map an all-black
off-world frame. It is treated as no fix at all, the same guard the 0/0 null island gets.
"""
from meshterm.tools.map import gather_markers
run_id = ctx.repo.start_run("monitor", {})
ctx.repo.record_observation(run_id, Observation(
node="beefbeefbeef", name="BadFix", node_type=NODE_TYPE_REPEATER,
lat=-97.0, lon=-1041.97, observed_at=utcnow()))
ctx.repo.record_observation(run_id, Observation(
node="cafecafecafe", name="GoodFix", node_type=NODE_TYPE_REPEATER,
lat=45.5, lon=-73.6, observed_at=utcnow()))
labels = {m.label for m in await gather_markers(ctx)}
assert "GoodFix" in labels
assert "BadFix" not in labels
def test_repository_round_trips_map_view(ctx) -> None:
"""The saved map viewport persists and reads back; absent by default."""
assert ctx.repo.get_map_view() is None
+287
View File
@@ -0,0 +1,287 @@
"""Node detail screen tests: the mini-map, the page render/navigation, and its helpers.
The screen is a pure render-and-route view, so these drive it headless — display data is
built by hand (the way :func:`~meshterm.ui.node_detail_screen.open_node_detail` assembles
it) and rendered/keyed against a fake session, the same approach as the trace and time
machine screen tests. The topology-driven helpers are exercised against a real (in-memory)
evidence graph.
"""
from __future__ import annotations
import re
from types import SimpleNamespace
from rich.text import Text
from meshterm.core.models import Contact, utcnow
from meshterm.services.topology import build_topology
from meshterm.services.trace_runner import (
make_name_key_resolver,
make_node_resolver,
make_node_type_resolver,
)
from meshterm.ui.map_render import MapMarker
from meshterm.ui.minimap import MiniMap
from meshterm.ui.node_detail_screen import (
NodeDetailScreen,
_Action,
_PathView,
_bearing,
_distance_km,
_path_view,
_range_text,
_route_row,
_signal_row,
_suggest_row,
)
from meshterm.ui.tui.screen import CANCEL
from meshterm.ui.widgets import highlighted_hash, route_graph_style
US = "aaaaaaaaaaaa"
HUB = Contact(name="Hub", public_key="3d63c6429436" + "0" * 52, key_prefix="3d63c6429436",
node_type=2)
FAR = Contact(name="Far", public_key="f2c24f54551e" + "0" * 52, key_prefix="f2c24f54551e")
def _plain(lines: list[str]) -> str:
return re.sub(r"\x1b\[[0-9;]*m", "", "\n".join(lines))
class _FakeSession:
def __init__(self) -> None:
self.repaints = 0
def invalidate(self) -> None:
self.repaints += 1
class _OfflineSource:
"""A tile source with no basemap, so the mini-map plots markers on a blank grid."""
available = False
def load_tile(self, z: int, x: int, y: int): # noqa: ANN201
return None
# --- the mini-map ---------------------------------------------------------------
def test_minimap_offline_renders_markers_on_a_blank_grid() -> None:
"""With no basemap the preview still fills its box and plots the node's marker."""
mini = MiniMap(
_FakeSession(), _OfflineSource(), 14,
center_lat=45.5, center_lon=-73.6, zoom=13,
markers=[MapMarker(label="Hub", lat=45.5, lon=-73.6, is_repeater=True, key="3d63aa")],
)
lines = mini.render(40, 6)
assert len(lines) == 6 # the canvas fills exactly the requested row box
assert mini.pending == 0 and mini.has_basemap is False # offline: no fetches scheduled
assert any(ch != " " for ch in _plain(lines)) # the marker drew something
def test_minimap_clamps_zoom_to_the_source_ceiling() -> None:
"""A zoom past the source's max (plus overzoom) is clamped, never runs away."""
mini = MiniMap(
_FakeSession(), _OfflineSource(), 10,
center_lat=0.0, center_lon=0.0, zoom=99, markers=[],
)
assert mini._zoom == 12 # max_tile_zoom (10) + overzoom (2)
# --- geographic helpers ---------------------------------------------------------
def test_distance_and_bearing_are_sane() -> None:
"""Range in km and an 8-point compass bearing between two nearby points."""
# ~1.11 km due north (0.01° latitude), so bearing reads N.
assert 1.0 < _distance_km(45.5, -73.6, 45.51, -73.6) < 1.2
assert _bearing(45.5, -73.6, 45.51, -73.6) == "N"
assert _bearing(45.5, -73.6, 45.5, -73.59) == "E" # due east
def test_range_text_omits_bearing_without_our_own_fix() -> None:
"""The location value carries range+bearing only when we know where we are."""
placed = _plain([_range_text(45.5, -73.6, 45.4, -73.5).plain])
assert "45.5000, -73.6000" in placed and "km" in placed
bare = _range_text(45.5, -73.6, None, None)
assert "km" not in bare.plain and "45.5000" in bare.plain
def test_signal_row_summarizes_snr_and_rssi() -> None:
"""The signal row folds median/best SNR and last RSSI, or is dropped when unmeasured."""
row = _signal_row(SimpleNamespace(median_snr=3.2, best_snr=7.0, last_rssi=-92.0))
assert row is not None
assert "median" in row.plain and "best" in row.plain and "RSSI -92" in row.plain
# A node with nothing measured (or our own node) contributes no row at all.
assert _signal_row(SimpleNamespace(median_snr=None, best_snr=None, last_rssi=None)) is None
assert _signal_row(None) is None
# --- the topology-driven rows ---------------------------------------------------
def _topo_with_route(): # noqa: ANN202
"""A graph where Far is reached through the Hub, from repeated trace evidence."""
from meshterm.persistence.repository import TracedPath
walks = [
TracedPath(when=utcnow(), hops=[("3d", 12.0), ("f2", -5.0), ("3d", -5.5), (None, 12.0)])
for _ in range(4)
]
return build_topology(
self_id=US + "0" * 52, contacts=[HUB, FAR],
trace_paths=walks, packet_paths=[], neighbour_links=[],
)
def test_route_and_suggest_rows_speak_the_evidence() -> None:
"""The route row names the learned route; the suggest row names the observed best path.
Both render their hops through THE path widget at a 1-byte hash width, so each hop reads
``name (3d)`` — the first-byte tag the route graph prints beside its markers.
"""
topo = _topo_with_route()
resolve = make_node_resolver([HUB, FAR])
learned = _plain([_route_row(("3d63c6429436",), resolve=resolve, self_name="Us").plain])
assert "device route" in learned and "Hub" in learned
assert "(3d)" in learned # the first-byte tag, matching the graph's byte label
assert "floods" in _route_row(None, resolve=resolve, self_name="Us").plain # no route
best = topo.suggested("f2c24f54551e")
suggest = _suggest_row(best, resolve=resolve, self_name="Us")
assert "Hub" in suggest.plain and "(3d)" in suggest.plain and "×" in suggest.plain
assert "none observed" in _suggest_row(None, resolve=resolve, self_name="Us").plain
def test_path_view_draws_evidence_and_notes_its_absence() -> None:
"""With route evidence the graph draws us→node; without any, a muted note stands in."""
topo = _topo_with_route()
style_args = dict(
resolve=make_node_resolver([HUB, FAR]),
type_of=make_node_type_resolver([HUB, FAR]),
key_of=make_name_key_resolver([HUB, FAR]),
style=route_graph_style,
self_name="Us",
node_label="Far",
)
view = _path_view(
topo, topo.scenarios("f2c24f54551e", device_route=("3d63c6429436",)),
topo.suggested("f2c24f54551e"), ("3d63c6429436",), "f2c24f54551e", **style_args,
)
assert view.layers and view.glyph_of is not None # a graph, not a note
# The Hub is a repeater, so the graph earns its node-type legend.
assert view.legend is True
empty = build_topology(self_id=US + "0" * 52, contacts=[FAR],
trace_paths=[], packet_paths=[], neighbour_links=[])
note = _path_view(
empty, empty.scenarios("f2c24f54551e"), None, None, "f2c24f54551e", **style_args
)
assert not note.layers and "no route observed" in note.note
def test_path_view_puts_us_on_the_left_and_the_target_on_the_right() -> None:
"""The route graph reads us → target: our star on the left endpoint, the node on the right."""
from meshterm.ui.pathgraph import DST_NODE, SRC_NODE
topo = _topo_with_route()
view = _path_view(
topo, topo.scenarios("f2c24f54551e", device_route=("3d63c6429436",)),
topo.suggested("f2c24f54551e"), ("3d63c6429436",), "f2c24f54551e",
resolve=make_node_resolver([HUB, FAR]),
type_of=make_node_type_resolver([HUB, FAR]),
key_of=make_name_key_resolver([HUB, FAR]),
style=route_graph_style, self_name="Us", node_label="Far",
)
assert view.glyph_of(SRC_NODE)[0] == "★" # the left endpoint is our own star
assert view.label_of(SRC_NODE) == "Us" # …labelled as us
assert view.label_of(DST_NODE) == "Far" # the right endpoint is the target
# A relay resolves to its first hash byte, wherever it lands between the endpoints.
assert view.label_of("3d63c6429436") == "3d"
def test_located_accepts_real_fixes_and_rejects_junk() -> None:
"""The location preview is gated on a real fix — no null island, no out-of-range advert."""
from meshterm.ui.node_detail_screen import _located
assert _located(45.5, -73.6) is True
assert _located(None, -73.6) is False # missing coordinate
assert _located(0.0, 0.0) is False # null island (no-GPS sentinel)
assert _located(-97.0, -1041.97) is False # the Homestead out-of-range advert
# --- the screen -----------------------------------------------------------------
def _screen(**over) -> NodeDetailScreen:
"""A node detail screen over hand-built display data (no map, a bare path note)."""
header = Text("▲ ", style="#a78bfa")
header.append("Hub", style="accent")
header.append(" repeater", style="muted")
kwargs = dict(
title="Node — Hub",
header=header,
info_rows=[
("key", highlighted_hash("3d63c6429436" + "0" * 52, 1)),
("heard", Text("5m ago")),
("packets", Text("42")),
],
actions=[
_Action("trace", "🎯", "", "Trace target — suggested path"),
_Action("timemachine", "⏳", "", "Time machine — 42 receptions"),
_Action("back", "", "", "Back"),
],
minimap=None,
map_caption=None,
path=_PathView(note="no route observed yet — trace to discover one"),
)
kwargs.update(over)
return NodeDetailScreen(**kwargs)
def test_node_detail_screen_renders_its_sections() -> None:
"""The page shows identity, info, the path section, and the action rows."""
screen = _screen()
body = _plain(screen.render_body(72))
assert "Hub" in body and "repeater" in body # identity
assert "42" in body # a packet tally from the info block
assert "Path to node" in body and "no route observed yet" in body
assert "Trace target" in body and "Time machine" in body and "Back" in body
# Every rendered line fits the 72-column standard.
for line in screen.render_body(72):
assert len(_plain([line])) <= 72
assert len(screen.footer_hint) <= 72
def test_node_detail_screen_cursor_and_commit() -> None:
"""↑/↓ move the action cursor (pinned in view); Enter resolves its key, Esc cancels."""
screen = _screen()
resolved: list = []
screen.resolve = lambda value: resolved.append(value) # type: ignore[method-assign]
# Opens un-pinned (top visible) with the cursor on the first action.
assert screen.cursor_line() is None
screen.render_body(72)
screen.handle("down") # onto "Time machine"
assert screen._pin_cursor and screen.cursor_line() is not None
screen.render_body(72)
screen.handle("enter")
assert resolved == ["timemachine"]
screen.handle("escape")
assert resolved == ["timemachine", CANCEL]
def test_node_detail_screen_includes_the_location_section_with_a_map() -> None:
"""A located node draws the Location heading and the inline preview under it."""
mini = MiniMap(
_FakeSession(), _OfflineSource(), 14,
center_lat=45.5, center_lon=-73.6, zoom=13,
markers=[MapMarker(label="Hub", lat=45.5, lon=-73.6, key="3d63aa")],
)
screen = _screen(minimap=mini, map_caption=Text("Hub · centred here", style="faint"))
body = _plain(screen.render_body(72))
assert "Location" in body and "centred here" in body
assert screen.consume_edge_scrub() == 2 # the braille edge gets scrubbed
+21
View File
@@ -139,6 +139,27 @@ def test_scenarios_rank_observed_route_and_pin_device_route_first() -> None:
assert sum(1 for s in scenarios if s.hops == ("3d63c6429436",)) == 1
def test_suggested_returns_the_strongest_observed_route_only() -> None:
"""suggested() is the data's answer: the best observed multi-hop route to the target."""
walks = [
_traced(("3d", 12.0), ("f2", -5.0), ("3d", -5.5), (None, 12.0)) for _ in range(4)
]
topo = _topo(trace_paths=walks)
best = topo.suggested("f2c24f54551e")
assert best is not None
assert best.source == "observed" # never the device/direct families
assert best.hops == ("3d63c6429436",) # us → Hub → Far
assert best.score > 0 and best.samples >= 4 # evidence-backed
def test_suggested_is_none_without_an_observed_repeater_route() -> None:
"""A target ever only reached directly (or not at all) has no route to suggest."""
# One direct trace to the Hub — us → Hub → us, no intermediate repeater.
topo = _topo(trace_paths=[_traced(("3d", 9.0), (None, 9.0))])
assert topo.suggested("3d63c6429436") is None # direct-only: nothing to suggest
assert topo.suggested("f2c24f54551e") is None # never reached at all
def test_scenario_spec_ends_at_target_and_collapses_width() -> None:
"""Specs walk out to the target then mirror the hops back, at a uniform width."""
walks = [_traced(("3d", 12.0), ("f2", -5.0), ("3d", -5.5), (None, 12.0))]