Contacts: a contact is dropped one at a time, from its own page

The list could only sweep contacts by age — a purge or nothing. Removing one
named contact now lives where the reader is already looking at it: the last
action on its Node detail page, behind a red Cancel/Remove confirm, and the
list it returns to rebuilds without the row.

The deletion lands in both halves of what the list shows — the device's table
and the cross-session store — because forgetting only the radio's half merges
the contact straight back on the next read. A refusal is put in a dialog and
nothing is forgotten: a contact the radio still holds must not vanish from the
list. Only the contact goes; its reception history and chat messages stay, and
a later send offers to write it back.

An action row's tint now survives the icon lane being dropped — it lands on the
label, as marked_label already does for menu rows — so the delete still reads
as a delete on the PicoCalc.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5 committed 2026-08-26 01:39:22 -04:00
1 parent c66e2c86b6
commit 80a2a9bd0b
5 files changed
+387 -17

No files matched your search

+21 -10
View File
@@ -10,13 +10,18 @@ and backing out of that page returns to the list right where it stood. The one-s
(``meshterm contacts --sort …``) still renders the static
:func:`~meshterm.ui.widgets.contacts_table`; only the menu gets the live list.
Below the contacts sits one maintenance action — **Purge stale contacts** — that sweeps out
the contacts a device has accumulated but no longer hears. It offers an age ladder (a day up
to a year, plus a *never heard* bucket), each rung showing a live count of how many contacts
it would remove, so the impact is visible before anything is chosen; the pick is then gated
behind a typed ``delete`` confirm. A purge deletes the contacts from the device's table and
forgets them from the cross-session store (see :mod:`~meshterm.core.contact_store`) so a
firmware-less bridge doesn't merge them back — but only the *contact* is dropped: each node's
Removing *one* named contact belongs to that contact, not to the list: it is the last
action on its Node detail page (see :mod:`~meshterm.ui.node_detail_screen`), where the
reader is already looking at the node they mean to drop. The list only rebuilds afterwards.
Below the contacts sits the list's own maintenance action — **Purge stale contacts** — the
bulk counterpart, sweeping out the contacts a device has accumulated but no longer hears. It
offers an age ladder (a day up to a year, plus a *never heard* bucket), each rung showing a
live count of how many contacts it would remove, so the impact is visible before anything is
chosen; the pick is then gated behind a typed ``delete`` confirm. Either way — one contact
or a sweep — the removal lands in both halves of what the list shows: the device's own
table, and the cross-session store (see :mod:`~meshterm.core.contact_store`), so a
firmware-less bridge doesn't merge them back. Only the *contact* is dropped: each node's
reception history and overheard traffic in MeshTerm are untouched. Our own node, pinned above
the list, is never a purge candidate (it isn't in the device's contact table).
"""
@@ -174,8 +179,9 @@ async def open_contacts(
Runs the show/open/reshow loop: the sortable list, then whichever node's detail page
Enter commits (or the purge flow the tail action opens), then the list again (same sort,
the highlight kept on its row) — until Esc, or the ``Back`` row, backs out of the list
itself. A purge that removes anything re-reads the device and rebuilds the list so the
swept contacts are gone from it.
itself. Anything that removes a contact — a purge here, or the detail page's own
single-contact ``Remove contact…`` — re-reads the device and rebuilds the list, so the
contacts that went are gone from it.
Args:
ctx: Shared application context (must be in the interactive menu).
@@ -219,7 +225,12 @@ async def open_contacts(
)
continue
# The own-node sentinel opens our own node's page; any other value is a Contact.
await open_node_detail(ctx, None if chosen == YOU else chosen)
# The page 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.
if await open_node_detail(ctx, None if chosen == YOU else chosen):
contacts = await ctx.devstate.contacts()
screen = ContactsScreen(self_name, self_key, contacts, prefix_bytes, counts, sort)
async def _purge_stale(ctx: "AppContext", self_key: str) -> int:
+113 -6
View File
@@ -21,9 +21,14 @@ the node itself, in full:
static basemap preview (see :class:`~meshterm.ui.minimap.MiniMap`) centred on the node,
grown to whatever rows the viewport spares. Its actions: ``Open full map`` (the full
map opens centred here with its find filter seeded to this node, so it lights among
the rest), ``Time machine``, and ``Share contact`` — a popup contact card (QR code +
the rest), ``Time machine``, ``Share contact`` — a popup contact card (QR code +
``meshcore://`` link, see :func:`~meshterm.ui.config_editor.show_contact_card`),
offered whenever the node's full key is known.
offered whenever the node's full key is known — and, last, ``Remove contact``: the
single-contact counterpart to the Contacts list's bulk purge (see
:mod:`~meshterm.ui.contacts_screen`), dropping *this* node from the device's contact
table behind a red confirm. It is the one thing on the page that changes anything, so
it sits at the foot of the actions, and committing it closes the page — the contact it
details no longer exists to detail.
* **Routes** — the routes we've actually heard the node arrive over, drawn on the shared
route graph (:mod:`~meshterm.ui.pathgraph`) node→us (the inbound direction the packets
travelled, contact on the left, us on the right), each relay tagged by its first hash
@@ -1045,11 +1050,15 @@ class NodeDetailScreen(Screen):
"""One action row: ``❯`` + icon + label, the whole row lit when it is the cursor's."""
text = Text("❯ " if selected else " ", style="cursor" if selected else "")
# The icon lane is decoration a platform may drop whole (command_icon); the label
# is what names the action, so an emptied lane simply gives it the cells.
# is what names the action, so an emptied lane simply gives it the cells. A tinted
# icon carries a claim the decoration can't take with it, though — a red 🗑 is how a
# destructive row announces itself — so where the lane goes, the tint lands on the
# label instead. Same move as :func:`~meshterm.ui.menus.marked_label` makes for a
# menu row, for the same reason: a delete must not read like any other action.
mark = command_icon(action.glyph) if action.glyph else ""
if mark:
text.append(f"{mark} ", style=action.glyph_style)
text.append(action.label)
text.append(action.label, style="" if mark else action.glyph_style)
if selected:
text.style = "cursor"
text.no_wrap = True
@@ -1126,20 +1135,25 @@ def _located(lat: Optional[float], lon: Optional[float]) -> bool:
# -- data gathering + the action loop -----------------------------------------
async def open_node_detail(ctx: "AppContext", contact: Optional["Contact"]) -> None:
async def open_node_detail(ctx: "AppContext", contact: Optional["Contact"]) -> 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.
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.
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).
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.
Raises:
RuntimeError: If called outside the interactive menu (no full-screen session).
"""
@@ -1344,6 +1358,11 @@ async def open_node_detail(ctx: "AppContext", contact: Optional["Contact"]) -> N
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"))
# 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…"))
try:
adv_type = int(node_type) if node_type is not None else 1
except (TypeError, ValueError):
@@ -1356,6 +1375,8 @@ async def open_node_detail(ctx: "AppContext", contact: Optional["Contact"]) -> N
tail_actions = [_Action("back", "", "", "Back")]
title = f"Node — {label}" if not you else f"Node — {label} (you)"
# Whether the visit ended by deleting the contact — the caller's cue to rebuild its list.
contact_removed = False
while True:
screen = NodeDetailScreen(
title=title,
@@ -1395,11 +1416,97 @@ async def open_node_detail(ctx: "AppContext", contact: Optional["Contact"]) -> N
await open_timemachine_self(ctx)
else:
await open_timemachine_node(ctx, node_id, label)
elif action == "remove":
# The confirm floats over this page (run_screen just popped it), so re-push it
# as the backdrop for the dialog's lifetime — the reader confirms against the
# node they are looking at. A removal ends the visit: there is no contact left
# to detail, and the list we return to rebuilds without it.
assert contact is not None # the row only exists for a real contact
session.push(screen)
try:
contact_removed = await _remove_contact(ctx, contact, self_key, label)
finally:
session.pop(screen)
if contact_removed:
break
if minimap is not None:
# The preview's braille may have smeared the terminal (double-width fallback
# glyphs prompt_toolkit's diff can't see); force one clean repaint of the list
# underneath, exactly as the full map does on the way out.
session.request_full_repaint()
return contact_removed
async def _remove_contact(
ctx: "AppContext", contact: "Contact", self_key: str, label: str
) -> bool:
"""Confirm and drop one contact from the device; ``True`` once it is gone.
The single-contact counterpart to the Contacts list's bulk purge (see
:func:`~meshterm.ui.contacts_screen._purge_stale`), and it removes the contact in the
same two places, because the list a screen sees is the *union* of the two: the device's
own contact table, and the contacts MeshTerm remembers for that device (see
:mod:`meshterm.core.contact_store`). Forget only the first and the store merges the
contact straight back on the next read, so the deletion would look like a screen that
did nothing.
Only the *contact* goes. The node's reception history, its overheard traffic and the
chat messages exchanged with it are all MeshTerm's own and are untouched — what is lost
is the device's ability to address it, which is why a chat send to a contact the
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.
Args:
ctx: The shared application context (interactive menu; the page is pushed as the
confirm's backdrop by the caller).
contact: The contact to delete, 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 removed, ``False`` if the user cancelled or the device
refused (the refusal is shown, never swallowed — a contact still on the radio must
not vanish from the list).
"""
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"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",
default=1,
destructive=True,
):
return False
device = await ctx.device()
try:
await device.remove_contact(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"
)
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.forget(dev_pub, contact.public_key)
# The device's table just changed under the session cache; the list we return to re-reads.
ctx.devstate.invalidate_contacts()
# No success notice: unlike the purge — whose outcome is a count nobody could predict —
# this one is self-evident. The page closes on the contact it detailed and the list
# behind it comes back without the row, which says it better than a dialog to dismiss.
return True
def _signal_row(hn) -> Optional[Text]: # noqa: ANN001 - Optional[HeardNode]
+202
View File
@@ -418,6 +418,145 @@ async def test_purge_sweeps_under_a_progress_bar_and_reports_in_a_dialog() -> No
assert removed_from_device == ["Old0", "Old1", "Old2"]
async def test_removing_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
MeshTerm remembers for that device, so a removal that only reached the radio would be
merged straight back on the next read and read as a screen that did nothing. It also
drops the cached contacts so the list it returns to actually re-reads.
"""
import logging
from types import SimpleNamespace
from meshterm.core.models import Contact
from meshterm.ui.node_detail_screen import _remove_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] = []
forgotten: 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 # the committing button
ui.dialog = _dialog # type: ignore[method-assign]
ctx = SimpleNamespace(
ui=ui,
log=logging.getLogger("test.remove"),
contact_store=SimpleNamespace(
forget=lambda dev, key: forgotten.append((dev, key))
),
devstate=SimpleNamespace(invalidate_contacts=lambda: invalidated.append(True)),
device=lambda: _device(_Device()),
)
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.
assert asked[0]["destructive"] is True
assert [label for label, _v in asked[0]["buttons"]] == ["Cancel", "Remove"]
assert asked[0]["default"] == 1
assert "Hub" in asked[0]["prompt"] and "history" in asked[0]["prompt"]
# Both halves of the union, then the cache the list re-reads through.
assert removed == ["Hub"]
assert forgotten == [("cc" * 32, "3d" * 32)]
assert invalidated == [True]
async def test_cancelling_the_remove_confirm_touches_nothing() -> None:
"""Esc/Cancel on the confirm leaves the contact on the device and the caller's list."""
import logging
from types import SimpleNamespace
from meshterm.core.models import Contact
from meshterm.ui.node_detail_screen import _remove_contact
from meshterm.ui.surface import TuiUi
from meshterm.ui.tui.session import TuiSession
touched: list[str] = []
class _Device:
async def remove_contact(self, contact) -> None: # noqa: ANN001
touched.append(contact.name)
ui = TuiUi(TuiSession())
async def _declined(*a, **k): # noqa: ANN001, ANN002, ANN003
return None # what Esc resolves a button dialog to
ui.dialog = _declined # type: ignore[method-assign]
ctx = SimpleNamespace(
ui=ui,
log=logging.getLogger("test.remove"),
contact_store=SimpleNamespace(forget=lambda *a: touched.append("forgot")),
devstate=SimpleNamespace(invalidate_contacts=lambda: touched.append("invalidated")),
device=lambda: _device(_Device()),
)
assert await _remove_contact(ctx, Contact(name="Hub", public_key="3d" * 32), "cc" * 32,
"Hub") is False
assert touched == []
async def test_a_refused_removal_is_shown_and_the_contact_stays() -> None:
"""A device that refuses is reported in a dialog — the row must not vanish on a lie.
Only the *device* can drop a contact from its table; if it refuses, forgetting our own
half of the union would hide a contact the radio still holds. So nothing is forgotten,
the failure is put in front of the reader, and the page stays open on the node.
"""
import asyncio
import logging
from types import SimpleNamespace
from meshterm.core.models import Contact
from meshterm.ui.node_detail_screen import _remove_contact
from meshterm.ui.surface import TuiUi
from meshterm.ui.tui.session import TuiSession
forgotten: list = []
class _Device:
async def remove_contact(self, contact) -> None: # noqa: ANN001
await asyncio.sleep(0)
raise RuntimeError("contact table is busy")
session = TuiSession()
ui = TuiUi(session)
async def _accepted(*a, **k): # noqa: ANN001, ANN002, ANN003
return True
ui.dialog = _accepted # type: ignore[method-assign]
ctx = SimpleNamespace(
ui=ui,
log=logging.getLogger("test.remove"),
contact_store=SimpleNamespace(forget=lambda *a: forgotten.append(a)),
devstate=SimpleNamespace(invalidate_contacts=lambda: forgotten.append("cache")),
device=lambda: _device(_Device()),
)
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))
assert "contact table is busy" in _screen_text(failed)
failed.handle("escape")
assert await task is False
assert forgotten == [] # the device still holds it, so neither do we forget it
async def _true() -> bool:
return True
@@ -452,6 +591,69 @@ async def _step_until_screen(session, predicate, *, limit: int = 500): # noqa:
raise AssertionError("the expected screen never reached the top of the stack")
async def test_the_list_rebuilds_when_the_detail_page_deletes_the_contact(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A contact removed on its own page is gone from the list you come back to.
The detail page is where a single contact is deleted, so the list has to be told: it
hands the page a contact and takes back whether that contact survived, re-reading the
device and rebuilding when it didn't. Without the rebuild the reader returns to a row
for a contact the radio no longer holds.
"""
import asyncio
import logging
from types import SimpleNamespace
from meshterm.core.models import Contact
from meshterm.ui import node_detail_screen
from meshterm.ui.contacts_screen import ContactsScreen, open_contacts
from meshterm.ui.surface import TuiUi
from meshterm.ui.tui.session import TuiSession
alice = Contact(name="Alice", public_key="aa" * 32)
bob = Contact(name="Bob", public_key="bb" * 32)
remaining = [alice, bob]
detailed: list = []
async def _fake_detail(ctx, contact): # noqa: ANN001
"""Stand in for the page: report that it deleted whichever contact it was handed."""
detailed.append(contact)
remaining.remove(contact)
return True
monkeypatch.setattr(node_detail_screen, "open_node_detail", _fake_detail)
session = TuiSession()
ctx = SimpleNamespace(
ui=TuiUi(session),
log=logging.getLogger("test.contacts"),
contact_store=None,
devstate=SimpleNamespace(contacts=lambda: _contacts(remaining)),
)
task = asyncio.ensure_future(
open_contacts(ctx, "Us", "cc" * 32, list(remaining), 1, {}, _contacts_sort())
)
listed = await _step_until_screen(session, lambda s: isinstance(s, ContactsScreen))
assert "2 known" in listed.title
listed.handle("down") # off our own node, onto the first contact
listed.handle("enter")
# The page deleted it, so the list that comes back is a *new* one, re-read without it.
rebuilt = await _step_until_screen(
session, lambda s: isinstance(s, ContactsScreen) and "1 known" in s.title
)
assert rebuilt is not listed
assert detailed == [alice]
assert "Alice" not in _screen_text(rebuilt)
assert "Bob" in _screen_text(rebuilt)
rebuilt.handle("escape")
await task
def test_contacts_screen_tail_offers_purge_only_when_populated() -> None:
"""A populated list closes with the purge action + Back; an empty one has no tail action."""
from meshterm.core.models import Contact
+7 -1
View File
@@ -175,7 +175,13 @@ def _node_detail(cols: int, rows: int) -> Screen:
minimap=None,
map_caption=None,
routes=_RoutesView(note="no route observed yet — trace to discover one"),
info_actions=[_Action("timemachine", "⏳", "", "Time machine — 42 receptions")],
info_actions=[
_Action("timemachine", "⏳", "", "Time machine — 42 receptions"),
# The page's destructive row: here so the specimen shows how a delete reads
# on each platform — a red 🗑 on the desktop, the tint on the words where
# the PicoCalc drops the icon lane.
_Action("remove", "🗑", "err", "Remove contact…"),
],
trace_action=_Action("trace", "\U0001f3af", "", "Trace — auto route …"),
tail_actions=[_Action("back", "", "", "Back")],
)
+44
View File
@@ -546,6 +546,50 @@ def test_node_detail_screen_renders_its_sections() -> None:
assert len(screen.footer_hint) <= 72
def test_the_remove_row_is_tinted_and_keeps_its_tint_where_the_icon_lane_goes() -> None:
"""The destructive action announces itself in ``err`` on both platforms.
On the desktop that is the red 🗑 leading the row. On the PicoCalc the icon lane is
dropped whole (``command_icon`` returns ``""``), and a tint that left with the
decoration would leave a delete row reading like any other — so it lands on the label,
exactly as :func:`~meshterm.ui.menus.marked_label` does for a menu row.
"""
import re
from meshterm.platforms import PICOCALC, set_platform
remove = _Action("remove", "🗑", "err", "Remove contact…")
screen = _screen(info_actions=[remove])
screen.note_viewport(30)
line = screen._action_line(remove, selected=False, width=40)
assert "🗑" in line and "Remove contact…" in _plain([line])
set_platform(PICOCALC)
screen = _screen(info_actions=[remove])
screen.note_viewport(30)
folded = screen._action_line(remove, selected=False, width=40)
assert "🗑" not in folded # the icon lane is gone...
assert "Remove contact" in _plain([folded])
# ...and the tint it carried is now on the words: the label is opened by a colour
# sequence, where an untinted action's label is opened by nothing at all.
assert re.search(r"\[[0-9;]*m *Remove contact", folded)
plain_row = screen._action_line(
_Action("timemachine", "⏳", "", "Time machine — 42 receptions"), False, 40
)
assert not re.search(r"\[[0-9;]*m *Time machine", plain_row)
def test_the_remove_row_resolves_its_own_token() -> None:
"""Enter on the remove row hands ``open_node_detail`` the token it deletes on."""
screen = _screen(info_actions=[_Action("remove", "🗑", "err", "Remove contact…")])
resolved: list = []
screen.resolve = lambda value: resolved.append(value) # type: ignore[method-assign]
screen.note_viewport(30)
screen.render_body(72)
screen.handle("enter")
assert resolved == ["remove"]
def test_node_detail_screen_cursor_and_commit() -> None:
"""↑/↓ move the cursor (kept in view); Enter resolves its key, Esc cancels."""
screen = _screen()