Repeater admin: set up remote nodes over the mesh

A new Device management entry for administering repeaters and room
servers. The shared credentialed-first picker (extracted from TX
optimize) chooses the node, login runs on remembered passwords with a
one-time prompt otherwise (forgotten on rejection), and the editor
lands in the local device-configuration screen's exact lanes — but
speaking the node's text CLI through a new public
Device.send_remote_command, which brings the repeater-only knobs the
local editor never had: TX delay, Direct TX delay, RX delay, airtime
factor, advert intervals, flood max, repeat, guest password.

Reads cost one paced mesh round trip each, so the editor never
bulk-reads on open: values show what the last read said, age-stamped,
from a new per-node remote.json cache; Read settings refreshes them
under an abortable progress dialog and Apply sends the staged sets
the same way, folding confirmed values back into the cache and
keeping refused ones staged. Advert, clock sync, password change, and
reboot run as confirmed popups.

The Command line is a readline-style screen onto the node's raw CLI:
per-node history persisted across sessions (↑↓ recall, adjacent-dupe
suppression, capped), Tab completion over the known verbs plus every
catalog get/set spelling with ghost-text preview, one command in
flight at a time. The simulator grows a full repeater CLI so all of
it drives against --mock, and a scripted one-shot
(repeater-admin <node> <command…>) covers automation.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Fable 5 committed 2026-07-11 04:14:16 -04:00
1 parent 62585f5602
commit aef80d18bb
10 files changed
+1733 -69

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
"""The admin-node picker: choose a remote node you hold (or will enter) credentials for.
Shared by the tools that administer remote nodes over the mesh — TX optimize and the
repeater admin screen — so "pick the node to manage" reads identically everywhere.
Credentialed nodes lead the list in their own 🔑 section (those are the nodes previously
administered, the likeliest picks), repeaters and room servers follow, then everything
else; each section orders by how recently the node was heard. Any contact with a public
key is offerable, since holding a password is a fact about the *user*, not the node.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from rich.text import Text
from ..core.models import NODE_TYPE_REPEATER, NODE_TYPE_ROOM, Contact
if TYPE_CHECKING:
from ..context import AppContext
async def pick_admin_node(
ctx: "AppContext",
contacts: list[Contact],
*,
title: str,
prompt: str,
) -> Optional[Contact]:
"""Pick a remote node to administer, credentialed and infrastructure nodes first.
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.
Returns:
The chosen contact, or ``None`` if cancelled (or there is nothing to pick).
"""
from .tui import Choice, Separator
from .widgets import _DEFAULT_GLYPH, _NODE_GLYPHS
candidates = [c for c in contacts if (c.public_key or c.key_prefix).strip()]
if not candidates:
ctx.ui.note("[err]no contacts with a key — receive an advert first[/err]")
await ctx.ui.present(title=title)
return None
def row(contact: Contact) -> Choice:
glyph, style = _NODE_GLYPHS.get(contact.node_type, _DEFAULT_GLYPH)
label = Text(glyph, style=style)
label.append(f" {contact.name}")
return Choice(title=label, value=contact.name)
def recency(contact: Contact) -> float:
return -(contact.last_seen.timestamp() if contact.last_seen else 0.0)
remembered = [c for c in candidates if ctx.admin_store.get(c) is not None]
infrastructure = [
c for c in candidates
if c not in remembered and c.node_type in (NODE_TYPE_REPEATER, NODE_TYPE_ROOM)
]
others = [c for c in candidates if c not in remembered and c not in infrastructure]
items: list = []
if remembered:
items.append(Separator("── 🔑 Remembered admins ──", style="accent"))
items.extend(row(c) for c in sorted(remembered, key=recency))
if infrastructure:
items.append(Separator("── Repeaters & rooms ──", style="accent"))
items.extend(row(c) for c in sorted(infrastructure, key=recency))
if others:
items.append(Separator("── Other contacts ──", style="accent"))
items.extend(row(c) for c in sorted(others, key=recency))
items.append(Separator(" "))
items.append(Choice(title="Back", value=None))
choice = await ctx.ui.select(title, items, prompt=prompt, wrap=False)
if choice is None:
return None
return next((c for c in candidates if c.name == choice), None)
+203
View File
@@ -0,0 +1,203 @@
"""The remote command line: talk to a repeater's CLI over the mesh, readline-style.
A full-screen terminal onto a logged-in remote node (part of the repeater-admin
feature): type a command, watch it fly, read the reply in a growing transcript. Every
command is one mesh transmission, so the screen sends exactly what you commit and one
at a time — a command in flight parks the prompt until the reply lands (or times out;
repeaters answer tersely and sometimes not at all).
The input line behaves like a shell:
* **↑/↓** recall the node's command history, which persists per node (see
:class:`~meshterm.core.remote_store.RemoteStore`) so last week's incantation is one
keystroke away next session.
* **Tab** completes the current text against the known repeater commands — the fixed
verbs plus every ``get``/``set`` spelling in the settings catalog — and the best
match previews muted, ghost-text style, after the cursor.
* **Enter** sends. The transcript keeps every exchange of the session, newest at the
bottom, and the view follows the prompt as it grows.
The screen renders state and routes keys; the owning flow injects ``send`` (which owns
the radio, the history store, and the reply plumbing) and feeds replies back through
:meth:`reply` / :meth:`failed`.
"""
from __future__ import annotations
from typing import Callable, Optional
from rich.console import Group
from rich.text import Text
from ..core.remote_config import known_commands
from .tui.prompt import _LineEditor
from .tui.render import render_lines
from .tui.screen import Screen
from .tui.spinner import Spinner
#: The transcript's history depth in exchanges (the body scrolls; this caps memory).
_LOG_CAP = 400
class RemoteCliScreen(Screen):
"""A shell-like screen onto one remote node's CLI. The owner does the radio work."""
floating = False
def __init__(
self,
*,
node_label: str,
history: list[str],
send: Callable[[str], None],
session: object,
) -> None:
"""Create the command line over a node's persisted history.
Args:
node_label: The remote node's display name (title and prompt chrome).
history: The node's prior commands, oldest first (recalled with ↑).
send: Commits one command (owner-guarded; no-op while one is flying).
session: The running TUI session (for repaints).
"""
super().__init__()
self.title = f"command line · {node_label}"
self._node_label = node_label
self._send = send
self._session = session
self._editor = _LineEditor()
self._log: list[Text] = []
self._history = list(history)
self._recall: Optional[int] = None # index into history while ↑/↓ browse it
self._draft = "" # what was typed before recall began, restored on ↓ past the end
self._completions = known_commands()
self.busy = False
self._spinner = Spinner()
self._prompt_line = 0 # body index of the input line (pinned into view)
# --- owner feed ------------------------------------------------------------------
def sent(self, command: str) -> None:
"""Echo a just-sent command into the transcript and park the prompt."""
row = Text("❯ ", style="brand")
row.append(command)
self._append(row)
self._history.append(command)
self._recall = None
self.busy = True
self._spinner.reset()
self._session.invalidate()
def reply(self, text: str) -> None:
"""Land the node's reply (possibly multi-line) and free the prompt."""
for line in text.splitlines() or [""]:
self._append(Text(f" {line}"))
self.busy = False
self._session.invalidate()
def failed(self, note: str, *, error: bool = False) -> None:
"""Land a timeout/error note and free the prompt."""
self._append(Text(f" {note}", style="err" if error else "muted"))
self.busy = False
self._session.invalidate()
def tick(self) -> None:
"""Advance the in-flight spinner (driven by the owner's animation timer)."""
self._spinner.tick()
def _append(self, row: Text) -> None:
row.no_wrap = False
self._log.append(row)
del self._log[:-_LOG_CAP]
# --- input -----------------------------------------------------------------------
@property
def footer_hint(self) -> str: # type: ignore[override]
"""The footer keys, tracking whether a command is in flight."""
if self.busy:
return "waiting for the reply… · PgUp/PgDn scroll · Esc back"
return "Enter send · ↑↓ history · Tab complete · PgUp/PgDn scroll · Esc back"
def handle(self, action: str, data: str = "") -> None:
"""Edit the buffer, recall history, complete, send, scroll, or dismiss."""
if action == "enter":
command = self._editor.text.strip()
if command and not self.busy:
self._editor = _LineEditor()
self._send(command)
elif action == "up":
self._recall_step(-1)
elif action == "down":
self._recall_step(1)
elif action == "tab":
completion = self._completion()
if completion is not None:
self._editor = _LineEditor(completion)
elif action == "pageup":
self.scroll_pages(-1)
elif action in ("pagedown",):
self.scroll_pages(1)
elif action == "escape":
self.resolve(None)
elif self._editor.edit(action, data):
self._recall = None # typing leaves the history walk; the buffer is a draft
self._session.invalidate()
def _recall_step(self, direction: int) -> None:
"""Walk the history with ↑/↓, keeping the un-sent draft safe at the new end."""
if not self._history:
return
if self._recall is None:
if direction > 0:
return # nothing newer than the draft
self._draft = self._editor.text
self._recall = len(self._history) - 1
else:
self._recall += direction
if self._recall >= len(self._history):
self._recall = None
self._editor = _LineEditor(self._draft)
return
self._recall = max(0, self._recall)
self._editor = _LineEditor(self._history[self._recall])
def _completion(self) -> Optional[str]:
"""The first known command extending the current text, or ``None``."""
prefix = self._editor.text.lstrip()
if not prefix:
return None
return next((c for c in self._completions if c.startswith(prefix) and c != prefix),
None)
# --- rendering ---------------------------------------------------------------------
def render_body(self, width: int) -> list[str]:
"""Render the intro, the transcript, and the prompt with its ghost completion."""
intro = Text(
f"Talking to {self._node_label} over the mesh — every command is one "
"transmission.",
style="muted",
)
lines = render_lines(Group(intro, Text(), *self._log), width)
self._prompt_line = len(lines)
lines.extend(render_lines(self._prompt(), width))
self._scroll_total = max(1, len(lines))
return lines
def cursor_line(self) -> Optional[int]:
"""Pin the prompt into view, so the transcript follows itself as it grows."""
return self._prompt_line
def _prompt(self) -> Text:
"""The input line: spinner while waiting, else the editor and its ghost text."""
if self.busy:
line = self._spinner.text()
line.append(" waiting for the reply…", style="muted")
return line
line = Text("❯ ", style="brand")
line.append_text(self._editor.render())
completion = self._completion()
if completion is not None:
line.append(completion[len(self._editor.text.lstrip()):], style="faint")
return line
+650
View File
@@ -0,0 +1,650 @@
"""The repeater-admin screens: configure a remote node over the mesh, editor-style.
The interactive face of the ``repeater-admin`` tool. Picking a node (the shared
credentialed-first picker) and logging in (remembered passwords, the one-time prompt
otherwise) opens an editor deliberately shaped like the local device-configuration
screen — the same setting / value / description lanes, staged ``current → new`` values,
Apply — but speaking the repeater's text CLI (see :mod:`meshterm.core.remote_config`)
instead of the companion's binary protocol, which brings the repeater-only knobs the
local editor never had: TX delay, Direct TX delay, airtime factor, advert intervals.
Because every read is one paced mesh round trip, the editor never bulk-reads on open:
values show what the last read (or the last applied set) said, stamped with age, from
the per-node cache (:class:`~meshterm.core.remote_store.RemoteStore`); the *Read
settings* action refreshes them all under an abortable progress dialog, one paced
``get`` at a time. Apply sends the staged ``set`` commands the same way and folds each
confirmed value straight back into the cache.
Beyond the settings, the action rows cover the box itself — advert, clock sync, change
admin password, reboot, each behind its own floating confirmation — and the **Command
line** opens the readline-style remote CLI (:mod:`meshterm.ui.remote_cli`) for anything
the catalog doesn't spell.
"""
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Any, Optional
from rich.cells import cell_len
from rich.text import Text
from ..core.models import Contact
from ..core.remote_config import (
RemoteSetting,
parse_reply_value,
reply_is_error,
settings_by_category,
)
from .trace_screen import TracingDialog
from .tui import Choice, Separator
from .tui.spinner import Spinner
from .widgets import _age_seconds, _format_age
if TYPE_CHECKING:
from ..context import AppContext
from ..core.connection import Device
#: Seconds between spinner frames while a remote command is in flight.
_SPINNER_INTERVAL = 0.12
#: Seconds to wait for one remote reply. Repeaters answer over the mesh — multi-hop
#: routes take seconds — so this is deliberately more patient than a local command.
_REPLY_TIMEOUT_S = 10.0
# Menu action sentinels (distinct from setting keys, which are CLI parameter names).
_CLI = "__cli__"
_READ = "__read__"
_ADVERT = "__advert__"
_CLOCK = "__clock__"
_PASSWORD = "__password__"
_REBOOT = "__reboot__"
_APPLY = "__apply__"
_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.
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.
Raises:
RuntimeError: If called outside the interactive menu (no full-screen session).
"""
from .admin_picker import pick_admin_node
from .surface import TuiUi
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()
contacts = await device.get_contacts()
node = await pick_admin_node(
ctx,
contacts,
title="Repeater admin — node to manage",
prompt="The remote node to set up (you need its admin password):",
)
if node is None:
return None
if not await _login(ctx, device, node):
return None
return await _admin_session(ctx, device, node)
async def _login(ctx: "AppContext", device: "Device", node: Contact) -> bool:
"""Log in to ``node``: remembered password silently, else one floating prompt.
A working password is remembered; a rejected one is forgotten so the next attempt
asks fresh (the app-wide remote-admin convention).
"""
session = ctx.ui.session
password = ctx.admin_store.get(node)
prompted = password is None
if password is None:
password = await session.text(
f"Admin password for {node.name}",
prompt="The node ignores admin commands without a login.",
password=True,
)
if not password:
return False
async with ctx.ui.busy_overlay():
accepted = await device.admin_login(node, password)
if not accepted:
ctx.admin_store.forget(node)
await session.message_dialog(
Text(
f"{node.name!r} rejected the admin login (wrong password?). "
+ ("" if prompted else "The saved password was cleared; ")
+ "try again to enter a new one.",
style="err",
),
title="admin login",
)
return False
ctx.admin_store.remember(node, password)
return True
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)."""
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
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)):
continue
return {"node": node.name, "applied": applied}
if choice == _APPLY:
applied += await _apply(ctx, device, node, pending)
elif choice == _READ:
await _read_all(ctx, device, node)
elif choice == _CLI:
await _command_line(ctx, device, node)
elif choice == _ADVERT:
await _simple_action(
ctx, device, node, "advert",
title="📡 Send advert",
prompt=f"Ask {node.name} to announce itself (flood) now?",
commit="Send",
)
elif choice == _CLOCK:
await _simple_action(
ctx, device, node, "clock sync",
title="🕒 Sync clock",
prompt=f"Set {node.name}'s clock from this companion's time?",
commit="Sync",
)
elif choice == _PASSWORD:
await _change_password(ctx, device, node)
elif choice == _REBOOT:
await _simple_action(
ctx, device, node, "reboot",
title="🔄 Reboot node",
prompt=f"Reboot {node.name} now? It drops off the mesh while booting.",
commit="Reboot",
danger=True,
)
else: # a setting key
await _stage_setting(ctx, str(choice), cache, pending)
finally:
session.pop(menu)
# --- the menu ------------------------------------------------------------------------
def _menu_items(
node: Contact, cache: dict, pending: dict[str, str]
) -> tuple[str, list]:
"""Build the editor menu's title and rows for the cache + staged state.
The same lane layout as the local device-configuration editor — setting, value
(with any staged ``→ new``), description under one header line — so administering
a remote node reads exactly like configuring the local one.
"""
sections: list[tuple[str, list[tuple[str, Text, str, Any]]]] = []
for category, specs in settings_by_category():
rows: list[tuple[str, Text, str, Any]] = []
for spec in specs:
rows.append((spec.label, _value_text(spec, cache, pending), spec.help, spec.key))
sections.append((category, rows))
label_w = max(cell_len(label) for _, rows in sections for label, _, _, _ in rows)
value_w = max(cell_len(value.plain) for _, rows in sections for _, value, _, _ in rows)
items: list = [
Separator(
" " + "SETTING".ljust(label_w + 2) + "VALUE".ljust(value_w + 2) + "DESCRIPTION"
)
]
for category, rows in sections:
items.append(Separator(f"── {category} ──", style="accent"))
for label, value, help_text, key in rows:
items.append(
Choice(title=_lane_row(label, value, help_text, label_w, value_w), value=key)
)
items.append(Separator("── Actions ──", style="accent"))
actions: list[tuple[str, str, str]] = [
("↻ Read settings", "Fetch every value from the node, one paced get", _READ),
("⌨ Command line…", "Talk to the node's CLI directly", _CLI),
("📡 Send advert…", "Have the node announce itself now", _ADVERT),
("🕒 Sync clock…", "Set the node's clock over the mesh", _CLOCK),
("🔐 Admin password…", "Change the node's admin password", _PASSWORD),
("🔄 Reboot node…", "Restart it remotely", _REBOOT),
]
action_w = max(cell_len(label) for label, _, _ in actions)
for label, help_text, value in actions:
row = Text(label)
row.append(" " * (action_w - cell_len(label) + 2))
row.append(help_text, style="muted")
items.append(Choice(title=row, value=value))
items.append(Separator(" "))
staged = len(pending)
if staged:
items.append(
Choice(
title=Text.assemble(("✓ ", "ok"), f"Apply {_changes(staged)}"),
value=_APPLY,
)
)
items.append(
Choice(
title=Text.assemble(("✗ ", "err"), "Back — discard staged changes"),
value=_CANCEL,
)
)
else:
items.append(Choice(title="Back", value=_CANCEL))
title = f"Repeater admin — {node.name}" + (f" · {staged} staged" if staged else "")
return title, items
def _value_text(spec: RemoteSetting, cache: dict, pending: dict[str, str]) -> Text:
"""One setting's VALUE lane: cached value (with its age), and any staged arrow."""
cached = cache.get(spec.key)
if not spec.readable:
value = Text("write-only", style="faint")
elif cached is None:
value = Text("?", style="muted")
else:
value = Text(cached.value)
age = _format_age(_age_seconds(cached.read_at))
if age != "now":
value.append(f" ·{age}", style="faint")
if spec.key in pending:
value.append(f" → {pending[spec.key]}", style="warn")
return value
def _lane_row(label: str, value: Text, help_text: str, label_w: int, value_w: int) -> Text:
"""Lay one row out in the SETTING / VALUE / DESCRIPTION lanes (cell-padded)."""
row = Text(label)
row.append(" " * (label_w - cell_len(label) + 2))
row.append_text(value)
row.append(" " * (value_w - cell_len(value.plain) + 2))
row.append(help_text, style="muted")
return row
def _changes(count: int) -> str:
"""``"1 staged change"`` / ``"3 staged changes"`` for dialogs and menu rows."""
return f"{count} staged change{'' if count == 1 else 's'}"
async def _confirm_discard(ctx: "AppContext", staged: int) -> bool:
"""Ask before dropping staged changes on the way out; ``True`` means discard."""
choice = await ctx.ui.dialog(
f"Discard {_changes(staged)} without sending them?",
[("Keep editing", "keep"), ("Discard", "discard")],
title="Unsaved changes",
default=1,
danger=True,
)
return choice == "discard"
# --- staging and applying ---------------------------------------------------------
async def _stage_setting(
ctx: "AppContext", key: str, cache: dict, pending: dict[str, str]
) -> None:
"""Prompt for one setting's new value and stage it (nothing is sent yet)."""
from ..core.remote_config import get_setting, validate_value
spec = get_setting(key)
if spec is None or not spec.writable: # pragma: no cover - menu offers only real keys
return
cached = cache.get(key)
current = pending.get(key, cached.value if cached is not None else "")
if spec.kind == "bool":
picked = await ctx.ui.dialog(
spec.help,
[("Off", "off"), ("On", "on")],
title=spec.label,
default=1 if current == "on" else 0,
keys={"0": "off", "1": "on", "n": "off", "y": "on"},
)
if picked is None:
return
value = str(picked)
else:
hint = ""
if spec.minimum is not None and spec.maximum is not None:
hint = f"Allowed: {spec.minimum:g} – {spec.maximum:g}"
elif spec.minimum is not None:
hint = f"Allowed: ≥ {spec.minimum:g}"
if spec.unit:
hint = f"{hint} ({spec.unit})" if hint else f"In {spec.unit}."
raw = await ctx.ui.text(
spec.label,
prompt=spec.help,
default=str(current),
validate=lambda t: validate_value(spec, t),
help_text=hint,
)
if raw is None:
return
value = raw.strip()
if cached is not None and value == cached.value:
pending.pop(key, None) # back to what the node last said — nothing to send
else:
pending[key] = value
async def _apply(
ctx: "AppContext", device: "Device", node: Contact, pending: dict[str, str]
) -> int:
"""Send every staged ``set`` command, paced, under an abortable progress dialog.
Each confirmed value folds straight into the per-node cache; a rejected or
unanswered set stays staged so it can be retried (or unstaged) rather than being
silently dropped. Records one ``runs`` row for the batch.
Returns:
How many settings the node accepted.
"""
from ..core.remote_config import get_setting
session = ctx.ui.session
run_id = ctx.repo.start_run(
"repeater-admin",
{"node": node.name, "mode": "apply", "settings": sorted(pending)},
ctx.profile_name,
)
outcomes: list[Text] = []
applied = 0
async def work(dialog: TracingDialog) -> None:
nonlocal applied
total = len(pending)
for i, (key, value) in enumerate(sorted(pending.items()), start=1):
spec = get_setting(key)
assert spec is not None
dialog.status = f"set {key} · {i}/{total}"
session.invalidate()
reply = await device.send_remote_command(
node, spec.set_command(value), timeout=_REPLY_TIMEOUT_S
)
if reply is not None and not reply_is_error(reply):
ctx.remote_store.remember_setting(node, key, value)
pending.pop(key, None)
applied += 1
outcomes.append(Text.assemble(("✓ ", "ok"), f"{spec.label} = {value}"))
elif reply is None:
outcomes.append(Text.assemble(
("? ", "warn"), f"{spec.label} — no reply (still staged)"
))
else:
outcomes.append(Text.assemble(
("✗ ", "err"), f"{spec.label} — {reply.strip()} (still staged)"
))
if i < total:
await asyncio.sleep(ctx.settings.trace_cooldown_s)
aborted = await _run_under_dialog(ctx, f"applying · {node.name}", work)
ctx.repo.finish_run(
run_id, "error" if aborted else "ok",
{"applied": applied, "staged_left": len(pending)},
)
summary = Text.assemble(
(f"{applied}", "brand"), f" of {applied + len(pending)} settings applied"
)
if aborted:
summary.append(" (aborted — the rest stay staged)", style="warn")
await ctx.ui.session.message_dialog(
Text("\n").join([summary, Text(), *outcomes]) if outcomes else summary,
title=f"apply · {node.name}",
)
return applied
async def _read_all(ctx: "AppContext", device: "Device", node: Contact) -> None:
"""Refresh every readable setting from the node, one paced ``get`` at a time.
Values that parse land in the cache (and on screen); firmware that doesn't know a
key just leaves that row unknown. Abort keeps everything already read.
"""
session = ctx.ui.session
specs = [s for cat, ss in settings_by_category() for s in ss if s.readable]
run_id = ctx.repo.start_run(
"repeater-admin", {"node": node.name, "mode": "read"}, ctx.profile_name
)
read = 0
async def work(dialog: TracingDialog) -> None:
nonlocal read
for i, spec in enumerate(specs, start=1):
dialog.status = f"get {spec.key} · {i}/{len(specs)}"
session.invalidate()
reply = await device.send_remote_command(
node, spec.get_command, timeout=_REPLY_TIMEOUT_S
)
value = parse_reply_value(spec, reply)
if value is not None:
ctx.remote_store.remember_setting(node, spec.key, value)
read += 1
if i < len(specs):
await asyncio.sleep(ctx.settings.trace_cooldown_s)
aborted = await _run_under_dialog(ctx, f"reading · {node.name}", work)
ctx.repo.finish_run(
run_id, "error" if aborted else "ok", {"read": read, "asked": len(specs)}
)
async def _run_under_dialog(ctx: "AppContext", title: str, work) -> bool:
"""Run an async remote batch under a floating spinner dialog with Abort.
Args:
ctx: The shared application context.
title: The dialog's heading.
work: ``async work(dialog)`` performing the batch, updating ``dialog.status``.
Returns:
``True`` if the user aborted, ``False`` if the batch ran to completion.
"""
session = ctx.ui.session
spinner = Spinner()
dialog = TracingDialog(title, spinner=spinner, on_abort=lambda: None)
dialog.show_last = False
task = asyncio.ensure_future(work(dialog))
dialog.on_abort = task.cancel
async def animate() -> None:
while True:
await asyncio.sleep(_SPINNER_INTERVAL)
spinner.tick()
session.invalidate()
ticker = asyncio.ensure_future(animate())
session.push(dialog)
aborted = False
try:
await task
except asyncio.CancelledError:
aborted = True
except Exception as exc: # noqa: BLE001 - surface in a dialog, keep the screen
await session.message_dialog(Text(str(exc), style="err"), title=title)
finally:
ticker.cancel()
try:
await ticker
except asyncio.CancelledError:
pass
except Exception: # noqa: BLE001 - a spinner hiccup must never break the batch
pass
session.pop(dialog)
return aborted
# --- one-shot actions ------------------------------------------------------------
async def _simple_action(
ctx: "AppContext",
device: "Device",
node: Contact,
command: str,
*,
title: str,
prompt: str,
commit: str,
danger: bool = False,
) -> None:
"""Confirm and send one fixed CLI command, showing the node's reply."""
choice = await ctx.ui.dialog(
prompt,
[("Cancel", None), (commit, "go")],
title=title,
default=1,
danger=danger,
)
if choice != "go":
return
async with ctx.ui.busy_overlay():
reply = await device.send_remote_command(node, command, timeout=_REPLY_TIMEOUT_S)
if reply is None:
body = Text("no reply — the command may still have landed", style="warn")
else:
body = Text(reply.strip(), style="err" if reply_is_error(reply) else "ok")
await ctx.ui.session.message_dialog(body, title=title)
async def _change_password(ctx: "AppContext", device: "Device", node: Contact) -> None:
"""Change the node's admin password (and re-remember it on success)."""
new = await ctx.ui.text(
f"New admin password for {node.name}",
prompt="Sent over the mesh; the node applies it immediately.",
password=True,
)
if not new:
return
confirmed = await ctx.ui.dialog(
f"Change {node.name}'s admin password now? You will need the new one everywhere.",
[("Cancel", None), ("Change", "go")],
title="🔐 Admin password",
default=1,
danger=True,
)
if confirmed != "go":
return
async with ctx.ui.busy_overlay():
reply = await device.send_remote_command(
node, f"password {new}", timeout=_REPLY_TIMEOUT_S
)
if reply is not None and not reply_is_error(reply):
ctx.admin_store.remember(node, new) # the working password just changed
body = Text("✓ password changed and remembered", style="ok")
elif reply is None:
body = Text(
"no reply — the change may or may not have landed; the old password "
"stays remembered until a login proves otherwise",
style="warn",
)
else:
body = Text(reply.strip(), style="err")
await ctx.ui.session.message_dialog(body, title="admin password")
# --- the command line ---------------------------------------------------------------
async def _command_line(ctx: "AppContext", device: "Device", node: Contact) -> None:
"""Open the readline-style remote CLI for ``node`` (history persists per node)."""
from .remote_cli import RemoteCliScreen
session = ctx.ui.session
worker: Optional[asyncio.Task] = None
ticker: Optional[asyncio.Task] = None
def send(command: str) -> None:
nonlocal worker
if worker is not None and not worker.done():
return # one command in flight at a time — every send is a transmission
screen.sent(command)
ctx.remote_store.append_history(node, command)
worker = asyncio.ensure_future(roundtrip(command))
async def roundtrip(command: str) -> None:
try:
reply = await device.send_remote_command(
node, command, timeout=_REPLY_TIMEOUT_S
)
except asyncio.CancelledError:
screen.failed("cancelled", error=False)
raise
except Exception as exc: # noqa: BLE001 - shown inline, the screen stays up
screen.failed(str(exc), error=True)
return
if reply is None:
screen.failed(f"no reply within {_REPLY_TIMEOUT_S:.0f} s")
else:
screen.reply(reply)
screen = RemoteCliScreen(
node_label=node.name,
history=ctx.remote_store.history(node),
send=send,
session=session,
)
async def animate() -> None:
while True:
await asyncio.sleep(_SPINNER_INTERVAL)
if screen.busy:
screen.tick()
session.invalidate()
ticker = asyncio.ensure_future(animate())
try:
await session.run_screen(screen)
finally:
for task in (worker, ticker):
if task is not None and not task.done():
task.cancel()
for task in (worker, ticker):
if task is not None:
try:
await task
except asyncio.CancelledError:
pass
except Exception: # noqa: BLE001 - the screen is closed; nothing to surface
pass