Editors keep their place too: rows change, the reader doesn't move

Six lists rebuilt themselves as a whole new screen every round, because their
content is data: an editor's rows carry a staged `current → new` value, its
title counts what is staged, the outbox loses the message it just sent, the
watchtower's log rewrites the row you acknowledged. Each approximated the cost
with `default=cursor`, which recovers only the cursor, and only while the row it
names still exists — the typed filter went every time.

SelectScreen.replace_items swaps the rows (and optionally the title) in place
instead. The place is kept by value, so the highlight lands back on its row
wherever that row moved to, and falls back to the same position in the list when
the row is gone entirely — which is what you want after deleting the row you
were sitting on. The filter rides along.

So the config editor, device actions, the channel manager, the courier outbox,
the watchtower and the repeater-admin editor all hold one screen for the whole
visit now, refreshed after each action. The courier's ticker is started once for
the visit rather than per round, and folds a flow's effect in immediately rather
than waiting up to a second for the next tick.

The admin node picker gains a `stay` form. Repeater admin used to draw a second,
identical SelectScreen as a static backdrop so the password prompt had something
behind it, then drop the list before the session; the real list stays up through
both now — so cancelling the password lands back on the node list rather than
bowing out of the flow, and leaving a node's admin session lands there too.
Administering two repeaters in a row is an Esc and a pick.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5 committed 2026-08-30 13:38:26 -04:00
1 parent a409fd4e9b
commit f2a49c8e2d
11 files changed
+443 -220

No files matched your search

