From 6e07b08c259c6cf63f6007671e0445875a5573a8 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Tue, 3 Nov 2026 00:46:40 -0500 Subject: [PATCH] =?UTF-8?q?Managed=20nodes=20get=20a=20name,=20a=20?= =?UTF-8?q?=F0=9F=94=91=20mark,=20and=20node=20page=20repairs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A node whose admin password MeshTerm stores is now a "managed node": a πŸ”‘ beside the type mark in the Contacts list, the admin picker (its first section, renamed from "Remembered admins"), and the node page header. The menu's "Other nodes" section is now "Managed nodes". Contacts carry adverts_refused_until: the device's stored advert time when it is in the future, so the firmware's replay check drops every new advert. The node page shows it and offers "Accept its adverts again…", which rewrites the device's own record with only last_advert lowered (Device.accept_adverts_again). A managed repeater or room gets "Sync its clock…". The Clock drift page lists refused contacts. Co-Authored-By: Claude Haiku 5.5 --- CLAUDE.md | 3 +- README.md | 4 +- docs/cli/README.md | 4 +- docs/development/writing-style.md | 1 + docs/guide/features.md | 6 +- meshterm/core/connection.py | 84 ++++++++++++++ meshterm/core/models.py | 35 ++++++ meshterm/tools/base.py | 10 +- meshterm/tools/clocks.py | 11 +- meshterm/tools/preferences.py | 2 +- meshterm/tools/regions.py | 2 +- meshterm/tools/repeater_admin.py | 2 +- meshterm/tools/tx_optimize.py | 2 +- meshterm/ui/admin_picker.py | 20 +++- meshterm/ui/clocks_screen.py | 38 ++++++- meshterm/ui/contactlist.py | 34 +++--- meshterm/ui/contacts_screen.py | 27 +++++ meshterm/ui/marks.py | 8 ++ meshterm/ui/node_detail_screen.py | 125 ++++++++++++++++++--- meshterm/ui/repeater_admin.py | 25 +++++ scripts/reel_tours.py | 2 +- tests/test_gallery.py | 3 + tests/test_managed_nodes.py | 178 ++++++++++++++++++++++++++++++ tests/test_menus.py | 2 +- 24 files changed, 571 insertions(+), 57 deletions(-) create mode 100644 tests/test_managed_nodes.py diff --git a/CLAUDE.md b/CLAUDE.md index 4f76fbb..442659c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -74,6 +74,7 @@ them instead of hand-rolling: | Term | Meaning | |---|---| | node | any device on the mesh β€” a radio broadcasting packets; roles: companion, repeater, room server, sensor. The umbrella term | +| managed node | a node whose admin password MeshTerm stores (`admin_store`) β€” the user can log in to it without a prompt. Marked `πŸ”‘` (`marks.MANAGED_ICON`, `*` on the PicoCalc) beside the type mark in the Contacts list, the admin picker, and the node page header; listed first on the Clock drift page. The menu section of the admin tools is **Managed nodes** (JP, 2026-11-03; it was "Other nodes") | | contact | a node your device knows: **discovered** (heard broadcasting, not yet added) or **added** (in the contact list, messageable). Every contact is a node; not every node is a contact | | heard | received from ("last heard", "first heard") β€” never "seen" in UX text | | key | the full fixed-length value β€” a node's public key, a channel secret | @@ -82,7 +83,7 @@ them instead of hand-rolling: | route | the concrete node sequence a trace walked or will walk | | via | prefix for a packet/message's relay chain | | region | a named area a repeater relays floods for (`region put yul`); shown bare, never `#yul` β€” the `#` belongs to key derivation only | -| scope | the region a flood is limited to β€” a packet's, a channel's send scope, the device's default scope. A direct packet has none. MeshCore's sense and the only one: the menu's This node / Other nodes / This app sections name *whose* a setting is, never a "scope" | +| scope | the region a flood is limited to β€” a packet's, a channel's send scope, the device's default scope. A direct packet has none. MeshCore's sense and the only one: the menu's This node / Managed nodes / This app sections name *whose* a setting is, never a "scope" | | unscoped | a plain flood, relayed by any repeater that allows the wildcard `*` | | room | a room server's message board β€” what you *join*, read, and *post* to. The node is the *room server*; the people let in are its *members*, at an *access* of member, admin, or read-only. Its two passwords are the *room password* and the *admin password* | | post | a message on a room's board, filed under its *author*: the key prefix the room signs it with, named by whatever names that key. A room's other traffic (its command replies) shares its key and is never a post | diff --git a/README.md b/README.md index aa0d07a..3c37b59 100644 --- a/README.md +++ b/README.md @@ -281,8 +281,8 @@ Three sections name an activity. **Message** has chat, channels, the courier out contacts. **Watch** has the dashboard, the live feed, the watchtower, the clock drift report, and the time machine. **Explore** has the map, the mesh walk, tracing, and the trophy case. The other three -sections name the owner. **This node** is the radio in your hand. **Other nodes** is the -someone else's radio, which you reach over the mesh. **This app** is MeshTerm itself, with +sections name the owner. **This node** is the radio in your hand. **Managed nodes** are +the radios that you administer over the mesh. **This app** is MeshTerm itself, with the preferences, the diagnostics, and the written pages. Almost all of these have a mirror `meshterm` subcommand. The same registry builds the menu diff --git a/docs/cli/README.md b/docs/cli/README.md index adae1d6..2a4cf1d 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -32,7 +32,7 @@ instead, because the plain face can change between releases. - [The mesh around you](#the-mesh-around-you) - [Messaging](#messaging) - [Tracing](#tracing) - - [Other nodes](#other-nodes) + - [Managed nodes](#managed-nodes) - [MeshTerm itself](#meshterm-itself) - [Recipes](#recipes) - [What has no command](#what-has-no-command) @@ -1681,7 +1681,7 @@ node stays at its original power. --- -### Other nodes +### Managed nodes #### `meshterm repeater-admin` diff --git a/docs/development/writing-style.md b/docs/development/writing-style.md index 8f69113..1509fe9 100644 --- a/docs/development/writing-style.md +++ b/docs/development/writing-style.md @@ -171,6 +171,7 @@ and in quoted text. | contact | A node that your device knows. It is **discovered** (heard, not added) or **added** (in the contact list, and you can send messages to it). Each contact is a node. Not each node is a contact | | | our node | The node of the companion that MeshTerm is connected to. On the screen, it is "you" (β˜…) | own node, self node, local node | | companion | A node that a program (such as MeshTerm) controls through USB, Bluetooth, or TCP | | +| managed node | A node whose admin password MeshTerm stores, so that the user can log in to it with no prompt. It has the `πŸ”‘` mark | remembered admin, administered node | | device | The companion that MeshTerm is connected to (the `Device` class) | radio (for the companion) | | handheld | A small computer that runs MeshTerm on its own screen: the PicoCalc, the Cardputer Zero, or the uConsole | device (for the computer), on-device | | radio | The LoRa radio in a node | | diff --git a/docs/guide/features.md b/docs/guide/features.md index e9adde6..cacc783 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -6,8 +6,8 @@ for the scripted half. The main menu asks one question: "What would you like to do?" It has six sections. The first three sections name an action: Message, Watch, and Explore. The last three sections name -whose setting it is. "This node" is the radio in your hand. "Other nodes" are radios of -other persons, which you reach over the mesh. "This app" is the program in front of you. +whose setting it is. "This node" is the radio in your hand. "Managed nodes" are the radios +that you administer over the mesh. "This app" is the program in front of you. This page lists each interactive screen with its scripted equivalent, where one exists. @@ -51,7 +51,7 @@ This page lists each interactive screen with its scripted equivalent, where one | **πŸ“‘ Send advert** | Announce this node to the mesh with a zero-hop advert or a flood advert. You can also share the contact card of this node as a QR code. | `meshterm config advert` / `config share` | | **πŸ”Œ Devices** | This is not a menu screen. You select the companion on the startup splash. The splash lists the serial companions and the Bluetooth LE companions. If only one companion is present, MeshTerm selects it. You can add a network (TCP) companion with host:port. MeshTerm remembers the last good default. If the link drops, MeshTerm detects it at once and offers to reconnect. `meshterm devices` lists what discovery finds. | `meshterm devices` | -## πŸ—Ό Other nodes: the radio of another person, over the mesh +## πŸ—Ό Managed nodes: the radios that you administer over the mesh | Feature | What it does | Scripted | | --- | --- | --- | diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py index f83e310..e84e467 100644 --- a/meshterm/core/connection.py +++ b/meshterm/core/connection.py @@ -49,7 +49,9 @@ from .models import ( RoomAccess, RoomLogin, TraceResult, + advert_gate, advert_time, + clock_tolerance_s, utcnow, ) from .privatekey import normalize as normalize_key @@ -1329,6 +1331,33 @@ class Device(ABC): device rejected the removal for any other reason. """ + @abstractmethod + async def accept_adverts_again(self, node: Contact) -> bool: + """Lower the stored advert time of a contact, so that the device hears its adverts again. + + The firmware drops each advert that is not newer than the advert time that it stores + for the contact (a replay check). When a clock that was ahead is set correctly, the + stored time stays in the future, and the device ignores the node until the real + time passes it (refer to :attr:`~meshterm.core.models.Contact.adverts_refused_until`). + This method reads the contact record from the device, and writes it back with the + stored time lowered to our clock less the clock tolerance. Only that field changes: + the flags, the learned path, the name, and the position go back as the device has + them. The time is never zero, so the device still refuses a replay of an older + advert. + + Args: + node: The contact. It must have a full public key. + + Returns: + ``True`` when the method wrote the record. ``False`` when the stored time was not + in the future, so that there was nothing to change. + + Raises: + ContactNotOnDeviceError: If the device has no contact with that key. + DeviceCommandError: If the contact has no full key, or the device refused the + write. + """ + @abstractmethod async def get_tx_power(self) -> int | None: """Return the current TX power level, or ``None`` if it is not known.""" @@ -3353,6 +3382,7 @@ class MeshCoreDevice(Device): lat=lat, lon=lon, route_hops=_contact_route(info), + adverts_refused_until=advert_gate(info.get("last_advert")), ) ) return contacts @@ -3406,6 +3436,49 @@ class MeshCoreDevice(Device): f"couldn't remove {node.name} from the device: {reject_reason(result)}" ) + async def accept_adverts_again(self, node: Contact) -> bool: # noqa: D102 - inherited docstring + mc = self._require() + pub = self._node_pubkey(node) # raises DeviceCommandError if it has no key + if len(pub) != 64: + raise DeviceCommandError(f"{node.name} is known only by a key prefix") + record = await self._contact_record(mc, pub) + if record is None: + raise ContactNotOnDeviceError(node) + lowered = int(utcnow().timestamp()) - clock_tolerance_s() + if int(record.get("last_advert") or 0) <= lowered: + return False + # A new read of the record, written back with only the advert time changed. The + # command of the firmware writes each field of the frame into the stored contact + # (``updateContactFromFrame``). Thus a field that MeshTerm made up (a flood route, + # zero flags) would erase what the device learned. + record = {**record, "last_advert": lowered} + result = await mc.commands.add_contact(record) + if result is None or getattr(result, "is_error", lambda: False)(): + raise DeviceCommandError( + f"couldn't change the advert time of {node.name}: {reject_reason(result)}" + ) + return True + + async def _contact_record(self, mc, pub: str) -> dict | None: # noqa: ANN001 + """The raw contact record that the device has for a full key, or ``None``. + + The one-contact read comes first (``CMD_GET_CONTACT_BY_KEY``). A firmware that does + not have that command gets the full table read instead, which is slower but sure. + """ + try: + event = await mc.commands.get_contact_by_key(bytes.fromhex(pub)) + except Exception: # noqa: BLE001 - an older library or firmware: read the table + event = None + payload = dict(getattr(event, "payload", None) or {}) if event is not None else {} + if event is not None and not getattr(event, "is_error", lambda: False)() and payload: + if str(payload.get("public_key", "")).lower() == pub: + return payload + table = await self._contacts_payload(mc) + for info in table.values(): + if str((info or {}).get("public_key", "")).lower() == pub: + return dict(info) + return None + async def get_tx_power(self) -> int | None: # noqa: D102 - inherited docstring info = await self.get_self_info() value = info.get("tx_power") @@ -4933,6 +5006,17 @@ class MockDevice(Device): raise ContactNotOnDeviceError(node) self._contacts = [c for c in self._contacts if self._mock_key(c) != key] + async def accept_adverts_again(self, node: Contact) -> bool: # noqa: D102 - inherited docstring + await asyncio.sleep(0) + key = self._mock_key(node) + for i, contact in enumerate(self._contacts): + if self._mock_key(contact) == key: + if contact.adverts_refused_until is None: + return False + self._contacts[i] = replace(contact, adverts_refused_until=None) + return True + raise ContactNotOnDeviceError(node) + async def get_tx_power(self) -> int | None: # noqa: D102 - inherited docstring return self._tx_power diff --git a/meshterm/core/models.py b/meshterm/core/models.py index aa4d28d..58fac3c 100644 --- a/meshterm/core/models.py +++ b/meshterm/core/models.py @@ -308,6 +308,35 @@ def advert_time(last_advert: object) -> datetime | None: return when +def advert_gate(last_advert: object) -> datetime | None: + """The stored advert time of a contact when it is in the future, or ``None``. + + This is the other half of :func:`advert_time`. That function refuses a time in the + future as a fact about *when we heard* the node. This function keeps it, because it is + a fact about the *device*. MeshCore's ``onAdvertRecv`` drops each advert whose time is + not newer than the stored one, as a possible replay. Thus a node whose clock was once + ahead, and was then set correctly, is not heard again until the real time passes the + stored time. That can take months. + + Args: + last_advert: The raw ``last_advert`` field from a contact payload. + + Returns: + The stored time, when it is more than :func:`clock_tolerance_s` ahead of our clock. + """ + try: + seconds = int(last_advert) # type: ignore[arg-type] + except (TypeError, ValueError): + return None + if seconds <= 0: + return None + try: + when = datetime.fromtimestamp(seconds, tz=timezone.utc) + except (OverflowError, OSError, ValueError): + return None + return when if when > utcnow() + timedelta(seconds=clock_tolerance_s()) else None + + @dataclass(slots=True) class Contact: """A node that the connected companion knows. @@ -329,6 +358,11 @@ class Contact: means that the firmware thinks that the contact is a direct neighbour (a zero-hop route). ``None`` means that the device learned no route (or that the transport did not report one). + adverts_refused_until: The advert time that the device stores for this contact, + when that time is in the future (refer to :func:`advert_gate`). The firmware + refuses each advert that is not newer than the stored one, as a replay. Thus, + after the owner corrects a clock that was ahead, the device drops each new + advert of the node until this time. ``None`` when nothing is refused. """ name: str @@ -339,6 +373,7 @@ class Contact: lat: float | None = None lon: float | None = None route_hops: tuple[str, ...] | None = None + adverts_refused_until: datetime | None = None @property def has_location(self) -> bool: diff --git a/meshterm/tools/base.py b/meshterm/tools/base.py index ab8742f..5e1e420 100644 --- a/meshterm/tools/base.py +++ b/meshterm/tools/base.py @@ -223,11 +223,13 @@ _REGISTRY: dict[str, Tool] = {} #: features for each day, and the list from which you select a recipient). Then come Watch #: (what the mesh does, what it did, and what to get notifications about) and Explore #: (where the nodes are, how they get to each other, and the boards that score the walks). -#: Then come the two owners of a setting: This node (the radio in your hand) and Other -#: nodes (the radio of another person, over the mesh). +#: Then come the two owners of a setting: This node (the radio in your hand) and Managed +#: nodes (the radios that you administer over the mesh). The managed +#: section was "Other nodes" until 2026-11-03: its tools log in with an admin password, and +#: a node whose password MeshTerm stores is a *managed node* everywhere else in the app. #: #: This app ends the list as the third and last *owner*, after the radio in your hand and -#: the radio of another person over the mesh: it is the program in front of you. It holds +#: the radios that you manage over the mesh: it is the program in front of you. It holds #: the one item that changes how MeshTerm behaves (Preferences), and the four pages that #: say what MeshTerm is. These are questions that no activity above can hold, and that #: nothing on the mesh can answer. This app is last because the user who has nothing more @@ -238,7 +240,7 @@ _CATEGORY_ORDER = [ "Watch", "Explore", "This node", - "Other nodes", + "Managed nodes", "This app", ] diff --git a/meshterm/tools/clocks.py b/meshterm/tools/clocks.py index ea82bff..e917555 100644 --- a/meshterm/tools/clocks.py +++ b/meshterm/tools/clocks.py @@ -150,19 +150,20 @@ async def clock_rows(ctx: AppContext) -> list[ClockRow]: managed = admin is not None and admin.get(contact) is not None rows.append(ClockRow(offset, name, key, contact.node_type, managed, contact)) - # The managed nodes that sent no sample in the window: the newest offset from all the - # history, or none. + # The managed nodes, and the contacts whose adverts the device refuses, that sent no + # sample in the window: the newest offset from all the history, or none. listed = {r.offset.who for r in rows if r.offset is not None and r.offset.keyed} - for contact in contacts if admin is not None else (): + for contact in contacts: node_id = (contact.public_key or contact.key_prefix or "").lower().removeprefix("0x")[:12] if not node_id or node_id in listed or node_id == self_id: continue - if admin.get(contact) is None: + managed = admin is not None and admin.get(contact) is not None + if not managed and contact.adverts_refused_until is None: continue older = node_offset(ctx.repo, node_id, name=contact.name, key_of=key_of) key = contact.public_key or contact.key_prefix rows.append( - ClockRow(older, contact.name, key, contact.node_type, True, contact, current=False) + ClockRow(older, contact.name, key, contact.node_type, managed, contact, current=False) ) return rows diff --git a/meshterm/tools/preferences.py b/meshterm/tools/preferences.py index 588315a..0f21e2d 100644 --- a/meshterm/tools/preferences.py +++ b/meshterm/tools/preferences.py @@ -14,7 +14,7 @@ for eleven changes that the page staged, and for one ``preferences set``. This tool is the tool of the app, not of the device, on purpose. It reads nothing from the companion, it transmits nothing, and it works with no device connected. For this reason, it is the first row of the **This app** section (the third owner, after this node and -other nodes), and it is not next to Device config. +the managed nodes), and it is not next to Device config. """ from __future__ import annotations diff --git a/meshterm/tools/regions.py b/meshterm/tools/regions.py index 54ed373..ed0528e 100644 --- a/meshterm/tools/regions.py +++ b/meshterm/tools/regions.py @@ -49,7 +49,7 @@ class RegionsTool(Tool): title = "Regions" icon = "πŸ”–" help = "Ask a repeater which regions it relays floods for" - category = "Other nodes" + category = "Managed nodes" order = 20 menu_visible = False # the menu asks from the repeater's node page diff --git a/meshterm/tools/repeater_admin.py b/meshterm/tools/repeater_admin.py index efd1e11..ef0af64 100644 --- a/meshterm/tools/repeater_admin.py +++ b/meshterm/tools/repeater_admin.py @@ -42,7 +42,7 @@ class RepeaterAdminTool(Tool): title = "Repeater admin" icon = "πŸ—Ό" help = "Run a remote repeater β€” settings and actions" - category = "Other nodes" + category = "Managed nodes" order = 10 # the remote equivalent of the local config tools async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None: diff --git a/meshterm/tools/tx_optimize.py b/meshterm/tools/tx_optimize.py index 8abf91f..2d14484 100644 --- a/meshterm/tools/tx_optimize.py +++ b/meshterm/tools/tx_optimize.py @@ -49,7 +49,7 @@ class TxOptimizeTool(Tool): title = "TX optimize" icon = "πŸ“Ά" help = "Tune a remote node's TX power for a target" - category = "Other nodes" + category = "Managed nodes" order = 20 # the same as Repeater admin: a remote radio, changed over the mesh async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None: diff --git a/meshterm/ui/admin_picker.py b/meshterm/ui/admin_picker.py index c256cde..ec05d00 100644 --- a/meshterm/ui/admin_picker.py +++ b/meshterm/ui/admin_picker.py @@ -3,8 +3,9 @@ The tools that administer remote nodes over the mesh share this picker: TX optimize and the repeater admin screen. Thus "select the node to manage" reads the same everywhere. -The nodes that have credentials are first in the list, in their own πŸ”‘ section. These are -the nodes that the user administered before, so they are the most probable selections. +The nodes that have credentials are first in the list, in their own section: the *managed +nodes*, each with the ``πŸ”‘`` of :data:`~meshterm.ui.marks.MANAGED_ICON`. These are the nodes +that the user administered before, so they are the most probable selections. Repeaters and room servers follow, then all the other nodes. Each section is in order of how recently the node was heard. MeshTerm offers each contact that has a public key, because a password is a fact about the *user* and not about the node. @@ -46,7 +47,11 @@ def admin_picker_rows(ctx: AppContext, contacts: list[Contact]) -> tuple[list, l offer (those that have a key). Both are empty when MeshTerm can offer nothing. The caller shows a note about this and does not open a list. """ + from rich.cells import cell_len + + from .marks import MANAGED_ICON from .menus import section_heading + from .theme import glyph as platform_glyph from .theme import name_style from .tui import Choice from .widgets import DEFAULT_GLYPH, NODE_GLYPHS @@ -54,6 +59,12 @@ def admin_picker_rows(ctx: AppContext, contacts: list[Contact]) -> tuple[list, l candidates = [c for c in contacts if (c.public_key or c.key_prefix).strip()] if not candidates: return [], candidates + remembered = [c for c in candidates if ctx.admin_store.get(c) is not None] + # The mark column, as in the Contacts list: the key of a managed node, or blanks of the + # same width, so that each type mark stays in one column. No cells when no node is + # managed. + key_mark = platform_glyph(MANAGED_ICON) + mark_w = cell_len(key_mark) + 1 if remembered else 0 def row(contact: Contact) -> Choice: # The type mark keeps its own fixed hue. The *name* takes the hue that comes from @@ -62,6 +73,8 @@ def admin_picker_rows(ctx: AppContext, contacts: list[Contact]) -> tuple[list, l # type too.) glyph, glyph_style = NODE_GLYPHS.get(contact.node_type, DEFAULT_GLYPH) label = Text() + if mark_w: + label.append(f"{key_mark} " if contact in remembered else " " * mark_w) label.append(f"{glyph} ", style=glyph_style) label.append( contact.name, @@ -72,7 +85,6 @@ def admin_picker_rows(ctx: AppContext, contacts: list[Contact]) -> tuple[list, l def recency(contact: Contact) -> float: return -(contact.last_seen.timestamp() if contact.last_seen else 0.0) - remembered = [c for c in candidates if ctx.admin_store.get(c) is not None] infrastructure = [ c for c in candidates @@ -82,7 +94,7 @@ def admin_picker_rows(ctx: AppContext, contacts: list[Contact]) -> tuple[list, l items: list = [] if remembered: - items.append(section_heading("Remembered admins")) + items.append(section_heading("Managed nodes")) items.extend(row(c) for c in sorted(remembered, key=recency)) if infrastructure: items.append(section_heading("Repeaters & rooms")) diff --git a/meshterm/ui/clocks_screen.py b/meshterm/ui/clocks_screen.py index 1cf602b..7097599 100644 --- a/meshterm/ui/clocks_screen.py +++ b/meshterm/ui/clocks_screen.py @@ -2,13 +2,17 @@ """The Clock drift page: how far the clock of each node is from ours. The page reads the clock samples of the last ``clock_report_days`` (refer to -:mod:`~meshterm.services.clock_offsets`) and shows them in four sections: +:mod:`~meshterm.services.clock_offsets`) and shows them in these sections: * **Managed nodes** (the nodes whose admin password MeshTerm stores) come first, each one always, also when its clock is correct, because these are the clocks that the user can set (JP, 2026-11-03). A managed node with no sample in the window shows its newest offset from all the history, or ``no sample``. A repeater sends no message, so its adverts are its only samples, and a new install has none yet. +* **Adverts refused**: the contacts whose adverts the device drops, because their clocks + were once ahead (refer to + :attr:`~meshterm.core.models.Contact.adverts_refused_until`), with the date until which + it drops them. The node page of each one has the repair. * **All clocks**: a histogram of the offsets, in log steps on two sides. The clocks behind ours are at the top, the clocks in sync in the centre, and the clocks ahead at the bottom (JP, 2026-11-02). A clock can be wrong by seconds or by years, so one linear axis @@ -288,6 +292,27 @@ def _row_text(row: ClockRow, tolerance_s: float, width: int) -> Text: return text +def _refused_header(width: int) -> Text: + """The header line of the refused adverts: ``NAME`` and ``UNTIL``.""" + text = Text(" " * (_POINTER_W + _MARK_W), style="muted", no_wrap=True, overflow="ellipsis") + text.append(fit_cells("NAME", _name_w(width - _POINTER_W))) + text.append(" " + fit_cells("UNTIL", _OFFSET_W + 2 + _AGE_W, align="right")) + return text + + +def _refused_text(row: ClockRow, width: int) -> Text: + """One contact whose adverts the device refuses: its name, and the date in warn.""" + assert row.contact is not None and row.contact.adverts_refused_until is not None + glyph, glyph_style = NODE_GLYPHS.get(row.node_type, DEFAULT_GLYPH) + text = Text(no_wrap=True, overflow="ellipsis") + text.append(f"{glyph} ", style=glyph_style) + hue = name_style(row.name, row.key) if row.name else "node.unknown" + text.append(fit_cells(row.label, _name_w(width)), style=hue) + until = f"{row.contact.adverts_refused_until.astimezone():%Y-%m-%d}" + text.append(" " + fit_cells(until, _OFFSET_W + 2 + _AGE_W, align="right"), style="warn") + return text + + def _name_line(row: ClockRow, tolerance_s: float, width: int) -> Text: """One sender with no key: page text under the row column, in the unknown grey.""" text = Text(" " * (_POINTER_W + _MARK_W), no_wrap=True, overflow="ellipsis") @@ -333,6 +358,17 @@ def clock_drift_screen(rows: Sequence[ClockRow], *, tolerance_s: float) -> Selec items.append(Separator(_node_header)) items += node_rows(managed) + # The contacts whose adverts the device refuses, because their clocks were once ahead + # (refer to Contact.adverts_refused_until). Their node page has the repair. + refused = sorted( + (r for r in rows if r.contact is not None and r.contact.adverts_refused_until), + key=lambda r: r.label.casefold(), + ) + if refused: + items.append(section_heading("Adverts refused")) + items.append(Separator(_refused_header)) + items += [Choice(lambda w, r=r: _refused_text(r, w), r.contact) for r in refused] + counted = histogram(rows, tolerance_s) peak = max((count for _step, count in counted), default=0) or 1 items.append(section_heading("All clocks")) diff --git a/meshterm/ui/contactlist.py b/meshterm/ui/contactlist.py index e3d13d1..c53ff58 100644 --- a/meshterm/ui/contactlist.py +++ b/meshterm/ui/contactlist.py @@ -38,7 +38,7 @@ from typing import Any from rich.cells import cell_len from rich.text import Text -from .marks import LOCK_ICON, SELF_MARK +from .marks import LOCK_ICON, MANAGED_ICON, SELF_MARK from .menus import fit_cells from .theme import glyph, name_style from .tui.select import Choice, SelectScreen, Separator @@ -135,26 +135,29 @@ TRACE_LANES: tuple[ContactLane, ...] = (TRACED_LANE, HEARD_LANE, PKTS_LANE) ARCHIVED_LANES: tuple[ContactLane, ...] = (ARCHIVED_LANE,) -def _lock_lane_width(rows: list[ContactRow]) -> int: - """The width of the lock column in cells: the platform padlock and its gap, or ``0``. +def _row_marks(row: ContactRow) -> str: + """The marks of a row before its type glyph: the padlock, then the key of a managed node.""" + return (glyph(LOCK_ICON) if row.locked else "") + (glyph(MANAGED_ICON) if row.managed else "") - The column is on the left of the type glyph. It is there only while a row is locked, so - a list with no locks uses no cells for it. On the 53 cells of the PicoCalc, those cells - are for a name. + +def _lock_lane_width(rows: list[ContactRow]) -> int: + """The width of the mark column in cells: the widest marks of a row and a gap, or ``0``. + + The column is on the left of the type glyph. It holds the padlock of a locked contact + and the key of a managed node (:func:`_row_marks`). It is there only while a row has a + mark, so a list with no marks uses no cells for it. On the 53 cells of the PicoCalc, + those cells are for a name. """ - if not any(row.locked for row in rows): - return 0 - return cell_len(glyph(LOCK_ICON)) + 1 + widest = max((cell_len(_row_marks(row)) for row in rows), default=0) + return widest + 1 if widest else 0 def _lock_cell(row: ContactRow, lock_w: int) -> str: - """The lock column of a row: the padlock and its gap when locked, or else blanks.""" + """The mark column of a row: its marks and the gap, or else blanks.""" if not lock_w: return "" - if not row.locked: - return " " * lock_w - mark = glyph(LOCK_ICON) - return mark + " " * (lock_w - cell_len(mark)) + marks = _row_marks(row) + return marks + " " * (lock_w - cell_len(marks)) #: The muted ``(you)`` tag on the lane of our node (refer to :func:`_lane`). Its width is part @@ -251,6 +254,8 @@ class ContactRow: locked: Whether the contact is locked, so that it cannot be archived. A padlock then starts the row, on the left of the type glyph. ``False`` draws nothing there. + managed: Whether the contact is a managed node: MeshTerm stores its admin + password. The ``πŸ”‘`` then goes in the same column, after a padlock. you: Whether this is our node. Our node gets the ``β˜…`` marker, the pure-white ``you`` name style with a muted ``(you)`` tag, and faint ``β€”`` heard and packet lanes (MeshTerm never hears our node). Its row is pinned above the sorted @@ -266,6 +271,7 @@ class ContactRow: last_traced: datetime | None = None archived_at: datetime | None = None locked: bool = False + managed: bool = False you: bool = False diff --git a/meshterm/ui/contacts_screen.py b/meshterm/ui/contacts_screen.py index 67feb14..c63fd6f 100644 --- a/meshterm/ui/contacts_screen.py +++ b/meshterm/ui/contacts_screen.py @@ -119,6 +119,7 @@ class ContactsScreen(ContactListScreen): locked: frozenset[str] = frozenset(), locator: Locator | None = None, can_lock: bool = False, + managed: frozenset[str] = frozenset(), ) -> None: """Create the contacts screen over contact data that MeshTerm already got. @@ -145,11 +146,15 @@ class ContactsScreen(ContactListScreen): :class:`~meshterm.ui.map_screen.Locator`). With ``None``, ^L does nothing. can_lock: Whether the caller can store a lock, for ^K. With ``False``, ^K does nothing. + managed: The full keys (lowercase hex) of the managed nodes: the contacts whose + admin password MeshTerm stores. Each of those rows has the ``πŸ”‘`` in its + mark column (refer to :data:`~meshterm.ui.marks.MANAGED_ICON`). """ self._self_name, self._self_key = self_name, self_key self._locator = locator self._can_lock = can_lock self._locked = locked + self._managed = managed self._contacts, self._counts = contacts, counts rows = self._contact_rows_for(locked) # The maintenance actions close the list, after each contact, for each sort. First @@ -211,6 +216,7 @@ class ContactsScreen(ContactListScreen): last_seen=c.last_seen, count=contact_packets(c, self._counts), locked=(c.public_key or "").lower().removeprefix("0x") in locked, + managed=(c.public_key or "").lower().removeprefix("0x") in self._managed, ) ) return rows @@ -360,6 +366,7 @@ async def open_contacts( locked=_locked_keys(ctx, self_key), locator=locator, can_lock=_can_lock(ctx, self_key), + managed=managed_keys(ctx, contacts), ) screen = build() @@ -445,6 +452,26 @@ def _toggle_lock(ctx: AppContext, self_key: str, contact: Contact) -> None: store.set_locked(dev_pub, contact, not store.is_locked(dev_pub, contact.public_key)) +def managed_keys(ctx: AppContext, contacts: list[Contact]) -> frozenset[str]: + """The full keys of the managed nodes among ``contacts``: those with a stored admin password. + + Args: + ctx: The shared application context. Its ``admin_store`` holds the passwords. + contacts: The contacts to examine. + + Returns: + The keys in lowercase hex. Empty when the context has no admin store. + """ + store = getattr(ctx, "admin_store", None) + if store is None: + return frozenset() + return frozenset( + (c.public_key or "").lower().removeprefix("0x") + for c in contacts + if c.public_key and store.get(c) is not None + ) + + def _locked_keys(ctx: AppContext, self_key: str) -> frozenset[str]: """The keys of the contacts locked on this device. These rows draw a padlock.""" store = getattr(ctx, "contact_store", None) diff --git a/meshterm/ui/marks.py b/meshterm/ui/marks.py index b07b613..d822d18 100644 --- a/meshterm/ui/marks.py +++ b/meshterm/ui/marks.py @@ -61,6 +61,14 @@ MASK_MARK = "β€’" #: see. LOCK_ICON = "πŸ”’" +#: The mark of a **managed node**: a node whose admin password MeshTerm stores (JP, +#: 2026-11-02). It is the ``πŸ”‘`` of a credential key in the icon lexicon, because the stored +#: password is what makes the node one that the user manages. It is in the same column as +#: the padlock in the Contacts list, before the type glyph, and on the node page next to +#: the type. :func:`~meshterm.ui.theme.glyph` gives the ``*`` of a masked secret on the +#: PicoCalc. A node that is not managed draws nothing, for the same reason as the padlock. +MANAGED_ICON = "πŸ”‘" + #: Sentinels that name the endpoints of a path on the route graph. ``\x00`` never occurs #: in a node hash, so the sentinels can share the namespace of node ids and not collide #: with an id. diff --git a/meshterm/ui/node_detail_screen.py b/meshterm/ui/node_detail_screen.py index 6414198..25d2997 100644 --- a/meshterm/ui/node_detail_screen.py +++ b/meshterm/ui/node_detail_screen.py @@ -111,12 +111,12 @@ from rich.text import Text from ..core.connection import ContactNotOnDeviceError, DeviceCommandError from ..core.geo import haversine_km, usable_fix -from ..core.models import NODE_TYPE_LABELS, NODE_TYPE_REPEATER, Contact, utcnow +from ..core.models import NODE_TYPE_LABELS, NODE_TYPE_REPEATER, NODE_TYPE_ROOM, Contact, utcnow from ..platforms import Platform, on_platform from ..services.clock_offsets import node_offset from . import menus from .mapcanvas import RGB -from .marks import SELF_MARK +from .marks import MANAGED_ICON, SELF_MARK from .minimap import MiniMap from .pathgraph import ( DST_NODE, @@ -139,6 +139,7 @@ from .pathline import ( hops_atom, with_action_mark, ) +from .theme import glyph as platform_glyph from .theme import mark_rgb, name_style, snr_style from .tui.render import crop_cells, render_hanging, render_lines, render_to_ansi from .tui.screen import CANCEL, ListWindow, Screen @@ -1512,6 +1513,13 @@ async def open_node_detail( header.append(" your node", style="muted") elif type_label: header.append(f" {type_label}", style="muted") + # A managed node: MeshTerm stores its admin password. The key says so next to the type, + # the same mark as in the Contacts list. + admin_store = getattr(ctx, "admin_store", None) + managed = not you and contact is not None and admin_store is not None + managed = managed and admin_store.get(contact) is not None + if managed: + header.append(f" {platform_glyph(MANAGED_ICON)} managed", style="muted") # -- the observed topology: the suggested best path, and the routes to draw. target_hash = key.lower().removeprefix("0x") @@ -1557,14 +1565,21 @@ async def open_node_detail( signal = _signal_row(hn) if signal is not None: info_rows.append(("signal", signal)) - clock = _clock_row( + clock_offset = _clock_offset( ctx, node_id, name, make_name_key_resolver(contacts, stored_names, heard=named_at), ) - if clock is not None: - info_rows.append(("clock", clock)) + if clock_offset is not None: + info_rows.append( + ("clock", _clock_text(clock_offset, ctx.preferences.clock_tolerance_s)) + ) + refused = contact.adverts_refused_until if contact is not None else None + if refused is not None: + # The device drops each advert of the node until this date (refer to + # ``Contact.adverts_refused_until``). The row says why the node looks silent. + info_rows.append(("adverts", _refused_text(refused))) if lat is not None and lon is not None: info_rows.append(("where", _range_text(lat, lon, self_lat, self_lon))) # The regions of a repeater: what it was last heard to relay, from the region store (its @@ -1654,6 +1669,16 @@ async def open_node_detail( # It acts immediately (one anonymous request, one transmission), so no "…" at the # end. info_actions.append(_Action("regions", "πŸ”–", "", "Ask which regions it carries")) + # A managed repeater or room server can have its clock set from here: its password is + # stored, so the login asks nothing. The action is offered whatever the offset, because + # an unknown offset is a reason to set the clock too. + if managed and node_type in (NODE_TYPE_REPEATER, NODE_TYPE_ROOM): + info_actions.append(_Action("clock", "πŸ•’", "", "Sync its clock…")) + # The device refuses each advert of this node until a date in the future. The repair + # writes the record back with that date lowered (refer to + # ``Device.accept_adverts_again``). It writes to the device, so it confirms first. + if refused is not None and not you and contact is not None and contact.public_key: + info_actions.append(_Action("adverts", "πŸ“‘", "warn", "Accept its adverts again…")) # -- contact management: the last group of the page, and the only actions that end the # visit. None of them shows when the caller opened the page to look, not to act (refer # to ``manage``), except the lock when the caller lets the page lock (refer to @@ -1756,6 +1781,19 @@ async def open_node_detail( await open_timemachine_self(ctx) else: await open_timemachine_node(ctx, node_id, label) + elif action == "clock": + from .repeater_admin import sync_clock + + assert contact is not None # offered only for a managed contact + await sync_clock(ctx, contact) + elif action == "adverts": + assert contact is not None # offered only for a contact with a full key + if await _accept_adverts(ctx, contact, label): + base_actions = [a for a in base_actions if a.key != "adverts"] + screen.replace_info_actions(management(locked)) + screen.replace_info_row( + "adverts", Text("accepted again β€” the next advert updates it", "ok") + ) elif action == "restore": # A restore writes the contact back, and it ends the visit for the same reason # as a delete. The page was opened from the Archived list, and the row that @@ -2076,6 +2114,52 @@ async def _remove_contact(ctx: AppContext, contact: Contact, self_key: str, labe return True +async def _accept_adverts(ctx: AppContext, contact: Contact, label: str) -> bool: + """Confirm, then make the device hear the adverts of this contact again. + + The device refuses each advert that is not newer than the advert time that it stores. + That time is in the future when the clock of the node was once ahead (refer to + :meth:`~meshterm.core.connection.Device.accept_adverts_again`). The write changes only + that time, but it writes to the device, so the confirm is amber. + + Args: + ctx: The shared application context (interactive menu). + contact: The contact, with a full key. + label: The name of the node on the page. + + Returns: + ``True`` when the device has the lower time now (or had nothing to lower). + ``False`` when the user cancelled or the write failed. A failure is shown. + """ + from .surface import TuiUi + + assert isinstance(ctx.ui, TuiUi) # open_node_detail makes sure of this + session = ctx.ui.session + if not await ctx.ui.dialog( + f"This device ignores {label}'s adverts, because its clock was once ahead. " + "Lower the stored advert time so its next advert updates its name, position, " + "and path? Older adverts stay refused.", + [("Cancel", False), ("Accept", True)], + title="Accept adverts", + default=1, + danger=True, + ): + return False + device = await ctx.device() + try: + await device.accept_adverts_again(contact) + except Exception as exc: # noqa: BLE001 - a refused write is reported, not raised + ctx.log.debug("contacts: advert time not lowered for %s: %s", contact.name, exc) + await session.message_dialog( + Text(f"βœ— couldn't change {label}'s advert time β€” {exc}", style="err"), + title="Accept adverts", + ) + return False + # The table of the device changed. The next read shows the lower time. + ctx.devstate.invalidate_contacts() + return True + + #: Why a repeater may not answer the regions request, in the words that the page uses. _REGIONS_REACH = "it answers only a neighbour, or over a known route" @@ -2183,24 +2267,28 @@ def _signal_row(hn) -> Text | None: # noqa: ANN001 - Optional[HeardNode] return text if text.plain else None -def _clock_row(ctx, node_id: str, name: str | None, key_of) -> Text | None: # noqa: ANN001 - """How far the clock of the node is from ours, or ``None`` when no packet told it. +def _clock_offset(ctx, node_id: str, name: str | None, key_of): # noqa: ANN001, ANN202 + """The clock offset of the node, or ``None`` when no packet told it. - The offset is in ``warn`` when it is past the ``clock_tolerance_s`` preference, so that - a node whose times are wrong is visible on its own page. The muted aside says how old - the newest sample is (refer to :mod:`~meshterm.services.clock_offsets`). + Refer to :mod:`~meshterm.services.clock_offsets`. A failed read gives ``None``: the page + is useful without the clock line. """ if not node_id: return None try: - offset = node_offset(ctx.repo, node_id, name=name, key_of=key_of) + return node_offset(ctx.repo, node_id, name=name, key_of=key_of) except Exception: # noqa: BLE001 - the page is useful without the clock line return None - if offset is None: - return None - tolerance = ctx.preferences.clock_tolerance_s + + +def _clock_text(offset, tolerance_s: float) -> Text: # noqa: ANN001 - a ClockOffset + """The value of the ``clock`` row: how far the clock is from ours, and how old that is. + + The offset is in ``warn`` when it is past the ``clock_tolerance_s`` preference, so that + a node whose times are wrong is visible on its own page. + """ text = Text() - if offset.out_of_sync(tolerance): + if offset.out_of_sync(tolerance_s): text.append(format_offset(offset.offset_s), style="warn") else: text.append("in sync") @@ -2208,6 +2296,13 @@ def _clock_row(ctx, node_id: str, name: str | None, key_of) -> Text | None: # n return text +def _refused_text(until: datetime) -> Text: + """The value of the ``adverts`` row: the date until which the device refuses them.""" + text = Text(f"refused until {until.astimezone():%Y-%m-%d}", style="warn") + text.append(" Β· its clock was ahead", style="muted") + return text + + def _hop_hash(key: str | None, fallback: str, hash_bytes: int) -> str: """The hash of a key at ``hash_bytes`` width, or ``fallback`` when there is no usable key.""" hex_key = (key or "").lower().removeprefix("0x") diff --git a/meshterm/ui/repeater_admin.py b/meshterm/ui/repeater_admin.py index 42ae1be..1884d25 100644 --- a/meshterm/ui/repeater_admin.py +++ b/meshterm/ui/repeater_admin.py @@ -1081,6 +1081,31 @@ async def _simple_action( await ctx.ui.session.message_dialog(body, title=title) +async def sync_clock(ctx: AppContext, node: Contact) -> None: + """Log in to a managed node and set its clock from ours, from outside the admin page. + + This is the ``Sync clock`` row of the admin page, for the node page and the Clock drift + page. A managed node has its password stored, so the login asks nothing. The confirm, + the login, and the reply are those of the admin page. + + Args: + ctx: The shared application context (the interactive menu must be running). + node: The repeater or room server. + """ + device = await ctx.device() + if not await _login(ctx, device, node): + return + await _simple_action( + ctx, + device, + node, + "clock sync", + title="Sync clock", + prompt=f"Set {node.name}'s clock from this companion's time?", + commit="Sync", + ) + + async def _change_password(ctx: AppContext, device: Device, node: Contact) -> None: """Change the admin password of the node (and remember the new password if it succeeds).""" new = await ctx.ui.text( diff --git a/scripts/reel_tours.py b/scripts/reel_tours.py index 9b8bcfe..6a010bc 100644 --- a/scripts/reel_tours.py +++ b/scripts/reel_tours.py @@ -496,7 +496,7 @@ def advert(d: Director) -> None: d.hold(4.0) -# --------------------------------------------------------------------------- Other nodes +# --------------------------------------------------------------------------- Managed nodes def repeater_admin(d: Director) -> None: diff --git a/tests/test_gallery.py b/tests/test_gallery.py index dfda978..ed00e8c 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -239,6 +239,9 @@ def _contacts(cols: int, rows: int) -> Screen: archived=12, locked=frozenset({"aa" * 32}), can_lock=True, + # The locked contact is also a managed node: the mark column then holds the + # padlock and the key, its widest form, on each platform. + managed=frozenset({"aa" * 32}), ) screen.handle("down") return screen diff --git a/tests/test_managed_nodes.py b/tests/test_managed_nodes.py new file mode 100644 index 0000000..d78bb36 --- /dev/null +++ b/tests/test_managed_nodes.py @@ -0,0 +1,178 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Managed nodes and refused adverts: the marks, the section, and the advert gate repair. + +A managed node is a node whose admin password MeshTerm stores. It has the ``πŸ”‘`` mark in +each list of nodes. A contact whose stored advert time is in the future is a node that the +device no longer hears, and the node page can lower that time. +""" + +from __future__ import annotations + +import asyncio +from datetime import timedelta +from pathlib import Path +from types import SimpleNamespace + +import pytest +from rich.cells import cell_len + +from meshterm.core.admin_store import AdminStore +from meshterm.core.connection import ContactNotOnDeviceError, MeshCoreDevice, MockDevice +from meshterm.core.models import ( + CLOCK_TOLERANCE_S, + NODE_TYPE_REPEATER, + Contact, + advert_gate, + utcnow, +) +from meshterm.services.clock_offsets import ClockOffset +from meshterm.ui.clocks_screen import ClockRow, clock_drift_screen +from meshterm.ui.contactlist import ContactRow, _lock_cell, _lock_lane_width +from meshterm.ui.marks import LOCK_ICON, MANAGED_ICON +from meshterm.ui.theme import glyph +from tests.conftest import plain + +KEY = "ab" * 32 + + +def _stamp(delta: timedelta) -> int: + return int((utcnow() + delta).timestamp()) + + +# -- the advert gate ------------------------------------------------------------------------ + + +def test_only_a_stored_time_past_the_tolerance_closes_the_gate() -> None: + """A time far in the future is a closed gate. A near or past time, or none, is not.""" + far = advert_gate(_stamp(timedelta(days=90))) + assert far is not None and far > utcnow() + timedelta(days=89) + assert advert_gate(_stamp(timedelta(seconds=CLOCK_TOLERANCE_S // 2))) is None + assert advert_gate(_stamp(timedelta(days=-1))) is None + assert advert_gate(0) is None + assert advert_gate("garbage") is None + + +def test_the_simulator_opens_the_gate_once() -> None: + """The first call lowers the time. A second has nothing to do. An unknown key raises.""" + device = MockDevice() + gated = Contact( + name="Gated", + public_key=KEY, + key_prefix=KEY[:12], + adverts_refused_until=utcnow() + timedelta(days=30), + ) + asyncio.run(device.add_contact(gated)) + assert asyncio.run(device.accept_adverts_again(gated)) is True + assert asyncio.run(device.accept_adverts_again(gated)) is False + with pytest.raises(ContactNotOnDeviceError): + asyncio.run(device.accept_adverts_again(Contact(name="Nobody", public_key="cd" * 32))) + + +class _Commands: + """A stand-in for the command set of the library: one stored record, and the writes.""" + + def __init__(self, record: dict) -> None: + self.record = record + self.written: list[dict] = [] + + async def get_contact_by_key(self, pubkey: bytes): # noqa: ANN201 + assert pubkey.hex() == self.record["public_key"] + return SimpleNamespace(payload=dict(self.record), is_error=lambda: False) + + async def add_contact(self, record: dict): # noqa: ANN201 + self.written.append(record) + return SimpleNamespace(payload={}, is_error=lambda: False) + + +def test_the_device_writes_back_only_a_lower_advert_time() -> None: + """The record goes back as the device has it, with only a lower advert time. + + The flags, the path, the name, and the position do not change. The time goes to our + clock less the tolerance, and never to zero. + """ + record = { + "public_key": KEY, + "type": NODE_TYPE_REPEATER, + "flags": 1, + "out_path_len": 2, + "out_path_hash_mode": 0, + "out_path": "3d27", + "adv_name": "Hilltop", + "last_advert": _stamp(timedelta(days=200)), + "adv_lat": 45.5, + "adv_lon": -73.6, + } + commands = _Commands(record) + device = MeshCoreDevice(port="mock") + device._mc = SimpleNamespace(commands=commands) + assert asyncio.run(device.accept_adverts_again(Contact(name="Hilltop", public_key=KEY))) + (written,) = commands.written + now = int(utcnow().timestamp()) + assert now - CLOCK_TOLERANCE_S - 5 <= written["last_advert"] <= now - CLOCK_TOLERANCE_S + 5 + assert {k: v for k, v in written.items() if k != "last_advert"} == { + k: v for k, v in record.items() if k != "last_advert" + } + + # A stored time that is already in the past changes nothing. + commands.record = {**record, "last_advert": now - 3600} + commands.written.clear() + assert ( + asyncio.run(device.accept_adverts_again(Contact(name="Hilltop", public_key=KEY))) is False + ) + assert commands.written == [] + + +# -- the marks ------------------------------------------------------------------------------ + + +def test_the_mark_column_holds_the_padlock_and_the_key() -> None: + """A managed node has the key in the mark column. A locked and managed one has both.""" + rows = [ + ContactRow(value=1, name="Plain"), + ContactRow(value=2, name="Managed", managed=True), + ContactRow(value=3, name="Both", locked=True, managed=True), + ] + width = _lock_lane_width(rows) + assert _lock_cell(rows[0], width).strip() == "" + assert _lock_cell(rows[1], width).strip() == glyph(MANAGED_ICON) + assert _lock_cell(rows[2], width).strip() == glyph(LOCK_ICON) + glyph(MANAGED_ICON) + assert _lock_lane_width(rows[:1]) == 0 # no marks, no cells + + +def test_the_admin_picker_lists_managed_nodes_first_with_the_key(tmp_path: Path) -> None: + """The first section of the picker is "Managed nodes", and its rows have the key.""" + from meshterm.ui.admin_picker import admin_picker_rows + from meshterm.ui.tui import Choice + + store = AdminStore(tmp_path / "admin.json") + managed = Contact(name="Hilltop", public_key=KEY, node_type=NODE_TYPE_REPEATER) + other = Contact(name="Valley", public_key="cd" * 32, node_type=NODE_TYPE_REPEATER) + store.remember(managed, "secret") + items, _ = admin_picker_rows(SimpleNamespace(admin_store=store), [other, managed]) + lines = [str(item.text(80) if isinstance(item, Choice) else item.text(80)) for item in items] + text = "\n".join(lines) + assert text.index("Managed nodes") < text.index("Hilltop") < text.index("Valley") + hilltop = next(line for line in lines if "Hilltop" in line) + valley = next(line for line in lines if "Valley" in line) + assert hilltop.startswith(glyph(MANAGED_ICON)) + # One column for the names, in cells: the key is one character but two cells wide. + assert cell_len(valley[: valley.index("Valley")]) == cell_len( + hilltop[: hilltop.index("Hilltop")] + ) + + +# -- the Clock drift page ------------------------------------------------------------------- + + +def test_the_page_lists_the_contacts_whose_adverts_are_refused() -> None: + """A section after the managed nodes names each one, with the date in warn.""" + until = utcnow() + timedelta(days=60) + gated = Contact(name="Gated", public_key=KEY, adverts_refused_until=until) + offset = ClockOffset(KEY[:12], True, 2.0, 3, utcnow()) + screen = clock_drift_screen( + [ClockRow(offset, "Gated", KEY, None, False, gated)], tolerance_s=CLOCK_TOLERANCE_S + ) + text = plain("\n".join(screen.render_body(72))) + assert "Adverts refused" in text + assert f"{until.astimezone():%Y-%m-%d}" in text + assert text.index("Adverts refused") < text.index("All clocks") diff --git a/tests/test_menus.py b/tests/test_menus.py index 36eb13c..23075e2 100644 --- a/tests/test_menus.py +++ b/tests/test_menus.py @@ -205,7 +205,7 @@ def test_main_menu_sections_answer_the_menus_own_question() -> None: "Watch": ["dashboard", "livefeed", "watchtower", "clocks", "timemachine"], "Explore": ["map", "walk", "trace", "trace-path", "records"], "This node": ["info", "config", "advert"], - "Other nodes": ["repeater-admin", "tx-optimize"], + "Managed nodes": ["repeater-admin", "tx-optimize"], "This app": [ "preferences", "diagnostics",