From 0b931e7cc4b0a87487177ecd0a0d1d46a900b49e Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Thu, 22 Oct 2026 00:22:05 -0400 Subject: [PATCH] The Courier outbox is a TARGET and TRIGGER table, and Enter opens the message Each section of the outbox now has column headers: TARGET and TRIGGER for waiting entries, TARGET and OUTCOME for finished ones. The rows no longer show the message. Enter on a waiting entry opens it to edit (the courier holds the entry while the prompt is open, so the old text cannot go out meanwhile), and Enter on a finished one shows it. Del deletes an entry after a red confirm, and ^R sends a waiting entry now; on the PicoCalc they ride F3 as Send, with Delete behind it. On a narrow screen a long name gives cells to the trigger and breaks off on its crack. The message field has the colours of the chat's compose line: a white prompt mark and white text. Co-Authored-By: Claude Opus 5.5 (1M context) --- meshterm/core/courier_store.py | 34 +++ meshterm/services/courier.py | 37 ++- meshterm/tools/courier.py | 4 +- meshterm/ui/courier_screen.py | 457 ++++++++++++++++++++++++--------- meshterm/ui/tui/prompt.py | 27 +- meshterm/ui/tui/session.py | 5 + tests/test_courier.py | 323 ++++++++++++++++++++--- tests/test_tui.py | 22 ++ 8 files changed, 744 insertions(+), 165 deletions(-) diff --git a/meshterm/core/courier_store.py b/meshterm/core/courier_store.py index 075e5d9..fab1b3c 100644 --- a/meshterm/core/courier_store.py +++ b/meshterm/core/courier_store.py @@ -235,6 +235,40 @@ class CourierStore: self._save() return True + def edit(self, ident: int, text: str) -> bool: + """Replace the body of a waiting entry. Its schedule and its attempts stay. + + A finished entry is history: its body is what went out (or what MeshTerm stopped + trying to send), so it does not change. + + Returns: + Whether a waiting entry got the new body. + """ + message = self.get(ident) + if message is None or message.status != QUEUED: + return False + if message.text != text: + message.text = text + self._save() + return True + + def delete(self, ident: int) -> bool: + """Remove one entry, waiting or finished. + + For a waiting entry, this is the same as :meth:`cancel`. The outbox screen deletes + one row of either section with the Delete key. + + Returns: + Whether an entry was removed. + """ + messages = self._load() + kept = [m for m in messages if m.ident != ident] + if len(kept) == len(messages): + return False + self._messages = kept + self._save() + return True + def clear_done(self) -> None: """Remove all the finished entries, and do not change the waiting queue.""" messages = self._load() diff --git a/meshterm/services/courier.py b/meshterm/services/courier.py index ec55f04..edd2169 100644 --- a/meshterm/services/courier.py +++ b/meshterm/services/courier.py @@ -29,6 +29,8 @@ the header comes on when a delivery during the night is at last complete. from __future__ import annotations import asyncio +from collections.abc import Iterator +from contextlib import contextmanager from datetime import datetime from typing import TYPE_CHECKING @@ -81,8 +83,11 @@ class CourierService: #: The time when MeshTerm last heard each node id in this session (the freshness #: map). self._heard: dict[str, datetime] = {} - #: Re-entry guard: only one try at a time is in progress, from a pass or forced. - self._sending = False + #: Re-entry guard: only one try at a time is in progress, from a pass or forced. It + #: is the id of the entry that the try sends, or ``None`` when no try runs. + self._in_flight: int | None = None + #: The ids of the entries that the user edits now. A pass does not try them. + self._held: set[int] = set() @property def active(self) -> bool: @@ -93,6 +98,24 @@ class CourierService: """How many messages wait in the outbox.""" return self._ctx.courier_store.pending_count() + def in_flight(self, ident: int) -> bool: + """Whether a delivery try of the entry ``ident`` is in progress now.""" + return self._in_flight == ident + + @contextmanager + def holding(self, ident: int) -> Iterator[None]: + """Keep the passes off one entry while the user edits its body. + + Without the hold, a pass can send the old body while the edit prompt is open. Then + the edit changes the text of a message that already went out. A forced try + (:meth:`attempt_now`) does not read the hold, because the user asks for it. + """ + self._held.add(ident) + try: + yield + finally: + self._held.discard(ident) + # --- lifecycle --------------------------------------------------------------------- async def start(self) -> None: @@ -191,11 +214,11 @@ class CourierService: async def _pass(self) -> None: """One pass: try the oldest eligible entry, if there is one (one for each pass).""" - if not self._ctx.is_connected or self._sending: + if not self._ctx.is_connected or self._in_flight is not None: return now = utcnow() for message in self._ctx.courier_store.pending(): - if self.eligible(message, now): + if message.ident not in self._held and self.eligible(message, now): await self._attempt(message) return @@ -212,14 +235,14 @@ class CourierService: message = self._ctx.courier_store.get(ident) if message is None or message.status != QUEUED: return "gone" - if self._sending: + if self._in_flight is not None: return "busy" return await self._attempt(message) async def _attempt(self, message: QueuedMessage) -> str: """Run one delivery try, and set the new state of the entry.""" store = self._ctx.courier_store - self._sending = True + self._in_flight = message.ident try: contact = await self._resolve(message) if contact is None: @@ -258,7 +281,7 @@ class CourierService: ) return "no ack" finally: - self._sending = False + self._in_flight = None def _delivered_late(self, ident: int) -> None: """The ack of a try arrived after the try stopped its wait: the message was delivered. diff --git a/meshterm/tools/courier.py b/meshterm/tools/courier.py index 9633ea9..6339352 100644 --- a/meshterm/tools/courier.py +++ b/meshterm/tools/courier.py @@ -17,8 +17,8 @@ On the CLI, subcommands give script access to the same outbox: - ``send`` forces one delivery try now. - ``list``, ``cancel``, and ``clear`` examine the outbox and remove entries from it. -These subcommands are the script form of the Send-now, Cancel, and Clear-finished actions -of the outbox screen. +These subcommands are the script form of the actions of the outbox screen: Send now +(``^R``), Delete (``cancel`` deletes only a waiting entry), and Clear finished. """ from __future__ import annotations diff --git a/meshterm/ui/courier_screen.py b/meshterm/ui/courier_screen.py index c0ef7a3..7aec11a 100644 --- a/meshterm/ui/courier_screen.py +++ b/meshterm/ui/courier_screen.py @@ -4,13 +4,16 @@ The interactive face of the ``courier`` tool. One select-list screen holds the whole feature (the persistent-backdrop pattern). It has these parts: -- The waiting outbox. Each entry shows its live state: it waits to hear the contact, it is - scheduled for a time, or it backs off between retries. -- The finished history (delivered or given up). +- The waiting outbox. Each row shows its target (the recipient) and its trigger: what the + entry waits for before it goes out. It waits to hear the contact, it is scheduled for a + time, or it backs off between retries. +- The finished history (delivered or given up), with the outcome of each entry. - The queueing flow: select a contact, write the message, choose when to send it. -Enter on a waiting entry offers *Send now* (one forced attempt, and the outcome is in a -dialog) and *Cancel*. +A row does not show its message. Enter on a waiting entry opens the message to edit, and +Enter on a finished entry opens it to read. ``^R`` on a waiting entry is *Send now* (one +forced attempt, and the outcome is in a dialog). Delete removes an entry of either section, +after a confirm. The outbox is **live** while it is open. Each row is a callable title that the code computes again at each paint, so "retry in ~N m" counts down in real time. A ticker @@ -37,9 +40,16 @@ from rich.text import Text from ..core.courier_store import DELIVERED, QUEUED, QueuedMessage from ..core.models import Contact, is_direct_messageable, utcnow from .contactlist import SORT_COLUMNS, SORT_OPENS_ASCENDING, ContactListScreen, ContactRow -from .menus import icon_lane, marked_label, run_steps, section_heading -from .pathline import PathHop -from .tui import CANCEL, DM_BYTE_LIMIT, Choice, SelectScreen, Separator +from .menus import ( + Lane, + column_header, + icon_lane, + marked_label, + run_steps, + section_heading, +) +from .pathline import PathHop, cut_to +from .tui import CANCEL, DM_BYTE_LIMIT, Choice, DeleteRequest, SelectScreen, Separator from .watchtower_screen import contact_watch_key from .widgets import ( DESTINATION, @@ -58,6 +68,9 @@ if TYPE_CHECKING: _QUEUE = ("queue",) _CLEAR = ("clear",) +#: The first item of the value with which ``^R`` resolves the outbox: ``("send", ident)``. +_SEND = "send" + #: The status marks that an outbox entry starts with: waiting, delivered, gave up. They are #: the outcome of the row and not decoration. Thus, unlike the icon of a command row, they #: are drawn on each platform. The code measures them raw, because the render fold of the @@ -75,14 +88,23 @@ _COMMAND_ICONS = ("πŸ“¨", "πŸ—‘") #: The seconds between the refresh ticks of the open outbox (shape check and paint). _REFRESH_S = 1.0 -#: The maximum width at which a message body renders in a row, before the row gets an -#: ellipsis. -_TEXT_W = 36 +#: The cells between the TARGET lane and the lane after it. +_GAP = 2 +#: The fewest cells that the last lane (TRIGGER or OUTCOME) keeps on a narrow screen. A +#: long name gives cells back first, because the first letters of a chip already show who +#: it is, and the trigger is what the user opens the outbox to read. +_LAST_MIN = 20 -def _shorten(text: str, width: int = _TEXT_W) -> str: - """The message body, shortened for the display in a row.""" - return text if len(text) <= width else text[: width - 1] + "…" +#: How many finished entries the history section shows. The store keeps more (refer to the +#: ``courier_history_kept`` preference). +_DONE_SHOWN = 15 + +#: The footer of the outbox. :meth:`CourierOutboxScreen._key_atoms` adds the atoms of the +#: keys that act on an entry, only while the highlight is on such an entry. +_OUTBOX_HINT = "↑↓ move Β· type to filter Β· Enter open Β· Esc back" +_SEND_HINT = "^R send" +_DELETE_HINT = "Del delete" def _local_stamp(when: datetime) -> str: @@ -150,7 +172,7 @@ async def open_courier(ctx: AppContext) -> dict[str, Any] | None: # how to compose its sections again around the highlight # (:meth:`CourierOutboxScreen.refresh`). The ticker calls this method once each second # while the list is open. The code runs the screen through a visit. Thus each sub-flow - # (queue a message, the actions of an entry, the clear confirm) floats over the list and + # (queue a message, the message of an entry, a send, a confirm) floats over the list and # returns to the row from which it opened. Also, the code starts the ticker one time, # and not for each round. menu = CourierOutboxScreen(ctx) @@ -182,8 +204,12 @@ async def open_courier(ctx: AppContext) -> dict[str, Any] | None: destructive=True, ): store.clear_done() + elif isinstance(choice, DeleteRequest): + await _delete_entry(ctx, int(choice.value[1])) + elif isinstance(choice, tuple) and choice[0] == _SEND: + await _send_now(ctx, int(choice[1])) elif isinstance(choice, tuple) and choice[0] == "msg": - await _entry_actions(ctx, int(choice[1])) + await _open_entry(ctx, int(choice[1])) # Take in the effect of the flow at once, and do not wait for a tick. Thus # the list to which the user returns already shows what the user did. menu.refresh() @@ -212,6 +238,11 @@ class CourierOutboxScreen(SelectScreen): store. It composes the sections again in place only when the fingerprint changed, and the highlight stays on its entry (the rebuild idiom of :class:`~meshterm.ui.contactlist.ContactListScreen`). + + Three keys act on the highlighted entry. Enter opens its message (refer to + :func:`_open_entry`), Delete asks to remove it, and ``^R`` sends a waiting entry now. + The footer and the F-key lane name ``^R`` and Delete only on the rows on which they act. + ``^R`` is a chord, because this list filters as the user types. """ def __init__(self, ctx: AppContext, *, default: Any = None) -> None: @@ -226,9 +257,69 @@ class CourierOutboxScreen(SelectScreen): "Courier β€” store-and-forward outbox", _menu_items(ctx, ctx.courier_store.entries()), default=default, - footer_hint="↑↓ move Β· Enter select Β· Esc back", + footer_hint=_OUTBOX_HINT, + key_hint=self._key_atoms, ) + def _waiting(self, value: Any) -> int | None: + """The id of the entry that ``value`` names, if that entry waits in the outbox.""" + ident = _entry_ident(value) + if ident is None: + return None + message = self._ctx.courier_store.get(ident) + return ident if message is not None and message.status == QUEUED else None + + def _highlighted_waiting(self) -> int | None: + """The id of the highlighted entry, if it waits in the outbox.""" + current = self._current_choice() + return self._waiting(current.value) if current is not None else None + + def _key_atoms(self, value: Any) -> str: + """The footer atoms of the keys that act on the row of ``value``. + + ``^R`` acts only on a waiting entry, because a finished entry has left the outbox. + Delete acts on each entry, and on no command row. + """ + atoms = [] + if self._waiting(value) is not None: + atoms.append(_SEND_HINT) + if _entry_ident(value) is not None: + atoms.append(_DELETE_HINT) + return " Β· ".join(atoms) + + @property + def picocalc_lyra_lane(self): + """The lane of the list, with ``Send`` on F3 and ``Delete`` behind it. + + F1/F2 are the section jumps, and F4/F5 are the pager. F3 is the slot that a select + list uses for its own verb. Send and Delete have the same subject (the highlighted + entry). Thus they are the two halves of that slot, as Read and Remove are in the + region editor. Each is dim where it does not act. On a command row, both are dim, + not empty: the two actions exist on this screen, but not for that row. + """ + from .tui.fkeys import FPair + + lane = list(super().picocalc_lyra_lane) + current = self._current_choice() + lane[2] = FPair( + "Send", + "retry", + opp_label="Delete", + opp_action="delete", + enabled=self._highlighted_waiting() is not None, + opp_enabled=current is not None and current.deletable, + ) + return lane + + def handle(self, action: str, data: str = "") -> None: + """Send the highlighted waiting entry now on ``^R``. Other keys act as in each list.""" + if action == "retry": + ident = self._highlighted_waiting() + if ident is not None: + self.resolve((_SEND, ident)) + return + super().handle(action, data) + def _fingerprint(self) -> tuple: """The shape of the store: which entries exist and the status of each.""" return tuple((m.ident, m.status) for m in self._ctx.courier_store.entries()) @@ -254,14 +345,27 @@ class CourierOutboxScreen(SelectScreen): self._index = max(0, min(self._index, len(choices) - 1)) if choices else 0 +def _entry_ident(value: Any) -> int | None: + """The id of the entry that a row value names (``("msg", ident)``), or ``None``.""" + if isinstance(value, tuple) and len(value) == 2 and value[0] == "msg": + return int(value[1]) + return None + + def _menu_items(ctx: AppContext, entries: list[QueuedMessage]) -> list: """Build the rows of the screen: the waiting outbox, then the finished history. - The entry rows are callables with no argument, so that their live state renders again at - each paint. The fixed action rows stay plain strings. + Each section is a table under its own column header: the status mark, the TARGET (the + recipient), and one more lane. In the outbox, that lane is the TRIGGER: what the entry + waits for before it goes out. In the history, it is the OUTCOME. A row does not show + the message, because Enter opens it (refer to :func:`_open_entry`). + + The entry rows are callables of the render width. Thus their live state renders again + at each paint, and their TARGET lane fits the screen (refer to :func:`_target_lane`). + The fixed action rows stay plain strings. """ waiting = [m for m in entries if m.status == QUEUED] - done = [m for m in entries if m.status != QUEUED] + done = [m for m in entries if m.status != QUEUED][:_DONE_SHOWN] # One icon column for the whole list, across both sections. The terminal draws ⏳ and # πŸ“¨ in two cells, but βœ“ βœ— πŸ—‘ in one cell. Thus rows that were written as @@ -271,24 +375,81 @@ def _menu_items(ctx: AppContext, entries: list[QueuedMessage]) -> list: # command icons go where the platform draws no icon lane, and marked_label leaves those # two labels bare. It does not pad them for a mark that is not there. lane = max(icon_lane(_COMMAND_ICONS), _MARK_LANE) + # One TARGET lane for both sections, so that the lane after it starts in the same cell + # in each. It is never narrower than its label, so the label never runs into the next. + target_w = max([cell_len("TARGET")] + [_target_chip(m).cell_len for m in waiting + done]) items: list = [section_heading("Outbox")] - if not waiting: + if waiting: + items.append(_column_header("TRIGGER", lane, target_w)) + else: items.append(Separator(" empty β€” queued messages wait here for their moment")) for message in waiting: - items.append(Choice(lambda m=message: _waiting_row(ctx, m, lane), ("msg", message.ident))) + items.append( + Choice( + lambda width, m=message: _waiting_row( + ctx, m, lane, _target_lane(lane, target_w, width) + ), + ("msg", message.ident), + deletable=True, + ) + ) items.append(Separator(" ")) # put space between the action and the outbox rows above it items.append(Choice(marked_label("πŸ“¨", "Queue a message…", "", lane=lane), _QUEUE)) if done: items.append(section_heading("Finished")) - for message in done[:15]: - items.append(Choice(lambda m=message: _done_row(m, lane), ("msg", message.ident))) + items.append(_column_header("OUTCOME", lane, target_w)) + for message in done: + items.append( + Choice( + lambda width, m=message: _done_row( + m, lane, _target_lane(lane, target_w, width) + ), + ("msg", message.ident), + deletable=True, + ) + ) items.append(Choice(marked_label("πŸ—‘", "Clear finished", "", lane=lane), _CLEAR)) return items +def _column_header(label: str, lane: int, target_w: int) -> Separator: + """The column header of one section: ``TARGET`` over the chips, then ``label``. + + It comes immediately after the heading of its section. Thus it pins with the heading + while the rows of the section scroll. It starts after the pointer, the mark, and the + space after the mark, so that ``TARGET`` is over the first cell of each chip. + + Args: + label: The name of the last lane: ``TRIGGER`` in the outbox, ``OUTCOME`` in the + history. + lane: The icon column of the list in cells (refer to :func:`_menu_items`). + target_w: The width of the widest chip in cells, without the gap after it. + """ + + def header(width: int) -> str: + # The rows get the width less the 2 cells of the pointer, so the header asks for + # the TARGET lane at that width too. Thus each label stays over its lane. + target = _target_lane(lane, target_w, width - 2) + lanes = [Lane("TARGET", target + _GAP), Lane(label)] + return column_header(lanes, width, indent=2 + lane + 1) + + return Separator(header) + + +def _target_lane(lane: int, target_w: int, avail: int) -> int: + """The width of the TARGET lane in a row that has ``avail`` cells after the pointer. + + The lane is as wide as the widest chip. Where the last lane then gets fewer than + :data:`_LAST_MIN` cells, the TARGET lane gives cells back, and a chip that is too wide + breaks off on its crack. It is never narrower than its label. + """ + room = avail - (lane + 1) - _GAP - _LAST_MIN + return max(cell_len("TARGET"), min(target_w, room)) + + def _entry_mark(mark: str, style: str, lane: int) -> Text: """The status mark of an entry, with a tint, and padded to the icon column of the outbox. @@ -302,62 +463,82 @@ def _entry_mark(mark: str, style: str, lane: int) -> Text: lane: The icon column of the list in cells (refer to :func:`_menu_items`). Returns: - The mark, followed by enough spaces to start the words in the column after it. + The mark, followed by enough spaces to start the words in the column after it. The + style is a span on the mark only. As the base style of the row, it made each lane + after the mark bold. """ - text = Text(mark, style=style) + text = Text() + text.append(mark, style=style) text.append(" " * (lane - cell_len(mark) + 1)) return text -def _waiting_row(ctx: AppContext, message: QueuedMessage, lane: int = _MARK_LANE) -> Text: - """One waiting entry: the recipient, the body, and what the entry waits for. +def _target_chip(message: QueuedMessage) -> Text: + """The TARGET of an entry: its recipient, as a destination chip. - The recipient is the destination of the message, so it is a chip that opens on the - notch (refer to :func:`~meshterm.ui.widgets.hop_chip`), in the hue of its key. + The recipient is the destination of the message, so the chip opens on the notch (refer + to :func:`~meshterm.ui.widgets.hop_chip`). A waiting recipient has the hue of its key. A + finished entry is history, and all of its row is muted. Thus its chip is muted too. + """ + if message.status == QUEUED: + return name_chip(message.node_name, message.node_key, role=DESTINATION) + return hop_chip(PathHop(message.node_name, style="muted"), role=DESTINATION) + + +def _row(mark: Text, chip: Text, target_w: int, last: Text) -> Text: + """One entry row: the mark, the chip fitted to the TARGET lane, then the last lane.""" + if chip.cell_len > target_w: + chip = cut_to(chip, target_w) # the chip continues past its lane, so it cracks + mark.append_text(chip) + mark.append(" " * (max(0, target_w - chip.cell_len) + _GAP)) + mark.append_text(last) + return mark + + +def _trigger(ctx: AppContext, message: QueuedMessage) -> Text: + """The TRIGGER of a waiting entry: what it waits for before it goes out. + + The rules are those of :meth:`~meshterm.services.courier.CourierService.eligible`, in + the same order: a schedule, then the backoff after a failed try, then a sign of life. """ - row = _entry_mark("⏳", "warn", lane) - row.append_text(name_chip(message.node_name, message.node_key, role=DESTINATION)) - row.append(f" β€œ{_shorten(message.text)}”", style="muted") - row.append(" Β· ", style="muted") now = utcnow() if message.not_before is not None and now < message.not_before: - row.append(f"scheduled {_local_stamp(message.not_before)}", style="brand") - else: - retry = ctx.courier.next_retry_s(message, now) - if retry is not None: - row.append( - f"try {message.attempts} Β· retry in ~{max(1, round(retry / 60))} m", - style="warn", - ) - elif message.attempts > 0: - row.append(f"try {message.attempts} Β· waiting to hear it again", style="muted") - elif ctx.courier.heard_recently(message.node_key, now): - row.append("contact is fresh β€” next pass", style="ok") - else: - row.append("waiting to hear the contact", style="muted") - return row + return Text(f"at {_local_stamp(message.not_before)}", style="brand") + retry = ctx.courier.next_retry_s(message, now) + if retry is not None: + minutes = max(1, round(retry / 60)) + return Text(f"retry in ~{minutes} m Β· try {message.attempts}", style="warn") + if message.attempts > 0: + return Text(f"when heard again Β· try {message.attempts}", style="muted") + if ctx.courier.heard_recently(message.node_key, now): + return Text("next pass β€” contact is fresh", style="ok") + return Text("when heard", style="muted") -def _done_row(message: QueuedMessage, lane: int = _MARK_LANE) -> Text: - """One finished entry: the outcome mark, the recipient, the body, and when it ended. - - The recipient is a destination chip, the same as in the outbox. But a finished entry is - history, and all of its row is muted. Thus the chip is muted too. - """ - if message.status == DELIVERED: - row = _entry_mark("βœ“", "ok", lane) - else: - row = _entry_mark("βœ—", "err", lane) - row.append_text(hop_chip(PathHop(message.node_name, style="muted"), role=DESTINATION)) - row.append(f" β€œ{_shorten(message.text)}”", style="muted") +def _outcome(message: QueuedMessage) -> str: + """The OUTCOME of a finished entry: how it ended, when, and after how many tries.""" when = message.finished or message.created verb = "delivered" if message.status == DELIVERED else "gave up" - row.append( - f" Β· {verb} {format_ago(age_seconds(when))}" - f" Β· {message.attempts} attempt{'s' if message.attempts != 1 else ''}", - style="muted", + tries = f"{message.attempts} attempt{'s' if message.attempts != 1 else ''}" + return f"{verb} {format_ago(age_seconds(when))} Β· {tries}" + + +def _waiting_row( + ctx: AppContext, message: QueuedMessage, lane: int = _MARK_LANE, target_w: int = 0 +) -> Text: + """One waiting entry: the mark, the TARGET, and the TRIGGER.""" + return _row( + _entry_mark("⏳", "warn", lane), _target_chip(message), target_w, _trigger(ctx, message) ) - return row + + +def _done_row(message: QueuedMessage, lane: int = _MARK_LANE, target_w: int = 0) -> Text: + """One finished entry: the outcome mark, the TARGET, and the OUTCOME.""" + if message.status == DELIVERED: + mark = _entry_mark("βœ“", "ok", lane) + else: + mark = _entry_mark("βœ—", "err", lane) + return _row(mark, _target_chip(message), target_w, Text(_outcome(message), style="muted")) # --- the flows -------------------------------------------------------------------------- @@ -367,6 +548,10 @@ def _done_row(message: QueuedMessage, lane: int = _MARK_LANE) -> Text: #: an Enter that commits. Esc cancels the queueing step in which the picker is. _PICK_HINT = "↑↓ move Β· ^←→↑↓ sort Β· type to filter Β· Enter select Β· Esc cancel" +#: The instruction above the message field: the same when the user writes the message and +#: when the user edits it. +_MESSAGE_PROMPT = "Delivered as a normal direct message when its moment comes." + class CourierRecipientScreen(ContactListScreen): """The recipient picker on the shared contact list. @@ -467,8 +652,9 @@ async def _queue_flow(ctx: AppContext, contacts: list[Contact]) -> None: lambda vals: _next_recipient(visit), lambda vals: session.text( f"Message for {vals[0].name}", - prompt="Delivered as a normal direct message when its moment comes.", + prompt=_MESSAGE_PROMPT, byte_limit=DM_BYTE_LIMIT, + compose=True, default=vals[1] or "", ), lambda vals: _schedule_step(ctx, vals[0].name), @@ -569,60 +755,97 @@ async def _pick_schedule(ctx: AppContext, name: str): return when -async def _entry_actions(ctx: AppContext, ident: int) -> None: - """Float the action menu of one entry: send now, cancel, or only look at it.""" +def _not_blank(text: str) -> bool | str: + """The validator of an edited message: an empty message is refused, not sent.""" + return True if text.strip() else "The message is empty β€” Esc keeps it as it was." + + +async def _open_entry(ctx: AppContext, ident: int) -> None: + """Open the message of one entry: to edit while it waits, to read after it finished. + + The edit holds the entry (refer to + :meth:`~meshterm.services.courier.CourierService.holding`). Without the hold, a pass + can send the old text while the prompt is open. A try that is already in progress + cannot be stopped, so the message then opens to read, with a note. + """ session = ctx.ui.session store = ctx.courier_store message = store.get(ident) if message is None: return - if message.status != QUEUED: - # A finished entry has no actions. Show its full text instead. + title = f"Message for {message.node_name}" + if message.status != QUEUED or ctx.courier.in_flight(ident): body = Text(message.text) - body.append( - f"\n\n{message.status} Β· {message.attempts} attempt" - f"{'s' if message.attempts != 1 else ''}", - style="muted", - ) - await session.message_dialog(body, title=message.node_name) + if message.status != QUEUED: + body.append(f"\n\n{_outcome(message)}", style="muted") + else: + body.append("\n\nsending now β€” edit it after this attempt", style="muted") + await session.message_dialog(body, title=title) return - # One measured column for both rows. πŸ“€ draws two cells and βœ— draws one cell. The Cancel - # row measured only its own mark, so its words started one column to the left of the - # words of Send now. Where the platform draws no icon lane, both rows have no icon, and - # the err tint of Cancel moves onto its words. - lane = icon_lane(("πŸ“€", "βœ—")) - items = [ - Choice(marked_label("πŸ“€", "Send now β€” one forced attempt", "", lane=lane), "send"), - Choice(marked_label("βœ—", "Cancel this message", "err", lane=lane), "cancel"), - ] - picked = await session.select( - f"{message.node_name} β€” β€œ{_shorten(message.text, 28)}”", - items, - filterable=False, - footer_hint="↑↓ move Β· Enter select Β· Esc back", - ) - if picked == "cancel": - store.cancel(ident) - elif picked == "send": - try: - async with ctx.ui.busy_overlay(f"sending to {message.node_name}…"): - outcome = await ctx.courier.attempt_now(ident) - except Exception as exc: # noqa: BLE001 - show the failure, and keep the queue - await session.message_dialog(Text(f"send failed: {exc}", style="err"), title="Courier") - return - notes = { - "delivered": Text("βœ“ delivered β€” acknowledged by the contact", style="ok"), - "no ack": Text( - "sent, but no acknowledgement β€” it stays queued and the courier " - "will retry with backoff", - style="warn", - ), - "gave up": Text("no acknowledgement β€” the retry budget is spent", style="err"), - "unknown contact": Text( - "the device's contact list doesn't know this contact yet; it stays queued", - style="warn", - ), - "busy": Text("another delivery is in flight β€” try again in a moment", style="muted"), - "gone": Text("this entry is no longer queued", style="muted"), - } - await session.message_dialog(notes.get(outcome, Text(outcome)), title="Courier") + with ctx.courier.holding(ident): + text = await session.text( + title, + prompt=_MESSAGE_PROMPT, + default=message.text, + validate=_not_blank, + byte_limit=DM_BYTE_LIMIT, + compose=True, + ) + if text is None or text == message.text: + return + if not store.edit(ident, text): + # A late acknowledgement can finish the entry while the prompt is open. + await session.message_dialog( + Text("this message left the outbox during the edit β€” it was not changed", style="warn"), + title="Courier", + ) + + +async def _delete_entry(ctx: AppContext, ident: int) -> None: + """Ask to delete one entry (waiting or finished), with the red confirm of a delete.""" + store = ctx.courier_store + message = store.get(ident) + if message is None: + return + if message.status == QUEUED: + prompt = f"Delete the message for {message.node_name}? It will not be sent." + else: + prompt = f"Delete the message for {message.node_name} from the history?" + if await ctx.ui.dialog( + prompt, + [("Cancel", False), ("Delete", True)], + title="Delete message", + default=1, + destructive=True, + ): + store.delete(ident) + + +async def _send_now(ctx: AppContext, ident: int) -> None: + """Force one delivery try of a waiting entry, and show the outcome in a dialog.""" + session = ctx.ui.session + message = ctx.courier_store.get(ident) + if message is None or message.status != QUEUED: + return + try: + async with ctx.ui.busy_overlay(f"sending to {message.node_name}…"): + outcome = await ctx.courier.attempt_now(ident) + except Exception as exc: # noqa: BLE001 - show the failure, and keep the queue + await session.message_dialog(Text(f"send failed: {exc}", style="err"), title="Courier") + return + notes = { + "delivered": Text("βœ“ delivered β€” acknowledged by the contact", style="ok"), + "no ack": Text( + "sent, but no acknowledgement β€” it stays queued and the courier " + "will retry with backoff", + style="warn", + ), + "gave up": Text("no acknowledgement β€” the retry budget is spent", style="err"), + "unknown contact": Text( + "the device's contact list doesn't know this contact yet; it stays queued", + style="warn", + ), + "busy": Text("another delivery is in flight β€” try again in a moment", style="muted"), + "gone": Text("this entry is no longer queued", style="muted"), + } + await session.message_dialog(notes.get(outcome, Text(outcome)), title="Courier") diff --git a/meshterm/ui/tui/prompt.py b/meshterm/ui/tui/prompt.py index d1d6a38..1a6db37 100644 --- a/meshterm/ui/tui/prompt.py +++ b/meshterm/ui/tui/prompt.py @@ -187,7 +187,12 @@ class LineEditor: return i def render( - self, mask: bool = False, *, overflow_at: int | None = None, slots: int | None = None + self, + mask: bool = False, + *, + overflow_at: int | None = None, + slots: int | None = None, + compose: bool = False, ) -> Text: """Render the current line with a reverse-video cursor cell. @@ -200,12 +205,22 @@ class LineEditor: slots: When set, render exactly this number of fixed positions (a masked PIN field). A typed position shows a bullet, and a blank position shows a muted centre dot. This argument has priority over ``mask`` and ``overflow_at``. + compose: When ``True``, draw the line as the compose line of a chat draws it: + the ``β€Ί`` in the ``cursor`` white and the text in the ``compose`` white + (refer to :meth:`~meshterm.ui.compose.MentionEditor.render_line`). Thus a + message that the user writes outside a chat looks the same as in a chat. """ if slots is not None: return self._render_slots(slots) shown = MASK_MARK * len(self.text) if mask else self.text - text = Text("β€Ί ", style="accent") - self._append_run(text, shown, 0, len(shown), overflow_at) + if compose: + # The style goes on the ``β€Ί`` alone, as in the chat. As the base style of the + # line, it also colours the typed text, and the compose white is then bold. + text = Text() + text.append("β€Ί ", style="cursor") + else: + text = Text("β€Ί ", style="accent") + self._append_run(text, shown, 0, len(shown), overflow_at, "compose" if compose else None) if self.cursor >= len(shown): # cursor past the last character β†’ trailing block text.append(" ", style="reverse") return text @@ -293,6 +308,7 @@ class TextScreen(_KeylessDialog): help_text: str = "", password: bool = False, byte_limit: int | None = None, + compose: bool = False, footer_hint: str = "Enter accept Β· Esc cancel", ) -> None: """Build a text prompt. @@ -312,6 +328,8 @@ class TextScreen(_KeylessDialog): submission when the text is longer than the limit. Use it for a field that feeds a packet with a size limit (a direct message, a courier entry). Keep ``None`` for a field with no limit. + compose: When ``True``, the field is a message, and it has the colours of the + compose line of a chat (refer to :meth:`LineEditor.render`). footer_hint: The key hint in the footer. """ super().__init__() @@ -323,6 +341,7 @@ class TextScreen(_KeylessDialog): self._help = help_text self._password = password self._byte_limit = byte_limit + self._compose = compose self._error = "" @property @@ -358,7 +377,7 @@ class TextScreen(_KeylessDialog): if self._prompt: parts.append(Text(self._prompt)) parts.append(Text("")) - field = self._editor.render(mask=self._password) + field = self._editor.render(mask=self._password, compose=self._compose) if self._byte_limit is not None: # The gauge pins to the right edge of the field: a steady fuel gauge in the corner, # exactly as the chat compose bar draws it (both through ``byte_counter``). diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index 3b77e3e..700fb55 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -1526,6 +1526,7 @@ class TuiSession: help_text: str = "", password: bool = False, byte_limit: int | None = None, + compose: bool = False, floating: bool = False, ) -> str | None: """Show a text prompt. Return the string, or ``None`` if the user cancelled. @@ -1539,6 +1540,9 @@ class TuiSession: ``byte_limit`` puts the shared UTF-8 byte gauge on the field, and blocks a submission that is longer than the limit. Use it for a field that goes into a packet with a maximum size (refer to :class:`TextScreen`). + + ``compose`` gives the field the colours of the compose line of a chat. Use it for a + field that holds a message. """ screen = TextScreen( title, @@ -1548,6 +1552,7 @@ class TuiSession: help_text=help_text, password=password, byte_limit=byte_limit, + compose=compose, ) runner = self.run_dialog if floating else self.run_screen result = await runner(screen) diff --git a/tests/test_courier.py b/tests/test_courier.py index d4c0417..f6043fc 100644 --- a/tests/test_courier.py +++ b/tests/test_courier.py @@ -25,7 +25,6 @@ from meshterm.services.courier import FRESH_S, MAX_ATTEMPTS, CourierService from meshterm.ui.courier_screen import ( CANCEL_SCHEDULE, WHEN_HEARD, - _entry_actions, _pick_schedule, parse_clock, ) @@ -121,6 +120,32 @@ def test_store_caps_the_finished_history(tmp_path: Path) -> None: assert store.get(keeper.ident) is not None +def test_store_edits_a_waiting_body_and_deletes_any_entry(tmp_path: Path) -> None: + """An edit changes only a waiting body. A delete removes an entry of either section. + + A finished body is what went out, so it never changes. The edit keeps the schedule and + the attempts, because the backoff counts tries to reach the contact, not versions of + the text. + """ + path = tmp_path / "courier.json" + store = CourierStore(path) + when = utcnow() + timedelta(hours=1) + waiting = store.queue(NODE, "Hub", "first draft", not_before=when) + store.note_attempt(waiting.ident) + done = store.queue(NODE, "Hub", "sent text") + store.mark_delivered(done.ident) + + assert store.edit(waiting.ident, "second draft") is True + again = CourierStore(path).get(waiting.ident) + assert again.text == "second draft" and again.not_before == when and again.attempts == 1 + assert store.edit(done.ident, "rewritten") is False + assert store.get(done.ident).text == "sent text" + + assert store.delete(done.ident) is True and store.get(done.ident) is None + assert store.delete(waiting.ident) is True and store.entries() == [] + assert store.delete(waiting.ident) is False + + # --- eligibility ------------------------------------------------------------------------- @@ -251,6 +276,40 @@ async def test_attempt_now_forces_a_send(tmp_path: Path) -> None: assert await service.attempt_now(entry.ident) == "gone" # the entry is already settled +async def test_a_held_entry_waits_while_the_user_edits_it(tmp_path: Path) -> None: + """A pass does not try an entry that the user edits, and tries it after the edit. + + Without the hold, a pass could send the old text while the edit prompt is open. + """ + service = _service(tmp_path, [True]) + ctx = service._ctx + entry = ctx.courier_store.queue(NODE, "Hub", "hello") + service._heard[NODE] = utcnow() + with service.holding(entry.ident): + await service._pass() + assert ctx.chat.sent == [] + await service._pass() + assert ctx.chat.sent == [("Hub", "hello")] + + +async def test_in_flight_names_the_entry_that_a_try_sends(tmp_path: Path) -> None: + """While a try runs, ``in_flight`` is true for its entry only. After the try, it is false.""" + service = _service(tmp_path, [True]) + ctx = service._ctx + entry = ctx.courier_store.queue(NODE, "Hub", "hello") + seen: list[tuple[bool, bool]] = [] + send = ctx.chat.send_direct + + async def spy(contact, text, **kwargs): # noqa: ANN001, ANN202 + seen.append((service.in_flight(entry.ident), service.in_flight(entry.ident + 1))) + return await send(contact, text, **kwargs) + + ctx.chat.send_direct = spy + await service.attempt_now(entry.ident) + assert seen == [(True, False)] + assert not service.in_flight(entry.ident) + + # --- the scripted CLI actions ------------------------------------------------------------- @@ -534,7 +593,7 @@ def test_outbox_rows_recompute_live_state_per_repaint(tmp_path: Path) -> None: ctx = _outbox_ctx(tmp_path) entry = ctx.courier_store.queue(NODE, "Hub", "patience") screen = CourierOutboxScreen(ctx) - assert "waiting to hear the contact" in _outbox_plain(screen) + assert "when heard" in _outbox_plain(screen) # An attempt just happened. The same row now shows the countdown to the next attempt. # ``refresh()`` is not necessary, because the callable title reads the entry again at @@ -561,9 +620,9 @@ def test_outbox_draws_each_recipient_as_a_destination_chip(tmp_path: Path, power def _title_plain(choice) -> str: """The label of a row as plain text. - It resolves a live (callable) title in the same way as a paint. + It resolves a live (callable) title at each read, in the same way as a paint. """ - title = choice.title() if callable(choice.title) else choice.title + title = choice.label return title.plain if isinstance(title, Text) else title @@ -583,22 +642,6 @@ def _outbox_titles(tmp_path: Path) -> list[str]: return [_title_plain(choice) for choice in CourierOutboxScreen(ctx)._choices()] -async def _entry_action_titles(tmp_path: Path) -> list[str]: - """The labels in the action menu of a waiting entry (the menu closes with no answer).""" - offered: list = [] - - class _Session: - async def select(self, title, items, **kwargs): - offered.extend(items) - return None - - store = CourierStore(tmp_path / "courier.json") - entry = store.queue(NODE, "Hub", "hello") - ctx = SimpleNamespace(ui=SimpleNamespace(session=_Session()), courier_store=store) - await _entry_actions(ctx, entry.ident) - return [_title_plain(choice) for choice in offered] - - def _word_starts(rows: list[str], leads: dict[str, str]) -> set[int]: """The display cell where the first word of each row starts. @@ -612,33 +655,29 @@ def _word_starts(rows: list[str], leads: dict[str, str]) -> set[int]: return starts -async def test_courier_rows_start_every_label_in_the_same_cell(tmp_path: Path) -> None: - """The two lists of the courier have one icon column, with no regard for the width of each mark. +def test_courier_rows_start_every_label_in_the_same_cell(tmp_path: Path) -> None: + """The outbox has one icon column, with no regard for the width of each mark. The outbox has marks of two cells (⏳ a waiting entry, πŸ“¨ the queue row) and marks of one cell (βœ“ βœ— a finished entry, πŸ—‘ the clear row). It wrote each as ``mark + " "``. Thus a finished recipient was one column to the left of a waiting recipient, and *Clear - finished* was one column to the left of *Queue a message…*. The actions of an entry - had the same fault with πŸ“€ over βœ—. The measure is cells, not characters, because the - terminal aligns cells. + finished* was one column to the left of *Queue a message…*. The measure is cells, not + characters, because the terminal aligns cells. """ outbox = {"Waiting": "⏳", "Queue": "πŸ“¨", "Landed": "βœ“", "Lost": "βœ—", "Clear": "πŸ—‘"} - actions = {"Send": "πŸ“€", "Cancel": "βœ—"} assert {cell_len(mark) for mark in outbox.values()} == {1, 2}, "a mixed list, or no proof" - assert {cell_len(mark) for mark in actions.values()} == {1, 2} assert len(_word_starts(_outbox_titles(tmp_path), outbox)) == 1 - assert len(_word_starts(await _entry_action_titles(tmp_path), actions)) == 1 -async def test_courier_command_rows_go_bare_where_the_platform_draws_no_icons( +def test_courier_command_rows_go_bare_where_the_platform_draws_no_icons( tmp_path: Path, ) -> None: """If there is no icon lane, the command icons go with no padding. The entry marks stay. The βœ“, βœ—, or ⏳ of an entry is its outcome, not decoration. Thus the PicoCalc keeps it, - and it keeps those rows in line with each other. The queue, clear, send, and cancel rows - lose their icons in the same way as each other command row there. + and it keeps those rows in line with each other. The queue and clear rows lose their + icons in the same way as each other command row there. """ from meshterm.platforms import PICOCALC_LYRA, REGULAR, set_platform @@ -648,14 +687,228 @@ async def test_courier_command_rows_go_bare_where_the_platform_draws_no_icons( assert "Queue a message…" in rows and "Clear finished" in rows marks = {"Waiting": "⏳", "Landed": "βœ“", "Lost": "βœ—"} assert len(_word_starts(rows, marks)) == 1 - assert await _entry_action_titles(tmp_path / "actions") == [ - "Send now β€” one forced attempt", - "Cancel this message", - ] finally: set_platform(REGULAR) +def _cell(line: str, word: str) -> int: + """The display cell where ``word`` starts in ``line``.""" + return cell_len(line[: line.index(word)]) + + +def test_outbox_rows_are_target_and_trigger_under_column_headers(tmp_path: Path) -> None: + """Each section is a table: TARGET and TRIGGER in the outbox, TARGET and OUTCOME after it. + + A row does not show its message, because Enter opens it. Each section has its own + header, so the lane after TARGET has one meaning in each section. That lane starts in + the same cell in both sections, and each label is over its lane. + """ + from meshterm.ui.courier_screen import CourierOutboxScreen + + ctx = _outbox_ctx(tmp_path) + ctx.courier_store.queue(NODE, "Waiting", "hold this text") + landed = ctx.courier_store.queue(NODE, "Landed Longer Name", "got it") + ctx.courier_store.mark_delivered(landed.ident) + lines = _outbox_plain(CourierOutboxScreen(ctx)).splitlines() + + assert not any("hold this" in line or "got it" in line for line in lines) + trigger = next(line for line in lines if "TRIGGER" in line) + outcome = next(line for line in lines if "OUTCOME" in line) + waiting = next(line for line in lines if "Waiting" in line) + done = next(line for line in lines if "Landed" in line) + assert _cell(trigger, "TARGET") == _cell(waiting, "Waiting") == _cell(done, "Landed") + assert _cell(outcome, "TARGET") == _cell(trigger, "TARGET") + assert _cell(trigger, "TRIGGER") == _cell(waiting, "when heard") + assert _cell(outcome, "OUTCOME") == _cell(done, "delivered") == _cell(trigger, "TRIGGER") + + +def test_outbox_triggers_name_what_each_entry_waits_for(tmp_path: Path) -> None: + """The TRIGGER lane says what sends the entry: a time, the end of a backoff, or a contact.""" + from meshterm.ui.courier_screen import _trigger + + ctx = _outbox_ctx(tmp_path) + store = ctx.courier_store + later = store.queue(NODE, "Hub", "x", not_before=utcnow() + timedelta(hours=2)) + assert _trigger(ctx, later).plain.startswith("at ") + plain = store.queue(NODE, "Hub", "y") + assert _trigger(ctx, plain).plain == "when heard" + ctx.courier._heard[NODE] = utcnow() + assert _trigger(ctx, plain).plain == "next pass β€” contact is fresh" + store.note_attempt(plain.ident) + assert _trigger(ctx, store.get(plain.ident)).plain == "retry in ~5 m Β· try 1" + + +def test_outbox_cut_ends_on_an_ellipsis_not_on_a_stray_crack(tmp_path: Path, powerline) -> None: + """A row that is wider than the screen ends in ``…``, not in a half block of the chip fill. + + The cut lands in the TRIGGER text, after the chip. The crack is for a cut inside a + chip. Here it once drew a half block in the fill of the TARGET chip at the right edge of + the row, far from the chip. + """ + from meshterm.ui.courier_screen import CourierOutboxScreen + from meshterm.ui.pathline import CRACK_TAIL + + powerline(True) + ctx = _outbox_ctx(tmp_path) + ctx.courier_store.queue(NODE, "Hub", "hello") + ctx.courier._heard[NODE] = utcnow() # the longest trigger: "next pass β€” contact is fresh" + body = _outbox_plain(CourierOutboxScreen(ctx), 40).splitlines() + row = next(line for line in body if "⏳" in line) + assert cell_len(row) == 40 + assert row.endswith("…") and CRACK_TAIL not in row + + +def test_a_long_target_gives_cells_to_the_trigger(tmp_path: Path, powerline) -> None: + """On a narrow screen, a long name breaks off on its crack, and the trigger stays readable. + + The TARGET lane is as wide as the widest chip only while the TRIGGER lane keeps its + minimum. The header follows the same lane, so TRIGGER stays over the triggers. + """ + from meshterm.ui.courier_screen import _LAST_MIN, CourierOutboxScreen + from meshterm.ui.pathline import CRACK_TAIL + + powerline(True) + ctx = _outbox_ctx(tmp_path) + ctx.courier_store.queue(NODE, "A Rather Long Contact Name For Width", "hello") + lines = _outbox_plain(CourierOutboxScreen(ctx), 53).splitlines() + header = next(line for line in lines if "TARGET" in line) + row = next(line for line in lines if "⏳" in line) + assert row.rstrip().endswith("when heard") + assert CRACK_TAIL in row # the chip continues past its lane + assert _cell(header, "TRIGGER") == _cell(row, "when heard") <= 53 - _LAST_MIN + + +def test_outbox_keys_act_only_on_the_rows_they_name(tmp_path: Path) -> None: + """``^R`` sends a waiting entry, Delete asks to remove an entry, and neither acts elsewhere. + + The footer and the F-key lane name each key only on the rows on which it acts. + """ + from meshterm.ui.courier_screen import _QUEUE, CourierOutboxScreen + from meshterm.ui.tui import DeleteRequest + + ctx = _outbox_ctx(tmp_path) + waiting = ctx.courier_store.queue(NODE, "Waiting", "hold this") + landed = ctx.courier_store.queue(NODE, "Landed", "got it") + ctx.courier_store.mark_delivered(landed.ident) + resolved: list = [] + + def on(value) -> CourierOutboxScreen: # noqa: ANN001 + screen = CourierOutboxScreen(ctx, default=value) + screen.resolve = resolved.append # type: ignore[method-assign] + return screen + + screen = on(("msg", waiting.ident)) + assert screen.footer_hint == ( + "↑↓ move Β· type to filter Β· Enter open Β· ^R send Β· Del delete Β· Esc back" + ) + assert cell_len(screen.footer_hint) <= 72 + slot = screen.picocalc_lyra_lane[2] + assert (slot.label, slot.opp_label, slot.enabled, slot.opp_enabled) == ( + "Send", + "Delete", + True, + True, + ) + screen.handle("retry") + assert resolved.pop() == ("send", waiting.ident) + + screen = on(("msg", landed.ident)) + assert "^R" not in screen.footer_hint and "Del delete" in screen.footer_hint + assert not screen.picocalc_lyra_lane[2].enabled + screen.handle("retry") + assert resolved == [] # a finished entry left the outbox, so there is nothing to send + screen.handle("delete") + assert resolved.pop() == DeleteRequest(("msg", landed.ident)) + + screen = on(_QUEUE) + assert screen.footer_hint == "↑↓ move Β· type to filter Β· Enter open Β· Esc back" + screen.handle("delete") + screen.handle("retry") + assert resolved == [] + + +class _EntrySession: + """A script for the dialogs of one entry. It records what MeshTerm asked and showed.""" + + def __init__(self, answer: str | None = None, on_text=None) -> None: # noqa: ANN001 + self.answer = answer + self.on_text = on_text + self.asked: list[dict] = [] + self.shown: list[tuple[str, str]] = [] + + async def text(self, title, **kwargs): # noqa: ANN001, ANN201 + self.asked.append({"title": title, **kwargs}) + if self.on_text is not None: + await self.on_text() + return self.answer + + async def message_dialog(self, body, *, title=""): # noqa: ANN001, ANN201 + self.shown.append((title, body.plain if isinstance(body, Text) else str(body))) + + +async def test_enter_on_a_waiting_entry_edits_its_message(tmp_path: Path) -> None: + """Enter opens the message of a waiting entry in a compose field, and Enter there saves it. + + The entry is held while the prompt is open. Thus a pass in that time sends nothing, + and the message that goes out later is the edited one. + """ + from meshterm.ui.courier_screen import _open_entry + + ctx = _outbox_ctx(tmp_path) + entry = ctx.courier_store.queue(NODE, "Hub", "old text") + ctx.courier._heard[NODE] = utcnow() + session = _EntrySession("new text", on_text=ctx.courier._pass) + ctx.ui = SimpleNamespace(session=session) + + await _open_entry(ctx, entry.ident) + asked = session.asked[0] + assert asked["title"] == "Message for Hub" + assert asked["default"] == "old text" and asked["compose"] is True + assert ctx.chat.sent == [] # the pass during the prompt left the held entry alone + assert ctx.courier_store.get(entry.ident).text == "new text" + await ctx.courier._pass() + assert ctx.chat.sent == [("Hub", "new text")] + + +async def test_enter_on_a_finished_entry_shows_its_message(tmp_path: Path) -> None: + """A finished message is history. Enter shows it with its outcome, and asks nothing.""" + from meshterm.ui.courier_screen import _open_entry + + ctx = _outbox_ctx(tmp_path) + entry = ctx.courier_store.queue(NODE, "Hub", "what went out") + ctx.courier_store.mark_delivered(entry.ident) + session = _EntrySession() + ctx.ui = SimpleNamespace(session=session) + + await _open_entry(ctx, entry.ident) + assert session.asked == [] + title, body = session.shown[0] + assert title == "Message for Hub" + assert body.startswith("what went out") and "delivered" in body + + +async def test_delete_asks_in_red_and_removes_the_entry(tmp_path: Path) -> None: + """Delete is a red Cancel/Delete confirm. Cancel keeps the entry, and Delete removes it.""" + from meshterm.ui.courier_screen import _delete_entry + + ctx = _outbox_ctx(tmp_path) + entry = ctx.courier_store.queue(NODE, "Hub", "nope") + asked: list[dict] = [] + answers = [False, True] + + async def dialog(prompt, buttons, **kwargs): # noqa: ANN001, ANN202 + asked.append({"prompt": prompt, "buttons": buttons, **kwargs}) + return answers.pop(0) + + ctx.ui = SimpleNamespace(dialog=dialog) + await _delete_entry(ctx, entry.ident) + assert ctx.courier_store.get(entry.ident) is not None + await _delete_entry(ctx, entry.ident) + assert ctx.courier_store.get(entry.ident) is None + assert asked[0]["destructive"] is True and asked[0]["default"] == 1 + assert [label for label, _value in asked[0]["buttons"]] == ["Cancel", "Delete"] + + # --- the recipient picker ---------------------------------------------------------------- diff --git a/tests/test_tui.py b/tests/test_tui.py index a6bf0e2..8ca1131 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -1418,6 +1418,28 @@ def test_text_screen_byte_limit_gauges_and_blocks_an_oversize_entry() -> None: assert _run(screen, "enter") == "hello wor" +def test_text_screen_compose_field_has_the_colours_of_the_chat_compose_line() -> None: + """A message field draws its ``β€Ί`` in the cursor white and its text in the compose white. + + These are the colours of the compose line of a chat. A plain field keeps the accent + ``β€Ί`` and the default colour of the text. + """ + from meshterm.ui.tui.prompt import LineEditor + + editor = LineEditor("hi") + line = editor.render(compose=True) + assert not str(line.style) # a base style also colours the typed text + prompt = {str(span.style) for span in line.spans if span.start == 0} + typed = {str(span.style) for span in line.spans if (span.start, span.end) == (2, 3)} + assert (prompt, typed) == ({"cursor"}, {"compose"}) + plain = editor.render() + assert str(plain.style) == "accent" + assert "compose" not in {str(span.style) for span in plain.spans} + + screen = TextScreen("Message for Hub", byte_limit=10, compose=True) + assert screen._compose is True + + def test_line_editor_word_motion() -> None: """Ctrl+Left and Ctrl+Right move by word.