Charts: the mirror returns where the frame affords it; Rhythm seeks its finest slice

The right-gutter marks come back on the desktop (redundant but nice)
and the console keeps the bare tick - axis_chrome is the one number a
caller budgets, platform-bound like the rest of the chrome. The Rhythm
ladder widens to 1/5/10/15/20/30/60-minute slices, finest that fits:
the desktop keeps its 15-minute sweep at 72 cols and earns finer on a
wide terminal; the mesh page re-slices one minute-grid scan.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Fable 5 committed 2026-08-09 00:10:53 -04:00
1 parent 70fb0ceea3
commit b83c9005c7
7 files changed
+130 -81

No files matched your search

+14 -14
View File
@@ -1237,34 +1237,34 @@ class Repository:
return counts
def rhythm_activity(self, *, since: Optional[datetime] = None) -> list[int]:
"""Observation counts by local ten-minute slice of day (0–143) across the history.
"""Observation counts by local minute of day (0–1439) across the history.
The fine-grained base grid behind the whole-mesh Rhythm chart: ten minutes is the
common divisor of every slice width the chart may settle on (20/30/60 minutes —
see the Time Machine's slice ladder), so one scan here folds client-side into any
of them without re-querying. The slice index is ``(HH * 60 + MM) // 10``, computed
in SQL off the ``HH``/``MM`` substrings of ``datetime(…, 'localtime')``
(``observed_at`` is stored as UTC, rotated per-instant into the machine's zone
before slicing, so DST-correct), so the histogram lands in local time with no
caller rotation. The cost stays 144 rows however deep the history grows.
The base grid behind the whole-mesh Rhythm chart: a minute divides every slice
width the chart may settle on (1/5/10/15/20/30/60 minutes — see the Time
Machine's slice ladder), so one scan here folds client-side into any of them
without re-querying. The slot index is ``HH * 60 + MM``, computed in SQL off the
``HH``/``MM`` substrings of ``datetime(…, 'localtime')`` (``observed_at`` is
stored as UTC, rotated per-instant into the machine's zone before slicing, so
DST-correct), so the histogram lands in local time with no caller rotation. The
cost stays at most 1440 rows however deep the history grows.
Args:
since: Only observations at or after this time, if given.
Returns:
144 counts, index = local ten-minute slice of the day.
1440 counts, index = local minute of the day.
"""
sql = (
"SELECT (CAST(substr(datetime(observed_at, 'localtime'), 12, 2) AS INTEGER) "
"* 60 + CAST(substr(datetime(observed_at, 'localtime'), 15, 2) AS INTEGER)) "
"/ 10 AS slot, COUNT(*) AS n FROM observations"
"SELECT CAST(substr(datetime(observed_at, 'localtime'), 12, 2) AS INTEGER) "
"* 60 + CAST(substr(datetime(observed_at, 'localtime'), 15, 2) AS INTEGER) "
"AS slot, COUNT(*) AS n FROM observations"
)
params: list[Any] = []
if since is not None:
sql += " WHERE observed_at >= ?"
params.append(since.isoformat())
sql += " GROUP BY slot"
counts = [0] * 144
counts = [0] * 1440
for row in self._conn.execute(sql, params).fetchall():
try:
counts[int(row["slot"])] += int(row["n"])
+43 -10
View File
@@ -35,10 +35,11 @@ Beyond timelines, the module owns the app's two other braille conventions:
fills in intermediate marks whenever the chart is wide enough to fit them.
* :func:`axis_chart` — frames :func:`timeline_rows` output in a numeric y-axis
(the dashboard's activity chart, the Time Machine's per-day and rhythm
charts): marks on the left gutter only — the right edge closes with a bare
border, its mirror dropped as redundant (JP, 2026-08-08) — each mark
compacted through :func:`compact_label` so the gutter never outgrows three
cells however deep the tallies run.
charts). Marks tick both edges; whether the right edge also *prints* its
mark follows the platform (see :func:`axis_chrome`) — the desktop mirrors
it, the 53-column console keeps the tick alone and gives the cells to the
chart. Each mark compacts through :func:`compact_label` so the gutter never
outgrows three cells however deep the tallies run.
"""
from __future__ import annotations
@@ -47,6 +48,35 @@ from typing import Callable, Optional, Sequence, Union
from rich.text import Text
from ..platforms import Platform, on_platform
#: Whether :func:`axis_chart` mirrors each mark on the right gutter too. The marks are
#: redundant but nice (JP, 2026-08-09: keep them where space allows), so the roomy
#: desktop frame mirrors them and the 53-column console spends those cells on the chart
#: instead. The right-edge ``├`` tick stays on *both* platforms — dropping the label
#: never drops the tick. Bound at platform-switch time, like every platform-derived
#: constant; :func:`axis_chrome` is how callers size their chart to whichever shape is
#: bound.
_MIRROR_LABELS = True
@on_platform
def _bind_axis_chrome(platform: Platform) -> None:
"""Bind the right-gutter mirror to the platform (runs now and on every switch)."""
global _MIRROR_LABELS
_MIRROR_LABELS = platform.frame_border
def axis_chrome(label_w: int) -> int:
"""Cells one framed chart row spends beside its chart cells, on this platform.
The left gutter (``label_w`` + the space + the ``┤`` tick), the right ``├`` tick,
and — where the platform mirrors its marks — the right gutter's space + label. THE
number a caller subtracts from its render width to size ``chars``, so the layout
can never disagree with what :func:`axis_chart` actually draws.
"""
return label_w + 3 + (label_w + 1 if _MIRROR_LABELS else 0)
#: Braille dot bit for each dot row counted from the *bottom* of a cell (row 0 is
#: the cell's lowest dot), left and right columns. The Unicode braille block
#: numbers its rows top-down (dots 1,2,3,7 left / 4,5,6,8 right); these tables
@@ -552,13 +582,14 @@ def axis_chart(
floor: float = 0.0,
ticks: Optional[Sequence[tuple[int, str]]] = None,
) -> list[Text]:
"""Frame :func:`timeline_rows` output with a left y-axis and an x-axis caption.
"""Frame :func:`timeline_rows` output with a mirrored y-axis and an x-axis caption.
Each row's ticked-dot value marks the left gutter (blank where it would repeat
the mark above or read zero), compacted through :func:`compact_label`; the right
edge closes with a bare border — the mirrored gutter it used to carry was
redundant, and its cells go to the chart (JP, 2026-08-08). A boxed bottom border
and an x-axis caption indented to clear the gutter close the frame.
the mark above or read zero), compacted through :func:`compact_label`. The right
edge always carries the matching ``├`` tick; whether the mark itself is printed
after it follows the platform (see :func:`axis_chrome`) — the desktop mirrors it,
the console keeps the tick alone. A boxed bottom border and an x-axis caption
indented to clear the gutter close the frame.
The caption comes one of two ways. A *continuous* chart passes ``label_at`` and
the ends-plus-quarters marks of :func:`axis_caption` fill in whatever fits. A
@@ -597,7 +628,9 @@ def axis_chart(
for mark, row in zip(marks, chart_rows):
line = Text(f"{mark:>{label_w}} " + ("┤" if mark else "│"), style=style)
line.append_text(row)
line.append("│", style=style)
line.append("├" if mark else "│", style=style)
if mark and _MIRROR_LABELS:
line.append(f" {mark}", style=style)
out.append(line)
if ticks is not None:
border, caption_text = _tick_axis(chars, label_w, ticks, style)
+8 -7
View File
@@ -43,7 +43,7 @@ from rich.text import Text
from ..core.events import MeshEvent
from ..core.models import NODE_TYPE_REPEATER, Observation, utcnow
from ..persistence.repository import OBSERVATION_WINDOW
from .braillechart import axis_chart, axis_label_w, meter, timeline_rows
from .braillechart import axis_chart, axis_chrome, axis_label_w, meter, timeline_rows
from .packet_viewer import (
DEFAULT_ICON,
KIND_ICONS,
@@ -279,16 +279,17 @@ class DashboardScreen(Screen):
"""The all-packet chart — newest minute at the right — plus the pulse line.
One dot column per minute, two per character cell, stretched across every
cell the terminal offers past the left scale gutter (the right edge closes
with a bare border — see :func:`~meshterm.ui.braillechart.axis_chart`); a
wider terminal simply shows more history. Time runs oldest→now left to
right, every MeshTerm timeline's direction.
cell the terminal offers between the scale gutters (drawn as the platform
draws them — the desktop mirrors its marks on the right, the console keeps
the tick alone; see :func:`~meshterm.ui.braillechart.axis_chrome`); a wider
terminal simply shows more history. Time runs oldest→now left to right,
every MeshTerm timeline's direction.
"""
histogram = list(self._activity()) # newest first, one count per minute
# Size the label lane from the whole histogram's peak (not just the visible
# slice) so the gutter never shifts as a burst scrolls out of view.
# slice) so the gutters never shift as a burst scrolls out of view.
label_w = axis_label_w(max(histogram, default=0), _CHART_ROWS)
chars = max(10, width - (label_w + 3))
chars = max(10, width - axis_chrome(label_w))
minutes = chars * 2
shown = (histogram + [0] * minutes)[:minutes]
peak = max(shown)
+30 -26
View File
@@ -36,6 +36,7 @@ from .braillechart import (
_TICK_GAP,
GAP,
axis_chart,
axis_chrome,
axis_label_w,
chart_span,
timeline_rows,
@@ -107,13 +108,13 @@ def bucketize(stamps: list[datetime], start: datetime, end: datetime, buckets: i
return counts
#: The Rhythm chart's candidate slice widths in minutes, finest first. The old 15-minute
#: slices are gone (JP, 2026-08-08): their 48 chart cells plus a gutter outran the
#: PicoCalc's 53 columns, so the chart now takes the finest of these whose full day fits
#: the width — 20-minute slices (72 slots, 36 cells) on both standard terminals, stepping
#: down to 30 minutes and then a full hour only where the width forces it. If even the
#: hour chart is too wide, it draws anyway — tough shit, per the spec.
_RHYTHM_SLICES: tuple[int, ...] = (20, 30, 60)
#: The Rhythm chart's candidate slice widths in minutes, finest first: the chart takes
#: the finest whose full day fits the width (JP, 2026-08-09). A fixed 15-minute slicing
#: used to outrun the PicoCalc's 53 columns; now the standard desktop keeps its 15-minute
#: sweep (48 cells + both gutters), the console steps down only as far as its width
#: forces, and a terminal wide enough earns the finer sweeps. If even the hour chart is
#: too wide, it draws anyway — tough shit, per the spec.
_RHYTHM_SLICES: tuple[int, ...] = (1, 5, 10, 15, 20, 30, 60)
def _slice_note(minutes: int) -> str:
@@ -130,15 +131,15 @@ def _rhythm_slots(stamps: list[datetime], minutes: int) -> list[int]:
return slots
def _fold_slots(tens: list[int], minutes: int) -> list[int]:
"""Fold the repository's ten-minute base grid into ``minutes``-wide slices.
def _fold_slots(minute_grid: list[int], minutes: int) -> list[int]:
"""Fold the repository's minute-of-day base grid into ``minutes``-wide slices.
Ten divides every rung of :data:`_RHYTHM_SLICES`, so the mesh page re-slices the one
:meth:`~meshterm.persistence.repository.Repository.rhythm_activity` scan client-side
instead of re-querying per candidate width.
A minute divides every rung of :data:`_RHYTHM_SLICES`, so the mesh page re-slices the
one :meth:`~meshterm.persistence.repository.Repository.rhythm_activity` scan
client-side instead of re-querying per candidate width.
"""
per = max(1, minutes // 10)
return [sum(tens[i : i + per]) for i in range(0, len(tens), per)]
per = max(1, minutes)
return [sum(minute_grid[i : i + per]) for i in range(0, len(minute_grid), per)]
def _fit_rhythm(
@@ -148,16 +149,17 @@ def _fit_rhythm(
``base_w`` is the gutter width the section's other charts already need; the rhythm's
own scale joins it (a slice's tally can top a single volume bucket's), and the fit is
judged against the row a chart actually draws — the gutter, its tick, the cells, and
the bare closing border. The coarsest slice comes back even when it doesn't fit: the
ladder has nowhere further to step, and a clipped hour chart beats no rhythm at all.
judged against the row a chart actually draws — both gutters as the platform draws
them (:func:`~meshterm.ui.braillechart.axis_chrome`) plus the cells. The coarsest
slice comes back even when it doesn't fit: the ladder has nowhere further to step,
and a clipped hour chart beats no rhythm at all.
"""
slots: list[int] = [0]
label_w = base_w
for minutes in _RHYTHM_SLICES:
slots = slots_at(minutes)
label_w = max(base_w, axis_label_w(max(slots), _CHART_ROWS))
if label_w + 3 + len(slots) // 2 <= width:
if axis_chrome(label_w) + len(slots) // 2 <= width:
return slots, minutes, label_w
return slots, _RHYTHM_SLICES[-1], label_w
@@ -346,8 +348,9 @@ def _node_sections(
# fits (see :data:`_RHYTHM_SLICES`) — a slice's tally can top a single volume
# bucket's, so its peak joins the sizing too.
def _layout(label_w: int) -> tuple[int, int]:
# A chart row spends label_w + 2 on the gutter and 1 on the bare closing border.
chars = max(20, width - (label_w + 3))
# A chart row spends axis_chrome(label_w) beside its cells -- both gutters, as
# the platform draws them (the desktop mirrors its marks, the console doesn't).
chars = max(20, width - axis_chrome(label_w))
return chars, chars * 2
chars, buckets = _layout(1)
@@ -458,8 +461,9 @@ def _self_sections(
# volume bucket, so its peak joins the shared-gutter sizing (see _node_sections for
# the same provisional-then-real width dance).
def _layout(label_w: int) -> tuple[int, int]:
# A chart row spends label_w + 2 on the gutter and 1 on the bare closing border.
chars = max(20, width - (label_w + 3))
# A chart row spends axis_chrome(label_w) beside its cells -- both gutters, as
# the platform draws them (the desktop mirrors its marks, the console doesn't).
chars = max(20, width - axis_chrome(label_w))
return chars, chars * 2
chars, buckets = _layout(1)
@@ -956,11 +960,11 @@ def _mesh_sections(
# The mesh-wide rhythm (charted below) folds the whole window into local time-of-day
# slices at the finest width the ladder fits (see :data:`_RHYTHM_SLICES`), re-sliced
# client-side from one ten-minute base scan. A busy slice's tally can top any single
# client-side from one minute-grid base scan. A busy slice's tally can top any single
# day's, so its peak joins the day peaks in sizing one shared y-axis gutter. The
# slices come back already in local time (rotated per-instant in SQL), no offset
# shuffle here.
tens = ctx.repo.rhythm_activity(since=since)
minute_grid = ctx.repo.rhythm_activity(since=since)
# The y-axis gutter is sized from the whole window's peaks (not just the visible
# slice) and shared by every chart, so all their gutters — and thus their left edges —
@@ -970,9 +974,9 @@ def _mesh_sections(
axis_label_w(max(d[2] for d in series), _CHART_ROWS),
)
slots, slice_minutes, label_w = _fit_rhythm(
lambda minutes: _fold_slots(tens, minutes), width, base_w
lambda minutes: _fold_slots(minute_grid, minutes), width, base_w
)
chars = max(20, width - (label_w + 3))
chars = max(20, width - axis_chrome(label_w))
shown = series[-chars * 2 :]
out: list[RenderableType] = []
packets = [d[1] for d in shown]
+18 -7
View File
@@ -257,20 +257,31 @@ def test_y_axis_labels_blanks_a_repeated_mark() -> None:
assert y_axis_labels(1, 3) == ["1", "", ""]
def test_axis_chart_marks_the_left_gutter_only() -> None:
"""Marks tick the left gutter; the right edge closes with a bare border (no mirror)."""
def test_axis_chart_mirrors_marks_where_the_platform_affords_them() -> None:
"""The desktop frames a chart with marks on both gutters; the console keeps the
right ``├`` tick but spends the mirrored label's cells on the chart instead."""
from meshterm.platforms import PICOCALC, set_platform
from meshterm.ui.braillechart import axis_chrome
rows = timeline_rows([9] * 8, rows=2)
out = axis_chart(rows, 9, 4, lambda f: "now" if f >= 1.0 else "old")
assert len(out) == 4 # 2 chart rows + bottom border + caption
assert out[0].plain == "8 ┤⣿⣿⣿⣿│" # ticked-dot value (the widest mark sizes the gutter)
assert out[1].plain == "3 ┤⣿⣿⣿⣿│"
assert out[0].plain == "8 ┤⣿⣿⣿⣿├ 8" # ticked-dot values, mirrored on the desktop
assert out[1].plain == "3 ┤⣿⣿⣿⣿├ 3"
assert out[2].plain.startswith(" └") and out[2].plain.endswith("┘")
assert axis_chrome(1) == 2 * (1 + 2) # what a caller must budget beside the cells
set_platform(PICOCALC)
tight = axis_chart(timeline_rows([9] * 8, rows=2), 9, 4, lambda f: "x")
assert tight[0].plain == "8 ┤⣿⣿⣿⣿├" # the tick survives; the label's cells don't
assert tight[1].plain == "3 ┤⣿⣿⣿⣿├"
assert axis_chrome(1) == 1 + 3
def test_axis_chart_compacts_deep_tallies_into_the_gutter() -> None:
"""Counts above 999 read as k/M marks, and the gutter sizes to the widest printed mark.
A 1.5k peak prints ``1k`` while a lower tick still lands three digits wide (``563``),
A 1.5k peak prints ``1k`` while a lower tick still lands three digits wide (``562``),
so the gutter takes three cells — sized from the marks, never from the bare peak.
"""
from meshterm.ui.braillechart import axis_label_w, compact_label
@@ -282,8 +293,8 @@ def test_axis_chart_compacts_deep_tallies_into_the_gutter() -> None:
rows = timeline_rows([1500] * 8, rows=2)
out = axis_chart(rows, 1500, 4, lambda f: "x")
assert axis_label_w(1500, 2) == 3
assert out[0].plain == " 1k ┤⣿⣿⣿⣿│" # round(1500 · 7/8) → 1312 → 1k
assert out[1].plain == "562 ┤⣿⣿⣿⣿│" # round(1500 · 3/8) → the three-digit tick
assert out[0].plain == " 1k ┤⣿⣿⣿⣿├ 1k" # round(1500 · 7/8) → 1312 → 1k
assert out[1].plain == "562 ┤⣿⣿⣿⣿├ 562" # round(1500 · 3/8) → the three-digit tick
def test_y_axis_labels_signed_span_quotes_both_extremes() -> None:
+15 -15
View File
@@ -85,8 +85,8 @@ def test_dashboard_renders_all_three_sections() -> None:
assert "advert" in body and "Alice" in body # traffic class + the busiest node
def test_dashboard_activity_chart_reads_newest_right_with_left_scale() -> None:
"""'now' anchors the right edge; the scale marks the left gutter, the right closes bare.
def test_dashboard_activity_chart_reads_newest_right_with_mirrored_scale() -> None:
"""'now' anchors the right edge and the scale marks mirror on both gutters.
Peak 9 over 3 rows (12 dots): the top gutter's ┤ tick crosses its row's third
dot (an 11-dot bar → 9·11/12 ≈ 8), so the mark reads 8, not the peak itself.
@@ -95,14 +95,14 @@ def test_dashboard_activity_chart_reads_newest_right_with_left_scale() -> None:
lines = _stripped(screen.render_body(80))
top = next(line for line in lines if "┤" in line)
assert top.strip().startswith("8 ┤")
assert top.rstrip().endswith("│") # no mirrored mark — the cells went to the chart
assert top.rstrip().endswith("├ 8")
caption = next(line for line in lines if "now" in line)
assert caption.index("−") < caption.index("now") # oldest left, newest right
# The lone newest-minute burst draws against the chart's right border, and the
# The lone newest-minute burst draws against the chart's right gutter, and the
# left half of the chart is bare flatline.
chart = [line for line in lines if "┤" in line or "│" in line]
bottom = chart[-1]
left_half = bottom[3 : 3 + (len(bottom) - 4) // 2]
left_half = bottom[3 : 3 + (len(bottom) - 6) // 2]
assert all(ch in (chr(0x2800), chr(0x2800 | 0x40 | 0x80), " ") for ch in left_half)
assert any(0x2800 <= ord(ch) <= 0x28FF and ord(ch) & 0x3F for ch in chart[0])
@@ -302,13 +302,13 @@ def test_recent_observations_rehydrate_the_packet_payload_class(tmp_path: Path)
repo.close()
def test_rhythm_activity_buckets_by_10_minute_slice(tmp_path: Path) -> None:
"""Observations fall into 144 ten-minute-of-day slots (``(HH * 60 + MM) // 10``).
def test_rhythm_activity_buckets_by_minute_of_day(tmp_path: Path) -> None:
"""Observations fall into 1440 minute-of-day slots (``HH * 60 + MM``).
The slots are local time-of-day, so the observations are stamped at local
wall-clock instants (naive → ``.astimezone()``) — the slice index then matches
each ``HH:MM`` directly, in any runner zone. Ten minutes is the base grid every
rhythm slice width (20/30/60 min) folds from without re-querying.
wall-clock instants (naive → ``.astimezone()``) — the slot index then matches
each ``HH:MM`` directly, in any runner zone. A minute is the base grid every
rhythm slice width (1/5/10/15/20/30/60 min) folds from without re-querying.
"""
repo = Repository(tmp_path / "q.db")
run = repo.start_run("monitor", {}, None)
@@ -319,12 +319,12 @@ def test_rhythm_activity_buckets_by_10_minute_slice(tmp_path: Path) -> None:
observed_at=datetime(2026, 7, 8, hh, mm).astimezone(),
)
for hh, mm in [(0, 0), (0, 44), (17, 55), (17, 59)]:
for hh, mm in [(0, 0), (0, 44), (17, 55), (17, 55)]:
repo.record_observation(run, at(hh, mm))
slots = repo.rhythm_activity()
assert len(slots) == 144
assert slots[0] == 1 # 00:00 → slot 0
assert slots[4] == 1 # 00:44 → slot 4 (44 // 10)
assert slots[107] == 2 # 17:55 and 17:59 → slot (17*60 + 55) // 10
assert len(slots) == 1440
assert slots[0] == 1 # 00:00 → slot 0
assert slots[44] == 1 # 00:44 → slot 44
assert slots[17 * 60 + 55] == 2 # both 17:55 stamps share one minute slot
assert sum(slots) == 4
repo.close()
+2 -2
View File
@@ -416,7 +416,7 @@ def test_node_page_renders_all_sections(tmp_path: Path) -> None:
body = _plain(_node_sections(ctx, NODE, "YUL", None, 90))
assert "Volume" in body and "24 receptions" in body
assert "SNR" in body and "-2.0" in body and "+8.0" in body
assert "Rhythm" in body and "20-min" in body # the ladder's finest slice fits here
assert "Rhythm" in body and "10-min" in body # the finest slice 90 cols affords
assert "Record" in body and "median" in body
assert "advert 24" in body # kinds breakdown, packet rows absent
repo.close()
@@ -468,7 +468,7 @@ def test_mesh_page_renders_days_rhythm_arrivals_and_ledger(tmp_path: Path) -> No
ctx = SimpleNamespace(repo=repo)
body = _plain(_mesh_sections(ctx, None, 90, prefix_bytes=2))
assert "Packets per day" in body and "Nodes per day" in body
assert "Rhythm" in body and "20-min" in body # the ladder's finest slice fits here
assert "Rhythm" in body and "10-min" in body # the finest slice 90 cols affords
assert "Arrivals" in body and "Newcomer" in body
# Arrivals are aligned lanes: the key sits in its own column (labelled KEY,
# per the lexicon) and the old per-row "first heard" prefix now lives once,