A reboot sent from Device config raises the reconnect dialog at once

The reboot flow used to send the command and then wait for a liveness poll
to see the link drop. A quick reboot behind a port that never goes away
(a USB-UART bridge) was never seen, so the app went on sending commands to
a board mid-restart. Sending the reboot now declares the link down itself:
the session watcher wakes on the announcement, the Device rebooting dialog
takes over, and the first reconnect attempt waits a moment for the board to
actually begin restarting.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5.5 committed 2026-09-29 01:09:32 -04:00
1 parent 3f73716ff5
commit cdea534fa0
5 files changed
+120 -35

No files matched your search

+37 -4
View File
@@ -8,6 +8,7 @@ never open a serial port.
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
@@ -151,11 +152,15 @@ class AppContext:
#: the older handle no longer names it. Typed ``object`` so ``bleak`` stays optional.
_ble_handle: object | None = field(default=None, init=False, repr=False)
unpair_on_exit: bool = field(default=False, init=False, repr=False)
#: Set by the config editor just before it sends a reboot command, so the session's
#: disconnect watcher can label the ensuing (expected) link drop as a reboot in
#: progress rather than a surprise unplug. Cleared by the reconnect dialog that
#: consumes it (see :func:`meshterm.ui.menu._handle_disconnect`).
#: Set by :meth:`announce_reboot` once a reboot command has gone out, so the reconnect
#: dialog presents the drop as a reboot in progress rather than a surprise unplug.
#: Cleared by :meth:`take_reboot` in the dialog that consumes it (see
#: :func:`meshterm.ui.menu._handle_disconnect`).
reboot_in_progress: bool = field(default=False, init=False, repr=False)
#: Set alongside :attr:`reboot_in_progress`: wakes the session's disconnect watcher at
#: once, without waiting for a liveness poll to *observe* the drop — which it may never
#: do, since a board behind a USB-UART bridge keeps its port through a reboot.
_link_going_down: asyncio.Event = field(default_factory=asyncio.Event, init=False, repr=False)
_resume_intent: tuple[bool, bool, bool] | None = field(default=None, init=False, repr=False)
_events: EventHub | None = field(default=None, init=False, repr=False)
_monitor: MonitorService | None = field(default=None, init=False, repr=False)
@@ -282,6 +287,34 @@ class AppContext:
except Exception: # noqa: BLE001 - a liveness-check failure must not fake a disconnect
return True
def announce_reboot(self) -> None:
"""Declare the link down because we just told the companion to reboot.
Called *after* the reboot command was sent (never before: the watcher it wakes
cancels the screen that sent it, and a cancel mid-write could leave the command half
out). From then on the device is not ours to talk to until it comes back, so the
session's disconnect watcher (:meth:`link_going_down`) fires at once and the
reconnect dialog takes over — rather than hoping a liveness poll catches the drop,
which misses a quick reboot entirely where the serial port never goes away.
"""
self.reboot_in_progress = True
self._link_going_down.set()
async def link_going_down(self) -> None:
"""Resolve once :meth:`announce_reboot` has declared the link down."""
await self._link_going_down.wait()
def take_reboot(self) -> bool:
"""Consume a pending reboot announcement, returning whether there was one.
Clears both halves, so a later, genuine disconnect goes back to the generic
wording and the next watcher waits for a real drop again.
"""
pending = self.reboot_in_progress
self.reboot_in_progress = False
self._link_going_down.clear()
return pending
@property
def ui(self) -> Ui:
"""The active UI surface, defaulting to the plain console surface for the CLI.
+4
View File
@@ -302,6 +302,10 @@ async def apply_ops(
await device.reboot()
ctx.ui.ack("[warn]device rebooting[/warn]")
report.append(_acted("reboot", rebooted=True))
if ctx.active_transport is not None:
# Run from the menu's command line, this hands off to the reconnect dialog
# as the config editor's reboot does; a scripted run has no watcher to wake.
ctx.announce_reboot()
elif kind == "export_key":
report.append(await _export_key(ctx, device, op[1] if len(op) > 1 else None, artifacts))
elif kind == "import_key":
+19 -27
View File
@@ -97,13 +97,11 @@ _OTHER = "__other__"
#: The setting keys the map pick sets together (each also has its own row, for a typed value).
_COORD_KEYS = ("adv_lat", "adv_lon")
#: How long the reboot flow waits to *observe* the link actually dropping before handing
#: off to the session's reconnect dialog (seconds). A companion normally vanishes from the
#: bus well within this; on timeout we hand off anyway.
_REBOOT_DROP_TIMEOUT_S = 10.0
#: Poll cadence while waiting for the rebooting companion's link to drop (seconds).
_REBOOT_DROP_POLL_S = 0.25
#: How long the reboot flow holds the actions screen after announcing the reboot, waiting
#: for the session's disconnect watcher to cancel it and raise the reconnect dialog
#: (seconds). The watcher wakes on the announcement itself, so this only runs out where
#: no watcher is running.
_REBOOT_HANDOFF_TIMEOUT_S = 5.0
async def cached_snapshot(ctx: AppContext, device: Device) -> dict:
@@ -1182,10 +1180,11 @@ async def _show_contact_card(ctx: AppContext, snapshot: dict) -> None:
async def _reboot(ctx: AppContext, device: Device, snapshot: dict) -> bool:
"""Confirm and reboot the device, handing off to the session's reconnect dialog.
After the command is sent, we wait to actually observe the link dropping — flagging
:attr:`~meshterm.context.AppContext.reboot_in_progress` so the session-wide
disconnect watcher labels the ensuing dialog as a reboot, waits for the companion to
come back, and reconnects — exactly the unplugged-device flow.
Once the command is sent the link is declared down
(:meth:`~meshterm.context.AppContext.announce_reboot`) rather than waited on, so the
session-wide disconnect watcher raises its dialog at once, labelled as a reboot, waits
for the companion to come back, and reconnects — exactly the unplugged-device flow,
and nothing else is sent to the board while it restarts.
Returns:
``True`` if the reboot was sent and the actions screen should close; ``False``
@@ -1208,22 +1207,15 @@ async def _reboot(ctx: AppContext, device: Device, snapshot: dict) -> bool:
await ctx.ui.present(title="Reboot")
return False
# Flag the drop as expected *before* sending, so however quickly the watcher fires,
# the reconnect dialog already knows to present it as a reboot.
ctx.reboot_in_progress = True
try:
await device.reboot()
except Exception:
ctx.reboot_in_progress = False
raise
# Hold here until the link is actually observed down (or a generous timeout), so the
# actions screen doesn't flash back to the menu for the second or two before the
# watcher notices. The watcher may cancel us mid-wait when it fires — that's the handoff.
deadline = asyncio.get_running_loop().time() + _REBOOT_DROP_TIMEOUT_S
while asyncio.get_running_loop().time() < deadline:
if not await ctx.link_alive():
break
await asyncio.sleep(_REBOOT_DROP_POLL_S)
await device.reboot()
# The command is out, so the link is as good as gone: declare it, rather than wait for
# a liveness poll to notice — a quick reboot behind a port that never disappears is
# never noticed at all, and the next command would go to a board mid-restart.
ctx.announce_reboot()
# The session's watcher now cancels us and raises the reconnect dialog; hold here until
# it does, so the actions screen doesn't flash back to the menu in between. The timeout
# only matters where no watcher is running to take the handoff.
await asyncio.sleep(_REBOOT_HANDOFF_TIMEOUT_S)
return True
+32 -4
View File
@@ -79,6 +79,12 @@ _BLE_PRESENCE_SCAN_S = 8.0
#: stops the loop spinning when scanning fails instantly (no adapter, Bluetooth switched off).
_BLE_RESCAN_PAUSE_S = 1.0
#: After a reboot we sent, how long to leave the companion alone before the first reconnect
#: attempt (seconds). The dialog is up the instant the command is out, which is before the
#: board has necessarily started restarting; a port that stays put through the reboot would
#: otherwise be reopened against the old session, which dies under it a moment later.
_REBOOT_SETTLE_S = 1.5
def _arm_exit_watchdog(seconds: float = _EXIT_WATCHDOG_S) -> None:
"""Guarantee the process terminates even if the exit path wedges.
@@ -1044,6 +1050,20 @@ async def _wait_for_disconnect(ctx: AppContext) -> None:
if ctx.mock:
await asyncio.Event().wait() # the simulator is never "unplugged"; wait forever
return
# A reboot we sent is a drop we already know about: race it against the poll so the
# reconnect dialog is up the moment the command is out, not whenever (or if ever) a
# poll happens to land inside the reboot.
announced = asyncio.ensure_future(ctx.link_going_down())
polled = asyncio.ensure_future(_poll_for_disconnect(ctx))
try:
await asyncio.wait({announced, polled}, return_when=asyncio.FIRST_COMPLETED)
finally:
await _cancel_and_wait(announced)
await _cancel_and_wait(polled)
async def _poll_for_disconnect(ctx: AppContext) -> None:
"""Resolve once the liveness check sees the link gone, debounced against a blip."""
while True:
await asyncio.sleep(_LIVENESS_POLL_S)
if not ctx.is_connected:
@@ -1076,8 +1096,8 @@ async def _handle_disconnect(ctx: AppContext, session: TuiSession) -> bool:
# A drop the config editor announced (it just sent a reboot command) is expected, so
# the dialog says what is actually happening instead of implying an unplug. The flag
# is consumed here so a later, genuine disconnect goes back to the generic wording.
if ctx.reboot_in_progress:
ctx.reboot_in_progress = False
rebooting = ctx.take_reboot()
if rebooting:
dialog = ReconnectDialog(
"Rebooting — waiting for the device to come back…",
title="Device rebooting",
@@ -1096,7 +1116,9 @@ async def _handle_disconnect(ctx: AppContext, session: TuiSession) -> bool:
session.push(base)
session.push(dialog)
animator = asyncio.ensure_future(_animate_dialog(session, dialog))
reconnector = asyncio.ensure_future(_auto_reconnect(ctx, dialog))
reconnector = asyncio.ensure_future(
_auto_reconnect(ctx, dialog, settle_s=_REBOOT_SETTLE_S if rebooting else 0.0)
)
try:
result = await dialog.future
finally:
@@ -1115,7 +1137,7 @@ async def _animate_dialog(session: TuiSession, dialog: ReconnectDialog) -> None:
session.invalidate()
async def _auto_reconnect(ctx: AppContext, dialog: ReconnectDialog) -> None:
async def _auto_reconnect(ctx: AppContext, dialog: ReconnectDialog, *, settle_s: float = 0.0) -> None:
"""Poll for the device to return, reconnect when it does, then dismiss ``dialog``.
The dead link is released up front (:meth:`~meshterm.context.AppContext.release_link`) so
@@ -1141,6 +1163,10 @@ async def _auto_reconnect(ctx: AppContext, dialog: ReconnectDialog) -> None:
Args:
ctx: The shared application context.
dialog: The reconnect dialog to dismiss once the link is back.
settle_s: How long to leave the device alone after releasing the link, before the
first attempt. Nonzero only for a reboot we sent: the watcher fires the instant
the command is out, and a serial port that never went away would otherwise be
reopened against a board that has not yet begun to restart.
"""
from ..core.connection import serial_port_present
from ..core.discovery import find_ble_device
@@ -1149,6 +1175,8 @@ async def _auto_reconnect(ctx: AppContext, dialog: ReconnectDialog) -> None:
# still nominally connected to does not advertise, so the scan below would wait out a
# peripheral that is powered on and silent purely because we never let go of it.
await ctx.release_link()
if settle_s:
await asyncio.sleep(settle_s)
while True:
ble_device: object | None = None
+28
View File
@@ -1038,6 +1038,34 @@ async def test_wait_for_disconnect_ignores_the_simulator(tmp_path: Path) -> None
ctx.repo.close()
async def test_wait_for_disconnect_fires_on_an_announced_reboot(
tmp_path: Path, monkeypatch
) -> None:
"""A reboot we sent fires the watcher at once, though the port never goes away.
A board behind a USB-UART bridge keeps its port through a reboot, so the poll alone
would never see the drop; the announcement is the evidence.
"""
ctx = _make_ctx(tmp_path)
ctx.mock = False
ctx._device = _FakeSerialDevice("COM_TEST")
ctx._active_transport = "serial"
ctx._active_port = "COM_TEST"
monkeypatch.setattr(connection, "serial_port_present", lambda port: True) # never leaves
try:
watcher = asyncio.ensure_future(menu._wait_for_disconnect(ctx))
await asyncio.sleep(0)
assert not watcher.done()
ctx.announce_reboot()
await asyncio.wait_for(watcher, timeout=0.5) # well inside one liveness poll
assert ctx.take_reboot() is True
assert ctx.take_reboot() is False # consumed: the next drop reads as an unplug
with pytest.raises(asyncio.TimeoutError): # and the next watcher waits for one
await asyncio.wait_for(menu._wait_for_disconnect(ctx), timeout=0.2)
finally:
ctx.repo.close()
class _FakeBleDevice:
"""A minimal stand-in for a connected BLE :class:`Device` in liveness tests.