diff --git a/meshterm/tools/chat.py b/meshterm/tools/chat.py index 64273f0..40424f9 100644 --- a/meshterm/tools/chat.py +++ b/meshterm/tools/chat.py @@ -15,9 +15,11 @@ from __future__ import annotations import asyncio import time from collections.abc import Callable +from dataclasses import dataclass from typing import TYPE_CHECKING, Any import typer +from rich.cells import cell_len from rich.text import Text from ..context import AppContext @@ -127,7 +129,16 @@ class ChatTool(Tool): picker = SelectScreen( "Chat — pick a conversation", await self._picker_items(ctx), - delete_hint="Del delete history", + # Enter pushes the chat screen, so the committing verb is `open`. Neither the + # scroll nor the erase atom is written into the base: the select list splices + # each in exactly when its key would act — ←→ only while the highlighted row + # overflows, Del only on a thread that has history to lose — and the three of + # them together are what has to stay inside 72 cells (the purge preview's list + # is the same arithmetic). `Del erase` is that budget's doing: the row already + # names the conversation, so the atom spends its cells on the verb, and `erase` + # is the word the app uses elsewhere for taking data away. + footer_hint="↑↓ move · type to filter · Enter open · Esc back", + delete_hint="Del erase", ) opened = 0 shown = 0 @@ -179,35 +190,43 @@ class ChatTool(Tool): # colour rule); a name no contact or stored advert carries stays muted. key_of = make_name_key_resolver(contacts, ctx.repo.node_names()) + # 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)) + # One measurement for the whole list, headings and rows alike, taken before either is + # built: the name lane is only as wide as the names actually in it, and every cell it + # gives back goes to the message preview (see _lanes). + lanes = _lanes(channels + direct) + # 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), + Separator(lambda w: _picker_header(lanes, w), pinned=True), section_heading("📡 Channels"), ] for conversation in channels: items.append( Choice( - title=_row_title(ctx, conversation, live, key_of), + title=_row_title(ctx, conversation, live, key_of, lanes), value=conversation, + # ←→ slide the message alone; the lanes in front of it hold (_Lanes.head). + hscroll_from=lanes.head, ) ) 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), + title=_row_title(ctx, conversation, live, key_of, lanes), 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, + hscroll_from=lanes.head, ) ) else: @@ -630,25 +649,87 @@ class _LiveLasts: return self._cache.get(key) -#: Column width (display cells) the conversation label is padded/ellipsized to, so the unread -#: badge and message preview line up in fixed lanes down the picker. -_LABEL_WIDTH = 22 #: Width of the unread-badge lane between the label and the age (fits ``● 999``). _BADGE_WIDTH = 5 #: Width of the relative-age lane between the badge and the preview (right-aligned; fits ``now`` #: and two-digit spans like ``59m`` / ``23h``), so every row's message text starts in one column. _AGE_WIDTH = 3 -#: Longest message preview shown before it is ellipsized. -_PREVIEW_WIDTH = 40 +#: Floor for the conversation lane. The header word is ``CONVERSATION`` (12 cells) and the +#: lane carries a two-cell gap after it, so anything narrower than this runs the heading +#: straight into ``UNREAD`` on a mesh whose every name is ``Bob``. +_LABEL_MIN = 12 +#: Ceiling for it. The lane is sized to the longest name it actually holds (see +#: :func:`_lanes`), and this is where that stops paying: one very long name would otherwise +#: buy padding in front of every *short* one. It holds the long-but-ordinary shape of a +#: repeater-style name (``YUL-Cartierville``), a name past it ellipsizes — the row is a way +#: in to the conversation, whose own screen is titled with the whole name — and every cell +#: the ceiling saves goes to the preview. +_LABEL_MAX = 16 -def _picker_header(width: int) -> str: +@dataclass(frozen=True) +class _Lanes: + """The picker's fixed lane widths, measured once per list build. + + Both the column header and every row are laid out from one of these, so the headings + cannot drift off the columns they name. Only the first two vary: the marker is the + platform's own glyph width (a channel glyph is double-cell on regular and single on the + PicoCalc console) and the label lane is sized to the longest name the list actually + holds, within :data:`_LABEL_MIN` / :data:`_LABEL_MAX`. + + Attributes: + marker: The leading glyph lane — a channel glyph or contact dot plus its space. + label: Cells the conversation name is padded/ellipsized to. + """ + + marker: int + label: int + + @property + def head(self) -> int: + """Cells before the preview: everything ←→ leave pinned (:attr:`Choice.hscroll_from`). + + Marker, name, unread badge and age, with the two-cell gap that follows each — the + columns that say *which conversation this row is*. The preview is the only run that + slides, which is the point: the lanes are the reader's place in the list and they + already fit. + """ + return self.marker + self.label + 2 + _BADGE_WIDTH + 2 + _AGE_WIDTH + 2 + + +def _lanes(conversations: list[Conversation]) -> _Lanes: + """Measure the picker's lanes against the conversations it is about to draw. + + The name lane used to be a flat 22 cells, which is a wide claim on a 72-column terminal + and a very wide one on the PicoCalc's 53: every cell it holds past the longest name in + the list is padding taken straight out of the last-message preview. Sized to the content + instead, a mesh of ``Alice`` and ``Bob`` keeps its names inside the header word's own + lane and gives everything else to the messages. + + Args: + conversations: Every row the list will hold, channels and direct alike. + + Returns: + The lane widths for both the header and the rows. + """ + longest = max((cell_len(c.label) for c in conversations), default=0) + return _Lanes( + # The marker is "glyph + space", and the glyph is the platform's: double-cell on + # regular, single on the console font. Read from the widget rather than assumed, so + # the two groups' lanes line up on both platforms — a contact's dot is padded to + # whatever a channel's glyph measures here (see _append_marker). + marker=cell_len(channel_glyph("Public", None)) + 1, + label=max(_LABEL_MIN, min(_LABEL_MAX, longest)), + ) + + +def _picker_header(lanes: _Lanes, width: int) -> str: """Column headers over the picker's fixed lanes (see :func:`_title` for the layout). - The five-cell indent covers the select screen's pointer column (2 cells, drawn on choice - rows but not separators) plus the marker lane (3 cells), so each header lands exactly - over its column. UNREAD borrows its lane's trailing gap — the badge lane itself is one - cell too narrow for the word — which still leaves a space before the age column. + The indent covers the select screen's pointer column (2 cells, drawn on choice rows but + not separators) plus the marker lane, so each header lands exactly over its column. + UNREAD borrows its lane's trailing gap — the badge lane itself is one cell too narrow + for the word — which still leaves a space before the age column. Resolved against the render width (the header row is pinned, so it must stay one row): on a terminal too narrow for the whole line, ``LAST MESSAGE`` gives its cells back a @@ -657,13 +738,13 @@ def _picker_header(width: int) -> str: """ return column_header( [ - Lane("CONVERSATION", _LABEL_WIDTH + 2), + Lane("CONVERSATION", lanes.label + 2), Lane("UNREAD", _BADGE_WIDTH + 2), Lane("TIME", _AGE_WIDTH + 2), Lane(("LAST MESSAGE", "LAST MSG", "LAST")), ], width, - indent=5, + indent=2 + lanes.marker, ) @@ -672,6 +753,7 @@ def _row_title( conversation: Conversation, lasts: _LiveLasts, key_of: NameKeyResolver, + lanes: _Lanes, ) -> Callable[[], str | Text]: """Return a picker-row title *callable* the select screen re-renders on each repaint. @@ -684,11 +766,12 @@ def _row_title( conversation: The conversation the row represents. lasts: The self-refreshing latest-message view feeding the preview. key_of: Maps a sender name back to its node's key, for the preview hues. + lanes: The list's measured lane widths. Returns: A zero-argument callable producing the current row title. """ - return lambda: _title(ctx, conversation, lasts, key_of) + return lambda: _title(ctx, conversation, lasts, key_of, lanes) def _title( @@ -696,6 +779,7 @@ def _title( conversation: Conversation, lasts: _LiveLasts, key_of: NameKeyResolver, + lanes: _Lanes, ) -> str | Text: """Build a picker row as fixed-width, colour-coded lanes. @@ -713,6 +797,7 @@ def _title( conversation: The conversation the row represents. lasts: The self-refreshing latest-message view. key_of: Maps a preview sender/mention name back to its node's key. + lanes: The list's measured lane widths. Returns: The row title as a styled :class:`~rich.text.Text`. @@ -720,12 +805,12 @@ def _title( unread = ctx.chat.unread(conversation.key) last = lasts.get(conversation.key) text = Text(no_wrap=True, overflow="ellipsis") - _append_marker(text, conversation, last) + _append_marker(text, conversation, last, lanes) label_style = "" if not conversation.is_channel and conversation.contact is not None: contact = conversation.contact label_style = name_style(conversation.label, contact.public_key or contact.key_prefix) - text.append(fit_cells(conversation.label, _LABEL_WIDTH), style=label_style or None) + text.append(fit_cells(conversation.label, lanes.label), style=label_style or None) text.append(" ") # Unread badge lane (_BADGE_WIDTH cells): a red ● with the count in warn, or blank filler so # the following lanes still line up on rows with nothing unread. @@ -751,21 +836,28 @@ def _title( _COMPANION_DOT_STYLE = _NODE_GLYPHS[NODE_TYPE_CHAT][1] -def _append_marker(text: Text, conversation: Conversation, last: ChatMessage | None) -> None: - """Prepend the row's leading marker (3 display cells) — a channel glyph or a contact dot. +def _append_marker( + text: Text, conversation: Conversation, last: ChatMessage | None, lanes: _Lanes +) -> None: + """Prepend the row's leading marker — a channel glyph or a contact dot — in its own lane. A channel keeps its openness marker (# / 🌐 / 🔒). A contact gets a small circle in the standard companion pink — filled (``●``) once we've exchanged messages, a hollow ring (``○``) before any — so the hollow-vs-filled shape marks whether there's history while the - name itself carries the person's key-derived hue. The contact dot is padded to the same - width as a channel's double-cell glyph so the labels line up across both sections. + name itself carries the person's key-derived hue. + + The dot is padded out to :attr:`_Lanes.marker`, which is measured from the channel glyph + itself rather than assumed: that glyph is double-cell on regular and single-cell on the + PicoCalc console font, so a hard-coded pad lined the two sections up on one platform and + left every channel row a cell to the left of every direct row on the other. """ if conversation.is_channel: - text.append(f"{channel_glyph(conversation.label, conversation.secret)} ") + glyph = channel_glyph(conversation.label, conversation.secret) + text.append(glyph + " " * max(1, lanes.marker - cell_len(glyph))) else: dot = "●" if last is not None else "○" text.append(dot, style=_COMPANION_DOT_STYLE) - text.append(" ") + text.append(" " * max(1, lanes.marker - cell_len(dot))) def _preview_text(last: ChatMessage, key_of: NameKeyResolver) -> Text: @@ -774,8 +866,12 @@ def _preview_text(last: ChatMessage, key_of: NameKeyResolver) -> Text: Mirrors the live transcript: our own messages get a ``you:`` prefix, an inbound channel message's inline ``Name:`` sender is coloured in its key-derived hue (muted when no known node carries the name), and every ``@[Name]`` mention reads as a bare ``@Name`` the same - way — so the list and the chat speak the same colour language. The result is clipped to - :data:`_PREVIEW_WIDTH` cells. + way — so the list and the chat speak the same colour language. + + The preview is built *whole*, however long the message ran. It used to be clipped to a + fixed 40 cells, which is a cut nothing could undo: the row is what ←→ scroll now, and a + preview pre-truncated to roughly the visible lane would have had nothing left to reveal. + The list cuts it at the right edge like any other row; the scroll walks past that. """ body_raw = last.text.replace("\n", " ") text = Text() @@ -792,7 +888,6 @@ def _preview_text(last: ChatMessage, key_of: NameKeyResolver) -> Text: _append_body(text, body_raw, key_of) else: _append_body(text, body_raw, key_of) - text.truncate(_PREVIEW_WIDTH, overflow="ellipsis") return text diff --git a/tests/test_chat.py b/tests/test_chat.py index 59c84f7..e63bfb7 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -11,6 +11,7 @@ import re from pathlib import Path import pytest +from rich.cells import cell_len from meshterm.core.channels import DEFAULT_PUBLIC_SECRET, derive_secret from meshterm.core.config import Settings @@ -27,7 +28,7 @@ from meshterm.core.preferences import Preferences from meshterm.persistence.repository import Repository from meshterm.services.chat_service import ChatService from meshterm.services.event_hub import EventHub -from meshterm.tools.chat import _PREVIEW_WIDTH, _LiveLasts, _preview_text, _title +from meshterm.tools.chat import _lanes, _LiveLasts, _preview_text, _title from meshterm.ui.chat import ChatScreen from meshterm.ui.tui import fkeys from meshterm.ui.tui.screen import CANCEL @@ -441,11 +442,10 @@ def test_preview_colours_channel_sender_and_mentions() -> None: assert any(s.style == "node.unknown" and s.start <= zed < s.end for s in preview.spans) -def test_preview_ellipsizes_long_text() -> None: - """An over-long preview is clipped to the width budget with a trailing ellipsis.""" - long = ChatMessage(text="x" * 100, is_channel=True, channel_idx=0) - out = _preview_text(long, _NO_KEYS).plain - assert len(out) == _PREVIEW_WIDTH and out.endswith("…") +def test_preview_keeps_the_whole_message() -> None: + """The preview is built whole — the row's own cut is what the ←→ scroll walks past.""" + long = ChatMessage(text="x" * 300, is_channel=True, channel_idx=0) + assert _preview_text(long, _NO_KEYS).plain == "x" * 300 def test_title_shows_badge_and_author_preview(repo: Repository) -> None: @@ -453,7 +453,7 @@ def test_title_shows_badge_and_author_preview(repo: Repository) -> None: conv = Conversation(label="General", is_channel=True, channel_idx=0, channel_id="c0") ctx = _RowCtx(repo, unread={"chan:c0": 3}) last = ChatMessage(text="Bob: hi there", is_channel=True, channel_id="c0") # sender inline - title = _title(ctx, conv, {"chan:c0": last}, _NO_KEYS) + title = _title(ctx, conv, {"chan:c0": last}, _NO_KEYS, _lanes([conv])) line = title.plain # a Text, since there is unread assert line.startswith("🔒 General") # a private channel leads with its openness glyph assert "● 3" in line @@ -465,7 +465,7 @@ def test_title_reddens_only_the_unread_dot(repo: Repository) -> None: from rich.text import Text conv = Conversation(label="General", is_channel=True, channel_idx=0, channel_id="c0") - unread = _title(_RowCtx(repo, unread={"chan:c0": 2}), conv, {}, _NO_KEYS) + unread = _title(_RowCtx(repo, unread={"chan:c0": 2}), conv, {}, _NO_KEYS, _lanes([conv])) assert isinstance(unread, Text) dot = unread.plain.index("●") reddened = [ @@ -473,7 +473,7 @@ def test_title_reddens_only_the_unread_dot(repo: Repository) -> None: ] assert reddened and all(span.end - span.start == 1 for span in reddened) # just the glyph - read = _title(_RowCtx(repo, unread={}), conv, {}, _NO_KEYS) + read = _title(_RowCtx(repo, unread={}), conv, {}, _NO_KEYS, _lanes([conv])) assert isinstance(read, Text) # always a Text now, so its spans can carry the row's colour assert "●" not in read.plain # nothing unread -> no badge dot assert not any(span.style == "err" for span in read.spans) @@ -488,8 +488,9 @@ def test_title_preview_column_aligns_regardless_of_label_length(repo: Repository ) m0 = ChatMessage(text="X: hello", is_channel=True, channel_id="c0") m1 = ChatMessage(text="Y: hello", is_channel=True, channel_id="c1") - l0 = _title(ctx, short, {"chan:c0": m0}, _NO_KEYS).plain - l1 = _title(ctx, long, {"chan:c1": m1}, _NO_KEYS).plain + lanes = _lanes([short, long]) # one measurement for the list, as the picker does + l0 = _title(ctx, short, {"chan:c0": m0}, _NO_KEYS, lanes).plain + l1 = _title(ctx, long, {"chan:c1": m1}, _NO_KEYS, lanes).plain assert l0.index("X: hello") == l1.index("Y: hello") @@ -498,7 +499,7 @@ def test_title_leads_with_openness_glyph(repo: Repository) -> None: ctx = _RowCtx(repo) def head(conv): - return _title(ctx, conv, {}, _NO_KEYS).plain.split(" ", 1)[0] + return _title(ctx, conv, {}, _NO_KEYS, _lanes([conv])).plain.split(" ", 1)[0] named = Conversation( label="#general", is_channel=True, channel_id="c0", secret=derive_secret("#general") @@ -533,7 +534,7 @@ def test_title_contact_dot_reflects_conversation_history(repo: Repository) -> No ) # No history yet — a hollow ring in the standard companion pink. - fresh = _title(ctx, contact, {}, _NO_KEYS) + fresh = _title(ctx, contact, {}, _NO_KEYS, _lanes([contact])) assert fresh.plain.startswith("○") and dot_is_pink(fresh) # The name lane carries Alice's key-derived hue. name_at = fresh.plain.index("Alice") @@ -541,7 +542,7 @@ def test_title_contact_dot_reflects_conversation_history(repo: Repository) -> No # Once we've exchanged messages the same pink dot fills in. last = ChatMessage(text="hi", peer=contact.peer) - talked = _title(ctx, contact, {contact.key: last}, _NO_KEYS) + talked = _title(ctx, contact, {contact.key: last}, _NO_KEYS, _lanes([contact])) assert talked.plain.startswith("●") and dot_is_pink(talked) @@ -1791,9 +1792,135 @@ async def test_picker_pins_its_column_header_over_the_group_heading( assert top[0].startswith("CONVERSATION") and top[0].endswith("LAST MESSAGE") assert top[1] == "── 👤 Direct ──" assert above is True - # Too narrow for the whole line, the trailing label shortens — never wraps. - assert header.text(50).endswith("LAST MSG") - assert "\n" not in header.text(40) + # Too narrow for the whole line, the trailing label shortens — never wraps. The + # lane is sized to these six-cell names now, so the squeeze starts well below any + # real terminal: the fallback is what is under test, not the width it happens at. + assert header.text(40).endswith("LAST MSG") + assert "\n" not in header.text(30) + + +async def test_picker_lane_is_sized_to_the_names_it_holds(repo: Repository) -> None: + """The conversation lane fits the longest name, between its floor and its ceiling. + + Every cell the lane holds past that longest name is padding taken out of the message + preview, which is the row's only unbounded content — so it is measured, not written down. + """ + from meshterm.tools.chat import _LABEL_MAX, _LABEL_MIN, _lanes + + def lane(*names: str) -> int: + return _lanes([Conversation(label=n, is_channel=True, channel_id=n) for n in names]).label + + assert lane("Bob", "Ann") == _LABEL_MIN # short names can't shrink it under the header word + assert lane("Bob", "YUL-Cartierville") == len("YUL-Cartierville") + assert lane("A Rather Long Contact Name Indeed") == _LABEL_MAX # nor grow it without end + + +async def test_picker_rows_scroll_the_message_under_pinned_lanes(repo: Repository) -> None: + """A row hands ←→ the preview alone: the lanes in front of it are where it starts to slide. + + Those lanes are the reader's place in the list, so the scroll begins exactly where the + message does — which is one column for every row, long name or short. + """ + from types import SimpleNamespace + + from meshterm.tools.chat import ChatTool + from meshterm.ui.tui import Choice + + contacts = [ + Contact(name="Alice", public_key="d4" + "0" * 62, node_type=1), + Contact(name="A Rather Long Contact Name", public_key="60" + "0" * 62, node_type=1), + ] + alice = Conversation(label="Alice", is_channel=False, contact=contacts[0]) + repo.record_chat_message(ChatMessage(text="x" * 200, peer=alice.peer)) + ctx = SimpleNamespace(devstate=_PickerDevstate(contacts), repo=repo, chat=_PickerChat()) + rows = [it for it in await ChatTool()._picker_items(ctx) if isinstance(it, Choice)] + + heads = {row.hscroll_from for row in rows} + assert len(heads) == 1 and heads.pop() > 0 # one head block for the whole list + talked = next(row for row in rows if row.value.label == "Alice") + line = talked.label.plain + # Measured in cells, not characters: a channel glyph is one character and two cells. + assert cell_len(line[: line.index("x")]) == talked.hscroll_from + # And the preview keeps the whole message: the cut is the row's, and ←→ walk past it. + assert talked.label.plain.endswith("x" * 200) + + +def test_picker_marker_lane_lines_the_two_groups_up(repo: Repository) -> None: + """A channel glyph and a contact dot claim the same cells — on either platform. + + That glyph is double-cell on regular and single-cell in the console font, so the dot is + padded to whatever it actually measures rather than to a written-down width: a + hard-coded pad left every channel row a cell adrift of every direct row on the PicoCalc. + """ + from meshterm.platforms import PICOCALC, REGULAR, set_platform + from meshterm.tools.chat import _lanes + + channel = Conversation(label="Public", is_channel=True, channel_idx=0, channel_id="c0") + contact = Conversation( + label="Alice", is_channel=False, contact=Contact(name="Alice", public_key="d4" * 32) + ) + ctx = _RowCtx(repo) + try: + for platform in (REGULAR, PICOCALC): + set_platform(platform) + lanes = _lanes([channel, contact]) + rows = [_title(ctx, c, {}, _NO_KEYS, lanes).plain for c in (channel, contact)] + names = ("Public", "Alice") + at = [cell_len(r[: r.index(n)]) for r, n in zip(rows, names, strict=True)] + assert at[0] == at[1] == lanes.marker + finally: + set_platform(REGULAR) + + +async def test_picker_footer_fits_with_every_atom_showing(repo: Repository, monkeypatch) -> None: + """Scroll, erase and the base atoms together stay inside the 72-cell footer budget. + + The three of them coincide on an ordinary row — a thread with history long enough to + scroll — so the budget is the wording's constraint, not a corner case (it is what + ``Del erase`` is: the row already names the conversation it would take the history of). + """ + 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) + conv = Conversation(label="Ally", is_channel=False, contact=ally) + repo.record_chat_message(ChatMessage(text="y" * 200, peer=conv.peer)) + ctx = SimpleNamespace(devstate=_PickerDevstate([ally]), repo=repo, chat=_PickerChat()) + hints: list[str] = [] + + with create_pipe_input() as inp: + session = TuiSession(input=inp, output=DummyOutput()) + ctx.ui = TuiUi(session) + + 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.render_body(72) # the overflow probe reads the last render width + picker.handle("down") # onto the one Direct row: deletable, and overflowing + picker.render_body(72) + hints.append(picker.footer_hint) + picker.resolve(CANCEL) + await asyncio.wait_for(run, timeout=2) + + await asyncio.wait_for(session.run(main()), timeout=5) + + hint = hints[0] + assert cell_len(hint) <= 72, f"{cell_len(hint)} cells: {hint!r}" + for atom in ("←→ scroll", "Enter open", "Del erase", "Esc back"): + assert atom in hint async def test_picker_del_deletes_history_after_a_red_confirm(repo: Repository) -> None: diff --git a/tests/test_gallery.py b/tests/test_gallery.py index 7c99b05..fb1f8e6 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -22,6 +22,7 @@ starts reporting XPASS. from __future__ import annotations +import asyncio import logging import tempfile from collections.abc import Callable @@ -339,6 +340,92 @@ def _chat(cols: int, rows: int) -> Screen: ) +class _PickerChat: + """The unread counter the picker rows read live.""" + + def __init__(self, unread: dict[str, int]) -> None: + self._unread = unread + + def unread(self, key: str) -> int: + return self._unread.get(key, 0) + + +class _PickerDevstate: + """The session-cached device reads the picker builds itself from.""" + + def __init__(self, contacts: list[Contact], slots: list) -> None: + self._contacts = contacts + self._slots = slots + + async def channel_slots(self) -> list: + return list(self._slots) + + async def contacts(self) -> list[Contact]: + return list(self._contacts) + + +class _PickerRepo: + """The stored history behind each row's age, badge and last-message preview.""" + + def __init__(self, lasts: dict) -> None: + self._lasts = lasts + + def last_chat_messages(self) -> dict: + return dict(self._lasts) + + def node_names(self) -> dict: + return {} + + +def _chat_picker(cols: int, rows: int) -> Screen: + """The conversation picker, built through the tool's own row funnel. + + Its widest case: a name at the lane's ceiling, a three-digit-capable unread badge, and + a last message far longer than any terminal — which is the row ←→ scroll, so it has to + be cut rather than fitted (see :meth:`meshterm.tools.chat.ChatTool._picker_items`). + """ + from meshterm.tools.chat import ChatTool + + contacts = [ + Contact(name="Alice", public_key="aa" * 32, key_prefix="aa" * 6, node_type=1), + Contact(name="A Rather Long Contact Name", public_key="d4" * 32, key_prefix="d4" * 6), + Contact(name="Homestead", public_key="60" * 32, key_prefix="60" * 6, node_type=1), + ] + now = datetime(2026, 7, 12, 14, 30, tzinfo=timezone.utc) + lasts = { + # The default public channel, as _channels_from_slots names it with no slots read. + "chan:slot:0": ChatMessage( + text="Alice: anyone up around the Plateau tonight? testing a new antenna", + is_channel=True, + channel_idx=0, + channel_id="slot:0", + created_at=now, + ), + f"dm:{'aa' * 6}": ChatMessage( + text="on my way, should be there soon - the bridge is backed up again", + peer="aa" * 6, + created_at=now, + ), + } + ctx = _PickerCtx(contacts, lasts) + items = asyncio.run(ChatTool()._picker_items(ctx)) + return SelectScreen( + "Chat - pick a conversation", + items, + footer_hint="↑↓ move · type to filter · Enter open · Esc back", + delete_hint="Del erase", + ) + + +class _PickerCtx: + """The minimal AppContext surface :meth:`ChatTool._picker_items` reads.""" + + def __init__(self, contacts: list[Contact], lasts: dict) -> None: + self.devstate = _PickerDevstate(contacts, []) + self.repo = _PickerRepo(lasts) + self.chat = _PickerChat({"chan:slot:0": 3, f"dm:{'aa' * 6}": 12}) + + def _livefeed(cols: int, rows: int) -> Screen: return LiveFeedScreen( session=_GallerySession(cols, rows), @@ -701,6 +788,7 @@ _ENTRIES: list[_Entry] = [ _Entry("node_detail", _node_detail), _Entry("map", _map), _Entry("chat", _chat), + _Entry("chat_picker", _chat_picker), _Entry("livefeed", _livefeed), _Entry("walk", _walk), _Entry("timemachine", _timemachine),