Path lines: notch every chip's left edge; merge duplicate hops

The gap between chips was one-sided: the previous chip tapered out to a
point onto the page, but the next one started on a flat edge. Both faces
now angle the way the path flows — the seam is two cells, a taper out and
the same point notched back inward out of the next chip's fill, with a
sliver of bare page between them. It is the notch a wrapped line already
opened on, so a fold now looks exactly like the seam it interrupted.

The composer's suggestion list could show one node twice. The evidence
graph keeps a hop hash it can't pin down as its own vertex — a 1-byte "3d"
matching two contacts stays "3d", apart from the "3d63c6429436" its wider
sightings landed on — and it is right not to guess; but once the name
resolver names them, they are one row drawn twice. They now fold onto the
longer id with their readings pooled, so the row's sample count and median
SNR describe the whole node. Merging takes both a shared name and a shared
prefix, so two unnamed hashes never fold and neither do two same-named
nodes on unrelated keys.

Folding the stub away must not fold its links away with it, so a step off
the merged node gathers from every id it reads as — otherwise merging would
quietly cost the composer whatever was only ever heard under the stub. Name
lookup and that alias walk are both memoized: they now run over the graph
on the way to each repaint, and neither the topology nor the resolver moves
while a composer is open.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5 committed 2026-07-27 20:28:18 -04:00
1 parent 2c2f13ce41
commit fc9a459eda
4 files changed
+238 -48

No files matched your search

