Contacts: rename the mislabeled Nodes feature; sharpen node vs contact

The "Nodes" menu was a contacts roster mislabeled — it lists the device's
contacts (get_contacts), which upstream meshcore calls "contact" too. Rename
throughout, no CLI alias:

- tools/nodes.py -> tools/contacts.py (ContactsTool, `meshterm contacts`)
- ui/nodes_screen.py -> ui/contacts_screen.py (ContactsScreen/open_contacts)
- ui/nodelist.py -> ui/contactlist.py (ContactListScreen/ContactRow)
- widgets: NodesSort->ContactsSort, nodes_table->contacts_table

Courier's recipient is a contact you address, so its prose and CLI arg
(`courier queue CONTACT ...`) follow; persisted node_key/node_name stay.

The reception/hardware layer keeps "node" — HeardNode, heard_nodes(),
observations.node, trace_hops.node, map/atlas participants, node types, admin
targets, and the Time Machine's reception picker (its "Nodes" heading stands).
CLAUDE.md's lexicon is rewritten to the refined definitions: node = any mesh
radio; contact = a node your device knows (discovered or added).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 4.8 committed 2026-07-19 11:42:11 -04:00
1 parent b49ef9f2c6
commit 733a68857c
17 files changed
+238 -229

No files matched your search

