diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py index 14ebf01..7797b66 100644 --- a/meshterm/core/connection.py +++ b/meshterm/core/connection.py @@ -78,6 +78,17 @@ class DeviceCommandError(RuntimeError): """ +class DeviceAuthenticationError(DeviceCommandError): + """A Bluetooth companion refused the connection because it needs a pairing PIN/bond. + + A distinct :class:`DeviceCommandError` subclass so callers can tell "this device needs a + PIN" apart from an ordinary command failure and offer to collect one: the interactive + picker opens a PIN dialog and retries, while the scripted CLI (which catches the base + class) prints the message and bails, since it can't prompt. The message already names the + fix (``--ble-pin`` and OS pairing). + """ + + #: Exception class names that signal the link to the companion has dropped — the device was #: unplugged, powered off, moved out of range, or its port/transport otherwise vanished — as #: opposed to an ordinary command-level failure. Matched by name in :func:`is_connection_lost` @@ -697,7 +708,7 @@ class MeshCoreDevice(Device): # propagates unchanged so genuine link-loss still flows to is_connection_lost. if not _is_ble_auth_error(exc): raise - raise DeviceCommandError(self._ble_auth_message()) from exc + raise DeviceAuthenticationError(self._ble_auth_message()) from exc def _ble_auth_message(self) -> str: """A clean, actionable error for a Bluetooth companion that requires a PIN/bond. diff --git a/meshterm/ui/device_picker.py b/meshterm/ui/device_picker.py index c0b9002..1967c89 100644 --- a/meshterm/ui/device_picker.py +++ b/meshterm/ui/device_picker.py @@ -25,7 +25,7 @@ from typing import TYPE_CHECKING, Awaitable, Callable, Optional from rich.cells import cell_len from rich.text import Text -from ..core.connection import DeviceCommandError +from ..core.connection import DeviceAuthenticationError, DeviceCommandError from ..core.device_store import DeviceStore, RememberedDevice from ..core.discovery import DiscoveredDevice from .logo import load_logo @@ -34,12 +34,13 @@ from .tui import Choice, Separator if TYPE_CHECKING: from .surface import Ui -#: A smoke test: probe a chosen device and return its self-info dict if it is a MeshCore -#: companion, else ``None``. Supplied by the caller so this UI module stays free of the -#: connection *logic*. It may raise :class:`DeviceCommandError` for an actionable failure the -#: user can fix (e.g. a Bluetooth device that needs a PIN); the picker shows that message -#: verbatim instead of the generic "didn't answer". -Verify = Callable[[DiscoveredDevice], Awaitable[Optional[dict]]] +#: A smoke test: probe a chosen device with an optional Bluetooth PIN and return its self-info +#: dict if it is a MeshCore companion, else ``None``. Supplied by the caller so this UI module +#: stays free of the connection *logic*. It may raise :class:`DeviceAuthenticationError` when +#: the device needs a PIN (the picker then collects one and retries with it), or another +#: :class:`DeviceCommandError` for a different actionable failure (shown verbatim). The second +#: argument is the PIN to try, or ``None`` to use whatever default the caller holds. +Verify = Callable[[DiscoveredDevice, Optional[str]], 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". @@ -152,6 +153,95 @@ def _model_from(info: dict) -> str: return str(info.get("model") or "") +async def _smoke_test( + ui: "Ui", + chosen: DiscoveredDevice, + name: str, + where: str, + verify: Verify, + footnote: Optional[str], +) -> Optional[dict]: + """Smoke-test ``chosen`` behind the splash spinner, collecting a Bluetooth PIN if needed. + + Runs the ``verify`` probe on the chromeless splash (its wordmark and box unchanged, only an + animated spinner where the device list was). If the device answers but demands a pairing + PIN, opens the :class:`~meshterm.ui.tui.prompt.PinDialog` popup and retries with what the + user enters — re-opening it with a "rejected" note on a wrong code — until the device + connects or the user presses Esc. + + Args: + ui: The interactive surface used for the spinner, PIN dialog, and failure notices. + chosen: The device being tested. + name: Its display name, woven into the spinner line and the PIN prompt. + where: A human phrase for its transport ("over Bluetooth" / "on COM5"). + verify: The smoke-test callback (see :data:`Verify`); called with the PIN to try. + footnote: The splash footnote to keep drawn under the box (``None`` after the copyright + is retired). + + Returns: + The device's self-info dict once it answers, or ``None`` — after showing the relevant + notice — to send the user back to the device list (not a MeshCore endpoint, an + unrecoverable failure, or a cancelled PIN prompt). + """ + pin: Optional[str] = None + pin_error = "" # empty on the first ask; set once a PIN has been rejected + while True: + # BLE connect and service discovery take a few seconds, so the spinner matters most here. + try: + info = await ui.busy_startup( + f"Talking to {name} {where}…", + verify(chosen, pin), + title="Checking companion", + banner=load_logo(), + footnote=footnote, + ) + except DeviceAuthenticationError: + # The device answered the scan but won't connect until it's bonded (or the last PIN + # was wrong). Collect one in the popup and loop to retry; Esc returns to the list. + entered = await ui.prompt_pin_startup( + name, + error=pin_error, + help_text="The 6-digit code shown on the device or in the MeshCore app.", + banner=load_logo(), + footnote=footnote, + ) + if entered is None: + return None # the user gave up → back to the device list + pin = entered + pin_error = "That PIN was rejected — check the code and try again." + continue + except DeviceCommandError as exc: + # A different actionable failure (not a PIN): show its remedy verbatim, then back to + # the list. Plain styled text so the message's own punctuation isn't parsed as markup. + notice = Text() + notice.append(str(exc), style="warn") + notice.append("\nChoose another device.") + await ui.notify_startup( + notice, title="Can't connect yet", banner=load_logo(), footnote=footnote + ) + return None + + if info is None: + reason = ( + "It may be out of range, powered off, already connected elsewhere, or busy." + if chosen.is_ble + else "It may be a different kind of serial device, powered off, or busy." + ) + await ui.notify_startup( + Text.from_markup( + f"[warn]{name} {where} didn't answer as a MeshCore device.[/warn]\n" + f"{reason}\n" + "Choose another device." + ), + title="Not a MeshCore device", + banner=load_logo(), + footnote=footnote, + ) + return None + + return info + + async def prompt_device( ui: "Ui", devices: list[DiscoveredDevice], @@ -221,49 +311,10 @@ async def prompt_device( name = _display_name(chosen, registry) # "over Bluetooth" reads better than an address; a serial device names its port. where = "over Bluetooth" if chosen.is_ble else f"on {chosen.port}" - # Smoke-test the choice in place: the splash keeps its wordmark and box, only the box - # contents swap for an animated spinner while we talk to the device. BLE connect and - # service discovery take a few seconds, so the spinner matters most here. - try: - info = await ui.busy_startup( - f"Talking to {name} {where}…", - verify(chosen), - title="Checking companion", - banner=load_logo(), - footnote=footnote, - ) - except DeviceCommandError as exc: - # The probe reached the device but it told us how it must be reached (e.g. it needs - # a BLE PIN). Show that remedy verbatim — not the generic "didn't answer" below, - # which would leave the user with no idea a PIN was the missing piece. Built as - # plain styled text so the message's own punctuation is never parsed as markup. - notice = Text() - notice.append(str(exc), style="warn") - notice.append("\nChoose another device.") - await ui.notify_startup( - notice, - title="Can't connect yet", - banner=load_logo(), - footnote=footnote, - ) - continue - + # Smoke-test the choice in place (prompting for a PIN and retrying if it needs one). + # ``None`` means the smoke test failed and already showed the user why — pick again. + info = await _smoke_test(ui, chosen, name, where, verify, footnote) if info is None: - reason = ( - "It may be out of range, powered off, already connected elsewhere, or busy." - if chosen.is_ble - else "It may be a different kind of serial device, powered off, or busy." - ) - await ui.notify_startup( - Text.from_markup( - f"[warn]{name} {where} didn't answer as a MeshCore device.[/warn]\n" - f"{reason}\n" - "Choose another device." - ), - title="Not a MeshCore device", - banner=load_logo(), - footnote=footnote, - ) continue # Confirmed: remember it forever. We return straight away, so there's no need to diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index 0117c08..e341d65 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -16,7 +16,7 @@ import sys import threading import time from contextlib import contextmanager -from typing import Iterator +from typing import Iterator, Optional from rich.logging import RichHandler from rich.text import Text @@ -284,8 +284,12 @@ async def _startup(ctx: AppContext) -> bool: # it for the session rather than reopening (boards often reset on each open). probed: dict = {} - async def verify(device: DiscoveredDevice): - result = await probe_device(device, baudrate=baudrate, pin=ctx.ble_pin) + async def verify(device: DiscoveredDevice, pin: Optional[str] = None): + # ``pin`` is what the picker's PIN dialog collected on a retry; fall back to any + # ``--ble-pin`` supplied on the CLI for the first attempt. + result = await probe_device( + device, baudrate=baudrate, pin=pin if pin is not None else ctx.ble_pin + ) if result is None: return None connection, info = result diff --git a/meshterm/ui/surface.py b/meshterm/ui/surface.py index b82c7d7..9c51e7f 100644 --- a/meshterm/ui/surface.py +++ b/meshterm/ui/surface.py @@ -94,6 +94,18 @@ class Ui: """Await ``coro`` while showing a spinner on the startup splash; return its result.""" raise NotImplementedError + async def prompt_pin_startup( + self, + device_name: str, + *, + error: str = "", + help_text: str = "", + banner: Any = None, + footnote: Optional[str] = None, + ) -> Optional[str]: + """Ask for a Bluetooth companion's pairing PIN on the startup splash; ``None`` if cancelled.""" + raise NotImplementedError + async def reorder(self, title: str, labels: list[str]) -> list[int]: """Let the user rearrange rows with the arrows; return the new order of row indices.""" raise NotImplementedError @@ -207,6 +219,22 @@ class PlainUi(Ui): """No splash in scripted CLI mode; just await the task and return its result.""" return await coro + async def prompt_pin_startup( + self, + device_name: str, + *, + error: str = "", + help_text: str = "", + banner: Any = None, + footnote: Optional[str] = None, + ) -> Optional[str]: + """Unsupported in scripted CLI mode — a PIN must be supplied non-interactively. + + The scripted path can't pop a dialog, so a PIN-protected device is handled by the + clean ``DeviceAuthenticationError`` message (pass ``--ble-pin``) rather than a prompt. + """ + raise self._no_prompt() + async def reorder(self, title: str, labels: list[str]) -> list[int]: """Unsupported in scripted CLI mode.""" raise self._no_prompt() @@ -364,6 +392,20 @@ class TuiUi(Ui): message, coro, title=title, banner=banner, footnote=footnote ) + async def prompt_pin_startup( + self, + device_name: str, + *, + error: str = "", + help_text: str = "", + banner: Any = None, + footnote: Optional[str] = None, + ) -> Optional[str]: + """Delegate to the session's startup PIN dialog.""" + return await self.session.prompt_pin_startup( + device_name, error=error, help_text=help_text, banner=banner, footnote=footnote + ) + async def reorder(self, title: str, labels: list[str]) -> list[int]: """Delegate to the session's reorder screen.""" return await self.session.reorder(title, labels) diff --git a/meshterm/ui/tui/prompt.py b/meshterm/ui/tui/prompt.py index 940f0cc..75fac2b 100644 --- a/meshterm/ui/tui/prompt.py +++ b/meshterm/ui/tui/prompt.py @@ -193,6 +193,65 @@ class TextScreen(Screen): self._error = "" +class PinDialog(Screen): + """A startup popup that collects a Bluetooth pairing PIN, re-asking on a rejected code. + + Shown by the device picker when a chosen companion answers the scan but refuses the GATT + connection until it is bonded. It presents a masked field centered in its own bordered box + under the wordmark — the same chromeless-splash presentation as the picker and its spinner + — so it reads as one more step of the startup flow rather than a context switch. + + It only *collects* a PIN; verifying it means actually opening the BLE connection, which the + picker does. So a rejected code isn't detected here — the picker catches the authentication + failure and re-opens this dialog with ``error`` set, which is why the field starts empty each + time. Resolves with the entered PIN, or :data:`CANCEL` on Esc (the user gave up — the picker + returns them to the device list). + """ + + footer_hint = "Enter connect · Esc cancel" + + def __init__(self, device_name: str, *, error: str = "", help_text: str = "") -> None: + """Build the PIN dialog. + + Args: + device_name: The companion's display name, woven into the prompt. + error: A message shown in the error style — set by the picker on a re-ask after a + rejected PIN; empty on the first ask. + help_text: A muted hint under the field (e.g. where to read the code). + """ + super().__init__() + self.title = "Bluetooth PIN required" + self._device = device_name + self._error = error + self._help = help_text + self._editor = _LineEditor("") + + def render_body(self, width: int) -> list[str]: + """Render the prompt, the masked field, any hint, and a rejected-PIN error.""" + prompt = Text() + prompt.append(self._device, style="brand") + prompt.append(" needs a pairing PIN to connect.") + parts: list[RenderableType] = [prompt, Text(""), self._editor.render(mask=True)] + if self._help: + parts.append(Text(self._help, style="muted")) + if self._error: + parts.append(Text(self._error, style="err")) + return render_lines(Group(*parts), width) + + def handle(self, action: str, data: str = "") -> None: + """Edit the field, submit a non-empty PIN on Enter, or cancel on Esc.""" + if action == "enter": + pin = self._editor.text.strip() + if not pin: # an empty PIN can't be right — nudge rather than pointlessly retry + self._error = "Enter the PIN, or press Esc to cancel." + return + self.resolve(pin) + elif action == "escape": + super().handle("escape") + elif self._editor.edit(action, data): + self._error = "" + + class ConfirmScreen(Screen): """A yes/no prompt. Resolves with a bool, or CANCEL on Esc.""" diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index 4a214be..56d3557 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -26,7 +26,14 @@ from rich.text import Text from . import frame from .progress import TuiProgress -from .prompt import AutocompleteScreen, ButtonDialog, ConfirmScreen, TextScreen, Validator +from .prompt import ( + AutocompleteScreen, + ButtonDialog, + ConfirmScreen, + PinDialog, + TextScreen, + Validator, +) from .screen import CANCEL, BusyScreen, Screen, ScrollScreen from .select import Choice, ReorderScreen, SelectScreen, Separator @@ -309,6 +316,38 @@ class TuiSession: pass self.pop(screen) + async def prompt_pin_startup( + self, + device_name: str, + *, + error: str = "", + help_text: str = "", + banner: Optional[Any] = None, + footnote: Optional[str] = None, + ) -> Optional[str]: + """Ask for a companion's Bluetooth PIN on the chromeless startup splash. + + Drawn like :meth:`notify_startup` / :meth:`select_startup` — a bordered box centered + under ``banner`` with no status bars — so the PIN request is visually part of the same + device-selection flow. ``error`` is shown in the box on a re-ask after a rejected code. + + Args: + device_name: The companion's display name, shown in the prompt. + error: A rejected-PIN message to display (empty on the first ask). + help_text: A muted hint under the field. + banner: Wordmark rows drawn above the box (as on the other startup splashes). + footnote: Muted line drawn below the box. + + Returns: + The entered PIN, or ``None`` if the user pressed Esc to cancel. + """ + screen = PinDialog(device_name, error=error, help_text=help_text) + screen.chrome = False + screen.banner = banner + screen.footnote = footnote + result = await self.run_screen(screen) + return None if result is CANCEL else result + async def reorder(self, title: str, labels: list[str]) -> list[int]: """Show a drag-with-arrows reorder screen; return the final order of row indices.""" result = await self.run_screen(ReorderScreen(title, labels)) diff --git a/tests/test_disconnect.py b/tests/test_disconnect.py index fe44180..df050a5 100644 --- a/tests/test_disconnect.py +++ b/tests/test_disconnect.py @@ -116,24 +116,26 @@ def test_ble_auth_error_walks_the_exception_chain() -> None: async def test_create_ble_translates_auth_error_to_pin_guidance() -> None: - """A raw GATT auth rejection becomes a clean DeviceCommandError that names the PIN fix.""" + """A raw GATT auth rejection becomes a DeviceAuthenticationError that names the PIN fix.""" class _FakeMeshCore: @staticmethod async def create_ble(**kwargs): raise BleakGATTProtocolError("Insufficient Authentication") - # No PIN supplied → tell the user to pass one. + # No PIN supplied → tell the user to pass one. The subclass lets the interactive picker + # catch "needs a PIN" specifically, while the CLI still catches it as DeviceCommandError. dev = connection.MeshCoreDevice(transport="ble", address="00:11:22:33:44:55") - with pytest.raises(DeviceCommandError) as excinfo: + with pytest.raises(connection.DeviceAuthenticationError) as excinfo: await dev._create_ble(_FakeMeshCore) + assert isinstance(excinfo.value, DeviceCommandError) # so the scripted CLI catches it too assert "--ble-pin" in str(excinfo.value) # PIN supplied but rejected → say it was wrong, not that none was given. dev_pin = connection.MeshCoreDevice( transport="ble", address="00:11:22:33:44:55", pin="123456" ) - with pytest.raises(DeviceCommandError) as excinfo_pin: + with pytest.raises(connection.DeviceAuthenticationError) as excinfo_pin: await dev_pin._create_ble(_FakeMeshCore) assert "rejected" in str(excinfo_pin.value).lower() diff --git a/tests/test_tui.py b/tests/test_tui.py index 0fe49e1..bbc5686 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -611,7 +611,7 @@ def test_device_picker_smoke_tests_and_reprompts(tmp_path) -> None: # First probe fails (not MeshCore), second answers with self-info. results = [None, {"adv_name": "BaseStation"}] - async def verify(_device): + async def verify(_device, _pin=None): return results.pop(0) chosen = asyncio.run(prompt_device(ui, devices, store, verify)) @@ -647,7 +647,7 @@ def test_device_picker_drops_copyright_after_first_selection(tmp_path) -> None: # First probe fails (re-pick), second passes — exercising every post-selection screen. results = [None, {"adv_name": "BaseStation"}] - async def verify(_device): + async def verify(_device, _pin=None): return results.pop(0) asyncio.run(prompt_device(_Ui(), devices, store, verify)) @@ -657,6 +657,90 @@ def test_device_picker_drops_copyright_after_first_selection(tmp_path) -> None: assert all(footnote is None for _kind, footnote in footnotes[1:]) +def test_device_picker_prompts_and_retries_ble_pin(tmp_path) -> None: + """A PIN-protected device opens the popup, re-asks on a wrong code, then connects.""" + from meshterm.core.connection import DeviceAuthenticationError + from meshterm.core.device_store import DeviceStore + from meshterm.core.discovery import DiscoveredDevice + from meshterm.ui.device_picker import prompt_device + + devices = [ + DiscoveredDevice(transport="ble", address="00:11:22:33:44:55", name="MeshCore-Pinned") + ] + store = DeviceStore(tmp_path / "devices.json") + + entered = iter(["000000", "654321"]) # a wrong code, then the right one + errors: list = [] + + class _Ui: + async def select_startup(self, title, items, *, default=None, banner=None, footnote=None): + return next(it.value for it in items if isinstance(it, Choice)) + + async def notify_startup(self, renderable, *, title="", banner=None, footnote=None): + raise AssertionError("a successful PIN connect shows no failure notice") + + async def busy_startup(self, message, coro, *, title="", banner=None, footnote=None): + return await coro + + async def prompt_pin_startup( + self, device_name, *, error="", help_text="", banner=None, footnote=None + ): + errors.append(error) + return next(entered) + + async def verify(_device, pin=None): + if pin != "654321": # the first probe (no PIN) and the wrong code both get rejected + raise DeviceAuthenticationError("needs a Bluetooth pairing PIN") + return {"adv_name": "Pinned", "model": "Seeed Tracker T1000-E"} + + chosen = asyncio.run(prompt_device(_Ui(), devices, store, verify)) + assert chosen is devices[0] + # Asked twice: first with no error, then with a "rejected" note after the wrong code. + assert errors[0] == "" + assert "rejected" in errors[1].lower() + remembered = store.load() + assert remembered is not None + assert remembered.node_name == "Pinned" + assert remembered.hardware_model == "Seeed Tracker T1000-E" # learned once connected + + +def test_device_picker_pin_cancel_returns_to_list(tmp_path) -> None: + """Esc on the PIN popup returns to the device list instead of connecting.""" + from meshterm.core.connection import DeviceAuthenticationError + from meshterm.core.device_store import DeviceStore + from meshterm.core.discovery import DiscoveredDevice + from meshterm.ui.device_picker import _QUIT, prompt_device + + devices = [ + DiscoveredDevice(transport="ble", address="00:11:22:33:44:55", name="MeshCore-Pinned") + ] + store = DeviceStore(tmp_path / "devices.json") + picks = iter([0, "quit"]) # pick the device once, then quit the re-opened list + + class _Ui: + async def select_startup(self, title, items, *, default=None, banner=None, footnote=None): + choices = [it for it in items if isinstance(it, Choice)] + step = next(picks) + if step == "quit": + return next(it.value for it in choices if it.value is _QUIT) + return choices[step].value + + async def busy_startup(self, message, coro, *, title="", banner=None, footnote=None): + return await coro + + async def prompt_pin_startup( + self, device_name, *, error="", help_text="", banner=None, footnote=None + ): + return None # the user cancels the PIN entry + + async def verify(_device, pin=None): + raise DeviceAuthenticationError("needs a Bluetooth pairing PIN") + + result = asyncio.run(prompt_device(_Ui(), devices, store, verify)) + assert result is None # cancelling the PIN then quitting leaves the picker empty-handed + assert store.load() is None # nothing was remembered + + 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