Add "Unpair & quit" to drop a BLE bond on exit

The quit dialog grows a third button, shown only when the session is on a
Bluetooth link that Windows actually holds a bond for (never serial, an open
PIN-less companion, or a non-Windows platform). Choosing it disconnects the
link and then drops the OS-level pairing during teardown, so the next launch
re-runs the PIN ceremony. MeshTerm's remembered-device record is deliberately
kept — unpairing forgets the credential, not the device identity.

Backing this: static WinRT helpers is_ble_paired / unpair_ble mirroring
_pair_ble_windows (Windows-gated, best-effort), an active_address on the
context, and _can_unpair / _unpair_on_exit in the menu.

Also close the WinRT BluetoothLEDevice handles in every helper. Each
from_bluetooth_address_async returns an IClosable that pins the OS ACL link
open; unpair removes the bond but not the link, so a leaked handle left the
device "unpaired but still connected" and refusing to re-pair until it was
power-cycled. Closing the handle in a finally is what finally tears the link
down.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 4.8 committed 2026-07-09 20:46:02 -04:00
1 parent 0d2ffac70f
commit 12577a1538
4 files changed
+267 -6

No files matched your search

+13
View File
@@ -69,6 +69,7 @@ class AppContext:
_active_port: Optional[str] = field(default=None, init=False, repr=False)
_active_transport: Optional[str] = field(default=None, init=False, repr=False)
_active_address: Optional[str] = field(default=None, init=False, repr=False)
unpair_on_exit: bool = field(default=False, init=False, repr=False)
_resume_intent: Optional[tuple[bool, bool, bool]] = field(
default=None, init=False, repr=False
)
@@ -100,6 +101,18 @@ class AppContext:
return None
return self._active_port or self.port_override
@property
def active_address(self) -> Optional[str]:
"""The Bluetooth address of the current BLE connection, if any (``None`` otherwise).
Set when a real *BLE* connection is opened, so post-session teardown (e.g. the quit
dialog's unpair step) can address the peripheral even after the device handle is torn
down. ``None`` for the simulator and for serial connections, which have no BLE address.
"""
if self.mock or self.active_transport != "ble":
return None
return self._active_address or self.ble_override
@property
def active_transport(self) -> Optional[str]:
"""The transport of the current/selected connection: ``"serial"``, ``"ble"``, or ``None``.
+123
View File
@@ -791,6 +791,7 @@ class MeshCoreDevice(Device):
_log.debug("BLE PIN pairing unavailable (winrt import failed): %s", exc)
return False
device = None
try:
device = await BluetoothLEDevice.from_bluetooth_address_async(address)
if device is None:
@@ -802,6 +803,7 @@ class MeshCoreDevice(Device):
# Tear the stale bond down, then re-fetch: the pairing object is a snapshot and
# won't reflect the unpair, so a fresh device_information is needed to re-pair.
await pairing.unpair_async()
MeshCoreDevice._close_ble_device(device) # release the pre-unpair handle
device = await BluetoothLEDevice.from_bluetooth_address_async(address)
if device is None:
return False
@@ -833,6 +835,8 @@ class MeshCoreDevice(Device):
except Exception as exc: # noqa: BLE001 - best-effort; caller falls through on False
_log.debug("BLE ProvidePin pairing attempt failed for %s: %s", self._address, exc)
return False
finally:
MeshCoreDevice._close_ble_device(device)
@staticmethod
def _ble_address_int(address: str) -> Optional[int]:
@@ -853,6 +857,125 @@ class MeshCoreDevice(Device):
except ValueError:
return None
@staticmethod
def _close_ble_device(device) -> None: # noqa: ANN001 - winrt BluetoothLEDevice
"""Release a WinRT ``BluetoothLEDevice`` handle, dropping the OS's link to the peripheral.
Every ``BluetoothLEDevice.from_bluetooth_address_async`` hands back an ``IClosable`` that
pins the operating system's ACL connection to the radio open for as long as the object is
alive. Unpairing removes the *bond* but never tears down that *link* — the link only goes
away when the last handle to it closes. If we leak the handle, Windows reports the device
as still "connected" (just unpaired), the peripheral never sees a clean disconnect, and it
refuses to re-pair until it is power-cycled. So every helper that opens one of these must
close it, even on the error paths.
Best-effort and silent: a missing ``close`` projection or a double-close is not worth
surfacing during teardown.
"""
try:
if device is not None:
device.close()
except Exception as exc: # noqa: BLE001 - releasing a handle must never raise
_log.debug("BLE device handle close failed: %s", exc)
@staticmethod
async def is_ble_paired(address: str) -> bool:
"""Whether Windows currently holds a bond for the BLE peripheral at ``address``.
The read-only companion to :meth:`_pair_ble_windows` / :meth:`unpair_ble`: it asks
WinRT whether an OS-level pairing exists, so the UI can decide whether an "unpair"
affordance is meaningful (a device bonded with a PIN) or moot (an open companion that
never bonded, or a serial link). It reflects the *OS bond*, not MeshTerm's remembered
record — the two are independent — and holds true across sessions even when this run
supplied no PIN, because Windows persists the bond.
Best-effort and self-contained: returns ``False`` (rather than raising) off Windows,
when the winrt projection is unavailable, when the address isn't a parseable MAC, or on
any WinRT hiccup — so a caller can treat it as a plain "is there anything to unpair?".
Args:
address: The Bluetooth MAC (``AA:BB:CC:DD:EE:FF`` or dash-separated) to query.
Returns:
``True`` only when Windows reports a live bond for the device.
"""
if sys.platform != "win32":
return False
addr = MeshCoreDevice._ble_address_int(address or "")
if addr is None:
return False
try:
from winrt.windows.devices.bluetooth import BluetoothLEDevice
except Exception as exc: # noqa: BLE001 - winrt projection unavailable; nothing to unpair
_log.debug("BLE pairing query unavailable (winrt import failed): %s", exc)
return False
device = None
try:
device = await BluetoothLEDevice.from_bluetooth_address_async(addr)
if device is None:
return False
return bool(device.device_information.pairing.is_paired)
except Exception as exc: # noqa: BLE001 - a status hiccup is not a bond
_log.debug("BLE pairing query failed for %s: %s", address, exc)
return False
finally:
MeshCoreDevice._close_ble_device(device)
@staticmethod
async def unpair_ble(address: str) -> bool:
"""Drop the Windows OS-level bond for the BLE peripheral at ``address`` (Windows only).
The inverse of :meth:`_pair_ble_windows`: it removes the persisted
``ENCRYPTION_AND_AUTHENTICATION`` bond so the next connection has to re-run the PIN
ceremony from scratch — the "forget this pairing" primitive behind the quit dialog's
*Unpair & quit*. It touches only the OS bond, never MeshTerm's remembered-device record,
which is deliberately left intact (the device keeps its friendly name and stays in the
picker; it just asks for its PIN again next time).
Call it only *after* the companion link is torn down — you can't cleanly drop a bond that
an open connection is still using. Best-effort and self-contained: returns a bool rather
than raising, and no-ops (returns ``False``) off Windows, when winrt is unavailable, when
the address isn't a MAC, or when there is no bond to remove.
Args:
address: The Bluetooth MAC (``AA:BB:CC:DD:EE:FF`` or dash-separated) to unpair.
Returns:
``True`` if a bond was removed, ``False`` if there was nothing to unpair or the
attempt failed.
"""
if sys.platform != "win32":
return False
addr = MeshCoreDevice._ble_address_int(address or "")
if addr is None:
return False
try:
from winrt.windows.devices.bluetooth import BluetoothLEDevice
from winrt.windows.devices.enumeration import DeviceUnpairingResultStatus
except Exception as exc: # noqa: BLE001 - winrt projection unavailable; fall through
_log.debug("BLE unpair unavailable (winrt import failed): %s", exc)
return False
device = None
try:
device = await BluetoothLEDevice.from_bluetooth_address_async(addr)
if device is None:
return False
pairing = device.device_information.pairing
if not pairing.is_paired:
return False # nothing bonded — treat as a no-op success-of-intent
result = await pairing.unpair_async()
status = int(result.status)
ok = status == int(DeviceUnpairingResultStatus.UNPAIRED)
_log.debug("BLE unpair for %s: status=%d ok=%s", address, status, ok)
return ok
except Exception as exc: # noqa: BLE001 - best-effort teardown; never crash exit
_log.debug("BLE unpair attempt failed for %s: %s", address, exc)
return False
finally:
# Closing the handle is what actually drops the OS's link to the peripheral; without
# it the device stays "connected" after the unpair and won't re-pair until rebooted.
MeshCoreDevice._close_ble_device(device)
def _ble_auth_message(self) -> str:
"""A clean, actionable error for a Bluetooth companion that requires a PIN/bond.
+76 -6
View File
@@ -174,6 +174,11 @@ async def run_menu(ctx: AppContext) -> None:
await ctx.monitor.aclose()
await ctx.chat.aclose()
await ctx.events.aclose()
# If the user chose "Unpair & quit", drop the OS bond now — after the services are
# down and the link is torn down, since a bond can't be cleanly removed while it is
# in use. Best-effort: a failure must not block the exit.
if ctx.unpair_on_exit:
await _unpair_on_exit(ctx)
# Everything the app owns is released; the remaining exit steps (prompt_toolkit's
# full-screen unwind, the device disconnect in the CLI driver, the interpreter's
# atexit thread joins) must never be able to hang the process. See
@@ -185,6 +190,56 @@ async def run_menu(ctx: AppContext) -> None:
ctx.console.print("[muted]bye 73![/muted]")
async def _can_unpair(ctx: AppContext) -> bool:
"""Whether the quit dialog should offer to drop the current device's OS pairing.
True only when this session is on a Bluetooth link whose peripheral Windows actually holds
a bond for — so the affordance appears for a PIN-paired companion but never for a serial
port, an open (PIN-less) BLE companion, or a platform where we can't unpair. The bond query
reflects the OS pairing (independent of MeshTerm's remembered record), so it correctly lights
up even for a device bonded in an earlier session and reconnected here without a PIN.
Args:
ctx: The shared application context.
Returns:
``True`` if an unpair-and-quit button is warranted.
"""
if ctx.active_transport != "ble":
return False
address = ctx.active_address
if not address:
return False
from ..core.connection import MeshCoreDevice
return await MeshCoreDevice.is_ble_paired(address)
async def _unpair_on_exit(ctx: AppContext) -> None:
"""Tear down the live connection and drop the device's OS bond, on the way out.
Ordered deliberately: the companion link is disconnected first (a bond can't be cleanly
removed while an open connection is using it), then the Windows pairing is forgotten so the
next launch re-runs the PIN ceremony. MeshTerm's remembered-device record is left untouched —
unpairing forgets the *credential*, not the device's identity. Best-effort throughout: any
failure is swallowed so it can never wedge the exit.
Args:
ctx: The shared application context (its device is disconnected as a side effect).
"""
address = ctx.active_address
if ctx._device is not None:
try:
await ctx._device.disconnect()
except Exception: # noqa: BLE001 - a dead/lost link must not block unpair or exit
pass
ctx._device = None
if address:
from ..core.connection import MeshCoreDevice
await MeshCoreDevice.unpair_ble(address)
async def _menu_loop(ctx: AppContext, session: TuiSession) -> None:
"""Show the tool menu and run selections until the user quits.
@@ -227,21 +282,36 @@ async def _menu_loop(ctx: AppContext, session: TuiSession) -> None:
# over the (still-pushed) menu so a stray key doesn't drop the user out. Cancel
# (Esc) sits left of Quit (Enter); Quit starts highlighted so Enter commits it.
if selection in (None, "__quit__"):
leave = await session.button_dialog(
# Offer to drop the OS pairing on the way out, but only when there is a live
# Bluetooth bond to drop — never on serial, an open (PIN-less) companion, or a
# platform we can't unpair. The extra button sits between Cancel and Quit and is
# never the default, so it takes a deliberate choice, not a stray Enter.
unpairable = await _can_unpair(ctx)
buttons = [("Cancel", "cancel")]
if unpairable:
buttons.append(("Unpair & quit", "unpair"))
buttons.append(("Quit", "quit"))
choice = await session.button_dialog(
"Are you sure you want to quit?",
[("Cancel", False), ("Quit", True)],
buttons,
title="Quit MeshTerm",
default=1,
default=len(buttons) - 1, # highlight Quit
footer_hint="Esc cancel · Enter quit",
prompt_style="warn",
button_style="selected",
button_idle_style="muted",
border_style="warn",
)
if leave:
if choice == "unpair":
# Forget the OS bond as we leave; the disconnect must happen first, so the
# actual unpair is deferred to teardown (see run_menu). The remembered-device
# record is intentionally kept — the device just asks for its PIN again.
ctx.unpair_on_exit = True
return
# Keep the cursor on "quit" when that is what they chose, so a follow-up
# attempt lands where they expect; a stray Esc leaves it where it was.
if choice == "quit":
return
# Cancel (button or Esc → None). Keep the cursor on "quit" when that is what
# they chose, so a follow-up attempt lands where they expect.
if selection == "__quit__":
last_selection = "__quit__"
continue
+55
View File
@@ -229,6 +229,61 @@ def test_ble_address_int_parses_macs_and_rejects_others() -> None:
assert parse("550e8400-e29b-41d4-a716-446655440000") is None # CoreBluetooth UUID
async def test_ble_pairing_helpers_noop_for_non_mac_address() -> None:
"""The bond query and unpair short-circuit (never touching WinRT) for a non-MAC address."""
# A non-MAC address fails the parse before any winrt import, so these stay hermetic on any
# platform — no real Bluetooth stack is consulted.
assert await connection.MeshCoreDevice.is_ble_paired("not-a-mac") is False
assert await connection.MeshCoreDevice.unpair_ble("not-a-mac") is False
assert await connection.MeshCoreDevice.is_ble_paired("") is False
async def test_can_unpair_only_for_bonded_ble(monkeypatch: pytest.MonkeyPatch) -> None:
"""The quit dialog offers unpair only on a BLE link that Windows actually holds a bond for."""
async def _is_paired(address: str) -> bool:
return address == "00:11:22:33:44:55"
monkeypatch.setattr(
connection.MeshCoreDevice, "is_ble_paired", staticmethod(_is_paired)
)
# Serial: never offered, whatever the address.
serial_ctx = SimpleNamespace(active_transport="serial", active_address=None)
assert await menu._can_unpair(serial_ctx) is False
# BLE but no address to act on: not offered.
ble_no_addr = SimpleNamespace(active_transport="ble", active_address=None)
assert await menu._can_unpair(ble_no_addr) is False
# BLE with a live bond: offered.
bonded = SimpleNamespace(active_transport="ble", active_address="00:11:22:33:44:55")
assert await menu._can_unpair(bonded) is True
# BLE but open (no bond, e.g. the PIN-less companion): not offered.
open_ble = SimpleNamespace(active_transport="ble", active_address="AA:BB:CC:DD:EE:FF")
assert await menu._can_unpair(open_ble) is False
async def test_unpair_on_exit_disconnects_before_unpairing(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Teardown drops the live link first, then forgets the OS bond (order matters)."""
order: list[str] = []
class _Dev:
async def disconnect(self) -> None:
order.append("disconnect")
async def _unpair(address: str) -> bool:
order.append(f"unpair:{address}")
return True
monkeypatch.setattr(connection.MeshCoreDevice, "unpair_ble", staticmethod(_unpair))
ctx = SimpleNamespace(active_address="00:11:22:33:44:55", _device=_Dev())
await menu._unpair_on_exit(ctx)
# Disconnect precedes unpair (a bond can't be dropped while in use), and the device handle
# is released. The device_store is never touched — the remembered record survives.
assert order == ["disconnect", "unpair:00:11:22:33:44:55"]
assert ctx._device is None
def _make_ctx(tmp_path: Path) -> AppContext:
"""Build a real, mock-backed application context for reconnect tests."""
settings = Settings(config_dir=tmp_path, db_path=tmp_path / "disc.db")