From 66ffae49f683d069872c42dcb90cfd276231aea0 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sun, 22 Nov 2026 00:39:35 -0500 Subject: [PATCH] The name Public asks again, and the Public offer reads the key #Public is not the standard Public channel: its key comes from its name, so its hash differs and no other node is on it. But the two add rows sit side by side, and Public is the obvious word to type into "Public channel name:". A user who did that got a channel that looked right in every list, that sent with no error, and that nobody heard. Two halves of the same hole. The name now asks again and offers the standard channel instead, without refusing the name. And the Chat picker's offer no longer waits for slot 0 to be empty: the well-known key decides, not the slot, so a #Public in slot 0 cannot hide the one way back to the real channel. The offer names the lowest free slot, and the add confirms that slot against the real capacity before it writes. Co-Authored-By: Claude Opus 5 --- meshterm/tools/chat.py | 79 +++++++++++++++++++++++++++-------------- meshterm/ui/channels.py | 79 ++++++++++++++++++++++++++++++++++++----- tests/test_chat.py | 54 +++++++++++++++++++++++++++- 3 files changed, 176 insertions(+), 36 deletions(-) diff --git a/meshterm/tools/chat.py b/meshterm/tools/chat.py index 0ff0bfa..a059fa9 100644 --- a/meshterm/tools/chat.py +++ b/meshterm/tools/chat.py @@ -31,6 +31,7 @@ from ..core import exitcodes, mcoimg from ..core.channels import ( CHANNEL_SLOT_PROBE_CAP, DEFAULT_PUBLIC_SECRET, + MAX_CHANNELS, MENTION, channel_hash, channel_identity, @@ -643,18 +644,24 @@ def _channels_from_slots(slots: list[ChannelSlot]) -> list[Conversation]: This function maps that cached :class:`~meshterm.core.channel_probe.ChannelSlot` list onto the :class:`~meshterm.core.models.Conversation` rows of the picker. - When slot 0 is empty and no slot has the Public channel, this function adds a Public row - with ``on_device=False``. The device cannot send on a slot that it does not have: it - refuses the send. Thus that row never opens a chat. It is an offer: Enter asks to add - Public to slot 0 (refer to :func:`_add_public_channel`). Issue #36 was a row that looked - the same as a real channel and failed on each send. + When no slot has the Public channel, this function adds a Public row with + ``on_device=False``, on the lowest free slot. The device cannot send on a slot that it + does not have: it refuses the send. Thus that row never opens a chat. It is an offer: + Enter asks to add Public (refer to :func:`_add_public_channel`). Issue #36 was a row + that looked the same as a real channel and failed on each send. + + The offer asks only for the key of the channel, and not for slot 0. A user who made a + ``#Public`` channel by mistake (its key comes from its name, so it is a different + channel that nobody else is on) filled slot 0 with it. The offer then disappeared, + which hid the one way back to the real channel. The name of a slot proves nothing: only + the well-known key does. Args: slots: The configured channel slots, from the session cache. Returns: One :class:`~meshterm.core.models.Conversation` for each slot. A Public offer is at - the start when the device has no Public channel and slot 0 is empty. + the start when the device has no Public channel and a slot is free for it. """ conversations = [ Conversation( @@ -666,46 +673,56 @@ def _channels_from_slots(slots: list[ChannelSlot]) -> list[Conversation]: ) for slot in slots ] - if not any(c.channel_idx == 0 for c in conversations) and not any( - slot.secret == DEFAULT_PUBLIC_SECRET for slot in slots - ): - conversations.insert( - 0, - Conversation( - label="Public", - is_channel=True, - channel_idx=0, - channel_id="slot:0", - secret=DEFAULT_PUBLIC_SECRET, - on_device=False, - ), - ) + if not any(slot.secret == DEFAULT_PUBLIC_SECRET for slot in slots): + # The slot that the row names is the lowest one that no channel uses. The capacity + # of the device is not read here: that probe is a round trip, and this function runs + # at each paint of the picker. The add confirms the slot against the real capacity + # (refer to :func:`_add_public_channel`), and says so if there is no slot to give. + used = {slot.idx for slot in slots} + free = next((i for i in range(MAX_CHANNELS) if i not in used), None) + if free is not None: + conversations.insert( + 0, + Conversation( + label="Public", + is_channel=True, + channel_idx=free, + channel_id=f"slot:{free}", + secret=DEFAULT_PUBLIC_SECRET, + on_device=False, + ), + ) return conversations async def _add_public_channel(ctx: AppContext) -> Conversation | None: - """Ask to add the Public channel to slot 0. Write it if the user agrees. + """Ask to add the Public channel to a free slot. Write it if the user agrees. The Chat picker calls this function for its Public offer (``on_device=False``, refer to :func:`_channels_from_slots`). The function asks first and does not write silently, because the write changes what the device stores. The precedent is the contact that is not on the device (refer to :func:`meshterm.ui.chat._restore_contact`). + The slot comes from :func:`~meshterm.ui.channels._pick_free_slot`, which the channel + manager uses for each add. Thus the capacity of the device sets the slot, and the slot + is read one more time before the write. A cached slot list can be short (a probe that + stopped in the middle), and a slot that the probe did not reach must not be overwritten. + Args: ctx: The shared application context. Returns: The conversation of the Public channel on the device, ready to open. ``None`` if the - user cancelled, or if the probe after the write does not find the channel. + user cancelled, if no slot is free, or if the probe after the write does not find + the channel. Raises: DeviceCommandError: If the device refused the write. """ - from ..ui.channels import write_channel + from ..ui.channels import _pick_free_slot, write_channel add = await ctx.ui.dialog( - "This device has no Public channel, so it can't send there. " - "Add Public to slot 0 and open it?", + "This device has no Public channel, so it can't send there. Add Public and open it?", [("Cancel", False), ("Add", True)], title="Channel not on device", default=1, @@ -713,9 +730,17 @@ async def _add_public_channel(ctx: AppContext) -> Conversation | None: if not add: return None device = await ctx.device() - await write_channel(ctx, device, 0, "Public", DEFAULT_PUBLIC_SECRET) + slots = await ctx.devstate.channel_slots() + idx = await _pick_free_slot(ctx, device, slots, await ctx.devstate.channel_capacity()) + if idx is None: # full, or the slot could not be read: _pick_free_slot said why + return None + await write_channel(ctx, device, idx, "Public", DEFAULT_PUBLIC_SECRET) channels = _channels_from_slots(await ctx.devstate.channel_slots()) - return next((c for c in channels if c.on_device and c.channel_idx == 0), None) + # The key identifies the channel, and not the slot: the write went to the slot that the + # confirming read gave, which can be another slot than the one that the row named. + return next( + (c for c in channels if c.on_device and c.secret == DEFAULT_PUBLIC_SECRET), None + ) async def _read_channels(device: Device) -> list[Conversation]: diff --git a/meshterm/ui/channels.py b/meshterm/ui/channels.py index aa3b9c5..baf3bcd 100644 --- a/meshterm/ui/channels.py +++ b/meshterm/ui/channels.py @@ -77,6 +77,7 @@ from ..core.channel_file import ( ) from ..core.channel_probe import ChannelSlot, probe_channel_slots from ..core.channels import ( + DEFAULT_PUBLIC_NAME, DEFAULT_PUBLIC_SECRET, MAX_CHANNELS, derive_secret, @@ -1181,23 +1182,85 @@ async def _add_default_public( return 1 -async def _add_public( - ctx: AppContext, device: Device, slots: list[ChannelSlot], capacity: int -) -> int: - """Create a public channel. The key comes from its name, which starts with ``#``.""" - idx = await _pick_free_slot(ctx, device, slots, capacity) - if idx is None: - return 0 +async def _ask_public_name(ctx: AppContext, slots: list[ChannelSlot]) -> tuple[str, bool] | None: + """Ask for the name of a public channel, and ask again when the name says ``Public``. + + The built-in Public channel of MeshCore has a fixed key that does not come from its name + (:data:`~meshterm.core.channels.DEFAULT_PUBLIC_SECRET`). Thus ``#Public`` is **not** that + channel. Its key comes from its name, its hash is different, and no other node is on it. + But the two rows that add a channel are beside each other in the menu, and ``Public`` is + the obvious word to type for the name of a public channel. A user who did this got a + channel that looked correct, that sent with no error, and that nobody heard. + + Thus this name gets a question. The question does not refuse the name: a user who wants + ``#Public`` can have it. It offers the standard channel instead, which is what the user + almost always wanted, and it says where that channel already is when a slot has it. + + Args: + ctx: The shared application context. + slots: The slots as they were last read, to find the standard Public channel. + + Returns: + The name to write, and whether the name derives the key (``False`` for the standard + Public channel, which carries its own fixed key). ``None`` if the user cancelled. + """ raw = await ctx.ui.text( "Public channel name:", help_text="A leading # is added automatically; the key is derived from the name", validate=_nonblank, ) if not raw: - return 0 + return None name = raw.strip() if not name.startswith("#"): name = f"#{name}" + if name.lstrip("#").casefold() != DEFAULT_PUBLIC_NAME: + return name, True + warning = ( + f"{name} is not the standard Public channel. Its key comes from its name, " + "so no other node is on that channel." + ) + here = next((slot for slot in slots if slot.secret == DEFAULT_PUBLIC_SECRET), None) + if here is not None: # nothing to offer: the real channel is already on the device + answer = await ctx.ui.dialog( + Text(f"{warning} The standard Public is already on slot {here.idx}.", style="warn"), + [("Cancel", None), (name, "named")], + title="Not the standard Public", + default=1, + danger=True, + ) + return (name, True) if answer == "named" else None + answer = await ctx.ui.dialog( + Text(f"{warning} The standard Public channel has one fixed key.", style="warn"), + [("Cancel", None), (name, "named"), ("Standard", "standard")], + title="Not the standard Public", + default=2, + danger=True, + ) + if answer == "standard": + return "Public", False + return (name, True) if answer == "named" else None + + +async def _add_public( + ctx: AppContext, device: Device, slots: list[ChannelSlot], capacity: int +) -> int: + """Create a public channel. The key comes from its name, which starts with ``#``. + + The name ``Public`` is the one name that asks again, because it names another channel + than the one that the user means (refer to :func:`_ask_public_name`). The answer can + write the standard Public channel on the slot instead. + """ + idx = await _pick_free_slot(ctx, device, slots, capacity) + if idx is None: + return 0 + chosen = await _ask_public_name(ctx, slots) + if chosen is None: + return 0 + name, derived = chosen + if not derived: # the standard Public channel, which carries its own well-known key + await write_channel(ctx, device, idx, name, DEFAULT_PUBLIC_SECRET) + return 1 secret = derive_secret(name) # what the firmware will calculate. It is for the QR and share await write_channel(ctx, device, idx, name, None) # None: the firmware derives the key await _show_share(ctx, name, secret) diff --git a/tests/test_chat.py b/tests/test_chat.py index be31422..6a66357 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -10,6 +10,7 @@ from __future__ import annotations import asyncio import logging import re +from contextlib import asynccontextmanager from pathlib import Path from types import SimpleNamespace @@ -4116,6 +4117,17 @@ def test_a_sender_with_no_key_opens_trace_target_under_its_name(monkeypatch) -> # -- the Public offer (issue #36) --------------------------------------------- +@asynccontextmanager +async def _nothing(): + """A busy dialog that draws nothing, for the fake UI of the offer tests.""" + yield + + +async def _empty_slot(_idx: int) -> dict: + """A slot read that proves the slot is free.""" + return {} + + def test_picker_offers_public_when_the_device_has_none() -> None: """With no Public on the device, the picker offers it on slot 0, as a row that is not on it.""" from meshterm.core.channel_probe import ChannelSlot @@ -4127,6 +4139,34 @@ def test_picker_offers_public_when_the_device_has_none() -> None: assert [c.on_device for c in _channels_from_slots([other])] == [False, True] +def test_picker_offers_public_when_another_channel_holds_slot_zero() -> None: + """A full slot 0 does not hide the offer. The key of the channel decides, not the slot. + + A user who made ``#Public`` by mistake (a different channel, whose key comes from its + name) filled slot 0 with it. The offer then disappeared, which hid the one way back to + the real channel. + """ + from meshterm.core.channel_probe import ChannelSlot + from meshterm.tools.chat import _channels_from_slots + + wrong = ChannelSlot(0, "#Public", derive_secret("#Public")) + rows = _channels_from_slots([wrong]) + assert [(c.label, c.channel_idx, c.on_device) for c in rows] == [ + ("Public", 1, False), # the offer, on the lowest free slot + ("#Public", 0, True), + ] + + +def test_picker_has_no_offer_when_each_slot_is_full() -> None: + """With no free slot, the offer has nowhere to go, so the picker does not show it.""" + from meshterm.core.channel_probe import ChannelSlot + from meshterm.core.channels import MAX_CHANNELS + from meshterm.tools.chat import _channels_from_slots + + full = [ChannelSlot(i, f"#c{i}", derive_secret(f"#c{i}")) for i in range(MAX_CHANNELS)] + assert all(c.on_device for c in _channels_from_slots(full)) + + def test_picker_has_no_offer_when_public_is_on_the_device() -> None: """A Public channel on any slot is the real row. The picker adds no second Public.""" from meshterm.core.channel_probe import ChannelSlot @@ -4151,11 +4191,18 @@ class _OfferUi: def __init__(self, answer) -> None: self.answer = answer self.asked: list[str] = [] + self.session = None async def dialog(self, prompt, buttons, **_kw): self.asked.append(prompt) return self.answer + def busy_dialog(self, *_a, **_kw): + return _nothing() + + def note(self, *_a, **_kw) -> None: + return None + class _OfferDevstate: def __init__(self) -> None: @@ -4164,6 +4211,9 @@ class _OfferDevstate: async def channel_slots(self): return list(self.slots) + async def channel_capacity(self): + return 8 + def _offer_ctx(answer, monkeypatch: pytest.MonkeyPatch): from types import SimpleNamespace @@ -4180,7 +4230,9 @@ def _offer_ctx(answer, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr("meshterm.ui.channels.write_channel", write_channel) async def device(): - return object() + # _pick_free_slot reads the slot one more time before it writes. An empty answer + # proves that the slot is free. + return SimpleNamespace(get_channel=_empty_slot) ctx = SimpleNamespace(ui=_OfferUi(answer), devstate=devstate, device=device) return ctx, writes