Activity sparkline: scale to a peak, shared across a column

Bar heights now scale relative to a peak the way the dashboard's tall
activity chart does, instead of stepping at fixed count thresholds: the
busiest bucket fills the column and the rest draw in proportion.

A new `peak` argument is the scaling ceiling and the sharing mechanism.
Left None, each sparkline self-scales to its own window (the header
pulse, alone on its row). Passed a value, every sparkline handed the
same one shares a scale, so their bars are comparable — the channel
manager computes the busiest bucket across all channels via a new
_LiveStats.peak() and hands it to each row. No hidden cross-instance
state: the scale is a pure function of each call's inputs, which stays
correct for the windowed channel list where only visible rows render.

Drops the _HEADER_ACTIVITY_LEVELS / _ACTIVITY_LEVELS threshold ladders.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 4.8 committed 2026-07-18 03:32:44 -04:00
1 parent a524c610e1
commit f07f8c1b93
6 files changed
+118 -70

No files matched your search

+31 -11
View File
@@ -41,7 +41,6 @@ Beyond timelines, the module owns the app's two other braille conventions:
from __future__ import annotations
from bisect import bisect_right
from typing import Callable, Optional, Sequence, Union
from rich.text import Text
@@ -163,25 +162,40 @@ def timeline_rows(
def activity_sparkline(
histogram: Sequence[int],
levels: tuple[int, ...],
buckets: int,
*,
peak: Optional[float] = None,
style: str = "ok",
column_styles: Optional[Sequence[str]] = None,
) -> Text:
"""A one-row activity sparkline over a newest-first histogram, "now" rightmost.
Bar 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 regardless
of what else is on screen and a lone packet never vanishes. The histogram
arrives newest-first — the natural order the monitor and repository keep — and
is reversed here, so the current bucket lands on the right edge and traffic
slides *left* as it ages, like every other MeshTerm timeline.
Bar heights scale to a *peak* the way :func:`timeline_rows` scales a chart: the
peak bucket fills all four dot rows and the rest draw in proportion, so the
sparkline reads its shape against a ceiling rather than a fixed threshold ladder.
Any non-zero bucket still lights at least one dot, so a lone packet never
vanishes; a silent bucket (and an all-silent window) draws only the faint zero
baseline. The histogram arrives newest-first — the natural order the monitor and
repository keep — and is reversed here, so the current bucket lands on the right
edge and traffic slides *left* as it ages, like every other MeshTerm timeline.
``peak`` is the scaling ceiling, and it is how several sparklines drawn together
share one scale. Left ``None``, each sparkline self-scales to *its own* window's
busiest bucket — right for a chart that stands alone (the header pulse, alone on
its row). Passed a value, every sparkline handed the same one shares a scale, so
their bar heights are directly comparable — how the channel manager draws a whole
column of per-channel rows against the busiest channel on screen. The caller
computes that shared peak from the same data all the rows draw from (see the
channel manager's ``_LiveStats.peak``) and hands each row the one value; there is
deliberately no hidden cross-instance state here, so the scale is a pure function
of what each call is given.
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).
peak: The bucket count that fills the column; ``None`` self-scales to the
drawn window's busiest bucket. Zero (or an all-silent window) is a
flatline. A shared peak below a bucket's own count clamps to full height.
style: Style for lit cells.
column_styles: Optional per-bucket styles aligned with ``histogram``
(newest first, reversed here alongside it), overriding ``style`` —
@@ -191,14 +205,20 @@ def activity_sparkline(
A styled Rich :class:`Text` of ``buckets / 2`` braille characters.
"""
window = (tuple(histogram) + (0,) * buckets)[:buckets]
# The window's own peak when the caller names none; a one-row chart is four dot
# rows tall, so a bucket at the peak fills all four (see timeline_rows' up=total).
scale = peak if peak is not None else max(window, default=0)
per_column: Optional[list[str]] = None
if column_styles is not None:
padded = (list(column_styles) + [style] * buckets)[:buckets]
per_column = list(reversed(padded))
bars: list[Optional[tuple[int, int]]] = []
for count in reversed(window):
height = bisect_right(levels, count)
bars.append((0, height - 1) if height else None)
if count <= 0 or scale <= 0:
bars.append(None)
else:
height = min(4, max(1, round(count / scale * 4)))
bars.append((0, height - 1))
return _assemble(
bars, [float(c) for c in reversed(window)], 1, 0, style, "faint", per_column
)[0]
+35 -15
View File
@@ -368,8 +368,8 @@ class _LiveStats:
self._cache: Optional[dict[str, "ChannelStats"]] = None
self._at = 0.0
def get(self, channel_id: str) -> Optional["ChannelStats"]:
"""Return the stats for one channel identity, refreshing once the TTL lapses."""
def _snapshot(self) -> dict[str, "ChannelStats"]:
"""Every channel's stats, re-reading the repository at most once per ``ttl``."""
now = time.monotonic()
if self._cache is None or now - self._at >= self._ttl:
try:
@@ -377,7 +377,27 @@ class _LiveStats:
except Exception: # noqa: BLE001 - keep the last good snapshot on a read error
self._cache = self._cache or {}
self._at = now
return self._cache.get(channel_id)
return self._cache
def get(self, channel_id: str) -> Optional["ChannelStats"]:
"""Return the stats for one channel identity, refreshing once the TTL lapses."""
return self._snapshot().get(channel_id)
def peak(self, buckets: int) -> int:
"""The busiest bucket across *every* channel, the shared sparkline scale.
Read live through the same cache/TTL as :meth:`get`, over each channel's
trailing ``buckets`` window. Handing this one value to every row's
:func:`~meshterm.ui.braillechart.activity_sparkline` scales the whole activity
column against the loudest channel on screen, so the rows' bar heights are
comparable at a glance — a quiet channel reads as short beside a busy one
instead of each self-scaling to its own ceiling. Zero when the window is
silent everywhere, which the sparkline draws as a flatline.
"""
return max(
(max(st.histogram[:buckets], default=0) for st in self._snapshot().values()),
default=0,
)
#: Widest the name lane grows (longer names are ellipsized so the lanes stay put).
@@ -388,20 +408,15 @@ _BADGE_WIDTH = 5
_COUNT_WIDTH = 5
#: Width of the right-aligned last-message-age lane (fits ``never``-length ages).
_AGE_WIDTH = 5
#: Message counts a bucket must reach for each extra dot of bar height (Fibonacci-ish, so
#: each dot roughly means "a conversation tier up"): 1 message lights one dot, 3 light two,
#: 8 light three, and 21 or more max the column out.
_ACTIVITY_LEVELS = (1, 3, 8, 21)
def _activity_sparkline(histogram: "tuple[int, ...]") -> Text:
def _activity_sparkline(histogram: "tuple[int, ...]", peak: int) -> Text:
"""The channel's braille activity sparkline over the trailing two hours, now at the right.
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.
The shared :func:`~meshterm.ui.braillechart.activity_sparkline` over the repository
histogram's :data:`ACTIVITY_BUCKETS` five-minute buckets, scaled to ``peak`` — the
busiest bucket across every channel (see :meth:`_LiveStats.peak`) — so the whole
activity column shares one scale and the rows' bars are comparable at a glance.
"""
return activity_sparkline(histogram, _ACTIVITY_LEVELS, ACTIVITY_BUCKETS)
return activity_sparkline(histogram, ACTIVITY_BUCKETS, peak=peak)
# --- menus -------------------------------------------------------------------
@@ -481,7 +496,12 @@ def _slot_text(
age = _format_age(_age_seconds(st.last_at)) if st is not None and st.last_at else ""
text.append(f"{age:>{_AGE_WIDTH}}", style="muted")
text.append(" ")
text.append_text(_activity_sparkline(st.histogram if st is not None else ()))
# The shared peak across all channels, so every row's sparkline uses one scale.
text.append_text(
_activity_sparkline(
st.histogram if st is not None else (), stats.peak(ACTIVITY_BUCKETS)
)
)
return text
+3 -8
View File
@@ -114,13 +114,6 @@ def _silence_console_logging() -> Iterator[None]:
logger.addHandler(handler)
#: Packet counts a one-minute bucket must reach for each extra dot of the header
#: indicator's bar height. Higher-shouldered than the channel sparkline's thresholds
#: because this counts *every* packet the hub hears (adverts, telemetry, messages,
#: acks), not one conversation: 1 packet lights a dot, 3 light two, 8 light three,
#: 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.
@@ -171,10 +164,12 @@ def _header(ctx: AppContext, cache: dict, width: int) -> Text:
styles = [
"ok" if live else "muted" for live in ctx.monitor.activity_session_flags()
]
# No shared peak: alone on its row, the pulse self-scales to its own window's
# busiest minute (whatever slice of history the room fits), like the dashboard's
# tall activity chart against its window peak.
header.append_text(
activity_sparkline(
ctx.monitor.activity_histogram(),
_HEADER_ACTIVITY_LEVELS,
room * 2,
column_styles=styles,
)
+24 -10
View File
@@ -166,24 +166,38 @@ def test_timeline_per_cell_style_callable_sees_the_cells_readings() -> None:
def test_sparkline_puts_now_on_the_right() -> None:
"""A newest-first histogram renders with the current bucket at the right edge."""
# Newest bucket maxed, everything older silent: only the final cell's *right*
# dot column lights (with the floor dot keeping the left column's baseline).
text = activity_sparkline((21, 0, 0, 0), (1, 3, 8, 21), 4)
# Newest bucket the sole traffic, so it is the self-scaled peak and fills the
# column: only the final cell's *right* dot column lights (with the floor dot
# keeping the left column's baseline).
text = activity_sparkline((21, 0, 0, 0), 4)
assert text.plain == _BASE + _ch(_R[4], 0x40)
def test_sparkline_thresholds_step_the_bar_heights() -> None:
"""The level shoulders map counts to 1–4 dots, oldest to the left."""
# Newest-first (1, 3, 8, 21) reads 21,8,3,1 left→right once flipped.
text = activity_sparkline((1, 3, 8, 21), (1, 3, 8, 21), 4)
assert text.plain == _ch(_L[4], _R[3]) + _ch(_L[2], _R[1])
def test_sparkline_scales_to_the_window_peak() -> None:
"""With no shared peak, the busiest bucket fills the column and the rest scale to it."""
# Newest-first (16, 12, 8, 4) is a full/¾/½/¼ ramp against its own peak of 16;
# flipped for display it climbs 1→4 dots left→right toward now.
text = activity_sparkline((16, 12, 8, 4), 4)
assert text.plain == _ch(_L[1], _R[2]) + _ch(_L[3], _R[4])
def test_sparkline_shares_a_peak_across_instances() -> None:
"""A passed peak scales the bars to one ceiling, so quiet windows read short.
The same bucket draws a taller bar when it *is* the window's peak than when a
louder sibling's peak is scaled in — the channel manager's shared-scale column.
"""
solo = activity_sparkline((8, 0), 2) # self-scaled: 8 is its own peak → full height
shared = activity_sparkline((8, 0), 2, peak=32) # 8 against 32 → a quarter, one dot
assert solo.plain == _ch(0x40, _R[4]) # right column full (4 dots), left on baseline
assert shared.plain == _ch(0x40, _R[1]) # right column a single dot
def test_sparkline_pads_and_crops_to_the_window() -> None:
"""A short histogram pads with silence; a long one crops to the newest buckets."""
padded = activity_sparkline((21,), (1, 3, 8, 21), 6)
padded = activity_sparkline((21,), 6)
assert padded.plain == _BASE * 2 + _ch(_R[4], 0x40)
cropped = activity_sparkline((0, 0, 21, 21, 9, 9), (1, 3, 8, 21), 2)
cropped = activity_sparkline((0, 0, 21, 21, 9, 9), 2)
assert cropped.plain == _BASE # only the two newest (silent) buckets survive
+16 -19
View File
@@ -509,26 +509,23 @@ 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 heights, newest at the right."""
"""The sparkline draws two buckets per cell, scaled to the shared peak, newest 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 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 _activity_sparkline((0,) * 24, 0).plain == "⣀" * 12 # silent window: a flatline
assert _activity_sparkline((), 0).plain == "⣀" * 12 # a channel with no stats at all
assert _activity_sparkline((21,) * 24, 21).plain == "⣿" * 12 # every bucket at the peak
# A bucket well under the shared peak rides the baseline as a single dot in the
# *final* cell's right column (now sits at the right edge) — so the glyph matches
# the flatline and the ok-green style is what marks it as traffic.
lone = _activity_sparkline((1,) + (0,) * 23, 16)
assert lone.plain == "⣀" * 12
styles = [span.style for span in lone.spans]
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(
chr(0x2800 | left | right)
for left, right in ((0x47, 0xB8), (0x46, 0xB0), (0x44, 0xA0), (0x40, 0x80))
)
# Heights scale to the peak: a 16/12/8/4 ramp climbs quarter→full, the newest
# (fullest here) pair in the rightmost cell.
ramp = _activity_sparkline((16, 12, 8, 4) + (0,) * 20, 16).plain
assert ramp[-2:] == chr(0x2800 | 0x40 | 0xA0) + chr(0x2800 | 0x46 | 0xB8)
async def test_channel_rows_carry_stats_unread_and_lanes(ctx: AppContext) -> None:
@@ -557,10 +554,10 @@ async def test_channel_rows_carry_stats_unread_and_lanes(ctx: AppContext) -> Non
assert "private" not in plain and slot.hash not 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 *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
# Both just-recorded messages sit in the sparkline's newest bucket. With only this
# channel carrying traffic it *is* the shared peak, so the final cell's right column
# fills to full height at the row's right edge, the rest of the window on the flatline.
assert plain.rstrip().endswith("⣀" * 11 + chr(0x2800 | 0x40 | 0xB8))
label = row.label
assert label.spans[-1].style == "ok" # …and its newest cell reads as live traffic
+9 -7
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
from types import SimpleNamespace
from meshterm.ui.menu import _HEADER_ACTIVITY_LEVELS, _header
from meshterm.ui.menu import _header
def _ctx(histogram=(), unread=0, alerts=0, battery=None) -> SimpleNamespace:
@@ -67,16 +67,18 @@ def test_header_wider_terminal_shows_deeper_history() -> None:
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 = (21, 8, 3, 1) + (0,) * 356
def test_header_scales_to_the_window_peak() -> None:
"""The pulse scales to its window's busiest minute, not a fixed threshold ladder.
A 16/12/8/4 ramp against its own peak of 16 climbs one dot per step, so the four
newest minutes read heights 1,2,3,4 left→right in the row's final two cells — the
same relative scaling the dashboard's tall activity chart draws with.
"""
histogram = (16, 12, 8, 4) + (0,) * 356
header = _header(_ctx(histogram=histogram), {}, 80).plain
spark = [ch for ch in header if 0x2800 <= ord(ch) <= 0x28FF]
left = (0x00, 0x40, 0x44, 0x46, 0x47)
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])]