A sent channel message shows whether it went past your near relays

A channel has no acknowledgement, but the radio hears each repeater that
relays our message, and each copy names the relays that it went through.
The end of our channel message now shows a spinner, then a check and the
number of relays past the near relays (the first hops of the outbound
paths that apply), a warning when only the near relays sent it back, or a
cross when no relay did. A near relay is near by identity, at any place
in a path. Managed nodes play no part: a remote managed repeater counts.

- services/heard_by.py: the verdict, and a tracker that fills in the
  background and refreshes on each channel packet. Settled verdicts are
  stored (schema 24, heard_relays), with the near relays of each send.
- The picked message names the relays and the near relay that carried it.
- ^P counts the relays past the near relays.
- chat history --channel: a HEARD lane; --json gives heard, heard_by,
  heard_via.
- New preference heard_wait_s (Relay wait, 30 s).
- Fix: a copy of our own channel message must carry the time of that
  send, so two messages with the same text no longer share copies.

Closes #38

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5.5 committed 2026-11-20 20:29:59 -05:00
1 parent fa912032a3
commit f4b1d659d1
14 files changed
+1162 -23

No files matched your search

+26
View File
@@ -9,6 +9,32 @@ can change how things behave. It does not only add new things.
## [Unreleased]
### Added
- **A channel message that you send shows whether it went past your own repeaters.** A
channel has no acknowledgement, but your radio hears each repeater that relays your
message, and each copy names the relays that it went through. The end of your message
shows a spinner, then `✓` and the number of relays that heard it past your **near
relays**. Your near relays are the first hops of the outbound paths of your active site.
At home, a relay by the repeater next to you proves only that the message left your
radio. `⚠` means that only your near relays sent it back, and `✗` means that no relay
sent it back. A copy that comes late changes the mark. Select the message to see the
names of the relays, and which of your near relays carried it out. The wait is the new
*Relay wait* preference (`heard_wait_s`, 30 s). With no outbound paths, each relay
counts. MeshTerm sees only the relays that your radio hears, and only while it is
connected. `meshterm chat history --channel` shows the same verdict in a `HEARD` column,
and `--json` gives `heard`, `heard_by`, and `heard_via` (#38).
- **^P on your own channel message counts the relays past your near relays.** The line
under the quote of the message adds `3 past your near relays` to the copies and paths
that it already counted.
### Fixed
- **Two channel messages with the same text no longer share their copies.** The paths
dialog matched a copy of your channel message by its text in a window of 15 minutes. Two
"test" messages a few minutes apart then showed the copies of both. Now a copy of your
own message must also carry the time of that send.
## [0.13.0] - 2026-11-20
**MeshTerm shows the pixel images that other MeshCore apps send.** A channel message can
+26 -1
View File
@@ -1145,6 +1145,27 @@ $ meshterm --absolute chat history --to Alice
takes the rest of the line. A message body is the one field that can hold any text, so no
column can follow it.
**Relays.** A channel has no acknowledgement. But your radio hears the repeaters that relay
your message, and each copy names the relays that it went through. The `history` of a
channel has a `HEARD` column for each of your own messages:
```console
$ meshterm chat history --channel 0
TIME DIR PEER SNR_DB HEARD TEXT
12m in Public +6.5 - Alice: anyone on the ridge?
10m out Public - 3 heading up now
4m out Public - near at the top
now out Public - wait coming down
```
A number is the count of relays past your **near relays**: the first hop of each outbound
path of the active site, or of the fixed device (refer to `meshterm outbound`). These
relays heard your message, so it went farther than the repeaters next to you. `near`
means that only your near relays sent it back. `none` means that no relay sent it back.
`wait` means that the message is still in its wait (the `heard_wait_s` preference). With
no outbound paths, each relay counts. MeshTerm sees only the relays that your radio hears,
and only while it is connected. A received message has no value (`-`).
**Rooms.** A room server is a message board that lives on a radio. First, join the room
with [`meshterm rooms join`](#meshterm-rooms). After that, post with `send --to`, in the
same way as a direct message. `acked yes` means that the room stored the post. It does
@@ -1222,7 +1243,10 @@ $ meshterm chat send "all clear" --channel 0 --scope '*' --json
the purpose of the one absence token. It is also the reason why the plain face prints
nothing there: it has no way to say it.
`history` is an array, with the oldest message first:
`history` is an array, with the oldest message first. Each record also has `heard`
(`"waiting"`, `"beyond"`, `"nearby"`, `"unheard"`, or `null` when the message is not
your own channel message), `heard_by` (the hashes of the relays past your near relays),
and `heard_via` (the near relays that carried the message out):
```json
{"created_at":"2026-09-08T08:27:37Z","direction":"out","node":{"name":"Alice","key":null,"hash":"d4e5f6a7","type":null,"self":false},"channel":null,"author":null,"snr_db":null,"text":"on my way","acked":true}
@@ -2002,6 +2026,7 @@ flood_advert_cooldown_s 60 60
weekly_flood_advert off off Flood an advert after a week without one
advert_quiet_s 30 30 Silence to wait for before the weekly advert
direct_message_soft_retries 0 0 Times to resend a message that gets no reply
heard_wait_s 30 30 Wait this long for a relay of a channel message
room_relogin_minutes 30 30 Opening a room this quiet logs in again
tx_opt_min 18 18 Weakest power it will try
tx_opt_max 28 28 Strongest power it will try
+1
View File
@@ -183,6 +183,7 @@ and in quoted text.
| path | An ordered list of hops that you write or force (`a1,3d,…`) | |
| route | The sequence of nodes that a trace went through or will go through | |
| hop | One node in a path or a route | |
| near relay | The first hop of an outbound path that applies now. A copy of our channel message that only near relays sent back proves that the message left our radio, not that it went farther | own repeater, home repeater, local relay |
| outbound path | A path that starts at our node and goes out into the mesh, one or more hops long. The user trusts it for the first hops of a route, because the user knows which way out works | outbound leg (for this: an outbound leg is the outbound half of a trace) |
| site | A name for where the user takes the computer (`Home`, `Foulab`), with its outbound paths in order. One site is active | profile (for this: a profile is a connection alias in `config.toml`) |
| fixed device | A companion that never moves. It keeps its own outbound paths, and the active site does not apply to it | |
+1 -1
View File
@@ -15,7 +15,7 @@ This page lists each interactive screen with its scripted equivalent, where one
| Feature | What it does | Scripted |
| --- | --- | --- |
| **💬 Chat** | Live full-screen messages on channels and to contacts. The transcript scrolls, the input line stays at the bottom, and sent and received messages appear together. The rooms that you joined are also here. Each post shows under the name of its author. MeshTerm stores each message. Unread counts show in the menu header. To see each path on which a message reached your node, select the message and press ^P. Enter on a path opens a trace of that route: back to the sender of a received message, or out to the contact of a sent direct message. When the trace comes home, the Device route row can make that route the radio's route to the contact. | `meshterm chat send / history / list / listen` |
| **💬 Chat** | Live full-screen messages on channels and to contacts. The transcript scrolls, the input line stays at the bottom, and sent and received messages appear together. The rooms that you joined are also here. Each post shows under the name of its author. MeshTerm stores each message. Unread counts show in the menu header. To see each path on which a message reached your node, select the message and press ^P. Your own channel message shows whether it went past your near relays (the first hops of your outbound paths): a spinner, then `✓` and the number of relays that heard it, `⚠` when only your near relays sent it back, or `✗` when no relay did. Enter on a path opens a trace of that route: back to the sender of a received message, or out to the contact of a sent direct message. When the trace comes home, the Device route row can make that route the radio's route to the contact. | `meshterm chat send / history / list / listen` |
| **📻 Channels** | Create, join, reorder, mute, and share mesh channels. You can share a channel with a QR code or a `meshcore://` link. If you give a channel a **send scope**, its messages are flooded into one region. Only the repeaters that carry that region relay them. When you change to a new device, export all the channels to a file, then import the file on the new device. The **channel guide** lists the public channels that MeshTerm heard, also the channels that are not on your device, and adds one with Enter. | `meshterm channels list / add / join / import / share / clear / scope / export / guide` |
| **📌 Rooms** | Each room server that your radio knows. A room server is a message board on a radio. It keeps the latest posts and sends you the posts that you missed. Join a room with its password. If a room does not answer, MeshTerm tells you what it knows and offers the next step to try. For example, it can send again by flood when the route that your radio learned is no longer good. When the clock of a room goes back (often after a reboot), the room sends you no new post, because each new post looks older than the ones that you have. The node page of the room then says so and offers to ask for all its posts again. | `meshterm rooms list / join / forget` |
| **📨 Courier** | A store-and-forward outbox for contacts that you cannot reach yet. Queue a message. MeshTerm sends it when the contact is next heard, or at a time that you set. It tracks the acks, and it waits longer between each try (exponential backoff). | `meshterm courier queue / list / send / cancel / clear` |
+15
View File
@@ -326,6 +326,21 @@ PREFERENCES: tuple[PrefSpec, ...] = (
minimum=0,
maximum=2,
),
PrefSpec(
key="heard_wait_s",
label="Relay wait",
help="Wait this long for a relay of a channel message",
group="Sending",
value_type="int",
# A channel message that we sent shows a spinner until a relay that is not a near
# relay sends a copy back, or until this wait is over. Then it shows ⚠ (only near
# relays) or ✗ (no copy). A flood goes out through the mesh in seconds, and 30 s
# also covers a busy channel (refer to meshterm.services.heard_by).
default=30,
minimum=5,
maximum=600,
unit="s",
),
PrefSpec(
key="room_relogin_minutes",
label="Room re-login",
+12 -1
View File
@@ -12,7 +12,7 @@ import json
import sqlite3
from pathlib import Path
SCHEMA_VERSION = 23
SCHEMA_VERSION = 24
_SCHEMA = """
CREATE TABLE IF NOT EXISTS schema_meta (
@@ -189,6 +189,17 @@ CREATE TABLE IF NOT EXISTS node_places (
found_at TEXT NOT NULL -- UTC ISO-8601
);
-- Our own channel messages: whether a relay that is not one of our near relays heard them
-- (refer to meshterm.services.heard_by). near_hops is a JSON list of the near relays at the
-- time of the send. paths is a JSON list of the relay paths of the copies that came back,
-- written one time when the message is out of the match window of the packet log. NULL:
-- not settled yet.
CREATE TABLE IF NOT EXISTS heard_relays (
message_id INTEGER PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
near_hops TEXT,
paths TEXT
);
CREATE INDEX IF NOT EXISTS idx_traces_run ON traces(run_id);
CREATE INDEX IF NOT EXISTS idx_trace_hops_trace ON trace_hops(trace_id);
CREATE INDEX IF NOT EXISTS idx_tx_samples_run ON tx_samples(run_id);
+70
View File
@@ -2252,6 +2252,76 @@ class Repository:
self._conn.execute("UPDATE messages SET acked = ? WHERE id = ?", (int(acked), message_id))
self._conn.commit()
# -- relays that heard our channel messages ---------------------------------------
def set_near_hops(self, message_id: int, near: tuple[str, ...]) -> None:
"""Keep the near relays at the time that one of our channel messages went out.
Thus a change of site later does not change the verdict of the message (refer to
:mod:`~meshterm.services.heard_by`).
Args:
message_id: The ``messages`` row of the sent message.
near: The near relays, as lowercase hex.
"""
self._conn.execute(
"INSERT INTO heard_relays (message_id, near_hops) VALUES (?, ?) "
"ON CONFLICT(message_id) DO UPDATE SET near_hops = excluded.near_hops",
(message_id, json.dumps(list(near))),
)
self._conn.commit()
def settle_heard(
self, message_id: int, near: tuple[str, ...], paths: list[tuple[str, ...]]
) -> None:
"""Store the relay paths of the copies of one message, when no more can come.
Args:
message_id: The ``messages`` row of the sent message.
near: The near relays that the verdict used.
paths: The relay paths of the copies that came back. An empty list is a stored
"no copy came back".
"""
self._conn.execute(
"INSERT INTO heard_relays (message_id, near_hops, paths) VALUES (?, ?, ?) "
"ON CONFLICT(message_id) DO UPDATE SET near_hops = excluded.near_hops, "
"paths = excluded.paths",
(message_id, json.dumps(list(near)), json.dumps([list(p) for p in paths])),
)
self._conn.commit()
def heard_records(
self, message_ids: list[int]
) -> dict[int, tuple[tuple[str, ...] | None, list[tuple[str, ...]] | None]]:
"""The stored near relays and relay paths of some of our channel messages.
Args:
message_ids: The ``messages`` rows to read.
Returns:
For each row that has a record: the near relays (``None`` when they were not
kept), and the relay paths (``None`` when the message is not settled yet).
"""
out: dict[int, tuple[tuple[str, ...] | None, list[tuple[str, ...]] | None]] = {}
ids = [int(i) for i in message_ids if i is not None]
for start in range(0, len(ids), 500):
part = ids[start : start + 500]
marks = ",".join("?" * len(part))
rows = self._conn.execute(
f"SELECT message_id, near_hops, paths FROM heard_relays "
f"WHERE message_id IN ({marks})",
part,
).fetchall()
for row in rows:
near = tuple(json.loads(row["near_hops"])) if row["near_hops"] else None
paths = (
[tuple(p) for p in json.loads(row["paths"])]
if row["paths"] is not None
else None
)
out[int(row["message_id"])] = (near, paths)
return out
def delete_chat_history(self, peer: str | None) -> int:
"""Delete all the stored messages of one direct conversation.
+11
View File
@@ -834,6 +834,17 @@ class ChatService:
scope=await self._sent_under(asked),
)
chat.row_id = self._ctx.repo.record_chat_message(chat, run_id=self._run_id)
# The near relays of this send, so that a later change of site does not change
# whether the message went past them (refer to meshterm.services.heard_by).
if getattr(self._ctx, "outbound_store", None) is not None:
try:
from .heard_by import near_relays
from .outbound import current_choice
choice = await current_choice(self._ctx)
self._ctx.repo.set_near_hops(chat.row_id, near_relays(choice.paths))
except Exception as exc: # noqa: BLE001 - the message went out. Only the mark is less exact
self._ctx.log.debug("couldn't keep the near relays of a send: %s", exc)
return chat
async def _sent_under(self, asked: str | None) -> str | None:
+347
View File
@@ -0,0 +1,347 @@
# SPDX-License-Identifier: Apache-2.0
"""Tell whether a channel message that we sent went past our own repeaters (issue #38).
A channel broadcast has no acknowledgement. But the device hears the relay of our
broadcast by each repeater in range, and its RX log records each copy with the path that
the copy went through (refer to :mod:`~meshterm.services.message_paths`). Each hop in that
path heard the message. Thus the copies that come back are the proof that somebody heard
it.
A copy from a repeater next to us proves little: it shows that the message left our
radio. The user names these repeaters already, as the first hops of the **outbound
paths** of the active site or of a fixed device (refer to
:mod:`~meshterm.core.outbound_store`). This module calls them the **near relays**. Each
other hop in a copy is a relay that is not near, and it proves that the message went
farther. A near relay is near by its identity, not by its place in a path: the path
``UpperSalaberry → Cartierville`` has two near relays at home, and no other relay.
A managed node is not a near relay. The user can manage a repeater on the other side of
the city, and a relay by that repeater is good proof that the message went out.
The verdict of a message has four states:
* :data:`WAITING`: no relay that is not near was heard yet, and the wait
(``heard_wait_s``) is not over. The chat shows a spinner.
* :data:`BEYOND`: one or more relays that are not near heard it. The chat shows ``✓`` and
the number of these relays.
* :data:`NEARBY`: after the wait, only near relays sent a copy back. The chat shows ``⚠``.
* :data:`UNHEARD`: after the wait, no copy came back. The chat shows ``✗``.
A copy that comes back late changes the verdict, as a late acknowledgement does for a
direct message. After the match window of the packet log
(:data:`~meshterm.services.message_paths.CHANNEL_WINDOW`), nothing can change it, and
MeshTerm stores the paths, so that the next visit does not decrypt the log again.
Two limits stay. MeshTerm sees only the relays that our radio hears, so a relay farther
away than that never shows. And MeshTerm must be connected while the copies come back.
Nothing in this module transmits. It is a read-model over the repository.
"""
from __future__ import annotations
import asyncio
from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass, field
from datetime import datetime
from typing import TYPE_CHECKING
from ..core.models import ChatMessage, utcnow
from .message_paths import CHANNEL_WINDOW, Arrival, channel_arrivals
if TYPE_CHECKING:
from ..context import AppContext
from ..persistence.repository import Repository
#: The verdict states (refer to the module docstring).
WAITING = "waiting"
BEYOND = "beyond"
NEARBY = "nearby"
UNHEARD = "unheard"
#: The number of messages that :meth:`HeardTracker.fill` examines before each yield to the
#: event loop. Each one is a query of the packet log and some decryptions.
_CHUNK = 4
#: A relay path, as hop hashes in the order of propagation.
RelayPath = tuple[str, ...]
@dataclass(frozen=True, slots=True)
class HeardBy:
"""The verdict on one channel message that we sent.
Attributes:
state: :data:`WAITING`, :data:`BEYOND`, :data:`NEARBY`, or :data:`UNHEARD`.
beyond: The hashes of the relays that are not near, in the order first heard.
Each one heard the message.
via: The near relays that started the copies that went farther, in the order first
heard. Thus the user sees which of the repeaters at home carried the message
out.
copies: The number of copies that came back.
"""
state: str
beyond: tuple[str, ...] = ()
via: tuple[str, ...] = ()
copies: int = 0
def near_relays(paths: Iterable[Sequence[str]]) -> tuple[str, ...]:
"""The first hop of each outbound path, without duplicates, in order.
Args:
paths: The outbound paths that apply
(:attr:`~meshterm.core.outbound_store.OutboundChoice.paths`).
Returns:
The near relays, as lowercase hex.
"""
out: list[str] = []
for path in paths:
if path:
hop = str(path[0]).lower()
if hop not in out:
out.append(hop)
return tuple(out)
def is_near(hop: str, near: Sequence[str]) -> bool:
"""Whether a hop of a path is one of the near relays.
A hop in a packet path is a hash: one to three bytes of the key. A near relay is a
longer key prefix. The hop matches when one starts with the other. When two
repeaters share a one-byte hash, a relay that is not near can match a near relay. Then
the count is too low, but it never claims a relay that did not occur.
"""
hop = hop.lower()
return bool(hop) and any(n.startswith(hop) or hop.startswith(n) for n in near)
def relay_paths(arrivals: Iterable[Arrival]) -> list[RelayPath]:
"""The paths of the copies that tell which relays heard the message.
A copy with no hops tells nothing (a flood of ours always comes back through a relay),
and a direct-routed copy that used all its route tells nothing either (refer to
:attr:`~meshterm.services.message_paths.Arrival.route_known`).
"""
return [a.hops for a in arrivals if a.hops and a.route_known]
def judge(
paths: Sequence[RelayPath], near: Sequence[str], *, age_s: float, wait_s: float
) -> HeardBy:
"""The verdict on a message from the paths of its copies.
Args:
paths: The relay paths of the copies that came back, in the order heard.
near: The near relays at the time of the send.
age_s: The time since the send, in seconds.
wait_s: The wait before "no relay" becomes the verdict (``heard_wait_s``).
Returns:
The verdict.
"""
beyond: list[str] = []
via: list[str] = []
for path in paths:
far = [hop.lower() for hop in path if not is_near(hop, near)]
for hop in far:
if hop not in beyond:
beyond.append(hop)
if far:
for hop in path:
if hop.lower() == far[0]:
break
if hop.lower() not in via:
via.append(hop.lower())
if beyond:
state = BEYOND
elif age_s < wait_s:
state = WAITING
elif paths:
state = NEARBY
else:
state = UNHEARD
return HeardBy(state, tuple(beyond), tuple(via), len(paths))
@dataclass(slots=True)
class _Record:
"""What the tracker knows about one message: its near relays, and the copies so far."""
near: tuple[str, ...]
paths: list[RelayPath] = field(default_factory=list)
settled: bool = False
class HeardTracker:
"""The verdicts on our channel messages in one conversation, kept current.
The chat screen reads :meth:`verdict` at each paint, and that read never touches the
packet log. The work is in :meth:`fill`, which runs in the background when the screen
opens, and in :meth:`refresh`, which the screen calls when the device hears a channel
packet. A message that is out of the match window is **settled**: MeshTerm stores its
paths one time, and reads them back on the next visit.
"""
def __init__(
self,
repo: Repository,
*,
channel_name: str,
secret: bytes | None,
near_now: tuple[str, ...],
wait_s: Callable[[], float],
clock: Callable[[], datetime] = utcnow,
) -> None:
"""Make a tracker for one channel.
Args:
repo: The repository with the packet log and the stored verdicts.
channel_name: The name of the channel (for the decryption).
secret: The key of the channel. With no key, nothing can be matched, and each
verdict is ``None``.
near_now: The near relays that apply now. A message sent before MeshTerm kept
the near relays of each send uses these.
wait_s: Gives the ``heard_wait_s`` preference, read at each verdict.
clock: Gives the current time (a fixed clock in the tests).
"""
self._repo = repo
self._channel_name = channel_name
self._secret = secret
self._near_now = near_now
self._wait_s = wait_s
self._clock = clock
self._records: dict[int, _Record] = {}
self._revision = 0
@property
def revision(self) -> int:
"""A number that changes each time that a verdict can have changed."""
return self._revision
def _ours(self, message: ChatMessage) -> bool:
return bool(self._secret and message.outbound and message.is_channel and message.row_id)
def _age_s(self, message: ChatMessage) -> float:
return (self._clock() - message.created_at).total_seconds()
def verdict(self, message: ChatMessage) -> HeardBy | None:
"""The verdict on one message, or ``None`` when there is none to show.
``None`` is for a message that is not our own channel message, and for one that
:meth:`fill` did not examine yet.
"""
if not self._ours(message):
return None
record = self._records.get(message.row_id) # type: ignore[arg-type]
if record is None:
return None
return judge(record.paths, record.near, age_s=self._age_s(message), wait_s=self._wait_s())
def note_sent(self, message: ChatMessage) -> None:
"""Start the verdict of a message that was sent while the screen is open."""
if self._ours(message):
self._records[message.row_id] = _Record(near=self._near_now) # type: ignore[index]
self._revision += 1
async def fill(self, messages: Sequence[ChatMessage]) -> None:
"""Examine each of our channel messages, the newest first, in small steps.
The settled verdicts come from storage in one query. Each other message costs a
query of the packet log, so the work yields to the event loop after each few.
Args:
messages: The transcript of the conversation.
"""
ours = [m for m in messages if self._ours(m)]
stored = self._repo.heard_records([m.row_id for m in ours]) # type: ignore[misc]
for message in ours:
near, paths = stored.get(message.row_id, (None, None)) # type: ignore[arg-type]
if paths is not None:
self._records[message.row_id] = _Record( # type: ignore[index]
near=near if near is not None else self._near_now,
paths=list(paths),
settled=True,
)
self._revision += 1
todo = [m for m in reversed(ours) if m.row_id not in self._records]
for start in range(0, len(todo), _CHUNK):
for message in todo[start : start + _CHUNK]:
near, _paths = stored.get(message.row_id, (None, None)) # type: ignore[arg-type]
self._examine(message, near if near is not None else self._near_now)
self._revision += 1
await asyncio.sleep(0)
def refresh(self, messages: Sequence[ChatMessage]) -> bool:
"""Examine again the messages that are not settled, after a new channel packet.
Args:
messages: The transcript of the conversation.
Returns:
``True`` when a verdict can have changed.
"""
changed = False
for message in messages:
if not self._ours(message):
continue
record = self._records.get(message.row_id) # type: ignore[arg-type]
if record is None or record.settled:
continue
before = list(record.paths)
self._examine(message, record.near)
changed = changed or self._records[message.row_id].paths != before # type: ignore[index]
if changed:
self._revision += 1
return changed
def waiting(self, messages: Sequence[ChatMessage]) -> bool:
"""Whether one of the messages shows the spinner now."""
return any((v := self.verdict(m)) is not None and v.state == WAITING for m in messages)
def _examine(self, message: ChatMessage, near: tuple[str, ...]) -> None:
"""Match the copies of one message in the packet log, and settle it if it is old."""
assert self._secret is not None and message.row_id is not None
arrivals = channel_arrivals(
self._repo, message, channel_name=self._channel_name, secret=self._secret
)
paths = relay_paths(arrivals)
settled = self._age_s(message) > CHANNEL_WINDOW.total_seconds()
self._records[message.row_id] = _Record(near=near, paths=paths, settled=settled)
if settled:
self._repo.settle_heard(message.row_id, near, paths)
async def make_tracker(
ctx: AppContext, *, channel_name: str, secret: bytes | None
) -> HeardTracker | None:
"""A tracker for one channel, with the near relays that apply now.
Args:
ctx: The shared application context (the repository, the outbound paths, and the
preferences).
channel_name: The name of the channel.
secret: The key of the channel. With no key, there is no tracker.
Returns:
The tracker, or ``None`` when the channel has no key at hand.
"""
if not secret:
return None
from .outbound import current_choice
near: tuple[str, ...] = ()
if getattr(ctx, "outbound_store", None) is not None:
try:
near = near_relays((await current_choice(ctx)).paths)
except Exception: # noqa: BLE001 - with no outbound paths, each relay counts
near = ()
return HeardTracker(
ctx.repo,
channel_name=channel_name,
secret=secret,
near_now=near,
wait_s=lambda: float(ctx.preferences.heard_wait_s),
)
+18 -3
View File
@@ -15,7 +15,9 @@ message reached our node:
recover the plaintext. A packet whose text is equal to the text of the message is one
arrival of that message. The comparison accepts the ``Name: `` sender prefix on either
side. Our own broadcasts are included, because the device overhears the relay of our
broadcast by a repeater and logs it like all other packets.
broadcast by a repeater and logs it like all other packets. For our own broadcast, the
sender time in the packet must also be near the stored time of the send. Thus two
messages with the same text a few minutes apart do not share their copies.
* **Direct messages** go in ECDH-encrypted ``TEXT_MSG`` packets that only the recipient
can decrypt. Thus a match by content is not possible from the log. But such a packet
carries its **addressing and its MAC** in clear text (:mod:`~meshterm.core.frames`): the
@@ -55,7 +57,14 @@ if TYPE_CHECKING:
#: The span of the log that MeshTerm searches around a channel message. It is wide,
#: because an inbound message has the time of the sender's clock, and that clock can be
#: minutes different from our clock.
_CHANNEL_WINDOW = timedelta(minutes=15)
CHANNEL_WINDOW = timedelta(minutes=15)
#: The largest difference between the sender time in a copy of our own channel message and
#: the time that MeshTerm stored for the send. The library puts the clock of the computer
#: on the packet, and MeshTerm stores the time after the companion accepts it. Two
#: messages with the same text ("test") inside the match window are then two different
#: messages, and not one message with the copies of both.
_SEND_SLACK = timedelta(seconds=10)
#: The span of the log that MeshTerm searches around a direct message, before the other
#: messages of the conversation make it narrower (refer to :func:`direct_window`). This
@@ -194,7 +203,7 @@ def channel_arrivals(
# Around the arrival time, not the sender time: a sender with a wrong clock put the
# window hours or years away from its packets.
at = message.arrived_at
frames = repo.packet_frames_between(at - _CHANNEL_WINDOW, at + _CHANNEL_WINDOW)
frames = repo.packet_frames_between(at - CHANNEL_WINDOW, at + CHANNEL_WINDOW)
arrivals: list[Arrival] = []
for frame in frames:
raw = frame.raw if isinstance(frame.raw, dict) else {}
@@ -208,6 +217,12 @@ def channel_arrivals(
decrypted = decrypt_channel_text(chan_hash, cipher_mac, crypted, [(channel_name, secret)])
if decrypted is None or not _texts_match(decrypted.text, message.text):
continue
if (
message.outbound
and decrypted.sent_at is not None
and abs(decrypted.sent_at - message.created_at) > _SEND_SLACK
):
continue
arrivals.append(
Arrival(
when=frame.observed_at,
+72 -5
View File
@@ -80,6 +80,7 @@ if TYPE_CHECKING:
from datetime import datetime
from ..core.channel_probe import ChannelSlot
from ..services.heard_by import HeardBy
from ..ui.report import Facts, Listing
#: The number of recent messages that ``chat history`` prints by default.
@@ -419,12 +420,14 @@ class ChatTool(Tool):
room = False
name_of: NodeResolver | None = None
me: NodeRef | None = None
heard: Callable[[ChatMessage], HeardBy | None] | None = None
if channel is not None:
channel_id = await ctx.chat.channel_id_for(int(channel))
messages = ctx.repo.recent_chat_messages(
is_channel=True, channel_id=channel_id, limit=limit
)
label = f"#{channel}"
heard = await _channel_verdicts(ctx, int(channel), messages)
else:
device = await ctx.device()
contacts = await device.get_contacts()
@@ -443,7 +446,7 @@ class ChatTool(Tool):
return ToolResult(
summary={"conversation": label, "messages": len(messages)},
report=(_transcript(messages, room=room, name_of=name_of, me=me),),
report=(_transcript(messages, room=room, name_of=name_of, me=me, heard=heard),),
exit_code=exitcodes.OK if messages else exitcodes.NO_RESULT,
)
@@ -1255,7 +1258,7 @@ def _channel_ref(idx: int | None, label: str, secret: bytes | None) -> ChannelRe
)
def _message_columns(*, author_lane: bool = False) -> tuple:
def _message_columns(*, author_lane: bool = False, heard_lane: bool = False) -> tuple:
"""The columns of one transcript row, shared by ``history`` and the ``listen`` stream.
``DIR`` holds what the transcript of the menu writes into its sender lane as the word
@@ -1282,7 +1285,7 @@ def _message_columns(*, author_lane: bool = False) -> tuple:
"""
from dataclasses import replace
from ..ui import fields
from ..ui import fields, report
peer = fields.plain_only(fields.name("conversation", "PEER"))
when = fields.plain_only(fields.when("shown_at", "TIME"))
@@ -1308,8 +1311,20 @@ def _message_columns(*, author_lane: bool = False) -> tuple:
fields.channel("channel", lanes=()),
_author_column(lane=author_lane),
fields.snr("snr_db", "SNR_DB"),
*(
(
fields.plain_only(
report.Column(key="heard_cell", lanes=(report.Lane(header="HEARD"),))
),
)
if heard_lane
else ()
),
fields.free("text", "TEXT"),
fields.hidden("acked"),
fields.hidden("heard"),
fields.hidden("heard_by"),
fields.hidden("heard_via"),
)
@@ -1355,12 +1370,38 @@ def _author_ref(author: str, name_of: NodeResolver | None) -> NodeRef:
return NodeRef(name=label if key else None, hash=author)
async def _channel_verdicts(
ctx: AppContext, channel: int, messages: list[ChatMessage]
) -> Callable[[ChatMessage], HeardBy | None] | None:
"""The verdicts on our messages in a channel: did a relay past the near relays hear them?
Refer to :mod:`~meshterm.services.heard_by`. With no key for the slot, there is no
verdict, and the column is absent on each row.
"""
from ..services.heard_by import make_tracker
try:
device = await ctx.device()
payload = await device.get_channel(channel)
raw = (payload or {}).get("channel_secret")
secret = bytes(raw) if raw else None
name = str((payload or {}).get("channel_name") or f"#{channel}")
except Exception: # noqa: BLE001 - no key, no verdict. The history still prints
return None
tracker = await make_tracker(ctx, channel_name=name, secret=secret)
if tracker is None:
return None
await tracker.fill(messages)
return tracker.verdict
def _transcript(
messages: list[ChatMessage],
*,
room: bool = False,
name_of: NodeResolver | None = None,
me: NodeRef | None = None,
heard: Callable[[ChatMessage], HeardBy | None] | None = None,
) -> Listing:
"""The stored messages of a conversation, oldest first, one record for each.
@@ -1371,6 +1412,9 @@ def _transcript(
each row).
name_of: Names the key of an author, for a room.
me: Our node, the author of our own posts in a room.
heard: Gives the verdict on each of our channel messages (refer to
:mod:`~meshterm.services.heard_by`). With it, the plain face has a ``HEARD``
lane. The document always has ``heard``, ``heard_by``, and ``heard_via``.
"""
from ..ui.report import Listing
@@ -1383,6 +1427,7 @@ def _transcript(
else None
)
corrected = message.corrected(tolerance)
verdict = heard(message) if heard is not None else None
rows.append(
{
"created_at": message.created_at,
@@ -1403,16 +1448,38 @@ def _transcript(
"snr_db": message.snr,
"text": message.text,
"acked": message.acked,
"heard": verdict.state if verdict is not None else None,
"heard_by": list(verdict.beyond) if verdict is not None else None,
"heard_via": list(verdict.via) if verdict is not None else None,
"heard_cell": _heard_cell(verdict),
}
)
lanes = ("TIME", "DIR", "AUTHOR" if room else "PEER", "SNR_DB")
return Listing(
key="messages",
columns=_message_columns(author_lane=room),
columns=_message_columns(author_lane=room, heard_lane=heard is not None),
rows=rows,
order=("TIME", "DIR", "AUTHOR" if room else "PEER", "SNR_DB", "TEXT"),
order=(*lanes, "HEARD", "TEXT") if heard is not None else (*lanes, "TEXT"),
)
def _heard_cell(verdict: HeardBy | None) -> str:
"""The plain ``HEARD`` cell: the number of relays past the near relays, or a word.
``near`` is a message that only the near relays sent back, ``none`` is one that no
relay sent back, and ``wait`` is one that is still in its wait. A message that is not
ours has no verdict (``-``).
"""
from ..services.heard_by import BEYOND, NEARBY, UNHEARD, WAITING
from ..ui import script
if verdict is None:
return script.NONE
if verdict.state == BEYOND:
return str(len(verdict.beyond))
return {NEARBY: "near", UNHEARD: "none", WAITING: "wait"}.get(verdict.state, script.NONE)
def _live_messages() -> Listing:
"""The shape that ``chat listen`` streams: what arrived, when it arrived.
+233 -12
View File
@@ -40,6 +40,7 @@ from ..core.models import (
)
from ..core.regions import WILDCARD
from ..platforms import Platform, on_platform
from ..services.heard_by import BEYOND, NEARBY, UNHEARD, WAITING, HeardBy, HeardTracker
from . import pixelart
from .compose import MentionEditor
from .pathline import PATH_INK, PathHop
@@ -87,6 +88,12 @@ _CORRECTED = ("?", "warn")
#: animated spinner instead (refer to :meth:`ChatScreen._delivery_glyph`).
_DELIVERED = ("✓", "ok")
_FAILED = ("✗", "err")
#: The mark of our channel message that only the near relays sent back: it left our radio,
#: and nothing proves that it went farther (refer to :mod:`~meshterm.services.heard_by`).
_NEAR_ONLY = ("⚠", "warn")
#: The time that the chat waits after a channel packet before it looks for copies of our
#: messages in the packet log. The recorder stores each packet in the background.
_HEARD_SETTLE_S = 1.0
#: A word between whitespace. The wrap moves a word only as a whole. Thus the run that a
#: wrap must not cut a URL in is the word that has the URL, with a bracket or a full stop
@@ -285,6 +292,8 @@ class ChatScreen(Screen):
self_name: str | None = None,
self_key: str | None = None,
resend_flood: Callable[[ChatMessage], Awaitable[ChatMessage]] | None = None,
heard: HeardTracker | None = None,
hop_name: Callable[[str], str] | None = None,
) -> None:
"""Build the chat screen.
@@ -328,8 +337,20 @@ class ChatScreen(Screen):
resend_flood: Like ``resend``, but it first forgets the route that the device
learned to the contact, so that the retry floods (direct chats only).
With ``None``, ^R always retries on the route, as it did before.
heard: The verdicts on our own channel messages: whether a relay that is not a
near relay sent a copy back (refer to :mod:`~meshterm.services.heard_by`).
With ``None`` (a direct chat, or a channel with no key), our channel
messages show no mark.
hop_name: Gives the name of a relay from its hash, for the note under a
selected message. With ``None``, the note shows the hashes.
"""
super().__init__()
self._heard_by = heard
self._hop_name: Callable[[str], str] = hop_name or (lambda hop: hop)
# The task that turns the spinner while one of our channel messages waits for a
# relay, and the task that examines the packet log again after a channel packet.
self._heard_ticker: asyncio.Task | None = None
self._heard_refresh: asyncio.Task | None = None
self._self_name = self_name
self._self_key = self_key
self._scope = scope if conversation.is_channel else None
@@ -714,7 +735,7 @@ class ChatScreen(Screen):
# the divider. The heading of a select list can also have its description.
self._sticky_headers = []
ids: list[int] = []
ackeds: list[bool | None] = []
ackeds: list[tuple] = []
selecteds: list[bool] = []
boundaries: list[int] = []
prev_group: tuple[bool, str] | None = None
@@ -739,14 +760,17 @@ class ChatScreen(Screen):
# A slice that the selection changes renders again, now and on the next paint
# after the selection leaves it: the selected message, and the head of its group.
marked = selected or idx == picked_head
pending = message.acked is None and message.outbound and not message.is_channel
mark_key = self._mark_key(message)
pending = (message.acked is None and message.outbound and not message.is_channel) or (
mark_key[1] is not None and mark_key[1][0] == WAITING
)
reusable = (
not marked
and not pending
and idx < cache_count
and not cached_selected[idx]
and cached_ids[idx] == id(message)
and cached_acked[idx] == message.acked
and cached_acked[idx] == mark_key
)
# A blank line closes the messages of an author and the messages of a day, where
# the preferences ask for it (:meth:`~meshterm.ui.tui.screen.Screen.section_spacing`,
@@ -791,7 +815,7 @@ class ChatScreen(Screen):
self._selected_end = len(lines)
prev_group, prev_day = group, day
ids.append(id(message))
ackeds.append(message.acked)
ackeds.append(mark_key)
selecteds.append(marked)
boundaries.append(len(lines))
@@ -963,6 +987,11 @@ class ChatScreen(Screen):
)
indent = prefix.cell_len
lines += render_hanging(Text(" " * indent), note, width, indent=indent)
heard = self._heard(message) if selected else None
heard_note = self._heard_note(heard) if heard is not None else None
if heard_note is not None:
indent = prefix.cell_len
lines += render_hanging(Text(" " * indent), heard_note, width, indent=indent)
if image is not None and self._show_images:
picture = pixelart.decoded(body)
if picture is not None:
@@ -998,6 +1027,11 @@ class ChatScreen(Screen):
if message.is_channel:
if message.acked is False:
text.append(" ⚠ no ack", style="warn")
else:
heard = self._heard(message)
if heard is not None:
text.append(" ")
text.append_text(self._heard_mark(heard))
text.append_text(self._scope_note(message))
else:
text.append(" ")
@@ -1087,6 +1121,122 @@ class ChatScreen(Screen):
glyph, style = _DELIVERED if acked else _FAILED
return Text(glyph, style=style)
# --- relays that heard our channel messages (issue #38) ------------------------
def _heard(self, message: ChatMessage) -> HeardBy | None:
"""The verdict on one of our channel messages, or ``None`` when it has no mark."""
return self._heard_by.verdict(message) if self._heard_by is not None else None
def _mark_key(self, message: ChatMessage) -> tuple:
"""What the mark at the end of a message depends on, for the render cache."""
heard = self._heard(message)
return (
message.acked,
None if heard is None else (heard.state, heard.beyond, heard.via),
)
def _heard_mark(self, heard: HeardBy) -> Text:
"""The mark at the end of our channel message: the marks of a direct message.
The spinner turns while no relay that is not near sent a copy back, until the
``heard_wait_s`` wait is over. Then ``✓`` and the number of these relays, ``⚠`` for
a message that only the near relays sent back, or ``✗`` for no copy at all.
"""
if heard.state == WAITING:
return self._spinner.text()
if heard.state == BEYOND:
glyph, style = _DELIVERED
return Text(f"{glyph} {len(heard.beyond)}", style=style)
if heard.state == NEARBY:
return Text(_NEAR_ONLY[0], style=_NEAR_ONLY[1])
glyph, style = _FAILED
return Text(glyph, style=style)
def _heard_note(self, heard: HeardBy) -> Text | None:
"""The line under a selected channel message of ours: which relays heard it."""
note = Text()
if heard.state == BEYOND:
names = ", ".join(self._hop_name(hop) for hop in heard.beyond)
note.append(f"{_DELIVERED[0]} ", style=_DELIVERED[1])
note.append(f"heard by {names}", style="muted")
if heard.via:
via = ", ".join(self._hop_name(hop) for hop in heard.via)
note.append(f" · via {via}", style="muted")
elif heard.state == NEARBY:
note.append(f"{_NEAR_ONLY[0]} ", style=_NEAR_ONLY[1])
note.append("only your near relays sent it back", style="muted")
elif heard.state == UNHEARD:
note.append(f"{_FAILED[0]} ", style=_FAILED[1])
note.append("no relay sent it back", style="muted")
else:
return None
return note
def start_heard(self) -> None:
"""Examine our channel messages in the background, then turn the spinners."""
if self._heard_by is None:
return
async def fill() -> None:
assert self._heard_by is not None
await self._heard_by.fill(self._messages)
self._render_cache = None
self._session.invalidate()
self._tick_heard()
self._spawn(fill())
def track_sent(self, message: ChatMessage) -> None:
"""Start the verdict of a channel message that we just sent."""
if self._heard_by is None:
return
self._heard_by.note_sent(message)
self._tick_heard()
def heard_packet(self) -> None:
"""The device heard a channel packet: look again for copies of our messages.
The recorder stores the packet in the background, so the look waits a moment. One
look covers each packet that arrives in that moment.
"""
if self._heard_by is None or (
self._heard_refresh is not None and not self._heard_refresh.done()
):
return
async def refresh() -> None:
assert self._heard_by is not None
await asyncio.sleep(_HEARD_SETTLE_S)
if self._heard_by.refresh(self._messages):
self._session.invalidate()
self._heard_refresh = self._spawn(refresh())
def _tick_heard(self) -> None:
"""Turn the spinner while one of our channel messages waits for a relay.
The loop stops when no message waits. At the end of a wait, it looks one more
time in the packet log, so that the mark that replaces the spinner is current.
"""
if self._heard_by is None or (
self._heard_ticker is not None and not self._heard_ticker.done()
):
return
async def tick() -> None:
assert self._heard_by is not None
try:
while self._heard_by.waiting(self._messages):
await asyncio.sleep(spinner_interval())
self._spinner.tick()
self._session.invalidate()
self._heard_by.refresh(self._messages)
self._session.invalidate()
except Exception: # noqa: BLE001 - a spinner problem must never break the chat
pass
self._heard_ticker = self._spawn(tick())
def _pick_banner(self) -> Text:
"""A one-line note above the input while a message is selected.
@@ -1599,6 +1749,7 @@ class ChatScreen(Screen):
message = await self._send(text)
if message is not None:
self._messages.append(message)
self.track_sent(message)
self._status = ""
except Exception as exc: # noqa: BLE001 - show the error inline, keep the chat open
self._status = f"send failed: {exc}"
@@ -1830,6 +1981,7 @@ class ChatScreen(Screen):
message = await self._resend_unscoped(target)
if message is not None:
self._messages.append(message)
self.track_sent(message)
self._status = ""
except Exception as exc: # noqa: BLE001 - show the error inline, keep the chat open
self._status = f"resend failed: {exc}"
@@ -1995,6 +2147,7 @@ async def open_chat(ctx: AppContext, conversation: Conversation) -> int:
paths = await _make_paths_presenter(ctx, conversation, device)
self_name, self_key = await our_node(ctx)
heard, hop_name = await _make_heard_tracker(ctx, conversation, device, contacts)
screen = ChatScreen(
conversation,
history,
@@ -2011,8 +2164,11 @@ async def open_chat(ctx: AppContext, conversation: Conversation) -> int:
self_name=self_name,
self_key=self_key,
resend_flood=resend_flood,
heard=heard,
hop_name=hop_name,
)
ctx.chat.set_active(conversation.key)
screen.start_heard()
def on_event(event: MeshEvent) -> None:
message = event.message
@@ -2024,15 +2180,85 @@ async def open_chat(ctx: AppContext, conversation: Conversation) -> int:
)
)
def on_packet(event: MeshEvent) -> None:
obs = event.observation
raw = obs.raw if obs is not None and isinstance(obs.raw, dict) else {}
if raw.get("payload_typename") == "GRP_TXT":
screen.heard_packet()
unsubscribe = ctx.events.subscribe(on_event, EventKind.MESSAGE)
unsubscribe_packets = (
ctx.events.subscribe(on_packet, EventKind.OBSERVATION) if heard is not None else None
)
try:
await session.run_screen(screen)
finally:
unsubscribe()
if unsubscribe_packets is not None:
unsubscribe_packets()
ctx.chat.set_active(None)
return len(screen._messages)
async def _channel_secret(conversation: Conversation, device: Any) -> bytes | None:
"""The key of a channel conversation, from the conversation or from its slot."""
secret = conversation.secret
if conversation.is_channel and not secret and conversation.channel_idx is not None:
try:
payload = await device.get_channel(conversation.channel_idx)
raw = (payload or {}).get("channel_secret")
secret = bytes(raw) if raw else None
except Exception: # noqa: BLE001 - no key, no decrypt. The callers say so
secret = None
return secret
async def _make_heard_tracker(
ctx: AppContext, conversation: Conversation, device: Any, contacts: list[Contact]
) -> tuple[HeardTracker | None, Callable[[str], str] | None]:
"""The verdicts on our channel messages in this conversation, and a namer for relays.
A direct chat has its acknowledgements, and a channel with no key at hand cannot match
its copies. Both get ``None``, and our messages show no mark.
"""
if not conversation.is_channel:
return None, None
from ..services import trace_runner
from ..services.heard_by import make_tracker
secret = await _channel_secret(conversation, device)
tracker = await make_tracker(ctx, channel_name=conversation.label, secret=secret)
if tracker is None:
return None, None
stored_names, _named_at = ctx.repo.node_names_with_times()
resolve = trace_runner.make_node_resolver(contacts, stored_names)
return tracker, lambda hop: resolve(hop) or hop
async def _past_near_atom(ctx: AppContext, message: ChatMessage, arrivals: list) -> str:
"""The atom of the paths dialog that counts the relays past our near relays.
The near relays are the ones kept with the send, or the ones that apply now for a
message sent before MeshTerm kept them (refer to :mod:`~meshterm.services.heard_by`).
"""
from ..services.heard_by import judge, near_relays, relay_paths
from ..services.outbound import current_choice
near: tuple[str, ...] | None = None
if message.row_id is not None:
near, _paths = ctx.repo.heard_records([message.row_id]).get(message.row_id, (None, None))
if near is None and getattr(ctx, "outbound_store", None) is not None:
try:
near = near_relays((await current_choice(ctx)).paths)
except Exception: # noqa: BLE001 - with no outbound paths, each relay counts
near = None
heard = judge(relay_paths(arrivals), near or (), age_s=float("inf"), wait_s=0.0)
count = len(heard.beyond)
if not near:
return f" · {count} relay{'s' if count != 1 else ''}"
return f" · {count} past your near relay{'s' if len(near) != 1 else ''}"
async def _with_restore(ctx: AppContext, attempt: Callable[[], Awaitable[Any]]) -> Any:
"""Run a direct send. If the device forgot the contact, offer to restore it, then retry.
@@ -2310,14 +2536,7 @@ async def _make_paths_presenter(
# only gets no white highlight.
self_name, self_key = await our_node(ctx)
secret = conversation.secret
if conversation.is_channel and not secret and conversation.channel_idx is not None:
try:
payload = await device.get_channel(conversation.channel_idx)
raw = (payload or {}).get("channel_secret")
secret = bytes(raw) if raw else None
except Exception: # noqa: BLE001 - no key, no decrypt. The view says so correctly
secret = None
secret = await _channel_secret(conversation, device)
async def present(message: ChatMessage) -> None:
peer_key: str | None = None
@@ -2333,6 +2552,8 @@ async def _make_paths_presenter(
if arrivals
else "no copies in the packet log"
)
if arrivals and message.outbound:
summary += await _past_near_atom(ctx, message, arrivals)
elif conversation.is_channel:
await session.scroll(
Text(
+60
View File
@@ -68,6 +68,7 @@ from meshterm.platforms import (
set_platform,
)
from meshterm.services.courier import CourierService
from meshterm.services.heard_by import BEYOND, NEARBY, UNHEARD, WAITING, HeardBy
from meshterm.services.message_paths import Arrival
from meshterm.services.monitor_service import ACTIVITY_BUCKETS
from meshterm.services.records import CATEGORY_BY_ID
@@ -811,6 +812,64 @@ _WOODPECKER = (
)
class _GalleryHeard:
"""A fixed verdict for each of our channel messages, by its text (issue #38)."""
def __init__(self, verdicts: dict[str, HeardBy]) -> None:
self._verdicts = verdicts
def verdict(self, message: ChatMessage) -> HeardBy | None:
return self._verdicts.get(message.text) if message.outbound else None
def waiting(self, messages) -> bool: # noqa: ANN001 - the transcript
return False
def _chat_heard(cols: int, rows: int) -> Screen:
"""Our channel messages with the four relay marks, and the note of the picked one.
The marks are the spinner, ``⚠`` (only the near relays sent it back), ``✗`` (no copy),
and ``✓ 3`` (three relays past the near relays). The newest message is picked, so its
note names the relays and the near relay that carried it out. The names are long, so
the note wraps under the body on the PicoCalc.
"""
conv = Conversation(label="Lakeside", is_channel=True, channel_idx=1)
messages = [
ChatMessage(text="Alice: anyone on the ridge tonight?", is_channel=True),
ChatMessage(text="testing the new antenna", outbound=True, is_channel=True, row_id=1),
ChatMessage(text="anyone hear this?", outbound=True, is_channel=True, row_id=2),
ChatMessage(text="one more try", outbound=True, is_channel=True, row_id=3),
ChatMessage(text="heading up the ridge now", outbound=True, is_channel=True, row_id=4),
]
heard = _GalleryHeard(
{
"testing the new antenna": HeardBy(UNHEARD),
"anyone hear this?": HeardBy(NEARBY, copies=2),
"one more try": HeardBy(WAITING),
"heading up the ridge now": HeardBy(
BEYOND, beyond=("a1", "b2", "c3"), via=("3d",), copies=4
),
}
)
names = {
"a1": "Lakeside-North-Shore",
"b2": "Marina-Tower",
"c3": "Ridge-Top-Solar",
"3d": "Home-Yagi",
}
screen = ChatScreen(
conv,
messages,
send=None,
names={},
session=_GallerySession(cols, rows),
heard=heard, # type: ignore[arg-type]
hop_name=lambda hop: names.get(hop, hop),
)
screen.handle("up")
return screen
def _chat_image(cols: int, rows: int, *, picked: bool = False) -> Screen:
"""A channel message that is a pixel image: its caption, and the image in half blocks.
@@ -2036,6 +2095,7 @@ _ENTRIES: list[_Entry] = [
_Entry("map_find", _map_find),
_Entry("chat", _chat),
_Entry("chat_channel_scoped", _chat_channel_scoped),
_Entry("chat_heard", _chat_heard),
_Entry("chat_urls", _chat_urls),
_Entry("chat_long_url", _chat_long_url),
_Entry("chat_image", _chat_image),
+270
View File
@@ -0,0 +1,270 @@
# SPDX-License-Identifier: Apache-2.0
"""Tests for the verdict on our channel messages: did a relay past our near relays hear it?
The pure part (:func:`judge` and its helpers) is tested with plain paths. The tracker runs
against a real temporary repository, with GRP_TXT packets in the firmware form, so the
tests also use the window query, the decryption, and the stored verdicts.
"""
from __future__ import annotations
import asyncio
from datetime import datetime, timedelta, timezone
from pathlib import Path
from Crypto.Cipher import AES
from Crypto.Hash import HMAC, SHA256
from meshterm.core.channels import channel_hash, derive_secret
from meshterm.core.models import ChatMessage, Observation, utcnow
from meshterm.persistence.repository import Repository
from meshterm.services.heard_by import (
BEYOND,
NEARBY,
UNHEARD,
WAITING,
HeardTracker,
is_near,
judge,
near_relays,
relay_paths,
)
from meshterm.services.message_paths import Arrival, channel_arrivals
SECRET = derive_secret("#general")
# Invented repeaters: two near relays at home (one of them on a yagi), and two far ones.
HOME_OMNI = "3d00aa000001"
HOME_YAGI = "27d4bb000002"
NEAR = (HOME_OMNI, HOME_YAGI)
def _grp_txt_raw(secret: bytes, text: str, *, sent: datetime | None = None) -> dict:
"""A GRP_TXT packet payload in the firmware form, with ``sent`` as its sender time."""
stamp = int(sent.timestamp()) if sent is not None else 0
plain = stamp.to_bytes(4, "little") + bytes([0]) + text.encode("utf-8")
plain += b"\x00" * (-len(plain) % 16)
crypted = AES.new(secret, AES.MODE_ECB).encrypt(plain)
mac = HMAC.new(secret, digestmod=SHA256)
mac.update(crypted)
return {
"payload_typename": "GRP_TXT",
"chan_hash": channel_hash(secret),
"cipher_mac": mac.digest()[:2].hex(),
"crypted": crypted.hex(),
}
def _repo(tmp_path: Path) -> tuple[Repository, int]:
repo = Repository(tmp_path / "test.db")
return repo, repo.start_run("monitor", {}, None)
def _copy(repo: Repository, run: int, *, when: datetime, path: str, text: str, sent=None):
repo.record_observation(
run,
Observation(
node=None,
kind="packet",
path=path,
snr=1.0,
observed_at=when,
raw=_grp_txt_raw(SECRET, f"Homestead: {text}", sent=sent),
),
)
def _sent(repo: Repository, text: str, at: datetime) -> ChatMessage:
message = ChatMessage(
text=text, outbound=True, is_channel=True, channel_id="general", created_at=at
)
message.row_id = repo.record_chat_message(message)
return message
# --- the pure verdict ------------------------------------------------------------------
def test_near_relays_are_the_first_hops_of_the_outbound_paths() -> None:
"""Each outbound path gives its first hop one time, in order, in lowercase."""
paths = [("3D00AA000001", "51548cda57ae"), ("27d4bb000002", "3d00aa000001"), ()]
assert near_relays(paths) == (HOME_OMNI, HOME_YAGI)
def test_a_hash_matches_a_near_relay_by_its_prefix() -> None:
"""A one-byte hash matches the longer key prefix of a near relay, in either case."""
assert is_near("3D", NEAR)
assert is_near("27d4", NEAR)
assert not is_near("51", NEAR)
assert not is_near("", NEAR)
def test_a_relay_past_the_near_relays_makes_the_verdict_beyond() -> None:
"""A copy through a far relay proves that the message went farther, at once."""
heard = judge([("3d", "51"), ("27", "3d")], NEAR, age_s=1, wait_s=30)
assert heard.state == BEYOND
assert heard.beyond == ("51",)
assert heard.via == ("3d",)
assert heard.copies == 2
def test_near_relays_are_near_at_any_place_in_the_path() -> None:
"""The yagi relay after the omni relay is still a near relay, so nothing went farther."""
heard = judge([("27", "3d")], NEAR, age_s=60, wait_s=30)
assert heard.state == NEARBY
assert heard.beyond == ()
def test_the_verdict_waits_before_it_says_nearby_or_unheard() -> None:
"""Inside the wait, no copy and near copies both wait. After it, they differ."""
assert judge([], NEAR, age_s=5, wait_s=30).state == WAITING
assert judge([("3d",)], NEAR, age_s=5, wait_s=30).state == WAITING
assert judge([("3d",)], NEAR, age_s=31, wait_s=30).state == NEARBY
assert judge([], NEAR, age_s=31, wait_s=30).state == UNHEARD
def test_with_no_near_relays_each_relay_counts() -> None:
"""With no outbound paths, a relay next to us is proof too."""
heard = judge([("3d",), ("27", "51")], (), age_s=1, wait_s=30)
assert heard.state == BEYOND
assert heard.beyond == ("3d", "27", "51")
assert heard.via == ()
def test_the_via_names_each_near_relay_that_started_a_far_copy() -> None:
"""Both repeaters at home show when each of them carried the message out."""
heard = judge([("3d", "51"), ("27", "a9", "51")], NEAR, age_s=1, wait_s=30)
assert heard.beyond == ("51", "a9")
assert heard.via == ("3d", "27")
def test_relay_paths_skip_the_copies_that_tell_nothing() -> None:
"""An empty path, and a direct-routed copy that used its route, name no relay."""
now = utcnow()
arrivals = [
Arrival(when=now, hops=("3d",), snr=None, routed=False),
Arrival(when=now, hops=(), snr=None, routed=False),
Arrival(when=now, hops=(), snr=None, routed=True),
]
assert relay_paths(arrivals) == [("3d",)]
# --- the match of our own messages -----------------------------------------------------
def test_two_sends_of_the_same_text_keep_their_own_copies(tmp_path: Path) -> None:
"""Two "test" messages five minutes apart do not share copies: the sender time decides."""
repo, run = _repo(tmp_path)
first_at = utcnow().replace(microsecond=0) - timedelta(minutes=5)
second_at = first_at + timedelta(minutes=5)
first = _sent(repo, "test", first_at)
second = _sent(repo, "test", second_at)
_copy(repo, run, when=first_at + timedelta(seconds=2), path="3d", text="test", sent=first_at)
_copy(repo, run, when=second_at + timedelta(seconds=2), path="51", text="test", sent=second_at)
one = channel_arrivals(repo, first, channel_name="#general", secret=SECRET)
two = channel_arrivals(repo, second, channel_name="#general", secret=SECRET)
assert [a.hops for a in one] == [("3d",)]
assert [a.hops for a in two] == [("51",)]
repo.close()
# --- the tracker -----------------------------------------------------------------------
def _tracker(repo: Repository, now: datetime, *, near=NEAR) -> HeardTracker:
return HeardTracker(
repo,
channel_name="#general",
secret=SECRET,
near_now=near,
wait_s=lambda: 30.0,
clock=lambda: now,
)
def test_the_tracker_gives_no_verdict_before_it_examined_the_message(tmp_path: Path) -> None:
"""The paint never touches the packet log: an unexamined message has no mark yet."""
repo, _run = _repo(tmp_path)
now = utcnow().replace(microsecond=0)
message = _sent(repo, "hello", now)
tracker = _tracker(repo, now)
assert tracker.verdict(message) is None
asyncio.run(tracker.fill([message]))
verdict = tracker.verdict(message)
assert verdict is not None and verdict.state == WAITING
repo.close()
def test_the_tracker_ignores_other_messages(tmp_path: Path) -> None:
"""A received message and a direct message have no verdict."""
repo, _run = _repo(tmp_path)
now = utcnow()
inbound = ChatMessage(text="hi", is_channel=True, created_at=now, row_id=1)
direct = ChatMessage(text="hi", outbound=True, created_at=now, row_id=2)
tracker = _tracker(repo, now)
asyncio.run(tracker.fill([inbound, direct]))
assert tracker.verdict(inbound) is None
assert tracker.verdict(direct) is None
repo.close()
def test_a_late_copy_changes_the_verdict(tmp_path: Path) -> None:
"""A copy through a far relay after the wait turns the verdict from nearby to beyond."""
repo, run = _repo(tmp_path)
sent_at = utcnow().replace(microsecond=0) - timedelta(seconds=40)
message = _sent(repo, "hello", sent_at)
_copy(repo, run, when=sent_at + timedelta(seconds=1), path="3d", text="hello", sent=sent_at)
tracker = _tracker(repo, sent_at + timedelta(seconds=40))
asyncio.run(tracker.fill([message]))
assert tracker.verdict(message).state == NEARBY # type: ignore[union-attr]
_copy(repo, run, when=sent_at + timedelta(seconds=35), path="3d,51", text="hello", sent=sent_at)
assert tracker.refresh([message]) is True
verdict = tracker.verdict(message)
assert verdict is not None and verdict.state == BEYOND and verdict.beyond == ("51",)
repo.close()
def test_an_old_message_is_stored_and_read_back(tmp_path: Path) -> None:
"""Out of the match window, the paths are stored, and the next visit reads them."""
repo, run = _repo(tmp_path)
sent_at = utcnow().replace(microsecond=0) - timedelta(hours=2)
message = _sent(repo, "old one", sent_at)
_copy(
repo, run, when=sent_at + timedelta(seconds=3), path="27,9f", text="old one", sent=sent_at
)
asyncio.run(_tracker(repo, utcnow()).fill([message]))
stored = repo.heard_records([message.row_id]) # type: ignore[list-item]
assert stored[message.row_id] == (NEAR, [("27", "9f")]) # type: ignore[index]
# A second visit with other near relays keeps the ones that the verdict used.
again = _tracker(repo, utcnow(), near=())
asyncio.run(again.fill([message]))
verdict = again.verdict(message)
assert verdict is not None and verdict.beyond == ("9f",) and verdict.via == ("27",)
repo.close()
def test_the_near_relays_of_the_send_win_over_the_ones_of_today(tmp_path: Path) -> None:
"""A message keeps the near relays of its send, also after a change of site."""
repo, run = _repo(tmp_path)
sent_at = utcnow().replace(microsecond=0) - timedelta(seconds=60)
message = _sent(repo, "from home", sent_at)
repo.set_near_hops(message.row_id, NEAR) # type: ignore[arg-type]
_copy(repo, run, when=sent_at + timedelta(seconds=2), path="3d", text="from home", sent=sent_at)
tracker = _tracker(repo, sent_at + timedelta(seconds=60), near=("51000000",))
asyncio.run(tracker.fill([message]))
assert tracker.verdict(message).state == NEARBY # type: ignore[union-attr]
repo.close()
def test_a_message_sent_while_the_screen_is_open_waits(tmp_path: Path) -> None:
"""A new send starts in the wait, with the near relays that apply now."""
repo, _run = _repo(tmp_path)
now = datetime.now(timezone.utc).replace(microsecond=0)
message = _sent(repo, "new", now)
tracker = _tracker(repo, now)
before = tracker.revision
tracker.note_sent(message)
assert tracker.revision != before
assert tracker.waiting([message])
repo.close()