From 4ded134c05c2179a2642eb5f40f723b329987f7e Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Tue, 3 Nov 2026 02:31:02 -0500 Subject: [PATCH] The bulk clock sync shows each node's progress in one dialog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "Sync their clocks…" now opens a dialog that lists every managed repeater and room from the start: ○ waiting, a spinner with what it waits for (the transmit cooldown, the login, the command), then ✓ with the node's reply or a red ✗ with the reason. Long reasons wrap under the name. Esc stops the run after the node in progress; the OK chip closes the dialog once the run is done. Co-Authored-By: Claude Haiku 5.5 --- docs/guide/features.md | 2 +- meshterm/ui/clock_sync_dialog.py | 164 +++++++++++++++++++++++++++++++ meshterm/ui/repeater_admin.py | 110 ++++++++++++--------- tests/test_clocks.py | 64 ++++++++---- tests/test_gallery.py | 19 ++++ 5 files changed, 294 insertions(+), 65 deletions(-) create mode 100644 meshterm/ui/clock_sync_dialog.py diff --git a/docs/guide/features.md b/docs/guide/features.md index 3c96921..d1a1ecb 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -28,7 +28,7 @@ This page lists each interactive screen with its scripted equivalent, where one | **📊 Dashboard** | The live overview of the mesh. It has a two-hour chart of the activity of all packets with a pulse line, the traffic counts of the session for each packet class, and window RF health next to the live numbers of the radio. The screen updates each second. | none | | **📰 Live feed** | Each packet as it arrives, newest first. A row shows the time, the type of the packet (its parsed payload class), and what the packet is about. For an advert, that is the node. For a channel text, it is the channel. For a direct message or a request, it is sender → recipient. For a trace, it is the tag. The row also shows the reception quality and, for a scoped flood, the region of the flood. Press Enter to open a row in the packet viewer, with its route graph. | none | | **🚨 Watchtower** | A passive watcher of the nodes that you star. It gives a silence alarm when a watched node goes quiet. It warns you when the SNR of a node gets worse, and it tells you when the node returns. It also tells you when a node is heard for the first time. It runs in the background during the whole session. Alerts that you did not acknowledge show as a badge in the header. | none | -| **🕒 Clock drift** | How far the clock of each node is from yours. A node with a wrong clock puts wrong times on what it sends, and only its owner can set it. The page starts with a histogram of all the offsets, from the clocks behind yours, through the clocks in sync, to the clocks ahead. Then it lists your managed nodes (the nodes whose admin password MeshTerm stores), each one always, because you can set these clocks yourself. `Sync their clocks…` sets the clock of each managed repeater and room server in turn, with a pause between them, also when its clock looks correct: a repeater with no battery loses its time at each power cycle. Then each other node whose clock is out of sync, the largest offset first. Press Enter to open the node page. In a chat, a message from a wrong clock shows the time when it arrived, with a `?` mark. | `meshterm clocks` | +| **🕒 Clock drift** | How far the clock of each node is from yours. A node with a wrong clock puts wrong times on what it sends, and only its owner can set it. The page starts with a histogram of all the offsets, from the clocks behind yours, through the clocks in sync, to the clocks ahead. Then it lists your managed nodes (the nodes whose admin password MeshTerm stores), each one always, because you can set these clocks yourself. `Sync their clocks…` sets the clock of each managed repeater and room server in turn, with a pause between them, in a dialog that shows the result of each one, also when its clock looks correct: a repeater with no battery loses its time at each power cycle. Then each other node whose clock is out of sync, the largest offset first. Press Enter to open the node page. In a chat, a message from a wrong clock shows the time when it arrived, with a `?` mark. | `meshterm clocks` | | **⏳ Time machine** | Everything that the recorder ever heard, as braille charts: reception volume, the median-SNR band, the rhythm of the hours of the day, packets and nodes for each day, and first-ever arrivals. You can switch the time window between 24h, 7d, 30d, and all time. On the PicoCalc, the windows stop at 30d. You can look at one node or at the whole mesh. | none | | **🎧 Monitor** | The app always records passively. On the command line, this command captures a window of a fixed length in the foreground. It shows each overheard packet as it arrives, and it gives a summary at the end. It transmits nothing. It only listens. | `meshterm monitor --seconds 60` | diff --git a/meshterm/ui/clock_sync_dialog.py b/meshterm/ui/clock_sync_dialog.py new file mode 100644 index 0000000..9b1c9a6 --- /dev/null +++ b/meshterm/ui/clock_sync_dialog.py @@ -0,0 +1,164 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The dialog of the bulk clock sync: one line for each managed node, as the run goes. + +The bulk ``Sync their clocks…`` of the Clock drift page sets each managed repeater and room +server in turn (refer to :func:`~meshterm.ui.repeater_admin.sync_clocks`). This dialog lists +all of them from the start, so the user sees what the run will do and how far it is (JP, +2026-11-03): + +* ``○`` waiting, muted, for a node that the run did not reach yet. +* The spinner, with what the node waits for now: the transmit cooldown (``next in 4s``), + the login, or the command. +* ``✓`` with the short reply of the node, or a red ``✗`` with the reason. + +While the run works, Esc (or Enter) stops it after the node in progress, and each node that +it did not reach says ``not done``. The user is never trapped behind a run of a minute. +When the run is done, the ``OK`` chip closes the dialog. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from dataclasses import dataclass + +from rich.cells import cell_len +from rich.text import Text + +from ..core.models import Contact +from .theme import name_style +from .tui.render import render_hanging, render_to_ansi +from .tui.screen import Screen +from .tui.spinner import Spinner + +#: The states of one line. +WAITING, ACTIVE, OK, FAILED, NOT_DONE = "waiting", "active", "ok", "failed", "not_done" + + +@dataclass(slots=True) +class _Line: + """The state of one node in the dialog.""" + + node: Contact + state: str = WAITING + note: str = "" + + +class ClockSyncDialog(Screen): + """A floating dialog with one line for each node of a bulk clock sync. + + The owner changes the lines with :meth:`update`, and calls :meth:`finish` when the run + ends. The dialog resolves (with ``None``) only when the user closes it after that. + """ + + floating = True + #: The run owns the keyboard: ^W must not unwind the stack under it. + modal = True + + def __init__( + self, + nodes: Sequence[Contact], + *, + spinner: Spinner, + invalidate: Callable[[], None] = lambda: None, + ) -> None: + """Build the dialog with each node waiting. + + Args: + nodes: The nodes of the run, in the order of the run. + spinner: The spinner of the line in progress (the owner animates it). + invalidate: Asks the session for a paint, after each change. + """ + super().__init__() + self.title = "Sync clocks" + self._lines = [_Line(node) for node in nodes] + self._spinner = spinner + self._invalidate = invalidate + #: Called when the user stops the run. The owner connects it to its task. + self.on_stop: Callable[[], None] = lambda: None + self.done = False + + @property + def picocalc_lyra_lane(self): # noqa: ANN201 + """No lane: Enter and Esc are the only keys, and the hint names them.""" + from .tui.fkeys import EMPTY_LANE + + return EMPTY_LANE + + @property + def footer_hint(self) -> str: # type: ignore[override] + """``Esc stop`` while the run works, then the acknowledgement of a lone button.""" + return "Enter OK · Esc close" if self.done else "Esc stop" + + @property + def dialog_width(self) -> int: + """The natural width: the widest line, the title, and the hint.""" + widths = [cell_len(self.title), cell_len("Enter OK · Esc close")] + widths += [ + 4 + cell_len(line.node.name) + 4 + max(cell_len(line.note), 22) for line in self._lines + ] + return max(widths) + 8 + + def update(self, index: int, state: str, note: str = "") -> None: + """Change the state of one line, and paint. + + Args: + index: The position of the node in the run. + state: :data:`ACTIVE`, :data:`OK`, or :data:`FAILED`. + note: What the node waits for, its short reply, or the reason of the failure. + """ + line = self._lines[index] + line.state, line.note = state, note + self._invalidate() + + def finish(self) -> None: + """End the run: each line that the run did not complete says ``not done``.""" + for line in self._lines: + if line.state in (WAITING, ACTIVE): + line.state, line.note = NOT_DONE, "not done" + self.done = True + self._invalidate() + + def _line_parts(self, line: _Line) -> tuple[Text, Text]: + """One node as its mark (the prefix) and its name with its note (the body).""" + mark = Text() + if line.state == ACTIVE: + mark.append_text(self._spinner.text()) + elif line.state == OK: + mark.append("✓", style="ok") + elif line.state == FAILED: + mark.append("✗", style="err") + else: + mark.append("○", style="muted") + mark.append(" ") + body = Text() + key = line.node.public_key or line.node.key_prefix + body.append(line.node.name, style=name_style(line.node.name, key)) + note = line.note or ("waiting" if line.state == WAITING else "") + if note: + style = "err" if line.state == FAILED else "muted" + body.append(f" · {note}", style=style) + return mark, body + + def render_body(self, width: int) -> list[str]: + """The lines of the nodes, then the chip of the one button: Stop, then OK.""" + from .tui.prompt import _center + + lines: list[str] = [] + for line in self._lines: + # A long reason wraps under the name, never at column 0, so that it stays easy + # to read on the 53 columns of a handheld. + mark, body = self._line_parts(line) + lines.extend(render_hanging(mark, body, width, indent=mark.cell_len)) + lines.append("") + button = Text(" OK " if self.done else " Stop ", style="selected") + lines.append(render_to_ansi(_center(button, width), width)) + return lines + + def handle(self, action: str, data: str = "") -> None: + """Enter, Esc, or Space: stop the run while it works, or close the dialog after.""" + if action not in ("enter", "escape", "space"): + return + if self.done: + self.resolve(None) + else: + self.on_stop() diff --git a/meshterm/ui/repeater_admin.py b/meshterm/ui/repeater_admin.py index d0fbddc..11d1855 100644 --- a/meshterm/ui/repeater_admin.py +++ b/meshterm/ui/repeater_admin.py @@ -1109,26 +1109,26 @@ async def sync_clock(ctx: AppContext, node: Contact) -> None: async def sync_clocks(ctx: AppContext, nodes: list[Contact]) -> None: """Set the clocks of several managed nodes from ours, one node at a time. - This is the bulk ``Sync their clocks…`` of the Clock drift page. One confirm for the - whole list, then for each node a login with its stored password and the ``clock sync`` - command. MeshTerm never sends a burst: before each node it waits for the transmit - cooldown (refer to :func:`~meshterm.ui.cooldown.wait_for_cooldown`), whose countdown the - user can cancel. A cancel stops the run, and the summary says which nodes got their - clocks. + This is the bulk ``Sync their clocks…`` of the Clock drift page. One confirm, then the + dialog of the run (refer to :class:`~meshterm.ui.clock_sync_dialog.ClockSyncDialog`), + which lists each node from the start and shows each result as it comes. For each node: + the wait for the transmit cooldown, a login with its stored password, and the ``clock + sync`` command. MeshTerm never sends a burst. The cooldown shows on the line of the next + node (``next in 4s``). Esc stops the run, and the dialog closes when the user says so. Args: ctx: The shared application context (the interactive menu must be running). nodes: The managed repeaters and room servers to set. """ - from .cooldown import wait_for_cooldown + from ..core import transmit_gate + from .clock_sync_dialog import ACTIVE, FAILED, OK, ClockSyncDialog if not nodes: return - names = ", ".join(node.name for node in nodes) + count = f"{len(nodes)} managed {'node' if len(nodes) == 1 else 'nodes'}" choice = await ctx.ui.dialog( - f"Set the clocks of {len(nodes)} managed nodes from this companion's time? " - f"MeshTerm logs in to each one and sends one command, with a pause between " - f"transmissions. ({names})", + f"Set the clocks of {count} from this companion's time? MeshTerm logs in to " + "each one and sends one command, with a pause between them.", [("Cancel", None), ("Sync", "go")], title="Sync clocks", default=1, @@ -1136,43 +1136,62 @@ async def sync_clocks(ctx: AppContext, nodes: list[Contact]) -> None: if choice != "go": return device = await ctx.device() - results: list[tuple[Contact, bool, str]] = [] - for node in nodes: - # One wait for each node, before its login. The login and the command are one - # exchange with one node, as on the admin page, and the command marks the - # transmit clock that the wait of the next node reads. - if not await wait_for_cooldown(ctx, action=f"Sync clock — {node.name}"): - break - ok, reason = await _quiet_login(ctx, device, node) - if ok: - async with ctx.ui.busy_overlay(): - reply = await device.send_remote_command( - node, "clock sync", timeout=_REPLY_TIMEOUT_S - ) - if reply is None: - ok, reason = False, "no reply — the command may still have landed" - else: - ok, reason = not reply_is_error(reply), reply.strip() - results.append((node, ok, reason)) - body = Text() - for node, ok, reason in results: - if body.plain: - body.append("\n") - body.append("✓ " if ok else "✗ ", style="ok" if ok else "err") - body.append(node.name) - body.append(f" · {reason}", style="muted") - skipped = len(nodes) - len(results) - if skipped: - body.append(f"\n{skipped} not done: the run was cancelled", style="warn") - await ctx.ui.session.message_dialog(body, title="Sync clocks") + session = ctx.ui.session + spinner = Spinner() + dialog = ClockSyncDialog(nodes, spinner=spinner, invalidate=session.invalidate) + + async def run() -> None: + for index, node in enumerate(nodes): + # One wait for each node, before its login. The login and the command are one + # exchange with one node, as on the admin page, and the command marks the + # transmit clock that the wait of the next node reads. + while (left := transmit_gate.remaining()) > 0: + dialog.update(index, ACTIVE, f"next in {int(left + 0.999)}s") + await asyncio.sleep(min(left, 0.2)) + try: + dialog.update(index, ACTIVE, "logging in…") + ok, note = await _quiet_login(ctx, device, node) + if ok: + dialog.update(index, ACTIVE, "setting the clock…") + reply = await device.send_remote_command( + node, "clock sync", timeout=_REPLY_TIMEOUT_S + ) + if reply is None: + ok, note = False, "no reply — it may still have landed" + else: + ok, note = not reply_is_error(reply), reply.strip() + except Exception as exc: # noqa: BLE001 - one node's failure is its own line + ok, note = False, str(exc) + dialog.update(index, OK if ok else FAILED, note) + + async def animate() -> None: + while True: + await asyncio.sleep(spinner_interval()) + spinner.tick() + session.invalidate() + + task = asyncio.ensure_future(run()) + dialog.on_stop = task.cancel + task.add_done_callback(lambda _task: dialog.finish()) + ticker = asyncio.ensure_future(animate()) + try: + await session.run_screen(dialog) + finally: + task.cancel() + ticker.cancel() + for job in (task, ticker): + try: + await job + except (asyncio.CancelledError, Exception): # noqa: BLE001 - only the cleanup + pass async def _quiet_login(ctx: AppContext, device: Device, node: Contact) -> tuple[bool, str]: """Log in to a managed node with its stored password, with no dialog. - The bulk sync reports each failure in one summary, not one dialog for each node. The - password rules are those of :func:`_login`: a refused password is forgotten, and a - silence keeps it. + The bulk sync shows each failure on the line of its node, not in a dialog for each + node. The password rules are those of :func:`_login`: a refused password is forgotten, + and a silence keeps it. Returns: ``(True, "")`` when the session opened, else ``(False, the reason)``. @@ -1182,11 +1201,10 @@ async def _quiet_login(ctx: AppContext, device: Device, node: Contact) -> tuple[ password = ctx.admin_store.get(node) if password is None: return False, "no stored password" - async with ctx.ui.busy_overlay(): - outcome = await device.admin_login(node, password) + outcome = await device.admin_login(node, password) ctx.admin_store.record(node, password, outcome) if outcome is LoginResult.REFUSED: - return False, "the login was refused; the saved password was cleared" + return False, "login refused; the saved password was cleared" if not outcome: return False, "no reply to the login" return True, "" diff --git a/tests/test_clocks.py b/tests/test_clocks.py index 16f83bf..00fc23c 100644 --- a/tests/test_clocks.py +++ b/tests/test_clocks.py @@ -231,28 +231,27 @@ def test_the_bulk_row_ends_the_managed_section_for_each_repeater_and_room() -> N class _Ui: - """The UI of the bulk sync: the confirm, the busy overlay, and the summary.""" + """The UI of the bulk sync: the confirm, then the dialog of the run. + + ``run_screen`` waits until the run is done, as a user who reads the dialog does, keeps + what the dialog shows, then closes it. + """ def __init__(self) -> None: - self.summary = None + self.shown = "" self.session = self async def dialog(self, prompt, buttons, **kw): # noqa: ANN001, ANN003, ANN201 return "go" - def busy_overlay(self): # noqa: ANN201 - return _AsyncNull() + def invalidate(self) -> None: + pass - async def message_dialog(self, body, **kw): # noqa: ANN001, ANN003, ANN201 - self.summary = body.plain - - -class _AsyncNull: - async def __aenter__(self) -> None: - return None - - async def __aexit__(self, *exc) -> None: # noqa: ANN002 - return None + async def run_screen(self, dialog): # noqa: ANN001, ANN201 + while not dialog.done: + await asyncio.sleep(0) + self.shown = plain("\n".join(dialog.render_body(72))) + dialog.handle("enter") class _Device: @@ -271,8 +270,8 @@ class _Device: return "OK - clock set" -def test_the_bulk_sync_sets_each_clock_and_sums_up(tmp_path: Path, monkeypatch) -> None: # noqa: ANN001 - """One confirm, then each node in turn. The summary names each result.""" +def test_the_bulk_sync_sets_each_clock_and_shows_each_result(tmp_path: Path, monkeypatch) -> None: # noqa: ANN001 + """One confirm, then each node in turn. The dialog shows the result of each line.""" from meshterm.core import transmit_gate from meshterm.ui.repeater_admin import sync_clocks @@ -290,6 +289,35 @@ def test_the_bulk_sync_sets_each_clock_and_sums_up(tmp_path: Path, monkeypatch) ctx = type("Ctx", (), {"ui": ui, "admin_store": admin, "device": staticmethod(get_device)}) asyncio.run(sync_clocks(ctx, [behind, silent])) assert device.commands == ["Behind: clock sync"] # no command after a silent login - assert "✓ Behind" in ui.summary and "OK - clock set" in ui.summary - assert "✗ Silent" in ui.summary and "no reply to the login" in ui.summary + assert "✓ Behind · OK - clock set" in ui.shown + assert "✗ Silent · no reply to the login" in ui.shown + assert "OK" in ui.shown.splitlines()[-1] # the run is done: the chip closes it assert admin.get(silent) == "secret" # a silence keeps the password + + +def test_the_dialog_lists_each_node_and_closes_only_when_done() -> None: + """Each node waits, then works, then ends. Esc stops a run, and only a done run closes.""" + from meshterm.ui.clock_sync_dialog import ACTIVE, FAILED, OK, ClockSyncDialog + from meshterm.ui.tui.spinner import Spinner + + nodes = [_managed(name, None).contact for name in ("One", "Two", "Three")] + dialog = ClockSyncDialog(nodes, spinner=Spinner()) + stops: list[int] = [] + dialog.on_stop = lambda: stops.append(1) + text = plain("\n".join(dialog.render_body(72))) + assert text.count("○") == 3 and "waiting" in text and "Stop" in text + assert dialog.footer_hint == "Esc stop" + + dialog.update(0, OK, "clock set") + dialog.update(1, FAILED, "no reply to the login") + dialog.update(2, ACTIVE, "next in 4s") + text = plain("\n".join(dialog.render_body(72))) + assert "✓ One · clock set" in text and "✗ Two · no reply to the login" in text + assert "Three · next in 4s" in text + + dialog.handle("escape") + assert stops == [1] and not dialog.done # a stop asks the owner, and does not close + dialog.finish() + text = plain("\n".join(dialog.render_body(72))) + assert "Three · not done" in text and "OK" in text.splitlines()[-1] + assert dialog.footer_hint == "Enter OK · Esc close" diff --git a/tests/test_gallery.py b/tests/test_gallery.py index ed00e8c..7a158e5 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -1802,9 +1802,28 @@ def _clock_drift(cols: int, rows: int) -> Screen: return clock_drift_screen(rows_, tolerance_s=300) +def _clock_sync(cols: int, rows: int) -> Screen: + """The dialog of a bulk clock sync in its fullest form: each state, the longest notes.""" + from meshterm.ui.clock_sync_dialog import ACTIVE, FAILED, OK, ClockSyncDialog + from meshterm.ui.tui.spinner import Spinner + + nodes = [ + Contact(name="Hilltop-Repeater", public_key=_HUB_KEY), + Contact(name="A Rather Long Repeater Name For Width", public_key="ab" * 32), + Contact(name="MTL BBS", public_key="cd" * 32), + Contact(name="Valley", public_key="ef" * 32), + ] + dialog = ClockSyncDialog(nodes, spinner=Spinner()) + dialog.update(0, OK, "OK - clock set: 14:02 - 3/11/2026 UTC") + dialog.update(1, FAILED, "login refused; the saved password was cleared") + dialog.update(2, ACTIVE, "next in 5s") + return dialog + + _ENTRIES: list[_Entry] = [ _Entry("dashboard", _dashboard), _Entry("clock_drift", _clock_drift), + _Entry("clock_sync", _clock_sync), _Entry("dashboard-scoped", _dashboard_scoped), _Entry("contacts", _contacts), _Entry("archive_ladder", _archive_ladder),