Message paths: a path graph over selectable, sideways-scrolling rows

The ^P view grows from a static scroll window into its own dialog. Up
top, every distinct path the message took drawn in the atlas's edge
style — origin left, us right, the final relay → us link coloured by
that path's reception SNR, earlier links slate — with markers for every
node but labels only along the currently selected path, so a many-path
graph stays readable; the selected path draws bright, the rest dim.
Beneath, one row per arrival with a selection cursor: ↑↓ move it (the
graph follows), and a row longer than the dialog scrolls horizontally
with ←→ — the whole line shifts under an edge …, and snaps back the
moment the selection moves on. crop_cells in tui.render is the new
cell-exact window primitive behind that.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Fable 5 committed 2026-07-12 15:47:56 -04:00
1 parent 2dca52fa56
commit 94aba0cbcd
4 files changed
+517 -76

No files matched your search

+30 -76
View File
@@ -30,7 +30,6 @@ from .tui.prompt import _LineEditor
from .tui.render import render_hanging, render_lines, right_aligned_tail
from .tui.screen import CANCEL, Screen
from .tui.spinner import Spinner
from .widgets import path_text
if TYPE_CHECKING:
from ..context import AppContext
@@ -893,6 +892,7 @@ async def _make_paths_presenter(
direct_frames_near,
distinct_paths,
)
from .message_paths_screen import MessagePathsScreen
from .timemachine_screen import _routing_prefix_bytes
session = ctx.ui.session
@@ -920,88 +920,42 @@ async def _make_paths_presenter(
arrivals = channel_arrivals(
ctx.repo, message, channel_name=conversation.label, secret=secret
)
body = _paths_view(
message, arrivals, matched=True, resolve=resolve,
prefix_bytes=prefix_bytes, self_name=self_name,
summary=f"heard {len(arrivals)} time{'s' if len(arrivals) != 1 else ''}"
matched = True
summary = (
f"heard {len(arrivals)} time{'s' if len(arrivals) != 1 else ''}"
f" · {distinct_paths(arrivals)} distinct "
f"path{'s' if distinct_paths(arrivals) != 1 else ''}"
if arrivals else "no copies in the packet log",
if arrivals else "no copies in the packet log"
)
elif conversation.is_channel:
body = Text(
"This channel's key isn't at hand, so overheard frames can't be "
"matched to the message.",
style="muted",
await session.scroll(
Text(
"This channel's key isn't at hand, so overheard frames can't be "
"matched to the message.",
style="muted",
),
title="Message paths",
)
return
else:
arrivals = direct_frames_near(ctx.repo, message)
body = _paths_view(
message, arrivals, matched=False, resolve=resolve,
prefix_bytes=prefix_bytes, self_name=self_name,
summary="direct frames are encrypted — matched by time alone (±90 s)",
)
await session.scroll(body, title="Message paths")
return present
def _paths_view(
message: ChatMessage,
arrivals: list,
*,
matched: bool,
resolve, # noqa: ANN001 - NodeResolver
prefix_bytes: int,
self_name: Optional[str],
summary: str,
) -> Group:
"""Lay one message's arrivals out: the quoted text, a summary, then one row each.
Every row reads through the shared compact path widget, so a path here looks
exactly like the same path in the dashboard feed or the packet viewer: time,
reception SNR, then ``direct`` or the relay chain (with a resend counter when a
decrypted channel frame carried one).
"""
quoted = message.text.replace("\n", " ")
if len(quoted) > 64:
quoted = quoted[:63] + "…"
head = Text(f"“{quoted}”")
stamp = Text(message.created_at.astimezone().strftime("%b %d %H:%M"), style="muted")
stamp.append(" · ", style="muted")
stamp.append(summary, style="muted" if matched else "warn")
parts: list[RenderableType] = [head, stamp]
if not arrivals:
parts.append(Text())
if matched:
parts.append(Text(
"Nothing overheard — the radio only logs frames it hears while "
"MeshTerm is listening.", style="muted",
))
matched = False
summary = "direct frames are encrypted — matched by time alone (±90 s)"
# The graph's left endpoint: who the message set out from. Our own sends are
# us; an inbound channel message names its sender on the wire; a direct chat's
# origin is the conversation's peer (billed as time-matched by the summary).
if message.outbound:
source = self_name
elif conversation.is_channel:
source, _body = _split_channel_sender(message.text)
else:
parts.append(Text("No direct-message frames logged in the window.", style="muted"))
return Group(*parts)
parts.append(Text())
for arrival in arrivals:
row = Text(no_wrap=True, overflow="ellipsis")
row.append(arrival.when.astimezone().strftime("%H:%M:%S"), style="muted")
row.append(" ")
if arrival.snr is not None:
row.append(f"{arrival.snr:+5.1f} dB", style=snr_style(arrival.snr))
else:
row.append(" " * 8, style="muted")
row.append(" ")
if arrival.hops:
row.append("via ", style="muted")
row.append_text(
path_text(
arrival.hops, resolve,
prefix_bytes=prefix_bytes, self_name=self_name, empty="direct",
source = conversation.label
await session.run_screen(
MessagePathsScreen(
message, arrivals, matched=matched, resolve=resolve,
prefix_bytes=prefix_bytes, self_name=self_name, summary=summary,
source=source or None,
)
)
if arrival.resend:
row.append(f" (resend #{arrival.resend})", style="muted")
parts.append(row)
return Group(*parts)
return present
+350
View File
@@ -0,0 +1,350 @@
"""The Message paths dialog: every way one chat message reached this radio.
The interactive face of :mod:`~meshterm.services.message_paths`, opened from the chat
with ``^P`` (or Enter on a picked direct message). The evidence — one logged frame per
arrival, each with the relay path it rode — is laid out twice, so the shape and the
detail read together:
* a **graph** up top draws every distinct path the message took, in the atlas's edge
style: braille lines, the final relay → us link coloured by that path's reception
SNR (green → amber → red), earlier links slate (their SNR was never ours to
measure). The origin sits at the left, we sit at the right, every relay in between
gets a marker — but only the nodes on the *currently selected* path are labelled,
so a many-path graph stays readable. The selected path draws bright; the rest dim.
* the **arrival list** beneath is one row per logged copy — time, reception SNR, and
the relay chain through the shared compact path widget. ↑↓ move the selection (the
graph's highlight follows); a row longer than the dialog **scrolls horizontally
with ←→**, the whole line shifting under a ``…`` at whichever edge continues, and
snaps back the moment the selection moves on.
Nothing here transmits; like the service beneath it, this is a read-model over what
the radio already heard.
"""
from __future__ import annotations
from statistics import median
from typing import Optional
from rich.text import Text
from ..core.models import ChatMessage
from ..services.message_paths import Arrival
from .atlas_screen import _NO_READING, _UNKNOWN, _scaled, _snr_rgb
from .map_render import _NODE, _SELF
from .mapcanvas import MapCanvas, parse_hex
from .theme import snr_style
from .tui.render import crop_cells, render_to_ansi
from .tui.screen import Screen
from .widgets import NodeResolver, path_text
#: Sentinel node ids for the graph's endpoints (NUL never collides with hex hops).
_SRC = "\x00src"
_DST = "\x00dst"
#: Cells one ←/→ press shifts the selected row by.
_HSTEP = 4
#: Vertical dot separation between path lanes, and the graph's height bounds in rows.
_LANE_STEP_DOTS = 8
_GRAPH_MIN_H = 3
_GRAPH_MAX_H = 10
#: Dot-space margin the endpoint markers keep from the canvas edges.
_GRAPH_PAD_DOTS = 6
#: The widest a node label may render on the graph before it is ellipsized.
_GRAPH_LABEL_W = 12
class MessagePathsScreen(Screen):
"""A floating dialog: one message's arrivals as a path graph over a row list."""
def __init__(
self,
message: ChatMessage,
arrivals: list[Arrival],
*,
matched: bool,
resolve: NodeResolver,
prefix_bytes: int,
self_name: Optional[str],
summary: str,
source: Optional[str] = None,
) -> None:
"""Build the dialog over one message's matched arrivals.
Args:
message: The chat message whose delivery evidence is shown.
arrivals: Its logged arrivals, oldest first (may be empty).
matched: Whether the arrivals were matched by content (a decrypted
channel frame) rather than merely by time — the summary line warns
when they weren't.
resolve: Maps a hop hash to a friendly name when known.
prefix_bytes: Path-hash width to light in unnamed hops' hashes.
self_name: Our own node's name (the graph's right endpoint, white).
summary: The one-line evidence summary shown under the quoted text.
source: Display name of the message's origin — the sender parsed from a
channel message, us for an outbound one, the peer for a direct chat
(``None`` reads as an unknown ``?`` origin).
"""
super().__init__()
self.title = "Message paths"
self._message = message
self._arrivals = arrivals
self._matched = matched
self._resolve = resolve
self._prefix_bytes = prefix_bytes
self._self_name = self_name
self._summary = summary
self._source = source
self._index = 0
#: Cells the selected row is shifted left by (reset whenever ↑↓ move), and
#: how far it *can* shift, measured against the width of the last render.
self._hshift = 0
self._hmax = 0
self._cursor: Optional[int] = None
# --- input ---------------------------------------------------------------
@property
def footer_hint(self) -> str: # type: ignore[override]
"""Row keys while there are rows; a bare close hint otherwise."""
if self._arrivals:
return "↑↓ move · ←→ scroll line · Esc close"
return "Esc close"
def handle(self, action: str, data: str = "") -> None:
"""Move the selection, shift the selected line sideways, or dismiss."""
rows = len(self._arrivals)
if action == "up" and rows:
self._index = (self._index - 1) % rows
self._hshift = 0
elif action == "down" and rows:
self._index = (self._index + 1) % rows
self._hshift = 0
elif action == "pageup" and rows:
self._index = max(0, self._index - self._page_step)
self._hshift = 0
elif action in ("pagedown", "space") and rows:
self._index = min(rows - 1, self._index + self._page_step)
self._hshift = 0
elif action in ("home", "ctrl_home") and rows:
self._index = 0
self._hshift = 0
elif action in ("end", "ctrl_end") and rows:
self._index = rows - 1
self._hshift = 0
elif action == "left":
self._hshift = max(0, self._hshift - _HSTEP)
elif action == "right":
self._hshift = min(self._hmax, self._hshift + _HSTEP)
elif action in ("escape", "enter"):
self.resolve(None)
def cursor_line(self) -> Optional[int]:
"""The selected row, so a tall arrival list scrolls with the selection."""
return self._cursor
# --- rendering -------------------------------------------------------------
def render_body(self, width: int) -> list[str]:
"""The quoted message and summary, the path graph, then the arrival rows."""
quoted = self._message.text.replace("\n", " ")
if len(quoted) > 64:
quoted = quoted[:63] + "…"
stamp = Text(self._message.created_at.astimezone().strftime("%b %d %H:%M"),
style="muted")
stamp.append(" · ", style="muted")
stamp.append(self._summary, style="muted" if self._matched else "warn")
lines = [
render_to_ansi(Text(f"“{quoted}”"), width, no_wrap=True),
render_to_ansi(stamp, width, no_wrap=True),
]
self._cursor = None
if not self._arrivals:
lines.append("")
note = (
"Nothing overheard — the radio only logs frames it hears while "
"MeshTerm is listening."
if self._matched
else "No direct-message frames logged in the window."
)
lines.append(render_to_ansi(Text(note, style="muted"), width))
self._scroll_total = len(lines)
return lines
lines.append("")
lines.extend(self._graph_lines(width))
caption = Text("origin → you · edge = last-hop SNR · bright = selected path",
style="faint")
lines.append(render_to_ansi(caption, width, no_wrap=True))
lines.append("")
for i, arrival in enumerate(self._arrivals):
if i == self._index:
self._cursor = len(lines)
lines.append(self._selected_line(arrival, width))
else:
row = Text(" ")
row.append_text(self._row_text(arrival))
lines.append(render_to_ansi(row, width, no_wrap=True))
self._scroll_total = len(lines)
return lines
# -- the rows --
def _row_text(self, arrival: Arrival) -> Text:
"""One arrival, unabridged: time, reception SNR, and its relay path."""
row = Text()
row.append(arrival.when.astimezone().strftime("%H:%M:%S"), style="muted")
row.append(" ")
if arrival.snr is not None:
row.append(f"{arrival.snr:+5.1f} dB", style=snr_style(arrival.snr))
else:
row.append(" " * 8)
row.append(" ")
if arrival.hops:
row.append("via ", style="muted")
row.append_text(
path_text(
arrival.hops, self._resolve,
prefix_bytes=self._prefix_bytes, self_name=self._self_name,
empty="direct",
)
)
if arrival.resend:
row.append(f" (resend #{arrival.resend})", style="muted")
return row
def _selected_line(self, arrival: Arrival, width: int) -> str:
"""The highlighted row: ``❯`` pointer, shifted by ``←→`` under edge ``…``.
The whole line scrolls — timestamp and SNR included — and the shift bound
is measured here against the current width, so a resize can only ever leave
the row clamped back into range.
"""
full = self._row_text(arrival)
avail = max(1, width - 2)
self._hmax = max(0, full.cell_len - avail)
self._hshift = min(self._hshift, self._hmax)
shift = self._hshift
left_more = 1 if shift > 0 else 0
right_more = 1 if shift + avail < full.cell_len else 0
inner = max(1, avail - left_more - right_more)
line = Text("❯ ", style="brand", no_wrap=True)
if left_more:
line.append("…", style="muted")
line.append_text(crop_cells(full, shift + left_more, inner))
if right_more:
line.append("…", style="muted")
line.style = "brand"
return render_to_ansi(line, width, no_wrap=True)
# -- the graph --
def _paths(self) -> list[tuple[str, ...]]:
"""The distinct relay paths across the arrivals, in first-heard order."""
seen: list[tuple[str, ...]] = []
for arrival in self._arrivals:
if arrival.hops not in seen:
seen.append(arrival.hops)
return seen
def _path_snr(self, path: tuple[str, ...]) -> Optional[float]:
"""The median reception SNR across the arrivals that rode ``path``."""
readings = [
a.snr for a in self._arrivals if a.hops == path and a.snr is not None
]
return median(readings) if readings else None
def _graph_lines(self, width: int) -> list[str]:
"""Draw every distinct path origin → us, the selected one bright and labelled.
Lanes fan out from the vertical centre (first path on it, the next below,
the next above, …); a node shared between paths averages its lanes, so a
common relay pulls the paths together where they actually met.
"""
paths = self._paths()
selected = self._arrivals[self._index].hops
offsets = [(-1) ** k * ((k + 1) // 2) for k in range(len(paths))] # 0 -1 1 -2 2…
max_off = max(abs(o) for o in offsets)
step = _LANE_STEP_DOTS
rows = max(_GRAPH_MIN_H, (2 * max_off * step + 14) // 4)
if rows > _GRAPH_MAX_H:
rows = _GRAPH_MAX_H
step = max(4, (rows * 4 - 14) // (2 * max_off))
canvas = MapCanvas(width, rows)
dot_w, dot_h = width * 2, rows * 4
cy = dot_h // 2
span = dot_w - 2 * _GRAPH_PAD_DOTS
# Positions: x by mean relative slot along the paths through a node, y by
# mean lane — endpoints pinned to the margins and the centre line.
rel: dict[str, list[float]] = {}
lanes: dict[str, list[int]] = {}
seqs = [(_SRC, *path, _DST) for path in paths]
for off, seq in zip(offsets, seqs):
hops = len(seq) - 1
for i, node in enumerate(seq):
rel.setdefault(node, []).append(i / hops)
lanes.setdefault(node, []).append(off)
def pos(node: str) -> tuple[int, int]:
x = _GRAPH_PAD_DOTS + round(
sum(rel[node]) / len(rel[node]) * span
)
if node in (_SRC, _DST):
return x, cy
return x, cy + round(sum(lanes[node]) / len(lanes[node]) * step)
# Edges, the selected path drawn last and bright so shared cells go to it.
ordered = sorted(zip(paths, seqs), key=lambda ps: ps[0] == selected)
for path, seq in ordered:
bright = 1.0 if path == selected else 0.55
priority = 3 if path == selected else 2
snr_rgb = _snr_rgb(self._path_snr(path))
for i in range(len(seq) - 1):
last = i == len(seq) - 2 # the final relay → us link owns the SNR
color = _scaled(snr_rgb if last else _NO_READING, bright)
canvas.draw_line([pos(seq[i]), pos(seq[i + 1])], color, priority)
# Markers for every node; labels only along the selected path (endpoints
# first, so they win label collisions against mid-path relays).
for node in rel:
glyph, color_hex = self._node_glyph(node)
canvas.marker(*pos(node), glyph, parse_hex(color_hex))
for node in (_DST, _SRC, *selected):
label = self._node_label(node)
if len(label) > _GRAPH_LABEL_W:
label = label[: _GRAPH_LABEL_W - 1] + "…"
rgb = (
(255, 255, 255)
if node == _DST
else parse_hex(self._node_glyph(node)[1])
)
x, y = pos(node)
for dy in (0, 4, -4):
if canvas.marker_label(x, y + dy, label, rgb):
break
return canvas.to_ansi_lines()
def _node_glyph(self, node: str) -> tuple[str, str]:
"""The graph marker for a node: us a star, named nodes dots, unknowns rings."""
if node == _DST:
return _SELF
if node == _SRC:
if self._source and self._self_name and self._source == self._self_name:
return _SELF
return _NODE if self._source else _UNKNOWN
named = self._resolve(node)
return _NODE if named and named != node else _UNKNOWN
def _node_label(self, node: str) -> str:
"""A node's graph label: its name when known, else its short hash."""
if node == _DST:
return self._self_name or "you"
if node == _SRC:
return self._source or "?"
named = self._resolve(node)
return named if named and named != node else node[:8]
+39
View File
@@ -13,6 +13,7 @@ from __future__ import annotations
from io import StringIO
from rich.cells import cell_len
from rich.console import Console, RenderableType
from rich.text import Text
@@ -130,6 +131,44 @@ def right_aligned_tail(body: Text, tail: Text, width: int) -> Text:
return combined
def crop_cells(text: Text, start: int, width: int) -> Text:
"""Cut a single-line styled Text to the cell window ``[start, start + width)``.
The horizontal-scroll primitive: a row wider than its lane is shown ``width``
cells at a time, shifted ``start`` cells in, styling preserved. Boundaries are
measured in display cells, so a double-width glyph straddling either edge is
dropped (replaced by a pad space on the left) rather than half-shown.
Args:
text: The styled line to crop (treated as a single line).
start: Cells to skip from the left (clamped at 0).
width: Cells the window spans.
Returns:
A new :class:`Text` at most ``width`` cells wide, ``no_wrap`` set so the
caller can drop it straight into a row.
"""
start = max(0, start)
plain = text.plain
index, pad = len(plain), 0
if start == 0:
index = 0
else:
acc = 0
for i, ch in enumerate(plain):
w = cell_len(ch)
if acc + w > start:
# This character crosses the cut: keep it when it starts exactly at
# the boundary, else drop it and pad for its protruding half.
index, pad = (i, 0) if acc == start else (i + 1, acc + w - start)
break
acc += w
out = Text(" " * pad, no_wrap=True)
out.append_text(text[index:])
out.truncate(max(0, width))
return out
def render_hanging(prefix: Text, body: Text, width: int, *, indent: int) -> list[str]:
"""Render ``prefix + body`` at ``width``, wrapping the body with a hanging indent.
+98
View File
@@ -0,0 +1,98 @@
"""Message-paths dialog tests: the graph-over-rows view behind the chat's ^P.
Driven headless like the atlas tests: render_body is pure lines-out, handle() pure
state, so the selection cursor, the horizontal line scroll, and the selected-path
labelling are all assertable without a terminal.
"""
from __future__ import annotations
import re
from datetime import timedelta
from meshterm.core.models import ChatMessage, utcnow
from meshterm.services.message_paths import Arrival
from meshterm.ui.message_paths_screen import MessagePathsScreen
def _resolve(hop: str) -> str:
return {"3d63": "YUL-Cartierville", "a1b2": "Waymarker"}.get(hop, hop)
def _plain(lines: list[str]) -> str:
return re.sub(r"\x1b\[[0-9;]*m", "", "\n".join(lines))
def _screen(arrivals: list[Arrival], **kwargs) -> MessagePathsScreen:
message = ChatMessage(text="on my way", is_channel=True, created_at=utcnow())
defaults = dict(
matched=True, resolve=_resolve, prefix_bytes=1, self_name="Homestead",
summary="heard twice", source="Alice",
)
defaults.update(kwargs)
return MessagePathsScreen(message, arrivals, **defaults)
def _arrivals() -> list[Arrival]:
now = utcnow()
return [
Arrival(when=now, hops=("3d63",), snr=4.0),
Arrival(when=now + timedelta(seconds=2), hops=("a1b2", "77aa"), snr=-2.0),
]
def test_paths_screen_renders_graph_rows_and_cursor() -> None:
"""The quoted text, the graph endpoints, and one selectable row per arrival."""
screen = _screen(_arrivals())
body = _plain(screen.render_body(76))
assert "“on my way”" in body
assert "Alice" in body and "Homestead" in body # origin and us, on the graph
assert body.count("via") == 2 # one row per arrival
assert "❯" in body
assert "bright = selected path" in body
assert screen.cursor_line() is not None
def test_paths_screen_labels_only_the_selected_path() -> None:
"""Relay labels follow the selection: the other path keeps bare markers."""
screen = _screen(_arrivals())
graph = _plain(screen.render_body(76)).split("origin →")[0]
assert "YUL-Cartier" in graph # the selected (first) path's relay is named
assert "Waymarker" not in graph # the other path's relays stay unlabelled
screen.handle("down")
graph = _plain(screen.render_body(76)).split("origin →")[0]
assert "Waymarker" in graph
assert "YUL-Cartier" not in graph
def test_paths_screen_scrolls_the_selected_line_sideways() -> None:
"""→ shifts the whole selected row under a leading …; ↑↓ snap it back."""
now = utcnow()
long = Arrival(when=now, hops=tuple(f"{i:02x}{i:02x}" for i in range(12)), snr=1.0)
screen = _screen([long, Arrival(when=now, hops=(), snr=None)])
narrow = 40
before = _plain(screen.render_body(narrow))
selected_before = next(ln for ln in before.split("\n") if ln.startswith("❯"))
assert screen._hmax > 0 # the row genuinely overflows at this width
for _ in range(3):
screen.handle("right")
after = _plain(screen.render_body(narrow))
selected_after = next(ln for ln in after.split("\n") if ln.startswith("❯"))
assert selected_after != selected_before
assert "…" in selected_after # the left edge marks the hidden head
stamp = long.when.astimezone().strftime("%H:%M:%S")
assert stamp in selected_before and stamp not in selected_after # whole line shifts
screen.handle("down")
assert screen._hshift == 0 # only the selected line stays scrolled
def test_paths_screen_direct_arrival_and_empty_state() -> None:
"""A hop-less arrival reads direct; no arrivals at all explain themselves."""
now = utcnow()
screen = _screen([Arrival(when=now, hops=(), snr=2.5)])
body = _plain(screen.render_body(76))
assert "direct" in body
empty = _screen([], matched=False)
body = _plain(empty.render_body(76))
assert "No direct-message frames logged in the window." in body
assert empty.footer_hint == "Esc close"