diff --git a/meshterm/services/monitor_service.py b/meshterm/services/monitor_service.py index 6d1e7e9..5584a05 100644 --- a/meshterm/services/monitor_service.py +++ b/meshterm/services/monitor_service.py @@ -22,15 +22,18 @@ from typing import TYPE_CHECKING, Optional from ..core.connection import Unsubscribe from ..core.events import EventKind, MeshEvent -from ..persistence.repository import ACTIVITY_BUCKETS if TYPE_CHECKING: from ..context import AppContext -#: Seconds per bucket of the all-packet activity histogram — five minutes, one braille -#: dot column of the header's indicator, matching the channel sparkline's geometry -#: (:data:`~meshterm.persistence.repository.ACTIVITY_BUCKETS` buckets = two hours). -ACTIVITY_BUCKET_S = 300 +#: Seconds per bucket of the all-packet activity histogram — one minute, one braille +#: dot column of the header indicator and the dashboard's activity chart. +ACTIVITY_BUCKET_S = 60 + +#: How many one-minute buckets the histogram retains — six hours, deep enough that the +#: header and the dashboard can both stretch their charts to fill any realistic terminal +#: width (two buckets per character cell) and still be drawing history, not padding. +ACTIVITY_BUCKETS = 360 class MonitorService: @@ -52,10 +55,10 @@ class MonitorService: self._run_id: Optional[int] = None self._session_count = 0 self._run_start_count = 0 - # All-packet activity, bucketed by wall-clock five-minute slot (epoch // span → - # count). Every hub event counts — observations, messages, acks — because the - # header's indicator answers "is the mesh alive?", not "any mail?". Pruned as it - # rolls, so it never holds more than the two-hour window plus one closing bucket. + # All-packet activity, bucketed by wall-clock minute (epoch // span → count). + # Every hub event counts — observations, messages, acks — because the header's + # indicator answers "is the mesh alive?", not "any mail?". Pruned as it rolls, + # so it never holds more than the six-hour window plus one closing bucket. self._activity: dict[int, int] = {} # Session-long tallies by packet class (advert/telemetry/packet/message/ack), # fed by the same kind-unfiltered subscription — the dashboard's traffic panel. @@ -80,14 +83,15 @@ class MonitorService: return self._start_total + self._session_count def activity_histogram(self) -> tuple[int, ...]: - """All-packet counts per five-minute bucket over the trailing two hours. + """All-packet counts per one-minute bucket over the trailing six hours. - Newest first — index 0 is the current five minutes — the order the header's - braille indicator draws. Counts everything the hub fans out this session; time - before launch simply reads as silence. + 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. Returns: - :data:`~meshterm.persistence.repository.ACTIVITY_BUCKETS` bucket counts. + :data:`ACTIVITY_BUCKETS` bucket counts. """ bucket = int(time.time() // ACTIVITY_BUCKET_S) return tuple(self._activity.get(bucket - i, 0) for i in range(ACTIVITY_BUCKETS)) diff --git a/meshterm/ui/dashboard_screen.py b/meshterm/ui/dashboard_screen.py index c2fbff2..3ec9fc8 100644 --- a/meshterm/ui/dashboard_screen.py +++ b/meshterm/ui/dashboard_screen.py @@ -4,11 +4,12 @@ The interactive face of the ``dashboard`` tool. One full-screen, always-repainti stacks four reads of the mesh, coarsest first: * **Activity** — a tall braille bar chart of *every* packet the hub hears (adverts, - telemetry, RX-logged packets, messages, acks) over the trailing two hours, one column - per five-minute bucket, newest at the left — the header indicator's big sibling, - drawn from the same :meth:`~meshterm.services.monitor_service.MonitorService` - buckets. A pulse line beneath it reads the rate, who's been heard, and the busiest - node of the window. + telemetry, RX-logged packets, messages, acks), one dot column per minute — braille's + full horizontal resolution, two minutes per character — stretched across whatever + width the terminal offers, newest at the left with the count scale mirrored on both + edges. The header indicator's big sibling, drawn from the same + :meth:`~meshterm.services.monitor_service.MonitorService` buckets. A pulse line + beneath it reads the rate, who's been heard, and the busiest node of the window. * **Traffic** — the session's tallies by packet class, each with a proportional bar, from the monitor's kind counters. * **RF health** — the trailing window's reception quality: median SNR (on the trace @@ -35,7 +36,7 @@ from rich.text import Text from ..core.events import EventKind, MeshEvent from ..core.models import NODE_TYPE_REPEATER, Observation, utcnow -from ..persistence.repository import ACTIVITY_BUCKETS, ACTIVITY_WINDOW +from ..persistence.repository import ACTIVITY_WINDOW from .theme import snr_style from .trace_screen import snr_bar from .tui.render import render_lines @@ -84,20 +85,52 @@ def _fit(text: str, width: int) -> str: return text.ljust(width) -def braille_bars(values: list[int], *, rows: int = _CHART_ROWS) -> list[Text]: - """Render ``values`` as a braille bar chart, one full character column per value. +def _span_label(minutes: int) -> str: + """A compact duration — ``45 min`` under two hours, else ``2.5 h`` / ``3 h``.""" + if minutes < 120: + return f"{minutes} min" + text = f"{minutes / 60:.1f}" + return (text[:-2] if text.endswith(".0") else text) + " h" - Each value becomes one character-wide column (both dot columns at the same height), - scaled so the window's peak fills all ``rows × 4`` dot rows. Zero columns draw a - faint two-dot baseline on the bottom row — the flatline convention of the app's - sparklines — and blank braille above, so the chart floor is always visible. + +def _axis_labels(peak: int, rows: int) -> list[str]: + """Each chart row's top-edge count, top row first, dupes and zeros blanked. + + The top row always reads the peak; lower rows read the proportional counts at + their upper edges, but a mark that would repeat the one above (a low peak makes + neighbouring rows round to the same value) or read zero is left blank, so the + scale never shows the same number twice. + """ + labels: list[str] = [] + seen: set[int] = set() + for i in range(rows): + value = round(peak * (rows - i) / rows) + if peak and value and value not in seen: + labels.append(str(value)) + seen.add(value) + else: + labels.append("") + return labels + + +def braille_bars(values: list[int], *, rows: int = _CHART_ROWS) -> list[Text]: + """Render ``values`` as a braille bar chart, one *dot column* per value. + + Braille offers two dot columns per character cell — the font's full horizontal + resolution — so consecutive values pair up into one cell, each rising to its own + height. Bars are scaled so the window's peak fills all ``rows × 4`` dot rows, and + any non-zero value lights at least one dot, so a lone packet never vanishes. A + silent dot column keeps a faint one-dot floor on the bottom row — the flatline + convention of the app's sparklines — so the chart floor is always visible. Args: - values: The bucket counts, drawn left to right. + values: The bucket counts, drawn left to right (two per character cell; an + odd count is padded with one silent column). rows: How many braille rows tall the chart is. Returns: - ``rows`` :class:`Text` lines, top row first. + ``rows`` :class:`Text` lines, top row first, ``ceil(len(values) / 2)`` + characters wide. """ peak = max(values, default=0) total_dots = rows * 4 @@ -105,14 +138,22 @@ def braille_bars(values: list[int], *, rows: int = _CHART_ROWS) -> list[Text]: (0 if peak == 0 or v <= 0 else max(1, round(v / peak * total_dots))) for v in values ] + if len(heights) % 2: + heights.append(0) lines: list[Text] = [] for row in range(rows): floor = (rows - 1 - row) * 4 # dot rows below this braille row line = Text() - for value, height in zip(values, heights): - fill = min(4, max(0, height - floor)) - if fill: - line.append(chr(0x2800 | _COL_LEFT[fill] | _COL_RIGHT[fill]), style="ok") + for left, right in zip(heights[0::2], heights[1::2]): + lf = min(4, max(0, left - floor)) + rf = min(4, max(0, right - floor)) + if lf or rf: + mask = _COL_LEFT[lf] | _COL_RIGHT[rf] + if row == rows - 1: + # Keep the floor continuous under a half-silent cell: the silent + # dot column still shows its bottom baseline dot. + mask |= (0x40 if lf == 0 else 0) | (0x80 if rf == 0 else 0) + line.append(chr(0x2800 | mask), style="ok") elif row == rows - 1: line.append(chr(0x2800 | 0x40 | 0x80), style="faint") # the flatline else: @@ -218,7 +259,7 @@ class DashboardScreen(Screen): """Render the four stacked sections for the current state.""" self._prune() sections: list[RenderableType] = [ - *self._activity_section(), + *self._activity_section(width), Text(), *self._traffic_section(), Text(), @@ -232,61 +273,93 @@ class DashboardScreen(Screen): # -- activity -- - def _activity_section(self) -> list[RenderableType]: - """The two-hour all-packet chart, oldest at the left, plus the pulse line.""" - histogram = list(self._activity()) - peak = max(histogram, default=0) + def _activity_section(self, width: int) -> list[RenderableType]: + """The all-packet chart — newest minute at the left — plus the pulse line. + + One dot column per minute, two per character cell, stretched across every + cell the terminal offers between the two scale gutters; a wider terminal + simply shows more history. The scale is mirrored on both edges so the counts + are readable from either end of a wide chart. + """ + 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 gutters never shift as a burst scrolls out of view. + label_w = max(1, len(str(max(histogram, default=0)))) + chars = max(10, width - 2 * (label_w + 2)) + minutes = chars * 2 + shown = (histogram + [0] * minutes)[:minutes] + peak = max(shown) + heading = Text("Activity", style="accent") - heading.append(" · every packet heard · 2 h", style="muted") - # The histogram arrives newest-first; the chart reads left→right in time, so - # flip it — a burst enters at the right edge and slides left as it ages. - chart_rows = braille_bars(histogram[::-1]) - label_w = len(str(peak)) if peak else 1 + heading.append(" · every packet heard · one minute per dot column", + style="muted") + chart_rows = braille_bars(shown) + marks = _axis_labels(peak, len(chart_rows)) out: list[RenderableType] = [heading] - for i, row in enumerate(chart_rows): - prefix = f"{peak:>{label_w}} ┤" if i == 0 else " " * label_w + " │" - line = Text(prefix, style="muted") + for mark, row in zip(marks, chart_rows): + line = Text(f"{mark:>{label_w}} " + ("┤" if mark else "│"), style="muted") line.append_text(row) + line.append("├" if mark else "│", style="muted") + if mark: + line.append(f" {mark}", style="muted") out.append(line) - axis = Text(" " * label_w + " └", style="muted") - span = ACTIVITY_BUCKETS # one character per bucket - axis.append("─" * span, style="muted") + axis = Text(" " * label_w + " └" + "─" * chars + "┘", style="muted") out.append(axis) - caption = Text(" " * (label_w + 2), style="muted") - caption.append("−2 h", style="faint") - pad = span - len("−2 h") - len("now") - caption.append(" " * max(1, pad)) + span = "−" + _span_label(minutes) + caption = Text(" " * (label_w + 2)) caption.append("now", style="faint") + caption.append(" " * max(1, chars - len("now") - len(span))) + caption.append(span, style="faint") out.append(caption) out.append(Text()) - out.append(self._pulse_line(histogram)) + out.append(self._pulse_line(shown, width)) return out - def _pulse_line(self, histogram: list[int]) -> Text: - """Rates, who's been heard, and the window's busiest transmitter.""" - recent = sum(histogram[:3]) / 15.0 # the last three 5-min buckets - overall = sum(histogram) / (ACTIVITY_BUCKETS * 5.0) + def _pulse_line(self, shown: list[int], width: int) -> Text: + """Rates, who's been heard, and the window's busiest transmitter. + + ``shown`` is the chart's visible slice (newest first, one bucket per minute), + so the quoted rates describe exactly what the chart draws. The word "heard" + after the node count is a luxury: it is kept only when the line fits ``width`` + without wrapping. + """ + recent = sum(shown[:15]) / max(1, min(15, len(shown))) + overall = sum(shown) / max(1, len(shown)) + span = _span_label(len(shown)) nodes = {o.node for o in self._window if o.node and o.kind != "packet"} repeaters = { o.node for o in self._window if o.node and o.node_type == NODE_TYPE_REPEATER } - line = Text("pulse ", style="muted") - line.append(f"{recent:.1f} pkt/min", style="brand") - line.append(f" (15 m) · {overall:.1f} (2 h)", style="muted") - line.append(" · ", style="muted") - line.append(str(len(nodes))) - line.append(f" node{'s' if len(nodes) != 1 else ''} heard", style="muted") - if repeaters: - line.append(f" ({len(repeaters)} repeater{'s' if len(repeaters) != 1 else ''})", - style="muted") + + def compose(heard: bool) -> Text: + line = Text("pulse ", style="muted") + line.append(f"{recent:.1f} pkt/min", style="brand") + line.append(f" (15 m) · {overall:.1f} ({span})", style="muted") + line.append(" · ", style="muted") + line.append(str(len(nodes))) + suffix = f" node{'s' if len(nodes) != 1 else ''}" + line.append(suffix + (" heard" if heard else ""), style="muted") + if repeaters: + line.append( + f" ({len(repeaters)} repeater{'s' if len(repeaters) != 1 else ''})", + style="muted", + ) + return line + + line = compose(heard=True) + if len(line.plain) > width: + line = compose(heard=False) busiest = self._busiest() if busiest is not None: name, count = busiest line.append("\nbusiest ", style="muted") line.append(name, style="brand") - line.append(f" {count} packets in the window", style="muted") + line.append( + f" {count} packet{'s' if count != 1 else ''} in the window", + style="muted", + ) return line def _busiest(self) -> Optional[tuple[str, int]]: @@ -317,8 +390,13 @@ class DashboardScreen(Screen): count = counts[kind] row = Text(f"{kind.ljust(label_w)} ", style="muted") row.append(f"{count:>{count_w}} ") - bar_len = max(1, round(count / peak * 24)) - row.append("⣿" * bar_len, style=_KIND_STYLES.get(kind, "brand")) + # Bars step in half characters — braille's two dot columns per cell — + # so the lane resolves 48 levels across its 24 cells. + halves = max(1, round(count / peak * 48)) + style = _KIND_STYLES.get(kind, "brand") + row.append("⣿" * (halves // 2), style=style) + if halves % 2: + row.append("⡇", style=style) # a lone left dot column: the half step rows.append(row) return rows diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 32f7fd9..70ab5e8 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -6,12 +6,14 @@ approach as the live trace/TX screen tests. from __future__ import annotations +import re from datetime import timedelta from pathlib import Path from meshterm.core.events import MeshEvent from meshterm.core.models import Ack, Message, Observation, utcnow -from meshterm.persistence.repository import ACTIVITY_BUCKETS, Repository +from meshterm.persistence.repository import Repository +from meshterm.services.monitor_service import ACTIVITY_BUCKETS from meshterm.ui.dashboard_screen import DashboardScreen, braille_bars @@ -45,34 +47,56 @@ def _plain(lines: list[str]) -> str: return "\n".join(lines) +def _stripped(lines: list[str]) -> list[str]: + """The rendered lines with ANSI escapes removed, for structural assertions.""" + return [re.sub(r"\x1b\[[0-9;]*m", "", line) for line in lines] + + # --- braille_bars -------------------------------------------------------------------- def test_braille_bars_scales_the_peak_to_full_height() -> None: - """The window's peak fills the whole chart; a zero column draws the flatline.""" - rows = braille_bars([0, 6, 12], rows=3) + """The window's peak fills the chart; values pair up two dot columns per cell.""" + rows = braille_bars([12, 12, 0, 0], rows=3) assert len(rows) == 3 - assert all(len(r.plain) == 3 for r in rows) - # The peak column is fully lit on the top row; the zero column is blank there. - assert rows[0].plain[2] == chr(0x2800 | 0x47 | 0xB8) - assert rows[0].plain[0] == chr(0x2800) - # The zero column keeps the faint two-dot floor on the bottom row. - assert rows[2].plain[0] == chr(0x2800 | 0x40 | 0x80) + assert all(len(r.plain) == 2 for r in rows) + # The peak pair fills both dot columns of its cell on the top row; the silent + # pair is blank there and keeps the faint two-dot floor on the bottom row. + assert rows[0].plain[0] == chr(0x2800 | 0x47 | 0xB8) + assert rows[0].plain[1] == chr(0x2800) + assert rows[2].plain[1] == chr(0x2800 | 0x40 | 0x80) + + +def test_braille_bars_gives_each_dot_column_its_own_height() -> None: + """Two values sharing a cell rise independently — braille's full resolution.""" + rows = braille_bars([12, 6], rows=3) + assert rows[0].plain[0] == chr(0x2800 | 0x47) # left full, right below + assert rows[1].plain[0] == chr(0x2800 | 0x47 | 0xA0) # right's head: 2 dots + assert rows[2].plain[0] == chr(0x2800 | 0x47 | 0xB8) # both full at the base def test_braille_bars_never_hides_a_lone_packet() -> None: """A tiny non-zero value still lights (in the lit style, not the faint floor's).""" - rows = braille_bars([1, 1000], rows=3) + rows = braille_bars([1, 0, 1000, 1000], rows=3) first_span = rows[2].spans[0] assert first_span.start == 0 and first_span.style == "ok" def test_braille_bars_all_silent_is_a_flatline() -> None: """With nothing heard the chart is a floor line, not a divide-by-zero.""" - rows = braille_bars([0, 0, 0], rows=2) + rows = braille_bars([0, 0, 0, 0, 0, 0], rows=2) assert rows[1].plain == chr(0x2800 | 0x40 | 0x80) * 3 +def test_braille_bars_pads_an_odd_tail_column() -> None: + """An odd value count still renders whole cells (the tail column stays silent).""" + rows = braille_bars([4], rows=1) + assert len(rows[0].plain) == 1 + # The lone value fills its left dot column; the padded right column keeps the + # floor dot so the baseline stays continuous. + assert rows[0].plain[0] == chr(0x2800 | 0x47 | 0x80) + + # --- the screen ---------------------------------------------------------------------- @@ -91,6 +115,40 @@ def test_dashboard_renders_all_four_sections() -> None: assert "advert" in body and "Alice" in body and "YUL" in body +def test_dashboard_activity_chart_reads_newest_left_with_mirrored_scale() -> None: + """'now' anchors the left edge and the peak count marks both gutters.""" + screen = _screen(histogram=[9] + [0] * (ACTIVITY_BUCKETS - 1)) + lines = _stripped(screen.render_body(80)) + top = next(line for line in lines if "┤" in line) + assert top.strip().startswith("9 ┤") + assert top.rstrip().endswith("├ 9") + caption = next(line for line in lines if "now" in line) + assert caption.index("now") < caption.index("−") # newest left, oldest right + + +def test_dashboard_activity_chart_fills_the_width() -> None: + """The chart stretches to the render width: wider terminal, more minutes shown.""" + screen = _screen(histogram=[5] * ACTIVITY_BUCKETS) + for width in (60, 110): + lines = _stripped(screen.render_body(width)) + top = next(line for line in lines if "┤" in line) + assert len(top) == width # gutters + chart consume every cell + narrow = next(line for line in _stripped(screen.render_body(60)) if "└" in line) + wide = next(line for line in _stripped(screen.render_body(110)) if "└" in line) + assert wide.count("─") > narrow.count("─") + + +def test_dashboard_pulse_drops_heard_only_when_it_wont_fit() -> None: + """The pulse line keeps ' heard' at full width and sheds it instead of wrapping.""" + screen = _screen(window=[_obs(), _obs(node="3d63", node_type=2)]) + shown = [1] * 120 + roomy = screen._pulse_line(shown, 100).plain.splitlines()[0] + assert "nodes heard" in roomy + tight = screen._pulse_line(shown, len(roomy) - 1).plain.splitlines()[0] + assert "heard" not in tight and "nodes" in tight + assert len(tight) <= len(roomy) - 1 + + def test_dashboard_live_events_land_in_the_feed_and_window() -> None: """Observations, messages, and acks each fold into the feed as they arrive.""" screen = _screen() diff --git a/tests/test_monitor.py b/tests/test_monitor.py index cb010c7..c1832d8 100644 --- a/tests/test_monitor.py +++ b/tests/test_monitor.py @@ -295,7 +295,7 @@ async def test_monitor_service_counts_every_packet_kind(tmp_path: Path) -> None: """The activity histogram counts observations, messages, and acks alike, newest first.""" from meshterm.core.events import MeshEvent from meshterm.core.models import Ack, Message - from meshterm.persistence.repository import ACTIVITY_BUCKETS + from meshterm.services.monitor_service import ACTIVITY_BUCKETS repo = Repository(tmp_path / "act.db") ctx = _StubContext(repo, MockDevice())