+121 -10
View File
@@ -67,7 +67,9 @@ from rich.cells import cell_len
from rich.text import Text
from ..services.records import first_repeated_edge
from ..services.topology import MeshTopology, _is_hex, render_custom_spec, render_forced_spec
from ..services.topology import (
HopSuggestion, Link, MeshTopology, _is_hex, render_custom_spec, render_forced_spec,
)
from .theme import snr_style
from .tui.render import render_lines, render_to_ansi
from .tui.screen import ListWindow, Screen
@@ -189,6 +191,10 @@ class PathComposerScreen(Screen):
self._device_hash = (device_hash or "").lower().removeprefix("0x")
self._topology = topology
self._resolve = resolve
#: Resolved display names by node id — see :meth:`_resolve_entry`.
self._names: dict[str, str] = {}
#: The graph ids each node reads as — see :meth:`_aliases`.
self._alias_cache: dict[str, set[str]] = {}
self._width_bytes = width_bytes
self._hops: list[str] = list(hops or [])
#: The insertion cursor: which joining arrow of the editable leg it sits on.
@@ -228,14 +234,97 @@ class PathComposerScreen(Screen):
"""
return self._hops[self._cursor - 1] if self._cursor else self._topology.self_id
def _same_node(self, a: str, b: str) -> bool:
"""Whether two graph ids read as one node — same name, one prefixing the other.
The evidence graph keeps a hop hash it can't pin down as its own vertex: a
1-byte ``3d`` that prefix-matches two contacts stays ``3d``, separate from the
``3d63c6429436`` its wider sightings landed on. Both are real ids with real
evidence, and the graph is right not to guess — but on screen, once the name
resolver has named them (see :meth:`_resolve_entry`), they are one row shown
twice. The test is deliberately both halves: a shared *name*, and one hash a
prefix of the other. Two unnamed hashes never merge (they resolve to
themselves, so the names differ) and two same-named nodes on unrelated keys —
a duplicate contact name, a renamed node — never merge either.
Args:
a: One node id.
b: The other.
Returns:
Whether the two should be shown, and addressed, as a single node.
"""
if a == b:
return True
if not (a.startswith(b) or b.startswith(a)):
return False
named = self._resolve_entry(a)
return named != a and named == self._resolve_entry(b)
def _aliases(self, node: str) -> set[str]:
"""Every id in the graph that reads as ``node`` — the stubs it is split across.
The other half of :meth:`_same_node`: a merged suggestion must also *stand* as
the merged node, so the next step out of it sees everything all its ids have
been heard talking to. Without this, folding ``3d`` into ``3d63c6429436`` would
quietly cost the composer whatever was only ever observed under the stub.
Cached per node, since this walks the whole graph and :meth:`_suggestions` runs
several times per keystroke (the row list, the dialog's width, the paint). The
topology is fixed for the screen's lifetime — a neighbour fetch builds a fresh
one — so the answer can't go stale under the cache.
"""
ids = self._alias_cache.get(node)
if ids is not None:
return ids
ids = {node}
for link in self._topology.links():
for end in (link.a, link.b):
if end not in ids and self._same_node(end, node):
ids.add(end)
self._alias_cache[node] = ids
return ids
def _pooled(self, one, other): # noqa: ANN001, ANN201
"""Fold two suggestions for the same node into one row, evidence pooled.
The surviving id is the longer of the two — the more specific identity, and the
one that addresses the node best when the spec is rendered. The readings behind
it are summed exactly as the topology pools evidence when it coalesces a stub
itself, so the row's ``n×`` and median SNR describe the whole node rather than
whichever half happened to rank first.
"""
node = one.node if len(one.node) >= len(other.node) else other.node
stamps = [
link.last_seen for link in (one.link, other.link) if link.last_seen is not None
]
ends = sorted((self._anchor(), node))
return HopSuggestion(
node=node,
link=Link(
a=ends[0], b=ends[1],
samples=one.link.samples + other.link.samples,
snrs=[*one.link.snrs, *other.link.snrs],
last_seen=max(stamps) if stamps else None,
sources=one.link.sources | other.link.sources,
),
strength=max(one.strength, other.strength),
)
def _suggestions(self) -> list:
"""The current suggestion rows, filtered by the typed entry.
"""The current suggestion rows — duplicates merged, filtered by the typed entry.
Target mode excludes the target (the path implicitly turns at it) and every
used hop (revisiting one on the outbound leg is never useful — the mirror
already recrosses it). Path mode only excludes ourselves and the cursor's
two neighbours (either would make the inserted hop a self-loop): a return
leg legitimately reuses outbound repeaters.
leg legitimately reuses outbound repeaters. Every exclusion covers the excluded
node's aliases too, so a stub of the anchor can't be proposed as a step off it.
Suggestions are gathered from all of the anchor's aliases and then folded
pairwise (:meth:`_same_node`, :meth:`_pooled`), so a node the graph holds under
both a stub and a full id appears once, with all of its evidence, ranked by its
best link.
Returns:
The (possibly filtered) :class:`~meshterm.services.topology.HopSuggestion`
@@ -248,16 +337,29 @@ class PathComposerScreen(Screen):
exclude = frozenset(
{self._topology.self_id, self._anchor()} | ({after} if after else set())
)
suggestions = self._topology.next_hops(self._anchor(), exclude=exclude)
merged: list = []
for tail in sorted(self._aliases(self._anchor()), key=len, reverse=True):
for suggestion in self._topology.next_hops(tail, exclude=exclude):
if any(self._same_node(suggestion.node, other) for other in exclude):
continue
at = next(
(i for i, m in enumerate(merged)
if self._same_node(m.node, suggestion.node)),
None,
)
if at is None:
merged.append(suggestion)
else:
merged[at] = self._pooled(merged[at], suggestion)
merged.sort(key=lambda s: (-s.strength, s.node))
needle = self._entry.strip().lower()
if needle:
suggestions = [
merged = [
s
for s in suggestions
if s.node.startswith(needle)
or needle in (self._topology.display_name(s.node) or "").lower()
for s in merged
if s.node.startswith(needle) or needle in self._resolve_entry(s.node).lower()
]
return suggestions[:_MAX_SUGGESTIONS]
return merged[:_MAX_SUGGESTIONS]
def _custom_hex(self) -> Optional[str]:
"""The typed entry as an addable hex hop, or ``None`` when it isn't one."""
@@ -336,10 +438,19 @@ class PathComposerScreen(Screen):
to it means a node the trace window shows as *YUL-Poly* is *YUL-Poly* here too,
instead of a bare ``3d`` the reader has to decode. Nothing is invented: an
unmatched hash comes back unchanged and renders as a hash.
Memoized: both resolvers scan the contact list, and this now runs over every
link in the graph on the way to each repaint (see :meth:`_aliases`). Neither
the topology nor the resolver changes while a composer is open — a neighbour
fetch builds a fresh screen — so the answers are stable for its lifetime.
"""
if self._target_id is not None and entry == (self._target_hash or self._target_id):
return self._target_label or entry
return self._topology.display_name(entry) or self._resolve(entry) or entry
named = self._names.get(entry)
if named is None:
named = self._topology.display_name(entry) or self._resolve(entry) or entry
self._names[entry] = named
return named
def _node_text(self, node: str, *, dim: bool = False) -> Text:
"""One route node through THE path widget, the trace presentation.
+60 -33
View File
@@ -8,11 +8,11 @@ caller), a :class:`PathLine` separates *what the hops are* from *how the line is
drawn*, so every surface the survey found can eventually route through it:
* **Two separator styles.** ``plain`` joins hops with muted ``→`` arrows — today's
look, unchanged. ``powerline`` renders each hop as a colour-filled chip separated by
the solid-triangle U+E0B0 drawn on the page — the gapped oh-my-posh look: each chip
tapers out to a point and the page shows through the wedge behind it, so a route
reads as a row of distinct blocks rather than one fused ribbon. The
chip fill is the node's hash-derived hue
look, unchanged. ``powerline`` renders each hop as a colour-filled chip, seams drawn
as two solid triangles U+E0B0 — the previous chip tapering out to a point, the next
one notched inward out of its own fill, a sliver of bare page between them: the gapped
oh-my-posh look, where a route reads as a row of distinct blocks rather than one
fused ribbon. The chip fill is the node's hash-derived hue
(:func:`~meshterm.ui.theme.node_style`), our own node the pure ``you`` white, a
faded hop dark slate, a keyless hop grey. ``auto`` (the default) picks powerline exactly
when the terminal can draw it (:func:`~meshterm.ui.termfont.powerline_enabled` —
@@ -329,17 +329,19 @@ class PathLine:
Returns:
``(cells, join, tail, lead, head)`` — each hop's cells, the cells one join
between two hops costs, the cells a line always closes with (chip mode's
edge; nothing in arrow mode), the cells every line *after the first* opens
with (chip mode's reopened seam), and the cells the *first* line opens with
(chip mode's rounded cap, nothing where the font has none).
between two hops costs (chip mode's seam is two: the point tapering out and
the notch cut into the next chip), the cells a line always closes with (chip
mode's edge; nothing in arrow mode), the cells every line *after the first*
opens with (chip mode's notch, the seam's second half redrawn), and the
cells the *first* line opens with (chip mode's rounded cap, nothing where
the font has none).
"""
if plain:
return [self._plain_hop(hop).cell_len for hop in hops], cell_len(self._separator), 0, 0, 0
widths = [self._chip(hop, self._chip_fill(hop)).cell_len for hop in hops]
sep = cell_len(POWERLINE_SEP)
head = cell_len(POWERLINE_ROUND_OPEN) if powerline_full() else 0
return widths, sep, sep, sep, head
return widths, sep * 2, sep, sep, head
@staticmethod
def _fill(
@@ -530,13 +532,15 @@ class PathLine:
def _render_chips(
self, hops: list[PathHop], *, carry_in: bool = False, carry_on: bool = False
) -> Text:
"""Powerline chips: each hop filled with its hue, a page-wide gap at every seam.
"""Powerline chips: each hop filled with its hue, a two-cell gap at every seam.
The two outer ends say whether this line *is* the path or only part of it. A
line that opens the path opens rounded (squared off where the font has no
rounded caps); one that continues a wrapped path opens on the break's other
half. A line that ends the path closes rounded; one the path outruns closes on
the point, the same "goes on" cue arrow mode spells with a trailing ``→``.
half — which is exactly the seam's own second cell, so a fold looks like the
seam it interrupted. A line that ends the path closes rounded; one the path
outruns closes on the point, the same "goes on" cue arrow mode spells with a
trailing ``→``.
Args:
hops: The hops of this one line, in order.
@@ -547,40 +551,63 @@ class PathLine:
rounded = powerline_full()
text = Text()
if carry_in:
# The break's other half: the page notched into this chip's left edge, so
# the line reads as arriving. Reverse video paints the notch in the
# terminal's own background — the only way to name the page's colour
# without knowing it — so not a trace of the line above bleeds into this
# one, and the point still faces the way the path flows.
text.append(POWERLINE_SEP, style=f"{fills[0]} reverse")
text.append_text(self._notch(fills[0])) # the break's other half
elif rounded:
text.append(POWERLINE_ROUND_OPEN, style=fills[0])
for i, hop in enumerate(hops):
if i:
text.append(POWERLINE_SEP, style=self._seam(fills[i - 1], fills[i]))
text.append_text(self._seam(fills[i - 1], fills[i]))
text.append_text(self._chip(hop, fills[i]))
close = POWERLINE_SEP if carry_on or not rounded else POWERLINE_ROUND_CLOSE
text.append(close, style=fills[-1]) # the edge into the page: pointed or round
return text
@staticmethod
def _seam(before: str, after: str) -> str:
"""One seam's style: the previous chip's point, open onto the page.
@classmethod
def _seam(cls, before: str, after: str) -> Text:
"""The two cells between two chips: a point tapering out, a notch cut back in.
The point is drawn in the previous fill with *no* background of its own, so the
page shows through the wedge it tapers out of — the small gap oh-my-posh leaves
between segments. The alternative (interlocking the point into the next chip's
fill) packs the row tighter, but it fuses the route into one continuous ribbon,
and two neighbours that happen to land on the same fill — a hue collision, a run
of faded hops, two keyless greys — then read as a single block where the route
has two nodes. One gap, every seam: a chip is always a chip.
The previous chip's point carries *no* background, so the page shows through the
wedge it tapers into; the next chip's left edge then opens on the same point in
the page's own colour, notched inward out of its fill. Both faces angle the way
the path flows, and between them sits a sliver of bare page — the small gap
oh-my-posh leaves between its segments.
The alternative (one cell, the previous fill interlocked *on* the next) packs
the row tighter but fuses the route into a continuous ribbon, and two neighbours
that happen to land on the same fill — a hue collision, a run of faded hops, two
keyless greys — then read as a single block where the route has two nodes. One
gap, every seam: a chip is always a chip.
Args:
before: The fill the seam tapers out of (the previous chip's).
after: The fill the next chip opens on — no longer part of the seam, kept
so callers still read as "this seam, between these two fills".
after: The fill the seam notches back into (the next chip's).
Returns:
The seam's two cells, styled.
"""
return before
text = Text()
text.append(POWERLINE_SEP, style=before)
text.append_text(cls._notch(after))
return text
@staticmethod
def _notch(fill: str) -> Text:
"""A chip's left edge: the point cut inward out of its own fill.
Reverse video paints the notch in the terminal's own background — the only way
to name the page's colour without knowing it — so nothing of whatever sits left
of the chip (the previous chip's taper, the line above a wrapped break) bleeds
into it, and the point still faces the way the path flows.
Args:
fill: The chip's fill colour, which the notch is cut out of.
Returns:
The one styled cell.
"""
text = Text()
text.append(POWERLINE_SEP, style=f"{fill} reverse")
return text
def _chip_fill(self, hop: PathHop) -> str:
"""A chip's fill colour: override, dim slate, white you, hue, keyless grey.
+8 -5
View File
@@ -87,18 +87,21 @@ def test_empty_path_reads_as_the_callers_word() -> None:
def test_chips_are_separated_by_a_gap_not_an_interlock() -> None:
"""Every seam's triangle carries only a foreground — the previous chip's fill — so
the page shows through the wedge and the chips read as separate blocks (the
oh-my-posh gap), interior seams and the closing edge alike."""
"""A seam is two points, not one interlock: the previous chip tapers out with no
background of its own (the page shows through the wedge), and the next chip's left
edge notches the same point back inward out of its own fill. The closing edge keeps
its single taper — nothing follows it to notch."""
alice_fill = node_style("aa").split()[-1]
line = PathLine(
[PathHop("Alice", key="aa"), PathHop("you", you=True)], mode="powerline"
)
text = line.text()
assert text.plain == f" Alice {POWERLINE_SEP} you {POWERLINE_SEP}"
assert text.plain == f" Alice {POWERLINE_SEP * 2} you {POWERLINE_SEP}"
seam_styles = [str(s.style) for s in text.spans
if text.plain[s.start:s.end] == POWERLINE_SEP]
assert seam_styles == [alice_fill, "#ffffff"] # no "on": nothing behind the point
# taper out of Alice, notch into you (reverse = the page's own colour), closing edge
assert seam_styles == [alice_fill, "#ffffff reverse", "#ffffff"]
assert all(" on " not in style for style in seam_styles) # never an interlock
def test_chips_keep_the_same_words_and_honour_style_overrides() -> None:
+49
View File
@@ -22,6 +22,7 @@ from meshterm.persistence.repository import (
)
from meshterm.services.path_probe import ProbeCandidate, ProbeOutcome, probe_paths
from meshterm.services.topology import build_topology, collapse_width, render_custom_spec
from meshterm.services.trace_runner import make_node_resolver
from meshterm.ui.path_composer import AUTO_SPEC, FetchNeighbours, PathComposerScreen
from meshterm.ui.pathline import SELF_GLYPH
from meshterm.ui.tui.screen import CANCEL
@@ -650,6 +651,54 @@ def test_composer_names_an_ambiguous_hop_through_the_owning_screens_resolver() -
assert "Hub (3d)" in body # the name, and the hash it is addressed by beside it
def test_composer_merges_a_stub_and_its_full_id_into_one_suggestion() -> None:
"""One node the graph holds twice reads — and is addressed — as one row.
``3d`` prefix-matches two contacts, so the topology keeps it as its own vertex
rather than guessing, separate from the ``3d63c6429436`` its wider sightings landed
on. Once both are named, the list would propose the same node twice; they fold onto
the longer id, evidence pooled. The 3d-prefixed *twin* is a different name, so it
stays its own row — a shared prefix alone never merges two nodes.
"""
twin = Contact(name="Twin", public_key="3d99" + "0" * 60, key_prefix="3d9900000000")
walks = [
_traced(("3d", 6.0), (None, 6.0)), # the ambiguous stub
_traced(("3d63c6429436", 8.0), (None, 8.0)), # the very same node, full id
_traced(("3d9900000000", 4.0), (None, 4.0)), # a different node behind 3d
]
topo = _topo(trace_paths=walks, contacts=[REPEATER, twin])
assert topo.display_name("3d") is None # ambiguous: the graph won't fold it itself
assert {s.node for s in topo.next_hops(topo.self_id)} == {
"3d", "3d63c6429436", "3d9900000000",
}
screen = _composer(topo, target=False, resolve=make_node_resolver([REPEATER, twin]))
rows = screen._suggestions()
assert [r.node for r in rows] == ["3d63c6429436", "3d9900000000"]
assert rows[0].link.samples == 4 # both walks' out-and-back readings, pooled
assert rows[0].link.median_snr == 7.0 # 6.0 and 8.0 twice each
def test_composer_steps_off_a_merged_node_with_all_its_evidence() -> None:
"""Standing on the merged node sees everything *either* of its ids was heard by.
Folding the stub away must not fold its links away with it — otherwise merging
would quietly cost the composer whatever was only ever observed under the stub.
"""
twin = Contact(name="Twin", public_key="3d99" + "0" * 60, key_prefix="3d9900000000")
walks = [
_traced(("3d", 6.0), ("f2", -5.0), ("3d", -5.5), (None, 6.0)), # Far, via the stub
_traced(("3d63c6429436", 8.0), (None, 8.0)), # the full id
_traced(("3d9900000000", 4.0), (None, 4.0)), # the other 3d node
]
topo = _topo(trace_paths=walks, contacts=[REPEATER, FAR, twin])
screen = _composer(topo, target=False, hops=["3d63c6429436"], resolve=make_node_resolver(
[REPEATER, FAR, twin]
))
# Far was only ever heard through the stub, and is still offered from the full id.
assert [s.node for s in screen._suggestions()] == ["f2c24f54551e"]
async def test_composer_path_mode_suggests_through_anything_and_commits_verbatim() -> None:
"""A path walk routes *through* any node and commits exactly the composed hops."""
import asyncio