From f27492b2e4c7e0569b86b66b783b0060a39468a1 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Fri, 11 Sep 2026 03:23:21 -0400 Subject: [PATCH] Device config carries the device actions and every setting the firmware has The Device actions menu entry is gone: clock sync, backup/restore, the identity key, reboot and factory reset are an Actions section on the Device config page, which now takes the repeater admin page's shape. It is full-screen, titled with the node's name and a staged count, and Apply sends in place, one value at a time; a value the device refuses stays staged with its reason. Read settings re-reads the device, and unread and blank values read ? and empty. The settings were checked against the companion firmware (MyMesh.cpp). New: client repeat, the radio command's trailing byte. Every radio edit now restates it, because the firmware reads a missing byte as off and a retune silently stopped a relaying companion. Also new: the auto-add hop limit, read off the raw frame the library half-parses, and a row for each custom variable the device reports. The firmware's own bounds now apply: a PIN of 0 or six digits, path-hash modes 0-2, telemetry deny / by contact / allow all, 150-2500 MHz, 7-500 kHz, and TX power from -9 dBm. Neither editor page slides its rows sideways any more. The Actions rows pin a head block, which on its own turned on horizontal scrolling for repeater admin's whole list and slid its setting labels out of view. SelectScreen(hscroll=False) now holds against the rows, and both pages use it, so long rows end at the edge the way Device config's always did. Co-Authored-By: Claude Opus 5 (1M context) --- README.md | 3 +- meshterm/core/connection.py | 179 ++++++++++- meshterm/core/device_config.py | 141 ++++++++- meshterm/tools/advert.py | 4 +- meshterm/tools/config.py | 40 +-- meshterm/tools/device_actions.py | 72 ----- meshterm/tools/repeater_admin.py | 2 +- meshterm/ui/channels.py | 2 +- meshterm/ui/config_editor.py | 502 ++++++++++++++++++++++--------- meshterm/ui/menus.py | 6 +- meshterm/ui/repeater_admin.py | 13 + meshterm/ui/theme.py | 1 - meshterm/ui/tui/select.py | 24 +- tests/test_config_editor.py | 311 +++++++++++++++---- tests/test_device_config.py | 23 +- tests/test_menus.py | 2 +- tests/test_paired_settings.py | 141 ++++++++- tests/test_repeater_admin.py | 14 + tests/test_tui.py | 20 ++ 19 files changed, 1170 insertions(+), 330 deletions(-) delete mode 100644 meshterm/tools/device_actions.py diff --git a/README.md b/README.md index dfd942f..0c9c1a7 100644 --- a/README.md +++ b/README.md @@ -225,8 +225,7 @@ here with its scripted equivalent, where one exists. | Feature | What it does | Scripted | | --- | --- | --- | | **πŸ“‹ Device info** | The connected companion's identity and full radio configuration at a glance. | `meshterm info` | -| **πŸ”§ Device config** | View and *stage* changes to every setting (name, radio, behaviour, experimental) for review before applying, with TOML backup/restore. | `meshterm config` / `config set ` | -| **πŸ”¨ Device actions** | Immediate operations on the box itself: clock sync, TOML backup/restore, the identity key, reboot, and factory reset β€” each acting the moment it's confirmed, with destructive ops gated. | `config backup` / `restore` / `reboot` / … | +| **πŸ”§ Device config** | Every setting the companion firmware exposes β€” name, radio, client repeat, auto-add, telemetry, custom variables β€” *staged* for review and applied in place, plus the operations on the box itself: clock sync, TOML backup/restore, the identity key, reboot, and factory reset, each acting the moment it's confirmed, with destructive ops gated. Laid out like Repeater admin, so the radio in your hand and one over the mesh are configured the same way. | `meshterm config` / `config set ` / `config backup` / `reboot` / … | | **πŸ“‘ Send advert** | Announce this node to the mesh β€” a zero-hop or flood advertisement, or share this node's contact card as a QR code. | `meshterm config advert` / `config share` | | **πŸ”Œ Device discovery** | Enumerate serial *and* Bluetooth LE companions, pick one interactively (or auto-select the only one present), add a network (TCP) companion by host:port, and remember the last good default. A dropped link is detected live and offers to reconnect. | `meshterm devices` | diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py index 420cb31..de42521 100644 --- a/meshterm/core/connection.py +++ b/meshterm/core/connection.py @@ -18,7 +18,7 @@ import logging import random import sys from abc import ABC, abstractmethod -from collections.abc import Callable +from collections.abc import Callable, Iterable from dataclasses import replace from datetime import datetime, timedelta, timezone from typing import TYPE_CHECKING @@ -210,6 +210,41 @@ class DeviceAuthenticationError(DeviceCommandError): #: ``ERR_CODE_NOT_FOUND`` β€” the companion has no entry matching what a command addressed. _ERR_NOT_FOUND = 2 +#: ``CMD_SET_AUTOADD_CONFIG`` β€” the auto-add bitmask, and (as an optional second byte, which +#: the ``meshcore`` library never sends) the hop limit. +_CMD_SET_AUTOADD_CONFIG = 58 + +#: ``RESP_CODE_AUTOADD_CONFIG`` β€” the reply to a read of the auto-add configuration. Its +#: second payload byte is the hop limit, which the library's parser drops (it keeps only the +#: bitmask), so :meth:`MeshCoreDevice.get_autoadd_config` recognises the raw frame by this. +_RESP_AUTOADD_CONFIG = 25 + +#: Sentinel: no hop limit has been read alongside the last auto-add bitmask. +_UNREAD = object() + +#: The client-repeat frequencies (MHz) the companion firmware allows when a board defines +#: none of its own (``repeat_freq_ranges`` in MeshCore's ``examples/companion_radio/MyMesh.cpp``). +_DEFAULT_REPEAT_FREQS: tuple[tuple[float, float], ...] = ( + (433.0, 433.0), + (869.495, 869.495), + (918.0, 918.0), +) + +#: How far a radio frequency may sit from an allowed repeat range and still be inside it +#: (MHz). Frequencies travel in kHz, so half of one is the whole rounding error. +_REPEAT_FREQ_TOLERANCE_MHZ = 0.0005 + + +def repeat_freq_allowed(freq: float, ranges: Iterable[tuple[float, float]]) -> bool: + """Whether ``freq`` (MHz) lies in one of the firmware's client-repeat ``ranges``. + + The firmware's own ``isValidClientRepeatFreq``, in MHz: it refuses to turn relaying on + anywhere else. + """ + tol = _REPEAT_FREQ_TOLERANCE_MHZ + return any(low - tol <= float(freq) <= high + tol for low, high in ranges) + + #: What each companion error code means, in a sentence that finishes "the device …". #: The wire carries only the number and the library's ``ERR_CODE_*`` spelling (see #: ``meshcore.events.ErrorMessages``), which is diagnostic text, not something to put in @@ -754,6 +789,24 @@ class Device(ABC): advert types the firmware adds to contacts automatically. """ + async def get_autoadd_max_hops(self) -> int | None: + """Return the auto-add hop limit, or ``None`` where the firmware doesn't report one. + + The second byte of the firmware's auto-add configuration (``autoadd_max_hops``, + capped at 64). Not abstract: a device without the field has nothing to say, and the + snapshot leaves its row unread rather than failing. + """ + return None + + async def get_allowed_repeat_freqs(self) -> list[tuple[float, float]]: + """Return the frequency ranges (MHz, inclusive) client repeat may be enabled on. + + The firmware refuses to relay outside them (``isValidClientRepeatFreq``), so the + editor can check before staging instead of after a refusal. Empty where the firmware + doesn't say β€” which means *unknown*, not *nowhere*. + """ + return [] + @abstractmethod async def get_default_flood_scope(self) -> str | None: """Return the persisted default flood scope's name (``""`` when unset). @@ -858,7 +911,9 @@ class Device(ABC): """Set the device's BLE pairing PIN.""" @abstractmethod - async def set_radio(self, freq: float, bw: float, sf: int, cr: int) -> None: + async def set_radio( + self, freq: float, bw: float, sf: int, cr: int, repeat: bool | None = None + ) -> None: """Set the core radio parameters. Args: @@ -866,6 +921,11 @@ class Device(ABC): bw: Bandwidth in kHz. sf: Spreading factor. cr: Coding rate denominator (``5``-``8`` for 4/5-4/8). + repeat: Whether the companion relays mesh traffic (client repeat, firmware v9+). + The firmware takes it as an optional trailing byte of this same command and + reads the byte's *absence* as off β€” so a caller changing any radio field on + firmware that reports it must restate it, or the change quietly stops the + relaying. ``None`` omits the byte, for firmware that predates it. """ @abstractmethod @@ -897,8 +957,12 @@ class Device(ABC): """Set the three telemetry mode fields together (each ``0``-``3``).""" @abstractmethod - async def set_autoadd_config(self, flags: int) -> None: - """Set the contact auto-add bitmask (see :meth:`get_autoadd_config`).""" + async def set_autoadd_config(self, flags: int, max_hops: int | None = None) -> None: + """Set the contact auto-add bitmask (see :meth:`get_autoadd_config`), and its hop limit. + + The firmware reads the hop limit as an optional second byte and leaves it where it + was when that byte is absent, so ``None`` changes the bitmask alone. + """ @abstractmethod async def set_default_flood_scope(self, scope: str) -> None: @@ -1704,7 +1768,13 @@ class MeshCoreDevice(Device): async def get_self_info(self) -> dict: # noqa: D102 - inherited docstring mc = self._require() result = await mc.commands.send_appstart() - return dict(getattr(result, "payload", {}) or {}) + info = dict(getattr(result, "payload", {}) or {}) + # The firmware sends TX power as a signed byte (it accepts down to -9 dBm) and the + # library reads it unsigned, so a negative power would arrive as 247 and up. + power = info.get("tx_power") + if isinstance(power, int) and power > 127: + info["tx_power"] = power - 256 + return info async def get_device_info(self) -> dict: # noqa: D102 - inherited docstring mc = self._require() @@ -1825,7 +1895,9 @@ class MeshCoreDevice(Device): async def set_tx_power(self, value: int) -> None: # noqa: D102 - inherited docstring mc = self._require() - await mc.commands.set_tx_power(value) + # The firmware reads a signed byte; the library packs an unsigned int, which refuses a + # negative one. Two's complement is the same low byte, so -9 dBm survives the trip. + await mc.commands.set_tx_power(int(value) & 0xFFFFFFFF) @staticmethod def _node_pubkey(node: Contact) -> str: @@ -2474,12 +2546,54 @@ class MeshCoreDevice(Device): "airtime_factor": int(payload.get("airtime_factor", 0)) / 1000.0, } + #: The hop limit that arrived in the same frame as the last bitmask, until it is taken. + _autoadd_hops: object = _UNREAD + async def get_autoadd_config(self) -> int | None: # noqa: D102 - inherited docstring - event = self._ok(await self._require().commands.get_autoadd_config()) + mc = self._require() + # One reply carries the bitmask *and* the hop limit, but the library's parser keeps + # only the first. So the reader is tapped for the length of this one read β€” every + # transport hands frames to ``reader.handle_rx`` by attribute lookup, so an instance + # attribute sees them first β€” and the raw frame's second byte is kept. + reader = getattr(mc, "_reader", None) + frames: list[bytes] = [] + tapped = reader is not None and "handle_rx" not in vars(reader) + if tapped: + original = reader.handle_rx + + async def tap(data: bytearray) -> None: + if data and data[0] == _RESP_AUTOADD_CONFIG: + frames.append(bytes(data)) + await original(data) + + reader.handle_rx = tap + try: + event = self._ok(await mc.commands.get_autoadd_config()) + finally: + if tapped: + del reader.handle_rx payload = getattr(event, "payload", {}) or {} config = payload.get("config") + frame = frames[-1] if frames else b"" + self._autoadd_hops = frame[2] if len(frame) >= 3 else None return None if config is None else int(config) + async def get_autoadd_max_hops(self) -> int | None: # noqa: D102 - inherited docstring + # build_snapshot asks for the bitmask and then for this. The frame that answered the + # first question already carried the second, so it is taken rather than asked again. + if self._autoadd_hops is _UNREAD: + await self.get_autoadd_config() + hops, self._autoadd_hops = self._autoadd_hops, _UNREAD + return hops # type: ignore[return-value] + + async def get_allowed_repeat_freqs(self) -> list[tuple[float, float]]: # noqa: D102 + event = self._ok(await self._require().commands.get_allowed_repeat_freq()) + payload = getattr(event, "payload", {}) or {} + # Ranges travel in kHz, like every other frequency on this protocol. + return [ + (int(r["min"]) / 1000.0, int(r["max"]) / 1000.0) for r in payload.get("freqs") or [] + ] + async def get_default_flood_scope(self) -> str | None: # noqa: D102 event = self._ok(await self._require().commands.get_default_flood_scope()) payload = getattr(event, "payload", {}) or {} @@ -2575,8 +2689,14 @@ class MeshCoreDevice(Device): async def set_device_pin(self, pin: int) -> None: # noqa: D102 - inherited docstring self._ok(await self._require().commands.set_devicepin(pin)) - async def set_radio(self, freq: float, bw: float, sf: int, cr: int) -> None: # noqa: D102 - self._ok(await self._require().commands.set_radio(freq, bw, sf, cr)) + async def set_radio( # noqa: D102 - inherited docstring + self, freq: float, bw: float, sf: int, cr: int, repeat: bool | None = None + ) -> None: + self._ok( + await self._require().commands.set_radio( + freq, bw, sf, cr, None if repeat is None else int(bool(repeat)) + ) + ) async def set_tuning(self, rx_delay: float, airtime_factor: float) -> None: # noqa: D102 # CMD_SET_TUNING_PARAMS carries both floats Γ—1000; the firmware divides them @@ -2587,8 +2707,19 @@ class MeshCoreDevice(Device): ) ) - async def set_autoadd_config(self, flags: int) -> None: # noqa: D102 - self._ok(await self._require().commands.set_autoadd_config(int(flags))) + async def set_autoadd_config( # noqa: D102 - inherited docstring + self, flags: int, max_hops: int | None = None + ) -> None: + from meshcore import EventType + + mc = self._require() + if max_hops is None: + self._ok(await mc.commands.set_autoadd_config(int(flags))) + else: + # The library sends the bitmask alone; the hop limit is the byte after it. + frame = bytes([_CMD_SET_AUTOADD_CONFIG, int(flags) & 0xFF, min(int(max_hops), 64)]) + self._ok(await mc.commands.send(frame, [EventType.OK, EventType.ERROR])) + self._autoadd_hops = _UNREAD async def set_default_flood_scope(self, scope: str) -> None: # noqa: D102 # The library treats "", "0", "None" and "*" as "clear the scope"; normalize to @@ -2777,6 +2908,9 @@ class MockDevice(Device): } self._tuning: dict = {"rx_delay": 0.0, "airtime_factor": 0.0} self._autoadd_config = 0 + self._autoadd_max_hops = 0 + # Client repeat (firmware v9+): off, as a freshly flashed companion ships. + self._client_repeat = False self._flood_scope = "" # Simulated clock skew (seconds behind the host), so the sync-clock flow has a # visible drift to correct until set_time is called. @@ -2815,6 +2949,7 @@ class MockDevice(Device): "ver": "mock", "fw_build": "mock", "ble_pin": self._device_pin, + "repeat": self._client_repeat, } async def get_contacts(self) -> list[Contact]: # noqa: D102 - inherited docstring @@ -3051,6 +3186,12 @@ class MockDevice(Device): async def get_autoadd_config(self) -> int | None: # noqa: D102 return self._autoadd_config + async def get_autoadd_max_hops(self) -> int | None: # noqa: D102 - inherited docstring + return self._autoadd_max_hops + + async def get_allowed_repeat_freqs(self) -> list[tuple[float, float]]: # noqa: D102 + return list(_DEFAULT_REPEAT_FREQS) + async def get_default_flood_scope(self) -> str | None: # noqa: D102 return self._flood_scope @@ -3105,8 +3246,16 @@ class MockDevice(Device): async def set_device_pin(self, pin: int) -> None: # noqa: D102 - inherited docstring self._device_pin = pin - async def set_radio(self, freq: float, bw: float, sf: int, cr: int) -> None: # noqa: D102 + async def set_radio( # noqa: D102 - inherited docstring + self, freq: float, bw: float, sf: int, cr: int, repeat: bool | None = None + ) -> None: + # Modelled on the firmware: relaying is refused off the allowed frequencies, and a + # command that leaves the repeat byte off turns relaying *off* β€” the trap a radio + # change has to restate its way around. + if repeat and not repeat_freq_allowed(freq, _DEFAULT_REPEAT_FREQS): + raise DeviceCommandError("device rejected the command: illegal argument") self._info.update(radio_freq=freq, radio_bw=bw, radio_sf=sf, radio_cr=cr) + self._client_repeat = bool(repeat) async def set_tuning(self, rx_delay: float, airtime_factor: float) -> None: # noqa: D102 # Round-trip through the wire's Γ—1000 integer scaling so the simulator loses @@ -3116,8 +3265,12 @@ class MockDevice(Device): "airtime_factor": round(float(airtime_factor) * 1000) / 1000.0, } - async def set_autoadd_config(self, flags: int) -> None: # noqa: D102 + async def set_autoadd_config( # noqa: D102 - inherited docstring + self, flags: int, max_hops: int | None = None + ) -> None: self._autoadd_config = int(flags) + if max_hops is not None: # the firmware leaves the limit alone when it isn't sent + self._autoadd_max_hops = min(int(max_hops), 64) async def set_default_flood_scope(self, scope: str) -> None: # noqa: D102 # Mirror the transport layer: empty clears, a bare name gains its leading #. diff --git a/meshterm/core/device_config.py b/meshterm/core/device_config.py index 14b4a01..010503f 100644 --- a/meshterm/core/device_config.py +++ b/meshterm/core/device_config.py @@ -17,7 +17,7 @@ from collections.abc import Awaitable, Callable from dataclasses import dataclass from typing import Any -from .connection import Device +from .connection import Device, repeat_freq_allowed # Display categories, in the order the editor and `config show` present them. CATEGORIES = ("Identity", "Radio", "Tuning", "Behavior", "Experimental") @@ -53,6 +53,9 @@ class SettingSpec: the connected hardware actually supports. max_length: For ``str`` values, the longest accepted string (protocol field widths, e.g. the flood scope's 31-byte name slot). + validate: A last rule for a typed, in-range value, given the snapshot when there + is one: it returns the complaint, or ``None``. For what a bound can't state β€” + the PIN's "zero or six digits", relaying only on an allowed frequency. getter: Extracts the current value from a snapshot dict. apply: Coroutine applying a parsed value to a device, given the snapshot. """ @@ -70,6 +73,7 @@ class SettingSpec: strict_choices: bool = True max_key: str | None = None max_length: int | None = None + validate: Callable[[Any, dict | None], str | None] | None = None # --- value parsing / formatting ---------------------------------------------- @@ -92,8 +96,19 @@ def parse_value(spec: SettingSpec, raw: Any, snapshot: dict | None = None) -> An The typed, range-checked value ready for :meth:`SettingSpec.apply`. Raises: - DeviceConfigError: If the value is the wrong type or out of range. + DeviceConfigError: If the value is the wrong type, out of range, or breaks the + setting's own :attr:`~SettingSpec.validate` rule. """ + value = _parse_typed(spec, raw, snapshot) + if spec.validate is not None: + complaint = spec.validate(value, snapshot) + if complaint: + raise DeviceConfigError(f"{spec.key}: {complaint}") + return value + + +def _parse_typed(spec: SettingSpec, raw: Any, snapshot: dict | None) -> Any: + """:func:`parse_value` short of the setting's own rule: the type, bounds and choices.""" text = str(raw).strip() if spec.value_type == "str": # `config show` prints an empty string as the two characters `""`, because a key @@ -212,7 +227,9 @@ async def build_snapshot( Returns: A dict keyed like ``SELF_INFO`` plus ``rx_delay``, ``airtime_factor``, - ``path_hash_mode``, ``autoadd_config`` and ``flood_scope``. + ``path_hash_mode``, ``autoadd_config``, ``autoadd_max_hops`` and ``flood_scope``, + with the device-query frame's facts (``ble_pin``, ``model``, client ``repeat``) + underneath and, where the firmware relays at all, its ``repeat_freqs``. """ snapshot = dict(self_info if self_info is not None else await device.get_self_info()) try: @@ -230,6 +247,12 @@ async def build_snapshot( snapshot["autoadd_config"] = await device.get_autoadd_config() except Exception: # noqa: BLE001 - optional read; absence is acceptable pass + try: + hops = await device.get_autoadd_max_hops() + except Exception: # noqa: BLE001 - optional read; absence is acceptable + hops = None + if hops is not None: + snapshot["autoadd_max_hops"] = hops try: snapshot["flood_scope"] = await device.get_default_flood_scope() except Exception: # noqa: BLE001 - optional read; absence is acceptable @@ -244,6 +267,15 @@ async def build_snapshot( snapshot = {**await device.get_device_info(), **snapshot} except Exception: # noqa: BLE001 - optional read; absence is acceptable pass + # Client repeat (firmware v9+) may only be switched on where the firmware allows. The + # ranges are one more round trip, so they are asked only of firmware that can relay. + if "repeat" in snapshot: + try: + freqs = await device.get_allowed_repeat_freqs() + except Exception: # noqa: BLE001 - optional read; absence is acceptable + freqs = [] + if freqs: + snapshot["repeat_freqs"] = [tuple(pair) for pair in freqs] return snapshot @@ -273,7 +305,15 @@ def _radio_apply(field_name: str) -> Callable[[Device, Any, dict], Awaitable[Non "cr": snapshot.get("radio_cr"), } params[field_name] = value - await device.set_radio(params["freq"], params["bw"], params["sf"], params["cr"]) + # Client repeat rides the same command, and the firmware reads its absence as off: + # restate it, or retuning the radio quietly stops the node relaying. + await device.set_radio( + params["freq"], + params["bw"], + params["sf"], + params["cr"], + repeat=snapshot.get("repeat"), + ) snapshot[f"radio_{field_name}"] = value return apply @@ -317,23 +357,66 @@ def _telemetry_apply(field_name: str) -> Callable[[Device, Any, dict], Awaitable return apply +async def _client_repeat_apply(device: Device, value: Any, snapshot: dict) -> None: + """Switch client repeat, restating the four radio fields it travels with.""" + radio = [snapshot.get(key) for key in ("radio_freq", "radio_bw", "radio_sf", "radio_cr")] + if any(field is None for field in radio): + raise DeviceConfigError( + "client_repeat: the radio settings were never read, so they can't be restated" + ) + await device.set_radio(*radio, repeat=bool(value)) + snapshot["repeat"] = bool(value) + + +async def _autoadd_hops_apply(device: Device, value: Any, snapshot: dict) -> None: + """Set the auto-add hop limit, restating the bitmask it travels behind.""" + flags = snapshot.get("autoadd_config") + if flags is None: + raise DeviceConfigError( + "autoadd_max_hops: the auto-add bitmask was never read, so it can't be restated" + ) + await device.set_autoadd_config(int(flags), max_hops=int(value)) + snapshot["autoadd_max_hops"] = value + + +def _pin_rule(value: Any, snapshot: dict | None) -> str | None: + """The firmware takes a pairing PIN of zero (none) or exactly six digits, nothing else.""" + if value == 0 or 100000 <= value <= 999999: + return None + return f"must be 0 (no PIN) or six digits, got {value}" + + +def _repeat_rule(value: Any, snapshot: dict | None) -> str | None: + """Relaying goes on only at a frequency the firmware allows it (when both are known).""" + if not value or not snapshot: + return None + ranges, freq = snapshot.get("repeat_freqs"), snapshot.get("radio_freq") + if not ranges or freq is None or repeat_freq_allowed(freq, ranges): + return None + allowed = ", ".join(f"{low:g}" if low == high else f"{low:g}–{high:g}" for low, high in ranges) + return f"this firmware relays only on {allowed} MHz, not {float(freq):g}" + + def _get(key: str) -> Callable[[dict], Any]: """Build a getter that reads ``key`` from a snapshot.""" return lambda snapshot: snapshot.get(key) -_TELEMETRY_CHOICES = {0: "off", 1: "always", 2: "device-only", 3: "all"} +# The firmware's TELEM_MODE_DENY / TELEM_MODE_ALLOW_FLAGS / TELEM_MODE_ALLOW_ALL: nobody, the +# contacts whose telemetry permission flag is set, or anyone who asks. There is no mode 3. +# The labels stay short because the widest value sizes the editor's value lane for every row. +_TELEMETRY_CHOICES = {0: "deny", 1: "by contact", 2: "allow all"} # adv_loc_policy / multi_acks are single firmware bytes; we list the values seen in the # wild but keep them non-strict so an unfamiliar value is still accepted. _ADV_LOC_CHOICES = {0: "off", 1: "on"} _MULTI_ACKS_CHOICES = {0: "off", 1: "on"} -# path_hash_mode is a 2-bit field; the hash size carried per hop is mode + 1 bytes. +# path_hash_mode is a 2-bit field; the hash size carried per hop is mode + 1 bytes. The field +# has room for a mode 3, but CMD_SET_PATH_HASH_MODE refuses it (``cmd_frame[2] >= 3``). _PATH_HASH_CHOICES = { 0: "1-byte hashes (default)", 1: "2-byte hashes", 2: "3-byte hashes", - 3: "4-byte hashes", } @@ -347,7 +430,7 @@ def _telemetry_spec(key: str, label: str) -> SettingSpec: value_type="enum", choices=_TELEMETRY_CHOICES, minimum=0, - maximum=3, + maximum=2, getter=_get(key), apply=_telemetry_apply(key), ) @@ -473,6 +556,7 @@ DEVICE_SETTINGS: list[SettingSpec] = [ "The name other nodes see", "Identity", "str", + max_length=31, # the firmware's 32-byte name field, its terminator included getter=_get("name"), apply=lambda d, v, s: d.set_name(v), ), @@ -512,6 +596,7 @@ DEVICE_SETTINGS: list[SettingSpec] = [ "int", minimum=0, maximum=999999, + validate=_pin_rule, getter=lambda snapshot: snapshot.get("ble_pin", snapshot.get("device_pin")), apply=lambda d, v, s: d.set_device_pin(v), ), @@ -522,8 +607,9 @@ DEVICE_SETTINGS: list[SettingSpec] = [ "Must match every other node on your mesh", "Radio", "float", - minimum=100.0, - maximum=1000.0, + # The bounds CMD_SET_RADIO_PARAMS itself enforces (150–2500 MHz, 7–500 kHz below). + minimum=150.0, + maximum=2500.0, getter=_get("radio_freq"), apply=_radio_apply("freq"), ), @@ -533,8 +619,8 @@ DEVICE_SETTINGS: list[SettingSpec] = [ "Wider is faster, narrower reaches further", "Radio", "float", - minimum=1.0, - maximum=1000.0, + minimum=7.0, + maximum=500.0, getter=_get("radio_bw"), apply=_radio_apply("bw"), ), @@ -566,12 +652,26 @@ DEVICE_SETTINGS: list[SettingSpec] = [ "How loud this radio transmits", "Radio", "int", - minimum=1, + minimum=-9, # CMD_SET_RADIO_TX_POWER's floor; the ceiling is the board's own maximum=30, max_key="max_tx_power", getter=_get("tx_power"), apply=lambda d, v, s: d.set_tx_power(v), ), + SettingSpec( + # Client repeat (firmware v9+): the companion relays mesh traffic like a repeater. + # Reported in the device-query frame as ``repeat`` and written as the optional last + # byte of the radio command, so it restates the radio and every radio change + # restates it (see _radio_apply). The firmware allows it only on a few frequencies. + "client_repeat", + "Repeat", + "Relay mesh traffic; allowed frequencies only", + "Radio", + "bool", + getter=_get("repeat"), + apply=_client_repeat_apply, + validate=_repeat_rule, + ), # Tuning. Both are firmware floats moved over the wire Γ—1000; the ranges are the # firmware's own constrain() bounds. (The repeater-side TX delay factors are *not* # here: companion firmware ignores them β€” they are remote-CLI settings on repeaters.) @@ -618,6 +718,19 @@ DEVICE_SETTINGS: list[SettingSpec] = [ getter=_get("autoadd_config"), apply=lambda d, v, s: d.set_autoadd_config(v), ), + SettingSpec( + # The firmware compares it with an advert's path hash count: 0 is no limit, 1 is + # direct neighbours only, N admits up to N-1 hops. Capped at 64. + "autoadd_max_hops", + "Auto-add max hops", + "Only auto-add nodes this near; 1 = direct, 0 = any", + "Behavior", + "int", + minimum=0, + maximum=64, + getter=_get("autoadd_max_hops"), + apply=_autoadd_hops_apply, + ), SettingSpec( "flood_scope", "Flood scope", @@ -664,7 +777,7 @@ DEVICE_SETTINGS: list[SettingSpec] = [ "enum", choices=_PATH_HASH_CHOICES, minimum=0, - maximum=3, + maximum=2, getter=_get("path_hash_mode"), apply=lambda d, v, s: d.set_path_hash_mode(v), ), diff --git a/meshterm/tools/advert.py b/meshterm/tools/advert.py index fd6dcdb..c95f921 100644 --- a/meshterm/tools/advert.py +++ b/meshterm/tools/advert.py @@ -7,7 +7,7 @@ as modal dialogs (the quit-dialog pattern), so the everyday action stays a quick in-place popup rather than a screen change. Menu-only: the scripted equivalents are ``config advert`` and ``config share``, so no -duplicate subcommand is registered here (the same pattern as ``device-actions``). +duplicate subcommand is registered here. """ from __future__ import annotations @@ -38,7 +38,7 @@ class SendAdvertTool(Tool): The flow presents its own result (the sent-advert note or the contact-card view) before returning, so by the time the user backs out there is nothing left for :meth:`run` to do β€” returning ``None`` tells the menu the invocation - is complete (the same pattern as the Device actions screen). + is complete (the same pattern as the Device config page). Args: ctx: Shared application context. diff --git a/meshterm/tools/config.py b/meshterm/tools/config.py index 77c5b0e..7c69f74 100644 --- a/meshterm/tools/config.py +++ b/meshterm/tools/config.py @@ -1,12 +1,12 @@ -"""The ``config`` tool: view and change every device configuration value. +"""The ``config`` tool: every device setting, and the operations on the box itself. -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 ``--yes``-gated set of destructive operations. Everything funnels through -:func:`apply_ops`: the editor stages value changes for :meth:`ConfigTool.run` to execute -and log, and the Device actions screen (the sibling ``device-actions`` tool) and the -standalone ``advert`` tool run their immediate operations (adverts, reboot, key -management, factory reset) through the same executor. +Interactively it opens the Device config page (see :mod:`meshterm.ui.config_editor`) β€” +settings staged and applied in place, with the clock, backup/restore, the identity key, +reboot and factory reset as actions below them. On the CLI it exposes generic key/value +subcommands plus backup/restore, channels, custom vars, and a ``--yes``-gated set of +destructive operations. Everything funnels through :func:`apply_ops`: the page's Apply and +its actions, :meth:`ConfigTool.run` for the scripted commands, and the standalone ``advert`` +tool's sends all run through the one executor. """ from __future__ import annotations @@ -41,25 +41,27 @@ class ConfigTool(Tool): name = "config" title = "Device config" icon = "πŸ”§" - help = "Device settings β€” identity, radio, tuning, …" + help = "Settings and actions β€” radio, backup, reboot, …" category = "This node" order = 20 async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None: - """Launch the interactive editor and collect the operations to perform. + """Run the Device config page; there are never parameters to collect. + + The page applies what is staged and runs its actions itself, logging a ``runs`` row + for each Apply (the same pattern as ``repeater-admin``), so by the time the reader + backs out there is nothing left for :meth:`run` to do. Args: ctx: Shared application context. Returns: - ``{"ops": [...]}`` to execute, or ``None`` if the user cancelled. + Always ``None``. """ from ..ui.config_editor import edit_config - ops = await edit_config(ctx) - if not ops: - return None - return {"ops": ops} + await edit_config(ctx) + return None async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: """Execute a list of configuration operations against the device. @@ -213,10 +215,10 @@ async def apply_ops( ) -> tuple[int, list[str], Report]: """Execute a list of configuration operation tuples against ``device``. - This is the single executor for every config operation, used both by - :meth:`ConfigTool.run` (for staged, applied changes) and by the interactive editor's - device actions (adverts, reboot, backup/restore, key management, factory reset β€” - which run immediately rather than staging). + This is the single executor for every config operation, used by :meth:`ConfigTool.run` + (the scripted commands) and by the Device config page β€” its Apply, one staged value at a + time, and its actions (reboot, backup/restore, key management, factory reset), which run + immediately rather than staging. Args: ctx: Shared application context (for console output). diff --git a/meshterm/tools/device_actions.py b/meshterm/tools/device_actions.py deleted file mode 100644 index 1d664f6..0000000 --- a/meshterm/tools/device_actions.py +++ /dev/null @@ -1,72 +0,0 @@ -"""The ``device-actions`` tool: immediate operations on the companion device itself. - -Opens the Device actions screen (see :func:`meshterm.ui.config_editor.device_actions`) β€” -clock sync, backup/restore, the identity key, reboot, and factory reset. Where the -sibling ``config`` tool *stages* value changes for review, everything here acts on the -box the moment it is confirmed, so the two concerns get their own menu entries and -screens. Sending an advert is not here: that everyday operation lives in its own -main-menu entry (the sibling ``advert`` tool β€” see :mod:`meshterm.tools.advert`). - -Menu-only: every action already has a first-class scripted equivalent under the ``config`` -CLI group (``config backup``, ``config restore``, ``config reboot``, ...), so no duplicate -subcommand is registered here. -""" - -from __future__ import annotations - -from typing import Any - -import typer - -from ..context import AppContext -from .base import Tool, ToolResult, register - - -@register -class DeviceActionsTool(Tool): - """Run immediate device operations: clock, backup, identity key, reboot, reset.""" - - name = "device-actions" - title = "Device actions" - icon = "πŸ”¨" - help = "Clock, backup, identity key, reboot, reset" - category = "This node" - order = 30 - - async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None: - """Run the interactive actions screen; there are never parameters to collect. - - Each action executes and presents its result inside the screen itself, so by the - time the user backs out there is nothing left for :meth:`run` to do β€” returning - ``None`` tells the menu the invocation is complete (the same pattern as backing - out of the config editor with nothing staged). - - Args: - ctx: Shared application context. - - Returns: - Always ``None``. - """ - from ..ui.config_editor import device_actions - - await device_actions(ctx) - return None - - async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: - """Nothing runs here: the actions execute inside :meth:`prompt_params`. - - Args: - ctx: Shared application context. - params: Unused. - - Returns: - An empty :class:`ToolResult` (only reachable from a scripted call). - """ - return ToolResult(summary={}) - - def register_cli(self, app: typer.Typer) -> None: - """Register no CLI command β€” the scripted equivalents live under ``config``. - - Args: - app: The Typer application (untouched). - """ diff --git a/meshterm/tools/repeater_admin.py b/meshterm/tools/repeater_admin.py index 53c1b56..87377d1 100644 --- a/meshterm/tools/repeater_admin.py +++ b/meshterm/tools/repeater_admin.py @@ -42,7 +42,7 @@ class RepeaterAdminTool(Tool): async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None: """Run the interactive flow; there are never parameters to collect. - The flow presents everything itself (the same pattern as ``device-actions``), + The flow presents everything itself (the same pattern as ``config``), so returning ``None`` tells the menu the invocation is complete. Args: diff --git a/meshterm/ui/channels.py b/meshterm/ui/channels.py index 87ed157..3525163 100644 --- a/meshterm/ui/channels.py +++ b/meshterm/ui/channels.py @@ -833,7 +833,7 @@ def _detail_summary(ctx: AppContext, slot: ChannelSlot, stats: _LiveStats) -> st def _detail_items(ctx: AppContext, slot: ChannelSlot) -> list: """Build the channel-detail rows: label and description in two aligned lanes. - The Device actions presentation (menu-style lanes, no header line β€” these are commands, + The Actions presentation (menu-style lanes, no header line β€” these are commands, not tabular data), padded in display cells so the double-width emoji can't skew the description column. Open-in-chat carries the channel's live unread badge, the notifications row reads as a toggle whose glyph and verb reflect the current mute state diff --git a/meshterm/ui/config_editor.py b/meshterm/ui/config_editor.py index 5a9a037..269dd47 100644 --- a/meshterm/ui/config_editor.py +++ b/meshterm/ui/config_editor.py @@ -1,22 +1,23 @@ -"""Interactive device-configuration screens, rendered in the full-screen session. +"""The Device config page: every setting of the companion, and the operations on the box. -Two sibling screens live here, deliberately kept distinct: +Behind the ``config`` tool (:func:`edit_config`), and shaped deliberately like the +repeater-admin page (:mod:`meshterm.ui.repeater_admin`) β€” the same full-screen list, the +same setting / value / description lanes under category headings, staged ``current β†’ new`` +values, Apply in place, and an **Actions** section closing the list β€” so configuring the +radio in your hand reads exactly like configuring one over the mesh. -* **Device config** (:func:`edit_config`, behind the ``config`` tool) β€” one grouped, - column-aligned list of every setting under its category heading, each row showing its - current value, any staged change, and a one-line explanation. Editing a row *stages* the - new value (shown as ``current β†’ new``) and nothing touches the radio until *Apply*; - backing out with staged changes asks before discarding them. The editor returns the - staged operations for :class:`~meshterm.tools.config.ConfigTool` to execute and log. -* **Device actions** (:func:`device_actions`, behind the ``device-actions`` tool) β€” the - operations that act on the box itself rather than a value: backup/restore, the - identity key, clock sync, reboot, and factory reset. These *run immediately* (after - their own confirmation dialog β€” destructive ones gate behind typing a confirmation - word); they have no meaningful "preview", so their result is shown at once. They share - the settings snapshot and :func:`~meshterm.tools.config.apply_ops` executor with the - editor, which is why both screens live in this module. The everyday advert action - lives in its own main-menu entry instead (the ``advert`` tool, via - :func:`send_advert`), one keystroke away as a popup over the menu. +* **Settings** β€” every value the companion firmware lets an app read and write (see + :data:`~meshterm.core.device_config.DEVICE_SETTINGS`), each custom variable the device + reports, and MeshTerm's own background-advert cadences. Editing a row *stages* the new + value and nothing touches the radio until *Apply*, which sends the staged values one at a + time and stays on the page: one the device refuses stays staged with its reason, as on + the remote page. Backing out with changes staged asks before discarding them. +* **Actions** β€” the operations on the box itself rather than on a value: re-read, clock + sync, backup/restore, the identity key, reboot, and factory reset. These *run + immediately*, each behind its own confirmation (destructive ones behind typing a word), + and share the snapshot and the :func:`~meshterm.tools.config.apply_ops` executor with + Apply. The everyday advert lives in its own main-menu entry instead (the ``advert`` tool, + via :func:`send_advert`), one keystroke away as a popup over the menu. Multiple-choice values are picked in dialogs (booleans as an On/Off button pair, enums as a floating select), the node's location can be set by pointing at the full-screen map (see @@ -36,6 +37,7 @@ from urllib.parse import quote from rich import box from rich.cells import cell_len +from rich.markup import escape from rich.table import Table from rich.text import Text @@ -47,6 +49,7 @@ from ..core.advert_store import ( cadence_label, ) from ..core.device_config import ( + DEVICE_SETTINGS, DeviceConfigError, SettingSpec, build_snapshot, @@ -62,8 +65,10 @@ from .marks import MASK_MARK from .menus import ( confirm_discard, exit_rows, + icon_lane, lane_header, lane_row, + marked_label, menu_rows, run_steps, section_heading, @@ -79,8 +84,11 @@ if TYPE_CHECKING: _LOCATION = "__location__" _PRESETS = "__presets__" _CUSTOM = "__custom__" +#: Prefix of a custom variable's row value; the variable's name follows it. +_CUSTOM_VAR = "__custom_var__:" _ADVERT_DIRECT = "__advert_direct__" _ADVERT_FLOOD = "__advert_flood__" +_READ = "__read__" _SYNC_CLOCK = "__sync_clock__" _REBOOT = "__reboot__" _BACKUP = "__backup__" @@ -125,15 +133,23 @@ async def cached_snapshot(ctx: AppContext, device: Device) -> dict: return await build_snapshot(device, self_info=self_info, path_hash_mode=path_hash_mode) -async def edit_config(ctx: AppContext) -> list[tuple] | None: - """Run the interactive editor and return the staged operations to perform. +async def edit_config(ctx: AppContext) -> dict[str, Any] | None: + """Run the Device config page until the reader leaves it. + + One screen for the whole visit, its rows refreshed in place after every round: they + carry the staged ``current β†’ new`` values and the title counts them, so the content + moves under a highlight β€” and a typed filter β€” that stay where the reader put them. + Every sub-prompt floats over the page. Apply sends what is staged and stays (see + :func:`_apply`); each action runs where it is picked; Esc leaves, asking first while + anything is still staged; and a reboot closes the page and hands off to the session's + reconnect dialog. Args: ctx: Shared application context (provides the connected device and UI surface). Returns: - A list of operation tuples for the tool to execute, or ``None`` if the user - cancelled without anything staged to apply. + ``{"applied": n}`` when staged values reached the device during the visit, or + ``None`` when none did. """ from .tui import CANCEL @@ -142,61 +158,95 @@ async def edit_config(ctx: AppContext) -> list[tuple] | None: custom = await device.get_custom_vars() # The background-advert cadences are app-side settings (MeshTerm sends the adverts, # not the firmware), but they're staged and applied exactly like device values so - # the editor stays one coherent surface. + # the page stays one coherent surface. policy = ctx.advert_store.load(str(snapshot.get("public_key") or "")) - # The editor is menu-only, so a full-screen session is always present. Keep the main - # menu *pushed on the stack* for the whole session (rather than popping it between - # prompts): every sub-prompt then floats over it as a modal popup with its own border - # β€” the quit-dialog pattern β€” instead of replacing the screen. See _menu_loop. session = getattr(ctx.ui, "session", None) if session is None: # pragma: no cover - guarded by the menu-only caller raise RuntimeError("the config editor is only available in the menu") - pending: dict[str, Any] = {} # setting key -> staged new value - extra_ops: list[tuple] = [] # staged custom-variable ops, in order + pending: dict[str, Any] = {} # setting key (or cadence sentinel) -> staged new value + custom_pending: dict[str, str] = {} # custom variable name -> staged new value + applied = 0 - # The editor's rows *are* its data β€” each carries its staged ``current β†’ new`` value and - # the title counts what is staged β€” so they are refreshed in place after every round - # (``replace_items``) rather than rebuilt as a new screen. One screen for the whole - # session means the typed filter survives editing a setting, not just the cursor. + def staged() -> int: + return len(pending) + len(custom_pending) + + def summary() -> dict[str, Any] | None: + return {"applied": applied} if applied else None + + # The rows read ``snapshot``, ``custom`` and ``policy`` through this closure, so a + # re-read that rebinds them is exactly what the next refresh draws. menu = _ConfigMenu( session, lambda reveal: _menu_items( - snapshot, pending, len(pending) + len(extra_ops), policy, reveal + snapshot, + pending, + staged(), + policy, + reveal, + custom=custom, + custom_pending=custom_pending, ), conceals=has_pin(snapshot), footer_hint="↑↓ move Β· type to filter Β· Enter select Β· Esc back", ) async with session.stay(menu) as visit: while True: - staged = len(pending) + len(extra_ops) choice = await visit.result() - if choice is CANCEL: # Esc at the menu + if choice is CANCEL: # Esc at the page choice = _CANCEL if choice in (None, _CANCEL): - if staged and not await confirm_discard(ctx, staged, verb="applying"): - continue # keep editing β€” the same menu, the same place in it - return None + if staged() and not await confirm_discard(ctx, staged(), verb="applying"): + continue # keep editing β€” the same page, the same place in it + return summary() if choice == _APPLY: - ops: list[tuple] = [] - for k, v in pending.items(): - if k in (_ADVERT_DIRECT, _ADVERT_FLOOD): - ops.append(("advert_cadence", k == _ADVERT_FLOOD, v)) - else: - ops.append(("set", k, v)) - ops.extend(extra_ops) - return ops or None - if choice in (_ADVERT_DIRECT, _ADVERT_FLOOD): + applied += await _apply(ctx, device, snapshot, pending, custom_pending) + snapshot, custom = await _reread(ctx, device) + policy = ctx.advert_store.load(str(snapshot.get("public_key") or "")) + elif choice == _READ: + snapshot, custom = await _reread(ctx, device) + _unstage_held(snapshot, custom, pending, custom_pending) + elif choice == _SYNC_CLOCK: + await _sync_clock(ctx, device, snapshot) + elif choice == _BACKUP: + await _backup_now(ctx, device, snapshot) + elif choice == _RESTORE: + if await _restore_now(ctx, device, snapshot): + snapshot, custom = await _reread(ctx, device) + _unstage_held(snapshot, custom, pending, custom_pending) + elif choice == _IDENTITY_KEY: + if await _identity_key_menu(ctx, device, snapshot): + snapshot, custom = await _reread(ctx, device) + elif choice == _REBOOT: + # A reboot ends the visit and would take anything staged with it, so ask + # first β€” and a discard agreed to is a discard, whatever the reboot does. + if staged(): + if not await confirm_discard(ctx, staged(), verb="applying"): + continue + pending.clear() + custom_pending.clear() + if await _reboot(ctx, device, snapshot): + return summary() # the link is dropping; the reconnect dialog takes over + elif choice == _RESET: + if await _factory_reset(ctx, device, snapshot): + # Everything staged was staged against a device that no longer exists. + pending.clear() + custom_pending.clear() + snapshot, custom = await _reread(ctx, device) + elif choice in (_ADVERT_DIRECT, _ADVERT_FLOOD): await _stage_advert_cadence(ctx, choice == _ADVERT_FLOOD, policy, pending) elif choice == _LOCATION: await _stage_location(ctx, snapshot, pending) elif choice == _PRESETS: await _stage_preset(ctx, snapshot, pending) elif choice == _CUSTOM: - await _stage_custom_var(ctx, custom, extra_ops) + await _stage_custom_var(ctx, custom, custom_pending) + elif isinstance(choice, str) and choice.startswith(_CUSTOM_VAR): + await _stage_var(ctx, choice.removeprefix(_CUSTOM_VAR), custom, custom_pending) else: # a setting key await _stage_setting(ctx, choice, snapshot, pending) + menu.conceal_pin(has_pin(snapshot)) menu.refresh() @@ -403,11 +453,24 @@ def _setting_value( session's staging. """ hide = spec.key == PIN_KEY and not reveal_pin - shown = format_value(spec, spec.getter(snapshot)) - value = Text(conceal(shown) if hide else shown) + current = spec.getter(snapshot) + # The repeater page's words for the two non-values: ``?`` never reported, ``empty`` a + # string the device holds blank β€” muted, and never parenthesized. + if current is None: + value = Text("?", style="muted") + elif spec.value_type == "str" and current == "": + value = Text("empty", style="muted") + else: + shown = format_value(spec, current) + value = Text(conceal(shown) if hide else shown) if spec.key in pending: - staged = format_value(spec, pending[spec.key]) - value.append(f" β†’ {conceal(staged) if hide else staged}", style="warn") + new = pending[spec.key] + if spec.value_type == "str" and new == "": + staged = "empty" + else: + staged = format_value(spec, new) + staged = conceal(staged) if hide else staged + value.append(f" β†’ {staged}", style="warn") return value @@ -445,8 +508,14 @@ class _ConfigMenu(SelectScreen): them in place through :meth:`~meshterm.ui.tui.select.SelectScreen.replace_items` β€” which follows the highlighted row by value and keeps the typed filter β€” rather than rebuilding the screen under a reader who was part-way down it. + + It is a full-screen page, not a floating popup β€” the same as the repeater-admin page it + mirrors: a device's whole configuration, with its actions, is a place the reader works + in for a while, and the value prompts, confirms and results float over it. """ + floating = False + def __init__( self, session, # noqa: ANN001 - TuiSession, imported lazily to avoid a cycle @@ -466,12 +535,22 @@ class _ConfigMenu(SelectScreen): **kwargs: Passed to :class:`~meshterm.ui.tui.select.SelectScreen`. """ title, items = build(False) + # The lanes end at the edge rather than slide. The Actions rows pin a head block + # (menus.menu_rows), which on its own turns ←→ scrolling on for the whole list β€” and + # a setting row, pinning nothing, would then slide its label out with its description. + kwargs.setdefault("hscroll", False) super().__init__(title, items, **kwargs) self._session = session self._build = build self._conceals = conceals self._revealed = False + def conceal_pin(self, conceals: bool) -> None: + """Say whether the device reports a PIN now β€” a reset or a restore can change it.""" + self._conceals = conceals + if not conceals: + self._revealed = False + def refresh(self) -> None: """Re-read the rows for what is staged now, keeping the reveal, cursor and filter.""" title, items = self._build(self._revealed) @@ -520,17 +599,24 @@ def _menu_items( staged: int, policy: AdvertPolicy, reveal_pin: bool = False, + *, + custom: dict[str, str] | None = None, + custom_pending: dict[str, str] | None = None, ) -> tuple[str, list]: - """Build the editor menu's title and rows for the current snapshot + staged state. + """Build the page's title and rows for the current snapshot + staged state. - Returns the ``(title, items)`` the caller pushes as a persistent backdrop screen (so - sub-prompts float over it). The rows sit in three aligned columns β€” setting, current - value (and any staged new value), description β€” under one header line, so the list - reads like the full-configuration table it stages changes for. + The settings sit in three aligned lanes β€” setting, current value (and any staged new + value), description β€” under one header line, grouped by category; the device's custom + variables and MeshTerm's own advert cadences follow in the same lanes; and the + **Actions** close the list. The same shape as the repeater-admin page (see + :func:`meshterm.ui.repeater_admin._menu_items`), so the two read as one editor. ``reveal_pin`` is :class:`_ConfigMenu`'s toggle, passed straight through to the PIN's - value lane. + value lane. ``custom`` holds the variables the device reports and ``custom_pending`` + the values staged for them. """ + custom = custom or {} + custom_pending = custom_pending or {} # First pass: collect every row's lanes per category, so the columns can be sized to # their content (including any staged ``β†’ new`` arrows) before a single row is built. sections: list[tuple[str, list[tuple[str, Text, str, Any]]]] = [] @@ -567,17 +653,19 @@ def _menu_items( _PRESETS, ) ) - elif category == "Experimental": - rows.append( - ( - "Custom variables…", - Text(), - "Set a raw firmware variable by name", - _CUSTOM, - ) - ) sections.append((category, rows)) + # Custom variables: each one the firmware or this board's sensors report, staged like a + # setting (the firmware's own, GPS, carry a name and a type β€” see _KNOWN_VARS), plus + # any new name staged by hand and the row to stage one. + var_rows: list[tuple[str, Text, str, Any]] = [] + for name in sorted(set(custom) | set(custom_pending)): + label, help_text, _kind = _KNOWN_VARS.get(name, (name, "A firmware variable", "str")) + value = _custom_value(name, custom, custom_pending) + var_rows.append((label, value, help_text, _CUSTOM_VAR + name)) + var_rows.append(("Set by name…", Text(), "Set a raw firmware variable by name", _CUSTOM)) + sections.append(("Custom variables", var_rows)) + # App-side rows: the background-advert cadences MeshTerm itself runs (see the # advert scheduler). They stage and apply like device settings, so they sit in the # same lanes under their own heading. @@ -617,12 +705,41 @@ def _menu_items( Choice(title=lane_row(label, value, help_text, label_w, value_w), value=key) ) - # Nothing at all while the editor is clean β€” Esc leaves, and a row saying so was + # The operations on the box itself, run the moment they are confirmed β€” the local + # counterpart of the repeater page's own Actions, built the same way. ↻ and ⚠ are one + # cell where πŸ•’ πŸ’Ύ πŸ“‚ πŸ” πŸ”„ are two, so the column is measured once and every mark padded + # out to it. The one irreversible row is tinted, on its mark (or its words, iconless). + actions = [ + ("↻", "Read settings", "Re-read every value from the device", _READ), + ("πŸ•’", "Sync clock…", "Set the device clock from this computer", _SYNC_CLOCK), + ("πŸ’Ύ", "Back up config…", "Write every setting to a TOML file", _BACKUP), + ("πŸ“‚", "Restore config…", "Preview or apply a saved TOML backup", _RESTORE), + ("πŸ”", "Identity key…", "Export or import the node's private key", _IDENTITY_KEY), + ("πŸ”„", "Reboot device…", "Restart the companion and reconnect", _REBOOT), + ("⚠", "Factory reset…", "Erase everything (typed confirmation)", _RESET), + ] + lane = icon_lane(icon for icon, _, _, _ in actions) + items.append(section_heading("Actions")) + items.extend( + menu_rows( + ( + marked_label(icon, label, "err" if value == _RESET else "", lane=lane), + help_text, + value, + ) + for icon, label, help_text, value in actions + ) + ) + + # Nothing at all while the page is clean β€” Esc leaves, and a row saying so was # retired app-wide. With changes staged the pair appears below one blank line: Apply # has no key of its own, and Back spells out what leaving costs (see menus.exit_rows). items.extend(exit_rows(staged, apply_value=_APPLY, back_value=_CANCEL)) - title = "Device config" + (f" β€” {staged} staged" if staged else "") + name = str(snapshot.get("name") or "") + title = "Device config" + (f" β€” {name}" if name else "") + if staged: + title += f" Β· {staged} staged" return title, items @@ -647,6 +764,13 @@ async def _stage_setting( value = await _prompt_value(ctx, spec, current, snapshot) if value is None: return + # A typed value was checked as it was typed; a picked one (relaying on or off) is + # checked here β€” against the radio as staged, not only as the device still holds it. + complaint = spec.validate(value, {**snapshot, **pending}) if spec.validate else None + if complaint: + ctx.ui.note(f"[err]βœ—[/err] {escape(complaint)}") + await ctx.ui.present(title=spec.label) + return if value == spec.getter(snapshot): pending.pop(key, None) # set back to the device's value β€” nothing to change else: @@ -864,9 +988,9 @@ async def _stage_preset(ctx: AppContext, snapshot: dict, pending: dict[str, Any] async def _stage_custom_var( - ctx: AppContext, custom: dict[str, str], extra_ops: list[tuple] + ctx: AppContext, custom: dict[str, str], custom_pending: dict[str, str] ) -> None: - """Prompt for a custom/experimental variable and stage a set operation. + """Prompt for a custom/experimental variable by name and stage a value for it. Known variable names are offered as suggestions so an existing one can be recalled without retyping it; any new name is accepted as free text. @@ -887,7 +1011,10 @@ async def _stage_custom_var( if answers is None: return key, value = answers - extra_ops.append(("set_custom", key, value)) + if value == custom.get(key): + custom_pending.pop(key, None) # what the device already holds β€” nothing to send + else: + custom_pending[key] = value async def _ask_custom_name( @@ -913,80 +1040,183 @@ async def _ask_custom_name( return typed.strip() if typed and typed.strip() else None -# --- device actions (run immediately) ----------------------------------------- +#: Custom variables the companion firmware itself defines (``CMD_SET_CUSTOM_VAR`` in +#: MeshCore's ``examples/companion_radio/MyMesh.cpp``): ``(label, description, kind)``, so +#: their rows read like settings. Anything else a board's sensors report is listed under its +#: own name and edited as text. +_KNOWN_VARS: dict[str, tuple[str, str, str]] = { + "gps": ("GPS", "Run the GPS receiver (boards with one)", "bool"), + "gps_interval": ("GPS interval (s)", "Seconds between GPS position reads", "int"), +} + +#: The firmware's ceiling on ``gps_interval`` (``constrain(…, 0, 86400)``): one day. +_GPS_INTERVAL_MAX = 86400 -async def device_actions(ctx: AppContext) -> None: - """Run the Device actions screen: immediate operations on the companion itself. +def _custom_value(name: str, custom: dict[str, str], custom_pending: dict[str, str]) -> Text: + """One custom variable's VALUE lane: ``current [β†’ staged]``, in the settings' words.""" - The action counterpart of :func:`edit_config`, behind the ``device-actions`` tool. - Nothing here is staged β€” each action runs as soon as its own confirmation is given - (destructive ones gate behind typing a confirmation word) and presents its result at - once. The menu stays open between actions so several can be run in a row; Esc (or - Back) returns to the main menu, and a reboot closes the screen and hands off to the - session's reconnect dialog. + def shown(raw: str) -> str: + if _KNOWN_VARS.get(name, ("", "", "str"))[2] == "bool" and raw in ("0", "1"): + return "on" if raw == "1" else "off" + return raw if raw != "" else "empty" - Args: - ctx: Shared application context (provides the connected device and UI surface). + if name not in custom: + value = Text("?", style="muted") # staged by name; the device never reported it + elif custom[name] == "": + value = Text("empty", style="muted") + else: + value = Text(shown(custom[name])) + if name in custom_pending: + value.append(f" β†’ {shown(custom_pending[name])}", style="warn") + return value + + +async def _stage_var( + ctx: AppContext, name: str, custom: dict[str, str], custom_pending: dict[str, str] +) -> None: + """Prompt for one listed custom variable's new value and stage it.""" + label, help_text, kind = _KNOWN_VARS.get(name, (name, "A firmware variable", "str")) + current = custom_pending.get(name, custom.get(name, "")) + if kind == "bool": + picked = await ctx.ui.dialog( + help_text, + [("Off", "0"), ("On", "1")], + title=label, + default=1 if current == "1" else 0, + keys={"0": "0", "1": "1", "n": "0", "y": "1"}, + ) + if picked is None: + return + value = str(picked) + else: + extra: dict[str, Any] = {} + if kind == "int": + extra = { + "validate": _valid_interval, + "help_text": f"Allowed: 0 – {_GPS_INTERVAL_MAX}", + } + raw = await ctx.ui.text(label, prompt=f"Value for {name}:", default=current, **extra) + if raw is None: + return + value = raw.strip() + if value == custom.get(name): + custom_pending.pop(name, None) # back to what the device holds β€” nothing to send + else: + custom_pending[name] = value + + +def _valid_interval(text: str) -> bool | str: + """Validate a whole number of seconds within the firmware's GPS-interval bound.""" + try: + seconds = int(text.strip()) + except ValueError: + return "Enter a whole number of seconds." + return True if 0 <= seconds <= _GPS_INTERVAL_MAX else f"Must be 0 – {_GPS_INTERVAL_MAX}." + + +# --- applying, and re-reading --------------------------------------------------- + + +def _staged_ops(pending: dict[str, Any], custom_pending: dict[str, str]) -> list[tuple[str, tuple]]: + """The staged values as ``(stage key, op)`` pairs, in the order they should be sent. + + Settings go in the registry's order rather than the order they were staged in, so a + retuned frequency lands before relaying is switched on for it; the advert cadences and + the custom variables follow. """ - from .tui import CANCEL, SelectScreen - - device = await ctx.device() - snapshot = await cached_snapshot(ctx, device) - - # Same persistent-backdrop pattern as the editor: the menu stays pushed while each - # action's prompts float over it as modal popups (see edit_config). - session = getattr(ctx.ui, "session", None) - if session is None: # pragma: no cover - guarded by the menu-only caller - raise RuntimeError("device actions are only available in the menu") - # One screen for the whole visit: the action rows are fixed, so nothing here needs - # rebuilding β€” and the cursor and any typed filter simply stay where the reader left them - # while each action's prompts float over the list. - menu = SelectScreen("Device actions", _action_items()) - async with session.stay(menu) as visit: - while True: - choice = await visit.result() - if choice is CANCEL or choice is None: # Esc - return - if choice == _SYNC_CLOCK: - await _sync_clock(ctx, device, snapshot) - elif choice == _BACKUP: - await _backup_now(ctx, device, snapshot) - elif choice == _RESTORE: - if await _restore_now(ctx, device, snapshot): - snapshot = await build_snapshot(device) - elif choice == _IDENTITY_KEY: - if await _identity_key_menu(ctx, device, snapshot): - snapshot = await build_snapshot(device) - elif choice == _REBOOT: - if await _reboot(ctx, device, snapshot): - return # the link is dropping; the reconnect dialog takes over - elif choice == _RESET: - if await _factory_reset(ctx, device, snapshot): - snapshot = await build_snapshot(device) + order = {spec.key: i for i, spec in enumerate(DEVICE_SETTINGS)} + ops = [ + (key, ("set", key, pending[key])) + for key in sorted((k for k in pending if k in order), key=order.__getitem__) + ] + ops += [ + (key, ("advert_cadence", key == _ADVERT_FLOOD, pending[key])) + for key in (_ADVERT_DIRECT, _ADVERT_FLOOD) + if key in pending + ] + ops += [(name, ("set_custom", name, value)) for name, value in custom_pending.items()] + return ops -def _action_items() -> list: - """Build the Device actions rows: label and description in two aligned columns. +#: What the result window calls a staged value whose stage key is a sentinel. +_STAGE_NAMES = {_ADVERT_DIRECT: "direct advert", _ADVERT_FLOOD: "flood advert"} - The shared menu-row presentation (see :func:`~meshterm.ui.menus.menu_rows`). - Factory reset keeps its err-tinted label so the one irreversible row reads as such. + +async def _apply( + ctx: AppContext, + device: Device, + snapshot: dict, + pending: dict[str, Any], + custom_pending: dict[str, str], +) -> int: + """Send every staged value, one at a time, and show what the device made of each. + + The local twin of the repeater page's Apply. Each value goes through + :func:`~meshterm.tools.config.apply_ops` β€” the executor ``config set`` runs too β€” in + :func:`_staged_ops`'s order. One the device takes leaves the stage; one it refuses + *stays* staged with the reason beside it, to be corrected or unstaged, never silently + dropped. A lost link is not a refusal: it is re-raised for the app's disconnect + handling. One ``runs`` row records the batch, naming settings and never their values β€” + one of them may be the pairing PIN. + + Returns: + How many staged values the device accepted. """ - items = menu_rows( - [ - ("πŸ•’ Sync clock…", "Set the device clock from this computer", _SYNC_CLOCK), - ("πŸ’Ύ Back up config to a file…", "Write every setting to TOML", _BACKUP), - ("πŸ“‚ Restore config from a backup…", "Preview or apply a saved TOML", _RESTORE), - ("πŸ” Identity key…", "Export or import the node's private key", _IDENTITY_KEY), - ("πŸ”„ Reboot device…", "Restart the companion and reconnect", _REBOOT), - ( - Text("⚠ Factory reset…", style="err"), - "Erase everything (typed confirmation)", - _RESET, - ), - ] + from ..core.connection import is_connection_lost + from ..tools.config import apply_ops + + batch = _staged_ops(pending, custom_pending) + names = [_STAGE_NAMES.get(key, key) for key, _op in batch] + run_id = ctx.repo.start_run("config", {"mode": "apply", "settings": names}, ctx.profile_name) + accepted = 0 + for (key, op), name in zip(batch, names, strict=True): + try: + await apply_ops(ctx, device, snapshot, [op]) + except Exception as exc: # noqa: BLE001 - a refusal is shown, and stays staged + if is_connection_lost(exc): + ctx.repo.finish_run(run_id, "error", {"applied": accepted, "error": str(exc)}) + raise + ctx.ui.note( + f"[err]βœ—[/err] [brand]{escape(name)}[/brand] β€” {escape(str(exc))} (still staged)" + ) + continue + accepted += 1 + (custom_pending if op[0] == "set_custom" else pending).pop(key, None) + left = len(batch) - accepted + ctx.repo.finish_run( + run_id, "error" if left else "ok", {"applied": accepted, "staged_left": left} ) - return items + ctx.ui.note( + f"[brand]{accepted}[/brand] of {len(batch)} staged changes applied" + + (" [warn](the rest stay staged)[/warn]" if left else "") + ) + await ctx.ui.present(title="Apply") + return accepted + + +async def _reread(ctx: AppContext, device: Device) -> tuple[dict, dict[str, str]]: + """Read the whole device again, after an apply or an action changed it under the page. + + Raw rather than through the session cache, which is exactly what just went stale β€” and + the cache is dropped on the way, so the next screen that trusts it reads the truth too. + """ + ctx.devstate.invalidate_config() + async with ctx.ui.busy_overlay(): + snapshot = await build_snapshot(device) + custom = await device.get_custom_vars() + return snapshot, custom + + +def _unstage_held( + snapshot: dict, custom: dict[str, str], pending: dict[str, Any], custom_pending: dict[str, str] +) -> None: + """Unstage every value the device turns out to hold already β€” a re-read can settle one.""" + for key in [k for k in pending if k not in _STAGE_NAMES]: + if get_spec(key).getter(snapshot) == pending[key]: + del pending[key] + for name in [n for n, value in custom_pending.items() if custom.get(n) == value]: + del custom_pending[name] async def _run_now( diff --git a/meshterm/ui/menus.py b/meshterm/ui/menus.py index 7e9951c..6efd6a9 100644 --- a/meshterm/ui/menus.py +++ b/meshterm/ui/menus.py @@ -11,7 +11,7 @@ construction: an err-tinted ``βœ— Back β€” discard staged changes``, and *nothing at all* when clean. * :func:`menu_rows` β€” label + muted description :class:`Choice` rows in two aligned lanes, padded in display cells so double-width emoji can't skew the description - column (the Device actions presentation), its icons lined up by :func:`align_icons`. + column (the editor pages' Actions presentation), its icons lined up by :func:`align_icons`. * :func:`align_icons` β€” THE icon column for labels that carry their icon inside the string: a one-cell ``⌨`` and a two-cell ``πŸ“‘`` start their words in the same cell. A list that builds its :class:`Choice` rows by hand runs its labels through it. @@ -292,8 +292,8 @@ def exit_rows(staged: int, *, apply_value: Any, back_value: Any) -> list: def menu_rows(rows: Iterable[tuple[str | Text, str, Any]]) -> list: """Label + description :class:`Choice` rows in two aligned lanes. - The menu-style presentation shared by Device actions, the channel detail, and the - repeater actions: no header line (these are commands, not tabular data), the + The menu-style presentation shared by the channel detail and the Actions of the Device + config and repeater-admin pages: no header line (these are commands, not tabular data), the description column starting two cells past the widest label, padding computed in display cells so a double-width emoji can't skew it. diff --git a/meshterm/ui/repeater_admin.py b/meshterm/ui/repeater_admin.py index 869dfea..250cf43 100644 --- a/meshterm/ui/repeater_admin.py +++ b/meshterm/ui/repeater_admin.py @@ -117,6 +117,19 @@ class AdminMenu(SelectScreen): floating = False + def __init__(self, title: str, items: list, **kwargs: Any) -> None: + """Build the page's list, its rows ending at the edge rather than sliding under ←→. + + The Device config page's handling, kept here on purpose. The Actions rows pin a head + block (:func:`~meshterm.ui.menus.menu_rows`), which on its own turns ←→ scrolling on + for the whole list β€” and a setting row, pinning nothing, then slid its label out of + view along with its description, under a footer that grew a ``←→ scroll`` atom. + ``hscroll=False`` keeps every row whole and cut with the ellipsis, as every other + editor lane is. + """ + kwargs.setdefault("hscroll", False) + super().__init__(title, items, **kwargs) + def _readable_key(self) -> str | None: """The highlighted row's setting key, when it is a setting the node can be asked.""" current = self._current_choice() diff --git a/meshterm/ui/theme.py b/meshterm/ui/theme.py index d3e34aa..c6a3298 100644 --- a/meshterm/ui/theme.py +++ b/meshterm/ui/theme.py @@ -687,7 +687,6 @@ _GLYPH_MAP: dict[str, str] = { "πŸ”†": "Β°", # brightest sighting "πŸ“Ά": "β‰₯", # TX power sweep β€” the power ramp "πŸ”§": "βš™", # config (parameter concept) - "πŸ”¨": "!", # device actions (probe family) "πŸ“‹": "i", # info "πŸ“°": "…", # live feed β€” a stream of items "🎧": "β‰ˆ", # monitor β€” listening to the waveform diff --git a/meshterm/ui/tui/select.py b/meshterm/ui/tui/select.py index 0f476eb..4f98b41 100644 --- a/meshterm/ui/tui/select.py +++ b/meshterm/ui/tui/select.py @@ -317,7 +317,7 @@ class SelectScreen(Screen): footer_hint: str | None = None, delete_hint: str = "", filterable: bool = True, - hscroll: bool = False, + hscroll: bool | None = None, hscroll_hint: str = "←→ scroll", keys: Mapping[str, Any] | None = None, key_hint: Callable[[Any], str] | None = None, @@ -339,8 +339,13 @@ class SelectScreen(Screen): filterable: Whether typing narrows the list. Off for short, fixed lists (e.g. the startup device picker) where type-to-filter would only get in the way. hscroll: Whether ←/β†’ horizontally scroll the *highlighted* row so an over-long - line can be read to its end (the Watchtower's alert log). Off by default β€” - rows simply ellipsize at the right edge and ←/β†’ stay inert. Only a row that + line can be read to its end (the Watchtower's alert log). ``None`` (the + default) lets the rows decide: one that pins a head block + (:attr:`Choice.hscroll_from`) turns scrolling on, and without one the rows + simply ellipsize at the right edge and ←/β†’ stay inert. ``False`` keeps it off + whatever the rows declare β€” the editor pages (Device config, repeater admin), + whose Actions rows pin heads but whose lanes are meant to end at the edge + rather than slide. Only a row that actually overflows the width scrolls; a short row (and every separator or column header) stays put, and the shift resets to the start whenever the highlight moves to another row or the filter is edited β€” each row scrolls @@ -376,8 +381,12 @@ class SelectScreen(Screen): # one turns the list's scrolling on without the builder having to reach the screen # it will be shown in. That is what makes every label+description list # (:func:`~meshterm.ui.menus.menu_rows`, the main menu) scroll its description - # wherever it is opened, ``ctx.ui.select`` included. - self._hscroll = hscroll or any(getattr(item, "hscroll_from", 0) > 0 for item in items) + # wherever it is opened, ``ctx.ui.select`` included β€” unless the list itself has + # said ``hscroll=False``, which the rows cannot overrule. + self._hscroll_auto = hscroll is None + self._hscroll = bool(hscroll) or ( + self._hscroll_auto and any(getattr(item, "hscroll_from", 0) > 0 for item in items) + ) self._hscroll_hint = hscroll_hint # Shortcuts are the non-filterable list's compensation for having no filter: the # letters are free, so a list may spend them (see the ``keys`` argument). @@ -435,7 +444,10 @@ class SelectScreen(Screen): was = current.value if current is not None else None position = self._index self._items = items - self._hscroll = self._hscroll or any(getattr(item, "hscroll_from", 0) > 0 for item in items) + if self._hscroll_auto: + self._hscroll = self._hscroll or any( + getattr(item, "hscroll_from", 0) > 0 for item in items + ) if title is not None: self.title = title if prompt is not None: diff --git a/tests/test_config_editor.py b/tests/test_config_editor.py index e33dbbd..9be0a7c 100644 --- a/tests/test_config_editor.py +++ b/tests/test_config_editor.py @@ -31,7 +31,6 @@ from meshterm.ui.config_editor import ( _valid_coords, config_table, contact_share_url, - device_actions, edit_config, has_pin, send_advert, @@ -700,6 +699,10 @@ class _ScriptedUi: def discard(self) -> None: pass + @asynccontextmanager + async def busy_overlay(self) -> Any: + yield + @pytest.fixture() def ctx(tmp_path: Path) -> AppContext: @@ -724,18 +727,39 @@ def _install(ctx: AppContext, script: list[tuple[str, Any]]) -> _ScriptedUi: return ui -async def test_editor_stages_a_setting_and_returns_ops_on_apply(ctx: AppContext) -> None: - """Editing a value stages it; Apply returns the set operations for the tool to run.""" - _install( +@pytest.fixture +def applied_ops(monkeypatch: pytest.MonkeyPatch) -> list[tuple]: + """Every op the page's Apply hands the executor, recorded on its way to the device.""" + from meshterm.tools import config as config_tool + + recorded: list[tuple] = [] + real = config_tool.apply_ops + + async def _recording(ctx, device, snapshot, ops): # noqa: ANN001 + recorded.extend(ops) + return await real(ctx, device, snapshot, ops) + + monkeypatch.setattr(config_tool, "apply_ops", _recording) + return recorded + + +async def test_editor_stages_a_setting_and_applies_it_in_place( + ctx: AppContext, applied_ops: list[tuple] +) -> None: + """Editing a value stages it; Apply sends it, and the page stays up for the next round.""" + ui = _install( ctx, [ ("select", "name"), ("text", "NewName"), ("select", "__apply__"), + ("select", None), # still on the page after Apply; nothing staged, so Esc leaves ], ) - ops = await edit_config(ctx) - assert ops == [("set", "name", "NewName")] + assert await edit_config(ctx) == {"applied": 1} + assert applied_ops == [("set", "name", "NewName")] + assert (await (await ctx.device()).get_self_info())["name"] == "NewName" + assert ui.presented == ["Apply"] async def test_editor_restaging_the_current_value_clears_the_stage(ctx: AppContext) -> None: @@ -755,7 +779,9 @@ async def test_editor_restaging_the_current_value_clears_the_stage(ctx: AppConte assert await edit_config(ctx) is None -async def test_editor_stages_background_advert_cadence(ctx: AppContext) -> None: +async def test_editor_stages_background_advert_cadence( + ctx: AppContext, applied_ops: list[tuple] +) -> None: """Picking a cadence stages it under its sentinel; Apply maps it to its own op.""" _install( ctx, @@ -763,10 +789,11 @@ async def test_editor_stages_background_advert_cadence(ctx: AppContext) -> None: ("select", "__advert_flood__"), ("select", 48), # every 48 h ("select", "__apply__"), + ("select", None), ], ) - ops = await edit_config(ctx) - assert ops == [("advert_cadence", True, 48)] + await edit_config(ctx) + assert applied_ops == [("advert_cadence", True, 48)] async def test_editor_repicking_the_cadence_in_force_clears_the_stage(ctx: AppContext) -> None: @@ -784,8 +811,10 @@ async def test_editor_repicking_the_cadence_in_force_clears_the_stage(ctx: AppCo assert await edit_config(ctx) is None -async def test_editor_asks_before_discarding_staged_changes(ctx: AppContext) -> None: - """Cancelling with staged changes confirms; Keep editing returns to the menu.""" +async def test_editor_asks_before_discarding_staged_changes( + ctx: AppContext, applied_ops: list[tuple] +) -> None: + """Cancelling with staged changes confirms; Keep editing returns to the page.""" _install( ctx, [ @@ -794,10 +823,11 @@ async def test_editor_asks_before_discarding_staged_changes(ctx: AppContext) -> ("select", "__cancel__"), ("dialog", "keep"), # changed my mind β€” keep editing ("select", "__apply__"), + ("select", None), ], ) - ops = await edit_config(ctx) - assert ops == [("set", "name", "NewName")] + await edit_config(ctx) + assert applied_ops == [("set", "name", "NewName")] async def test_editor_discards_staged_changes_when_confirmed(ctx: AppContext) -> None: @@ -839,7 +869,9 @@ async def test_editor_menu_pins_the_column_header_over_the_category(ctx: AppCont assert any("Flood advert" in _ANSI.sub("", row) for row in visible) -async def test_editor_location_typed_coordinates_stage_both_axes(ctx: AppContext) -> None: +async def test_editor_location_typed_coordinates_stage_both_axes( + ctx: AppContext, applied_ops: list[tuple] +) -> None: """Typing a coordinate pair stages latitude and longitude together.""" _install( ctx, @@ -848,15 +880,16 @@ async def test_editor_location_typed_coordinates_stage_both_axes(ctx: AppContext ("dialog", "type"), ("text", "45.5, -73.6"), ("select", "__apply__"), + ("select", None), ], ) - ops = await edit_config(ctx) - assert ("set", "adv_lat", 45.5) in ops - assert ("set", "adv_lon", -73.6) in ops + await edit_config(ctx) + assert ("set", "adv_lat", 45.5) in applied_ops + assert ("set", "adv_lon", -73.6) in applied_ops async def test_editor_location_map_pick_stages_rounded_coordinates( - ctx: AppContext, monkeypatch: pytest.MonkeyPatch + ctx: AppContext, monkeypatch: pytest.MonkeyPatch, applied_ops: list[tuple] ) -> None: """Picking on the map stages the chosen point, rounded to advert precision.""" @@ -871,14 +904,17 @@ async def test_editor_location_map_pick_stages_rounded_coordinates( ("select", "__location__"), ("dialog", "map"), ("select", "__apply__"), + ("select", None), ], ) - ops = await edit_config(ctx) - assert ("set", "adv_lat", 45.512346) in ops - assert ("set", "adv_lon", -73.654321) in ops + await edit_config(ctx) + assert ("set", "adv_lat", 45.512346) in applied_ops + assert ("set", "adv_lon", -73.654321) in applied_ops -async def test_editor_location_clear_stages_the_no_fix_pair(ctx: AppContext) -> None: +async def test_editor_location_clear_stages_the_no_fix_pair( + ctx: AppContext, applied_ops: list[tuple] +) -> None: """Clear stages 0, 0 β€” MeshCore's "no fix" value β€” for both axes.""" device = await ctx.device() await device.set_coords(45.5, -73.6) # give the device a position to clear @@ -888,11 +924,12 @@ async def test_editor_location_clear_stages_the_no_fix_pair(ctx: AppContext) -> ("select", "__location__"), ("dialog", "clear"), ("select", "__apply__"), + ("select", None), ], ) - ops = await edit_config(ctx) - assert ("set", "adv_lat", 0.0) in ops - assert ("set", "adv_lon", 0.0) in ops + await edit_config(ctx) + assert ("set", "adv_lat", 0.0) in applied_ops + assert ("set", "adv_lon", 0.0) in applied_ops async def test_send_advert_sends_zero_hop_and_flood_immediately(ctx: AppContext) -> None: @@ -912,12 +949,10 @@ async def test_send_advert_sends_zero_hop_and_flood_immediately(ctx: AppContext) assert any("flood" in n for n in ui.notes) -async def test_device_actions_no_longer_lists_the_advert_row(ctx: AppContext) -> None: - """The advert action lives only in the main menu now β€” the actions screen dropped it.""" - from meshterm.ui.config_editor import _action_items - - labels = [str(getattr(item, "title", "")) for item in _action_items()] - assert not any("advert" in label.lower() for label in labels) +def test_the_page_leaves_sending_an_advert_to_its_own_menu_entry() -> None: + """The box's actions moved onto the page; sending an advert stayed a main-menu popup.""" + _title, items = _menu_items(_SNAPSHOT, {}, 0, AdvertPolicy()) + assert not any("Send advert" in row for row in _row_texts(items)) async def test_send_advert_standalone_shares_the_contact_card(ctx: AppContext) -> None: @@ -953,7 +988,7 @@ async def test_actions_factory_reset_gates_on_typed_confirmation(ctx: AppContext ("select", None), ], ) - await device_actions(ctx) + await edit_config(ctx) assert await device.get_custom_vars() == {"mode": "test"} # Confirmed: the reset runs and the device comes back empty. @@ -965,7 +1000,7 @@ async def test_actions_factory_reset_gates_on_typed_confirmation(ctx: AppContext ("select", None), ], ) - await device_actions(ctx) + await edit_config(ctx) assert await device.get_custom_vars() == {} @@ -983,7 +1018,7 @@ async def test_actions_import_key_gates_on_typed_confirmation(ctx: AppContext) - ("select", None), ], ) - await device_actions(ctx) + await edit_config(ctx) assert await device.export_private_key() == new_key @@ -997,7 +1032,7 @@ async def test_actions_reboot_on_simulator_stays_on_the_screen(ctx: AppContext) ("select", None), ], ) - await device_actions(ctx) + await edit_config(ctx) assert ctx.reboot_in_progress is False assert any("rebooting" in n for n in ui.notes) @@ -1016,7 +1051,7 @@ async def test_actions_sync_clock_corrects_the_device_time(ctx: AppContext) -> N ("select", None), ], ) - await device_actions(ctx) + await edit_config(ctx) assert abs((await device.get_time()) - int(time.time())) <= 2 assert any("clock set to" in n for n in ui.notes) @@ -1033,29 +1068,29 @@ async def test_actions_sync_clock_cancel_leaves_the_clock_alone(ctx: AppContext) ("select", None), ], ) - await device_actions(ctx) + await edit_config(ctx) assert abs((await device.get_time()) - before) <= 2 # still ticking on the old drift -async def test_editor_stages_flood_scope(ctx: AppContext) -> None: - """The flood scope is a first-class staged setting, hashtag-normalized on apply.""" - from meshterm.core.device_config import build_snapshot - from meshterm.tools.config import apply_ops +async def test_editor_stages_flood_scope(ctx: AppContext, applied_ops: list[tuple]) -> None: + """The flood scope is a first-class staged setting, hashtag-normalized on apply. + The device reads it back as ``#alpha``, not the ``alpha`` that was staged β€” and the row + must still leave the stage, because the device *took* it: what unstages a value is its + acceptance, never a string comparison. + """ _install( ctx, [ ("select", "flood_scope"), ("text", "alpha"), ("select", "__apply__"), + ("select", None), # nothing left staged: Esc leaves without a discard dialog ], ) - ops = await edit_config(ctx) - assert ops == [("set", "flood_scope", "alpha")] - - device = await ctx.device() - await apply_ops(ctx, device, await build_snapshot(device), ops) - assert await device.get_default_flood_scope() == "#alpha" + await edit_config(ctx) + assert applied_ops == [("set", "flood_scope", "alpha")] + assert await (await ctx.device()).get_default_flood_scope() == "#alpha" async def test_actions_backup_writes_immediately(ctx: AppContext, tmp_path: Path) -> None: @@ -1069,12 +1104,14 @@ async def test_actions_backup_writes_immediately(ctx: AppContext, tmp_path: Path ("select", None), ], ) - await device_actions(ctx) + await edit_config(ctx) assert target.exists() assert any("wrote" in n for n in ui.notes) -async def test_editor_bool_prompt_uses_the_button_dialog(ctx: AppContext) -> None: +async def test_editor_bool_prompt_uses_the_button_dialog( + ctx: AppContext, applied_ops: list[tuple] +) -> None: """A boolean setting is toggled through the On/Off dialog and staged.""" _install( ctx, @@ -1082,13 +1119,16 @@ async def test_editor_bool_prompt_uses_the_button_dialog(ctx: AppContext) -> Non ("select", "manual_add_contacts"), ("dialog", True), ("select", "__apply__"), + ("select", None), ], ) - ops = await edit_config(ctx) - assert ops == [("set", "manual_add_contacts", True)] + await edit_config(ctx) + assert applied_ops == [("set", "manual_add_contacts", True)] -async def test_editor_custom_var_suggests_known_names(ctx: AppContext) -> None: +async def test_editor_custom_var_suggests_known_names( + ctx: AppContext, applied_ops: list[tuple] +) -> None: """With existing custom vars the name prompt offers them as suggestions.""" device = await ctx.device() await device.set_custom_var("existing", "1") @@ -1099,7 +1139,170 @@ async def test_editor_custom_var_suggests_known_names(ctx: AppContext) -> None: ("autocomplete", "existing"), ("text", "2"), ("select", "__apply__"), + ("select", None), ], ) - ops = await edit_config(ctx) - assert ops == [("set_custom", "existing", "2")] + await edit_config(ctx) + assert applied_ops == [("set_custom", "existing", "2")] + assert (await device.get_custom_vars())["existing"] == "2" + + +# -- the page's shape: the repeater-admin page's, for the radio in your hand -------------- + + +def _row_texts(items: list) -> list[str]: + """The plain text of every selectable row on the page.""" + from meshterm.ui.tui import Choice + + return [ + getattr(item.title, "plain", str(item.title)) for item in items if isinstance(item, Choice) + ] + + +def test_the_page_is_full_screen_like_repeater_admin() -> None: + """The page fills the frame; only its prompts, confirms and results float over it.""" + assert _editor(_SNAPSHOT).floating is False + + +def test_the_page_ends_long_rows_at_the_edge_despite_its_actions() -> None: + """Rows are cut with the ellipsis and ←→ stay inert, Actions rows and all. + + Those rows pin a head block, which on its own turns a list's ←→ scrolling on; the + page keeps the handling it always had, and the repeater page now shares it. + """ + menu = _editor(_SNAPSHOT) + before = list(menu.render_body(40)) + assert "←→" not in menu.footer_hint + menu.handle("right") + assert list(menu.render_body(40)) == before + + +def test_the_title_names_the_device_and_counts_what_is_staged() -> None: + """``Feature β€” subject Β· status``: the node's name, then the staged count as an atom.""" + assert _menu_items(_SNAPSHOT, {}, 0, AdvertPolicy())[0] == "Device config β€” Homestead-Hub" + staged_title, _items = _menu_items(_SNAPSHOT, {"tx_power": 14}, 1, AdvertPolicy()) + assert staged_title == "Device config β€” Homestead-Hub Β· 1 staged" + + +def test_the_actions_close_the_page_every_label_in_the_same_cell() -> None: + """The box's operations sit last, one icon column wide, as on the repeater page. + + ``↻`` and ``⚠`` are one cell among two-cell siblings; a row that wrote ``icon + " "`` + would start those two labels a column early. + """ + from rich.cells import cell_len + + _title, items = _menu_items(_SNAPSHOT, {}, 0, AdvertPolicy()) + rows = _row_texts(items) + labels = ( + "Read settings", + "Sync clock…", + "Back up config…", + "Restore config…", + "Identity key…", + "Reboot device…", + "Factory reset…", + ) + starts = { + label: cell_len(row[: row.index(label)]) for row in rows for label in labels if label in row + } + assert set(starts) == set(labels) + assert len(set(starts.values())) == 1, f"a label starts a column early: {starts}" + assert "Factory reset…" in rows[-1] # nothing staged: the last verb ends the list + + +def test_custom_variables_are_rows_of_their_own() -> None: + """Each reported variable is a row like a setting; the firmware's own read in words.""" + _title, items = _menu_items( + _SNAPSHOT, + {}, + 1, + AdvertPolicy(), + custom={"gps": "1", "probe": ""}, + custom_pending={"gps": "0"}, + ) + rows = _row_texts(items) + assert "on β†’ off" in next(row for row in rows if row.startswith("GPS ")) + assert "empty" in next(row for row in rows if row.startswith("probe")) + assert any(row.startswith("Set by name…") for row in rows) + + +async def test_a_listed_custom_variable_stages_and_applies( + ctx: AppContext, applied_ops: list[tuple] +) -> None: + """The firmware's GPS switch is an On/Off pick, applied like any other staged value.""" + device = await ctx.device() + await device.set_custom_var("gps", "1") + _install( + ctx, + [ + ("select", "__custom_var__:gps"), + ("dialog", "0"), + ("select", "__apply__"), + ("select", None), + ], + ) + await edit_config(ctx) + assert applied_ops == [("set_custom", "gps", "0")] + assert (await device.get_custom_vars())["gps"] == "0" + + +async def test_a_refused_value_stays_staged_while_the_rest_apply( + ctx: AppContext, applied_ops: list[tuple] +) -> None: + """The repeater page's rule: a refusal is shown and kept staged, never silently dropped.""" + device = await ctx.device() + + async def _refuse(name: str) -> None: + raise RuntimeError("device rejected the command: illegal argument") + + device.set_name = _refuse # type: ignore[method-assign] + ui = _install( + ctx, + [ + ("select", "name"), + ("text", "Refused"), + ("select", "flood_scope"), + ("text", "alpha"), + ("select", "__apply__"), + ("select", None), # the refused name is still staged, so leaving asks first + ("dialog", "discard"), + ], + ) + assert await edit_config(ctx) == {"applied": 1} + assert [op[1] for op in applied_ops] == ["name", "flood_scope"] + assert await device.get_default_flood_scope() == "#alpha" + assert any("still staged" in note for note in ui.notes) + assert any("1[/brand] of 2" in note for note in ui.notes) + + +async def test_repeat_is_refused_off_the_frequencies_the_firmware_allows(ctx: AppContext) -> None: + """Switching relaying on at a frequency the firmware refuses says so, and stages nothing.""" + ui = _install(ctx, [("select", "client_repeat"), ("dialog", True), ("select", None)]) + assert await edit_config(ctx) is None + assert any("relays only on" in note for note in ui.notes) + assert ui.presented == ["Repeat"] + + +async def test_repeat_goes_on_with_the_frequency_staged_beside_it( + ctx: AppContext, applied_ops: list[tuple] +) -> None: + """Checked against the radio as staged, and sent after it whatever the staging order.""" + _install( + ctx, + [ + ("select", "client_repeat"), + ("dialog", True), # refused: the device still sits on 869.618 + ("select", "radio_freq"), + ("text", "869.495"), + ("select", "client_repeat"), + ("dialog", True), # allowed now: checked against the staged frequency + ("select", "__apply__"), + ("select", None), + ], + ) + await edit_config(ctx) + assert [op[1] for op in applied_ops] == ["radio_freq", "client_repeat"] + device = await ctx.device() + assert (await device.get_device_info())["repeat"] is True + assert (await device.get_self_info())["radio_freq"] == 869.495 diff --git a/tests/test_device_config.py b/tests/test_device_config.py index 0cc8cc1..5685172 100644 --- a/tests/test_device_config.py +++ b/tests/test_device_config.py @@ -59,16 +59,31 @@ def test_parse_value_range_and_enum_errors() -> None: def test_format_value() -> None: """Formatting renders booleans, enums, and unknowns readably.""" assert format_value(get_spec("manual_add_contacts"), True) == "true" - assert format_value(get_spec("telemetry_mode_base"), 1) == "1 (always)" + assert format_value(get_spec("telemetry_mode_base"), 1) == "1 (by contact)" assert format_value(get_spec("name"), None) == "?" def test_path_hash_mode_is_strict_enum() -> None: - """path_hash_mode accepts its four modes and rejects anything else.""" - assert parse_value(get_spec("path_hash_mode"), "3") == 3 + """path_hash_mode takes the three modes the firmware accepts; it refuses a mode 3.""" + assert parse_value(get_spec("path_hash_mode"), "2") == 2 assert format_value(get_spec("path_hash_mode"), 0) == "0 (1-byte hashes (default))" with pytest.raises(DeviceConfigError, match="one of"): - parse_value(get_spec("path_hash_mode"), "4") + parse_value(get_spec("path_hash_mode"), "3") + + +def test_device_pin_is_zero_or_six_digits() -> None: + """The firmware refuses any other PIN, so the value is refused before it is sent.""" + spec = get_spec("device_pin") + assert parse_value(spec, "0") == 0 + assert parse_value(spec, "123456") == 123456 + with pytest.raises(DeviceConfigError, match="six digits"): + parse_value(spec, "1234") + + +def test_telemetry_modes_stop_at_the_firmware_s_three() -> None: + """Deny, by contact, allow all β€” there is no fourth mode to offer.""" + with pytest.raises(DeviceConfigError, match="one of"): + parse_value(get_spec("telemetry_mode_env"), "3") def test_highlighted_hash_highlights_path_hash_prefix() -> None: diff --git a/tests/test_menus.py b/tests/test_menus.py index 4bcd662..4528192 100644 --- a/tests/test_menus.py +++ b/tests/test_menus.py @@ -169,7 +169,7 @@ def test_main_menu_sections_answer_the_menus_own_question() -> None: "Message": ["chat", "channels", "courier", "contacts"], "Watch": ["dashboard", "livefeed", "watchtower", "timemachine"], "Explore": ["map", "walk", "trace", "trace-path", "records"], - "This node": ["info", "config", "device-actions", "advert"], + "This node": ["info", "config", "advert"], "Other nodes": ["repeater-admin", "tx-optimize"], "This app": ["preferences", "about", "about-author", "discord", "support"], } diff --git a/tests/test_paired_settings.py b/tests/test_paired_settings.py index 63b5502..4df200c 100644 --- a/tests/test_paired_settings.py +++ b/tests/test_paired_settings.py @@ -19,6 +19,7 @@ import pytest from meshterm.core.device_config import ( DEVICE_SETTINGS, + DeviceConfigError, build_snapshot, get_spec, parse_value, @@ -33,10 +34,14 @@ class _RecordingDevice: self.radio_calls: list[tuple] = [] self.coord_calls: list[tuple] = [] self.tuning_calls: list[tuple] = [] + self.repeat_calls: list = [] - async def set_radio(self, freq, bw, sf, cr) -> None: + async def set_radio(self, freq, bw, sf, cr, repeat=None) -> None: self.radio_calls.append((freq, bw, sf, cr)) + self.repeat_calls.append(repeat) self.state.update(radio_freq=freq, radio_bw=bw, radio_sf=sf, radio_cr=cr) + if repeat is not None: + self.state["repeat"] = repeat async def set_coords(self, lat, lon) -> None: self.coord_calls.append((lat, lon)) @@ -242,6 +247,140 @@ def test_every_coupled_setting_is_covered_here() -> None: "radio_cr", "rx_delay", "airtime_factor", + "client_repeat", + "autoadd_max_hops", } known = {spec.key for spec in DEVICE_SETTINGS} assert coupled <= known, coupled - known + + +# -- client repeat: the byte on the end of the radio command ------------------------------ + + +def test_retuning_the_radio_restates_client_repeat() -> None: + """THE trap: firmware reads a radio command without its repeat byte as "stop relaying". + + So a companion relaying for its neighbours stopped the moment anyone touched its + spreading factor, and nothing said so. + """ + device = _RecordingDevice( + radio_freq=869.495, radio_bw=62.5, radio_sf=8, radio_cr=5, repeat=True + ) + snapshot = dict(device.state) + asyncio.run(_apply_all(device, snapshot, [("radio_sf", "9")])) + assert device.repeat_calls == [True] + + +def test_firmware_without_client_repeat_is_sent_no_repeat_byte() -> None: + """Firmware that never reported the setting predates the byte, so none is sent.""" + device = _RecordingDevice(radio_freq=869.525, radio_bw=250.0, radio_sf=11, radio_cr=5) + snapshot = dict(device.state) + asyncio.run(_apply_all(device, snapshot, [("radio_sf", "10")])) + assert device.repeat_calls == [None] + + +def test_the_simulator_models_the_trap_the_restating_avoids() -> None: + """A bare radio command turns the simulator's relaying off; the registry's keeps it on.""" + from meshterm.core.connection import MockDevice + + async def scenario() -> tuple[bool, bool]: + device = MockDevice() + await device.connect() + await device.set_radio(869.495, 62.5, 8, 5, repeat=True) + await device.set_radio(869.495, 62.5, 9, 5) # the byte left off + dropped = (await device.get_device_info())["repeat"] + await device.set_radio(869.495, 62.5, 8, 5, repeat=True) + snapshot = await build_snapshot(device) + spec = get_spec("radio_sf") + await spec.apply(device, parse_value(spec, "9", snapshot), snapshot) + return dropped, (await device.get_device_info())["repeat"] + + dropped, kept = asyncio.run(scenario()) + assert dropped is False + assert kept is True + + +def test_client_repeat_restates_the_radio_it_rides_with() -> None: + """Switching relaying resends the four radio fields unchanged beside it.""" + device = _RecordingDevice( + radio_freq=869.495, + radio_bw=62.5, + radio_sf=8, + radio_cr=5, + repeat=False, + repeat_freqs=[(869.495, 869.495)], + ) + snapshot = dict(device.state) + asyncio.run(_apply_all(device, snapshot, [("client_repeat", "on")])) + assert device.radio_calls == [(869.495, 62.5, 8, 5)] + assert device.repeat_calls == [True] + + +def test_client_repeat_is_refused_off_an_allowed_frequency() -> None: + """The firmware relays only on its allowed frequencies; turning it off is always fine.""" + snapshot = {"radio_freq": 869.618, "repeat_freqs": [(433.0, 433.0), (869.495, 869.495)]} + with pytest.raises(DeviceConfigError, match="relays only on 433, 869.495 MHz"): + parse_value(get_spec("client_repeat"), "on", snapshot) + assert parse_value(get_spec("client_repeat"), "off", snapshot) is False + + +# -- the auto-add hop limit: the byte after the bitmask ----------------------------------- + + +def test_the_auto_add_hop_limit_restates_the_bitmask() -> None: + """The limit travels behind the bitmask, so setting it resends the bitmask unchanged.""" + + class _AutoAdd: + def __init__(self) -> None: + self.calls: list[tuple] = [] + + async def set_autoadd_config(self, flags, max_hops=None) -> None: + self.calls.append((flags, max_hops)) + + device = _AutoAdd() + asyncio.run(_apply_all(device, {"autoadd_config": 0x1E}, [("autoadd_max_hops", "3")])) + assert device.calls == [(0x1E, 3)] + + +def test_the_hop_limit_is_read_from_the_frame_the_library_half_parses() -> None: + """The library keeps the reply's first byte; the second is taken off the raw frame.""" + from types import SimpleNamespace + + from meshterm.core.connection import MeshCoreDevice + + class _Reader: + async def handle_rx(self, data) -> None: + self.last = bytes(data) + + reader = _Reader() + + class _Commands: + async def get_autoadd_config(self): + # What a transport does with a frame: hand it to the reader, by attribute. + await reader.handle_rx(bytearray([25, 0x1E, 3])) + return SimpleNamespace(payload={"config": 0x1E}, is_error=lambda: False) + + device = object.__new__(MeshCoreDevice) + device._mc = SimpleNamespace(_reader=reader, commands=_Commands()) + + async def read() -> tuple: + return await device.get_autoadd_config(), await device.get_autoadd_max_hops() + + assert asyncio.run(read()) == (0x1E, 3) + assert reader.last == bytes([25, 0x1E, 3]) # the library still saw its frame + assert "handle_rx" not in vars(reader) # and the tap came off again + + +def test_a_negative_tx_power_reads_back_signed() -> None: + """The firmware takes -9 dBm and reports a signed byte the library reads unsigned.""" + from types import SimpleNamespace + + from meshterm.core.connection import MeshCoreDevice + + class _Commands: + async def send_appstart(self): + return SimpleNamespace(payload={"tx_power": 247}) + + device = object.__new__(MeshCoreDevice) + device._mc = SimpleNamespace(commands=_Commands()) + assert asyncio.run(device.get_self_info())["tx_power"] == -9 diff --git a/tests/test_repeater_admin.py b/tests/test_repeater_admin.py index d8fe6e8..807c593 100644 --- a/tests/test_repeater_admin.py +++ b/tests/test_repeater_admin.py @@ -577,6 +577,20 @@ def test_admin_editor_is_a_full_screen_page() -> None: assert AdminMenu(title, items).floating is False +def test_admin_editor_ends_long_rows_at_the_edge_like_device_config() -> None: + """A long row is cut with the ellipsis and ←→ stay inert β€” the Device config handling. + + The Actions rows pin a head block, which alone used to turn ←→ scrolling on for the + whole page: the footer grew a ``←→ scroll`` atom and a setting's label slid out of view. + """ + title, items = repeater_admin._menu_items(NODE, {}, {}) + menu = AdminMenu(title, items, footer_hint="↑↓ move Β· type to filter Β· Enter select Β· Esc back") + before = list(menu.render_body(40)) # narrow enough that the highlighted row overflows + assert "←→" not in menu.footer_hint + menu.handle("right") + assert list(menu.render_body(40)) == before + + # --- the command-line screen ----------------------------------------------------------- diff --git a/tests/test_tui.py b/tests/test_tui.py index 3aab58d..825fc64 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -2672,6 +2672,26 @@ def test_select_scrolls_for_a_row_that_pins_a_head_without_being_told() -> None: assert _row_plains(plain, 40)[0] == before +def test_a_list_that_says_no_hscroll_is_not_overruled_by_its_rows() -> None: + """``hscroll=False`` holds against rows that pin a head, through a row swap too. + + The editor pages end their lanes at the edge; their Actions rows pin heads, and the + rows' say-so used to turn the whole page's ←→ scrolling on regardless. + """ + from meshterm.ui.tui.select import Choice, SelectScreen + + lanes = "Send advert " + row = Choice(lanes + "Announce this node " + "and then some " * 6, 1, hscroll_from=len(lanes)) + screen = SelectScreen("editor", [row], hscroll=False) + before = _row_plains(screen, 40)[0] + screen.handle("right") + assert _row_plains(screen, 40)[0] == before + assert "←→" not in screen.footer_hint + screen.replace_items([row]) # a refresh must not turn it back on + screen.handle("right") + assert _row_plains(screen, 40)[0] == before + + def test_menu_rows_pin_their_label_lane_so_only_the_description_slides() -> None: """The shared label+description builder hands each row its own head block.""" from meshterm.ui.menus import menu_rows