From 8e931efe6f31d206db79a1ca8da8913d514fd778 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sat, 11 Jul 2026 14:56:50 -0400 Subject: [PATCH] Header + channel sparklines: now on the right, tighter status row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both sparklines draw through ui.braillechart, so the current minute lands at the right edge and history trails left (JP reversed the earlier newest-left convention). The header also sheds the events-hub live-dot — it cost cells and read as noise — and drops its roomy separators to a compact " · " whenever they would squeeze the pulse below 24 cells, so a 72-column terminal keeps a readable stretch of graph. Co-Authored-By: Claude Fable 5 --- meshterm/persistence/repository.py | 8 ++-- meshterm/services/monitor_service.py | 9 ++-- meshterm/ui/channels.py | 7 +-- meshterm/ui/menu.py | 66 +++++++++++++++++++--------- meshterm/ui/widgets.py | 44 ------------------- tests/test_channels.py | 28 +++++++----- tests/test_header.py | 48 +++++++++++++++----- 7 files changed, 111 insertions(+), 99 deletions(-) diff --git a/meshterm/persistence/repository.py b/meshterm/persistence/repository.py index a80e673..d51f737 100644 --- a/meshterm/persistence/repository.py +++ b/meshterm/persistence/repository.py @@ -71,9 +71,9 @@ class ChannelStats: last_at: When the channel's most recent message was stored, or ``None`` if the stored timestamp can't be parsed. histogram: The window's messages split into :data:`ACTIVITY_BUCKETS` equal time - buckets, *newest first* — bucket 0 is the current five minutes, so the - sparkline drawn from it reads now→past left-to-right and traffic slides right - as it ages. ``recent`` is always its sum. + buckets, *newest first* — bucket 0 is the current five minutes, the order + :func:`~meshterm.ui.braillechart.activity_sparkline` expects (it flips the + window so "now" draws at the right edge). ``recent`` is always its sum. """ total: int @@ -981,7 +981,7 @@ class Repository: try: created_at = datetime.fromisoformat(row["created_at"]) # Bucket by *age* so the histogram comes out newest-first (bucket 0 holds - # the current five minutes) — the order the sparkline draws it in. + # the current five minutes) — the order the sparkline widget expects. idx = min(ACTIVITY_BUCKETS - 1, int((now - created_at) / bucket_span)) except (TypeError, ValueError): continue # a malformed/naive stray simply doesn't land in a bucket diff --git a/meshterm/services/monitor_service.py b/meshterm/services/monitor_service.py index 5584a05..35831a1 100644 --- a/meshterm/services/monitor_service.py +++ b/meshterm/services/monitor_service.py @@ -85,10 +85,11 @@ class MonitorService: def activity_histogram(self) -> tuple[int, ...]: """All-packet counts per one-minute bucket over the trailing six hours. - Newest first — index 0 is the current minute — the order the header's braille - indicator draws. Counts everything the hub fans out this session; time before - launch simply reads as silence. Consumers slice however much of the window - fits their chart and treat the rest as history in reserve. + Newest first — index 0 is the current minute — the order the chart widgets + expect (they draw "now" at the right edge). Counts everything the hub fans out + this session; time before launch simply reads as silence. Consumers slice + however much of the window fits their chart and treat the rest as history in + reserve. Returns: :data:`ACTIVITY_BUCKETS` bucket counts. diff --git a/meshterm/ui/channels.py b/meshterm/ui/channels.py index 7888bf3..d53d9f4 100644 --- a/meshterm/ui/channels.py +++ b/meshterm/ui/channels.py @@ -52,9 +52,10 @@ from ..core.channels import ( from ..core.connection import Device from ..core.models import Conversation from ..persistence.repository import ACTIVITY_BUCKETS +from .braillechart import activity_sparkline from .qr import qr_text from .tui import CANCEL, Choice, SelectScreen, Separator -from .widgets import _age_seconds, _format_age, activity_sparkline, channel_glyph +from .widgets import _age_seconds, _format_age, channel_glyph if TYPE_CHECKING: from ..context import AppContext @@ -344,9 +345,9 @@ _ACTIVITY_LEVELS = (1, 3, 8, 21) def _activity_sparkline(histogram: "tuple[int, ...]") -> Text: - """The channel's braille activity sparkline over the trailing two hours. + """The channel's braille activity sparkline over the trailing two hours, now at the right. - The shared :func:`~meshterm.ui.widgets.activity_sparkline`, drawn at this list's + The shared :func:`~meshterm.ui.braillechart.activity_sparkline`, drawn at this list's message-count thresholds over the repository histogram's :data:`ACTIVITY_BUCKETS` five-minute buckets. """ diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index ddb9719..5ee9903 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -27,7 +27,7 @@ from ..context import AppContext from ..persistence.logging import get_logger from ..tools import all_tools from .surface import TuiUi -from .widgets import activity_sparkline +from .braillechart import activity_sparkline from .theme import make_console from .tui import ( CANCEL, @@ -120,17 +120,22 @@ def _silence_console_logging() -> Iterator[None]: #: and 21 or more max the column out. _HEADER_ACTIVITY_LEVELS = (1, 3, 8, 21) +#: The fewest sparkline cells the header aims to keep. When the fixed segments with +#: roomy " · " separators would leave less than this, the header re-lays itself with +#: the compact " · " so a 72-column terminal still shows a readable stretch of pulse. +_SPARK_MIN_CELLS = 24 + def _header(ctx: AppContext, cache: dict, width: int) -> Text: """Build the persistent one-line header: who's connected, unread mail, mesh pulse. Left to right: the app mark, the connected node's own name with where it's reached - (``(COM5)`` / ``(BLE)``), an unread-message badge (channels and direct alike, shown - only when something is waiting, in the red-dot language of the channel list and the - conversation picker), and a braille activity indicator counting every packet the - hub hears at one minute per dot column — stretched to fill every remaining cell of - the row, so a wider terminal simply shows deeper history — with a leading ●/○ - live-light for whether the hub is pumping yet. + (``(COM5)`` / ``(BLE)``), unread-message and Watchtower badges (shown only when + something is waiting), and the braille activity pulse counting every packet the hub + hears at one minute per dot column — newest at the right edge, like every MeshTerm + timeline — stretched to fill every remaining cell of the row, so a wider terminal + simply shows deeper history. Separators are roomy by default and drop to a compact + ``·`` when that would squeeze the pulse below :data:`_SPARK_MIN_CELLS`. Args: ctx: The shared application context, read live on every repaint. @@ -144,10 +149,39 @@ def _header(ctx: AppContext, cache: dict, width: int) -> Text: single line (see ``frame.compose_base``), so a too-narrow terminal chops the tail rather than wrapping. """ + header = _header_segments(ctx, cache, " · ") + if width - header.cell_len < _SPARK_MIN_CELLS: + header = _header_segments(ctx, cache, " · ") + # Two dot columns per cell: every cell left of the row's edge shows two minutes. + room = width - header.cell_len + if room > 0: + header.append_text( + activity_sparkline( + ctx.monitor.activity_histogram(), _HEADER_ACTIVITY_LEVELS, room * 2 + ) + ) + return header + + +def _header_segments(ctx: AppContext, cache: dict, sep: str) -> Text: + """The header's fixed segments — everything left of the pulse — at one separator width. + + Built twice per repaint at worst (roomy first, compact if the row is tight; see + :func:`_header`). The trailing separator is included, so the caller can append the + sparkline directly after it. + + Args: + ctx: The shared application context. + cache: The device-label cache (see :func:`_device_label`). + sep: The separator between segments (``" · "`` or the compact ``" · "``). + + Returns: + The fixed-left portion of the header row. + """ header = Text() header.append("MeshTerm", style="brand") header.append(f" v{__version__}", style="muted") - header.append(" · ") + header.append(sep) if ctx.mock: header.append("simulator", style="warn") else: @@ -157,26 +191,16 @@ def _header(ctx: AppContext, cache: dict, width: int) -> Text: header.append(f" ({where})", style="muted") unread = ctx.chat.unread_total() if unread: - header.append(" · ") + header.append(sep) header.append("●", style="err") header.append(f" {unread}", style="warn") alerts = ctx.watchtower.unacked_count() if alerts: # The Watchtower's badge: a triangle so it never reads as unread mail. - header.append(" · ") + header.append(sep) header.append("▲", style="err") header.append(f" {alerts}", style="warn") - header.append(" · ") - header.append("●" if ctx.events.active else "○", style="ok" if ctx.events.active else "muted") - header.append(" ") - # Two dot columns per cell: every cell left of the row's edge shows two minutes. - room = width - header.cell_len - if room > 0: - header.append_text( - activity_sparkline( - ctx.monitor.activity_histogram(), _HEADER_ACTIVITY_LEVELS, room * 2 - ) - ) + header.append(sep) return header diff --git a/meshterm/ui/widgets.py b/meshterm/ui/widgets.py index fd78a5a..41d0035 100644 --- a/meshterm/ui/widgets.py +++ b/meshterm/ui/widgets.py @@ -491,50 +491,6 @@ def _format_age(secs: Optional[float]) -> str: return f"{int(secs // 604800)}w" -#: Braille dot masks for a bar filled bottom-up to height 0–4 in a cell's left column -#: (dots 7, 3, 2, 1 — the Unicode braille block numbers its rows top-down) and right -#: column (dots 8, 6, 5, 4). OR one of each, add to U+2800, and that's the character. -_BRAILLE_LEFT = (0x00, 0x40, 0x44, 0x46, 0x47) -_BRAILLE_RIGHT = (0x00, 0x80, 0xA0, 0xB0, 0xB8) -#: A braille cell with just its two bottom dots (7 and 8) lit — the resting baseline a -#: silent pair of buckets draws, so a quiet stretch still shows a flatline, not a gap. -_SPARK_BASELINE = chr(0x2800 | 0x40 | 0x80) - - -def activity_sparkline( - histogram: "tuple[int, ...]", levels: tuple[int, ...], buckets: int -) -> Text: - """A braille activity sparkline: one dot column per bucket, two columns per cell. - - Each bucket's bar rises bottom-up through the cell's four dot rows. Heights are - absolute, stepped at ``levels`` (the count a bucket must reach for each extra dot), - so the same traffic always draws the same bar and a lone packet never vanishes. Time - runs *newest first*: "now" is the leftmost column and traffic slides right as it - ages. Cells with traffic draw in the ok green; a silent cell drops to a faint - two-bottom-dot baseline, so a quiet stretch reads as a flatline under the green - spikes rather than a hole in the row. - - Args: - histogram: Per-bucket counts, newest first; padded/cropped to ``buckets``. - levels: Ascending count thresholds for bar heights 1..4. - buckets: How many buckets to draw (half this many characters). - - Returns: - A styled Rich :class:`Text` of ``buckets / 2`` braille characters. - """ - from bisect import bisect_right - - histogram = (tuple(histogram) + (0,) * buckets)[:buckets] - text = Text() - for left, right in zip(histogram[0::2], histogram[1::2]): - lh, rh = bisect_right(levels, left), bisect_right(levels, right) - if lh or rh: - text.append(chr(0x2800 | _BRAILLE_LEFT[lh] | _BRAILLE_RIGHT[rh]), style="ok") - else: - text.append(_SPARK_BASELINE, style="faint") - return text - - def _recency_style(secs: Optional[float]) -> str: """The heat-map name colour for a contact last heard ``secs`` ago (hotter = more recent). diff --git a/tests/test_channels.py b/tests/test_channels.py index ced5bef..f9cef13 100644 --- a/tests/test_channels.py +++ b/tests/test_channels.py @@ -369,23 +369,25 @@ def test_channel_stats_aggregates_totals_window_and_recency(ctx: AppContext) -> def test_activity_sparkline_packs_24_buckets_into_braille() -> None: - """The sparkline draws two buckets per cell at absolute, thresholded heights.""" + """The sparkline draws two buckets per cell at absolute heights, newest at the right.""" from meshterm.ui.channels import _activity_sparkline assert _activity_sparkline((0,) * 24).plain == "⣀" * 12 # silent window: a flatline assert _activity_sparkline(()).plain == "⣀" * 12 # a channel with no stats at all assert _activity_sparkline((21,) * 24).plain == "⣿" * 12 # flat-out: every dot lit - # A lone message in the newest bucket: one dot in the *first* cell's left column (time - # runs newest→oldest), the rest of the window on the faint baseline. + # A lone message in the newest bucket: one tier-one dot in the *final* cell's right + # column (now sits at the right edge), riding the continuing baseline — so the glyph + # matches the flatline and the ok-green style is what marks it as traffic. lone = _activity_sparkline((1,) + (0,) * 23) - assert lone.plain == "⡀" + "⣀" * 11 + assert lone.plain == "⣀" * 12 styles = [span.style for span in lone.spans] - assert styles[0] == "ok" and set(styles[1:]) == {"faint"} - # Heights step at the absolute thresholds 1 / 3 / 8 / 21 messages per bucket. + assert styles[-1] == "ok" and set(styles[:-1]) == {"faint"} + # Heights step at the absolute thresholds 1 / 3 / 8 / 21 messages per bucket, the + # newest (tallest here) pair in the rightmost cell. steps = _activity_sparkline((1, 2, 3, 7, 8, 20, 21, 999) + (0,) * 16).plain - assert steps[:4] == "".join( + assert steps[-4:] == "".join( chr(0x2800 | left | right) - for left, right in ((0x40, 0x80), (0x44, 0xA0), (0x46, 0xB0), (0x47, 0xB8)) + for left, right in ((0x47, 0xB8), (0x46, 0xB0), (0x44, 0xA0), (0x40, 0x80)) ) @@ -412,10 +414,12 @@ async def test_channel_rows_carry_stats_unread_and_lanes(ctx: AppContext) -> Non assert "Ops" in plain and "private" in plain and slot.hash in plain assert "● 2" in plain # the unread badge assert "now" in plain # the just-recorded message's age - # Both just-recorded messages sit in the sparkline's newest bucket — the *first* cell's - # left column (one dot: two messages is still tier one) — with the rest of the window - # on the faint flatline baseline. - assert plain.rstrip().endswith("⡀" + "⣀" * 11) # the sparkline is the final lane + # Both just-recorded messages sit in the sparkline's newest bucket — the *final* + # cell's right column (one dot: two messages is still tier one), riding the baseline + # at the row's right edge — with the rest of the window on the faint flatline. + assert plain.rstrip().endswith("⣀" * 12) # the sparkline is the final lane + label = row.label + assert label.spans[-1].style == "ok" # …and its newest cell reads as live traffic async def test_detail_summary_reads_slot_totals_and_unread(ctx: AppContext) -> None: diff --git a/tests/test_header.py b/tests/test_header.py index b72f5ab..f37c8b2 100644 --- a/tests/test_header.py +++ b/tests/test_header.py @@ -7,12 +7,11 @@ from types import SimpleNamespace from meshterm.ui.menu import _HEADER_ACTIVITY_LEVELS, _header -def _ctx(histogram=(), unread=0, active=True, alerts=0) -> SimpleNamespace: +def _ctx(histogram=(), unread=0, alerts=0) -> SimpleNamespace: """A minimal stand-in exposing only what the header reads (simulator path).""" return SimpleNamespace( mock=True, chat=SimpleNamespace(unread_total=lambda: unread), - events=SimpleNamespace(active=active), monitor=SimpleNamespace(activity_histogram=lambda: tuple(histogram)), watchtower=SimpleNamespace(unacked_count=lambda: alerts), ) @@ -32,6 +31,16 @@ def test_header_sparkline_fills_the_row_exactly() -> None: assert "⣿" in header.plain # maxed-out cells all the way to the edge +def test_header_puts_now_at_the_right_edge() -> None: + """The current minute's traffic draws in the row's final cell, not its first.""" + header = _header(_ctx(histogram=(21,) + (0,) * 359), {}, 80).plain + spark = [ch for ch in header if 0x2800 <= ord(ch) <= 0x28FF] + # The newest bucket is the final cell's *right* dot column (its left column is + # the minute before, silent bar the continuing baseline dot). + assert spark[-1] == chr(0x2800 | 0xB8 | 0x40) + assert all(ch == chr(0x2800 | 0x40 | 0x80) for ch in spark[:-1]) # older = flatline + + def test_header_wider_terminal_shows_deeper_history() -> None: """A burst 90 minutes ago is off a narrow header but visible on a wide one. @@ -39,25 +48,42 @@ def test_header_wider_terminal_shows_deeper_history() -> None: renders as a lit cell only when the row leaves that much room. """ histogram = tuple(0 if i != 90 else 21 for i in range(360)) - narrow = _header(_ctx(histogram=histogram), {}, 60).plain - wide = _header(_ctx(histogram=histogram), {}, 120).plain - full_bar = chr(0x2800 | 0x47) # a maxed-out lone left dot column - assert full_bar not in narrow - assert full_bar in wide + + def burst_cells(row: str) -> list[str]: + # Anything lit above the bottom dot row (bits beyond dots 7/8) is the burst; + # the baseline flatline and blank braille never set those bits. + return [ch for ch in row if 0x2800 <= ord(ch) <= 0x28FF and ord(ch) & 0x3F] + + assert not burst_cells(_header(_ctx(histogram=histogram), {}, 60).plain) + assert burst_cells(_header(_ctx(histogram=histogram), {}, 120).plain) def test_header_thresholds_step_the_bar_heights() -> None: """The documented 1/3/8/21 shoulders map counts to 1–4 dots.""" assert _HEADER_ACTIVITY_LEVELS == (1, 3, 8, 21) - histogram = (1, 0, 3, 0, 8, 0, 21, 0) + (0,) * 352 + histogram = (21, 8, 3, 1) + (0,) * 356 header = _header(_ctx(histogram=histogram), {}, 80).plain - spark = header[header.index("●") + 2 :] # after the live-light and its space + spark = [ch for ch in header if 0x2800 <= ord(ch) <= 0x28FF] left = (0x00, 0x40, 0x44, 0x46, 0x47) - assert [spark[i] for i in range(4)] == [chr(0x2800 | left[h]) for h in (1, 2, 3, 4)] + right = (0x00, 0x80, 0xA0, 0xB0, 0xB8) + # Flipped for display, the four newest minutes read 1,3,8,21 left→right in the + # row's final two cells: heights (1,2) then (3,4). + assert spark[-2:] == [chr(0x2800 | left[1] | right[2]), chr(0x2800 | left[3] | right[4])] + + +def test_header_tight_row_drops_to_compact_separators() -> None: + """When roomy separators would squeeze the pulse, they narrow to ' · '.""" + roomy = _header(_ctx(), {}, 100).plain + assert " · " in roomy + tight = _header(_ctx(unread=12, alerts=3), {}, 60).plain + assert " · " not in tight and " · " in tight + # The compaction buys real sparkline room even on a badge-laden 60-column row. + spark = [ch for ch in tight if 0x2800 <= ord(ch) <= 0x28FF] + assert len(spark) >= 14 def test_header_survives_a_sliver_terminal() -> None: """When the fixed segments already overflow the width, the sparkline just stays out.""" header = _header(_ctx(histogram=(9,) * 360), {}, 10) # No room left: no braille at all, nothing stretched past the edge. - assert all(not (0x2800 <= ord(ch) <= 0x28FF) for ch in header.plain) + assert all(not (0x2800 <= ord(ch) <= 0x28FF) for ch in header.plain) \ No newline at end of file