From 7dd7cb5a6207cc95b68f9f6bd9711b630eef0382 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Tue, 3 Nov 2026 03:01:12 -0500 Subject: [PATCH] ^N shows the places of the nodes on Node detail, the packet viewer, Live feed, and Trace Each screen opens with node names and keeps its own choice. Node detail acts only on the Routes tab (F1). The packet viewer changes its via line and its from/to chips (F1). Live feed changes the endpoint chips of an addressed packet (F1). Trace changes its route lane and its per-hop links (F1). Each hint and chip shows only where a line has a named hop. Co-Authored-By: Claude Sonnet 5.5 --- meshterm/ui/livefeed_screen.py | 65 +++++++- meshterm/ui/node_detail_screen.py | 86 +++++++++-- meshterm/ui/packet_viewer.py | 59 +++++++- meshterm/ui/trace_screen.py | 146 +++++++++++++----- tests/test_place_mode_screens.py | 244 ++++++++++++++++++++++++++++++ 5 files changed, 537 insertions(+), 63 deletions(-) create mode 100644 tests/test_place_mode_screens.py diff --git a/meshterm/ui/livefeed_screen.py b/meshterm/ui/livefeed_screen.py index 682e490..4ab8364 100644 --- a/meshterm/ui/livefeed_screen.py +++ b/meshterm/ui/livefeed_screen.py @@ -96,6 +96,8 @@ from .packet_viewer import ( unnamed_scope, ) from .pathline import SELF_GLYPH, PathHop, cut_to +from .placemode import ACTION as PLACES_ACTION +from .placemode import PlaceToggle, node_of, placed_hops, places_of_session from .theme import name_style, snr_style from .tui.render import crop_cells, render_to_ansi from .tui.screen import ListWindow, Screen @@ -288,6 +290,11 @@ class LiveFeedScreen(Screen): floating = False + #: The hint sheds this atom first when it is too wide (refer to + #: :func:`~meshterm.ui.tui.frame.fit_hint`). The user can try the arrow keys on a row + #: that is too wide, but nothing else shows ^N. + spare_hint_atoms = ("←→ scroll line",) + @property def picocalc_lyra_lane(self): """The shared lane, which stays dim until there are packets to move through. @@ -302,10 +309,16 @@ class LiveFeedScreen(Screen): An empty feed has no cursor and no place to move to. Thus all four chips are dim until the first packet arrives. - """ - from .tui.fkeys import default_lane - return default_lane(nav=bool(self._feed)) + F1 is the place mode of the route chips (^N). It has a chip only while the feed + holds a row that draws such a chip. + """ + from .tui.fkeys import FPair, default_lane + + lane = list(default_lane(nav=bool(self._feed))) + if self._places_available(): + lane[0] = FPair(self._places.chip, PLACES_ACTION) + return lane def __init__( self, @@ -399,6 +412,8 @@ class LiveFeedScreen(Screen): #: range. self._hshift = 0 self._hmax = 0 + #: ^N: the route chips of the subject lane show the node names, or the places. + self._places = PlaceToggle() # --- live feed ----------------------------------------------------------------- @@ -457,10 +472,39 @@ class LiveFeedScreen(Screen): This is the same rule ("advertise a key only where it acts") that the ``hscroll`` hint of the select list follows. """ - base = "↑↓ PgUp/PgDn Home/End move · Enter open · Esc back" + atoms = ["↑↓ PgUp/PgDn Home/End move"] if self._selected is not None and self._hmax > 0: - return "↑↓ PgUp/PgDn Home/End move · ←→ scroll line · Enter open · Esc back" - return base + atoms.append("←→ scroll line") + atoms.append("Enter open") + if self._places_available(): + atoms.append(self._places.hint) + atoms.append("Esc back") + return " · ".join(atoms) + + def _places_available(self) -> bool: + """Whether ^N acts: a row of the feed draws its subject as a route chip pair.""" + return any(self._has_endpoints(entry) for entry in self._feed) + + def _has_endpoints(self, entry: PacketEntry) -> bool: + """Whether the subject of the row is the two endpoints of an addressed packet. + + The tests follow the order of :meth:`_feed_subject`. A packet that names a node, a + message, and a channel packet each have another subject. Also, one of the two + endpoints must have a name, because only a name is a chip that ^N can change. + """ + raw = entry.raw if isinstance(entry.raw, dict) else {} + if not raw.get("dest_hash") or not (raw.get("src_key") or raw.get("src_hash")): + return False + if entry.kind == "message" or raw.get("payload_typename") in CHANNEL_CLASSES: + return False + if node_label(entry, self._resolve, self._self_name)[0] != "?": + return False + ends = (raw.get("dest_hash"), raw.get("src_key") or raw.get("src_hash")) + names = (self._resolve(end) for end in ends) + return any( + name and name != end and name != self._self_name + for name, end in zip(names, ends, strict=True) + ) def handle(self, action: str, data: str = "") -> None: """Move the cursor, commit the row that it is on, scroll a row, or leave.""" @@ -487,6 +531,10 @@ class LiveFeedScreen(Screen): self._select_stop(0) elif action in ("end", "ctrl_end"): self._select_stop(len(self._feed)) + elif action == PLACES_ACTION: + if self._places_available(): + self._places.flip() + self._session.invalidate() elif action == "left": self._scroll_line(-_HSCROLL_STEP) elif action == "right": @@ -921,7 +969,10 @@ class LiveFeedScreen(Screen): if name and name == self._self_name: return PathHop(SELF_GLYPH, you=True) if name and name != value: - return PathHop(name, key=value) + hop = PathHop(name, key=value) + if self._places.on: + hop = placed_hops([hop], places_of_session(), node_of(self._resolve))[0] + return hop return PathHop(short, key=value, lit_bytes=ENDPOINT_HASH_BYTES) @staticmethod diff --git a/meshterm/ui/node_detail_screen.py b/meshterm/ui/node_detail_screen.py index 030c25c..cfdf6ea 100644 --- a/meshterm/ui/node_detail_screen.py +++ b/meshterm/ui/node_detail_screen.py @@ -141,6 +141,8 @@ from .pathline import ( hops_atom, with_action_mark, ) +from .placemode import ACTION as PLACES_ACTION +from .placemode import NodeOf, PlaceToggle, node_of, placed, places_of_session from .theme import glyph as platform_glyph from .theme import mark_rgb, name_style, snr_style from .tui.render import crop_cells, render_hanging, render_lines, render_to_ansi @@ -328,12 +330,15 @@ class _Route: context: The line that hangs under ``path``: the hop count, then the bottleneck SNR, the sample count, and a ``★ best`` or ``device route`` tag when the route has them. The hop count is always there, so this line is never empty. + line: The same path line before it became text. With it, place mode (^N) can name + the hops by their places. ``None`` means that the route has no place mode. """ draw: tuple[str, ...] spec: str path: Text context: Text + line: PathLine | None = None @dataclass(slots=True) @@ -382,6 +387,8 @@ class _RoutesView: legend: Whether to draw the node-type legend below the graph (a relay with a known type was shown). note: The muted line shown instead of a graph when there is no evidence. + find: Gives the node id for the hash of a hop (:func:`~meshterm.ui.placemode.node_of` + of the resolver), for place mode. ``None`` when the resolver cannot tell. """ routes: list[_Route] = field(default_factory=list) @@ -390,6 +397,7 @@ class _RoutesView: label_rgb_of: LabelRgbOf | None = None legend: bool = False note: str = "" + find: NodeOf | None = None @dataclass(slots=True) @@ -446,10 +454,15 @@ class NodeDetailScreen(Screen): The pager works only when the route list is really in a list window. On the Info tab, and on a node whose routes all fit, the keys move nothing. + + F1 is the place mode of the path lines (^N). It has a chip only while the Routes tab + shows a path line that place mode can change. """ from .tui.fkeys import FPair, default_lane lane = list(default_lane(nav=self._list_hidden)) + if self._places_available(): + lane[0] = FPair(self._places.chip, PLACES_ACTION) if len(self._tabs) >= 2: nxt = self._tabs[(self._tab_index + 1) % len(self._tabs)] lane[2] = FPair(nxt.name, "tab") @@ -573,6 +586,8 @@ class NodeDetailScreen(Screen): #: The last render width. With it, the footer hint can tell whether the path line of #: the highlighted route really overflows (nothing overflows before the first paint). self._last_width = 0 + #: ^N: the path lines of the Routes tab show the node names, or the places. + self._places = PlaceToggle() # --- input ----------------------------------------------------------------- @@ -600,9 +615,24 @@ class NodeDetailScreen(Screen): parts.append("←→ scroll") elif self._key_overflows(): parts.append("←→ scroll key") + if self._places_available(): + parts.append(self._places.hint) parts.append("Esc back") return " · ".join(parts) + def _places_available(self) -> bool: + """Whether ^N acts: the Routes tab is open and a route has a path line to change.""" + tab = self._tabs[self._tab_index] if self._tabs else None + if tab is None or tab.kind != "routes" or self._routes is None: + return False + return any(route.line is not None for route in self._routes.routes) + + def _route_path(self, route: _Route) -> Text: + """The path line of a route as text: with its places while place mode is on.""" + if self._places.on and route.line is not None and self._routes is not None: + return placed(route.line, places_of_session(), self._routes.find).text() + return route.path + def _selected_route_overflows(self) -> bool: """Whether the highlighted path line is too wide for the content lane of the list. @@ -623,7 +653,7 @@ class NodeDetailScreen(Screen): # The `…` at the end is chrome outside the lane (pathline.with_action_mark), so it # is not part of what must fit. A route exactly as wide as its lane does not scroll, # and the mark is the thing that is not shown. - return cell_len(routes[self._row_index].path.plain) > avail + return cell_len(self._route_path(routes[self._row_index]).plain) > avail def _on_info_tab(self) -> bool: """Whether the Info tab fills the stage (thus its key lane is visible).""" @@ -751,6 +781,9 @@ class NodeDetailScreen(Screen): else: assert isinstance(payload, _Action) self.resolve(payload.key) + elif action == PLACES_ACTION: + if self._places_available(): + self._places.flip() elif action == "tab": self._switch_tab(1) elif action == "shift_tab": @@ -1158,7 +1191,7 @@ class NodeDetailScreen(Screen): indent = _ROUTE_INDENT avail = max(1, width - indent) pointer = Text("❯ " if selected else " ", style="cursor" if selected else "") - marked = route.path + marked = self._route_path(route) if selected and self._hshift: total = cell_len(marked.plain) # A scrolled row gave one cell to its left mark, so its last visible part has @@ -2520,6 +2553,27 @@ def _route_line( each route has a length. Before, a row whose second line came and went with the evidence made the list one row taller when the highlight moved. """ + line = _route_path_line( + node_label, + name_key, + hops_out, + resolve=resolve, + node_known=node_known, + hash_bytes=hash_bytes, + ) + return line.text(), _route_context(hops_out, tag, weakest, samples) + + +def _route_path_line( + node_label: str, + name_key: str, + hops_out: tuple[str, ...], + *, + resolve, # noqa: ANN001 - NodeResolver, with no strict type, like the graph callbacks + node_known: bool, + hash_bytes: int, +) -> PathLine: + """The path line of one route, from the contact to our node (refer to :func:`_route_line`).""" hash_bytes = max(hash_bytes, 1) # an unknown mode still must have a real width to slice def hop_of(hop: str) -> PathHop: @@ -2528,7 +2582,7 @@ def _route_line( return PathHop(named, key=hop) return PathHop(_hop_hash(hop, hop, hash_bytes)) # unknown: its hash, in the grey - path = PathLine( + return PathLine( [ PathHop(node_label, key=name_key) if node_known and name_key @@ -2536,8 +2590,13 @@ def _route_line( *(hop_of(hop) for hop in reversed(hops_out)), PathHop(SELF_GLYPH, you=True), ] - ).text() + ) + +def _route_context( + hops_out: tuple[str, ...], tag: str, weakest: float | None, samples: int +) -> Text: + """The line of context under one route (refer to :func:`_route_line`).""" atoms: list[Text] = [hops_atom(len(hops_out))] if weakest is not None: snr = Text("weakest ", style="muted") @@ -2554,7 +2613,7 @@ def _route_line( if i: context.append(" · ", style="muted") context.append_text(atom) - return path, context + return context def _cluster_presentation(members: tuple[str, ...], type_of) -> _Cluster: # noqa: ANN001 @@ -2711,19 +2770,23 @@ 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 "" - path, context = _route_line( + line = _route_path_line( node_label, name_key, hops_out, - tag, - weakest, - samples, resolve=resolve, node_known=node_known, - self_name=self_name, hash_bytes=hash_bytes, ) - routes.append(_Route(draw=tuple(reversed(hops_out)), spec=spec, path=path, context=context)) + routes.append( + _Route( + draw=tuple(reversed(hops_out)), + spec=spec, + path=line.text(), + context=_route_context(hops_out, tag, weakest, samples), + line=line, + ) + ) # The legend explains the marks of the relays with a known type. Thus the real types of # the members decide it, before the contraction folds the members of a dense cluster @@ -2777,6 +2840,7 @@ def _routes_view( label_of=label_of, label_rgb_of=cluster_label_rgb_of, legend=legend, + find=node_of(resolve), ) diff --git a/meshterm/ui/packet_viewer.py b/meshterm/ui/packet_viewer.py index c1ed09b..5f26e50 100644 --- a/meshterm/ui/packet_viewer.py +++ b/meshterm/ui/packet_viewer.py @@ -66,6 +66,8 @@ from .marks import SELF_MARK, UNKNOWN_MARK from .menus import SEP_COMPACT, SEP_ROOMY from .pathgraph import PathLayer, render_path_graph, revisited_hops from .pathline import PathHop, PathLine, hops_atom, path_line +from .placemode import ACTION as PLACES_ACTION +from .placemode import PlaceToggle, node_of, placed, placed_hops, places_of_session from .theme import glyph, name_style, snr_style from .trace_screen import snr_bar from .tui.render import render_lines, render_to_ansi @@ -430,6 +432,10 @@ class PacketViewer(Screen): grow_only = True + #: The hint sheds these atoms first (refer to :func:`~meshterm.ui.tui.frame.fit_hint`). + #: The user finds the paging keys without the hint, but nothing else shows ^N. + spare_hint_atoms = ("Home/End ends", "PgUp/PgDn scroll") + @property def picocalc_lyra_lane(self): """The shared pager over the body, with the jumps named for their destinations. @@ -445,10 +451,15 @@ class PacketViewer(Screen): pin also when the list holds one packet (as the ``Top`` chip of the feed does, on the screen under this dialog). When the dialog opens over a single packet of a snapshot, all four chips are dim at the same time. + + F1 is the place mode of the path lines (^N). It has a chip only while the shown + packet has a path line or a hop chip to change. """ from .tui.fkeys import FPair, default_lane lane = list(default_lane(nav=self.content_overflows)) + if self._places_available(): + lane[0] = FPair(self._places.chip, PLACES_ACTION) many = len(self._entries) > 1 or self._can_pin lane[3] = FPair( "Page ↓", "pagedown", "Oldest", "end", enabled=self.content_overflows, opp_enabled=many @@ -540,6 +551,8 @@ class PacketViewer(Screen): self._key_of = key_of self._scope_of: ScopeOf = scope_of or unnamed_scope self._message_scope = message_scope + #: ^N: the path line and the hop chips show the node names, or the places. + self._places = PlaceToggle() #: Whether the viewer is on the pin: the stop above the newest packet, which #: holds the top position instead of a packet. It means that ``_index == 0``. The #: pin is a mode on the newest entry, so all the code that reads the viewer (the @@ -578,9 +591,38 @@ class PacketViewer(Screen): atoms = [] if len(self._entries) > 1 or self._can_pin: atoms += ["PgUp/PgDn scroll", "Home/End ends"] + if self._places_available(): + atoms.append(self._places.hint) atoms.append("Esc close") self.footer_hint = " · ".join(atoms) + def _places_available(self) -> bool: + """Whether ^N acts: the shown packet has a path line or a named hop chip.""" + if not self._entries: + return False + entry = self._entries[self._index] + raw = entry.raw if isinstance(entry.raw, dict) else {} + if entry.kind == "packet" and any((entry.path or "").split(",")): + return True + if (entry.node or entry.name) and node_label(entry, self._resolve, self._self_name)[ + 1 + ] not in ( + "muted", + "you", + ): + return True + for end in (raw.get("dest_hash"), raw.get("src_key") or raw.get("src_hash")): + named = self._resolve(end) if end else "" + if named and named != end and named != self._self_name: + return True + return False + + def _place_hop(self, hop: PathHop) -> PathHop: + """The hop with its place for a label, while place mode is on.""" + if not self._places.on: + return hop + return placed_hops([hop], places_of_session(), node_of(self._resolve))[0] + @property def _can_pin(self) -> bool: """Whether this viewer has a stream to follow, which is what a ``source`` is. @@ -678,6 +720,10 @@ class PacketViewer(Screen): self.scroll_pages(-1) elif action in ("pagedown", "space"): self.scroll_pages(1) + elif action == PLACES_ACTION: + if self._places_available(): + self._places.flip() + self._update_footer() elif action in ("escape", "enter"): self.resolve(None) @@ -761,9 +807,9 @@ class PacketViewer(Screen): # moment before. The store caches the lookup, so a request at each paint costs a # dict hit. # The card is also a function of whether the frame is short, because a short - # frame removes the node-type legend. + # frame removes the node-type legend. It is also a function of place mode (^N). short = short_frame(self._scroll_viewport) - key = (id(entry), width, age_minute, self._entry_scope(entry), short) + key = (id(entry), width, age_minute, self._entry_scope(entry), short, self._places.on) cached = self._body_cache.get(key) if cached is not None: self._body_cache.move_to_end(key) @@ -852,7 +898,7 @@ class PacketViewer(Screen): # The node that sent the packet is the origin of its route. Thus it is a chip # that closes on the point, and the ``via`` row continues that route. hop = PathHop(label, you=True) if style == "you" else PathHop(label, key=entry.node) - who.append_text(hop_chip(hop, role=ORIGIN)) + who.append_text(hop_chip(self._place_hop(hop), role=ORIGIN)) if entry.node and label != entry.node: who.append(" ") who.append_text(highlighted_hash(entry.node, self._prefix_bytes)) @@ -997,7 +1043,7 @@ class PacketViewer(Screen): says that the route continues past the chip. A flat end claims that the first relay was the origin. """ - return path_line( + line = path_line( (entry.path or "").split(","), self._resolve, prefix_bytes=self._prefix_bytes, @@ -1006,6 +1052,9 @@ class PacketViewer(Screen): from_origin=False, to_destination=False, ) + if self._places.on: + line = placed(line, places_of_session(), node_of(self._resolve)) + return line @staticmethod def _empty_via(entry: PacketEntry) -> str: @@ -1212,7 +1261,7 @@ class PacketViewer(Screen): if known: ours = bool(self._self_name and named == self._self_name) hop = PathHop(named, you=True) if ours else PathHop(named, key=value) - text.append_text(hop_chip(hop, role=role)) + text.append_text(hop_chip(self._place_hop(hop), role=role)) text.append(" ") text.append_text(highlighted_hash(value, self._prefix_bytes or 1, known=known)) return text diff --git a/meshterm/ui/trace_screen.py b/meshterm/ui/trace_screen.py index 76fb4af..f318f47 100644 --- a/meshterm/ui/trace_screen.py +++ b/meshterm/ui/trace_screen.py @@ -127,6 +127,8 @@ from .pathline import ( hops_atom, path_line, ) +from .placemode import ACTION as PLACES_ACTION +from .placemode import PlaceToggle, node_of, placed, places_of_session from .theme import snr_style from .tui.render import crop_cells, render_lines, render_to_ansi from .tui.screen import Screen @@ -264,6 +266,12 @@ def _slid(line: Text, shift: int, width: int) -> Text: return out +def _is_hash(hop: PathHop) -> bool: + """Whether a hop shows its hash and no name: place mode keeps such a hop as it is.""" + key = (hop.key or "").lower().removeprefix("0x") + return hop.label.lower().removeprefix("0x") == key + + def _note(text: str, indent: int, *, style: str = "faint") -> Text: """The trailing note of a lane (a source, a stamp, a count), on its own hanging line.""" return Text(" " * indent + text, style=style) @@ -438,6 +446,25 @@ class TraceScreen(Screen): floating = False + #: The hint sheds this atom first when it is too wide (refer to + #: :func:`~meshterm.ui.tui.frame.fit_hint`). The user finds the paging keys without + #: the hint, but nothing else shows ^N. + spare_hint_atoms = ("PgUp/PgDn scroll",) + + @property + def picocalc_lyra_lane(self): + """The shared lane, with the place mode of the route lines on F1. + + F1 is the ^N chip. It has a chip only while a route line is on the page that has + a named hop (refer to :meth:`_places_available`). + """ + from .tui.fkeys import DEFAULT_LANE, FPair + + lane = list(DEFAULT_LANE) + if self._places_available(): + lane[0] = FPair(self._places.chip, PLACES_ACTION) + return lane + def __init__( self, target: str, @@ -590,6 +617,8 @@ class TraceScreen(Screen): #: the footer. self._hshift = 0 self._hop_pan = 0 + #: ^N: the route lines show the node names, or the places. + self._places = PlaceToggle() # --- state ----------------------------------------------------------------- @@ -602,7 +631,29 @@ class TraceScreen(Screen): return f"tracing {done}/{total}… · PgUp/PgDn scroll · Esc back" return "tracing… · PgUp/PgDn scroll · Esc back" slide = " · ←→ scroll" if self._hop_pan else "" - return f"↑↓ actions{slide} · Enter run · PgUp/PgDn scroll · Esc back" + places = f" · {self._places.hint}" if self._places_available() else "" + return f"↑↓ actions{slide} · Enter run · PgUp/PgDn scroll{places} · Esc back" + + def _places_available(self) -> bool: + """Whether ^N acts: the route lane shows a line with a named hop. + + The hop lines of the results come from the walked route. Thus the route lane, + which draws the same hops, decides it for both. + """ + current = next((t for t in reversed(self._traces) if t.success), None) + shown = self._shown_route(current) + if shown is None: + return False + return any( + hop.key and hop.label and not hop.you and not hop.gap and not _is_hash(hop) + for hop in shown[0].hops + ) + + def _placed(self, line: PathLine) -> PathLine: + """The path line with its places for the node names, while place mode is on.""" + if self._places.on: + return placed(line, places_of_session(), node_of(self._resolve)) + return line def start_trace(self) -> None: """Start a trace run in the background (does nothing while a run is in progress).""" @@ -776,6 +827,9 @@ class TraceScreen(Screen): self._pin_cursor = False step = _HSCROLL_STEP if action == "right" else -_HSCROLL_STEP self._hshift = max(0, min(self._hop_pan, self._hshift + step)) + elif action == PLACES_ACTION: + if self._places_available(): + self._places.flip() elif action == "enter": self._commit_action() elif action == "up": @@ -966,7 +1020,7 @@ class TraceScreen(Screen): it changes. A *running* trace does not use the cache at all, because its log row has the live spinner glyph. """ - key = (self._traces_rev, self._status, width, self._hshift) + key = (self._traces_rev, self._status, width, self._hshift, self._places.on) if not self._running and self._tail_memo is not None and self._tail_memo[0] == key: return self._tail_memo[1] lines: list[str] = [] @@ -983,7 +1037,10 @@ class TraceScreen(Screen): if not self._running: # The key is the shift at which the rows were drawn, which _hop_lines can # clamp. Thus the next paint finds it. - self._tail_memo = ((self._traces_rev, self._status, width, self._hshift), lines) + self._tail_memo = ( + (self._traces_rev, self._status, width, self._hshift, self._places.on), + lines, + ) return lines def cursor_line(self) -> int | None: @@ -1060,39 +1117,46 @@ class TraceScreen(Screen): continuations already have the indent of the lane. """ indent = len(_ROUTE_LANE) - if current is not None: - route = route_path( - current, - self._device_label, - self._resolve, - self._device_hash, - bare_self=True, - show_hash=False, - ) - return route.wrapped(width, indent=indent) - planned = self._planned_route() - if planned is not None: - 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: - route = route_path( - self._previous, - self._device_label, - self._resolve, - self._device_hash, - bare_self=True, - show_hash=False, - ) - lines = route.wrapped(width, indent=indent) - stamp = self._previous.timestamp.astimezone().strftime("%b %d %H:%M") - lines.append(_note(f"(previous · {stamp})", indent)) + shown = self._shown_route(current) + if shown is not None: + route, note = shown + lines = self._placed(route).wrapped(width, indent=indent) + if note: + lines.append(_note(note, 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")] + def _shown_route(self, current: TraceResult | None) -> tuple[PathLine, str] | None: + """The path line of the route lane, and the note under it (``""`` for none). + + The order is the order that :meth:`_route_value` explains: the live route, the + planned route, the previous route. The result is ``None`` when there is no route to + show. The line is not changed by place mode (refer to :meth:`_placed`). + """ + if current is not None: + return self._walked_route(current), "" + planned = self._planned_route() + if planned is not None: + auto = self._effective_spec()[1] and self._auto_source + return planned, f"(auto · {self._auto_source})" if auto else "" + if self._previous is not None: + stamp = self._previous.timestamp.astimezone().strftime("%b %d %H:%M") + return self._walked_route(self._previous), f"(previous · {stamp})" + return None + + def _walked_route(self, result: TraceResult) -> PathLine: + """The route that a trace walked, with bare ends and no hashes after the names.""" + return route_path( + result, + self._device_label, + self._resolve, + self._device_hash, + bare_self=True, + show_hash=False, + ) + def _effective_spec(self) -> tuple[str, bool]: """The wire spec that the next Trace walks, and whether automatic resolution gave it. @@ -1361,15 +1425,17 @@ class TraceScreen(Screen): None if not node or node == self._device_label else node for node in (agg.origin, agg.destination) ] - return path_line( - ends, - self._resolve, - prefix_bytes=hash_bytes or 8, - self_name=self._device_label, - hash_bytes=hash_bytes, - bare_self=True, - from_origin=from_origin, - to_destination=to_destination, + return self._placed( + path_line( + ends, + self._resolve, + prefix_bytes=hash_bytes or 8, + self_name=self._device_label, + hash_bytes=hash_bytes, + bare_self=True, + from_origin=from_origin, + to_destination=to_destination, + ) ).text() def _trace_log(self) -> RenderableType: diff --git a/tests/test_place_mode_screens.py b/tests/test_place_mode_screens.py new file mode 100644 index 0000000..28f8459 --- /dev/null +++ b/tests/test_place_mode_screens.py @@ -0,0 +1,244 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Place mode (^N) on the path screens: Node detail, the packet viewer, the live feed, and Trace. + +Each screen opens with node names. ^N changes its path lines to the places of the nodes +(refer to :mod:`meshterm.ui.placemode`), and the hint and the lane chip say what the key +does now. The place service of the session is replaced by a small fake in each test. +""" + +from __future__ import annotations + +import pytest +from rich.text import Text + +from meshterm.core.events import MeshEvent +from meshterm.core.models import Hop, Observation, TraceResult, utcnow +from meshterm.core.places import Place +from meshterm.ui import placemode +from meshterm.ui.livefeed_screen import LiveFeedScreen +from meshterm.ui.node_detail_screen import ( + NodeDetailScreen, + _Route, + _RoutesView, + _Tab, +) +from meshterm.ui.packet_viewer import PacketEntry, PacketViewer +from meshterm.ui.pathline import PathHop, PathLine +from meshterm.ui.trace_screen import TraceScreen +from tests.conftest import plain as _plain + +#: The node that has a place in these tests (12 hex digits, the id of a node). +_HUB = "3d63c6429436" + + +class _Places: + """A fake place service: the hub is in Villeray, and no other node has a place.""" + + def get(self, node: str | None) -> Place | None: + return Place("Villeray", None, "tiles") if node == _HUB else None + + +@pytest.fixture +def places(monkeypatch: pytest.MonkeyPatch) -> _Places: + """Make the fake service the place service of the session.""" + service = _Places() + monkeypatch.setattr("meshterm.services.places._CURRENT", service) + return service + + +def _lane_places(screen) -> list: # noqa: ANN001 + """The slots of the lane that ^N drives.""" + return [pair for pair in screen.picocalc_lyra_lane if pair and pair.action == placemode.ACTION] + + +# -- Node detail ------------------------------------------------------------------- + + +def _detail(with_line: bool = True) -> NodeDetailScreen: + line = PathLine([PathHop("Hub", key=_HUB), PathHop("★", you=True)]) + route = _Route( + draw=(_HUB,), + spec="3d,f2", + path=line.text(), + context=Text("1 hop"), + line=line if with_line else None, + ) + routes = _RoutesView( + routes=[route], + glyph_of=lambda n: ("●", "#ffffff"), + label_of=lambda n: n[:2], + label_rgb_of=lambda n: (200, 200, 200), + ) + screen = NodeDetailScreen( + title="Node — Hub", + header=Text("Hub"), + info_rows=[("heard", Text("5m ago"))], + tabs=[_Tab("Info", "info"), _Tab("Routes", "routes")], + routes=routes, + ) + screen.note_viewport(30) + return screen + + +def test_node_detail_places_act_only_on_the_routes_tab(places: _Places) -> None: + """^N shows on the Routes tab only, and it changes the route row (not the header).""" + screen = _detail() + assert "^N" not in screen.footer_hint # the Info tab has no path line + assert not _lane_places(screen) + screen.handle(placemode.ACTION) + assert not screen._places.on # the key does nothing there + + screen.handle("tab") + assert "^N places" in screen.footer_hint + assert [p.label for p in _lane_places(screen)] == ["Places"] + assert "❯ Hub" in _plain(screen.render_body(72)) + + screen.handle(placemode.ACTION) + body = _plain(screen.render_body(72)) + assert "❯ Villeray" in body and "❯ Hub" not in body + assert "^N names" in screen.footer_hint + assert [p.label for p in _lane_places(screen)] == ["Names"] + + screen.handle(placemode.ACTION) + assert "❯ Hub" in _plain(screen.render_body(72)) + + +def test_node_detail_without_a_path_line_hides_the_key() -> None: + """A route with no path line to change gives no hint and no chip.""" + screen = _detail(with_line=False) + screen.handle("tab") + assert "^N" not in screen.footer_hint and not _lane_places(screen) + + +# -- the packet viewer ----------------------------------------------------------------- + + +def _resolver(names: dict[str, str]): # noqa: ANN202 + """A node resolver that also tells the node of a hash, as ``make_node_resolver`` does.""" + + def resolve(hop: str) -> str: + return names.get(hop, "") + + resolve.node_of = lambda hop: _HUB if hop in names else None # type: ignore[attr-defined] + return resolve + + +def _row(body: str, label: str) -> str: + """The line of a card that starts with ``label``.""" + return next(line for line in body.splitlines() if line.startswith(label)) + + +def test_packet_viewer_places_change_the_via_chain_and_the_sender(places: _Places) -> None: + """The ``from`` chip and the ``via`` line change. The route graph keeps its labels.""" + entry = PacketEntry(when=utcnow(), kind="packet", node=_HUB, path=_HUB, raw={}) + viewer = PacketViewer([entry], 0, resolve=_resolver({_HUB: "Hub"})) + assert "^N places" in viewer.footer_hint + assert viewer.footer_hint.endswith("Esc close") + assert [p.label for p in _lane_places(viewer)] == ["Places"] + body = _plain(viewer.render_body(80)) + assert "Hub" in _row(body, "from") and "Hub" in _row(body, "via") + + viewer.handle(placemode.ACTION) + body = _plain(viewer.render_body(80)) + assert "Villeray" in _row(body, "from") and "Villeray" in _row(body, "via") + assert "Hub" not in _row(body, "from") + _row(body, "via") + assert "^N names" in viewer.footer_hint + assert [p.label for p in _lane_places(viewer)] == ["Names"] + + +def test_packet_viewer_hides_the_key_when_no_hop_is_drawn() -> None: + """An ack has no path line and no hop chip, so ^N has no hint, no chip, and no effect.""" + entry = PacketEntry(when=utcnow(), kind="ack", where="abcd") + viewer = PacketViewer([entry], 0, resolve=lambda h: "") + assert "^N" not in viewer.footer_hint and not _lane_places(viewer) + viewer.handle(placemode.ACTION) + assert not viewer._places.on + + +# -- the live feed ----------------------------------------------------------------------- + + +class _FeedSession: + def invalidate(self) -> None: + pass + + +def test_livefeed_places_change_the_route_chips(places: _Places) -> None: + """The two endpoints of an addressed packet change with ^N. An empty feed has no key.""" + resolve = _resolver({_HUB: "Hub", "a1": "Alice"}) + screen = LiveFeedScreen(session=_FeedSession(), resolve=resolve, seed=[]) + screen.note_viewport(48) + assert "^N" not in screen.footer_hint and not _lane_places(screen) # no row yet + + raw = {"payload_typename": "TEXT_MSG", "dest_hash": _HUB, "src_hash": "a1"} + obs = Observation( + node="", name="", kind="packet", snr=5.0, rssi=-90.0, observed_at=utcnow(), raw=raw + ) + screen.on_event(MeshEvent.observation_event(obs)) + assert "^N places" in screen.footer_hint + assert [p.label for p in _lane_places(screen)] == ["Places"] + body = _plain(screen.render_body(100)) + assert "Hub" in body + + screen.handle(placemode.ACTION) + body = _plain(screen.render_body(100)) + assert "Villeray" in body and "Hub" not in body + assert "^N names" in screen.footer_hint + assert [p.label for p in _lane_places(screen)] == ["Names"] + + +# -- Trace ------------------------------------------------------------------------------- + + +class _TraceSession: + def invalidate(self) -> None: + pass + + +def _trace_screen(auto_spec: str) -> TraceScreen: + async def flow(current): # noqa: ANN001, ANN202 + return current + + async def trace(path_spec, on_trace): # noqa: ANN001, ANN202 + on_trace(TraceResult(target="Hub", success=True, hops=[Hop(index=0, node=_HUB, snr=5.0)])) + + screen = TraceScreen( + "Hub", + device_label="Us", + device_hash="aabb" + "00" * 30, + resolve=_resolver({_HUB: "Hub"}), + session=_TraceSession(), + trace=trace, + compose_path=flow, + explore=flow, + pick_width=flow, + pick_samples=flow, + width_bytes=lambda: 6, + sample_count=lambda: 1, + pace_s=0.0, + auto_spec=lambda: auto_spec, + ) + screen.note_viewport(40) + return screen + + +def test_trace_places_change_the_route_lane(places: _Places) -> None: + """The planned route changes with ^N, and the hint and the chip say what the key does.""" + screen = _trace_screen(_HUB) + assert "^N places" in screen.footer_hint + assert [p.label for p in _lane_places(screen)] == ["Places"] + assert "Hub" in _plain(screen.render_body(100)) + + screen.handle(placemode.ACTION) + body = _plain(screen.render_body(100)) + assert "Villeray" in body + assert "^N names" in screen.footer_hint + assert [p.label for p in _lane_places(screen)] == ["Names"] + + +def test_trace_hides_the_key_when_there_is_no_route() -> None: + """With no route on the page, ^N has no hint, no chip, and no effect.""" + screen = _trace_screen("") + assert "^N" not in screen.footer_hint and not _lane_places(screen) + screen.handle(placemode.ACTION) + assert not screen._places.on