diff --git a/meshterm/tools/nodes.py b/meshterm/tools/nodes.py index 5b3a4d5..b45c5b9 100644 --- a/meshterm/tools/nodes.py +++ b/meshterm/tools/nodes.py @@ -15,7 +15,7 @@ class NodesTool(Tool): """List this node and its known contacts, each with its path-hash prefix.""" name = "nodes" - help = "List this node and known contacts (full keys, path-hash prefix highlighted)." + help = "List this node and known contacts (last heard, packets, type, path-hash prefix)." category = "Device" order = 12 @@ -29,7 +29,8 @@ class NodesTool(Tool): Returns: A :class:`ToolResult` summarizing the number of known contacts. """ - from ..ui.widgets import nodes_table + from ..ui.surface import TuiUi + from ..ui.widgets import NodesSort, nodes_table device = await ctx.device() info = await device.get_self_info() @@ -44,9 +45,22 @@ class NodesTool(Tool): mode = None prefix_bytes = (mode + 1) if isinstance(mode, int) and 0 <= mode <= 3 else 0 + # Overheard-packet tallies from background monitoring, keyed by node hash; a + # contact we've never passively overheard simply has no entry. + counts = {n.node: n.count for n in ctx.repo.heard_nodes() if n.node} + self_name = str(info.get("name") or "this node") self_key = str(info.get("public_key") or "") - ctx.ui.show(nodes_table(self_name, self_key, contacts, prefix_bytes)) + sort = NodesSort.from_name(str(params.get("sort") or "name")) + + # In the menu, hand the list to the interactive screen so the arrows re-sort it live; + # on the scripted CLI, render the table once in the requested order. + if isinstance(ctx.ui, TuiUi): + from ..ui.nodes_screen import open_nodes + + await open_nodes(ctx, self_name, self_key, contacts, prefix_bytes, counts, sort) + else: + ctx.ui.show(nodes_table(self_name, self_key, contacts, prefix_bytes, counts, sort)) return ToolResult(summary={"contacts": len(contacts)}) @@ -59,5 +73,9 @@ class NodesTool(Tool): from ..cli import run_tool_command @app.command(name=self.name, help=self.help) - def _nodes() -> None: - run_tool_command(self, {}) + def _nodes( + sort: str = typer.Option( + "name", "--sort", "-s", help="Order contacts by: name, heard, packets." + ), + ) -> None: + run_tool_command(self, {"sort": sort}) diff --git a/meshterm/ui/map_render.py b/meshterm/ui/map_render.py index ab70e48..cee3dca 100644 --- a/meshterm/ui/map_render.py +++ b/meshterm/ui/map_render.py @@ -50,9 +50,13 @@ class MapMarker: return 2 if self.is_self else (1 if self.is_repeater else 0) -_SELF = ("★", "#ffffff") -_REPEATER = ("▲", "#ff5d73") -_NODE = ("●", "#22d3ee") +# Marker palette, shared across the whole app. The basemap is blue (water), green (parks) and +# warm amber (roads), so markers use the hues a map never contains — pink/violet — to stand +# out against it. Ordinary nodes are the loudest (bright pink); repeaters recede a step (a +# calmer violet); our own node stays the fixed yellow star. +_SELF = ("★", "#facc15") +_REPEATER = ("▲", "#a78bfa") +_NODE = ("●", "#f472b6") # -- basemap styling ---------------------------------------------------------- diff --git a/meshterm/ui/nodes_screen.py b/meshterm/ui/nodes_screen.py new file mode 100644 index 0000000..fe53481 --- /dev/null +++ b/meshterm/ui/nodes_screen.py @@ -0,0 +1,120 @@ +"""The interactive nodes list: the node table with arrow-key sorting. + +This wraps :func:`~meshterm.ui.widgets.nodes_table` in a full-screen TUI layer whose sort the +user steers with the arrows — left/right pick the column, up/down set ascending/descending — +so the table re-renders in place. The one-shot CLI (``meshterm nodes --sort …``) renders the +same table statically; only the menu gets the live sorting. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from .tui.render import render_lines +from .tui.screen import Screen +from .widgets import NodesSort, nodes_table + +if TYPE_CHECKING: + from ..context import AppContext + from ..core.models import Contact + + +class NodesScreen(Screen): + """A full-screen, keyboard-sortable list of this node and its known contacts.""" + + floating = False + footer_hint = "←→ column · ↑ asc ↓ desc · PgUp/PgDn scroll · Esc back" + + def __init__( + self, + self_name: str, + self_key: str, + contacts: list[Contact], + prefix_bytes: int, + counts: dict[str, int], + sort: NodesSort, + ) -> None: + """Create the nodes screen over already-fetched contact data. + + Args: + self_name: This node's advertised name. + self_key: This node's full public key (hex). + contacts: Known contacts to list under our own node. + prefix_bytes: Path-hash width in bytes to highlight in every key. + counts: Overheard-packet counts keyed by lowercased 12-hex node id. + sort: The initial sort; mutated in place as the user presses the arrows. + """ + super().__init__() + self.title = "nodes" + self._self_name = self_name + self._self_key = self_key + self._contacts = contacts + self._prefix_bytes = prefix_bytes + self._counts = counts + self._sort = sort + + def render_body(self, width: int) -> list[str]: + """Render the table+legend at the current sort and remember its line count.""" + table = nodes_table( + self._self_name, + self._self_key, + self._contacts, + self._prefix_bytes, + self._counts, + self._sort, + ) + lines = render_lines(table, width) + self._scroll_total = max(1, len(lines)) + return lines + + def handle(self, action: str, data: str = "") -> None: + """Re-sort with the arrows, scroll with PageUp/PageDown/Home/End, or dismiss.""" + if action == "left": + self._sort.move(-1) + elif action == "right": + self._sort.move(1) + elif action == "up": + self._sort.ascending = True + elif action == "down": + self._sort.ascending = False + elif action == "pageup": + self.scroll_pages(-1) + elif action in ("pagedown", "space"): + self.scroll_pages(1) + elif action in ("home", "ctrl_home"): + self.scroll_to_top() + elif action in ("end", "ctrl_end"): + self.scroll_to_bottom() + elif action in ("escape", "enter"): + self.resolve(None) + + +async def open_nodes( + ctx: AppContext, + self_name: str, + self_key: str, + contacts: list[Contact], + prefix_bytes: int, + counts: dict[str, int], + sort: NodesSort, +) -> None: + """Open the interactive, arrow-sortable nodes list and run until dismissed. + + Args: + ctx: Shared application context (must be in the interactive menu). + self_name: This node's advertised name. + self_key: This node's full public key (hex). + contacts: Known contacts to list under our own node. + prefix_bytes: Path-hash width in bytes to highlight in every key. + counts: Overheard-packet counts keyed by lowercased 12-hex node id. + sort: The initial sort (column + direction). + + Raises: + RuntimeError: If called outside the interactive menu (no full-screen session). + """ + from .surface import TuiUi + + if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller + raise RuntimeError("the interactive nodes list is only available in the menu") + screen = NodesScreen(self_name, self_key, contacts, prefix_bytes, counts, sort) + await ctx.ui.session.run_screen(screen) diff --git a/meshterm/ui/widgets.py b/meshterm/ui/widgets.py index 88d5958..6aeb17d 100644 --- a/meshterm/ui/widgets.py +++ b/meshterm/ui/widgets.py @@ -2,8 +2,12 @@ from __future__ import annotations +import math +from dataclasses import dataclass +from datetime import datetime from typing import TYPE_CHECKING, Callable, Optional +from rich import box from rich.console import Console, Group from rich.panel import Panel from rich.progress import ( @@ -21,12 +25,19 @@ from .. import __version__ from ..core.channels import is_name_derived, is_public_channel, is_public_name from ..core.models import ( LOCAL_DEVICE_LABEL, + NODE_TYPE_CHAT, + NODE_TYPE_LABELS, + NODE_TYPE_REPEATER, + NODE_TYPE_ROOM, + NODE_TYPE_SENSOR, Contact, HopAggregate, TraceResult, TraceStats, TxOptResult, + utcnow, ) +from .map_render import _NODE, _REPEATER, _SELF from .theme import snr_style if TYPE_CHECKING: @@ -436,22 +447,178 @@ def stats_panel( return Panel(body, title="[accent]trace summary[/accent]", border_style="accent", expand=False) -def _contact_recency_key(contact: Contact) -> tuple: - """Sort key ordering contacts by last-heard time (newest first), then name. +# Node-type glyphs and their colours, consistent with the map's marker palette across the +# whole app (see ui.map_render): our own node is the yellow ``★``, plain nodes the loud pink +# ``●`` and repeaters the calmer violet ``▲``. The remaining types take map-safe hues that +# stay distinct from those — a white square for rooms (the house glyph read poorly) and an +# orange ringed dot for sensors. All are single-width BMP glyphs so columns stay aligned. +_ROOM_COLOR = "#ffffff" +_SENSOR_COLOR = "#fb923c" +_NODE_GLYPHS: dict[int, tuple[str, str]] = { + NODE_TYPE_REPEATER: (_REPEATER[0], _REPEATER[1]), + NODE_TYPE_ROOM: ("■", _ROOM_COLOR), + NODE_TYPE_SENSOR: ("◉", _SENSOR_COLOR), + NODE_TYPE_CHAT: (_NODE[0], _NODE[1]), +} +_DEFAULT_GLYPH: tuple[str, str] = (_NODE[0], _NODE[1]) - Contacts with a known ``last_seen`` sort first, most-recent advert at the top; those - never heard sort after them, alphabetically. The leading ``0``/``1`` keeps the two - groups apart so their differently-typed tie-breakers never compare. +# A heat-map gradient for a contact's name, hottest (most recently heard) to coldest: white +# → yellow → orange → red → grey. Each stop pairs an age anchor (log10 of seconds since heard) +# with an RGB colour; :func:`_recency_style` interpolates continuously between them, so the +# colour glides with recency rather than snapping between a handful of discrete shades. +_HEAT_STOPS: tuple[tuple[float, tuple[int, int, int]], ...] = ( + (math.log10(300), (255, 255, 255)), # ≤5m — white (fresh) + (math.log10(3600), (250, 204, 21)), # ~1h — yellow + (math.log10(21600), (251, 146, 60)), # ~6h — orange + (math.log10(86400), (248, 113, 113)), # ~1d — red + (math.log10(604800), (148, 163, 184)), # ~1w — grey + (math.log10(2592000), (100, 116, 139)), # ~30d+ — cold slate +) +_RECENCY_NEVER = "#64748b" # never heard — the coldest slate - Args: - contact: The contact to rank. - Returns: - A tuple usable as a ``sorted`` key. +def _age_seconds(when: Optional[datetime]) -> Optional[float]: + """Seconds since ``when`` (aware UTC), or ``None`` when unknown/naive.""" + if when is None or getattr(when, "tzinfo", None) is None: + return None + return max(0.0, (utcnow() - when).total_seconds()) + + +def _format_age(secs: Optional[float]) -> str: + """A compact relative age — ``now``, ``5m``, ``3h``, ``2d``, ``4w`` — or ``never``.""" + if secs is None: + return "never" + if secs < 60: + return "now" + if secs < 3600: + return f"{int(secs // 60)}m" + if secs < 86400: + return f"{int(secs // 3600)}h" + if secs < 604800: + return f"{int(secs // 86400)}d" + return f"{int(secs // 604800)}w" + + +def _recency_style(secs: Optional[float]) -> str: + """The heat-map name colour for a contact last heard ``secs`` ago (hotter = more recent). + + Interpolates the RGB channels between the two :data:`_HEAT_STOPS` bracketing ``secs`` (in + log-age space), clamping to white below the first stop and cold slate above the last. """ - if contact.last_seen is not None: - return (0, -contact.last_seen.timestamp()) - return (1, contact.name.casefold()) + if secs is None: + return _RECENCY_NEVER + x = math.log10(max(secs, 0.0) + 1.0) + if x <= _HEAT_STOPS[0][0]: + r, g, b = _HEAT_STOPS[0][1] + elif x >= _HEAT_STOPS[-1][0]: + r, g, b = _HEAT_STOPS[-1][1] + else: + (x0, c0), (x1, c1) = next( + (lo, hi) for lo, hi in zip(_HEAT_STOPS, _HEAT_STOPS[1:]) if lo[0] <= x <= hi[0] + ) + f = (x - x0) / (x1 - x0) + r, g, b = (round(a + (bb - a) * f) for a, bb in zip(c0, c1)) + return f"#{r:02x}{g:02x}{b:02x}" + + +def _key_id(value: str) -> str: + """Normalise a key/prefix to the lowercased 12-hex id used to match heard nodes.""" + return value.lower().removeprefix("0x")[:12] + + +def _contact_pkts(contact: Contact, counts: dict[str, int]) -> Optional[int]: + """The overheard-packet tally for ``contact``, or ``None`` if never overheard.""" + ident = contact.public_key or contact.key_prefix + return counts.get(_key_id(ident)) if ident else None + + +# The columns the node list can be sorted by, left-to-right, and the direction each opens on +# — name A→Z, most-recently-heard first, most packets first — chosen so a fresh sort shows +# the "interesting" end at the top. +_SORT_COLUMNS: tuple[str, ...] = ("name", "heard", "packets") +_SORT_OPENS_ASCENDING: dict[str, bool] = {"name": True, "heard": True, "packets": False} + + +@dataclass +class NodesSort: + """Which column the node list is sorted by, and in which direction. + + ``column`` is one of :data:`_SORT_COLUMNS`; ``ascending`` sorts the column's underlying + metric low-to-high — name A→Z, *age* (so ascending = most recently heard first), packet + count low-to-high. The interactive screen mutates this in place as the user presses the + arrows. + """ + + column: str = "name" + ascending: bool = True + + @classmethod + def from_name(cls, name: str) -> "NodesSort": + """Build a sort for ``name``, opening in that column's natural direction.""" + column = name if name in _SORT_COLUMNS else "name" + return cls(column, _SORT_OPENS_ASCENDING[column]) + + def move(self, delta: int) -> None: + """Step the active column ``delta`` places (wrapping), adopting its natural direction.""" + index = (_SORT_COLUMNS.index(self.column) + delta) % len(_SORT_COLUMNS) + self.column = _SORT_COLUMNS[index] + self.ascending = _SORT_OPENS_ASCENDING[self.column] + + +def _ordered_contacts( + contacts: list[Contact], counts: dict[str, int], sort: NodesSort +) -> list[Contact]: + """Contacts sorted per ``sort`` (our own node is pinned separately, above these). + + Sorts ascending by the active column's metric with a case-folded name tiebreak, then + reverses for a descending sort. Never-heard / never-overheard rows carry an extreme + metric so they gather at the ascending end. + """ + if sort.column == "heard": + def metric(c: Contact) -> float: + secs = _age_seconds(c.last_seen) + return secs if secs is not None else float("inf") + elif sort.column == "packets": + def metric(c: Contact) -> float: + return _contact_pkts(c, counts) or 0 + else: + def metric(c: Contact) -> object: + return c.name.casefold() + + ordered = sorted(contacts, key=lambda c: (metric(c), c.name.casefold())) + if not sort.ascending: + ordered.reverse() + return ordered + + +def _sort_header(label: str, column: str, sort: NodesSort) -> str: + """A column header: plain-muted, or cyan with a direction triangle when it's the sort key. + + The active column's name and its triangle are lit cyan together (so the interactive + left/right selection is obvious) — ``▲`` for ascending, ``▼`` for descending. The column + reserves its width (see :func:`nodes_table`) so toggling the sort doesn't shift the row. + """ + if column != sort.column: + return label + triangle = "▲" if sort.ascending else "▼" + return f"[bold #22d3ee]{label} {triangle}[/]" + + +def _nodes_legend(contacts: list[Contact]) -> Text: + """A one-line glyph legend covering the node types actually present (plus us).""" + present = {c.node_type for c in contacts} + if any(t not in _NODE_GLYPHS for t in present): + present.add(NODE_TYPE_CHAT) # unknown/None types render as a plain node + legend = Text(" ") # a small indent to sit under the table body + legend.append(_SELF[0], style=_SELF[1]) + legend.append(" you", style="muted") + for node_type in (NODE_TYPE_REPEATER, NODE_TYPE_CHAT, NODE_TYPE_ROOM, NODE_TYPE_SENSOR): + if node_type in present: + glyph, color = _NODE_GLYPHS[node_type] + legend.append(" ") + legend.append(glyph, style=color) + legend.append(f" {NODE_TYPE_LABELS[node_type]}", style="muted") + return legend def nodes_table( @@ -459,39 +626,78 @@ def nodes_table( self_key: str, contacts: list[Contact], prefix_bytes: int, -) -> Table: - """List this node and its known contacts, full keys with the path-hash prefix lit. + counts: dict[str, int], + sort: Optional[NodesSort] = None, +) -> Group: + """List this node and its known contacts with recency, packets, type, key, and legend. - Our own node is the first row, its name highlighted to set it apart. Every node's key - is shown in full with the leading ``prefix_bytes`` bytes — the slice a forced trace - path addresses at the current path-hash mode — highlighted. + Our own node is the first row (``★``, name in accent); contacts follow in ``sort`` order. + A per-type glyph marks each node in the app's shared colours, the name is coloured by how + recently it was last heard (brighter = fresher), and the full key is shown with its + path-hash prefix lit — chopped with an ellipsis only when the terminal is too narrow. Args: self_name: This node's advertised name. self_key: This node's full public key (hex); blank renders as ``?``. contacts: Known contacts, listed after our own node. prefix_bytes: Path-hash width in bytes to highlight in every key. + counts: Overheard-packet counts keyed by lowercased 12-hex node id (from + monitoring); a contact with no entry shows ``—``. + sort: The active sort (column + direction); defaults to name-ascending. The sorted + column's header is lit cyan with an up/down direction triangle. Returns: - A Rich :class:`Table` of name and full public key. + A Rich :class:`Group` of the frameless table and its glyph legend. """ - table = Table(title=f"Nodes ({len(contacts)} contacts)", border_style="muted") - table.add_column("Name") - table.add_column("Public key [muted](path-hash prefix highlighted)[/muted]") + sort = sort if sort is not None else NodesSort() + + # expand=True lets the key column (the only flexible one) soak up all spare width and be + # the sole column Rich squeezes when narrow — the fixed columns keep their natural size. + table = Table( + title=f"[accent]Nodes[/accent] [muted]· {len(contacts)} known[/muted]", + title_justify="left", + box=box.SIMPLE_HEAD, + show_edge=False, + pad_edge=False, + header_style="muted", + expand=True, + padding=(0, 2, 0, 0), + ) + # Each sortable header reserves two extra columns for its " ▲" direction marker (via + # min_width = label + 2) so the same width holds whether or not it's the active sort — + # switching the sort never widens a column and shifts the rest of the row. + table.add_column("", no_wrap=True) # node-type glyph + table.add_column(_sort_header("Name", "name", sort), no_wrap=True, min_width=6) + table.add_column( + _sort_header("Heard", "heard", sort), justify="right", no_wrap=True, min_width=7 + ) + table.add_column( + _sort_header("Pkts", "packets", sort), justify="right", no_wrap=True, min_width=6 + ) + # The full key, chopped to an ellipsis by Rich only when the row won't otherwise fit. + table.add_column("Key", no_wrap=True, overflow="ellipsis", ratio=1, min_width=10) unknown = Text("?", style="muted") table.add_row( - Text(f"{self_name} (this node)", style="accent"), # our node, name highlighted + Text(_SELF[0], style=_SELF[1]), + Text.assemble((self_name, "accent"), (" (you)", "muted")), + Text("—", style="muted"), + Text("—", style="muted"), highlighted_hash(self_key, prefix_bytes) if self_key else unknown, ) table.add_section() - # Most-recently-heard contacts first; those never heard fall to the end, alphabetically. - for c in sorted(contacts, key=_contact_recency_key): + for c in _ordered_contacts(contacts, counts, sort): + secs = _age_seconds(c.last_seen) + glyph, glyph_style = _NODE_GLYPHS.get(c.node_type, _DEFAULT_GLYPH) + pkts = _contact_pkts(c, counts) table.add_row( - Text(c.name, style="brand"), + Text(glyph, style=glyph_style), + Text(c.name, style=_recency_style(secs)), + Text(_format_age(secs), style="muted"), + Text(str(pkts), style="brand") if pkts else Text("—", style="muted"), highlighted_hash(c.public_key, prefix_bytes) if c.public_key else unknown, ) - return table + return Group(table, Text(""), _nodes_legend(contacts)) def tx_opt_table(result: TxOptResult) -> Table: diff --git a/tests/test_device_config.py b/tests/test_device_config.py index 3904e04..39c4554 100644 --- a/tests/test_device_config.py +++ b/tests/test_device_config.py @@ -82,20 +82,102 @@ def test_highlighted_hash_highlights_path_hash_prefix() -> None: assert text.plain[highlighted[0].start : highlighted[0].end] == "aabbcc" -def test_nodes_table_lists_us_first_with_full_keys() -> None: - """The nodes table puts our node first (name highlighted) with full keys.""" +def _nodes_names(counts, sort: str, prefix_bytes: int = 3): + """Render a nodes table for ``sort`` and return (table, name-column plain text).""" from meshterm.core.models import Contact - from meshterm.ui.widgets import nodes_table + from meshterm.ui.widgets import NodesSort, nodes_table - contacts = [Contact(name="Alice", public_key="3d63c6" + "00" * 29, key_prefix="3d63c6")] - table = nodes_table("Homestead", "aabbcc" + "00" * 29, contacts, prefix_bytes=3) - # Two body rows: our node, then Alice. - names = [cell.plain if hasattr(cell, "plain") else str(cell) for cell in table.columns[0].cells] + contacts = [ + Contact(name="Bob", public_key="9f1a2b" + "00" * 29, key_prefix="9f1a2b"), + Contact(name="Alice", public_key="3d63c6" + "00" * 29, key_prefix="3d63c6"), + ] + group = nodes_table( + "Homestead", "aabbcc" + "00" * 29, contacts, prefix_bytes, counts, NodesSort.from_name(sort) + ) + table = group.renderables[0] # (table, blank line, legend) + names = [c.plain if hasattr(c, "plain") else str(c) for c in table.columns[1].cells] + return table, names + + +def test_nodes_table_lists_us_first_with_full_keys() -> None: + """The nodes table pins our node first, sorts by name, and shows full highlighted keys.""" + counts = {"3d63c6000000": 14} # Alice was overheard; Bob wasn't + table, names = _nodes_names(counts, sort="name") + + # Column 1 is the name; us first, then contacts alphabetically (Alice before Bob). assert names[0].startswith("Homestead") - assert "Alice" in names[1] - keys = list(table.columns[1].cells) - assert keys[0].plain == "aabbcc" + "00" * 29 # full key, not a short prefix - assert any(s.style == "brand" for s in keys[0].spans) # prefix highlighted + assert names[1] == "Alice" + assert names[2] == "Bob" + + # Packet counts (column 3): Alice shows her tally, Bob shows the em dash. + pkts = [c.plain if hasattr(c, "plain") else str(c) for c in table.columns[3].cells] + assert pkts[1] == "14" + assert pkts[2] == "—" + + # Keys (column 4) are the full key with the path-hash prefix highlighted (no truncation + # in the model; Rich ellipsizes only at render time when the terminal is too narrow). + keys = list(table.columns[4].cells) + assert keys[1].plain == "3d63c6" + "00" * 29 + assert any(s.style == "brand" for s in keys[1].spans) # prefix highlighted + + +def test_nodes_table_sorts_by_heard_and_packets() -> None: + """Non-default sorts reorder contacts while keeping our node pinned first.""" + from datetime import timedelta + + from meshterm.core.models import Contact, utcnow + + # Bob was heard more recently than Alice, but Alice has more overheard packets. + contacts = [ + Contact( + name="Bob", + public_key="9f1a2b" + "00" * 29, + key_prefix="9f1a2b", + last_seen=utcnow() - timedelta(minutes=5), + ), + Contact( + name="Alice", + public_key="3d63c6" + "00" * 29, + key_prefix="3d63c6", + last_seen=utcnow() - timedelta(days=2), + ), + ] + counts = {"3d63c6000000": 14, "9f1a2b000000": 3} + from meshterm.ui.widgets import NodesSort, nodes_table + + def names(sort: NodesSort): + group = nodes_table("Us", "aabbcc" + "00" * 29, contacts, 3, counts, sort) + cells = group.renderables[0].columns[1].cells + return [c.plain if hasattr(c, "plain") else str(c) for c in cells] + + # Freshest first: Bob (5m) before Alice (2d) under the default (ascending-age) heard sort. + assert names(NodesSort.from_name("heard"))[1:] == ["Bob", "Alice"] + # Most packets first: Alice (14) before Bob (3) under the default (descending) packets sort. + assert names(NodesSort.from_name("packets"))[1:] == ["Alice", "Bob"] + # Descending flips it: oldest-heard first puts Alice (2d) above Bob (5m). + assert names(NodesSort(column="heard", ascending=False))[1:] == ["Alice", "Bob"] + + +def test_nodes_screen_arrows_steer_the_sort() -> None: + """Left/right walk the sort column (wrapping); up/down set ascending/descending.""" + from meshterm.ui.nodes_screen import NodesScreen + from meshterm.ui.widgets import NodesSort + + screen = NodesScreen("Us", "aabbcc" + "00" * 29, [], 3, {}, NodesSort()) + assert (screen._sort.column, screen._sort.ascending) == ("name", True) + + screen.handle("right") # name -> heard, opening in its natural (ascending) direction + assert (screen._sort.column, screen._sort.ascending) == ("heard", True) + screen.handle("right") # heard -> packets, which opens descending + assert (screen._sort.column, screen._sort.ascending) == ("packets", False) + screen.handle("up") # force ascending + assert screen._sort.ascending is True + screen.handle("down") # force descending + assert screen._sort.ascending is False + screen.handle("right") # packets -> wraps back to name + assert screen._sort.column == "name" + screen.handle("left") # name -> wraps to packets + assert screen._sort.column == "packets" def test_non_strict_enum_accepts_unlisted_value() -> None: