diff --git a/meshterm/ui/node_detail_screen.py b/meshterm/ui/node_detail_screen.py index 7196823..1d219f3 100644 --- a/meshterm/ui/node_detail_screen.py +++ b/meshterm/ui/node_detail_screen.py @@ -26,13 +26,16 @@ the node itself, in full: travelled, contact on the left, us on the right). Beneath the graph sits the *route list*: one selectable row per distinct route (the firmware's learned route and the observed alternatives, the strongest marked ``★ best``), each spelled out through THE - path widget with a hanging wrap. ``↑↓`` moves the selection; the picked route lights - white in the graph while the rest go grey and every node not on it fades its label to - grey, so the graph reads as *this* route through the fan. Only *good* routes are drawn — - stale evidence and far-weaker outliers are dropped, so the list is the routes worth - trusting rather than every chain ever heard. Enter on a route arms a trace on it - (nothing transmits here — it opens the trace screen loaded with that path); when there - is no route evidence to list, a ``🎯 Trace — auto route …`` action stands in. + path widget as a single hash-chain line, its bottleneck SNR / sample count / tag hanging + on the line below. ``↑↓`` moves the selection; the picked route lights white in the graph + while the rest go grey and every node not on it fades its label to grey, so the graph + reads as *this* route through the fan. A pathline too wide for the lane never wraps — + the highlighted row instead scrolls horizontally (``←→``) to read it to the end; an + unselected long row just ellipsizes. Only *good* routes are drawn — stale evidence and + far-weaker outliers are dropped, so the list is the routes worth trusting rather than + every chain ever heard. Enter on a route arms a trace on it (nothing transmits here — it + opens the trace screen loaded with that path); when there is no route evidence to list, a + ``🎯 Trace — auto route …`` action stands in. * **the ways in** — each tab's action rows (``↑↓`` moves the cursor through them, Enter commits) and the shared ``Back`` closing every tab; Esc backs to the list. @@ -62,6 +65,7 @@ from dataclasses import dataclass, field, replace from datetime import datetime from typing import TYPE_CHECKING, Optional +from rich.cells import cell_len from rich.text import Text from ..core.geo import EARTH_RADIUS_KM, usable_fix @@ -80,7 +84,7 @@ from .pathgraph import ( render_path_graph, ) from .theme import name_style, snr_style -from .tui.render import render_hanging, render_lines, render_to_ansi +from .tui.render import crop_cells, render_hanging, render_lines, render_to_ansi from .pathline import PathHop, PathLine, path_line from .tui.screen import CANCEL, ListWindow, Screen from .widgets import ( @@ -156,6 +160,26 @@ _GREY = (120, 120, 120) #: any real hop, mirroring the graph's own endpoint sentinels. _CLUSTER_NODE = "\x00clu" +#: Columns a route row's pathline and its hanging context line indent by — the ``"❯ "``/ +#: ``" "`` pointer's own width, so the context lines up under the path it belongs to. +_ROUTE_INDENT = 2 + +#: The app-wide opens-further-prompts mark, trailing every route row's pathline (Enter on +#: it arms a trace). Applied at render time rather than baked into :attr:`_Route.path`, so +#: measuring/cropping the raw hash chain for horizontal scroll never has to account for it. +_OPENS_MARKER = " …" + +#: Cells one ←/→ press horizontally scrolls the highlighted route's pathline (see +#: :meth:`NodeDetailScreen.handle`) — the same step the app-wide select list's ``hscroll`` +#: uses. +_HSCROLL_STEP = 8 + +#: Cursor moves that abandon a route's in-progress horizontal scroll — each row scrolls on +#: its own, so leaving it resets the shift rather than carrying it to whatever row is next. +_HSHIFT_RESET_ACTIONS = frozenset({ + "up", "down", "pageup", "pagedown", "home", "ctrl_home", "end", "ctrl_end", +}) + @dataclass(slots=True) class _Action: @@ -184,15 +208,19 @@ class _Route: the left endpoint and our star on the right. Empty = a straight zero-hop shot. spec: The forced-path spec a trace arms on when this route is selected (the symmetric round trip through these hops); ``""`` lets the trace screen auto-resolve. - row: The pre-rendered route line — the whole path named through THE path widget, - contact → relays → us, with the bottleneck SNR / sample count and a ``★ best`` or - ``device route`` tag trailing. Shown hanging-wrapped, so a long route lines up - under itself. + path: The pre-rendered pathline — the whole route named through THE path widget, + contact → relays → us — with the trailing opens-further-prompts mark applied at + render time (:data:`_OPENS_MARKER`), not baked in here. One line, never wrapped: + the highlighted row instead horizontally scrolls to read a long hash chain past + the lane's width, and an unselected row simply ellipsizes. + context: The line shown hanging under ``path`` — the bottleneck SNR, sample count, + and a ``★ best`` / ``device route`` tag — empty when a route earns none of them. """ draw: tuple[str, ...] spec: str - row: Text + path: Text + context: Text @dataclass(slots=True) @@ -338,21 +366,56 @@ class NodeDetailScreen(Screen): self._list_top = 0 self._list_page = 1 self._list_hidden = False + #: The highlighted route's pathline horizontal scroll (cells shifted in, ``←/→``); + #: resets whenever the cursor leaves that row (see :data:`_HSHIFT_RESET_ACTIONS`). + self._hshift = 0 + #: The last render width, so the footer hint can tell whether the highlighted + #: route's pathline actually overflows (nothing does before the first paint). + self._last_width = 0 # --- input ----------------------------------------------------------------- @property def footer_hint(self) -> str: # type: ignore[override] - """Tab switch (when there are tabs to switch), move, open, list paging, Esc last.""" + """Tab switch (when there are tabs to switch), move, open, list/pathline scroll, Esc last. + + The scroll atom folds ``PgUp/PgDn`` and ``←→`` into one when both apply (a busy node's + list is windowed *and* its highlighted route overflows) rather than stacking two atoms + and risking the 72-column hint budget. + """ parts: list[str] = [] if len(self._tabs) >= 2: parts.append("Tab/⇧Tab switch") parts.extend(("↑↓ move", "Enter open")) - if self._list_hidden: + hscroll = self._selected_route_overflows() + if self._list_hidden and hscroll: + parts.append("PgUp/PgDn/←→ scroll") + elif self._list_hidden: parts.append("PgUp/PgDn scroll") + elif hscroll: + parts.append("←→ scroll") parts.append("Esc back") return " · ".join(parts) + def _selected_route_overflows(self) -> bool: + """Whether the highlighted route's pathline is too wide for the list's content lane. + + Gates both the ``←→`` scroll and its footer atom — a pathline that fits has nowhere + to scroll. Measured against the last render width (``0`` before the first paint, so + nothing reads as overflowing until a real width is known). + """ + if self._last_width <= 0 or self._routes is None: + return False + tab = self._tabs[self._tab_index] if self._tabs else None + if tab is None or tab.kind != "routes": + return False + routes = self._routes.routes + if not routes or not (0 <= self._row_index < len(routes)): + return False + avail = max(1, self._last_width - _ROUTE_INDENT) + total = cell_len(routes[self._row_index].path.plain) + cell_len(_OPENS_MARKER) + return total > avail + def selected_spec(self) -> str: """The forced-path spec of the currently-highlighted route (``""`` = auto). @@ -375,6 +438,8 @@ class NodeDetailScreen(Screen): """Switch tab, move the cursor within a tab, commit a row, page the list, or leave.""" focus = self._focusables() n = len(focus) + if action in _HSHIFT_RESET_ACTIONS: + self._hshift = 0 # leaving a row abandons its scroll — each one rides its own if action == "enter": if n: kind, payload = focus[self._row_index % n] @@ -416,9 +481,19 @@ class NodeDetailScreen(Screen): if n: self._row_index = n - 1 self._sync_route_sel(focus) + elif action == "left": + if self._on_route_row(focus): + self._hshift = max(0, self._hshift - _HSCROLL_STEP) + elif action == "right": + if self._on_route_row(focus): + self._hshift += _HSCROLL_STEP # clamped to the pathline's tail at render elif action == "escape": self.resolve(CANCEL) + def _on_route_row(self, focus: list[tuple[str, object]]) -> bool: + """Whether the cursor currently rests on a route row (as opposed to an action row).""" + return bool(focus) and focus[self._row_index % len(focus)][0] == "path" + def cursor_line(self) -> Optional[int]: """The highlighted row's body line — the frame keeps it in view, which only matters on a terminal too short for the pinned layout's minimums.""" @@ -432,6 +507,7 @@ class NodeDetailScreen(Screen): self._row_index = 0 self._route_sel = 0 self._list_top = 0 + self._hshift = 0 self.scroll_to_top() self._sync_route_sel(self._focusables()) @@ -475,6 +551,7 @@ class NodeDetailScreen(Screen): lines — so nothing here ever pushes the graph or the actions off the screen. """ viewport = self._scroll_viewport + self._last_width = width focus = self._focusables() if focus: self._row_index %= len(focus) @@ -681,17 +758,45 @@ class NodeDetailScreen(Screen): return lines def _route_row_lines(self, route: _Route, selected: bool, width: int) -> list[str]: - """One route row: a ``❯`` pointer when picked, the route hanging-wrapped under itself. + """One route row: a ``❯``-pointed pathline, its context hanging on the line below. The route keeps its per-node colours even when selected (the pointer, and the white line in the graph above, carry the selection) — unlike the plain action rows, which go fully brand, since here the colour *is* the content. The trailing ``…`` is the - app-wide opens-further-prompts mark: Enter on the row arms a trace on it. + app-wide opens-further-prompts mark: Enter on the row arms a trace on it. The + pathline never hop-wraps — it is one line, cropped: the highlighted row rides + :attr:`_hshift` (``←→``, see :meth:`handle`) so a hash chain wider than the lane can + still be read to its end, while every other row (and the context line under any row) + just ellipsizes. The context — bottleneck SNR, sample count, the ``★ best`` / + ``device route`` tag — is dropped entirely when a route earns none of it. """ - prefix = Text("❯ " if selected else " ", style="brand" if selected else "") - row = route.row.copy() - row.append(" …", style="muted") - return render_hanging(prefix, row, width, indent=2) + indent = _ROUTE_INDENT + avail = max(1, width - indent) + pointer = Text("❯ " if selected else " ", style="brand" if selected else "") + marked = route.path.copy() + marked.append(_OPENS_MARKER, style="muted") + if selected and self._hshift: + total = cell_len(marked.plain) + self._hshift = max(0, min(self._hshift, max(0, total - avail))) + path = crop_cells(marked, self._hshift, avail) + else: + path = marked + path.no_wrap = True + path.overflow = "ellipsis" + path.truncate(avail) + line1 = Text() + line1.append_text(pointer) + line1.append_text(path) + lines = [render_to_ansi(line1, width)] + if route.context.plain: + context = route.context.copy() + context.no_wrap = True + context.overflow = "ellipsis" + context.truncate(avail) + line2 = Text(" " * indent) + line2.append_text(context) + lines.append(render_to_ansi(line2, width)) + return lines def _action_line(self, action: _Action, selected: bool, width: int) -> str: """One action row: ``❯`` + icon + label, the whole row brand when it is the cursor's.""" @@ -961,8 +1066,10 @@ async def open_node_detail(ctx: "AppContext", contact: Optional["Contact"]) -> N key_of=make_name_key_resolver(contacts, stored_names), style=route_graph_style, self_name=self_name, + self_key=self_key, node_label=label, name_key=key, + hash_bytes=prefix_bytes, ) # -- the tabs (Info always; Routes only when there is a routes view) and their actions. @@ -1061,6 +1168,12 @@ def _signal_row(hn) -> Optional[Text]: # noqa: ANN001 - Optional[HeardNode] return text if text.plain else None +def _hop_hash(key: Optional[str], fallback: str, hash_bytes: int) -> str: + """A key's hash at ``hash_bytes`` width, or ``fallback`` when there is no usable key.""" + hex_key = (key or "").lower().removeprefix("0x") + return hex_key[: hash_bytes * 2] if hex_key else fallback + + def _route_line( node_label: str, name_key: str, @@ -1069,38 +1182,50 @@ def _route_line( weakest: Optional[float], samples: int, *, - resolve, self_name: Optional[str], -) -> Text: - """One route rendered as a full line: contact → relays → us, then its context and tag. + self_key: Optional[str], + hash_bytes: int, +) -> tuple[Text, Text]: + """One route as ``(path, context)`` — the pathline, and the line it hangs its context under. The whole route reads left to right in the graph's own direction (contact on the left, us - on the right), so the row and the drawn line cross-read. The line is one - :class:`~meshterm.ui.pathline.PathLine` — the contact and our own node anchoring the two - ends in their own hues (the contact's key-derived, us the white ``you``), the relays at a - 1-byte hash width, each ``name (3d)`` — the trace presentation, as powerline chips where - the terminal can draw them. The bottleneck SNR and sample count trail as muted context, - and a ``★ best`` / ``device route`` tag marks the winner and the firmware's learned route. + on the right), so the row and the drawn line cross-read. ``path`` is one + :class:`~meshterm.ui.pathline.PathLine` — every hop, endpoints included, shown as its hash + at our own node's path-hash-mode width rather than a resolved name, so the line reads as + the same key-derived identity the graph's chips and column colours already use, and at the + width the device itself carries per hop, as powerline chips where the terminal can draw + them. ``context`` is the bottleneck SNR, sample count, and a ``★ best`` / ``device route`` + tag marking the winner and the firmware's learned route — kept off the pathline itself so + a long hash chain never crowds it out, and empty when a route earns none of them. """ + hash_bytes = max(hash_bytes, 1) # an unknown mode still needs a real width to slice relays = path_line( - list(reversed(hops_out)), resolve, prefix_bytes=1, self_name=self_name, - show_hash=True, hash_bytes=1, + list(reversed(hops_out)), lambda _hop: None, prefix_bytes=hash_bytes, + self_name=self_name, hash_bytes=hash_bytes, ) - text = PathLine([ - PathHop(node_label, key=name_key), + path = PathLine([ + PathHop(_hop_hash(name_key, node_label, hash_bytes), key=name_key, lit_bytes=hash_bytes), *relays.hops, - PathHop(self_name or "us", you=True), + PathHop(_hop_hash(self_key, self_name or "us", hash_bytes), you=True), ]).text() + + atoms: list[Text] = [] if weakest is not None: - text.append(" · weakest ", style="muted") - text.append(f"{weakest:+.1f} dB", style=snr_style(weakest)) + snr = Text("weakest ", style="muted") + snr.append(f"{weakest:+.1f} dB", style=snr_style(weakest)) + atoms.append(snr) if samples: - text.append(f" · {samples}×", style="muted") + atoms.append(Text(f"{samples}×", style="muted")) if tag == "best": - text.append(" ★ best", style="brand") + atoms.append(Text("★ best", style="brand")) elif tag == "device": - text.append(" device route", style="accent") - return text + atoms.append(Text("device route", style="accent")) + context = Text() + for i, atom in enumerate(atoms): + if i: + context.append(" · ", style="muted") + context.append_text(atom) + return path, context def _cluster_presentation(members: tuple[str, ...], type_of) -> _Cluster: # noqa: ANN001 @@ -1174,8 +1299,10 @@ def _routes_view( key_of, style, self_name, + self_key, node_label, name_key, + hash_bytes, ) -> _RoutesView: """Build the Routes tab's selectable routes (node → us) + graph callbacks, or a muted note. @@ -1247,11 +1374,11 @@ def _routes_view( routes: list[_Route] = [] for hops_out, tag, weakest, samples in entries: spec = render_forced_spec(hops_out, target_hash, width_bytes) if target_hash else "" - row = _route_line( + path, context = _route_line( node_label, name_key, hops_out, tag, weakest, samples, - resolve=resolve, self_name=self_name, + self_name=self_name, self_key=self_key, hash_bytes=hash_bytes, ) - routes.append(_Route(draw=tuple(reversed(hops_out)), spec=spec, row=row)) + routes.append(_Route(draw=tuple(reversed(hops_out)), spec=spec, path=path, context=context)) # The legend explains the typed relay marks, so it is decided on the members' real types — # before contraction folds a dense cluster's members behind one synthetic id. diff --git a/meshterm/ui/pathline.py b/meshterm/ui/pathline.py index 10303fc..8e83db1 100644 --- a/meshterm/ui/pathline.py +++ b/meshterm/ui/pathline.py @@ -21,7 +21,10 @@ drawn*, so every surface the survey found can eventually route through it: h-scroll it themselves), :meth:`PathLine.ellipsized` fits a width by eliding *middle* hops behind a ``⋯`` mark — both endpoints survive, unlike a tail truncation that amputates the destination — and :meth:`PathLine.wrapped` breaks - at hop boundaries under a hanging indent (never mid-name, never mid-chip). + at hop boundaries under a hanging indent (never mid-name, never mid-chip), + folding where the route *means* something: the fewest lines it can take, evened + out across them rather than greedily crammed, and preferring the seam where the + path fades from composed to mirrored when that fold is free. * **The same hop semantics everywhere.** A :class:`PathHop` carries what the app's conventions need: the label (a name, or a hash standing as identity), the key any known prefix of which picks the hue, the ``you`` flag, the trace-flavour @@ -29,7 +32,9 @@ drawn*, so every surface the survey found can eventually route through it: ``highlighted_hash`` two-tone), the ``dim`` fade for resolved return legs, and an explicit style override for context colourings that outrank identity. Chips keep the exact same words as arrows — only colours and separators change — so a route - reads identically whichever mode drew it. + reads identically whichever mode drew it. A hop with *no* label is drawn as pure + seam — the arrow alone, no chip, no word — which is how a surface says "this end + is us" without spending cells on saying so (see ``bare_self``). Existing call sites still render through ``path_text``; migrating them here is a separate, per-surface pass. The composer's insertion cursor is the one deliberate @@ -42,17 +47,23 @@ from __future__ import annotations from dataclasses import dataclass from typing import Callable, Optional, Sequence +from rich.cells import cell_len from rich.text import Text from ..core.models import LOCAL_DEVICE_LABEL from .termfont import powerline_enabled from .theme import MESH_THEME, node_style -#: The powerline solid right-pointing triangle (U+E0B0) — the one glyph the widget -#: uses, deliberately the *core* set so every recommended font qualifies (the rounded -#: caps at U+E0B4+ exist only in full Nerd Font patches). +#: The powerline solid right-pointing triangle (U+E0B0) — the male point every chip +#: seam is drawn with, deliberately from the *core* set so every recommended font +#: qualifies (the rounded caps at U+E0B4+ exist only in full Nerd Font patches). POWERLINE_SEP = "\ue0b0" +#: Its mirror (U+E0B2, core too): the female point opening a *wrapped* line's first +#: chip, so a continuation never reads as a fresh path. Only the very first chip of the +#: whole line keeps the plain square left edge. +POWERLINE_CAP = "\ue0b2" + #: The plain-mode joining arrow, exactly as ``path_text`` draws it today. _ARROW = " → " @@ -80,7 +91,10 @@ class PathHop: Attributes: label: What is shown — a resolved name, or a hash standing as the node's - identity (set ``lit_bytes`` for the two-tone prefix in that case). + identity (set ``lit_bytes`` for the two-tone prefix in that case). An + empty label (with no annotation) makes the hop *bare*: it draws as its + seam alone — a bit of arrow, no chip, no word — which is how a route + whose ends are obviously us says so without spending cells on it. key: Any known prefix of the node's key/hash — picks the hash-derived hue (its first byte, so every prefix agrees). ``None`` renders muted/grey: colour is reserved for keyed identities. @@ -105,6 +119,11 @@ class PathHop: style: Optional[str] = None +def _bare(hop: PathHop) -> bool: + """Is this hop drawn as pure seam? (An empty label with nothing to annotate.)""" + return not hop.label and not hop.annotation + + def _style_hex(style: str) -> Optional[str]: """The ``#rrggbb`` a style string or theme name resolves to, else ``None``.""" for token in reversed(style.split()): @@ -211,9 +230,18 @@ class PathLine: line, so that line is returned *without* the indent prefix while every continuation starts with ``indent`` spaces; all lines fit ``width`` and the content column is uniformly ``width - indent`` wide. Plain-mode lines that - continue end with a trailing ``→`` (the "path goes on" cue); chip lines - always close with their pointed edge. A single hop wider than the content - column stands alone, truncated with an ellipsis. + continue end with the separator's own mark — a trailing ``→`` for an + arrow-joined path, the bare ``,`` for a comma-joined wire spec — the "path + goes on" cue; chip lines always close with their pointed edge and *open*, from + the second line down, with the female one (:data:`POWERLINE_CAP`), so a + continuation is never mistakable for a path starting over. A single hop wider + than the content column stands alone, truncated with an ellipsis. + + Where the breaks fall is chosen for how it *reads* (see :meth:`_flow` and + :meth:`_turn_seam`), not by cramming each line full: the fold takes the + fewest lines the hops allow, spread evenly across them, and lands on the + route's turn — where a leg gives way to its mirrored return — when folding + there costs no extra line. Args: width: The full line budget, indent included. @@ -229,17 +257,18 @@ class PathLine: return [Text(self._empty, style="muted")] budget = max(1, width - indent) plain = cursor_arrow is not None or self._resolved_mode() != "powerline" - trail = Text.assemble((" →", "muted")) if plain else Text() - - groups: list[list[PathHop]] = [[]] - for hop in self._hops: - candidate = groups[-1] + [hop] - rendered = self._render(candidate, force_plain=plain) - # Reserve the continuation cue: any line but the last will carry it. - if groups[-1] and rendered.cell_len + trail.cell_len > budget: - groups.append([hop]) - else: - groups[-1] = candidate + # The continuation cue is the separator's own mark, minus the space the next + # hop would have sat in: " → " reads " →", a wire spec's "," stays ",". + cue = self._separator.rstrip() if plain else "" + groups = self._flow(self._hops, budget, plain, len(cue), 0) + seam = self._turn_seam() + if seam is not None and len(groups) > 1: + # The outbound leg's own last line still continues into the return, so it + # holds the cue back where the whole path's final line doesn't. + legs = self._flow(self._hops[:seam], budget, plain, len(cue), len(cue)) + legs += self._flow(self._hops[seam:], budget, plain, len(cue), 0) + if len(legs) <= len(groups): # the turn folds for free — take it + groups = legs lines: list[Text] = [] base = 0 # the global index of the group's first hop, for cursor mapping @@ -248,20 +277,155 @@ class PathLine: if cursor_arrow is not None and 0 <= cursor_arrow - base < len(group) - 1: local = cursor_arrow - base line = Text() if i == 0 else Text(" " * indent) - body = self._render(group, cursor_arrow=local, force_plain=plain) - if body.cell_len > budget: - body.truncate(budget, overflow="ellipsis") + body = self._render(group, cursor_arrow=local, force_plain=plain, cap=bool(i)) + # A lone hop too wide for the column is truncated — leaving room for the + # cue it still has to carry, so even that line stays inside the width. A + # column too narrow to hold both drops the cue: content wins the cells. + continues = i < len(groups) - 1 and 0 < cell_len(cue) < budget + room = budget - (cell_len(cue) if continues else 0) + if body.cell_len > room: + body.truncate(room, overflow="ellipsis") line.append_text(body) - if plain and i < len(groups) - 1: + if continues: if cursor_arrow == base + len(group) - 1: # the cursor rides the break - line.append(" ") - line.append("→", style="selected") + line.append(cue[:-1]) + line.append(cue[-1], style="selected") else: - line.append_text(trail.copy()) + line.append(cue, style="muted") base += len(group) lines.append(line) return lines + # --- where the breaks fall -------------------------------------------------------- + + def _measure(self, hops: list[PathHop], plain: bool) -> tuple[list[int], int, int, int]: + """Each hop's own width, plus what joining, opening and closing a line costs. + + Fitting hops to a column is arithmetic once every hop has been measured once — + which matters because :meth:`_flow` tries a whole series of columns, and the + screens re-fit on every repaint (a spinner tick included). + + Args: + hops: The hops to measure, in order. + plain: Measure as arrow text rather than as chips. + + Returns: + ``(cells, join, tail, lead)`` — each hop's cells, the cells one join between + two hops costs, the cells a line always closes with (the chip mode's pointed + edge; nothing in arrow mode), and the cells every line *after the first* + opens with (chip mode's female cap). + + Note: + Joins are measured at their full width even where a bare neighbour trims one + (:meth:`_join`), and the closing edge is charged even to a line ending bare — + an over-estimate of a cell, which packs a hair early and never overflows. + """ + if plain: + widths = [self._plain_hop(hop).cell_len for hop in hops] + return widths, cell_len(self._separator), 0, 0 + widths = [self._chip(hop, self._chip_fill(hop)).cell_len for hop in hops] + return widths, cell_len(POWERLINE_SEP), cell_len(POWERLINE_SEP), cell_len(POWERLINE_CAP) + + @staticmethod + def _fill( + cells: list[int], + join: int, + tail: int, + budget: int, + reserve: int, + last: int, + lead: int = 0, + ) -> list[int]: + """Pack hop widths into lines of ``budget`` cells, greedily, never splitting one. + + Args: + cells: Each hop's width, in order (see :meth:`_measure`). + join: Cells one join between two hops costs. + tail: Cells every line closes with. + budget: The content column's width in cells. + reserve: Cells held back on a line for the continuation cue it will carry. + last: Cells held back on a line ending at the *final* hop — ``0`` when the + path really ends there (nothing follows to cue), ``reserve`` when this + is only one leg of a path that goes on. + lead: Cells every line but the first opens with (the female cap). + + Returns: + How many hops each line takes; a hop too wide for ``budget`` gets a line of + its own (the caller truncates it). + """ + sizes: list[int] = [] + width = count = 0 + for i, cell in enumerate(cells): + grown = width + cell + (join if count else 0) + held = last if i == len(cells) - 1 else reserve + if count and grown + tail + held > budget: + sizes.append(count) + width, count = lead + cell, 1 + else: + width, count = grown, count + 1 + sizes.append(count) + return sizes + + def _flow( + self, hops: list[PathHop], budget: int, plain: bool, reserve: int, last: int + ) -> list[list[PathHop]]: + """Break ``hops`` into the fewest lines, then even those lines out. + + Greedy packing alone widows the tail: a route whose last hop misses the first + line by a cell or two strands ``us`` alone underneath a full one. Since the + line *count* is what costs screen rows — and greedy already achieves the + minimum — the same count is re-packed at the narrowest column that still + needs it, which spreads the hops across the lines instead of cramming the + first and starving the last (``us → a → b → c →`` / ``us`` becomes + ``us → a →`` / ``b → c → us``). + + Args: + hops: The hops to break up, in order. + budget: The content column's width in cells. + plain: Render as arrows rather than chips. + reserve: Cells held back on a line for the continuation cue it carries. + last: Cells held back on the line the hops end on (see :meth:`_fill`). + + Returns: + The hops grouped per line. + """ + cells, join, tail, lead = self._measure(hops, plain) + lines = len(self._fill(cells, join, tail, budget, reserve, last, lead)) + low, high = 1, budget + while low < high: # the narrowest column still taking `lines` rows + mid = (low + high) // 2 + if len(self._fill(cells, join, tail, mid, reserve, last, lead)) <= lines: + high = mid + else: + low = mid + 1 + groups: list[list[PathHop]] = [] + at = 0 + for size in self._fill(cells, join, tail, low, reserve, last, lead): + groups.append(hops[at : at + size]) + at += size + return groups + + def _turn_seam(self) -> Optional[int]: + """The hop index a fold would read best at — where the route turns — or ``None``. + + Two things mark a turn. A dimmed tail is one: the composed outbound leg ends + and the mirrored return begins (see :attr:`PathHop.dim`). A walked boomerang is + the other — nothing is dimmed once a trace has actually answered, but the hop + sequence is its own mirror, so its middle *is* that same turn; folding the plan + and the walk that answered it in the same place keeps the two readings of one + route looking like one route. Either way the fold needs real legs on both + sides — at least two hops each — so a path whose *only* dim hop is the + automatic landing back on us never widows it onto a line of its own. + """ + seam = next((i for i, hop in enumerate(self._hops) if hop.dim), None) + if seam is None: + marks = [(hop.label, hop.annotation) for hop in self._hops] + if len(marks) % 2 and marks == marks[::-1]: + seam = len(marks) // 2 + 1 # the first hop of the way home + if seam is None or seam < 2 or len(self._hops) - seam < 2: + return None + return seam + # --- rendering ---------------------------------------------------------------- def _resolved_mode(self) -> str: @@ -276,10 +440,15 @@ class PathLine: *, cursor_arrow: Optional[int] = None, force_plain: bool = False, + cap: bool = False, ) -> Text: - """Join ``hops`` in the effective mode (plain whenever a cursor is asked).""" + """Join ``hops`` in the effective mode (plain whenever a cursor is asked). + + ``cap`` marks a wrapped continuation and only means anything to chips; arrow + mode says the same thing with the trailing cue the line above ends on. + """ if not force_plain and cursor_arrow is None and self._resolved_mode() == "powerline": - return self._render_chips(hops) + return self._render_chips(hops, cap=cap) return self._render_plain(hops, cursor_arrow) def _render_plain(self, hops: list[PathHop], cursor_arrow: Optional[int]) -> Text: @@ -287,15 +456,31 @@ class PathLine: text = Text() for i, hop in enumerate(hops): if i: + gap = self._join(hops[i - 1], hop) if cursor_arrow is not None and i - 1 == cursor_arrow: - text.append(" ") - text.append("→", style="selected") - text.append(" ") + mark = gap.strip() + text.append(gap[: len(gap) - len(gap.lstrip())]) + text.append(mark, style="selected") + text.append(gap[len(gap.rstrip()) :]) else: - text.append(self._separator, style="faint" if hop.dim else "muted") + text.append(gap, style="faint" if hop.dim else "muted") text.append_text(self._plain_hop(hop)) return text + def _join(self, before: PathHop, after: PathHop) -> str: + """The separator between two hops, minus the padding a bare neighbour vacates. + + A bare hop takes no cells, so the space the separator holds for it would sit + against the line's edge: ``us → a → us`` with bare ends reads ``→ a →``, the + arrows alone standing for the endpoints. + """ + gap = self._separator + if _bare(before): + gap = gap.lstrip() + if _bare(after): + gap = gap.rstrip() + return gap + def _plain_hop(self, hop: PathHop) -> Text: """One arrow-mode hop: label in its identity style, annotation muted.""" note_style = "faint" if hop.dim else "muted" @@ -318,15 +503,28 @@ class PathLine: text.append(f" ({hop.annotation})", style=note_style) return text - def _render_chips(self, hops: list[PathHop]) -> Text: - """Powerline chips: each hop filled with its hue, seams interlocked.""" + def _render_chips(self, hops: list[PathHop], *, cap: bool = False) -> Text: + """Powerline chips: each hop filled with its hue, seams interlocked. + + Args: + hops: The hops of this one line, in order. + cap: Open the line with the female point (:data:`POWERLINE_CAP`) in the + first chip's own fill — the mark of a wrapped continuation, where the + whole line's very first chip instead keeps its square left edge. + """ fills = [self._chip_fill(hop) for hop in hops] text = Text() + if cap: + text.append(POWERLINE_CAP, style=fills[0]) for i, hop in enumerate(hops): if i: - text.append(POWERLINE_SEP, style=f"{fills[i - 1]} on {fills[i]}") + # A bare hop has no field for the arrow to land in, so the seam points + # into the page instead: that lone arrowhead *is* the endpoint. + style = fills[i - 1] if _bare(hop) else f"{fills[i - 1]} on {fills[i]}" + text.append(POWERLINE_SEP, style=style) text.append_text(self._chip(hop, fills[i])) - text.append(POWERLINE_SEP, style=fills[-1]) # the pointed edge into the page + if not _bare(hops[-1]): + text.append(POWERLINE_SEP, style=fills[-1]) # the pointed edge into the page return text def _chip_fill(self, hop: PathHop) -> str: @@ -344,7 +542,12 @@ class PathLine: return _KEYLESS_BG def _chip(self, hop: PathHop, fill: str) -> Text: - """One chip: same words as arrow mode, dark ink on the identity fill.""" + """One chip: same words as arrow mode, dark ink on the identity fill. + + A bare hop draws no chip at all — its seam alone carries it (see :meth:`_render_chips`). + """ + if _bare(hop): + return Text() ink = _DIM_FG if hop.dim else _CHIP_FG soft = _DIM_FG if hop.dim else _CHIP_FG_SOFT text = Text() @@ -380,6 +583,7 @@ def path_line( device_hash: Optional[str] = None, dim_from: Optional[int] = None, hash_as_name: bool = False, + bare_self: bool = False, mode: str = "auto", ) -> PathLine: """Build a :class:`PathLine` from raw hop hashes — ``path_text``'s vocabulary. @@ -389,7 +593,8 @@ def path_line( so a call site swaps builders without changing what it says — a named hop reads ``Name`` (annotated ``Name (3d)`` under ``show_hash``), an unnamed hop its prefix-lit hash (or its muted identity hash under ``hash_as_name``), ``None`` is - our own device in white, ``dim_from`` fades a resolved tail. The plain rendering + our own device in white — or, under ``bare_self``, its bit of arrow and nothing + else — and ``dim_from`` fades a resolved tail. The plain rendering is character- and style-identical to ``path_text``; what the swap buys is the :class:`PathLine` shapes (ellipsized / wrapped) and the powerline mode. @@ -409,6 +614,10 @@ def path_line( dim_from: Fade hops at/after this rendered index (``None`` dims nothing). hash_as_name: Present each unnamed hop as its muted identity hash at the ``prefix_bytes`` width, annotated with its addressed byte. + bare_self: Draw our own device (a ``None`` hop) with no words at all — just + its bit of arrow. For a surface whose route *always* begins and ends on + us, the name and hash on both ends say nothing the reader doesn't know, + and cost the cells the hops in between need. mode: The :class:`PathLine` mode (``"auto"``/``"powerline"``/``"plain"``). Returns: @@ -419,6 +628,9 @@ def path_line( for i, hop in enumerate(shown): dim = dim_from is not None and i >= dim_from if hop is None: + if bare_self: + built.append(PathHop("", you=True, dim=dim)) + continue note = _shorten(device_hash, hash_bytes) if (show_hash and device_hash) else None built.append( PathHop(self_name or LOCAL_DEVICE_LABEL, you=True, annotation=note, dim=dim) diff --git a/meshterm/ui/trace_screen.py b/meshterm/ui/trace_screen.py index 08b7da8..c610e6c 100644 --- a/meshterm/ui/trace_screen.py +++ b/meshterm/ui/trace_screen.py @@ -61,12 +61,19 @@ whatever you make it, and nothing transmits until you say so. An action list dri Layout, top to bottom: the walked route (live when a reply has landed, else the route the next Trace will walk — composed by hand, or auto-resolved from the device's learned route or the stored history and labelled with that provenance — else the most recent -stored trace), the run's robust aggregates, the +stored trace), the run's robust aggregates, the wire spec that route amounts to, the action list, then the results — per-hop median SNR with quality bars and the individual traces newest-first — scrolling in a window beneath the pinned controls: PgUp/PgDn/Home/End slide it (↑/↓ belong to the action cursor), and faint ``↑/↓ n more`` markers count what the window hides. +Both path lanes draw through THE path widget (:mod:`~meshterm.ui.pathline`) and break +at hop boundaries under their own value column: a route folds between nodes — never +parting a name from the hash it is addressed by, and preferring the turn where a +boomerang's mirrored return begins — while the spec below it folds after a comma, +never mid-hash. Whatever a route's provenance is (an auto plan's source, a previous +walk's timestamp) hangs on the line under it rather than crowding its right edge. + Every trace is persisted exactly like a scripted run: one ``runs`` row per trace, recorded under it, so the stored history reads the same no matter which front end produced it. Path walks record under :data:`~meshterm.core.models.PATH_TRACE_TARGET`, @@ -91,11 +98,11 @@ from ..services.topology import render_forced_spec from .braillechart import meter from .menus import back_rows from .theme import snr_style -from .tui.render import render_hanging, render_lines, render_to_ansi +from .tui.render import render_lines, render_to_ansi from .tui.screen import ListWindow, Screen from .tui.spinner import Spinner -from .pathline import path_line -from .widgets import NodeResolver, _link_text, _route_text, highlighted_hash, path_text +from .pathline import PathHop, PathLine, path_line +from .widgets import NodeResolver, _link_text, _route_path, highlighted_hash if TYPE_CHECKING: from ..context import AppContext @@ -137,6 +144,63 @@ TraceOnce = Callable[ #: The sample-count flow shares the shape and simply always resolves ``None``. PathFlow = Callable[[str], Awaitable[Optional[str]]] +#: The route lane's label column: the word plus its padding. Its width is the column +#: the route's wrapped continuations (and its provenance note) hang under. +_ROUTE_LANE = "route " + +#: The path lane's label column — the aggregate block's own label width, so the wire +#: spec starts, and hangs, in the same column as the numbers above it. +_PATH_LANE = "path " + + +def _lane_lines(label: str, value: list[Text], width: int) -> list[str]: + """Render a labelled lane whose value hangs, already broken, under its own column. + + The counterpart to :func:`~meshterm.ui.tui.render.render_hanging` for values that + know their own line breaks: :meth:`~meshterm.ui.pathline.PathLine.wrapped` hands + back lines that hop-wrap and carry their indent, so re-wrapping them here would + only undo that. The label rides the first line; the rest are drawn as given. + + Args: + label: The lane's label column, padding included (the value hangs under it). + value: The value's lines — first bare, continuations self-indented. + width: The render width; lines are cropped, never folded. + + Returns: + The rendered ANSI lines. + """ + lines: list[str] = [] + for i, line in enumerate(value): + row = Text(label, style="muted") if i == 0 else Text() + row.append_text(line) + lines.append(render_to_ansi(row, width, no_wrap=True)) + return lines + + +def _note(text: str, indent: int, *, style: str = "faint") -> Text: + """A lane's trailing note — provenance, a stamp, a count — on its own hanging line.""" + return Text(" " * indent + text, style=style) + + +def _spec_line(spec: str) -> PathLine: + """The literal wire spec as a path line: comma-joined, each hop in its own hue. + + Exactly the characters the radio is handed (``3d63,7f21,3d63``) — the lane's whole + point is being the verbatim spec, so it stays plain-mode text rather than becoming + chips. What THE path widget adds is the app-wide key colouring (each addressed + slice lit in its own key-derived hue instead of one flat brand smear) and hop- + boundary wrapping, so a spec too long for its column breaks after a comma. + + Args: + spec: The wire spec (comma-separated hex hop hashes; blanks tolerated). + + Returns: + The spec's :class:`~meshterm.ui.pathline.PathLine`, comma-separated. + """ + tokens = [t.strip() for t in spec.split(",") if t.strip()] + hops = [PathHop(t, key=t, lit_bytes=len(t) // 2) for t in tokens] + return PathLine(hops, mode="plain", separator=",") + 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. @@ -678,18 +742,12 @@ class TraceScreen(Screen): """ stats = TraceStats.from_traces(self._target, self._traces) current = next((t for t in reversed(self._traces) if t.success), None) - # The route hangs under its own value block when it wraps (the app-wide - # labelled-row rule), so a long walk never folds back to column zero. - lines = render_hanging( - Text("route ", style="muted"), self._route_line(current), width, indent=7 - ) + # Both path lanes break at hop boundaries under their own value column (the + # app-wide labelled-row rule): a long walk never folds back to column zero, + # and never splits a name from its hash or a wire spec mid-hash. + lines = _lane_lines(_ROUTE_LANE, self._route_value(current, width), width) lines.extend(render_lines(Group(Text(), self._summary(stats)), width)) - # The path lane hangs under its own value block like the route above it, so a - # long wire spec never folds back to column zero. - lines.extend(render_hanging( - Text("path ", style="muted"), self._path_value(current), width, - indent=16, - )) + lines.extend(_lane_lines(_PATH_LANE, self._path_value(current, width), width)) lines.append("") self._cursor: Optional[int] = None for i, key in enumerate(self._actions): @@ -787,29 +845,53 @@ class TraceScreen(Screen): text.style = "brand" return text - def _route_line(self, current: Optional[TraceResult]) -> Text: - """The route: live when a reply has landed, else planned, else the stored one. + def _route_value(self, current: Optional[TraceResult], width: int) -> list[Text]: + """The route lane's value lines: the path, hop-wrapped, then its provenance. - The label lane ("route ") is added by the caller, which renders this body - with a hanging indent so wrapped routes align under themselves. + The route itself is live once a reply has landed, else the plan the next Trace + walks, else the last stored walk, else a muted note. Whichever it is, it breaks + at hop boundaries under the lane's own column — a name never parts from its + hash, and a boomerang folds at its turn — while the provenance (where an auto + plan came from, when a previous walk ran) takes the line below rather than + crowding the route's right edge. + + Both ends go bare (``bare_self``): every walk on this screen leaves us and comes + back to us, so naming ourselves twice would only push the hops that *are* news + out of the lane. + + Args: + current: The newest successful trace of this session, if any. + width: The full body width; the lines fit it, indent included. + + Returns: + The value's lines — the first bare (the label rides it), continuations + already carrying the lane's indent. """ + indent = len(_ROUTE_LANE) if current is not None: - return _route_text(current, self._device_label, self._resolve, self._device_hash) + route = _route_path( + current, self._device_label, self._resolve, self._device_hash, + bare_self=True, + ) + return route.wrapped(width, indent=indent) planned = self._planned_route() if planned is not None: - return planned + lines = planned.wrapped(width, indent=indent) + if self._effective_spec()[1] and self._auto_source: + lines.append(_note(f"(auto · {self._auto_source})", indent)) + return lines if self._previous is not None: - line = _route_text( - self._previous, self._device_label, self._resolve, self._device_hash + route = _route_path( + self._previous, self._device_label, self._resolve, self._device_hash, + bare_self=True, ) + lines = route.wrapped(width, indent=indent) stamp = self._previous.timestamp.astimezone().strftime("%b %d %H:%M") - # On its own line so a long route never squeezes the stamp off the - # right edge. - line.append(f"\n(previous · {stamp})", style="faint") - return line + lines.append(_note(f"(previous · {stamp})", indent)) + return lines if self._mode == "path": - return Text("none — compose a path to walk", style="muted") - return Text("unknown — press Enter to trace", style="muted") + return [Text("none — compose a path to walk", style="muted")] + return [Text("unknown — press Enter to trace", style="muted")] def _effective_spec(self) -> tuple[str, bool]: """The wire spec the next Trace walks, and whether auto resolution supplied it. @@ -871,20 +953,20 @@ class TraceScreen(Screen): asyncio.ensure_future(run()) - def _planned_route(self) -> Optional[Text]: + def _planned_route(self) -> Optional[PathLine]: """The route the next Trace walks as a preview, or ``None`` without one. - Renders the literal wire spec through the shared path widget — the whole - walk, since the trace protocol has no separate return-path field. In target - mode the spec is the symmetric boomerang (outbound hops, the target, those - hops mirrored): its second half is dimmed via the widget's ``dim_from``, - reading as "this part isn't yours to compose". A path walk's spec is the - whole route (hand-composed, or the last stored walk), so every hop renders - in full colour and only the automatic landing back on us stays faint. An - auto-resolved spec carries a faint provenance line naming where the route - came from. + Renders the literal wire spec through THE path widget — the whole walk, since + the trace protocol has no separate return-path field. In target mode the spec + is the symmetric boomerang (outbound hops, the target, those hops mirrored): + its second half is dimmed via the widget's ``dim_from``, reading as "this part + isn't yours to compose" — and, when the line wraps, giving the fold its natural + seam (the turn). A path walk's spec is the whole route (hand-composed, or the + last stored walk), so every hop renders in full colour and only the automatic + landing back on us stays faint. Our own endpoints go bare, as in + :meth:`_route_value` — the arrow alone. """ - spec, auto = self._effective_spec() + spec, _ = self._effective_spec() tokens = [h.strip() for h in spec.split(",") if h.strip()] if not tokens: return None @@ -893,19 +975,15 @@ class TraceScreen(Screen): outbound, return_leg = tokens[: mid + 1], tokens[mid + 1 :] else: outbound, return_leg = tokens, [] - text = path_text( + return path_line( [None, *outbound, *return_leg, None], self._resolve, prefix_bytes=8, # spec tokens are the addressed slices: light them whole self_name=self._device_label, show_hash=True, dim_from=1 + len(outbound), + bare_self=True, ) - if auto and self._auto_source: - # On its own line (like the previous-trace stamp) so a long route - # never squeezes the provenance off the right edge. - text.append(f"\n(auto · {self._auto_source})", style="faint") - return text def _displayed_hop_count(self, current: Optional[TraceResult]) -> Optional[int]: """How many nodes the displayed route passes through, endpoints excluded. @@ -939,21 +1017,40 @@ class TraceScreen(Screen): ("median RTT ", "muted"), (rtt, ""), ) - def _path_value(self, current: Optional[TraceResult]) -> Text: - """The ``path`` lane's value: the wire spec (or its auto/none note) + hop count.""" - value = Text() + def _path_value(self, current: Optional[TraceResult], width: int) -> list[Text]: + """The ``path`` lane's value lines: the wire spec (or its note) + hop count. + + A pinned spec is the verbatim string the radio is handed, drawn through THE + path widget (:func:`_spec_line`) so it breaks after a comma instead of + splitting a hash in half; the auto/none states stay prose. The hop count + trails the last line, dropping to a line of its own only when it doesn't fit. + + Args: + current: The newest successful trace of this session, if any — its walked + route is what the count describes once one has landed. + width: The full body width; the lines fit it, indent included. + + Returns: + The value's lines, indented like :meth:`_route_value`'s. + """ + indent = len(_PATH_LANE) if self._path_spec: - value.append(self._path_spec, style="brand") + lines = _spec_line(self._path_spec).wrapped(width, indent=indent) elif self._effective_spec()[1] and self._auto_source: - value.append(f"auto · {self._auto_source}", style="muted") + lines = [Text(f"auto · {self._auto_source}", style="muted")] elif self._mode == "path": - value.append("none — compose a path first", style="muted") + lines = [Text("none — compose a path first", style="muted")] else: - value.append("auto — path-less (unknown target)", style="muted") + lines = [Text("auto — path-less (unknown target)", style="muted")] hops = self._displayed_hop_count(current) if hops is not None: - value.append(f" · {hops} hop{'s' if hops != 1 else ''}", style="muted") - return value + count = f"{hops} hop{'s' if hops != 1 else ''}" + used = lines[-1].cell_len + (indent if len(lines) == 1 else 0) + if used + len(count) + 4 <= width: + lines[-1].append(f" · {count}", style="muted") + else: + lines.append(_note(count, indent, style="muted")) + return lines def _hops_table(self, stats: TraceStats, hash_bytes: Optional[int]) -> Table: """The per-hop median SNRs with quality bars, in path order.""" @@ -1107,6 +1204,54 @@ def _best_observed(topo: Any, target_hash: str) -> Optional[tuple[tuple[str, ... return scenario.hops, source +def _scenario_path( + scenario: Any, topo: Any, target_id: str, *, device_label: str, width_bytes: int +) -> Text: + """A scenario's pathline: us, the candidate hops, and the target — one line. + + Full boomerang endpoints included (not just the intermediate hops a + :class:`~meshterm.services.topology.PathScenario` stores), so the row reads as + the whole route rather than a fragment the reader has to mentally close. + Renders through the shared path widget, so every hop wears its own key hue (an + unnamed hop its prefix-lit hash) instead of the old single-colour smear. + """ + route = path_line( + [None, *scenario.hops, target_id], + topo.display_name, + prefix_bytes=width_bytes, + self_name=device_label, + ) + return route.text() + + +def _scenario_detail(scenario: Any) -> Text: + """The line hanging under a scenario's pathline: its provenance and evidence. + + The device route and the direct shot keep their short provenance tag (observed + candidates *are* their hop sequence, so they carry none); then the bottleneck + SNR and sample count a trace would expect to measure, or ``unobserved`` when + the evidence graph has nothing to say about it yet. + """ + atoms: list[Text] = [] + if scenario.source in ("device", "direct"): + style = "accent" if scenario.source == "device" else "muted" + atoms.append(Text(scenario.label, style=style)) + if scenario.weakest_snr is not None: + snr = Text("weakest ", style="muted") + snr.append(f"{scenario.weakest_snr:+.1f} dB", style=snr_style(scenario.weakest_snr)) + atoms.append(snr) + if scenario.samples: + atoms.append(Text(f"{scenario.samples}×", style="muted")) + elif scenario.score == 0: + atoms.append(Text("unobserved", style="faint")) + detail = Text() + for i, atom in enumerate(atoms): + if i: + detail.append(" · ", style="muted") + detail.append_text(atom) + return detail + + async def open_trace(ctx: "AppContext", target: str, *, initial_spec: str = "") -> int: """Open the live *Trace target* screen for ``target`` and run it until dismissed. @@ -1185,13 +1330,7 @@ async def _open_session( from ..core.connection import DeviceAuthenticationError from ..core.models import LOCAL_DEVICE_LABEL, Contact, NeighbourInfo from ..services.path_probe import ProbeCandidate, ProbeOutcome, probe_paths - from ..services.topology import ( - MeshTopology, - PathScenario, - _is_hex, - build_topology, - collapse_width, - ) + from ..services.topology import MeshTopology, _is_hex, build_topology, collapse_width from .path_composer import FetchNeighbours, PathComposerScreen from .surface import TuiUi from .tui import CANCEL, Choice, SelectScreen, Separator @@ -1582,37 +1721,6 @@ async def _open_session( sample_count = int(picked) return None - def scenario_title(scenario: PathScenario, topo: MeshTopology) -> Text: - """One scenario as a select row: the route itself, and its observed evidence. - - Observed candidates *are* their hop sequence, so the row leads with the route - and no label; the device route and the direct shot keep their short labels — - that provenance is the point of offering them. The route renders through the - shared path widget, so every hop wears its own key hue (an unnamed hop its - prefix-lit hash) instead of the old single-colour smear. - """ - route = path_line( - list(scenario.hops), topo.display_name, prefix_bytes=width_bytes - ) - if scenario.source == "observed": - text = route.text() - else: - styles = {"device": "accent", "direct": "muted"} - text = Text(scenario.label, style=styles.get(scenario.source, "")) - if scenario.hops: - text.append(" via ", style="muted") - text.append_text(route.text()) - else: - text.append(" no repeaters", style="muted") - if scenario.weakest_snr is not None: - text.append(" · weakest ", style="muted") - text.append(f"{scenario.weakest_snr:+.1f} dB", style=snr_style(scenario.weakest_snr)) - if scenario.samples: - text.append(f" · {scenario.samples}×", style="muted") - elif scenario.score == 0: - text.append(" · unobserved", style="faint") - return text - def outcome_title(rank: int, outcome: ProbeOutcome) -> Text: """One probed candidate as a ranked select row: one measured trace, not a guess.""" stats = outcome.stats @@ -1756,7 +1864,14 @@ async def _open_session( ] for scenario in scenarios: items.append( - Choice(title=scenario_title(scenario, topo), value=("use", scenario)) + Choice( + title=_scenario_path( + scenario, topo, target_id, + device_label=device_label, width_bytes=width_bytes, + ), + detail=_scenario_detail(scenario), + value=("use", scenario), + ) ) items.append(Separator(" ")) items.append( diff --git a/meshterm/ui/tui/select.py b/meshterm/ui/tui/select.py index 34476f4..98a091b 100644 --- a/meshterm/ui/tui/select.py +++ b/meshterm/ui/tui/select.py @@ -32,17 +32,29 @@ class Choice: resolves the list with a :class:`DeleteRequest` wrapping this row's value instead of choosing it, so the caller can run a remove flow and re-open the list. Off by default, so an ordinary list ignores Delete. + detail: An optional second line, drawn hanging under ``title`` at the pointer's + indent — context that doesn't belong in the selectable line itself (a route's + weakest SNR/sample count/provenance tag, say). Never scrolls or wraps; it + ellipsizes on its own if too wide. ``None`` (the default) draws nothing, so an + ordinary row stays exactly one line. May be a zero-argument callable like + ``title``. """ title: Union[str, Text, Callable[[], Union[str, Text]]] value: Any deletable: bool = False + detail: Union[str, Text, Callable[[], Union[str, Text]], None] = None @property def label(self) -> Union[str, Text]: """The row's current text, resolving a callable title on each read.""" return self.title() if callable(self.title) else self.title + @property + def detail_label(self) -> Optional[Union[str, Text]]: + """The row's current detail line, resolving a callable on each read.""" + return self.detail() if callable(self.detail) else self.detail + @dataclass class DeleteRequest: @@ -345,6 +357,8 @@ class SelectScreen(Screen): for item in self._items: label = item.title if isinstance(item, Separator) else item.label widths.append(cell_len(_plain(label)) + 2) # + the "❯ " / " " pointer column + if isinstance(item, Choice) and item.detail_label is not None: + widths.append(cell_len(_plain(item.detail_label)) + 2) # same hanging indent return max(widths, default=20) + 8 def render_body(self, width: int) -> list[str]: @@ -379,6 +393,9 @@ class SelectScreen(Screen): self._sticky_headers = [] if self._filter: lines.append(render_to_ansi(Text(f"/{self._filter}", style="warn"), width)) + # A row's detail line (see Choice.detail) can make it two lines tall, so the cursor + # is tracked inline as rows are drawn rather than derived from the row index. + cursor_at: Optional[int] = None for item in rows: if isinstance(item, Separator): # A Text title carries its own spans (a two-colour column header); a plain @@ -391,6 +408,8 @@ class SelectScreen(Screen): lines.append(sep) continue is_sel = item is selected + if is_sel: + cursor_at = len(lines) pointer = "❯ " if is_sel else " " style = "brand" if is_sel else "" label = item.label @@ -409,12 +428,22 @@ class SelectScreen(Screen): text.overflow = "ellipsis" text.truncate(width) lines.append(render_to_ansi(text, width)) + detail = item.detail_label if isinstance(item, Choice) else None + if detail is not None and _plain(detail): + # Hangs under the row at the pointer's own indent — never scrolls or + # wraps, just ellipsizes on its own if it's too wide to fit. + detail_text = detail if isinstance(detail, Text) else Text(detail) + line = Text(" ") + line.append_text(detail_text) + line.no_wrap = True + line.overflow = "ellipsis" + line.truncate(width) + lines.append(render_to_ansi(line, width)) if not choices: lines.append(render_to_ansi(Text("no matches", style="muted"), width)) # Remember where the highlighted row landed so the session can keep it in view, # shifted past any prompt lines drawn above the list. - base_cursor = _cursor_line(rows, selected, bool(self._filter)) - self._cursor = None if base_cursor is None else base_cursor + prefix + self._cursor = None if cursor_at is None else cursor_at + prefix return lines def cursor_line(self) -> Optional[int]: @@ -616,24 +645,3 @@ class ReorderScreen(Screen): super().handle("escape") # Back resolves CANCEL, same as Esc elif action == "escape": super().handle("escape") - - -def _cursor_line(rows: list, selected: Optional[Choice], filtered: bool) -> Optional[int]: - """Compute the rendered body line index of the selected row. - - Args: - rows: The displayed rows (choices and separators). - selected: The currently highlighted choice, if any. - filtered: Whether a filter line precedes the rows (offsetting every row by one). - - Returns: - The zero-based line index of the highlighted row, or ``None`` if nothing is - selected. - """ - if selected is None: - return None - offset = 1 if filtered else 0 - for i, item in enumerate(rows): - if item is selected: - return i + offset - return None diff --git a/meshterm/ui/widgets.py b/meshterm/ui/widgets.py index 8284893..428f148 100644 --- a/meshterm/ui/widgets.py +++ b/meshterm/ui/widgets.py @@ -40,6 +40,7 @@ from ..core.models import ( from .map_render import _NODE, _REPEATER, _SELF, _UNKNOWN from .mapcanvas import RGB, parse_hex from .pathgraph import DST_NODE, GlyphOf, LabelOf, LabelRgbOf, SRC_NODE +from .pathline import PathLine, path_line from .theme import name_style, node_style, snr_style if TYPE_CHECKING: @@ -554,18 +555,59 @@ def route_graph_style( return glyph_of, label_of, label_rgb_of +def _route_path( + result: TraceResult, + device_label: str = LOCAL_DEVICE_LABEL, + resolve: NodeResolver = _identity, + device_hash: Optional[str] = None, + *, + bare_self: bool = False, +) -> PathLine: + """A trace's walked route as THE path widget's line object. + + The same route :func:`_route_text` renders — this hands back the + :class:`~meshterm.ui.pathline.PathLine` itself, so a surface with room to spare + can wrap it at hop boundaries (:meth:`~meshterm.ui.pathline.PathLine.wrapped`) + rather than taking the one-liner and folding it mid-name. + + Args: + result: The trace whose route to build. + device_label: Name to show for our own device at the path's endpoints. + resolve: Maps a raw hop hash to a friendly contact name when known. + device_hash: Our own device's key/hash, annotated onto its endpoints when known. + bare_self: Draw both ``us`` endpoints as their bare arrow — for a surface (the + trace screens' route lane) where a walk starting and ending on us is the + premise, not news. + + Returns: + The route's :class:`~meshterm.ui.pathline.PathLine` (hopless — reading + ``no hops recorded`` — when the trace recorded none). + """ + edges = result.edges(device_label) + if not edges: + return PathLine([], empty="no hops recorded") + hash_bytes = result.path_hash_bytes + nodes = [edges[0].origin] + [edge.destination for edge in edges] + hops = [None if not node or node == device_label else node for node in nodes] + return path_line( + hops, resolve, prefix_bytes=hash_bytes or 8, self_name=device_label, + show_hash=True, hash_bytes=hash_bytes, device_hash=device_hash, + bare_self=bare_self, + ) + + def _route_text( result: TraceResult, device_label: str = LOCAL_DEVICE_LABEL, resolve: NodeResolver = _identity, device_hash: Optional[str] = None, ) -> Text: - """Render a trace's walked route through THE path widget. + """Render a trace's walked route through THE path widget, on one line. Shows the path the trace actually walked — the forced path, or the route the - device resolved when auto-routing — as a :func:`path_text` in the trace - presentation: each node annotated by its hash at the command's path-hash width, - our own device bracketing both ends, e.g. + device resolved when auto-routing — in the trace presentation: each node + annotated by its hash at the command's path-hash width, our own device + bracketing both ends, e.g. ``Me (a1b2) → Alice (3d63) → Bob (f2a1) → Me (a1b2)``. Args: @@ -577,16 +619,7 @@ def _route_text( Returns: A :class:`Text` with the node sequence, or a muted note when no hops exist. """ - edges = result.edges(device_label) - if not edges: - return Text("no hops recorded", style="muted") - hash_bytes = result.path_hash_bytes - nodes = [edges[0].origin] + [edge.destination for edge in edges] - hops = [None if not node or node == device_label else node for node in nodes] - return path_text( - hops, resolve, prefix_bytes=hash_bytes or 8, self_name=device_label, - show_hash=True, hash_bytes=hash_bytes, device_hash=device_hash, - ) + return _route_path(result, device_label, resolve, device_hash).text() def _hop_medians_table( diff --git a/tests/test_live_screens.py b/tests/test_live_screens.py index 998e953..f770cef 100644 --- a/tests/test_live_screens.py +++ b/tests/test_live_screens.py @@ -8,14 +8,19 @@ and headless (the same approach as ``test_tui``). from __future__ import annotations import asyncio +import re from datetime import timedelta import pytest -from meshterm.core.models import Hop, TraceResult, TraceStats, TxLevelResult, TxOptResult, utcnow +from meshterm.core.models import Contact, Hop, TraceResult, TraceStats, TxLevelResult, \ + TxOptResult, utcnow +from meshterm.services.topology import PathScenario, build_topology from meshterm.ui.braillechart import _METER_SLIM from meshterm.ui.theme import snr_style -from meshterm.ui.trace_screen import _BAR_WIDTH, OPEN_TROPHY_CASE, TraceScreen, snr_bar +from meshterm.ui.trace_screen import ( + _BAR_WIDTH, OPEN_TROPHY_CASE, TraceScreen, _scenario_detail, _scenario_path, snr_bar, +) from meshterm.ui.tx_screen import TxSweepScreen # The slim meter's fill glyphs (the SNR bar draws through the shared braille meter). @@ -58,9 +63,14 @@ def _trace(*snrs: float, success: bool = True, target: str = "Alice") -> TraceRe ) +#: SGR escapes, stripped out of rendered lines so assertions read as plain text (a +#: per-hop-coloured path splits its own characters across a dozen colour runs). +_ANSI = re.compile(r"\x1b\[[0-9;]*m") + + def _plain(lines: list[str]) -> str: - """Join rendered ANSI lines and strip nothing — assertions use substring checks.""" - return "\n".join(lines) + """Join rendered lines with their colour escapes stripped, for substring checks.""" + return _ANSI.sub("", "\n".join(lines)) # --- snr_bar ------------------------------------------------------------------- @@ -365,8 +375,9 @@ async def test_trace_screen_composer_updates_the_spec() -> None: assert screen._path_spec == "3d,f2,3d" body = _plain(screen.render_body(100)) assert "3d,f2,3d" in body - # the planned route previews outbound *and* the resolved, dimmed return leg - assert body.count("Us") >= 2 + # the planned route previews outbound *and* the resolved, dimmed return leg, + # our own ends spending no words — just their bit of arrow + assert "route → 3d → f2 → 3d →" in body assert body.count("3d") >= 2 @@ -628,7 +639,10 @@ async def test_escaping_mid_run_skips_the_record_dialog() -> None: def test_planned_route_dims_only_the_mirrored_return_leg() -> None: - """A palindromic target-mode spec dims its second half; hand walks never dim.""" + """A palindromic target-mode spec dims its second half; hand walks never dim. + + Both ends are ours, so both go bare: the line opens and closes on a lone arrow. + """ screen, _ = _trace_screen() def faint_cells(text) -> int: # noqa: ANN001 @@ -637,18 +651,50 @@ def test_planned_route_dims_only_the_mirrored_return_leg() -> None: ) screen._path_spec = "3d,f2,3d" # symmetric boomerang: the mirror is dimmed - symmetric = screen._planned_route() - assert symmetric.plain == "Us → 3d → f2 → 3d → Us" + symmetric = screen._planned_route().text() + assert symmetric.plain == "→ 3d → f2 → 3d →" screen._path_spec = "3d,f2,27" # a stale hand walk: every hop is the user's - custom = screen._planned_route() - assert custom.plain == "Us → 3d → f2 → 27 → Us" + custom = screen._planned_route().text() + assert custom.plain == "→ 3d → f2 → 27 →" assert faint_cells(symmetric) > faint_cells(custom) # In path mode even a there-and-back-the-same-way walk is fully hand-composed, # so a palindrome must NOT read as "not yours to compose". walk, _ = _trace_screen(mode="path") walk._path_spec = "3d,f2,3d" - assert faint_cells(walk._planned_route()) == faint_cells(custom) + assert faint_cells(walk._planned_route().text()) == faint_cells(custom) + + +def test_route_lane_wraps_at_hop_boundaries_under_its_own_column() -> None: + """A route too wide for the lane breaks between hops, never inside one. + + Every continuation hangs under the value column (never back at column zero), the + line it continues from ends on the ``→`` cue, and no name is ever parted from the + hash it is addressed by. + """ + names = {"3d": "YUL-Cartierville", "f2": "Mile-End-Rooftop", "27": "Beaubien-Sud"} + screen, _ = _trace_screen(mode="path") + screen._resolve = lambda h: names.get(h, h) + screen._path_spec = "3d,f2,27" + lines = [line.plain for line in screen._route_value(None, 60)] + assert len(lines) > 1 # it really did wrap at this width + assert all(len(line) <= 60 for line in lines) + assert all(line.startswith(" " * 7) for line in lines[1:]) # hanging, not column 0 + assert all(line.rstrip().endswith("→") for line in lines[:-1]) + for hop, name in names.items(): # every name still carries its own hash, whole + assert any(f"{name} ({hop})" in line for line in lines) + + +def test_path_lane_breaks_the_wire_spec_after_a_comma() -> None: + """The spec lane stays the verbatim wire string, folding only at its commas.""" + screen, _ = _trace_screen(mode="path") + screen._path_spec = "3d63ab99,7f21cd01,27aa1122,f2c20099" + lines = [line.plain for line in screen._path_value(None, 44)] + assert len(lines) > 1 + assert all(len(line) <= 44 for line in lines) + assert lines[0].endswith(",") # the comma is the cue, not an arrow + spec = "".join(line.strip() for line in lines) + assert spec.startswith(screen._path_spec) # character for character, hop count after def test_summary_appends_the_displayed_hop_count() -> None: @@ -670,9 +716,11 @@ def test_auto_resolved_route_renders_with_its_provenance() -> None: screen, _ = _trace_screen( auto_spec=lambda: "3d63,f2c2,aabb,f2c2,3d63", auto_source="last trace · Jul 09 14:32" ) - plan = screen._planned_route().plain - assert "Us → 3d63 → f2c2 → aabb → f2c2 → 3d63 → Us" in plan - assert "(auto · last trace · Jul 09 14:32)" in plan + plan = screen._planned_route().text().plain + assert "→ 3d63 → f2c2 → aabb → f2c2 → 3d63 →" in plan + # The provenance hangs on its own line under the route, not inside the path itself. + route = "\n".join(line.plain for line in screen._route_value(None, 100)) + assert route.endswith("(auto · last trace · Jul 09 14:32)") body = _plain(screen.render_body(100)) assert "auto · last trace · Jul 09 14:32" in body # the summary's path row assert "· 5 hops" in body @@ -682,8 +730,8 @@ def test_composed_path_outranks_the_auto_route() -> None: """A hand-composed spec replaces the auto plan everywhere — display and wire.""" screen, _ = _trace_screen(auto_spec=lambda: "aabb", auto_source="device route") screen._path_spec = "3d63,aabb,3d63" - plan = screen._planned_route().plain - assert "Us → 3d63 → aabb → 3d63 → Us" in plan + plan = screen._planned_route().text().plain + assert "→ 3d63 → aabb → 3d63 →" in plan assert "(auto ·" not in plan assert screen._effective_spec() == ("3d63,aabb,3d63", False) @@ -730,9 +778,9 @@ async def test_trace_screen_path_mode_arms_from_the_previous_walk() -> None: body = _plain(screen.render_body(100)) assert "Trace — one transmission" in body # armed, not "compose a path first" assert "auto · last walk · Jul 09 14:32" in body # the summary's path row - plan = screen._planned_route().plain - assert "Us → 3d → f2 → Us" in plan - assert "(auto · last walk · Jul 09 14:32)" in plan + plan = screen._planned_route().text().plain + assert "→ 3d → f2 →" in plan + assert "(auto · last walk · Jul 09 14:32)" in body # hanging under the route screen.handle("enter") # the cursor opens on Trace assert screen._running await screen._worker @@ -767,7 +815,7 @@ async def test_reverse_flips_a_path_walk_and_restarts_the_run() -> None: assert screen._path_spec == "27,f2,3d" # end-for-end assert screen._traces == [] # the forward aggregates cleared assert screen._total_traces == 1 # the session count survives the restart - assert "Us → 27 → f2 → 3d → Us" in screen._planned_route().plain + assert "→ 27 → f2 → 3d →" in screen._planned_route().text().plain def test_reverse_adopts_and_flips_the_visible_auto_walk() -> None: @@ -779,7 +827,7 @@ def test_reverse_adopts_and_flips_the_visible_auto_walk() -> None: screen._index = screen._actions.index("reverse") screen.handle("enter") assert screen._path_spec == "f2,3d" # the shown auto walk, flipped and pinned - assert "Us → f2 → 3d → Us" in screen._planned_route().plain + assert "→ f2 → 3d →" in screen._planned_route().text().plain def test_reverse_is_inert_without_a_reversible_path() -> None: @@ -1082,3 +1130,70 @@ def test_parse_tx_range_clamps_and_rejects() -> None: assert parse_tx_range("2-99") == (12, 28) # clamped to the firmware window assert parse_tx_range("24-14") is None assert parse_tx_range("banana") is None + + +# --- explore-paths scenario rows -------------------------------------------------- + +_US = "aaaaaaaaaaaa" +_HUB = Contact(name="Hub", public_key="3d63c6429436" + "0" * 52, key_prefix="3d63c6429436") +_FAR = Contact(name="Far", public_key="f2c24f54551e" + "0" * 52, key_prefix="f2c24f54551e") + + +def _scenario_topo() -> object: + return build_topology( + self_id=_US + "0" * 52, contacts=[_HUB, _FAR], + trace_paths=[], packet_paths=[], neighbour_links=[], + ) + + +def test_scenario_path_leads_and_ends_with_us_and_the_target() -> None: + """The pathline names the whole boomerang leg, not just the stored intermediate hops.""" + topo = _scenario_topo() + scenario = PathScenario( + label="observed path", hops=("3d63c6429436",), source="observed", score=1.0, + ) + text = _scenario_path( + scenario, topo, "f2c24f54551e", device_label="YUL-Me", width_bytes=1 + ) + assert text.plain == "YUL-Me → Hub → Far" + + +def test_scenario_path_direct_scenario_still_names_both_endpoints() -> None: + """A direct (no-repeaters) scenario's pathline is just us and the target — no gap.""" + topo = _scenario_topo() + scenario = PathScenario(label="direct", hops=(), source="direct", score=0.0) + text = _scenario_path( + scenario, topo, "f2c24f54551e", device_label="YUL-Me", width_bytes=1 + ) + assert text.plain == "YUL-Me → Far" + + +def test_scenario_detail_carries_provenance_snr_and_samples() -> None: + """The device/direct provenance tag, weakest SNR, and sample count all show, in order.""" + scenario = PathScenario( + label="device route", hops=("3d63c6429436",), source="device", score=2.0, + weakest_snr=-6.0, samples=3, + ) + detail = _scenario_detail(scenario) + assert "device route" in detail.plain + assert "weakest -6.0 dB" in detail.plain + assert "3×" in detail.plain + + +def test_scenario_detail_observed_carries_no_provenance_tag() -> None: + """An observed candidate's detail line skips the tag — the route itself is the point.""" + scenario = PathScenario( + label="observed path", hops=("3d63c6429436",), source="observed", score=1.0, + weakest_snr=-4.0, samples=2, + ) + detail = _scenario_detail(scenario) + assert "observed" not in detail.plain + assert "weakest -4.0 dB" in detail.plain + + +def test_scenario_detail_unscored_scenario_reads_unobserved() -> None: + """A scenario with no evidence at all (score 0, no samples) reads plainly unobserved.""" + scenario = PathScenario(label="direct", hops=(), source="direct", score=0.0) + detail = _scenario_detail(scenario) + assert "direct" in detail.plain + assert "unobserved" in detail.plain diff --git a/tests/test_node_detail.py b/tests/test_node_detail.py index 3642d87..b0ea7af 100644 --- a/tests/test_node_detail.py +++ b/tests/test_node_detail.py @@ -192,36 +192,50 @@ def test_tab_strip_collapses_a_lone_tab_to_a_plain_heading() -> None: # --- the folded-in route line --------------------------------------------------- -def test_route_line_reads_contact_to_us_with_relays_named() -> None: - """A route row runs contact → relays → us, each relay named and hash-tagged, tag trailing.""" - resolve = make_node_resolver([HUB, FAR]) - line = _route_line( +def test_route_line_shows_hashes_not_names() -> None: + """The pathline runs contact → relays → us, every hop by its hash; the tag trails on context.""" + path, context = _route_line( "Far", FAR.public_key, ("3d63c6429436",), "device", None, 0, - resolve=resolve, self_name="Us", - ).plain - assert line.startswith("Far") # the contact anchors the left - assert "Hub" in line and "(3d)" in line # the relay named + its first-byte tag - assert line.rstrip().endswith("device route") # the firmware-route tag trails - assert "Us" in line # our own node anchors the right + self_name="Us", self_key=US + "0" * 52, hash_bytes=1, + ) + line = path.plain + assert line.startswith("f2") # the contact anchors the left, by hash + assert "3d" in line # the relay's first-byte hash + assert "Far" not in line and "Hub" not in line # names are not resolved into the line + assert "aa" in line # our own node anchors the right, by hash + assert context.plain == "device route" # the firmware-route tag, off the pathline itself + + +def test_route_line_hash_width_follows_our_path_hash_mode() -> None: + """A device carrying 3-byte routing hashes shows 3-byte hops, not the 1-byte default.""" + path, _context = _route_line( + "Far", FAR.public_key, ("3d63c6429436",), "", None, 0, + self_name="Us", self_key=US + "0" * 52, hash_bytes=3, + ) + line = path.plain + assert "f2c24f" in line # the contact's hash at 3 bytes + assert "3d63c6" in line # the relay's hash at 3 bytes + assert "aaaaaa" in line # our own node's hash at 3 bytes def test_route_line_marks_the_best_route_and_its_context() -> None: - """The winner wears ★ best and trails its bottleneck SNR and sample count.""" - resolve = make_node_resolver([HUB, FAR]) - line = _route_line( + """The winner wears ★ best and trails its bottleneck SNR and sample count, on the context line.""" + _path, context = _route_line( "Far", FAR.public_key, ("3d63c6429436",), "best", 6.5, 4, - resolve=resolve, self_name="Us", - ).plain + self_name="Us", self_key=US + "0" * 52, hash_bytes=1, + ) + line = context.plain assert "★ best" in line and "weakest" in line and "6.5" in line and "4×" in line def test_route_line_direct_route_has_no_relay() -> None: """A zero-hop route reads contact → us with nothing between them.""" - line = _route_line( + path, _context = _route_line( "Far", FAR.public_key, (), "best", None, 0, - resolve=make_node_resolver([FAR]), self_name="Us", - ).plain - assert "Far" in line and "Us" in line and "→" in line + self_name="Us", self_key=US + "0" * 52, hash_bytes=1, + ) + line = path.plain + assert "f2" in line and "aa" in line and "→" in line # --- the routes view (list + graph callbacks) ----------------------------------- @@ -249,8 +263,10 @@ def _view(topo, suggested, device_route, target, node_label, contacts, name_key= resolve=make_node_resolver(contacts), type_of=make_node_type_resolver(contacts), key_of=make_name_key_resolver(contacts), - style=route_graph_style, self_name="Us", node_label=node_label, + style=route_graph_style, self_name="Us", self_key=US + "0" * 52, + node_label=node_label, name_key=name_key or (target + "0" * 52), + hash_bytes=1, ) @@ -268,7 +284,9 @@ def test_routes_view_draws_evidence_and_notes_its_absence() -> None: empty, empty.scenarios("f2c24f54551e"), None, None, "f2c24f54551e", "f2c24f54551e", 1, resolve=make_node_resolver([FAR]), type_of=make_node_type_resolver([FAR]), key_of=make_name_key_resolver([FAR]), style=route_graph_style, self_name="Us", + self_key=US + "0" * 52, node_label="Far", name_key=FAR.public_key, + hash_bytes=1, ) assert not note.routes and "no route observed" in note.note @@ -396,15 +414,15 @@ def test_contract_bidir_clusters_folds_a_knot_but_keeps_the_rows() -> None: from meshterm.ui.node_detail_screen import _contract_bidir_clusters routes = [ - _Route(draw=("aa", "bb", "cc"), spec="s1", row=Text("A B C")), - _Route(draw=("cc", "bb", "aa"), spec="s2", row=Text("C B A")), + _Route(draw=("aa", "bb", "cc"), spec="s1", path=Text("A B C"), context=Text("")), + _Route(draw=("cc", "bb", "aa"), spec="s2", path=Text("C B A"), context=Text("")), ] new, clusters = _contract_bidir_clusters(routes, lambda _n: 2) # all repeaters (cid, cluster), = clusters.items() assert cluster.label == "3 repeaters" and cluster.glyph == "▲" assert [r.draw for r in new] == [(cid,), (cid,)] # members folded to the one cluster stop assert [r.spec for r in new] == ["s1", "s2"] # traces still arm on the real path - assert [r.row.plain for r in new] == ["A B C", "C B A"] # the list keeps the full order + assert [r.path.plain for r in new] == ["A B C", "C B A"] # the list keeps the full order def test_contract_leaves_a_two_node_pair_and_unclustered_routes_alone() -> None: @@ -412,8 +430,8 @@ def test_contract_leaves_a_two_node_pair_and_unclustered_routes_alone() -> None: from meshterm.ui.node_detail_screen import _contract_bidir_clusters routes = [ - _Route(draw=("aa", "bb"), spec="s1", row=Text("A B")), - _Route(draw=("bb", "aa"), spec="s2", row=Text("B A")), + _Route(draw=("aa", "bb"), spec="s1", path=Text("A B"), context=Text("")), + _Route(draw=("bb", "aa"), spec="s2", path=Text("B A"), context=Text("")), ] new, clusters = _contract_bidir_clusters(routes, lambda _n: 2) assert clusters == {} @@ -426,8 +444,8 @@ def test_contract_labels_a_mixed_cluster_generically() -> None: from meshterm.ui.node_detail_screen import _contract_bidir_clusters routes = [ - _Route(draw=("aa", "bb", "cc"), spec="", row=Text("")), - _Route(draw=("cc", "bb", "aa"), spec="", row=Text("")), + _Route(draw=("aa", "bb", "cc"), spec="", path=Text(""), context=Text("")), + _Route(draw=("cc", "bb", "aa"), spec="", path=Text(""), context=Text("")), ] _new, clusters = _contract_bidir_clusters(routes, lambda n: {"aa": 2, "bb": 3, "cc": 4}[n[:2]]) (_cid, cluster), = clusters.items() @@ -537,8 +555,8 @@ def _two_routes() -> _RoutesView: """A routes view with two selectable routes, the way the assembly hands them over.""" return _RoutesView( routes=[ - _Route(draw=("3d63c6429436",), spec="3d,f2,3d", row=Text("via Hub")), - _Route(draw=("a1a1a1a1a1a1",), spec="a1,f2,a1", row=Text("via Alt")), + _Route(draw=("3d63c6429436",), spec="3d,f2,3d", path=Text("via Hub"), context=Text("")), + _Route(draw=("a1a1a1a1a1a1",), spec="a1,f2,a1", path=Text("via Alt"), context=Text("")), ], glyph_of=lambda n: ("●", "#ffffff"), label_of=lambda n: n[:2], @@ -562,6 +580,88 @@ def test_node_detail_screen_route_selection_arms_the_trace() -> None: assert "Trace" not in body # the auto-route stand-in only shows with no routes to list +def test_node_detail_screen_context_hangs_under_the_pathline() -> None: + """The weakest/samples/tag context draws on its own line, indented under the pathline.""" + routes = _RoutesView( + routes=[ + _Route( + draw=("3d63c6429436",), spec="3d,f2,3d", + path=Text("f2 3d aa"), + context=Text("weakest -6.0 dB · 3× · ★ best"), + ), + ], + glyph_of=lambda n: ("●", "#ffffff"), + label_of=lambda n: n[:2], + label_rgb_of=lambda n: (200, 200, 200), + ) + screen = _screen(routes=routes, tabs=[_Tab("Routes", "routes")]) + screen.note_viewport(30) + lines = screen.render_body(72) + body = _plain(lines) + assert "f2 3d aa …" in body # the pathline, opens-marked + assert "weakest -6.0 dB" in body and "★ best" in body # the context, drawn too + path_idx = next(i for i, l in enumerate(lines) if "f2 3d aa" in _plain([l])) + assert _plain([lines[path_idx]]).startswith("❯ f2 3d aa") # the pointer leads the pathline + context_line = _plain([lines[path_idx + 1]]) + assert context_line.startswith(" weakest") # hanging two columns under it, no pointer + + +def test_node_detail_screen_context_line_absent_when_theres_nothing_to_show() -> None: + """A route with no weakest SNR, sample count, or tag draws just its pathline — no bare + hanging line under it.""" + routes = _RoutesView( + routes=[_Route(draw=(), spec="", path=Text("f2 aa"), context=Text(""))], + glyph_of=lambda n: ("●", "#ffffff"), + label_of=lambda n: n[:2], + label_rgb_of=lambda n: (200, 200, 200), + ) + screen = _screen(routes=routes, tabs=[_Tab("Routes", "routes")]) + screen.note_viewport(30) + lines = screen.render_body(72) + path_idx = next(i for i, l in enumerate(lines) if "f2 aa" in _plain([l])) + # The very next line is already the next chunk of chrome (the rule/actions), not a blank + # or muted context line — nothing hangs under a route that earned no context. + assert not _plain([lines[path_idx + 1]]).strip().startswith("weakest") + + +def test_node_detail_screen_hscrolls_the_selected_pathline() -> None: + """A pathline too wide for the lane scrolls with ←/→ on the highlighted row only; moving + the cursor off it abandons the scroll, and an unselected long row just ellipsizes.""" + long_path = Text("f2 " + " ".join(f"{i:02x}" for i in range(40)) + " aa") + routes = _RoutesView( + routes=[ + _Route(draw=("3d",), spec="s0", path=long_path.copy(), context=Text("")), + _Route(draw=("a1",), spec="s1", path=Text("f2 3d aa"), context=Text("")), + ], + glyph_of=lambda n: ("●", "#ffffff"), + label_of=lambda n: n[:2], + label_rgb_of=lambda n: (200, 200, 200), + ) + screen = _screen(routes=routes, tabs=[_Tab("Routes", "routes")]) + screen.note_viewport(30) + body = _plain(screen.render_body(72)) + assert "f2 00 01 02" in body # unscrolled, the chain's start shows + assert "←→ scroll" in screen.footer_hint # the overflow earns the footer atom + + screen.handle("right") + screen.handle("right") + body = _plain(screen.render_body(72)) + assert "f2 00 01 02" not in body # the view has shifted away from the start + + screen.handle("left") + body = _plain(screen.render_body(72)) + assert "f2 00 01 02" not in body # one step back, still short of the start + + screen.handle("down") # onto route 1 — abandons route 0's scroll, short row can't scroll + screen.render_body(72) + assert "←→ scroll" not in screen.footer_hint # route 1's short pathline earns no hint + + screen.handle("up") # back onto route 0 + body = _plain(screen.render_body(72)) + assert "f2 00 01 02" in body # the shift reset, back at the start + assert "←→ scroll" in screen.footer_hint # route 0 overflows again + + def test_node_detail_enter_on_a_route_row_opens_its_trace() -> None: """Enter on any route row arms a trace on that route — no separate Trace row needed.""" screen = _screen(routes=_two_routes(), tabs=[_Tab("Routes", "routes")]) @@ -589,8 +689,8 @@ def test_route_labels_light_through_a_coalesced_hop() -> None: routes = _RoutesView( routes=[ - _Route(draw=("bf61f2fb1d9e", "3d63c6429436"), spec="s0", row=Text("wide")), - _Route(draw=("bf61f2fb1d9e", "3d"), spec="s1", row=Text("short")), + _Route(draw=("bf61f2fb1d9e", "3d63c6429436"), spec="s0", path=Text("wide"), context=Text("")), + _Route(draw=("bf61f2fb1d9e", "3d"), spec="s1", path=Text("short"), context=Text("")), ], glyph_of=lambda n: ("●", "#ffffff"), label_of=lambda n: n[:2], @@ -608,7 +708,7 @@ def test_node_detail_route_list_windows_inside_the_page() -> None: action rows never leave the screen, however many routes a busy node has.""" routes = _RoutesView( routes=[ - _Route(draw=(f"{i:x}{i:x}" * 6,), spec=f"s{i}", row=Text(f"route {i}")) + _Route(draw=(f"{i:x}{i:x}" * 6,), spec=f"s{i}", path=Text(f"route {i}"), context=Text("")) for i in range(12) ], glyph_of=lambda n: ("●", "#ffffff"), diff --git a/tests/test_pathline.py b/tests/test_pathline.py index d0e97d3..51cd88a 100644 --- a/tests/test_pathline.py +++ b/tests/test_pathline.py @@ -8,10 +8,14 @@ cell budget — so these tests assert rendered strings and span styles, not vibe from __future__ import annotations +import random + import pytest import meshterm.ui.pathline as pathline -from meshterm.ui.pathline import POWERLINE_SEP, PathHop, PathLine, path_line +from meshterm.ui.pathline import ( + POWERLINE_CAP, POWERLINE_SEP, PathHop, PathLine, _style_hex, path_line, +) from meshterm.ui.theme import node_style from meshterm.ui.widgets import path_text @@ -157,6 +161,99 @@ def test_wrapped_breaks_at_hops_under_a_hanging_indent() -> None: assert all(line.cell_len <= 16 for line in lines) +def test_wrapped_evens_the_lines_instead_of_widowing_the_tail() -> None: + """A hop that misses the first line by a cell doesn't get stranded alone below it. + + Greedy packing would cram ``us → a → b →`` and widow ``us``; the fold takes the + same number of lines either way, so it spreads the hops across them instead. + """ + hops = [PathHop(label) for label in ("us", "alpha", "bravo", "us")] + lines = PathLine(hops, mode="plain").wrapped(20, indent=0) + assert [line.plain for line in lines] == ["us → alpha →", "bravo → us"] + + +def test_wrapped_folds_a_faded_return_leg_at_its_turn() -> None: + """A boomerang breaks where it turns — composed leg above, its echo below. + + The dimmed hops are the mirrored return, so folding there gives the wrapped route + a shape instead of an arbitrary mid-leg seam. It is only taken when free: here the + turn fold costs no more lines than the greedy break would. + """ + out = [PathHop(n) for n in ("me", "north-relay", "east-relay", "dest")] + back = [PathHop(n, dim=True) for n in ("east-relay", "north-relay", "me")] + lines = PathLine(out + back, mode="plain").wrapped(40, indent=0) + assert [line.plain for line in lines] == [ + "me → north-relay → east-relay → dest →", # out, ending on the target + "east-relay → north-relay → me", # and the mirror it comes home by + ] + + +def test_wrapped_folds_a_walked_boomerang_at_its_turn_too() -> None: + """A trace that answered dims nothing, but its route is still its own mirror. + + So the turn is found from the hop sequence itself, and the walk folds exactly + where the plan that armed it folded — one route, one shape. + """ + walked = [PathHop(n) for n in ("me", "north-relay", "east-relay", "dest")] + walked += [PathHop(n) for n in ("east-relay", "north-relay", "me")] + lines = PathLine(walked, mode="plain").wrapped(46, indent=0) + assert [line.plain for line in lines] == [ + "me → north-relay → east-relay → dest →", + "east-relay → north-relay → me", + ] + + +def test_wrapped_never_folds_before_a_lone_faded_landing() -> None: + """A path whose only dim hop is the automatic landing home keeps it on a real line. + + Path-mode walks dim just that last ``us``; folding at "the fade" there would widow + it, so the seam needs two hops on each side to count as a turn. + """ + hops = [PathHop(label) for label in ("us", "alpha", "bravo", "charlie")] + hops.append(PathHop("us", dim=True)) + lines = PathLine(hops, mode="plain").wrapped(26, indent=0) + assert len(lines) == 2 + assert lines[-1].plain != "us" + assert lines[-1].plain.endswith("→ us") + + +def test_wrapped_lines_always_fit_their_width() -> None: + """No mix of hops, mode, width, or indent ever produces a line past the budget. + + Lines are fitted arithmetically from per-hop measurements rather than by rendering + every candidate group, so this sweeps that model against what actually gets drawn — + over-wide lone hops (truncated, cue included) and chip lines (which carry a closing + edge no arrow line has) are where the two would drift apart. + """ + rng = random.Random(7) + for _ in range(200): + hops = [ + PathHop( + "N" * rng.randint(1, 16), + key=f"{i:02x}aa", + annotation=f"{i:02x}" if rng.random() < 0.5 else None, + dim=rng.random() < 0.3, + you=rng.random() < 0.2, + lit_bytes=rng.choice((0, 1, 2)), + ) + for i in range(rng.randint(1, 9)) + ] + for mode in ("plain", "powerline"): + for width, indent in ((20, 0), (34, 2), (47, 7), (72, 16)): + lines = PathLine(hops, mode=mode).wrapped(width, indent=indent) + assert all(line.cell_len <= width for line in lines) + + +def test_wrapped_continuation_cue_follows_the_separator() -> None: + """A comma-joined line (the trace screen's wire spec) continues on a comma, not an + arrow — the cue is the separator's own mark, so the spec stays verbatim.""" + hops = [PathHop(label) for label in ("3d63ab99", "7f21cd01", "27aa1122")] + lines = PathLine(hops, mode="plain", separator=",").wrapped(20, indent=2) + assert lines[0].plain.endswith(",") + assert "→" not in "".join(line.plain for line in lines) + assert "".join(line.plain.strip() for line in lines) == "3d63ab99,7f21cd01,27aa1122" + + def test_path_line_factory_matches_path_text_character_for_character() -> None: """The migration bridge: the trace flavour — device endpoints with annotated hashes, a named hop, a prefix-lit unnamed hop, a dimmed tail — renders through @@ -199,11 +296,46 @@ def test_wrapped_carries_the_cursor_even_onto_a_line_break() -> None: assert not any(str(s.style) == "selected" for s in on_break[1].spans) -def test_wrapped_chip_lines_each_close_their_pointed_edge() -> None: - """Chip wrapping never splits a chip; every line ends on the pointed edge.""" +def test_wrapped_chip_lines_close_male_and_open_female() -> None: + """Chip wrapping never splits a chip; every line ends on the pointed edge, and + every line *but the first* opens on its mirror — the continuation's own mark, so + only the path's very first chip shows a square left edge.""" hops = [PathHop(label) for label in ("AAAA", "BBBB", "CCCC", "DDDD")] - lines = PathLine(hops, mode="powerline").wrapped(16, indent=2) + lines = PathLine(hops, mode="powerline").wrapped(18, indent=2) assert len(lines) == 2 - assert lines[1].plain.startswith(" ") + assert lines[0].plain.startswith(" AAAA") # the square edge: this is the start + assert lines[1].plain.startswith(" " + POWERLINE_CAP) # …and this is a carry-on assert all(line.plain.endswith(POWERLINE_SEP) for line in lines) - assert all(line.cell_len <= 16 for line in lines) + assert all(line.cell_len <= 18 for line in lines) + + +def test_bare_hops_draw_as_their_seam_alone() -> None: + """An empty label spends no cells: arrow mode drops the padding it would have sat + in, chip mode gives it no chip at all — the arrow into the page *is* the hop.""" + hops = [PathHop("", you=True), PathHop("Alice", key="aa"), PathHop("", you=True)] + assert PathLine(hops, mode="plain").text().plain == "→ Alice →" + + chips = PathLine(hops, mode="powerline").text() + assert chips.plain == POWERLINE_SEP + " Alice " + POWERLINE_SEP + styles = [str(span.style) for span in chips.spans] + # The leading seam is us pointing into Alice's field; the trailing one is Alice's + # own point into the page — the closing edge a named tail would have added. + assert styles[0] == f"#ffffff on {_style_hex(node_style('aa'))}" + assert styles[-1] == _style_hex(node_style("aa")) + + +def test_bare_self_endpoints_survive_wrapping() -> None: + """``bare_self`` strips our name and hash from a route's ends; a line that wraps + still opens on the female point, and a widowed bare end still draws one.""" + hops = [None, *(f"{i:02x}aa" for i in range(6)), None] + line = path_line(hops, prefix_bytes=2, self_name="Me", show_hash=True, + device_hash="a1b2", bare_self=True, mode="plain") + assert line.text().plain.startswith("→ 00aa") + assert line.text().plain.endswith("05aa →") + assert "Me" not in line.text().plain + + lines = path_line(hops, prefix_bytes=2, self_name="Me", bare_self=True, + mode="powerline").wrapped(28, indent=2) + assert len(lines) > 1 + assert all(line.plain.startswith(" " + POWERLINE_CAP) for line in lines[1:]) + assert all(line.cell_len <= 28 for line in lines) diff --git a/tests/test_tui.py b/tests/test_tui.py index 3f11d9d..6174eb9 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -2008,3 +2008,54 @@ def test_select_without_hscroll_ignores_left_right() -> None: screen.handle("right") screen.handle("left") assert screen.render_body(40) == before and screen._hshift == 0 + + +# --- row detail lines (opt-in) ------------------------------------------------------- + + +def test_select_choice_detail_hangs_under_its_row() -> None: + """A Choice.detail draws as a second, indented line right under its title.""" + from meshterm.ui.tui.select import Choice, SelectScreen + + screen = SelectScreen( + "pick", [Choice("first row", 1, detail="weakest -6.0 dB · 3×"), Choice("second", 2)] + ) + lines = _row_plains(screen, 40) + idx = next(i for i, ln in enumerate(lines) if "first row" in ln) + assert lines[idx + 1].startswith(" weakest -6.0 dB") + assert "second" in lines[idx + 2] + + +def test_select_choice_without_detail_draws_one_line() -> None: + """A Choice with no detail (the default, or one resolving empty) stays a single line.""" + from meshterm.ui.tui.select import Choice, SelectScreen + + screen = SelectScreen("pick", [Choice("first row", 1), Choice("second", 2, detail="")]) + lines = _row_plains(screen, 40) + assert lines[1].strip() == "second" + + +def test_select_cursor_tracks_the_highlight_past_a_detail_line() -> None: + """The cursor lands on the title line even when an earlier row grew a detail line.""" + from meshterm.ui.tui.select import Choice, SelectScreen + + screen = SelectScreen( + "pick", + [Choice("first row", 1, detail="has detail"), Choice("second", 2)], + default=2, + ) + lines = _row_plains(screen, 40) + assert screen.cursor_line() == next(i for i, ln in enumerate(lines) if "second" in ln) + + +def test_select_hscroll_leaves_the_detail_line_unshifted() -> None: + """←→ slides the highlighted row's title only — its detail line never scrolls.""" + from meshterm.ui.tui.select import Choice, SelectScreen + + long_title = "row-one-" + "x" * 60 + "-tail" + screen = SelectScreen( + "pick", [Choice(long_title, 1, detail="weakest -6.0 dB")], hscroll=True + ) + screen.handle("right") + lines = _row_plains(screen, 40) + assert "weakest -6.0 dB" in lines[1]