diff --git a/meshterm/core/contact_score.py b/meshterm/core/contact_score.py index 395a2a3..62fe36b 100644 --- a/meshterm/core/contact_score.py +++ b/meshterm/core/contact_score.py @@ -473,7 +473,8 @@ def _reasons( phrases.append((0.0, "never heard")) else: phrases.append((contribution["recency"], _age_phrase(signals.heard_age_days))) - phrases.append((contribution["volume"], f"{signals.packets} pkts")) + packets = signals.packets + phrases.append((contribution["volume"], f"{packets} pkt{'' if packets == 1 else 's'}")) if signals.hops is not None: hops = signals.hops label = "direct" if hops < 0.5 else f"{hops:g} hops" diff --git a/meshterm/tools/trace.py b/meshterm/tools/trace.py index cb21469..68865f5 100644 --- a/meshterm/tools/trace.py +++ b/meshterm/tools/trace.py @@ -195,6 +195,7 @@ class TraceTool(Tool): :meth:`_prompt_target`. """ from ..ui.contactlist import ( + TRACE_LANES, TRACE_SORT_COLUMNS, TRACE_SORT_OPENS_ASCENDING, ContactListScreen, @@ -219,7 +220,7 @@ class TraceTool(Tool): "traced", TRACE_SORT_COLUMNS, TRACE_SORT_OPENS_ASCENDING ), footer_hint="↑↓ move · ^←→↑↓ sort · type to filter · Enter select · Esc back", - show_traced=True, + lanes=TRACE_LANES, ) return picker, contacts diff --git a/meshterm/ui/archived_screen.py b/meshterm/ui/archived_screen.py new file mode 100644 index 0000000..1c23f36 --- /dev/null +++ b/meshterm/ui/archived_screen.py @@ -0,0 +1,163 @@ +"""The Archived contacts list: what the sweep took off the device, and when. + +A purge (see :mod:`~meshterm.ui.purge_screen`) removes a contact from the *device* — the +scarce resource — and keeps it here in full. This screen is where those contacts live: the +same sortable, filterable lane layout as the Contacts list, in its own lane set +(``NAME · ARCHIVED · KEY``, :data:`~meshterm.ui.contactlist.ARCHIVED_LANES`), with its own +sort ring over exactly those three columns. + +The ``ARCHIVED`` lane is drawn as ``HEARD`` is on the main list — a relative age under +recency heat — because it answers the same shape of question about a different event, and a +second grammar for "how long ago" would have been one for the reader to learn for nothing. +It opens sorted by it, freshest first: the question this screen answers is *what did that +sweep just take?*, and the answer belongs at the top. + +**It carries no actions.** Not a select list with the verbs removed — a list with nothing to +commit, which Esc leaves. Everything you might do to an archived contact belongs to that one +contact and lives on its Node detail page, which Enter opens: restoring it to the device, or +deleting it for good. Putting a restore verb on this screen as well would have been a second +route to the same write, and the page is where the reader can actually see which node they +are about to act on. +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from typing import TYPE_CHECKING, Optional + +from .contactlist import ( + ARCHIVED_LANES, + ARCHIVED_SORT_COLUMNS, + ARCHIVED_SORT_OPENS_ASCENDING, + ContactListScreen, + ContactRow, +) +from .tui.screen import CANCEL +from .widgets import ContactsSort + +if TYPE_CHECKING: + from ..context import AppContext + from ..core.contact_store import RememberedContact + +#: The list's footer: navigation, the sort, filtering, then Esc last. ``Enter open`` because +#: a row pushes the node's detail page — the same verb the Contacts list uses for the same +#: gesture. +_HINT = "↑↓ move · ^←→↑↓ sort · type to filter · Enter open · Esc back" + + +def _archived_time(stamp: Optional[int]) -> Optional[datetime]: + """A stored archive stamp as an aware UTC datetime, or ``None`` if it carries none. + + Stored as unix seconds (see :class:`~meshterm.core.contact_store.RememberedContact`) and + rendered as a local-time age by the lane, so it crosses into the list's own currency + here rather than in three places downstream. + """ + if not stamp: + return None + try: + return datetime.fromtimestamp(int(stamp), tz=timezone.utc) + except (OverflowError, OSError, ValueError): + return None # a corrupt stamp reads "never", not a crash + + +def archived_rows(archived: "list[RememberedContact]") -> list[ContactRow]: + """Turn remembered contacts into the shared list's row data. + + Args: + archived: The device's archived contacts, from + :meth:`~meshterm.core.contact_store.ContactStore.archived`. + + Returns: + One :class:`~meshterm.ui.contactlist.ContactRow` each, carrying the rebuilt + :class:`~meshterm.core.models.Contact` as its value so Enter hands the whole record + to the detail page with no re-lookup. + """ + return [ + ContactRow( + value=remembered.to_contact(), + name=remembered.name, + key=remembered.public_key, + node_type=remembered.node_type, + archived_at=_archived_time(remembered.archived_at), + ) + for remembered in archived + ] + + +class ArchivedScreen(ContactListScreen): + """A full-screen, sortable list of the contacts a sweep took off this device.""" + + def __init__(self, rows: list[ContactRow], prefix_bytes: int, sort: ContactsSort) -> None: + """Build the list over already-resolved rows. + + Args: + rows: The archived contacts' lane data (see :func:`archived_rows`). + prefix_bytes: Path-hash width in bytes to highlight in every key. + sort: The sort, mutated in place by the Ctrl+arrows. Its ring should span + :data:`~meshterm.ui.contactlist.ARCHIVED_SORT_COLUMNS`. + """ + super().__init__( + f"Archived contacts · {len(rows)} kept", + rows=rows, + prefix_bytes=prefix_bytes, + sort=sort, + prompt=( + "Off the device, kept here with their history. Open one to restore it." + ), + footer_hint=_HINT, + lanes=ARCHIVED_LANES, + ) + + +async def open_archived(ctx: "AppContext", self_key: str, prefix_bytes: int) -> bool: + """Open the archived list; Enter opens Node detail, Esc leaves. ``True`` if anything changed. + + The list stays pushed for the whole visit, so a detail page nests above it and Esc from + there lands back on the row it was opened from — same sort, same filter, same scroll. + A page that *restored* or *deleted* the contact it detailed ends the visit and the list + is rebuilt without the row, which is the same deliberate exception the Contacts list + makes: the row it was holding a place in no longer exists. + + Args: + ctx: Shared application context (interactive menu). + self_key: The device's own public key (hex) — how the store scopes this device's + remembered contacts. + prefix_bytes: Path-hash width in bytes to highlight in every key. + + Returns: + ``True`` if any contact was restored or deleted, so the caller's own contact list + knows to re-read. + """ + from .node_detail_screen import open_node_detail + from .surface import TuiUi + + assert isinstance(ctx.ui, TuiUi) # guaranteed by the Contacts screen + session = ctx.ui.session + store = ctx.contact_store + dev_pub = (self_key or "").lower().removeprefix("0x") + sort = ContactsSort.from_name( + "archived", ARCHIVED_SORT_COLUMNS, ARCHIVED_SORT_OPENS_ASCENDING + ) + changed = False + while True: + rows = archived_rows(store.archived(dev_pub) if store and dev_pub else []) + if not rows: + # Everything was restored or deleted while the reader was in here; there is no + # list left to show, and an empty screen they would have to Esc out of says + # less than the note does on the way back. + ctx.ui.note("[muted]no archived contacts[/muted]") + return changed + screen = ArchivedScreen(rows, prefix_bytes, sort) + rebuild = False + async with session.stay(screen) as visit: + while True: + chosen = await visit.result() + if chosen is CANCEL or chosen is None: # Esc + return changed + # The page manages the contact it details — restore it, or delete it for + # good — and says so on the way out, at which point this list is stale. + if await open_node_detail(ctx, chosen): + changed = rebuild = True + break + if not rebuild: + return changed diff --git a/meshterm/ui/contactlist.py b/meshterm/ui/contactlist.py index 0c53b23..960ba9f 100644 --- a/meshterm/ui/contactlist.py +++ b/meshterm/ui/contactlist.py @@ -1,14 +1,24 @@ """The shared contact list: one sortable, filterable lane layout for every screenful of contacts. Extracted from the Time Machine's subject picker so the app has exactly one way to draw "a -full-screen list of contacts": aligned ``NAME · HEARD · PKTS · KEY`` lanes under a sort-aware -column header, our own node pinned first, the sort riding the Ctrl+arrows (plain arrows keep -the highlight, letters keep type-to-filter), and the name lane sized to its content so the -columns anchor left while the key lane soaks up the rest of the terminal. The Contacts screen, -the Time Machine picker, and the courier recipient list all build on :class:`ContactListScreen`; -each hands its rows over as :class:`ContactRow` values — however it learned them (stored history -of *discovered* contacts, the device's *added* contact table) — so the lists render, sort, and -steer identically without sharing a data source. +full-screen list of contacts": aligned lanes under a sort-aware column header, our own node +pinned first, the sort riding the Ctrl+arrows (plain arrows keep the highlight, letters keep +type-to-filter), and the name lane sized to its content so the columns anchor left while the +key lane soaks up the rest of the terminal. The Contacts screen, the Time Machine picker, the +Archived list and the courier recipient list all build on :class:`ContactListScreen`; each +hands its rows over as :class:`ContactRow` values — however it learned them (stored history of +*discovered* contacts, the device's *added* contact table, the contacts a sweep archived) — so +the lists render, sort, and steer identically without sharing a data source. + +**Name and key are fixtures; everything between them is a lane set.** Every list opens on the +name and closes on the key — those two are what a contact *is*, and the flexing widths are +built around them — and declares the middle lanes it wants as a tuple of :class:`ContactLane` +(:data:`DEFAULT_LANES` for ``NAME · HEARD · PKTS · KEY``, :data:`TRACE_LANES` for the Trace +picker's extra ``TRACED``, :data:`ARCHIVED_LANES` for the Archived list's single ``ARCHIVED``). +A lane carries its own sort-ring id, header label, width, and how to read its value off a row, +so adding one is a declaration rather than a branch: the header, the row builder, the sort +metric and the lane-width arithmetic all read the same tuple. It replaces a ``show_traced`` +flag that had already made three of those four places say "and if it's the trace picker…". """ from __future__ import annotations @@ -52,16 +62,65 @@ _HASH_MIN = 8 _GAP = 3 _GAP_S = " " * _GAP -#: Everything in a row *besides* the name and key lanes, in cells: the select pointer (2), -#: the type glyph and its space (2), then the two gapped fixed lanes — heard (gap + 5) and -#: packets (gap + 5) — and the gap before the key. The name lane is content-sized and the -#: key lane takes the rest (see :meth:`ContactListScreen._lane_widths`). -_LEAD = 2 + 2 + (_GAP + 5) + (_GAP + 5) + _GAP +#: Everything in a row besides the name lane, the key lane, and the middle lanes: the select +#: pointer (2), the type glyph and its space (2), and the gap before the key. Each declared +#: :class:`ContactLane` adds its own gapped width on top (see +#: :meth:`ContactListScreen._lane_widths`); the name lane is content-sized and the key lane +#: takes whatever is left. +_LEAD = 2 + 2 + _GAP -#: The optional TRACED lane's width in cells: a lane gap plus a 6-wide age field (wide -#: enough for the ``TRACED`` header). Only the Trace-target picker shows it (``show_traced``), -#: inserted between the name lane and HEARD; every other contact list omits it (and its width). -_TRACED_LANE = _GAP + 6 + +@dataclass(frozen=True) +class ContactLane: + """One of the fixed lanes drawn between a row's name and its key. + + A lane is a *declaration*, not a branch: it names the sort-ring column it answers to, the + header label over it, its width in cells, and how to read its value off a + :class:`ContactRow`. The header builder, the row builder, the sort metric and the + lane-width arithmetic all read the same tuple, so a new lane is added in one place. + + Attributes: + column: The sort-ring id this lane sorts under (see :data:`SORT_COLUMNS`). + label: The header label. Never wider than :attr:`width`, or the header would + outrun the value lane under it and shift every column after it. + width: The lane's field width in cells; values are right-aligned into it. + field: The :class:`ContactRow` attribute holding the lane's value. + kind: ``"age"`` for a datetime drawn as a recency-heat-coloured relative age, or + ``"count"`` for an integer tally drawn muted (a faint ``—`` when ``None``). + """ + + column: str + label: str + width: int + field: str + kind: str = "age" + + +#: How long the node was last heard ago — the lane every list of *live* contacts carries. +HEARD_LANE = ContactLane("heard", "HEARD", 5, "last_seen") + +#: How many transmissions MeshTerm has overheard from the node. +PKTS_LANE = ContactLane("packets", "PKTS", 5, "count", kind="count") + +#: How long ago the node was last traced — the Trace-target picker's extra lane. +TRACED_LANE = ContactLane("traced", "TRACED", 6, "last_traced") + +#: How long ago the contact was archived off the device — the Archived list's only lane. +#: Drawn exactly as ``HEARD`` is, recency heat and all: it is the same question (how long +#: ago did this happen) about a different event, and giving it its own visual language would +#: have been a second grammar for the reader to learn for no gain. +ARCHIVED_LANE = ContactLane("archived", "ARCHIVED", 8, "archived_at") + +#: The ordinary contact list's middle lanes: ``NAME · HEARD · PKTS · KEY``. +DEFAULT_LANES: tuple[ContactLane, ...] = (HEARD_LANE, PKTS_LANE) + +#: The Trace-target picker's, which inserts ``TRACED`` ahead of the usual two. +TRACE_LANES: tuple[ContactLane, ...] = (TRACED_LANE, HEARD_LANE, PKTS_LANE) + +#: The Archived list's: ``NAME · ARCHIVED · KEY``. No ``HEARD`` and no ``PKTS`` — an archived +#: contact is off the device, so what it is still doing on the air is not what this screen is +#: about; when it left is. +ARCHIVED_LANES: tuple[ContactLane, ...] = (ARCHIVED_LANE,) #: The muted ``(you)`` tag on the own-node lane (see :func:`_lane`), its width folded into #: the name lane's content sizing so the tag never truncates. @@ -79,14 +138,26 @@ SORT_OPENS_ASCENDING: dict[str, bool] = { } #: The Trace-target picker's wider sort ring. It adds a ``traced`` column — how long ago the -#: node was last traced — between name and heard, and opens on it *descending*: the -#: most-recently-traced node on top, never-traced gathered at the bottom (a trace time is the -#: metric, so descending is newest-first — see :func:`_ordered`). The picker builds its -#: :class:`~meshterm.ui.widgets.ContactsSort` over these, so the Ctrl+arrows walk all five -#: columns; a list without the ``traced`` lane keeps to :data:`SORT_COLUMNS`. +#: node was last traced — between name and heard, and opens on it *ascending*, which is what +#: every age lane's natural open is: the metric is an **age**, so ascending is freshest-first +#: and never-traced rows carry ``+inf`` and gather at the bottom under either direction (see +#: :func:`_ordered`). It read ``False`` while ``traced`` alone sorted on a raw timestamp; the +#: lane spec made that special case unnecessary, and one age column now sorts like the rest. +#: The picker builds its :class:`~meshterm.ui.widgets.ContactsSort` over these, so the +#: Ctrl+arrows walk all five columns; a list without the ``traced`` lane keeps to +#: :data:`SORT_COLUMNS`. TRACE_SORT_COLUMNS: tuple[str, ...] = ("name", "traced", "heard", "packets", "hash") TRACE_SORT_OPENS_ASCENDING: dict[str, bool] = { - "name": True, "traced": False, "heard": True, "packets": False, "hash": True, + "name": True, "traced": True, "heard": True, "packets": False, "hash": True, +} + +#: The Archived list's ring — ``NAME · ARCHIVED · KEY``, matching :data:`ARCHIVED_LANES`. +#: ``archived`` opens *ascending* on the lane's age, so the most recently archived contacts +#: come first: the question this screen answers is "what did that sweep just take?", and the +#: answer should be at the top of it. +ARCHIVED_SORT_COLUMNS: tuple[str, ...] = ("name", "archived", "hash") +ARCHIVED_SORT_OPENS_ASCENDING: dict[str, bool] = { + "name": True, "archived": True, "hash": True, } #: What the active sort column and its triangle are lit in, matching the static Contacts @@ -119,10 +190,11 @@ class ContactRow: last_seen: When the contact was last heard (aware UTC) — fills the heard lane, coloured by recency heat; ``None`` reads ``never`` in the cold style. count: The packet tally; ``None`` renders a faint ``—`` (never overheard). - last_traced: When this node was last traced (aware UTC) — fills the optional - ``TRACED`` lane (only shown when the list is built with ``show_traced``), - coloured by recency heat; ``None`` reads ``never``. Ignored by lists that don't - show the lane. + last_traced: When this node was last traced (aware UTC) — fills the ``TRACED`` lane + (:data:`TRACE_LANES`), coloured by recency heat; ``None`` reads ``never``. + Ignored by lists that don't declare the lane. + archived_at: When this contact was archived off the device (aware UTC) — fills the + ``ARCHIVED`` lane (:data:`ARCHIVED_LANES`). Ignored by lists without it. you: Whether this is our own node: the ``★`` marker, the pure-white ``you`` name style with a muted ``(you)`` tag, faint ``—`` heard/packet lanes (we never overhear ourselves), pinned above the sorted block whatever the sort. @@ -135,20 +207,23 @@ class ContactRow: last_seen: Optional[datetime] = None count: Optional[int] = None last_traced: Optional[datetime] = None + archived_at: Optional[datetime] = None you: bool = False -def _header(name_w: int, sort: ContactsSort, show_traced: bool = False) -> Text: +def _header( + name_w: int, sort: ContactsSort, lanes: "tuple[ContactLane, ...]" = DEFAULT_LANES +) -> Text: """Column labels over the contact lanes (see :func:`_lane`). - The lanes read ``NAME · HEARD · PKTS · KEY`` — or ``NAME · TRACED · HEARD · PKTS · KEY`` - when ``show_traced`` inserts the Trace picker's extra lane — matching the row builder. - The four leading spaces cover the select screen's pointer column (2 cells) plus the - one-cell type glyph and its gap, so each label lands over its lane. + The lanes read ``NAME``, then each declared :class:`ContactLane` in order, then ``KEY`` + — matching the row builder, which walks the same tuple. The four leading spaces cover + the select screen's pointer column (2 cells) plus the one-cell type glyph and its gap, + so each label lands over its lane. - All four columns are sortable, so any one can be the active sort. The active column's - label *and* its direction triangle (``▲`` ascending, ``▼`` descending) are lit cyan - together — the same cue the static Contacts table's + Every column is sortable, so any one can be the active sort. The active column's label + *and* its direction triangle (``▲`` ascending, ``▼`` descending) are lit together in the + app's ``cursor`` white — the same cue the static Contacts table's :func:`~meshterm.ui.widgets._sort_header` lights. The triangle lands in the column's trailing :data:`_GAP`, flanked by a space on each side so it never abuts the next column's label, and every column reserves that same gap whether or not it holds a @@ -176,26 +251,43 @@ def _header(name_w: int, sort: ContactsSort, show_traced: bool = False) -> Text: header = Text(" ", style="muted") # pointer (2) + the row's type glyph and gap (2) column(header, "NAME", "name", name_w) - if show_traced: - column(header, "TRACED", "traced", 6) # 6-wide lane fits the ``TRACED`` header - column(header, "HEARD", "heard", 5) - column(header, f"{'PKTS':>5}", "packets", 5) + for lane in lanes: + # Right-aligned label over a right-aligned value, so a narrow field's header sits + # where its digits will (``PKTS`` over a 5-cell count) rather than off to the left. + column(header, f"{lane.label:>{lane.width}}", lane.column, lane.width) column(header, "KEY", "hash", 3, last=True) return header +def _lane_cell(row: "ContactRow", lane: "ContactLane") -> Text: + """One row's value for one lane, right-aligned into the lane's width and styled by kind. + + An ``age`` lane draws the relative age in the column form (:func:`_format_age`) under + recency heat, so a fresh value glows and a cold one greys — the same reading whatever + the event the lane times. A ``count`` lane draws the tally muted, or a faint ``—`` where + there is nothing to count, and clamps so a runaway tally can't widen the column. + """ + value = getattr(row, lane.field, None) + if lane.kind == "count": + if value is None: + return Text(f"{'—':>{lane.width}}", style="faint") + return Text(f"{min(value, 99999):>{lane.width}}", style="muted") + secs = _age_seconds(value) + return Text(f"{_format_age(secs):>{lane.width}}", style=_recency_style(secs)) + + def _you_lane( - row: ContactRow, name_w: int, prefix_bytes: int, hash_w: int, show_traced: bool = False + row: "ContactRow", name_w: int, prefix_bytes: int, hash_w: int, + lanes: "tuple[ContactLane, ...]" = DEFAULT_LANES, ) -> Text: """Our own node's lane — laid out exactly like :func:`_lane`'s regular rows. Drawn like the map and the static table draw us: the ``★`` self marker (yellow), the name in the pure-white ``you`` style with a muted ``(you)`` tag, and our key with its hash lit at the routing width, filling the flexing key lane — our 64-hex key is longer - than any lane, so it shows as many digits as fit and ellipsizes. The heard and packet - lanes (and the optional ``TRACED`` lane) read a faint ``—``: we never overhear or trace - ourselves, so there is no reception age, count, or trace age to show. With no reachable - device to name us, the name falls back to a bare ``you`` and the key to ``?``. + than any lane, so it shows as many digits as fit and ellipsizes. **Every middle lane + reads a faint ``—``**, whatever the list declares: we never overhear, trace, or archive + ourselves, so none of those has a value to show and each says so identically. """ text = Text(no_wrap=True, overflow="ellipsis") text.append(_SELF[0], style=_SELF[1]) @@ -211,13 +303,9 @@ def _you_lane( text.append(" " * (name_w - used)) else: text.append(fit_cells(row.name or "you", name_w), style="you") - text.append(_GAP_S) - if show_traced: - text.append(f"{'—':>6}", style="faint") # traced: we never trace ourselves + for lane in lanes: text.append(_GAP_S) - text.append(f"{'—':>5}", style="faint") # heard: we don't hear ourselves - text.append(_GAP_S) - text.append(f"{'—':>5}", style="faint") # packets: nothing to count + text.append(f"{'—':>{lane.width}}", style="faint") text.append(_GAP_S) # the lane gap the header's KEY lane keeps (see _header) if row.key: text.append_text(highlighted_hash(row.key, prefix_bytes, width=hash_w)) @@ -227,7 +315,8 @@ def _you_lane( def _lane( - row: ContactRow, name_w: int, prefix_bytes: int, hash_w: int, show_traced: bool = False + row: "ContactRow", name_w: int, prefix_bytes: int, hash_w: int, + lanes: "tuple[ContactLane, ...]" = DEFAULT_LANES, ) -> Text: """One contact as fixed, colour-coded lanes under :func:`_header`'s columns. @@ -235,11 +324,8 @@ def _lane( repeater, ``■`` for a room, ``◉`` for a sensor, ``●`` for a plain node. The name takes the contact's hash-derived palette hue (a nameless contact's ``unknown`` placeholder stays muted — colour marks a name, and the hash lane already carries the identity) and - the flexing name lane (``name_w`` cells). With ``show_traced`` the last-traced age comes - next (the Trace picker's lane, recency-heat coloured, ``never`` cold). The last-heard age - follows, glowing with recency heat (brighter = fresher) so a freshly heard contact still - reads hot at a glance; then the packet count, right-aligned — a contact never overheard - reads a faint ``—``; the key closes the row in the shared key widget, its hash lit at the + the flexing name lane (``name_w`` cells). Each declared lane follows in order, drawn by + :func:`_lane_cell`; the key closes the row in the shared key widget, its hash lit at the device's routing width, or a muted ``?`` when no key is known at all. An own-node row (:attr:`ContactRow.you`) takes its own drawing — see :func:`_you_lane`. @@ -249,13 +335,11 @@ def _lane( prefix_bytes: The hash width in bytes to light at the head of the key. hash_w: The flexing key lane's width in cells (a short key pads out to it; see :func:`~meshterm.ui.widgets.highlighted_hash`). - show_traced: Whether to draw the ``TRACED`` lane (last-traced age) between the name - and heard lanes — only the Trace-target picker does. + lanes: The middle lanes to draw between the name and the key. """ if row.you: - return _you_lane(row, name_w, prefix_bytes, hash_w, show_traced) + return _you_lane(row, name_w, prefix_bytes, hash_w, lanes) glyph, glyph_style = _NODE_GLYPHS.get(row.node_type, _DEFAULT_GLYPH) - secs = _age_seconds(row.last_seen) text = Text(no_wrap=True, overflow="ellipsis") text.append(glyph, style=glyph_style) text.append(" ") @@ -263,17 +347,9 @@ def _lane( fit_cells(row.name or "unknown", name_w), style=name_style(row.name, row.key) if row.name else "muted", ) - text.append(_GAP_S) - if show_traced: - tsecs = _age_seconds(row.last_traced) - text.append(f"{_format_age(tsecs):>6}", style=_recency_style(tsecs)) + for lane in lanes: text.append(_GAP_S) - text.append(f"{_format_age(secs):>5}", style=_recency_style(secs)) - text.append(_GAP_S) - if row.count is None: - text.append(f"{'—':>5}", style="faint") - else: - text.append(f"{min(row.count, 99999):>5}", style="muted") + text.append_text(_lane_cell(row, lane)) text.append(_GAP_S) # the lane gap the header's KEY lane keeps (see _header) if row.key: # A nameless row is an unidentified node: its key lane greys whole (prefix @@ -287,37 +363,42 @@ def _lane( return text -def _ordered(rows: list[ContactRow], sort: ContactsSort) -> list[ContactRow]: +def _ordered( + rows: "list[ContactRow]", sort: ContactsSort, + lanes: "tuple[ContactLane, ...]" = DEFAULT_LANES, +) -> "list[ContactRow]": """Order the sortable rows by the active sort (own-node rows are pinned elsewhere). - The columns' natural metrics: name A→Z, ``heard`` by age so ascending is - most-recently-heard first (a never-heard row gathers at the old end), ``packets`` by - count, ``hash`` by the displayed key (ascending = ``0`` → ``f``). The optional - ``traced`` column sorts by *trace time*, so descending — its natural open (see - :data:`TRACE_SORT_OPENS_ASCENDING`) — is most-recently-traced first, with never-traced - rows carrying ``-inf`` so they gather at the bottom. A name-ascending pre-sort is the - stable tiebreak, so two contacts sharing a metric keep an A→Z order under both - directions rather than flipping with the primary key. - """ + The two fixture columns sort on themselves — name A→Z, ``hash`` by the displayed key + (ascending = ``0`` → ``f``). Every other column is a declared :class:`ContactLane`, and + sorts by the lane's own metric: a ``count`` lane by its tally, an ``age`` lane by *age in + seconds*, so ascending is freshest-first and a row with no value at all gathers at the + old end whichever direction is in force. That last property is what makes ``heard``, + ``traced`` and ``archived`` behave identically without one line of code naming any of + them. - def key_name(row: ContactRow) -> str: + A name-ascending pre-sort is the stable tiebreak, so two contacts sharing a metric keep + an A→Z order under both directions rather than flipping with the primary key. + """ + by_column = {lane.column: lane for lane in lanes} + + def key_name(row: "ContactRow") -> str: return (row.name or "unknown").casefold() - def metric(row: ContactRow): # noqa: ANN202 - homogeneous per sort + def metric(row: "ContactRow"): # noqa: ANN202 - homogeneous per sort if sort.column == "name": return key_name(row) - if sort.column == "packets": - return row.count or 0 if sort.column == "hash": return row.key - if sort.column == "traced": - # Sort by trace time (epoch), so descending = newest trace first and a - # never-traced row (-inf) always lands last, whichever direction is active. - when = row.last_traced - if when is None or getattr(when, "tzinfo", None) is None: - return float("-inf") - return when.timestamp() - secs = _age_seconds(row.last_seen) # "heard": ascending = freshest first + lane = by_column.get(sort.column) + if lane is None: + # A sort ring wider than the lanes on screen (a saved sort from another list): + # nothing to order by, so the stable name pre-sort stands. + return 0 + value = getattr(row, lane.field, None) + if lane.kind == "count": + return value or 0 + secs = _age_seconds(value) return secs if secs is not None else float("inf") ordered = sorted(rows, key=key_name) @@ -328,24 +409,25 @@ def _ordered(rows: list[ContactRow], sort: ContactsSort) -> list[ContactRow]: class ContactListScreen(SelectScreen): """A full-screen, sortable, filterable contact list in the shared lane layout. - The rows run in aligned lanes — name (in the contact's hash-derived palette hue), - last-heard age (coloured by recency heat), packet count, and key — own-node rows - first, then the rest in the active sort order. Building with ``show_traced`` inserts - one more lane, ``TRACED`` (how long ago the node was last traced), between name and - heard — the Trace-target picker only, which opens sorted by it. The lanes anchor to - the left: the name lane is sized to its widest name (not - the terminal), so the columns stay put as the window widens and the freed width flows - to the key lane, which shows each key as fully as it fits (see :meth:`_lane_widths`). - It is a full-screen list, not a floating popup. + The rows run in aligned lanes — the name (in the contact's hash-derived palette hue), + then whatever middle lanes the list declared, then the key — own-node rows first, then + the rest in the active sort order. ``lanes`` picks the set: :data:`DEFAULT_LANES` for + the usual ``NAME · HEARD · PKTS · KEY``, :data:`TRACE_LANES` for the Trace picker's + extra ``TRACED``, :data:`ARCHIVED_LANES` for the Archived list's ``NAME · ARCHIVED · + KEY``. Pair the set with a ``sort`` whose ring spans it. The lanes anchor to the left: + the name lane is sized to its widest name (not the terminal), so the columns stay put + as the window widens and the freed width flows to the key lane, which shows each key as + fully as it fits (see :meth:`_lane_widths`). It is a full-screen list, not a floating + popup. The sort rides the Ctrl+arrows, leaving the plain arrows for the highlight and the - letters for type-to-filter: **Ctrl+←/→** pick the column (name → heard → packets → - hash, each adopting its natural direction) and **Ctrl+↑/↓** force ascending/ - descending. Every change re-sorts the contact block in place — the lead rows and headers - stay pinned, the highlight rides its contact, and any active filter holds — the same - :class:`~meshterm.ui.widgets.ContactsSort` model and cyan triangle cue the static Contacts - table uses, only its keys moved off the plain arrows that a filterable list already - spends. + letters for type-to-filter: **Ctrl+←/→** pick the column (each adopting its natural + direction) and **Ctrl+↑/↓** force ascending/descending. Every change re-sorts the + contact block in place — the lead rows and headers stay pinned, the highlight rides its + contact, and any active filter holds — the same + :class:`~meshterm.ui.widgets.ContactsSort` model and white column cue the static + Contacts table uses, only its keys moved off the plain arrows that a filterable list + already spends. """ floating = False @@ -391,7 +473,7 @@ class ContactListScreen(SelectScreen): lead: Optional[list] = None, tail: Optional[list] = None, footer_hint: str = _HINT, - show_traced: bool = False, + lanes: "tuple[ContactLane, ...]" = DEFAULT_LANES, ) -> None: """Build the list over already-resolved rows. @@ -401,26 +483,26 @@ class ContactListScreen(SelectScreen): the order given), the rest re-sorted here per ``sort``. prefix_bytes: The hash width in bytes to light at the head of each key. sort: The sort state, mutated in place by the Ctrl+arrows — pass the same - instance across re-opens so the chosen order persists. Its ring should - span :data:`SORT_COLUMNS` for the hash column to be reachable (or - :data:`TRACE_SORT_COLUMNS` when ``show_traced`` adds the traced column). + instance across re-opens so the chosen order persists. Its ring should span + the ring matching ``lanes`` (:data:`SORT_COLUMNS`, + :data:`TRACE_SORT_COLUMNS` or :data:`ARCHIVED_SORT_COLUMNS`), so every + column on screen is reachable and no column off it is. prompt: An optional instruction shown above the list. lead: Rows (choices/separators) drawn above the column header — the Time Machine's whole-mesh row and its section heading; ``None`` for none. tail: Rows (choices/separators) drawn *below* the sorted contacts — the - Contacts screen's ``Purge stale contacts…`` action and its ``Back`` exit - group. They sit past every contact whatever the sort, and (being ordinary - choices) fall out of view while a type-to-filter narrows the list, exactly - like the Trophy case's delete rows. ``None`` for a pure pick-list. + Contacts screen's maintenance actions. They sit past every contact whatever + the sort, and (being ordinary choices) fall out of view while a + type-to-filter narrows the list, exactly like the Trophy case's delete rows. + ``None`` for a pure pick-list. footer_hint: Footer key hint; the default advertises the full grammar. - show_traced: Whether to draw the ``TRACED`` lane (last-traced age) between the - name and heard lanes — the Trace-target picker only. Pair it with a ``sort`` - whose ring includes the ``traced`` column. + lanes: The fixed lanes drawn between each row's name and its key. See + :data:`DEFAULT_LANES`, :data:`TRACE_LANES` and :data:`ARCHIVED_LANES`. """ self._contact_rows = rows self._prefix_bytes = prefix_bytes self._sort = sort - self._show_traced = show_traced + self._lanes = tuple(lanes) self._lead = list(lead) if lead else [] self._tail = list(tail) if tail else [] # Provisional until the first render learns the true width (see render_body). @@ -444,16 +526,15 @@ class ContactListScreen(SelectScreen): # The lane names lead the contacts as their landmark, so they pin overhead while the # list scrolls — a row deep in the sort can still be read off its columns. items.append( - Separator(_header(self._name_w, self._sort, self._show_traced), heading=True) + Separator(_header(self._name_w, self._sort, self._lanes), heading=True) ) pinned = [row for row in self._contact_rows if row.you] rest = [row for row in self._contact_rows if not row.you] - for row in (*pinned, *_ordered(rest, self._sort)): + for row in (*pinned, *_ordered(rest, self._sort, self._lanes)): items.append( Choice( _lane( - row, self._name_w, self._prefix_bytes, self._hash_w, - self._show_traced, + row, self._name_w, self._prefix_bytes, self._hash_w, self._lanes, ), row.value, ) @@ -520,12 +601,13 @@ class ContactListScreen(SelectScreen): The name lane is content-sized (see :meth:`_widest_name`) so it stays put as the window grows; it only yields when a very long name would starve the key lane past - its :data:`_HASH_MIN` floor. The key lane then takes all the width the fixed - lanes and the name lane leave, so keys show as fully as they fit — a heard id's 12 - hex digits with room to spare, a 64-hex key ellipsized to the lane. The optional - ``TRACED`` lane widens the fixed lead by :data:`_TRACED_LANE` when shown. + its :data:`_HASH_MIN` floor. The key lane then takes all the width the fixed lanes + and the name lane leave, so keys show as fully as they fit — a heard id's 12 hex + digits with room to spare, a 64-hex key ellipsized to the lane. Each declared lane + adds its gapped width to the fixed lead, so a list that drops two lanes (the + Archived one) hands both back to the key. """ - lead = _LEAD + (_TRACED_LANE if self._show_traced else 0) + lead = _LEAD + sum(_GAP + lane.width for lane in self._lanes) name_cap = max(_NAME_MIN, width - lead - _HASH_MIN) name_w = max(_NAME_MIN, min(self._widest_name(), name_cap)) hash_w = max(_HASH_MIN, width - lead - name_w) diff --git a/meshterm/ui/contacts_screen.py b/meshterm/ui/contacts_screen.py index 28a8242..10afc1e 100644 --- a/meshterm/ui/contacts_screen.py +++ b/meshterm/ui/contacts_screen.py @@ -18,10 +18,12 @@ weakest off the device while MeshTerm keeps them; the flow, its ladder and its p in :mod:`~meshterm.ui.purge_screen`. Our own node, pinned above the list, is never a candidate — it isn't in the device's contact table. -The contacts a sweep archived are listed under their own **Archived** section at the foot of -this screen. They are shown rather than hidden because silent archiving is how a reader -loses track of what they archived, and because the section is the route back: Enter opens -the node's detail page, which offers to restore it. +What a sweep took is never hidden: **View archived contacts** sits directly under the purge +action and opens the archived list (see :mod:`~meshterm.ui.archived_screen`) — its own +screen, in the same lane layout, sorted on its own ``NAME · ARCHIVED · KEY`` columns. It +earns a screen rather than a section at the foot of this one because it is a different list +with different columns: an archived contact has no live heard-age or packet tally worth a +lane, and what it does have — when it left — has no column here to sit in. Removing *one* named contact for good still belongs to that contact rather than to the list: it is the last action on its Node detail page, where the reader is already looking at the @@ -34,11 +36,12 @@ MeshTerm are untouched. from __future__ import annotations -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING +from .archived_screen import open_archived from .contactlist import ContactListScreen, ContactRow from .menus import marked_label -from .purge_screen import archived_rows, purge_contacts +from .purge_screen import purge_contacts from .tui import Choice, Separator from .tui.screen import CANCEL from .widgets import ContactsSort, _contact_pkts @@ -52,8 +55,9 @@ if TYPE_CHECKING: YOU = ("you",) #: The contact-list tail sentinels (distinct from any :class:`~meshterm.core.models.Contact` -#: and from :data:`YOU`): the purge action row and the bare ``Back`` exit row. +#: and from :data:`YOU`): the sweep, and the way in to what it has already taken. _PURGE = ("purge",) +_ARCHIVED = ("archived",) class ContactsScreen(ContactListScreen): @@ -72,7 +76,7 @@ class ContactsScreen(ContactListScreen): prefix_bytes: int, counts: dict[str, int], sort: ContactsSort, - archived: Optional[list] = None, + archived: int = 0, ) -> None: """Create the contacts screen over already-fetched contact data. @@ -86,11 +90,11 @@ class ContactsScreen(ContactListScreen): sort: The initial sort; mutated in place by the Ctrl+arrows. Its ring should span :data:`~meshterm.ui.contactlist.SORT_COLUMNS` so the hash sort is reachable. - archived: Pre-built rows for the ``Archived`` section (see - :func:`~meshterm.ui.purge_screen.archived_rows`), appended after the purge - action. ``None`` draws no section at all. + archived: How many contacts are archived off this device. Non-zero adds the + ``View archived contacts`` row and shows the count on it, so the tally is + visible without opening the list; zero draws no row, since a screen should + not offer a way into an empty list. """ - archived = list(archived or []) rows = [ContactRow(value=YOU, name=self_name, key=self_key, you=True)] for c in contacts: rows.append( @@ -105,21 +109,24 @@ class ContactsScreen(ContactListScreen): count=_contact_pkts(c, counts), ) ) - # The maintenance action closes the list, past every contact whatever the sort: a - # blank spacer, then the err-tinted purge row (a `…` — it opens further prompts). - # Offered only when there are contacts to purge. Anything already archived follows - # it in its own section, so the two halves of the sweep — what it can still take, - # and what it has taken — sit together at the foot of the list. + # The maintenance actions close the list, past every contact whatever the sort: a + # blank spacer, then the err-tinted sweep (a `…` — it opens further prompts), then + # the way in to what the sweep has already taken. The two sit together because they + # are the two halves of one idea, and the archived row is *under* the purge for the + # same reason: it is where the purge's output went. tail: list = [] if contacts: tail = [ Separator(" "), - Choice( - title=marked_label("🗑", "Purge contacts…", "err"), - value=_PURGE, - ), + Choice(title=marked_label("🗑", "Purge contacts…", "err"), value=_PURGE), ] - tail += archived + if archived: + tail = tail or [Separator(" ")] + # The tally rides the row muted, as a status atom rather than as part of the + # verb: it is what the row leads to, not what the row does. + label = marked_label("📂", "View archived contacts", "") + label.append(f" · {archived}", style="muted") + tail.append(Choice(title=label, value=_ARCHIVED)) super().__init__( f"Contacts · {len(contacts)} known", rows=rows, @@ -141,14 +148,13 @@ async def open_contacts( """Open the interactive contacts list; Enter opens Node detail, Esc leaves. The list stays pushed for the whole visit, so whichever node's detail page Enter commits - (or the purge flow the tail action opens) nests *above* it and Esc from there is one pop - back onto the row it was opened from — same sort, same filter, same scroll. Anything that - removes a contact — a purge here, or the detail page's own single-contact - ``Remove contact…`` — ends the visit, re-reads the device and starts a fresh one, so the - contacts that went are gone from the list. That rebuild is the deliberate exception to - keeping the screen: the rows it was holding a place in no longer exist. A row under the - ``Archived`` section is a rebuilt :class:`~meshterm.core.models.Contact` like any other, - so Enter on one opens the same detail page — where it can be restored to the device. + (or the purge flow, or the archived list, that the tail actions open) nests *above* it + and Esc from there is one pop back onto the row it was opened from — same sort, same + filter, same scroll. Anything that changes which contacts the device holds — a sweep + here, a single archive, restore or delete on a detail page, or a restore made from + inside the archived list — ends the visit, re-reads the device and starts a fresh one. + That rebuild is the deliberate exception to keeping the screen: the rows it was holding a + place in no longer exist. Args: ctx: Shared application context (must be in the interactive menu). @@ -169,10 +175,15 @@ async def open_contacts( if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller raise RuntimeError("the interactive contacts list is only available in the menu") session = ctx.ui.session - screen = ContactsScreen( - self_name, self_key, contacts, prefix_bytes, counts, sort, - archived=archived_rows(ctx, self_key), - ) + + def build() -> ContactsScreen: + """The screen over the current contacts, with the live archived tally on its tail.""" + return ContactsScreen( + self_name, self_key, contacts, prefix_bytes, counts, sort, + archived=_archived_count(ctx, self_key), + ) + + screen = build() while True: rebuild = False async with session.stay(screen) as visit: @@ -190,18 +201,32 @@ async def open_contacts( rebuild = True break continue + if chosen == _ARCHIVED: + # The archived list is a screen, not a section: it nests above this one + # and Esc comes back to this row. It rebuilds us only if something was + # restored or deleted in there, since that is when this list is stale. + if await open_archived(ctx, self_key, prefix_bytes): + rebuild = True + break + continue # The own-node sentinel opens our own node's page; any other value is a - # Contact. The page nests above this list and can also *delete* the contact - # it details (its ``Remove contact…`` row); when it does, it says so on the - # way out and the list rebuilds without the row — the same re-read the purge - # does, one contact at a time. + # Contact. The page nests above this list and carries the single-contact + # management verbs — archive, restore, delete; when one of them runs, the + # page says so on its way out and this list rebuilds without the row, the + # same re-read the sweep does, one contact at a time. if await open_node_detail(ctx, None if chosen == YOU else chosen): rebuild = True break if not rebuild: return contacts = await ctx.devstate.contacts() - screen = ContactsScreen( - self_name, self_key, contacts, prefix_bytes, counts, sort, - archived=archived_rows(ctx, self_key), - ) + screen = build() + + +def _archived_count(ctx: "AppContext", self_key: str) -> int: + """How many contacts are archived off this device — the tail row's tally and its gate.""" + store = getattr(ctx, "contact_store", None) + dev_pub = (self_key or "").lower().removeprefix("0x") + if store is None or not dev_pub: + return 0 + return len(store.archived(dev_pub)) diff --git a/meshterm/ui/node_detail_screen.py b/meshterm/ui/node_detail_screen.py index ebcb54a..c14647c 100644 --- a/meshterm/ui/node_detail_screen.py +++ b/meshterm/ui/node_detail_screen.py @@ -75,6 +75,7 @@ from __future__ import annotations import asyncio import math import re +import time from dataclasses import dataclass, field, replace from datetime import datetime from typing import TYPE_CHECKING, Optional @@ -1122,24 +1123,41 @@ def _located(lat: Optional[float], lon: Optional[float]) -> bool: # -- data gathering + the action loop ----------------------------------------- -async def open_node_detail(ctx: "AppContext", contact: Optional["Contact"]) -> bool: +async def open_node_detail( + ctx: "AppContext", contact: Optional["Contact"], *, manage: bool = True +) -> bool: """Open the Node detail page for a contact (or our own node) and run its action loop. Assembles the page from stored history, the device's contacts, and the observed topology — identity, reception stats, a location preview, and the observed routes — then loops: show the page, run whatever action the user commits (trace, full map, time machine), and show it again, until Esc backs out. This is the same show/act/reshow loop - the Time Machine and Contacts list use. One action ends the loop instead of returning to - it — removing the contact, which leaves nothing to show. + the Time Machine and Contacts list use. + + **Three actions end the loop instead of returning to it**, because each leaves a page + describing a state that no longer holds: archiving the contact off the device, restoring + it, and deleting it outright. All three are *contact management*, they are grouped last + on the Info tab, and the page offers exactly the ones that make sense — a live contact + can be archived or deleted, an archived one restored or deleted. + + ``manage`` is how a caller says the page is being opened to *look*, not to act. The + purge preview passes ``False``: a screen whose whole job is choosing what to archive + should not also hand out a second, singular way to archive — or a delete — from inside + its own candidate list. The rule is that management verbs belong to the list a contact + actually lives in, never to a page opened out of a list that is about to act on it + wholesale. Args: ctx: The shared application context (must be running the interactive TUI). contact: The contact to detail, or ``None`` for our own node (an identity-and-ledger page — we never overhear ourselves, so there is no reception history to show). + manage: Whether to offer the contact-management actions (archive, restore, delete). + ``False`` draws none of them, and the page can then only ever return ``False``. Returns: - ``True`` if the visit ended by removing the contact from the device (the caller's - cue to re-read and rebuild the list it came from), ``False`` on any ordinary exit. + ``True`` if the visit ended by archiving, restoring, or deleting the contact — the + caller's cue to re-read and rebuild the list it came from — ``False`` on any + ordinary exit. Raises: RuntimeError: If called outside the interactive menu (no full-screen session). @@ -1345,18 +1363,27 @@ async def open_node_detail(ctx: "AppContext", contact: Optional["Contact"]) -> b full_key = key.lower().removeprefix("0x") if len(full_key) == 64 and _is_hex(full_key): info_actions.append(_Action("share", "📱", "", "Share contact — QR / link")) - # An archived contact is off the device but remembered in full (see - # :mod:`~meshterm.ui.purge_screen`), so the page it opens from the Contacts list's - # ``Archived`` section offers the way back rather than the way out. Above the removal, - # because it is the constructive one of the pair. - archived = _is_archived(ctx, contact, self_key) - if archived: - info_actions.append(_Action("restore", "📂", "ok", "Restore to device")) - # The page's one destructive action, and so its last row: drop this single contact from - # the device's table. Offered only for a contact we can actually address by key — our own - # node is no contact, and a node with neither key nor prefix has nothing to delete by. - if not you and contact is not None and (contact.public_key or contact.key_prefix): - info_actions.append(_Action("remove", "🗑", "err", "Remove contact…")) + # -- contact management, the page's last group and the only actions that end the visit. + # Withheld entirely when the caller opened the page to look rather than to act (see + # ``manage``), and never offered for our own node or for a contact carrying no key at + # all — there would be nothing to address the write by. + archived = manage and _is_archived(ctx, contact, self_key) + manageable = ( + manage and not you and contact is not None + and bool(contact.public_key or contact.key_prefix) + ) + if manageable: + # The constructive verb first, then the destructive one, so the row a mistaken press + # is likeliest to land on is the recoverable one. Archive and restore are the two + # halves of one reversible move, and take the ``💾``/``📂`` pair the lexicon already + # gives put-it-away and bring-it-back; only a contact with a full key can be written + # back to the device, so a prefix-only contact is never offered the archive that + # would strand it. + if archived: + info_actions.append(_Action("restore", "📂", "ok", "Restore to device")) + elif len((contact.public_key or "").lower().removeprefix("0x")) == 64: + info_actions.append(_Action("archive", "💾", "", "Archive contact")) + info_actions.append(_Action("remove", "🗑", "err", "Delete contact…")) try: adv_type = int(node_type) if node_type is not None else 1 except (TypeError, ValueError): @@ -1423,12 +1450,17 @@ async def open_node_detail(ctx: "AppContext", contact: Optional["Contact"]) -> b await open_timemachine_node(ctx, node_id, label) elif action == "restore": # A restore writes the contact back and ends the visit for the same reason a - # removal does: the page was opened from the Archived section, and the row it + # deletion does: the page was opened from the Archived list, and the row it # was opened from is about to stop existing there. assert contact is not None # the row only exists for a real contact if await _restore_archived(ctx, contact, self_key, label): contact_removed = True break + elif action == "archive": + assert contact is not None + if await _archive_contact(ctx, contact, self_key, label): + contact_removed = True + break elif action == "remove": # The confirm floats over this page, which is already the backdrop — the # reader confirms against the node they are looking at. A removal ends the @@ -1463,6 +1495,72 @@ def _is_archived( return any(c.public_key == key for c in store.archived(dev_pub)) +async def _archive_contact( + ctx: "AppContext", contact: "Contact", self_key: str, label: str +) -> bool: + """Confirm and archive one contact off the device; ``True`` once it is gone from the radio. + + The single-contact counterpart to the bulk sweep (see + :func:`~meshterm.ui.purge_screen.purge_contacts`), doing exactly what the sweep does to + each of its victims: remove from the device, then record it in the cross-session store + with an archive stamp so nothing is actually lost. + + The confirm is **amber, not red, and takes no typing**. Two escalating caution tiers + exist for two different costs, and this one is recoverable: the contact keeps its key, + its reception history and its transcripts, the Archived list is one row on the Contacts + screen away, and a restore is a single write. Red and a typed word are for + :func:`_remove_contact`, which is the one that cannot be undone. + + Args: + ctx: The shared application context (interactive menu; the page is the backdrop). + contact: The contact to archive, addressed by the key it carries. + self_key: The device's own public key (hex) — how the contact store scopes this + device's remembered contacts. + label: How the node is named on the page, for the prompt and the failure notice. + + Returns: + ``True`` if the contact was archived, ``False`` if the user cancelled or the device + refused. A device that has no such contact is not a refusal: the archive finishes on + our side, since being off the radio is the state it was asking for. + """ + from .surface import TuiUi + + assert isinstance(ctx.ui, TuiUi) # guaranteed by open_node_detail + session = ctx.ui.session + + if not await ctx.ui.dialog( + f"Archive {label}? It comes off this device's contact list, freeing a slot for a " + "new one. MeshTerm keeps it — with its key, reception history and messages — and " + "you can restore it at any time.", + [("Cancel", False), ("Archive", True)], + title="Archive contact", + default=1, + danger=True, + ): + return False + + device = await ctx.device() + try: + await device.remove_contact(contact) + except ContactNotOnDeviceError: + # The radio doesn't hold it, which is where the archive was taking it anyway: the + # store write below is the whole of the remaining work. + ctx.log.debug("contacts: %s was not on the device; archiving ours", contact.name) + except Exception as exc: # noqa: BLE001 - a refused removal is reported, not raised + ctx.log.debug("contacts: archive failed for %s: %s", contact.name, exc) + await session.message_dialog( + Text(f"✗ couldn't archive {label} — {exc}", style="err"), + title="Archive contact", + ) + return False + + dev_pub = (self_key or "").lower().removeprefix("0x") + if ctx.contact_store is not None and dev_pub and contact.public_key: + ctx.contact_store.archive(dev_pub, contact, when=int(time.time())) + ctx.devstate.invalidate_contacts() + return True + + async def _restore_archived( ctx: "AppContext", contact: "Contact", self_key: str, label: str ) -> bool: @@ -1530,9 +1628,11 @@ async def _remove_contact( firmware no longer holds offers to write it back rather than failing (see :func:`~meshterm.ui.chat._restore_contact`). - Irreversible from this device's point of view — nothing here can re-derive a key the - store has forgotten — so the confirm wears the reserved red: Cancel on the left, the - committing Remove on the right and default. + **Irreversible, and the confirm says so.** Nothing here can re-derive a key the store has + forgotten, so this is the one contact action with no way back — which is exactly what + separates it from :func:`_archive_contact`, whose amber confirm sits one row above it on + the same page. It wears the reserved red for data loss: Cancel on the left, the + committing Delete on the right and default. Args: ctx: The shared application context (interactive menu; the page is pushed as the @@ -1555,10 +1655,11 @@ async def _remove_contact( session = ctx.ui.session if not await ctx.ui.dialog( - f"Remove {label} from this device's contacts? It can't be messaged again until " - "it's added back. Its reception history and chat messages in MeshTerm are kept.", - [("Cancel", False), ("Remove", True)], - title="Remove contact", + f"Delete {label} for good? Its key is forgotten by both this device and MeshTerm, " + "so it can't be messaged or restored — only heard again. To free the device slot " + "and keep the contact, archive it instead.", + [("Cancel", False), ("Delete", True)], + title="Delete contact", default=1, destructive=True, ): @@ -1576,16 +1677,16 @@ async def _remove_contact( ctx.log.debug("contacts: %s was not on the device; removing ours", contact.name) await session.message_dialog( Text( - f"⚠ {label} wasn't in this device's contacts — removed from the ones " + f"⚠ {label} wasn't in this device's contacts — deleted from the ones " "MeshTerm remembers for it.", style="warn", ), - title="Remove contact", + title="Delete contact", ) except Exception as exc: # noqa: BLE001 - a refused removal is reported, not raised ctx.log.debug("contacts: remove failed for %s: %s", contact.name, exc) await session.message_dialog( - Text(f"✗ couldn't remove {label} — {exc}", style="err"), title="Remove contact" + Text(f"✗ couldn't delete {label} — {exc}", style="err"), title="Delete contact" ) return False diff --git a/meshterm/ui/purge_screen.py b/meshterm/ui/purge_screen.py index 62220b3..a315424 100644 --- a/meshterm/ui/purge_screen.py +++ b/meshterm/ui/purge_screen.py @@ -11,13 +11,22 @@ the pushed Contacts list: haven't heard in a year"). Both carry the real number of contacts they would archive, computed from the actual ranking rather than from arithmetic on the table size, because protected contacts are never victims. -2. **Read the list.** Every contact the sweep would take, weakest first, with its - percentile and the two or three facts that put it there — for the age rungs too, since - knowing how the contacts an age threshold caught actually *rank* is exactly the check - that threshold cannot do for itself. Ending in the Apply/Back pair that +2. **Read the list, and edit it.** Every contact the sweep would take, weakest first, with + its percentile and the two or three facts that put it there — for the age rungs too, + since knowing how the contacts an age threshold caught actually *rank* is exactly the + check that threshold cannot do for itself. ``Delete`` drops a row from the list, so a + contact the reader wants to keep is spared without abandoning the whole sweep and picking + a shallower rung; ``←→`` scroll a row too wide for the terminal. Enter on a contact opens + its detail page to *look* at, with the page's own contact-management verbs withheld (see + :func:`~meshterm.ui.node_detail_screen.open_node_detail`) — a screen for choosing what to + archive should not also hand out a singular archive or delete from inside its own + candidate list. It ends in the Apply/Back pair that :func:`~meshterm.ui.menus.exit_rows` draws for staged changes, because that is what this is: a choice with a cost on both sides, not an exit. -3. **Confirm by typing.** The bulk-deletion gate, red like every other. +3. **Confirm.** An amber Cancel/Purge dialog, not the red typed gate a deletion gets: this + is reversible. Every contact keeps its key, its reception history and its transcripts, + the Archived list is one row away on the Contacts screen, and a restore is a single + write. Saving the red for what cannot be undone is what keeps the red meaning anything. **Only the percentile is ever shown.** A raw score means nothing without the distribution it came from, and would need a legend the moment the weights were ever retuned; a contact's @@ -38,6 +47,7 @@ message anyway is restored in passing rather than being a dead end. from __future__ import annotations +import math import time from dataclasses import replace from typing import TYPE_CHECKING, Optional @@ -150,24 +160,19 @@ def _victim_row(scored: ScoredContact) -> Text: return row -def _rung_desc(archived: int, cutoff: Optional[int]) -> str: - """A rung's description lane: what it archives, and how far up the ranking it reaches. +def _rung_desc(kept: int, archived: int) -> str: + """A rung's description lane, in the number the reader is actually choosing. - The cutoff is the *highest* percentile among the contacts the rung would take — so an - age rung reaching into contacts that rank perfectly well says so on its own row, which - is the thing an age threshold can never tell the reader by itself. - - Phrased as "the weakest *n*%" rather than as an ordinal percentile. Two reasons, and the - second is the one that settled it: the phrase means the same thing to a reader who has - never met a percentile, and — after the label lane — a 53-column console leaves this - lane 27 cells, which "up to the 11th percentile" overran by twenty. A rung whose only - interesting half is clipped away on the platform that needs it most is a rung that - doesn't say anything. + **How many contacts you keep**, not how many go. The device's contact table is the + scarce thing and the whole reason to sweep at all, so the useful number is the one that + has to fit in it — how many are archived is the arithmetic left over, and it follows in + the muted half rather than leading. A percentile cutoff led this lane for one round and + was the wrong unit twice over: it answered a question nobody asked at this step, and at + 53 columns it did not fit anyway. """ if not archived: - return "nothing to archive" - head = f"{archived} contact{'' if archived == 1 else 's'}" - return head if cutoff is None else f"{head} · weakest {cutoff}%" + return f"keeps all {kept}" + return f"keeps {kept} · archives {archived}" async def _rank(ctx: "AppContext", contacts: list[Contact]) -> list[ScoredContact]: @@ -307,7 +312,13 @@ def victims_for( """ route, value = picked if route == "keep": - return sweep_candidates(ranked, keep=round(len(sweepable) * int(value) / 100)) + # Rounded *up*: "keep the strongest 90%" of five contacts keeps five, because you + # cannot keep four and a half and the safe direction on a keep is more. Python's + # ``round`` is banker's rounding, which quietly made the 90% and 75% rungs identical + # on a five-contact table by sending 4.5 and 3.75 to the same 4. + return sweep_candidates( + ranked, keep=math.ceil(len(sweepable) * int(value) / 100) + ) matched = [] for scored in sweepable: age = _age_seconds(scored) @@ -333,8 +344,10 @@ def _target_screen(ranked: list[ScoredContact], sweepable: list[ScoredContact]): def rung(label: str, value: tuple) -> tuple: victims = victims_for(ranked, sweepable, value) - cutoff = max((v.percentile for v in victims), default=None) - return (label, _rung_desc(len(victims), cutoff), value) + # What remains on the device: every protected contact, plus the sweepable ones this + # rung doesn't take. Counted from the ranking rather than from the rung's own + # percentage, because a protection is never a victim and the two would disagree. + return (label, _rung_desc(len(ranked) - len(victims), len(victims)), value) items: list = [section_heading("By standing")] items += menu_rows( @@ -350,9 +363,8 @@ def _target_screen(ranked: list[ScoredContact], sweepable: list[ScoredContact]): f"Purge contacts — {len(ranked)} known{held}", items, prompt=( - "Contacts are ranked on how lately and often you hear them, whether you have " - "messaged, how near they are, and how much they post. The weakest are archived " - "off the device and kept here." + "Archives the weakest off the device, keeping them here. Ranked on messages, " + "how lately and often heard, hops and distance." ), footer_hint="↑↓ move · Enter select · Esc back", filterable=False, @@ -361,10 +373,21 @@ def _target_screen(ranked: list[ScoredContact], sweepable: list[ScoredContact]): def _preview_items(victims: list[ScoredContact]) -> list: - """The preview's rows: a pinned column header, one line per victim, then Apply/Back.""" + """The preview's rows: a pinned column header, one line per victim, then Apply/Back. + + Each contact row is ``deletable``, so ``Delete`` lifts it out of the sweep, and pins its + percentile lane out of the ``←→`` scroll (``hscroll_from``): the number is the reader's + place in a list ordered by it, and sliding it away to read a long reasons lane would + cost the row its bearing to gain nothing — the percentile is the part that already fits. + """ return [ Separator(_preview_header, pinned=True), - *(Choice(title=_victim_row(v), value=v) for v in victims), + *( + Choice( + title=_victim_row(v), value=v, deletable=True, hscroll_from=_PCTL_W + ) + for v in victims + ), # The same shape ``exit_rows`` draws, in this flow's own words: Apply has no key of # its own, so it needs a visible counterpart naming what the other way out costs. # Not ``exit_rows`` itself — these are not *staged changes* to a set of values, and @@ -378,17 +401,25 @@ def _preview_items(victims: list[ScoredContact]) -> list: ] -def _preview_screen(items: list, count: int): - """The preview screen over already-built rows.""" +def _preview_screen(victims: list[ScoredContact]): + """The preview screen over a victim list, sized and worded to what it currently holds.""" from .tui import SelectScreen return SelectScreen( - f"Purge contacts — {_count_desc(count)} to archive", - items, + f"Purge contacts — {_count_desc(len(victims))} to archive", + _preview_items(victims), prompt="Archived contacts leave the device but stay here, with their history.", + # Neither the scroll nor the keep atom is written into the base hint: the select + # list splices each in exactly when its key would act — ``←→`` only while the + # highlighted row actually overflows, ``Del keep`` only on a row that can be spared + # — which is the same "advertise a key only where it acts" rule the whole footer + # follows, and what keeps all three atoms inside 72 cells at once. footer_hint="↑↓ move · type to filter · Enter select · Esc back", + delete_hint="Del keep", default=_APPLY, wrap=False, + hscroll=True, + hscroll_hint="←→ scroll", ) @@ -399,20 +430,59 @@ async def _preview(ctx: "AppContext", victims: list[ScoredContact]) -> bool: dozen contacts on a number nobody can check is precisely the operation that deserves to be looked at once. The list is filterable like any other — a reader who wants to know whether one particular node is in it should be able to type its name. - """ - items = _preview_items(victims) - while True: - chosen = await ctx.ui.session.run_screen(_preview_screen(items, len(victims))) - if chosen is CANCEL or chosen is None or chosen == _BACK: - return False - if chosen == _APPLY: - return True - # Any other row is a contact: Enter opens its node detail page, so a reader who - # doesn't recognise a name can go and look before archiving it. The preview stays - # pushed underneath, so Esc from the page lands back on the row it was opened from. - from .node_detail_screen import open_node_detail - await open_node_detail(ctx, chosen.contact) + It is also **editable**. ``Delete`` drops a contact out of the sweep, because the + alternative was to back out and pick a shallower rung, which spares the one contact you + recognised by also sparing forty you didn't care about. The row list is *data* here, so + it refreshes through + :meth:`~meshterm.ui.tui.select.SelectScreen.replace_items` — the highlight follows by + value and the typed filter holds — rather than by rebuilding the screen and dropping the + reader back at the top of a list they were halfway down. + + Args: + ctx: Shared application context. + victims: The candidates, weakest first. **Mutated** when the reader drops rows, so + the caller's list is what actually gets swept. + + Returns: + Whether the reader committed to archiving whatever survived their edits. + """ + from .node_detail_screen import open_node_detail + from .tui.select import DeleteRequest + + screen = _preview_screen(victims) + # A hub: it owns a loop, so it is pushed once and stays for the whole visit. That is what + # lets a spared row refresh the rows underneath the reader's cursor, and a detail page + # nest above without this screen losing its place. + async with ctx.ui.session.stay(screen) as visit: + while True: + chosen = await visit.result() + if chosen is CANCEL or chosen is None or chosen == _BACK: + return False + if chosen == _APPLY: + return bool(victims) + if isinstance(chosen, DeleteRequest): + spared = chosen.value + if spared in victims: + victims.remove(spared) + if not victims: + # The reader spared every candidate: there is no sweep left to preview, + # and an empty list under an "Archive no contacts" row would be a screen + # asking them to confirm nothing. + return False + # The title counts the victims, so it is content too and moves with them. + screen.replace_items( + _preview_items(victims), + title=f"Purge contacts — {_count_desc(len(victims))} to archive", + ) + continue + # Any other row is a contact: Enter opens its node detail page, so a reader who + # doesn't recognise a name can go and look before archiving it. The page is + # opened with ``manage=False`` — this screen is already where archiving is being + # decided, and a second, singular archive or delete reachable from inside its own + # candidate list would be two answers to one question. The preview stays pushed + # underneath, so Esc from the page lands back on the row it was opened from. + await open_node_detail(ctx, chosen.contact, manage=False) def _count_desc(n: int) -> str: @@ -427,17 +497,27 @@ async def _sweep( ) -> int: """Confirm, then remove each victim from the device and archive it here. Returns the count. + The confirm is **amber and takes no typing**, unlike the red typed gate a bulk deletion + wears. The two tiers exist for two different costs and this one is recoverable — every + contact keeps its key, its reception history and its transcripts, and a restore is one + write from the Archived list. A red typed confirm here would have spent the app's + loudest warning on its most reversible bulk action, which is how a warning stops meaning + anything. + The removal is a companion-local command per contact — no LoRa traffic — so it runs straight through under the progress dialog rather than being paced. The store write follows each successful removal rather than being batched at the end, so an interrupted sweep leaves a consistent state: every contact off the device is recorded as archived. """ - warning = ( - f"This archives {_count_desc(len(victims))}, removing them from this device's " - "contact list to free space for new ones. MeshTerm keeps them — with their " - "reception history and message transcripts — and can put any of them back." - ) - if not await ctx.ui.typed_confirm(warning, "archive", title="Purge contacts"): + if not await ctx.ui.dialog( + f"Archive {_count_desc(len(victims))}? They come off this device's contact list, " + "freeing space for new ones. MeshTerm keeps them — with their keys, reception " + "history and messages — under Archived contacts, and any of them can be restored.", + [("Cancel", False), ("Purge", True)], + title="Purge contacts", + default=1, + danger=True, + ): return 0 device = await ctx.device() @@ -476,45 +556,3 @@ async def _sweep( outcome = Text("no contacts could be archived", style="err") await ctx.ui.session.message_dialog(outcome, title="Purge contacts") return archived - - -def archived_rows(ctx: "AppContext", self_key: str) -> list: - """The Contacts list's ``Archived`` section: the contacts swept off this device. - - Drawn always rather than behind a toggle. Silent archiving is how a reader loses track - of what they archived — and the section is also the only route back: Enter on a row - opens the node's detail page, where ``Restore to device`` puts it back. - - Args: - ctx: Shared application context. - self_key: The device's own public key (hex). - - Returns: - The rows to append after the live contacts, or nothing when none are archived. - """ - store = ctx.contact_store - dev_pub = (self_key or "").lower().removeprefix("0x") - if store is None or not dev_pub: - return [] - archived = store.archived(dev_pub) - if not archived: - return [] - rows: list = [section_heading("Archived")] - for remembered in archived: - contact = remembered.to_contact() - label = Text( - remembered.name, - style=name_style(remembered.name, remembered.public_key), - ) - label.append(f" · archived {_ago(remembered.archived_at)}", style="muted") - rows.append(Choice(title=label, value=contact)) - return rows - - -def _ago(stamp: Optional[int]) -> str: - """How long ago an archive stamp was, in the prose form ``format_ago`` speaks.""" - from .widgets import format_ago - - if not stamp: - return "some time ago" - return format_ago(max(0.0, time.time() - stamp)) diff --git a/tests/test_device_config.py b/tests/test_device_config.py index f06e23a..528de01 100644 --- a/tests/test_device_config.py +++ b/tests/test_device_config.py @@ -361,7 +361,7 @@ def test_purge_age_rungs_split_stale_from_never_heard() -> None: async def test_purge_sweeps_under_a_progress_bar_and_reports_in_a_dialog() -> None: - """The sweep counts down a real bar, then hands its outcome back in a dialog. + """The whole sweep, end to end: ladder → preview → amber confirm → bar → outcome dialog. Two things the busy overlay could not do (JP, 2026-08-10). It only ever said "working", and only in the gaps *between* screens — over the pushed contacts list it drew nothing @@ -390,6 +390,7 @@ async def test_purge_sweeps_under_a_progress_bar_and_reports_in_a_dialog() -> No for i in range(3) ] removed_from_device: list[str] = [] + archived: list[str] = [] class _Device: async def remove_contact(self, contact) -> None: # noqa: ANN001 @@ -413,12 +414,20 @@ async def test_purge_sweeps_under_a_progress_bar_and_reports_in_a_dialog() -> No session = TuiSession() ui = TuiUi(session) - ui.typed_confirm = lambda *a, **k: _true() # the red gate is its own tested thing + asked: list[dict] = [] + + async def _dialog(prompt, buttons, **kw): # noqa: ANN001 + asked.append({"prompt": prompt, "buttons": buttons, **kw}) + return True + + ui.dialog = _dialog # type: ignore[method-assign] ctx = SimpleNamespace( ui=ui, log=logging.getLogger("test.purge"), repo=_Repo(), - contact_store=None, + contact_store=SimpleNamespace( + archive=lambda dev, contact, when: archived.append(contact.name) + ), watch_store=None, admin_store=None, devstate=SimpleNamespace( @@ -435,6 +444,9 @@ async def test_purge_sweeps_under_a_progress_bar_and_reports_in_a_dialog() -> No # year", which catches all three — the standing rungs keep a share, so none of them # ever takes a whole table. ladder = await _step_until_screen(session, lambda s: s.title.startswith("Purge contacts")) + body = _screen_text(ladder) + # A rung is described by what it *keeps* — the number that has to fit the device. + assert "keeps" in body for _ in range(9): ladder.handle("down") ladder.handle("enter") @@ -448,9 +460,16 @@ async def test_purge_sweeps_under_a_progress_bar_and_reports_in_a_dialog() -> No assert all(v.name in body for v in victims) preview.handle("enter") - # The sweep now runs under the progress dialog, which is the frontmost screen for its - # whole lifetime — so the list underneath cannot be walked while it works. + # The confirm is amber and button-only: this is reversible, so it spends neither the + # reserved red nor a typed word. bar = await _step_until_screen(session, lambda s: isinstance(s, ProgressScreen)) + assert asked and asked[0]["danger"] is True + assert "destructive" not in asked[0] + assert [label for label, _v in asked[0]["buttons"]] == ["Cancel", "Purge"] + assert "restored" in asked[0]["prompt"] + + # The sweep runs under the progress dialog, which is the frontmost screen for its whole + # lifetime — so the list underneath cannot be walked while it works. assert bar.title == "Purge contacts" assert bar.render_body(60) # a real bar, with a real total to count down bar.handle("down") # every key is swallowed; nothing underneath moves @@ -463,9 +482,112 @@ async def test_purge_sweeps_under_a_progress_bar_and_reports_in_a_dialog() -> No done.handle("escape") assert await task == 3 assert sorted(removed_from_device) == ["Old0", "Old1", "Old2"] + # Off the device, but kept: every victim landed in the store as archived. + assert sorted(archived) == ["Old0", "Old1", "Old2"] -async def test_removing_one_contact_drops_it_from_the_device_and_the_store() -> None: +async def test_sparing_a_row_shrinks_the_sweep_without_leaving_the_preview() -> None: + """Delete on a preview row lifts that contact out of the sweep, in place. + + The alternative was to back out and pick a shallower rung — which spares the one contact + you recognised by also sparing forty you did not care about. The list refreshes through + ``replace_items`` rather than being rebuilt, so the reader keeps their place instead of + being dropped at the top of a list they were halfway down, and the row that survives is + genuinely dropped from what the sweep goes on to archive. + """ + import asyncio + + from meshterm.core.contact_score import ContactSignals, ScoredContact + from meshterm.core.models import Contact + from meshterm.ui.purge_screen import _preview + from meshterm.ui.surface import TuiUi + from meshterm.ui.tui.session import TuiSession + from types import SimpleNamespace + + def scored(name: str, pct: int) -> ScoredContact: + key = f"{ord(name[-1]):02x}" * 32 + return ScoredContact( + contact=Contact(name=name, public_key=key, key_prefix=key[:12]), + signals=ContactSignals(node=key[:12]), + score=float(pct), + percentile=pct, + ) + + victims = [scored("Weak", 3), scored("Middling", 9), scored("Keeper", 14)] + session = TuiSession() + ctx = SimpleNamespace(ui=TuiUi(session)) + task = asyncio.ensure_future(_preview(ctx, victims)) + + screen = await _step_until_screen(session, lambda s: "to archive" in getattr(s, "title", "")) + assert "3 contacts to archive" in screen.title + # Every contact row can be spared; the Apply/Back pair cannot — there is nothing to + # remove from a decision. And the percentile lane is pinned out of the ←→ scroll: it is + # the reader's place in a list ordered by it. + rows = [c for c in screen._choices() if isinstance(c.value, ScoredContact)] + assert len(rows) == 3 and all(c.deletable and c.hscroll_from > 0 for c in rows) + assert not any( + c.deletable for c in screen._choices() if not isinstance(c.value, ScoredContact) + ) + + # The cursor opens on Apply (the committing row is the default), so walk to the top of + # the contacts and down to "Keeper", then spare it. The screen stays up — this is an + # edit, not an exit. + screen.handle("home") + screen.handle("down") + screen.handle("down") + assert screen._current_choice().value.contact.name == "Keeper" + screen.handle("delete") + # Wait for the loop to take the delete — and prove the refresh landed on the *same* + # screen object rather than a rebuilt one, which is what keeps the reader's place. + same = await _step_until_screen( + session, lambda s: "2 contacts to archive" in getattr(s, "title", "") + ) + assert same is screen, "the preview refreshed in place rather than being rebuilt" + body = _screen_text(screen) + assert "Keeper" not in body + assert "Weak" in body and "Middling" in body + assert "Archive 2 contacts" in body # the Apply row re-counts what is left + + # Committing now archives exactly the two that survived the edit: End lands on Back, + # one step up is Apply. + screen.handle("end") + screen.handle("up") + assert screen._current_choice().value == ("apply",) + screen.handle("enter") + assert await task is True + assert [v.contact.name for v in victims] == ["Weak", "Middling"] + + +async def test_sparing_every_row_leaves_the_sweep_with_nothing_to_do() -> None: + """A preview emptied by the reader backs out rather than confirming an empty archive.""" + import asyncio + + from meshterm.core.contact_score import ContactSignals, ScoredContact + from meshterm.core.models import Contact + from meshterm.ui.purge_screen import _preview + from meshterm.ui.surface import TuiUi + from meshterm.ui.tui.session import TuiSession + from types import SimpleNamespace + + key = "aa" * 32 + only = ScoredContact( + contact=Contact(name="Solo", public_key=key, key_prefix=key[:12]), + signals=ContactSignals(node=key[:12]), + score=1.0, + percentile=1, + ) + victims = [only] + session = TuiSession() + task = asyncio.ensure_future(_preview(SimpleNamespace(ui=TuiUi(session)), victims)) + screen = await _step_until_screen(session, lambda s: "to archive" in getattr(s, "title", "")) + screen.handle("home") # off the default Apply row and onto the only contact + screen.handle("delete") + assert await task is False + assert victims == [] + + + +async def test_deleting_one_contact_drops_it_from_the_device_and_the_store() -> None: """The single-contact delete: a red confirm, then both halves of the union forgotten. The list a screen shows is the device's contact table *unioned* with the contacts @@ -510,11 +632,14 @@ async def test_removing_one_contact_drops_it_from_the_device_and_the_store() -> assert await _remove_contact(ctx, hub, "cc" * 32, "Hub") is True # The confirm is the app's single-record delete: red, Cancel on the left, the - # committing verb on the right and default, and it names what survives the deletion. + # committing verb on the right and default. It says plainly that this one is final — + # and points at the archive, which is the reversible way to free the same device slot. assert asked[0]["destructive"] is True - assert [label for label, _v in asked[0]["buttons"]] == ["Cancel", "Remove"] + assert [label for label, _v in asked[0]["buttons"]] == ["Cancel", "Delete"] assert asked[0]["default"] == 1 - assert "Hub" in asked[0]["prompt"] and "history" in asked[0]["prompt"] + prompt = asked[0]["prompt"] + assert "Hub" in prompt and "for good" in prompt and "restored" in prompt + assert "archive it instead" in prompt # Both halves of the union, then the cache the list re-reads through. assert removed == ["Hub"] assert forgotten == [("cc" * 32, "3d" * 32)] @@ -597,7 +722,7 @@ async def test_a_refused_removal_is_shown_and_the_contact_stays() -> None: task = asyncio.ensure_future( _remove_contact(ctx, Contact(name="Hub", public_key="3d" * 32), "cc" * 32, "Hub") ) - failed = await _step_until_screen(session, lambda s: "couldn't remove" in _screen_text(s)) + failed = await _step_until_screen(session, lambda s: "couldn't delete" in _screen_text(s)) assert "contact table is busy" in _screen_text(failed) failed.handle("escape") assert await task is False @@ -776,6 +901,124 @@ def test_contacts_screen_tail_offers_purge_only_when_populated() -> None: assert _PURGE not in values # nothing to purge — no action row +def test_the_archived_row_appears_only_when_something_is_archived() -> None: + """The way in to the archived list is drawn, with its tally, exactly when there is one. + + A screen should not offer a route into an empty list, and the tally rides the row so the + count is readable without opening it — the sweep's output being visible from the sweep's + own screen is what keeps archiving from being something you lose track of. + """ + from meshterm.core.models import Contact + from meshterm.ui.contacts_screen import _ARCHIVED, _PURGE, ContactsScreen + + contacts = [Contact(name="Alice", public_key="aa" * 32)] + + none_yet = ContactsScreen("Us", "cc" * 32, contacts, 1, {}, _contacts_sort()) + assert _ARCHIVED not in [c.value for c in none_yet._choices()] + + some = ContactsScreen("Us", "cc" * 32, contacts, 1, {}, _contacts_sort(), archived=12) + values = [c.value for c in some._choices()] + # Under the purge, because it is where the purge's output went. + assert values[-2:] == [_PURGE, _ARCHIVED] + row = next(c for c in some._choices() if c.value == _ARCHIVED) + assert "View archived contacts" in row.label and "12" in row.label + + # It stands on its own for a device whose whole table has been swept: there is nothing + # left to purge, but there is very much something to go and look at. + swept = ContactsScreen("Us", "cc" * 32, [], 1, {}, _contacts_sort(), archived=3) + values = [c.value for c in swept._choices()] + assert _PURGE not in values and values[-1] == _ARCHIVED + + +async def test_archiving_one_contact_takes_it_off_the_device_and_keeps_it() -> None: + """The single-contact archive: an amber confirm, off the radio, stamped in the store. + + The reversible half of the pair the detail page offers. It wears ``danger`` rather than + ``destructive`` and asks for no typed word, because everything it takes is recoverable — + which is the whole reason the app has two caution tiers. + """ + import logging + from types import SimpleNamespace + + from meshterm.core.models import Contact + from meshterm.ui.node_detail_screen import _archive_contact + from meshterm.ui.surface import TuiUi + from meshterm.ui.tui.session import TuiSession + + hub = Contact(name="Hub", public_key="3d" * 32, key_prefix="3d" * 6) + removed: list[str] = [] + archived: list[tuple[str, str]] = [] + invalidated: list[bool] = [] + + class _Device: + async def remove_contact(self, contact) -> None: # noqa: ANN001 + removed.append(contact.name) + + ui = TuiUi(TuiSession()) + asked: list[dict] = [] + + async def _dialog(prompt, buttons, **kw): # noqa: ANN001 + asked.append({"prompt": prompt, "buttons": buttons, **kw}) + return True + + ui.dialog = _dialog # type: ignore[method-assign] + ctx = SimpleNamespace( + ui=ui, + log=logging.getLogger("test.archive"), + contact_store=SimpleNamespace( + archive=lambda dev, contact, when: archived.append((dev, contact.public_key)) + ), + devstate=SimpleNamespace(invalidate_contacts=lambda: invalidated.append(True)), + device=lambda: _device(_Device()), + ) + + assert await _archive_contact(ctx, hub, "cc" * 32, "Hub") is True + assert asked[0]["danger"] is True and "destructive" not in asked[0] + assert [label for label, _v in asked[0]["buttons"]] == ["Cancel", "Archive"] + assert asked[0]["default"] == 1 + assert "restore it at any time" in asked[0]["prompt"] + # Off the radio, kept here, and the cached contact list dropped so the list re-reads. + assert removed == ["Hub"] + assert archived == [("cc" * 32, "3d" * 32)] + assert invalidated == [True] + + +async def test_restoring_writes_the_contact_back_before_clearing_the_mark() -> None: + """A refused write leaves the contact archived — never listed as live on a radio without it.""" + import logging + from types import SimpleNamespace + + from meshterm.core.connection import DeviceCommandError + from meshterm.core.models import Contact + from meshterm.ui.node_detail_screen import _restore_archived + from meshterm.ui.surface import TuiUi + from meshterm.ui.tui.session import TuiSession + + hub = Contact(name="Hub", public_key="3d" * 32, key_prefix="3d" * 6) + restored: list[str] = [] + + class _Refuses: + async def add_contact(self, contact) -> None: # noqa: ANN001 + raise DeviceCommandError("contact table full") + + session = TuiSession() + ctx = SimpleNamespace( + ui=TuiUi(session), + log=logging.getLogger("test.restore"), + contact_store=SimpleNamespace(restore=lambda dev, key: restored.append(key)), + devstate=SimpleNamespace(invalidate_contacts=lambda: None), + device=lambda: _device(_Refuses()), + ) + + import asyncio + + task = asyncio.ensure_future(_restore_archived(ctx, hub, "cc" * 32, "Hub")) + shown = await _step_until_screen(session, lambda s: "couldn't restore" in _screen_text(s)) + shown.handle("escape") + assert await task is False + assert restored == [], "the archive mark survives a write the device refused" + + def test_non_strict_enum_accepts_unlisted_value() -> None: """multi_acks/adv_loc_policy list common values but still accept other ints.""" spec = get_spec("multi_acks") @@ -1040,3 +1283,54 @@ async def _channels(device: MockDevice) -> list[dict]: if ch: channels.append(ch) return channels + + +async def test_the_preview_opens_node_pages_with_no_management_verbs( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Enter on a purge candidate opens its page to *look* at, not to act on. + + The rule (JP, 2026-09-01): management verbs belong to the list a contact actually lives + in, never to a page opened out of a list that is about to act on it wholesale. A preview + whose whole job is choosing what to archive should not also hand out a singular archive — + or a delete — from inside its own candidate list, which is two answers to one question. + """ + import asyncio + from types import SimpleNamespace + + import meshterm.ui.node_detail_screen as nd + from meshterm.core.contact_score import ContactSignals, ScoredContact + from meshterm.core.models import Contact + from meshterm.ui.purge_screen import _preview + from meshterm.ui.surface import TuiUi + from meshterm.ui.tui.session import TuiSession + + opened: list[dict] = [] + + async def _fake_detail(ctx, contact, *, manage=True): # noqa: ANN001 + opened.append({"name": contact.name, "manage": manage}) + return False + + monkeypatch.setattr(nd, "open_node_detail", _fake_detail) + + key = "aa" * 32 + victims = [ + ScoredContact( + contact=Contact(name="Solo", public_key=key, key_prefix=key[:12]), + signals=ContactSignals(node=key[:12]), + score=1.0, + percentile=1, + ) + ] + session = TuiSession() + task = asyncio.ensure_future(_preview(SimpleNamespace(ui=TuiUi(session)), victims)) + screen = await _step_until_screen(session, lambda s: "to archive" in getattr(s, "title", "")) + screen.handle("home") # off the default Apply row and onto the contact + screen.handle("enter") + await _step_until_screen(session, lambda s: bool(opened)) + assert opened == [{"name": "Solo", "manage": False}] + + # The preview is still up underneath — looking at a candidate is not leaving the sweep. + assert session.top is screen + screen.handle("escape") + assert await task is False diff --git a/tests/test_gallery.py b/tests/test_gallery.py index 0eef7a0..a5375e8 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -71,8 +71,7 @@ from meshterm.ui.records_screen import RecordDialog from meshterm.ui.remote_cli import RemoteCliScreen from meshterm.ui.timemachine_screen import TimeMachineScreen from meshterm.ui.trace_screen import TraceScreen -from meshterm.ui.menus import section_heading -from meshterm.ui.tui import Choice, Screen, Separator, frame +from meshterm.ui.tui import Screen, frame from meshterm.ui.tx_screen import TxSweepScreen from meshterm.ui.walk_screen import WalkScreen from meshterm.ui.theme import name_style @@ -146,59 +145,87 @@ def _contacts(cols: int, rows: int) -> Screen: Contact(name="Alice", public_key="aa" * 32), Contact(name="A Rather Long Repeater Name For Width", public_key=_HUB_KEY), ] - # An archived row too: the sweep's section is part of this screen's populated state, - # and its "· archived 3d ago" suffix is the widest thing the tail ever draws. - archived = [ - Separator(" "), - section_heading("Archived"), - Choice(title=Text("hop-9 · archived 3d ago", style="muted"), value=contacts[0]), - ] + # A non-zero archived tally, so the tail draws both maintenance rows — its populated + # state, and the widest the tail ever gets. return ContactsScreen( - "Homestead", "cc" * 32, contacts, 1, {"aa" * 6: 7}, sort, archived=archived + "Homestead", "cc" * 32, contacts, 1, {"aa" * 6: 7}, sort, archived=12 ) -def _purge_scored(name: str, key: str, percentile: int, **signals): # noqa: ANN001, ANN201 - """One ranked contact for the sweep's screens, built through the real dataclasses.""" - from meshterm.core.contact_score import ContactSignals, ScoredContact, _reasons - from meshterm.core.contact_score import DEFAULT_WEIGHTS as w +def _purge_ranked(): # noqa: ANN201 + """A ranked contact table for the sweep's screens — scored by the real function. - sig = ContactSignals(node=key[:12], **signals) - terms = {"dm": 0.0, "recency": 0.1, "volume": 0.2, "channel": 0.5, - "hops": 0.3, "distance": 0.5} - return ScoredContact( - contact=Contact(name=name, public_key=key, key_prefix=key[:12]), - signals=sig, - score=float(percentile), - percentile=percentile, - reasons=_reasons(sig, terms, w), - ) + Deliberately *not* hand-stamped percentiles. The whole point of the gallery is that a + specimen comes out of the app's own funnels, and a percentile is the one number on these + screens that cannot be written down by hand and still be true: it is a contact's rank + against the others in the same list, so faking it renders a screen that is internally + inconsistent — three contacts reading 2, 7 and 11 out of a field of three. + """ + from meshterm.core.contact_score import ContactSignals, rank_contacts + + specs = [ + ("Alice", "aa" * 32, dict(heard_age_days=0.2, packets=140, dm_total=18, + dm_age_days=2.0, known_days=300.0, hops=0.0)), + ("A Rather Long Repeater Name For Width", _HUB_KEY, + dict(heard_age_days=95.0, packets=3, known_days=200.0, hops=2.0)), + ("hop-9", "9a" * 32, dict(heard_age_days=400.0, packets=1, known_days=420.0, + hops=4.0)), + ("YUL-Poly", "3d" * 32, dict(heard_age_days=30.0, packets=22, known_days=250.0, + hops=1.0)), + ("sensor-2", "7c" * 32, dict(heard_age_days=210.0, packets=2, known_days=260.0)), + ] + contacts = [Contact(name=n, public_key=k, key_prefix=k[:12]) for n, k, _ in specs] + signals = { + k[:12]: ContactSignals(node=k[:12], **sig) for _, k, sig in specs + } + return rank_contacts(contacts, signals) def _purge_victims(): # noqa: ANN201 - """The sweep's victim list — a long name, a deep age, and a never-heard row.""" - return [ - _purge_scored("hop-9", "9a" * 32, 2, heard_age_days=400.0, packets=1, - known_days=420.0, hops=4.0), - _purge_scored("A Rather Long Repeater Name For Width", _HUB_KEY, 7, - heard_age_days=95.0, packets=3, known_days=200.0, - hops=2.0), - _purge_scored("Alice", "aa" * 32, 11, packets=6, known_days=90.0), - ] + """The sweep's victim list: the weakest half of the ranking, weakest first.""" + from meshterm.core.contact_score import sweep_candidates + + ranked = _purge_ranked() + return sweep_candidates(ranked, keep=2) def _purge_ladder(cols: int, rows: int) -> Screen: from meshterm.ui.purge_screen import _target_screen - ranked = _purge_victims() - return _target_screen(ranked, ranked) + ranked = _purge_ranked() + return _target_screen(ranked, [r for r in ranked if not r.protected]) def _purge_preview(cols: int, rows: int) -> Screen: - from meshterm.ui.purge_screen import _preview_items, _preview_screen + from meshterm.ui.purge_screen import _preview_screen - victims = _purge_victims() - return _preview_screen(_preview_items(victims), len(victims)) + return _preview_screen(_purge_victims()) + + +def _archived(cols: int, rows: int) -> Screen: + from meshterm.core.contact_store import RememberedContact + from meshterm.ui.archived_screen import ArchivedScreen, archived_rows + from meshterm.ui.contactlist import ( + ARCHIVED_SORT_COLUMNS, + ARCHIVED_SORT_OPENS_ASCENDING, + ) + + now = int(datetime(2026, 8, 31, 12, 0, tzinfo=timezone.utc).timestamp()) + remembered = [ + RememberedContact(public_key="9a" * 32, name="hop-9", archived_at=now - 3 * 86400), + RememberedContact( + public_key=_HUB_KEY, name="A Rather Long Repeater Name For Width", + node_type=2, archived_at=now - 40 * 86400, + ), + RememberedContact(public_key="7c" * 32, name="sensor-2", archived_at=None), + ] + return ArchivedScreen( + archived_rows(remembered), + 1, + ContactsSort.from_name( + "archived", ARCHIVED_SORT_COLUMNS, ARCHIVED_SORT_OPENS_ASCENDING + ), + ) def _node_detail_header() -> Text: @@ -471,6 +498,7 @@ _ENTRIES: list[_Entry] = [ _Entry("contacts", _contacts), _Entry("purge_ladder", _purge_ladder), _Entry("purge_preview", _purge_preview), + _Entry("archived", _archived), _Entry("node_detail", _node_detail), _Entry("map", _map), _Entry("chat", _chat), diff --git a/tests/test_navigation.py b/tests/test_navigation.py index 1ca748d..8b7e57e 100644 --- a/tests/test_navigation.py +++ b/tests/test_navigation.py @@ -319,6 +319,7 @@ def test_update_rows_resorts_the_lanes_and_keeps_the_highlight_on_its_contact() from datetime import datetime, timedelta, timezone from meshterm.ui.contactlist import ( + TRACE_LANES, TRACE_SORT_COLUMNS, TRACE_SORT_OPENS_ASCENDING, ContactListScreen, @@ -338,7 +339,7 @@ def test_update_rows_resorts_the_lanes_and_keeps_the_highlight_on_its_contact() sort=ContactsSort.from_name( "traced", TRACE_SORT_COLUMNS, TRACE_SORT_OPENS_ASCENDING ), - show_traced=True, + lanes=TRACE_LANES, ) screen.handle("text", "bet") # find-as-you-type down to the never-traced node assert screen._current_choice().value == "beta" diff --git a/tests/test_timemachine.py b/tests/test_timemachine.py index 3629913..5dee91e 100644 --- a/tests/test_timemachine.py +++ b/tests/test_timemachine.py @@ -669,9 +669,19 @@ def test_picker_header_highlights_only_the_active_sort_column() -> None: assert not any(any(other in seg for other in ("NAME", "HEARD", "KEY")) for seg in lit) -def test_traced_lane_shows_only_when_enabled() -> None: - """The optional TRACED lane sits between NAME and HEARD — and only with show_traced.""" +def test_a_list_draws_exactly_the_lanes_it_declares() -> None: + """The lane set is the whole story — header, row and widths all read the same tuple. + + Three sets in one assertion sweep, because what matters is that none of them is a + special case: the ordinary list, the Trace picker's extra ``TRACED``, and the Archived + list's ``NAME · ARCHIVED · KEY`` all come out of the same two builders. + """ from meshterm.ui.contactlist import ( + ARCHIVED_LANES, + ARCHIVED_SORT_COLUMNS, + ARCHIVED_SORT_OPENS_ASCENDING, + DEFAULT_LANES, + TRACE_LANES, TRACE_SORT_COLUMNS, TRACE_SORT_OPENS_ASCENDING, ContactRow, @@ -680,29 +690,46 @@ def test_traced_lane_shows_only_when_enabled() -> None: ) from meshterm.ui.widgets import ContactsSort + # The ordinary list: no TRACED column, lanes read NAME·HEARD·PKTS·KEY. + plain = _header(10, ContactsSort.from_name("heard"), DEFAULT_LANES).plain + assert "TRACED" not in plain and "ARCHIVED" not in plain + assert plain.index("NAME") < plain.index("HEARD") < plain.index("PKTS") < plain.index("KEY") + + # The Trace picker: TRACED lands between NAME and HEARD and opens as the active sort. sort = ContactsSort.from_name("traced", TRACE_SORT_COLUMNS, TRACE_SORT_OPENS_ASCENDING) - # Off (the default of every other list): no TRACED column, lanes read NAME·HEARD·PKTS·KEY. - assert "TRACED" not in _header(10, ContactsSort.from_name("heard")).plain - # On: TRACED lands between NAME and HEARD, and opens as the default sort (descending). - header = _header(10, sort, show_traced=True).plain + header = _header(10, sort, TRACE_LANES).plain assert header.index("NAME") < header.index("TRACED") < header.index("HEARD") - assert "TRACED ▼" in header + assert "TRACED ▲" in header # an age lane opens ascending: freshest first + + # The Archived list: one middle lane, and the two it drops are really gone. + arch_sort = ContactsSort.from_name( + "archived", ARCHIVED_SORT_COLUMNS, ARCHIVED_SORT_OPENS_ASCENDING + ) + arch = _header(10, arch_sort, ARCHIVED_LANES).plain + assert arch.index("NAME") < arch.index("ARCHIVED") < arch.index("KEY") + assert "HEARD" not in arch and "PKTS" not in arch row = ContactRow( value="x", name="Poly", key="3d" * 6, last_seen=utcnow() - timedelta(minutes=90), last_traced=utcnow() - timedelta(minutes=2), + archived_at=utcnow() - timedelta(days=3), ) - # The traced age ("2m") renders left of the heard age ("1h") in the shown lane. - traced_lane = _lane(row, 10, 1, 12, True).plain + # The traced age ("2m") renders left of the heard age ("1h") in the picker's lanes. + traced_lane = _lane(row, 10, 1, 12, TRACE_LANES).plain assert traced_lane.index("2m") < traced_lane.index("1h") - # With the lane off, only the heard age shows. - assert "2m" not in _lane(row, 10, 1, 12, False).plain + # Without the lane, only the heard age shows. + assert "2m" not in _lane(row, 10, 1, 12, DEFAULT_LANES).plain + # And the Archived row shows its archive age and neither of the dropped lanes. + archived_lane = _lane(row, 10, 1, 12, ARCHIVED_LANES).plain + assert "3d" in archived_lane + assert "1h" not in archived_lane and "2m" not in archived_lane def test_traced_sort_orders_most_recent_first_never_last() -> None: """The traced sort opens most-recently-traced first, never-traced gathered at the bottom.""" from meshterm.ui.contactlist import ( + TRACE_LANES, TRACE_SORT_COLUMNS, TRACE_SORT_OPENS_ASCENDING, ContactRow, @@ -717,12 +744,13 @@ def test_traced_sort_orders_most_recent_first_never_last() -> None: ContactRow(value="fresh", name="Fresh", last_traced=now - timedelta(minutes=1)), ] sort = ContactsSort.from_name("traced", TRACE_SORT_COLUMNS, TRACE_SORT_OPENS_ASCENDING) - assert sort.column == "traced" and sort.ascending is False # opens descending - # Descending (the default): freshest trace on top, never-traced last. - assert [r.value for r in _ordered(rows, sort)] == ["fresh", "stale", "never"] - # Ascending flips the traced order but keeps never-traced out of the fresh block. - sort.ascending = True - assert [r.value for r in _ordered(rows, sort)] == ["never", "stale", "fresh"] + assert sort.column == "traced" and sort.ascending is True # an age lane opens ascending + # Ascending (the default): freshest trace on top, never-traced last. + assert [r.value for r in _ordered(rows, sort, TRACE_LANES)] == ["fresh", "stale", "never"] + # Descending flips the traced order but keeps never-traced out of the fresh block: the + # metric is an age, so "never" carries +inf and stays at the far end either way. + sort.ascending = False + assert [r.value for r in _ordered(rows, sort, TRACE_LANES)] == ["never", "stale", "fresh"] def _picker(listed, *, prefix_bytes=0, sort=None, type_of=None, resolve_key=None, width=80): @@ -875,17 +903,19 @@ def test_picker_resort_keeps_the_highlight_on_its_node_and_the_filter() -> None: def test_picker_name_lane_is_content_sized_and_hash_lane_flexes() -> None: """Columns anchor left: the name lane hugs its content and stays put as the window widens, and the freed width flows to the hash lane so more of each key shows.""" - from meshterm.ui.contactlist import _LEAD + from meshterm.ui.contactlist import _GAP, _LEAD screen = _picker(_heard_nodes(), width=72) + # The fixed lead is the chrome plus every declared lane's own gapped width. + lead = _LEAD + sum(_GAP + lane.width for lane in screen._lanes) # The widest name here is the "unknown" fallback (7 cells); the lane sizes to it. name_w, hash_w = screen._name_w, screen._hash_w assert name_w == len("unknown") - assert hash_w == 72 - _LEAD - name_w + assert hash_w == 72 - lead - name_w # Widen the terminal: the name lane does not move, the hash lane takes the extra width. screen.render_body(120) assert screen._name_w == name_w - assert screen._hash_w == 120 - _LEAD - name_w + assert screen._hash_w == 120 - lead - name_w assert screen._hash_w > hash_w