From e0a681b293bb186248bcabdba2eeb4fd85aeae19 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Tue, 25 Aug 2026 02:12:26 -0400 Subject: [PATCH] Busy screens: stop the spinner starving the work it reports on MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On the PicoCalc a repaint costs about 154ms, and these two loops waited 60ms (the overlay) and 120ms (the splash) between them — rates hardcoded past spinner_interval(), which every other animated wait in the app already sleeps on. The animation asked for repaints faster than the console could finish them, so it took the event loop from the device read it was covering for: the wait got slower for being animated, and the spinner stuttered anyway. Both defer to the platform now (0.5s there, 0.12s on the desktop). Two calls were also blocking the loop outright, which stops the animation dead however it is paced. Enumerating serial ports is a SetupAPI/sysfs walk — behind the "Scanning for companion devices…" splash, and again on every poll of the reconnect dialog — so both go to a thread. The UI itself cannot: prompt_toolkit owns the loop for render and keys. Moving the blocking work off it is the same fix from the other side. Two tests: neither busy screen may carry a spin rate of its own, and the spinner advances *during* an awaited read rather than only side of it. Also drops the "· experimental" tag from the network-device row. Co-Authored-By: Claude Opus 5 (1M context) --- meshterm/core/discovery.py | 6 ++++- meshterm/ui/device_picker.py | 7 ++---- meshterm/ui/menu.py | 4 ++- meshterm/ui/tui/session.py | 19 ++++++++++---- tests/test_tui.py | 49 ++++++++++++++++++++++++++++++++++-- 5 files changed, 71 insertions(+), 14 deletions(-) diff --git a/meshterm/core/discovery.py b/meshterm/core/discovery.py index 40702a6..e5d9cbd 100644 --- a/meshterm/core/discovery.py +++ b/meshterm/core/discovery.py @@ -25,6 +25,7 @@ in range. The companion connection itself still goes through from __future__ import annotations +import asyncio import logging from dataclasses import dataclass from typing import Optional @@ -421,7 +422,10 @@ async def discover_all( Returns: All discovered devices: serial (likely-LoRa first), then BLE companions. """ - serial = discover_devices() + # ``comports()`` is a blocking SetupAPI/sysfs walk — hundreds of milliseconds on + # Windows, and long enough on a slow console to freeze whatever spinner is covering + # this call. Off the event loop, so the animation reporting the wait keeps running. + serial = await asyncio.to_thread(discover_devices) if not ble: return serial # A device paired over both USB and BLE is vanishingly unlikely to collide by stable_id diff --git a/meshterm/ui/device_picker.py b/meshterm/ui/device_picker.py index ca65b84..f5063a9 100644 --- a/meshterm/ui/device_picker.py +++ b/meshterm/ui/device_picker.py @@ -669,14 +669,11 @@ def _action_rows() -> list: """The trailing splash rows: name a network device by hand, then quit. A network (TCP) companion doesn't advertise and isn't attached, so it can't be scanned - for — the "add a network device" row opens a host:port prompt to name one. It's flagged - experimental (TCP companion support is still settling), with the tag in the cautionary - hue so it reads as a caveat rather than a description. The Quit row mirrors the main menu. - The leading spaces line both up under the device-name column. + for — the "add a network device" row opens a host:port prompt to name one. The Quit row + mirrors the main menu. The leading spaces line both up under the device-name column. """ add_row = Text() add_row.append(f" {_TCP_ICON} Add a network device…") - add_row.append(" · experimental", style="warn") return [ Separator(" "), Choice(title=add_row, value=_ADD_TCP), diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index 2c9f8d5..307fec1 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -957,7 +957,9 @@ async def _auto_reconnect(ctx: AppContext, dialog: ReconnectDialog) -> None: # ``create_ble``/``create_tcp`` connect by address/endpoint and fail fast when absent. if ctx.active_transport == "serial": port = ctx.active_port - if port is not None and not serial_port_present(port): + # Off the loop: the probe enumerates ports, which blocks long enough to stall + # the very spinner this dialog is showing while it waits. + if port is not None and not await asyncio.to_thread(serial_port_present, port): await asyncio.sleep(_LIVENESS_POLL_S) continue try: diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index f3841b9..3223609 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -44,6 +44,7 @@ from .prompt import ( Validator, ) from .screen import CANCEL, BusyScreen, Screen, ScrollScreen +from .spinner import spinner_interval from .select import Choice, ReorderScreen, SelectScreen, Separator #: Every Ctrl-letter chord the app binds, keyed by the bare lowercase letter — the single @@ -695,7 +696,7 @@ class TuiSession: title: str = "", banner: Optional[Any] = None, footnote: Optional[str] = None, - interval: float = 0.12, + interval: Optional[float] = None, ) -> Any: """Await ``coro`` while showing an animated spinner on the chromeless splash. @@ -710,11 +711,15 @@ class TuiSession: title: Optional panel title for the splash box. banner: Wordmark rows drawn above the box (as on the other startup splashes). footnote: Muted line drawn below the box. - interval: Seconds between spinner frames. + interval: Seconds between spinner frames. Defaults to the platform's cadence, + which is the point on a slow console: a repaint there costs more than this + loop used to wait between them, so a hardcoded rate spent the whole event + loop redrawing the spinner and starved the very work it was reporting on. Returns: Whatever ``coro`` resolves to. """ + tick = spinner_interval() if interval is None else interval screen = BusyScreen(message, title=title) screen.chrome = False screen.banner = banner @@ -723,7 +728,7 @@ class TuiSession: async def animate() -> None: while True: - await asyncio.sleep(interval) + await asyncio.sleep(tick) screen.tick() self.invalidate() @@ -997,7 +1002,7 @@ class TuiSession: message: str = "", *, title: str = "", - interval: float = 0.06, + interval: Optional[float] = None, ) -> AsyncIterator[BusyOverlay]: """Float a skeleton card on top of everything for the duration of a block. @@ -1020,10 +1025,14 @@ class TuiSession: message: An optional caption drawn beside the working chip. title: An optional heading naming the screen being fetched. interval: Seconds between animation frames (also the fade's repaint cadence). + Defaults to the platform's cadence — see :meth:`busy_startup`, which this + shares a hazard with: the card animates *over* a device read, so a rate the + console can't sustain steals the loop from the read it is covering for. Yields: The live :class:`BusyOverlay`, in case the caller wants to update its caption. """ + tick = spinner_interval() if interval is None else interval # A nested busy_overlay keeps the outer one (the outermost wait owns the screen); its # own body still runs, it just doesn't install a second card. if self._overlay is not None: @@ -1036,7 +1045,7 @@ class TuiSession: async def animate() -> None: while True: - await asyncio.sleep(interval) + await asyncio.sleep(tick) overlay.tick() # Only repaint when the card is actually on screen, so an overlay waiting # behind a live prompt doesn't churn that prompt's repaints for nothing. diff --git a/tests/test_tui.py b/tests/test_tui.py index 8da95dd..e84d6f4 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -33,6 +33,7 @@ from meshterm.ui.tui.prompt import ( ) from meshterm.ui.tui.render import render_lines, render_to_ansi from meshterm.ui.tui.screen import CANCEL, Screen, ScrollScreen +from meshterm.ui.tui.spinner import spinner_interval from meshterm.ui.tui.select import Choice, ReorderScreen, SelectScreen, Separator from meshterm.ui.tui.session import TuiSession @@ -1150,8 +1151,7 @@ def test_device_picker_builds_aligned_columns(tmp_path) -> None: ] # Two devices plus the trailing action rows (add a network device, then Quit). assert len(rows) == 4 - assert "Add a network device…" in rows[-2] - assert rows[-2].strip().endswith("· experimental") # the row is flagged experimental + assert rows[-2].strip().endswith("Add a network device…") # no caveat tag trailing it assert rows[-1].strip().endswith("Quit") device_rows = rows[:2] assert all(port in row for port, row in zip(("COM5", "/dev/ttyUSB0"), device_rows)) @@ -1849,6 +1849,51 @@ async def test_session_busy_startup_animates_and_returns() -> None: assert session.top is None # the splash was popped when the task finished +async def test_busy_screens_spin_at_the_platform_cadence() -> None: + """Neither busy screen carries a spin rate of its own. + + A repaint on the PicoCalc console costs more than these loops used to wait between + them, so a hardcoded cadence spent the event loop redrawing the spinner and starved + the device read it was covering for — the wait got *slower* for being animated. Both + default to the one platform decision, like every other animated wait in the app. + """ + import inspect + + from meshterm.ui.tui.session import TuiSession as _Session + + for name in ("busy_startup", "busy_overlay"): + interval = inspect.signature(getattr(_Session, name)).parameters["interval"] + assert interval.default is None, f"{name} pins its own spin rate: {interval.default!r}" + + +async def test_busy_startup_keeps_ticking_through_a_slow_await() -> None: + """The spinner animates while the awaited work runs, not just before and after. + + The animation shares the event loop with the request it reports on, so anything that + blocks the loop stops it dead — which is the whole reason the slow parts of a device + read (enumerating serial ports, reading history) are handed to a thread. + """ + from meshterm.ui.tui.screen import BusyScreen + + with create_pipe_input() as inp: + session = TuiSession(input=inp, output=DummyOutput()) + frames: list[str] = [] + + async def work() -> str: + screen = session.top + assert isinstance(screen, BusyScreen) + for _ in range(6): # span several spins without blocking the loop + await asyncio.sleep(spinner_interval()) + frames.append(screen._spinner.frame) + return "ok" + + async def main() -> None: + await session.busy_startup("checking…", work(), interval=spinner_interval() / 4) + + await asyncio.wait_for(session.run(main()), timeout=15) + assert len(set(frames)) > 1, f"the spinner never advanced: {frames}" + + async def test_session_text_dispatches_typed_keys() -> None: """A text prompt captures typed characters and commits on Enter, end to end.""" with create_pipe_input() as inp: