From d8d87d5b50c03379852d8839d9ba1d24e0916f83 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Fri, 10 Jul 2026 05:24:06 -0400 Subject: [PATCH] Trace becomes a live screen: pick a target, watch replies stream in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The menu's trace flow joins the living-screen pattern (chat, nodes, map). One recency-ordered picker — recently traced targets first, then contacts by freshness — replaces the target/samples/path prompt chain, and the screen opens tracing immediately: each reply lands in a newest-first log as it arrives, the route line and per-hop medians (with SNR quality bars) update live, and Enter / s / p run another burst, cycle the burst size, and edit the forced path without leaving the screen. Esc steps back to the picker, chat-style. The route line opens seeded from the target's last stored trace, so the path history last saw shows while the first reply is still in flight. Every burst persists exactly like a scripted run — one runs row, each trace recorded under it — and the scripted CLI keeps its one-shot table output unchanged. Co-Authored-By: Claude Fable 5 --- meshterm/tools/trace.py | 236 +++++++++++++------ meshterm/ui/trace_screen.py | 458 ++++++++++++++++++++++++++++++++++++ 2 files changed, 617 insertions(+), 77 deletions(-) create mode 100644 meshterm/ui/trace_screen.py diff --git a/meshterm/tools/trace.py b/meshterm/tools/trace.py index e38a2f9..465f094 100644 --- a/meshterm/tools/trace.py +++ b/meshterm/tools/trace.py @@ -1,8 +1,14 @@ -"""The ``trace`` tool: run repeated path traces and report aggregated SNR. +"""The ``trace`` tool: path traces to a target, live in the menu, one-shot on the CLI. -This is the measurement workhorse of the skeleton and the template every other tool -follows: it gathers params (interactively or from CLI flags), runs a service, persists -results, and renders modern Rich output. +In the interactive menu this opens the live trace screen +(:mod:`meshterm.ui.trace_screen`): pick a target from a recency-ordered list and traces +start streaming immediately — further bursts, sample counts, and a forced path are +keystrokes inside the screen, following the same living-screen pattern as chat and the +nodes list. On the CLI it stays a scriptable one-shot: run N traces, print the per-trace +table and the aggregate summary, exit. + +Both front ends persist identically: one ``runs`` row per burst with every trace recorded +under it, so stored history reads the same no matter where it came from. """ from __future__ import annotations @@ -10,78 +16,175 @@ from __future__ import annotations from typing import Any, Optional import typer +from rich.text import Text from ..context import AppContext -from ..core.models import LOCAL_DEVICE_LABEL +from ..core.models import LOCAL_DEVICE_LABEL, Contact from ..services import trace_runner from ..ui.widgets import stats_panel, traces_table from .base import Tool, ToolResult, register -#: Upper bound on traces per run — the per-trace table renders one column each, so -#: this keeps the output readable and the radio's duty cycle in check. +#: Upper bound on traces per scripted run — the per-trace table renders one column each, +#: so this keeps the output readable and the radio's duty cycle in check. MAX_TRACES = 9 +_BACK = "__back__" + @register class TraceTool(Tool): - """Trace the path to a target N times and summarize per-hop SNR.""" + """Trace the path to a target and watch per-hop SNR, live or scripted.""" name = "trace" title = "Trace" - help = "Run repeated path traces to a target and aggregate SNR" + help = "Trace the path to a target and watch per-hop SNR live" category = "Diagnostics" order = 10 async def prompt_params(self, ctx: AppContext) -> Optional[dict[str, Any]]: - """Interactively choose a target contact and sample count. + """Pick the first target for the live screen. Args: ctx: Shared application context. Returns: - A parameter dict, or ``None`` if the user cancelled. + ``{"live": True, "target": name}``, or ``None`` if the user backed out. """ - device = await ctx.device() - contacts = await device.get_contacts() - choices = [c.name for c in contacts] - prompt = "Target node (name or key prefix):" - # With no known contacts, fall back to a free-text entry so the user can still - # type a name or key prefix; otherwise suggest the known contacts. - if choices: - target = await ctx.ui.autocomplete(prompt, choices) - else: - target = await ctx.ui.text(prompt) - if not target: + target = await self._pick_target(ctx) + if target is None: return None + return {"live": True, "target": target} - samples_raw = await ctx.ui.text( - f"How many traces? (1-{MAX_TRACES})", default="3", validate=_is_valid_sample_count - ) - if samples_raw is None: - return None + async def execute(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: + """Run — without the outer run row on the live path. - # Optional explicit path, MeshCore-app style: comma-separated contact names - # and/or hex key prefixes (e.g. ``3d,f2,3d``). Blank lets the device route. - path_prompt = "Force a path? (comma-separated contacts/hex prefixes, blank = auto):" - validate_path = lambda v: _validate_path(v, contacts) # noqa: E731 - if choices: - path_spec = await ctx.ui.autocomplete(path_prompt, choices, validate=validate_path) - else: - path_spec = await ctx.ui.text(path_prompt, validate=validate_path) - if path_spec is None: - return None - - params: dict[str, Any] = {"target": target.strip(), "samples": int(samples_raw)} - if path_spec.strip(): - params["path"] = path_spec.strip() - return params - - async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: - """Run the traces, persist each one, and render the summary. + The live screen opens one ``runs`` row *per burst* (matching what a scripted + invocation records), so wrapping the whole screen session in another row would + double-log it. Scripted runs keep the base class's logging. Args: ctx: Shared application context. - params: ``target`` (str), ``samples`` (int), and the injected ``_run_id``. + params: Parameters for this invocation. + + Returns: + The :class:`ToolResult` from :meth:`run`. + """ + if params.get("live"): + return await self.run(ctx, params) + return await super().execute(ctx, params) + + async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: + """Open the live screen (menu) or run a persisted one-shot burst (CLI). + + Args: + ctx: Shared application context. + params: ``live`` + ``target`` from the menu picker; or ``target`` (str), + ``samples`` (int), optional ``path``, and the injected ``_run_id`` from + the CLI. + + Returns: + A :class:`ToolResult` with the aggregated statistics. + """ + if params.get("live"): + return await self._run_live(ctx, str(params["target"])) + return await self._run_cli(ctx, params) + + # -- interactive (menu) ------------------------------------------------------- + + async def _run_live(self, ctx: AppContext, target: str) -> ToolResult: + """Loop the live screen and the target picker until the user backs out. + + Backing out of a trace session (Esc) steps back to the target picker rather than + all the way to the main menu — the chat pattern — with the just-closed target + pre-highlighted; Esc from the picker returns to the menu. + + Args: + ctx: Shared application context. + target: The first target to open. + + Returns: + A :class:`ToolResult` counting the sessions and traces run. + """ + from ..ui.trace_screen import open_trace + + sessions = 0 + traces = 0 + current: Optional[str] = target + while current is not None: + traces += await open_trace(ctx, current) + sessions += 1 + current = await self._pick_target(ctx, default=current) + return ToolResult(summary={"sessions": sessions, "traces": traces}) + + async def _pick_target( + self, ctx: AppContext, *, default: Optional[str] = None + ) -> Optional[str]: + """Pick a trace target: recently traced first, then contacts by recency. + + Args: + ctx: Shared application context. + default: A target name to pre-highlight (the one just traced), so the cursor + lands where the user left. + + Returns: + The chosen target name, or ``None`` if cancelled. With no known contacts and + no history, falls back to a free-text prompt so a key prefix can be typed. + """ + from ..ui.tui import Choice, Separator + from ..ui.widgets import _DEFAULT_GLYPH, _NODE_GLYPHS + + device = await ctx.device() + contacts = await device.get_contacts() + recent = ctx.repo.traced_targets() + + if not contacts and not recent: + entered = await ctx.ui.text("Target node (name or key prefix):") + return entered.strip() if entered else None + + by_name = {c.name: c for c in contacts} + + def row(name: str) -> Choice: + contact = by_name.get(name) + glyph, style = ( + _NODE_GLYPHS.get(contact.node_type, _DEFAULT_GLYPH) + if contact is not None + else _DEFAULT_GLYPH + ) + label = Text(glyph, style=style) + label.append(f" {name}") + return Choice(title=label, value=name) + + items: list = [] + listed: set[str] = set() + if recent: + items.append(Separator("── ⏱ Recently traced ──", style="accent")) + for name in recent: + items.append(row(name)) + listed.add(name) + remaining = [c for c in contacts if c.name not in listed] + if remaining: + items.append(Separator("── 👤 Contacts ──", style="accent")) + for contact in _by_recency(remaining): + items.append(row(contact.name)) + items.append(Separator(" ")) + items.append(Choice(title="Back", value=_BACK)) + + choice = await ctx.ui.select( + "Trace — pick a target", items, default=default, wrap=False + ) + if choice in (None, _BACK): + return None + return str(choice) + + # -- scripted (CLI) ------------------------------------------------------------- + + async def _run_cli(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: + """Run the traces, persist each one, and print the summary tables. + + Args: + ctx: Shared application context. + params: ``target`` (str), ``samples`` (int), optional ``path``, and the + injected ``_run_id``. Returns: A :class:`ToolResult` with the aggregated statistics. @@ -176,7 +279,7 @@ class TraceTool(Tool): """ from ..cli import run_tool_command - @app.command(name=self.name, help=self.help) + @app.command(name=self.name, help="Run repeated path traces to a target and aggregate SNR") def _trace( target: str = typer.Option(..., "--target", "-t", help="Target node name/prefix"), samples: int = typer.Option( @@ -195,40 +298,19 @@ class TraceTool(Tool): run_tool_command(self, tool_params) -def _validate_path(value: str, contacts: list[Any]) -> bool | str: - """Validate an optional forced-path spec for the interactive prompt. +def _by_recency(contacts: list[Contact]) -> list[Contact]: + """Order contacts most-recently-heard first (never-heard last, alphabetically). Args: - value: The raw comma-separated path entry; blank means "let the device route". - contacts: Known contacts used to resolve names in the spec. + contacts: The contacts to order. Returns: - ``True`` if valid (including blank), otherwise an error message string. + A new sorted list; the input is left untouched. """ - if not value.strip(): - return True - try: - trace_runner.parse_trace_path(value, contacts) - return True - except ValueError as exc: - return str(exc) + def key(c: Contact) -> tuple: + heard = c.last_seen is not None and getattr(c.last_seen, "tzinfo", None) is not None + stamp = c.last_seen.timestamp() if heard else 0.0 + return (not heard, -stamp, c.name.casefold()) -def _is_valid_sample_count(value: str) -> bool | str: - """Validate that a questionary text answer is a trace count in ``1..MAX_TRACES``. - - Args: - value: The raw user input. - - Returns: - ``True`` if valid, otherwise an error message string. - """ - try: - count = int(value) - except ValueError: - return "Enter a whole number." - if count < 1: - return "Enter a number greater than zero." - if count > MAX_TRACES: - return f"Maximum {MAX_TRACES} traces." - return True + return sorted(contacts, key=key) diff --git a/meshterm/ui/trace_screen.py b/meshterm/ui/trace_screen.py new file mode 100644 index 0000000..e020cad --- /dev/null +++ b/meshterm/ui/trace_screen.py @@ -0,0 +1,458 @@ +"""The live trace screen: watch repeated path traces stream in, hop by hop. + +This is the interactive face of the ``trace`` tool (the scripted CLI keeps its one-shot +table output). Where the old flow chained three prompts into a progress bar and a static +result window, this screen follows the app's living-screen pattern (chat, nodes, map): +pick a target, and the screen opens tracing immediately — each reply lands in a running +log as it arrives, the route line and per-hop medians update live, and further bursts, +sample-count changes, and a forced path are all one keystroke away without ever leaving +the screen. + +Layout, top to bottom: the walked route (seeded from the target's last stored trace until +a fresh reply arrives), the run's robust aggregates (success rate, median bottleneck SNR, +median RTT), per-hop median SNR with quality bars, and the individual traces newest-first. + +Every burst is persisted exactly like a scripted run: one ``runs`` row per burst, each +trace recorded under it, so the stored history reads the same no matter which front end +produced it. +""" + +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING, Any, Awaitable, Callable, Optional + +from rich.console import Group, RenderableType +from rich.table import Table +from rich.text import Text + +from ..core.models import TraceResult, TraceStats +from ..services import trace_runner +from .theme import snr_style +from .tui.render import render_lines +from .tui.screen import Screen +from .tui.spinner import Spinner +from .widgets import NodeResolver, _link_text, _route_text + +if TYPE_CHECKING: + from ..context import AppContext + +#: Seconds between spinner frames while a burst is in flight. +_SPINNER_INTERVAL = 0.12 + +#: The sample counts the ``s`` key cycles through — small odd numbers, so the median is +#: always a real reading and the radio's duty cycle stays polite. +_SAMPLE_CYCLE = (1, 3, 5, 9) + +#: How wide the per-hop SNR quality bars draw, in cells. +_BAR_WIDTH = 16 + +#: The SNR range the bars span, in dB: -15 (barely readable) to +10 (excellent). Values +#: outside clamp to the ends, so the bar always shows *something* for a heard hop. +_BAR_SNR_MIN = -15.0 +_BAR_SNR_MAX = 10.0 + +#: A burst runner: ``(samples, path_spec, on_trace)`` → runs the traces, streaming each +#: result to ``on_trace`` as it lands. Provided by :func:`open_trace`, which closes over +#: the device, repository, and settings so the screen stays free of persistence concerns. +BurstRunner = Callable[[int, str, Callable[[TraceResult], None]], Awaitable[None]] + + +def snr_bar(snr: Optional[float], width: int = _BAR_WIDTH) -> Text: + """Render an SNR reading as a horizontal quality bar in the shared SNR colours. + + Args: + snr: The reading in dB, or ``None`` (renders as an empty, muted track). + width: Total bar track width in cells. + + Returns: + A :class:`Text` of filled blocks over a faint track, coloured by + :func:`~meshterm.ui.theme.snr_style`. + """ + if snr is None: + return Text("·" * width, style="faint") + span = _BAR_SNR_MAX - _BAR_SNR_MIN + frac = min(1.0, max(0.0, (snr - _BAR_SNR_MIN) / span)) + filled = max(1, round(frac * width)) + bar = Text("▆" * filled, style=snr_style(snr)) + bar.append("·" * (width - filled), style="faint") + return bar + + +class TraceScreen(Screen): + """A full-screen live trace session for one target. + + Keys: Enter runs another burst, ``s`` cycles the burst's sample count, ``p`` edits the + forced path in a floating prompt, the usual scroll keys move the view, and Esc backs + out (cancelling any in-flight burst; already-recorded traces are kept). + """ + + floating = False + + def __init__( + self, + target: str, + *, + device_label: str, + device_hash: Optional[str], + resolve: NodeResolver, + session: Any, + burst: BurstRunner, + edit_path: Callable[[str], Awaitable[Optional[str]]], + previous: Optional[TraceResult] = None, + samples: int = 3, + ) -> None: + """Create the screen (traces start when :meth:`start_burst` is first called). + + Args: + target: The trace destination (contact name or key prefix). + device_label: Our own node's name, labelling the route's endpoints. + device_hash: Our own public key, so the endpoints carry a hash like every hop. + resolve: Maps a hop's raw hash to a friendly contact name when known. + session: The running TUI session (for repaints). + burst: Runs one burst of traces, streaming results (see :data:`BurstRunner`). + edit_path: Shows the floating forced-path prompt over this screen, seeded with + the current spec; resolves to the new spec or ``None`` when cancelled. + previous: The target's most recent stored trace, if any — its route seeds the + route line so the screen opens knowing the path history last saw. + samples: Traces per burst to start with. + """ + super().__init__() + self.title = f"trace · {target}" + self._target = target + self._device_label = device_label + self._device_hash = device_hash + self._resolve = resolve + self._session = session + self._burst = burst + self._edit_path = edit_path + self._previous = previous + self._samples = samples if samples in _SAMPLE_CYCLE else 3 + self._path_spec = "" + self._traces: list[TraceResult] = [] + self._running = False + self._dialog_open = False + self._status = "" + self._spinner = Spinner() + self._worker: Optional[asyncio.Task] = None + + # --- state ----------------------------------------------------------------- + + @property + def footer_hint(self) -> str: # type: ignore[override] + """The footer keys, tracking whether a burst is in flight.""" + if self._running: + return "tracing… · ↑↓ PgUp/PgDn scroll · Esc back" + return "Enter trace · s samples · p path · ↑↓ PgUp/PgDn scroll · Esc back" + + def start_burst(self) -> None: + """Kick off one burst of traces in the background (no-op while one is running).""" + if self._running: + return + self._running = True + self._status = "" + self._spinner.reset() + self._worker = asyncio.ensure_future(self._run_burst()) + self._session.invalidate() + + async def _run_burst(self) -> None: + """Drive one burst to completion, animating the spinner and reporting failures.""" + ticker = asyncio.ensure_future(self._animate()) + try: + await self._burst(self._samples, self._path_spec, self._on_trace) + except asyncio.CancelledError: + raise + except Exception as exc: # noqa: BLE001 - report inline, keep the screen alive + self._status = f"trace failed: {exc}" + finally: + ticker.cancel() + try: + await ticker + except asyncio.CancelledError: + pass + except Exception: # noqa: BLE001 - a spinner hiccup must never break a burst + pass + self._running = False + self._session.invalidate() + + async def _animate(self) -> None: + """Advance the in-flight spinner and repaint on a steady cadence, until cancelled.""" + while True: + await asyncio.sleep(_SPINNER_INTERVAL) + self._spinner.tick() + self._session.invalidate() + + def _on_trace(self, result: TraceResult) -> None: + """Append one landed trace and repaint (called by the burst as replies arrive).""" + self._traces.append(result) + self._session.invalidate() + + def cancel(self) -> None: + """Cancel any in-flight burst (already-recorded traces are kept).""" + if self._worker is not None and not self._worker.done(): + self._worker.cancel() + + # --- input ------------------------------------------------------------------- + + def handle(self, action: str, data: str = "") -> None: + """Run bursts, tweak samples/path, scroll, or dismiss.""" + if action == "enter": + self.start_burst() + elif action == "text" and data.lower() == "s": + if not self._running: + idx = _SAMPLE_CYCLE.index(self._samples) + self._samples = _SAMPLE_CYCLE[(idx + 1) % len(_SAMPLE_CYCLE)] + elif action == "text" and data.lower() == "p": + self._open_path_dialog() + elif action == "up": + self.scroll_lines(-1) + elif action == "down": + self.scroll_lines(1) + elif action == "pageup": + self.scroll_pages(-1) + elif action in ("pagedown", "space"): + self.scroll_pages(1) + elif action in ("home", "ctrl_home"): + self.scroll_to_top() + elif action in ("end", "ctrl_end"): + self.scroll_to_bottom() + elif action == "escape": + self.cancel() + self.resolve(None) + + def _open_path_dialog(self) -> None: + """Float the forced-path prompt over the screen (one at a time, not mid-burst).""" + if self._dialog_open or self._running: + return + self._dialog_open = True + + async def edit() -> None: + try: + spec = await self._edit_path(self._path_spec) + if spec is not None: + self._path_spec = spec.strip() + finally: + self._dialog_open = False + self._session.invalidate() + + asyncio.ensure_future(edit()) + + # --- rendering ----------------------------------------------------------------- + + def render_body(self, width: int) -> list[str]: + """Render the route, aggregates, per-hop medians, and the trace log.""" + lines = render_lines(Group(*self._sections()), width) + self._scroll_total = max(1, len(lines)) + return lines + + def _sections(self) -> list[RenderableType]: + """Assemble the screen's stacked sections for the current state.""" + stats = TraceStats.from_traces(self._target, self._traces) + current = next((t for t in reversed(self._traces) if t.success), None) + sections: list[RenderableType] = [ + self._route_line(current), + Text(), + self._summary(stats), + ] + if stats.hop_snrs: + hash_bytes = current.path_hash_bytes if current is not None else None + sections += [Text(), Text("Per-hop medians", style="accent")] + sections.append(self._hops_table(stats, hash_bytes)) + sections += [Text(), Text("Traces", style="accent")] + sections.append(self._trace_log()) + return sections + + def _route_line(self, current: Optional[TraceResult]) -> Text: + """The walked route: fresh when a reply has landed, else the stored previous one.""" + line = Text("route ", style="muted") + shown = current or self._previous + if shown is None: + line.append("unknown — waiting for the first reply", style="muted") + return line + line.append_text( + _route_text(shown, self._device_label, self._resolve, self._device_hash) + ) + if current is None: + stamp = shown.timestamp.astimezone().strftime("%b %d %H:%M") + line.append(f" (previous · {stamp})", style="faint") + return line + + def _summary(self, stats: TraceStats) -> Text: + """The run's aggregates plus the current burst configuration, label-aligned.""" + snr = stats.median_min_snr + snr_text = ( + Text(f"{snr:+.1f} dB", style=snr_style(snr)) if snr is not None else Text("—") + ) + rtt = f"{stats.median_rtt_ms:.0f} ms" if stats.median_rtt_ms is not None else "—" + rate = f"{stats.success_rate:.0%} ({stats.successes}/{stats.samples})" + summary = Text.assemble( + ("success rate ", "muted"), (rate if stats.samples else "—", ""), ("\n", ""), + ("median min SNR ", "muted"), snr_text, ("\n", ""), + ("median RTT ", "muted"), (rtt, ""), ("\n", ""), + ("burst ", "muted"), + (f"{self._samples} trace{'s' if self._samples != 1 else ''}", ""), + (" · path ", "muted"), + ) + if self._path_spec: + summary.append(self._path_spec, style="brand") + else: + summary.append("auto (device-routed)", style="muted") + return summary + + def _hops_table(self, stats: TraceStats, hash_bytes: Optional[int]) -> Table: + """The per-hop median SNRs with quality bars, in path order.""" + table = Table(box=None, padding=(0, 1, 0, 0), expand=False, show_header=False) + table.add_column(justify="right", style="muted") # hop index + table.add_column() # link + table.add_column(justify="right") # median snr + table.add_column() # bar + for agg in stats.hop_snrs: + table.add_row( + str(agg.index), + _link_text( + agg.origin, agg.destination, self._device_label, self._resolve, + hash_bytes, self._device_hash, + ), + Text(f"{agg.median_snr:+.1f} dB", style=snr_style(agg.median_snr)), + snr_bar(agg.median_snr), + ) + return table + + def _trace_log(self) -> RenderableType: + """The individual traces, newest first, with the in-flight spinner on top.""" + rows: list[RenderableType] = [] + if self._running: + spin = self._spinner.text() + spin.append(" tracing…", style="muted") + rows.append(spin) + elif self._status: + rows.append(Text(self._status, style="err")) + elif not self._traces: + rows.append(Text("press Enter to trace", style="muted")) + for number, trace in zip(range(len(self._traces), 0, -1), reversed(self._traces)): + rows.append(self._trace_row(number, trace)) + return Group(*rows) + + def _trace_row(self, number: int, trace: TraceResult) -> Text: + """One log line: number, local time, outcome, hop count, bottleneck SNR, RTT.""" + stamp = trace.timestamp.astimezone().strftime("%H:%M:%S") + row = Text.assemble((f"#{number:<3}", "muted"), (f"{stamp} ", "muted")) + if not trace.success: + row.append("✗ no reply", style="err") + return row + row.append("✓ ", style="ok") + row.append(f"{trace.hop_count} hop{'s' if trace.hop_count != 1 else ''}", style="") + if trace.min_snr is not None: + row.append(" min ", style="muted") + row.append(f"{trace.min_snr:+.1f} dB", style=snr_style(trace.min_snr)) + if trace.round_trip_ms is not None: + row.append(f" {trace.round_trip_ms:.0f} ms", style="muted") + return row + + +async def open_trace(ctx: "AppContext", target: str) -> int: + """Open the live trace screen for ``target`` and run it until dismissed. + + Wires the screen to the radio and the database: each burst opens its own ``runs`` + row, records every trace under it, and closes it with the same summary a scripted + ``meshterm trace`` writes — so history stays uniform across front ends. The first + burst starts immediately; the screen's route line is seeded from the target's most + recent stored trace so the path history last saw shows while the first reply is + still in flight. + + Args: + ctx: The shared application context (must be running the interactive TUI surface). + target: The trace destination (contact name or key prefix). + + Returns: + The number of traces run while the screen was open. + + Raises: + RuntimeError: If called outside the interactive menu (no full-screen session). + """ + from .surface import TuiUi + + if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller + raise RuntimeError("the live trace screen is only available in the menu") + session = ctx.ui.session + + device = await ctx.device() + contacts = await device.get_contacts() + resolve = trace_runner.make_node_resolver(contacts) + self_info = await device.get_self_info() + from ..core.models import LOCAL_DEVICE_LABEL + + device_label = str(self_info.get("name") or LOCAL_DEVICE_LABEL) + device_hash = str(self_info.get("public_key") or "") or None + + async def burst(samples: int, path_spec: str, on_trace: Callable[[TraceResult], None]) -> None: + """Run one persisted burst, streaming each landed trace to the screen.""" + path = trace_runner.parse_trace_path(path_spec, contacts) if path_spec.strip() else None + params: dict[str, Any] = {"target": target, "samples": samples} + if path: + params["path"] = path + run_id = ctx.repo.start_run("trace", params, ctx.profile_name) + try: + results = await trace_runner.run_traces( + device, + target, + samples=samples, + path=path, + cooldown_s=ctx.settings.trace_cooldown_s, + on_result=lambda _done, _total, result: on_trace(result), + persist=lambda t: ctx.repo.record_trace(run_id, t), + ) + except BaseException as exc: + # A cancelled or failed burst still closes its run row, so no ``running`` + # orphan is left behind; the traces already recorded stay. + ctx.repo.finish_run(run_id, "error", {"error": str(exc) or type(exc).__name__}) + raise + stats = TraceStats.from_traces(target, results) + ctx.repo.finish_run( + run_id, + "ok", + { + "target": stats.target, + "samples": stats.samples, + "success_rate": round(stats.success_rate, 3), + "median_min_snr": stats.median_min_snr, + "median_rtt_ms": stats.median_rtt_ms, + }, + ) + + async def edit_path(current: str) -> Optional[str]: + """Float the forced-path prompt over the screen; blank means device-routed.""" + + def validate(value: str) -> bool | str: + if not value.strip(): + return True + try: + trace_runner.parse_trace_path(value, contacts) + return True + except ValueError as exc: + return str(exc) + + return await session.autocomplete( + "Force a path", + [c.name for c in contacts], + prompt="Comma-separated contacts/hex prefixes · blank = device-routed", + default=current, + validate=validate, + ) + + screen = TraceScreen( + target, + device_label=device_label, + device_hash=device_hash, + resolve=resolve, + session=session, + burst=burst, + edit_path=edit_path, + previous=ctx.repo.latest_trace(target), + ) + screen.start_burst() + try: + await session.run_screen(screen) + finally: + screen.cancel() + return len(screen._traces)