Chat offers to add Public instead of opening a channel the device lacks
When slot 0 was empty, the Chat picker showed a Public row that looked like a real channel, and every send on it failed with "the device has no contact with that key" (#36). The row is now an offer: Enter asks to add Public to slot 0, and the chat opens only after the write. The CLI lists only the channels on the device, and a refused channel send names the empty slot. Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6490f1ecd3
commit
888dc3b633
4 files changed
+171
-25
No files matched your search
@@ -4537,7 +4537,14 @@ class MeshCoreDevice(Device):
|
||||
) -> None:
|
||||
transmit_gate.mark()
|
||||
async with self.transmitting():
|
||||
self._ok(await self._require().commands.send_chan_msg(index, text))
|
||||
event = await self._require().commands.send_chan_msg(index, text)
|
||||
# For a channel send, "not found" is an empty slot, not a contact. The general
|
||||
# clause names a contact, which was the wrong lead in issue #36.
|
||||
if error_code(event) == 2:
|
||||
raise RuntimeError(
|
||||
f"device rejected the command: the device has no channel in slot {index}"
|
||||
)
|
||||
self._ok(event)
|
||||
|
||||
@staticmethod
|
||||
def _ok(event): # type: ignore[no-untyped-def]
|
||||
|
||||
@@ -917,6 +917,9 @@ class Conversation:
|
||||
secret: For channels: the 16-byte secret of the channel. MeshTerm uses it only to
|
||||
show the public or private mark of the channel. ``None`` when it is not known.
|
||||
contact: The contact, for direct conversations and rooms.
|
||||
on_device: For channels: ``False`` when the device has no such channel. The Chat
|
||||
picker shows the Public channel in this state when no slot has it. The row is
|
||||
an offer to add the channel, and it never opens a chat.
|
||||
"""
|
||||
|
||||
label: str
|
||||
@@ -925,6 +928,7 @@ class Conversation:
|
||||
channel_id: str | None = None
|
||||
secret: bytes | None = None
|
||||
contact: Contact | None = None
|
||||
on_device: bool = True
|
||||
|
||||
@property
|
||||
def peer(self) -> str | None:
|
||||
|
||||
+67
-24
@@ -177,6 +177,14 @@ class ChatTool(Tool):
|
||||
await self._delete_history(ctx, choice.value)
|
||||
elif choice is CANCEL or choice is None: # Esc: back to the menu
|
||||
return ToolResult(summary={"conversations": opened, "messages": shown})
|
||||
elif not choice.on_device:
|
||||
# A channel that the device does not have never opens: the device
|
||||
# refuses each send on it. Enter asks to add it. After a refusal, the
|
||||
# picker stays.
|
||||
added = await _add_public_channel(ctx)
|
||||
if added is not None:
|
||||
shown = await open_chat(ctx, added)
|
||||
opened += 1
|
||||
else:
|
||||
shown = await open_chat(ctx, choice)
|
||||
opened += 1
|
||||
@@ -623,23 +631,26 @@ def _enable_receive_debug() -> None:
|
||||
|
||||
|
||||
def _channels_from_slots(slots: list[ChannelSlot]) -> list[Conversation]:
|
||||
"""Change cached channel slots into channel conversations, and always offer Public (slot 0).
|
||||
"""Change cached channel slots into channel conversations, and offer Public if it is absent.
|
||||
|
||||
The picker reads its channels through the session cache
|
||||
(:meth:`~meshterm.services.device_state.DeviceState.channel_slots`). Thus it uses the one
|
||||
slow slot probe again, and does not read each slot again each time that Chat opens.
|
||||
This function maps that cached :class:`~meshterm.core.channel_probe.ChannelSlot` list
|
||||
onto the :class:`~meshterm.core.models.Conversation` rows of the picker. When the
|
||||
firmware reports no slot for channel 0 (the default public channel), this function
|
||||
makes one. Thus there is always a place to chat. :func:`_read_channels` (the CLI path)
|
||||
gives the same guarantee.
|
||||
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.
|
||||
|
||||
Args:
|
||||
slots: The configured channel slots, from the session cache.
|
||||
|
||||
Returns:
|
||||
One :class:`~meshterm.core.models.Conversation` for each slot, with Public at the
|
||||
start when slot 0 is absent.
|
||||
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.
|
||||
"""
|
||||
conversations = [
|
||||
Conversation(
|
||||
@@ -651,7 +662,9 @@ def _channels_from_slots(slots: list[ChannelSlot]) -> list[Conversation]:
|
||||
)
|
||||
for slot in slots
|
||||
]
|
||||
if not any(c.channel_idx == 0 for c in conversations):
|
||||
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(
|
||||
@@ -660,23 +673,60 @@ def _channels_from_slots(slots: list[ChannelSlot]) -> list[Conversation]:
|
||||
channel_idx=0,
|
||||
channel_id="slot:0",
|
||||
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.
|
||||
|
||||
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`).
|
||||
|
||||
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.
|
||||
|
||||
Raises:
|
||||
DeviceCommandError: If the device refused the write.
|
||||
"""
|
||||
from ..ui.channels import 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?",
|
||||
[("Cancel", False), ("Add", True)],
|
||||
title="Channel not on device",
|
||||
default=1,
|
||||
)
|
||||
if not add:
|
||||
return None
|
||||
device = await ctx.device()
|
||||
await write_channel(ctx, device, 0, "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)
|
||||
|
||||
|
||||
async def _read_channels(device: Device) -> list[Conversation]:
|
||||
"""Probe the channel slots, and return them as channel conversations.
|
||||
|
||||
This function always offers channel 0 (the default public channel), also when the
|
||||
firmware reports no configured slots. Thus there is always a place to chat.
|
||||
This function returns only the channels that are on the device. The device refuses a
|
||||
send on an empty slot. Thus a listed channel that is not on the device is a promise that
|
||||
fails at the first send (issue #36). ``channels join`` with the well-known key adds the
|
||||
Public channel.
|
||||
|
||||
Args:
|
||||
device: The connected device to probe.
|
||||
|
||||
Returns:
|
||||
One :class:`~meshterm.core.models.Conversation` for each configured channel (at
|
||||
least channel 0).
|
||||
One :class:`~meshterm.core.models.Conversation` for each configured channel.
|
||||
"""
|
||||
conversations: list[Conversation] = []
|
||||
for idx in range(CHANNEL_SLOT_PROBE_CAP):
|
||||
@@ -696,17 +746,6 @@ async def _read_channels(device: Device) -> list[Conversation]:
|
||||
secret=secret,
|
||||
)
|
||||
)
|
||||
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
|
||||
|
||||
|
||||
@@ -1003,7 +1042,11 @@ def _title(
|
||||
else:
|
||||
text.append(lane, style="muted")
|
||||
text.append(" ")
|
||||
if last is not None:
|
||||
if not conversation.on_device:
|
||||
# The preview lane explains the offer. Enter asks to add the channel (it never opens
|
||||
# a chat), so the text ends with the ellipsis of a row that opens a prompt.
|
||||
text.append("not on the device — Enter adds it…", style="muted")
|
||||
elif last is not None:
|
||||
text.append_text(_preview_text(last, key_of, name_of, us=us))
|
||||
return text
|
||||
|
||||
|
||||
@@ -3801,3 +3801,95 @@ def test_a_sender_with_no_key_opens_trace_target_under_its_name(monkeypatch) ->
|
||||
_trace_walk(_trace_ctx(), walk, contacts=[], label="Lindsay", node_type=NODE_TYPE_CHAT)
|
||||
)
|
||||
assert calls == [("target", "Lindsay", "3d,51,1b,40,1b,51,3d", "Lindsay", NODE_TYPE_CHAT)]
|
||||
|
||||
|
||||
# -- the Public offer (issue #36) ---------------------------------------------
|
||||
|
||||
|
||||
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
|
||||
from meshterm.tools.chat import _channels_from_slots
|
||||
|
||||
(offer,) = _channels_from_slots([])
|
||||
assert offer.label == "Public" and offer.channel_idx == 0 and not offer.on_device
|
||||
other = ChannelSlot(1, "#test", derive_secret("#test"))
|
||||
assert [c.on_device for c in _channels_from_slots([other])] == [False, True]
|
||||
|
||||
|
||||
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
|
||||
from meshterm.tools.chat import _channels_from_slots
|
||||
|
||||
on_two = _channels_from_slots([ChannelSlot(2, "Public", DEFAULT_PUBLIC_SECRET)])
|
||||
assert [(c.channel_idx, c.on_device) for c in on_two] == [(2, True)]
|
||||
on_zero = _channels_from_slots([ChannelSlot(0, "Public", DEFAULT_PUBLIC_SECRET)])
|
||||
assert [(c.channel_idx, c.on_device) for c in on_zero] == [(0, True)]
|
||||
|
||||
|
||||
def test_offer_row_says_the_channel_is_not_on_the_device(repo: Repository) -> None:
|
||||
"""The offer row explains itself in the preview lane, and shows no message preview."""
|
||||
from meshterm.tools.chat import _channels_from_slots
|
||||
|
||||
(offer,) = _channels_from_slots([])
|
||||
title = _title(_RowCtx(repo, unread={}), offer, {}, _NO_KEYS, _lanes([offer]))
|
||||
assert "not on the device — Enter adds it…" in title.plain
|
||||
|
||||
|
||||
class _OfferUi:
|
||||
def __init__(self, answer) -> None:
|
||||
self.answer = answer
|
||||
self.asked: list[str] = []
|
||||
|
||||
async def dialog(self, prompt, buttons, **_kw):
|
||||
self.asked.append(prompt)
|
||||
return self.answer
|
||||
|
||||
|
||||
class _OfferDevstate:
|
||||
def __init__(self) -> None:
|
||||
self.slots: list = []
|
||||
|
||||
async def channel_slots(self):
|
||||
return list(self.slots)
|
||||
|
||||
|
||||
def _offer_ctx(answer, monkeypatch: pytest.MonkeyPatch):
|
||||
from types import SimpleNamespace
|
||||
|
||||
from meshterm.core.channel_probe import ChannelSlot
|
||||
|
||||
writes: list[tuple] = []
|
||||
devstate = _OfferDevstate()
|
||||
|
||||
async def write_channel(ctx, device, idx, name, secret) -> None:
|
||||
writes.append((idx, name, secret))
|
||||
devstate.slots.append(ChannelSlot(idx, name, secret))
|
||||
|
||||
monkeypatch.setattr("meshterm.ui.channels.write_channel", write_channel)
|
||||
|
||||
async def device():
|
||||
return object()
|
||||
|
||||
ctx = SimpleNamespace(ui=_OfferUi(answer), devstate=devstate, device=device)
|
||||
return ctx, writes
|
||||
|
||||
|
||||
def test_public_offer_cancel_writes_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Cancel on the offer writes nothing and opens nothing: the picker stays."""
|
||||
from meshterm.tools.chat import _add_public_channel
|
||||
|
||||
ctx, writes = _offer_ctx(False, monkeypatch)
|
||||
assert asyncio.run(_add_public_channel(ctx)) is None
|
||||
assert ctx.ui.asked and writes == []
|
||||
|
||||
|
||||
def test_public_offer_add_writes_slot_zero(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Add writes Public with its well-known key to slot 0, and returns the real channel."""
|
||||
from meshterm.tools.chat import _add_public_channel
|
||||
|
||||
ctx, writes = _offer_ctx(True, monkeypatch)
|
||||
added = asyncio.run(_add_public_channel(ctx))
|
||||
assert writes == [(0, "Public", DEFAULT_PUBLIC_SECRET)]
|
||||
assert added is not None and added.on_device and added.channel_idx == 0
|
||||
Reference in new issue
Block a user