diff --git a/meshterm/ui/device_picker.py b/meshterm/ui/device_picker.py index 4e5604a..7e8f3ef 100644 --- a/meshterm/ui/device_picker.py +++ b/meshterm/ui/device_picker.py @@ -19,12 +19,13 @@ device; anything else sends the user back to the list to choose another. from __future__ import annotations -from typing import TYPE_CHECKING, Awaitable, Callable, Optional +from typing import TYPE_CHECKING, Awaitable, Callable, Mapping, Optional from rich.cells import cell_len from rich.text import Text from .. import copyright_notice +from ..core.config import DeviceProfile from ..core.connection import DeviceAuthenticationError, DeviceCommandError from ..core.device_store import DeviceStore, RememberedDevice from ..core.discovery import ( @@ -262,6 +263,7 @@ async def prompt_device( devices: list[DiscoveredDevice], store: DeviceStore, verify: Verify, + profiles: Optional[Mapping[str, DeviceProfile]] = None, ) -> Optional[DiscoveredDevice]: """Prompt the user to choose a companion device on the startup splash. @@ -276,6 +278,9 @@ async def prompt_device( record a device once its smoke test passes. verify: Async smoke test returning a device's self-info dict, or ``None`` if it is not a reachable MeshCore companion. + profiles: The configured device profiles (``config.toml`` ``[profiles.*]``). Their TCP + entries are folded into the list so a hand-authored network companion appears here + without having to be connected to first (see :func:`_profile_tcp_devices`). Returns: The chosen, confirmed :class:`DiscoveredDevice`, or ``None`` if the user chose to @@ -291,8 +296,11 @@ async def prompt_device( registry = store.load_all() # A TCP companion isn't discoverable, so a previously confirmed one only reappears if we # rebuild it from its remembered endpoint and fold it into the list alongside the - # scanned devices (the scan never produces it). + # scanned devices (the scan never produces it). Configured TCP profiles are folded in + # the same way, after the scanned/remembered set so an already-known endpoint keeps its + # richer remembered row rather than being shadowed by the profile. listed = scanned + _remembered_tcp_devices(scanned, registry) + listed += _profile_tcp_devices(listed, profiles) # Preselect the remembered "last known good" device when it is currently attached/in range. default = next((d for d in listed if remembered and remembered.matches(d)), None) @@ -375,6 +383,44 @@ def _remembered_tcp_devices( return rebuilt +def _profile_tcp_devices( + listed: list[DiscoveredDevice], + profiles: Optional[Mapping[str, DeviceProfile]], +) -> list[DiscoveredDevice]: + """Rebuild configured TCP profiles as :class:`DiscoveredDevice` rows for the picker. + + A ``[profiles.]`` block with ``transport = "tcp"`` names a network companion the + user wants to reach — but a TCP endpoint isn't discoverable, so without this it would only + ever surface via ``meshterm -p `` on the command line, never in the interactive + splash. Each such profile is turned into a device carrying its alias as the DEVICE-column + name (that is how the user addresses it), so it lists like a hand-added network device and + smoke-tests the same way. Any profile whose endpoint is already present — scanned, or a + remembered companion carrying its real node name — is skipped so the richer existing row + wins rather than being duplicated by the bare profile. + + Args: + listed: The devices already gathered (scanned + remembered), for de-duplication. + profiles: The configured profiles, or ``None`` when none are loaded. + + Returns: + One TCP :class:`DiscoveredDevice` per not-yet-listed TCP profile, in profile order. + """ + if not profiles: + return [] + seen = {d.stable_id for d in listed} + rebuilt: list[DiscoveredDevice] = [] + for profile in profiles.values(): + if not profile.is_tcp or not profile.host: + continue + port = profile.tcp_port or DEFAULT_TCP_PORT + device = tcp_device(profile.host, port, name=profile.name) + if device.stable_id in seen: + continue + seen.add(device.stable_id) + rebuilt.append(device) + return rebuilt + + async def _add_network_device( ui: "Ui", store: DeviceStore, diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index 74d7a06..c9831eb 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -553,7 +553,9 @@ async def _startup(ctx: AppContext) -> bool: probed["device"] = connection return info - chosen = await prompt_device(ctx.ui, devices, ctx.device_store, verify) + chosen = await prompt_device( + ctx.ui, devices, ctx.device_store, verify, ctx.settings.profiles + ) if chosen is None: return False # the user quit at the splash — exit without opening the menu ctx.selected_device = chosen diff --git a/tests/test_tui.py b/tests/test_tui.py index eae805f..3f11d9d 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -974,6 +974,74 @@ def test_device_picker_reinjects_remembered_tcp_device(tmp_path) -> None: assert _TCP_ICON in top.plain # marked with the network TYPE glyph +def test_device_picker_lists_configured_tcp_profile(tmp_path) -> None: + """A ``[profiles.*]`` TCP entry shows up in the picker under its alias, ready to select.""" + from meshterm.core.config import DeviceProfile + from meshterm.core.device_store import DeviceStore + from meshterm.ui.device_picker import _TCP_ICON, prompt_device + + store = DeviceStore(tmp_path / "devices.json") + profiles = { + "bridge": DeviceProfile( + name="bridge", transport="tcp", host="127.0.0.1", tcp_port=5000 + ) + } + + captured: dict = {} + + class _Ui: + async def select_startup(self, title, items, *, default=None, banner=None, footnote=None): + captured["items"] = items + return None # skip past the smoke test + + async def _never(_device): + raise AssertionError("verify should not run when selection is skipped") + + # Nothing scanned or remembered — the profile alone puts the endpoint in the list. + asyncio.run(prompt_device(_Ui(), [], store, _never, profiles)) + rows = [it.title for it in captured["items"] if isinstance(it, Choice)] + device_rows = [r for r in rows if hasattr(r, "plain") and "bridge" in r.plain] + assert device_rows, "the configured TCP profile should be listed" + top = device_rows[0] + assert "127.0.0.1:5000" in top.plain # its host:port sits in the address column + assert _TCP_ICON in top.plain # marked with the network TYPE glyph + + +def test_device_picker_profile_yields_to_remembered_endpoint(tmp_path) -> None: + """A profile at an already-remembered endpoint doesn't double-list — the richer row wins.""" + from meshterm.core.config import DeviceProfile + from meshterm.core.device_store import DeviceStore + from meshterm.core.discovery import tcp_device + from meshterm.ui.device_picker import prompt_device + + store = DeviceStore(tmp_path / "devices.json") + # Confirmed before, so it carries the real node name learned at connect time. + store.remember(tcp_device("127.0.0.1", 5000), node_name="uConsole") + profiles = { + "bridge": DeviceProfile( + name="bridge", transport="tcp", host="127.0.0.1", tcp_port=5000 + ) + } + + captured: dict = {} + + class _Ui: + async def select_startup(self, title, items, *, default=None, banner=None, footnote=None): + captured["items"] = items + return None + + async def _never(_device): + raise AssertionError("verify should not run when selection is skipped") + + asyncio.run(prompt_device(_Ui(), [], store, _never, profiles)) + rows = [it.title for it in captured["items"] if isinstance(it, Choice)] + endpoint_rows = [r for r in rows if hasattr(r, "plain") and "127.0.0.1:5000" in r.plain] + assert len(endpoint_rows) == 1, "the endpoint should appear exactly once" + # The remembered node name wins over the bare profile alias. + assert "uConsole" in endpoint_rows[0].plain + assert "bridge" not in endpoint_rows[0].plain + + def test_device_picker_adds_network_device(tmp_path) -> None: """The 'add a network device' row prompts for host:port and confirms the TCP companion.""" from meshterm.core.device_store import DeviceStore