Shared logic sits in the layer that reads it, and the CLI answers --version

A pre-release architecture and QA pass, applied as one change because the moves
share files and only the whole set was gate-tested (2480 passed, ruff clean).

Three new modules pull logic down out of layers that should not own it:
core/channel_probe.py (ChannelSlot, read_channel_slots, probe_channel_slots)
so services/device_state.py no longer imports a screen; services/markers.py
(gather_markers, with MapMarker a core/models dataclass) so two screens stop
importing a tool; core/tracing.py (trace_timeout, path_hash_flags) so
core/connection.py no longer imports services. The routing-prefix width is
DeviceState.routing_prefix_bytes(), replacing five private cross-module imports.

One definition per thing: is_path_hash, the NodeResolver/NameKeyResolver
aliases, TILE_RETRY_SECONDS, haversine_km, marks.SELF_MARK, MENTION; nine
private names that crossed module boundaries got public ones and menus.__all__
lists what other modules import. A preference's default is written once
(ALERT_CAP, DONE_CAP, DEFAULT_VIEW_FRACTION read the registry), the stranded
PREFERENCES doc comment sits on its subject, and three docstrings stop naming
questionary, a library dropped long ago.

The command line gains --version (eager, exit 0, documented, tested) and drops
the -p short form on trace, trace-path and tx-optimize: the root lifts -p as
--profile before a leaf ever sees it, so the leaf's could never work, and a
derived test now checks every leaf against every root short option.
tx-optimize with a one-hop --path is a usage error, exit 2, because nothing
transmitted is not a device failure. Log handlers are closed before they are
cleared (197 unclosed-file warnings gone), chat's fire-and-forget tasks keep a
reference, coroutines use get_running_loop(), the never-awaited MapScreen._load
in a test is awaited, and the CLI sweep passes --no-ble to devices so a test
run stops turning on the Bluetooth radio three times (the suite is 40 % faster).
The about page lists every dependency, and the release skill bumps the README's
download names, which still said 0.2.8.

apply_ops stays in tools/: it and its helpers build report blocks and open two
screens, so moving it to core/ would invert core over ui. The widgets CLAUDE.md
names by their private spellings (_format_age, _NODE_GLYPHS) keep them until
CLAUDE.md is edited alongside.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Fable 5.1 committed 2026-09-12 19:19:45 -04:00
1 parent 8b80a88f03
commit ffd2649a35
69 files changed
+924 -712

No files matched your search

+18
View File
@@ -96,6 +96,24 @@ version is written**. `[project] version` in `pyproject.toml` is `dynamic` and h
reads the attribute, so the number in a built wheel cannot drift from the number in the
source. Do not add a second one.
### Then re-point the README's download commands
`installers.yml` names each asset `meshterm-${version}-<label><ext>`, so **the file a reader
downloads is named after the release** — and the README tells them what to type at it. Those
lines are prose, not code, so nothing rewrites them for you:
```
grep -n '<the previous version>' README.md
```
Every hit is a download or run command (`.\meshterm-X.Y.Z-windows-x64.exe`,
`chmod +x meshterm-X.Y.Z-*`, the `xattr` quarantine note, the `MESHTERM_HOME` trial runs).
Replace the old number with the one just bumped to, and re-read each line: they must name
the file the workflow is about to publish, or the first thing a new user does fails.
Also check `docs/cli.md` for a sample document carrying a `"version"` field, which is the
live `{version}` placeholder and must show the new number too.
## 5. Commit, tag, push
```
+10 -8
View File
@@ -51,6 +51,7 @@ With no command, MeshTerm launches the interactive menu instead.
| Option | What it does |
| --- | --- |
| `--version` | Print `meshterm <version>` and exit `0`, before anything else is opened. |
| `-p`, `--profile NAME` | Use a named device profile from `config.toml`. |
| `--port PORT` | Serial port to connect to (`COM5`, `/dev/ttyACM0`), overriding the profile. |
| `--ble ADDRESS` | Bluetooth address of a companion; selects the BLE transport. |
@@ -70,8 +71,8 @@ for. A bare `--` stops the lifting, the standard way to say the rest is data, an
`--help` is never lifted: `meshterm contacts --help` stays the *contacts* help.
Commands that need a radio open one, do their work, and close it. Commands that only read
stored history (`records`) or MeshTerm's own state (`preferences`, the written pages) need
no device at all and work with nothing attached.
stored history (`records`) or MeshTerm's own state (`preferences`, `platform`, `specimen`,
the written pages) need no device at all and work with nothing attached.
> **One transmission per invocation.** A trace transmits exactly once — repeaters
> penalise, and can blacklist, nodes that burst traffic. To sample more, run the command
@@ -984,7 +985,7 @@ The live transcript is a menu screen; from the command line, pick a subcommand.
| `send TEXT --channel N` | Broadcast on a channel slot. |
| `history [--to NAME \| --channel N] [--limit N]` | Print a conversation's stored transcript. Default limit 50. |
| `list` | Every channel and contact with its unread count and last message. |
| `listen [-s SECONDS] [--debug]` | Tail inbound messages live. |
| `listen [-s SECONDS] [--debug]` | Tail inbound messages live. `-s 0` (the default) runs until Ctrl-C. |
Exactly one of `--to` and `--channel` is required on `send` and `history`.
@@ -1201,7 +1202,7 @@ Walk the path to a target once and report what came back.
| Option | What it does |
| --- | --- |
| `-t`, `--target NAME` | **Required.** Target node name or key prefix. |
| `-p`, `--path SPEC` | Force a route: comma-separated contact names and/or hex hashes, mixed freely (`3d,f2,3d`). Omit it and the device routes. |
| `--path SPEC` | Force a route: comma-separated contact names and/or hex hashes, mixed freely (`3d,f2,3d`). Omit it and the device routes. |
`--target` is required, so `meshterm trace --path …` alone is a usage error — the
target-free form is [`trace-path`](#meshterm-trace-path).
@@ -1238,7 +1239,7 @@ whichever way you choose. It only has to end within earshot of this node.
| Option | What it does |
| --- | --- |
| `-p`, `--path SPEC` | **Required.** The whole walk, comma-separated. |
| `--path SPEC` | **Required.** The whole walk, comma-separated. |
```console
$ meshterm trace-path --path "a1,d4,a1"
@@ -1288,7 +1289,7 @@ gets through reliably.
| Option | What it does |
| --- | --- |
| `-p`, `--path SPEC` | **Required.** Forced path ending at the target (`Repeater,Target`, or `3d,f2`). The hop before the target is the node being tuned. |
| `--path SPEC` | **Required.** Forced path ending at the target (`Repeater,Target`, or `3d,f2`). The hop before the target is the node being tuned. |
| `-n`, `--samples N` | Traces per TX level. Default 3. |
| `--step N` | Coarse sweep step. Default 3. |
| `--min N` / `--max N` | Bound the sweep (else the `tx_opt_min` / `tx_opt_max` preferences). |
@@ -1388,7 +1389,8 @@ CLI grammar, and a document that pretended to would be inventing structure. `rep
#### `meshterm preferences`
How MeshTerm behaves, as opposed to how the radio is configured. Reads nothing from the
companion, transmits nothing, and works with no device attached.
companion, transmits nothing, and works with no device attached. With no subcommand it
runs `show`.
| Subcommand | What it does |
| --- | --- |
@@ -1455,7 +1457,7 @@ each link; the scripted face prints the link alone.
**`--json`:**
```json
{"page":"discord","title":"Join Discord","version":"0.2.8","text":"Join the Discord\n Questions, ideas, bug reports, and mesh talk.\n\n • https://discord.gg/AZwe5Uvb3S","links":["https://discord.gg/AZwe5Uvb3S"]}
{"page":"discord","title":"Join Discord","version":"0.3.2","text":"Join the Discord\n Questions, ideas, bug reports, and mesh talk.\n\n • https://discord.gg/AZwe5Uvb3S","links":["https://discord.gg/AZwe5Uvb3S"]}
```
| Field | Type | Meaning |
+2 -2
View File
@@ -58,8 +58,8 @@ author — a fork that keeps soliciting through it, without pointing it at
itself, isn't affiliated with MeshTerm.
Built on **MeshCore** *https://meshcore.io/* — its firmware and companion
library — with Rich, prompt_toolkit, Typer, bleak, pyserial, pycryptodome
and Segno, each under its own terms.
library — with Rich, prompt_toolkit, Typer, bleak, pyserial, pycryptodome,
markdown-it-py, PyYAML, tomli/tomli-w and Segno, each under its own terms.
Map data **© OpenStreetMap contributors**, served as vector tiles by
**OpenFreeMap** *https://openfreemap.org/*, used under the
+24
View File
@@ -17,6 +17,7 @@ import typer
from rich.console import Console
from typer.core import TyperGroup
from . import __version__
from .context import AppContext
from .core import exitcodes, win32dll
from .core.admin_store import AdminStore
@@ -126,6 +127,21 @@ app = typer.Typer(
epilog=EXIT_STATUS_EPILOG,
)
def _print_version(value: bool) -> None:
"""Print the version and stop, the moment ``--version`` is seen.
Eager, so it answers before the callback opens a database, resolves a platform or looks
for a radio — the one question that is true of the program rather than of a run. Bare
``meshterm <version>``: the caller asked for a version, and a script reading it back has
one field to take. Exits ``0``, because knowing the version is a success.
"""
if not value:
return
script.console().print(f"meshterm {__version__}", highlight=False)
raise typer.Exit(exitcodes.OK)
# The context built by the callback and consumed by subcommands within one process.
_state: AppContext | None = None
@@ -137,6 +153,13 @@ _platform_resolution: Resolution | None = None
@app.callback(invoke_without_command=True)
def main_callback(
ctx: typer.Context,
version: bool = typer.Option(
False,
"--version",
help="Print the version and exit",
callback=_print_version,
is_eager=True,
),
profile: str | None = typer.Option(None, "--profile", "-p", help="Device profile"),
port: str | None = typer.Option(None, "--port", help="Serial port override"),
ble: str | None = typer.Option(
@@ -167,6 +190,7 @@ def main_callback(
Args:
ctx: The Click/Typer context.
version: Print the version and exit (handled eagerly by :func:`_print_version`).
profile: Named device profile to use.
port: Explicit serial port, overriding the profile.
ble: Explicit Bluetooth address, selecting the BLE transport.
+165
View File
@@ -0,0 +1,165 @@
"""Reading the device's channel slots back off the radio.
One configured channel slot (:class:`ChannelSlot`) and the two reads that discover them.
Every derived property on the slot delegates to :mod:`meshterm.core.channels`, which owns the
key/identity maths; this module is only the device-facing half — the scan, and what it means
when the scan stops.
It lives in :mod:`meshterm.core` rather than beside the channel manager screen because the
screen is not the only reader: the device-state session cache
(:class:`~meshterm.services.device_state.DeviceState`) warms the probe, the ``channels`` and
``chat`` tools read slots for their CLI faces, and a service must never have to reach up into
``ui/`` for a device read. It is a separate module from :mod:`meshterm.core.channels` because
it needs :class:`~meshterm.core.connection.Device`, and ``connection`` already imports
``channels`` — keeping the maths free of the transport is what keeps that direction one-way.
"""
from __future__ import annotations
from dataclasses import dataclass
from .channels import (
CHANNEL_SLOT_EMPTY_RUN,
CHANNEL_SLOT_PROBE_CAP,
channel_hash,
channel_identity,
full_channel_hash,
is_name_derived,
is_public_channel,
)
from .connection import Device, DeviceCommandError, is_connection_lost
from .models import Conversation
@dataclass(slots=True)
class ChannelSlot:
"""One configured channel slot read back from the device.
Attributes:
idx: The 0-based slot index.
name: The channel's name.
secret: The channel's 16-byte shared secret.
"""
idx: int
name: str
secret: bytes
@property
def is_name_derived(self) -> bool:
"""Whether this channel's key is reproducible from its name (so it needn't be stored)."""
return is_name_derived(self.name, self.secret)
@property
def is_public(self) -> bool:
"""Whether this channel is public (shared meshwide) rather than a private one.
Covers both name-derived channels and the firmware's fixed-key default ``Public``.
"""
return is_public_channel(self.name, self.secret)
@property
def hash(self) -> str:
"""The channel's two-character hash fingerprint (the leading byte MeshCore shows)."""
return channel_hash(self.secret)
@property
def full_hash(self) -> str:
"""The channel's complete ``sha256(secret)`` digest; its first byte is :attr:`hash`."""
return full_channel_hash(self.secret)
@property
def identity(self) -> str:
"""The channel's slot-independent identity, used to key its chat history."""
return channel_identity(self.name, self.secret)
@property
def conversation(self) -> Conversation:
"""A :class:`~meshterm.core.models.Conversation` for opening this channel in chat."""
return Conversation(
label=self.name,
is_channel=True,
channel_idx=self.idx,
channel_id=self.identity,
secret=self.secret,
)
async def read_channel_slots(device: Device) -> list[ChannelSlot]:
"""Probe the channel slots and return the configured ones, in index order.
The scan stops as soon as the firmware rejects a slot index, so it reads exactly the
slots a well-behaved device has regardless of its capacity. Firmware that never rejects
an out-of-range index (it answers every slot with an empty payload instead of raising)
would otherwise walk all :data:`CHANNEL_SLOT_PROBE_CAP` slots on every read; a run of
:data:`CHANNEL_SLOT_EMPTY_RUN` consecutive empty slots ends the scan on such firmware.
That is safe because the manager packs channels from slot 0 up, so an unbroken empty run
that long means every configured channel has already been seen (see the constant's note).
Args:
device: The connected device to query.
Returns:
One :class:`ChannelSlot` per configured slot (an empty slot is skipped).
"""
slots, _complete = await probe_channel_slots(device)
return slots
async def probe_channel_slots(device: Device) -> tuple[list[ChannelSlot], bool]:
"""The probe behind :func:`read_channel_slots`, reporting whether it *finished*.
The scan stops for two very different reasons and the plain list cannot tell them
apart. Off the end of the configured slots (a rejected index, or a long enough run of
empty ones) the answer is complete and worth keeping. A read that simply *failed* —
a timeout, a link hiccup, and then every subsequent read failing too because the
firmware's reply no longer matches the slot asked for — ends the scan early with
whatever it happened to have, which is not the device's layout and must not be cached
or acted on as if it were: an empty one reads as "no channels configured", and a
truncated one makes the next free slot look free when a channel is sitting in it.
The two endings raise different things, and that is what separates them: the firmware
*answering* "no such slot" surfaces as a plain rejection, while a link that stopped
answering surfaces as a timeout, a :class:`~meshterm.core.connection.DeviceCommandError`
(whose whole subject is a companion that did not reply in time), or one of the dropped-
link signatures :func:`~meshterm.core.connection.is_connection_lost` knows. Only the
first ending is a layout. A read that fails for some fourth reason is treated as a
rejection, which is the safe way round: the list is used but the cache re-probes.
Args:
device: The connected device to query.
Returns:
The slots read, and whether the scan ran to a clean end.
"""
slots: list[ChannelSlot] = []
empty_run = 0
for idx in range(CHANNEL_SLOT_PROBE_CAP):
try:
payload = await device.get_channel(idx)
except Exception as exc: # noqa: BLE001 - a rejected index, or a read that failed
return slots, not _read_failed(exc)
if payload and payload.get("channel_name"):
empty_run = 0
slots.append(
ChannelSlot(
idx=idx,
name=str(payload["channel_name"]),
secret=bytes(payload.get("channel_secret") or b"\x00" * 16),
)
)
else:
empty_run += 1
if empty_run >= CHANNEL_SLOT_EMPTY_RUN:
break # off the end of a never-rejecting firmware; nothing more to find
return slots, True
def _read_failed(exc: BaseException) -> bool:
"""Whether ``exc`` means the *read* failed, rather than the firmware refusing a slot.
A refusal is the probe's ordinary ending and leaves a complete list behind it. A
failure leaves a short one that looks exactly the same — which is the whole reason
this distinction has to be drawn somewhere (see :func:`probe_channel_slots`).
"""
return isinstance(exc, (TimeoutError, DeviceCommandError)) or is_connection_lost(exc)
+8 -1
View File
@@ -35,6 +35,13 @@ from urllib.parse import parse_qs, quote, urlsplit
#: be followed by ``": "`` — conservative enough to leave ``http://…`` and ``note:x`` alone.
SENDER_PREFIX = re.compile(r"^([^\s:][^:]{0,19}):[ \t]+(.*)$", re.DOTALL)
#: Matches an ``@[Name]`` mention token, as the reply flow primes into the compose line. A
#: transcript renders each as a bare ``@Name`` coloured in that sender's hue instead of
#: showing the literal brackets, and the CLI's history face lifts the same names out — so the
#: token lives here with the rest of the message-body parsing rather than in either renderer.
#: Name is 1–20 non-``]`` characters.
MENTION = re.compile(r"@\[([^\]]{1,20})\]")
def split_channel_sender(text: str) -> tuple[str | None, str]:
"""Split a channel message into ``(sender_name, body)`` when it carries a name prefix.
@@ -74,7 +81,7 @@ MAX_CHANNELS = 8
CHANNEL_SLOT_PROBE_CAP = 64
#: A run of this many consecutive *empty* slots ends a *configured-channel* scan (see
#: :func:`meshterm.ui.channels.read_channel_slots`) on firmware that never rejects an
#: :func:`meshterm.core.channel_probe.read_channel_slots`) on firmware that never rejects an
#: out-of-range index — some builds answer every index with an empty payload instead of
#: raising, so the scan would otherwise walk all :data:`CHANNEL_SLOT_PROBE_CAP` slots on
#: every read. The channel manager packs channels from slot 0 up within the stock
+3 -8
View File
@@ -41,6 +41,7 @@ from .models import (
advert_time,
utcnow,
)
from .tracing import path_hash_flags, trace_timeout
if TYPE_CHECKING:
from .discovery import DiscoveredDevice
@@ -704,7 +705,7 @@ class Device(ABC):
timeout: Seconds to wait for the trace reply. ``None`` (the default) sizes the
wait to the route: a trace has to travel the whole path out and back, so a
long walk is given proportionally longer to come home
(:func:`~meshterm.services.trace_runner.trace_timeout`).
(:func:`~meshterm.core.tracing.trace_timeout`).
Returns:
A :class:`TraceResult`; ``success`` is ``False`` on timeout.
@@ -1924,8 +1925,6 @@ class MeshCoreDevice(Device):
async def admin_login(self, node: Contact, password: str) -> LoginResult: # noqa: D102
from meshcore import EventType
from ..services.trace_runner import trace_timeout
mc = self._require()
pub = self._node_pubkey(node)
loop = asyncio.get_running_loop()
@@ -2159,11 +2158,9 @@ class MeshCoreDevice(Device):
transmit_gate.mark()
from meshcore import EventType # local import keeps mock path dependency-free
from ..services.trace_runner import path_hash_flags, trace_timeout
mc = self._require()
tag = random.randint(0, 0xFFFFFFFF)
loop = asyncio.get_event_loop()
loop = asyncio.get_running_loop()
started = loop.time()
# A trace packet has no destination field — it walks an explicit path of
@@ -2286,8 +2283,6 @@ class MeshCoreDevice(Device):
``(path_bytes, flags)`` to walk, or ``None`` only when the contact is
unknown or carries no public key to address.
"""
from ..services.trace_runner import path_hash_flags
payload = await self._contacts_payload(mc)
needle = target.casefold()
for name, info in payload.items():
+2 -2
View File
@@ -529,7 +529,7 @@ def rank_contacts(
gathered: list[ContactSignals] = []
for contact in contacts:
node = _node_id(contact)
node = node_id(contact)
found = signals.get(node) or ContactSignals(node=node)
gathered.append(replace(found, distance_km=_self_distance(contact, self_lat, self_lon)))
@@ -607,7 +607,7 @@ def sweep_candidates(ranked: Sequence[ScoredContact], keep: int) -> list[ScoredC
return list(reversed(victims))
def _node_id(contact: Contact) -> str:
def node_id(contact: Contact) -> str:
"""The 12-hex canonical id a contact's history is keyed by (see ``observations.node``)."""
ident = contact.public_key or contact.key_prefix or ""
return ident.lower().removeprefix("0x")[:12]
+2 -1
View File
@@ -28,7 +28,8 @@ DELIVERED = "delivered"
GAVE_UP = "gave-up"
#: How many finished (delivered / given-up) entries are kept for the screen's history —
#: the code's default behind the ``courier_history_kept`` preference.
#: *the* default behind the ``courier_history_kept`` preference, which the registry names
#: rather than re-types (:data:`meshterm.core.preferences.PREFERENCES`).
DONE_CAP = 100
+6 -2
View File
@@ -33,7 +33,9 @@ TILE_PX = 256
#: :mod:`meshterm.ui.map_screen` for it dragged the whole map stack (and, through the
#: basemap's tile fetcher, ``urllib.request`` → ``http.client`` → ``ssl``) into every run,
#: including runs that never open a map. This module is pure arithmetic and already on the
#: boot path, so the constant is free here.
#: boot path, so the constant is free here. It is also what the ``map_view_fraction``
#: preference defaults to — the registry names this constant rather than re-typing the
#: number, so the code default and the preference default are one value.
DEFAULT_VIEW_FRACTION = 0.5
@@ -87,7 +89,9 @@ def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
dphi = math.radians(lat2 - lat1)
dlambda = math.radians(lon2 - lon1)
a = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlambda / 2) ** 2
return 2 * EARTH_RADIUS_KM * math.asin(math.sqrt(a))
# Clamped because rounding can push ``a`` a hair past 1 for near-antipodal points, and
# ``asin`` of that raises a domain error rather than returning half the planet.
return 2 * EARTH_RADIUS_KM * math.asin(min(1.0, math.sqrt(a)))
def _central_points(
+48
View File
@@ -8,10 +8,25 @@ from __future__ import annotations
import statistics
from collections import Counter
from collections.abc import Callable
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from enum import Enum
#: Maps a hop's raw key-prefix hash to a display label (a contact name when known, or the
#: hash itself when not). ``None`` passes through, being our own device. THE alias for the
#: name side of a hop, shared by everything that builds one
#: (:func:`~meshterm.services.trace_runner.make_node_resolver`) and everything that takes
#: one (every screen that draws a route).
NodeResolver = Callable[[str | None], str | None]
#: Maps a display name back to the node's key — as full as we hold one: a public key, a key
#: prefix, or a stored node id — or ``None`` for a name no known node carries. The colour
#: side of :data:`NodeResolver`: where that turns hex into names, this turns a bare name back
#: into the key its palette hue derives from
#: (:func:`~meshterm.services.trace_runner.make_name_key_resolver`).
NameKeyResolver = Callable[[str], str | None]
#: Label used for our own (local) device when framing a trace path's endpoints.
LOCAL_DEVICE_LABEL = "us"
@@ -177,6 +192,39 @@ class Contact:
return self.node_type == NODE_TYPE_REPEATER
@dataclass(slots=True)
class MapMarker:
"""One mesh node to overlay on the map.
Data, not drawing: a located node with the little the map needs to place and label it.
It lives here rather than beside the renderer because it is assembled well below the UI
— :func:`~meshterm.services.markers.gather_markers` builds the list from contacts and
observations, and three separate surfaces draw it.
Attributes:
label: Node name shown beside the marker.
lat: Latitude in decimal degrees.
lon: Longitude in decimal degrees.
is_repeater: Whether the node is a repeater (prioritised marker).
is_self: Whether this is our own node (highlighted).
detail: Extra text for the CLI legend (e.g. ``"18 pkts · +6.0 dB"``).
key: The node's key hex (as full as the caller holds), seeding the label's
key-derived hue; ``None`` leaves the label the muted no-key grey.
"""
label: str
lat: float
lon: float
is_repeater: bool = False
is_self: bool = False
detail: str = ""
key: str | None = None
def _rank(self) -> int:
"""Draw order: self on top of repeaters on top of leaf nodes."""
return 2 if self.is_self else (1 if self.is_repeater else 0)
@dataclass(slots=True)
class NeighbourInfo:
"""One entry of a remote repeater's neighbour table, fetched over the mesh.
+14 -10
View File
@@ -43,7 +43,9 @@ from pathlib import Path
from typing import Any
from .atomicwrite import write_atomically
from .watch_store import DEFAULT_SILENCE_HOURS, OFF, SILENCE_CHOICES_H
from .courier_store import DONE_CAP
from .geo import DEFAULT_VIEW_FRACTION
from .watch_store import ALERT_CAP, DEFAULT_SILENCE_HOURS, OFF, SILENCE_CHOICES_H
#: Display groups, in the order the page and the file present them. The order is the
#: order a session happens in — what MeshTerm puts on the air, how loud, what it watches
@@ -140,12 +142,6 @@ _COLOR_DEPTH_CHOICES: dict[str, str] = {
"16": "16",
}
#: Every preference MeshTerm has, in page order. Adding one here gives it a row on the
#: Preferences page, a key in the YAML file, a ``preferences get``/``set`` CLI face, and a
#: default — nothing else has to follow.
#: What the log file keeps. The plain level names, which are what every other tool calls
#: these — someone being talked through a problem is being told "set it to debug", not
#: "set it to everything".
#: What MeshTerm may offer when it lands in a console that cannot draw it. Only ever
#: consulted on the classic Windows console, the one host with no font fallback of its own.
_CONSOLE_SETUP_CHOICES: dict[str, str] = {
@@ -153,6 +149,9 @@ _CONSOLE_SETUP_CHOICES: dict[str, str] = {
"off": "Leave it alone",
}
#: What the log file keeps. The plain level names, which are what every other tool calls
#: these — someone being talked through a problem is being told "set it to debug", not
#: "set it to everything".
_LOG_LEVEL_CHOICES: dict[str, str] = {
"ERROR": "Error",
"WARNING": "Warning",
@@ -161,6 +160,11 @@ _LOG_LEVEL_CHOICES: dict[str, str] = {
}
#: Every preference MeshTerm has, in page order. Adding one here gives it a row on the
#: Preferences page, a key in the YAML file, a ``preferences get``/``set`` CLI face, and a
#: default — nothing else has to follow. A default that a module already states as its
#: code-level behaviour is named, never re-typed: one source, so changing it cannot leave
#: the constant and the registry disagreeing about what MeshTerm does.
PREFERENCES: tuple[PrefSpec, ...] = (
# --- Sending -----------------------------------------------------------------
PrefSpec(
@@ -245,7 +249,7 @@ PREFERENCES: tuple[PrefSpec, ...] = (
help="How many past alerts to keep",
group="Watchtower",
value_type="int",
default=200,
default=ALERT_CAP,
minimum=10,
maximum=5000,
),
@@ -256,7 +260,7 @@ PREFERENCES: tuple[PrefSpec, ...] = (
help="Share of nodes to fit on screen; 1 shows them all",
group="Map",
value_type="float",
default=0.5,
default=DEFAULT_VIEW_FRACTION,
minimum=0.1,
maximum=1.0,
),
@@ -297,7 +301,7 @@ PREFERENCES: tuple[PrefSpec, ...] = (
help="Finished outbox messages to keep",
group="History",
value_type="int",
default=100,
default=DONE_CAP,
minimum=10,
maximum=5000,
),
+81
View File
@@ -0,0 +1,81 @@
"""The arithmetic a trace is sized and flagged by.
Two pure functions and the four constants behind them: how a per-hop path-hash width is
encoded into the trace ``flags`` byte, and how long to wait for a trace's reply given the
route it has to walk. Both are protocol arithmetic with no device, no persistence and no
rendering, and :class:`~meshterm.core.connection.MeshCoreDevice` needs them on the send path —
they live here so ``core`` never has to reach up into ``services`` for them. The trace
*runner* (:mod:`meshterm.services.trace_runner`) re-exports both under their own names, which
is where every other caller still reads them from.
"""
from __future__ import annotations
def path_hash_flags(width_bytes: int) -> int | None:
"""Return the trace ``flags`` value that encodes a per-hop path-hash width.
The trace subsystem encodes the hash size as ``1 << (flags & 3)`` on both the
send and receive sides (``send_trace`` and the ``TRACE_DATA`` reader), so only
widths of 1, 2, 4, or 8 bytes are representable. This is independent of, and
differs from, the ``mode = size - 1`` encoding used for *contact routing*
(``out_path_hash_mode``).
Args:
width_bytes: Path-hash width in bytes.
Returns:
The flags value (the exponent ``s``), or ``None`` if the width is not a
representable power of two.
"""
for s in range(4):
if (1 << s) == width_bytes:
return s
return None
#: Fixed overhead in a trace's reply-wait budget, in seconds: our own transmit, the far
#: endpoint's turnaround, and our receive-side decode — the cost that doesn't grow with
#: the route.
TRACE_TIMEOUT_BASE_S = 4.0
#: Per-hop allowance added to the budget, in seconds. Each entry in the walked path is one
#: relay transmission, and this covers its packet airtime, the repeater's processing, and
#: the randomised transmit backoff MeshCore adds so relays don't collide.
TRACE_TIMEOUT_PER_HOP_S = 1.6
#: Upper bound on the reply-wait, in seconds, so a route that never comes home still
#: surrenders the trace (and the session) in bounded time rather than scaling without end.
TRACE_TIMEOUT_CEILING_S = 30.0
#: Fallback budget, in seconds, when the hop count can't be known ahead of the send — a
#: path-less flood to a contact we hold no route for. This is the historical flat value,
#: kept for exactly the case where we can't size the walk.
TRACE_TIMEOUT_FLOOD_S = 10.0
def trace_timeout(hop_count: int) -> float:
"""Return the reply-wait budget, in seconds, for a trace walking ``hop_count`` hops.
A trace is a *single* packet that has to travel the whole path — out to the far hop
and back over the mirrored return leg — before its reply reaches us, so the wait has
to grow with the route. A flat budget sized for a neighbour cuts a long walk off
mid-flight: the packet completes the circuit on the mesh, but our wait has already
expired, so we log a phantom "no reply" for a route that actually worked. The budget
is a fixed base (:data:`TRACE_TIMEOUT_BASE_S`) plus a per-hop allowance
(:data:`TRACE_TIMEOUT_PER_HOP_S`) for each relay transmission, capped at
:data:`TRACE_TIMEOUT_CEILING_S`.
``hop_count`` is the number of hops in the *transmitted* path, which already includes
the mirrored return leg (see
:meth:`~meshterm.core.connection.MeshCoreDevice._trace_path_to_contact`), so it maps
one-to-one onto relay transmissions and must not be doubled here.
Args:
hop_count: Hops in the walked path (return leg included). ``0`` (or less) means the
count is unknown — a path-less flood — and yields :data:`TRACE_TIMEOUT_FLOOD_S`.
Returns:
The number of seconds to wait for the trace reply.
"""
if hop_count <= 0:
return TRACE_TIMEOUT_FLOOD_S
budget = TRACE_TIMEOUT_BASE_S + TRACE_TIMEOUT_PER_HOP_S * hop_count
return min(budget, TRACE_TIMEOUT_CEILING_S)
+3 -2
View File
@@ -37,8 +37,9 @@ DEFAULT_SILENCE_HOURS = 12
#: The stored value meaning "this rule is off".
OFF = 0
#: How many alerts the log retains (oldest dropped first) — the code's default behind
#: the ``watch_alerts_kept`` preference.
#: How many alerts the log retains (oldest dropped first) — *the* default behind the
#: ``watch_alerts_kept`` preference, which the registry names rather than re-types
#: (:data:`meshterm.core.preferences.PREFERENCES`), so the two can never disagree.
ALERT_CAP = 200
#: Minimum seconds between disk flushes for the packet-driven last-heard updates.
+19 -2
View File
@@ -97,7 +97,7 @@ def configure_logging(
"""
logger = logging.getLogger(_LOGGER_NAME)
logger.setLevel(logging.DEBUG)
logger.handlers.clear()
_drop_handlers(logger)
logger.propagate = False
if not quiet:
@@ -161,12 +161,29 @@ def _quiet_library_console(file_handler: logging.Handler) -> None:
for name in _LIBRARY_LOGGERS:
lib = logging.getLogger(name)
lib.handlers.clear()
_drop_handlers(lib)
lib.setLevel(logging.INFO)
lib.propagate = False
lib.addHandler(file_handler)
def _drop_handlers(logger: logging.Logger) -> None:
"""Detach ``logger``'s handlers, closing each on the way out.
Clearing the list alone drops the *reference* and leaves the file open: every
reconfigure — a reconnect in the app, each in-process CLI invocation under test — leaked
another descriptor on ``meshterm.log``, which on Windows is also a lock on a file the
rotation then wants to rename. A handler that refuses to close is dropped anyway: the
point of this call is that the old handlers stop receiving records.
"""
for handler in list(logger.handlers):
try:
handler.close()
except Exception: # noqa: BLE001 - a handler we are discarding cannot fail the app
pass
logger.handlers.clear()
def get_logger(name: str | None = None) -> logging.Logger:
"""Return a child of the application logger.
+4 -3
View File
@@ -1,6 +1,7 @@
"""Algorithm layer: pure logic for tracing, TX search, and path exploration.
Services depend on the :class:`~meshterm.core.connection.Device` interface and domain
models only. They contain no UI or persistence code, so they are straightforward to unit
test against the simulator.
Services may depend on :mod:`meshterm.core` (the :class:`~meshterm.core.connection.Device`
interface and the domain models), on the persistence layer's *types*, and on the app
context; never on ``ui/`` or ``tools/``. Nothing here renders, so every service is
straightforward to unit test against the simulator.
"""
+8
View File
@@ -69,6 +69,14 @@ DEFAULT_TILEJSON_URL = "https://tiles.openfreemap.org/planet"
#: the tile path is no place to discover either.
_USER_AGENT = f"MeshTerm/{__version__} (+https://github.com/jpmartineau/MeshTerm; mesh node map)"
#: How long a tile the source gave no answer about is left alone before it is asked for
#: again. Long enough that a genuinely offline map isn't retrying every visible tile on a
#: loop, short enough that a Wi-Fi blip costs a few seconds of missing streets rather than
#: the rest of the session. It lives here, beside the source that failed to answer, because
#: both surfaces that draw tiles wait out the same cooldown (see
#: :meth:`meshterm.ui.map_screen.MapScreen._load` and the minimap's).
TILE_RETRY_SECONDS = 20.0
#: Fallback max tile zoom if the TileJSON doesn't declare one (OpenFreeMap serves 14).
_DEFAULT_MAX_ZOOM = 14
+31 -10
View File
@@ -4,8 +4,9 @@ Opening a screen used to re-read the same stable facts from the companion every
the contacts table, the node's own self-info, the path-hash routing width, the configured
channel slots, the channel-slot capacity. Over Bluetooth each of those is a full
request→reply round-trip, and the channel-slot reads dominate: ``get_contacts`` on a busy
node (hundreds of contacts), the slot probe (:func:`~meshterm.ui.channels.read_channel_slots`)
and the capacity probe (:meth:`~meshterm.core.connection.Device.channel_capacity`) each walk
node (hundreds of contacts), the slot probe
(:func:`~meshterm.core.channel_probe.read_channel_slots`) and the capacity probe
(:meth:`~meshterm.core.connection.Device.channel_capacity`) each walk
the slot table one index at a time and are measured in *seconds* on firmware that never
rejects an out-of-range index. Firing them on every navigation is what made moving between
screens feel like it stalled.
@@ -43,10 +44,11 @@ from dataclasses import replace
from datetime import datetime, timezone
from typing import TYPE_CHECKING
from ..core.channel_probe import ChannelSlot, probe_channel_slots
if TYPE_CHECKING:
from ..context import AppContext
from ..core.models import Contact
from ..ui.channels import ChannelSlot
#: How long a cached contacts list is served before a read triggers a background refresh
#: (seconds). Contacts only grow as the mesh advertises, and the list is a naming/addressing
@@ -286,26 +288,45 @@ class DeviceState:
self._path_hash_mode = int(await device.get_path_hash_mode())
return self._path_hash_mode
async def routing_prefix_bytes(self) -> int:
"""The device's path-hash width in bytes, or 0 when unknowable.
What a surface that *highlights* hashes actually wants: how many leading bytes of a
key the mesh routes on, which is what :func:`~meshterm.ui.widgets.highlighted_hash`
lights. Best-effort, because every caller reads stored history and must work with no
radio at all — an unreachable device (or firmware that doesn't report the mode) just
leaves every hash un-highlighted rather than failing the screen.
Returns:
The hash width in bytes (1–4), or 0 when the mode could not be read.
"""
try:
if not (self._ctx.is_connected or self._ctx.settings.connect_on_start):
return 0
mode = await self.path_hash_mode()
except Exception: # noqa: BLE001 - optional read; absence just skips highlighting
return 0
return (mode + 1) if isinstance(mode, int) and 0 <= mode <= 3 else 0
# -- channel slots (held until the channel editor invalidates them) --------
async def channel_slots(self) -> list[ChannelSlot]:
"""Return the configured channel slots, cached until a channel edit invalidates them.
The underlying probe (:func:`~meshterm.ui.channels.read_channel_slots`) walks every
slot index on the firmware, which is one of the slowest reads on a screen open — so it
The underlying probe (:func:`~meshterm.core.channel_probe.read_channel_slots`) walks
every slot index on the firmware, which is one of the slowest reads on a screen open — so it
is well worth reading once. It is best-effort itself (an unsupported firmware yields an
empty list rather than raising), but a probe that ended early because a *read failed*
is answered and then dropped rather than cached — see :func:`~meshterm.ui.channels.
probe_channel_slots` for why a short list is not a layout.
is answered and then dropped rather than cached — see
:func:`~meshterm.core.channel_probe.probe_channel_slots` for why a short list is not a
layout.
Returns:
One :class:`~meshterm.ui.channels.ChannelSlot` per configured slot, in index order.
One :class:`~meshterm.core.channel_probe.ChannelSlot` per slot, in index order.
"""
if self._channels is None:
async with self._channels_lock:
if self._channels is None:
from ..ui.channels import probe_channel_slots
device = await self._ctx.device()
slots, complete = await probe_channel_slots(device)
if complete:
+1 -1
View File
@@ -205,7 +205,7 @@ class EventHub:
Returns:
The matching :class:`MeshEvent`, or ``None`` if ``timeout`` elapsed first.
"""
loop = asyncio.get_event_loop()
loop = asyncio.get_running_loop()
future: asyncio.Future = loop.create_future()
def handler(event: MeshEvent) -> None:
+136
View File
@@ -0,0 +1,136 @@
"""Collecting the mesh's located nodes into map markers.
One list, three surfaces: the ``map`` tool's full-screen map, the node page's preview minimap,
and the editors' pick-a-location map all plot the same mesh, so they all come through
:func:`gather_markers`. It sits in ``services/`` because it is an assembly job over the
device's contacts and the observation history — the layer below anything that draws — and
because two screens and one tool need it, none of which may import from the others.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from ..core.geo import usable_fix
from ..core.models import NODE_TYPE_REPEATER, MapMarker
if TYPE_CHECKING: # pragma: no cover - typing only
from ..context import AppContext
async def gather_markers(ctx: AppContext, *, wait: bool = True) -> list[MapMarker]:
"""Collect every located node to plot: the device's contacts, plus our own node.
The companion's **contact list** is the authoritative source for a node's name,
type (repeater vs. leaf), and advertised position — the passive-monitor
observations only carry a location for the rare node that broadcasts one in an
advert. So contacts drive the markers, and each contact is enriched with signal
detail from the observations when we've overheard it directly.
Args:
ctx: Shared application context.
wait: Whether to wait on the radio for contacts and our own position the session
has not cached yet. ``False`` builds the markers from what is already in hand —
the cache and our own history — and never makes a round trip, for a surface
whose nodes are only context (the location picker): a companion refusing the
contacts read can otherwise hold it closed for twenty-odd seconds.
"""
observed = {n.node: n for n in ctx.repo.heard_nodes() if n.node}
markers: list[MapMarker] = []
seen: set[str] = set()
contacts = await _contacts(ctx) if wait else (ctx.devstate.peek_contacts() or [])
for contact in contacts:
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:
seen.add(key)
markers.append(
MapMarker(
label=contact.name or key or "?",
lat=float(contact.lat),
lon=float(contact.lon),
is_repeater=contact.is_repeater,
detail=_signal_detail(observed.get(key)),
key=contact.public_key or contact.key_prefix or None,
)
)
# A node we overheard advertising a location but that isn't in our contacts.
for node in observed.values():
if not node.has_location or node.node in seen:
continue
if not usable_fix(node.lat, node.lon):
continue
markers.append(
MapMarker(
label=node.name or node.node or "?",
lat=float(node.lat),
lon=float(node.lon),
is_repeater=node.is_repeater,
detail=_signal_detail(node),
key=node.public_key or node.node or None,
)
)
if wait:
self_marker = await _self_marker(ctx)
else:
info = ctx.devstate.peek_self_info()
self_marker = _marker_for_self(info) if info is not None else None
if self_marker is not None:
markers.append(self_marker)
return markers
async def _contacts(ctx: AppContext) -> list:
"""Fetch the device's contacts, best-effort (an unreachable radio yields none)."""
try:
return await ctx.devstate.contacts()
except Exception: # noqa: BLE001 - the map still works from observations alone
return []
async def _self_marker(ctx: AppContext) -> MapMarker | None:
"""Build a marker for our own node from the device, if its location is known."""
try:
info = await ctx.devstate.self_info()
except Exception: # noqa: BLE001 - the map is useful without our own position
return None
return _marker_for_self(info)
def _marker_for_self(info: dict) -> MapMarker | None:
"""Our own node's marker from a self-info payload, or ``None`` where it has no fix."""
lat, lon = _as_float(info.get("adv_lat")), _as_float(info.get("adv_lon"))
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,
lon=lon,
is_repeater=info.get("adv_type") == NODE_TYPE_REPEATER,
is_self=True,
key=str(info.get("public_key") or "") or None,
)
def _signal_detail(node: object) -> str:
"""A compact 'N pkts · +x.x dB' reception note for a heard node, or '' if unheard."""
if node is None:
return ""
detail = f"{node.count} pkts" # type: ignore[attr-defined]
if node.median_snr is not None: # type: ignore[attr-defined]
detail += f" · {node.median_snr:+.1f} dB" # type: ignore[attr-defined]
return detail
def _as_float(value: object) -> float | None:
"""Best-effort float conversion, returning ``None`` on missing/garbage values."""
if value is None:
return None
try:
return float(value) # type: ignore[arg-type]
except (TypeError, ValueError):
return None
+2 -2
View File
@@ -280,7 +280,7 @@ CATEGORIES: tuple[Category, ...] = (
CATEGORY_BY_ID: dict[str, Category] = {c.id: c for c in CATEGORIES}
def _local_xy(origin: tuple[float, float], point: tuple[float, float]) -> tuple[float, float]:
def local_xy(origin: tuple[float, float], point: tuple[float, float]) -> tuple[float, float]:
"""Project a lat/lon onto a local plane around ``origin``, in km.
An equirectangular approximation — exact enough for mesh-sized areas (a few tens
@@ -353,7 +353,7 @@ def compute_walk_stats(
if self_pos is not None:
placed = [p for p in points[:-1] if p is not None] # circuit closes itself
if len(placed) >= 3:
xy = [_local_xy(self_pos, p) for p in placed]
xy = [local_xy(self_pos, p) for p in placed]
twice = sum(
xy[i][0] * xy[(i + 1) % len(xy)][1] - xy[(i + 1) % len(xy)][0] * xy[i][1]
for i in range(len(xy))
+8 -3
View File
@@ -85,8 +85,13 @@ _HEX_DIGITS = frozenset("0123456789abcdef")
_MISS = object()
def _is_hex(value: str) -> bool:
"""Whether ``value`` is non-empty, even-length hex (a plausible path hash)."""
def is_path_hash(value: str) -> bool:
"""Whether ``value`` could be a path hash: non-empty hex, a whole number of bytes.
THE test, shared by everything that has to tell a hop id from a name or a graph
sentinel. Even length because a hash is bytes, never a half one — which is also what
keeps a one-character endpoint marker out.
"""
return bool(value) and len(value) % 2 == 0 and all(c in _HEX_DIGITS for c in value)
@@ -340,7 +345,7 @@ class MeshTopology:
if cached is not _MISS:
return cached
needle = hop.lower().removeprefix("0x")
if not _is_hex(needle):
if not is_path_hash(needle):
result: str | None = None
else:
matches = {
+12 -82
View File
@@ -14,15 +14,21 @@ import asyncio
from collections.abc import Awaitable, Callable
from ..core.connection import Device
from ..core.models import Contact, TraceResult
from ..core.models import Contact, NameKeyResolver, NodeResolver, TraceResult
# Trace arithmetic lives in ``core`` because the device layer sizes its own sends with it;
# re-exported here so the runner's long-standing public names keep working.
from ..core.tracing import ( # noqa: F401 - re-exported for this module's callers
TRACE_TIMEOUT_BASE_S,
TRACE_TIMEOUT_CEILING_S,
TRACE_TIMEOUT_FLOOD_S,
TRACE_TIMEOUT_PER_HOP_S,
path_hash_flags,
trace_timeout,
)
ProgressCallback = Callable[[int, int, TraceResult], None]
#: Maps a trace hop's key-prefix hash to a display label (a contact name, or the
#: hash itself when unknown). ``None`` passes through (our own device).
NodeResolver = Callable[[str | None], str | None]
_HEX_DIGITS = frozenset("0123456789abcdef")
@@ -163,13 +169,6 @@ def make_key_resolver(contacts: list[Contact] | None) -> NodeResolver:
return resolve
#: Maps a display name to the node's key (as full as we hold one — a public key, a key
#: prefix, or a stored node id), or ``None`` for a name no known node carries. The
#: colour side of :func:`make_node_resolver`: where that resolver turns hex into names,
#: this one turns a bare name back into the key its palette hue derives from.
NameKeyResolver = Callable[[str], str | None]
def make_name_key_resolver(
contacts: list[Contact] | None,
stored_names: dict[str, str] | None = None,
@@ -269,75 +268,6 @@ def parse_trace_path(spec: str, contacts: list[Contact] | None = None) -> str:
return ",".join(hops)
def path_hash_flags(width_bytes: int) -> int | None:
"""Return the trace ``flags`` value that encodes a per-hop path-hash width.
The trace subsystem encodes the hash size as ``1 << (flags & 3)`` on both the
send and receive sides (``send_trace`` and the ``TRACE_DATA`` reader), so only
widths of 1, 2, 4, or 8 bytes are representable. This is independent of, and
differs from, the ``mode = size - 1`` encoding used for *contact routing*
(``out_path_hash_mode``).
Args:
width_bytes: Path-hash width in bytes.
Returns:
The flags value (the exponent ``s``), or ``None`` if the width is not a
representable power of two.
"""
for s in range(4):
if (1 << s) == width_bytes:
return s
return None
#: Fixed overhead in a trace's reply-wait budget, in seconds: our own transmit, the far
#: endpoint's turnaround, and our receive-side decode — the cost that doesn't grow with
#: the route.
TRACE_TIMEOUT_BASE_S = 4.0
#: Per-hop allowance added to the budget, in seconds. Each entry in the walked path is one
#: relay transmission, and this covers its packet airtime, the repeater's processing, and
#: the randomised transmit backoff MeshCore adds so relays don't collide.
TRACE_TIMEOUT_PER_HOP_S = 1.6
#: Upper bound on the reply-wait, in seconds, so a route that never comes home still
#: surrenders the trace (and the session) in bounded time rather than scaling without end.
TRACE_TIMEOUT_CEILING_S = 30.0
#: Fallback budget, in seconds, when the hop count can't be known ahead of the send — a
#: path-less flood to a contact we hold no route for. This is the historical flat value,
#: kept for exactly the case where we can't size the walk.
TRACE_TIMEOUT_FLOOD_S = 10.0
def trace_timeout(hop_count: int) -> float:
"""Return the reply-wait budget, in seconds, for a trace walking ``hop_count`` hops.
A trace is a *single* packet that has to travel the whole path — out to the far hop
and back over the mirrored return leg — before its reply reaches us, so the wait has
to grow with the route. A flat budget sized for a neighbour cuts a long walk off
mid-flight: the packet completes the circuit on the mesh, but our wait has already
expired, so we log a phantom "no reply" for a route that actually worked. The budget
is a fixed base (:data:`TRACE_TIMEOUT_BASE_S`) plus a per-hop allowance
(:data:`TRACE_TIMEOUT_PER_HOP_S`) for each relay transmission, capped at
:data:`TRACE_TIMEOUT_CEILING_S`.
``hop_count`` is the number of hops in the *transmitted* path, which already includes
the mirrored return leg (see
:meth:`~meshterm.core.connection.MeshCoreDevice._trace_path_to_contact`), so it maps
one-to-one onto relay transmissions and must not be doubled here.
Args:
hop_count: Hops in the walked path (return leg included). ``0`` (or less) means the
count is unknown — a path-less flood — and yields :data:`TRACE_TIMEOUT_FLOOD_S`.
Returns:
The number of seconds to wait for the trace reply.
"""
if hop_count <= 0:
return TRACE_TIMEOUT_FLOOD_S
budget = TRACE_TIMEOUT_BASE_S + TRACE_TIMEOUT_PER_HOP_S * hop_count
return min(budget, TRACE_TIMEOUT_CEILING_S)
async def run_traces(
device: Device,
target: str,
+2 -1
View File
@@ -109,7 +109,8 @@ class Tool(ABC):
"""Interactively gather parameters for the menu.
The default implementation requires no parameters. Tools override this to ask
the user via ``questionary``.
the user through :attr:`AppContext.ui` — a dialog or a select list in the menu, and
nothing at all on the CLI, where the arguments came off the command line.
Args:
ctx: Shared application context.
+4 -3
View File
@@ -84,7 +84,7 @@ class ChannelsTool(Tool):
async def _cli_list(self, ctx: AppContext) -> ToolResult:
"""List the configured channel slots."""
from ..ui.channels import read_channel_slots
from ..core.channel_probe import read_channel_slots
device = await ctx.device()
slots = await read_channel_slots(device)
@@ -150,7 +150,7 @@ class ChannelsTool(Tool):
the secret and the share URL leave the app at all — every other channel document
carries the identity and stops there.
"""
from ..ui.channels import read_channel_slots
from ..core.channel_probe import read_channel_slots
device = await ctx.device()
idx = int(params["index"])
@@ -175,7 +175,8 @@ class ChannelsTool(Tool):
command (a private channel's key is lost with the slot unless it's saved
elsewhere), mirroring the interactive flow's danger confirmation.
"""
from ..ui.channels import read_channel_slots, write_channel
from ..core.channel_probe import read_channel_slots
from ..ui.channels import write_channel
device = await ctx.device()
idx = int(params["index"])
+6 -5
View File
@@ -27,9 +27,11 @@ from ..core import exitcodes
from ..core.channels import (
CHANNEL_SLOT_PROBE_CAP,
DEFAULT_PUBLIC_SECRET,
MENTION,
channel_hash,
channel_identity,
is_public_channel,
split_channel_sender,
)
from ..core.connection import Device
from ..core.events import EventKind, MeshEvent
@@ -43,7 +45,6 @@ from ..core.models import (
)
from ..services.trace_runner import NameKeyResolver, make_name_key_resolver
from ..ui import renderers
from ..ui.chat import _MENTION, _split_channel_sender
from ..ui.fields import ChannelRef, NodeRef
from ..ui.menus import Lane, column_header, fit_cells, section_heading
from ..ui.theme import name_style
@@ -52,7 +53,7 @@ from ..ui.widgets import _NODE_GLYPHS, _age_seconds, _format_age, channel_glyph
from .base import Tool, ToolResult, register
if TYPE_CHECKING:
from ..ui.channels import ChannelSlot
from ..core.channel_probe import ChannelSlot
from ..ui.report import Facts, Listing
#: How many recent messages ``chat history`` prints by default.
@@ -498,7 +499,7 @@ def _channels_from_slots(slots: list[ChannelSlot]) -> list[Conversation]:
The picker reads its channels through the session cache
(:meth:`~meshterm.services.device_state.DeviceState.channel_slots`) so it reuses the one
slow slot probe instead of re-walking every slot on each Chat open; this maps that cached
:class:`~meshterm.ui.channels.ChannelSlot` list onto the picker's
:class:`~meshterm.core.channel_probe.ChannelSlot` list onto the picker's
:class:`~meshterm.core.models.Conversation` rows. Channel 0 (the default public channel) is
synthesised when the firmware reports no slot for it, so there is always somewhere to chat —
the same guarantee :func:`_read_channels` (the CLI path) makes.
@@ -879,7 +880,7 @@ def _preview_text(last: ChatMessage, key_of: NameKeyResolver) -> Text:
text.append("you: ", style="accent")
_append_body(text, body_raw, key_of)
elif last.is_channel:
name, body = _split_channel_sender(body_raw)
name, body = split_channel_sender(body_raw)
if name is not None:
text.append(name, style=name_style(name, key_of(name)))
text.append(": ", style="muted")
@@ -898,7 +899,7 @@ def _append_body(text: Text, body: str, key_of: NameKeyResolver) -> None:
name resolves to no node we know.
"""
pos = 0
for match in _MENTION.finditer(body):
for match in MENTION.finditer(body):
if match.start() > pos:
text.append(body[pos : match.start()], style="muted")
name = match.group(1)
+2 -2
View File
@@ -138,7 +138,7 @@ def _listing(contacts: list[Contact], counts: dict[str, int], prefix_bytes: int)
"""
from ..ui import fields
from ..ui.report import Listing
from ..ui.widgets import _contact_pkts
from ..ui.widgets import contact_packets
rows = []
for contact in contacts:
@@ -152,7 +152,7 @@ def _listing(contacts: list[Contact], counts: dict[str, int], prefix_bytes: int)
type=NODE_TYPE_LABELS.get(contact.node_type),
),
"heard_at": contact.last_seen,
"packets": _contact_pkts(contact, counts),
"packets": contact_packets(contact, counts),
"position": (
fields.Position(contact.lat, contact.lon) if contact.has_location else None
),
+2 -128
View File
@@ -20,8 +20,7 @@ from typing import TYPE_CHECKING, Any
import typer
from ..context import AppContext
from ..core.geo import usable_fix
from ..core.models import NODE_TYPE_REPEATER
from ..services.markers import gather_markers
from .base import Tool, ToolResult, register
@@ -44,7 +43,7 @@ def _fraction(ctx: AppContext, params: dict[str, Any]) -> float:
if TYPE_CHECKING:
from ..ui.map_render import MapMarker
from ..core.models import MapMarker
@register
@@ -115,128 +114,3 @@ class MapTool(Tool):
Args:
app: The Typer application (untouched).
"""
async def gather_markers(ctx: AppContext, *, wait: bool = True) -> list[MapMarker]:
"""Collect every located node to plot: the device's contacts, plus our own node.
The companion's **contact list** is the authoritative source for a node's name,
type (repeater vs. leaf), and advertised position — the passive-monitor
observations only carry a location for the rare node that broadcasts one in an
advert. So contacts drive the markers, and each contact is enriched with signal
detail from the observations when we've overheard it directly.
Shared by the ``map`` tool, the node page's preview and the editors' pick-a-location
map, so all of them show the same mesh.
Args:
ctx: Shared application context.
wait: Whether to wait on the radio for contacts and our own position the session
has not cached yet. ``False`` builds the markers from what is already in hand —
the cache and our own history — and never makes a round trip, for a surface
whose nodes are only context (the location picker): a companion refusing the
contacts read can otherwise hold it closed for twenty-odd seconds.
"""
from ..ui.map_render import MapMarker
observed = {n.node: n for n in ctx.repo.heard_nodes() if n.node}
markers: list[MapMarker] = []
seen: set[str] = set()
contacts = await _contacts(ctx) if wait else (ctx.devstate.peek_contacts() or [])
for contact in contacts:
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:
seen.add(key)
markers.append(
MapMarker(
label=contact.name or key or "?",
lat=float(contact.lat),
lon=float(contact.lon),
is_repeater=contact.is_repeater,
detail=_signal_detail(observed.get(key)),
key=contact.public_key or contact.key_prefix or None,
)
)
# A node we overheard advertising a location but that isn't in our contacts.
for node in observed.values():
if not node.has_location or node.node in seen:
continue
if not usable_fix(node.lat, node.lon):
continue
markers.append(
MapMarker(
label=node.name or node.node or "?",
lat=float(node.lat),
lon=float(node.lon),
is_repeater=node.is_repeater,
detail=_signal_detail(node),
key=node.public_key or node.node or None,
)
)
if wait:
self_marker = await _self_marker(ctx)
else:
info = ctx.devstate.peek_self_info()
self_marker = _marker_for_self(info) if info is not None else None
if self_marker is not None:
markers.append(self_marker)
return markers
async def _contacts(ctx: AppContext) -> list:
"""Fetch the device's contacts, best-effort (an unreachable radio yields none)."""
try:
return await ctx.devstate.contacts()
except Exception: # noqa: BLE001 - the map still works from observations alone
return []
async def _self_marker(ctx: AppContext) -> MapMarker | None:
"""Build a marker for our own node from the device, if its location is known."""
try:
info = await ctx.devstate.self_info()
except Exception: # noqa: BLE001 - the map is useful without our own position
return None
return _marker_for_self(info)
def _marker_for_self(info: dict) -> MapMarker | None:
"""Our own node's marker from a self-info payload, or ``None`` where it has no fix."""
from ..ui.map_render import MapMarker
lat, lon = _as_float(info.get("adv_lat")), _as_float(info.get("adv_lon"))
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,
lon=lon,
is_repeater=info.get("adv_type") == NODE_TYPE_REPEATER,
is_self=True,
key=str(info.get("public_key") or "") or None,
)
def _signal_detail(node: object) -> str:
"""A compact 'N pkts · +x.x dB' reception note for a heard node, or '' if unheard."""
if node is None:
return ""
detail = f"{node.count} pkts" # type: ignore[attr-defined]
if node.median_snr is not None: # type: ignore[attr-defined]
detail += f" · {node.median_snr:+.1f} dB" # type: ignore[attr-defined]
return detail
def _as_float(value: object) -> float | None:
"""Best-effort float conversion, returning ``None`` on missing/garbage values."""
if value is None:
return None
try:
return float(value) # type: ignore[arg-type]
except (TypeError, ValueError):
return None
+9 -6
View File
@@ -185,7 +185,6 @@ class TraceTool(Tool):
ContactListScreen,
)
from ..ui.surface import TuiUi
from ..ui.timemachine_screen import _routing_prefix_bytes
from ..ui.widgets import ContactsSort
# Through the session cache: this picker runs on every Trace open, and the contacts
@@ -199,7 +198,7 @@ class TraceTool(Tool):
picker = ContactListScreen(
"Trace target — pick a target",
rows=self._picker_rows(ctx, contacts),
prefix_bytes=await _routing_prefix_bytes(ctx),
prefix_bytes=await ctx.devstate.routing_prefix_bytes(),
sort=ContactsSort.from_name("traced", TRACE_SORT_COLUMNS, TRACE_SORT_OPENS_ASCENDING),
footer_hint="↑↓ move · ^←→↑↓ sort · type to filter · Enter select · Esc back",
lanes=TRACE_LANES,
@@ -226,7 +225,7 @@ class TraceTool(Tool):
given (the screen sorts them).
"""
from ..ui.contactlist import ContactRow
from ..ui.widgets import _contact_pkts
from ..ui.widgets import contact_packets
traced = _last_traced_by_name(contacts, ctx.repo.target_last_traced())
counts = {n.node: n.count for n in ctx.repo.heard_nodes() if n.node}
@@ -237,7 +236,7 @@ class TraceTool(Tool):
key=c.public_key or c.key_prefix or "",
node_type=c.node_type,
last_seen=c.last_seen,
count=_contact_pkts(c, counts),
count=contact_packets(c, counts),
last_traced=traced.get(c.name),
)
for c in contacts
@@ -279,7 +278,9 @@ class TraceTool(Tool):
path: str | None = typer.Option(
None,
"--path",
"-p",
# No ``-p`` short form: ``-p`` is the global ``--profile``, and
# ``_globals_first`` lifts a group option ahead of the subcommand wherever it
# is typed — so a leaf ``-p`` could never reach this option, only shadow it.
help="Force a route: comma-separated contact names/hex prefixes (e.g. 3d,f2,3d)",
),
) -> None:
@@ -361,7 +362,9 @@ class TracePathTool(Tool):
path: str = typer.Option(
...,
"--path",
"-p",
# No ``-p`` short form: ``-p`` is the global ``--profile``, and
# ``_globals_first`` lifts a group option ahead of the subcommand wherever it
# is typed — so a leaf ``-p`` could never reach this option, only shadow it.
help="The whole walk: comma-separated contact names/hex prefixes "
"(must end within earshot of this node)",
),
+10 -4
View File
@@ -385,7 +385,9 @@ class TxOptimizeTool(Tool):
path: str = typer.Option(
...,
"--path",
"-p",
# No ``-p`` short form: ``-p`` is the global ``--profile``, and
# ``_globals_first`` lifts a group option ahead of the subcommand wherever it
# is typed — so a leaf ``-p`` could never reach this option, only shadow it.
help="Forced path ending at the target (e.g. 'Repeater,Target' or '3d,f2')",
),
samples: int = typer.Option(3, "--samples", "-n", help="Traces per TX level"),
@@ -424,12 +426,16 @@ def _resolve_link(path: str, contacts: list[Contact]) -> tuple[Contact, str]:
:class:`Contact` (needed for login), and a friendly name for the last hop.
Raises:
DeviceCommandError: If the path has fewer than two hops, or the admin hop can't
be matched to a known contact carrying a public key.
typer.BadParameter: If the path has fewer than two hops — the argument is what is
wrong and nothing was transmitted, so that is a usage error (exit 2), not a
device failure.
DeviceCommandError: If the admin hop can't be matched to a known contact carrying a
public key. That one *is* about the mesh: the path is well formed and we simply
have not heard from the node it names.
"""
hops = [h for h in path.split(",") if h]
if len(hops) < 2:
raise DeviceCommandError(
raise typer.BadParameter(
"the path needs at least two hops: the node to tune and the target after it "
"(e.g. 'AdminNode,Target')."
)
+1 -1
View File
@@ -1 +1 @@
"""Presentation layer: Rich theme/widgets and the Questionary-driven menu."""
"""Presentation layer: Rich theme/widgets and the prompt_toolkit full-screen session."""
+1 -148
View File
@@ -36,7 +36,6 @@ from __future__ import annotations
import time
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from functools import lru_cache
from typing import TYPE_CHECKING
@@ -44,24 +43,17 @@ from rich.cells import cell_len
from rich.console import Group
from rich.text import Text
from ..core.channel_probe import ChannelSlot
from ..core.channels import (
CHANNEL_SLOT_EMPTY_RUN,
CHANNEL_SLOT_PROBE_CAP,
DEFAULT_PUBLIC_SECRET,
MAX_CHANNELS,
channel_hash,
channel_identity,
derive_secret,
full_channel_hash,
is_name_derived,
is_public_channel,
normalize_secret,
parse_share_url,
random_secret,
share_url,
)
from ..core.connection import Device
from ..core.models import Conversation
from ..persistence.repository import ACTIVITY_DRAWN_BUCKETS
from ..platforms import get_platform
from .braillechart import activity_peak, activity_sparkline
@@ -104,60 +96,6 @@ _EDIT = "edit"
_CLEAR = "clear"
@dataclass(slots=True)
class ChannelSlot:
"""One configured channel slot read back from the device.
Attributes:
idx: The 0-based slot index.
name: The channel's name.
secret: The channel's 16-byte shared secret.
"""
idx: int
name: str
secret: bytes
@property
def is_name_derived(self) -> bool:
"""Whether this channel's key is reproducible from its name (so it needn't be stored)."""
return is_name_derived(self.name, self.secret)
@property
def is_public(self) -> bool:
"""Whether this channel is public (shared meshwide) rather than a private one.
Covers both name-derived channels and the firmware's fixed-key default ``Public``.
"""
return is_public_channel(self.name, self.secret)
@property
def hash(self) -> str:
"""The channel's two-character hash fingerprint (the leading byte MeshCore shows)."""
return channel_hash(self.secret)
@property
def full_hash(self) -> str:
"""The channel's complete ``sha256(secret)`` digest; its first byte is :attr:`hash`."""
return full_channel_hash(self.secret)
@property
def identity(self) -> str:
"""The channel's slot-independent identity, used to key its chat history."""
return channel_identity(self.name, self.secret)
@property
def conversation(self) -> Conversation:
"""A :class:`~meshterm.core.models.Conversation` for opening this channel in chat."""
return Conversation(
label=self.name,
is_channel=True,
channel_idx=self.idx,
channel_id=self.identity,
secret=self.secret,
)
async def manage_channels(ctx: AppContext) -> int:
"""Run the interactive channel manager until the user backs out.
@@ -342,91 +280,6 @@ async def _refresh_chat_channels(ctx: AppContext) -> None:
ctx.log.debug("channels: chat cache refresh failed: %s", exc)
# --- reading -----------------------------------------------------------------
async def read_channel_slots(device: Device) -> list[ChannelSlot]:
"""Probe the channel slots and return the configured ones, in index order.
The scan stops as soon as the firmware rejects a slot index, so it reads exactly the
slots a well-behaved device has regardless of its capacity. Firmware that never rejects
an out-of-range index (it answers every slot with an empty payload instead of raising)
would otherwise walk all :data:`CHANNEL_SLOT_PROBE_CAP` slots on every read; a run of
:data:`CHANNEL_SLOT_EMPTY_RUN` consecutive empty slots ends the scan on such firmware.
That is safe because the manager packs channels from slot 0 up, so an unbroken empty run
that long means every configured channel has already been seen (see the constant's note).
Args:
device: The connected device to query.
Returns:
One :class:`ChannelSlot` per configured slot (an empty slot is skipped).
"""
slots, _complete = await probe_channel_slots(device)
return slots
async def probe_channel_slots(device: Device) -> tuple[list[ChannelSlot], bool]:
"""The probe behind :func:`read_channel_slots`, reporting whether it *finished*.
The scan stops for two very different reasons and the plain list cannot tell them
apart. Off the end of the configured slots (a rejected index, or a long enough run of
empty ones) the answer is complete and worth keeping. A read that simply *failed* —
a timeout, a link hiccup, and then every subsequent read failing too because the
firmware's reply no longer matches the slot asked for — ends the scan early with
whatever it happened to have, which is not the device's layout and must not be cached
or acted on as if it were: an empty one reads as "no channels configured", and a
truncated one makes the next free slot look free when a channel is sitting in it.
The two endings raise different things, and that is what separates them: the firmware
*answering* "no such slot" surfaces as a plain rejection, while a link that stopped
answering surfaces as a timeout, a :class:`~meshterm.core.connection.DeviceCommandError`
(whose whole subject is a companion that did not reply in time), or one of the dropped-
link signatures :func:`~meshterm.core.connection.is_connection_lost` knows. Only the
first ending is a layout. A read that fails for some fourth reason is treated as a
rejection, which is the safe way round: the list is used but the cache re-probes.
Args:
device: The connected device to query.
Returns:
The slots read, and whether the scan ran to a clean end.
"""
slots: list[ChannelSlot] = []
empty_run = 0
for idx in range(CHANNEL_SLOT_PROBE_CAP):
try:
payload = await device.get_channel(idx)
except Exception as exc: # noqa: BLE001 - a rejected index, or a read that failed
return slots, not _read_failed(exc)
if payload and payload.get("channel_name"):
empty_run = 0
slots.append(
ChannelSlot(
idx=idx,
name=str(payload["channel_name"]),
secret=bytes(payload.get("channel_secret") or b"\x00" * 16),
)
)
else:
empty_run += 1
if empty_run >= CHANNEL_SLOT_EMPTY_RUN:
break # off the end of a never-rejecting firmware; nothing more to find
return slots, True
def _read_failed(exc: BaseException) -> bool:
"""Whether ``exc`` means the *read* failed, rather than the firmware refusing a slot.
A refusal is the probe's ordinary ending and leaves a complete list behind it. A
failure leaves a short one that looks exactly the same — which is the whole reason
this distinction has to be drawn somewhere (see :func:`probe_channel_slots`).
"""
from ..core.connection import DeviceCommandError, is_connection_lost
return isinstance(exc, (TimeoutError, DeviceCommandError)) or is_connection_lost(exc)
def _next_free_slot(slots: list[ChannelSlot], capacity: int) -> int | None:
"""Return the lowest unused slot index, or ``None`` when every slot is full."""
used = {s.idx for s in slots}
+26 -28
View File
@@ -16,14 +16,13 @@ screen is open.
from __future__ import annotations
import asyncio
import re
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, Any
from rich.console import Group, RenderableType
from rich.text import Text
from ..core.channels import split_channel_sender
from ..core.channels import MENTION, split_channel_sender
from ..core.connection import ContactNotOnDeviceError
from ..core.events import EventKind, MeshEvent
from ..core.models import ChatMessage, Contact, Conversation, Message, utcnow
@@ -31,7 +30,7 @@ from .theme import name_style, snr_style
from .tui.prompt import (
CHANNEL_BYTE_LIMIT,
DM_BYTE_LIMIT,
_LineEditor,
LineEditor,
byte_counter,
)
from .tui.render import render_hanging, render_lines, right_aligned_tail
@@ -43,12 +42,6 @@ if TYPE_CHECKING:
from ..context import AppContext
#: Matches an ``@[Name]`` mention token, as the reply flow primes into the compose line (see
#: :meth:`ChatScreen._begin_reply`). The transcript renders each as a bare ``@Name`` colored
#: in that sender's hue instead of showing the literal brackets. Name is 1–20 non-``]`` chars.
_MENTION = re.compile(r"@\[([^\]]{1,20})\]")
#: Delivery-state marks for a *resolved* outbound direct message, shown at the end of its
#: line: acknowledged, or transmitted-but-unacknowledged (retryable via ^R). The app-wide
#: ``✓``/``✗`` status marks in their ok/err styles — not the ✅/❌ emoji, which belong to
@@ -57,12 +50,6 @@ _MENTION = re.compile(r"@\[([^\]]{1,20})\]")
_DELIVERED = ("✓", "ok")
_FAILED = ("✗", "err")
#: The sender-prefix parser, shared app-wide from the protocol layer (the transcript,
#: the conversation picker, the dashboard feed, and the message-paths matcher must all
#: split ``Name: body`` identically). Kept under its old private name for the callers
#: that import it from here.
_split_channel_sender = split_channel_sender
class ChatScreen(Screen):
"""A live conversation: a scrolling transcript above a pinned input line.
@@ -183,7 +170,7 @@ class ChatScreen(Screen):
self._paths = paths
self._names = names
self._session = session
self._editor = _LineEditor()
self._editor = LineEditor()
self._sending = False
# Cycled while a direct message is in flight, so its trailing glyph spins (rather than
# a static hourglass) until the ack resolves. Shared across messages: only one send or
@@ -201,6 +188,18 @@ class ChatScreen(Screen):
# something outside the transcript (a keystroke, the 1s idle tick, a spinner
# frame) only re-renders the rows that actually changed. See _render_grouped.
self._render_cache: dict | None = None
# Strong references to the sends, resends and spinner tickers started off a key
# handler. The event loop only holds a *weak* one, so a task nothing else names can
# be collected mid-flight — a half-transmitted message, or a spinner that stops
# turning. Each task discards itself from the set when it finishes.
self._tasks: set[asyncio.Task] = set()
def _spawn(self, coro) -> asyncio.Task: # noqa: ANN001 - any coroutine this screen owns
"""Start ``coro`` on the loop and hold a reference to it until it finishes."""
task = asyncio.ensure_future(coro)
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)
return task
@property
def footer_hint(self) -> str:
@@ -446,7 +445,7 @@ class ChatScreen(Screen):
if message.outbound:
return "you", message.text
if message.is_channel:
name, body = _split_channel_sender(message.text)
name, body = split_channel_sender(message.text)
return (name or "·"), body
return (self._name(message.peer) or message.peer or "?"), message.text
@@ -515,7 +514,7 @@ class ChatScreen(Screen):
base = "cursor" if selected else None
text = Text()
pos = 0
for match in _MENTION.finditer(body):
for match in MENTION.finditer(body):
if match.start() > pos:
text.append(body[pos : match.start()], style=base)
name = match.group(1)
@@ -723,7 +722,7 @@ class ChatScreen(Screen):
self._status = ""
self._session.invalidate()
asyncio.ensure_future(run())
self._spawn(run())
def _move_selection(self, delta: int) -> None:
"""Move the reply selection by ``delta`` messages (negative = toward older).
@@ -797,7 +796,7 @@ class ChatScreen(Screen):
sender, _ = self._sender_and_body(message)
named = not message.outbound and sender != "·"
mention = f"@[{sender}] " if named else "@"
self._editor = _LineEditor(mention + self._editor.text)
self._editor = LineEditor(mention + self._editor.text)
self._clear_selection()
self._stick = True
self._session.invalidate()
@@ -817,13 +816,13 @@ class ChatScreen(Screen):
self._status = f"Too long by {over} byte{'s' if over != 1 else ''} — trim to send."
self._session.invalidate()
return
self._editor = _LineEditor()
self._editor = LineEditor()
self._sending = True
self._stick = True
if self._is_channel:
self._status = "sending…"
self._session.invalidate()
asyncio.ensure_future(self._send_channel(text))
self._spawn(self._send_channel(text))
else:
# Direct chats show an optimistic bubble whose trailing mark tracks delivery:
# a spinner now, then ✓/✗ once the ack resolves (or times out). acked=None
@@ -832,7 +831,7 @@ class ChatScreen(Screen):
self._messages.append(pending)
self._status = ""
self._session.invalidate()
asyncio.ensure_future(self._send_direct(pending))
self._spawn(self._send_direct(pending))
async def _send_channel(self, text: str) -> None:
"""Broadcast a channel message and append it once the companion accepts it."""
@@ -866,7 +865,7 @@ class ChatScreen(Screen):
self._spinner.tick()
self._session.invalidate()
ticker = asyncio.ensure_future(animate())
ticker = self._spawn(animate())
try:
return await coro
finally:
@@ -926,7 +925,7 @@ class ChatScreen(Screen):
self._status = "retrying…"
self._stick = True
self._session.invalidate()
asyncio.ensure_future(self._resend_message(target))
self._spawn(self._resend_message(target))
async def _resend_message(self, message: ChatMessage) -> None:
"""Drive a retry to completion, refreshing the message's delivery state in place."""
@@ -1182,7 +1181,6 @@ async def _make_paths_presenter(
distinct_paths,
)
from .message_paths_screen import MessagePathsScreen
from .timemachine_screen import _routing_prefix_bytes
session = ctx.ui.session
contacts = await ctx.devstate.contacts()
@@ -1190,7 +1188,7 @@ async def _make_paths_presenter(
resolve = trace_runner.make_node_resolver(contacts, stored_names)
type_of = trace_runner.make_node_type_resolver(contacts)
key_of = trace_runner.make_name_key_resolver(contacts, stored_names)
prefix_bytes = await _routing_prefix_bytes(ctx)
prefix_bytes = await ctx.devstate.routing_prefix_bytes()
self_name: str | None = None
self_key: str | None = None
try:
@@ -1274,7 +1272,7 @@ async def _make_paths_presenter(
if not conversation.is_channel:
destination = conversation.label
elif conversation.is_channel:
source, _body = _split_channel_sender(message.text)
source, _body = split_channel_sender(message.text)
else:
source = conversation.label
await session.run_screen(
+2 -2
View File
@@ -76,7 +76,7 @@ from .menus import (
section_heading,
)
from .tui import Choice, SelectScreen, Separator
from .tui.select import _splice_hint
from .tui.select import splice_hint
if TYPE_CHECKING:
from ..context import AppContext
@@ -543,7 +543,7 @@ class _ConfigMenu(SelectScreen):
if not self._conceals:
return base
verb = "hide" if self._revealed else "show"
return _splice_hint(base, f"{REVEAL_KEY} {verb} PIN")
return splice_hint(base, f"{REVEAL_KEY} {verb} PIN")
@property
def fkey_lane(self):
+2 -2
View File
@@ -29,7 +29,7 @@ from datetime import datetime
from rich.cells import cell_len
from rich.text import Text
from .map_render import _SELF
from .marks import SELF_MARK
from .menus import fit_cells
from .theme import name_style
from .tui.select import Choice, SelectScreen, Separator
@@ -301,7 +301,7 @@ def _you_lane(
ourselves, so none of those has a value to show and each says so identically.
"""
text = Text(no_wrap=True, overflow="ellipsis")
text.append(_SELF[0], style=_SELF[1])
text.append(SELF_MARK[0], style=SELF_MARK[1])
text.append(" ")
# The name lane, exactly name_w cells: the name (white) with a snug muted "(you)" tag —
# padded out to fill the lane — or, when the name alone would crowd out the tag, the
+2 -2
View File
@@ -44,7 +44,7 @@ from .menus import icon_lane, marked_label
from .purge_screen import purge_contacts
from .tui import Choice, Separator
from .tui.screen import CANCEL
from .widgets import ContactsSort, _contact_pkts
from .widgets import ContactsSort, contact_packets
if TYPE_CHECKING:
from ..context import AppContext
@@ -111,7 +111,7 @@ class ContactsScreen(ContactListScreen):
key=c.public_key,
node_type=c.node_type,
last_seen=c.last_seen,
count=_contact_pkts(c, counts),
count=contact_packets(c, counts),
)
)
# The maintenance actions close the list, past every contact whatever the sort: a
+3 -5
View File
@@ -34,7 +34,7 @@ from .contactlist import SORT_COLUMNS, SORT_OPENS_ASCENDING, ContactListScreen,
from .menus import icon_lane, marked_label, run_steps, section_heading
from .tui import CANCEL, DM_BYTE_LIMIT, Choice, SelectScreen, Separator
from .watchtower_screen import contact_watch_key
from .widgets import ContactsSort, _age_seconds, _contact_pkts, format_ago
from .widgets import ContactsSort, _age_seconds, contact_packets, format_ago
if TYPE_CHECKING:
from ..context import AppContext
@@ -377,7 +377,7 @@ class CourierRecipientScreen(ContactListScreen):
key=c.public_key or c.key_prefix or "",
node_type=c.node_type,
last_seen=c.last_seen,
count=_contact_pkts(c, counts),
count=contact_packets(c, counts),
)
for c in contacts
]
@@ -400,8 +400,6 @@ async def _queue_flow(ctx: AppContext, contacts: list[Contact]) -> None:
message was being written to), and from there out to the outbox. Nothing typed is lost
to a single keypress — see :func:`~meshterm.ui.menus.run_steps`.
"""
from .timemachine_screen import _routing_prefix_bytes
session = ctx.ui.session
# A courier message is a direct message, so only companions can receive one — a
# repeater, room, or sensor is never a recipient (the app-wide DM rule, see
@@ -421,7 +419,7 @@ async def _queue_flow(ctx: AppContext, contacts: list[Contact]) -> None:
# The shared contact-list presentation (see CourierRecipientScreen), opened A→Z by
# name — the default of a re-sortable list, with heard/packets/key a Ctrl+arrow away.
counts = {n.node: n.count for n in ctx.repo.heard_nodes() if n.node}
prefix_bytes = await _routing_prefix_bytes(ctx)
prefix_bytes = await ctx.devstate.routing_prefix_bytes()
picker = CourierRecipientScreen(
contacts=companions,
prefix_bytes=prefix_bytes,
+1 -2
View File
@@ -840,7 +840,6 @@ async def open_livefeed(ctx: AppContext) -> None:
"""
from ..services import trace_runner
from .surface import TuiUi
from .timemachine_screen import _routing_prefix_bytes
if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller
raise RuntimeError("the live feed is only available in the menu")
@@ -868,7 +867,7 @@ async def open_livefeed(ctx: AppContext) -> None:
resolve = trace_runner.make_node_resolver(contacts, stored_names)
type_of = trace_runner.make_node_type_resolver(contacts)
key_of = trace_runner.make_name_key_resolver(contacts, stored_names)
prefix_bytes = await _routing_prefix_bytes(ctx)
prefix_bytes = await ctx.devstate.routing_prefix_bytes()
# The cap is the only bound: the newest _FEED_CAP packets ever recorded, however
# long ago the quiet stretch before them began.
+3 -33
View File
@@ -26,45 +26,15 @@ from collections import Counter
from dataclasses import dataclass, field
from ..core.geo import Viewport
from ..core.models import MapMarker
from ..core.mvt import GEOM_LINE, GEOM_POLYGON, Layer
from ..platforms import Platform, on_platform
from .mapcanvas import MapCanvas, Raster
from .marks import NODE_MARK, REPEATER_MARK, RGB, SELF_MARK, UNKNOWN_MARK, parse_hex
from .theme import mark_rgb
# -- node markers -------------------------------------------------------------
@dataclass(slots=True)
class MapMarker:
"""One mesh node to overlay on the map.
Attributes:
label: Node name shown beside the marker.
lat: Latitude in decimal degrees.
lon: Longitude in decimal degrees.
is_repeater: Whether the node is a repeater (prioritised marker).
is_self: Whether this is our own node (highlighted).
detail: Extra text for the CLI legend (e.g. ``"18 pkts · +6.0 dB"``).
key: The node's key hex (as full as the caller holds), seeding the label's
key-derived hue; ``None`` leaves the label the muted no-key grey.
"""
label: str
lat: float
lon: float
is_repeater: bool = False
is_self: bool = False
detail: str = ""
key: str | None = None
def _rank(self) -> int:
"""Draw order: self on top of repeaters on top of leaf nodes."""
return 2 if self.is_self else (1 if self.is_repeater else 0)
# Marker palette, shared across the whole app — canonical tuples in ui.marks; the old
# private names stay bound here for this module and its existing importers.
# Marker palette, shared across the whole app — canonical tuples in ui.marks. These are
# local shorthand for the renderer's own hot paths; anything else imports from ui.marks.
_SELF = SELF_MARK
_REPEATER = REPEATER_MARK
_NODE = NODE_MARK
+5 -10
View File
@@ -40,7 +40,7 @@ from ..core.geo import DEFAULT_VIEW_FRACTION, EARTH_RADIUS_KM, Viewport, clamp_l
from ..core.mvt import Layer
from ..platforms import get_platform
from ..services import modifier_watch
from ..services.basemap import BasemapSource
from ..services.basemap import TILE_RETRY_SECONDS, BasemapSource
from .map_render import Ghost, MapMarker, render_ground, render_map
from .tui.render import query_line
from .tui.screen import Screen
@@ -117,12 +117,6 @@ _PREFETCH_SETTLE = 1.0
#: tile-grid corner from walking the whole neighbourhood.
_PREFETCH_MAX = 12
#: How long a tile the source gave no answer about is left alone before it is asked for
#: again. Long enough that a genuinely offline map isn't retrying every visible tile on a
#: loop, short enough that a Wi-Fi blip costs a few seconds of missing streets rather than
#: the rest of the session (see :meth:`MapScreen._load`).
_TILE_RETRY_SECONDS = 20.0
#: The zoom a frame homes in at when the matches set no extent of their own — a
#: single node (or several at one spot) has nothing to frame, so ^Enter zooms to this
#: street-level closeness rather than the fit's neutral default. Capped at the tile
@@ -668,7 +662,8 @@ class MapScreen(Screen):
map that opened a moment too early stays empty for the rest of the session. The
fetch resolves the source itself, in its own thread, so asking is what un-sticks it.
A tile the source never answered about waits out :data:`_TILE_RETRY_SECONDS` in
A tile the source never answered about waits out
:data:`~meshterm.services.basemap.TILE_RETRY_SECONDS` in
:attr:`_unanswered` and is then asked for again — see :meth:`_load` for why that
isn't the same as a tile it answered "nothing here" about.
"""
@@ -912,7 +907,7 @@ class MapScreen(Screen):
if layers is not None or self._source.answered_empty(*t):
self._tiles[t] = layers
else:
self._unanswered[t] = monotonic() + _TILE_RETRY_SECONDS
self._unanswered[t] = monotonic() + TILE_RETRY_SECONDS
self._session.invalidate()
# --- input ---------------------------------------------------------------
@@ -1262,7 +1257,7 @@ async def pick_location(
"""
import asyncio
from ..tools.map import gather_markers
from ..services.markers import gather_markers
from .surface import TuiUi
from .tui.screen import CANCEL
+10
View File
@@ -638,14 +638,24 @@ def fit_cells(text: str, width: int, *, align: str = "left") -> str:
__all__ = [
"SEP_COMPACT",
"SEP_ROOMY",
"Lane",
"WizardPage",
"align_icons",
"changes_phrase",
"column_header",
"command_label",
"confirm_discard",
"exit_rows",
"fit_cells",
"icon_lane",
"icon_mark",
"lane_header",
"lane_row",
"marked_label",
"menu_rows",
"run_steps",
"run_wizard",
"section_heading",
]
+2 -6
View File
@@ -23,6 +23,7 @@ from typing import TYPE_CHECKING
from ..core.geo import Viewport, clamp_lat
from ..core.mvt import Layer
from ..services.basemap import TILE_RETRY_SECONDS
from .map_render import MapMarker, render_map
if TYPE_CHECKING: # pragma: no cover - typing only
@@ -33,11 +34,6 @@ if TYPE_CHECKING: # pragma: no cover - typing only
#: (blurred) basemap rather than blank tiles.
_OVERZOOM = 2
#: How long a tile the source gave no answer about is left alone before the preview asks
#: for it again — the big map's cooldown, for the same reason (see
#: :meth:`meshterm.ui.map_screen.MapScreen._load`).
_TILE_RETRY_SECONDS = 20.0
def _loop_running() -> bool:
"""Whether there is an event loop to hand background work to.
@@ -168,5 +164,5 @@ class MiniMap:
if layers is not None or self._source.answered_empty(*t):
self._tiles[t] = layers # an answer, settled for the session
else:
self._unanswered[t] = monotonic() + _TILE_RETRY_SECONDS # silence — ask again
self._unanswered[t] = monotonic() + TILE_RETRY_SECONDS # silence — ask again
self._session.invalidate()
+10 -21
View File
@@ -85,11 +85,12 @@ from rich.cells import cell_len
from rich.text import Text
from ..core.connection import ContactNotOnDeviceError
from ..core.geo import EARTH_RADIUS_KM, usable_fix
from ..core.geo import haversine_km, usable_fix
from ..core.models import NODE_TYPE_LABELS, Contact, utcnow
from ..platforms import Platform, on_platform
from . import menus
from .mapcanvas import RGB
from .marks import SELF_MARK
from .minimap import MiniMap
from .pathgraph import (
DST_NODE,
@@ -130,9 +131,6 @@ from .widgets import (
if TYPE_CHECKING: # pragma: no cover - typing only
from ..context import AppContext
#: Our own node's marker glyph and hue, matching the map/mesh-walk star.
_SELF_GLYPH = ("★", "#facc15")
#: Whether the route fan is captioned ("node → you, as heard · white = selected route")
#: and allowed to keep the empty canvas row its top air leaves. Both go on the PicoCalc
#: (JP, 2026-08-09) and both rows go to the graph instead: the caption explains a picture
@@ -1032,15 +1030,6 @@ class NodeDetailScreen(Screen):
_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)
@@ -1055,7 +1044,7 @@ def _range_text(lat: float, lon: float, self_lat: float | None, self_lon: float
"""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)
km = haversine_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
@@ -1121,18 +1110,18 @@ async def open_node_detail(
Raises:
RuntimeError: If called outside the interactive menu (no full-screen session).
"""
from ..services.topology import _is_hex, build_topology
from ..services.markers import gather_markers
from ..services.topology import build_topology, is_path_hash
from ..services.trace_runner import (
make_name_key_resolver,
make_node_resolver,
make_node_type_resolver,
)
from ..tools.map import gather_markers
from .config_editor import show_contact_card
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 .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
@@ -1160,7 +1149,7 @@ async def open_node_detail(
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)
width_bytes = collapse_trace_width(mode)
except Exception: # noqa: BLE001 - optional reads; sane defaults keep the page working
prefix_bytes, width_bytes = 0, 1
@@ -1200,7 +1189,7 @@ async def open_node_detail(
# -- identity header.
if you:
glyph, glyph_style = _SELF_GLYPH
glyph, glyph_style = SELF_MARK
name_hue = "you"
else:
glyph, glyph_style = _NODE_GLYPHS.get(node_type, _DEFAULT_GLYPH)
@@ -1216,7 +1205,7 @@ async def open_node_detail(
# -- 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
target_hash = target_hash if (not you and is_path_hash(target_hash)) else None
topo = build_topology(
self_id=(self_key.lower().removeprefix("0x")[:12]) or "local",
contacts=contacts,
@@ -1325,7 +1314,7 @@ async def open_node_detail(
# synced from the device) has nothing scannable to offer, so the row only shows when
# the whole key is known.
full_key = key.lower().removeprefix("0x")
if len(full_key) == 64 and _is_hex(full_key):
if len(full_key) == 64 and is_path_hash(full_key):
info_actions.append(_Action("share", "📱", "", "Share contact — QR / link"))
# -- contact management, the page's last group and the only actions that end the visit.
# Withheld entirely when the caller opened the page to look rather than to act (see
+3 -3
View File
@@ -51,7 +51,7 @@ from rich.text import Text
from ..core.channels import decrypt_channel_text, identify_channel
from ..core.models import NODE_TYPE_LABELS, Observation, utcnow
from ..services.trace_runner import NodeResolver
from .map_render import _SELF, _UNKNOWN
from .marks import SELF_MARK, UNKNOWN_MARK
from .menus import SEP_COMPACT, SEP_ROOMY
from .pathgraph import PathLayer, render_path_graph, revisited_hops
from .pathline import PathLine, hops_atom, path_line
@@ -773,12 +773,12 @@ class PacketViewer(Screen):
The ``(glyph, style)`` pair, ready to append to the row.
"""
if style == "you":
return _SELF
return SELF_MARK
node_type = entry.node_type
if node_type is None and entry.node and self._type_of is not None:
node_type = self._type_of(entry.node)
if node_type is None:
return _UNKNOWN
return UNKNOWN_MARK
return _NODE_GLYPHS.get(node_type, _DEFAULT_GLYPH)
def _tail_rows(self, entry: PacketEntry) -> list[tuple[str, RenderableType]]:
+4 -4
View File
@@ -71,7 +71,7 @@ from ..services.topology import (
HopSuggestion,
Link,
MeshTopology,
_is_hex,
is_path_hash,
render_custom_spec,
render_forced_spec,
)
@@ -79,7 +79,7 @@ from .pathline import PathLine, cut_to, path_line
from .theme import snr_style
from .tui.render import query_line, render_lines, render_to_ansi
from .tui.screen import ListWindow, Screen
from .widgets import NodeResolver, _age_seconds, _format_age, _identity, path_text
from .widgets import NodeResolver, _age_seconds, _format_age, identity_label, path_text
#: Sentinel spec meaning "no forced path — let the device route" (the trace screen's
#: empty-spec convention). Only meaningful in target mode; a path walk has no target
@@ -177,7 +177,7 @@ class PathComposerScreen(Screen):
hops: list[str] | None = None,
cursor: int | None = None,
fetch_nodes: frozenset[str] = frozenset(),
resolve: NodeResolver = _identity,
resolve: NodeResolver = identity_label,
) -> None:
"""Build the composer.
@@ -385,7 +385,7 @@ class PathComposerScreen(Screen):
def _custom_hex(self) -> str | None:
"""The typed entry as an addable hex hop, or ``None`` when it isn't one."""
needle = self._entry.strip().lower().removeprefix("0x")
return needle if _is_hex(needle) else None
return needle if is_path_hash(needle) else None
def _rows(self) -> list[tuple[str, object]]:
"""The cursor-addressable rows: custom hop, suggestions, fetch, then actions."""
+3 -10
View File
@@ -107,6 +107,7 @@ from dataclasses import dataclass
from itertools import pairwise, permutations, product
from math import ceil
from ..services.topology import is_path_hash
from .mapcanvas import MapCanvas
from .marks import ( # noqa: F401 - canonical home; re-exported for existing importers
DST_NODE,
@@ -281,9 +282,6 @@ def _collapse(layers: Sequence[PathLayer]) -> list[PathLayer]:
return drawn
_HEX_DIGITS = frozenset("0123456789abcdef")
def _coalesce_prefixes(layers: Sequence[PathLayer]) -> list[PathLayer]:
"""Fold an under-specified hop into the longer id it can only be, across the layers.
@@ -338,14 +336,14 @@ def _prefix_merge(nodes: set[str]) -> tuple[str, str] | None:
only name that one node. Shortest ids are offered first, collapsing a chain from its end.
"""
for short in sorted(nodes, key=len):
if len(short) >= 12 or not _is_hex(short):
if len(short) >= 12 or not is_path_hash(short):
continue
exts = [
other
for other in nodes
if other != short
and len(other) > len(short)
and _is_hex(other)
and is_path_hash(other)
and other.startswith(short)
]
if not exts:
@@ -356,11 +354,6 @@ def _prefix_merge(nodes: set[str]) -> tuple[str, str] | None:
return None
def _is_hex(value: str) -> bool:
"""Whether every character of ``value`` is a hex digit (endpoint sentinels are not)."""
return bool(value) and all(char in _HEX_DIGITS for char in value)
def revisited_hops(hops: Sequence[str]) -> tuple[str, ...]:
"""The hops one path touches more than once, in first-appearance order.
+2 -2
View File
@@ -192,9 +192,9 @@ async def _rank(ctx: AppContext, contacts: list[Contact]) -> list[ScoredContact]
Returns:
The full ranking, strongest first.
"""
from ..core.contact_score import _node_id
from ..core.contact_score import node_id
nodes = [_node_id(c) for c in contacts]
nodes = [node_id(c) for c in contacts]
signals = ctx.repo.contact_signals(nodes)
# Channel attribution is by display name — a channel frame carries no sender key — so a
+2 -2
View File
@@ -45,7 +45,7 @@ from rich.text import Text
from ..core.geo import haversine_km
from ..persistence.repository import DiscoveredPath
from ..services import trace_runner
from ..services.records import CATEGORIES, CATEGORY_BY_ID, Category, _local_xy
from ..services.records import CATEGORIES, CATEGORY_BY_ID, Category, local_xy
from .mapcanvas import RGB, MapCanvas
from .menus import fit_cells, icon_lane, marked_label, section_heading
from .pathgraph import PathLayer, render_path_graph
@@ -854,7 +854,7 @@ async def open_records(ctx: AppContext) -> dict:
pos, ntype = node_geo(node_id)
if pos is None:
continue
east, north = _local_xy(self_pos, pos)
east, north = local_xy(self_pos, pos)
# The node-type glyph in the node's *name* hue — the pin reads as that mesh
# name, the way the route line and graph labels colour it; an unnamed hop keeps
# the neutral shape tone so it never masquerades as a coloured name.
+6 -6
View File
@@ -30,7 +30,7 @@ from rich.console import Group
from rich.text import Text
from ..core.remote_config import known_commands
from .tui.prompt import _LineEditor
from .tui.prompt import LineEditor
from .tui.render import render_lines
from .tui.screen import Screen
from .tui.spinner import Spinner
@@ -83,7 +83,7 @@ class RemoteCliScreen(Screen):
self._node_label = node_label
self._send = send
self._session = session
self._editor = _LineEditor()
self._editor = LineEditor()
self._log: list[Text] = []
self._history = list(history)
self._recall: int | None = None # index into history while ↑/↓ browse it
@@ -142,7 +142,7 @@ class RemoteCliScreen(Screen):
if action == "enter":
command = self._editor.text.strip()
if command and not self.busy:
self._editor = _LineEditor()
self._editor = LineEditor()
self._send(command)
elif action == "up":
self._recall_step(-1)
@@ -151,7 +151,7 @@ class RemoteCliScreen(Screen):
elif action == "tab":
completion = self._completion()
if completion is not None:
self._editor = _LineEditor(completion)
self._editor = LineEditor(completion)
elif action == "pageup":
self.scroll_pages(-1)
elif action in ("pagedown",):
@@ -175,10 +175,10 @@ class RemoteCliScreen(Screen):
self._recall += direction
if self._recall >= len(self._history):
self._recall = None
self._editor = _LineEditor(self._draft)
self._editor = LineEditor(self._draft)
return
self._recall = max(0, self._recall)
self._editor = _LineEditor(self._history[self._recall])
self._editor = LineEditor(self._history[self._recall])
def _completion(self) -> str | None:
"""The first known command extending the current text, or ``None``."""
+2 -2
View File
@@ -62,7 +62,7 @@ from .menus import (
)
from .trace_screen import TracingDialog
from .tui import Choice, Separator
from .tui.select import SelectScreen, _splice_hint
from .tui.select import SelectScreen, splice_hint
from .tui.spinner import Spinner, spinner_interval
if TYPE_CHECKING:
@@ -145,7 +145,7 @@ class AdminMenu(SelectScreen):
def footer_hint(self) -> str: # type: ignore[override]
"""The list's own hint, plus the read atom while a readable setting is highlighted."""
base = super().footer_hint
return _splice_hint(base, READ_ONE_HINT) if self._readable_key() else base
return splice_hint(base, READ_ONE_HINT) if self._readable_key() else base
@property
def fkey_lane(self):
+1 -17
View File
@@ -1144,22 +1144,6 @@ def _known_name(resolve: NodeResolver, node: str | None, name: str | None) -> st
return None
async def _routing_prefix_bytes(ctx: AppContext) -> int:
"""The device's path-hash width in bytes, or 0 when unknowable.
Best-effort, exactly like the Nodes tool: the Time Machine reads stored history
and must work with no radio at all, so an unreachable device (or firmware that
doesn't report the mode) just leaves every hash un-highlighted.
"""
try:
if not (ctx.is_connected or ctx.settings.connect_on_start):
return 0
mode = await ctx.devstate.path_hash_mode()
except Exception: # noqa: BLE001 - optional read; absence just skips highlighting
return 0
return (mode + 1) if isinstance(mode, int) and 0 <= mode <= 3 else 0
async def _contact_resolvers(
ctx: AppContext,
) -> tuple[NodeResolver, Callable[[str | None], int | None], NodeResolver]:
@@ -1305,7 +1289,7 @@ async def open_timemachine(ctx: AppContext) -> None:
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
prefix_bytes = await _routing_prefix_bytes(ctx)
prefix_bytes = await ctx.devstate.routing_prefix_bytes()
resolve, type_of, resolve_key = await _contact_resolvers(ctx)
self_name, self_key = await _self_identity(ctx)
# One sort for the whole visit, so the order the user picks survives leaving a subject
+11 -11
View File
@@ -103,7 +103,7 @@ from .theme import snr_style
from .tui.render import render_lines, render_to_ansi
from .tui.screen import ListWindow, Screen
from .tui.spinner import Spinner, spinner_interval
from .widgets import NodeResolver, _link_text, _route_path, highlighted_hash
from .widgets import NodeResolver, highlighted_hash, link_text, route_path
if TYPE_CHECKING:
from ..context import AppContext
@@ -559,7 +559,7 @@ class TraceScreen(Screen):
if total > 1:
dialog.status = f"trace {done + 1}/{total} · transmitting…"
self._session.invalidate()
self._last_tx = asyncio.get_event_loop().time()
self._last_tx = asyncio.get_running_loop().time()
await self._trace_once(self._path_spec, self._on_trace)
except asyncio.CancelledError:
raise
@@ -590,7 +590,7 @@ class TraceScreen(Screen):
"""Seconds still owed before the next transmission may go out (0 when clear)."""
if self._last_tx is None or self._pace_s <= 0:
return 0.0
elapsed = asyncio.get_event_loop().time() - self._last_tx
elapsed = asyncio.get_running_loop().time() - self._last_tx
return max(0.0, self._pace_s - elapsed)
async def _animate(self) -> None:
@@ -951,7 +951,7 @@ class TraceScreen(Screen):
"""
indent = len(_ROUTE_LANE)
if current is not None:
route = _route_path(
route = route_path(
current,
self._device_label,
self._resolve,
@@ -967,7 +967,7 @@ class TraceScreen(Screen):
lines.append(_note(f"(auto · {self._auto_source})", indent))
return lines
if self._previous is not None:
route = _route_path(
route = route_path(
self._previous,
self._device_label,
self._resolve,
@@ -1022,7 +1022,7 @@ class TraceScreen(Screen):
prompt.append_text(
# The hashes read at the width the screen addresses hops by, like
# every other node this session shows.
_link_text(
link_text(
edge[0],
edge[1],
self._device_label,
@@ -1165,7 +1165,7 @@ class TraceScreen(Screen):
for agg in stats.hop_snrs:
table.add_row(
str(agg.index),
_link_text(
link_text(
agg.origin,
agg.destination,
self._device_label,
@@ -1212,7 +1212,7 @@ class TraceScreen(Screen):
return row
def _collapse_trace_width(mode: int) -> int:
def collapse_trace_width(mode: int) -> int:
"""Collapse a routing hash mode to the widest trace-representable hop width.
Routing widths are ``mode + 1`` bytes, but a trace's flags can only encode 1, 2, 4,
@@ -1460,7 +1460,7 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st
NeighbourInfo,
)
from ..services.path_probe import ProbeCandidate, ProbeOutcome, probe_paths
from ..services.topology import MeshTopology, _is_hex, build_topology, collapse_width
from ..services.topology import MeshTopology, build_topology, collapse_width, is_path_hash
from .path_composer import FetchNeighbours, PathComposerScreen
from .surface import TuiUi
from .tui import CANCEL, Choice, SelectScreen, Separator
@@ -1488,7 +1488,7 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st
# protocol default and what all stored evidence uses anyway. The user can override
# it for the session through the screen's *Path width* action (see pick_width).
try:
width_bytes = _collapse_trace_width(int(await ctx.devstate.path_hash_mode()))
width_bytes = collapse_trace_width(int(await ctx.devstate.path_hash_mode()))
except Exception: # noqa: BLE001 - optional read; the 1-byte default always works
width_bytes = 1
device_width = width_bytes # remembered so the width dialog can mark the default
@@ -1520,7 +1520,7 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st
.lower()
.removeprefix("0x")
)
target_hash = raw_hash if _is_hex(raw_hash) else None
target_hash = raw_hash if is_path_hash(raw_hash) else None
target_label = target_contact.name if target_contact else target
def fresh_topology() -> MeshTopology:
+6 -6
View File
@@ -79,7 +79,7 @@ def _center(content: Text, width: int) -> Text:
return line
class _LineEditor:
class LineEditor:
"""A minimal single-line text editor (insert, delete, and cursor movement).
Shared by :class:`TextScreen` and :class:`AutocompleteScreen`. Tracks the text and the
@@ -287,7 +287,7 @@ class TextScreen(_KeylessDialog):
self.title = title
self.footer_hint = footer_hint
self._prompt = prompt
self._editor = _LineEditor(default)
self._editor = LineEditor(default)
self._validate = validate
self._help = help_text
self._password = password
@@ -397,7 +397,7 @@ class PinDialog(_KeylessDialog):
self._device = device_name
self._error = error
self._help = help_text
self._editor = _LineEditor("", max_length=self.PIN_LENGTH)
self._editor = LineEditor("", max_length=self.PIN_LENGTH)
def render_body(self, width: int) -> list[str]:
"""Render the prompt, the six-slot PIN field, any hint, and a rejected-PIN error."""
@@ -718,7 +718,7 @@ class TypedConfirmDialog(_KeylessDialog):
self.title = title
self._warning = warning
self._word = word
self._editor = _LineEditor("")
self._editor = LineEditor("")
self._error = ""
@property
@@ -873,7 +873,7 @@ class AutocompleteScreen(_KeylessDialog):
self.title = title
self.footer_hint = footer_hint
self._prompt = prompt
self._editor = _LineEditor(default)
self._editor = LineEditor(default)
self._choices = choices
self._validate = validate
self._error = ""
@@ -928,7 +928,7 @@ class AutocompleteScreen(_KeylessDialog):
self._sugg = min(len(suggestions) - 1, self._sugg + 1) if suggestions else 0
elif action == "tab":
if suggestions:
self._editor = _LineEditor(suggestions[self._sugg])
self._editor = LineEditor(suggestions[self._sugg])
self._error = ""
elif action == "enter":
value = self._editor.text
+7 -7
View File
@@ -143,7 +143,7 @@ def _plain(label: str | Text) -> str:
return label.plain if isinstance(label, Text) else label
def _splice_hint(base: str, segment: str) -> str:
def splice_hint(base: str, segment: str) -> str:
"""Insert ``segment`` into a footer hint just before its trailing ``Esc`` clause.
Keeps the hint grammar's "Esc last" rule when a per-row hint (e.g. ``Del remove`` on a
@@ -182,7 +182,7 @@ def _insert_atom(base: str, atom: str, index: int = 1) -> str:
Surfaces a conditional *navigation* atom (the ←→ per-row scroll) right after the
leading move atom, keeping the hint's navigation-then-actions-then-``Esc`` shape — where
:func:`_splice_hint` instead places an *action* atom just before the trailing ``Esc``.
:func:`splice_hint` instead places an *action* atom just before the trailing ``Esc``.
"""
parts = base.split(" · ")
parts.insert(min(index, len(parts)), atom)
@@ -587,7 +587,7 @@ class SelectScreen(Screen):
advertises a key that would do nothing:
* the :attr:`_delete_hint` atom, spliced just before the trailing ``Esc`` clause
(see :func:`_splice_hint`) while the highlighted row is :attr:`Choice.deletable`;
(see :func:`splice_hint`) while the highlighted row is :attr:`Choice.deletable`;
* whatever ``key_hint`` names for the highlighted row's value — the shortcut keys
(``keys``) that would act on *it*, spliced the same way;
* the :attr:`_hscroll_hint` atom (``hscroll`` lists only), inserted right after the
@@ -600,11 +600,11 @@ class SelectScreen(Screen):
base = self._footer_base
current = self._current_choice()
if self._delete_hint and current is not None and current.deletable:
base = _splice_hint(base, self._delete_hint)
base = splice_hint(base, self._delete_hint)
if self._key_hint is not None:
atoms = self._key_hint(current.value if current is not None else None)
if atoms:
base = _splice_hint(base, atoms)
base = splice_hint(base, atoms)
if self._hscroll and self._hscroll_hint and self._selected_overflows():
base = _insert_atom(base, self._hscroll_hint)
if self._filter:
@@ -646,7 +646,7 @@ class SelectScreen(Screen):
lands on a deletable row.
"""
if self._delete_hint:
return _splice_hint(self._footer_base, self._delete_hint)
return splice_hint(self._footer_base, self._delete_hint)
return self._footer_base
# --- rendering -----------------------------------------------------------
@@ -665,7 +665,7 @@ class SelectScreen(Screen):
whole header, and the header only abbreviates once the *terminal* caps the box.
"""
footer = (
_splice_hint(self._footer_base, self._delete_hint)
splice_hint(self._footer_base, self._delete_hint)
if self._delete_hint
else self._footer_base
)
+2 -2
View File
@@ -45,7 +45,7 @@ from ..services.topology import build_topology, render_custom_spec
from .menus import icon_lane, icon_mark
from .pathline import SELF_GLYPH, PathHop, PathLine, cut_to, path_line
from .theme import name_style, snr_style
from .trace_screen import TracingDialog, _collapse_trace_width, snr_bar
from .trace_screen import TracingDialog, collapse_trace_width, snr_bar
from .tui.render import render_lines, render_to_ansi
from .tui.screen import Screen
from .tui.spinner import Spinner, spinner_interval
@@ -630,7 +630,7 @@ async def open_tx_optimize(
device_hash = str(self_info.get("public_key") or "") or None
try:
width_bytes = _collapse_trace_width(int(await ctx.devstate.path_hash_mode()))
width_bytes = collapse_trace_width(int(await ctx.devstate.path_hash_mode()))
except Exception: # noqa: BLE001 - optional read; the 1-byte default always works
width_bytes = 1
+8 -9
View File
@@ -67,8 +67,8 @@ from rich.text import Text
from ..core.models import NODE_TYPE_REPEATER, Contact, utcnow
from ..platforms import get_platform
from ..services.topology import Link, MeshTopology
from .map_render import _SELF, _UNKNOWN
from .mapcanvas import RGB, MapCanvas, parse_hex
from .marks import SELF_MARK, UNKNOWN_MARK
from .menus import fit_cells
from .pathline import ELIDE_HEAD, ELIDE_TAIL, SELF_GLYPH, PathHop, PathLine, cut_mark
from .theme import mark_rgb, name_style, snr_style
@@ -859,7 +859,7 @@ class WalkScreen(Screen):
for other, (x, y) in placed.items():
node = stand_in if other == _MORE else other
if node is None:
canvas.marker(x, y, "…", mark_rgb(_UNKNOWN[1]))
canvas.marker(x, y, "…", mark_rgb(UNKNOWN_MARK[1]))
continue
glyph, _colour = self._glyph(node)
canvas.marker(x, y, glyph, self._marker_rgb(node))
@@ -872,7 +872,7 @@ class WalkScreen(Screen):
self._label_right(canvas, x, y, self._label(other), self._label_rgb(other))
if _MORE in placed:
x, y = placed[_MORE]
grey = mark_rgb(_UNKNOWN[1])
grey = mark_rgb(UNKNOWN_MARK[1])
if stand_in is not None:
# The marker is that node now: its own mark, and its name in the selection
# white — a collapsed node is *only ever drawn while selected*, so white is
@@ -1133,10 +1133,10 @@ class WalkScreen(Screen):
"""
legend = Text()
for (glyph, colour), word in (
(_SELF, " you "),
(SELF_MARK, " you "),
(_NODE_GLYPHS[NODE_TYPE_REPEATER], " repeater "),
(_DEFAULT_GLYPH, " node "),
(_UNKNOWN, " unknown"),
(UNKNOWN_MARK, " unknown"),
):
legend.append(glyph, style=colour)
legend.append(word, style="muted")
@@ -1406,10 +1406,10 @@ class WalkScreen(Screen):
the platform must pick its own slot).
"""
if node == self._topo.self_id:
return _SELF
return SELF_MARK
contact = self._contacts.get(node)
if contact is None:
return _UNKNOWN
return UNKNOWN_MARK
return _NODE_GLYPHS.get(contact.node_type, _DEFAULT_GLYPH)
def _label(self, node: str) -> str:
@@ -1435,7 +1435,6 @@ async def open_walk(ctx: AppContext) -> None:
"""
from ..services.topology import build_topology
from .surface import TuiUi
from .timemachine_screen import _routing_prefix_bytes
if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller
raise RuntimeError("the mesh walk is only available in the menu")
@@ -1452,7 +1451,7 @@ async def open_walk(ctx: AppContext) -> None:
self_hash = str(info.get("public_key") or "") or None
except Exception: # noqa: BLE001 - names are a nicety; the graph renders without them
contacts = []
prefix_bytes = await _routing_prefix_bytes(ctx)
prefix_bytes = await ctx.devstate.routing_prefix_bytes()
topo = build_topology(
self_id=self_hash or "local",
+19 -24
View File
@@ -34,6 +34,8 @@ from ..core.models import (
NODE_TYPE_SENSOR,
Contact,
HopAggregate,
NameKeyResolver,
NodeResolver,
TraceResult,
TraceStats,
TxOptResult,
@@ -59,13 +61,6 @@ from .theme import glyph, mark_rgb, name_style, node_style, snr_style
if TYPE_CHECKING:
from ..core.discovery import DiscoveredDevice
#: Maps a hop's raw key-prefix hash to a display label (a contact name when known).
NodeResolver = Callable[[str | None], str | None]
#: Maps a display name back to its node's key hex, or ``None`` for a name no known
#: node carries (built by :func:`~meshterm.services.trace_runner.make_name_key_resolver`).
NameKeyResolver = Callable[[str], str | None]
def channel_glyph(name: str, secret: bytes | None) -> str:
"""The one-character openness marker for a channel, shared across channel-facing screens.
@@ -93,7 +88,7 @@ def channel_glyph(name: str, secret: bytes | None) -> str:
return glyph("🔒")
def _identity(label: str | None) -> str | None:
def identity_label(label: str | None) -> str | None:
"""Default node resolver: leave labels untouched."""
return label
@@ -146,11 +141,11 @@ def make_progress(console: Console) -> Progress:
)
def _link_text(
def link_text(
origin: str | None,
destination: str | None,
device_label: str,
resolve: NodeResolver = _identity,
resolve: NodeResolver = identity_label,
hash_bytes: int | None = None,
device_hash: str | None = None,
) -> Text:
@@ -187,7 +182,7 @@ def _link_text(
def traces_table(
traces: list[TraceResult],
device_label: str = LOCAL_DEVICE_LABEL,
resolve: NodeResolver = _identity,
resolve: NodeResolver = identity_label,
device_hash: str | None = None,
) -> Table:
"""Render every trace's per-hop SNR side by side, one column per trace.
@@ -227,7 +222,7 @@ def traces_table(
for idx in indices:
link = next(
(
_link_text(
link_text(
edges[idx].origin,
edges[idx].destination,
device_label,
@@ -265,7 +260,7 @@ def traces_table(
def path_text(
hops: Sequence[str | None],
resolve: NodeResolver = _identity,
resolve: NodeResolver = identity_label,
*,
prefix_bytes: int = 0,
self_name: str | None = None,
@@ -348,7 +343,7 @@ def path_text(
def revisit_note(
repeats: Sequence[str],
resolve: NodeResolver = _identity,
resolve: NodeResolver = identity_label,
*,
prefix_bytes: int = 0,
self_name: str | None = None,
@@ -678,10 +673,10 @@ def route_graph_style(
return glyph_of, label_of, label_rgb_of
def _route_path(
def route_path(
result: TraceResult,
device_label: str = LOCAL_DEVICE_LABEL,
resolve: NodeResolver = _identity,
resolve: NodeResolver = identity_label,
device_hash: str | None = None,
*,
bare_self: bool = False,
@@ -733,7 +728,7 @@ def _route_path(
def _route_text(
result: TraceResult,
device_label: str = LOCAL_DEVICE_LABEL,
resolve: NodeResolver = _identity,
resolve: NodeResolver = identity_label,
device_hash: str | None = None,
) -> Text:
"""Render a trace's walked route through THE path widget, on one line.
@@ -753,13 +748,13 @@ def _route_text(
Returns:
A :class:`Text` with the node sequence, or a muted note when no hops exist.
"""
return _route_path(result, device_label, resolve, device_hash).text()
return route_path(result, device_label, resolve, device_hash).text()
def _hop_medians_table(
hop_snrs: list[HopAggregate],
device_label: str,
resolve: NodeResolver = _identity,
resolve: NodeResolver = identity_label,
hash_bytes: int | None = None,
device_hash: str | None = None,
) -> Table:
@@ -782,7 +777,7 @@ def _hop_medians_table(
for agg in hop_snrs:
table.add_row(
str(agg.index),
_link_text(agg.origin, agg.destination, device_label, resolve, hash_bytes, device_hash),
link_text(agg.origin, agg.destination, device_label, resolve, hash_bytes, device_hash),
Text(f"{agg.median_snr:+.1f} dB", style=snr_style(agg.median_snr)),
)
return table
@@ -791,7 +786,7 @@ def _hop_medians_table(
def stats_panel(
stats: TraceStats,
device_label: str = LOCAL_DEVICE_LABEL,
resolve: NodeResolver = _identity,
resolve: NodeResolver = identity_label,
route: TraceResult | None = None,
device_hash: str | None = None,
) -> Panel:
@@ -1026,7 +1021,7 @@ def _key_id(value: str) -> str:
return value.lower().removeprefix("0x")[:12]
def _contact_pkts(contact: Contact, counts: dict[str, int]) -> int | None:
def contact_packets(contact: Contact, counts: dict[str, int]) -> int | None:
"""The overheard-packet tally for ``contact``, or ``None`` if never overheard."""
ident = contact.public_key or contact.key_prefix
return counts.get(_key_id(ident)) if ident else None
@@ -1116,7 +1111,7 @@ def ordered_contacts(
elif sort.column == "packets":
def metric(c: Contact) -> float:
return _contact_pkts(c, counts) or 0
return contact_packets(c, counts) or 0
else:
def metric(c: Contact) -> object:
@@ -1353,7 +1348,7 @@ def contacts_table(
for c in ordered_contacts(contacts, counts, sort):
secs = _age_seconds(c.last_seen)
glyph, glyph_style = _NODE_GLYPHS.get(c.node_type, _DEFAULT_GLYPH)
pkts = _contact_pkts(c, counts)
pkts = contact_packets(c, counts)
table.add_row(
Text(glyph, style=glyph_style),
Text(c.name, style=name_style(c.name, c.public_key or c.key_prefix)),
+14 -11
View File
@@ -187,9 +187,11 @@ class _FakeMeshCore:
@pytest.fixture()
def quick_budget(monkeypatch): # noqa: ANN001
"""Shrink the route-sized reply budget so a no-reply test is not a ten-second wait."""
import meshterm.services.trace_runner as trace_runner
# Patched where the device *reads* it: the budget arithmetic lives in ``core.tracing``
# and ``core.connection`` binds the name at import, so that binding is the one in play.
import meshterm.core.connection as connection
monkeypatch.setattr(trace_runner, "trace_timeout", lambda hops: 0.05)
monkeypatch.setattr(connection, "trace_timeout", lambda hops: 0.05)
def _device(mc) -> MeshCoreDevice: # noqa: ANN001
@@ -353,22 +355,22 @@ def test_the_reply_budget_is_sized_to_the_route_the_login_has_to_walk() -> None:
The login goes out along the contact's route and the answer comes back over it, so the
wire carries twice the stored one-way hops — the same shape ``run_trace`` budgets for.
"""
import meshterm.services.trace_runner as trace_runner
import meshterm.core.connection as connection
asked: list[int] = []
real = trace_runner.trace_timeout
real = connection.trace_timeout
def spy(hops): # noqa: ANN001
asked.append(hops)
return 0.01
trace_runner.trace_timeout = spy
connection.trace_timeout = spy
try:
two_hops = Contact(name="Hub-Far", public_key="a1b2c3d4" * 8, route_hops=("3d", "f2"))
asyncio.run(_device(_FakeMeshCore()).admin_login(two_hops, "hunter2"))
asyncio.run(_device(_FakeMeshCore()).admin_login(_NODE, "hunter2"))
finally:
trace_runner.trace_timeout = real
connection.trace_timeout = real
# Each login asks twice: for its own walk, and for the routeless floor (hops ``0``)
# it may never be given less than.
@@ -384,10 +386,11 @@ def test_a_known_short_route_never_buys_less_patience_than_no_route_at_all() ->
narrower window than the routeless contact beside it that floods — so the flood budget
is the floor, and the route only ever widens it.
"""
import meshterm.services.trace_runner as trace_runner
import meshterm.core.connection as connection
import meshterm.core.tracing as tracing
budgets: list[float] = []
real = trace_runner.trace_timeout
real = connection.trace_timeout
def spy(hops): # noqa: ANN001
# The real shape, scaled down so the no-reply this provokes is not a real wait.
@@ -395,16 +398,16 @@ def test_a_known_short_route_never_buys_less_patience_than_no_route_at_all() ->
budgets.append(budget)
return budget
trace_runner.trace_timeout = spy
connection.trace_timeout = spy
try:
near = Contact(name="Hub-Near", public_key="a1b2c3d4" * 8, route_hops=("3d",))
asyncio.run(_device(_FakeMeshCore()).admin_login(near, "hunter2"))
finally:
trace_runner.trace_timeout = real
connection.trace_timeout = real
walked, floor = budgets
assert walked < floor # the literal trace sizing really is the narrower of the two
assert real(2) < real(0) == trace_runner.TRACE_TIMEOUT_FLOOD_S # and so at full scale
assert real(2) < real(0) == tracing.TRACE_TIMEOUT_FLOOD_S # and so at full scale
# --- the simulator speaks the same three answers --------------------------------------
+2 -1
View File
@@ -17,13 +17,14 @@ from rich.console import Console
from meshterm.context import AppContext
from meshterm.core.admin_store import AdminStore
from meshterm.core.channel_probe import read_channel_slots
from meshterm.core.channel_store import ChannelStore, reconcile
from meshterm.core.channels import DEFAULT_PUBLIC_SECRET, channel_identity, derive_secret
from meshterm.core.config import Settings
from meshterm.core.connection import make_device
from meshterm.core.device_store import DeviceStore
from meshterm.persistence.repository import Repository
from meshterm.ui.channels import read_channel_slots, write_channel
from meshterm.ui.channels import write_channel
PUB_A = "aa" * 32
PUB_B = "bb" * 32
+3 -8
View File
@@ -18,6 +18,7 @@ from rich.console import Console
from meshterm.context import AppContext
from meshterm.core.admin_store import AdminStore
from meshterm.core.channel_probe import ChannelSlot, read_channel_slots
from meshterm.core.channels import (
CHANNEL_SECRET_BYTES,
CHANNEL_SLOT_EMPTY_RUN,
@@ -37,13 +38,7 @@ from meshterm.core.device_store import DeviceStore
from meshterm.persistence.repository import Repository
from meshterm.services.chat_service import ChatService
from meshterm.tools.channels import ChannelsTool
from meshterm.ui.channels import (
_CREATE,
ChannelSlot,
_apply_order,
_next_free_slot,
read_channel_slots,
)
from meshterm.ui.channels import _CREATE, _apply_order, _next_free_slot
from meshterm.ui.qr import QrScreen, fit_qr, qr_text
_ANSI = re.compile(r"\x1b\[[0-9;]*m")
@@ -1076,8 +1071,8 @@ async def test_a_probe_cut_short_by_a_failed_read_is_not_a_layout() -> None:
They look identical in the returned list — a short one either way — which is what let
one timed-out read stand in for "this device has no channels".
"""
from meshterm.core.channel_probe import probe_channel_slots
from meshterm.core.connection import DeviceCommandError
from meshterm.ui.channels import probe_channel_slots
dropped = _FlakyDevice(["Alpha", "Beta"], fail_from=1, error=DeviceCommandError("no reply"))
slots, complete = await probe_channel_slots(dropped)
+6 -6
View File
@@ -1129,14 +1129,14 @@ def test_chat_screen_up_picks_and_ctrl_end_returns_to_compose() -> None:
def test_split_channel_sender_extracts_name_prefix() -> None:
"""A ``Name: message`` channel line splits into sender and cleaned body."""
from meshterm.ui.chat import _split_channel_sender
from meshterm.core.channels import split_channel_sender
assert _split_channel_sender("Alice: hey there") == ("Alice", "hey there")
assert _split_channel_sender("Yagi Repeater: online") == ("Yagi Repeater", "online")
assert split_channel_sender("Alice: hey there") == ("Alice", "hey there")
assert split_channel_sender("Yagi Repeater: online") == ("Yagi Repeater", "online")
# No plausible prefix: left untouched.
assert _split_channel_sender("just a message") == (None, "just a message")
assert _split_channel_sender("https://example.com") == (None, "https://example.com")
assert _split_channel_sender("14:30 standup") == (None, "14:30 standup")
assert split_channel_sender("just a message") == (None, "just a message")
assert split_channel_sender("https://example.com") == (None, "https://example.com")
assert split_channel_sender("14:30 standup") == (None, "14:30 standup")
def test_channel_transcript_groups_by_sender() -> None:
+74 -6
View File
@@ -81,6 +81,19 @@ _NOT_ONE_SHOT = {("monitor",), ("chat", "listen"), ("tx-optimize",)}
#: The one command whose output *is* its colour, and says so (:mod:`meshterm.ui.specimen`).
_KEEPS_ITS_COLOUR = {("specimen",)}
#: Extra arguments the derived sweep passes a leaf that would otherwise reach for real
#: hardware. ``devices`` enumerates serial ports *and* scans for Bluetooth companions, so
#: run bare it turned this machine's radio on three times per suite run and took its wall
#: time from whatever happened to be in the room. ``--no-ble`` drops the scan and keeps the
#: (cheap, local) serial walk. The tool is deliberately untouched: what the sweep checks is
#: the *shape* of an answer, and one transport's worth of rows proves that as well as two.
_SWEEP_ARGS: dict[tuple[str, ...], tuple[str, ...]] = {("devices",): ("--no-ble",)}
def _sweep(leaf: tuple[str, ...]) -> tuple[str, ...]:
"""The leaf as the sweep invokes it: its own path, plus any hardware-sparing flag."""
return (*leaf, *_SWEEP_ARGS.get(leaf, ()))
@pytest.fixture()
def run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): # noqa: ANN201 - a closure
@@ -166,7 +179,7 @@ def test_every_registered_command_obeys_the_rules(run, leaf) -> None: # noqa: A
``---`` in ``about`` drawn as a rule the width of a 16384-cell console, and the
``[muted]`` tags around what ``config export-key`` exists to emit.
"""
out = run(*leaf).stdout
out = run(*_sweep(leaf)).stdout
assert not _ANSI.search(out), f"{' '.join(leaf)} put an escape sequence on stdout"
assert not set(out) & set("─│┌┐└┘├┤━┃╭╮╰╯"), f"{' '.join(leaf)} drew a frame or a rule"
assert not _MARKUP.search(out), f"{' '.join(leaf)} printed a console markup tag"
@@ -188,7 +201,7 @@ def test_every_registered_command_answers_json_that_parses(run, leaf) -> None:
line on stdout is one complete document**, on success and on empty alike, and a
command that fails writes nothing there at all.
"""
result = run("--json", *leaf)
result = run("--json", *_sweep(leaf))
for line in result.stdout.splitlines():
json.loads(line) # raises, with the offending line, if anything else got out
if result.exit_code in (exitcodes.OK, exitcodes.NO_RESULT):
@@ -209,7 +222,7 @@ def test_the_two_faces_never_disagree_about_the_exit_status(run, leaf) -> None:
plain path said ``5``, so a script could not tell an empty scan from a full one by
asking the same question twice.
"""
assert run("--json", *leaf).exit_code == run(*leaf).exit_code, " ".join(leaf)
assert run("--json", *_sweep(leaf)).exit_code == run(*_sweep(leaf)).exit_code, " ".join(leaf)
@pytest.mark.parametrize("leaf", sorted(_REFUSES_JSON), ids=lambda leaf: "-".join(leaf))
@@ -221,7 +234,7 @@ def test_a_command_whose_output_is_the_colour_refuses_json_loudly(run, leaf) ->
refuse from. It is a usage error, so stdout stays empty and the sentence goes where
every other failure's does.
"""
result = run("--json", *leaf)
result = run("--json", *_sweep(leaf))
assert result.exit_code == exitcodes.USAGE
assert result.stdout == ""
assert "machine-readable" in result.stderr
@@ -238,6 +251,54 @@ def test_the_menu_has_no_document_and_says_so(run) -> None: # noqa: ANN001
assert result.stdout == ""
def test_no_leaf_command_declares_a_short_option_the_globals_already_claim() -> None:
"""A leaf short form that a global also spells could never be reached, only shadowed.
``_globals_first`` lifts any token matching a group option ahead of the subcommand
wherever it was typed, so ``trace -t Alice -p a1,d4`` handed ``a1,d4`` to ``--profile``
and failed with "no device profile named 'a1,d4'". Three commands documented ``-p`` as
the short form of ``--path``, and on all three it was unusable. Checked against the real
app rather than a list, because the next collision will be some other letter.
"""
from typer.main import get_command
from meshterm.cli import app
root = get_command(app)
globals_ = {
opt
for param in root.params
for opt in getattr(param, "opts", ())
if opt.startswith("-") and not opt.startswith("--")
}
assert globals_, "the root group declares no short options — has the callback moved?"
def walk(command, prefix: tuple[str, ...] = ()) -> None: # noqa: ANN001
for name, sub in sorted(getattr(command, "commands", {}).items()):
here = (*prefix, name)
if getattr(sub, "commands", None):
walk(sub, here)
continue
for param in sub.params:
clash = globals_ & {o for o in getattr(param, "opts", ()) if o.startswith("-")}
assert not clash, f"{' '.join(here)} declares {sorted(clash)}, a global's own"
walk(root)
def test_version_answers_without_touching_a_device(run) -> None: # noqa: ANN001
"""``--version`` is the one question that is about the program, not about a run.
Eager, so it answers before a database is opened or a radio looked for, and bare — one
field for a script to read back. Knowing the version is a success, so it exits ``0``.
"""
from meshterm import __version__
result = run("--version")
assert result.exit_code == exitcodes.OK
assert result.stdout.strip() == f"meshterm {__version__}"
def test_the_sweep_actually_covers_the_whole_command_surface() -> None:
"""A derived list is only a guarantee while it is still finding the commands.
@@ -562,8 +623,14 @@ def test_a_port_that_will_not_open_is_no_device_not_a_device_failure(run) -> Non
("repeater-admin", "Nobody", "get", "name"),
("courier", "queue", "Nobody", "hi"),
("courier", "queue", "Alice", "hi", "--at", "25:99"),
("tx-optimize", "--path", "Yagi-Repeater", "--samples", "1"),
],
ids=[
"unknown-admin-node",
"unknown-courier-contact",
"bad-at-time",
"tx-optimize-one-hop-path",
],
ids=["unknown-admin-node", "unknown-courier-contact", "bad-at-time"],
)
def test_a_bad_argument_is_never_reported_as_a_device_failure(run, args) -> None: # noqa: ANN001
"""``4`` promises a caller that the radio answered and a retry is worth trying.
@@ -571,7 +638,8 @@ def test_a_bad_argument_is_never_reported_as_a_device_failure(run, args) -> None
Each of these is the *argument* being wrong, decided before a word goes over the air —
so a caller that retried on ``4`` would retransmit nothing, forever. ``tx-optimize``
already answered the identical question the identical way for a missing password;
these three were the ones that had not caught up.
these are the ones that had not caught up — including its own one-hop ``--path``, which
reported ``4`` for a path that never left the machine.
"""
result = run(*args)
assert result.exit_code == exitcodes.USAGE, result.output
+6 -1
View File
@@ -566,6 +566,11 @@ async def test_location_picker_keeps_the_crosshair_when_the_basemap_lands(
assert coros, "no background raster was scheduled"
await coros[-1] # the raster finishes — long after the crosshair was taken back
# Every other coroutine the paint scheduled (the tile ``_load``) is collected, never
# awaited, so close them here: an un-awaited coroutine warns at collection time, and a
# RuntimeWarning from a passing test is noise the next real one hides behind.
for pending in coros[:-1]:
pending.close()
assert screen._frame is not None
assert "⌖" in _plain(screen._frame), "the basemap landed over the crosshair"
# And the finished frame is what the next paint serves, crosshair intact.
@@ -601,7 +606,7 @@ async def test_markers_without_waiting_never_ask_the_radio(
ctx: AppContext, monkeypatch: pytest.MonkeyPatch
) -> None:
"""The picker's markers come from what is in hand; the radio is never asked for them."""
from meshterm.tools.map import gather_markers
from meshterm.services.markers import gather_markers
device = await ctx.device()
+4 -2
View File
@@ -437,7 +437,8 @@ def _channels_manager(cols: int, rows: int) -> Screen:
mark folds to a different glyph on the console), a channel with no messages at all, and
a three-digit unread badge.
"""
from meshterm.ui.channels import _MANAGER_HINT, ChannelSlot, _LiveStats, _menu_items
from meshterm.core.channel_probe import ChannelSlot
from meshterm.ui.channels import _MANAGER_HINT, _LiveStats, _menu_items
slots = [
ChannelSlot(idx=0, name="Public", secret=DEFAULT_PUBLIC_SECRET),
@@ -452,7 +453,8 @@ def _channels_manager(cols: int, rows: int) -> Screen:
def _channel_detail(cols: int, rows: int) -> Screen:
"""One channel's action page, its vital-signs line above the rows."""
from meshterm.ui.channels import ChannelSlot, _detail_items, _detail_summary, _LiveStats
from meshterm.core.channel_probe import ChannelSlot
from meshterm.ui.channels import _detail_items, _detail_summary, _LiveStats
slot = ChannelSlot(idx=2, name="Lakeside emergency", secret=bytes(range(16)))
ctx = _ChannelsCtx(muted=set())
+11 -9
View File
@@ -29,9 +29,9 @@ from meshterm.core.models import (
utcnow,
)
from meshterm.core.mvt import GEOM_LINE, GEOM_POLYGON, Layer, decode_tile
from meshterm.services.basemap import TILE_RETRY_SECONDS as _TILE_RETRY
from meshterm.tools.map import MapTool
from meshterm.ui.map_screen import _PAN_DIRS, _PAN_STEP
from meshterm.ui.map_screen import _TILE_RETRY_SECONDS as _TILE_RETRY
from meshterm.ui.mapcanvas import MapCanvas, parse_hex
from tests.conftest import plain as _plain # THE strip-and-join screen reader
@@ -620,9 +620,10 @@ def _glyph_color(lines: list[str], glyph: str) -> tuple[int, int, int]:
def test_render_map_brightens_piled_markers() -> None:
"""A cell many nodes share renders its glyph brighter than a lone node's."""
from meshterm.ui.map_render import _NODE, MapMarker, render_map
from meshterm.ui.map_render import MapMarker, render_map
from meshterm.ui.marks import NODE_MARK
base = parse_hex(_NODE[1])
base = parse_hex(NODE_MARK[1])
vp = Viewport(45.50, -73.57, 14, 60, 40)
lone = render_map(vp, {}, [MapMarker("solo", 45.50, -73.57)])
@@ -1196,7 +1197,7 @@ async def test_gather_markers_drops_out_of_range_fix(ctx) -> None:
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
from meshterm.services.markers import gather_markers
run_id = ctx.repo.start_run("monitor", {})
ctx.repo.record_observation(
@@ -1244,7 +1245,7 @@ async def test_map_tool_reports_nothing_to_plot(ctx, monkeypatch) -> None:
async def _no_contacts(_ctx):
return []
monkeypatch.setattr("meshterm.tools.map._contacts", _no_contacts)
monkeypatch.setattr("meshterm.services.markers._contacts", _no_contacts)
result = await MapTool().run(ctx, {"static": True, "basemap": False})
assert result.summary == {"located": 0}
@@ -1257,7 +1258,7 @@ async def test_gather_markers_drops_null_island_fixes(ctx, monkeypatch) -> None:
fix at all, exactly as our own node's marker already is.
"""
from meshterm.core.models import Contact
from meshterm.tools.map import gather_markers
from meshterm.services.markers import gather_markers
async def _contacts(_ctx):
return [
@@ -1265,7 +1266,7 @@ async def test_gather_markers_drops_null_island_fixes(ctx, monkeypatch) -> None:
Contact(name="NoFix", public_key="bb" * 32, lat=0.0, lon=0.0),
]
monkeypatch.setattr("meshterm.tools.map._contacts", _contacts)
monkeypatch.setattr("meshterm.services.markers._contacts", _contacts)
labels = [m.label for m in await gather_markers(ctx)]
assert "Real" in labels
assert "NoFix" not in labels # the null-island node is dropped
@@ -1845,7 +1846,8 @@ def test_render_map_labels_take_the_name_hue_ours_white() -> None:
Our own label is white while the ★ glyph stays yellow, and a keyless label lands
on the muted grey.
"""
from meshterm.ui.map_render import _SELF, MapMarker, render_map
from meshterm.ui.map_render import MapMarker, render_map
from meshterm.ui.marks import SELF_MARK
from meshterm.ui.widgets import name_rgb
vp = Viewport.fit([(45.5, -73.6), (45.4, -73.5)], 120, 80, max_zoom=14)
@@ -1855,7 +1857,7 @@ def test_render_map_labels_take_the_name_hue_ours_white() -> None:
MapMarker("BARE", 45.45, -73.55),
]
lines = render_map(vp, {}, markers)
assert _glyph_color(lines, "★") == parse_hex(_SELF[1]) # the glyph keeps its yellow
assert _glyph_color(lines, "★") == parse_hex(SELF_MARK[1]) # the glyph keeps its yellow
assert _glyph_color(lines, "US") == (255, 255, 255) # ...the label goes you-white
assert _glyph_color(lines, "KEYED") == name_rgb("KEYED", "d4" * 32)
assert _glyph_color(lines, "BARE") == (148, 163, 184) # no key, the muted grey
+4
View File
@@ -169,6 +169,10 @@ async def test_the_trace_target_picker_is_a_popup_gone_before_the_live_screen(
async def contacts(self):
return list(contacts)
async def routing_prefix_bytes(self):
# What the real DeviceState answers with no radio: nothing to highlight.
return 0
class _Ctx:
repo = _Repo()
devstate = _Devstate()
+2 -2
View File
@@ -13,6 +13,7 @@ from types import SimpleNamespace
from rich.text import Text
from meshterm.core.geo import haversine_km
from meshterm.core.models import Contact, utcnow
from meshterm.services.topology import build_topology
from meshterm.services.trace_runner import (
@@ -26,7 +27,6 @@ from meshterm.ui.node_detail_screen import (
NodeDetailScreen,
_Action,
_bearing,
_distance_km,
_range_text,
_Route,
_route_line,
@@ -105,7 +105,7 @@ def test_minimap_clamps_zoom_to_the_source_ceiling() -> None:
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 1.0 < haversine_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
+1 -2
View File
@@ -556,12 +556,11 @@ def test_narrow_wordmark_keeps_its_dim_rows_off_the_bright_bank() -> None:
def test_mark_constants_reexport_from_their_old_hosts() -> None:
"""The P3 relocation to ``ui.marks`` left the old names bound in the old modules."""
from meshterm.ui.map_render import _NODE, _REPEATER, _SELF, _UNKNOWN
from meshterm.ui.mapcanvas import RGB, parse_hex
from meshterm.ui.marks import NODE_MARK, REPEATER_MARK, SELF_MARK, UNKNOWN_MARK
from meshterm.ui.pathgraph import DST_NODE, SRC_NODE, GlyphOf, LabelOf, LabelRgbOf
assert (_SELF, _REPEATER, _NODE, _UNKNOWN) == (
assert (SELF_MARK, REPEATER_MARK, NODE_MARK, UNKNOWN_MARK) == (
SELF_MARK,
REPEATER_MARK,
NODE_MARK,
+11 -11
View File
@@ -1058,9 +1058,9 @@ def test_text_screen_byte_limit_gauges_and_blocks_an_oversize_entry() -> None:
def test_line_editor_word_motion() -> None:
"""Ctrl+Left/Right hop by word — to the current word's start, else the previous/next."""
from meshterm.ui.tui.prompt import _LineEditor
from meshterm.ui.tui.prompt import LineEditor
editor = _LineEditor("the quick brown fox") # cursor at the end (len 20)
editor = LineEditor("the quick brown fox") # cursor at the end (len 20)
editor.edit("ctrl_left")
assert editor.cursor == 17 # start of "fox"
editor.edit("ctrl_left")
@@ -1086,33 +1086,33 @@ def test_text_screen_password_masks() -> None:
def test_line_editor_caps_length_and_truncates_paste() -> None:
"""A max_length editor swallows keys past the cap and truncates an over-long paste."""
from meshterm.ui.tui.prompt import _LineEditor
from meshterm.ui.tui.prompt import LineEditor
editor = _LineEditor("", max_length=6)
editor = LineEditor("", max_length=6)
for ch in "123456":
assert editor.edit("text", ch) is True
assert editor.edit("text", "9") is False # at capacity — key swallowed, buffer unchanged
assert editor.text == "123456"
pasted = _LineEditor("", max_length=6)
pasted = LineEditor("", max_length=6)
pasted.edit("text", "12345678") # one over-long insert
assert pasted.text == "123456" # filled only the six available slots
def test_line_editor_paste_folds_controls_and_respects_max_length() -> None:
"""A ``paste`` action folds newlines/controls to spaces and inserts the run at the cursor."""
from meshterm.ui.tui.prompt import _LineEditor
from meshterm.ui.tui.prompt import LineEditor
editor = _LineEditor("ab")
editor = LineEditor("ab")
editor.cursor = 1
assert editor.edit("paste", "X\nY") is True
assert editor.text == "aX Yb" # the newline became a space, inserted mid-buffer
capped = _LineEditor("", max_length=3)
capped = LineEditor("", max_length=3)
capped.edit("paste", "hello")
assert capped.text == "hel" # a paste is trimmed to the remaining room, like a big insert
assert _LineEditor("z").edit("paste", "") is False # nothing to paste leaves the buffer
assert LineEditor("z").edit("paste", "") is False # nothing to paste leaves the buffer
def test_pin_dialog_shows_six_slots_with_dots_for_blanks() -> None:
@@ -3304,11 +3304,11 @@ def test_the_splash_hint_stays_inside_the_box_it_is_drawn_in() -> None:
from meshterm.core.discovery import serial_device
from meshterm.platforms import PICOCALC, REGULAR
from meshterm.ui.device_picker import _shortcut_hint
from meshterm.ui.tui.select import _splice_hint
from meshterm.ui.tui.select import splice_hint
base = "↑↓ move · Enter select · Esc bye" # the splash's own send-off
radio = serial_device("COM7", name="A Radio")
common = _splice_hint(base, _shortcut_hint(0)(radio))
common = splice_hint(base, _shortcut_hint(0)(radio))
for platform in (REGULAR, PICOCALC):
budget = platform.readable_cols - platform.dialog_margin - 2
assert cell_len(common) <= budget, (platform.name, common)