diff --git a/meshterm/core/preferences.py b/meshterm/core/preferences.py index b072df9..a6a269b 100644 --- a/meshterm/core/preferences.py +++ b/meshterm/core/preferences.py @@ -305,6 +305,20 @@ PREFERENCES: tuple[PrefSpec, ...] = ( # meshterm.services.site_suggest. default=True, ), + PrefSpec( + key="public_on_empty_device", + label="Public on an empty radio", + help="Add the standard Public channel to a radio that has none", + group="Device", + value_type="bool", + # On: a radio with no channel at all cannot send anywhere (each send needs a slot), + # and a new user reads an empty Chat as "nobody is here". MeshTerm writes the + # channel that MeshCore itself ships, on slot 0 at startup, and says so. The write + # overwrites nothing, because the device had no channel. Off: nothing is written, + # and the Chat picker still offers Public on its own. Refer to + # meshterm.ui.public_default. + default=True, + ), # --- Sending ----------------------------------------------------------------- PrefSpec( key="trace_cooldown_s", diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index 87189ef..3ed9502 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -1114,6 +1114,13 @@ async def _startup(ctx: AppContext) -> bool: from .settings_offer import offer_remembered_settings await offer_remembered_settings(ctx) + # A device with no channel at all cannot send anywhere. Give it the standard Public + # channel, and say so. This step runs last, so that the replay of the remembered + # channels (at connect) and the settings offer are both done, and a device that forgot + # its own channels has them back before this step counts them. + from .public_default import add_public_when_empty + + await add_public_when_empty(ctx) return True diff --git a/meshterm/ui/public_default.py b/meshterm/ui/public_default.py new file mode 100644 index 0000000..8cd5361 --- /dev/null +++ b/meshterm/ui/public_default.py @@ -0,0 +1,131 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Add the standard Public channel at startup to a device that has no channels. + +A MeshCore companion ships with the standard ``Public`` channel on slot 0. A device that +arrives with **no channel at all** cannot send to anybody: each send needs a slot, and the +device refuses a send on a slot that it does not have (issue #36). A new user does not know +this. The user reads an empty Chat picker as "nobody is here", and not as "this radio has +no channel". + +Thus MeshTerm gives such a device the standard Public channel at startup, on slot 0, and +says what it did (JP, 2026-11-22). It does not ask. The channel is the one that MeshCore +itself ships, its key is well known, and the device had nothing to lose: the write +overwrites nothing. This is the same judgment as the position that MeshTerm restores +silently (refer to :mod:`meshterm.ui.settings_offer`): an empty slot is not a value that +competes. + +The step is one preference (``public_on_empty_device``, on by default). A user who wants a +radio with no channel turns it off, and then nothing is written. The Chat picker still +offers Public there, because that offer only asks (refer to +:func:`meshterm.tools.chat._add_public_channel`). + +The step is quiet and cheap. It reads slot 0 first, and a channel there ends the step after +one round trip. Thus a device that has channels pays almost nothing at each startup. Only a +device whose slot 0 is empty pays the full slot probe. + +The step runs after the replay of the remembered channels (refer to +:meth:`meshterm.context.AppContext._reconcile_channels`). Thus a device that forgot its +channels gets its own channels back first, and this step sees them. + +The simulator is the one device that the step passes over. It is not a radio, it keeps +nothing between launches, and it starts with no channel each time. Thus the step would +write and give its card at each ``--mock`` launch, which is each launch of the development +loop and of the emulator. The simulator instead shows the other half of the same feature: +the Chat picker offers Public on its own (refer to +:func:`meshterm.tools.chat._add_public_channel`). +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from rich.text import Text + +from ..core.channels import DEFAULT_PUBLIC_SECRET + +if TYPE_CHECKING: + from ..context import AppContext + from ..core.connection import Device + +#: The slot that the new channel goes into. The device had no channel, so slot 0 is free, +#: and slot 0 is where the firmware itself keeps Public. +PUBLIC_SLOT = 0 + + +async def _has_a_channel(ctx: AppContext, device: Device) -> bool: + """Whether the device has any channel at all, and whether that answer is proved. + + The function reads slot 0 by itself first, because a channel there answers the question + with one round trip. A full probe of the slots follows only for an empty slot 0. + + An unproved answer counts as "it has a channel". A probe that stopped because a read + failed returns a short list, and an empty short list looks exactly the same as a device + with no channels (refer to + :func:`~meshterm.core.channel_probe.probe_channel_slots`). MeshTerm must not write to a + device on that evidence. + + Args: + ctx: The shared application context, for the log. + device: The connected device. + + Returns: + ``True`` if the device has a channel, or if the code could not prove that it has + none. + """ + from ..core.channel_probe import probe_channel_slots + + try: + first = await device.get_channel(PUBLIC_SLOT) + except Exception as exc: # noqa: BLE001 - a read that failed proves nothing + ctx.log.debug("channels: could not read slot %s at startup: %s", PUBLIC_SLOT, exc) + return True + if first and first.get("channel_name"): + return True + slots, complete = await probe_channel_slots(device) + if not complete: + ctx.log.debug("channels: the slot probe did not finish, so the startup step stops") + return True + return bool(slots) + + +async def add_public_when_empty(ctx: AppContext) -> bool: + """Give a device with no channels the standard Public channel, and say so. + + The function does its best only, and it is quiet. It does nothing in these cases: the + preference is off, the simulator, no live link, a device that has a channel, or a probe + that could not prove that the device has none. It never opens the radio itself. A deferred connect + (``connect_on_start`` off) skips the function, because ``is_connected`` is false. A + failure here must not stop the user from reaching the menu, so the function guards each + step. + + Args: + ctx: The shared application context. + + Returns: + ``True`` if the function wrote the channel. + """ + from .channels import write_channel + from .logo import load_logo + + if not ctx.preferences.public_on_empty_device: + return False + if ctx.mock or not ctx.is_connected: + return False + try: + device = await ctx.device() + if await _has_a_channel(ctx, device): + return False + await write_channel(ctx, device, PUBLIC_SLOT, "Public", DEFAULT_PUBLIC_SECRET) + except Exception as exc: # noqa: BLE001 - a startup step must not stop the menu + ctx.log.debug("channels: could not add Public at startup: %s", exc) + return False + ctx.log.info("channels: added the standard Public channel to slot %s", PUBLIC_SLOT) + notice = Text.assemble( + ("This radio had no channel, so it could not send anywhere.\n", ""), + ("MeshTerm added ", ""), + ("Public", "accent"), + (f" to slot {PUBLIC_SLOT}: MeshCore's built-in meshwide channel.\n", ""), + ("Chat opens it. Preferences can turn this step off.", "muted"), + ) + await ctx.ui.notify_startup(notice, title="Public channel added", banner=load_logo()) + return True diff --git a/tests/test_channels.py b/tests/test_channels.py index 3e6d619..7db9d66 100644 --- a/tests/test_channels.py +++ b/tests/test_channels.py @@ -514,6 +514,8 @@ class _ScriptedUi: self._selects = list(selects) self._texts = list(texts) self._dialogs = list(dialogs) + self.asked: list[str] = [] + self.notices: list[str] = [] def show(self, *renderables) -> None: # noqa: ANN002 pass @@ -557,8 +559,20 @@ class _ScriptedUi: danger: bool = False, destructive: bool = False, ): + self.asked.append(prompt.plain if hasattr(prompt, "plain") else str(prompt)) return self._dialogs.pop(0) + async def notify_startup( # noqa: ANN201 + self, + renderable, # noqa: ANN001 + *, + title: str = "", + banner=None, # noqa: ANN001 + footnote: str | None = None, + ): + plain = renderable.plain if hasattr(renderable, "plain") else str(renderable) + self.notices.append(f"{title}: {plain}") + async def test_recreating_a_slot_refiles_messages_to_the_new_channel(ctx: AppContext) -> None: """If a channel is cleared and another channel uses its slot, the histories must not mix. @@ -1361,3 +1375,191 @@ async def test_a_reorder_that_breaks_partway_says_so(ctx: AppContext) -> None: device.set_channel = flaky # type: ignore[method-assign] assert await _reorder_channels(ctx, device, slots) == 0 # not counted as a complete reorder assert said and "reorder stopped partway" in said[0] + + +# -- the name that says Public (the #Public trap) ------------------------------ + + +async def test_the_name_public_offers_the_standard_channel_instead(ctx: AppContext) -> None: + """``Public`` typed as a # name asks again, and the answer can write the real channel. + + ``#Public`` is a different channel: its key comes from its name, so no other node is on + it. A user who made it by mistake had a channel that sent with no error and that nobody + heard. + """ + from meshterm.ui.channels import _add_public + + device = await ctx.device() + ctx.ui = _ScriptedUi(selects=[], texts=["Public"], dialogs=["standard"]) + assert await _add_public(ctx, device, [], 8) == 1 + (slot,) = await read_channel_slots(device) + assert (slot.idx, slot.name, slot.secret) == (0, "Public", DEFAULT_PUBLIC_SECRET) + assert ctx.ui.asked and "is not the standard Public channel" in ctx.ui.asked[0] + + +async def test_the_name_public_can_still_be_used_on_purpose(ctx: AppContext) -> None: + """The question does not refuse the name. A user who wants ``#Public`` can have it.""" + from meshterm.ui.channels import _add_public + + device = await ctx.device() + ctx.ui = _ScriptedUi(selects=[], texts=["Public"], dialogs=["named"]) + assert await _add_public(ctx, device, [], 8) == 1 + (slot,) = await read_channel_slots(device) + assert slot.name == "#Public" and slot.secret != DEFAULT_PUBLIC_SECRET + + +async def test_cancel_on_the_public_question_writes_nothing(ctx: AppContext) -> None: + """Cancel on the question leaves the slot as it was.""" + from meshterm.ui.channels import _add_public + + device = await ctx.device() + ctx.ui = _ScriptedUi(selects=[], texts=["#public"], dialogs=[None]) + assert await _add_public(ctx, device, [], 8) == 0 + assert await read_channel_slots(device) == [] + + +async def test_any_other_public_name_asks_nothing(ctx: AppContext) -> None: + """Only the one name that names the standard channel asks again. + + The scripted UI has no dialog to give. Thus a question here would raise. + """ + from meshterm.ui.channels import _add_public + + device = await ctx.device() + ctx.ui = _ScriptedUi(selects=[], texts=["yul"], dialogs=[]) + assert await _add_public(ctx, device, [], 8) == 1 + (slot,) = await read_channel_slots(device) + assert slot.name == "#yul" + + +async def test_the_question_says_where_the_standard_public_already_is(ctx: AppContext) -> None: + """With the real Public on the device, the question names its slot and offers no copy.""" + from meshterm.ui.channels import _add_public + + device = await ctx.device() + await device.set_channel(2, "Public", DEFAULT_PUBLIC_SECRET) + slots = list(await read_channel_slots(device)) + ctx.ui = _ScriptedUi(selects=[], texts=["Public"], dialogs=[None]) + assert await _add_public(ctx, device, slots, 8) == 0 + assert "already on slot 2" in ctx.ui.asked[0] + + +# -- the Public channel of a device that has none ------------------------------ + + +def _as_a_radio(ctx: AppContext) -> None: + """Let the startup step act, which it does not do on the simulator. + + The step passes over ``--mock``, because that device starts with no channel at each + launch (refer to :mod:`meshterm.ui.public_default`). These tests are about a real radio + with no channel, and the simulator is what stands in for it. + """ + ctx.mock = False + + +async def test_a_device_with_no_channel_gets_public_at_startup(ctx: AppContext) -> None: + """A radio with no channel at all cannot send. MeshTerm gives it Public, and says so.""" + from meshterm.ui.public_default import add_public_when_empty + + await ctx.device() # open the link, so that the step has one to use + _as_a_radio(ctx) + ctx.ui = _ScriptedUi(selects=[], texts=[], dialogs=[]) + assert await add_public_when_empty(ctx) is True + (slot,) = await read_channel_slots(await ctx.device()) + assert (slot.idx, slot.name, slot.secret) == (0, "Public", DEFAULT_PUBLIC_SECRET) + assert ctx.ui.notices and "Public channel added" in ctx.ui.notices[0] + + +async def test_a_device_that_has_a_channel_is_left_alone(ctx: AppContext) -> None: + """One channel is enough. The step then reads slot 0 only, and writes nothing.""" + from meshterm.ui.public_default import add_public_when_empty + + device = await ctx.device() + await device.set_channel(0, "#yul", None) + reads: list[int] = [] + real = device.get_channel + + async def counted(idx: int): # noqa: ANN202 + reads.append(idx) + return await real(idx) + + device.get_channel = counted # type: ignore[method-assign] + _as_a_radio(ctx) + ctx.ui = _ScriptedUi(selects=[], texts=[], dialogs=[]) + assert await add_public_when_empty(ctx) is False + assert reads == [0] # one round trip, at each startup of a device with channels + assert ctx.ui.notices == [] + + +async def test_a_device_with_channels_above_slot_zero_is_left_alone(ctx: AppContext) -> None: + """An empty slot 0 is not an empty device. The step counts each slot before it writes.""" + from meshterm.ui.public_default import add_public_when_empty + + device = await ctx.device() + await device.set_channel(3, "#yul", None) + _as_a_radio(ctx) + ctx.ui = _ScriptedUi(selects=[], texts=[], dialogs=[]) + assert await add_public_when_empty(ctx) is False + assert [s.idx for s in await read_channel_slots(device)] == [3] + + +async def test_a_probe_that_did_not_finish_writes_nothing(ctx: AppContext) -> None: + """A read that failed proves nothing: an empty short list looks like an empty device.""" + from meshterm.core.connection import DeviceCommandError + from meshterm.ui.public_default import add_public_when_empty + + device = await ctx.device() + real = device.get_channel + + async def flaky(idx: int): # noqa: ANN202 + if idx == 0: + return await real(idx) # empty, and that much is true + raise DeviceCommandError("no reply in time") + + device.get_channel = flaky # type: ignore[method-assign] + _as_a_radio(ctx) + ctx.ui = _ScriptedUi(selects=[], texts=[], dialogs=[]) + assert await add_public_when_empty(ctx) is False + device.get_channel = real # type: ignore[method-assign] + assert await read_channel_slots(device) == [] + + +async def test_the_startup_step_never_opens_the_radio(ctx: AppContext) -> None: + """With no live link, the step does nothing at all: it never connects to write.""" + from meshterm.ui.public_default import add_public_when_empty + + _as_a_radio(ctx) + ctx.ui = _ScriptedUi(selects=[], texts=[], dialogs=[]) + assert ctx.is_connected is False + assert await add_public_when_empty(ctx) is False + assert ctx.is_connected is False + + +async def test_the_preference_turns_the_step_off(ctx: AppContext) -> None: + """A user who wants a radio with no channel turns the preference off. + + The Chat picker still offers Public there, because that offer only asks. + """ + from meshterm.ui.public_default import add_public_when_empty + + device = await ctx.device() + _as_a_radio(ctx) + ctx.preferences.set("public_on_empty_device", False) + ctx.ui = _ScriptedUi(selects=[], texts=[], dialogs=[]) + assert await add_public_when_empty(ctx) is False + assert await read_channel_slots(device) == [] + + +async def test_the_simulator_is_passed_over(ctx: AppContext) -> None: + """``--mock`` starts with no channel at each launch, so the step leaves it alone. + + Without this, each launch of the development loop and of the emulator wrote a channel + and stopped on a card. + """ + from meshterm.ui.public_default import add_public_when_empty + + device = await ctx.device() + assert ctx.mock is True + ctx.ui = _ScriptedUi(selects=[], texts=[], dialogs=[]) + assert await add_public_when_empty(ctx) is False + assert await read_channel_slots(device) == []