From 101b48bc718ae8a3c96d6d5a5f21d59ef12bbec6 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Wed, 8 Jul 2026 18:09:27 -0400 Subject: [PATCH] Adopt the probed device and polish the startup splash Rework the startup device picker into a self-contained splash flow: - probe_meshcore (renamed from smoke_test_meshcore) now leaves the confirmed connection open and returns it, so AppContext.adopt_device reuses that live radio instead of reopening (many boards reset on each serial open). Restore the library's normal per-command timeout once the handshake succeeds. - Extract the Braille animation into a reusable tui.Spinner; BusyScreen now delegates to it. - Pin the wordmark to a fixed vertical anchor so it never shifts as the box swaps between the device list, spinner, and messages. - Esc or a trailing Quit row leaves the splash and exits the program. - Show the copyright only on the opening splash; retire it once a device is chosen, even across a failed smoke test and re-pick. - Disable prompt_toolkit's loop exception handler and route asyncio (and the awaited spinner ticker) errors to the file log, so a stray background-task error can't dump a traceback over the full-screen UI. Co-Authored-By: Claude Opus 4.8 --- meshterm/context.py | 13 +++++ meshterm/core/connection.py | 59 +++++++++++++-------- meshterm/persistence/logging.py | 6 ++- meshterm/ui/device_picker.py | 32 ++++++++--- meshterm/ui/menu.py | 33 +++++++++--- meshterm/ui/tui/__init__.py | 5 +- meshterm/ui/tui/frame.py | 17 ++++-- meshterm/ui/tui/screen.py | 16 +++--- meshterm/ui/tui/session.py | 17 +++++- meshterm/ui/tui/spinner.py | 69 ++++++++++++++++++++++++ tests/test_skeleton.py | 27 ++++++++++ tests/test_tui.py | 94 ++++++++++++++++++++++++++++++--- 12 files changed, 327 insertions(+), 61 deletions(-) create mode 100644 meshterm/ui/tui/spinner.py diff --git a/meshterm/context.py b/meshterm/context.py index 41a06db..9b2c2aa 100644 --- a/meshterm/context.py +++ b/meshterm/context.py @@ -141,6 +141,19 @@ class AppContext: """The application logger.""" return get_logger() + def adopt_device(self, device: Device) -> None: + """Adopt an already-connected device as the session's device. + + Used by the startup picker: it opens and confirms the chosen companion during its + smoke test, and hands that live connection here so :meth:`device` reuses it instead + of opening the radio a second time (many boards reset on each serial open, making a + reconnect slow and unreliable). + + Args: + device: A connected :class:`Device` to serve as this session's radio. + """ + self._device = device + async def device(self) -> Device: """Return a connected :class:`Device`, opening the connection on first use. diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py index bf3bee6..7286bd6 100644 --- a/meshterm/core/connection.py +++ b/meshterm/core/connection.py @@ -447,6 +447,14 @@ class MeshCoreDevice(Device): f"no response from a MeshCore companion on {self._port}; it may not be a " "MeshCore device, or it may be powered off or in use by another program." ) + # A short ``connect_timeout`` is only meant to bound the initial identity handshake + # (so a dead port is rejected quickly). Now that we're connected, restore the + # library's normal per-command timeout so the rest of the session isn't rushed. + if self._connect_timeout is not None: + commands = getattr(self._mc, "commands", None) + default = getattr(commands, "DEFAULT_TIMEOUT", None) + if commands is not None and default is not None: + commands.default_timeout = default async def disconnect(self) -> None: # noqa: D102 - inherited docstring if self._mc is None: @@ -1671,27 +1679,30 @@ def make_device( return MeshCoreDevice(port=port, baudrate=baudrate) -async def smoke_test_meshcore( +async def probe_meshcore( port: str, baudrate: int = 115200, *, timeout: float = 6.0 -) -> Optional[dict]: - """Briefly open ``port`` and confirm a MeshCore companion answers there. +) -> Optional[tuple["MeshCoreDevice", dict]]: + """Open ``port``, confirm a MeshCore companion answers, and return the live connection. - Opens a real serial connection and issues a single identity query (the APPSTART that - backs :meth:`MeshCoreDevice.get_self_info`). A genuine companion replies with a - self-info payload; anything else — a non-MeshCore serial gadget, the wrong baud rate, - an unresponsive port — never answers and is cut off by ``timeout``. The connection is - always closed before returning, so this is a non-destructive probe used by the startup - picker to verify a chosen device before committing to it. + Opens a real serial connection and issues an identity query (the APPSTART that backs + :meth:`MeshCoreDevice.get_self_info`). A genuine companion replies with a self-info + payload; anything else — a non-MeshCore serial gadget, the wrong baud rate, an + unresponsive port — never answers and is rejected within ``timeout``. + + On success the connection is **left open** and returned to the caller, which reuses it as + the session device. This is deliberate: many companion boards reset on each serial open, + so a probe-then-reopen cycle is slow and flaky — opening the radio exactly once is both + faster and far more reliable. On any failure the probe connection is closed. Args: port: Serial port to probe (e.g. ``COM5`` or ``/dev/ttyUSB0``). baudrate: Serial baud rate. - timeout: Seconds to wait for the connection and for the identity reply. + timeout: Seconds to bound the connection handshake and the identity reply. Returns: - The device's self-info dict on success (so the caller can also learn its mesh node - name from the same handshake), or ``None`` if it is not a reachable MeshCore - companion. + ``(device, self_info)`` with a connected :class:`MeshCoreDevice` on success (the + caller owns and must eventually close it), or ``None`` if the port is not a reachable + MeshCore companion. """ # ``timeout`` is the handshake window handed to the client, so a non-MeshCore port is # rejected in ~``timeout`` seconds and the client cleans up its own connection. The outer @@ -1699,15 +1710,21 @@ async def smoke_test_meshcore( # client mid-handshake (which would leak the open port). A real companion answers in well # under a second, so this never delays a good device. device = MeshCoreDevice(port=port, baudrate=baudrate, connect_timeout=timeout) - info: Optional[dict] = None try: await asyncio.wait_for(device.connect(), timeout + 4.0) info = await asyncio.wait_for(device.get_self_info(), timeout) except Exception: # noqa: BLE001 - any failure just means "not confirmed" - info = None - finally: - try: - await device.disconnect() - except Exception: # noqa: BLE001 - best-effort cleanup of the probe connection - pass - return dict(info) if info else None + await _safe_disconnect(device) + return None + if not info: + await _safe_disconnect(device) + return None + return device, dict(info) + + +async def _safe_disconnect(device: Device) -> None: + """Best-effort disconnect that never raises (used to discard a failed probe).""" + try: + await device.disconnect() + except Exception: # noqa: BLE001 - best-effort cleanup of the probe connection + pass diff --git a/meshterm/persistence/logging.py b/meshterm/persistence/logging.py index 8ab2002..6c98a95 100644 --- a/meshterm/persistence/logging.py +++ b/meshterm/persistence/logging.py @@ -85,8 +85,10 @@ def configure_logging( #: straight over the full-screen TUI. Routed to the file handler instead so they stay #: captured for debugging. ``meshcore`` is the notable offender: it calls #: ``logging.basicConfig(level=INFO)`` on import (e.g. "INFO:meshcore:Serial Connection -#: started"). -_LIBRARY_LOGGERS: tuple[str, ...] = ("meshcore",) +#: started"). ``asyncio`` is included so its default exception handler — the one that +#: reports stray background-task errors once prompt_toolkit's screen-dumping handler is +#: disabled — logs to the file instead of the console. +_LIBRARY_LOGGERS: tuple[str, ...] = ("meshcore", "asyncio") def _quiet_library_console(file_handler: logging.Handler) -> None: diff --git a/meshterm/ui/device_picker.py b/meshterm/ui/device_picker.py index 9815d76..3021fe2 100644 --- a/meshterm/ui/device_picker.py +++ b/meshterm/ui/device_picker.py @@ -32,6 +32,10 @@ if TYPE_CHECKING: #: connection layer. Verify = Callable[[DiscoveredDevice], Awaitable[Optional[dict]]] +#: The Quit row's value. Selecting it — like pressing Esc — leaves the splash without a +#: device, which the caller treats as "exit the program". +_QUIT = object() + def _copyright() -> str: """The splash's muted copyright line, dated to the current year.""" @@ -78,8 +82,9 @@ async def prompt_device( not a reachable MeshCore companion. Returns: - The chosen, confirmed :class:`DiscoveredDevice`, or ``None`` if the user skipped the - picker (e.g. pressed Esc to run against ``--mock`` / configure later). + The chosen, confirmed :class:`DiscoveredDevice`, or ``None`` if the user chose to + leave the picker without selecting one — by pressing Esc, choosing the Quit row, or + having no devices to pick — which the caller treats as a request to exit. """ if not devices: await ui.notify_startup( @@ -98,16 +103,25 @@ async def prompt_device( # Preselect the remembered "last known good" device when it is currently attached. default = next((d for d in devices if remembered and remembered.matches(d)), None) + # The copyright is a first-impression splash flourish: show it until the user commits to a + # device, then drop it for good — even if the smoke test fails and they return to re-pick. + footnote: Optional[str] = _copyright() + while True: chosen = await ui.select_startup( "Select a companion device", _build_items(devices, remembered, known), default=default, banner=load_logo(), - footnote=_copyright(), + footnote=footnote, ) - if chosen is None: + # Esc (``None``) and the Quit row both mean "leave the picker" — surface that to the + # caller as ``None`` so it can exit the program instead of continuing device-less. + if chosen is None or chosen is _QUIT: return None + # The user has committed to a device; retire the copyright from every screen after + # this point (the smoke-test spinner, any failure notice, and the re-opened picker). + footnote = None name = remembered.node_name if ( remembered and remembered.matches(chosen) and remembered.node_name @@ -119,7 +133,7 @@ async def prompt_device( verify(chosen), title="Checking companion", banner=load_logo(), - footnote=_copyright(), + footnote=footnote, ) if info is None: @@ -131,7 +145,7 @@ async def prompt_device( ), title="Not a MeshCore device", banner=load_logo(), - footnote=_copyright(), + footnote=footnote, ) continue @@ -151,7 +165,7 @@ def _build_items( The row for each device leads with its display name (the remembered node's name when known, else the hardware name); columns are padded to a shared width so they align. Devices already confirmed as MeshCore companions carry a bright tag; the remembered - default is starred. + default is starred. A trailing Quit row (like the menu's) lets the user exit from here. """ def _name(device: DiscoveredDevice) -> str: if remembered is not None and remembered.matches(device) and remembered.node_name: @@ -194,4 +208,8 @@ def _build_items( row.append(" ") row.append("· serial adapter", style="muted") items.append(Choice(title=row, value=device)) + # A trailing Quit row, mirroring the main menu, so exiting is an explicit choice as well + # as an Esc away — the leading spaces line it up under the device-name column. + items.append(Separator(" ")) + items.append(Choice(title=" quit", value=_QUIT)) return items diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index 7f39a2c..2c77461 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -102,8 +102,8 @@ async def run_menu(ctx: AppContext) -> None: async def main() -> None: try: - await _startup(ctx) - await _menu_loop(ctx, session) + if await _startup(ctx): + await _menu_loop(ctx, session) finally: # Stop history + chat recording (closing their run records) and the always-on # event hub, even on an unexpected exit. @@ -146,28 +146,45 @@ async def _menu_loop(ctx: AppContext, session: TuiSession) -> None: await _run_selection(ctx, selection) -async def _startup(ctx: AppContext) -> None: +async def _startup(ctx: AppContext) -> bool: """Pick a companion device (if needed) and resume passive monitoring. Args: ctx: The shared application context to update with the selection. + + Returns: + ``True`` to enter the menu, or ``False`` if the user chose to exit at the startup + splash (pressed Esc or picked Quit) — in which case the caller skips the menu loop. """ if not (ctx.mock or ctx.explicit_selection): - from ..core.connection import smoke_test_meshcore + from ..core.connection import probe_meshcore from ..core.discovery import DiscoveredDevice, discover_devices from .device_picker import prompt_device devices = discover_devices() baudrate = ctx.profile.baudrate if ctx.profile else 115200 + # The smoke test opens the radio; on success we keep that live connection and reuse + # it for the session rather than reopening (boards often reset on each serial open). + probed: dict = {} async def verify(device: DiscoveredDevice): - return await smoke_test_meshcore(device.port, baudrate) + result = await probe_meshcore(device.port, baudrate) + if result is None: + return None + connection, info = result + probed["port"] = device.port + probed["device"] = connection + return info chosen = await prompt_device(ctx.ui, devices, ctx.device_store, verify) - if chosen is not None: - ctx.selected_device = chosen - ctx.port_override = chosen.port + if chosen is None: + return False # the user quit at the splash — exit without opening the menu + ctx.selected_device = chosen + ctx.port_override = chosen.port + if probed.get("port") == chosen.port: + ctx.adopt_device(probed["device"]) await _resume_monitor(ctx) + return True async def _resume_monitor(ctx: AppContext) -> None: diff --git a/meshterm/ui/tui/__init__.py b/meshterm/ui/tui/__init__.py index 98d886f..c386cd0 100644 --- a/meshterm/ui/tui/__init__.py +++ b/meshterm/ui/tui/__init__.py @@ -16,14 +16,16 @@ from __future__ import annotations from .progress import ProgressScreen from .prompt import AutocompleteScreen, ConfirmScreen, TextScreen -from .screen import CANCEL, Screen, ScrollScreen +from .screen import CANCEL, BusyScreen, Screen, ScrollScreen from .select import Choice, SelectScreen, Separator from .session import TuiSession +from .spinner import Spinner __all__ = [ "TuiSession", "Screen", "ScrollScreen", + "BusyScreen", "SelectScreen", "Choice", "Separator", @@ -31,5 +33,6 @@ __all__ = [ "ConfirmScreen", "AutocompleteScreen", "ProgressScreen", + "Spinner", "CANCEL", ] diff --git a/meshterm/ui/tui/frame.py b/meshterm/ui/tui/frame.py index 29cc45b..c0814dc 100644 --- a/meshterm/ui/tui/frame.py +++ b/meshterm/ui/tui/frame.py @@ -158,6 +158,8 @@ def compose_startup(screen: Screen, cols: int, rows: int) -> str: An ANSI string of exactly ``rows`` lines, each within ``cols`` columns. """ banner = _banner_lines(screen.banner or [], cols) + banner_h = len(banner) + gap = 1 if banner else 0 # the blank line under the banner # Size the box to its widest real row (probe at a generous width, then measure), never # wider than the terminal and never narrower than the title/hint it must show. @@ -166,10 +168,16 @@ def compose_startup(screen: Screen, cols: int, rows: int) -> str: inner_w = max(measured, cell_len(screen.title), cell_len(screen.footer_hint)) inner_w = max(10, min(inner_w, cols - 6)) - # Leave room for the banner (and the blank line under it) plus the panel's own border. - reserved = len(banner) + (1 if banner else 0) + 2 + # Pin the banner to a fixed vertical anchor that depends only on the terminal height and + # the banner's own (constant) height, so the wordmark never moves as the box below it + # swaps contents between splash states (device list → spinner → message). The box hangs + # from just under the banner and only *it* grows or shrinks; the logo stays put. + top = max(0, rows // 2 - banner_h - gap) + footnote_h = 2 if screen.footnote else 0 # a blank spacer line plus the note itself + # Rows left for the box below the fixed banner block: the panel border is 2 rows. + below = rows - top - banner_h - gap body_lines = screen.render_body(inner_w) - viewport = max(1, min(len(body_lines), rows - reserved)) + viewport = max(1, min(len(body_lines), below - 2 - footnote_h)) visible, more_above, more_below = _visible_slice(screen, body_lines, viewport) body = Text.from_ansi("\n".join(visible)) @@ -193,8 +201,7 @@ def compose_startup(screen: Screen, cols: int, rows: int) -> str: note = Text.from_markup(f"[muted]{screen.footnote}[/muted]") footnote_lines = [""] + _center(render_lines(note, cell_len(screen.footnote)), cols) - block = banner + ([""] if banner else []) + panel_lines + footnote_lines - top = max(0, (rows - len(block)) // 2) + block = banner + ([""] * gap) + panel_lines + footnote_lines lines = [""] * top + block if len(lines) > rows: lines = lines[:rows] diff --git a/meshterm/ui/tui/screen.py b/meshterm/ui/tui/screen.py index 266df4f..248d560 100644 --- a/meshterm/ui/tui/screen.py +++ b/meshterm/ui/tui/screen.py @@ -19,6 +19,7 @@ from rich.console import RenderableType from rich.text import Text from .render import render_lines +from .spinner import Spinner #: Sentinel a screen resolves with when the user presses Esc to cancel, distinct from a #: legitimately selected ``None`` value. @@ -195,18 +196,16 @@ class ScrollScreen(Screen): class BusyScreen(Screen): - """A non-interactive splash body: an animated Braille spinner beside a message. + """A non-interactive splash body: an animated spinner beside a message. Used to keep the startup splash on screen — its wordmark and box unchanged — while a short async task runs (e.g. smoke-testing a chosen companion device). It set as a chromeless base so it redraws the same centered-under-the-wordmark splash, only swapping the box's contents. It resolves nothing and ignores every key; the session pops it when - the awaited task completes. + the awaited task completes. The animation itself is the reusable + :class:`~meshterm.ui.tui.spinner.Spinner`. """ - #: Braille-dot spinner frames, cycled on each :meth:`tick`. - _FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" - footer_hint = "working…" floating = False @@ -215,16 +214,15 @@ class BusyScreen(Screen): super().__init__() self.title = title self._message = message - self._frame = 0 + self._spinner = Spinner() def tick(self) -> None: """Advance the spinner to its next frame (driven by the session's animation timer).""" - self._frame = (self._frame + 1) % len(self._FRAMES) + self._spinner.tick() def render_body(self, width: int) -> list[str]: """Render the current spinner frame followed by the message.""" - line = Text() - line.append(self._FRAMES[self._frame], style="accent") + line = self._spinner.text() line.append(" ") line.append(self._message) return render_lines(line, width) diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index 1ce8e53..7bb25bb 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -217,6 +217,15 @@ class TuiSession: return await coro finally: ticker.cancel() + # Await the cancelled ticker so it is never garbage-collected while still + # pending: that surfaces as a screen-corrupting "Task was destroyed but it is + # pending!" loop error. The spinner is cosmetic, so any glitch is swallowed. + try: + await ticker + except asyncio.CancelledError: + pass + except Exception: # noqa: BLE001 - a spinner hiccup must never break startup + pass self.pop(screen) async def reorder(self, title: str, labels: list[str]) -> list[int]: @@ -306,7 +315,13 @@ class TuiSession: def pre_run() -> None: asyncio.ensure_future(driver()) - await self._app.run_async(pre_run=pre_run) + # Don't let prompt_toolkit install its own loop exception handler: on any stray + # background-task error it prints a traceback and a "Press ENTER to continue..." + # prompt straight over the full-screen UI. With it disabled, asyncio's default + # handler logs such errors to the ``asyncio`` logger instead, which is routed to the + # file log (see :func:`meshterm.persistence.logging.configure_logging`) and never + # touches the screen. Errors from ``main`` still propagate via ``driver``/``box``. + await self._app.run_async(pre_run=pre_run, set_exception_handler=False) if "exc" in box: raise box["exc"] diff --git a/meshterm/ui/tui/spinner.py b/meshterm/ui/tui/spinner.py new file mode 100644 index 0000000..396b06e --- /dev/null +++ b/meshterm/ui/tui/spinner.py @@ -0,0 +1,69 @@ +"""A reusable text spinner: one animated glyph for a "working" indicator. + +A small, screen-agnostic animation helper. It holds a cycle of frame glyphs and a current +position; a caller advances it with :meth:`tick` (typically from an animation timer) and +reads the current frame as a bare glyph or as a styled Rich :class:`~rich.text.Text`. The +busy splash uses it, but it is deliberately independent of any screen so any "working" +indicator across the toolkit can reuse the same animation. +""" + +from __future__ import annotations + +from typing import Optional + +from rich.text import Text + + +class Spinner: + """An animated spinner that cycles through a set of frame glyphs. + + Attributes: + style: The Rich style :meth:`text` applies to the current glyph. + """ + + #: The default Braille-dot frames — a smooth, single-cell rotation. + BRAILLE = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" + #: A plain ASCII cycle for terminals/fonts without Braille glyphs. + LINE = "|/-\\" + + def __init__(self, frames: str = BRAILLE, *, style: str = "accent") -> None: + """Create a spinner resting on its first frame. + + Args: + frames: The glyphs to cycle through, one per animation frame. + style: The Rich style :meth:`text` applies to the current glyph. + """ + if not frames: + raise ValueError("a spinner needs at least one frame") + self._frames = frames + self.style = style + self._index = 0 + + @property + def frame(self) -> str: + """The current frame's glyph.""" + return self._frames[self._index] + + @property + def frames(self) -> str: + """The full cycle of frame glyphs, in order.""" + return self._frames + + def tick(self) -> None: + """Advance to the next frame, wrapping around at the end of the cycle.""" + self._index = (self._index + 1) % len(self._frames) + + def reset(self) -> None: + """Return the spinner to its first frame.""" + self._index = 0 + + def text(self, style: Optional[str] = None) -> Text: + """Return the current glyph as a styled Rich :class:`~rich.text.Text`. + + Args: + style: A style to use instead of the spinner's own :attr:`style`. + + Returns: + The current glyph, styled. + """ + return Text(self.frame, style=self.style if style is None else style) diff --git a/tests/test_skeleton.py b/tests/test_skeleton.py index 262915f..0577e1f 100644 --- a/tests/test_skeleton.py +++ b/tests/test_skeleton.py @@ -183,6 +183,33 @@ def test_parse_trace_path_rejects_unknown_token() -> None: trace_runner.parse_trace_path(" ", contacts=[]) +async def test_adopt_device_is_reused_without_reopening(tmp_path: Path) -> None: + """A device adopted from the startup probe is returned by ``device()`` as-is.""" + from rich.console import Console + + from meshterm.context import AppContext + from meshterm.core.admin_store import AdminStore + from meshterm.core.config import Settings + from meshterm.core.device_store import DeviceStore + + settings = Settings(config_dir=tmp_path, db_path=tmp_path / "adopt.db") + ctx = AppContext( + console=Console(file=__import__("io").StringIO()), + settings=settings, + repo=Repository(settings.db_path), + device_store=DeviceStore(tmp_path / "devices.json"), + admin_store=AdminStore(tmp_path / "admin.json"), + ) + try: + adopted = MockDevice() + await adopted.connect() + ctx.adopt_device(adopted) + # ``device()`` must hand back the very connection we adopted — never open another. + assert await ctx.device() is adopted + finally: + ctx.repo.close() + + async def test_mock_device_honors_forced_path() -> None: """A forced path drives the repeater hops; a return-to-us hop is appended.""" device = MockDevice() diff --git a/tests/test_tui.py b/tests/test_tui.py index c755d3c..ff7325b 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -315,10 +315,16 @@ def test_device_picker_builds_aligned_columns(tmp_path) -> None: # A copyright footnote rides along for the splash to render below the box. assert "Homestead" in captured["footnote"] # Each device row's port sits at the same column, proving the name column is padded. - rows = [it.label.plain for it in captured["items"] if isinstance(it, Choice)] - assert len(rows) == 2 - assert all(port in row for port, row in zip(("COM5", "/dev/ttyUSB0"), rows)) - assert rows[0].index("COM5") == rows[1].index("/dev/ttyUSB0") + rows = [ + it.label.plain if hasattr(it.label, "plain") else it.label + for it in captured["items"] + if isinstance(it, Choice) + ] + assert len(rows) == 3 # two devices plus a trailing Quit row (like the main menu) + assert rows[-1].strip() == "quit" + device_rows = rows[:2] + assert all(port in row for port, row in zip(("COM5", "/dev/ttyUSB0"), device_rows)) + assert device_rows[0].index("COM5") == device_rows[1].index("/dev/ttyUSB0") class _PickerUi: @@ -361,6 +367,63 @@ def test_device_picker_smoke_tests_and_reprompts(tmp_path) -> None: assert store.is_known(devices[0]) +def test_device_picker_drops_copyright_after_first_selection(tmp_path) -> None: + """The copyright shows on the opening splash, then never again — even on a re-pick.""" + from meshterm.core.device_store import DeviceStore + from meshterm.core.discovery import DiscoveredDevice + from meshterm.ui.device_picker import prompt_device + + devices = [DiscoveredDevice(port="COM5", serial_number="SN1", product="Wio SX1262")] + store = DeviceStore(tmp_path / "devices.json") + footnotes: list = [] + + class _Ui: + async def select_startup(self, title, items, *, default=None, banner=None, footnote=None): + footnotes.append(("select", footnote)) + return next(it.value for it in items if isinstance(it, Choice)) + + async def notify_startup(self, renderable, *, title="", banner=None, footnote=None): + footnotes.append(("notify", footnote)) + + async def busy_startup(self, message, coro, *, title="", banner=None, footnote=None): + footnotes.append(("busy", footnote)) + return await coro + + # First probe fails (re-pick), second passes — exercising every post-selection screen. + results = [None, {"adv_name": "BaseStation"}] + + async def verify(_device): + return results.pop(0) + + asyncio.run(prompt_device(_Ui(), devices, store, verify)) + # Only the very first splash carries the copyright; the busy spinner, the failure + # notice, and the re-opened picker all drop it. + assert footnotes[0][0] == "select" and "Homestead" in footnotes[0][1] + assert all(footnote is None for _kind, footnote in footnotes[1:]) + + +def test_device_picker_quit_row_returns_none(tmp_path) -> None: + """Choosing the trailing Quit row leaves the picker (None) without a smoke test.""" + from meshterm.core.device_store import DeviceStore + from meshterm.core.discovery import DiscoveredDevice + from meshterm.ui.device_picker import _QUIT, prompt_device + + devices = [DiscoveredDevice(port="COM5", product="Wio SX1262")] + + class _QuitUi: + async def select_startup(self, title, items, *, default=None, banner=None, footnote=None): + # The last choice is the Quit row; picking it signals "exit". + quit_choice = [it for it in items if isinstance(it, Choice) and it.value is _QUIT] + assert quit_choice, "the picker offers a Quit row" + return quit_choice[0].value + + async def _never(_device): + raise AssertionError("verify must not run when the user quits") + + store = DeviceStore(tmp_path / "devices.json") + assert asyncio.run(prompt_device(_QuitUi(), devices, store, _never)) is None + + # --- busy splash -------------------------------------------------------------- @@ -369,6 +432,7 @@ def test_busy_screen_spins_over_its_message() -> None: from rich.text import Text as RichText from meshterm.ui.tui.screen import BusyScreen + from meshterm.ui.tui.spinner import Spinner screen = BusyScreen("Talking to Wio on COM5…") @@ -378,14 +442,30 @@ def test_busy_screen_spins_over_its_message() -> None: plain = RichText.from_ansi("\n".join(screen.render_body(60))).plain assert "Talking to Wio on COM5" in plain - assert glyph() in BusyScreen._FRAMES # a spinner glyph leads the line + assert glyph() in Spinner.BRAILLE # a spinner glyph leads the line # Ticking cycles through every frame and returns to the first. seen = {glyph()} - for _ in range(len(BusyScreen._FRAMES) - 1): + for _ in range(len(Spinner.BRAILLE) - 1): screen.tick() seen.add(glyph()) - assert seen == set(BusyScreen._FRAMES) + assert seen == set(Spinner.BRAILLE) + + +def test_spinner_cycles_and_resets() -> None: + """The reusable Spinner advances through its frames, wraps, and resets.""" + from meshterm.ui.tui.spinner import Spinner + + spinner = Spinner("ab", style="warn") + assert spinner.frame == "a" + assert spinner.text().plain == "a" and spinner.text().style == "warn" + spinner.tick() + assert spinner.frame == "b" + spinner.tick() # wraps back to the first frame + assert spinner.frame == "a" + spinner.tick() + spinner.reset() + assert spinner.frame == "a" # --- progress ----------------------------------------------------------------