Watchtower: type glyphs, key-hued names, sideways scroll

Watchlist rows now lead with the shared node-type marker in its own
colour (the type is stored at star time; legacy entries resolve
through the contact table) with the name in its key-derived hue —
silence keeps its ⚠ tail instead of tinting the glyph. Unacked alert
labels resolve back to a key for their hue (contacts first, then the
watchlist's own names, so a starred node colours even offline); acked
rows recede to muted whole. The star-a-node picker draws the same
glyph-and-hue rows. Long rows can now be read to the end: SelectScreen
grows an opt-in hscroll flag — ←/→ slide every row under the pinned
pointer via crop_cells, clamped at the widest row, surviving ↑↓ and
resetting on filter edits — enabled only here, with the footer
advertising it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Fable 5 committed 2026-07-19 01:09:56 -04:00
1 parent 4dc9608761
commit c4622d529a
5 files changed
+266 -23

No files matched your search

+17 -2
View File
@@ -56,6 +56,9 @@ class WatchedNode:
silence countdown is armed immediately).
silent_since: Set while a silence alarm is active, so it fires once and
re-arms only after the node is heard again.
node_type: The node's advertised type at star time (a ``NODE_TYPE_*``
constant), for the watchlist's type glyph; ``None`` for entries starred
before the field existed (the screen falls back to the contact table).
"""
key: str
@@ -64,6 +67,7 @@ class WatchedNode:
snr_watch: bool = True
last_heard: Optional[datetime] = None
silent_since: Optional[datetime] = None
node_type: Optional[int] = None
@dataclass(slots=True)
@@ -139,6 +143,7 @@ class WatchStore:
for key, record in watched.items():
if not isinstance(record, dict):
continue
raw_type = record.get("node_type")
state.watched[str(key)] = WatchedNode(
key=str(key),
name=str(record.get("name") or key),
@@ -146,6 +151,7 @@ class WatchStore:
snr_watch=bool(record.get("snr_watch", True)),
last_heard=_as_time(record.get("last_heard")),
silent_since=_as_time(record.get("silent_since")),
node_type=raw_type if isinstance(raw_type, int) and raw_type >= 0 else None,
)
for record in data.get("alerts", []):
if not isinstance(record, dict):
@@ -175,7 +181,14 @@ class WatchStore:
"""Whether ``key`` is on the watchlist."""
return key in self.state.watched
def watch(self, key: str, name: str, *, last_seen: Optional[datetime] = None) -> None:
def watch(
self,
key: str,
name: str,
*,
last_seen: Optional[datetime] = None,
node_type: Optional[int] = None,
) -> None:
"""Star a node with default rules.
The silence countdown arms immediately: it counts from the contact's known
@@ -187,9 +200,10 @@ class WatchStore:
key: The node's canonical 12-hex id.
name: Display label.
last_seen: When the node was last heard, if known.
node_type: The node's advertised type, if known (for the watchlist glyph).
"""
self.state.watched[key] = WatchedNode(
key=key, name=name, last_heard=last_seen or utcnow()
key=key, name=name, last_heard=last_seen or utcnow(), node_type=node_type
)
self._save()
@@ -361,6 +375,7 @@ class WatchStore:
"snr_watch": e.snr_watch,
"last_heard": e.last_heard.isoformat() if e.last_heard else None,
"silent_since": e.silent_since.isoformat() if e.silent_since else None,
"node_type": e.node_type,
}
for key, e in state.watched.items()
},
+35 -2
View File
@@ -14,7 +14,7 @@ from typing import Any, Callable, Optional, Union
from rich.cells import cell_len
from rich.text import Text
from .render import render_lines, render_to_ansi
from .render import crop_cells, render_lines, render_to_ansi
from .screen import Screen
@@ -108,6 +108,9 @@ class SelectScreen(Screen):
if the user presses Esc.
"""
#: Cells one ←/→ press shifts an h-scrolling list by (see the ``hscroll`` flag).
_HSCROLL_STEP = 8
def __init__(
self,
title: str,
@@ -119,6 +122,7 @@ class SelectScreen(Screen):
delete_hint: str = "",
filterable: bool = True,
wrap: bool = True,
hscroll: bool = False,
) -> None:
"""Build a select screen.
@@ -139,9 +143,16 @@ class SelectScreen(Screen):
wrap: Whether the highlight wraps around the ends (Down from the last row jumps
to the first, and vice versa). Off for grouped lists where wrapping across the
section headings reads as a jarring jump rather than continuing to scroll.
hscroll: Whether ←/→ shift every row sideways so an over-long line can be read
to its end (the Watchtower's alert log). Off by default — rows simply
ellipsize at the right edge and ←/→ stay inert, exactly as before. The
shift survives ↑↓ moves (you scrolled to a column; walking rows keeps it)
and resets when the filter is edited.
"""
super().__init__()
self.title = title
self._hscroll = hscroll
self._hshift = 0
if footer_hint is None:
footer_hint = (
"↑↓ move · type to filter · Enter select · Esc back"
@@ -293,6 +304,16 @@ class SelectScreen(Screen):
self._index = max(0, min(self._index, len(choices) - 1)) if choices else 0
selected = choices[self._index] if choices else None
# Clamp an active horizontal shift to the widest row, so → stops at the point
# where the longest line's tail has come into view (measured fresh each paint —
# callable titles may have changed width).
if self._hscroll and self._hshift:
widest = 0
for item in rows:
label = item.title if isinstance(item, Separator) else item.label
widest = max(widest, cell_len(_plain(label)) + 2)
self._hshift = max(0, min(self._hshift, widest - width))
lines: list[str] = []
# A prompt (when set) sits above the list, offsetting every row below it; the cursor
# line and sticky-header indices below are shifted by exactly this many lines.
@@ -314,6 +335,8 @@ class SelectScreen(Screen):
# string is drawn uniformly in the separator's style.
title = item.title
heading = title if isinstance(title, Text) else Text(title, style=item.style)
if self._hscroll and self._hshift:
heading = crop_cells(heading, self._hshift, width)
sep = render_to_ansi(heading, width)
self._sticky_headers.append((len(lines), sep))
lines.append(sep)
@@ -326,7 +349,11 @@ class SelectScreen(Screen):
# row's base style underneath, so the highlight tints the row while the badge
# keeps its colour. A plain string is styled uniformly as before.
text = Text(pointer, style=style)
text.append_text(label if isinstance(label, Text) else Text(label))
label_text = label if isinstance(label, Text) else Text(label)
if self._hscroll and self._hshift:
# The 2-cell pointer stays pinned; only the label slides under it.
label_text = crop_cells(label_text, self._hshift, max(1, width - 2))
text.append_text(label_text)
text.style = style
text.no_wrap = True
text.overflow = "ellipsis"
@@ -379,14 +406,20 @@ class SelectScreen(Screen):
# (e.g. a remembered network device in the picker); elsewhere it's inert.
if choices and choices[self._index].deletable:
self.resolve(DeleteRequest(choices[self._index].value))
elif action == "left" and self._hscroll:
self._hshift = max(0, self._hshift - self._HSCROLL_STEP)
elif action == "right" and self._hscroll:
self._hshift += self._HSCROLL_STEP # clamped to the widest row at render
elif action == "escape":
super().handle("escape")
elif action == "backspace" and self._filterable:
self._filter = self._filter[:-1]
self._index = 0
self._hshift = 0
elif action == "text" and self._filterable and data.isprintable():
self._filter += data
self._index = 0
self._hshift = 0
class ReorderScreen(Screen):
+78 -19
View File
@@ -16,15 +16,17 @@ is opened before that ever happened). Nothing transmits.
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Any, Callable, Optional
from rich.text import Text
from ..core.models import NODE_TYPE_REPEATER, Contact
from ..core.models import Contact
from ..core.watch_store import OFF, SILENCE_CHOICES_H, Alert, WatchedNode
from ..services.trace_runner import make_name_key_resolver
from .menus import back_rows, section_heading
from .theme import name_style
from .tui import Choice, Separator
from .widgets import _age_seconds, _format_age
from .widgets import _DEFAULT_GLYPH, _NODE_GLYPHS, _age_seconds, _format_age
if TYPE_CHECKING:
from ..context import AppContext
@@ -82,16 +84,31 @@ async def open_watchtower(ctx: "AppContext") -> Optional[dict[str, Any]]:
contacts = []
store = ctx.watch_store
# Legacy watched entries (starred before types were stored) fall back to the
# contact table's advertised type; alert labels resolve back to keys for their hue.
type_by_key = {
key: c.node_type
for c in contacts
if (key := contact_watch_key(c)) is not None and c.node_type is not None
}
contact_key_of = make_name_key_resolver(contacts)
loop = asyncio.get_running_loop()
cursor: Any = None
while True:
items = _menu_items(store.alerts(), store.watched(), store.new_node_alerts)
items = _menu_items(
store.alerts(),
store.watched(),
store.new_node_alerts,
type_of=type_by_key.get,
key_of=contact_key_of,
)
menu = SelectScreen(
"Watchtower — alerts & watched nodes",
items,
default=cursor,
wrap=False,
footer_hint="↑↓ move · Enter select/acknowledge · Esc back",
hscroll=True,
footer_hint="↑↓ move · ←→ scroll · Enter select/acknowledge · Esc back",
)
menu.future = loop.create_future()
session.push(menu)
@@ -121,14 +138,35 @@ async def open_watchtower(ctx: "AppContext") -> Optional[dict[str, Any]]:
def _menu_items(
alerts: list[Alert], watched: dict[str, WatchedNode], new_node_alerts: bool
alerts: list[Alert],
watched: dict[str, WatchedNode],
new_node_alerts: bool,
*,
type_of: Callable[[str], Optional[int]] = lambda key: None,
key_of: Callable[[str], Optional[str]] = lambda name: None,
) -> list:
"""Build the screen's rows: alerts, then the watchlist, then the actions."""
"""Build the screen's rows: alerts, then the watchlist, then the actions.
Args:
alerts: The alert log, newest first.
watched: The watchlist by canonical id.
new_node_alerts: Whether the mesh-wide new-node rule is on.
type_of: Maps a watch key to a node type, for entries starred before types
were stored.
key_of: Maps an alert's node label back to a key, for its hue; layered here
with the watchlist's own names so a starred node's alerts colour even
when the device (and its contact table) is offline.
"""
watched_keys = {entry.name.casefold(): entry.key for entry in watched.values()}
def label_key(label: str) -> Optional[str]:
return key_of(label) or watched_keys.get(label.casefold())
items: list = [section_heading("Alerts")]
if not alerts:
items.append(Separator(" nothing yet — tripped rules land here"))
for alert in alerts[:_SHOWN_ALERTS]:
items.append(Choice(_alert_row(alert), ("ack", alert.ident)))
items.append(Choice(_alert_row(alert, label_key), ("ack", alert.ident)))
unacked = sum(1 for a in alerts if not a.acked)
acked = len(alerts) - unacked
if unacked:
@@ -141,7 +179,7 @@ def _menu_items(
if not watched:
items.append(Separator(" none starred yet — silence and SNR rules need one"))
for key in sorted(watched, key=lambda k: watched[k].name.casefold()):
items.append(Choice(_watched_row(watched[key]), ("node", key)))
items.append(Choice(_watched_row(watched[key], type_of), ("node", key)))
items.append(Choice("⭐ Watch a node…", _WATCH))
items.append(Separator(" "))
@@ -157,8 +195,13 @@ def _menu_items(
return items
def _alert_row(alert: Alert) -> Text:
"""One alert as a row: marker, age, kind, node, and the message."""
def _alert_row(alert: Alert, key_of: Callable[[str], Optional[str]]) -> Text:
"""One alert as a row: marker, age, kind, node, and the message.
An unacked alert's node label takes its key-derived hue (resolved through
``key_of``, muted when no key is known); an acked row's label recedes to muted
with the rest of its history.
"""
row = Text()
if alert.acked:
row.append("○ ", style="muted")
@@ -167,16 +210,26 @@ def _alert_row(alert: Alert) -> Text:
age = _format_age(_age_seconds(alert.when))
row.append(f"{age:>5} ", style="muted")
row.append(alert.kind.ljust(10), style=_KIND_STYLES.get(alert.kind, "brand"))
row.append(alert.label, style="muted" if alert.acked else None)
if alert.acked:
row.append(alert.label, style="muted")
else:
row.append(alert.label, style=name_style(alert.label, key_of(alert.label)))
row.append(f" — {alert.message}", style="muted")
return row
def _watched_row(entry: WatchedNode) -> Text:
"""One watched node as a row: name, its rules, and when it was last heard."""
def _watched_row(entry: WatchedNode, type_of: Callable[[str], Optional[int]]) -> Text:
"""One watched node as a row: type glyph, hued name, its rules, and last heard.
The leading glyph is the node's shared type marker (``▲`` repeater, ``●`` node, …)
in its own type colour — silence is signalled by the trailing ``⚠ silent``, not the
glyph — and the name takes its key-derived hue (the entry's 12-hex watch key).
"""
node_type = entry.node_type if entry.node_type is not None else type_of(entry.key)
glyph, glyph_style = _NODE_GLYPHS.get(node_type, _DEFAULT_GLYPH)
row = Text()
row.append("▲ ", style="err" if entry.silent_since is not None else "brand")
row.append(entry.name)
row.append(f"{glyph} ", style=glyph_style)
row.append(entry.name, style=name_style(entry.name, entry.key))
silence = "off" if entry.silence_hours == OFF else f"{entry.silence_hours} h"
row.append(f" silence {silence}", style="muted")
row.append(" · SNR watch " + ("on" if entry.snr_watch else "off"), style="muted")
@@ -214,9 +267,13 @@ async def _pick_node(ctx: "AppContext", contacts: list[Contact]) -> None:
items: list = []
for key, contact in sorted(candidates, key=recency):
glyph, glyph_style = _NODE_GLYPHS.get(contact.node_type, _DEFAULT_GLYPH)
row = Text()
row.append("▲ " if contact.node_type == NODE_TYPE_REPEATER else "● ", style="brand")
row.append(contact.name)
row.append(f"{glyph} ", style=glyph_style)
row.append(
contact.name,
style=name_style(contact.name, contact.public_key or contact.key_prefix),
)
row.append(f" heard {_format_age(_age_seconds(contact.last_seen))}", style="muted")
items.append(Choice(row, (key, contact)))
picked = await session.select(
@@ -227,7 +284,9 @@ async def _pick_node(ctx: "AppContext", contacts: list[Contact]) -> None:
if picked is None:
return
key, contact = picked
store.watch(key, contact.name, last_seen=contact.last_seen)
store.watch(
key, contact.name, last_seen=contact.last_seen, node_type=contact.node_type
)
async def _node_rules(ctx: "AppContext", key: str) -> None:
+69
View File
@@ -1798,3 +1798,72 @@ async def test_session_busy_overlay_shows_between_screens_and_clears() -> None:
assert seen["rendered"] is True
assert seen["hidden_over_screen"] is True
assert session._overlay is None # cleared on exit
# --- horizontal scroll (opt-in) -------------------------------------------------------
def _hscroll_screen(width_of_rows: int = 60) -> "SelectScreen":
from meshterm.ui.tui.select import Choice, SelectScreen, Separator
return SelectScreen(
"long",
[
Separator("HEAD-" + "h" * width_of_rows),
Choice("row-one-" + "x" * width_of_rows + "-tail", 1),
Choice("short", 2),
],
hscroll=True,
filterable=True,
)
def _row_plains(screen, width: int) -> list[str]:
import re
return [re.sub(r"\x1b\[[0-9;]*m", "", ln) for ln in screen.render_body(width)]
def test_select_hscroll_shifts_rows_and_pins_the_pointer() -> None:
"""→ slides row content left under the pinned pointer; ← slides it back."""
screen = _hscroll_screen()
before = _row_plains(screen, 40)
assert any("row-one-" in ln for ln in before)
screen.handle("right")
shifted = _row_plains(screen, 40)
assert not any("row-one-" in ln for ln in shifted) # the head scrolled off
assert any(ln.startswith("❯ ") for ln in shifted) # the pointer stays pinned
assert any("HEAD-" not in ln and "hhh" in ln for ln in shifted) # headers slide too
screen.handle("left")
assert any("row-one-" in ln for ln in _row_plains(screen, 40))
def test_select_hscroll_clamps_at_the_widest_row() -> None:
"""→ stops once the longest row's tail is in view instead of scrolling to blank."""
screen = _hscroll_screen()
for _ in range(50):
screen.handle("right")
plains = _row_plains(screen, 40)
assert any("-tail" in ln for ln in plains) # the longest row's end is visible
assert screen._hshift <= 60 + len("row-one--tail") + 2
def test_select_hscroll_survives_moves_and_resets_on_filter() -> None:
"""The shift holds across ↑↓ (a chosen column) and resets when the filter edits."""
screen = _hscroll_screen()
screen.handle("right")
screen.handle("down")
assert screen._hshift > 0
screen.handle("text", "r")
assert screen._hshift == 0
def test_select_without_hscroll_ignores_left_right() -> None:
"""The flag defaults off: ←/→ stay inert and rows render exactly as before."""
from meshterm.ui.tui.select import Choice, SelectScreen
screen = SelectScreen("plain", [Choice("row", 1)])
before = screen.render_body(40)
screen.handle("right")
screen.handle("left")
assert screen.render_body(40) == before and screen._hshift == 0
+67
View File
@@ -185,3 +185,70 @@ def test_new_node_rule_can_be_switched_off(tmp_path: Path) -> None:
service.note(_obs(node="c9" * 6))
assert store.alerts() == []
assert store.known_contains("c9" * 6)
# --- the screen's rows ---------------------------------------------------------------
def test_store_round_trips_node_type(tmp_path: Path) -> None:
"""A starred node's advertised type persists; legacy entries load as None."""
path = tmp_path / "watch.json"
store = WatchStore(path)
store.watch("aa" * 6, "Roof", node_type=2)
store.watch("bb" * 6, "Old-style") # no type, like a pre-field entry
reloaded = WatchStore(path)
assert reloaded.watched()["aa" * 6].node_type == 2
assert reloaded.watched()["bb" * 6].node_type is None
def test_watched_row_type_glyph_and_hued_name(tmp_path: Path) -> None:
"""The watchlist row leads with the shared type glyph (own colour) and hues the
name by the entry's key; silence still reads from the trailing tail."""
from meshterm.core.watch_store import WatchedNode
from meshterm.ui.theme import name_style
from meshterm.ui.watchtower_screen import _watched_row
from meshterm.ui.widgets import _NODE_GLYPHS
entry = WatchedNode(key="a1" * 6, name="Roof", node_type=2, last_heard=utcnow())
row = _watched_row(entry, lambda key: None)
glyph, glyph_style = _NODE_GLYPHS[2]
assert row.plain.startswith(f"{glyph} Roof")
assert any(s.style == glyph_style and s.start == 0 for s in row.spans)
name_at = row.plain.index("Roof")
assert any(
s.style == name_style("Roof", "a1" * 6) and s.start <= name_at < s.end
for s in row.spans
)
# A legacy entry (no stored type) falls back to the contact table's resolver.
legacy = WatchedNode(key="a1" * 6, name="Roof")
resolved = _watched_row(legacy, lambda key: 2)
assert resolved.plain.startswith(f"{glyph} ")
# Silence is signalled by the ⚠ tail, never the glyph colour.
quiet = WatchedNode(key="a1" * 6, name="Roof", node_type=2, silent_since=utcnow())
assert "⚠ silent" in _watched_row(quiet, lambda key: None).plain
def test_alert_row_hues_the_label_by_resolved_key(tmp_path: Path) -> None:
"""An unacked alert's label takes its key-derived hue; acked recedes to muted."""
from meshterm.core.watch_store import Alert
from meshterm.ui.theme import name_style
from meshterm.ui.watchtower_screen import _alert_row
key_of = lambda label: "d4" * 6 if label == "Roof" else None
alert = Alert(ident=1, when=utcnow(), kind="silence", label="Roof", message="quiet")
row = _alert_row(alert, key_of)
at = row.plain.index("Roof")
assert any(
s.style == name_style("Roof", "d4" * 6) and s.start <= at < s.end
for s in row.spans
)
acked = Alert(
ident=2, when=utcnow(), kind="silence", label="Roof", message="quiet", acked=True
)
acked_row = _alert_row(acked, key_of)
at = acked_row.plain.index("Roof")
assert any(s.style == "muted" and s.start <= at < s.end for s in acked_row.spans)