From ea68b9f8905ec4d9979d6aafb51e10f6c99cd959 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sun, 30 Aug 2026 13:20:12 -0400 Subject: [PATCH] Navigation: the stack is the model, and ^W leaves it all at once MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Navigation was almost a stack already, and the survey in docs/survey-navigation.md catalogues where it wasn't. This is the machinery for the strict version, plus the one shortcut past it. A screen that owns a loop can now keep itself pushed for the whole visit: async with session.stay(screen) as visit: while True: chosen = await visit.result() One push, one pop, and the *object* survives its sub-screens — so the cursor, the sort, the scroll offset and any live filter are simply still there on the way back, rather than being approximated by a `default=` restore that can only recover the cursor and only when its row still exists. It also retires the pop-then-re-push-as-a-backdrop workaround: a screen that never left the stack already is one. ^W unwinds every frame at once, back to the main menu. It resolves the top screen with POP_ALL, which each navigation boundary turns into PopToMenu, and every frame pops itself in a finally on the way out — the same single-pop discipline applied N times. PopToMenu derives from BaseException so it crosses the `except Exception` guards that stop a broken tool from taking the menu down; those must not report an unwind as a tool failure. The flag it sets matters independently of the future: pressed during a device read there is nothing armed to carry the sentinel, so the next screen the flow tries to open refuses to open instead. It declines to fire over anything modal — an unanswered dialog, a progress bar, a busy splash — which is what `modal` is for. `floating` is only about being drawn as a box; a select list floats and is not modal, the busy splash is modal and does not float. ^Q quits from anywhere. Both chords are deliberately unadvertised: a global verb has no screen to belong to, so a footer atom or an F-key chip would ride on every screen, and the lane only has three free slots to begin with. A test walks every string literal in the package to keep them out of the UI. Quitting mid-screen used to abandon the coroutine driving the app: the chord exits the application straight from the key handler, so `run_async` returned while main() was still parked on a screen, and its finally — which closes the history and chat runs, stops the services and arms the exit watchdog — never ran. It is cancelled and awaited now. The menu is the root: built once, kept for the session, and the one frame that catches the unwind. Co-Authored-By: Claude Opus 5 (1M context) --- meshterm/ui/menu.py | 236 ++++++++++++++--------- meshterm/ui/tui/__init__.py | 12 +- meshterm/ui/tui/progress.py | 1 + meshterm/ui/tui/prompt.py | 6 + meshterm/ui/tui/screen.py | 35 ++++ meshterm/ui/tui/session.py | 227 +++++++++++++++++++++- tests/test_navigation.py | 365 ++++++++++++++++++++++++++++++++++++ 7 files changed, 785 insertions(+), 97 deletions(-) create mode 100644 tests/test_navigation.py diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index 307fec1..5afd6ff 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -35,6 +35,7 @@ from .widgets import battery_cell from .tui import ( CANCEL, Choice, + PopToMenu, ReconnectDialog, ScrollScreen, SelectScreen, @@ -459,104 +460,161 @@ async def _unpair_on_exit(ctx: AppContext) -> None: async def _menu_loop(ctx: AppContext, session: TuiSession) -> None: """Show the tool menu and run selections until the user quits. + The menu is the app's navigation **root**: it is built once and kept for the whole + session, so the cursor, any typed filter and the scroll offset are simply still there + when a tool closes — no ``default=`` restore, which could only ever recover the cursor. + It is also where the pop-all key lands: ^W raises + :class:`~meshterm.ui.tui.screen.PopToMenu` through every frame the user had opened, and + this is the one place that catches it. + + The menu is still *popped* while a full-screen tool runs (only a ``popup`` tool floats + over it). That is presentation, not navigation — the tool would hide it anyway — and the + screen object outliving the pop is what makes returning feel like a pop rather than a + rebuild. + Args: ctx: The shared application context. session: The running TUI session. """ - last_selection: str | None = None + # Two aligned columns — tool name, then its muted description — with no header + # line: these are commands, not tabular data, so the alignment alone carries it. + tools = [tool for tool in all_tools() if tool.menu_visible] + + def _label(tool) -> str: # noqa: ANN001 - registry Tool; typed at the source + title = tool.title or tool.name + icon = command_icon(tool.icon) + return f"{icon} {title}" if icon else title + + name_w = max((cell_len(_label(tool)) for tool in tools), default=0) + items: list = [] + current_category: str | None = None + for tool in tools: + if tool.category != current_category: + current_category = tool.category + items.append(section_heading(current_category)) + label = _label(tool) + row = Text(label) + row.append(" " * (name_w - cell_len(label) + 2)) + row.append(tool.help, style="muted") + # The tool's name is the row's identity and always fits; only the description + # runs long, so ←→ slide it alone under a pinned name (Choice.hscroll_from). + items.append(Choice(title=row, value=tool.name, hscroll_from=name_w + 2)) + items.append(Separator(" ")) + items.append(Choice(title=command_label("🚪 Quit"), value="__quit__")) + + # Drive the menu list ourselves (rather than via session.select) so it stays on the + # stack while the quit dialog floats over it: the confirm is drawn as a centered box + # on top of the still-visible menu, not as a screen that replaces it. + menu = SelectScreen( + "What would you like to do?", + items, + footer_hint="↑↓ move · type to filter · Enter select · Esc quit", + ) + session.set_root(menu) loop = asyncio.get_running_loop() - while True: - # Two aligned columns — tool name, then its muted description — with no header - # line: these are commands, not tabular data, so the alignment alone carries it. - tools = [tool for tool in all_tools() if tool.menu_visible] + try: + while True: + try: + await _menu_round(ctx, session, menu, tools, loop) + except _Quit as chosen: + ctx.unpair_on_exit = chosen.unpair + return + except PopToMenu: + # ^W from somewhere deep. Every frame between there and here has already + # popped itself on the way out; nothing is left to do but disarm and redraw + # the menu the user asked for. + session.unwound() + finally: + session.set_root(None) - def _label(tool) -> str: # noqa: ANN001 - registry Tool; typed at the source - title = tool.title or tool.name - icon = command_icon(tool.icon) - return f"{icon} {title}" if icon else title - name_w = max((cell_len(_label(tool)) for tool in tools), default=0) - items: list = [] - current_category: str | None = None - for tool in tools: - if tool.category != current_category: - current_category = tool.category - items.append(section_heading(current_category)) - label = _label(tool) - row = Text(label) - row.append(" " * (name_w - cell_len(label) + 2)) - row.append(tool.help, style="muted") - # The tool's name is the row's identity and always fits; only the description - # runs long, so ←→ slide it alone under a pinned name (Choice.hscroll_from). - items.append(Choice(title=row, value=tool.name, hscroll_from=name_w + 2)) - items.append(Separator(" ")) - items.append(Choice(title=command_label("🚪 Quit"), value="__quit__")) +class _Quit(Exception): + """The user confirmed the quit dialog; ``unpair`` says whether to drop the OS bond too. - # Drive the menu list ourselves (rather than via session.select) so it stays on the - # stack while the quit dialog floats over it: the confirm is drawn as a centered box - # on top of the still-visible menu, not as a screen that replaces it. Re-highlight the - # tool the user just backed out of so returning lands the cursor where they left. - menu = SelectScreen( - "What would you like to do?", - items, - default=last_selection, - footer_hint="↑↓ move · type to filter · Enter select · Esc quit", - ) - menu.future = loop.create_future() - session.push(menu) - ran_over_menu = False - try: - selection = await menu.future - if selection is CANCEL: # Esc at the top level - selection = None - # Both picking "quit" and pressing Esc ask to leave; confirm on a dialog floating - # 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__"): - # 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?", - buttons, - title="Quit MeshTerm", - default=len(buttons) - 1, # highlight Quit - footer_hint="Enter quit · Esc cancel", - prompt_style="warn", - button_style="selected", - button_idle_style="muted", - border_style="warn", - ) - 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 - 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 - last_selection = selection - # A popup tool runs while the menu is still pushed, so its prompts and - # result float over it as modal dialogs instead of replacing the screen. - tool = next((t for t in tools if t.name == selection), None) - if tool is not None and tool.popup: - ran_over_menu = True - await _run_selection(ctx, selection) - finally: - session.pop(menu) - if not ran_over_menu: + A menu round runs a whole tool inside itself, so "the user chose Quit" cannot be spelled + as a ``return`` — the loop would just show the menu again. It is raised instead, and + caught in the one frame that owns the decision to leave. + """ + + def __init__(self, *, unpair: bool) -> None: + """Record whether the OS pairing should be dropped on the way out.""" + super().__init__("quit") + self.unpair = unpair + + +async def _menu_round( + ctx: AppContext, + session: TuiSession, + menu: SelectScreen, + tools: list, + loop: "asyncio.AbstractEventLoop", +) -> None: + """Show the menu once, then run whatever it committed to. + + Split out of :func:`_menu_loop` so the whole of a round — the tool run included — sits + inside one ``try``, and an unwind raised anywhere in it lands on the menu rather than + escaping past the loop. + + Args: + ctx: The shared application context. + session: The running TUI session. + menu: The session-long menu screen (pushed here, popped before the tool runs). + tools: The menu-visible tools, in the order their rows were built. + loop: The running event loop, for the menu's per-round future. + + Raises: + _Quit: If the user confirmed the quit dialog. + PopToMenu: If ^W was pressed inside whatever this round ran. + """ + menu.future = loop.create_future() + session.push(menu) + ran_over_menu = False + try: + selection = await menu.future + if selection is CANCEL: # Esc at the top level + selection = None + # Both picking "quit" and pressing Esc ask to leave; confirm on a dialog floating + # 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__"): + # 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?", + buttons, + title="Quit MeshTerm", + default=len(buttons) - 1, # highlight Quit + footer_hint="Enter quit · Esc cancel", + prompt_style="warn", + button_style="selected", + button_idle_style="muted", + border_style="warn", + ) + # "Unpair & quit" forgets 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. Cancel (button or Esc → None) ends the round and redraws the menu, + # whose cursor never moved off the row they came from. + if choice in ("unpair", "quit"): + raise _Quit(unpair=choice == "unpair") + return + # A popup tool runs while the menu is still pushed, so its prompts and + # result float over it as modal dialogs instead of replacing the screen. + tool = next((t for t in tools if t.name == selection), None) + if tool is not None and tool.popup: + ran_over_menu = True await _run_selection(ctx, selection) + finally: + session.pop(menu) + if not ran_over_menu: + await _run_selection(ctx, selection) async def _startup(ctx: AppContext) -> bool: diff --git a/meshterm/ui/tui/__init__.py b/meshterm/ui/tui/__init__.py index 9cbb1ff..04fdc3e 100644 --- a/meshterm/ui/tui/__init__.py +++ b/meshterm/ui/tui/__init__.py @@ -5,6 +5,12 @@ content rendering), this package gives the interactive app a consistent, bounded UI: screens never overflow the terminal, long content scrolls, going deeper stacks dialogs over a dimmed parent, and Esc always dismisses the current layer. +Navigation is a strict stack: one push per screen entered, one pop per Esc, and the screen +object survives the whole visit so its cursor, sort and filter are still there when a +sub-screen closes (:meth:`~meshterm.ui.tui.session.TuiSession.stay`). The one shortcut past +it is ^W, which unwinds every frame at once by raising +:class:`~meshterm.ui.tui.screen.PopToMenu` through them. + Public API: - :class:`~meshterm.ui.tui.session.TuiSession` — the running session and prompt helpers. - :class:`~meshterm.ui.tui.select.Choice` / :class:`~meshterm.ui.tui.select.Separator` @@ -26,9 +32,9 @@ from .prompt import ( TypedConfirmDialog, byte_counter, ) -from .screen import CANCEL, BusyScreen, Screen, ScrollScreen +from .screen import CANCEL, BusyScreen, PopToMenu, Screen, ScrollScreen from .select import Choice, DeleteRequest, SelectScreen, Separator -from .session import TuiSession +from .session import TuiSession, Visit from .spinner import Spinner __all__ = [ @@ -49,6 +55,8 @@ __all__ = [ "Spinner", "BusyOverlay", "CANCEL", + "PopToMenu", + "Visit", "DM_BYTE_LIMIT", "CHANNEL_BYTE_LIMIT", "byte_counter", diff --git a/meshterm/ui/tui/progress.py b/meshterm/ui/tui/progress.py index 859969b..dc7de7a 100644 --- a/meshterm/ui/tui/progress.py +++ b/meshterm/ui/tui/progress.py @@ -39,6 +39,7 @@ class ProgressScreen(Screen): footer_hint = "working…" floating = True + modal = True # work in flight owns the keyboard; ^W must not unwind out from under it @property def fkey_lane(self): diff --git a/meshterm/ui/tui/prompt.py b/meshterm/ui/tui/prompt.py index f539f78..6debc06 100644 --- a/meshterm/ui/tui/prompt.py +++ b/meshterm/ui/tui/prompt.py @@ -233,8 +233,14 @@ class _KeylessDialog(Screen): **empty** rather than dim when the action is not a thing on this screen *at all* — dim is for a thing that just isn't available this paint — so these dialogs draw the bare key numbers (see :mod:`~meshterm.ui.tui.fkeys`). + + Every one of them is also :attr:`~meshterm.ui.tui.screen.Screen.modal`: a prompt is an + unanswered question, so the pop-all key (^W) declines to unwind past it and the reader + answers or Escs out first. """ + modal = True + @property def fkey_lane(self): """No slots: nothing on a prompt pages, jumps, or needs promoting off a chord.""" diff --git a/meshterm/ui/tui/screen.py b/meshterm/ui/tui/screen.py index c6e34bc..1560788 100644 --- a/meshterm/ui/tui/screen.py +++ b/meshterm/ui/tui/screen.py @@ -26,6 +26,31 @@ from .spinner import Spinner #: legitimately selected ``None`` value. CANCEL = object() +#: Sentinel the session resolves the top screen's future with when the pop-all key is +#: pressed (^W). It is never a legitimate result: every navigation boundary that sees it +#: turns it straight into :class:`PopToMenu`, so no caller ever has to test for it. +POP_ALL = object() + + +class PopToMenu(BaseException): + """Raised through every awaiting navigation frame to unwind to the main menu. + + The whole realized path is a stack of ``await``\ s — a screen's caller awaiting its + result, that caller's caller awaiting *it* — so the one way to leave every frame at + once is to raise through them all. Each frame pops its own screen in a ``finally`` on + the way out, which is exactly the strict single-pop discipline applied N times: no + screen is ever dropped without its owner unwinding. + + It derives from :class:`BaseException`, not :class:`Exception`, for the same reason + :class:`asyncio.CancelledError` does: the app is full of ``except Exception`` guards + that stop a misbehaving tool from taking down the menu + (:func:`~meshterm.ui.menu._run_selection` is the widest), and an unwind must pass + through them rather than be swallowed and reported as a tool failure. ``finally`` + blocks still run, so nothing leaks. + + Caught in exactly one place — the main menu loop, which is the unwind's destination. + """ + class Screen: """Base class for every TUI layer. @@ -37,6 +62,14 @@ class Screen: future: Resolved with the screen's result (or :data:`CANCEL`) when it commits. floating: Whether the session should draw this screen as a centered dialog over the dimmed screen beneath it (deeper layers float; the base does not). + modal: Whether this layer is a *dialog* — a prompt or a running operation that + owns the keyboard until it is answered or finishes. Distinct from + :attr:`floating`, which is only about how the layer is drawn: an ordinary + select list floats as a box and is not modal, while a progress dialog is + modal and a full-frame busy splash is modal without floating at all. The + pop-all key (^W) refuses to fire while a modal layer is on top, so an unwind + can never blow past an unanswered question or yank the stack out from under + work in flight. grow_only: Whether a floating dialog may only ever grow. Its box is sized to the tallest body — and, for a natural-width dialog, the widest — it has shown, not the current one, so a screen whose content swings as it changes (the packet @@ -55,6 +88,7 @@ class Screen: title: str = "" footer_hint: str = "Esc back" floating: bool = True + modal: bool = False grow_only: bool = False chrome: bool = True banner: Optional[Sequence[str]] = None @@ -587,6 +621,7 @@ class BusyScreen(Screen): footer_hint = "working…" floating = False + modal = True # work in flight owns the keyboard; ^W must not unwind out from under it @property def fkey_lane(self): diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index e83b661..7759876 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -43,7 +43,7 @@ from .prompt import ( TypedConfirmDialog, Validator, ) -from .screen import CANCEL, BusyScreen, Screen, ScrollScreen +from .screen import CANCEL, POP_ALL, BusyScreen, PopToMenu, Screen, ScrollScreen from .spinner import spinner_interval from .select import Choice, ReorderScreen, SelectScreen, Separator @@ -62,12 +62,23 @@ from .select import Choice, ReorderScreen, SelectScreen, Separator #: A chord's letter is the mnemonic of the *action*, not of one screen's word for it — #: ``locate`` is ^U for **you** (JP, 2026-08-09), the same key on the map and in the mesh #: walk, because what it names on both is our own node. +#: +#: Two of these are app-wide rather than a screen's: ``to_menu`` (^W) unwinds the whole +#: navigation stack back to the main menu, and ``quit`` (^Q, alongside the older ^C) leaves +#: the app from anywhere. Neither is advertised in a footer hint or an F-key chip — the lane +#: has three free slots per screen and a global verb would claim one on every screen forever, +#: so both are stated once on the About page's key list instead (JP, 2026-08-30). ^W was +#: picked for the close-this-whole-thing reflex; both were verified deliverable on the +#: Canadian Multilingual layout (^W ``U+0017``, ^Q ``U+0011``) and neither is eaten by the +#: terminal — prompt_toolkit's raw mode clears ``IXON``/``IXOFF``, so ^Q is not XON here. _CTRL_LETTER_CHORDS: dict[str, str] = { "c": "quit", "p": "paths", + "q": "quit", "r": "retry", "u": "locate", "v": "paste_clipboard", + "w": "to_menu", } #: Maps prompt_toolkit keys to the normalized action names screens understand. @@ -316,6 +327,58 @@ def _message_border(message: "Text | str") -> str: return "accent" +class Visit: + """One screen's stay on the stack, handed out by :meth:`TuiSession.stay`. + + Holds nothing but the session and the screen; :meth:`result` arms a fresh future on that + screen and awaits it, leaving the screen exactly where it is. Calling it again is the + next round of the same visit — the loop shape a hub screen wants. + """ + + __slots__ = ("_session", "_screen") + + def __init__(self, session: "TuiSession", screen: Screen) -> None: + """Bind a visit to its session and screen, and arm the screen's first round.""" + self._session = session + self._screen = screen + self._arm() + + @property + def screen(self) -> Screen: + """The screen being visited (the same object for the whole stay).""" + return self._screen + + def _arm(self) -> None: + """Give the screen a fresh future to resolve into. + + A visited screen is *always* armed — from the moment it is pushed until the visit + ends — because it is on the stack the whole time and a key can reach it whenever it + is on top. Arming only inside :meth:`result` would leave a gap between rounds in + which :meth:`~meshterm.ui.tui.screen.Screen.resolve` has nowhere to put its value + and the press is silently dropped. + """ + self._screen.future = asyncio.get_running_loop().create_future() + + async def result(self) -> Any: + """Await one round of the visited screen: its resolved value, or ``CANCEL`` on Esc. + + A round already resolved — because the screen was armed while the caller was still + busy with the last one — is returned immediately rather than waited for again. + + Raises: + PopToMenu: If the pop-all key was pressed, here or while the caller was busy. + """ + self._session._check_unwind() + future = self._screen.future + if future is None: + self._arm() + future = self._screen.future + try: + return self._session._unpack(await future) + finally: + self._arm() # the next round is live the moment this one is read + + class TuiSession: """A running full-screen TUI: screen stack, frame, input loop, and async prompts.""" @@ -353,6 +416,13 @@ class TuiSession: # full-repaint treatment. Reconciled against the layers actually drawn on every paint # (see :meth:`_reconcile_layers`). self._layers: dict[str, tuple[str, bool]] = {} + # Armed by the pop-all key (^W) and disarmed by the menu loop once it has caught the + # unwind. While armed, every navigation boundary raises PopToMenu rather than showing + # another screen — see :meth:`request_pop_all`. + self._unwinding = False + # The screen the unwind lands on (the main menu), so ^W can no-op when it is already + # the top rather than pointlessly rebuilding it. ``None`` until the menu declares it. + self._root: Optional[Screen] = None # --- stack --------------------------------------------------------------- @@ -395,6 +465,10 @@ class TuiSession: (their callers pop them in ``finally``), so dropping any stragglers here is safe. """ self._stack.clear() + # A reset is its own unwind — the caller has already abandoned whatever was running + # (see :func:`~meshterm.ui.menu._session_loop`), so an armed ^W has nothing left to + # unwind and would otherwise fire into the reconnect flow that replaces it. + self._unwinding = False self._expose_overlay() self.invalidate() @@ -409,6 +483,111 @@ class TuiSession: if self._overlay is not None and not self._stack: self._overlay.restart() + # --- navigation ---------------------------------------------------------- + + def set_root(self, screen: Optional[Screen]) -> None: + """Declare ``screen`` the navigation root — where an unwind lands. + + The main menu calls this with its own list. Only two things depend on it: ^W is a + no-op while the root is already the top screen (you cannot go back to where you + are), and nothing else in the app needs to know which screen is the menu. + + Args: + screen: The root screen, or ``None`` to forget it (the menu on its way out). + """ + self._root = screen + + def request_pop_all(self) -> bool: + """Arm the unwind to the navigation root (the ^W key). Returns whether it fired. + + Two refusals, both deliberate: + + * **A modal layer is on top.** A dialog is an unanswered question and a progress or + busy screen is work in flight (:attr:`~meshterm.ui.tui.screen.Screen.modal`); + unwinding past either would discard something the user is in the middle of, so ^W + simply does nothing there and they answer or wait first. + * **The root is already the top.** There is nowhere to go. + + Otherwise it sets the unwind flag and resolves the top screen's future with + :data:`~meshterm.ui.tui.screen.POP_ALL`, which the frame awaiting it turns into + :class:`~meshterm.ui.tui.screen.PopToMenu`. The flag matters independently of the + future: a key can arrive while *no* screen is awaiting anything (mid device read, + under the busy overlay), and then the unwind is raised by the next navigation + boundary instead — see :meth:`_check_unwind`. + + Returns: + ``True`` if the unwind was armed, ``False`` if it was refused. + """ + top = self.top + if top is not None and (top.modal or top is self._root): + return False + self._unwinding = True + if top is not None: + top.resolve(POP_ALL) + return True + + def unwound(self) -> None: + """Disarm the unwind — called by the menu loop once it has caught :class:`PopToMenu`.""" + self._unwinding = False + + def _check_unwind(self) -> None: + """Raise :class:`PopToMenu` if an unwind is armed, before showing another screen. + + Every navigation boundary calls this on the way *in* as well as reading the result on + the way out, which is what makes ^W work during a device read: the key arms the flag + while no future is armed to carry :data:`POP_ALL`, and the very next screen the flow + tries to open refuses to open and unwinds instead. + """ + if self._unwinding: + raise PopToMenu() + + @staticmethod + def _unpack(result: Any) -> Any: + """Return a screen's result, turning :data:`POP_ALL` into :class:`PopToMenu`. + + The sentinel exists only to travel through an ``asyncio.Future``; no caller in the + app ever sees it, so it is converted at the one boundary that reads a future. + """ + if result is POP_ALL: + raise PopToMenu() + return result + + @asynccontextmanager + async def stay(self, screen: Screen) -> AsyncIterator["Visit"]: + """Keep ``screen`` pushed for a whole visit while its sub-screens come and go. + + The counterpart to :meth:`run_screen`, and the shape every screen that *owns a loop* + should use:: + + screen = ContactsScreen(...) + async with session.stay(screen) as visit: + while True: + chosen = await visit.result() + if chosen is CANCEL: + return + await open_node_detail(ctx, chosen) # nests above the list + + One push, one pop, and the object survives the whole visit — so the cursor, the sort, + the scroll offset and any live filter are simply still there when a sub-screen closes, + without a ``default=`` restore that can only ever recover the cursor. Because the + screen never leaves the stack, a dialog raised from inside the loop already has it as + a backdrop, and a full-frame sub-screen pushed above it draws over it (see + :meth:`_base_index`) — the two things callers used to arrange by popping and + re-pushing the same screen by hand. + + Args: + screen: The screen to keep pushed for the duration of the block. + + Yields: + A :class:`Visit` whose :meth:`~Visit.result` awaits one round of the screen. + """ + self._check_unwind() + self.push(screen) + try: + yield Visit(self, screen) + finally: + self.pop(screen) + def invalidate(self) -> None: """Request a repaint if the application is running.""" if self._app is not None: @@ -514,14 +693,20 @@ class TuiSession: Returns: The screen's resolved value, or :data:`~meshterm.ui.tui.screen.CANCEL`. + + Raises: + PopToMenu: If the pop-all key was pressed — on this screen, or while the caller + was busy and had nothing pushed at all. """ + self._check_unwind() loop = asyncio.get_running_loop() screen.future = loop.create_future() self.push(screen) try: - return await screen.future + result = await screen.future finally: self.pop(screen) + return self._unpack(result) async def select( self, @@ -1086,18 +1271,27 @@ class TuiSession: loop = asyncio.get_running_loop() modifier_watch.start(lambda: loop.call_soon_threadsafe(self.invalidate)) box: dict[str, BaseException] = {} + task: dict[str, asyncio.Future] = {} async def driver() -> None: try: await main + except asyncio.CancelledError: + raise except BaseException as exc: # noqa: BLE001 - re-raised after the app unwinds box["exc"] = exc finally: - if self._app is not None and not self._app.is_done: + # ``is_running`` rather than ``not is_done``: prompt_toolkit clears its + # future on the way out, which makes ``is_done`` read False again once the + # app has already finished — and ``exit()`` on a finished app raises. This + # ``finally`` now also runs *after* the app is gone (the quit chords exit it + # from under us and ``run`` then cancels this task), so it has to tell "still + # up" from "already down" rather than "not yet finished". + if self._app is not None and self._app.is_running: self._app.exit() def pre_run() -> None: - asyncio.ensure_future(driver()) + task["driver"] = asyncio.ensure_future(driver()) # Don't let prompt_toolkit install its own loop exception handler: on any stray # background-task error it prints a traceback and a "Press ENTER to continue..." @@ -1106,6 +1300,20 @@ class TuiSession: # file log (see :func:`meshterm.persistence.logging.configure_logging`) and never # touches the screen. Errors from ``main`` still propagate via ``driver``/``box``. await self._app.run_async(pre_run=pre_run, set_exception_handler=False) + # The app can also exit from *under* the driver: the quit chords (^Q/^C) call + # ``Application.exit`` straight from the key handler, so ``run_async`` returns while + # ``main`` is still parked on whatever screen was up. Left alone, that coroutine is + # simply abandoned mid-await and its ``finally`` never runs — which is where the + # history and chat runs are closed, the background services stopped, and the exit + # watchdog armed. Cancel it and wait for the unwind so quitting from anywhere tears + # down exactly as much as quitting from the menu does. + driver_task = task.get("driver") + if driver_task is not None and not driver_task.done(): + driver_task.cancel() + try: + await driver_task + except asyncio.CancelledError: + pass if "exc" in box: raise box["exc"] @@ -1465,8 +1673,8 @@ class TuiSession: just the screen actions: right Ctrl-V pastes into a compose line instead of typing a ``v``, right Ctrl-C quits. - The two session-level actions are answered here rather than forwarded — no screen ever - sees ``quit`` or ``paste_clipboard``. + The three session-level actions are answered here rather than forwarded — no screen + ever sees ``to_menu``, ``quit`` or ``paste_clipboard``. The repaint keeps prompt_toolkit's fast differential paint; a frame carrying a glyph the terminal may draw narrower than pt reserves for it (an emoji) upgrades itself to a @@ -1493,6 +1701,13 @@ class TuiSession: action = _CTRL_CHORDS[action] elif action == "text" and data.lower() in _CTRL_LETTER_CHORDS and _right_ctrl_down(): action, data = _CTRL_LETTER_CHORDS[data.lower()], "" + if action == "to_menu": + # Pop every frame at once (^W). Refused over a dialog or work in flight; see + # request_pop_all. The repaint below is still wanted either way — a refusal + # changes nothing, and an armed unwind is about to change everything. + self.request_pop_all() + self.invalidate() + return if action == "quit": if self._app is not None: self._app.exit() diff --git a/tests/test_navigation.py b/tests/test_navigation.py new file mode 100644 index 0000000..12beb66 --- /dev/null +++ b/tests/test_navigation.py @@ -0,0 +1,365 @@ +"""Tests for the navigation stack: strict push/pop, kept state, and the two global chords. + +The app's realized path is a stack — the main menu at the bottom, one frame per screen or +dialog entered, one pop per Esc — and the machinery that guarantees it lives in +:mod:`meshterm.ui.tui.session` (``stay``/``Visit``/``run_screen``) and +:mod:`meshterm.ui.tui.screen` (``POP_ALL``/``PopToMenu``). These exercise the guarantees: +that a visit pushes and pops exactly once however many rounds it runs, that the screen +object outlives its sub-screens so its cursor and filter are still there on the way back, +and that ^W unwinds the whole stack while ^Q leaves the app — from anywhere, and never +through a dialog that is still asking something. +""" + +from __future__ import annotations + +import asyncio + +import pytest +from prompt_toolkit.input.defaults import create_pipe_input +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.select import Choice, SelectScreen +from meshterm.ui.tui.session import _CTRL_LETTER_CHORDS, _KEY_ACTIONS, TuiSession + +#: What the terminal actually sends for the two global chords (verified against the +#: prompt_toolkit key tables, and on the Canadian Multilingual layout with ``ToUnicodeEx``). +POP_ALL_KEY = "\x17" # ^W +QUIT_KEY = "\x11" # ^Q + + +def _session(inp) -> TuiSession: + """A headless session driven by a pipe, rendering nowhere.""" + return TuiSession(input=inp, output=DummyOutput()) + + +# --- the stack discipline ---------------------------------------------------- + + +async def test_a_visit_pushes_once_and_pops_once_however_many_rounds_it_runs() -> None: + """``stay`` is one push and one pop, not one per round. + + This is the difference from ``run_screen`` in a loop, which pops on every resolve and + leaves the screen off the stack while whatever it committed to runs. + """ + with create_pipe_input() as inp: + session = _session(inp) + screen = SelectScreen("hub", [Choice("a", 1), Choice("b", 2)]) + depths: list[int] = [] + + async def main() -> None: + async with session.stay(screen) as visit: + for _ in range(3): + depths.append(len(session._stack)) + screen.resolve(1) + assert await visit.result() == 1 + # A sub-screen opened from inside the loop nests *above* the hub. + child = ScrollScreen("child") + session.push(child) + depths.append(len(session._stack)) + session.pop(child) + + await asyncio.wait_for(session.run(main()), timeout=5) + assert depths == [1, 2, 1, 2, 1, 2] + assert session._stack == [], "the visit must pop its screen on the way out" + + +async def test_a_visit_keeps_the_screens_cursor_and_filter_across_a_sub_screen() -> None: + """Coming back from a sub-screen lands on the row you left, filter and all. + + Reusing the screen *object* is what buys this. A ``default=`` restore could only ever + recover the cursor, and only when the row it names still exists. + """ + with create_pipe_input() as inp: + session = _session(inp) + screen = SelectScreen( + "hub", [Choice("alpha", 1), Choice("beta", 2), Choice("gamma", 3)] + ) + + async def main() -> None: + async with session.stay(screen) as visit: + screen.handle("text", "a") # filter to the rows carrying an "a" + screen.handle("down") + before = (screen._filter, screen._index) + screen.resolve("go") + await visit.result() + await session.run_screen(ScrollScreen("a sub-screen")) + assert (screen._filter, screen._index) == before + + session_task = session.run(main()) + # The sub-screen is dismissed with Esc, which is the only key this flow needs. + inp.send_text("\x1b") + await asyncio.wait_for(session_task, timeout=5) + + +async def test_a_visited_screen_is_armed_from_the_moment_it_is_pushed() -> None: + """A key that lands before the caller loops back is kept, not dropped. + + The screen is on the stack for the whole visit, so it can be resolved at any moment — + including while the caller is still finishing the previous round. Arming only inside + :meth:`~meshterm.ui.tui.session.Visit.result` would leave a gap in which the press has + nowhere to go. + """ + with create_pipe_input() as inp: + session = _session(inp) + screen = ScrollScreen("hub") + + async def main() -> None: + async with session.stay(screen) as visit: + assert screen.future is not None, "armed by the push, before any round" + screen.resolve("early") # resolved before the caller asks for it + assert await visit.result() == "early" + # And the next round is live immediately, without another await first. + assert screen.future is not None and not screen.future.done() + screen.resolve("next") + assert await visit.result() == "next" + + await asyncio.wait_for(session.run(main()), timeout=5) + + +# --- ^W, the pop-all --------------------------------------------------------- + + +async def test_pop_all_unwinds_every_frame_at_once() -> None: + """^W from three screens deep pops all three and lands the caller past the whole flow.""" + with create_pipe_input() as inp: + session = _session(inp) + popped: list[str] = [] + landed: list[str] = [] + + async def main() -> None: + hub = ScrollScreen("hub") + try: + async with session.stay(hub) as visit: + try: + await session.run_screen(ScrollScreen("middle")) + finally: + popped.append("middle") + await visit.result() + except PopToMenu: + landed.append("menu") + finally: + popped.append("hub") + + inp.send_text(POP_ALL_KEY) + await asyncio.wait_for(session.run(main()), timeout=5) + assert landed == ["menu"], "the unwind must reach the frame that catches it" + assert popped == ["middle", "hub"], "every frame pops itself on the way out" + assert session._stack == [] + + +async def test_pop_all_passes_straight_through_an_except_exception_guard() -> None: + """An unwind is not a tool failure. + + The app wraps tool runs in ``except Exception`` so a broken tool cannot take the menu + down with it (:func:`meshterm.ui.menu._run_selection` is the widest such guard). An + unwind has to cross those without being caught and reported as an error, which is why + :class:`PopToMenu` derives from ``BaseException``. + """ + assert issubclass(PopToMenu, BaseException) + assert not issubclass(PopToMenu, Exception) + + with create_pipe_input() as inp: + session = _session(inp) + swallowed: list[str] = [] + landed: list[str] = [] + + async def a_tool() -> None: + try: + await session.run_screen(ScrollScreen("a tool's screen")) + except Exception: # noqa: BLE001 - the guard under test + swallowed.append("caught") + + async def main() -> None: + try: + await a_tool() + except PopToMenu: + landed.append("menu") + + inp.send_text(POP_ALL_KEY) + await asyncio.wait_for(session.run(main()), timeout=5) + assert swallowed == [] + assert landed == ["menu"] + + +async def test_pop_all_armed_while_nothing_is_pushed_fires_at_the_next_screen() -> None: + """^W during a device read still unwinds — at the next screen the flow tries to open. + + There is no future to carry the sentinel while the app sits under the busy overlay with + an empty stack, so the flag is what remembers the press. + """ + with create_pipe_input() as inp: + session = _session(inp) + opened: list[str] = [] + + async def main() -> None: + inp.send_text(POP_ALL_KEY) + await asyncio.sleep(0.05) # let the key reach the dispatcher + assert session.top is None, "nothing is pushed while the read is in flight" + with pytest.raises(PopToMenu): + await session.run_screen(ScrollScreen("the screen the read was for")) + opened.append("refused") + + await asyncio.wait_for(session.run(main()), timeout=5) + assert opened == ["refused"] + + +def test_pop_all_is_refused_over_anything_modal() -> None: + """A dialog is an unanswered question and progress is work in flight; ^W waits.""" + session = TuiSession(output=DummyOutput()) + for layer in ( + ButtonDialog("Delete it?", [("Cancel", False), ("Delete", True)]), + ProgressScreen("Working"), + BusyScreen("checking…"), + ): + session.push(layer) + assert session.request_pop_all() is False, f"{type(layer).__name__} must block ^W" + assert session._unwinding is False + session.pop(layer) + + +def test_pop_all_is_a_no_op_at_the_navigation_root() -> None: + """You cannot go back to where you already are.""" + session = TuiSession(output=DummyOutput()) + menu = SelectScreen("What would you like to do?", [Choice("a tool", "a")]) + session.set_root(menu) + session.push(menu) + assert session.request_pop_all() is False + assert session._unwinding is False + # One screen deeper, the same key fires. + deeper = ScrollScreen("a tool") + session.push(deeper) + assert session.request_pop_all() is True + assert deeper.future is None or True # resolving a screen with no future is harmless + + +def test_pop_all_resolves_the_top_screen_with_the_sentinel() -> None: + """The sentinel travels through the future; no caller in the app ever sees it.""" + session = TuiSession(output=DummyOutput()) + screen = ScrollScreen("deep") + + class _Fut: + def __init__(self) -> None: + self.value = None + + def done(self) -> bool: + return False + + def set_result(self, value: object) -> None: + self.value = value + + screen.future = _Fut() # type: ignore[assignment] + session.push(screen) + assert session.request_pop_all() is True + assert screen.future.value is POP_ALL # type: ignore[union-attr] + + +def test_a_stack_reset_disarms_a_pending_unwind() -> None: + """A disconnect abandons the flow itself, so an armed ^W has nothing left to unwind.""" + session = TuiSession(output=DummyOutput()) + session.push(ScrollScreen("deep")) + session.request_pop_all() + assert session._unwinding is True + session.reset() + assert session._unwinding is False + + +# --- ^Q, the quit ------------------------------------------------------------ + + +async def test_quit_from_a_nested_screen_still_runs_the_apps_teardown() -> None: + """^Q leaves from anywhere — and the flow's ``finally`` blocks still run. + + The chord exits the prompt_toolkit application straight from the key handler, so the + coroutine driving the app is parked on a screen when it returns. Left abandoned there, + the teardown that closes the history and chat runs, stops the services and arms the exit + watchdog would never happen. + """ + with create_pipe_input() as inp: + session = _session(inp) + torn_down: list[str] = [] + + async def main() -> None: + try: + await session.run_screen(ScrollScreen("two screens deep")) + finally: + torn_down.append("services closed") + + inp.send_text(QUIT_KEY) + await asyncio.wait_for(session.run(main()), timeout=5) + assert torn_down == ["services closed"] + + +# --- the bindings themselves ------------------------------------------------- + + +def test_both_global_chords_are_bound_on_both_ctrl_keys() -> None: + """^W and ^Q reach their action through the plain binding and the right-Ctrl rescue. + + The single chord table is what guarantees the second half: a chord added there can never + be bound without its rescue, which is the only way a layout that claims the right Ctrl as + a character-group modifier reaches it at all. + """ + assert _CTRL_LETTER_CHORDS["w"] == "to_menu" + assert _CTRL_LETTER_CHORDS["q"] == "quit" + from prompt_toolkit.keys import Keys + + assert _KEY_ACTIONS[Keys.ControlW] == "to_menu" + assert _KEY_ACTIONS[Keys.ControlQ] == "quit" + + +def test_neither_global_chord_is_advertised_anywhere() -> None: + """Both are deliberately undiscoverable in the UI — the About page states them instead. + + A global verb has no screen to belong to, so a footer atom or an F-key chip would have to + ride on *every* screen; the lane only has three free slots per screen to begin with. + """ + import ast + import re + from pathlib import Path + + root = Path(__file__).resolve().parents[1] / "meshterm" + chord = re.compile(r"\^[WQ]\b") + holders = (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef) + offenders: list[str] = [] + for path in sorted(root.rglob("*.py")): + tree = ast.parse(path.read_text(encoding="utf-8")) + # Docstrings explain the chords at length and are not what a reader of the UI sees; + # what matters is every string the module *states*. + docstrings = { + id(node.body[0].value) + for node in ast.walk(tree) + if isinstance(node, holders) + and node.body + and isinstance(node.body[0], ast.Expr) + and isinstance(node.body[0].value, ast.Constant) + and isinstance(node.body[0].value.value, str) + } + for node in ast.walk(tree): + if ( + isinstance(node, ast.Constant) + and isinstance(node.value, str) + and id(node) not in docstrings + and chord.search(node.value) + ): + offenders.append(f"{path.name}:{node.lineno}: {node.value.strip()[:70]}") + assert not offenders, "the global chords must not appear in any hint or chip:\n" + "\n".join( + offenders + ) + + +def test_only_navigational_layers_are_non_modal() -> None: + """``modal`` is about owning the keyboard, ``floating`` only about being drawn as a box. + + They are easy to conflate — most dialogs are both — so the two screens that break the + correlation are asserted outright: a plain select list floats and is not modal, and the + busy splash is modal without floating at all. + """ + assert SelectScreen("list", [Choice("a", 1)]).floating is True + assert SelectScreen("list", [Choice("a", 1)]).modal is False + assert BusyScreen("checking…").floating is False + assert BusyScreen("checking…").modal is True + assert Screen().modal is False + assert CANCEL is not POP_ALL