diff --git a/meshterm/ui/contacts_screen.py b/meshterm/ui/contacts_screen.py index 39addf4..7d5e8c4 100644 --- a/meshterm/ui/contacts_screen.py +++ b/meshterm/ui/contacts_screen.py @@ -300,6 +300,17 @@ class ContactsScreen(ContactListScreen): self._locked = locked self.update_rows(self._contact_rows_for(locked)) + def refresh_self(self, name: str, key: str) -> None: + """Draw the row of our node again in place, after our page can change our name. + + The page of our node runs Device config, which can rename our node. Our row is + still the same row, so the highlight, the sort, the scroll, and a typed filter stay. + """ + if (name, key) == (self._self_name, self._self_key): + return + self._self_name, self._self_key = name, key + self.update_rows(self._contact_rows_for(self._locked)) + def _with_opp(slot, label: str, action: str, enabled: bool): # noqa: ANN001, ANN202 - an FPair """``slot`` (an F-key slot, or ``None``) with ``label`` and ``action`` as its Shift half. @@ -433,6 +444,19 @@ async def open_contacts( if await open_node_detail(ctx, None if chosen == YOU else chosen): rebuild = True break + if chosen == YOU: + # Our page runs the tools of the "This node" section. Device config can + # rename our node, so our row reads the name again. The cache answers + # when nothing changed, so this costs no read from the radio. + try: + info = await ctx.devstate.self_info() + except Exception: # noqa: BLE001 - our row keeps the name that it has + info = {} + if info: + self_name = str(info.get("name") or "this node") + self_key = str(info.get("public_key") or "") + screen.refresh_self(self_name, self_key) + continue # The page can lock or unlock the contact without an end to the visit. The # store answers from memory, so MeshTerm only draws the padlocks again. screen.refresh_locks(_locked_keys(ctx, self_key)) diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index ca90ff1..8951131 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -936,11 +936,11 @@ async def _menu_round( tool = next((t for t in tools if t.name == selection), None) if tool is not None and tool.popup: ran_over_menu = True - await _run_selection(ctx, selection) + await run_tool(ctx, selection) finally: session.pop(menu) if not ran_over_menu: - await _run_selection(ctx, selection) + await run_tool(ctx, selection) async def _startup(ctx: AppContext) -> bool: @@ -1208,9 +1208,14 @@ def _reading_caption(ctx: AppContext) -> str: return "reading…" -async def _run_selection(ctx: AppContext, name: str) -> None: +async def run_tool(ctx: AppContext, name: str) -> None: """Get the parameters for one tool from the menu, run the tool, and show its result. + The main menu calls it for each tool row. The page of our node calls it too, for the + rows of the ``This node`` section that it shows (refer to + :func:`~meshterm.ui.node_detail_screen.open_node_detail`). Thus a tool behaves the same + from both places: the same prompts, the same result, and the same failure dialog. + This function does not handle a lost device link. The watcher for the full session (refer to :func:`_session_loop`) polls independently, and opens the reconnect dialog on any screen of the session. Thus, on a connection-lost error, this function removes diff --git a/meshterm/ui/node_detail_screen.py b/meshterm/ui/node_detail_screen.py index 399da5e..987fc24 100644 --- a/meshterm/ui/node_detail_screen.py +++ b/meshterm/ui/node_detail_screen.py @@ -1522,7 +1522,10 @@ async def open_node_detail( ctx: The shared application context (the interactive TUI must be running). contact: The contact to show, or ``None`` for our node (a page of identity and ledger only, because our node never overhears itself, so there is no reception - history to show). + history to show). The page of our node also offers the tools of the ``This + node`` section of the main menu. If one of them changes what the page shows + (Device config can change the name or the location), the page opens again with + the new values. manage: Whether to show the contact-management actions (lock, archive, restore, delete). ``False`` draws none of them, and then the page can only return ``False``. @@ -1560,10 +1563,7 @@ async def open_node_detail( # -- our node, for the "us" label, the centre of the location preview, and the range # and bearing. - try: - info = await ctx.devstate.self_info() - except Exception: # noqa: BLE001 - the page is useful without our identity and fix - info = {} + info = await _read_self_info(ctx) self_name = str(info.get("name") or "this node") self_key = str(info.get("public_key") or "") self_lat, self_lon = _as_float(info.get("adv_lat")), _as_float(info.get("adv_lon")) @@ -1840,6 +1840,10 @@ async def open_node_detail( # map (a roof, a tower), or a place for a node with no location at all. if places is not None and node_id: info_actions.append(_Action("place", "✎", "", "Set place…")) + if you: + # Our page is where the user looks at our node, so it offers the tools of the main + # menu that act on our node: its whole ``This node`` section, row for row. + info_actions.extend(_this_node_actions()) if asks_regions: # It acts immediately (one anonymous request, one transmission), so no "…" at the # end. @@ -1980,6 +1984,8 @@ async def open_node_detail( # Whether the visit ended with a delete of the contact. This tells the caller to build # its list again. contact_removed = False + # Whether a tool changed what the page shows of our node. Then the page opens again. + reopen = False # One screen for the full visit. The page is a *hub*: each action on it opens a different # screen and comes back. Thus the page stays pushed while each action runs # (``session.stay``), and it is not built again for each round. Before, each new build @@ -2097,14 +2103,70 @@ async def open_node_detail( contact_removed = await _remove_contact(ctx, contact, self_key, label) if contact_removed: break + elif isinstance(action, str) and action.startswith(_TOOL_ACTION): + from .menu import run_tool + + await run_tool(ctx, action.removeprefix(_TOOL_ACTION)) + # Device config can change what this page shows of our node: its name, its + # location, or its type. Then the page is built again from the new values. + fresh = await _read_self_info(ctx) if you else {} + if fresh and _shown_self(fresh) != _shown_self(info): + reopen = True + break if minimap is not None: # The braille of the preview may have left marks on the terminal (double-width # fallback glyphs that the diff of prompt_toolkit cannot see). Force one clean paint # of the list below, exactly as the full map does when it closes. session.request_full_repaint() + if reopen: + # The old page closed, and a new page opens in its place, one level above the same + # screen. Thus Esc from the new page still goes back to where the user came from. + return await open_node_detail(ctx, contact, manage=manage, lock=lock) return contact_removed +#: The section of the main menu whose tools act on our node. The page of our node offers +#: each tool of this section (refer to :func:`_this_node_actions`). +THIS_NODE_SECTION = "This node" + +#: The start of the token of an action row that runs a tool of the main menu. The rest of +#: the token is the name of the tool. +_TOOL_ACTION = "tool:" + +#: The fields of the self-info that the page of our node shows. When a tool that the page +#: runs changes one of them, the page is built again. +_SHOWN_SELF_FIELDS = ("name", "public_key", "adv_lat", "adv_lon", "adv_type") + + +def _this_node_actions() -> list[_Action]: + """One action row for each tool of the ``This node`` section of the main menu. + + The rows come from the tool registry, in the order of the menu, with the icon and the + title of each menu row. Thus a tool that MeshTerm adds to the section, or removes from + it, changes the page too, and the two places always use the same words. + """ + from ..tools import all_tools + + return [ + _Action(f"{_TOOL_ACTION}{tool.name}", tool.icon, "", tool.title or tool.name) + for tool in all_tools() + if tool.menu_visible and tool.category == THIS_NODE_SECTION + ] + + +async def _read_self_info(ctx: AppContext) -> dict: + """The self-info of the device, or an empty dict when the device does not answer.""" + try: + return await ctx.devstate.self_info() + except Exception: # noqa: BLE001 - the page is useful without our identity and fix + return {} + + +def _shown_self(info: dict) -> tuple: + """The values of the self-info that the page of our node shows.""" + return tuple(info.get(field) for field in _SHOWN_SELF_FIELDS) + + def _management_rows( *, locked: bool, lockable: bool, manageable: bool, archived: bool, whole_key: bool ) -> list[_Action]: diff --git a/meshterm/ui/tui/screen.py b/meshterm/ui/tui/screen.py index 0e738d6..4b8c7d7 100644 --- a/meshterm/ui/tui/screen.py +++ b/meshterm/ui/tui/screen.py @@ -59,7 +59,7 @@ class PopToMenu(BaseException): It derives from :class:`BaseException`, not :class:`Exception`, for the same reason as :class:`asyncio.CancelledError`. The app has many ``except Exception`` guards. These guards stop a tool that has a fault before it can stop the menu - (:func:`~meshterm.ui.menu._run_selection` has the widest guard). An unwind must go + (:func:`~meshterm.ui.menu.run_tool` has the widest guard). An unwind must go through these guards. They must not catch it and report it as a failure of a tool. ``finally`` blocks still run, so nothing leaks. diff --git a/tests/test_device_config.py b/tests/test_device_config.py index f873f5b..1f54b9f 100644 --- a/tests/test_device_config.py +++ b/tests/test_device_config.py @@ -2102,6 +2102,25 @@ def test_k_on_the_contacts_list_asks_to_toggle_the_lock_of_the_highlighted_conta assert "^K" not in plain.footer_hint +def test_our_row_takes_a_new_name_in_place() -> None: + """After our page renamed our node (Device config), our row shows the new name. + + The row stays the same row: the highlight stays where it was. + """ + from meshterm.core.models import Contact + from meshterm.ui.contacts_screen import ContactsScreen + from tests.conftest import plain + + alice = Contact(name="Alice", public_key="aa" * 32, key_prefix="aa" * 6) + screen = ContactsScreen("Us", "cc" * 32, [alice], 1, {}, _contacts_sort()) + screen.handle("down") + highlighted = screen._current_choice().value + screen.refresh_self("Renamed", "cc" * 32) + body = plain(screen.render_body(72)) + assert "Renamed" in body and "Us (you)" not in body + assert screen._current_choice().value is highlighted + + async def test_k_on_the_contacts_list_toggles_the_lock_in_place(tmp_path) -> None: # noqa: ANN001 """^K writes the lock to the store, and the row gains its padlock on the same screen. diff --git a/tests/test_disconnect.py b/tests/test_disconnect.py index 10cdedc..4a76334 100644 --- a/tests/test_disconnect.py +++ b/tests/test_disconnect.py @@ -2178,7 +2178,7 @@ async def _run_failing_tool(tmp_path: Path, monkeypatch, exc: Exception) -> _Too monkeypatch.setattr(tools, "get_tool", lambda name: _Tool()) monkeypatch.setattr(ctx, "ui", ui) try: - await menu._run_selection(ctx, "contacts") + await menu.run_tool(ctx, "contacts") finally: ctx.repo.close() return ui diff --git a/tests/test_navigation.py b/tests/test_navigation.py index afdbac1..cedce4e 100644 --- a/tests/test_navigation.py +++ b/tests/test_navigation.py @@ -802,7 +802,7 @@ async def test_pop_all_passes_straight_through_an_except_exception_guard() -> No """An unwind is not a tool failure. The app wraps tool runs in ``except Exception``, so that a broken tool cannot stop the - menu (:func:`meshterm.ui.menu._run_selection` is the widest such guard). An unwind must + menu (:func:`meshterm.ui.menu.run_tool` is the widest such guard). An unwind must cross these guards. They must not catch it and report it as an error. This is the reason that :class:`PopToMenu` derives from ``BaseException``. """ diff --git a/tests/test_node_detail.py b/tests/test_node_detail.py index b2f16de..b6358ad 100644 --- a/tests/test_node_detail.py +++ b/tests/test_node_detail.py @@ -1540,13 +1540,8 @@ def test_the_place_row_follows_the_finder_above_where() -> None: assert "Villeray" not in _plain(screen.render_body(72)) -async def test_our_own_page_opens_and_closes(tmp_path) -> None: # noqa: ANN001 - """Enter on our row of the Contacts list opens our page, and Esc closes it. - - The page of our node has no contact. Before, the action rows read a value that only the - page of a contact sets, and the page raised ``UnboundLocalError`` before it showed. - """ - import asyncio +def _own_page_ctx(tmp_path): # noqa: ANN001, ANN202 - a test AppContext + """A context with the simulator as its device, a store on disk, and a full-screen session.""" import io from rich.console import Console @@ -1556,10 +1551,11 @@ async def test_our_own_page_opens_and_closes(tmp_path) -> None: # noqa: ANN001 from meshterm.core.config import Settings from meshterm.core.device_store import DeviceStore from meshterm.persistence.repository import Repository - from meshterm.ui.node_detail_screen import NodeDetailScreen, open_node_detail + from meshterm.tools import load_all_tools from meshterm.ui.surface import TuiUi from meshterm.ui.tui.session import TuiSession + load_all_tools() # the page reads the menu sections from the registry settings = Settings(config_dir=tmp_path, db_path=tmp_path / "history.db") ctx = AppContext( console=Console(file=io.StringIO()), @@ -1570,18 +1566,52 @@ async def test_our_own_page_opens_and_closes(tmp_path) -> None: # noqa: ANN001 mock=True, ) ctx.ui = TuiUi(TuiSession()) + return ctx + + +async def _next_page(ctx, task, *, after=None): # noqa: ANN001, ANN202 - a NodeDetailScreen + """The node page on top of the session, once it is a page other than ``after``. + + The page of a node with a location reads the map in a thread, so the wait has a time + limit and not a count of loop turns. If the task ends first, this helper raises what + the task raised, or fails. + """ + import asyncio + import time + + from meshterm.ui.node_detail_screen import NodeDetailScreen + + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + top = ctx.ui.session.top + if isinstance(top, NodeDetailScreen) and top is not after: + return top + if task.done(): + task.result() + raise AssertionError("the page closed before it showed") + await asyncio.sleep(0.001) + raise AssertionError("no node page showed") + + +def _action_keys(page) -> list[str]: # noqa: ANN001 - a NodeDetailScreen + """The tokens of the action rows of the Info tab of ``page``.""" + return [action.key for action in page._info_actions] + + +async def test_our_own_page_opens_and_closes(tmp_path) -> None: # noqa: ANN001 + """Enter on our row of the Contacts list opens our page, and Esc closes it. + + The page of our node has no contact. Before, the action rows read a value that only the + page of a contact sets, and the page raised ``UnboundLocalError`` before it showed. + """ + import asyncio + + from meshterm.ui.node_detail_screen import open_node_detail + + ctx = _own_page_ctx(tmp_path) task = asyncio.ensure_future(open_node_detail(ctx, None)) try: - page = None - for _ in range(500): - top = ctx.ui.session.top - if isinstance(top, NodeDetailScreen) or task.done(): - page = top if isinstance(top, NodeDetailScreen) else None - break - await asyncio.sleep(0) - if task.done(): - task.result() # raise what the page raised, if anything - assert page is not None + page = await _next_page(ctx, task) assert page.title.endswith("(you)") page.resolve(CANCEL) assert await task is False @@ -1589,3 +1619,86 @@ async def test_our_own_page_opens_and_closes(tmp_path) -> None: # noqa: ANN001 if not task.done(): task.cancel() ctx.repo.close() + + +async def test_our_own_page_offers_the_this_node_section(tmp_path) -> None: # noqa: ANN001 + """Our page ends on the rows of the "This node" section of the main menu, in its order. + + The page of a contact does not offer them: these tools act on our node only. + """ + import asyncio + + from meshterm.ui.node_detail_screen import open_node_detail + + ctx = _own_page_ctx(tmp_path) + task = asyncio.ensure_future(open_node_detail(ctx, None)) + try: + page = await _next_page(ctx, task) + keys = _action_keys(page) + assert keys[-3:] == ["tool:info", "tool:config", "tool:advert"] + body = _plain(page.render_body(72)) + for title in ("Device info", "Device config", "Send advert"): + assert title in body + page.resolve(CANCEL) + await task + + contact = next(iter(await ctx.devstate.contacts())) + task = asyncio.ensure_future(open_node_detail(ctx, contact)) + page = await _next_page(ctx, task) + assert not [key for key in _action_keys(page) if key.startswith("tool:")] + page.resolve(CANCEL) + await task + finally: + if not task.done(): + task.cancel() + ctx.repo.close() + + +async def test_a_this_node_row_runs_its_tool_and_a_rename_opens_the_page_again( + tmp_path, monkeypatch +) -> None: # noqa: ANN001 + """A row runs its tool as the menu does. After a rename, the page shows the new name. + + A tool that changes nothing that the page shows leaves the same page, with its + highlight. A rename (Device config) opens a new page in its place, one level above the + same screen. + """ + import asyncio + + from meshterm.ui import menu + from meshterm.ui.node_detail_screen import open_node_detail + + ctx = _own_page_ctx(tmp_path) + info = dict(await ctx.devstate.self_info()) + ran: list[str] = [] + + async def _run_tool(_ctx, name: str) -> None: # noqa: ANN001 + ran.append(name) + if name == "config": + info["name"] = "Renamed" + + async def _self_info() -> dict: + return dict(info) + + monkeypatch.setattr(menu, "run_tool", _run_tool) + monkeypatch.setattr(ctx.devstate, "self_info", _self_info) + depth = len(ctx.ui.session._stack) + task = asyncio.ensure_future(open_node_detail(ctx, None)) + try: + page = await _next_page(ctx, task) + page.resolve("tool:info") + for _ in range(50): + await asyncio.sleep(0) + assert ran == ["info"] and ctx.ui.session.top is page + + page.resolve("tool:config") + renamed = await _next_page(ctx, task, after=page) + assert ran == ["info", "config"] + assert renamed.title == "Node — Renamed (you)" + assert len(ctx.ui.session._stack) == depth + 1 + renamed.resolve(CANCEL) + assert await task is False + finally: + if not task.done(): + task.cancel() + ctx.repo.close()