Trace records: the trail rule, a New record dialog, shallower stacks

A record walk must now be a trail — never the same link twice in the
same direction (the reverse crossing stays legal, so target boomerangs
still qualify). Repeating a stretch would let its score be farmed, so
walk_scores disqualifies such walks from every board at once; the
composer shows a yellow "not a trail" note while one is being built,
and Trace gates it behind an amber Cancel/Trace confirm. Matching
non-trail records were purged from the local database (one-off; the
rule never shipped, so no migration).

The inline "new record" note becomes a floating dialog once a run
settles (one per run, Close default, Trophy case on the left). Choosing
Trophy case resolves the whole trace session first, and the trophy
case's own Trace this path no longer reopens the browser behind the
trace screen — both directions unwind to the main menu instead of
piling up states to Esc through.

Committing the path composer also parks the action cursor on Trace, so
compose-then-Enter walks the new route; Esc leaves the cursor put.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Fable 5 committed 2026-07-18 17:25:55 -04:00
1 parent fa07d23adb
commit 0e93d21835
8 files changed
+472 -28

No files matched your search

+42 -1
View File
@@ -16,6 +16,13 @@ route, and its :class:`WalkStats`; :func:`walk_scores` scores those stats agains
discipline at once (a walk found while tracing one thing still counts everywhere it
places). The UI owns the radio and the database; nothing here transmits or persists.
One eligibility rule gates every board: a record walk must be a *trail* — a walk that
never crosses the same link twice in the same direction (see
:func:`first_repeated_edge`). Repeating a link would let any scoring subpath be stitched
in again for free score, so :func:`walk_scores` disqualifies such a walk outright.
Recrossing a link the *other* way stays legal: a Trace target boomerang retraces every
link backwards by design, and radio links genuinely differ by direction.
Records live per ``(category, width_bytes)`` because the per-hop hash width bounds both a
walk's maximum length (the transmitted path field is :data:`MAX_PATH_BYTES`) and its
collision odds — a 1-byte board and a 4-byte board are different games.
@@ -41,6 +48,33 @@ def max_hops(width_bytes: int) -> int:
return MAX_PATH_BYTES // max(1, width_bytes)
def first_repeated_edge(nodes: Sequence[str]) -> Optional[tuple[str, str]]:
"""The first link a walk crosses twice in the same direction, or ``None``.
The trophy case's no-cheat rule, shared by the arbiter and every screen that
warns about it: a record walk must be a *trail* (graph theory's name for a walk
with no repeated edge — here the directed edge ``a → b``, so ``a → b … b → a``
stays a trail while ``a → b … a → b`` does not). The walk's implicit endpoints
at our own node need not be passed in: the arcs touching us can't repeat unless
we relay through ourselves mid-walk.
Args:
nodes: The walked hops in order — spec tokens or canonical ids, compared
case-insensitively; blank entries are ignored.
Returns:
The ``(a, b)`` pair of the first link walked twice (as given, lowercased),
or ``None`` when the walk is a trail.
"""
walked = [n.strip().lower() for n in nodes if n and n.strip()]
seen: set[tuple[str, str]] = set()
for pair in zip(walked, walked[1:]):
if pair in seen:
return pair
seen.add(pair)
return None
# --------------------------------------------------------------------------- scoring
@@ -285,9 +319,16 @@ def compute_walk_stats(
def walk_scores(stats: WalkStats) -> dict[str, float]:
"""Score a walk against every category (the every-board-at-once rule).
A walk that repeats a directed link isn't a trail (see
:func:`first_repeated_edge`) and is disqualified from every board at once — the
arbiter's enforcement of the no-cheat rule, so no caller has to remember it.
Returns:
``category id → score`` for each category the walk can compete in.
``category id → score`` for each category the walk can compete in; empty
for a disqualified walk.
"""
if first_repeated_edge(stats.node_ids) is not None:
return {}
out: dict[str, float] = {}
for category in CATEGORIES:
value = category.score(stats)
+28
View File
@@ -34,6 +34,9 @@ Interaction, following the reorder screen's cursor-over-rows-and-actions pattern
resolves :class:`FetchNeighbours` and the owning flow fetches, refreshes the
topology, and reopens the composer mid-thought (hops preserved).
* Enter on **Use this path** commits the composed spec; Esc cancels with no change.
* A walk that crosses some link twice in the same direction shows a yellow ⚠ note
under the preview: still walkable, but no longer a *trail*, so the trophy case
will ignore it (the no-cheat rule — see :mod:`~meshterm.services.records`).
Nodes and the route preview render through the shared path widget
(:func:`~meshterm.ui.widgets.path_text`, trace flavour) — ``Name (hash)`` with names
@@ -51,6 +54,7 @@ from typing import Optional
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 .theme import snr_style
from .tui.render import render_lines, render_to_ansi
@@ -76,6 +80,14 @@ _CANCEL = "cancel"
#: N(eighbour table fetched from a repeater).
_SOURCE_TAGS = {"trace": "T", "route": "R", "packet": "P", "neighbour": "N"}
#: The inline no-cheat warning, shown under the route preview while the composed walk
#: crosses some link twice in the same direction — repeating a stretch would let its
#: score be farmed, so the trophy case disqualifies such a walk (it is no longer a
#: *trail*, graph theory's walk-with-no-repeated-edge; see
#: :func:`~meshterm.services.records.first_repeated_edge`). Composing one stays legal —
#: the warning only says the walk can't set records.
_NOT_A_TRAIL = "⚠ repeats a link — not a trail, so records ignore this walk"
@dataclass(frozen=True, slots=True)
class FetchNeighbours:
@@ -235,6 +247,18 @@ class PathComposerScreen(Screen):
)
return render_custom_spec(tuple(self._hops), self._width_bytes)
def _walk_nodes(self) -> list[str]:
"""The whole walk the current composition transmits, as canonical ids.
Target mode is the symmetric boomerang (outbound hops, the target, the
mirrored return); path mode is the composed hops verbatim. This is what the
record-eligibility check runs over — the mirror halves matter, because a
repeated outbound stretch repeats on the return leg too.
"""
if self._mirrored:
return [*self._hops, str(self._target_id), *reversed(self._hops)]
return list(self._hops)
# --- rendering ---------------------------------------------------------------
def _path_entry(self, node: str) -> Optional[str]:
@@ -346,6 +370,8 @@ class PathComposerScreen(Screen):
"""Natural outer width hugging the widest row (compositor still caps it)."""
widths = [cell_len(self.title), cell_len(self.footer_hint)]
widths.append(cell_len(self._route_preview().plain))
if first_repeated_edge(self._walk_nodes()) is not None:
widths.append(cell_len(_NOT_A_TRAIL))
for kind, payload in self._rows():
widths.append(cell_len(self._row_text(kind, payload).plain) + 2)
return max(widths, default=20) + 8
@@ -361,6 +387,8 @@ class PathComposerScreen(Screen):
self._index = max(0, min(self._index, len(rows) - 1))
lines = render_lines(self._route_preview(), width)
if first_repeated_edge(self._walk_nodes()) is not None:
lines.extend(render_lines(Text(_NOT_A_TRAIL, style="warn"), width))
lines.append("")
if self._entry:
lines.append(render_to_ansi(Text(f"/{self._entry}", style="warn"), width))
+10 -3
View File
@@ -17,7 +17,9 @@ opened from the main menu. Every successful trace — a *Trace target* boomerang
pins, no labels); then the full route and spec, and when/by which app version it was
set. The card scrolls (PgUp/PgDn/Home/End) when it outgrows the terminal. From there
*Trace this path* reopens Trace path with the record's route prefilled, so a claim
worth re-testing is one Enter from the air again;
worth re-testing is one Enter from the air again — and when that screen closes, the
flow unwinds to the main menu rather than re-entering the browser, so the user is
never left many Escs deep;
* deletion comes in three grains, each behind a red data-loss dialog: one record
behind a Cancel/Delete confirm, and — the bulk grains — one discipline (every width)
or everything, each gated behind typing ``delete``.
@@ -429,7 +431,8 @@ async def open_records(ctx: "AppContext") -> dict:
Wires the browser to the database and the observed contacts: records come straight
from :meth:`Repository.discoveries`, and hop hashes resolve to friendly names
through the same resolver the trace screens use. *Trace this path* hands off to the
live Trace path screen with the record's route prefilled and returns here after.
live Trace path screen with the record's route prefilled; when that screen closes,
this flow returns (unwinding to the main menu) instead of reopening the browser.
Args:
ctx: The shared application context (must be running the interactive TUI).
@@ -722,6 +725,10 @@ async def open_records(ctx: "AppContext") -> dict:
finally:
session.pop(browser)
# Tracing a path is a full hand-off to the Trace screen, not a dialog over the
# trophy case, so it runs only once the browser backdrop is down.
# trophy case, so it runs only once the browser backdrop is down — and the
# browser does not reopen behind it: when the trace screen closes, this whole
# flow returns, landing the user on the main menu instead of a trophy-case →
# trace → trophy-case stack that takes many Escs to climb out of.
if trace_spec is not None:
await open_trace_path(ctx, spec=trace_spec)
return {"records": len(ctx.repo.discoveries())}
+146 -23
View File
@@ -22,6 +22,8 @@ whatever you make it, and nothing transmits until you say so. An action list dri
repeater you hold admin credentials for, the composer can also *fetch that repeater's
neighbour table* over the mesh (login required; firmware ignores guests):
second-vantage evidence, persisted and folded straight back into the suggestions.
Committing the composer parks the action cursor on Trace — compose, then plain
Enter walks it — while backing out with Esc leaves the cursor where it was.
* **Reverse path** (Trace path only — a target-mode route is a symmetric boomerang,
so flipping it changes nothing) reverses the walk's hop order: ``us → a → b → c``
becomes ``us → c → b → a``. Radio links rarely read the same both ways, so this
@@ -47,7 +49,13 @@ whatever you make it, and nothing transmits until you say so. An action list dri
number of traces. While they fly, a floating *tracing* dialog (spinner, progress,
Abort) sits over the screen — replies stream into the log behind it, and Esc in the
dialog cancels without leaving the screen; traces already recorded are kept. The
screen keeps aggregating every trace of the session into its medians.
screen keeps aggregating every trace of the session into its medians. A walk that
crosses some link twice in the same direction first confirms on an amber
Cancel/Trace dialog — such a walk isn't a *trail*, so the trophy case ignores it
(the no-cheat rule; see :mod:`~meshterm.services.records`) — and a run that places
on the boards floats a *New record* dialog once it settles: Close (the default)
stays on the screen, Trophy case unwinds the whole session and opens the boards,
so leaving them lands on the main menu.
* **Back** leaves the screen, exactly like Esc.
Layout, top to bottom: the walked route (live when a reply has landed, else the route
@@ -78,6 +86,7 @@ from rich.text import Text
from ..core.models import PATH_TRACE_TARGET, TraceResult, TraceStats
from ..services import trace_runner
from ..services.records import first_repeated_edge
from ..services.topology import render_forced_spec
from .braillechart import meter
from .menus import back_rows
@@ -107,6 +116,12 @@ _BAR_SNR_MAX = 10.0
#: runs, paced between transmissions.
SAMPLE_CHOICES = (1, 2, 3, 5, 8)
#: What the trace screen resolves with when the new-record dialog's *Trophy case*
#: button is chosen. The session opener catches it and opens the trophy case only
#: after the screen has fully unwound, so leaving the trophy case afterwards lands
#: on the main menu instead of re-entering a stack of trace screens.
OPEN_TROPHY_CASE = "records"
#: A single-trace runner: ``(path_spec, on_trace)`` → runs exactly one trace, handing
#: the result — plus any trophy-case disciplines the walk just placed in, as short
#: ``"Title — score"`` labels — to ``on_trace`` when it lands. Provided by the session
@@ -334,10 +349,11 @@ class TraceScreen(Screen):
self._auto_spec = auto_spec
self._auto_source = auto_source
self._path_spec = initial_spec.strip()
#: The trophy-case disciplines the latest run placed in, as a ready-to-show
#: "★ new record · …" line — set when a walk scores, cleared when a run starts
#: or the path changes. Surfaced under the run's aggregates.
self._record_note = ""
#: The trophy-case disciplines the current run has placed in, keyed by
#: discipline title so an improving multi-sample run keeps only its latest
#: ``"Title — score"`` label per board. Cleared when a run starts; drained
#: into the floating new-record dialog once the run settles.
self._run_placed: dict[str, str] = {}
#: Traces aggregated on screen — the current route's run. Adopting a
#: different path clears it (old numbers describe the old route).
self._traces: list[TraceResult] = []
@@ -383,7 +399,7 @@ class TraceScreen(Screen):
return
self._running = True
self._status = ""
self._record_note = "" # this run earns its own records
self._run_placed.clear() # this run earns its own records
self._spinner.reset()
self._worker = asyncio.ensure_future(self._run_trace())
self._session.invalidate()
@@ -433,6 +449,13 @@ class TraceScreen(Screen):
self._running = False
self._progress = None
self._session.invalidate()
if self._run_placed and not (self.future is not None and self.future.done()):
# The run placed on the boards: float the new-record dialog once the
# tracing dialog is down. A separate task, because an aborted run
# reaches here already cancelled and couldn't await a dialog itself;
# a run whose screen is already resolving (Esc mid-run) skips it —
# a popup must never chase the user out of the screen.
asyncio.ensure_future(self._announce_records())
async def _animate(self) -> None:
"""Advance the in-flight spinner and repaint on a steady cadence, until cancelled."""
@@ -442,25 +465,61 @@ class TraceScreen(Screen):
self._session.invalidate()
def _on_trace(self, result: TraceResult, placed: Sequence[str] = ()) -> None:
"""Append the landed trace, note any records it set, echo it, and repaint.
"""Append the landed trace, bank any records it set, echo it, and repaint.
Args:
result: The trace that just landed.
placed: The trophy-case disciplines this walk placed in, as short
``"Title — score"`` labels (empty when it set nothing). A run that
sets nothing on a later trace leaves an earlier trace's note standing.
``"Title — score"`` labels (empty when it set nothing). They bank
into the run's tally — announced in one dialog when the run settles
(see :meth:`_announce_records`), a later improvement replacing the
earlier label on the same board.
"""
self._traces.append(result)
self._total_traces += 1
if placed:
if len(placed) == 1:
self._record_note = f"new record · {placed[0]}"
else:
self._record_note = f"{len(placed)} new records · " + " · ".join(placed)
for label in placed:
self._run_placed[label.split(" — ")[0]] = label
if self._flight is not None:
self._flight.last = result
self._session.invalidate()
async def _announce_records(self) -> None:
"""Float the new-record dialog for everything the settled run placed.
One dialog per run, however many samples scored: each placed discipline reads
as its own ``★ Title — score`` line. Platform-dialog shape — *Trophy case* on
the left, *Close* on the right and default — so Enter simply dismisses and Esc
closes. Choosing Trophy case resolves the whole screen with
:data:`OPEN_TROPHY_CASE`: the session opener then opens the trophy case only
*after* this screen (and everything stacked over it) has unwound, so backing
out of the trophy case lands on the main menu, never a pile of trace screens.
"""
if self._dialog_open:
return
self._dialog_open = True
try:
labels = list(self._run_placed.values())
self._run_placed.clear()
prompt = Text()
for i, label in enumerate(labels):
if i:
prompt.append("\n")
prompt.append("★ ", style="accent")
prompt.append(label, style="accent")
choice = await self._session.button_dialog(
prompt,
[("Trophy case", OPEN_TROPHY_CASE), ("Close", None)],
title="New record" if len(labels) == 1 else f"{len(labels)} new records",
default=1,
footer_hint="←→ choose · Enter select · Esc close",
)
finally:
self._dialog_open = False
self._session.invalidate()
if choice == OPEN_TROPHY_CASE:
self.cancel()
self.resolve(OPEN_TROPHY_CASE)
def cancel(self) -> None:
"""Cancel any in-flight trace run (already-recorded traces are kept)."""
if self._worker is not None and not self._worker.done():
@@ -508,7 +567,11 @@ class TraceScreen(Screen):
# back to device routing.
if self._mode == "path" and not self._effective_spec()[0]:
return
self.start_trace()
edge = first_repeated_edge(self._spec_tokens())
if edge is not None:
self._confirm_ineligible(edge)
else:
self.start_trace()
elif key == "width":
self._open_flow(self._pick_width)
elif key == "samples":
@@ -517,8 +580,11 @@ class TraceScreen(Screen):
# Seed the composer with the route the screen is showing — the composed
# spec if one stands, else the auto-resolved plan — not the bare
# (empty on first open) stored spec, so opening Compose always resumes
# from the visible route.
self._open_flow(self._compose_path, seed=self._effective_spec()[0])
# from the visible route. Committing the composer parks the cursor on
# Trace (see _open_flow): compose, then plain Enter walks it.
self._open_flow(
self._compose_path, seed=self._effective_spec()[0], focus_trace=True
)
elif key == "reverse":
self._reverse_path()
elif key == "explore" and self._explore is not None:
@@ -527,7 +593,9 @@ class TraceScreen(Screen):
self.cancel()
self.resolve(None)
def _open_flow(self, flow: PathFlow, seed: Optional[str] = None) -> None:
def _open_flow(
self, flow: PathFlow, seed: Optional[str] = None, focus_trace: bool = False
) -> None:
"""Float a path-picking flow over the screen (one at a time, not mid-trace).
The composer, the scenario explorer, and the width picker all resolve the
@@ -542,6 +610,10 @@ class TraceScreen(Screen):
no spec stands), so it never opens blank over a shown route. The
adopt test still compares against the stored spec, so re-confirming an
auto plan verbatim simply pins it, exactly like adopting it by hand.
focus_trace: Whether committing the flow (any non-``None`` resolution,
even the unchanged spec) should park the action cursor on Trace —
the composer's hand-back, so plain Enter walks what was just built.
Backing out with Esc leaves the cursor where it was.
"""
if self._dialog_open or self._running:
return
@@ -550,6 +622,8 @@ class TraceScreen(Screen):
async def run() -> None:
try:
spec = await flow(self._path_spec if seed is None else seed)
if spec is not None and focus_trace:
self._index = self._actions.index("trace")
if spec is not None and spec.strip() != self._path_spec:
# A different spec is a different measurement: the aggregates,
# per-hop medians, and log all belong to the old route, so the
@@ -557,7 +631,6 @@ class TraceScreen(Screen):
self._path_spec = spec.strip()
self._traces.clear()
self._status = ""
self._record_note = "" # the note described the old route's run
finally:
self._dialog_open = False
self._session.invalidate()
@@ -745,6 +818,52 @@ class TraceScreen(Screen):
spec = self._auto_spec()
return spec, bool(spec)
def _spec_tokens(self) -> list[str]:
"""The effective spec's hop hashes in walk order (empty = path-less trace)."""
spec, _ = self._effective_spec()
return [t.strip() for t in spec.split(",") if t.strip()]
def _confirm_ineligible(self, edge: tuple[str, str]) -> None:
"""Float the amber not-a-trail confirm before walking a record-ineligible path.
The walk about to fly crosses ``edge`` twice in the same direction, so it
isn't a trail and the trophy case will ignore whatever it scores (the
no-cheat rule — see :func:`~meshterm.services.records.first_repeated_edge`).
Walking it is still perfectly fine, so the dialog only makes the
disqualification explicit: Cancel backs out, Trace — on the right and the
default, like every committing verb — transmits anyway.
"""
if self._dialog_open or self._running:
return
self._dialog_open = True
async def run() -> None:
try:
prompt = Text("This walk crosses ", style="warn")
prompt.append_text(
_link_text(edge[0], edge[1], self._device_label, self._resolve)
)
prompt.append(" twice in the same direction, ", style="warn")
prompt.append(
"so it isn't a trail — records will ignore it. Trace anyway?",
style="warn",
)
choice = await self._session.button_dialog(
prompt,
[("Cancel", None), ("Trace", "trace")],
title="Not eligible for records",
default=1,
footer_hint="←→ choose · Enter select · Esc cancel",
border_style="warn",
)
finally:
self._dialog_open = False
self._session.invalidate()
if choice == "trace":
self.start_trace()
asyncio.ensure_future(run())
def _planned_route(self) -> Optional[Text]:
"""The route the next Trace walks as a preview, or ``None`` without one.
@@ -824,9 +943,6 @@ class TraceScreen(Screen):
hops = self._displayed_hop_count(current)
if hops is not None:
summary.append(f" · {hops} hop{'s' if hops != 1 else ''}", style="muted")
if self._record_note:
summary.append("\n★ ", style="accent")
summary.append(self._record_note, style="accent")
return summary
def _hops_table(self, stats: TraceStats, hash_bytes: Optional[int]) -> Table:
@@ -1756,7 +1872,14 @@ async def _open_session(
initial_spec=initial_spec if mode == "path" else "",
)
try:
await session.run_screen(screen)
result = await session.run_screen(screen)
finally:
screen.cancel()
if result == OPEN_TROPHY_CASE:
# The new-record dialog's hand-off: the trace screen (and every prompt over
# it) is already down, so the trophy case opens over a clean stack and Esc
# from it unwinds straight to the main menu — never back into this session.
from .records_screen import open_records
await open_records(ctx)
return screen._total_traces
+154 -1
View File
@@ -15,7 +15,7 @@ import pytest
from meshterm.core.models import Hop, TraceResult, TraceStats, TxLevelResult, TxOptResult, utcnow
from meshterm.ui.braillechart import _METER_SLIM
from meshterm.ui.theme import snr_style
from meshterm.ui.trace_screen import _BAR_WIDTH, TraceScreen, snr_bar
from meshterm.ui.trace_screen import _BAR_WIDTH, OPEN_TROPHY_CASE, TraceScreen, snr_bar
from meshterm.ui.tx_screen import TxSweepScreen
# The slim meter's fill glyphs (the SNR bar draws through the shared braille meter).
@@ -28,6 +28,10 @@ class _FakeSession:
def __init__(self) -> None:
self.repaints = 0
self.stack: list = []
#: Every button_dialog floated, as ``(prompt, buttons, kwargs)``; the next
#: one resolves with ``dialog_answer`` (``None`` = the Esc/idle-cancel path).
self.dialogs: list = []
self.dialog_answer = None
def invalidate(self) -> None:
self.repaints += 1
@@ -41,6 +45,10 @@ class _FakeSession:
elif screen in self.stack:
self.stack.remove(screen)
async def button_dialog(self, prompt, buttons, **kwargs): # noqa: ANN001
self.dialogs.append((prompt, buttons, kwargs))
return self.dialog_answer
def _trace(*snrs: float, success: bool = True, target: str = "Alice") -> TraceResult:
"""Build a trace with one hop per SNR reading."""
@@ -474,6 +482,151 @@ async def test_trace_screen_back_row_resolves_like_escape() -> None:
assert screen.future.result() is None
async def test_composer_commit_parks_the_cursor_on_trace() -> None:
"""Committing the composer hands the cursor to Trace, so plain Enter walks it."""
async def compose(current): # noqa: ANN001
return "3d,f2,3d"
screen, _ = _trace_screen(compose_path=compose)
screen._index = screen._actions.index("compose")
screen.handle("enter")
await asyncio.sleep(0)
assert screen._actions[screen._index] == "trace"
# The hand-back is the composer's alone: the width flow keeps the cursor put.
async def width(current): # noqa: ANN001
return "3d63,f2c2,3d63"
other, _ = _trace_screen(pick_width=width)
other._index = other._actions.index("width")
other.handle("enter")
await asyncio.sleep(0)
assert other._actions[other._index] == "width"
async def test_composer_escape_leaves_the_cursor_where_it_was() -> None:
"""Backing out of the composer with Esc moves nothing."""
async def compose(current): # noqa: ANN001
return None # the composer's Esc resolution
screen, _ = _trace_screen(compose_path=compose)
screen._index = screen._actions.index("compose")
screen.handle("enter")
await asyncio.sleep(0)
assert screen._actions[screen._index] == "compose"
# --- the no-cheat rule on Trace ------------------------------------------------------
async def _settle(screen) -> None: # noqa: ANN001
"""Let a just-committed dialog task run, then any trace worker it started."""
for _ in range(5):
await asyncio.sleep(0)
if screen._worker is not None:
await screen._worker
async def test_ineligible_walk_gates_trace_behind_an_amber_confirm() -> None:
"""A same-direction link recross floats Cancel/Trace and cancels cleanly."""
ran: list[str] = []
async def trace(path_spec, on_trace): # noqa: ANN001
ran.append(path_spec)
on_trace(_trace(5.0))
screen, session = _trace_screen(trace=trace, mode="path")
screen._path_spec = "3d,f2,3d,f2" # rides 3d → f2 twice the same way
screen._index = screen._actions.index("trace")
screen.handle("enter") # dialog_answer None = Cancel/Esc
await _settle(screen)
prompt, buttons, kwargs = session.dialogs[0]
assert [label for label, _ in buttons] == ["Cancel", "Trace"]
assert kwargs["default"] == 1 # Trace on the right and default: Enter commits it
assert kwargs["border_style"] == "warn" # the amber caution tier
assert "trail" in prompt.plain # the graph-theory name reaches the user
assert ran == [] # cancelled: nothing transmitted
session.dialog_answer = "trace"
screen.handle("enter")
await _settle(screen)
assert ran == ["3d,f2,3d,f2"] # confirmed: the walk still flies
async def test_eligible_walk_traces_without_a_confirm() -> None:
"""An out-and-back walk recrosses links the other way only — no dialog, no nag."""
screen, session = _trace_screen(mode="path")
screen._path_spec = "3d,f2,3d"
screen._index = screen._actions.index("trace")
screen.handle("enter")
await screen._worker
assert session.dialogs == []
assert len(screen._traces) == 1
# --- the new-record dialog -----------------------------------------------------------
async def test_record_run_floats_the_new_record_dialog() -> None:
"""A run that placed floats one dialog; Close (the default) keeps the screen up."""
async def trace(path_spec, on_trace): # noqa: ANN001
on_trace(_trace(5.0), ["Most nodes — 4 nodes"])
screen, session = _trace_screen(trace=trace)
screen.future = asyncio.get_running_loop().create_future()
screen.start_trace()
await screen._worker
await _settle(screen) # the announcement task floats after the run settles
prompt, buttons, kwargs = session.dialogs[0]
assert "Most nodes — 4 nodes" in prompt.plain
assert [label for label, _ in buttons] == ["Trophy case", "Close"]
assert kwargs["default"] == 1 # Close is the default: Enter simply dismisses
assert kwargs["title"] == "New record"
assert not screen.future.done() # Close/Esc: the screen stays up
assert screen._run_placed == {} # announced once, not again on the next run
async def test_record_dialog_trophy_case_hands_the_screen_off() -> None:
"""Choosing Trophy case resolves the screen with the hand-off sentinel."""
async def trace(path_spec, on_trace): # noqa: ANN001
on_trace(_trace(5.0), ["Most nodes — 4 nodes", "Longest distance — 12.4 km"])
screen, session = _trace_screen(trace=trace, samples=2)
session.dialog_answer = OPEN_TROPHY_CASE
screen.future = asyncio.get_running_loop().create_future()
screen.start_trace()
await screen._worker
await _settle(screen)
_prompt, _buttons, kwargs = session.dialogs[0]
assert kwargs["title"] == "2 new records" # one dialog for the whole run
assert len(session.dialogs) == 1 # however many samples scored
assert screen.future.result() == OPEN_TROPHY_CASE
async def test_escaping_mid_run_skips_the_record_dialog() -> None:
"""Esc while records are banked leaves quietly — no popup chases the user out."""
release = asyncio.Event()
async def trace(path_spec, on_trace): # noqa: ANN001
on_trace(_trace(5.0), ["Most nodes — 4 nodes"])
await release.wait()
screen, session = _trace_screen(trace=trace, samples=2)
screen.future = asyncio.get_running_loop().create_future()
screen.start_trace()
await asyncio.sleep(0)
screen.handle("escape") # resolves the screen and cancels the run
with pytest.raises(asyncio.CancelledError):
await screen._worker
for _ in range(3):
await asyncio.sleep(0)
assert session.dialogs == []
def test_planned_route_dims_only_the_mirrored_return_leg() -> None:
"""A palindromic target-mode spec dims its second half; hand walks never dim."""
screen, _ = _trace_screen()
+25
View File
@@ -12,6 +12,7 @@ from meshterm.persistence.repository import Repository
from meshterm.services.records import (
CATEGORY_BY_ID,
compute_walk_stats,
first_repeated_edge,
max_hops,
walk_from_trace,
walk_scores,
@@ -96,6 +97,30 @@ def test_max_hops_follows_the_64_byte_path_field() -> None:
assert max_hops(4) == 16
# --- the no-cheat rule (a record walk must be a trail) -------------------------------
def test_first_repeated_edge_flags_only_a_same_direction_recross() -> None:
"""a→b twice breaks the trail; the boomerang's b→a return leg never does."""
assert first_repeated_edge(("a", "b", "c")) is None
# A target boomerang retraces every link backwards by design: still a trail.
assert first_repeated_edge(("a", "b", "t", "b", "a")) is None
assert first_repeated_edge(("a", "b", "a", "b")) == ("a", "b")
assert first_repeated_edge(("A ", "b", "a", "B")) == ("a", "b") # case/space folded
assert first_repeated_edge(()) is None
def test_walk_scores_disqualify_a_non_trail_from_every_board() -> None:
"""Riding a link twice the same way pumps km and hops for free — every board says no."""
stats = compute_walk_stats(
(HUB_ID, FAR_ID, HUB_ID, FAR_ID), # Hub→Far ridden twice
_result(8.0, 6.0, 7.0, 5.0, 9.0).hops, rtt_ms=100.0,
positions=POSITIONS, self_pos=SELF_POS,
)
assert stats.km_travelled > 0 # it would have scored…
assert walk_scores(stats) == {} # …but the arbiter disqualifies it outright
# --- deriving a walk from a trace ---------------------------------------------------
+43
View File
@@ -328,3 +328,46 @@ async def test_delete_a_disciplines_records_is_a_popup_over_the_browser(tui_ctx)
task.cancel()
assert result == {"records": 1}
async def test_trace_this_path_unwinds_to_the_menu_not_the_browser(
tui_ctx, monkeypatch
) -> None:
"""After the Trace path hand-off, ``open_records`` returns instead of reopening.
The anti-deep-stack rule: trophy case → Trace this path → (trace screen closes)
must land on the main menu, not back in the browser — otherwise bouncing between
the boards and the trace screens piles up states the user has to Esc through.
"""
ctx = tui_ctx
session = ctx.ui.session
ctx.repo.record_discovery(
"grand_tour", 1, "3d,f2", (HUB_ID, FAR_ID),
score=2.0, stats={"hop_count": 2, "distinct_nodes": 2}, app_version="0.1.0",
)
walked: list[str] = []
async def fake_trace_path(ctx_, spec=""): # noqa: ANN001
walked.append(spec)
return 0
monkeypatch.setattr("meshterm.ui.trace_screen.open_trace_path", fake_trace_path)
task = asyncio.ensure_future(open_records(ctx))
try:
browser = await _step_until(lambda: _trophy_case(session))
assert browser is not None
record = ctx.repo.discoveries("grand_tour")[0]
browser.resolve(("open", CATEGORY_BY_ID["grand_tour"], 1, record))
dialog = await _step_until(
lambda: session._float_layers()[0] if session._has_float() else None
)
assert isinstance(dialog, RecordDialog)
dialog.resolve("trace") # "Trace this path"
result = await task # …and the flow returns; no browser re-entry to unwind
finally:
if not task.done():
task.cancel()
assert walked == ["3d,f2"] # the record's spec went straight to Trace path
assert result == {"records": 1}
+24
View File
@@ -358,6 +358,30 @@ def test_composer_typed_hex_adds_a_custom_hop_and_backspace_removes() -> None:
assert screen._hops == []
def test_composer_warns_when_the_walk_repeats_a_link() -> None:
"""Riding a link twice the same way shows the yellow not-a-trail note; fixing it clears."""
screen = _composer(
_topo(), hops=["3d63c6429436", "f2c24f54551e"], target=False
)
assert "not a trail" not in _rows_plain(screen)
screen._hops += ["3d63c6429436", "f2c24f54551e"] # …→ 3d → f2 ridden again
body = _rows_plain(screen)
assert "⚠" in body and "not a trail" in body and "records ignore" in body
screen.handle("backspace") # drop the second f2: the repeat is gone
assert "not a trail" not in _rows_plain(screen)
def test_composer_target_mode_warning_covers_the_mirrored_return() -> None:
"""The check runs over the whole boomerang — a repeated outbound stretch fires it."""
clean = _composer(_topo(), hops=["3d63c6429436"])
assert "not a trail" not in _rows_plain(clean) # the plain boomerang is a trail
screen = _composer(
_topo(),
hops=["3d63c6429436", "27d4396a2967", "3d63c6429436", "27d4396a2967"],
)
assert "not a trail" in _rows_plain(screen)
async def test_composer_fetch_row_resolves_a_fetch_request() -> None:
"""Standing on a fetchable repeater, Enter on the fetch row hands off to the owner."""
import asyncio