From 0c3a8b5b5c1942d7c8a40cf0b51e220e3730f82e Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Tue, 13 Oct 2026 18:16:15 -0400 Subject: [PATCH] The space between authors in a chat is a preference Two preferences in the Display group: "Author spacing" (auto, on, off; default auto) and "Spacing from" (the smallest terminal, in rows, that gets the blank line with auto; default 24). The test reads the real rows of the terminal before each paint, so a small desktop window drops the line as the Cardputer Zero does, and a change applies at the next paint. The transcript cache stores the spacing, so a change draws the lines again. The CLI manual's sample of `preferences show` is the real output again. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 7 +++-- docs/cli/README.md | 53 +++++++++++++++++++----------------- meshterm/core/preferences.py | 30 ++++++++++++++++++++ meshterm/ui/chat.py | 49 +++++++++++++++++++++------------ meshterm/ui/tui/session.py | 9 ++++++ tests/test_chat.py | 38 ++++++++++++++++++-------- tests/test_gallery.py | 3 ++ 7 files changed, 134 insertions(+), 55 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index abe2a13..12f234a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,8 +23,11 @@ can change how things behave. It does not only add new things. the node uses when it makes its own key. A firmware companion still gets the full 64-byte key, because it accepts only that form. - **In a chat, a blank line comes after the messages of each author.** Thus the - conversation is easier to follow when many people write. The Cardputer Zero has no - blank line there, because its screen has only 14 rows and each row shows a message. + conversation is easier to follow when many people write. By default, the line shows on + a terminal of 24 rows or more. A smaller terminal, and the 14 rows of the Cardputer Zero, + keep each row for a message. Two new preferences in the Display group control the line: + **Author spacing** (`auto`, `on`, or `off`) and **Spacing from** (the smallest terminal, + in rows, that gets the line with `auto`). ## [0.11.1] - 2026-10-13 diff --git a/docs/cli/README.md b/docs/cli/README.md index d6f6a80..9f97b9a 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -1727,31 +1727,34 @@ If you give no subcommand, it runs `show`. ```console $ meshterm preferences show -PREFERENCE VALUE DEFAULT DESCRIPTION -set_clock_on_connect off off Set the device clock from this computer when it connects -trace_cooldown_s 5 5 Wait this long before transmitting again -flood_advert_cooldown_s 60 60 Extra wait before another mesh-wide advert -weekly_flood_advert off off Flood an advert after a week without one -advert_quiet_s 30 30 Silence to wait for before the weekly advert -direct_message_soft_retries 0 0 Times to resend a message that gets no reply -tx_opt_min 18 18 Weakest power it will try -tx_opt_max 28 28 Strongest power it will try -tx_snr_tolerance_db 1 1 Signals this close are a tie, so less power wins -watch_silence_hours 12 12 Warn when a watched node goes quiet this long -watch_alerts_kept 200 200 How many past alerts to keep -map_view_fraction 0.5 0.5 Share of nodes to fit on screen; 1 shows them all -basemap_tilejson_url https://tiles.openfreemap.org/planet https://tiles.openfreemap.org/planet Where map images come from (next launch) -history_days 365 365 Older ones are deleted; 0 keeps everything -chat_history_limit 200 200 Old messages to load when you open a chat -courier_history_kept 100 100 Finished outbox messages to keep -cli_time_format relative relative Whether the command line prints ages or timestamps -fast_render on on Faster screen updates; turn off if it looks wrong (next launch) -full_width auto auto Use the extra column some terminals hide -color_depth auto auto How many colours to send this terminal (next launch) -console_setup auto auto Move to a better terminal when this console can't draw MeshTerm -console_font 6x12 6x12 Bigger text, or more rows on the handheld's panel -name_overlap_days 7 7 Grey a name two nodes used within this many days -log_level WARNING WARNING How much MeshTerm writes to its log file (next launch) +PREFERENCE VALUE DEFAULT DESCRIPTION +set_clock_on_connect off off Set the device clock from this computer when it connects +trace_cooldown_s 5 5 Wait this long before transmitting again +flood_advert_cooldown_s 60 60 Extra wait before another mesh-wide advert +weekly_flood_advert off off Flood an advert after a week without one +advert_quiet_s 30 30 Silence to wait for before the weekly advert +direct_message_soft_retries 0 0 Times to resend a message that gets no reply +room_relogin_minutes 30 30 Opening a room this quiet logs in again +tx_opt_min 18 18 Weakest power it will try +tx_opt_max 28 28 Strongest power it will try +tx_snr_tolerance_db 1 1 Signals this close are a tie, so less power wins +watch_silence_hours 12 12 Warn when a watched node goes quiet this long +watch_alerts_kept 200 200 How many past alerts to keep +map_view_fraction 0.5 0.5 Share of nodes to fit on screen; 1 shows them all +basemap_tilejson_url https://tiles.openfreemap.org/planet https://tiles.openfreemap.org/planet Where map images come from (next launch) +history_days 365 365 Older ones are deleted; 0 keeps everything +chat_history_limit 200 200 Old messages to load when you open a chat +courier_history_kept 100 100 Finished outbox messages to keep +cli_time_format relative relative Whether the command line prints ages or timestamps +fast_render on on Faster screen updates; turn off if it looks wrong (next launch) +full_width auto auto Use the extra column some terminals hide +color_depth auto auto How many colours to send this terminal (next launch) +console_setup auto auto Move to a better terminal when this console can't draw MeshTerm +console_font 6x12 6x12 Bigger text, or more rows on the handheld's panel +name_overlap_days 7 7 Grey a name two nodes used within this many days +chat_author_spacing auto auto A blank line after each author in a chat +chat_author_spacing_min_rows 24 24 With auto: the smallest terminal that gets it +log_level WARNING WARNING How much MeshTerm writes to its log file (next launch) ``` **`DESCRIPTION`** says what each preference does, because the name of a key does not give diff --git a/meshterm/core/preferences.py b/meshterm/core/preferences.py index 579e98f..4556283 100644 --- a/meshterm/core/preferences.py +++ b/meshterm/core/preferences.py @@ -173,6 +173,10 @@ _QUIET_CHOICES: dict[int, str] = {s: f"{s} s" for s in QUIET_CHOICES_S} #: column, and for the cost when MeshTerm reclaims a column that is not hidden. _WIDTH_CHOICES: dict[str, str] = {"auto": "auto", "yes": "yes", "no": "no"} +#: When a chat puts a blank line after the messages of each author. ``auto`` puts it on a +#: terminal that has at least ``chat_author_spacing_min_rows`` rows. +_SPACING_CHOICES: dict[str, str] = {"auto": "auto", "on": "on", "off": "off"} + #: How many colours to send to the terminal. ``auto`` is the honest default, and it is the #: only value that is not a depth. It means "take prompt_toolkit's verdict unless we can #: positively establish better". This rule is the difference between a repaired host and a @@ -504,6 +508,32 @@ PREFERENCES: tuple[PrefSpec, ...] = ( maximum=3650, unit="days", ), + PrefSpec( + key="chat_author_spacing", + label="Author spacing", + help="A blank line after each author in a chat", + group="Display", + value_type="enum", + # Auto, because the line costs one row for each group of messages. A tall terminal + # has the rows, and the 14 rows of the Cardputer Zero do not: there a blank line is + # a message less on the screen. The test is the real height of the terminal, so a + # small window on a desktop drops the line too (JP, 2026-10-13). + default="auto", + choices=_SPACING_CHOICES, + ), + PrefSpec( + key="chat_author_spacing_min_rows", + label="Spacing from", + help="With auto: the smallest terminal that gets it", + group="Display", + value_type="int", + # A standard terminal (24 rows) and the PicoCalc (26) get the line. The Cardputer + # Zero (14) and a smaller window do not (JP, 2026-10-13). + default=24, + minimum=10, + maximum=100, + unit="rows", + ), # --- Diagnostics --------------------------------------------------------------- PrefSpec( key="log_level", diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py index 608d4cb..ac9b81e 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -25,7 +25,7 @@ from rich.cells import cell_len from rich.console import Group, RenderableType from rich.text import Text -from ..core import links +from ..core import links, preferences from ..core.channels import MENTION, split_channel_sender from ..core.connection import ContactNotOnDeviceError from ..core.events import EventKind, MeshEvent @@ -75,26 +75,21 @@ _URL_GUTTER = 2 _URL_CODES = False -#: Whether a blank line closes the messages of each author. It costs one row for each -#: group. The PicoCalc (26 rows) and a terminal (24) have the rows for it. The 14 rows of -#: the Cardputer Zero do not: there a blank line on each group is a message less on the -#: screen (JP, 2026-10-13). -_GROUP_GAP = True - -#: The fewest rows (``Platform.readable_rows``) for which a transcript has that blank line. -_GROUP_GAP_MIN_ROWS = 20 +#: The rows of the terminal when the session cannot say (a stand-in session with no +#: ``terminal_rows``): the design minimum of the platform (``Platform.readable_rows``). +_FALLBACK_ROWS = 24 @on_platform def _bind(platform: Platform) -> None: """Bind the transcript to the platform (now and at each switch). - The platform says whether codes hang under URLs, and whether it has the rows for a - blank line after each author. + The platform says whether codes hang under URLs, and how many rows to assume when the + session cannot tell the height of the terminal. """ - global _URL_CODES, _GROUP_GAP + global _URL_CODES, _FALLBACK_ROWS _URL_CODES = platform.url_codes - _GROUP_GAP = platform.readable_rows >= _GROUP_GAP_MIN_ROWS + _FALLBACK_ROWS = platform.readable_rows #: The maximum width of a footer hint, in cells (refer to the UX standards). @@ -583,7 +578,8 @@ class ChatScreen(Screen): messages = self._messages total = len(messages) cache = self._render_cache - if cache is not None and cache["width"] == width: + spacing = self._author_spacing() + if cache is not None and cache["width"] == width and cache["spacing"] == spacing: cached_ids = cache["ids"] cached_acked = cache["acked"] cached_selected = cache["selected"] @@ -628,10 +624,10 @@ class ChatScreen(Screen): and cached_ids[idx] == id(message) and cached_acked[idx] == message.acked ) - # A blank line closes the messages of an author, where the platform has the rows - # for it (:data:`_GROUP_GAP`). It is the first line of the slice of the message + # A blank line closes the messages of an author, where the preferences ask for + # it (:meth:`_author_spacing`). It is the first line of the slice of the message # that starts the next group, so a cached slice brings it back with it. - gap = _GROUP_GAP and bool(lines) and (new_day or group != prev_group) + gap = spacing and bool(lines) and (new_day or group != prev_group) if reusable: start = cached_boundaries[idx - 1] if idx > 0 else 0 slice_lines = cached_lines[start : cached_boundaries[idx]] @@ -675,6 +671,7 @@ class ChatScreen(Screen): self._render_cache = { "width": width, + "spacing": spacing, "ids": ids, "acked": ackeds, "selected": selecteds, @@ -683,6 +680,24 @@ class ChatScreen(Screen): } return lines + def _author_spacing(self) -> bool: + """Whether a blank line closes the messages of each author, at this paint. + + The ``chat_author_spacing`` preference decides: ``on`` and ``off`` are fixed, and + ``auto`` puts the line on a terminal of ``chat_author_spacing_min_rows`` rows or + more. The line costs one row for each group of messages, so a short terminal (the + Cardputer Zero, or a small window) keeps the transcript dense. The test reads the + rows of the terminal before the paint, and reads the preferences at each paint, + so a change on the Preferences page applies when the user comes back. + """ + prefs = preferences.current() + mode = prefs.chat_author_spacing + if mode != "auto": + return mode == "on" + rows = getattr(self._session, "terminal_rows", None) + height = rows() if callable(rows) else _FALLBACK_ROWS + return height >= prefs.chat_author_spacing_min_rows + def _sender_and_body(self, message: ChatMessage) -> tuple[str, str]: """Return the display sender and the clean body of a message. diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index b948c47..309ca67 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -2056,6 +2056,15 @@ class TuiSession: size = self._app.output.get_size() # type: ignore[union-attr] return max(20, size.columns), max(6, size.rows) + def terminal_rows(self) -> int: + """The rows of the terminal now. A screen reads it before its paint, never after. + + The chat uses it for the space between authors (``chat_author_spacing``). The rows + that the frame records after a paint come one paint late, so the first paint of a + chat would come out without the space and then jump. + """ + return self._size()[1] + def base_body_size(self) -> tuple[int, int]: """Return the ``(width, height)`` in cells that the body of the base screen can use. diff --git a/tests/test_chat.py b/tests/test_chat.py index 26ab10f..4523662 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -41,12 +41,17 @@ from tests.conftest import plain as _strip_ansi # the only strip-and-join scree class _StubSession: """A session stand-in that counts the requests for a paint.""" - def __init__(self) -> None: + def __init__(self, rows: int = 24) -> None: self.invalidations = 0 + self.rows = rows def invalidate(self) -> None: self.invalidations += 1 + def terminal_rows(self) -> int: + """The rows of the terminal, for the space between authors.""" + return self.rows + def run_detached(self, work): # noqa: ANN001, ANN201 """Start the flow of a key handler as a task, as ``TuiSession.run_detached`` does.""" return asyncio.ensure_future(work) @@ -1545,17 +1550,20 @@ def test_channel_own_messages_do_not_merge_with_remote_namesake() -> None: assert rendered.count("you") == 1 and rendered.count("★ Me") == 1 -def test_a_blank_line_closes_each_author_where_the_rows_allow() -> None: - """A terminal and the PicoCalc put a blank line after the messages of each author. +def test_a_blank_line_closes_each_author_where_the_rows_allow( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """With ``auto``, a terminal of 24 rows or more puts a blank line after each author. The blank line also comes before the divider of a new day, and never before the first - line. The 14 rows of the Cardputer Zero have no row to spare for it. A second paint - reads the cached lines, and the divider of the second day still pins at its own line, - not at the blank line before it. + line. A terminal of fewer rows (the 14 of the Cardputer Zero) has no row to spare for + it. A second paint reads the cached lines, and the divider of the second day still pins + at its own line, not at the blank line before it. ``on`` and ``off`` ignore the rows, + and a change applies at the next paint. """ from datetime import datetime, timedelta, timezone - from meshterm.platforms import CARDPUTER_ZERO, REGULAR, set_platform + from meshterm.core import preferences base = datetime(2026, 7, 5, 14, 24, tzinfo=timezone.utc) @@ -1570,8 +1578,9 @@ def test_a_blank_line_closes_each_author_where_the_rows_allow() -> None: ChatMessage(text="Bob: later", is_channel=True, channel_idx=0, created_at=at(1440)), ] - set_platform(REGULAR) - screen = _channel_screen(transcript()) + prefs = preferences.Preferences() + monkeypatch.setattr(preferences, "current", lambda: prefs) + screen = _channel_screen(transcript(), session=_StubSession(rows=24)) lines = [_strip_ansi(line) for line in screen._render_grouped(53)] assert lines[0].startswith("──") and lines[1] == "Alice" assert lines[4] == "" and lines[5] == "Bob" # after the two messages of Alice @@ -1581,9 +1590,16 @@ def test_a_blank_line_closes_each_author_where_the_rows_allow() -> None: screen._render_grouped(53) # the cached lines assert screen._sticky_headers == first and [at for at, _ in first] == [0, 8] - set_platform(CARDPUTER_ZERO) - screen = _channel_screen(transcript()) + short = _channel_screen(transcript(), session=_StubSession(rows=14)) + assert "" not in [_strip_ansi(line) for line in short._render_grouped(53)] + + prefs.set("chat_author_spacing", "on") # always, also on 14 rows + assert "" in [_strip_ansi(line) for line in short._render_grouped(53)] + prefs.set("chat_author_spacing", "off") # never, and the cached lines change too assert "" not in [_strip_ansi(line) for line in screen._render_grouped(53)] + prefs.set("chat_author_spacing", "auto") + prefs.set("chat_author_spacing_min_rows", 14) + assert "" in [_strip_ansi(line) for line in short._render_grouped(53)] def test_a_mention_of_our_name_takes_our_chip() -> None: diff --git a/tests/test_gallery.py b/tests/test_gallery.py index 04a6ed7..e921c28 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -147,6 +147,9 @@ class _GallerySession: def base_body_size(self) -> tuple[int, int]: return self._cols, self._rows + def terminal_rows(self) -> int: + return self._rows + async def button_dialog(self, prompt, buttons, **kwargs): # noqa: ANN001 return None