From e07ef3b379669e18e5355283c0d27fc21e624621 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Mon, 13 Jul 2026 22:41:58 -0400 Subject: [PATCH] Device state: cache the picker reads that run before each screen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The session cache fixed the reads screens make on open, but opening the heaviest screens still stalled for seconds — because the pickers and screen-openers that run *in front of* those screens were still reading the radio directly. The menu wraps prompt-gathering and execution in one busy overlay, so a Trace or Chat open pays its picker's slow round-trips before the (already-cached) screen behind it ever builds, which is why caching the screens alone showed no improvement. Route the interactive-open reads through ctx.devstate too: - Chat's conversation picker read the channel-slot probe *and* the contacts table on every open (~5s) — both now come from the cache (channels mapped from the cached slots via the new _channels_from_slots, contacts served cached). The CLI list/send path keeps reading fresh. - Trace and TX-optimize target pickers now read contacts from the cache. - The repeater-admin screen and the channels manager (its slot probe, on a local copy so mutations still re-probe the fresh layout after invalidation) read through the cache. Small, session-stable reads (self-info, build_snapshot's tuning/path-hash) are left as direct reads — they were never the seconds. Co-Authored-By: Claude Opus 4.8 --- meshterm/tools/chat.py | 58 ++++++++++++++++++++++++++++++++--- meshterm/tools/trace.py | 7 +++-- meshterm/tools/tx_optimize.py | 6 ++-- meshterm/ui/channels.py | 7 ++++- meshterm/ui/repeater_admin.py | 6 +++- 5 files changed, 74 insertions(+), 10 deletions(-) diff --git a/meshterm/tools/chat.py b/meshterm/tools/chat.py index dbe7e3e..8f4f6fb 100644 --- a/meshterm/tools/chat.py +++ b/meshterm/tools/chat.py @@ -14,7 +14,7 @@ from __future__ import annotations import asyncio import time -from typing import Any, Callable, Optional, Union +from typing import TYPE_CHECKING, Any, Callable, Optional, Union import typer from rich.table import Table @@ -35,6 +35,9 @@ from ..ui.tui import Choice, Separator from ..ui.widgets import channel_glyph from .base import Tool, ToolResult, register +if TYPE_CHECKING: + from ..ui.channels import ChannelSlot + #: How many recent messages ``chat history`` prints by default. _HISTORY_LIMIT = 50 @@ -113,9 +116,14 @@ class ChatTool(Tool): The chosen :class:`~meshterm.core.models.Conversation`, or ``None`` if cancelled. """ - device = await ctx.device() - channels = await _read_channels(device) - contacts = await device.get_contacts() + # Through the session cache: this picker runs on every Chat open, and its two reads — + # the channel-slot probe and the contacts table — are the two slowest round-trips on a + # companion. Reading them from the device each time is what made opening Chat stall for + # seconds (the cached chat screen behind it never got the chance to help). The cache + # holds channels until the channel editor writes a slot and refreshes contacts in the + # background (see :class:`~meshterm.services.device_state.DeviceState`). + channels = _channels_from_slots(await ctx.devstate.channel_slots()) + contacts = await ctx.devstate.contacts() # A stable snapshot orders the rows (so the list doesn't reshuffle under the cursor), # while a self-refreshing view feeds each row's live preview (see _LiveLasts). lasts = ctx.repo.last_chat_messages() @@ -381,6 +389,48 @@ def _enable_receive_debug() -> None: log.addHandler(handler) +def _channels_from_slots(slots: list["ChannelSlot"]) -> list[Conversation]: + """Turn cached channel slots into channel conversations, always offering Public (slot 0). + + The picker reads its channels through the session cache + (:meth:`~meshterm.services.device_state.DeviceState.channel_slots`) so it reuses the one + slow slot probe instead of re-walking every slot on each Chat open; this maps that cached + :class:`~meshterm.ui.channels.ChannelSlot` list onto the picker's + :class:`~meshterm.core.models.Conversation` rows. Channel 0 (the default public channel) is + synthesised when the firmware reports no slot for it, so there is always somewhere to chat — + the same guarantee :func:`_read_channels` (the CLI path) makes. + + Args: + slots: The configured channel slots, from the session cache. + + Returns: + One :class:`~meshterm.core.models.Conversation` per slot, with Public prepended when + slot 0 is absent. + """ + conversations = [ + Conversation( + label=slot.name, + is_channel=True, + channel_idx=slot.idx, + channel_id=channel_identity(slot.name, slot.secret), + secret=slot.secret, + ) + for slot in slots + ] + if not any(c.channel_idx == 0 for c in conversations): + conversations.insert( + 0, + Conversation( + label="Public", + is_channel=True, + channel_idx=0, + channel_id="slot:0", + secret=DEFAULT_PUBLIC_SECRET, + ), + ) + return conversations + + async def _read_channels(device: Device) -> list[Conversation]: """Probe channel slots and return them as channel conversations. diff --git a/meshterm/tools/trace.py b/meshterm/tools/trace.py index 39c6467..9f9116f 100644 --- a/meshterm/tools/trace.py +++ b/meshterm/tools/trace.py @@ -130,8 +130,11 @@ class TraceTool(Tool): from ..ui.tui import Choice, Separator from ..ui.widgets import _DEFAULT_GLYPH, _NODE_GLYPHS - device = await ctx.device() - contacts = await device.get_contacts() + # Through the session cache: this picker runs on every Trace open, and the contacts + # table is a slow round-trip on a busy node — re-reading it here (in front of the + # already-cached trace screen) is what kept opening Trace feeling like a stall. See + # the note in the ``nodes`` tool and :class:`~meshterm.services.device_state.DeviceState`. + contacts = await ctx.devstate.contacts() recent = _recent_targets(ctx.repo.traced_targets(), contacts) if not contacts and not recent: diff --git a/meshterm/tools/tx_optimize.py b/meshterm/tools/tx_optimize.py index b9820a7..c13aeba 100644 --- a/meshterm/tools/tx_optimize.py +++ b/meshterm/tools/tx_optimize.py @@ -59,8 +59,10 @@ class TxOptimizeTool(Tool): """ from ..ui.admin_picker import pick_admin_node - device = await ctx.device() - contacts = await device.get_contacts() + # Through the session cache: this two-picker entry flow runs on every open, and the + # contacts table is a slow read on a busy node (see + # :class:`~meshterm.services.device_state.DeviceState`). + contacts = await ctx.devstate.contacts() admin = await pick_admin_node( ctx, contacts, diff --git a/meshterm/ui/channels.py b/meshterm/ui/channels.py index 98d72c3..4f923b5 100644 --- a/meshterm/ui/channels.py +++ b/meshterm/ui/channels.py @@ -152,7 +152,12 @@ async def manage_channels(ctx: "AppContext") -> int: highlight: Optional[object] = None while True: - slots = await read_channel_slots(device) + # 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(await ctx.devstate.channel_slots()) title, items = _menu_items(ctx, slots, capacity, stats) async def handle(choice: object) -> bool: diff --git a/meshterm/ui/repeater_admin.py b/meshterm/ui/repeater_admin.py index 1ba5481..f9e0059 100644 --- a/meshterm/ui/repeater_admin.py +++ b/meshterm/ui/repeater_admin.py @@ -84,7 +84,11 @@ async def open_repeater_admin(ctx: "AppContext") -> Optional[dict[str, Any]]: session = ctx.ui.session device = await ctx.device() - contacts = await device.get_contacts() + # Through the session cache — opening this screen shouldn't re-read the (slow) contacts + # table when another screen already has (see + # :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() node = await pick_admin_node( ctx, contacts,