diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py index dd4d9b7..3125f71 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -26,7 +26,12 @@ from ..core.channels import split_channel_sender from ..core.events import EventKind, MeshEvent from ..core.models import ChatMessage, Contact, Conversation, Message, utcnow from .theme import name_style, snr_style -from .tui.prompt import _LineEditor +from .tui.prompt import ( + CHANNEL_BYTE_LIMIT, + DM_BYTE_LIMIT, + _LineEditor, + byte_counter, +) from .tui.render import render_hanging, render_lines, right_aligned_tail from .tui.screen import CANCEL, Screen from .tui.spinner import Spinner @@ -54,22 +59,6 @@ _FAILED = ("✗", "err") #: Seconds between spinner frames on a message that is still awaiting its ack. _SPINNER_INTERVAL = 0.12 -#: How many UTF-8 bytes a single outgoing message may carry, by conversation kind. MeshCore's -#: LoRa payload caps a direct message at 150 bytes and an (unscoped) channel broadcast at 130; -#: over the limit the companion would silently drop the packet, so we block the send instead -#: and show the running byte budget in the compose bar. -_DM_BYTE_LIMIT = 150 -_CHANNEL_BYTE_LIMIT = 130 - -#: Byte-counter thresholds (bytes *remaining*) at which its color escalates, plus the two -#: mid-band hues. The theme's ``warn``/``err`` sit too close together (an amber that reads -#: orange, then red), so the counter names a truer yellow and orange directly to keep the -#: green→yellow→orange→red fuel gauge visibly stepped. -_BYTES_TIGHT, _BYTES_LOW = 20, 10 -_BYTES_YELLOW = "bold #fde047" -_BYTES_ORANGE = "bold #ff9500" - - def _sender_hue(sender: str) -> str: """The stable per-sender colour a name is drawn in, keyed on the name's characters. @@ -224,7 +213,7 @@ class ChatScreen(Screen): def _byte_limit(self) -> int: """The UTF-8 byte ceiling for a message in this conversation (channel vs direct).""" - return _CHANNEL_BYTE_LIMIT if self._is_channel else _DM_BYTE_LIMIT + return CHANNEL_BYTE_LIMIT if self._is_channel else DM_BYTE_LIMIT def _used_bytes(self) -> int: """UTF-8 byte length of the current compose buffer — what counts against the limit.""" @@ -244,28 +233,8 @@ class ChatScreen(Screen): return None def _byte_counter(self, limit: int) -> Text: - """The inline ``used/limit`` budget; only ``used`` is colored by how much is left. - - Green with room to spare, yellow within :data:`_BYTES_TIGHT` bytes, orange within - :data:`_BYTES_LOW`, and red once the limit is met or exceeded — so the number reads as - a fuel gauge while the ``/limit`` suffix stays muted (it never changes). - """ - used = self._used_bytes() - counter = Text() - counter.append(str(used), style=self._byte_style(limit - used)) - counter.append(f"/{limit}", style="muted") - return counter - - @staticmethod - def _byte_style(remaining: int) -> str: - """Map bytes remaining to the counter's escalating color (green→yellow→orange→red).""" - if remaining <= 0: - return "err" # at or over the limit — the send is blocked - if remaining <= _BYTES_LOW: - return _BYTES_ORANGE - if remaining <= _BYTES_TIGHT: - return _BYTES_YELLOW - return "ok" + """The inline ``used/limit`` budget — the shared compose gauge (:func:`byte_counter`).""" + return byte_counter(self._used_bytes(), limit) def _name(self, peer: Optional[str]) -> Optional[str]: """Resolve a sender key prefix to a contact name (exact, then prefix match).""" diff --git a/meshterm/ui/courier_screen.py b/meshterm/ui/courier_screen.py index 6f0d3f1..7712a8f 100644 --- a/meshterm/ui/courier_screen.py +++ b/meshterm/ui/courier_screen.py @@ -24,7 +24,7 @@ from rich.text import Text from ..core.courier_store import DELIVERED, QUEUED, QueuedMessage from ..core.models import Contact, utcnow from .menus import back_rows, section_heading -from .tui import Choice, Separator +from .tui import DM_BYTE_LIMIT, Choice, Separator from .watchtower_screen import contact_watch_key from .widgets import ( _DEFAULT_GLYPH, @@ -263,6 +263,7 @@ async def _queue_flow(ctx: "AppContext", contacts: list[Contact]) -> None: text = await session.text( f"Message for {contact.name}", prompt="Delivered as a normal direct message when its moment comes.", + byte_limit=DM_BYTE_LIMIT, ) if not text: return @@ -282,14 +283,25 @@ async def _queue_flow(ctx: "AppContext", contacts: list[Contact]) -> None: #: Sentinel: the schedule picker was cancelled (distinct from "no schedule"). CANCEL_SCHEDULE = object() +#: Sentinel: "send when it's next heard" — the no-schedule choice. It carries its own +#: value (never ``None``) because :meth:`session.select` already returns ``None`` for a +#: cancel; sharing that value made picking this row read as a cancel and silently drop the +#: message instead of queueing it. +WHEN_HEARD = object() + async def _pick_schedule(ctx: "AppContext", name: str): - """Float the when-to-send picker; return an aware UTC time, ``None``, or cancel.""" + """Float the when-to-send picker; return an aware UTC time, ``None``, or cancel. + + ``None`` means "no schedule — send on the next sign of life" (the explicit + *When it's next heard* row); an aware UTC datetime holds until then; + :data:`CANCEL_SCHEDULE` means the user backed out and nothing should queue. + """ session = ctx.ui.session now = utcnow() tomorrow_7 = parse_clock("07:00", now) items = [ - Choice("When it's next heard (recommended)", None), + Choice("When it's next heard (recommended)", WHEN_HEARD), Choice("In 1 h", now + timedelta(hours=1)), Choice("In 3 h", now + timedelta(hours=3)), Choice("In 8 h", now + timedelta(hours=8)), @@ -300,6 +312,12 @@ async def _pick_schedule(ctx: "AppContext", name: str): f"When should {name} get it?", items, filterable=False, footer_hint="↑↓ move · Enter select · Esc cancel", ) + if picked is None: + # Esc on the picker cancels the queueing; "when next heard" is its own explicit + # row (WHEN_HEARD below), so backing out never silently queues something. + return CANCEL_SCHEDULE + if picked is WHEN_HEARD: + return None # no schedule constraint — delivered on the next pass if picked == "custom": while True: typed = await session.text( @@ -311,10 +329,6 @@ async def _pick_schedule(ctx: "AppContext", name: str): when = parse_clock(typed) if when is not None: return when - if picked is None: - # Esc on the picker cancels the queueing; "when next heard" is the explicit - # first row, so backing out never silently queues something. - return CANCEL_SCHEDULE return picked diff --git a/meshterm/ui/surface.py b/meshterm/ui/surface.py index a67085c..8a34406 100644 --- a/meshterm/ui/surface.py +++ b/meshterm/ui/surface.py @@ -757,6 +757,7 @@ class TuiUi(Ui): validate: Optional[Validator] = None, help_text: str = "", password: bool = False, + byte_limit: Optional[int] = None, floating: bool = False, ) -> Optional[str]: """Delegate to the session's text screen.""" @@ -767,6 +768,7 @@ class TuiUi(Ui): validate=validate, help_text=help_text, password=password, + byte_limit=byte_limit, floating=floating, ) diff --git a/meshterm/ui/tui/__init__.py b/meshterm/ui/tui/__init__.py index 1af9b9f..9cbb1ff 100644 --- a/meshterm/ui/tui/__init__.py +++ b/meshterm/ui/tui/__init__.py @@ -17,11 +17,14 @@ from __future__ import annotations from .overlay import BusyOverlay from .progress import ProgressScreen from .prompt import ( + CHANNEL_BYTE_LIMIT, + DM_BYTE_LIMIT, AutocompleteScreen, ConfirmScreen, ReconnectDialog, TextScreen, TypedConfirmDialog, + byte_counter, ) from .screen import CANCEL, BusyScreen, Screen, ScrollScreen from .select import Choice, DeleteRequest, SelectScreen, Separator @@ -46,4 +49,7 @@ __all__ = [ "Spinner", "BusyOverlay", "CANCEL", + "DM_BYTE_LIMIT", + "CHANNEL_BYTE_LIMIT", + "byte_counter", ] diff --git a/meshterm/ui/tui/prompt.py b/meshterm/ui/tui/prompt.py index ec4f78e..fa69124 100644 --- a/meshterm/ui/tui/prompt.py +++ b/meshterm/ui/tui/prompt.py @@ -13,13 +13,53 @@ from rich.cells import cell_len from rich.console import Group, RenderableType from rich.text import Text -from .render import render_lines +from .render import render_lines, right_aligned_tail from .screen import Screen from .spinner import Spinner #: A validator returns ``True`` when the input is acceptable, or an error message to show. Validator = Callable[[str], "bool | str"] +#: MeshCore's LoRa payload caps a direct message at 150 UTF-8 bytes and an (unscoped) +#: channel broadcast at 130; past the cap the companion silently drops the packet. Every +#: compose bar that feeds one of those sends — the chat input, the courier's message entry — +#: counts bytes against these and blocks over the limit rather than losing the packet. +DM_BYTE_LIMIT = 150 +CHANNEL_BYTE_LIMIT = 130 + +#: Byte-counter thresholds (bytes *remaining*) at which its colour escalates, plus the two +#: mid-band hues. The theme's ``warn``/``err`` sit too close together (an amber that reads +#: orange, then red), so the counter names a truer yellow and orange directly to keep the +#: green→yellow→orange→red fuel gauge visibly stepped. +_BYTES_TIGHT, _BYTES_LOW = 20, 10 +_BYTES_YELLOW = "bold #fde047" +_BYTES_ORANGE = "bold #ff9500" + + +def byte_style(remaining: int) -> str: + """Map bytes remaining to the counter's escalating colour (green→yellow→orange→red).""" + if remaining <= 0: + return "err" # at or over the limit — the send is blocked + if remaining <= _BYTES_LOW: + return _BYTES_ORANGE + if remaining <= _BYTES_TIGHT: + return _BYTES_YELLOW + return "ok" + + +def byte_counter(used: int, limit: int) -> Text: + """The inline ``used/limit`` budget; only ``used`` is coloured by how much is left. + + Green with room to spare, yellow within :data:`_BYTES_TIGHT` bytes, orange within + :data:`_BYTES_LOW`, and red once the limit is met or exceeded — so the number reads as a + fuel gauge while the ``/limit`` suffix stays muted (it never changes). The shared gauge + the chat compose bar and the courier's message field both draw. + """ + counter = Text() + counter.append(str(used), style=byte_style(limit - used)) + counter.append(f"/{limit}", style="muted") + return counter + def _center(content: Text, width: int) -> Text: """Center ``content`` in ``width`` with plain padding on both sides. @@ -186,6 +226,7 @@ class TextScreen(Screen): validate: Optional[Validator] = None, help_text: str = "", password: bool = False, + byte_limit: Optional[int] = None, footer_hint: str = "Enter accept · Esc cancel", ) -> None: """Build a text prompt. @@ -200,6 +241,10 @@ class TextScreen(Screen): error and blocks submission. help_text: Optional muted hint shown under the field. password: When ``True``, mask the entered text. + byte_limit: When set, the field carries the shared UTF-8 byte gauge + (:func:`byte_counter`) pinned bottom-right and blocks submission once the + text exceeds it — for a field that feeds a size-capped packet (a direct + message, a courier entry). Left ``None`` for an unbounded field. footer_hint: Footer key hint. """ super().__init__() @@ -210,6 +255,7 @@ class TextScreen(Screen): self._validate = validate self._help = help_text self._password = password + self._byte_limit = byte_limit self._error = "" @property @@ -220,23 +266,37 @@ class TextScreen(Screen): comfortable field minimum — so a short prompt is a tidy box, not a banner stretched across the terminal. The compositor still caps this to the width available. """ + # A byte gauge rides the field's right edge, so the field lane needs room for the + # text, its cursor, and the counter ("150/150" ≈ 8 cells) without them colliding. + field_slack = 12 if self._byte_limit is not None else 4 inner = max( cell_len(self._prompt), cell_len(self.title), cell_len(self._help), cell_len(self.footer_hint), - cell_len(self._editor.text) + 4, # the field plus its cursor and a little slack + cell_len(self._editor.text) + field_slack, 36, # a comfortable minimum so a short field isn't a cramped sliver ) return inner + 8 # panel padding + border, plus horizontal breathing room + def _used_bytes(self) -> int: + """UTF-8 byte length of the field — what counts against ``byte_limit``.""" + return len(self._editor.text.encode("utf-8")) + def render_body(self, width: int) -> list[str]: - """Render the optional prompt, the field, any help text, and a validation error.""" + """Render the optional prompt, the field (+ byte gauge), help, and any error.""" parts: list[RenderableType] = [] if self._prompt: parts.append(Text(self._prompt)) parts.append(Text("")) - parts.append(self._editor.render(mask=self._password)) + field = self._editor.render(mask=self._password) + if self._byte_limit is not None: + # The gauge pins to the field's right edge — a steady fuel gauge in the corner, + # exactly as the chat compose bar draws it (both via ``byte_counter``). + field = right_aligned_tail( + field, byte_counter(self._used_bytes(), self._byte_limit), width + ) + parts.append(field) if self._help: parts.append(Text(self._help, style="muted")) if self._error: @@ -244,9 +304,14 @@ class TextScreen(Screen): return render_lines(Group(*parts), width) def handle(self, action: str, data: str = "") -> None: - """Edit the buffer, submit on Enter (if valid), or cancel on Esc.""" + """Edit the buffer, submit on Enter (if valid and within budget), or cancel on Esc.""" if action == "enter": value = self._editor.text + if self._byte_limit is not None: + over = self._used_bytes() - self._byte_limit + if over > 0: + self._error = f"Too long by {over} byte{'s' if over != 1 else ''} — trim to send." + return if self._validate is not None: result = self._validate(value) if result is not True: diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index 88e131c..29af01b 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -601,6 +601,7 @@ class TuiSession: validate: Optional[Validator] = None, help_text: str = "", password: bool = False, + byte_limit: Optional[int] = None, floating: bool = False, ) -> Optional[str]: """Show a text prompt; return the string or ``None`` if cancelled. @@ -611,6 +612,9 @@ class TuiSession: :meth:`typed_confirm` do (see :meth:`_run_dialog_screen`); with a screen already beneath it there is no difference, so leave it ``False`` for a prompt that is itself a tool's primary screen (the Trace target's typed fallback). + + ``byte_limit`` puts the shared UTF-8 byte gauge on the field and blocks submission + past it — for a field that feeds a size-capped packet (see :class:`TextScreen`). """ screen = TextScreen( title, @@ -619,6 +623,7 @@ class TuiSession: validate=validate, help_text=help_text, password=password, + byte_limit=byte_limit, ) runner = self._run_dialog_screen if floating else self.run_screen result = await runner(screen) diff --git a/tests/test_chat.py b/tests/test_chat.py index 0a2d60d..bc5d215 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -599,24 +599,23 @@ def test_byte_counter_stays_bottom_right_when_the_compose_wraps() -> None: def test_byte_style_escalates_as_budget_runs_out() -> None: """The used-byte color steps green → yellow → orange → red as fewer bytes remain.""" - from meshterm.ui.chat import _BYTES_ORANGE, _BYTES_YELLOW + from meshterm.ui.tui.prompt import _BYTES_ORANGE, _BYTES_YELLOW, byte_style - style = ChatScreen._byte_style - assert style(80) == "ok" # plenty left → green - assert style(20) == _BYTES_YELLOW # within the tight band → yellow - assert style(10) == _BYTES_ORANGE # within the low band → orange - assert style(0) == "err" # limit reached → red - assert style(-5) == "err" # over the limit → still red + assert byte_style(80) == "ok" # plenty left → green + assert byte_style(20) == _BYTES_YELLOW # within the tight band → yellow + assert byte_style(10) == _BYTES_ORANGE # within the low band → orange + assert byte_style(0) == "err" # limit reached → red + assert byte_style(-5) == "err" # over the limit → still red def test_channel_byte_limit_is_lower_than_direct() -> None: """A channel broadcast has a tighter byte budget than a direct message.""" - from meshterm.ui.chat import _CHANNEL_BYTE_LIMIT, _DM_BYTE_LIMIT + from meshterm.ui.tui.prompt import CHANNEL_BYTE_LIMIT, DM_BYTE_LIMIT direct = _screen(_StubSession(), send=None) channel = _channel_screen([]) - assert direct._byte_limit() == _DM_BYTE_LIMIT == 150 - assert channel._byte_limit() == _CHANNEL_BYTE_LIMIT == 130 + assert direct._byte_limit() == DM_BYTE_LIMIT == 150 + assert channel._byte_limit() == CHANNEL_BYTE_LIMIT == 130 def test_overflow_counts_multibyte_characters_by_byte() -> None: diff --git a/tests/test_courier.py b/tests/test_courier.py index c80328e..8ea1081 100644 --- a/tests/test_courier.py +++ b/tests/test_courier.py @@ -9,6 +9,7 @@ from __future__ import annotations import logging from datetime import timedelta from pathlib import Path +from types import SimpleNamespace import pytest @@ -16,7 +17,12 @@ from meshterm.core.courier_store import DONE_CAP, QUEUED, CourierStore from meshterm.core.models import ChatMessage, Contact, utcnow from meshterm.core.watch_store import WatchStore from meshterm.services.courier import FRESH_S, MAX_ATTEMPTS, CourierService -from meshterm.ui.courier_screen import parse_clock +from meshterm.ui.courier_screen import ( + CANCEL_SCHEDULE, + WHEN_HEARD, + _pick_schedule, + parse_clock, +) NODE = "3d" * 6 CONTACT = Contact(name="YUL", public_key="3d" * 32) @@ -341,3 +347,51 @@ def test_parse_clock_finds_the_next_occurrence() -> None: assert parse_clock("7h30", now) is not None assert parse_clock("25:00", now) is None assert parse_clock("soonish", now) is None + + +# --- the schedule picker ------------------------------------------------------------------ + + +class _StubScheduleSession: + """Scripts the when-to-send picker: ``choose`` maps the offered rows to a selection.""" + + def __init__(self, choose) -> None: + self._choose = choose + + async def select(self, title, items, **kwargs): + return self._choose(items) + + async def text(self, *args, **kwargs): # pragma: no cover - unused on these paths + return "" + + +class _ScheduleCtx: + def __init__(self, session) -> None: + self.ui = SimpleNamespace(session=session) + + +async def test_pick_schedule_when_next_heard_returns_no_schedule() -> None: + """Picking *When it's next heard* returns ``None`` (queue with no hold), not a cancel. + + Regression: the row once carried the value ``None``, which ``session.select`` also + returns on Esc, so choosing it read as a cancel and the message was never queued. + """ + ctx = _ScheduleCtx(_StubScheduleSession(lambda items: items[0].value)) + result = await _pick_schedule(ctx, "YUL") + assert result is None + assert result is not CANCEL_SCHEDULE + assert WHEN_HEARD is not None # the row's own sentinel, distinct from Esc's None + + +async def test_pick_schedule_esc_cancels_the_queueing() -> None: + """Esc on the picker (``select`` returns ``None``) backs out without queueing anything.""" + ctx = _ScheduleCtx(_StubScheduleSession(lambda items: None)) + assert await _pick_schedule(ctx, "YUL") is CANCEL_SCHEDULE + + +async def test_pick_schedule_a_fixed_delay_holds_until_its_time() -> None: + """A concrete offset row (e.g. In 1 h) comes back as its aware future datetime.""" + ctx = _ScheduleCtx(_StubScheduleSession(lambda items: items[1].value)) # In 1 h + result = await _pick_schedule(ctx, "YUL") + assert result is not None and result is not CANCEL_SCHEDULE + assert result > utcnow() diff --git a/tests/test_tui.py b/tests/test_tui.py index 06f39a0..03115e6 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -617,6 +617,27 @@ def test_text_screen_edits_and_validates() -> None: assert _run(screen, "enter") == "ok" +def test_text_screen_byte_limit_gauges_and_blocks_an_oversize_entry() -> None: + """A byte-limited field shows the shared used/limit gauge and blocks Enter over the cap.""" + import re + + screen = TextScreen("msg?", byte_limit=10) + for ch in "hello": + screen.handle("text", ch) + body = re.sub(r"\x1b\[[0-9;]*m", "", "\n".join(screen.render_body(40))) + assert "5/10" in body # the gauge reads used/limit + for ch in " world": # 11 bytes total, over the 10-byte cap + screen.handle("text", ch) + screen.future = _Fut() + screen.handle("enter") + assert not screen.future.done() # the over-limit entry is blocked + assert "Too long by 1 byte" in screen._error + # Trimming back within budget lets it submit. + for _ in range(2): + screen.handle("backspace") + assert _run(screen, "enter") == "hello wor" + + def test_line_editor_word_motion() -> None: """Ctrl+Left/Right hop by word — to the current word's start, else the previous/next.""" from meshterm.ui.tui.prompt import _LineEditor