From 0a0dc977e6dad8261a23b50ec664bb15ac2ed7c1 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Wed, 9 Sep 2026 00:23:29 -0400 Subject: [PATCH] A busy card that is actually there, and actually takes the keys The overlay could not report a hub's own slow work: it paints only on an empty stack, so over a screen kept up with stay() it draws nothing, and it is not a screen at all, so it takes no keys either. A visited hub stays armed the whole time it waits, which means every press during a slow device write still reaches it - letters into its live filter, Esc resolving a round nobody is waiting for yet, handed back the instant the work lands. BusyDialog is BusyScreen drawn as a box over what it interrupts: modal, so the press dies on the card instead. Nesting keeps the outermost one, so a batch of writes is one wait rather than a box per write, and its caption can change to say which step it is on. Co-Authored-By: Claude Opus 5 (1M context) --- meshterm/ui/surface.py | 21 +++++++++ meshterm/ui/tui/__init__.py | 3 +- meshterm/ui/tui/screen.py | 45 ++++++++++++++++++ meshterm/ui/tui/session.py | 91 +++++++++++++++++++++++++++++++++++- tests/test_navigation.py | 93 ++++++++++++++++++++++++++++++++++++- 5 files changed, 250 insertions(+), 3 deletions(-) diff --git a/meshterm/ui/surface.py b/meshterm/ui/surface.py index cde41d5..cd3c4b4 100644 --- a/meshterm/ui/surface.py +++ b/meshterm/ui/surface.py @@ -134,6 +134,18 @@ class Ui: """ raise NotImplementedError + def busy_dialog(self, message: str = "", *, title: str = ""): # noqa: ANN201 - async CM, varies by backend + """Return an async context manager that floats a **modal** busy card over a screen. + + The counterpart to :meth:`busy_overlay`, for slow work a *screen* starts rather than + work that happens in the gap between screens. The overlay is not a screen at all: it + draws only on an empty stack and it takes no keys, so a hub that stays pushed while + it works gets neither the card nor the protection. This one is pushed and modal — see + :meth:`~meshterm.ui.tui.session.TuiSession.busy_dialog` for what that buys. In + scripted CLI mode it does nothing, as the overlay does. + """ + raise NotImplementedError + async def select( self, title: str, @@ -407,6 +419,11 @@ class PlainUi(Ui): """Do nothing: the scripted CLI has no full-screen surface to float a skeleton over.""" yield + @asynccontextmanager + async def busy_dialog(self, message: str = "", *, title: str = "") -> AsyncIterator[None]: + """Do nothing: there is no screen to interrupt and no keyboard to take.""" + yield + def _no_prompt(self) -> RuntimeError: """Build the error raised if a rich prompt is reached on the non-interactive path.""" return RuntimeError("interactive prompts are only available in the menu") @@ -656,6 +673,10 @@ class TuiUi(Ui): """Float the session's top-most skeleton card while the wrapped block runs.""" return self.session.busy_overlay(message, title=title) + def busy_dialog(self, message: str = "", *, title: str = ""): # noqa: ANN201 + """Push the session's modal busy card over the current screen while the block runs.""" + return self.session.busy_dialog(message, title=title) + # --- input --------------------------------------------------------------- async def select( diff --git a/meshterm/ui/tui/__init__.py b/meshterm/ui/tui/__init__.py index 04fdc3e..09e7055 100644 --- a/meshterm/ui/tui/__init__.py +++ b/meshterm/ui/tui/__init__.py @@ -32,7 +32,7 @@ from .prompt import ( TypedConfirmDialog, byte_counter, ) -from .screen import CANCEL, BusyScreen, PopToMenu, Screen, ScrollScreen +from .screen import CANCEL, BusyDialog, BusyScreen, PopToMenu, Screen, ScrollScreen from .select import Choice, DeleteRequest, SelectScreen, Separator from .session import TuiSession, Visit from .spinner import Spinner @@ -41,6 +41,7 @@ __all__ = [ "TuiSession", "Screen", "ScrollScreen", + "BusyDialog", "BusyScreen", "SelectScreen", "Choice", diff --git a/meshterm/ui/tui/screen.py b/meshterm/ui/tui/screen.py index 355b528..6285a5f 100644 --- a/meshterm/ui/tui/screen.py +++ b/meshterm/ui/tui/screen.py @@ -17,6 +17,7 @@ from collections.abc import Callable, Sequence from collections.abc import Sequence as _SequenceABC from typing import Any +from rich.cells import cell_len from rich.console import RenderableType from rich.text import Text @@ -721,3 +722,47 @@ class BusyScreen(Screen): def handle(self, action: str, data: str = "") -> None: """Swallow all keys: the splash dismisses itself when the task finishes.""" return + + +class BusyDialog(BusyScreen): + """A busy splash drawn as a box over the screen it interrupts. + + :class:`BusyScreen`'s twin, for work started *from* a screen rather than instead of one: + same spinner, same caption, same swallow-everything :meth:`~BusyScreen.handle` — but + ``floating``, so the hub that started the work stays visible beneath it as a backdrop + instead of being replaced. + + Modal by inheritance, and that is the half that matters. A hub screen kept on the stack + with ``session.stay`` is *armed the whole time* (see + :meth:`~meshterm.ui.tui.session.Visit._arm`), so while it sits there waiting for a slow + device write every key a reader presses still reaches it: letters land in its live filter + and Esc resolves it, to be handed back the instant the work finishes. A modal screen on + top is what stops that — the key reaches this dialog and dies here. + + :meth:`~meshterm.ui.tui.session.TuiSession.busy_overlay` cannot do the job: it is not a + screen, so it is never consulted for a keypress, and it paints only when the stack is + empty — over a pushed hub it draws nothing at all. + """ + + floating = True + + @property + def dialog_width(self) -> int: + """Hug the caption rather than stretching to the dialog cap. + + A spinner and four words have no business in a 94-cell box. The compositor still + caps this to the terminal (see :func:`~meshterm.ui.tui.frame._dialog_layout`), and + the width ratchets, so a caption that grows mid-batch never makes the box shrink + back and jitter. + """ + return cell_len(self._message) + 8 # spinner, its two spaces, and the padded border + + @property + def message(self) -> str: + """The caption beside the spinner.""" + return self._message + + @message.setter + def message(self, text: str) -> None: + """Retitle the card mid-batch (a sequence of writes reporting which one it is on).""" + self._message = text diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index 51ce64c..85e0dac 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -46,7 +46,7 @@ from .prompt import ( TypedConfirmDialog, Validator, ) -from .screen import CANCEL, POP_ALL, BusyScreen, PopToMenu, Screen, ScrollScreen +from .screen import CANCEL, POP_ALL, BusyDialog, BusyScreen, PopToMenu, Screen, ScrollScreen from .select import Choice, ReorderScreen, SelectScreen, Separator from .spinner import spinner_interval @@ -496,6 +496,10 @@ class TuiSession: # deliberately *not* on the screen stack: it hovers above every layer and is shown/ # hidden by busy_overlay, independent of whatever screens are pushed. self._overlay: BusyOverlay | None = None + # The busy card currently pushed by :meth:`busy_dialog`, or None. Unlike the overlay + # this one *is* a screen — it has to be, to take the keys the hub underneath would + # otherwise bank — and this holds it so a nested wait rides it instead of stacking. + self._busy: BusyDialog | None = None # What each drawn layer last composed — ``layer -> (text, carries a wide glyph)`` — so # :meth:`_emit` can tell a frame that actually changed from one the 1 Hz refresh just # re-rendered identically, and can ask whether anything currently on screen needs the @@ -1388,6 +1392,91 @@ class TuiSession: self._overlay = None self.invalidate() + @asynccontextmanager + async def busy_dialog( + self, + message: str = "", + *, + title: str = "", + interval: float | None = None, + ) -> AsyncIterator[BusyDialog]: + """Float a modal busy card over the current screen for the duration of a block. + + The in-stack counterpart to :meth:`busy_overlay`, and the one a screen wants when + *it* starts the slow work:: + + async with session.busy_dialog("saving Lakeside…", title="Channels"): + await device.set_channel(...) + + Two things separate it from the overlay, and both are why the overlay could not do + this job. It is a real :class:`~meshterm.ui.tui.screen.BusyDialog` *pushed on the + stack*, so it draws over a hub instead of only in the gaps between screens — the + overlay paints on an empty stack alone (see :meth:`_overlay_visible`), which is + exactly never while a hub is visited. And being modal, it **owns the keyboard**: a + hub kept up with :meth:`stay` stays armed while the work runs, so without a modal + layer every key pressed during the wait still reaches it — letters landing in its + live filter (a list that comes back showing nothing), Esc resolving it to be handed + back the instant the work finishes (a screen that appears to close on its own a + beat later). Those presses now reach this card and stop there. + + Nesting keeps the outermost card, so a batch of writes reports as one wait rather + than flashing a box per write; the inner block still runs. The caller may retitle + the card as it goes — ``busy.message = …`` — which is how a sequence says which + step it is on. + + Unlike :meth:`busy_overlay` there is no fade-in. The fade is there so a fast + operation shows nothing at all, and that is a fine trade for a cosmetic card; this + one is also the key guard, and a guard that arrives late is a guard with a hole in + it. + + Args: + message: The caption drawn beside the spinner. + title: An optional heading naming the feature doing the work. + interval: Seconds between spinner frames; defaults to the platform's cadence + (see :meth:`busy_startup`, which shares the hazard: the card animates *over* + a device read, so a rate the console can't sustain steals the loop from the + work it is reporting on). + + Yields: + The live :class:`~meshterm.ui.tui.screen.BusyDialog`, so its caption can change. + """ + tick = spinner_interval() if interval is None else interval + if self._busy is not None: # a nested wait rides the card its caller already put up + yield self._busy + return + screen = BusyDialog(message, title=title) + # A lone floating screen on an empty stack is drawn *as* the background, framed and + # full-frame rather than as a box, so it gets the same blank backdrop every other + # dialog uses (see :meth:`_run_dialog_screen`). + backdrop = None + if not self._stack: + backdrop = ScrollScreen("", floating=False, footer_hint="") + self.push(backdrop) + self._busy = screen + self.push(screen) + + async def animate() -> None: + while True: + await asyncio.sleep(tick) + screen.tick() + self.invalidate() + + ticker = asyncio.ensure_future(animate()) + try: + yield screen + finally: + ticker.cancel() + try: + await ticker + except asyncio.CancelledError: + pass + except Exception: # noqa: BLE001 - a spinner hiccup must never break a flow + pass + self._busy = None + self.pop(screen) + if backdrop is not None: + self.pop(backdrop) + # --- application lifecycle ------------------------------------------------ async def run(self, main: Any) -> None: diff --git a/tests/test_navigation.py b/tests/test_navigation.py index 877dd99..18c664e 100644 --- a/tests/test_navigation.py +++ b/tests/test_navigation.py @@ -20,7 +20,15 @@ from prompt_toolkit.output import DummyOutput from meshterm.ui.tui.progress import ProgressScreen from meshterm.ui.tui.prompt import ButtonDialog -from meshterm.ui.tui.screen import CANCEL, POP_ALL, BusyScreen, PopToMenu, Screen, ScrollScreen +from meshterm.ui.tui.screen import ( + CANCEL, + POP_ALL, + BusyDialog, + BusyScreen, + PopToMenu, + Screen, + ScrollScreen, +) from meshterm.ui.tui.select import Choice, SelectScreen from meshterm.ui.tui.session import _CTRL_LETTER_CHORDS, _KEY_ACTIONS, TuiSession @@ -585,6 +593,7 @@ def test_pop_all_is_refused_over_anything_modal() -> None: ButtonDialog("Delete it?", [("Cancel", False), ("Delete", True)]), ProgressScreen("Working"), BusyScreen("checking…"), + BusyDialog("saving Lakeside…"), ): session.push(layer) assert session.request_pop_all() is False, f"{type(layer).__name__} must block ^W" @@ -733,6 +742,10 @@ def test_only_navigational_layers_are_non_modal() -> None: assert SelectScreen("list", [Choice("a", 1)]).modal is False assert BusyScreen("checking…").floating is False assert BusyScreen("checking…").modal is True + # ...and its twin is the same claim on the keyboard drawn as a box over what it + # interrupts, which is the pair's whole point. + assert BusyDialog("saving…").floating is True + assert BusyDialog("saving…").modal is True assert Screen().modal is False assert CANCEL is not POP_ALL @@ -809,3 +822,81 @@ async def test_a_detached_flow_still_reports_a_real_failure() -> None: task = session.run_detached(work()) with pytest.raises(RuntimeError): await task + + +# --- work in flight ---------------------------------------------------------- + + +async def test_a_key_pressed_during_a_slow_action_reaches_the_hub_that_is_still_armed() -> None: + """The defect ``busy_dialog`` exists to close, stated as a test. + + A hub kept up with ``stay`` is armed for the whole visit, so a key pressed while the + caller is off doing slow device work still lands on it. Esc resolves the round nobody + is waiting for yet, and it is handed back the instant the work finishes — the screen + closing on its own a beat after a press that appeared to do nothing. + """ + with create_pipe_input() as inp: + session = _session(inp) + screen = SelectScreen("hub", [Choice("alpha", 1)]) + banked: list = [] + + async def main() -> None: + async with session.stay(screen) as visit: + inp.send_text(ESC) # pressed "while the write is running" + await asyncio.sleep(0.05) # let the input loop dispatch it + banked.append(await asyncio.wait_for(visit.result(), timeout=1)) + + await asyncio.wait_for(session.run(main()), timeout=5) + + assert banked == [CANCEL] # the press was banked and comes straight back + + +async def test_the_busy_dialog_takes_the_keys_the_hub_would_have_banked() -> None: + """With the card up, the same press dies on it: nothing is banked, nothing resolves. + + This is what makes a slow channel write safe to sit through — the list underneath + cannot be filtered down to nothing, cannot be re-fired by an impatient second Enter, + and cannot be closed by an Esc that looks ignored until the work lands. + """ + with create_pipe_input() as inp: + session = _session(inp) + screen = SelectScreen("hub", [Choice("alpha", 1)]) + timed_out = [] + + async def main() -> None: + async with session.stay(screen) as visit: + async with session.busy_dialog("saving…", title="Channels"): + inp.send_text(ESC + "zzz" + ENTER) # Esc, filter letters, and Enter + await asyncio.sleep(0.05) + assert session.top.__class__ is BusyDialog # the card owns the keyboard + try: + await asyncio.wait_for(visit.result(), timeout=0.2) + except asyncio.TimeoutError: + timed_out.append(True) + + await asyncio.wait_for(session.run(main()), timeout=5) + + assert timed_out == [True] # nothing was banked while the card was up + assert screen._filter == "" # and the letters never reached the list's filter + + +async def test_the_busy_dialog_is_one_card_however_deeply_it_nests() -> None: + """A batch of writes reports as one wait, not a box flashing per write.""" + with create_pipe_input() as inp: + session = _session(inp) + depths: list[int] = [] + + async def main() -> None: + session.push(ScrollScreen("hub", floating=False)) + async with session.busy_dialog("reordering channels…") as outer: + depths.append(len(session._stack)) + async with session.busy_dialog("moving Lakeside · 1/2") as inner: + assert inner is outer # the nested wait rides the card already up + depths.append(len(session._stack)) + outer.message = "moving Dorval · 2/2" # the owner retitles it as it goes + depths.append(len(session._stack)) + depths.append(len(session._stack)) + + await asyncio.wait_for(session.run(main()), timeout=5) + + assert depths == [2, 2, 2, 1] # pushed once, popped once, hub still underneath