Rename project from MeshTools to MeshTerm

Rename the package directory, imports, brand strings, env-var prefixes,
console-script entry point, and the config/data dir (~/.config/meshterm).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 4.8 committed 2026-07-07 19:40:49 -04:00
1 parent 850a1b3f34
commit 2ec18138a7
95 files changed
+289 -289

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
"permissions": {
"defaultMode": "dontAsk",
"additionalDirectories": [
"C:\\Users\\user\\.config\\meshtools\\output"
"C:\\Users\\user\\.config\\meshterm\\output"
]
}
}
+1 -1
View File
@@ -14,6 +14,6 @@ dist/
# Other virtual environments
venv/
# MeshTools runtime data
# MeshTerm runtime data
*.db
output/
+20 -20
View File
@@ -1,9 +1,9 @@
# MeshTools
# MeshTerm
A modern, extensible command-line toolkit for tuning and exploring a
[MeshCore](https://meshcore.co.uk/) mesh through a serial-connected companion device.
MeshTools is interactive by default (a Rich + Questionary menu) and fully scriptable
MeshTerm is interactive by default (a Rich + Questionary menu) and fully scriptable
(every menu option is also a Typer subcommand). Every run is logged to SQLite and can be
turned into interactive HTML visualizations.
@@ -38,39 +38,39 @@ Python 3.10+ is required (matching the `meshcore` library).
```bash
# Interactive menu (default)
meshtools
meshterm
# Scripted: every menu option is also a subcommand
meshtools trace --target Alice --samples 10 --profile yagi
meshterm trace --target Alice --samples 10 --profile yagi
# Force a route through specific repeaters (MeshCore-app style): comma-separated
# contact names and/or hex key prefixes, mixed freely. Blank lets the device route.
meshtools trace --target Alice --path "3d,f2,3d"
meshtools trace --target Alice --path "3d,Bravo-Repeater,f2"
meshtools tx-optimize --target Alice --samples 6 --step 3 --apply
meshtools info
meshtools history
meshterm trace --target Alice --path "3d,f2,3d"
meshterm trace --target Alice --path "3d,Bravo-Repeater,f2"
meshterm tx-optimize --target Alice --samples 6 --step 3 --apply
meshterm info
meshterm history
# Messaging: live chat in the menu, or scripted from the CLI
meshtools chat # interactive: pick a conversation, chat live
meshtools chat send --to Alice "on my way" # direct message
meshtools chat send --channel 0 "net in 5" # channel broadcast
meshtools chat history --to Alice
meshtools chat list
meshterm chat # interactive: pick a conversation, chat live
meshterm chat send --to Alice "on my way" # direct message
meshterm chat send --channel 0 "net in 5" # channel broadcast
meshterm chat history --to Alice
meshterm chat list
# Device configuration: view, set, back up, restore
meshtools config # show all current settings
meshtools config set radio_sf 9 # change one setting
meshtools config backup node.toml # archive every setting to TOML
meshtools config restore node.toml --dry-run
meshterm config # show all current settings
meshterm config set radio_sf 9 # change one setting
meshterm config backup node.toml # archive every setting to TOML
meshterm config restore node.toml --dry-run
# No radio attached? Use the built-in simulator for development.
meshtools --mock trace --target Alice
meshterm --mock trace --target Alice
```
## Architecture
MeshTools is layered so features are added by dropping a single file in `meshtools/tools/`:
MeshTerm is layered so features are added by dropping a single file in `meshterm/tools/`:
```
cli.py Typer app; no subcommand -> interactive menu
+5 -5
View File
@@ -1,15 +1,15 @@
# MeshTools configuration.
# Copy to ~/.config/meshtools/config.toml (or pass --db / --port on the CLI).
# MeshTerm configuration.
# Copy to ~/.config/meshterm/config.toml (or pass --db / --port on the CLI).
#
# Profiles are optional. With no profile and no --port, MeshTools discovers attached
# Profiles are optional. With no profile and no --port, MeshTerm discovers attached
# serial devices, lets you pick one (interactively) or uses the single one present, and
# remembers the last device that connected as the default for next time. Define profiles
# below only to give your hardware stable aliases (e.g. --profile yagi).
default_profile = "s3"
trace_cooldown_s = 1.0
# db_path = "C:/Users/you/meshtools/meshtools.db"
# output_dir = "C:/Users/you/meshtools/output"
# db_path = "C:/Users/you/meshterm/meshterm.db"
# output_dir = "C:/Users/you/meshterm/output"
# One [profiles.<name>] block per physical companion device.
[profiles.s3]
+3
View File
@@ -0,0 +1,3 @@
"""MeshTerm: a modern command-line toolkit for tuning and exploring a MeshCore mesh."""
__version__ = "0.1.0"
@@ -1,4 +1,4 @@
"""Enable ``python -m meshtools``."""
"""Enable ``python -m meshterm``."""
from .cli import main
+2 -2
View File
@@ -1,7 +1,7 @@
"""Typer entry point.
Global options are parsed once in the callback, which builds the shared
:class:`~meshtools.context.AppContext`. Running with no subcommand launches the
:class:`~meshterm.context.AppContext`. Running with no subcommand launches the
interactive menu; otherwise the selected tool's subcommand runs. Both paths funnel
through :func:`run_tool_command` / :func:`run_menu`, so behavior stays identical.
"""
@@ -32,7 +32,7 @@ app = typer.Typer(
add_completion=False,
no_args_is_help=False,
rich_markup_mode="rich",
help="MeshTools — a modern toolkit for tuning and exploring your MeshCore mesh.",
help="MeshTerm — a modern toolkit for tuning and exploring your MeshCore mesh.",
)
# The context built by the callback and consumed by subcommands within one process.
File renamed without changes.
File renamed without changes.
@@ -2,7 +2,7 @@
The remote-admin optimizer logs in to a repeater to tune its TX power; storing the
password means the user isn't prompted on every run. Like the remembered device
(:mod:`meshtools.core.device_store`), this lives in a small JSON file in the config
(:mod:`meshterm.core.device_store`), this lives in a small JSON file in the config
directory (``<config_dir>/admin.json``) rather than the per-invocation SQLite database,
because admin credentials are global machine state.
@@ -19,7 +19,7 @@ from urllib.parse import parse_qs, quote, urlsplit
CHANNEL_SECRET_BYTES = 16
#: The channel-slot capacity assumed when a device can't be probed. Stock MeshCore companion
#: firmware is built with 8 slots; :meth:`meshtools.core.connection.Device.channel_capacity`
#: firmware is built with 8 slots; :meth:`meshterm.core.connection.Device.channel_capacity`
#: discovers the real number from the hardware at runtime, so this is only the fallback.
MAX_CHANNELS = 8
@@ -1,6 +1,6 @@
"""Configuration and named device profiles.
Settings are read from a TOML file (default ``~/.config/meshtools/config.toml``) and may
Settings are read from a TOML file (default ``~/.config/meshterm/config.toml``) and may
be overridden per-invocation by CLI flags. Profiles let you alias your hardware
(``yagi`` repeater, ``local`` repeater, ``observer`` bot, ``s3`` serial companion) to a
serial port and defaults so commands can target them by name.
@@ -20,7 +20,7 @@ else: # pragma: no cover - exercised only on 3.10
def default_config_dir() -> Path:
"""Return the directory MeshTools uses for config and data.
"""Return the directory MeshTerm uses for config and data.
Honors ``$XDG_CONFIG_HOME`` when set; otherwise falls back to ``~/.config``.
@@ -31,7 +31,7 @@ def default_config_dir() -> Path:
base = os.environ.get("XDG_CONFIG_HOME")
root = Path(base) if base else Path.home() / ".config"
return root / "meshtools"
return root / "meshterm"
@dataclass(slots=True)
@@ -85,7 +85,7 @@ class Settings:
def __post_init__(self) -> None:
"""Derive dependent paths that were not explicitly provided."""
if self.db_path is None:
self.db_path = self.config_dir / "meshtools.db"
self.db_path = self.config_dir / "meshterm.db"
if self.output_dir is None:
self.output_dir = self.config_dir / "output"
File renamed without changes.
@@ -33,10 +33,10 @@ from .models import (
TraceResult,
)
#: Module logger; enable DEBUG on ``meshtools.core.connection`` to trace the message pump.
#: Module logger; enable DEBUG on ``meshterm.core.connection`` to trace the message pump.
_log = logging.getLogger(__name__)
#: Callback invoked with each :class:`~meshtools.core.events.MeshEvent` the device emits
#: Callback invoked with each :class:`~meshterm.core.events.MeshEvent` the device emits
#: (an overheard packet, an inbound message, an acknowledgement).
EventCallback = Callable[[MeshEvent], None]
@@ -62,7 +62,7 @@ TX_POWER_MAX = 22
#: Default range explored when tuning a *remote* repeater's transmit power. Remote nodes
#: (e.g. high-gain repeaters) typically run hotter than the local companion, so this band
#: differs from the local ``TX_POWER_MIN``/``TX_POWER_MAX`` clamp. Both bounds are
#: user-configurable (see :class:`~meshtools.core.config.Settings`).
#: user-configurable (see :class:`~meshterm.core.config.Settings`).
REMOTE_TX_MIN = 12
REMOTE_TX_MAX = 28
@@ -76,10 +76,10 @@ class DeviceCommandError(RuntimeError):
class Device(ABC):
"""Abstract companion device exposing the operations MeshTools needs.
"""Abstract companion device exposing the operations MeshTerm needs.
Implementations manage their own connection lifecycle and translate raw protocol
events into the domain models in :mod:`meshtools.core.models`.
events into the domain models in :mod:`meshterm.core.models`.
"""
@abstractmethod
@@ -185,13 +185,13 @@ class Device(ABC):
"""Begin streaming the device's unsolicited inbound events, without blocking.
Subscribes to everything the companion surfaces on its own: overheard adverts and
telemetry (as :attr:`~meshtools.core.events.EventKind.OBSERVATION` events), inbound
direct/channel text messages (:attr:`~meshtools.core.events.EventKind.MESSAGE`),
and delivery acknowledgements (:attr:`~meshtools.core.events.EventKind.ACK`). Each
is delivered to ``on_event`` as a :class:`~meshtools.core.events.MeshEvent` as it
telemetry (as :attr:`~meshterm.core.events.EventKind.OBSERVATION` events), inbound
direct/channel text messages (:attr:`~meshterm.core.events.EventKind.MESSAGE`),
and delivery acknowledgements (:attr:`~meshterm.core.events.EventKind.ACK`). Each
is delivered to ``on_event`` as a :class:`~meshterm.core.events.MeshEvent` as it
arrives. Delivery continues in the background until the returned callable is
invoked to stop it; the radio is never asked to transmit, it only listens. This is
the primitive the always-on :class:`~meshtools.services.event_hub.EventHub` is
the primitive the always-on :class:`~meshterm.services.event_hub.EventHub` is
built on.
Note:
@@ -2,7 +2,7 @@
Each :class:`SettingSpec` describes one tunable setting: how to read its current value
from a device snapshot, how to parse/validate/format it, and how to apply it back to the
:class:`~meshtools.core.connection.Device`. The same registry drives the interactive
:class:`~meshterm.core.connection.Device`. The same registry drives the interactive
editor, the ``config`` CLI subcommands, and TOML backup/restore — add a setting once and
it appears everywhere, mirroring the tool registry pattern.
@@ -4,7 +4,7 @@ The "last known good" device is remembered in a small JSON file in the config di
(``<config_dir>/devices.json``), deliberately *not* in the SQLite database: the database
can be swapped per-invocation with ``--db``, whereas the remembered device is global
machine state that should survive that. The record is matched back to currently attached
hardware by :attr:`~meshtools.core.discovery.DiscoveredDevice.stable_id`.
hardware by :attr:`~meshterm.core.discovery.DiscoveredDevice.stable_id`.
"""
from __future__ import annotations
@@ -7,7 +7,7 @@ still appear, just sorted after the likely candidates.
This module has no UI and no persistent state; it only reads what is currently plugged in.
The companion connection itself still goes through
:class:`~meshtools.core.connection.MeshCoreDevice`.
:class:`~meshterm.core.connection.MeshCoreDevice`.
"""
from __future__ import annotations
@@ -1,15 +1,15 @@
"""Typed events carried by the always-on mesh event hub.
These are the domain-level events that flow from the connected companion device out to
any number of interested subscribers (see :class:`~meshtools.services.event_hub.EventHub`).
any number of interested subscribers (see :class:`~meshterm.services.event_hub.EventHub`).
Keeping them here — plain dataclasses with no I/O dependencies, alongside the other
domain models — lets the hub, its subscribers, and the tests all speak the same language
without importing the device layer.
The hub carries the unsolicited inbound streams a client reacts to: overheard packets
(:class:`~meshtools.core.models.Observation`), inbound text messages
(:class:`~meshtools.core.models.Message`), and delivery acknowledgements
(:class:`~meshtools.core.models.Ack`). Further kinds (contact updates, path changes) slot
(:class:`~meshterm.core.models.Observation`), inbound text messages
(:class:`~meshterm.core.models.Message`), and delivery acknowledgements
(:class:`~meshterm.core.models.Ack`). Further kinds (contact updates, path changes) slot
in by adding an :class:`EventKind` member and stamping the payload onto a
:class:`MeshEvent`; subscribers that don't ask for the new kind are unaffected.
@@ -45,7 +45,7 @@ class MeshEvent:
"""One event delivered to hub subscribers.
A thin envelope: :attr:`kind` selects who receives it and :attr:`payload` carries the
kind-specific data (an :class:`~meshtools.core.models.Observation` for
kind-specific data (an :class:`~meshterm.core.models.Observation` for
:attr:`EventKind.OBSERVATION`). Kind-specific accessors like :attr:`observation` give
callers a typed handle without matching on ``kind`` themselves.
File renamed without changes.
@@ -114,7 +114,7 @@ class Message:
Direct messages carry a :attr:`sender` key prefix; channel messages carry a
:attr:`channel` index instead. Both are surfaced by the always-on event hub as
:attr:`~meshtools.core.events.EventKind.MESSAGE` events, so client features (an inbox,
:attr:`~meshterm.core.events.EventKind.MESSAGE` events, so client features (an inbox,
notifications) can react to them without polling.
Attributes:
@@ -162,7 +162,7 @@ def conversation_key(
is how history, unread counts, and the live screen all agree on which thread a message
belongs to. It is deliberately keyed on something *intrinsic* to the conversation — a
channel's identity (derived from its secret; see
:func:`~meshtools.core.channels.channel_identity`) and a contact's key prefix — never on
:func:`~meshterm.core.channels.channel_identity`) and a contact's key prefix — never on
a slot index or list position, so reordering channels never re-points history.
Args:
@@ -195,7 +195,7 @@ class ChatMessage:
is_channel: Whether it belongs to a channel rather than a direct exchange.
channel_id: The channel's slot-independent identity, for channel messages. This is
what the message is keyed to, so its history follows the channel across slot
reorders (see :func:`~meshtools.core.channels.channel_identity`).
reorders (see :func:`~meshterm.core.channels.channel_identity`).
channel_idx: The channel slot the message went out on / arrived on. Retained only
for reference and legacy backfill — the conversation key never uses it.
peer: The other party's key prefix, for direct messages.
@@ -272,7 +272,7 @@ class Conversation:
is_channel: Whether this is a channel rather than a direct conversation.
channel_idx: The channel slot to address for sending / live matching, for channels.
channel_id: The channel's slot-independent identity, used to key its history (see
:func:`~meshtools.core.channels.channel_identity`).
:func:`~meshterm.core.channels.channel_identity`).
secret: The channel's 16-byte secret, for channels — used only to show its
public/private openness marker; ``None`` when unknown.
contact: The contact, for direct conversations.
@@ -2,7 +2,7 @@
Whether background monitoring is enabled is remembered between sessions in a small JSON
file in the config directory (``<config_dir>/monitor.json``), following the same pattern
as :class:`~meshtools.core.device_store.DeviceStore`: it is machine/user state managed by
as :class:`~meshterm.core.device_store.DeviceStore`: it is machine/user state managed by
the app rather than user-authored config, and it must survive a per-invocation ``--db``
override, so it lives beside the config rather than in the swappable database.
@@ -4,11 +4,11 @@ Vector tiles are Protocol-Buffer messages (spec: github.com/mapbox/vector-tile-s
than pull in a protobuf runtime and a geometry library, this decodes the small subset the map
needs by hand: the protobuf wire format (varints, length-delimited fields) and the MVT
geometry command encoding (MoveTo/LineTo/ClosePath with zig-zag deltas). It is pure and
offline — the network fetch lives in :mod:`meshtools.services.basemap`.
offline — the network fetch lives in :mod:`meshterm.services.basemap`.
The result is a list of :class:`Layer`, each with decoded :class:`Feature` geometry in
*tile-local* integer coordinates (``0..extent``) and a resolved ``tags`` dict, ready to be
projected to the screen by :class:`meshtools.core.geo.Viewport`.
projected to the screen by :class:`meshterm.core.geo.Viewport`.
"""
from __future__ import annotations
@@ -111,6 +111,6 @@ def resolve_device(
raise DeviceSelectionError(
"Multiple serial devices detected and no default to fall back on.\n"
f"{_format_device_list(devices)}\n"
"Choose one with --port <PORT> (or run 'meshtools devices' to inspect them). "
"Choose one with --port <PORT> (or run 'meshterm devices' to inspect them). "
"The chosen device is remembered as the default after it connects."
)
File renamed without changes.
File renamed without changes.
@@ -14,7 +14,7 @@ from typing import Optional
from rich.console import Console
from rich.logging import RichHandler
_LOGGER_NAME = "meshtools"
_LOGGER_NAME = "meshterm"
class JsonlFormatter(logging.Formatter):
@@ -51,12 +51,12 @@ def configure_logging(
Args:
console: The Rich console the handler should render to.
log_dir: Directory for the ``meshtools.log.jsonl`` event file.
log_dir: Directory for the ``meshterm.log.jsonl`` event file.
level: Console log level.
quiet: When ``True``, suppress console output (file logging continues).
Returns:
The configured ``meshtools`` logger.
The configured ``meshterm`` logger.
"""
logger = logging.getLogger(_LOGGER_NAME)
logger.setLevel(logging.DEBUG)
@@ -71,7 +71,7 @@ def configure_logging(
logger.addHandler(rich_handler)
log_dir.mkdir(parents=True, exist_ok=True)
file_handler = logging.FileHandler(log_dir / "meshtools.log.jsonl", encoding="utf-8")
file_handler = logging.FileHandler(log_dir / "meshterm.log.jsonl", encoding="utf-8")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(JsonlFormatter())
logger.addHandler(file_handler)
@@ -472,7 +472,7 @@ class Repository:
conversation, taken as the highest-id (most recent) message in each.
Returns:
A mapping of :func:`~meshtools.core.models.conversation_key` to its latest
A mapping of :func:`~meshterm.core.models.conversation_key` to its latest
:class:`ChatMessage`.
"""
rows = self._conn.execute(
@@ -1,6 +1,6 @@
"""Algorithm layer: pure logic for tracing, TX search, and path exploration.
Services depend on the :class:`~meshtools.core.connection.Device` interface and domain
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.
"""
@@ -3,7 +3,7 @@
This is the only networked part of the map. It resolves a tile source's (versioned) tile-URL
template from its TileJSON, fetches ``.pbf`` vector tiles over HTTPS, and caches them on disk
so panning back over ground you've seen is instant and later sessions work offline. Decoding
is delegated to the pure :mod:`meshtools.core.mvt`.
is delegated to the pure :mod:`meshterm.core.mvt`.
The default source is **OpenFreeMap** (openfreemap.org) — full-planet OpenStreetMap vector
tiles, free and requiring no API key. Everything here is best-effort: with no network and no
@@ -28,7 +28,7 @@ from ..core.mvt import Layer, decode_tile
DEFAULT_TILEJSON_URL = "https://tiles.openfreemap.org/planet"
#: Sent on every request; identifies the client per common tile-usage etiquette.
_USER_AGENT = "MeshTools/0.1 (+https://github.com/; mesh node map)"
_USER_AGENT = "MeshTerm/0.1 (+https://github.com/; mesh node map)"
#: Fallback max tile zoom if the TileJSON doesn't declare one (OpenFreeMap serves 14).
_DEFAULT_MAX_ZOOM = 14
@@ -1,15 +1,15 @@
"""The chat service: message persistence, unread tracking, and the send path.
Like the passive monitor, this service is not a listener in its own right — the always-on
:class:`~meshtools.services.event_hub.EventHub` (``ctx.events``) does the listening. This
:class:`~meshterm.services.event_hub.EventHub` (``ctx.events``) does the listening. This
service is one of its subscribers: the one that writes every inbound
:class:`~meshtools.core.models.Message` to history as a
:class:`~meshtools.core.models.ChatMessage`, so a conversation transcript survives across
:class:`~meshterm.core.models.Message` to history as a
:class:`~meshterm.core.models.ChatMessage`, so a conversation transcript survives across
sessions. It also owns the per-conversation *unread* counters shown in the menu header, and
the outbound send path (so both the CLI and the live chat screen record what they send the
same way).
The service is session-scoped state on the :class:`~meshtools.context.AppContext`
The service is session-scoped state on the :class:`~meshterm.context.AppContext`
(``ctx.chat``). Unlike the monitor it has no on/off preference: messages addressed to us are
communications, not overheard noise, so they are always recorded while a device is listening.
"""
@@ -2,17 +2,17 @@
The hub is the single seam between the raw companion-device event stream and everything
that wants to react to it. It opens *one* subscription to the connected device, normalizes
what arrives into typed :class:`~meshtools.core.events.MeshEvent` values, and fans each
what arrives into typed :class:`~meshterm.core.events.MeshEvent` values, and fans each
one out to any number of subscribers. Unlike a one-shot capture it is meant to run for the
whole life of an interactive session — a MeshCore client must always be listening — so
subscribers come and go while the pump keeps running underneath them.
This decouples *listening* from *consuming*: the passive monitor's database logging becomes
just one subscriber (see :class:`~meshtools.services.monitor_service.MonitorService`), and
just one subscriber (see :class:`~meshterm.services.monitor_service.MonitorService`), and
future client features (a live node list, an incoming-message inbox) attach as additional
subscribers without touching the device layer.
The hub is session-scoped state on the :class:`~meshtools.context.AppContext`
The hub is session-scoped state on the :class:`~meshterm.context.AppContext`
(``ctx.events``). Fan-out runs synchronously on the event loop as packets arrive, so
handlers should stay cheap; a handler that returns a coroutine is scheduled as a task.
"""
File renamed without changes.
@@ -6,7 +6,7 @@ usually is?" — it splits a target's traces into a recent window and an older b
then flags end-to-end and per-hop metrics that have degraded beyond a threshold (e.g. the
yagi→local hop sitting 6 dB below its 30-day median, or the success rate falling off).
It is pure logic over :class:`~meshtools.core.models.TraceResult` lists, so it runs
It is pure logic over :class:`~meshterm.core.models.TraceResult` lists, so it runs
identically on live data, replayed history, or the simulator.
"""
@@ -3,14 +3,14 @@
Passive monitoring records every advert/telemetry frame the companion overhears to the
database, building the longitudinal history the coverage map and link-quality alerting
read back. It is not a listener in its own right: the always-on
:class:`~meshtools.services.event_hub.EventHub` (``ctx.events``) does the listening, and
:class:`~meshterm.services.event_hub.EventHub` (``ctx.events``) does the listening, and
this service is simply one of its subscribers — the one that writes observations to the
database. Listening is therefore unconditional; the on/off preference this service owns
controls only whether what's heard is *persisted to history*.
The service is session-scoped state on the :class:`~meshtools.context.AppContext`
The service is session-scoped state on the :class:`~meshterm.context.AppContext`
(``ctx.monitor``). It owns the on/off preference (persisted via
:class:`~meshtools.core.monitor_store.MonitorStore`), the hub subscription that records
:class:`~meshterm.core.monitor_store.MonitorStore`), the hub subscription that records
observations, and the counters shown live in the menu.
"""
@@ -1,6 +1,6 @@
"""Route-stability aggregation: turn trace history into a mesh graph with churn metrics.
The MeshCore app traces a route once. Because MeshTools persists every trace, it can
The MeshCore app traces a route once. Because MeshTerm persists every trace, it can
instead show how *stable* routing is over time — which hops are always used and which the
mesh flaps between. This service aggregates a set of traces into:
@@ -9,8 +9,8 @@ mesh flaps between. This service aggregates a set of traces into:
* per-target **churn** metrics: how many distinct routes were seen and what share the
single most-common route held (the higher that share, the steadier the routing).
It is pure logic over :class:`~meshtools.core.models.TraceResult` lists; the pyvis
renderer in :mod:`meshtools.viz.route_graph` draws the result.
It is pure logic over :class:`~meshterm.core.models.TraceResult` lists; the pyvis
renderer in :mod:`meshterm.viz.route_graph` draws the result.
"""
from __future__ import annotations
File renamed without changes.
@@ -148,7 +148,7 @@ async def optimize_tx_power(
"""Tune ``admin_node``'s TX power for the best signal at ``target``.
The caller must already be logged in to ``admin_node`` (see
:meth:`~meshtools.core.connection.Device.admin_login`).
:meth:`~meshterm.core.connection.Device.admin_login`).
Args:
device: The connected local device, used to trace and to drive the remote node.
File renamed without changes.
@@ -34,7 +34,7 @@ class ToolResult:
class Tool(ABC):
"""Base class for all MeshTools features.
"""Base class for all MeshTerm features.
Class Attributes:
name: CLI/menu identifier (kebab-case), unique across tools.
@@ -1,6 +1,6 @@
"""The ``channels`` tool: create, join, and manage mesh channels.
Interactively it opens a full-screen channel manager (see :mod:`meshtools.ui.channels`) — a
Interactively it opens a full-screen channel manager (see :mod:`meshterm.ui.channels`) — a
first-class, phone-app-style experience for creating private channels, adding public ``#``
channels, joining with a key, importing a scanned ``meshcore://`` link, and sharing any
channel as a QR code. On the CLI it exposes ``list``, ``add``, ``join``, ``import``, and
@@ -1,12 +1,12 @@
"""The ``chat`` tool: channel and direct messaging over the mesh.
Interactively it opens a conversation picker and then a live, full-screen chat (see
:mod:`meshtools.ui.chat`) where sent and received messages stream together. On the CLI it
:mod:`meshterm.ui.chat`) where sent and received messages stream together. On the CLI it
exposes ``send``, ``history``, and ``list`` subcommands for scripted use. Channels are only
*listed* here for picking; creating and editing channel slots lives in the ``channels`` tool.
Every inbound message is recorded to history by the always-on
:class:`~meshtools.services.chat_service.ChatService`, and outbound messages are recorded on
:class:`~meshterm.services.chat_service.ChatService`, and outbound messages are recorded on
send, so ``history`` reflects the full transcript regardless of which path produced it.
"""
@@ -106,7 +106,7 @@ class ChatTool(Tool):
of), so the cursor lands there rather than at the top.
Returns:
The chosen :class:`~meshtools.core.models.Conversation`, or ``None`` if
The chosen :class:`~meshterm.core.models.Conversation`, or ``None`` if
cancelled.
"""
device = await ctx.device()
@@ -368,7 +368,7 @@ def _enable_receive_debug() -> None:
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(logging.Formatter("%(name)s %(levelname)s %(message)s"))
for name in ("meshcore", "meshtools.core.connection"):
for name in ("meshcore", "meshterm.core.connection"):
log = logging.getLogger(name)
log.setLevel(logging.DEBUG)
log.addHandler(handler)
@@ -384,7 +384,7 @@ async def _read_channels(device: Device) -> list[Conversation]:
device: The connected device to probe.
Returns:
One :class:`~meshtools.core.models.Conversation` per configured channel (at least
One :class:`~meshterm.core.models.Conversation` per configured channel (at least
channel 0).
"""
conversations: list[Conversation] = []
@@ -463,7 +463,7 @@ def _recency_key(conversation: Conversation, lasts: dict) -> tuple:
class _LiveLasts:
"""A self-refreshing view of each conversation's most recent message.
The picker snapshots :meth:`~meshtools.persistence.repository.Repository.last_chat_messages`
The picker snapshots :meth:`~meshterm.persistence.repository.Repository.last_chat_messages`
once to *order* the rows (so the list never reshuffles under the cursor), but the row
previews read through this so a message arriving while the list is open updates the
sender/text preview on the next repaint. It re-queries the repository at most a few times a
@@ -1,6 +1,6 @@
"""The ``config`` tool: view and change every device configuration value.
Interactively it launches a full editor (see :mod:`meshtools.ui.config_editor`); on the
Interactively it launches a full editor (see :mod:`meshterm.ui.config_editor`); on the
CLI it exposes generic key/value subcommands plus backup/restore, channels, custom vars,
and a gated set of destructive operations. Both paths funnel into :meth:`ConfigTool.run`,
which executes a list of operation tuples so every change is logged through the run record.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,6 +1,6 @@
"""The ``link-health`` tool: flag links that have degraded against their own baseline.
Every trace MeshTools runs is persisted, so each link has a history. This tool splits a
Every trace MeshTerm runs is persisted, so each link has a history. This tool splits a
target's trace history into a recent window and an older baseline and reports any
end-to-end or per-hop metric that has dropped beyond a threshold — turning the live SNR
number the app shows into "this hop is 6 dB below its usual median". Optionally it takes a
@@ -1,12 +1,12 @@
"""The ``map`` tool: plot the mesh's located nodes on an OpenStreetMap terminal map.
Nodes that share their location in adverts are collected from the passive-monitor history
(:meth:`~meshtools.persistence.repository.Repository.heard_nodes`), our own node is added when
(:meth:`~meshterm.persistence.repository.Repository.heard_nodes`), our own node is added when
its position is known, and everything is drawn over a real street basemap rendered as Unicode
braille (streets, rivers, place names — the same terminal-map idea as ``mapscii``).
In the menu it opens a full-screen, pannable/zoomable map (see
:mod:`meshtools.ui.map_screen`). On the CLI it prints a one-shot render fitted to the nodes.
:mod:`meshterm.ui.map_screen`). On the CLI it prints a one-shot render fitted to the nodes.
Repeaters are prioritised over ordinary nodes: a distinct marker, drawn on top, listed first.
The basemap is best-effort — with no network (and no cached tiles) the nodes are plotted on a
blank grid instead, and the tool still works offline.
@@ -6,8 +6,8 @@ history that the coverage map and link-quality alerting read back. It transmits
it only listens.
Listening itself is always on: the session-wide
:class:`~meshtools.services.event_hub.EventHub` overhears every packet, and
:class:`~meshtools.services.monitor_service.MonitorService` (``ctx.monitor``) records
:class:`~meshterm.services.event_hub.EventHub` overhears every packet, and
:class:`~meshterm.services.monitor_service.MonitorService` (``ctx.monitor``) records
them to history as one of its subscribers. This tool is the control panel for that
recording: toggling it on/off (a preference remembered between sessions) and reviewing the
heard-node history. The live packet counters are shown in the main-menu header, not here.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -104,7 +104,7 @@ class ChannelSlot:
@property
def conversation(self) -> Conversation:
"""A :class:`~meshtools.core.models.Conversation` for opening this channel in chat."""
"""A :class:`~meshterm.core.models.Conversation` for opening this channel in chat."""
return Conversation(
label=self.name,
is_channel=True,
+4 -4
View File
@@ -4,11 +4,11 @@ This is the interactive, full-screen chat experience: a scrolling transcript wit
line pinned at the bottom, where messages you send and messages that arrive over the mesh
appear together in real time. Like the device picker and config editor, this module sits in
the UI layer but is allowed to depend on the context and services — it wires the
:class:`~meshtools.services.chat_service.ChatService` send path and the always-on event hub
to a :class:`~meshtools.ui.tui.screen.Screen`.
:class:`~meshterm.services.chat_service.ChatService` send path and the always-on event hub
to a :class:`~meshterm.ui.tui.screen.Screen`.
The screen subscribes to the hub for the duration it is open so inbound messages for the
current conversation append live; :class:`~meshtools.services.chat_service.ChatService`
current conversation append live; :class:`~meshterm.services.chat_service.ChatService`
independently persists every inbound message, so history is complete whether or not the
screen is open.
"""
@@ -137,7 +137,7 @@ class ChatScreen(Screen):
message (or ``None`` if nothing was sent).
names: Map of contact key prefix to friendly name, for labeling inbound
direct messages.
session: The running :class:`~meshtools.ui.tui.session.TuiSession`, used to
session: The running :class:`~meshterm.ui.tui.session.TuiSession`, used to
request repaints when messages arrive or a send completes.
resend: Async callable that re-attempts delivery of an unacknowledged direct
message, updating it in place (direct chats only; ``None`` for channels).
@@ -5,7 +5,7 @@ showing its current value and any staged change), lets the user stage changes se
setting with type-aware prompts and validation, and handles custom variables,
backup/restore and the destructive "danger zone". (Channels have their own first-class
manager — see the ``channels`` tool.) It returns an operation list for
:class:`~meshtools.tools.config.ConfigTool` to execute and log; it performs no device writes
:class:`~meshterm.tools.config.ConfigTool` to execute and log; it performs no device writes
itself (except danger-zone actions, which run immediately and show their result at once).
"""
@@ -268,7 +268,7 @@ async def _stage_custom_var(
async def _stage_backup(ctx: AppContext, extra_ops: list[tuple]) -> None:
"""Prompt for a backup destination path and stage the operation."""
path = await ctx.ui.path("Write backup to:", default="meshtools-config.toml")
path = await ctx.ui.path("Write backup to:", default="meshterm-config.toml")
if path:
extra_ops.append(("backup", Path(path)))
File renamed without changes.
@@ -1,9 +1,9 @@
"""Compose a rendered map frame: basemap geometry, labels, and mesh nodes.
Given a :class:`~meshtools.core.geo.Viewport` and the decoded vector tiles covering it, this
Given a :class:`~meshterm.core.geo.Viewport` and the decoded vector tiles covering it, this
projects every street, river, water body and place label onto a :class:`MapCanvas`, then
overlays the mesh nodes with their names on top. It is pure and synchronous — tile *fetching*
happens elsewhere (:mod:`meshtools.services.basemap`) — so both the interactive screen and
happens elsewhere (:mod:`meshterm.services.basemap`) — so both the interactive screen and
the one-shot CLI render call the same code.
Colours target a dark terminal (the app theme): warm roads, grey minor streets, blue water
@@ -1,8 +1,8 @@
"""The interactive full-screen map: a pannable, zoomable slippy map in the terminal.
This drives the braille street map inside the TUI. It owns a :class:`~meshtools.core.geo.
This drives the braille street map inside the TUI. It owns a :class:`~meshterm.core.geo.
Viewport` over the mesh's nodes, fetches the vector tiles covering it in the background (so
the UI never blocks on the network), and redraws via :func:`~meshtools.ui.map_render.
the UI never blocks on the network), and redraws via :func:`~meshterm.ui.map_render.
render_map`. Keys:
* ``w`` / ``a`` / ``s`` / ``d`` (or the arrow keys) pan north / west / south / east,
File renamed without changes.
+2 -2
View File
@@ -1,7 +1,7 @@
"""The interactive main menu, built dynamically from the tool registry.
The menu groups registered tools by category and runs the selected tool's interactive flow
inside the full-screen :class:`~meshtools.ui.tui.session.TuiSession`. Because it is generated
inside the full-screen :class:`~meshterm.ui.tui.session.TuiSession`. Because it is generated
from the registry, adding a tool automatically adds a menu entry with no changes here. The
persistent header shows the connection target and live passive-monitor counters; each tool's
prompts layer as dialogs, and its output appears in a bounded, scrollable result window.
@@ -75,7 +75,7 @@ def _header(ctx: AppContext) -> Text:
# The frame crops this to a single line (see frame.compose_base), so a narrow terminal
# shows what fits and chops the rest rather than wrapping onto a second row.
return Text.from_markup(
f"[brand]MeshTools[/brand] [muted]v{__version__}[/muted] · "
f"[brand]MeshTerm[/brand] [muted]v{__version__}[/muted] · "
f"[muted]device:[/muted] {target} · "
f"[{glyph_style}]{glyph}[/{glyph_style}][muted]{rest}[/muted]"
f"{chat_segment}"
File renamed without changes.
@@ -7,7 +7,7 @@ implementations back it:
behavior is byte-for-byte what it was before the TUI existed.
* :class:`TuiUi` (interactive menu): collects a tool's output and presents it in a bounded,
scrollable result window, and routes every prompt/progress through the full-screen
:class:`~meshtools.ui.tui.session.TuiSession`.
:class:`~meshterm.ui.tui.session.TuiSession`.
The interactive prompt methods are only ever reached from a tool's ``prompt_params`` (menu
only), so :class:`PlainUi` leaves them unsupported.
@@ -10,7 +10,7 @@ MESH_THEME = Theme(
"brand": "bold #5eead4",
"accent": "bold #818cf8",
# Our own messages in a chat: pure white, deliberately outside the per-sender hue
# palette (see meshtools.ui.chat._SENDER_COLORS) so "you" is always easy to spot.
# palette (see meshterm.ui.chat._SENDER_COLORS) so "you" is always easy to spot.
"you": "bold #ffffff",
"ok": "bold #4ade80",
"warn": "bold #fbbf24",
@@ -31,7 +31,7 @@ def make_console() -> Console:
them to UTF-8 where the runtime supports it so output never raises ``UnicodeEncodeError``.
Returns:
A :class:`rich.console.Console` configured with the MeshTools theme.
A :class:`rich.console.Console` configured with the MeshTerm theme.
"""
import sys
@@ -6,8 +6,8 @@ UI: screens never overflow the terminal, long content scrolls, going deeper stac
over a dimmed parent, and Esc always dismisses the current layer.
Public API:
- :class:`~meshtools.ui.tui.session.TuiSession` — the running session and prompt helpers.
- :class:`~meshtools.ui.tui.select.Choice` / :class:`~meshtools.ui.tui.select.Separator`
- :class:`~meshterm.ui.tui.session.TuiSession` — the running session and prompt helpers.
- :class:`~meshterm.ui.tui.select.Choice` / :class:`~meshterm.ui.tui.select.Separator`
— items for ``session.select``.
- Screen classes for advanced/custom layers.
"""
@@ -23,7 +23,7 @@ terminals is a different component than the one that **paints** it:
Because no escape sequence reports the renderer's width back to the program, we
decide the width for :data:`_PROBE` in layers, most trustworthy first:
1. An explicit override via ``MESHTOOLS_EMOJI_VS16=1|2`` — always wins.
1. An explicit override via ``MESHTERM_EMOJI_VS16=1|2`` — always wins.
2. A fingerprint of renderers known to paint VS16 emoji narrow while their PTY
counts them wide (VS Code, Windows Terminal) — where a probe would mislead.
3. Otherwise, a live cursor probe (``GetConsoleScreenBufferInfo`` on Windows, a
@@ -84,7 +84,7 @@ def _decide_vs16_width() -> int | None:
``1`` or ``2`` when we have a confident answer, else ``None`` (leave Rich
untouched). See the module docstring for why a probe alone is not enough.
"""
override = os.environ.get("MESHTOOLS_EMOJI_VS16")
override = os.environ.get("MESHTERM_EMOJI_VS16")
if override in ("1", "2"):
return int(override)
File renamed without changes.
@@ -3,7 +3,7 @@
Trace and TX-optimize sweeps drive progress with ``add_task`` / ``advance`` / ``update`` on a
Rich ``Progress`` in CLI mode. In the TUI the same calls update a bounded, centered progress
dialog instead, so tool code stays identical across both front-ends (see
:meth:`meshtools.ui.surface.PlainUi.progress` vs :meth:`~meshtools.ui.surface.TuiUi.progress`).
:meth:`meshterm.ui.surface.PlainUi.progress` vs :meth:`~meshterm.ui.surface.TuiUi.progress`).
"""
from __future__ import annotations
File renamed without changes.
File renamed without changes.
@@ -1,8 +1,8 @@
"""The screen abstraction: one layer in the TUI's window stack.
A :class:`Screen` knows how to render its body (as Rich, converted to ANSI lines by
:mod:`~meshtools.ui.tui.render`) and how to react to normalized key *actions* dispatched by
the :class:`~meshtools.ui.tui.session.TuiSession`. Screens never touch prompt_toolkit or the
:mod:`~meshterm.ui.tui.render`) and how to react to normalized key *actions* dispatched by
the :class:`~meshterm.ui.tui.session.TuiSession`. Screens never touch prompt_toolkit or the
terminal directly, so they stay small, uniform, and testable.
Interactive screens (select, text, confirm) resolve an :class:`asyncio.Future` when the user
@@ -60,7 +60,7 @@ Item = "Choice | Separator"
class SelectScreen(Screen):
"""A grouped, filterable, single-choice list.
Resolves with the chosen :class:`Choice` value, or :data:`~meshtools.ui.tui.screen.CANCEL`
Resolves with the chosen :class:`Choice` value, or :data:`~meshterm.ui.tui.screen.CANCEL`
if the user presses Esc.
"""
@@ -1,10 +1,10 @@
"""The persistent full-screen session: the heart of the TUI library.
A :class:`TuiSession` owns one prompt_toolkit :class:`Application`, a stack of
:class:`~meshtools.ui.tui.screen.Screen` layers, and the persistent header/footer frame. It
:class:`~meshterm.ui.tui.screen.Screen` layers, and the persistent header/footer frame. It
translates prompt_toolkit key events into normalized *actions* dispatched to the top screen,
composes the current view (bounded to the terminal, reflowing on resize) via
:mod:`~meshtools.ui.tui.frame`, and exposes ``async`` helpers (``select``/``text``/
:mod:`~meshterm.ui.tui.frame`, and exposes ``async`` helpers (``select``/``text``/
``confirm``/``autocomplete``/``scroll``/``progress``) that push a screen, await its result,
and pop it — the push/await/pop model behind every prompt.
"""
@@ -74,7 +74,7 @@ class TuiSession:
defaults to the real terminal.
"""
self._stack: list[Screen] = []
self._header = header or (lambda: Text("MeshTools", style="brand"))
self._header = header or (lambda: Text("MeshTerm", style="brand"))
self._app: Optional[Application] = None
self._input = input
self._output = output
@@ -115,7 +115,7 @@ class TuiSession:
screen: The screen to run.
Returns:
The screen's resolved value, or :data:`~meshtools.ui.tui.screen.CANCEL`.
The screen's resolved value, or :data:`~meshterm.ui.tui.screen.CANCEL`.
"""
loop = asyncio.get_running_loop()
screen.future = loop.create_future()
@@ -258,7 +258,7 @@ class TuiSession:
def base_body_size(self) -> tuple[int, int]:
"""Return the ``(width, height)`` in cells available to the base screen's body.
Mirrors the layout math in :func:`~meshtools.ui.tui.frame.compose_base` so a
Mirrors the layout math in :func:`~meshterm.ui.tui.frame.compose_base` so a
full-screen screen (e.g. the map) can size its own content to fill the frame exactly,
without waiting a repaint to learn its height.
@@ -92,7 +92,7 @@ def banner(
else:
target = "[muted]no device[/muted]"
body = Text.from_markup(
f"[brand]MeshTools[/brand] [muted]v{__version__}[/muted]\n"
f"[brand]MeshTerm[/brand] [muted]v{__version__}[/muted]\n"
f"[muted]device:[/muted] {target}"
)
return Panel(body, border_style="accent", expand=False, title="[accent]mesh[/accent]")
File renamed without changes.
File renamed without changes.
File renamed without changes.
-3
View File
@@ -1,3 +0,0 @@
"""MeshTools: a modern command-line toolkit for tuning and exploring a MeshCore mesh."""
__version__ = "0.1.0"
+3 -3
View File
@@ -3,7 +3,7 @@ requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "meshtools"
name = "meshterm"
version = "0.1.0"
description = "A modern command-line toolkit for tuning and exploring a MeshCore mesh."
readme = "README.md"
@@ -34,10 +34,10 @@ dev = [
]
[project.scripts]
meshtools = "meshtools.cli:main"
meshterm = "meshterm.cli:main"
[tool.hatch.build.targets.wheel]
packages = ["meshtools"]
packages = ["meshterm"]
[tool.ruff]
line-length = 100
+15 -15
View File
@@ -13,9 +13,9 @@ from pathlib import Path
import pytest
from rich.console import Console
from meshtools.context import AppContext
from meshtools.core.admin_store import AdminStore
from meshtools.core.channels import (
from meshterm.context import AppContext
from meshterm.core.admin_store import AdminStore
from meshterm.core.channels import (
CHANNEL_SECRET_BYTES,
DEFAULT_PUBLIC_SECRET,
channel_hash,
@@ -26,18 +26,18 @@ from meshtools.core.channels import (
random_secret,
share_url,
)
from meshtools.core.config import Settings
from meshtools.core.device_store import DeviceStore
from meshtools.persistence.repository import Repository
from meshtools.tools.channels import ChannelsTool
from meshtools.services.chat_service import ChatService
from meshtools.ui.channels import (
from meshterm.core.config import Settings
from meshterm.core.device_store import DeviceStore
from meshterm.persistence.repository import Repository
from meshterm.tools.channels import ChannelsTool
from meshterm.services.chat_service import ChatService
from meshterm.ui.channels import (
ChannelSlot,
_apply_order,
_next_free_slot,
_read_slots,
)
from meshtools.ui.qr import qr_text
from meshterm.ui.qr import qr_text
_ANSI = re.compile(r"\x1b\[[0-9;]*m")
@@ -212,7 +212,7 @@ class _ScriptedUi:
"""A UI surface that replays queued answers, for driving the channel manager headless.
``select``/``text``/``confirm`` each pop their next scripted answer; the display methods
are no-ops. Enough of the :class:`~meshtools.ui.surface.Ui` contract for the channel
are no-ops. Enough of the :class:`~meshterm.ui.surface.Ui` contract for the channel
manager's create/clear flows.
"""
@@ -249,10 +249,10 @@ async def test_recreating_a_slot_refiles_messages_to_the_new_channel(ctx: AppCon
opening the old channel showed the new one's transcript. The manager must refresh the
cache after the mutation so a message on the reused slot lands in the right channel.
"""
from meshtools.core.channels import channel_identity
from meshtools.core.events import MeshEvent
from meshtools.core.models import Message
from meshtools.ui.channels import _BACK, _CLEAR, _CREATE, manage_channels
from meshterm.core.channels import channel_identity
from meshterm.core.events import MeshEvent
from meshterm.core.models import Message
from meshterm.ui.channels import _BACK, _CLEAR, _CREATE, manage_channels
device = await ctx.device()
await device.set_channel(0, "Public", DEFAULT_PUBLIC_SECRET)
+25 -25
View File
@@ -20,22 +20,22 @@ def _strip_ansi(text: str) -> str:
"""Remove ANSI color escapes from rendered lines for plain-text assertions."""
return _ANSI.sub("", text)
from meshtools.core.channels import DEFAULT_PUBLIC_SECRET, derive_secret
from meshtools.core.connection import MockDevice
from meshtools.core.events import MeshEvent
from meshtools.core.models import (
from meshterm.core.channels import DEFAULT_PUBLIC_SECRET, derive_secret
from meshterm.core.connection import MockDevice
from meshterm.core.events import MeshEvent
from meshterm.core.models import (
ChatMessage,
Contact,
Conversation,
Message,
conversation_key,
)
from meshtools.persistence.repository import Repository
from meshtools.services.chat_service import ChatService
from meshtools.services.event_hub import EventHub
from meshtools.tools.chat import _LiveLasts, _preview, _title
from meshtools.ui.chat import ChatScreen
from meshtools.ui.tui.screen import CANCEL
from meshterm.persistence.repository import Repository
from meshterm.services.chat_service import ChatService
from meshterm.services.event_hub import EventHub
from meshterm.tools.chat import _LiveLasts, _preview, _title
from meshterm.ui.chat import ChatScreen
from meshterm.ui.tui.screen import CANCEL
class _StubSession:
@@ -49,7 +49,7 @@ class _StubSession:
class _StubContext:
"""Minimal :class:`~meshtools.context.AppContext` stand-in for chat tests."""
"""Minimal :class:`~meshterm.context.AppContext` stand-in for chat tests."""
def __init__(self, device: MockDevice, repo: Repository) -> None:
self._device = device
@@ -123,7 +123,7 @@ async def test_message_pump_drains_until_empty() -> None:
"""
from meshcore import EventType
from meshtools.core.connection import MeshCoreDevice
from meshterm.core.connection import MeshCoreDevice
class _Ev:
def __init__(self, t) -> None: # noqa: ANN001
@@ -374,7 +374,7 @@ async def test_service_files_channel_message_by_current_slot_occupant(repo: Repo
must not misroute later messages: resolution reads the slot fresh, so a message on slot 0
lands in whatever channel occupies slot 0 at that moment — never a stale cached identity.
"""
from meshtools.core.channels import channel_identity
from meshterm.core.channels import channel_identity
device = MockDevice()
ctx = _StubContext(device, repo)
@@ -417,7 +417,7 @@ async def test_service_records_channel_messages_in_arrival_order(repo: Repositor
Each channel message resolves its identity with a device read; the serial inbound worker
guarantees they still land in the transcript (ordered by insertion) in the order received.
"""
from meshtools.core.channels import channel_identity
from meshterm.core.channels import channel_identity
device = MockDevice()
ctx = _StubContext(device, repo)
@@ -507,7 +507,7 @@ def test_byte_counter_shows_used_over_limit_and_colors_only_used() -> None:
def test_byte_style_escalates_as_budget_runs_out() -> None:
"""The used-byte color steps green → yellow → orange → red as fewer bytes remain."""
from meshtools.ui.chat import _BYTES_ORANGE, _BYTES_YELLOW
from meshterm.ui.chat import _BYTES_ORANGE, _BYTES_YELLOW
style = ChatScreen._byte_style
assert style(80) == "ok" # plenty left → green
@@ -519,7 +519,7 @@ def test_byte_style_escalates_as_budget_runs_out() -> None:
def test_channel_byte_limit_is_lower_than_direct() -> None:
"""A channel broadcast has a tighter byte budget than a direct message."""
from meshtools.ui.chat import _CHANNEL_BYTE_LIMIT, _DM_BYTE_LIMIT
from meshterm.ui.chat import _CHANNEL_BYTE_LIMIT, _DM_BYTE_LIMIT
direct = _screen(_StubSession(), send=None)
channel = _channel_screen([])
@@ -633,7 +633,7 @@ def test_chat_screen_scroll_detaches_and_end_reattaches() -> None:
def test_split_channel_sender_extracts_name_prefix() -> None:
"""A ``Name: message`` channel line splits into sender and cleaned body."""
from meshtools.ui.chat import _split_channel_sender
from meshterm.ui.chat import _split_channel_sender
assert _split_channel_sender("Alice: hey there") == ("Alice", "hey there")
assert _split_channel_sender("Yagi Repeater: online") == ("Yagi Repeater", "online")
@@ -679,7 +679,7 @@ def test_channel_self_style_keyed_on_concept_not_label() -> None:
A remote sender who happens to be named 'you' must still get a palette hue, never the
white style reserved for us.
"""
from meshtools.ui.chat import _SENDER_COLORS
from meshterm.ui.chat import _SENDER_COLORS
screen = _channel_screen([])
assert screen._sender_style("you", is_self=True) == "you" # us → white
@@ -844,13 +844,13 @@ async def test_open_chat_sends_through_real_session(tmp_path: Path) -> None:
from prompt_toolkit.output import DummyOutput
from rich.console import Console
from meshtools.context import AppContext
from meshtools.core.admin_store import AdminStore
from meshtools.core.config import Settings
from meshtools.core.device_store import DeviceStore
from meshtools.ui.chat import open_chat
from meshtools.ui.surface import TuiUi
from meshtools.ui.tui.session import TuiSession
from meshterm.context import AppContext
from meshterm.core.admin_store import AdminStore
from meshterm.core.config import Settings
from meshterm.core.device_store import DeviceStore
from meshterm.ui.chat import open_chat
from meshterm.ui.surface import TuiUi
from meshterm.ui.tui.session import TuiSession
settings = Settings(config_dir=tmp_path, db_path=tmp_path / "e2e.db")
ctx = AppContext(
+1 -1
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
from pathlib import Path
from meshtools.core.config import Settings
from meshterm.core.config import Settings
def test_connect_on_start_defaults_true() -> None:
+1 -1
View File
@@ -13,7 +13,7 @@ import asyncio
import pytest
from meshtools.core.connection import DeviceCommandError, MeshCoreDevice
from meshterm.core.connection import DeviceCommandError, MeshCoreDevice
class _Event:
+7 -7
View File
@@ -10,9 +10,9 @@ from pathlib import Path
import pytest
import typer
from meshtools.core.config_io import backup_config, plan_restore, read_backup
from meshtools.core.connection import MockDevice
from meshtools.core.device_config import (
from meshterm.core.config_io import backup_config, plan_restore, read_backup
from meshterm.core.connection import MockDevice
from meshterm.core.device_config import (
RADIO_PRESETS,
DeviceConfigError,
build_snapshot,
@@ -20,7 +20,7 @@ from meshtools.core.device_config import (
get_spec,
parse_value,
)
from meshtools.tools.config import _require_yes
from meshterm.tools.config import _require_yes
async def _connected_mock() -> MockDevice:
@@ -71,7 +71,7 @@ def test_path_hash_mode_is_strict_enum() -> None:
def test_highlighted_hash_highlights_path_hash_prefix() -> None:
"""The full key is shown with only its path-hash prefix bytes highlighted."""
from meshtools.ui.widgets import highlighted_hash
from meshterm.ui.widgets import highlighted_hash
pub = "aabbccddee" + "00" * 27
# mode 2 => 3-byte hashes => first 6 hex chars are the addressable prefix.
@@ -84,8 +84,8 @@ def test_highlighted_hash_highlights_path_hash_prefix() -> None:
def test_nodes_table_lists_us_first_with_full_keys() -> None:
"""The nodes table puts our node first (name highlighted) with full keys."""
from meshtools.core.models import Contact
from meshtools.ui.widgets import nodes_table
from meshterm.core.models import Contact
from meshterm.ui.widgets import nodes_table
contacts = [Contact(name="Alice", public_key="3d63c6" + "00" * 29, key_prefix="3d63c6")]
table = nodes_table("Homestead", "aabbcc" + "00" * 29, contacts, prefix_bytes=3)
+5 -5
View File
@@ -12,10 +12,10 @@ from typing import Optional
import pytest
from meshtools.core.config import DeviceProfile
from meshtools.core.device_store import DeviceStore
from meshtools.core.discovery import DiscoveredDevice, discover_devices
from meshtools.core.selection import DeviceSelectionError, resolve_device
from meshterm.core.config import DeviceProfile
from meshterm.core.device_store import DeviceStore
from meshterm.core.discovery import DiscoveredDevice, discover_devices
from meshterm.core.selection import DeviceSelectionError, resolve_device
@dataclass
@@ -208,7 +208,7 @@ def test_resolve_no_devices_raises() -> None:
def _remember(device: DiscoveredDevice):
"""Build a RememberedDevice for ``device`` without touching disk."""
from meshtools.core.device_store import RememberedDevice
from meshterm.core.device_store import RememberedDevice
return RememberedDevice(
stable_id=device.stable_id, port=device.port, label=device.label, last_connected=""
+6 -6
View File
@@ -8,17 +8,17 @@ from __future__ import annotations
import asyncio
import logging
from meshtools.core.connection import (
from meshterm.core.connection import (
_MOCK_MONITOR_INTERVAL_S as _MOCK_INTERVAL,
)
from meshtools.core.connection import MockDevice
from meshtools.core.events import EventKind, MeshEvent
from meshtools.core.models import Observation
from meshtools.services.event_hub import EventHub
from meshterm.core.connection import MockDevice
from meshterm.core.events import EventKind, MeshEvent
from meshterm.core.models import Observation
from meshterm.services.event_hub import EventHub
class _StubContext:
"""Minimal stand-in for :class:`~meshtools.context.AppContext` for hub tests."""
"""Minimal stand-in for :class:`~meshterm.context.AppContext` for hub tests."""
def __init__(self, device: MockDevice) -> None:
self._device = device
+2 -2
View File
@@ -8,8 +8,8 @@ from __future__ import annotations
import pytest
from meshtools.services import link_budget
from meshtools.services.link_budget import RadioConfig
from meshterm.services import link_budget
from meshterm.services.link_budget import RadioConfig
def test_symbol_time_and_low_data_rate() -> None:
+2 -2
View File
@@ -4,8 +4,8 @@ from __future__ import annotations
from datetime import timedelta
from meshtools.core.models import Hop, TraceResult, utcnow
from meshtools.services import link_quality
from meshterm.core.models import Hop, TraceResult, utcnow
from meshterm.services import link_quality
_NOW = utcnow()
+28 -28
View File
@@ -15,15 +15,15 @@ from pathlib import Path
import pytest
from rich.console import Console
from meshtools.core.geo import BBox, Viewport, haversine_km, lonlat_to_world, world_to_lonlat
from meshtools.core.models import (
from meshterm.core.geo import BBox, Viewport, haversine_km, lonlat_to_world, world_to_lonlat
from meshterm.core.models import (
NODE_TYPE_REPEATER,
Observation,
utcnow,
)
from meshtools.core.mvt import GEOM_LINE, GEOM_POLYGON, decode_tile
from meshtools.tools.map import MapTool
from meshtools.ui.mapcanvas import MapCanvas, parse_hex
from meshterm.core.mvt import GEOM_LINE, GEOM_POLYGON, decode_tile
from meshterm.tools.map import MapTool
from meshterm.ui.mapcanvas import MapCanvas, parse_hex
_FIXTURE = Path(__file__).parent / "fixtures" / "tile_14_4843_5861.mvt"
_ANSI = re.compile(r"\x1b\[[0-9;]*m")
@@ -187,7 +187,7 @@ def test_parse_hex() -> None:
def test_render_map_draws_basemap_streets_and_labels() -> None:
"""Rendering the real fixture yields braille geometry and a place label."""
from meshtools.ui.map_render import MapMarker, render_map
from meshterm.ui.map_render import MapMarker, render_map
vp = Viewport(45.5019, -73.5674, 14, 180, 120)
layers = decode_tile(_FIXTURE.read_bytes())
@@ -201,7 +201,7 @@ def test_render_map_draws_basemap_streets_and_labels() -> None:
def test_render_map_prioritises_repeater_glyph() -> None:
"""A repeater and a node at the same spot resolve to the repeater's marker on top."""
from meshtools.ui.map_render import MapMarker, render_map
from meshterm.ui.map_render import MapMarker, render_map
vp = Viewport(45.50, -73.57, 14, 60, 40)
markers = [
@@ -214,7 +214,7 @@ def test_render_map_prioritises_repeater_glyph() -> None:
def test_render_map_drops_crowded_labels_favouring_repeaters() -> None:
"""When labels can't all fit, the repeater's wins and a crowded node's is dropped."""
from meshtools.ui.map_render import MapMarker, render_map
from meshterm.ui.map_render import MapMarker, render_map
# Three nodes stacked on one spot: only the two sides (left/right) can hold a label,
# so one of the three must show as a bare marker — and the repeater must not be it.
@@ -242,7 +242,7 @@ 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 meshtools.ui.map_render import _NODE, MapMarker, render_map
from meshterm.ui.map_render import _NODE, MapMarker, render_map
base = parse_hex(_NODE[1])
vp = Viewport(45.50, -73.57, 14, 60, 40)
@@ -259,7 +259,7 @@ def test_render_map_brightens_piled_markers() -> None:
def test_render_map_works_without_basemap() -> None:
"""With no tiles the nodes still render on a blank grid (the offline fallback)."""
from meshtools.ui.map_render import MapMarker, render_map
from meshterm.ui.map_render import MapMarker, render_map
vp = Viewport.fit([(45.5, -73.6), (45.4, -73.5)], 120, 80, max_zoom=14)
markers = [
@@ -275,7 +275,7 @@ def test_render_map_works_without_basemap() -> None:
def test_basemap_source_offline_is_graceful(tmp_path: Path) -> None:
"""An unreachable source reports unavailable and returns no tiles, never raising."""
from meshtools.services.basemap import BasemapSource
from meshterm.services.basemap import BasemapSource
src = BasemapSource(tmp_path / "cache", tilejson_url="http://127.0.0.1:1/none", timeout=0.2)
assert src.available is False
@@ -285,7 +285,7 @@ def test_basemap_source_offline_is_graceful(tmp_path: Path) -> None:
def test_basemap_source_reads_cached_tile(tmp_path: Path) -> None:
"""A tile already on disk is decoded without any network access."""
from meshtools.services.basemap import BasemapSource
from meshterm.services.basemap import BasemapSource
cache = tmp_path / "cache"
dest = cache / "tiles" / "14" / "4843"
@@ -303,12 +303,12 @@ def test_basemap_source_reads_cached_tile(tmp_path: Path) -> None:
@pytest.fixture()
def ctx(tmp_path: Path):
"""A mock-backed application context with the plain (console) UI surface."""
from meshtools.context import AppContext
from meshtools.core.admin_store import AdminStore
from meshtools.core.config import Settings
from meshtools.core.device_store import DeviceStore
from meshtools.persistence.repository import Repository
from meshtools.ui.theme import MESH_THEME
from meshterm.context import AppContext
from meshterm.core.admin_store import AdminStore
from meshterm.core.config import Settings
from meshterm.core.device_store import DeviceStore
from meshterm.persistence.repository import Repository
from meshterm.ui.theme import MESH_THEME
settings = Settings(config_dir=tmp_path, db_path=tmp_path / "map.db")
context = AppContext(
@@ -396,9 +396,9 @@ class _StubSource:
def test_map_screen_renders_pans_zooms_and_resets() -> None:
"""The interactive screen fills its body, and wasd/zoom/reset move the viewport."""
from meshtools.core.geo import Viewport
from meshtools.ui.map_render import MapMarker
from meshtools.ui.map_screen import MapScreen
from meshterm.core.geo import Viewport
from meshterm.ui.map_render import MapMarker
from meshterm.ui.map_screen import MapScreen
session = _StubSession(80, 24)
markers = [
@@ -434,9 +434,9 @@ def test_map_screen_renders_pans_zooms_and_resets() -> None:
def test_map_screen_shift_pans_by_a_single_cell() -> None:
"""Holding Shift (Shift+arrow, or uppercase WASD) pans finely, by one character cell."""
from meshtools.core.geo import lonlat_to_world, world_to_lonlat
from meshtools.ui.map_render import MapMarker
from meshtools.ui.map_screen import MapScreen
from meshterm.core.geo import lonlat_to_world, world_to_lonlat
from meshterm.ui.map_render import MapMarker
from meshterm.ui.map_screen import MapScreen
markers = [MapMarker("A", 45.50, -73.60), MapMarker("B", 45.40, -73.50)]
screen = MapScreen(_StubSession(80, 24), markers, _StubSource(), 14)
@@ -465,8 +465,8 @@ def test_map_screen_shift_pans_by_a_single_cell() -> None:
def test_map_screen_restores_and_persists_view() -> None:
"""The screen reopens on a saved view and reports every centre/zoom change."""
from meshtools.ui.map_render import MapMarker
from meshtools.ui.map_screen import MapScreen
from meshterm.ui.map_render import MapMarker
from meshterm.ui.map_screen import MapScreen
saved: list[tuple[float, float, int]] = []
markers = [MapMarker("A", 45.50, -73.60), MapMarker("B", 45.40, -73.50)]
@@ -497,8 +497,8 @@ def test_map_screen_escape_dismisses() -> None:
"""Esc resolves the screen's future with None (backs out to the menu)."""
import asyncio
from meshtools.ui.map_render import MapMarker
from meshtools.ui.map_screen import MapScreen
from meshterm.ui.map_render import MapMarker
from meshterm.ui.map_screen import MapScreen
screen = MapScreen(_StubSession(80, 24), [MapMarker("A", 45.5, -73.6)], _StubSource(), 14)
+8 -8
View File
@@ -13,23 +13,23 @@ from pathlib import Path
import pytest
from meshtools.core.connection import (
from meshterm.core.connection import (
_MOCK_MONITOR_INTERVAL_S as _MOCK_INTERVAL,
)
from meshtools.core.connection import (
from meshterm.core.connection import (
MockDevice,
ack_from_event,
message_from_event,
observation_from_event,
)
from meshtools.core.models import HeardNode, Observation, utcnow
from meshtools.core.monitor_store import MonitorStore
from meshtools.persistence.repository import Repository
from meshtools.services.monitor_service import MonitorService
from meshterm.core.models import HeardNode, Observation, utcnow
from meshterm.core.monitor_store import MonitorStore
from meshterm.persistence.repository import Repository
from meshterm.services.monitor_service import MonitorService
class _StubContext:
"""Minimal stand-in for :class:`~meshtools.context.AppContext` for service tests."""
"""Minimal stand-in for :class:`~meshterm.context.AppContext` for service tests."""
def __init__(self, repo: Repository, device: MockDevice) -> None:
self.repo = repo
@@ -45,7 +45,7 @@ class _StubContext:
@property
def events(self):
"""Lazily build a real event hub bound to this stub context (as AppContext does)."""
from meshtools.services.event_hub import EventHub
from meshterm.services.event_hub import EventHub
if self._events is None:
self._events = EventHub(self)
+2 -2
View File
@@ -7,8 +7,8 @@ from pathlib import Path
import pytest
from meshtools.core.models import Hop, TraceResult
from meshtools.persistence.repository import Repository
from meshterm.core.models import Hop, TraceResult
from meshterm.persistence.repository import Repository
@pytest.fixture()
+12 -12
View File
@@ -5,9 +5,9 @@ from __future__ import annotations
import math
from pathlib import Path
from meshtools.core.models import Hop, TraceResult
from meshtools.services import route_stability
from meshtools.services.route_stability import RouteGraph
from meshterm.core.models import Hop, TraceResult
from meshterm.services import route_stability
from meshterm.services.route_stability import RouteGraph
def _trace(*nodes: str, snr: float = 5.0) -> TraceResult:
@@ -200,7 +200,7 @@ def test_multi_target_graph_without_target() -> None:
def test_render_route_graph_writes_html(tmp_path: Path) -> None:
"""The pyvis renderer produces a self-contained HTML file."""
from meshtools.viz.route_graph import render_route_graph
from meshterm.viz.route_graph import render_route_graph
traces = [_trace("3d", "f2") for _ in range(3)] + [_trace("aa", "f2")]
graph = route_stability.build_route_graph(traces, target="f2")
@@ -214,7 +214,7 @@ def test_render_route_graph_writes_html(tmp_path: Path) -> None:
def test_render_empty_graph_writes_valid_html(tmp_path: Path) -> None:
"""An empty graph still produces a valid HTML file."""
from meshtools.viz.route_graph import render_route_graph
from meshterm.viz.route_graph import render_route_graph
graph = RouteGraph(target="nobody")
out = render_route_graph(graph, tmp_path)
@@ -225,7 +225,7 @@ def test_render_empty_graph_writes_valid_html(tmp_path: Path) -> None:
def test_render_creates_output_dir(tmp_path: Path) -> None:
"""The renderer creates the output directory if it doesn't exist."""
from meshtools.viz.route_graph import render_route_graph
from meshterm.viz.route_graph import render_route_graph
nested = tmp_path / "a" / "b"
graph = route_stability.build_route_graph([_trace("x")], target="x")
@@ -235,7 +235,7 @@ def test_render_creates_output_dir(tmp_path: Path) -> None:
def test_render_whole_mesh_filename(tmp_path: Path) -> None:
"""Whole-mesh graphs use 'mesh' in the filename, not an empty slug."""
from meshtools.viz.route_graph import render_route_graph
from meshterm.viz.route_graph import render_route_graph
graph = route_stability.build_route_graph([_trace("x")], target=None)
out = render_route_graph(graph, tmp_path)
@@ -247,7 +247,7 @@ def test_render_whole_mesh_filename(tmp_path: Path) -> None:
def test_snr_color_thresholds() -> None:
"""SNR-to-colour mapping covers all four bands."""
from meshtools.viz.route_graph import _snr_color
from meshterm.viz.route_graph import _snr_color
assert _snr_color(10.0) == "#4ade80" # strong
assert _snr_color(5.0) == "#4ade80" # boundary: strong
@@ -260,7 +260,7 @@ def test_snr_color_thresholds() -> None:
def test_slug_edge_cases() -> None:
"""Slug handles special characters and pathological inputs."""
from meshtools.viz.route_graph import _slug
from meshterm.viz.route_graph import _slug
assert _slug("Alice") == "alice"
assert _slug("my node") == "my-node"
@@ -274,7 +274,7 @@ def test_slug_edge_cases() -> None:
def test_graph_panel_with_links() -> None:
"""The Rich panel renders without error when there are links."""
from meshtools.tools.route_map import _graph_panel
from meshterm.tools.route_map import _graph_panel
traces = [_trace("relay", "dest") for _ in range(3)]
graph = route_stability.build_route_graph(traces, target="dest")
@@ -284,7 +284,7 @@ def test_graph_panel_with_links() -> None:
def test_graph_panel_empty() -> None:
"""The Rich panel renders without error on an empty graph."""
from meshtools.tools.route_map import _graph_panel
from meshterm.tools.route_map import _graph_panel
graph = RouteGraph(target="nobody")
panel = _graph_panel(graph)
@@ -293,7 +293,7 @@ def test_graph_panel_empty() -> None:
def test_is_nonneg_int_validator() -> None:
"""The questionary validator accepts zero/positive and rejects negative/non-int."""
from meshtools.tools.route_map import _is_nonneg_int
from meshterm.tools.route_map import _is_nonneg_int
assert _is_nonneg_int("0") is True
assert _is_nonneg_int("5") is True
+32 -32
View File
@@ -9,10 +9,10 @@ from pathlib import Path
import pytest
from meshtools.core.connection import DeviceCommandError, MockDevice, clamp_tx_power
from meshtools.core.models import Contact, TraceResult, TraceStats
from meshtools.persistence.repository import Repository
from meshtools.services import trace_runner
from meshterm.core.connection import DeviceCommandError, MockDevice, clamp_tx_power
from meshterm.core.models import Contact, TraceResult, TraceStats
from meshterm.persistence.repository import Repository
from meshterm.services import trace_runner
def test_clamp_tx_power() -> None:
@@ -24,7 +24,7 @@ def test_clamp_tx_power() -> None:
def test_trace_stats_aggregation() -> None:
"""Robust stats reflect successes and bottleneck SNR."""
from meshtools.core.models import Hop
from meshterm.core.models import Hop
traces = [
TraceResult(target="x", success=True, hops=[Hop(0, "a", 5.0), Hop(1, "b", -2.0)]),
@@ -73,7 +73,7 @@ def test_path_hash_flags_power_of_two_only() -> None:
def test_parse_trace_hops_reads_path_snr() -> None:
"""Per-hop SNR comes from payload['path'] dicts; the final hash-less node counts."""
from meshtools.core.connection import parse_trace_hops
from meshterm.core.connection import parse_trace_hops
payload = {
"path": [
@@ -90,15 +90,15 @@ def test_parse_trace_hops_reads_path_snr() -> None:
def test_parse_trace_hops_empty_without_path() -> None:
"""A reply with no parsed path yields no hops (SNR shows as n/a)."""
from meshtools.core.connection import parse_trace_hops
from meshterm.core.connection import parse_trace_hops
assert parse_trace_hops({}) == []
def test_route_text_annotates_nodes_with_command_width_hash() -> None:
"""The route shows each node's hash at the command's path-hash width."""
from meshtools.core.models import Hop
from meshtools.ui.widgets import _route_text
from meshterm.core.models import Hop
from meshterm.ui.widgets import _route_text
resolve = trace_runner.make_node_resolver(
[Contact(name="Alice", public_key="3d63c6" + "00" * 26, key_prefix="3d63c6429436")]
@@ -120,8 +120,8 @@ def test_route_text_annotates_nodes_with_command_width_hash() -> None:
def test_route_text_annotates_our_device_with_hash() -> None:
"""Given our key, both endpoints (us) carry our hash at the command width."""
from meshtools.core.models import Hop
from meshtools.ui.widgets import _route_text
from meshterm.core.models import Hop
from meshterm.ui.widgets import _route_text
result = TraceResult(
target="x",
@@ -138,8 +138,8 @@ def test_route_text_annotates_our_device_with_hash() -> None:
def test_traces_table_annotates_links_with_hashes() -> None:
"""The per-trace From→To column shows ``name (hash)``, including our device."""
from meshtools.core.models import Hop
from meshtools.ui.widgets import traces_table
from meshterm.core.models import Hop
from meshterm.ui.widgets import traces_table
resolve = trace_runner.make_node_resolver(
[Contact(name="Alice", public_key="3d63c6" + "00" * 26, key_prefix="3d63c6429436")]
@@ -161,8 +161,8 @@ def test_traces_table_annotates_links_with_hashes() -> None:
def test_route_text_unknown_node_shows_hash_only() -> None:
"""An unresolved node shows just its hash, truncated to the command width."""
from meshtools.core.models import Hop
from meshtools.ui.widgets import _route_text
from meshterm.core.models import Hop
from meshterm.ui.widgets import _route_text
result = TraceResult(
target="x",
@@ -204,7 +204,7 @@ async def test_mock_device_blank_path_traces() -> None:
def test_trace_edges_endpoints_are_our_device() -> None:
"""The first edge originates at us and the last edge returns to us (#3/#4)."""
from meshtools.core.models import Hop
from meshterm.core.models import Hop
result = TraceResult(
target="Alice",
@@ -222,7 +222,7 @@ def test_trace_edges_endpoints_are_our_device() -> None:
def test_trace_stats_reports_per_hop_medians() -> None:
"""Aggregation yields a median SNR for every hop position (#5)."""
from meshtools.core.models import Hop
from meshterm.core.models import Hop
traces = [
TraceResult(target="x", success=True, hops=[Hop(0, "a", 4.0), Hop(1, None, 0.0)]),
@@ -283,7 +283,7 @@ async def test_admin_login_rejects_wrong_password() -> None:
async def test_tx_optimizer_finds_simulator_peak(tmp_path: Path) -> None:
"""The optimizer converges near the simulated remote optimum and applies it."""
from meshtools.services import tx_optimizer
from meshterm.services import tx_optimizer
device, admin, target, path = await _setup_link(optimal_remote_tx=20)
@@ -300,7 +300,7 @@ async def test_tx_optimizer_finds_simulator_peak(tmp_path: Path) -> None:
async def test_tx_optimizer_no_apply_restores_original(tmp_path: Path) -> None:
"""With apply off, the node is left at the power it started with."""
from meshtools.services import tx_optimizer
from meshterm.services import tx_optimizer
device, admin, target, path = await _setup_link()
await device.set_remote_tx_power(admin, 15) # a known starting power
@@ -317,8 +317,8 @@ async def test_tx_optimizer_no_apply_restores_original(tmp_path: Path) -> None:
def test_select_best_prefers_reliability_then_lowest_power() -> None:
"""A 100%-reliable level beats a flakier higher-SNR one; ties go to lower TX."""
from meshtools.core.models import TraceStats, TxLevelResult
from meshtools.services.tx_optimizer import select_best
from meshterm.core.models import TraceStats, TxLevelResult
from meshterm.services.tx_optimizer import select_best
def level(tx: int, snr: float, successes: int, samples: int = 5) -> TxLevelResult:
return TxLevelResult(
@@ -340,7 +340,7 @@ def test_select_best_prefers_reliability_then_lowest_power() -> None:
def test_round_trip_path_mirrors_back_to_a_reachable_node() -> None:
"""The trace path goes out to the target and back, so a near node answers."""
from meshtools.services.tx_optimizer import _round_trip_path
from meshterm.services.tx_optimizer import _round_trip_path
assert _round_trip_path(["3f", "f2"]) == "3f,f2,3f"
assert _round_trip_path(["3d", "3f", "f2"]) == "3d,3f,f2,3f,3d"
@@ -349,8 +349,8 @@ def test_round_trip_path_mirrors_back_to_a_reachable_node() -> None:
def test_trace_target_snr_matches_target_hop_not_position() -> None:
"""The target's SNR is read from its hash, even when it's the turn-around hop."""
from meshtools.core.models import Hop
from meshtools.services.tx_optimizer import trace_target_snr
from meshterm.core.models import Hop
from meshterm.services.tx_optimizer import trace_target_snr
# Round trip 3f -> f2 -> 3f -> us: the f2 hop (index 1) is what we want, not the
# later 3f hop or the hash-less return hop.
@@ -366,8 +366,8 @@ def test_tx_plot_writes_html(tmp_path: Path) -> None:
"""The Plotly renderer produces a self-contained HTML file."""
import asyncio
from meshtools.services import tx_optimizer
from meshtools.viz.tx_plot import render_tx_optimization
from meshterm.services import tx_optimizer
from meshterm.viz.tx_plot import render_tx_optimization
async def _build():
device, admin, target, path = await _setup_link()
@@ -415,7 +415,7 @@ async def test_three_byte_route_appends_destination_hash() -> None:
width), and the destination's own hash is appended as the final hop — a trace
only replies when its destination is the last hop.
"""
from meshtools.core.connection import MeshCoreDevice
from meshterm.core.connection import MeshCoreDevice
mc = _mc_with(
{
@@ -447,7 +447,7 @@ async def test_direct_neighbor_resolves_to_destination_hash() -> None:
contact's mode unknown (-1) the region's path-hash mode (3-byte) sets the width,
collapsed to the representable 2 bytes.
"""
from meshtools.core.connection import MeshCoreDevice
from meshterm.core.connection import MeshCoreDevice
mc = _mc_with(
{
@@ -474,7 +474,7 @@ async def test_direct_neighbor_resolves_to_destination_hash() -> None:
async def test_unknown_contact_resolves_to_none() -> None:
"""An unrecognized target yields ``None`` so the trace can fall back to path-less."""
from meshtools.core.connection import MeshCoreDevice
from meshterm.core.connection import MeshCoreDevice
mc = _mc_with(
{
@@ -495,7 +495,7 @@ async def test_unknown_contact_resolves_to_none() -> None:
async def test_contacts_payload_retries_transient_error() -> None:
"""A transient 'no event received' on contacts retrieval is retried, not fatal."""
from meshtools.core.connection import MeshCoreDevice
from meshterm.core.connection import MeshCoreDevice
calls = {"n": 0}
@@ -527,7 +527,7 @@ async def test_contacts_payload_retries_transient_error() -> None:
async def test_contacts_payload_raises_clean_error_after_retries() -> None:
"""Persistent contacts-retrieval failure raises a clean, actionable error."""
from meshtools.core.connection import DeviceCommandError, MeshCoreDevice
from meshterm.core.connection import DeviceCommandError, MeshCoreDevice
class _Err:
payload = {"reason": "no event received during contacts retrieval"}
@@ -550,7 +550,7 @@ async def test_contacts_payload_raises_clean_error_after_retries() -> None:
async def test_latest_trace_returns_previous_run(tmp_path: Path) -> None:
"""latest_trace rehydrates the most recent stored trace, excluding a given run."""
from meshtools.core.models import Hop
from meshterm.core.models import Hop
repo = Repository(tmp_path / "prev.db")
old_run = repo.start_run("trace", {"target": "Alice"})
+8 -8
View File
@@ -1,4 +1,4 @@
"""Unit tests for the reusable text-UI library (``meshtools.ui.tui``).
"""Unit tests for the reusable text-UI library (``meshterm.ui.tui``).
These exercise the pure logic — ANSI rendering/slicing, selection filtering and navigation,
scroll math, the frame composition's terminal-fit guarantee, prompt editing/validation, and
@@ -15,13 +15,13 @@ from prompt_toolkit.output import DummyOutput
from rich.table import Table
from rich.text import Text
from meshtools.ui.tui import frame
from meshtools.ui.tui.progress import ProgressScreen
from meshtools.ui.tui.prompt import AutocompleteScreen, ConfirmScreen, TextScreen
from meshtools.ui.tui.render import render_lines, render_to_ansi
from meshtools.ui.tui.screen import CANCEL, ScrollScreen
from meshtools.ui.tui.select import Choice, SelectScreen, Separator
from meshtools.ui.tui.session import TuiSession
from meshterm.ui.tui import frame
from meshterm.ui.tui.progress import ProgressScreen
from meshterm.ui.tui.prompt import AutocompleteScreen, ConfirmScreen, TextScreen
from meshterm.ui.tui.render import render_lines, render_to_ansi
from meshterm.ui.tui.screen import CANCEL, ScrollScreen
from meshterm.ui.tui.select import Choice, SelectScreen, Separator
from meshterm.ui.tui.session import TuiSession
_UNSET = object()