Contacts: remember heard contacts across sessions

A firmware-less radio bridge holds its contact table only in RAM, so the Contacts
screen and the chat recipient list come up empty (or only as sparse as this
session's adverts) after the bridge restarts, even though you were messaging those
nodes last time. Record every contact MeshTerm reads, keyed by the device's own
public key, and union any the device is no longer reporting back into the list at
the one read chokepoint both lists share (DeviceState.contacts()).

No device write is needed: a direct message addresses a node by a prefix of its
public key, which the remembered contact carries, so a restored contact is
messageable without being written back onto the device. The union is inert where
it isn't needed — a firmware radio reports its whole table, so nothing is added,
no device-type check required — and recording never removes a contact on an empty
read, so a bridge that just restarted doesn't wipe what it knew.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 4.8 committed 2026-07-24 20:59:34 -04:00
1 parent 842a58a515
commit 94e81a1b82
4 files changed
+534 -1

No files matched your search

+7
View File
@@ -16,6 +16,7 @@ from .core.admin_store import AdminStore
from .core.advert_store import AdvertStore
from .core.channel_store import ChannelStore
from .core.config import DeviceProfile, Settings
from .core.contact_store import ContactStore
from .core.courier_store import CourierStore
from .core.mute_store import MuteStore
from .core.remote_store import RemoteStore
@@ -69,6 +70,9 @@ class AppContext:
settings_store: Store for settings changed through MeshTerm, offered back on connect to
a device that forgot them (a firmware-less radio bridge). Keyed by device public
key; defaults to ``<config_dir>/settings.json`` when not injected.
contact_store: Store for contacts read through MeshTerm, merged back into the contact
lists for a device that forgot them (a firmware-less radio bridge). Keyed by device
public key; defaults to ``<config_dir>/contacts.json`` when not injected.
mock: Whether the simulator device is in use.
port_override: Explicit serial port (from ``--port`` or the interactive picker),
overriding the profile.
@@ -97,6 +101,7 @@ class AppContext:
mute_store: Optional[MuteStore] = None
channel_store: Optional[ChannelStore] = None
settings_store: Optional[SettingsStore] = None
contact_store: Optional[ContactStore] = None
profile: Optional[DeviceProfile] = None
mock: bool = False
port_override: Optional[str] = None
@@ -147,6 +152,8 @@ class AppContext:
self.channel_store = ChannelStore(self.settings.config_dir / "channels.json")
if self.settings_store is None:
self.settings_store = SettingsStore(self.settings.config_dir / "settings.json")
if self.contact_store is None:
self.contact_store = ContactStore(self.settings.config_dir / "contacts.json")
@property
def profile_name(self) -> Optional[str]:
+289
View File
@@ -0,0 +1,289 @@
"""Persistence for contacts heard through MeshTerm, so they survive a device that forgets them.
Most companions keep their contact table in firmware, so MeshTerm reads contacts live from the
device and never has to remember them. A firmware-less radio bridge is the exception: it holds
its contact table only in RAM, so every contact is gone when the bridge process restarts — the
Contacts screen and the chat recipient list come up empty (or only as sparse as the adverts
heard so far this session), even though you were messaging those nodes last time.
This store is the durable backup for exactly that case. Every time MeshTerm reads the device's
contacts it records them here, keyed by the device's own public key so two radios keep separate
sets. When a list is then drawn, :func:`merge_contacts` unions the device's live contacts with
any remembered contact the device isn't currently reporting — so a forgetful device still shows
the nodes you know, and they stay messageable: a direct message addresses a node by a prefix of
its public key, which the remembered contact carries, so nothing has to be written back onto the
device to reach them.
The union is inert where it isn't needed: a firmware radio always reports its whole table, so
every remembered contact is already present and nothing is added — no device-type check required.
Recording never *removes* a contact on a device's empty read, so a bridge that just restarted
doesn't wipe the memory of what it knew.
Like the other operator state (mutes, remembered channels, saved settings), this is global
machine state in a small JSON file (``<config_dir>/contacts.json``), not the per-invocation
SQLite database. Reads are served from memory after the first load; a write happens only when the
contact set actually changes, and flushes atomically.
"""
from __future__ import annotations
import json
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
from .models import Contact
def _norm(pubkey: str) -> str:
"""Normalise a public key (device or contact) to the lowercase hex used as a key."""
return (pubkey or "").lower().removeprefix("0x")
def _opt_int(value: object) -> Optional[int]:
"""Coerce a JSON value to ``int``, or ``None`` if absent/unparseable."""
if value is None:
return None
try:
return int(value)
except (TypeError, ValueError):
return None
def _opt_float(value: object) -> Optional[float]:
"""Coerce a JSON value to ``float``, or ``None`` if absent/unparseable."""
if value is None:
return None
try:
return float(value)
except (TypeError, ValueError):
return None
@dataclass(frozen=True)
class RememberedContact:
"""One contact MeshTerm remembers for a device: enough to list it and address a message.
Attributes:
public_key: The contact's full public key (lowercase hex) — how a direct message
addresses it, so it is what makes a remembered contact messageable.
name: The node's advertised name.
node_type: The advert type (see the ``NODE_TYPE_*`` constants), so the chat picker's
direct-messageable filter keeps behaving as it would for a live contact.
last_advert: Unix seconds of the node's most recent advert when last heard, for the
list's last-heard column; ``None`` when unknown.
lat: Last advertised latitude, if it shared one.
lon: Last advertised longitude, if it shared one.
"""
public_key: str
name: str
node_type: Optional[int] = None
last_advert: Optional[int] = None
lat: Optional[float] = None
lon: Optional[float] = None
@classmethod
def from_contact(cls, contact: Contact) -> "RememberedContact":
"""Distil a live :class:`~meshterm.core.models.Contact` into the fields we persist."""
epoch = int(contact.last_seen.timestamp()) if contact.last_seen else None
return cls(
public_key=_norm(contact.public_key),
name=contact.name,
node_type=contact.node_type,
last_advert=epoch,
lat=contact.lat,
lon=contact.lon,
)
def to_contact(self) -> Contact:
"""Rebuild a :class:`~meshterm.core.models.Contact` for the merged list.
The learned route is dropped (``route_hops=None``): a remembered contact floods until
the device relearns a path from received traffic, exactly as a freshly-heard one does.
"""
last_seen = (
datetime.fromtimestamp(self.last_advert, tz=timezone.utc)
if self.last_advert
else None
)
return Contact(
name=self.name,
public_key=self.public_key,
key_prefix=self.public_key[:12],
last_seen=last_seen,
node_type=self.node_type,
lat=self.lat,
lon=self.lon,
route_hops=None,
)
class ContactStore:
"""Reads and writes the per-device set of remembered contacts, memory-first.
Interact through :meth:`contacts` (a device's remembered contacts) and :meth:`remember_all`
(record the contacts just read from a device — an upsert that never drops one on absence).
The backing map is loaded once on first access and kept in memory; a mutation persists the
whole map atomically, and only when something actually changed.
"""
def __init__(self, path: Path) -> None:
"""Open the store against a JSON file location.
Args:
path: Path to the JSON state file (created lazily on the first remembered contact).
"""
self._path = path
self._devices: Optional[dict[str, dict[str, RememberedContact]]] = None
@property
def _state(self) -> dict[str, dict[str, RememberedContact]]:
"""The device -> {contact key -> remembered contact} map, loaded on first access."""
if self._devices is None:
self._devices = self._load()
return self._devices
def _load(self) -> dict[str, dict[str, RememberedContact]]:
"""Parse the file into the device map, or empty on a missing/corrupt file."""
try:
data = json.loads(self._path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
if not isinstance(data, dict):
return {}
devices: dict[str, dict[str, RememberedContact]] = {}
for pubkey, entries in (data.get("devices") or {}).items():
if not isinstance(entries, list):
continue
contacts: dict[str, RememberedContact] = {}
for entry in entries:
contact = _contact_from_json(entry)
if contact is not None:
contacts[contact.public_key] = contact
if contacts:
devices[_norm(str(pubkey))] = contacts
return devices
def contacts(self, device_pubkey: str) -> list[RememberedContact]:
"""The contacts remembered for a device (a copy, sorted by name), empty if none."""
remembered = self._state.get(_norm(device_pubkey), {})
return sorted(remembered.values(), key=lambda c: (c.name.lower(), c.public_key))
def remember_all(self, device_pubkey: str, contacts: list[Contact]) -> None:
"""Record the contacts just read from a device, upserting by public key.
A contact new to the device, or one whose fields changed (a rename, a fresher advert),
is stored; an unchanged one is left alone. A contact the device is *no longer* reporting
is **kept** — so a forgetful device's empty read never erases what it once knew. Persists
once, only if anything changed.
Args:
device_pubkey: The device's own public key.
contacts: The contacts just read from that device.
"""
dev = _norm(device_pubkey)
if not dev:
return
current = dict(self._state.get(dev, {}))
changed = False
for contact in contacts:
if not contact.public_key:
continue # unaddressable — nothing to remember it by
remembered = RememberedContact.from_contact(contact)
if current.get(remembered.public_key) != remembered:
current[remembered.public_key] = remembered
changed = True
if changed:
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)
contacts = self._state.get(dev)
key = _norm(contact_pubkey)
if not contacts or key not in contacts:
return
contacts = {k: v for k, v in contacts.items() if k != key}
if contacts:
self._state[dev] = contacts
else:
del self._state[dev]
self._save()
def _save(self) -> None:
"""Persist the whole device map atomically (a crash mid-write keeps the old file)."""
data = {
"devices": {
pubkey: [_contact_to_json(c) for c in sorted(
contacts.values(), key=lambda c: (c.name.lower(), c.public_key)
)]
for pubkey, contacts in sorted(self._state.items())
if contacts
}
}
self._path.parent.mkdir(parents=True, exist_ok=True)
tmp = self._path.with_suffix(self._path.suffix + ".tmp")
tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
tmp.replace(self._path)
def _contact_to_json(contact: RememberedContact) -> dict:
"""Serialise one remembered contact, omitting the fields it doesn't carry."""
entry: dict = {"public_key": contact.public_key, "name": contact.name}
if contact.node_type is not None:
entry["node_type"] = contact.node_type
if contact.last_advert is not None:
entry["last_advert"] = contact.last_advert
if contact.lat is not None:
entry["lat"] = contact.lat
if contact.lon is not None:
entry["lon"] = contact.lon
return entry
def _contact_from_json(entry: object) -> Optional[RememberedContact]:
"""Parse one stored contact entry, or ``None`` if it is malformed (no key or name)."""
if not isinstance(entry, dict):
return None
pubkey = _norm(str(entry.get("public_key", "")))
name = entry.get("name")
if not pubkey or not isinstance(name, str):
return None
return RememberedContact(
public_key=pubkey,
name=name,
node_type=_opt_int(entry.get("node_type")),
last_advert=_opt_int(entry.get("last_advert")),
lat=_opt_float(entry.get("lat")),
lon=_opt_float(entry.get("lon")),
)
def merge_contacts(
store: ContactStore, device_pubkey: str, live: list[Contact]
) -> list[Contact]:
"""Union a device's live contacts with any remembered ones it isn't currently reporting.
Live contacts pass through unchanged and first; a remembered contact whose key the device
already reports is left to the live entry (the fresher of the two), so nothing is
duplicated. A firmware radio reports its whole table, so this adds nothing there; a
forgetful device gets the missing contacts back, rebuilt from what was remembered.
Args:
store: The contact store to read remembered contacts from.
device_pubkey: The device's own public key.
live: The contacts the device is currently reporting.
Returns:
The live contacts followed by the remembered contacts the device is missing.
"""
present = {_norm(c.public_key) for c in live if c.public_key}
extra = [
remembered.to_contact()
for remembered in store.contacts(device_pubkey)
if remembered.public_key and remembered.public_key not in present
]
return list(live) + extra
+25 -1
View File
@@ -130,10 +130,34 @@ class DeviceState:
):
return self._contacts
device = await self._ctx.device()
self._contacts = await device.get_contacts()
self._contacts = await self._remember_and_merge(await device.get_contacts())
self._contacts_at = time.monotonic()
return self._contacts
async def _remember_and_merge(self, fetched: list["Contact"]) -> list["Contact"]:
"""Record the contacts just read, then union in any the device has since forgotten.
A firmware-less radio bridge loses its contact table on restart, so MeshTerm remembers
every contact it reads (keyed by the device's own public key) and merges the missing ones
back into the list — leaving a firmware radio, which reports its whole table, untouched
(see :mod:`meshterm.core.contact_store`). Best-effort: a store or self-info hiccup just
returns the live list unchanged, never blocking the read.
"""
store = getattr(self._ctx, "contact_store", None)
if store is None:
return fetched
from ..core.contact_store import merge_contacts
try:
pubkey = str((await self.self_info()).get("public_key") or "")
except Exception as exc: # noqa: BLE001 - never block a contacts read on the store
self._ctx.log.debug("devstate: contact remember/merge skipped: %s", exc)
return fetched
if not pubkey:
return fetched
store.remember_all(pubkey, fetched)
return merge_contacts(store, pubkey, fetched)
async def _refresh_contacts_quietly(self) -> None:
"""Background contacts refresh: update the cache, swallow a failure (keep the old list)."""
try:
+213
View File
@@ -0,0 +1,213 @@
"""Tests for remembering contacts across sessions (``core.contact_store``).
Covers the durable per-device store, the ``RememberedContact`` <-> ``Contact`` round-trip, the
``merge_contacts`` union that surfaces remembered contacts a device is no longer reporting, and
the write-through/merge wired into :class:`~meshterm.services.device_state.DeviceState`. The
integration test runs against the :class:`MockDevice` simulator, emptying its contact table to
stand in for the firmware-less radio bridge that loses its contacts on restart.
"""
from __future__ import annotations
import io
import json
from datetime import datetime, timezone
from pathlib import Path
import pytest
from rich.console import Console
from meshterm.context import AppContext
from meshterm.core.admin_store import AdminStore
from meshterm.core.config import Settings
from meshterm.core.contact_store import ContactStore, RememberedContact, merge_contacts
from meshterm.core.device_store import DeviceStore
from meshterm.core.models import NODE_TYPE_CHAT, NODE_TYPE_REPEATER, Contact, is_direct_messageable
from meshterm.persistence.repository import Repository
PUB_A = "aa" * 32
PUB_B = "bb" * 32
def _contact(name: str, key_byte: str, **kw) -> Contact:
"""A live Contact addressed by a full 32-byte key built from a repeated hex byte."""
pub = key_byte * 32
return Contact(name=name, public_key=pub, key_prefix=pub[:12], **kw)
@pytest.fixture()
def ctx(tmp_path: Path) -> AppContext:
"""A mock-backed application context with the plain (console) UI surface."""
settings = Settings(config_dir=tmp_path, db_path=tmp_path / "contacts.db")
context = AppContext(
console=Console(file=io.StringIO()),
settings=settings,
repo=Repository(settings.db_path),
device_store=DeviceStore(tmp_path / "devices.json"),
admin_store=AdminStore(tmp_path / "admin.json"),
mock=True,
)
yield context
context.repo.close()
# --- the store ---------------------------------------------------------------
def test_store_round_trips_and_persists(tmp_path: Path) -> None:
"""Remembered contacts survive a fresh store instance, kept per device, sorted by name."""
path = tmp_path / "contacts.json"
store = ContactStore(path)
store.remember_all(
PUB_A, [_contact("Bob", "cc", node_type=NODE_TYPE_CHAT), _contact("Al", "dd")]
)
store.remember_all(PUB_B, [_contact("Carol", "ee")])
reloaded = ContactStore(path) # a new process reads the same file
a = reloaded.contacts(PUB_A)
assert [c.name for c in a] == ["Al", "Bob"] # name order
assert a[1].public_key == "cc" * 32 and a[1].node_type == NODE_TYPE_CHAT
assert [c.name for c in reloaded.contacts(PUB_B)] == ["Carol"] # separate device
def test_remember_all_upserts_and_never_drops_absent(tmp_path: Path) -> None:
"""A rename updates in place; a contact absent from a later read is kept, not removed."""
store = ContactStore(tmp_path / "contacts.json")
store.remember_all(PUB_A, [_contact("Alice", "cc"), _contact("Bob", "dd")])
# A later read the device only reports Alice under a new name — Bob must survive.
store.remember_all(PUB_A, [_contact("Alice-2", "cc")])
by_key = {c.public_key: c.name for c in store.contacts(PUB_A)}
assert by_key == {"cc" * 32: "Alice-2", "dd" * 32: "Bob"}
def test_remember_all_skips_keyless_contacts(tmp_path: Path) -> None:
"""A contact with no public key is unaddressable and is not remembered."""
store = ContactStore(tmp_path / "contacts.json")
store.remember_all(PUB_A, [Contact(name="Ghost", public_key="")])
assert store.contacts(PUB_A) == []
def test_store_normalises_keys(tmp_path: Path) -> None:
"""Both the device key and the contact key are matched case-insensitively, 0x stripped."""
store = ContactStore(tmp_path / "contacts.json")
store.remember_all("AABB", [Contact(name="Al", public_key="0xCCDD")])
remembered = store.contacts("0xaabb")
assert remembered and remembered[0].public_key == "ccdd"
def test_store_ignores_corrupt_file(tmp_path: Path) -> None:
"""A garbage file reads as empty rather than raising, and stays writable."""
path = tmp_path / "contacts.json"
path.write_text("not json at all", encoding="utf-8")
store = ContactStore(path)
assert store.contacts(PUB_A) == []
store.remember_all(PUB_A, [_contact("Al", "cc")]) # recovers and persists
assert [c.name for c in ContactStore(path).contacts(PUB_A)] == ["Al"]
def test_store_drops_malformed_entries(tmp_path: Path) -> None:
"""Entries missing a public key or name are skipped; good ones kept."""
path = tmp_path / "contacts.json"
path.write_text(
json.dumps(
{
"devices": {
PUB_A: [
{"public_key": "cc" * 32, "name": "Good"},
{"name": "Keyless"}, # no public_key
{"public_key": "dd" * 32}, # no name
]
}
}
),
encoding="utf-8",
)
assert [c.name for c in ContactStore(path).contacts(PUB_A)] == ["Good"]
def test_forget_drops_one_contact(tmp_path: Path) -> None:
"""Forgetting removes a single remembered contact and persists the change."""
store = ContactStore(tmp_path / "contacts.json")
store.remember_all(PUB_A, [_contact("Al", "cc"), _contact("Bob", "dd")])
store.forget(PUB_A, "cc" * 32)
assert [c.name for c in store.contacts(PUB_A)] == ["Bob"]
# --- RememberedContact <-> Contact -------------------------------------------
def test_remembered_contact_round_trip() -> None:
"""A live contact distils to remembered fields and rebuilds with them intact."""
heard = datetime(2026, 7, 20, 12, 0, 0, tzinfo=timezone.utc)
live = _contact("Alice", "cc", node_type=NODE_TYPE_CHAT, last_seen=heard, lat=45.5, lon=-73.6)
remembered = RememberedContact.from_contact(live)
assert remembered.public_key == "cc" * 32 and remembered.last_advert == int(heard.timestamp())
rebuilt = remembered.to_contact()
assert rebuilt.name == "Alice"
assert rebuilt.public_key == "cc" * 32 and rebuilt.key_prefix == "cc" * 6
assert rebuilt.last_seen == heard
assert rebuilt.node_type == NODE_TYPE_CHAT and rebuilt.lat == 45.5 and rebuilt.lon == -73.6
assert rebuilt.route_hops is None # a remembered contact floods until a path is relearned
# --- merge -------------------------------------------------------------------
def test_merge_unions_remembered_the_device_forgot(tmp_path: Path) -> None:
"""Merge appends remembered contacts the device forgot, without duplicating present ones."""
store = ContactStore(tmp_path / "contacts.json")
store.remember_all(PUB_A, [_contact("Al", "cc"), _contact("Bob", "dd"), _contact("Cy", "ee")])
live = [_contact("Al", "cc")] # the device only currently reports Al
merged = merge_contacts(store, PUB_A, live)
names = [c.name for c in merged]
assert names[0] == "Al" # live first, untouched
assert set(names) == {"Al", "Bob", "Cy"} # the two forgotten ones are unioned back in
assert names.count("Al") == 1 # present contact not duplicated
def test_merge_adds_nothing_when_device_reports_all(tmp_path: Path) -> None:
"""A device reporting its whole table (a firmware radio) gets no additions."""
store = ContactStore(tmp_path / "contacts.json")
live = [_contact("Al", "cc"), _contact("Bob", "dd")]
store.remember_all(PUB_A, live)
assert len(merge_contacts(store, PUB_A, live)) == 2
# --- DeviceState integration -------------------------------------------------
async def test_devstate_remembers_and_restores_forgotten_contacts(ctx) -> None:
"""Reading contacts remembers them; a device that then forgets its table still lists them."""
device = await ctx.device()
original = await ctx.devstate.contacts(force=True) # first read remembers the mock's table
original_keys = {c.public_key for c in original if c.public_key}
assert original_keys # the simulator ships a non-empty contact table
# The bridge "restarts": its RAM contact table is wiped. A fresh read finds nothing live...
device._contacts = []
restored = await ctx.devstate.contacts(force=True)
restored_keys = {c.public_key for c in restored}
# ...yet every contact we'd remembered is merged back in and stays messageable.
assert original_keys <= restored_keys
messageable = {c.public_key for c in original if is_direct_messageable(c.node_type)}
still = {c.public_key for c in restored if is_direct_messageable(c.node_type)}
assert messageable <= still
async def test_devstate_merge_keeps_a_repeater_a_repeater(ctx) -> None:
"""A remembered repeater rebuilds with its type, so the DM filter still excludes it."""
device = await ctx.device()
device._contacts = [
Contact(name="Big-Repeater", public_key="ab" * 32, key_prefix="ab" * 6,
node_type=NODE_TYPE_REPEATER),
]
await ctx.devstate.contacts(force=True) # remember it
device._contacts = [] # forget it
restored = await ctx.devstate.contacts(force=True)
repeater = next(c for c in restored if c.public_key == "ab" * 32)
assert repeater.node_type == NODE_TYPE_REPEATER
assert not is_direct_messageable(repeater.node_type)