A contact can be locked against archiving

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5 committed 2026-09-16 23:35:59 -04:00
1 parent 8076ac1081
commit d38aca6c3c
14 files changed
+451 -83

No files matched your search

+6
View File
@@ -17,6 +17,12 @@ allowed to change behaviour, not just add to it.
## [Unreleased]
- **A contact can be locked.** Lock contact on a contact's page keeps it from ever being
archived: the archive sweep counts it protected, and the page hides Archive until you
unlock it. Locked contacts show a padlock at the end of their name in the Contacts list —
🔒, or the console font's own padlock on the PicoCalc. The lock is kept by MeshTerm, not
the radio, and reading the device never clears it.
- **Purge contacts is Archive contacts**, because archiving is what it does: every contact
it takes off the device stays in MeshTerm and can be restored. The row, its screens, its
confirm button and its progress bar all say Archive, and the row wears the 💾 that
+2 -1
View File
@@ -333,7 +333,8 @@ as a grouped list does. Filling a page in is editing its `.md`; no Python follow
to a whole route). Arrow mode spells the same claim with the separator alone, a leading
or trailing `→` with no hop on the far side of it.
- Concept icons: 📡 advert · 🕒 clock/sync · 🔄 reboot · 💾 backup · 📂 restore ·
🔑 channel/credential key · 🔐 identity/auth secret · 🗑 clear/delete · ✎ compose/edit ·
🔑 channel/credential key · 🔐 identity/auth secret ·
🔒 lock (a locked contact, a private channel) · 🔓 unlock · 🗑 clear/delete · ✎ compose/edit ·
⚙ parameter · `#` count · ▶ run · ⚡ explore/probe · ★ best/winner · ⭐ watch ·
📤 send now · 📨 courier/queue · 💬 chat · 🔔 notify · 🔕 mute (notifications off) ·
📱 QR · 🔗 link · ↻ re-read · ↕ reorder · ⇄ reverse (flip a path's direction) ·
+21 -6
View File
@@ -35,11 +35,11 @@ before this history began) has no arrival time to decay from and is protected ou
rather than being punished for MeshTerm's own ignorance — see :data:`PROTECT_UNOBSERVED`.
**Some contacts are never candidates.** A score is a heuristic and a heuristic must not
overrule an explicit choice, so :func:`protection_for` short-circuits four cases before any
arithmetic: a watched node, anyone you have sent a direct message to, a repeater whose
admin credentials are stored, and the unobserved contact above. They are still scored and
still ranked — they are real contacts and the percentile scale is the whole population —
but they are never swept.
overrule an explicit choice, so :func:`protection_for` short-circuits five cases before any
arithmetic: a contact you locked, a watched node, anyone you have sent a direct message to,
a repeater whose admin credentials are stored, and the unobserved contact above. They are
still scored and still ranked — they are real contacts and the percentile scale is the whole
population — but they are never swept.
**The score is never displayed.** A raw ``47.3`` means nothing without the distribution it
came from. What this module hands a screen instead is a *rank* — the list comes back ordered,
@@ -60,6 +60,10 @@ from statistics import median
from .geo import haversine_km
from .models import Contact
#: Protection reason: the reader locked this contact from its page. The most explicit claim
#: there is — a lock says nothing but "never archive this one" — so it is checked first.
PROTECT_LOCKED = "locked"
#: Protection reason: the node is starred in the Watchtower. An explicit pin outranks every
#: heuristic in this module — the user already said this one matters.
PROTECT_WATCHED = "watched"
@@ -81,10 +85,17 @@ PROTECT_UNOBSERVED = "unobserved"
#: The order protections are reported in when a contact qualifies for several — most
#: deliberate first, so the preview explains a row by the strongest claim on it.
PROTECTION_ORDER = (PROTECT_WATCHED, PROTECT_MESSAGED, PROTECT_ADMIN, PROTECT_UNOBSERVED)
PROTECTION_ORDER = (
PROTECT_LOCKED,
PROTECT_WATCHED,
PROTECT_MESSAGED,
PROTECT_ADMIN,
PROTECT_UNOBSERVED,
)
#: How a protection reads in the UI, keyed by the constants above.
PROTECTION_LABELS = {
PROTECT_LOCKED: "locked",
PROTECT_WATCHED: "watched",
PROTECT_MESSAGED: "you messaged",
PROTECT_ADMIN: "admin login",
@@ -181,6 +192,8 @@ class ContactSignals:
which is what :data:`PROTECT_UNOBSERVED` keys on.
watched: Whether the node is starred in the Watchtower.
has_admin: Whether admin credentials are stored for it.
locked: Whether the reader locked the contact against archiving (see
:meth:`~meshterm.core.contact_store.ContactStore.set_locked`).
"""
node: str
@@ -196,6 +209,7 @@ class ContactSignals:
known_days: float | None = None
watched: bool = False
has_admin: bool = False
locked: bool = False
@dataclass(frozen=True)
@@ -378,6 +392,7 @@ def protection_for(signals: ContactSignals) -> str | None:
One of the ``PROTECT_*`` constants, or ``None``.
"""
claims = {
PROTECT_LOCKED: signals.locked,
PROTECT_WATCHED: signals.watched,
PROTECT_MESSAGED: signals.dm_outbound > 0,
PROTECT_ADMIN: signals.has_admin,
+56 -21
View File
@@ -34,6 +34,13 @@ it back. So a restore is one write, and the chat screen already performs it on d
send is rejected for an unknown recipient (see
:class:`~meshterm.core.connection.ContactNotOnDeviceError`).
A live contact can also be **locked**, which is the reader's own word that it stays: a
locked contact is never a sweep candidate (see
:data:`~meshterm.core.contact_score.PROTECT_LOCKED`) and its page offers no Archive. The flag
lives here rather than on the device because the firmware has no such field — it is
MeshTerm's claim about the contact, kept beside the other one it makes (the archive stamp),
and a device read never clears it.
The one place to be careful is a firmware-less bridge, whose contact table is RAM-only and
for which this store *is* the memory: archiving there removes the contact from the lists for
real, and only a restore brings it back.
@@ -47,7 +54,7 @@ contact set actually changes, and flushes atomically.
from __future__ import annotations
import json
from dataclasses import dataclass
from dataclasses import dataclass, replace
from pathlib import Path
from .atomicwrite import write_atomically
@@ -97,6 +104,9 @@ class RememberedContact:
while it is a live contact. An archived contact is remembered in full but kept
*out* of :func:`merge_contacts`, so it stops occupying a device slot without
being forgotten — and the stamp is what lets a list say how long ago it went.
locked: Whether the reader locked this contact against archiving. MeshTerm's own
state, not the device's, so :meth:`ContactStore.remember_all` carries it across
every fresh read of the contact rather than resetting it.
"""
public_key: str
@@ -106,6 +116,7 @@ class RememberedContact:
lat: float | None = None
lon: float | None = None
archived_at: int | None = None
locked: bool = False
@property
def archived(self) -> bool:
@@ -219,7 +230,11 @@ class ContactStore:
if not contact.public_key:
continue # unaddressable — nothing to remember it by
remembered = RememberedContact.from_contact(contact)
if current.get(remembered.public_key) != remembered:
known = current.get(remembered.public_key)
if known is not None and known.locked:
# The lock is ours, not the device's: a fresh read knows nothing about it.
remembered = replace(remembered, locked=True)
if known != remembered:
current[remembered.public_key] = remembered
changed = True
if changed:
@@ -256,16 +271,7 @@ class ContactStore:
dev = _norm(device_pubkey)
if not dev or not contact.public_key:
return # unaddressable — there would be nothing to restore it by
remembered = RememberedContact.from_contact(contact)
entry = RememberedContact(
public_key=remembered.public_key,
name=remembered.name,
node_type=remembered.node_type,
last_advert=remembered.last_advert,
lat=remembered.lat,
lon=remembered.lon,
archived_at=int(when),
)
entry = replace(RememberedContact.from_contact(contact), archived_at=int(when))
current = dict(self._state.get(dev, {}))
if current.get(entry.public_key) == entry:
return
@@ -295,19 +301,45 @@ class ContactStore:
if entry is None or not entry.archived:
return None
current = dict(contacts)
current[key] = RememberedContact(
public_key=entry.public_key,
name=entry.name,
node_type=entry.node_type,
last_advert=entry.last_advert,
lat=entry.lat,
lon=entry.lon,
archived_at=None,
)
current[key] = replace(entry, archived_at=None)
self._state[dev] = current
self._save()
return entry
def locked_keys(self, device_pubkey: str) -> frozenset[str]:
"""The full keys (lowercase hex) of every contact locked on this device."""
remembered = self._state.get(_norm(device_pubkey), {}).values()
return frozenset(c.public_key for c in remembered if c.locked)
def is_locked(self, device_pubkey: str, contact_pubkey: str) -> bool:
"""Whether one contact is locked against archiving on this device."""
entry = self._state.get(_norm(device_pubkey), {}).get(_norm(contact_pubkey))
return entry is not None and entry.locked
def set_locked(self, device_pubkey: str, contact: Contact, locked: bool) -> None:
"""Lock or unlock one contact, upserting it so a contact the store never saw can be.
Only a live contact is locked — the lock exists to keep a contact *off* the archive
path, so locking an archived one would claim something about a contact that has
already gone. Persists only a real change.
Args:
device_pubkey: The device's own public key.
contact: The contact to lock or unlock, addressed by its full key.
locked: The state to leave it in.
"""
dev = _norm(device_pubkey)
if not dev or not contact.public_key:
return # unaddressable — nothing to hang the flag on
current = dict(self._state.get(dev, {}))
key = _norm(contact.public_key)
known = current.get(key) or RememberedContact.from_contact(contact)
if known.archived or known.locked == locked:
return
current[key] = replace(known, locked=locked)
self._state[dev] = current
self._save()
def forget(self, device_pubkey: str, contact_pubkey: str) -> None:
"""Drop one remembered contact; persist only a real change."""
dev = _norm(device_pubkey)
@@ -350,6 +382,8 @@ def _contact_to_json(contact: RememberedContact) -> dict:
entry["lon"] = contact.lon
if contact.archived_at is not None:
entry["archived_at"] = contact.archived_at
if contact.locked:
entry["locked"] = True
return entry
@@ -369,6 +403,7 @@ def _contact_from_json(entry: object) -> RememberedContact | None:
lat=_opt_float(entry.get("lat")),
lon=_opt_float(entry.get("lon")),
archived_at=_opt_int(entry.get("archived_at")),
locked=entry.get("locked") is True,
)
+35 -8
View File
@@ -32,7 +32,7 @@ from rich.text import Text
from .marks import SELF_MARK
from .menus import fit_cells
from .theme import name_style
from .theme import glyph, name_style
from .tui.select import Choice, SelectScreen, Separator
from .widgets import (
DEFAULT_GLYPH,
@@ -122,6 +122,19 @@ TRACE_LANES: tuple[ContactLane, ...] = (TRACED_LANE, HEARD_LANE, PKTS_LANE)
#: about; when it left is.
ARCHIVED_LANES: tuple[ContactLane, ...] = (ARCHIVED_LANE,)
#: The padlock a locked contact's name lane closes on (see :attr:`ContactRow.locked`) — the
#: private-channel ``🔒`` of the icon lexicon, which is the same claim (this one is closed to
#: something), and on the PicoCalc the font's own hand-drawn padlock ``⚿`` through
#: :func:`~meshterm.ui.theme.glyph`. An unlocked contact draws nothing: the mark is an
#: exception worth noticing, and a lane of open padlocks would bury the few that aren't.
_LOCK_ICON = "🔒"
def _lock_mark() -> str:
"""The lock suffix a locked row's name lane ends on: a space, then this platform's padlock."""
return " " + glyph(_LOCK_ICON)
#: The muted ``(you)`` tag on the own-node lane (see :func:`_lane`), its width folded into
#: the name lane's content sizing so the tag never truncates.
_YOU_TAG = " (you)"
@@ -204,6 +217,9 @@ class ContactRow:
Ignored by lists that don't declare the lane.
archived_at: When this contact was archived off the device (aware UTC) — fills the
``ARCHIVED`` lane (:data:`ARCHIVED_LANES`). Ignored by lists without it.
locked: Whether the contact is locked against archiving. Closes the name lane on a
padlock, right-aligned so every lock in the list stands in one column; ``False``
draws nothing.
you: Whether this is our own node: the ``★`` marker, the pure-white ``you`` name
style with a muted ``(you)`` tag, faint ``—`` heard/packet lanes (we never
overhear ourselves), pinned above the sorted block whatever the sort.
@@ -217,6 +233,7 @@ class ContactRow:
count: int | None = None
last_traced: datetime | None = None
archived_at: datetime | None = None
locked: bool = False
you: bool = False
@@ -339,7 +356,8 @@ def _lane(
repeater, ``■`` for a room, ``◉`` for a sensor, ``●`` for a plain node. The name takes
the contact's hash-derived palette hue (a nameless contact's ``unknown`` placeholder
stays muted — colour marks a name, and the hash lane already carries the identity) and
the flexing name lane (``name_w`` cells). Each declared lane follows in order, drawn by
the flexing name lane (``name_w`` cells), a locked contact's closing on its padlock.
Each declared lane follows in order, drawn by
:func:`_lane_cell`; the key closes the row in the shared key widget, its hash lit at the
device's routing width, or a muted ``?`` when no key is known at all. An own-node row
(:attr:`ContactRow.you`) takes its own drawing — see :func:`_you_lane`.
@@ -358,10 +376,17 @@ def _lane(
text = Text(no_wrap=True, overflow="ellipsis")
text.append(glyph, style=glyph_style)
text.append(" ")
text.append(
fit_cells(row.name or "unknown", name_w),
style=name_style(row.name, row.key) if row.name else "muted",
)
hue = name_style(row.name, row.key) if row.name else "muted"
if row.locked:
# The padlock takes the lane's last cells rather than following the name, so the
# locks stand in a column down the list; the lane was sized to hold a locked name
# *and* its mark (see ContactListScreen._widest_name), so only a name the terminal
# squeezed is cut to make room.
lock = _lock_mark()
text.append(fit_cells(row.name or "unknown", max(0, name_w - cell_len(lock))), hue)
text.append(lock)
else:
text.append(fit_cells(row.name or "unknown", name_w), style=hue)
for lane in lanes:
text.append(_GAP_S)
text.append_text(_lane_cell(row, lane))
@@ -603,7 +628,8 @@ class ContactListScreen(SelectScreen):
The name lane is sized to its content, not the terminal, so the columns anchor to
the left instead of drifting apart as the window widens. The measure spans the
regular rows (``unknown`` for the nameless, as the row renders them) and any
own-node row's name plus its ``(you)`` tag, so the tag always fits.
own-node row's name plus its ``(you)`` tag, so the tag always fits, and a locked row's
name plus its padlock, so the lock never costs a letter of the name.
"""
widths = [cell_len("unknown")]
for row in self._contact_rows:
@@ -612,7 +638,8 @@ class ContactListScreen(SelectScreen):
cell_len(row.name) + cell_len(_YOU_TAG) if row.name else cell_len("you")
)
else:
widths.append(cell_len(row.name or "unknown"))
lock = cell_len(_lock_mark()) if row.locked else 0
widths.append(cell_len(row.name or "unknown") + lock)
return max(widths)
def _lane_widths(self, width: int) -> tuple[int, int]:
+47 -14
View File
@@ -83,6 +83,7 @@ class ContactsScreen(ContactListScreen):
counts: dict[str, int],
sort: ContactsSort,
archived: int = 0,
locked: frozenset[str] = frozenset(),
) -> None:
"""Create the contacts screen over already-fetched contact data.
@@ -100,21 +101,12 @@ class ContactsScreen(ContactListScreen):
``View archived contacts`` row and shows the count on it, so the tally is
visible without opening the list; zero draws no row, since a screen should
not offer a way into an empty list.
locked: The full keys (lowercase hex) of the contacts locked against archiving;
each of those rows closes its name lane on a padlock.
"""
rows = [ContactRow(value=YOU, name=self_name, key=self_key, you=True)]
for c in contacts:
rows.append(
ContactRow(
# The contact itself is the row's identity, so Enter hands the whole
# record straight to the detail page — no re-lookup by name/key.
value=c,
name=c.name,
key=c.public_key,
node_type=c.node_type,
last_seen=c.last_seen,
count=contact_packets(c, counts),
)
)
self._self_name, self._self_key = self_name, self_key
self._contacts, self._counts = contacts, counts
rows = self._contact_rows_for(locked)
# The maintenance actions close the list, past every contact whatever the sort: a
# blank spacer, then the sweep (a `…` — it opens further prompts), then the way in
# to what the sweep has already taken. The two sit together because they are the
@@ -148,6 +140,34 @@ class ContactsScreen(ContactListScreen):
tail=tail,
)
def _contact_rows_for(self, locked: frozenset[str]) -> list[ContactRow]:
"""Our own node, then every contact, each marked locked or not by ``locked``."""
rows = [ContactRow(value=YOU, name=self._self_name, key=self._self_key, you=True)]
for c in self._contacts:
rows.append(
ContactRow(
# The contact itself is the row's identity, so Enter hands the whole
# record straight to the detail page — no re-lookup by name/key.
value=c,
name=c.name,
key=c.public_key,
node_type=c.node_type,
last_seen=c.last_seen,
count=contact_packets(c, self._counts),
locked=(c.public_key or "").lower().removeprefix("0x") in locked,
)
)
return rows
def refresh_locks(self, locked: frozenset[str]) -> None:
"""Redraw the padlocks in place after a detail page may have locked or unlocked one.
A lock changes a lane, not which contacts exist, so this is the
:meth:`~meshterm.ui.contactlist.ContactListScreen.update_rows` case rather than a
rebuild: the cursor, the sort, the scroll and a typed filter all stay where they were.
"""
self.update_rows(self._contact_rows_for(locked))
async def open_contacts(
ctx: AppContext,
@@ -199,6 +219,7 @@ async def open_contacts(
counts,
sort,
archived=_archived_count(ctx, self_key),
locked=_locked_keys(ctx, self_key),
)
screen = build()
@@ -235,6 +256,9 @@ async def open_contacts(
if await open_node_detail(ctx, None if chosen == YOU else chosen):
rebuild = True
break
# The page may have locked or unlocked the contact without ending the visit;
# the store answers from memory, so the padlocks are simply redrawn.
screen.refresh_locks(_locked_keys(ctx, self_key))
if not rebuild:
return
contacts = await ctx.devstate.contacts()
@@ -248,3 +272,12 @@ def _archived_count(ctx: AppContext, self_key: str) -> int:
if store is None or not dev_pub:
return 0
return len(store.archived(dev_pub))
def _locked_keys(ctx: AppContext, self_key: str) -> frozenset[str]:
"""The keys of the contacts locked on this device — which rows draw a padlock."""
store = getattr(ctx, "contact_store", None)
dev_pub = (self_key or "").lower().removeprefix("0x")
if store is None or not dev_pub:
return frozenset()
return store.locked_keys(dev_pub)
+76 -16
View File
@@ -446,10 +446,7 @@ class NodeDetailScreen(Screen):
#: The action rows' icon column, in cells — measured once over every mark this page
#: can draw, so a one-cell ``🗑`` pads out to its two-cell siblings and every label
#: starts in the same column. Zero on a platform that draws no icon lane at all.
self._icon_lane = menus.icon_lane(
action.glyph
for action in (*self._info_actions, *([trace_action] if trace_action else []))
)
self._icon_lane = self._measure_icon_lane()
self._tab_index = 0
self._row_index = 0
#: The highlighted route on the Routes tab (drives the graph); tracks the cursor as
@@ -574,6 +571,31 @@ class NodeDetailScreen(Screen):
return 0
return 2 if self._tabs[self._tab_index].kind == "info" else 0
def _measure_icon_lane(self) -> int:
"""The action rows' icon column over every mark currently on the page."""
trace = [self._trace_action] if self._trace_action else []
return menus.icon_lane(action.glyph for action in (*self._info_actions, *trace))
def replace_info_actions(self, actions: list[_Action]) -> None:
"""Swap the Info tab's action rows in place, keeping the cursor on the row it was on.
For an action that changes what the page offers without ending the visit — locking a
contact turns its row into Unlock and withdraws Archive. The highlight follows the
committed row by its :attr:`_Action.key` family (``lock`` and ``unlock`` are one
row), so the reader's next press lands where their last one did.
"""
focus = self._focusables()
current = focus[self._row_index % len(focus)][1] if focus else None
was = getattr(current, "key", None)
self._info_actions = list(actions)
self._icon_lane = self._measure_icon_lane()
family = {"lock": "unlock", "unlock": "lock"}
for index, (_kind, payload) in enumerate(self._focusables()):
key = getattr(payload, "key", None)
if key is not None and key in (was, family.get(was or "")):
self._row_index = index
break
def handle(self, action: str, data: str = "") -> None:
"""Answer one key press on the page.
@@ -1089,6 +1111,13 @@ async def open_node_detail(
on the Info tab, and the page offers exactly the ones that make sense — a live contact
can be archived or deleted, an archived one restored or deleted.
**Locking is management that stays.** A live contact can be locked against archiving
(see :meth:`~meshterm.core.contact_store.ContactStore.set_locked`): the sweep then never
counts it a candidate, and this page withdraws its Archive row for as long as the lock
holds. The toggle rewrites the page's action rows in place rather than ending the visit
— nothing about the contact the page describes has gone — and the list underneath redraws
its padlock when the reader comes back to it.
``manage`` is how a caller says the page is being opened to *look*, not to act. The
archive preview passes ``False``: a screen whose whole job is choosing what to archive
should not also hand out a second, singular way to archive — or a delete — from inside
@@ -1100,7 +1129,8 @@ async def open_node_detail(
ctx: The shared application context (must be running the interactive TUI).
contact: The contact to detail, or ``None`` for our own node (an identity-and-ledger
page — we never overhear ourselves, so there is no reception history to show).
manage: Whether to offer the contact-management actions (archive, restore, delete).
manage: Whether to offer the contact-management actions (lock, archive, restore,
delete).
``False`` draws none of them, and the page can then only ever return ``False``.
Returns:
@@ -1328,18 +1358,41 @@ async def open_node_detail(
and contact is not None
and bool(contact.public_key or contact.key_prefix)
)
if manageable:
# The constructive verb first, then the destructive one, so the row a mistaken press
# is likeliest to land on is the recoverable one. Archive and restore are the two
# halves of one reversible move, and take the ``💾``/``📂`` pair the lexicon already
# gives put-it-away and bring-it-back; only a contact with a full key can be written
# back to the device, so a prefix-only contact is never offered the archive that
# would strand it.
store = getattr(ctx, "contact_store", None)
dev_pub = self_key.lower().removeprefix("0x")
whole_key = contact is not None and len(contact.public_key.lower().removeprefix("0x")) == 64
# A lock is MeshTerm's own mark, hung on the full key in the contact store, and only a
# live contact carries one — it exists to keep a contact off the archive path.
lockable = manageable and not archived and whole_key and store is not None and bool(dev_pub)
base_actions = list(info_actions)
def management(locked: bool) -> list[_Action]:
"""The page's action rows, closing on the management group for this lock state."""
rows = list(base_actions)
if not manageable:
return rows
# The lock first: it changes nothing on the device and ends nothing, so it is the
# safest row in the group to land on. Then the constructive verb, then the
# destructive one, so the row a mistaken press is likeliest to land on is the
# recoverable one. Archive and restore are the two halves of one reversible move,
# and take the ``💾``/``📂`` pair the lexicon already gives put-it-away and
# bring-it-back; only a contact with a full key can be written back to the device,
# so a prefix-only contact is never offered the archive that would strand it — and
# a locked one is never offered it at all, which is what the lock is for.
if lockable:
if locked:
rows.append(_Action("unlock", "🔓", "", "Unlock contact"))
else:
rows.append(_Action("lock", "🔒", "", "Lock contact"))
if archived:
info_actions.append(_Action("restore", "📂", "ok", "Restore to device"))
elif len((contact.public_key or "").lower().removeprefix("0x")) == 64:
info_actions.append(_Action("archive", "💾", "", "Archive contact"))
info_actions.append(_Action("remove", "🗑", "err", "Delete contact…"))
rows.append(_Action("restore", "📂", "ok", "Restore to device"))
elif whole_key and not locked:
rows.append(_Action("archive", "💾", "", "Archive contact"))
rows.append(_Action("remove", "🗑", "err", "Delete contact…"))
return rows
locked = bool(lockable and store.is_locked(dev_pub, contact.public_key))
info_actions = management(locked)
try:
adv_type = int(node_type) if node_type is not None else 1
except (TypeError, ValueError):
@@ -1410,6 +1463,13 @@ async def open_node_detail(
if await _restore_archived(ctx, contact, self_key, label):
contact_removed = True
break
elif action in ("lock", "unlock"):
# No confirm and no notice: the lock is reversible from the very row that set
# it, and the row turning into its opposite is the acknowledgement.
assert contact is not None and store is not None # only offered when lockable
locked = action == "lock"
store.set_locked(dev_pub, contact, locked)
screen.replace_info_actions(management(locked))
elif action == "archive":
assert contact is not None
if await _archive_contact(ctx, contact, self_key, label):
+10 -6
View File
@@ -294,19 +294,20 @@ def _rung_row(label: str, kept: int, archived: int, label_w: int) -> Text:
return row
async def _rank(ctx: AppContext, contacts: list[Contact]) -> list[ScoredContact]:
async def _rank(ctx: AppContext, contacts: list[Contact], self_key: str) -> list[ScoredContact]:
"""Gather every signal these contacts have and rank them, strongest first.
Five grouped scans of the history (:meth:`
~meshterm.persistence.repository.Repository.contact_signals`), one pass over the channel
transcript for name attribution, and the two stores that carry the explicit protections
— the Watchtower's stars and the remembered admin logins. Our own position comes from
the device's self-info, and is simply absent on a device that advertises none, which the
distance term reads as unknown for everybody.
transcript for name attribution, and the three stores that carry the explicit protections
— the contacts you locked, the Watchtower's stars and the remembered admin logins. Our
own position comes from the device's self-info, and is simply absent on a device that
advertises none, which the distance term reads as unknown for everybody.
Args:
ctx: Shared application context.
contacts: The device's contacts (our own node is not among them).
self_key: The device's own public key (hex), which scopes the locks.
Returns:
The full ranking, strongest first.
@@ -328,6 +329,8 @@ async def _rank(ctx: AppContext, contacts: list[Contact]) -> list[ScoredContact]
if folded:
seen[folded] = seen.get(folded, 0) + 1
store = getattr(ctx, "contact_store", None)
locked = store.locked_keys(self_key) if store is not None and self_key else frozenset()
watch = getattr(ctx, "watch_store", None)
admin = getattr(ctx, "admin_store", None)
for contact, node in zip(contacts, nodes, strict=True):
@@ -342,6 +345,7 @@ async def _rank(ctx: AppContext, contacts: list[Contact]) -> list[ScoredContact]
channel_attributed=unique,
watched=bool(watch is not None and watch.is_watched(node)),
has_admin=bool(admin is not None and admin.get(contact)),
locked=(contact.public_key or "").lower().removeprefix("0x") in locked,
)
self_lat = self_lon = None
@@ -385,7 +389,7 @@ async def archive_contacts(ctx: AppContext, self_key: str) -> int:
async with ctx.ui.busy_overlay("Rating contacts"):
contacts = await ctx.devstate.contacts()
ranked = await _rank(ctx, contacts)
ranked = await _rank(ctx, contacts, self_key)
sweepable = [scored for scored in ranked if not scored.protected]
if not sweepable:
+2 -1
View File
@@ -660,7 +660,8 @@ _GLYPH_MAP: dict[str, str] = {
# Channel openness (widgets.channel_glyph)
"#": "#", # name-derived channel
"🌐": "@", # well-known public channel
"🔒": "⚿", # private channel (the padlock mark)
"🔒": "⚿", # private channel, locked contact (the padlock mark)
"🔓": "⚿", # unlock — the same padlock; the row's word says which way it turns
# Concept icons (menu/list rows)
"📡": "☼", # advert tool — same concept as the advert class
"🕒": "◷", # clock/sync (the clock-face mark)
+9 -1
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
from meshterm.core.contact_score import (
PROTECT_ADMIN,
PROTECT_LOCKED,
PROTECT_MESSAGED,
PROTECT_UNOBSERVED,
PROTECT_WATCHED,
@@ -145,11 +146,12 @@ def test_a_newcomer_is_given_a_fortnight_to_earn_its_keep() -> None:
def test_protections_outrank_the_arithmetic() -> None:
"""A star, a sent message, an admin login or an unheard contact is never a candidate.
"""A lock, a star, a sent message, an admin login or an unheard contact is never a candidate.
A heuristic must not overrule an explicit choice, and it must not punish a contact for
MeshTerm's own ignorance.
"""
assert protection_for(ContactSignals(node="a" * 12, **_BASE, locked=True)) == PROTECT_LOCKED
assert protection_for(ContactSignals(node="a" * 12, **_BASE, watched=True)) == PROTECT_WATCHED
assert protection_for(ContactSignals(node="a" * 12, **_BASE, dm_outbound=1)) == PROTECT_MESSAGED
assert protection_for(ContactSignals(node="a" * 12, **_BASE, has_admin=True)) == PROTECT_ADMIN
@@ -325,3 +327,9 @@ def test_a_stronger_contact_never_scores_below_a_weaker_one_on_every_axis() -> N
)
assert ranked["Better"].score > ranked["Worse"].score
assert ranked["Better"].percentile > ranked["Worse"].percentile
def test_a_lock_explains_a_contact_before_any_other_claim_on_it() -> None:
"""A lock says nothing but "keep this one", so it is the reason the preview gives."""
both = ContactSignals(node="a" * 12, **_BASE, locked=True, watched=True, dm_outbound=3)
assert protection_for(both) == PROTECT_LOCKED
+41
View File
@@ -312,3 +312,44 @@ def test_a_keyless_contact_cannot_be_archived(tmp_path) -> None: # noqa: ANN001
store = ContactStore(tmp_path / "contacts.json")
store.archive(PUB_A, Contact(name="Ghost"), when=1_700_000_000)
assert store.archived(PUB_A) == []
def test_a_lock_is_ours_and_survives_every_fresh_read_of_the_contact(tmp_path) -> None: # noqa: ANN001
"""The device knows nothing of a lock, so reading the device must never clear one."""
from meshterm.core.models import Contact
store = ContactStore(tmp_path / "contacts.json")
alice = Contact(name="Alice", public_key="aa" * 32, key_prefix="aa" * 6)
bob = Contact(name="Bob", public_key="bb" * 32, key_prefix="bb" * 6)
# Locking a contact the store never saw upserts it, as archiving does.
store.set_locked(PUB_A, alice, True)
assert store.is_locked(PUB_A, "aa" * 32)
assert store.locked_keys(PUB_A) == frozenset({"aa" * 32})
# A fresh read — a rename included — keeps the lock and changes the rest.
store.remember_all(PUB_A, [Contact(name="Alice II", public_key="aa" * 32), bob])
assert store.is_locked(PUB_A, "aa" * 32)
assert not store.is_locked(PUB_A, "bb" * 32)
assert [c.name for c in store.contacts(PUB_A)] == ["Alice II", "Bob"]
# Persisted, and scoped to the device it was set on.
reloaded = ContactStore(tmp_path / "contacts.json")
assert reloaded.locked_keys(PUB_A) == frozenset({"aa" * 32})
assert reloaded.locked_keys("ff" * 32) == frozenset()
reloaded.set_locked(PUB_A, alice, False)
assert ContactStore(tmp_path / "contacts.json").locked_keys(PUB_A) == frozenset()
def test_an_archived_or_keyless_contact_takes_no_lock(tmp_path) -> None: # noqa: ANN001
"""The lock keeps a live contact off the archive path; there is nothing else to lock."""
from meshterm.core.models import Contact
store = ContactStore(tmp_path / "contacts.json")
alice = Contact(name="Alice", public_key="aa" * 32, key_prefix="aa" * 6)
store.archive(PUB_A, alice, when=1_700_000_000)
store.set_locked(PUB_A, alice, True)
assert store.locked_keys(PUB_A) == frozenset()
store.set_locked(PUB_A, Contact(name="Ghost"), True)
assert store.locked_keys(PUB_A) == frozenset()
+107 -7
View File
@@ -462,7 +462,9 @@ async def test_archive_sweeps_under_a_progress_bar_and_reports_in_a_dialog() ->
log=logging.getLogger("test.archive"),
repo=_Repo(),
contact_store=SimpleNamespace(
archive=lambda dev, contact, when: archived.append(contact.name)
locked_keys=lambda *a: frozenset(),
is_locked=lambda *a: False,
archive=lambda dev, contact, when: archived.append(contact.name),
),
watch_store=None,
admin_store=None,
@@ -702,7 +704,11 @@ async def test_deleting_one_contact_drops_it_from_the_device_and_the_store() ->
ctx = SimpleNamespace(
ui=ui,
log=logging.getLogger("test.remove"),
contact_store=SimpleNamespace(forget=lambda dev, key: forgotten.append((dev, key))),
contact_store=SimpleNamespace(
locked_keys=lambda *a: frozenset(),
is_locked=lambda *a: False,
forget=lambda dev, key: forgotten.append((dev, key)),
),
devstate=SimpleNamespace(invalidate_contacts=lambda: invalidated.append(True)),
device=lambda: _device(_Device()),
)
@@ -748,7 +754,11 @@ async def test_cancelling_the_remove_confirm_touches_nothing() -> None:
ctx = SimpleNamespace(
ui=ui,
log=logging.getLogger("test.remove"),
contact_store=SimpleNamespace(forget=lambda *a: touched.append("forgot")),
contact_store=SimpleNamespace(
locked_keys=lambda *a: frozenset(),
is_locked=lambda *a: False,
forget=lambda *a: touched.append("forgot"),
),
devstate=SimpleNamespace(invalidate_contacts=lambda: touched.append("invalidated")),
device=lambda: _device(_Device()),
)
@@ -793,7 +803,11 @@ async def test_a_refused_removal_is_shown_and_the_contact_stays() -> None:
ctx = SimpleNamespace(
ui=ui,
log=logging.getLogger("test.remove"),
contact_store=SimpleNamespace(forget=lambda *a: forgotten.append(a)),
contact_store=SimpleNamespace(
locked_keys=lambda *a: frozenset(),
is_locked=lambda *a: False,
forget=lambda *a: forgotten.append(a),
),
devstate=SimpleNamespace(invalidate_contacts=lambda: forgotten.append("cache")),
device=lambda: _device(_Device()),
)
@@ -846,7 +860,11 @@ async def test_a_contact_the_device_never_held_is_still_removed_here() -> None:
ctx = SimpleNamespace(
ui=ui,
log=logging.getLogger("test.remove"),
contact_store=SimpleNamespace(forget=lambda dev, key: forgotten.append((dev, key))),
contact_store=SimpleNamespace(
locked_keys=lambda *a: frozenset(),
is_locked=lambda *a: False,
forget=lambda dev, key: forgotten.append((dev, key)),
),
devstate=SimpleNamespace(invalidate_contacts=lambda: invalidated.append(True)),
device=lambda: _device(_Device()),
)
@@ -1043,7 +1061,9 @@ async def test_archiving_one_contact_takes_it_off_the_device_and_keeps_it() -> N
ui=ui,
log=logging.getLogger("test.archive"),
contact_store=SimpleNamespace(
archive=lambda dev, contact, when: archived.append((dev, contact.public_key))
locked_keys=lambda *a: frozenset(),
is_locked=lambda *a: False,
archive=lambda dev, contact, when: archived.append((dev, contact.public_key)),
),
devstate=SimpleNamespace(invalidate_contacts=lambda: invalidated.append(True)),
device=lambda: _device(_Device()),
@@ -1082,7 +1102,11 @@ async def test_restoring_writes_the_contact_back_before_clearing_the_mark() -> N
ctx = SimpleNamespace(
ui=TuiUi(session),
log=logging.getLogger("test.restore"),
contact_store=SimpleNamespace(restore=lambda dev, key: restored.append(key)),
contact_store=SimpleNamespace(
locked_keys=lambda *a: frozenset(),
is_locked=lambda *a: False,
restore=lambda dev, key: restored.append(key),
),
devstate=SimpleNamespace(invalidate_contacts=lambda: None),
device=lambda: _device(_Refuses()),
)
@@ -1469,3 +1493,79 @@ async def test_the_preview_opens_node_pages_with_no_management_verbs(
assert session.top is screen
screen.handle("escape")
assert await task is False
def test_a_locked_contact_closes_its_name_lane_on_a_padlock_in_one_column() -> None:
"""Locked rows end their name lane on the padlock, lined up; unlocked rows draw nothing."""
from rich.cells import cell_len
from meshterm.core.models import Contact
from meshterm.ui.contacts_screen import ContactsScreen
contacts = [
Contact(name="Al", public_key="aa" * 32),
Contact(name="Bartholomew", public_key="bb" * 32),
Contact(name="Cy", public_key="cc" * 32),
]
screen = ContactsScreen(
"Us", "dd" * 32, contacts, 1, {}, _contacts_sort(), locked=frozenset({"aa" * 32})
)
# The lanes size themselves on the first paint.
screen.note_viewport(30)
screen.render_body(72)
lines = {}
for choice in screen._choices():
plain = choice.title.plain if hasattr(choice.title, "plain") else str(choice.title)
for name in ("Al", "Bartholomew", "Cy"):
if plain[2:].startswith(name + " ") or plain[2:].startswith(name + "\u00a0"):
lines[name] = plain
assert "🔒" in lines["Al"]
assert "🔒" not in lines["Bartholomew"] and "🔒" not in lines["Cy"]
# The lane grew to hold the locked name *and* its mark without cutting the longest name.
assert "Bartholomew" in lines["Bartholomew"]
# The padlock closes the lane that "Bartholomew" fills: the locks stand in one column.
lock_end = lines["Al"].index("🔒") + 1
assert cell_len(lines["Al"][:lock_end]) == cell_len("● Bartholomew")
# Unlocking redraws in place: the same screen, the padlock gone.
screen.refresh_locks(frozenset())
assert not any("🔒" in str(getattr(c.title, "plain", c.title)) for c in screen._choices())
async def test_a_locked_contact_is_never_offered_to_the_sweep() -> None:
"""The ranking reads the store's locks, so a locked contact is protected, not a victim."""
import logging
from types import SimpleNamespace
from meshterm.core.contact_score import PROTECT_LOCKED, ContactSignals
from meshterm.core.models import Contact
from meshterm.ui.sweep_screen import _rank
contacts = [
Contact(name="Kept", public_key="aa" * 32, key_prefix="aa" * 6),
Contact(name="Loose", public_key="bb" * 32, key_prefix="bb" * 6),
]
class _Repo:
def contact_signals(self, nodes): # noqa: ANN001, ANN202
return {
n: ContactSignals(node=n, heard_age_days=400.0, known_days=500.0) for n in nodes
}
def channel_post_counts(self): # noqa: ANN202
return {}
async def _self_info(): # noqa: ANN202
return {}
ctx = SimpleNamespace(
repo=_Repo(),
log=logging.getLogger("test.lock"),
contact_store=SimpleNamespace(locked_keys=lambda dev: frozenset({"aa" * 32})),
watch_store=None,
admin_store=None,
devstate=SimpleNamespace(self_info=_self_info),
)
ranked = {s.contact.name: s for s in await _rank(ctx, contacts, "cc" * 32)}
assert ranked["Kept"].protection == PROTECT_LOCKED
assert not ranked["Loose"].protected
+12 -2
View File
@@ -186,8 +186,18 @@ def _contacts(cols: int, rows: int) -> Screen:
Contact(name="A Rather Long Repeater Name For Width", public_key=_HUB_KEY),
]
# A non-zero archived tally, so the tail draws both maintenance rows — its populated
# state, and the widest the tail ever gets.
return ContactsScreen("Homestead", "cc" * 32, contacts, 1, {"aa" * 6: 7}, sort, archived=12)
# state, and the widest the tail ever gets — and a locked contact, so its padlock is held
# to both platforms' glyph contracts.
return ContactsScreen(
"Homestead",
"cc" * 32,
contacts,
1,
{"aa" * 6: 7},
sort,
archived=12,
locked=frozenset({"aa" * 32}),
)
def _archive_ranked(): # noqa: ANN201
+27
View File
@@ -1236,3 +1236,30 @@ def test_node_detail_single_tab_hides_the_switch_hint() -> None:
assert "↑↓ move" in screen.footer_hint and screen.footer_hint.endswith("Esc back")
# Nothing to switch to, so the lane leaves the slot empty rather than dimming it.
assert screen.fkey_lane[2] is None
def test_toggling_the_lock_rewrites_the_rows_and_keeps_the_cursor_on_it() -> None:
"""Lock becomes Unlock on the same row, and Archive is withdrawn while the lock holds."""
tm = _Action("timemachine", "⏳", "", "Time machine — 42 receptions")
delete = _Action("remove", "🗑", "err", "Delete contact…")
screen = _screen(
info_actions=[
tm,
_Action("lock", "🔒", "", "Lock contact"),
_Action("archive", "💾", "", "Archive contact"),
delete,
]
)
resolved: list = []
screen.resolve = lambda value: resolved.append(value) # type: ignore[method-assign]
screen.note_viewport(30)
screen.render_body(72)
screen.handle("down")
screen.handle("enter")
assert resolved == ["lock"]
screen.replace_info_actions([tm, _Action("unlock", "🔓", "", "Unlock contact"), delete])
screen.render_body(72)
screen.handle("enter")
assert resolved == ["lock", "unlock"]
assert [a.key for a in screen._info_actions] == ["timemachine", "unlock", "remove"]