+10 -2
View File
@@ -31,8 +31,8 @@ them instead of hand-rolling:
| Term | Meaning |
|---|---|
| node | any mesh participant |
| contact | a node the device knows (has a key) |
| node | any device on the mesh — a radio broadcasting packets; roles: client, repeater, room server. The umbrella term |
| contact | a node your device knows: **discovered** (heard broadcasting, not yet added) or **added** (in the contact list, messageable). Every contact is a node; not every node is a contact |
| heard | received from ("last heard", "first heard") — never "seen" in UX text |
| key | the full fixed-length value — a node's public key, a channel secret |
| hash | the short derived id — a key's first path-hash-mode bytes (the slice `highlighted_hash` lights), a channel hash, a path hop |
@@ -42,6 +42,14 @@ them instead of hand-rolling:
| Back | leave the current screen/list (the only exit word on rows) |
| Quit | leave the app (main menu, device splash) — nowhere else |
Node vs contact — the boundary: **node** is the hardware/participant sense — the map,
atlas, heard-nodes, relay hops, graph vertices, and node *types* (client/repeater/room/
sensor) all speak "node". **Contact** is the saved-identity sense — the Contacts screen,
the courier recipient, anything you *address*. The reception/persistence layer
(`observations.node`, `HeardNode`, `heard_nodes()`, `trace_hops.node`) stays "node"; the
sortable list you pick from is `contactlist.py` (`ContactListScreen`/`ContactRow`/
`ContactsSort`/`contacts_table`). The `contacts` tool lists the device's added contacts.
Relative ages: `format_ago` for prose ("now", "5m ago", "never" — never "now ago"),
`_format_age` for aligned columns ("now", "5m").
+5 -5
View File
@@ -33,12 +33,12 @@ your mesh's history is worth.
a scripted one-shot. The registry that builds the menu builds the CLI, so they never
drift apart.
- **It remembers.** A passive monitor logs every overheard advert and telemetry frame —
SNR, RSSI, shared location — to SQLite from the moment the radio opens. Maps, node lists,
SNR, RSSI, shared location — to SQLite from the moment the radio opens. Maps, contact lists,
charts, and the Time Machine all read back that history.
- **It measures.** Live trace with per-hop reliability, a coarse→refine→verify TX-power
sweep, and a walkable graph of how the mesh actually hangs together.
- **It talks.** Live channel and direct messaging, store-and-forward courier delivery for
nodes that aren't there yet, and shareable channels as QR codes and `meshcore://` links.
contacts that aren't there yet, and shareable channels as QR codes and `meshcore://` links.
- **It connects however your companion does.** Serial (USB), Bluetooth LE, or TCP (a WiFi
board or a network proxy) — the discoverable transports are auto-found and picked
interactively, a network device is named by hand, and every kind reconnects live when a link
@@ -98,7 +98,7 @@ with its scripted equivalent, where one exists.
| --- | --- | --- |
| **💬 Chat** | Live full-screen channel and direct messaging — a scrolling transcript with a pinned input line where sent and received messages stream together. Every message is logged; unread counts show in the menu header. | `meshterm chat send / history / list` |
| **# Channels** | Create, join, reorder, mute, and share mesh channels — with QR codes and `meshcore://` share links. | `meshterm channels list / add / join / import / share / clear` |
| **📨 Courier** | Store-and-forward outbox for nodes that aren't reachable yet. Queue a message; it goes out (with ack tracking and polite exponential backoff) the moment the node is next heard, or at a scheduled time. | `meshterm courier queue / list / send / cancel / clear` |
| **📨 Courier** | Store-and-forward outbox for contacts that aren't reachable yet. Queue a message; it goes out (with ack tracking and polite exponential backoff) the moment the contact is next heard, or at a scheduled time. | `meshterm courier queue / list / send / cancel / clear` |
### ⚙ Device management
@@ -113,7 +113,7 @@ with its scripted equivalent, where one exists.
| Feature | What it does | Scripted |
| --- | --- | --- |
| **☰ Nodes** | This node and its known contacts — a recency heat-map, overheard packet counts, and full public keys with the path-hash prefix highlighted. | `meshterm nodes` |
| **👥 Contacts** | This node and its known contacts — a recency heat-map, overheard packet counts, and full public keys with the path-hash prefix highlighted. | `meshterm contacts` |
| **🧭 Trace** | A live trace screen: pick a target and watch each trace stream in hop by hop, with running per-hop medians and reliability. Compose or force a route through specific repeaters. A trace transmits **exactly once** (repeaters can blacklist nodes that burst) — sample more by running it again. | `meshterm trace --target …` |
| **⚡ TX-power optimization** | Sweep a remote node's transmit power live — coarse, then refine, then verify — watch each level land, and decide whether to apply the winner. | `meshterm tx-optimize --path … [--apply]` |
| **⏳ Time machine** | Everything the recorder ever heard, as braille charts: reception volume, the median-SNR band, hour-of-day rhythm, packets and nodes per day, and first-ever arrivals — over a switchable 24h / 7d / 30d / all-time window, per node or mesh-wide. | — |
@@ -143,7 +143,7 @@ meshterm chat send --channel 0 "net in 5" # channel broadcast
meshterm chat history --to Alice
meshterm chat list
# Store-and-forward: queue for a node that's offline right now
# Store-and-forward: queue for a contact that's offline right now
meshterm courier queue Alice "ping me when you're back" --at 18:30
meshterm courier list # the outbox — waiting and finished
meshterm courier send 3 # force one delivery attempt now
+3 -3
View File
@@ -1,7 +1,7 @@
"""Persistence for the Courier: the store-and-forward outbox.
The Courier (see :mod:`meshterm.services.courier`) queues direct messages for nodes
that aren't reachable right now and delivers them when the node is next heard — or at
The Courier (see :mod:`meshterm.services.courier`) queues direct messages for contacts
that aren't reachable right now and delivers them when the contact is next heard — or at
a scheduled time. This store is the outbox itself: queued messages with their schedule
and attempt history, plus the finished ones (delivered or given-up) kept around, capped,
so the morning after tells the story.
@@ -9,7 +9,7 @@ so the morning after tells the story.
Like the remembered devices (:mod:`meshterm.core.device_store`), this is global machine
state in a small JSON file (``<config_dir>/courier.json``) rather than the
per-invocation SQLite database — a queued message must survive restarts, or the whole
promise ("it'll go out when the node shows up") is hollow.
promise ("it'll go out when the contact shows up") is hollow.
"""
from __future__ import annotations
+2 -2
View File
@@ -1,7 +1,7 @@
"""The Courier: store-and-forward delivery for the outbox.
A session-long background loop over the :class:`~meshterm.core.courier_store.
CourierStore`. Messages queue for nodes that aren't reachable right now; the courier
CourierStore`. Messages queue for contacts that aren't reachable right now; the courier
listens to the hub for signs of life and delivers when the recipient is *fresh* —
heard within the last few minutes — or when a scheduled entry's time arrives. Each
attempt is one ordinary chat send (:meth:`~meshterm.services.chat_service.ChatService.
@@ -13,7 +13,7 @@ Deliberately transmission-shy, like the advert scheduler:
* At most **one** delivery attempt per pass, so a backlog drains politely instead of
bursting onto a shared mesh.
* Failed attempts back off exponentially (5 min doubling to an hour) and — after the
first shot — wait until the node has been heard *again*, so an absent node is never
first shot — wait until the contact has been heard *again*, so an absent contact is never
hammered on faith alone. Only a scheduled entry's first attempt fires blind: the
schedule was an explicit instruction.
* After :data:`MAX_ATTEMPTS` unacknowledged tries the courier gives up and says so.
@@ -1,4 +1,4 @@
"""The ``nodes`` tool: list this node and the contacts it knows about."""
"""The ``contacts`` tool: list this node and the contacts it knows about."""
from __future__ import annotations
@@ -11,18 +11,18 @@ from .base import Tool, ToolResult, register
@register
class NodesTool(Tool):
class ContactsTool(Tool):
"""List this node and its known contacts, each with its path-hash prefix."""
name = "nodes"
title = "Nodes"
name = "contacts"
title = "Contacts"
icon = "👥"
help = "List this node and known contacts (last heard, packets, type, key)"
category = "Mesh"
order = 10 # right under the Dashboard: the "who's out there" view
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
"""Query the device and render the node/contact list.
"""Query the device and render the contacts list.
Args:
ctx: Shared application context.
@@ -32,7 +32,7 @@ class NodesTool(Tool):
A :class:`ToolResult` summarizing the number of known contacts.
"""
from ..ui.surface import TuiUi
from ..ui.widgets import NodesSort, nodes_table
from ..ui.widgets import ContactsSort, contacts_table
# Read through the session cache: on a busy node the contacts table is a slow
# round-trip, and re-fetching it (plus self-info) on every menu visit is a chief cause
@@ -59,22 +59,22 @@ class NodesTool(Tool):
sort_name = str(params.get("sort") or "name")
# In the menu, hand the list to the interactive screen so the Ctrl+arrows re-sort it
# live — its ring spans the shared node list's four columns (hash included); on the
# live — its ring spans the shared contact list's four columns (hash included); on the
# scripted CLI, render the static table once in the requested order.
if isinstance(ctx.ui, TuiUi):
from ..ui.nodelist import SORT_COLUMNS, SORT_OPENS_ASCENDING
from ..ui.nodes_screen import open_nodes
from ..ui.contactlist import SORT_COLUMNS, SORT_OPENS_ASCENDING
from ..ui.contacts_screen import open_contacts
sort = NodesSort.from_name(sort_name, SORT_COLUMNS, SORT_OPENS_ASCENDING)
await open_nodes(ctx, self_name, self_key, contacts, prefix_bytes, counts, sort)
sort = ContactsSort.from_name(sort_name, SORT_COLUMNS, SORT_OPENS_ASCENDING)
await open_contacts(ctx, self_name, self_key, contacts, prefix_bytes, counts, sort)
else:
sort = NodesSort.from_name(sort_name)
ctx.ui.show(nodes_table(self_name, self_key, contacts, prefix_bytes, counts, sort))
sort = ContactsSort.from_name(sort_name)
ctx.ui.show(contacts_table(self_name, self_key, contacts, prefix_bytes, counts, sort))
return ToolResult(summary={"contacts": len(contacts)})
def register_cli(self, app: typer.Typer) -> None:
"""Register the ``nodes`` subcommand.
"""Register the ``contacts`` subcommand.
Args:
app: The Typer application.
@@ -82,7 +82,7 @@ class NodesTool(Tool):
from ..cli import run_tool_command
@app.command(name=self.name, help=self.help)
def _nodes(
def _contacts(
sort: str = typer.Option(
"name", "--sort", "-s", help="Order contacts by: name, heard, packets"
),
+14 -14
View File
@@ -1,10 +1,10 @@
"""The ``courier`` tool: store-and-forward messaging for nodes that aren't there yet.
"""The ``courier`` tool: store-and-forward messaging for contacts that aren't there yet.
Interactively it opens the outbox screen (see :mod:`meshterm.ui.courier_screen`):
queued messages with their live state, the queueing flow (recipient → message →
when), forced sends, and the delivered/given-up history. Delivery runs in the
background for the whole session (see :mod:`meshterm.services.courier`): a queued
message goes out when its node is next heard — or at its scheduled time — as a normal
message goes out when its contact is next heard — or at its scheduled time — as a normal
direct message with acknowledgement tracking and polite exponential backoff, and the
outcome lights the header's Watchtower badge.
@@ -28,12 +28,12 @@ from .base import Tool, ToolResult, register
@register
class CourierTool(Tool):
"""Queue messages for offline nodes; they go out when the node is next heard."""
"""Queue messages for offline contacts; they go out when the contact is next heard."""
name = "courier"
title = "Courier"
icon = "📨"
help = "Store-and-forward outbox — deliver when the node is next heard"
help = "Store-and-forward outbox — deliver when the contact is next heard"
category = "Messaging"
order = 30 # after Chat and Channels: the same conversations, minus the waiting around
@@ -83,7 +83,7 @@ class CourierTool(Tool):
Args:
ctx: Shared application context.
params: ``node`` (contact name), ``text`` (the message body), and an
params: ``contact`` (contact name), ``text`` (the message body), and an
optional local ``at`` clock time (``HH:MM``, next occurrence).
Returns:
@@ -94,7 +94,7 @@ class CourierTool(Tool):
device = await ctx.device()
contacts = await device.get_contacts()
name = str(params["node"])
name = str(params["contact"])
needle = name.casefold()
contact = next((c for c in contacts if c.name.casefold() == needle), None)
if contact is None:
@@ -116,14 +116,14 @@ class CourierTool(Tool):
when = (
f"at {not_before.astimezone().strftime('%b %d %H:%M')}"
if not_before is not None
else "when the node is next heard"
else "when the contact is next heard"
)
ctx.ui.note(
f"[ok]queued[/ok] #{message.ident} for [brand]{contact.name}[/brand] — "
f"delivers {when} (an interactive session's courier does the sending)"
)
return ToolResult(
summary={"queued": message.ident, "node": contact.name, "at": params.get("at")}
summary={"queued": message.ident, "contact": contact.name, "at": params.get("at")}
)
async def _cli_list(self, ctx: AppContext) -> ToolResult:
@@ -179,18 +179,18 @@ class CourierTool(Tool):
"""Force one delivery attempt for a waiting entry, right now.
The scriptable ``Send now`` — one forced attempt through the same courier the
outbox screen uses, skipping the "wait until the node is heard" eligibility check.
outbox screen uses, skipping the "wait until the contact is heard" eligibility check.
"""
ident = int(params["id"])
if ctx.courier_store.get(ident) is None:
raise DeviceCommandError(f"no outbox entry #{ident}")
outcome = await ctx.courier.attempt_now(ident)
notes = {
"delivered": "[ok]✓ delivered[/ok] — acknowledged by the node",
"delivered": "[ok]✓ delivered[/ok] — acknowledged by the contact",
"no ack": "[warn]sent, but no acknowledgement[/warn] — it stays queued for retry",
"gave up": "[err]✗ gave up[/err] — the retry budget is spent",
"unknown contact": (
"[warn]the device's contacts don't know this node yet[/warn] — it stays queued"
"[warn]the device's contacts don't know this contact yet[/warn] — it stays queued"
),
"busy": "[muted]another delivery is in flight — try again in a moment[/muted]",
"gone": "[muted]that entry is no longer waiting[/muted]",
@@ -233,16 +233,16 @@ class CourierTool(Tool):
help=self.help, no_args_is_help=True, rich_markup_mode="rich"
)
@courier_app.command("queue", help="Queue a message for delivery when the node is next heard")
@courier_app.command("queue", help="Queue a message for delivery when the contact is next heard")
def _queue_cmd(
node: str = typer.Argument(..., help="The recipient contact's name"),
contact: str = typer.Argument(..., help="The recipient contact's name"),
text: list[str] = typer.Argument(..., help="The message to queue"),
at: Optional[str] = typer.Option(
None, "--at", help="Hold until this local time (HH:MM, next occurrence)"
),
) -> None:
tool_params: dict[str, Any] = {
"cli_action": "queue", "node": node, "text": " ".join(text)
"cli_action": "queue", "contact": contact, "text": " ".join(text)
}
if at is not None:
tool_params["at"] = at
+1 -1
View File
@@ -8,7 +8,7 @@ the section's first question — *what's going on out there?* — before any spe
is reached for.
Menu-only: the dashboard is inherently live (it rides the event hub and repaints every
second), so there is no scripted one-shot to register — the ``monitor`` and ``nodes``
second), so there is no scripted one-shot to register — the ``monitor`` and ``contacts``
subcommands cover scripted inspection.
"""
+2 -2
View File
@@ -198,8 +198,8 @@ def config_table(
"""
pending = pending or {}
show_staged = bool(pending)
# Match the nodes list: a frameless SIMPLE_HEAD table with a left-justified accent title
# and muted headers, so the two screens read as one family (see widgets.nodes_table).
# Match the contacts list: a frameless SIMPLE_HEAD table with a left-justified accent title
# and muted headers, so the two screens read as one family (see widgets.contacts_table).
table = Table(
title="[accent]Device configuration[/accent]",
title_justify="left",
@@ -1,13 +1,14 @@
"""The shared node list: one sortable, filterable lane layout for every screenful of nodes.
"""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 nodes": aligned ``NAME · HEARD · PKTS · KEY`` lanes under a sort-aware
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 Time Machine
picker and the Nodes screen both build on :class:`NodeListScreen`; each hands its rows over
as :class:`NodeRow` values — however it learned them (stored history, the device's contact
table) — so the two lists render, sort, and steer identically without sharing a data source.
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.
"""
from __future__ import annotations
@@ -30,7 +31,7 @@ from .widgets import (
_format_age,
_recency_style,
highlighted_hash,
NodesSort,
ContactsSort,
)
#: The narrowest the name lane shrinks to (a very narrow terminal), so the header's ``NAME``
@@ -47,7 +48,7 @@ _HASH_MIN = 8
#: 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 (2 gap + 5) and
#: packets (2 gap + 5) — and the 3-cell gap before the key. The name lane is content-sized
#: and the key lane takes the rest (see :meth:`NodeListScreen._lane_widths`).
#: and the key lane takes the rest (see :meth:`ContactListScreen._lane_widths`).
_LEAD = 2 + 2 + (2 + 5) + (2 + 5) + 3
#: The muted ``(you)`` tag on the own-node lane (see :func:`_lane`), its width folded into
@@ -55,17 +56,17 @@ _LEAD = 2 + 2 + (2 + 5) + (2 + 5) + 3
_YOU_TAG = " (you)"
#: The sort ring and each column's natural opening direction — name A→Z, most-recently-heard
#: first, most packets first, and ``hash`` on the node's key (ascending = ``0`` → ``f``).
#: first, most packets first, and ``hash`` on the contact's key (ascending = ``0`` → ``f``).
#: The ``hash`` ring id predates the lexicon and stays for saved-sort compatibility; its
#: column header reads ``KEY`` — the lane shows the key, with the hash lit inside it.
#: Callers build their :class:`~meshterm.ui.widgets.NodesSort` over these so the Ctrl+arrows
#: walk the same four columns on every node list.
#: Callers build their :class:`~meshterm.ui.widgets.ContactsSort` over these so the Ctrl+arrows
#: walk the same four columns on every contact list.
SORT_COLUMNS: tuple[str, ...] = ("name", "heard", "packets", "hash")
SORT_OPENS_ASCENDING: dict[str, bool] = {
"name": True, "heard": True, "packets": False, "hash": True,
}
#: The cyan the active sort column and its triangle are lit in, matching the static Nodes
#: The cyan the active sort column and its triangle are lit in, matching the static Contacts
#: table's header (see :func:`~meshterm.ui.widgets._sort_header`) so sort cues read
#: identically everywhere.
_SORT_ACTIVE = "bold #22d3ee"
@@ -75,21 +76,21 @@ _HINT = "↑↓ move · ^←→↑↓ sort · type filter · Enter open · Esc b
@dataclass
class NodeRow:
"""One node's lane data, however the caller learned it.
class ContactRow:
"""One contact's lane data, however the caller learned it.
Attributes:
value: What the row's :class:`~meshterm.ui.tui.select.Choice` resolves with —
also the identity a re-sort uses to keep the highlight on its node, so it
also the identity a re-sort uses to keep the highlight on its contact, so it
should be unique across the list.
name: The display name, drawn in the node's hash-derived palette hue; ``None``
name: The display name, drawn in the contact's hash-derived palette hue; ``None``
renders a muted ``unknown`` (an own-node row falls back to a bare ``you``
instead).
key: The hex the key lane shows — as full a key as the caller could resolve;
also the seed of the name's palette hue. Empty renders a muted ``?``.
node_type: The node's type for the leading glyph (``None`` = the plain-node
node_type: The contact's node type for the leading glyph (``None`` = the plain-node
``●``; ignored on the own-node row, which always leads with the yellow ``★``).
last_seen: When the node was last heard (aware UTC) — fills the heard lane,
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).
you: Whether this is our own node: the ``★`` marker, the pure-white ``you`` name
@@ -106,8 +107,8 @@ class NodeRow:
you: bool = False
def _header(name_w: int, sort: NodesSort) -> Text:
"""Column labels over the node lanes (see :func:`_lane`).
def _header(name_w: int, sort: ContactsSort) -> Text:
"""Column labels over the contact lanes (see :func:`_lane`).
The lanes read ``NAME · HEARD · PKTS · KEY``, matching the row builder. The four
leading spaces cover the select screen's pointer column (2 cells) plus the one-cell
@@ -115,7 +116,7 @@ def _header(name_w: int, sort: NodesSort) -> Text:
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 Nodes table's
together — the same cue the static Contacts table's
:func:`~meshterm.ui.widgets._sort_header` lights — and the triangle is drawn *into the
two-cell reserve that already follows every label*, so switching the sort never widens
a lane and shifts the rest of the row. Returned as a :class:`~rich.text.Text` (not a
@@ -145,7 +146,7 @@ def _header(name_w: int, sort: NodesSort) -> Text:
return header
def _you_lane(row: NodeRow, name_w: int, prefix_bytes: int, hash_w: int) -> Text:
def _you_lane(row: ContactRow, name_w: int, prefix_bytes: int, hash_w: int) -> 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
@@ -162,7 +163,7 @@ def _you_lane(row: NodeRow, name_w: int, prefix_bytes: int, hash_w: int) -> Text
# The name lane, exactly name_w cells: the name (white) with a snug muted "(you)" tag —
# padded out to fill the lane — or, when the name alone would crowd out the tag, the
# name fit to the lane with the tag dropped. The lane is sized to hold the tag (see
# NodeListScreen._widest_name), so the drop is a very-long-name guard.
# ContactListScreen._widest_name), so the drop is a very-long-name guard.
used = cell_len(row.name) + cell_len(_YOU_TAG) if row.name else 0
if row.name and used <= name_w:
text.append(row.name, style="you")
@@ -182,22 +183,22 @@ def _you_lane(row: NodeRow, name_w: int, prefix_bytes: int, hash_w: int) -> Text
return text
def _lane(row: NodeRow, name_w: int, prefix_bytes: int, hash_w: int) -> Text:
"""One node as fixed, colour-coded lanes under :func:`_header`'s columns.
def _lane(row: ContactRow, name_w: int, prefix_bytes: int, hash_w: int) -> Text:
"""One contact as fixed, colour-coded lanes under :func:`_header`'s columns.
The type glyph leads (the app's shared marker palette), so the mark reads ``▲`` for a
repeater, ``■`` for a room, ``◉`` for a sensor, ``●`` for a plain node. The name takes
the node's hash-derived palette hue (a nameless node'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). The last-heard age follows, glowing with recency
heat (brighter = fresher) so a freshly heard node still reads hot at a glance; then the
packet count, right-aligned — a node never overheard reads a faint ``—``; 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:`NodeRow.you`)
takes its own drawing — see :func:`_you_lane`.
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). 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 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`.
Args:
row: The node's lane data.
row: The contact's lane data.
name_w: The name lane's width in cells (content-sized across the whole list).
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
@@ -229,20 +230,20 @@ def _lane(row: NodeRow, name_w: int, prefix_bytes: int, hash_w: int) -> Text:
return text
def _ordered(rows: list[NodeRow], sort: NodesSort) -> list[NodeRow]:
def _ordered(rows: list[ContactRow], sort: ContactsSort) -> list[ContactRow]:
"""Order the sortable rows by the active sort (own-node rows are pinned elsewhere).
The four 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``). A name-ascending
pre-sort is the stable tiebreak, so two nodes sharing a metric keep an A→Z order
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.
"""
def key_name(row: NodeRow) -> str:
def key_name(row: ContactRow) -> str:
return (row.name or "unknown").casefold()
def metric(row: NodeRow): # 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":
@@ -257,10 +258,10 @@ def _ordered(rows: list[NodeRow], sort: NodesSort) -> list[NodeRow]:
return ordered
class NodeListScreen(SelectScreen):
"""A full-screen, sortable, filterable node list in the shared lane layout.
class ContactListScreen(SelectScreen):
"""A full-screen, sortable, filterable contact list in the shared lane layout.
The rows run in aligned lanes — name (in the node's hash-derived palette hue),
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. 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
@@ -270,9 +271,9 @@ class NodeListScreen(SelectScreen):
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 node block in place — the lead rows and headers
stay pinned, the highlight rides its node, and any active filter holds — the same
:class:`~meshterm.ui.widgets.NodesSort` model and cyan triangle cue the static Nodes
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.
"""
@@ -283,9 +284,9 @@ class NodeListScreen(SelectScreen):
self,
title: str,
*,
rows: list[NodeRow],
rows: list[ContactRow],
prefix_bytes: int,
sort: NodesSort,
sort: ContactsSort,
prompt: str = "",
lead: Optional[list] = None,
footer_hint: str = _HINT,
@@ -294,7 +295,7 @@ class NodeListScreen(SelectScreen):
Args:
title: Short heading shown in the border.
rows: Every node's lane data; :attr:`NodeRow.you` rows are pinned first (in
rows: Every contact's lane data; :attr:`ContactRow.you` rows are pinned first (in
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
@@ -305,7 +306,7 @@ class NodeListScreen(SelectScreen):
Machine's whole-mesh row and its section heading; ``None`` for none.
footer_hint: Footer key hint; the default advertises the full grammar.
"""
self._node_rows = rows
self._contact_rows = rows
self._prefix_bytes = prefix_bytes
self._sort = sort
self._lead = list(lead) if lead else []
@@ -321,14 +322,14 @@ class NodeListScreen(SelectScreen):
)
def _compose_items(self) -> list:
"""The lead rows, the sort-aware column header, then the node lanes.
"""The lead rows, the sort-aware column header, then the contact lanes.
Own-node rows lead the lanes and stay first whatever the sort: only the block
below them reorders (see :func:`_ordered`)."""
items: list = list(self._lead)
items.append(Separator(_header(self._name_w, self._sort)))
pinned = [row for row in self._node_rows if row.you]
rest = [row for row in self._node_rows if not row.you]
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)):
items.append(
Choice(
@@ -339,7 +340,7 @@ class NodeListScreen(SelectScreen):
return items
def _rebuild(self) -> None:
"""Recompose the rows for the current sort/width, keeping the highlight on its node."""
"""Recompose the rows for the current sort/width, keeping the highlight on its contact."""
current = self._current_choice()
keep = current.value if current is not None else None
self._items = self._compose_items()
@@ -363,7 +364,7 @@ class NodeListScreen(SelectScreen):
own-node row's name plus its ``(you)`` tag, so the tag always fits.
"""
widths = [cell_len("unknown")]
for row in self._node_rows:
for row in self._contact_rows:
if row.you:
widths.append(
cell_len(row.name) + cell_len(_YOU_TAG) if row.name else cell_len("you")
@@ -1,20 +1,20 @@
"""The interactive Nodes screen: the device's contacts in the shared sortable node list.
"""The interactive Contacts screen: the device's contacts in the shared sortable contact list.
The Time Machine picker's presentation pointed at the companion's contact table: the same
aligned ``NAME · HEARD · PKTS · KEY`` lanes, our own node pinned first, the same Ctrl+arrow
sort (now including the key column) and type-to-filter — one node list app-wide, whatever
the data source (see :mod:`~meshterm.ui.nodelist`). Enter is deliberately inert for now: the
highlight is a cursor, not yet a selection — a per-node action will land on it later. The
one-shot CLI (``meshterm nodes --sort …``) still renders the static
:func:`~meshterm.ui.widgets.nodes_table`; only the menu gets the live list.
sort (now including the key column) and type-to-filter — one contact list app-wide, whatever
the data source (see :mod:`~meshterm.ui.contactlist`). Enter is deliberately inert for now: the
highlight is a cursor, not yet a selection — a per-contact action will land on it later. The
one-shot CLI (``meshterm contacts --sort …``) still renders the static
:func:`~meshterm.ui.widgets.contacts_table`; only the menu gets the live list.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from .nodelist import NodeListScreen, NodeRow
from .widgets import NodesSort, _contact_pkts
from .contactlist import ContactListScreen, ContactRow
from .widgets import ContactsSort, _contact_pkts
if TYPE_CHECKING:
from ..context import AppContext
@@ -24,12 +24,12 @@ if TYPE_CHECKING:
#: device answered), so a re-sort can keep the highlight on it.
YOU = ("you",)
#: The Nodes list's footer: the shared list's grammar minus the Enter atom — pressing it
#: The Contacts list's footer: the shared list's grammar minus the Enter atom — pressing it
#: does nothing yet, so the hint doesn't advertise it.
_HINT = "↑↓ move · ^←→↑↓ sort · type filter · Esc back"
class NodesScreen(NodeListScreen):
class ContactsScreen(ContactListScreen):
"""A full-screen, Ctrl+arrow-sortable list of this node and its known contacts."""
def __init__(
@@ -39,9 +39,9 @@ class NodesScreen(NodeListScreen):
contacts: "list[Contact]",
prefix_bytes: int,
counts: dict[str, int],
sort: NodesSort,
sort: ContactsSort,
) -> None:
"""Create the nodes screen over already-fetched contact data.
"""Create the contacts screen over already-fetched contact data.
Args:
self_name: This node's advertised name.
@@ -51,13 +51,13 @@ class NodesScreen(NodeListScreen):
counts: Overheard-packet counts keyed by lowercased 12-hex node id; a contact
with no entry shows a faint ``—``.
sort: The initial sort; mutated in place by the Ctrl+arrows. Its ring should
span :data:`~meshterm.ui.nodelist.SORT_COLUMNS` so the hash sort is
span :data:`~meshterm.ui.contactlist.SORT_COLUMNS` so the hash sort is
reachable.
"""
rows = [NodeRow(value=YOU, name=self_name, key=self_key, you=True)]
rows = [ContactRow(value=YOU, name=self_name, key=self_key, you=True)]
for c in contacts:
rows.append(
NodeRow(
ContactRow(
value=c.public_key or c.name,
name=c.name,
key=c.public_key,
@@ -67,7 +67,7 @@ class NodesScreen(NodeListScreen):
)
)
super().__init__(
f"Nodes · {len(contacts)} known",
f"Contacts · {len(contacts)} known",
rows=rows,
prefix_bytes=prefix_bytes,
sort=sort,
@@ -77,7 +77,7 @@ class NodesScreen(NodeListScreen):
def handle(self, action: str, data: str = "") -> None:
"""Swallow Enter; every other key is the shared list's.
The highlight is only a cursor until per-node actions land, so committing it
The highlight is only a cursor until per-contact actions land, so committing it
must neither act nor dismiss the screen — only Esc leaves.
"""
if action == "enter":
@@ -85,16 +85,16 @@ class NodesScreen(NodeListScreen):
super().handle(action, data)
async def open_nodes(
async def open_contacts(
ctx: "AppContext",
self_name: str,
self_key: str,
contacts: "list[Contact]",
prefix_bytes: int,
counts: dict[str, int],
sort: NodesSort,
sort: ContactsSort,
) -> None:
"""Open the interactive, sortable nodes list and run until dismissed with Esc.
"""Open the interactive, sortable contacts list and run until dismissed with Esc.
Args:
ctx: Shared application context (must be in the interactive menu).
@@ -111,6 +111,6 @@ async def open_nodes(
from .surface import TuiUi
if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller
raise RuntimeError("the interactive nodes list is only available in the menu")
screen = NodesScreen(self_name, self_key, contacts, prefix_bytes, counts, sort)
raise RuntimeError("the interactive contacts list is only available in the menu")
screen = ContactsScreen(self_name, self_key, contacts, prefix_bytes, counts, sort)
await ctx.ui.session.run_screen(screen)
+19 -19
View File
@@ -2,7 +2,7 @@
The interactive face of the ``courier`` tool. One select-list screen carries the whole
feature (the persistent-backdrop pattern): the waiting outbox — each entry with its
live state (waiting to hear the node, scheduled for a time, backing off between
live state (waiting to hear the contact, scheduled for a time, backing off between
retries) — the finished history (delivered / given-up), and the queueing flow: pick a
contact, write the message, choose when. Enter on a waiting entry offers *Send now*
(one forced attempt, outcome in a dialog) and *Cancel*.
@@ -30,10 +30,10 @@ from rich.text import Text
from ..core.courier_store import DELIVERED, QUEUED, QueuedMessage
from ..core.models import Contact, utcnow
from .menus import back_rows, section_heading
from .nodelist import SORT_COLUMNS, SORT_OPENS_ASCENDING, NodeListScreen, NodeRow
from .contactlist import SORT_COLUMNS, SORT_OPENS_ASCENDING, ContactListScreen, ContactRow
from .tui import CANCEL, DM_BYTE_LIMIT, Choice, SelectScreen, Separator
from .watchtower_screen import contact_watch_key
from .widgets import NodesSort, _age_seconds, _contact_pkts, format_ago
from .widgets import ContactsSort, _age_seconds, _contact_pkts, format_ago
if TYPE_CHECKING:
from ..context import AppContext
@@ -172,7 +172,7 @@ class CourierOutboxScreen(SelectScreen):
finished, a new queue, a cleared history) can't be expressed by a row re-rendering
itself, so the opener's ticker calls :meth:`refresh`: it fingerprints the store's
shape and recomposes the sections in place only when that changed, keeping the
highlight on its entry (the :class:`~meshterm.ui.nodelist.NodeListScreen` rebuild
highlight on its entry (the :class:`~meshterm.ui.contactlist.ContactListScreen` rebuild
idiom).
"""
@@ -262,9 +262,9 @@ def _waiting_row(ctx: "AppContext", message: QueuedMessage) -> Text:
elif message.attempts > 0:
row.append(f"try {message.attempts} · waiting to hear it again", style="muted")
elif ctx.courier.heard_recently(message.node_key, now):
row.append("node is fresh — next pass", style="ok")
row.append("contact is fresh — next pass", style="ok")
else:
row.append("waiting to hear the node", style="muted")
row.append("waiting to hear the contact", style="muted")
return row
@@ -290,18 +290,18 @@ def _done_row(message: QueuedMessage) -> Text:
# --- the flows --------------------------------------------------------------------------
#: The recipient picker's footer: the shared node-list grammar with a committing Enter,
#: The recipient picker's footer: the shared contact-list grammar with a committing Enter,
#: Esc cancelling the queueing step it sits in.
_PICK_HINT = "↑↓ move · ^←→↑↓ sort · type filter · Enter select · Esc cancel"
class CourierRecipientScreen(NodeListScreen):
"""The recipient picker on the shared node list.
class CourierRecipientScreen(ContactListScreen):
"""The recipient picker on the shared contact list.
The full ``NAME · HEARD · PKTS · KEY`` lanes, the Ctrl+arrow sort ring, and
type-to-filter, exactly as the Nodes screen and the Time Machine picker draw
type-to-filter, exactly as the Contacts screen and the Time Machine picker draw
contacts — names in their key-derived hue, heard ages in recency heat. Unlike the
Nodes screen, Enter *commits*: the shared list's Enter resolves the highlighted
Contacts screen, Enter *commits*: the shared list's Enter resolves the highlighted
row's value, which is the :class:`~meshterm.core.models.Contact` itself.
"""
@@ -311,7 +311,7 @@ class CourierRecipientScreen(NodeListScreen):
contacts: list[Contact],
prefix_bytes: int,
counts: dict[str, int],
sort: NodesSort,
sort: ContactsSort,
) -> None:
"""Build the picker over the device's contacts.
@@ -322,7 +322,7 @@ class CourierRecipientScreen(NodeListScreen):
sort: The sort state (defaults open on ``heard``, freshest first).
"""
rows = [
NodeRow(
ContactRow(
value=c,
name=c.name,
key=c.public_key or c.key_prefix or "",
@@ -337,7 +337,7 @@ class CourierRecipientScreen(NodeListScreen):
rows=rows,
prefix_bytes=prefix_bytes,
sort=sort,
prompt="The message waits in the outbox until this node can take it:",
prompt="The message waits in the outbox until this contact can take it:",
footer_hint=_PICK_HINT,
)
@@ -350,14 +350,14 @@ async def _queue_flow(ctx: "AppContext", contacts: list[Contact]) -> None:
if not contacts:
await session.message_dialog(
Text(
"No contacts available — connect a device that knows some nodes first.",
"No contacts available — connect a device that knows some contacts first.",
style="muted",
),
title="Queue a message",
)
return
# The shared node-list presentation (see CourierRecipientScreen), opened on the
# The shared contact-list presentation (see CourierRecipientScreen), opened on the
# heard column so the most reachable candidates lead — the old fixed order, now
# just the default of a re-sortable list.
counts = {n.node: n.count for n in ctx.repo.heard_nodes() if n.node}
@@ -366,7 +366,7 @@ async def _queue_flow(ctx: "AppContext", contacts: list[Contact]) -> None:
contacts=contacts,
prefix_bytes=prefix_bytes,
counts=counts,
sort=NodesSort.from_name("heard", SORT_COLUMNS, SORT_OPENS_ASCENDING),
sort=ContactsSort.from_name("heard", SORT_COLUMNS, SORT_OPENS_ASCENDING),
)
contact = await session.run_screen(picker)
if not isinstance(contact, Contact): # Esc (CANCEL) or anything else backs out
@@ -481,14 +481,14 @@ async def _entry_actions(ctx: "AppContext", ident: int) -> None:
)
return
notes = {
"delivered": Text("✓ delivered — acknowledged by the node", style="ok"),
"delivered": Text("✓ delivered — acknowledged by the contact", style="ok"),
"no ack": Text(
"sent, but no acknowledgement — it stays queued and the courier "
"will retry with backoff", style="warn",
),
"gave up": Text("no acknowledgement — the retry budget is spent", style="err"),
"unknown contact": Text(
"the device's contact list doesn't know this node yet; "
"the device's contact list doesn't know this contact yet; "
"it stays queued", style="warn",
),
"busy": Text("another delivery is in flight — try again in a moment", style="muted"),
+12 -12
View File
@@ -32,7 +32,7 @@ from rich.text import Text
from ..core.models import utcnow
from .braillechart import _TICK_GAP, GAP, axis_chart, chart_span, timeline_rows
from .menus import fit_cells, section_heading
from .nodelist import SORT_COLUMNS, SORT_OPENS_ASCENDING, NodeListScreen, NodeRow
from .contactlist import SORT_COLUMNS, SORT_OPENS_ASCENDING, ContactListScreen, ContactRow
from .theme import name_style, snr_style
from .tui.render import render_lines
from .tui.screen import CANCEL, Screen
@@ -42,7 +42,7 @@ from .widgets import (
_recency_style,
format_ago,
highlighted_hash,
NodesSort,
ContactsSort,
)
if TYPE_CHECKING:
@@ -974,7 +974,7 @@ def _mesh_sections(
#: Widest the mesh page's arrivals name lane grows (longer names ellipsize so the lanes
#: stay put). The picker sizes its own name lane to content instead (see
#: :meth:`~meshterm.ui.nodelist.NodeListScreen._lane_widths`).
#: :meth:`~meshterm.ui.contactlist.ContactListScreen._lane_widths`).
_PICK_NAME_MAX = 18
#: The mesh page's arrivals key lane's *floor* in cells (a very narrow terminal). The lane
@@ -1074,11 +1074,11 @@ async def _self_identity(ctx: "AppContext") -> tuple[Optional[str], Optional[str
return (str(name) if name else None), (str(key) if key else None)
class TimeMachinePickerScreen(NodeListScreen):
"""The Time Machine's subject picker: the shared node list under the whole-mesh row.
class TimeMachinePickerScreen(ContactListScreen):
"""The Time Machine's subject picker: the shared list under the whole-mesh row.
The whole-mesh overview leads; under it runs the app's shared sortable node list
(see :class:`~meshterm.ui.nodelist.NodeListScreen` for the lanes, the Ctrl+arrow
The whole-mesh overview leads; under it runs the app's shared sortable list
(see :class:`~meshterm.ui.contactlist.ContactListScreen` for the lanes, the Ctrl+arrow
sort, and type-to-filter) — our own node first, then every node ever heard. A heard
node's hash lane shows its fullest known key: the one captured with an observation
(shows offline), else the device's contact list, else the stored 12-hex prefix.
@@ -1089,7 +1089,7 @@ class TimeMachinePickerScreen(NodeListScreen):
*,
listed: list[tuple["HeardNode", Optional[str]]],
prefix_bytes: int,
sort: NodesSort,
sort: ContactsSort,
prompt: str,
self_name: Optional[str] = None,
self_key: Optional[str] = None,
@@ -1104,7 +1104,7 @@ class TimeMachinePickerScreen(NodeListScreen):
prefix_bytes: Path-hash width in bytes to light in each hash.
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:`~meshterm.ui.nodelist.SORT_COLUMNS` for the hash column to be
:data:`~meshterm.ui.contactlist.SORT_COLUMNS` for the hash column to be
reachable.
prompt: The instruction shown above the list.
self_name: Our own node's advertised name, for the own-node lane that always
@@ -1121,10 +1121,10 @@ class TimeMachinePickerScreen(NodeListScreen):
the stored digits (see :func:`_contact_resolvers`); the default returns the
prefix unchanged, leaving the stored 12 hex to stand.
"""
rows = [NodeRow(value=SELF, name=self_name, key=self_key or "", you=True)]
rows = [ContactRow(value=SELF, name=self_name, key=self_key or "", you=True)]
for node, name in listed:
rows.append(
NodeRow(
ContactRow(
value=(node.node, name or node.node),
name=name,
# The full key, most-durable source first: the one captured with the
@@ -1172,7 +1172,7 @@ async def open_timemachine(ctx: "AppContext") -> None:
# One sort for the whole visit, so the order the user picks survives leaving a subject
# page and coming back. Opens most-recently-heard first, as the list always has; its ring
# spans the shared list's four columns so the Ctrl+arrows can reach the hash sort.
sort = NodesSort.from_name("heard", SORT_COLUMNS, SORT_OPENS_ASCENDING)
sort = ContactsSort.from_name("heard", SORT_COLUMNS, SORT_OPENS_ASCENDING)
while True:
heard = ctx.repo.heard_nodes()
+17 -17
View File
@@ -790,7 +790,7 @@ def _contact_pkts(contact: Contact, counts: dict[str, int]) -> Optional[int]:
return counts.get(_key_id(ident)) if ident else None
# The columns the node list can be sorted by, left-to-right, and the direction each opens on
# The columns the contact list can be sorted by, left-to-right, and the direction each opens on
# — name A→Z, most-recently-heard first, most packets first — chosen so a fresh sort shows
# the "interesting" end at the top.
_SORT_COLUMNS: tuple[str, ...] = ("name", "heard", "packets")
@@ -798,8 +798,8 @@ _SORT_OPENS_ASCENDING: dict[str, bool] = {"name": True, "heard": True, "packets"
@dataclass
class NodesSort:
"""Which column the node list is sorted by, and in which direction.
class ContactsSort:
"""Which column the contact list is sorted by, and in which direction.
``column`` is one of :attr:`columns`; ``ascending`` sorts the column's underlying
metric low-to-high — name A→Z, *age* (so ascending = most recently heard first), packet
@@ -807,7 +807,7 @@ class NodesSort:
arrows.
The sort *ring* is per-instance: :attr:`columns` and :attr:`opens_ascending` default to
the Nodes list's three (:data:`_SORT_COLUMNS`), but the Time Machine picker passes a
the Contacts list's three (:data:`_SORT_COLUMNS`), but the Time Machine picker passes a
wider set — it adds a sortable ``hash`` column — so the same model drives both without a
module-global column list that one screen would have to share with the other.
"""
@@ -823,7 +823,7 @@ class NodesSort:
name: str,
columns: tuple[str, ...] = _SORT_COLUMNS,
opens_ascending: Optional[dict[str, bool]] = None,
) -> "NodesSort":
) -> "ContactsSort":
"""Build a sort for ``name`` over ``columns``, opening in that column's natural direction.
Falls back to the ring's first column when ``name`` isn't one of ``columns`` (so a
@@ -842,12 +842,12 @@ class NodesSort:
def _ordered_contacts(
contacts: list[Contact], counts: dict[str, int], sort: NodesSort
contacts: list[Contact], counts: dict[str, int], sort: ContactsSort
) -> list[Contact]:
"""Contacts sorted per ``sort`` (our own node is pinned separately, above these).
The active column's metric drives the order (reversed for a descending sort); ties always
break by case-folded name *ascending*, so two nodes sharing a metric (e.g. the same
break by case-folded name *ascending*, so two contacts sharing a metric (e.g. the same
``heard`` age) keep a stable A→Z order instead of flipping with the primary direction.
Never-heard / never-overheard rows carry an extreme metric so they gather at the ascending
end.
@@ -875,12 +875,12 @@ def _ordered_contacts(
return ordered
def _sort_header(label: str, column: str, sort: NodesSort) -> str:
def _sort_header(label: str, column: str, sort: ContactsSort) -> str:
"""A column header: plain-muted, or cyan with a direction triangle when it's the sort key.
The active column's name and its triangle are lit cyan together (so the interactive
left/right selection is obvious) — ``▲`` for ascending, ``▼`` for descending. The column
reserves its width (see :func:`nodes_table`) so toggling the sort doesn't shift the row.
reserves its width (see :func:`contacts_table`) so toggling the sort doesn't shift the row.
"""
if column != sort.column:
return label
@@ -892,7 +892,7 @@ def node_type_legend(indent: str = "") -> Text:
"""The one-line key to the node-type marks: ``★ you ▲ repeater ● node …``.
Every glyph in its shared map colour (see :data:`_NODE_GLYPHS`), each named muted after
it. THE legend for any surface that draws typed node markers — the nodes list under its
it. THE legend for any surface that draws typed node markers — the contacts list under its
table, the route graph under its fan — so one glyph means one thing app-wide.
Args:
@@ -909,18 +909,18 @@ def node_type_legend(indent: str = "") -> Text:
return legend
def _nodes_legend() -> Text:
"""The node-type legend, indented to sit under the nodes table body."""
def _contacts_legend() -> Text:
"""The node-type legend, indented to sit under the contacts table body."""
return node_type_legend(indent=" ")
def nodes_table(
def contacts_table(
self_name: str,
self_key: str,
contacts: list[Contact],
prefix_bytes: int,
counts: dict[str, int],
sort: Optional[NodesSort] = None,
sort: Optional[ContactsSort] = None,
) -> Group:
"""List this node and its known contacts with recency, packets, type, key, and legend.
@@ -944,12 +944,12 @@ def nodes_table(
Returns:
A Rich :class:`Group` of the frameless table and its glyph legend.
"""
sort = sort if sort is not None else NodesSort()
sort = sort if sort is not None else ContactsSort()
# expand=True lets the key column (the only flexible one) soak up all spare width and be
# the sole column Rich squeezes when narrow — the fixed columns keep their natural size.
table = Table(
title=f"[accent]Nodes[/accent] [muted]· {len(contacts)} known[/muted]",
title=f"[accent]Contacts[/accent] [muted]· {len(contacts)} known[/muted]",
title_justify="left",
box=box.SIMPLE_HEAD,
show_edge=False,
@@ -993,7 +993,7 @@ def nodes_table(
Text(str(pkts), style="muted") if pkts else Text("—", style="faint"),
highlighted_hash(c.public_key, prefix_bytes) if c.public_key else unknown,
)
return Group(table, Text(""), _nodes_legend())
return Group(table, Text(""), _contacts_legend())
def tx_opt_table(result: TxOptResult) -> Table:
+9 -9
View File
@@ -115,7 +115,7 @@ def test_store_caps_the_finished_history(tmp_path: Path) -> None:
def test_eligibility_waits_for_freshness_and_schedule(tmp_path: Path) -> None:
"""Plain entries need the node heard; scheduled ones hold until their time."""
"""Plain entries need the contact heard; scheduled ones hold until their time."""
service = _service(tmp_path, [])
store = service._ctx.courier_store
now = utcnow()
@@ -135,7 +135,7 @@ def test_eligibility_waits_for_freshness_and_schedule(tmp_path: Path) -> None:
def test_eligibility_backs_off_after_failures(tmp_path: Path) -> None:
"""A failed attempt waits out its (doubling) backoff even when the node is fresh."""
"""A failed attempt waits out its (doubling) backoff even when the contact is fresh."""
service = _service(tmp_path, [])
store = service._ctx.courier_store
now = utcnow()
@@ -462,7 +462,7 @@ def test_outbox_rows_recompute_live_state_per_repaint(tmp_path: Path) -> None:
ctx = _outbox_ctx(tmp_path)
entry = ctx.courier_store.queue(NODE, "YUL", "patience")
screen = CourierOutboxScreen(ctx)
assert "waiting to hear the node" in _outbox_plain(screen)
assert "waiting to hear the contact" in _outbox_plain(screen)
# An attempt just happened: the same row now shows the retry countdown —
# no refresh() needed, the callable title re-reads the entry on repaint.
@@ -476,8 +476,8 @@ def test_outbox_rows_recompute_live_state_per_repaint(tmp_path: Path) -> None:
def test_recipient_picker_rides_the_shared_node_list(tmp_path: Path) -> None:
"""The picker draws the full lanes, opens freshest-heard first, and Enter commits."""
from meshterm.ui.courier_screen import _PICK_HINT, CourierRecipientScreen
from meshterm.ui.nodelist import SORT_COLUMNS, SORT_OPENS_ASCENDING
from meshterm.ui.widgets import NodesSort
from meshterm.ui.contactlist import SORT_COLUMNS, SORT_OPENS_ASCENDING
from meshterm.ui.widgets import ContactsSort
fresh = Contact(name="Fresh", public_key="aa" * 32, last_seen=utcnow())
stale = Contact(
@@ -488,7 +488,7 @@ def test_recipient_picker_rides_the_shared_node_list(tmp_path: Path) -> None:
contacts=[stale, fresh],
prefix_bytes=1,
counts=counts,
sort=NodesSort.from_name("heard", SORT_COLUMNS, SORT_OPENS_ASCENDING),
sort=ContactsSort.from_name("heard", SORT_COLUMNS, SORT_OPENS_ASCENDING),
)
import re
@@ -510,12 +510,12 @@ def test_recipient_picker_rides_the_shared_node_list(tmp_path: Path) -> None:
def test_recipient_picker_sort_keys_walk_the_ring(tmp_path: Path) -> None:
"""The same ^←→ keys the Nodes list uses re-sort the picker's columns."""
from meshterm.ui.courier_screen import CourierRecipientScreen
from meshterm.ui.nodelist import SORT_COLUMNS, SORT_OPENS_ASCENDING
from meshterm.ui.widgets import NodesSort
from meshterm.ui.contactlist import SORT_COLUMNS, SORT_OPENS_ASCENDING
from meshterm.ui.widgets import ContactsSort
a = Contact(name="Alpha", public_key="aa" * 32, last_seen=utcnow())
z = Contact(name="Zulu", public_key="bb" * 32)
sort = NodesSort.from_name("heard", SORT_COLUMNS, SORT_OPENS_ASCENDING)
sort = ContactsSort.from_name("heard", SORT_COLUMNS, SORT_OPENS_ASCENDING)
screen = CourierRecipientScreen(
contacts=[z, a], prefix_bytes=0, counts={}, sort=sort
)
+32 -32
View File
@@ -102,27 +102,27 @@ def test_highlighted_hash_truncates_on_a_byte_boundary() -> None:
assert highlighted_hash(pub, prefix_bytes=1, width=15).plain == "ab" * 7 + "…"
def _nodes_names(counts, sort: str, prefix_bytes: int = 3):
"""Render a nodes table for ``sort`` and return (table, name-column plain text)."""
def _contacts_names(counts, sort: str, prefix_bytes: int = 3):
"""Render a contacts table for ``sort`` and return (table, name-column plain text)."""
from meshterm.core.models import Contact
from meshterm.ui.widgets import NodesSort, nodes_table
from meshterm.ui.widgets import ContactsSort, contacts_table
contacts = [
Contact(name="Bob", public_key="9f1a2b" + "00" * 29, key_prefix="9f1a2b"),
Contact(name="Alice", public_key="3d63c6" + "00" * 29, key_prefix="3d63c6"),
]
group = nodes_table(
"Homestead", "aabbcc" + "00" * 29, contacts, prefix_bytes, counts, NodesSort.from_name(sort)
group = contacts_table(
"Homestead", "aabbcc" + "00" * 29, contacts, prefix_bytes, counts, ContactsSort.from_name(sort)
)
table = group.renderables[0] # (table, blank line, legend)
names = [c.plain if hasattr(c, "plain") else str(c) for c in table.columns[1].cells]
return table, names
def test_nodes_table_lists_us_first_with_full_keys() -> None:
"""The nodes table pins our node first, sorts by name, and shows full highlighted keys."""
def test_contacts_table_lists_us_first_with_full_keys() -> None:
"""The contacts table pins our node first, sorts by name, and shows full highlighted keys."""
counts = {"3d63c6000000": 14} # Alice was overheard; Bob wasn't
table, names = _nodes_names(counts, sort="name")
table, names = _contacts_names(counts, sort="name")
# Column 1 is the name; us first, then contacts alphabetically (Alice before Bob).
assert names[0].startswith("Homestead")
@@ -144,7 +144,7 @@ def test_nodes_table_lists_us_first_with_full_keys() -> None:
assert any(s.style == node_style("3d63c6") for s in keys[1].spans)
def test_nodes_table_sorts_by_heard_and_packets() -> None:
def test_contacts_table_sorts_by_heard_and_packets() -> None:
"""Non-default sorts reorder contacts while keeping our node pinned first."""
from datetime import timedelta
@@ -166,27 +166,27 @@ def test_nodes_table_sorts_by_heard_and_packets() -> None:
),
]
counts = {"3d63c6000000": 14, "9f1a2b000000": 3}
from meshterm.ui.widgets import NodesSort, nodes_table
from meshterm.ui.widgets import ContactsSort, contacts_table
def names(sort: NodesSort):
group = nodes_table("Us", "aabbcc" + "00" * 29, contacts, 3, counts, sort)
def names(sort: ContactsSort):
group = contacts_table("Us", "aabbcc" + "00" * 29, contacts, 3, counts, sort)
cells = group.renderables[0].columns[1].cells
return [c.plain if hasattr(c, "plain") else str(c) for c in cells]
# Freshest first: Bob (5m) before Alice (2d) under the default (ascending-age) heard sort.
assert names(NodesSort.from_name("heard"))[1:] == ["Bob", "Alice"]
assert names(ContactsSort.from_name("heard"))[1:] == ["Bob", "Alice"]
# Most packets first: Alice (14) before Bob (3) under the default (descending) packets sort.
assert names(NodesSort.from_name("packets"))[1:] == ["Alice", "Bob"]
assert names(ContactsSort.from_name("packets"))[1:] == ["Alice", "Bob"]
# Descending flips it: oldest-heard first puts Alice (2d) above Bob (5m).
assert names(NodesSort(column="heard", ascending=False))[1:] == ["Alice", "Bob"]
assert names(ContactsSort(column="heard", ascending=False))[1:] == ["Alice", "Bob"]
def test_nodes_table_breaks_metric_ties_by_name_ascending() -> None:
"""Two nodes with the same metric keep an A→Z order in both sort directions (no flip)."""
def test_contacts_table_breaks_metric_ties_by_name_ascending() -> None:
"""Two contacts with the same metric keep an A→Z order in both sort directions (no flip)."""
from datetime import timedelta
from meshterm.core.models import Contact, utcnow
from meshterm.ui.widgets import NodesSort, _ordered_contacts
from meshterm.ui.widgets import ContactsSort, _ordered_contacts
same = utcnow() - timedelta(minutes=5)
contacts = [
@@ -196,29 +196,29 @@ def test_nodes_table_breaks_metric_ties_by_name_ascending() -> None:
]
def order(ascending: bool) -> list[str]:
sort = NodesSort(column="heard", ascending=ascending)
sort = ContactsSort(column="heard", ascending=ascending)
return [c.name for c in _ordered_contacts(contacts, {}, sort)]
# Freshest first: the two 5-min nodes lead, ordered Alice→Charlie, then Bob (3h).
# Freshest first: the two 5-min contacts lead, ordered Alice→Charlie, then Bob (3h).
assert order(ascending=True) == ["Alice", "Charlie", "Bob"]
# Oldest first: Bob leads, but the tie still breaks Alice→Charlie — not Charlie→Alice.
assert order(ascending=False) == ["Bob", "Alice", "Charlie"]
def _nodes_sort(name: str = "name"):
"""The interactive Nodes screen's sort: the shared node list's four-column ring."""
from meshterm.ui.nodelist import SORT_COLUMNS, SORT_OPENS_ASCENDING
from meshterm.ui.widgets import NodesSort
def _contacts_sort(name: str = "name"):
"""The interactive Contacts screen's sort: the shared contact list's four-column ring."""
from meshterm.ui.contactlist import SORT_COLUMNS, SORT_OPENS_ASCENDING
from meshterm.ui.widgets import ContactsSort
return NodesSort.from_name(name, SORT_COLUMNS, SORT_OPENS_ASCENDING)
return ContactsSort.from_name(name, SORT_COLUMNS, SORT_OPENS_ASCENDING)
def test_nodes_screen_ctrl_arrows_steer_the_sort() -> None:
def test_contacts_screen_ctrl_arrows_steer_the_sort() -> None:
"""Ctrl+←/→ walk the shared four-column ring (wrapping); Ctrl+↑/↓ force the direction —
the Time Machine picker's keys, now the Nodes screen's too."""
from meshterm.ui.nodes_screen import NodesScreen
the Time Machine picker's keys, now the Contacts screen's too."""
from meshterm.ui.contacts_screen import ContactsScreen
screen = NodesScreen("Us", "aabbcc" + "00" * 29, [], 3, {}, _nodes_sort())
screen = ContactsScreen("Us", "aabbcc" + "00" * 29, [], 3, {}, _contacts_sort())
assert (screen._sort.column, screen._sort.ascending) == ("name", True)
screen.handle("ctrl_right") # name -> heard, opening in its natural (ascending) direction
@@ -237,13 +237,13 @@ def test_nodes_screen_ctrl_arrows_steer_the_sort() -> None:
assert screen._sort.column == "hash"
def test_nodes_screen_lists_contacts_in_the_shared_lanes() -> None:
def test_contacts_screen_lists_contacts_in_the_shared_lanes() -> None:
"""Contacts render in the shared NAME/HEARD/PKTS/KEY lanes, our node pinned first;
plain arrows only move the highlight, and Enter is inert (selection comes later)."""
import re
from meshterm.core.models import Contact, utcnow
from meshterm.ui.nodes_screen import YOU, NodesScreen
from meshterm.ui.contacts_screen import YOU, ContactsScreen
from meshterm.ui.tui.screen import CANCEL
contacts = [
@@ -251,7 +251,7 @@ def test_nodes_screen_lists_contacts_in_the_shared_lanes() -> None:
Contact(name="Bob", public_key="bb" * 32),
]
counts = {"aa" * 6: 7} # Alice was overheard; Bob never
screen = NodesScreen("Us", "cc" * 32, contacts, 1, counts, _nodes_sort())
screen = ContactsScreen("Us", "cc" * 32, contacts, 1, counts, _contacts_sort())
body = "\n".join(re.sub(r"\x1b\[[0-9;]*m", "", ln) for ln in screen.render_body(72))
# The shared column header (recorded sticky, so it pins once scrolled past)...
+1 -1
View File
@@ -58,7 +58,7 @@ def test_livefeed_tool_registers_under_the_dashboard() -> None:
tools = {t.name: t for t in all_tools()}
tool = tools["livefeed"]
assert tool.title == "Live feed" and tool.category == "Mesh"
assert tools["dashboard"].order < tool.order < tools["nodes"].order
assert tools["dashboard"].order < tool.order < tools["contacts"].order
def test_livefeed_live_events_land_in_the_feed() -> None:
+20 -20
View File
@@ -597,15 +597,15 @@ def test_picker_row_lanes_align_under_the_header() -> None:
"""Picker rows lane up under the header; the heard age glows hot, the hash prefix
lights in the key's own hue, and a nameless node's placeholder stays muted."""
from meshterm.core.models import HeardNode
from meshterm.ui.nodelist import NodeRow, _header, _lane
from meshterm.ui.widgets import NodesSort
from meshterm.ui.contactlist import ContactRow, _header, _lane
from meshterm.ui.widgets import ContactsSort
node = HeardNode(
node="3d" * 6, name=None, count=42, median_snr=None, best_snr=None,
last_rssi=None, last_seen=utcnow(),
)
row = _lane(
NodeRow(
ContactRow(
value=node.node, name=node.name, key=node.node or "",
last_seen=node.last_seen, count=node.count,
),
@@ -631,7 +631,7 @@ def test_picker_row_lanes_align_under_the_header() -> None:
)
# Header labels land over their lanes (+2 covers the select pointer column); the lanes
# now read NAME · HEARD · PKTS · KEY, with the key closing the row.
header = _header(10, NodesSort.from_name("heard")).plain
header = _header(10, ContactsSort.from_name("heard")).plain
assert header.index("NAME") == plain.index("unknown") + 2
assert header.index("KEY") == plain.index("3d" * 6) + 2
assert header.index("HEARD") < header.index("PKTS") < header.index("KEY")
@@ -639,27 +639,27 @@ def test_picker_row_lanes_align_under_the_header() -> None:
def test_picker_header_marks_the_active_sort_column() -> None:
"""The sort column carries a direction triangle; toggling flips ▲/▼, and only it."""
from meshterm.ui.nodelist import _header
from meshterm.ui.widgets import NodesSort
from meshterm.ui.contactlist import _header
from meshterm.ui.widgets import ContactsSort
heard_desc = _header(12, NodesSort("heard", ascending=False)).plain
heard_desc = _header(12, ContactsSort("heard", ascending=False)).plain
assert "HEARD ▼" in heard_desc and "▲" not in heard_desc
# Ascending flips the same column's glyph without touching the others.
assert "HEARD ▲" in _header(12, NodesSort("heard", ascending=True)).plain
assert "HEARD ▲" in _header(12, ContactsSort("heard", ascending=True)).plain
# A different active column moves the mark; packets opens descending.
packets = _header(12, NodesSort.from_name("packets")).plain
packets = _header(12, ContactsSort.from_name("packets")).plain
assert "PKTS ▼" in packets and "HEARD" in packets and "HEARD ▼" not in packets
# The key column (ring id "hash") is sortable too, so it carries the mark when active.
hash_sorted = _header(12, NodesSort("hash", ascending=True)).plain
hash_sorted = _header(12, ContactsSort("hash", ascending=True)).plain
assert "KEY ▲" in hash_sorted and "PKTS ▲" not in hash_sorted
def test_picker_header_highlights_only_the_active_sort_column() -> None:
"""The active column's label and its triangle are lit cyan; the other lanes stay muted."""
from meshterm.ui.nodelist import _SORT_ACTIVE, _header
from meshterm.ui.widgets import NodesSort
from meshterm.ui.contactlist import _SORT_ACTIVE, _header
from meshterm.ui.widgets import ContactsSort
header = _header(12, NodesSort.from_name("packets"))
header = _header(12, ContactsSort.from_name("packets"))
lit = [header.plain[s.start:s.end] for s in header.spans if s.style == _SORT_ACTIVE]
# Exactly the active PKTS lane (label + triangle) carries the highlight.
assert any("PKTS" in seg and "▼" in seg for seg in lit)
@@ -668,11 +668,11 @@ def test_picker_header_highlights_only_the_active_sort_column() -> None:
def _picker(listed, *, prefix_bytes=0, sort=None, type_of=None, resolve_key=None, width=80):
"""Build a rendered picker over ``listed`` and return it (rows sized to ``width``)."""
from meshterm.ui.nodelist import SORT_COLUMNS, SORT_OPENS_ASCENDING
from meshterm.ui.contactlist import SORT_COLUMNS, SORT_OPENS_ASCENDING
from meshterm.ui.timemachine_screen import TimeMachinePickerScreen
from meshterm.ui.widgets import NodesSort
from meshterm.ui.widgets import ContactsSort
default_sort = NodesSort.from_name("heard", SORT_COLUMNS, SORT_OPENS_ASCENDING)
default_sort = ContactsSort.from_name("heard", SORT_COLUMNS, SORT_OPENS_ASCENDING)
screen = TimeMachinePickerScreen(
listed=listed,
prefix_bytes=prefix_bytes,
@@ -816,7 +816,7 @@ 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.nodelist import _LEAD
from meshterm.ui.contactlist import _LEAD
screen = _picker(_heard_nodes(), width=72)
# The widest name here is the "unknown" fallback (7 cells); the lane sizes to it.
@@ -966,11 +966,11 @@ def test_self_sections_render_the_page_and_empty_window(tmp_path: Path) -> None:
def test_self_row_leads_the_node_list_as_a_lane() -> None:
"""The own-node lane shows our name + (you), faint — for heard/pkts, and our key hash."""
from meshterm.ui.nodelist import NodeRow, _lane
from meshterm.ui.contactlist import ContactRow, _lane
from meshterm.ui.timemachine_screen import SELF
named = _lane(
NodeRow(value=SELF, name="YUL-Johputer", key="3d" * 32, you=True),
ContactRow(value=SELF, name="YUL-Johputer", key="3d" * 32, you=True),
name_w=30, prefix_bytes=1, hash_w=30,
).plain
assert named.startswith("★")
@@ -979,7 +979,7 @@ def test_self_row_leads_the_node_list_as_a_lane() -> None:
assert "3d3d" in named # our key hash, its routing prefix lit
# No reachable device: a bare "you" name and a "?" hash, no "(you)" tag.
anon = _lane(
NodeRow(value=SELF, name=None, key="", you=True),
ContactRow(value=SELF, name=None, key="", you=True),
name_w=30, prefix_bytes=0, hash_w=30,
).plain
assert "you" in anon and "(you)" not in anon