From 23865e6c9a70991feb2fe24b27c76b32f79f1da2 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sun, 30 Aug 2026 17:53:08 -0400 Subject: [PATCH] Chat keeps one conversation list for the whole visit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Backing out of a thread already landed on the picker rather than the menu, but on a brand-new one: the tool re-ran the whole picker each round and put the cursor back with a default= restore, which recovers the cursor alone and only while the row it names still exists. Anything typed to narrow the list was gone every time, and the screen was rebuilt around two devstate reads. The picker moves into the tool's own loop and stays pushed, so a chat nests above it and Esc is one pop onto the row it was opened from — filter, scroll and all. The row builder splits out as _picker_items, and the rows are swapped in place after every chat and every delete: an exchange moves its thread up the recency order and a deleted history hollows its dot and demotes the row, so the list has to be re-read, and replace_items follows the highlighted thread there. The picker tests now read _picker_items directly rather than intercepting a select() call, and the two Del tests drive _delete_history and assert the rebuilt row demotes — the same coverage, one layer down from the loop. Co-Authored-By: Claude Opus 5 (1M context) --- meshterm/tools/chat.py | 224 +++++++++++++++++++++-------------------- tests/test_chat.py | 154 ++++++++++++++++------------ 2 files changed, 201 insertions(+), 177 deletions(-) diff --git a/meshterm/tools/chat.py b/meshterm/tools/chat.py index 2a0833f..8b16b8c 100644 --- a/meshterm/tools/chat.py +++ b/meshterm/tools/chat.py @@ -62,19 +62,19 @@ class ChatTool(Tool): order = 10 async def prompt_params(self, ctx: AppContext) -> Optional[dict[str, Any]]: - """Show the conversation picker and return the chosen thread to open. + """Nothing to gather here — the conversation picker lives inside :meth:`run`. + + The picker has to *stay pushed* while a chat runs, so backing out of a thread lands + on the very list it was opened from — same cursor, same typed filter. A prompt + gathered here would resolve, and pop, before the tool ran. Args: ctx: Shared application context. Returns: - ``{"conversation": Conversation}`` for the chosen thread, or ``None`` if the - user backed out. + ``{"live": True}`` — the menu's marker for the interactive path. """ - conversation = await self._pick_conversation(ctx) - if conversation is None: - return None - return {"conversation": conversation} + return {"live": True} async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: """Open a live chat (menu) or perform a scripted messaging action (CLI). @@ -89,128 +89,130 @@ class ChatTool(Tool): action = params.get("cli_action") if action is not None: return await self._run_cli(ctx, action, params) - - conversation: Optional[Conversation] = params.get("conversation") - if conversation is None: # pragma: no cover - prompt_params returns None to cancel - return ToolResult(summary={}) - - from ..ui.chat import open_chat - - # Loop picker ↔ chat so backing out of a conversation (Esc) steps back to the - # picker rather than all the way to the main menu; Esc from the picker ends the - # loop and returns to the menu. The just-closed conversation is pre-selected in - # the picker so the cursor lands where the user left. - opened = 0 - shown = 0 - while conversation is not None: - shown = await open_chat(ctx, conversation) - opened += 1 - conversation = await self._pick_conversation(ctx, default_key=conversation.key) - return ToolResult(summary={"conversations": opened, "messages": shown}) + return await self._run_live(ctx) # -- interactive picker ----------------------------------------------------- - async def _pick_conversation( - self, ctx: AppContext, *, default_key: Optional[str] = None - ) -> Optional[Conversation]: - """Let the user pick a channel or contact to chat with. + async def _run_live(self, ctx: AppContext) -> ToolResult: + """Keep the conversation picker pushed and open chats above it until it is left. + + One screen for the whole visit, so backing out of a thread lands on the row it was + opened from with the typed filter still narrowing the list. The picker used to be + rebuilt from scratch each round and the cursor put back by a ``default=`` restore, + which recovers the cursor alone — and only while the row it names still exists. + + The rows *are* data: an exchange moves its thread up the recency order, and deleting + a history hollows its dot and demotes the row to the alphabetical tail. So they are + re-read and swapped in place after each chat and each delete, which follows the + highlighted thread wherever it moved to. Args: ctx: Shared application context. - default_key: Conversation key to pre-highlight (e.g. the one just backed out - of), so the cursor lands there rather than at the top. Returns: - The chosen :class:`~meshterm.core.models.Conversation`, or ``None`` if - cancelled. + A :class:`ToolResult` counting the conversations opened and the messages the + last one showed. """ - while True: - # Through the session cache: this picker runs on every Chat open, and its two - # reads — the channel-slot probe and the contacts table — are the two slowest - # round-trips on a companion. Reading them from the device each time is what made - # opening Chat stall for seconds (the cached chat screen behind it never got the - # chance to help). The cache holds channels until the channel editor writes a - # slot and refreshes contacts in the background (see - # :class:`~meshterm.services.device_state.DeviceState`). - channels = _channels_from_slots(await ctx.devstate.channel_slots()) - contacts = await ctx.devstate.contacts() - # Only companion nodes are listed — we don't DM repeaters, rooms, or sensors; - # a contact whose type was never advertised gets the benefit of the doubt (the - # app-wide DM rule, see is_direct_messageable). - companions = [c for c in contacts if is_direct_messageable(c.node_type)] - # A stable snapshot orders the rows (so the list doesn't reshuffle under the - # cursor), while a self-refreshing view feeds each row's live preview - # (see _LiveLasts). - lasts = ctx.repo.last_chat_messages() - live = _LiveLasts(ctx, seed=lasts) - # Names in previews/mentions resolve back to keys for their hue (the app-wide - # colour rule); a name no contact or stored advert carries stays muted. - key_of = make_name_key_resolver(contacts, ctx.repo.node_names()) + from ..ui.chat import open_chat + from ..ui.tui import SelectScreen + from ..ui.tui.screen import CANCEL - # The lane names pin for the whole picker (they mean the same in both groups), - # so scrolling into Direct keeps them overhead with that group's heading under - # them, instead of the header vanishing one row in — see Screen.sticky_rows. - items: list = [ - Separator(_picker_header, pinned=True), - section_heading("📡 Channels"), + picker = SelectScreen( + "Chat — pick a conversation", + await self._picker_items(ctx), + wrap=False, + delete_hint="Del delete history", + ) + opened = 0 + shown = 0 + async with ctx.ui.session.stay(picker) as visit: + while True: + choice = await visit.result() + if isinstance(choice, DeleteRequest): + await self._delete_history(ctx, choice.value) + elif choice is CANCEL or choice is None: # Esc — out to the menu + return ToolResult( + summary={"conversations": opened, "messages": shown} + ) + else: + shown = await open_chat(ctx, choice) + opened += 1 + picker.replace_items(await self._picker_items(ctx)) + + async def _picker_items(self, ctx: AppContext) -> list: + """Build the picker's rows: the pinned lane names, the Channels group, then Direct. + + Read fresh every time the list is built or swapped, so a thread that just gained + messages sits where its recency puts it. Cheap enough to redo after each chat: the + two device reads go through the session cache and the rest is stored history. + + Args: + ctx: Shared application context. + + Returns: + The :class:`~meshterm.ui.tui.select.Choice` / ``Separator`` rows, in display + order. + """ + # Through the session cache: this picker runs on every Chat open, and its two + # reads — the channel-slot probe and the contacts table — are the two slowest + # round-trips on a companion. Reading them from the device each time is what made + # opening Chat stall for seconds (the cached chat screen behind it never got the + # chance to help). The cache holds channels until the channel editor writes a + # slot and refreshes contacts in the background (see + # :class:`~meshterm.services.device_state.DeviceState`). + channels = _channels_from_slots(await ctx.devstate.channel_slots()) + contacts = await ctx.devstate.contacts() + # Only companion nodes are listed — we don't DM repeaters, rooms, or sensors; + # a contact whose type was never advertised gets the benefit of the doubt (the + # app-wide DM rule, see is_direct_messageable). + companions = [c for c in contacts if is_direct_messageable(c.node_type)] + # A stable snapshot orders the rows (so the list doesn't reshuffle under the + # cursor), while a self-refreshing view feeds each row's live preview + # (see _LiveLasts). + lasts = ctx.repo.last_chat_messages() + live = _LiveLasts(ctx, seed=lasts) + # Names in previews/mentions resolve back to keys for their hue (the app-wide + # colour rule); a name no contact or stored advert carries stays muted. + key_of = make_name_key_resolver(contacts, ctx.repo.node_names()) + + # The lane names pin for the whole picker (they mean the same in both groups), + # so scrolling into Direct keeps them overhead with that group's heading under + # them, instead of the header vanishing one row in — see Screen.sticky_rows. + items: list = [ + Separator(_picker_header, pinned=True), + section_heading("📡 Channels"), + ] + for conversation in channels: + items.append( + Choice( + title=_row_title(ctx, conversation, live, key_of), + value=conversation, + ) + ) + + items.append(section_heading("👤 Direct")) + if companions: + # List contacts by recency — those with messages first, newest exchange at + # the top — then the never-contacted ones alphabetically (see _recency_key). + direct = [ + Conversation(label=c.name, is_channel=False, contact=c) + for c in companions ] - for conversation in channels: + direct.sort(key=lambda conv: _recency_key(conv, lasts)) + for conversation in direct: items.append( Choice( title=_row_title(ctx, conversation, live, key_of), value=conversation, + # Del offers to delete this thread's stored history — + # only where there is history to delete. + deletable=lasts.get(conversation.key) is not None, ) ) + else: + items.append(Separator(" no contacts yet — receive an advert first")) - items.append(section_heading("👤 Direct")) - if companions: - # List contacts by recency — those with messages first, newest exchange at - # the top — then the never-contacted ones alphabetically (see _recency_key). - direct = [ - Conversation(label=c.name, is_channel=False, contact=c) - for c in companions - ] - direct.sort(key=lambda conv: _recency_key(conv, lasts)) - for conversation in direct: - items.append( - Choice( - title=_row_title(ctx, conversation, live, key_of), - value=conversation, - # Del offers to delete this thread's stored history — - # only where there is history to delete. - deletable=lasts.get(conversation.key) is not None, - ) - ) - else: - items.append(Separator(" no contacts yet — receive an advert first")) - - default = next( - ( - it.value - for it in items - if isinstance(it, Choice) - and isinstance(it.value, Conversation) - and it.value.key == default_key - ), - None, - ) - choice = await ctx.ui.select( - "Chat — pick a conversation", - items, - default=default, - wrap=False, - delete_hint="Del delete history", - ) - if isinstance(choice, DeleteRequest): - conversation = choice.value - await self._delete_history(ctx, conversation) - # Re-enter with fresh rows: a deleted thread's dot hollows and the row - # demotes to the uncontacted (alphabetical) tail; keep the cursor on it. - default_key = conversation.key - continue - if choice is None: # Esc - return None - return choice + return items @staticmethod async def _delete_history(ctx: AppContext, conversation: Conversation) -> None: diff --git a/tests/test_chat.py b/tests/test_chat.py index 705c1ea..0cc1930 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -1696,21 +1696,11 @@ async def test_picker_lists_companions_only(repo: Repository) -> None: Contact(name="Tower", public_key="a1" + "0" * 62, node_type=NODE_TYPE_REPEATER), ] - class _Ui: - def __init__(self) -> None: - self.items = None - - async def select(self, title, items, **kw): - self.items = items - return None - - ctx = SimpleNamespace( - devstate=_PickerDevstate(contacts), repo=repo, ui=_Ui(), chat=_PickerChat() - ) - assert await ChatTool()._pick_conversation(ctx) is None + ctx = SimpleNamespace(devstate=_PickerDevstate(contacts), repo=repo, chat=_PickerChat()) + items = await ChatTool()._picker_items(ctx) direct = [ it.value.label - for it in ctx.ui.items + for it in items if isinstance(it, Choice) and isinstance(it.value, Conversation) and not it.value.is_channel @@ -1734,22 +1724,12 @@ async def test_picker_pins_its_column_header_over_the_group_heading( for i in range(12) ] - class _Ui: - def __init__(self) -> None: - self.items = None + ctx = SimpleNamespace(devstate=_PickerDevstate(contacts), repo=repo, chat=_PickerChat()) + items = await ChatTool()._picker_items(ctx) - async def select(self, title, items, **kw): - self.items = items - return None - - ctx = SimpleNamespace( - devstate=_PickerDevstate(contacts), repo=repo, ui=_Ui(), chat=_PickerChat() - ) - await ChatTool()._pick_conversation(ctx) - - header = ctx.ui.items[0] + header = items[0] assert header.pinned # the lanes mean the same in both groups — pinned for the list - screen = SelectScreen("Chat", ctx.ui.items, wrap=False) + screen = SelectScreen("Chat", items, wrap=False) for _ in range(8): # down past the Direct heading screen.handle("down") visible, above, _below = frame._visible_slice(screen, screen.render_body(72), 8) @@ -1764,11 +1744,11 @@ async def test_picker_pins_its_column_header_over_the_group_heading( async def test_picker_del_deletes_history_after_a_red_confirm(repo: Repository) -> None: """Del on a contacted thread: red destructive confirm, history gone, unread cleared, - and the re-entered picker's row is hollow (no longer deletable).""" + and the rebuilt rows show the thread hollow (no longer deletable).""" from types import SimpleNamespace from meshterm.tools.chat import ChatTool - from meshterm.ui.tui import Choice, DeleteRequest + from meshterm.ui.tui import Choice ally = Contact(name="Ally", public_key="d4" + "0" * 62, node_type=1) conv = Conversation(label="Ally", is_channel=False, contact=ally) @@ -1777,25 +1757,8 @@ async def test_picker_del_deletes_history_after_a_red_confirm(repo: Repository) class _Ui: def __init__(self) -> None: - self.selects = 0 self.dialogs: list[dict] = [] - async def select(self, title, items, **kw): - self.selects += 1 - assert kw.get("delete_hint") == "Del delete history" - row = next( - it - for it in items - if isinstance(it, Choice) - and isinstance(it.value, Conversation) - and not it.value.is_channel - ) - if self.selects == 1: - assert row.deletable # there is history to delete - return DeleteRequest(row.value) - assert not row.deletable # history gone: the row demoted to uncontacted - return None - async def dialog(self, prompt, buttons, **kw): self.dialogs.append({"prompt": prompt, "buttons": buttons, **kw}) return True # commit the Delete @@ -1804,8 +1767,10 @@ async def test_picker_del_deletes_history_after_a_red_confirm(repo: Repository) ctx = SimpleNamespace( devstate=_PickerDevstate([ally]), repo=repo, ui=_Ui(), chat=chat ) - assert await ChatTool()._pick_conversation(ctx) is None - assert ctx.ui.selects == 2 # the picker re-entered after the delete + tool = ChatTool() + assert _direct_row(await tool._picker_items(ctx)).deletable # there is history to delete + + await tool._delete_history(ctx, conv) confirm = ctx.ui.dialogs[0] assert confirm["destructive"] is True # the reserved red, data loss @@ -1816,6 +1781,8 @@ async def test_picker_del_deletes_history_after_a_red_confirm(repo: Repository) m.text for m in repo.recent_chat_messages(is_channel=True, channel_id="c0") ] == ["chan"] # channel history survives assert chat.cleared == [conv.key] + # The swapped-in rows show it: history gone, so the row demotes to uncontacted. + assert not _direct_row(await tool._picker_items(ctx)).deletable async def test_picker_del_cancel_keeps_the_history(repo: Repository) -> None: @@ -1823,29 +1790,12 @@ async def test_picker_del_cancel_keeps_the_history(repo: Repository) -> None: from types import SimpleNamespace from meshterm.tools.chat import ChatTool - from meshterm.ui.tui import Choice, DeleteRequest ally = Contact(name="Ally", public_key="d4" + "0" * 62, node_type=1) conv = Conversation(label="Ally", is_channel=False, contact=ally) repo.record_chat_message(ChatMessage(text="hi", peer=conv.peer)) class _Ui: - def __init__(self) -> None: - self.selects = 0 - - async def select(self, title, items, **kw): - self.selects += 1 - if self.selects == 1: - row = next( - it - for it in items - if isinstance(it, Choice) - and isinstance(it.value, Conversation) - and not it.value.is_channel - ) - return DeleteRequest(row.value) - return None - async def dialog(self, prompt, buttons, **kw): return False # Cancel backs out @@ -1853,11 +1803,83 @@ async def test_picker_del_cancel_keeps_the_history(repo: Repository) -> None: ctx = SimpleNamespace( devstate=_PickerDevstate([ally]), repo=repo, ui=_Ui(), chat=chat ) - assert await ChatTool()._pick_conversation(ctx) is None + await ChatTool()._delete_history(ctx, conv) assert [m.text for m in repo.recent_chat_messages(is_channel=False, peer=conv.peer)] == ["hi"] assert chat.cleared == [] +def _direct_row(items: list): + """The one Direct row in a built picker list (the tests above list a single contact).""" + from meshterm.ui.tui import Choice + + return next( + it + for it in items + if isinstance(it, Choice) + and isinstance(it.value, Conversation) + and not it.value.is_channel + ) + + +async def test_the_conversation_picker_stays_pushed_under_an_open_chat( + repo: Repository, monkeypatch +) -> None: + """Esc out of a chat is one pop, back onto the row it was opened from. + + The picker used to be gathered in ``prompt_params`` and rebuilt on every round, with the + cursor put back by a ``default=`` restore; keeping the one screen keeps the typed filter + and the scroll with it, and the rows are swapped in place so a thread that just gained + messages sits where its recency puts it. + """ + import asyncio + from types import SimpleNamespace + + from prompt_toolkit.input.defaults import create_pipe_input + from prompt_toolkit.output import DummyOutput + + from meshterm.tools.chat import ChatTool + from meshterm.ui.surface import TuiUi + from meshterm.ui.tui.screen import CANCEL + from meshterm.ui.tui.session import TuiSession + + ally = Contact(name="Ally", public_key="d4" + "0" * 62, node_type=1) + ctx = SimpleNamespace( + devstate=_PickerDevstate([ally]), repo=repo, chat=_PickerChat() + ) + depths: list[int] = [] + + with create_pipe_input() as inp: + session = TuiSession(input=inp, output=DummyOutput()) + ctx.ui = TuiUi(session) + + async def fake_open_chat(_ctx, conversation) -> int: + """Stand in for the chat screen: note the stack under it, then leave it.""" + depths.append(len(session._stack)) + return 3 + + monkeypatch.setattr("meshterm.ui.chat.open_chat", fake_open_chat) + + async def main() -> None: + run = asyncio.ensure_future(ChatTool()._run_live(ctx)) + loop = asyncio.get_running_loop() + deadline = loop.time() + 2 + while not session._stack: + assert loop.time() < deadline, "the picker never opened" + await asyncio.sleep(0) + picker = session._stack[-1] + picker.resolve(Conversation(label="Ally", is_channel=False, contact=ally)) + while not depths: + await asyncio.sleep(0) + picker.resolve(CANCEL) # Esc from the picker leaves for the menu + result = await asyncio.wait_for(run, timeout=2) + assert result.summary == {"conversations": 1, "messages": 3} + + await asyncio.wait_for(session.run(main()), timeout=5) + + assert depths == [1], "the picker is still on the stack while the chat runs" + assert session._stack == [], "and the visit pops it on the way out" + + # -- the badge rule: what raises the header's unread count --------------------