Introduce a UI surface abstraction (ctx.ui) that tools use for all input and output instead of touching questionary or the console directly. Two backends implement it: PlainUi for scripted CLI runs (prints immediately, byte-for-byte unchanged) and TuiUi for the interactive menu (bounded, scrollable result windows over a full-screen TuiSession). The new meshtools/ui/tui package reimplements the slice of questionary the app used — validated text input, confirm, autocomplete, and selectable lists — plus framing, progress, and screen management. Swap the dependency from questionary to prompt_toolkit. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
166 lines
5.8 KiB
Python
166 lines
5.8 KiB
Python
"""The interactive main menu, built dynamically from the tool registry.
|
|
|
|
The menu groups registered tools by category and runs the selected tool's interactive flow
|
|
inside the full-screen :class:`~meshtools.ui.tui.session.TuiSession`. Because it is generated
|
|
from the registry, adding a tool automatically adds a menu entry with no changes here. The
|
|
persistent header shows the connection target and live passive-monitor counters; each tool's
|
|
prompts layer as dialogs, and its output appears in a bounded, scrollable result window.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from rich.text import Text
|
|
|
|
from .. import __version__
|
|
from ..context import AppContext
|
|
from ..tools import all_tools
|
|
from .surface import TuiUi
|
|
from .theme import make_console
|
|
from .tui import Choice, Separator, TuiSession
|
|
|
|
|
|
def _header(ctx: AppContext) -> Text:
|
|
"""Build the persistent one-line header (target + live monitor status).
|
|
|
|
Args:
|
|
ctx: The shared application context, read for the target and monitor counters.
|
|
|
|
Returns:
|
|
A Rich :class:`Text` shown at the top of every screen; re-read on each repaint so
|
|
the passive-monitor counters tick live.
|
|
"""
|
|
if ctx.mock:
|
|
target = "[warn]simulator[/warn]"
|
|
elif ctx.profile_name:
|
|
target = ctx.profile_name
|
|
elif ctx.selected_device is not None:
|
|
target = ctx.selected_device.label
|
|
else:
|
|
target = "[muted]no device[/muted]"
|
|
return Text.from_markup(
|
|
f"[brand]MeshTools[/brand] [muted]v{__version__}[/muted] · "
|
|
f"[muted]device:[/muted] {target} · [muted]{ctx.monitor.status_text()}[/muted]"
|
|
)
|
|
|
|
|
|
async def run_menu(ctx: AppContext) -> None:
|
|
"""Run the interactive menu loop inside the full-screen session until the user quits.
|
|
|
|
Installs the TUI surface, starts the session, and drives device selection, monitor
|
|
resume, and the menu loop on the session's event loop. The full-screen frame is torn
|
|
down before the closing message prints.
|
|
|
|
Args:
|
|
ctx: The shared application context.
|
|
"""
|
|
session = TuiSession(header=lambda: _header(ctx))
|
|
ctx.ui = TuiUi(session)
|
|
|
|
async def main() -> None:
|
|
try:
|
|
await _startup(ctx)
|
|
await _menu_loop(ctx, session)
|
|
finally:
|
|
# Stop background capture and close its run record even on an unexpected exit.
|
|
await ctx.monitor.aclose()
|
|
|
|
await session.run(main())
|
|
ctx.console.print("[muted]bye 73![/muted]")
|
|
|
|
|
|
async def _menu_loop(ctx: AppContext, session: TuiSession) -> None:
|
|
"""Show the tool menu and run selections until the user quits.
|
|
|
|
Args:
|
|
ctx: The shared application context.
|
|
session: The running TUI session.
|
|
"""
|
|
while True:
|
|
items: list = []
|
|
current_category: str | None = None
|
|
for tool in all_tools():
|
|
if tool.category != current_category:
|
|
current_category = tool.category
|
|
items.append(Separator(f"── {current_category} ──"))
|
|
items.append(Choice(title=f"{tool.name} — {tool.help}", value=tool.name))
|
|
items.append(Separator(" "))
|
|
items.append(Choice(title="quit", value="__quit__"))
|
|
|
|
selection = await session.select("What would you like to do?", items)
|
|
if selection in (None, "__quit__"):
|
|
return
|
|
await _run_selection(ctx, selection)
|
|
|
|
|
|
async def _startup(ctx: AppContext) -> None:
|
|
"""Pick a companion device (if needed) and resume passive monitoring.
|
|
|
|
Args:
|
|
ctx: The shared application context to update with the selection.
|
|
"""
|
|
if not (ctx.mock or ctx.explicit_selection):
|
|
from ..core.discovery import discover_devices
|
|
from .device_picker import prompt_device
|
|
|
|
devices = discover_devices()
|
|
chosen = await prompt_device(ctx.ui, devices, ctx.device_store.load())
|
|
if chosen is not None:
|
|
ctx.selected_device = chosen
|
|
ctx.port_override = chosen.port
|
|
await _resume_monitor(ctx)
|
|
|
|
|
|
async def _resume_monitor(ctx: AppContext) -> None:
|
|
"""Resume passive monitoring if it was left enabled, ignoring a benign start failure.
|
|
|
|
A failure to start (typically no companion device selected) is non-fatal: the
|
|
preference stays on, so monitoring resumes automatically once a device is available.
|
|
The header reflects the resulting state, so nothing needs to be printed here.
|
|
|
|
Args:
|
|
ctx: The shared application context.
|
|
"""
|
|
if not ctx.monitor.enabled:
|
|
return
|
|
try:
|
|
await ctx.monitor.start()
|
|
except Exception: # noqa: BLE001 - surface via the header, don't crash the menu
|
|
pass
|
|
|
|
|
|
async def _run_selection(ctx: AppContext, name: str) -> None:
|
|
"""Gather parameters for, execute, and present a single tool from the menu.
|
|
|
|
Args:
|
|
ctx: The shared application context.
|
|
name: The selected tool's name.
|
|
"""
|
|
from ..tools import get_tool
|
|
|
|
tool = get_tool(name)
|
|
if tool is None: # pragma: no cover - registry and menu are always in sync
|
|
ctx.ui.note(f"[err]Unknown tool: {name}[/err]")
|
|
await ctx.ui.present(title=name)
|
|
return
|
|
|
|
try:
|
|
params = await tool.prompt_params(ctx)
|
|
if params is None: # user cancelled a prompt
|
|
ctx.ui.discard()
|
|
return
|
|
result = await tool.execute(ctx, params)
|
|
except Exception as exc: # noqa: BLE001 - surface errors without crashing the menu
|
|
ctx.ui.note(f"[err]✗ {tool.name} failed:[/err] {exc}")
|
|
await ctx.ui.present(title=tool.name)
|
|
return
|
|
|
|
if result.message:
|
|
ctx.ui.note(result.message)
|
|
for artifact in result.artifacts:
|
|
ctx.ui.note(f"[ok]●[/ok] wrote [accent]{artifact}[/accent]")
|
|
await ctx.ui.present(title=tool.name)
|
|
|
|
|
|
# Exposed for tools that need a standalone console outside a context (rare).
|
|
default_console = make_console
|