+74 -3
View File
@@ -10,7 +10,8 @@ key is offerable, since holding a password is a fact about the *user*, not the n
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from contextlib import asynccontextmanager
from typing import TYPE_CHECKING, Any, AsyncIterator, Optional
from rich.text import Text
@@ -94,6 +95,10 @@ async def pick_admin_node(
) -> Optional[Contact]:
"""Pick a remote node to administer, credentialed and infrastructure nodes first.
The one-shot form: the list comes down as soon as a node is picked. A caller whose next
step belongs *over* the list — the admin login, which asks about the node just picked —
wants :func:`admin_node_visit` instead.
Args:
ctx: Shared application context (for the UI surface and the admin store).
contacts: The device's known contacts.
@@ -105,11 +110,77 @@ async def pick_admin_node(
"""
items, candidates = admin_picker_rows(ctx, contacts)
if not candidates:
ctx.ui.note("[err]no contacts with a key — receive an advert first[/err]")
await ctx.ui.present(title=title)
await _note_nothing_to_pick(ctx, title)
return None
choice = await ctx.ui.select(title, items, prompt=prompt, wrap=False)
return _resolve(candidates, choice)
@asynccontextmanager
async def admin_node_visit(
ctx: "AppContext",
contacts: list[Contact],
*,
title: str,
prompt: str,
) -> "AsyncIterator[Optional[_AdminNodePicker]]":
"""Keep the node picker pushed for a whole visit, yielding a picker to draw from.
The list stays on the stack for the duration of the block, so everything the caller does
with a picked node — the password prompt, a rejection, the admin session itself — nests
*above* the very list the pick came from, with the picked node still highlighted, instead
of floating over a blank frame or being drawn again as a lookalike backdrop. Esc from any
of it is one pop back onto the list.
Yields ``None`` when there is nothing to pick (the caller has already been told).
Args:
ctx: Shared application context (for the UI surface and the admin store).
contacts: The device's known contacts.
title: The select screen's heading (names the calling feature).
prompt: One line above the list saying what the pick is for.
"""
from .surface import TuiUi
from .tui import SelectScreen
items, candidates = admin_picker_rows(ctx, contacts)
if not candidates or not isinstance(ctx.ui, TuiUi):
if not candidates:
await _note_nothing_to_pick(ctx, title)
yield None
return
screen = SelectScreen(title, items, prompt=prompt, wrap=False)
async with ctx.ui.session.stay(screen) as visit:
yield _AdminNodePicker(visit, candidates)
class _AdminNodePicker:
"""The visited node list: :meth:`pick` is one round of it, resolved to a contact."""
__slots__ = ("_visit", "_candidates")
def __init__(self, visit: Any, candidates: list[Contact]) -> None:
"""Bind the picker to the list's visit and the contacts its rows stand for."""
self._visit = visit
self._candidates = candidates
async def pick(self) -> Optional[Contact]:
"""Await one pick: the chosen contact, or ``None`` on Esc."""
from .tui.screen import CANCEL
choice = await self._visit.result()
return _resolve(self._candidates, None if choice is CANCEL else choice)
async def _note_nothing_to_pick(ctx: "AppContext", title: str) -> None:
"""Say there is no offerable node and show it — no list is opened at all."""
ctx.ui.note("[err]no contacts with a key — receive an advert first[/err]")
await ctx.ui.present(title=title)
def _resolve(candidates: list[Contact], choice: Any) -> Optional[Contact]:
"""The contact a picked row's name stands for, or ``None`` when nothing was picked."""
if choice is None:
return None
return next((c for c in candidates if c.name == choice), None)
+68 -45
View File
@@ -165,54 +165,77 @@ async def manage_channels(ctx: "AppContext") -> int:
changes = 0
highlight: Optional[object] = None
while True:
# Through the session cache — the slot probe walks every index and is one of the
# slowest reads on a screen open, so a screen opened after this one (or this one after
# another) reuses the one probe. A local copy so the mutation helpers below can work a
# working list; each mutation invalidates the cache (see below), so the next loop
# re-probes the fresh layout rather than trusting the stale copy.
slots: list = []
async def reload() -> tuple[str, list]:
"""Re-probe the slot layout and rebuild the list's title and rows.
Through the session cache — the slot probe walks every index and is one of the
slowest reads on a screen open, so a screen opened after this one (or this one after
another) reuses the one probe. A local copy so the mutation helpers below can work a
working list; each mutation invalidates the cache (see ``handle``), so this re-probes
the fresh layout rather than trusting the stale copy.
"""
nonlocal slots
slots = list(await ctx.devstate.channel_slots())
title, items = _menu_items(ctx, slots, capacity, stats)
return _menu_items(ctx, slots, capacity, stats)
async def handle(choice: object) -> bool:
"""Dispatch one menu choice (over the still-pushed list); ``False`` exits."""
nonlocal changes, highlight
if choice is None: # Esc
return False
highlight = choice
before = changes
if choice == _CREATE:
changes += await _create_private(ctx, device, slots, capacity)
elif choice == _DEFAULT_PUBLIC:
changes += await _add_default_public(ctx, device, slots, capacity)
elif choice == _PUBLIC:
changes += await _add_public(ctx, device, slots, capacity)
elif choice == _JOIN:
changes += await _join_with_key(ctx, device, slots, capacity)
elif choice == _IMPORT:
changes += await _import_link(ctx, device, slots, capacity)
elif choice == _REORDER:
changes += await _reorder_channels(ctx, device, slots)
else: # an existing slot index
slot = next((s for s in slots if s.idx == choice), None)
if slot is not None:
changes += await _channel_detail(ctx, device, slot, stats)
if changes > before:
# A slot's occupant changed (created, re-keyed, cleared, or moved). Drop the
# session cache's channel list so the dashboard (and anything else reading it)
# re-reads the new layout instead of a stale copy.
ctx.devstate.invalidate_channels()
# Inbound messages carry only a slot index, which the chat service maps to a
# channel identity through a cache keyed by slot; refresh it now so a message
# on a reused/re-keyed slot is filed under the channel that's actually there
# and not the one that used to be — otherwise its transcript surfaces in the
# wrong chat.
await _refresh_chat_channels(ctx)
return True
async def handle(choice: object) -> bool:
"""Dispatch one menu choice (over the still-pushed list); ``False`` exits."""
nonlocal changes, highlight
if choice is None: # Esc
return False
highlight = choice
before = changes
if choice == _CREATE:
changes += await _create_private(ctx, device, slots, capacity)
elif choice == _DEFAULT_PUBLIC:
changes += await _add_default_public(ctx, device, slots, capacity)
elif choice == _PUBLIC:
changes += await _add_public(ctx, device, slots, capacity)
elif choice == _JOIN:
changes += await _join_with_key(ctx, device, slots, capacity)
elif choice == _IMPORT:
changes += await _import_link(ctx, device, slots, capacity)
elif choice == _REORDER:
changes += await _reorder_channels(ctx, device, slots)
else: # an existing slot index
slot = next((s for s in slots if s.idx == choice), None)
if slot is not None:
changes += await _channel_detail(ctx, device, slot, stats)
if changes > before:
# A slot's occupant changed (created, re-keyed, cleared, or moved). Drop the
# session cache's channel list so the dashboard (and anything else reading it)
# re-reads the new layout instead of a stale copy.
ctx.devstate.invalidate_channels()
# Inbound messages carry only a slot index, which the chat service maps to a
# channel identity through a cache keyed by slot; refresh it now so a message
# on a reused/re-keyed slot is filed under the channel that's actually there
# and not the one that used to be — otherwise its transcript surfaces in the
# wrong chat.
await _refresh_chat_channels(ctx)
return True
if not await _menu_round(ctx, title, items, default=highlight, handle=handle):
return changes
# unreachable
# The list stays pushed for the whole visit: every sub-flow — creating a channel,
# importing a link, a slot's detail page — floats over it, and the rows are re-probed and
# swapped in place afterwards, so the highlight (and any typed filter) survives a layout
# that changed under it. A surface with no session — the plain CLI, scripted tests — has
# no stack to stay on and runs the same dispatcher a round at a time.
title, items = await reload()
session = getattr(ctx.ui, "session", None)
if session is None:
while True:
if not await _menu_round(ctx, title, items, default=highlight, handle=handle):
return changes
title, items = await reload()
menu = SelectScreen(title, items, wrap=False)
async with session.stay(menu) as visit:
while True:
choice = await visit.result()
if not await handle(None if choice is CANCEL else choice):
return changes
title, items = await reload()
menu.replace_items(items, title=title)
async def _menu_round(
+25 -33
View File
@@ -147,33 +147,28 @@ async def edit_config(ctx: "AppContext") -> Optional[list[tuple]]:
session = getattr(ctx.ui, "session", None)
if session is None: # pragma: no cover - guarded by the menu-only caller
raise RuntimeError("the config editor is only available in the menu")
loop = asyncio.get_running_loop()
pending: dict[str, Any] = {} # setting key -> staged new value
extra_ops: list[tuple] = [] # staged custom-variable ops, in order
cursor: Any = None # the row to re-highlight, so the menu reopens where you left it
while True:
staged = len(pending) + len(extra_ops)
title, items = _menu_items(snapshot, pending, staged, policy)
menu = SelectScreen(
title, items, default=cursor, wrap=False,
footer_hint="↑↓ move · type to filter · Enter select · Esc back",
)
menu.future = loop.create_future()
session.push(menu)
# Dispatch the choice while the menu is still pushed, so a sub-prompt floats over
# it; the menu is always popped in the finally, even on an early return.
try:
choice = await menu.future
# The editor's rows *are* its data — each carries its staged ``current → new`` value and
# the title counts what is staged — so they are refreshed in place after every round
# (``replace_items``) rather than rebuilt as a new screen. One screen for the whole
# session means the typed filter survives editing a setting, not just the cursor.
title, items = _menu_items(snapshot, pending, 0, policy)
menu = SelectScreen(
title, items, wrap=False,
footer_hint="↑↓ move · type to filter · Enter select · Esc back",
)
async with session.stay(menu) as visit:
while True:
staged = len(pending) + len(extra_ops)
choice = await visit.result()
if choice is CANCEL: # Esc at the menu
choice = _CANCEL
if choice not in (None, _CANCEL):
cursor = choice
if choice in (None, _CANCEL):
if staged and not await confirm_discard(ctx, staged, verb="applying"):
continue # keep editing — the same menu is rebuilt next loop
continue # keep editing — the same menu, the same place in it
return None
if choice == _APPLY:
ops: list[tuple] = []
@@ -194,8 +189,10 @@ async def edit_config(ctx: "AppContext") -> Optional[list[tuple]]:
await _stage_custom_var(ctx, custom, extra_ops)
else: # a setting key
await _stage_setting(ctx, choice, snapshot, pending)
finally:
session.pop(menu)
title, items = _menu_items(
snapshot, pending, len(pending) + len(extra_ops), policy
)
menu.replace_items(items, title=title)
# --- rendering ---------------------------------------------------------------
@@ -679,18 +676,15 @@ async def device_actions(ctx: "AppContext") -> None:
session = getattr(ctx.ui, "session", None)
if session is None: # pragma: no cover - guarded by the menu-only caller
raise RuntimeError("device actions are only available in the menu")
loop = asyncio.get_running_loop()
cursor: Any = None # the row to re-highlight, so the menu reopens where you left it
while True:
menu = SelectScreen("Device actions", _action_items(), default=cursor, wrap=False)
menu.future = loop.create_future()
session.push(menu)
try:
choice = await menu.future
# One screen for the whole visit: the action rows are fixed, so nothing here needs
# rebuilding — and the cursor and any typed filter simply stay where the reader left them
# while each action's prompts float over the list.
menu = SelectScreen("Device actions", _action_items(), wrap=False)
async with session.stay(menu) as visit:
while True:
choice = await visit.result()
if choice is CANCEL or choice is None: # Esc
return
cursor = choice
if choice == _SYNC_CLOCK:
await _sync_clock(ctx, device, snapshot)
elif choice == _BACKUP:
@@ -707,8 +701,6 @@ async def device_actions(ctx: "AppContext") -> None:
elif choice == _RESET:
if await _factory_reset(ctx, device, snapshot):
snapshot = await build_snapshot(device)
finally:
session.pop(menu)
def _action_items() -> list:
+36 -33
View File
@@ -114,42 +114,46 @@ async def open_courier(ctx: "AppContext") -> Optional[dict[str, Any]]:
contacts = []
store = ctx.courier_store
loop = asyncio.get_running_loop()
cursor: Any = None
while True:
menu = CourierOutboxScreen(ctx, default=cursor)
menu.future = loop.create_future()
session.push(menu)
# One screen for the whole visit, refreshed in place: the outbox already knows how to
# recompose its sections around the highlight (:meth:`CourierOutboxScreen.refresh`), which
# is what the once-a-second ticker calls while the list is open. Driving it through a
# visit means every sub-flow — queueing a message, an entry's actions, the clear confirm —
# floats over the list and lands back on the row it was opened from, and the ticker is
# started once rather than per round.
menu = CourierOutboxScreen(ctx)
async def tick(screen: "CourierOutboxScreen" = menu) -> None:
"""Fold store changes in and repaint, once a second, while the list is open."""
while True:
await asyncio.sleep(_REFRESH_S)
screen.refresh()
session.invalidate()
async def tick() -> None:
"""Fold store changes in and repaint, once a second, while the list is open."""
while True:
await asyncio.sleep(_REFRESH_S)
menu.refresh()
session.invalidate()
async with session.stay(menu) as visit:
ticker = asyncio.ensure_future(tick())
try:
choice = await menu.future
if choice in (None, CANCEL):
return {"queued": store.pending_count()}
cursor = choice
if choice == _QUEUE:
await _queue_flow(ctx, contacts)
elif choice == _CLEAR:
done = store.done_count()
if await ctx.ui.dialog(
f"Clear {done} finished "
f"{'entry' if done == 1 else 'entries'} from the history?",
[("Cancel", False), ("Clear", True)],
title="Clear finished",
default=1,
destructive=True,
):
store.clear_done()
cursor = None # the row itself disappears
elif isinstance(choice, tuple) and choice[0] == "msg":
await _entry_actions(ctx, int(choice[1]))
while True:
choice = await visit.result()
if choice in (None, CANCEL):
return {"queued": store.pending_count()}
if choice == _QUEUE:
await _queue_flow(ctx, contacts)
elif choice == _CLEAR:
done = store.done_count()
if await ctx.ui.dialog(
f"Clear {done} finished "
f"{'entry' if done == 1 else 'entries'} from the history?",
[("Cancel", False), ("Clear", True)],
title="Clear finished",
default=1,
destructive=True,
):
store.clear_done()
elif isinstance(choice, tuple) and choice[0] == "msg":
await _entry_actions(ctx, int(choice[1]))
# Fold the flow's effect in straight away rather than waiting for a tick,
# so the list the reader lands back on already shows what they just did.
menu.refresh()
finally:
ticker.cancel()
try:
@@ -158,7 +162,6 @@ async def open_courier(ctx: "AppContext") -> Optional[dict[str, Any]]:
pass
except Exception: # noqa: BLE001 - teardown must never surface a tick hiccup
pass
session.pop(menu)
# --- the menu ---------------------------------------------------------------------------
+48 -39
View File
@@ -71,22 +71,25 @@ _CANCEL = "__cancel__"
async def open_repeater_admin(ctx: "AppContext") -> Optional[dict[str, Any]]:
"""Run the repeater-admin flow: pick a node, log in, and administer it.
The picker stays up for the whole flow, so leaving a node's admin session lands back on
the list rather than on the main menu — administering two repeaters in a row is one Esc
and a pick, not a round trip through the menu.
Args:
ctx: The shared application context (must be running the interactive TUI surface).
Returns:
A summary of what happened (for the tool's log), or ``None`` on cancel.
A summary of the last node administered (for the tool's log), or ``None`` if the
reader left the picker without ever getting into a session.
Raises:
RuntimeError: If called outside the interactive menu (no full-screen session).
"""
from .admin_picker import admin_picker_rows, pick_admin_node
from .admin_picker import admin_node_visit
from .surface import TuiUi
from .tui import SelectScreen
if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller
raise RuntimeError("repeater admin is only available in the menu")
session = ctx.ui.session
device = await ctx.device()
# Through the session cache — opening this screen shouldn't re-read the (slow) contacts
@@ -94,24 +97,27 @@ async def open_repeater_admin(ctx: "AppContext") -> Optional[dict[str, Any]]:
# :class:`~meshterm.services.device_state.DeviceState`); the device handle below is still
# needed for the admin login and the CLI session that follow.
contacts = await ctx.devstate.contacts()
pick_title = "Repeater admin — node to manage"
pick_prompt = "The remote node to set up (you need its admin password):"
node = await pick_admin_node(ctx, contacts, title=pick_title, prompt=pick_prompt)
if node is None:
return None
# The picker was popped when it returned. Redraw it as a static backdrop and keep it
# pushed across the login, so the password prompt (and any rejection) floats over the
# node list the pick came from — the picked node still highlighted — rather than over a
# blank frame. The backdrop takes no input; the dialog above it owns the keyboard.
items, _candidates = admin_picker_rows(ctx, contacts)
backdrop = SelectScreen(pick_title, items, prompt=pick_prompt, default=node.name, wrap=False)
session.push(backdrop)
try:
if not await _login(ctx, device, node):
# The node list stays pushed for the whole flow, so the password prompt (and any
# rejection) floats over the very list the pick came from, and the admin session opens
# above it: Esc out of the session lands back on the list, ready to manage another node,
# and Esc again leaves. It used to draw a second, identical SelectScreen as a static
# backdrop for the login and then drop the list entirely before the session.
async with admin_node_visit(
ctx,
contacts,
title="Repeater admin — node to manage",
prompt="The remote node to set up (you need its admin password):",
) as picker:
if picker is None: # nothing offerable; the reader has been told
return None
finally:
session.pop(backdrop)
return await _admin_session(ctx, device, node)
summary: Optional[dict[str, Any]] = None
while True:
node = await picker.pick()
if node is None:
return summary
if not await _login(ctx, device, node):
continue
summary = await _admin_session(ctx, device, node)
async def _login(ctx: "AppContext", device: "Device", node: Contact) -> bool:
@@ -169,31 +175,31 @@ async def _login(ctx: "AppContext", device: "Device", node: Contact) -> bool:
async def _admin_session(
ctx: "AppContext", device: "Device", node: Contact
) -> dict[str, Any]:
"""Run the editor loop for one logged-in node (the persistent-backdrop pattern)."""
"""Run the editor loop for one logged-in node.
One screen for the whole session, its rows refreshed in place after every action: they
carry the cache's ``current → new`` values and their ages, and the title counts what is
staged, so the content moves under a highlight that stays where the reader put it —
typed filter included. Every sub-prompt floats over it, and Esc leaves the node.
"""
from .tui import CANCEL, SelectScreen
session = ctx.ui.session
loop = asyncio.get_running_loop()
pending: dict[str, str] = {} # setting key -> staged new value
applied = 0
cursor: Any = None # the row to re-highlight, so the menu reopens where you left it
while True:
cache = ctx.remote_store.settings(node)
title, items = _menu_items(node, cache, pending)
menu = SelectScreen(
title, items, default=cursor, wrap=False,
footer_hint="↑↓ move · type to filter · Enter select · Esc back",
)
menu.future = loop.create_future()
session.push(menu)
try:
choice = await menu.future
cache = ctx.remote_store.settings(node)
title, items = _menu_items(node, cache, pending)
menu = SelectScreen(
title, items, wrap=False,
footer_hint="↑↓ move · type to filter · Enter select · Esc back",
)
async with session.stay(menu) as visit:
while True:
choice = await visit.result()
if choice is CANCEL:
choice = _CANCEL
if choice not in (None, _CANCEL):
cursor = choice
if choice in (None, _CANCEL):
if pending and not await confirm_discard(ctx, len(pending), verb="sending"):
@@ -231,8 +237,11 @@ async def _admin_session(
)
else: # a setting key
await _stage_setting(ctx, str(choice), cache, pending)
finally:
session.pop(menu)
# A read or an apply rewrites the cache the rows are drawn from; re-read it so
# the values and their ages are the ones the action just produced.
cache = ctx.remote_store.settings(node)
title, items = _menu_items(node, cache, pending)
menu.replace_items(items, title=title)
# --- the menu ------------------------------------------------------------------------
+34 -23
View File
@@ -1330,29 +1330,40 @@ async def open_timemachine(ctx: "AppContext") -> None:
type_of=type_of,
resolve_key=resolve_key,
)
result = await session.run_screen(picker)
picked = None if result is CANCEL else result
if picked is None:
return
if picked == SELF:
label = self_name or "you"
build = lambda window, width: _self_sections(ctx, window, width) # noqa: E731
elif picked == MESH:
label = "the whole mesh"
build = ( # noqa: E731
lambda window, width, _pb=prefix_bytes: _mesh_sections(
ctx, window, width, _pb, resolve, resolve_key
)
)
else:
node_id, label = picked
build = ( # noqa: E731 - a tiny binding closure reads better than a def here
lambda window, width, _id=node_id, _lb=label: _node_sections(
ctx, _id, _lb, window, width
)
)
screen = TimeMachineScreen(session=session, label=label, build=build)
await session.run_screen(screen)
# The picker stays pushed for the whole visit, so a subject page nests above it and
# Esc lands back on the row it was opened from — cursor, sort and filter intact. The
# recorder keeps listening the whole time, though, so the subjects it knows can grow
# while a page is open; the list is rebuilt (and the place lost) only when it has.
subjects = {node.node for node, _ in listed}
async with session.stay(picker) as visit:
while True:
result = await visit.result()
picked = None if result is CANCEL else result
if picked is None:
return
if picked == SELF:
label = self_name or "you"
build = lambda window, width: _self_sections( # noqa: E731
ctx, window, width
)
elif picked == MESH:
label = "the whole mesh"
build = ( # noqa: E731
lambda window, width, _pb=prefix_bytes: _mesh_sections(
ctx, window, width, _pb, resolve, resolve_key
)
)
else:
node_id, label = picked
build = ( # noqa: E731 - a tiny binding closure beats a def here
lambda window, width, _id=node_id, _lb=label: _node_sections(
ctx, _id, _lb, window, width
)
)
screen = TimeMachineScreen(session=session, label=label, build=build)
await session.run_screen(screen)
if {n.node for n in ctx.repo.heard_nodes() if n.node} != subjects:
break # the mesh spoke while the page was open; relist
async def open_timemachine_node(ctx: "AppContext", node_id: str, label: str) -> None:
+36
View File
@@ -343,6 +343,42 @@ class SelectScreen(Screen):
self._index = i
break
def replace_items(self, items: list, *, title: Optional[str] = None) -> None:
"""Swap the list's rows (and optionally its title) in place, keeping the reader's place.
The counterpart to :meth:`~meshterm.ui.tui.session.TuiSession.stay` for a list whose
*content* is data: an editor's rows carrying a staged ``current → new`` value, a
title counting what is staged, a queue that just lost the message it sent. Those
lists used to be rebuilt as a whole new screen every round, which threw away the
typed filter and left the cursor to be approximated by a ``default=`` restore.
The place is kept by *value*, not by index: the highlight lands back on the row it
was on wherever that row moved to, and falls back to the same position in the list
(clamped) when the row is gone entirely — which is what a reader expects after
deleting the row they were sitting on. The filter and the horizontal shift ride
along; the shift resets when the highlighted row changes, exactly as it does when
the highlight is moved by hand.
Args:
items: The new rows, in display order.
title: A new heading, or ``None`` to keep the current one.
"""
current = self._current_choice()
was = current.value if current is not None else None
position = self._index
self._items = items
self._hscroll = self._hscroll or any(
getattr(item, "hscroll_from", 0) > 0 for item in items
)
if title is not None:
self.title = title
selectable = [it for it in self._rows() if isinstance(it, Choice)]
index = next((i for i, c in enumerate(selectable) if c.value == was), None)
if index is None:
index = max(0, min(position, len(selectable) - 1))
self._hshift = 0 # a different row is highlighted now
self._index = index
# --- filtering -----------------------------------------------------------
def _rows(self) -> list:
+30 -29
View File
@@ -92,12 +92,14 @@ async def open_watchtower(ctx: "AppContext") -> Optional[dict[str, Any]]:
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:
# An alert's node type, by its label — the contact table's advertised type wins
# (freshest), a watched entry's stored type backfills, so an alert's name gets its
# glyph even for a node no longer in the device's contacts.
def rows() -> list:
"""The current alert log and watch list, as menu rows.
An alert's node type comes by its label — the contact table's advertised type wins
(freshest), a watched entry's stored type backfills — so an alert's name gets its
glyph even for a node no longer in the device's contacts.
"""
type_by_name: dict[str, int] = {
entry.name.casefold(): entry.node_type
for entry in store.watched().values()
@@ -106,7 +108,7 @@ async def open_watchtower(ctx: "AppContext") -> Optional[dict[str, Any]]:
type_by_name.update(
{c.name.casefold(): c.node_type for c in contacts if c.node_type is not None}
)
items = _menu_items(
return _menu_items(
store.alerts(),
store.watched(),
store.new_node_alerts,
@@ -114,27 +116,28 @@ async def open_watchtower(ctx: "AppContext") -> Optional[dict[str, Any]]:
key_of=contact_key_of,
alert_type_of=lambda label: type_by_name.get(label.casefold()),
)
menu = SelectScreen(
"Watchtower — alerts & watched nodes",
items,
default=cursor,
wrap=False,
hscroll=True,
# ←→ scroll is surfaced by the list itself, but only while the highlighted
# alert actually overflows the width (see SelectScreen.hscroll_hint) — and it
# slides the *message* alone: each row pins its own lanes (see _alert_lanes).
# The two section headings below earn the list its ^PgUp/^PgDn jumps and their
# F1/F2 chips for free (SelectScreen.fkey_lane); the hint has no room to name
# them beside the ←→ atom, and no other grouped list spells them out either.
footer_hint="↑↓ move · Enter select/acknowledge · Esc back",
)
menu.future = loop.create_future()
session.push(menu)
try:
choice = await menu.future
# One screen for the whole visit, its rows refreshed in place after each action — every
# one of them changes the list it was chosen from (an ack rewrites its row, a star adds
# one, Clear takes several away), and the highlight rides along to wherever its row went.
menu = SelectScreen(
"Watchtower — alerts & watched nodes",
rows(),
wrap=False,
hscroll=True,
# ←→ scroll is surfaced by the list itself, but only while the highlighted
# alert actually overflows the width (see SelectScreen.hscroll_hint) — and it
# slides the *message* alone: each row pins its own lanes (see _alert_lanes).
# The two section headings below earn the list its ^PgUp/^PgDn jumps and their
# F1/F2 chips for free (SelectScreen.fkey_lane); the hint has no room to name
# them beside the ←→ atom, and no other grouped list spells them out either.
footer_hint="↑↓ move · Enter select/acknowledge · Esc back",
)
async with session.stay(menu) as visit:
while True:
choice = await visit.result()
if choice in (None, CANCEL):
return {"watched": len(store.watched()), "unacked": store.unacked_count()}
cursor = choice
if choice == _WATCH:
await _pick_node(ctx, contacts)
elif choice == _TOGGLE_NEW:
@@ -143,13 +146,11 @@ async def open_watchtower(ctx: "AppContext") -> Optional[dict[str, Any]]:
store.ack_all()
elif choice == _CLEAR:
store.clear_acked()
cursor = None # the row itself disappears
elif isinstance(choice, tuple) and choice[0] == "ack":
store.ack(int(choice[1]))
elif isinstance(choice, tuple) and choice[0] == "node":
await _node_rules(ctx, str(choice[1]))
finally:
session.pop(menu)
menu.replace_items(rows())
# --- the menu ---------------------------------------------------------------------------
+29 -4
View File
@@ -9,6 +9,7 @@ each prompt from a queue.
from __future__ import annotations
import re
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any, Optional
@@ -290,10 +291,11 @@ def test_location_picker_without_nodes_or_initial_shows_the_world() -> None:
class _FakeSession:
"""A minimal stand-in for the TUI session behind the editor's persistent menu.
The editor keeps its main menu *pushed on the session stack* (so sub-prompts float
over it as modal popups). Here, pushing the menu resolves its future straight from the
script's next ``select`` answer — the same FIFO the sub-prompts draw from — so the
modal-backdrop control flow is exercised without a real full-screen session.
The editor keeps its menu *pushed on the session stack* for the whole visit (so its
sub-prompts float over it as modal popups), driving it one round at a time through
``stay``/``Visit``. Here each round answers straight from the script's next ``select``
entry — the same FIFO the sub-prompts draw from — so the visit's control flow is
exercised without a real full-screen session.
"""
def __init__(self, ui: "_ScriptedUi") -> None:
@@ -310,6 +312,29 @@ class _FakeSession:
def pop(self, screen: Any = None) -> None:
pass
@asynccontextmanager
async def stay(self, screen: Any) -> Any:
"""Keep ``screen`` pushed and hand out a visit answering from the script."""
self.pushed.append(screen)
try:
yield _FakeVisit(self, screen)
finally:
pass
class _FakeVisit:
"""One round of a visited screen: the script's next ``select`` answer."""
def __init__(self, session: "_FakeSession", screen: Any) -> None:
self._session = session
self.screen = screen
async def result(self) -> Any:
from meshterm.ui.tui.screen import CANCEL
value = self._session.ui._answer("select")
return CANCEL if value is None else value
class _ScriptedUi:
"""A fake UI surface answering every prompt from a FIFO script.
+44
View File
@@ -119,6 +119,50 @@ async def test_a_visited_screen_is_armed_from_the_moment_it_is_pushed() -> None:
await asyncio.wait_for(session.run(main()), timeout=5)
# --- refreshing a visited list's rows ----------------------------------------
def test_replace_items_keeps_the_filter_and_follows_the_highlighted_row() -> None:
"""A list whose content is data can change under a reader without moving them.
The editors' rows carry live values and their titles count what is staged, so they have
to be rebuilt after every action. Rebuilding them as a whole new *screen* threw away the
typed filter and left the cursor to a ``default=`` restore; swapping the rows in place
keeps both, and follows the highlighted row by value wherever it moved to.
"""
screen = SelectScreen(
"Editor · nothing staged",
[Choice("alpha", "a"), Choice("beta", "b"), Choice("gamma", "g")],
)
screen.handle("text", "a") # filters to alpha / beta / gamma — all carry an "a"
screen.handle("down") # …onto beta
assert screen._current_choice().value == "b"
# beta moves to the front and its label gains a staged value; the title recounts.
screen.replace_items(
[Choice("beta → 12", "b"), Choice("alpha", "a"), Choice("gamma", "g")],
title="Editor · 1 staged",
)
assert screen.title == "Editor · 1 staged"
assert screen._filter == "a", "the typed filter survives the swap"
assert screen._current_choice().value == "b", "the highlight followed its row"
def test_replace_items_clamps_to_the_position_when_the_row_is_gone() -> None:
"""Deleting the row you were on leaves you where it was, not back at the top."""
screen = SelectScreen("Queue", [Choice(name, name) for name in ("a", "b", "c", "d")])
for _ in range(2):
screen.handle("down")
assert screen._current_choice().value == "c"
screen.replace_items([Choice(name, name) for name in ("a", "b", "d")])
assert screen._current_choice().value == "d", "the row that slid into the gap"
# And a swap that empties the list entirely must not leave a stale index behind.
screen.replace_items([])
assert screen._current_choice() is None
# --- ^W, the pop-all ---------------------------------------------------------
+19 -11
View File
@@ -217,13 +217,14 @@ def test_picker_rows_hue_each_name_by_its_own_key(tui_ctx) -> None:
async def test_login_password_floats_over_the_node_picker(tui_ctx) -> None:
"""The admin-login password prompt floats over the picker, not an erased background.
"""The admin-login password prompt floats over the picker itself, not a lookalike.
Regression: ``_login`` ran on an empty stack (the picker was popped when it returned),
so ``session.text`` pushed a *blank* base and the password box floated over an erased
frame. ``open_repeater_admin`` now redraws the node picker as a static backdrop and keeps
it pushed across the login, so the base under the floating prompt is the picker — the
picked node still highlighted — never a blank frame.
frame. That was patched by redrawing a second, identical ``SelectScreen`` as a static
backdrop; the picker now simply never leaves the stack, so the base under the prompt is
the list the pick came from — the same object, still highlighted on the row the reader
chose — and Esc out of the prompt is one pop back onto it rather than out of the flow.
"""
ctx = tui_ctx
session = ctx.ui.session
@@ -238,25 +239,32 @@ async def test_login_password_floats_over_the_node_picker(tui_ctx) -> None:
)
assert picker is not None, "the node picker never opened"
picker.resolve("Yagi-Repeater") # pick the repeater to administer
# Walk to the repeater's row and commit it, the way a reader does.
for _ in range(len(picker._items)):
current = picker._current_choice()
if current is not None and current.value == "Yagi-Repeater":
break
picker.handle("down")
picker.handle("enter")
prompt = await _step_until(
lambda: session._float_layers()[0] if session._has_float() else None
)
assert isinstance(prompt, TextScreen) # the password box floats
base = session._base_screen()
assert isinstance(base, SelectScreen) and base.title == pick_title # the picker backdrop
assert base is not picker # a fresh redraw kept as the backdrop, not the popped picker
current = base._current_choice() # the picked node stays highlighted behind the prompt
assert session._base_screen() is picker # the very list, not a redrawn stand-in
current = picker._current_choice() # still highlighted on the node being logged into
assert current is not None and current.value == "Yagi-Repeater"
prompt.resolve(CANCEL) # Esc — abandon the login
prompt.resolve(CANCEL) # Esc — abandon the login…
again = await _step_until(lambda: session.top if session.top is picker else None)
assert again is picker, "…and land back on the list, one pop, place kept"
picker.handle("escape") # Esc again leaves the flow
result = await task
finally:
if not task.done():
task.cancel()
assert result is None # cancelling the password bows the flow out
assert result is None # no node was ever administered
# --- the command-line screen -----------------------------------------------------------