Short outcomes pop as OK dialogs instead of filling the result frame

A one-line result like "✓ flood advertisement sent" used to open the
full scrollable result window — a huge frame for a single sentence.
TuiUi.present() now collapses small, text-only output (at most 3 lines,
none wider than 76 cells) into a centered popup with an OK button,
floating over whatever screen is beneath; tables, long errors, and
multi-line output keep the window. Fixed centrally in present(), the
upgrade covers every such site at once: adverts, clock sync, backups,
key import, "applied N changes", tool failures, and future ones.

ButtonDialog learns to render a pre-styled (multi-line) Text prompt so
note markup survives into the popup, and the border echoes the message's
strongest tone (err > warn > accent). When the popup would sit on an
empty stack (a tool run from the popped main menu), a blank base frame
is pushed beneath it first — the same trick as the reconnect dialog —
so it draws as a floating box, not as the base.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Fable 5 committed 2026-07-10 01:32:58 -04:00
1 parent 920b3f8b83
commit 3a972ea743
5 files changed
+306 -17

No files matched your search

+57 -7
View File
@@ -6,8 +6,10 @@ implementations back it:
* :class:`PlainUi` (scripted CLI): prints immediately and uses a Rich progress bar, so CLI
behavior is byte-for-byte what it was before the TUI existed.
* :class:`TuiUi` (interactive menu): collects a tool's output and presents it in a bounded,
scrollable result window, and routes every prompt/progress through the full-screen
:class:`~meshterm.ui.tui.session.TuiSession`.
scrollable result window — or, when the whole result is just a line or two of text
("✓ flood advertisement sent"), as a small centered popup with an OK button instead of
a full window (see :func:`_collapse_to_message`) — and routes every prompt/progress
through the full-screen :class:`~meshterm.ui.tui.session.TuiSession`.
The interactive prompt methods are only ever reached from a tool's ``prompt_params`` (menu
only), so :class:`PlainUi` leaves them unsupported.
@@ -26,6 +28,44 @@ from .tui.session import TuiSession
#: A validator returns ``True`` when input is acceptable, or an error message to show.
Validator = Callable[[str], "bool | str"]
#: Buffered output no taller than this many lines qualifies for the message dialog —
#: the OK popup :meth:`TuiUi.present` shows instead of a full result window. Kept small:
#: a dialog is an acknowledgement, not a reading surface.
_DIALOG_MAX_LINES = 3
#: ... and no line may be wider than this many cells, so the popup stays a tidy box on a
#: typical terminal and never has to wrap. Anything wider (a long path, a verbose error)
#: falls back to the scrollable result window, which wraps properly.
_DIALOG_MAX_CELLS = 76
def _collapse_to_message(buffered: list[RenderableType]) -> Optional[Text]:
"""Collapse small, text-only buffered output into one dialog message.
This is the gate for :meth:`TuiUi.present`'s popup upgrade: output qualifies only
when everything buffered is plain note text (:class:`Text` — a table or panel from
``show()`` disqualifies the lot) totalling at most :data:`_DIALOG_MAX_LINES` lines,
none wider than :data:`_DIALOG_MAX_CELLS` cells. Styling (the ``[ok]``/``[err]``
markup on outcome notes) is preserved in the joined message.
Args:
buffered: The renderables collected since the last present.
Returns:
The lines joined into one :class:`Text`, or ``None`` when the output belongs in
the scrollable result window instead.
"""
if not buffered or not all(isinstance(item, Text) for item in buffered):
return None
lines: list[Text] = []
for item in buffered:
lines.extend(item.split("\n") or [item])
if len(lines) > _DIALOG_MAX_LINES:
return None
if any(line.cell_len > _DIALOG_MAX_CELLS for line in lines):
return None
return Text("\n").join(lines)
class Ui:
"""Abstract UI surface. See :class:`PlainUi` and :class:`TuiUi` for the two backends."""
@@ -402,18 +442,28 @@ class TuiUi(Ui):
self._buffer.append(Text.from_markup(markup))
async def present(self, *, title: str = "") -> None:
"""Show everything buffered since the last present in a scrollable window.
"""Show everything buffered since the last present; window or popup to fit.
Clears the buffer afterward. Does nothing if nothing was buffered (e.g. a tool
that only produced a file artifact and an empty message).
A short, text-only outcome (a line or two of notes — "✓ flood advertisement
sent") floats as a centered OK dialog over the current screen, so a one-line
result never commandeers the whole frame; anything bigger, or anything holding
a table/panel, opens the bounded scrollable result window as before (see
:func:`_collapse_to_message` for the exact gate). Clears the buffer afterward.
Does nothing if nothing was buffered (e.g. a tool that only produced a file
artifact and an empty message).
Args:
title: Heading for the result window.
title: Heading for the result window or popup.
"""
if not self._buffer:
return
body = self._buffer[0] if len(self._buffer) == 1 else Group(*self._buffer)
buffered = self._buffer
self._buffer = []
message = _collapse_to_message(buffered)
if message is not None:
await self.session.message_dialog(message, title=title)
return
body = buffered[0] if len(buffered) == 1 else Group(*buffered)
await self.session.scroll(body, title=title)
def discard(self) -> None:
+25 -9
View File
@@ -388,7 +388,7 @@ class ButtonDialog(Screen):
def __init__(
self,
prompt: str,
prompt: "str | Text",
buttons: list[tuple[str, object]],
*,
title: str = "",
@@ -403,7 +403,10 @@ class ButtonDialog(Screen):
"""Build a button dialog.
Args:
prompt: The question shown above the buttons.
prompt: The question shown above the buttons. A plain string is styled with
``prompt_style``; a pre-styled (possibly multi-line) :class:`Text` is
rendered as-is, so a caller can float richly-marked output — e.g. the
message dialog's "[ok]✓[/ok] …" outcome lines — without losing colour.
buttons: ``(label, value)`` pairs laid out left to right.
title: Optional dialog heading.
default: Index of the initially highlighted button.
@@ -428,6 +431,18 @@ class ButtonDialog(Screen):
self._button_style = button_style
self._button_idle_style = button_idle_style
def _prompt_lines(self) -> list[Text]:
"""The prompt as one styled :class:`Text` per line.
A plain-string prompt becomes a single line in ``prompt_style``; a :class:`Text`
prompt keeps its own spans and is split on newlines so each line can be centered
independently (centering the block as a whole would skew every line to the
longest one's margin).
"""
if isinstance(self._prompt, Text):
return list(self._prompt.split("\n")) or [Text("")]
return [Text(self._prompt, style=self._prompt_style)]
@property
def _button_row_width(self) -> int:
"""Display width of the button row (`` Label `` cells joined by 4-space gaps)."""
@@ -439,12 +454,13 @@ class ButtonDialog(Screen):
def dialog_width(self) -> int:
"""Natural outer width so the frame sizes the box to its content, not the terminal.
The widest of the prompt, button row, title, and footer hint, plus a comfortable
margin and the border — so a short confirm reads as a tidy box rather than a banner
stretched across the screen. The compositor still caps this to the terminal.
The widest of the prompt lines, button row, title, and footer hint, plus a
comfortable margin and the border — so a short confirm reads as a tidy box rather
than a banner stretched across the screen. The compositor still caps this to the
terminal.
"""
inner = max(
cell_len(self._prompt),
max(line.cell_len for line in self._prompt_lines()),
self._button_row_width,
cell_len(self.title),
cell_len(self.footer_hint),
@@ -452,15 +468,15 @@ class ButtonDialog(Screen):
return inner + 12 # panel padding + border, plus horizontal breathing room
def render_body(self, width: int) -> list[str]:
"""Render the prompt centered above a centered row of buttons."""
"""Render the prompt line(s) centered above a centered row of buttons."""
row = Text()
for i, (label, _value) in enumerate(self._buttons):
if i:
row.append(" ")
style = self._button_style if i == self._index else self._button_idle_style
row.append(f" {label} ", style=style)
prompt = Text(self._prompt, style=self._prompt_style)
return render_lines(Group(_center(prompt, width), Text(""), _center(row, width)), width)
parts = [_center(line, width) for line in self._prompt_lines()]
return render_lines(Group(*parts, Text(""), _center(row, width)), width)
def handle(self, action: str, data: str = "") -> None:
"""Move the highlight, commit on Enter or a shortcut key, or cancel on Esc."""
+60 -1
View File
@@ -69,6 +69,29 @@ _KEY_ACTIONS: dict[Any, str] = {
}
def _message_border(message: "Text | str") -> str:
"""Pick a message dialog's border style from the strongest tone in the text.
Outcome notes carry their severity as theme spans (``[err]``, ``[warn]``, ``[ok]``),
so the dialog frame can echo it: an error message gets the ``err`` border, a warning
(e.g. "device rebooting") the cautionary one, and anything else — successes included —
the standard accent. A plain string carries no spans and always reads as neutral.
Args:
message: The dialog's message, styled or plain.
Returns:
The Rich style name for the dialog border.
"""
if isinstance(message, Text):
styles = {str(span.style) for span in message.spans}
if "err" in styles:
return "err"
if "warn" in styles:
return "warn"
return "accent"
class TuiSession:
"""A running full-screen TUI: screen stack, frame, input loop, and async prompts."""
@@ -405,7 +428,7 @@ class TuiSession:
async def button_dialog(
self,
prompt: str,
prompt: "str | Text",
buttons: list[tuple[str, Any]],
*,
title: str = "",
@@ -423,6 +446,7 @@ class TuiSession:
ButtonDialog`): the colours, prompt, buttons, and single-key shortcuts are all
parametrised, so a caller can theme it (e.g. a destructive action in red) or wire
instant y/n keys. ``keys`` maps a shortcut character to the value it commits.
The prompt may be a pre-styled :class:`Text` (see the ButtonDialog docs).
"""
screen = ButtonDialog(
prompt,
@@ -468,6 +492,41 @@ class TuiSession:
)
return None if result is CANCEL else result
async def message_dialog(self, message: "Text | str", *, title: str = "") -> None:
"""Show a short outcome in a centered popup with a single OK button.
The lightweight acknowledgement counterpart of :meth:`scroll`: a one-line result
("✓ flood advertisement sent") doesn't warrant a full result window, so it floats
as a small dialog over whatever screen is beneath — Enter (OK) or Esc dismisses
it. The border takes the message's strongest tone (see :func:`_message_border`),
so an error pops red while a success stays in the standard accent.
When the screen stack is empty — a tool run straight from the main menu, which is
popped while the tool executes — a blank base frame is pushed first, because a
lone floating screen is otherwise drawn *as* the base (full-frame, no popup); the
same trick the reconnect dialog uses.
Args:
message: The outcome to show — a pre-styled :class:`Text` (note markup
survives into the dialog) or a plain string.
title: Optional dialog heading (typically the tool or action name).
"""
backdrop: Optional[ScrollScreen] = None
if not self._stack:
backdrop = ScrollScreen("", floating=False, footer_hint="")
self.push(backdrop)
try:
await self.button_dialog(
message,
[("OK", "ok")],
title=title,
footer_hint="Enter OK",
border_style=_message_border(message),
)
finally:
if backdrop is not None:
self.pop(backdrop)
async def scroll(
self, renderable: RenderableType, *, title: str = "", footer_hint: str = ""
) -> None:
+145
View File
@@ -0,0 +1,145 @@
"""Tests for the TUI output surface's window-or-popup presentation.
:meth:`TuiUi.present` upgrades a short, text-only result ("✓ flood advertisement sent")
to a centered OK dialog instead of a full scrollable window. These cover the collapse
gate (:func:`_collapse_to_message`), the routing between the two presentations, and the
severity-to-border mapping the message dialog applies (:func:`_message_border`).
"""
from __future__ import annotations
import asyncio
from typing import Any
from rich.table import Table
from rich.text import Text
from meshterm.ui.surface import _DIALOG_MAX_CELLS, TuiUi, _collapse_to_message
from meshterm.ui.tui.session import TuiSession, _message_border
# -- the collapse gate ------------------------------------------------------------
def test_collapse_accepts_a_short_note_and_keeps_its_styling() -> None:
"""A one-line success note qualifies, with its markup spans intact."""
note = Text.from_markup("[ok]✓[/ok] flood advertisement sent")
message = _collapse_to_message([note])
assert message is not None
assert message.plain == "✓ flood advertisement sent"
assert any(str(span.style) == "ok" for span in message.spans)
def test_collapse_joins_a_few_notes_into_one_message() -> None:
"""Two or three separate notes collapse into one multi-line dialog message."""
notes = [Text("✓ device clock set"), Text("● wrote backup.toml")]
message = _collapse_to_message(notes)
assert message is not None
assert message.plain == "✓ device clock set\n● wrote backup.toml"
def test_collapse_rejects_tall_output() -> None:
"""More lines than fit a tidy popup fall back to the result window."""
assert _collapse_to_message([Text(f"line {i}") for i in range(4)]) is None
def test_collapse_rejects_wide_lines() -> None:
"""A line too wide for the popup (a long path, say) falls back to the window."""
assert _collapse_to_message([Text("x" * (_DIALOG_MAX_CELLS + 1))]) is None
def test_collapse_rejects_non_text_renderables() -> None:
"""Any table/panel in the buffer sends the whole result to the window."""
assert _collapse_to_message([Text("note"), Table()]) is None
assert _collapse_to_message([]) is None
# -- present() routing --------------------------------------------------------------
class _RecordingSession:
"""Stands in for :class:`TuiSession`, recording which presentation was used."""
def __init__(self) -> None:
self.dialogs: list[tuple[Text, str]] = []
self.scrolls: list[tuple[Any, str]] = []
async def message_dialog(self, message: Text, *, title: str = "") -> None:
self.dialogs.append((message, title))
async def scroll(self, body: Any, *, title: str = "", footer_hint: str = "") -> None:
self.scrolls.append((body, title))
async def test_present_floats_a_short_note_as_a_dialog() -> None:
"""A single outcome note pops as an OK dialog, not a full result window."""
session = _RecordingSession()
ui = TuiUi(session) # type: ignore[arg-type]
ui.note("[ok]✓[/ok] zero-hop advertisement sent")
await ui.present(title="Advert")
assert session.scrolls == []
(message, title), = session.dialogs
assert message.plain == "✓ zero-hop advertisement sent"
assert title == "Advert"
async def test_present_keeps_big_output_in_the_result_window() -> None:
"""Tables (and any oversized output) still open the scrollable window."""
session = _RecordingSession()
ui = TuiUi(session) # type: ignore[arg-type]
ui.note("heading")
ui.show(Table(title="nodes"))
await ui.present(title="Nodes")
assert session.dialogs == []
assert [title for _, title in session.scrolls] == ["Nodes"]
async def test_present_clears_the_buffer_either_way() -> None:
"""After presenting, a second present has nothing to show (no double popup)."""
session = _RecordingSession()
ui = TuiUi(session) # type: ignore[arg-type]
ui.note("✓ done")
await ui.present(title="Once")
await ui.present(title="Twice")
assert len(session.dialogs) == 1 and session.scrolls == []
# -- the popup end-to-end through a real session ------------------------------------
async def test_message_dialog_floats_over_a_blank_backdrop_end_to_end() -> None:
"""On an empty stack the popup pushes a blank base beneath itself, then pops both.
This is the main-menu tool path: the menu is popped while a tool runs, so without
the backdrop the lone dialog would be drawn as the base (full-frame). Driving a
real session with piped keys proves Enter (OK) dismisses it and the stack unwinds.
"""
from prompt_toolkit.input.defaults import create_pipe_input
from prompt_toolkit.output import DummyOutput
with create_pipe_input() as inp:
session = TuiSession(input=inp, output=DummyOutput())
async def main() -> None:
inp.send_text("\r") # Enter commits the OK button
await session.message_dialog(
Text.from_markup("[ok]✓[/ok] flood advertisement sent"), title="Advert"
)
assert session._stack == [] # dialog and its backdrop both popped
await asyncio.wait_for(session.run(main()), timeout=5)
# -- the message dialog's border tone -----------------------------------------------
def test_message_border_echoes_the_strongest_tone() -> None:
"""err outranks warn; warn outranks the neutral accent; ok stays neutral."""
err = Text.from_markup("[err]✗ Trace failed:[/err] timeout")
warn = Text.from_markup("[warn]device rebooting[/warn]")
ok = Text.from_markup("[ok]✓[/ok] private key imported")
both = Text.from_markup("[warn]careful[/warn] [err]broken[/err]")
assert _message_border(err) == "err"
assert _message_border(warn) == "warn"
assert _message_border(ok) == "accent"
assert _message_border(both) == "err"
assert _message_border("plain string") == "accent"
+19
View File
@@ -512,6 +512,25 @@ def test_button_dialog_escape_cancels() -> None:
assert _run(screen, "escape") is CANCEL
def test_button_dialog_renders_a_styled_text_prompt_line_per_line() -> None:
"""A pre-styled multi-line Text prompt renders each line, keeping its content."""
message = Text.from_markup("[ok]✓[/ok] clock set\n[ok]●[/ok] wrote backup.toml")
screen = ButtonDialog(message, [("OK", "ok")])
body = "\n".join(screen.render_body(60))
plain = Text.from_ansi(body).plain
assert "✓ clock set" in plain
assert "● wrote backup.toml" in plain
assert "OK" in plain
def test_button_dialog_sizes_to_the_widest_prompt_line() -> None:
"""dialog_width follows the longest line of a multi-line Text prompt."""
wide = "a really quite long outcome line for sizing"
message = Text(f"short\n{wide}")
screen = ButtonDialog(message, [("OK", "ok")])
assert screen.dialog_width == len(wide) + 12 # matches the margin the dialog adds
def test_autocomplete_suggests_and_tab_completes() -> None:
"""Suggestions match case-insensitively; Tab fills the highlighted one; Enter commits."""
screen = AutocompleteScreen("target?", ["Alice", "Bob", "alfred"])