^W is a stack verb, not a call-chain one

Pressing it in the packet viewer closed the viewer and stopped there, then fired
at whatever the reader pressed next. A screen opened from a key handler cannot
be awaited by its opener — a handler is sync, so the live feed floats the viewer
with a detached task — and the sentinel went only to the top screen, so the
unwind it raised had nowhere to propagate and died in that task. The live feed
below was meanwhile parked on a visit.result() that no press would resolve, and
the flag stayed armed to unwind at the next navigation boundary the reader
happened to cross. The chat's delivery paths and the trace screen's path flows
open the same way and had the same fault.

The unwind now arms every frame on the stack, top first, down to but never
including the root, stopping at anything modal for the reason the top-of-stack
refusal already gives. Every frame is on the stack whether or not something
awaits it, so the stack is the reliable path down; resolving a frame nothing is
waiting on is inert.

The detached launches go through session.run_detached, which absorbs the
PopToMenu its task cannot carry — a duplicate of an unwind already travelling
out through the screen that opened it — so a press no longer leaves an
unretrieved task error behind. Flows keep their own finally blocks.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5 committed 2026-08-31 02:19:56 -04:00
1 parent 332f81583a
commit 2a7d01108b
8 files changed
+158 -12

No files matched your search

+7 -1
View File
@@ -92,7 +92,13 @@ deliberately, one at a time, and say why in the code.
answered in `TuiSession._dispatch` and neither is ever advertised — a global verb has no
screen to belong to, and the F-key lane has only three free slots per screen. They are
stated once, on the About page. `test_navigation` walks every string literal in the
package to keep them out of the UI.
package to keep them out of the UI. ^W arms **every frame on the stack**, not just the
top (`request_pop_all`), stopping at anything modal: a screen opened from a key handler
— the packet viewer, the chat's delivery paths, a trace path flow — runs in a task no
navigation frame awaits, so an unwind sent only to the top died there while the hub
below sat on a `visit.result()` nothing would resolve. Such a flow is launched through
`session.run_detached`, which absorbs the duplicate `PopToMenu` its task cannot carry;
the stack is what the unwind actually travels down.
- `modal` is *owning the keyboard* (a prompt, progress, a busy splash); `floating` is only
*drawn as a box*. They are not the same flag: a select list floats and is not modal, the
busy splash is modal and does not float. ^W declines to unwind past anything modal.
+1 -1
View File
@@ -675,7 +675,7 @@ class ChatScreen(Screen):
self._paths_open = False
self._session.invalidate()
asyncio.ensure_future(run())
self._session.run_detached(run())
def _begin_paste(self, data: str) -> None:
"""Confirm a clipboard paste on an amber dialog, then insert it into the compose line.
+1 -1
View File
@@ -425,7 +425,7 @@ class LiveFeedScreen(Screen):
# that arrive while it is open instead of freezing at this snapshot.
source=lambda: list(self._feed),
)
asyncio.ensure_future(self._session.run_screen(viewer))
self._session.run_detached(self._session.run_screen(viewer))
# --- rendering ---------------------------------------------------------------------
+1 -1
View File
@@ -783,7 +783,7 @@ class TraceScreen(Screen):
self._dialog_open = False
self._session.invalidate()
asyncio.ensure_future(run())
self._session.run_detached(run())
def _reverse_path(self) -> None:
"""Flip the walked path end-for-end and re-arm on the reversed direction.
+66 -8
View File
@@ -508,12 +508,32 @@ class TuiSession:
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`.
Otherwise it sets the unwind flag and resolves **every** frame's future with
:data:`~meshterm.ui.tui.screen.POP_ALL` — top first, down to but never including
the root — which each frame awaiting one turns into
:class:`~meshterm.ui.tui.screen.PopToMenu`.
Arming the whole stack, not just the top, is what makes ^W a *stack* verb rather
than a *call chain* one. A screen opened from a key handler cannot be awaited by
its opener — a handler is sync, so the live feed floats the packet viewer with
``ensure_future(run_screen(...))`` and the chain that would have carried an unwind
ends in a detached task. Sending the sentinel only to the top left that unwind to
die there while the hub below sat on a ``visit.result()`` nothing would resolve:
^W closed the viewer and stopped, and the still-armed flag fired at whatever the
reader pressed next instead (JP, 2026-08-31). Every frame is on the stack whether
or not anything awaits it, so the stack is the reliable path down.
The walk stops at a **modal** frame for the reason the top-of-stack refusal above
gives: work in flight is not to be discarded out from under itself. The flag stays
armed, so the unwind still fires at the next navigation boundary past it. Resolving
a frame that is not being awaited is inert — the value is simply never read, and
:meth:`~meshterm.ui.tui.screen.Screen.resolve` no-ops on a screen with no future
at all.
The flag matters independently of the futures: 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.
@@ -522,8 +542,12 @@ class TuiSession:
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)
for screen in reversed(self._stack):
if screen is self._root:
break # the root is where the unwind lands; it is not unwound itself
if screen is not top and screen.modal:
break
screen.resolve(POP_ALL)
return True
def unwound(self) -> None:
@@ -685,6 +709,40 @@ class TuiSession:
# --- async prompt helpers ------------------------------------------------
def run_detached(self, work: Any) -> "asyncio.Future":
"""Run ``work`` — a flow that opens a screen — off a key handler, unawaited.
A screen's ``handle`` is synchronous, so a key that opens something over the
current screen (the live feed's packet viewer, the chat's delivery paths, the
trace screen's path flows) can only *start* the flow, as a task. That task sits
outside the navigation call chain: nothing awaits it, so a
:class:`~meshterm.ui.tui.screen.PopToMenu` raised inside it has nowhere to
propagate and lands in the event loop's exception handler as an unretrieved
error.
Absorbing it here is safe because the unwind never travelled this way to begin
with: ^W arms every frame on the stack (see :meth:`request_pop_all`), so the
screen that opened this one carries the unwind out on its own awaited frame. What
this catch drops is a duplicate of an unwind already in flight — and the flow's
own ``finally`` blocks still run on the way through it.
Args:
work: The coroutine to run, usually a :meth:`run_screen` call.
Returns:
The task, for a caller that wants to cancel or await it. The app's own
callers are key handlers and ignore it; the screen they opened is on the
stack, which is how everything else finds it.
"""
async def guarded() -> None:
try:
await work
except PopToMenu:
pass # the stack carries the unwind; this task was never on its path
return asyncio.ensure_future(guarded())
async def run_screen(self, screen: Screen) -> Any:
"""Push a screen, await its result, then pop it.
+4
View File
@@ -43,6 +43,10 @@ class _StubSession:
def invalidate(self) -> None:
self.invalidations += 1
def run_detached(self, work): # noqa: ANN001, ANN201
"""Start a key handler's flow as a task, as ``TuiSession.run_detached`` does."""
return asyncio.ensure_future(work)
class _StubContext:
"""Minimal :class:`~meshterm.context.AppContext` stand-in for chat tests."""
+4
View File
@@ -54,6 +54,10 @@ class _FakeSession:
self.dialogs.append((prompt, buttons, kwargs))
return self.dialog_answer
def run_detached(self, work): # noqa: ANN001, ANN201
"""Start a key handler's flow as a task, as ``TuiSession.run_detached`` does."""
return asyncio.ensure_future(work)
def _trace(*snrs: float, success: bool = True, target: str = "Alice") -> TraceResult:
"""Build a trace with one hop per SNR reading."""
+74
View File
@@ -727,3 +727,77 @@ def test_only_navigational_layers_are_non_modal() -> None:
assert BusyScreen("checking…").modal is True
assert Screen().modal is False
assert CANCEL is not POP_ALL
async def test_pop_all_unwinds_from_a_screen_a_key_handler_opened() -> None:
"""^W in the packet viewer unwinds, though nothing awaits the frame that opened it.
A screen opened from a key handler cannot be awaited by its opener — a handler is
sync, so the live feed floats the viewer with ``ensure_future(run_screen(...))`` and
the call chain that would have carried the unwind ends in a detached task. The hub
below is meanwhile parked on ``visit.result()``, which no press resolves. ^W used to
close the viewer and stop there, leaving the flag armed to fire on some later
keystroke — the unwind arrived at the next thing the reader did instead of at the
key they pressed (JP, 2026-08-31).
"""
with create_pipe_input() as inp:
session = _session(inp)
landed: list[str] = []
popped: list[str] = []
async def main() -> None:
hub = ScrollScreen("the live feed", floating=False)
try:
async with session.stay(hub) as visit:
viewer = ScrollScreen("a packet")
# Exactly how a key handler opens one: detached, never awaited.
asyncio.ensure_future(session.run_screen(viewer))
await asyncio.sleep(0.05) # let it push
assert session.top is viewer
inp.send_text(POP_ALL_KEY)
await visit.result()
except PopToMenu:
landed.append("menu")
finally:
popped.append("hub")
await asyncio.wait_for(session.run(main()), timeout=5)
assert landed == ["menu"], "^W must reach the menu, not stop at the screen it was pressed on"
assert popped == ["hub"]
assert session._stack == []
async def test_a_detached_flow_absorbs_the_unwind_it_cannot_carry() -> None:
"""The task a key handler starts is off the navigation chain, so the copy stops there.
``request_pop_all`` arms every frame, so the unwind is already travelling out through
the screen that opened this one. Left to propagate here as well it would reach nothing
but the event loop's exception handler, logged as an unretrieved task error. The
flow's own cleanup still runs on the way through.
"""
session = TuiSession(output=DummyOutput())
steps: list[str] = []
async def work() -> None:
try:
steps.append("opened")
raise PopToMenu()
finally:
steps.append("cleaned up")
task = session.run_detached(work())
await task
assert task.exception() is None, "an unwind must not become an unretrieved task error"
assert steps == ["opened", "cleaned up"]
async def test_a_detached_flow_still_reports_a_real_failure() -> None:
"""Only the unwind is absorbed — a broken flow still surfaces as a task error."""
session = TuiSession(output=DummyOutput())
async def work() -> None:
raise RuntimeError("the flow broke")
task = session.run_detached(work())
with pytest.raises(RuntimeError):
await task