diff --git a/meshterm/tools/atlas.py b/meshterm/tools/atlas.py index 395bc9f..eac9e57 100644 --- a/meshterm/tools/atlas.py +++ b/meshterm/tools/atlas.py @@ -28,7 +28,12 @@ class AtlasTool(Tool): name = "atlas" title = "Mesh atlas" - icon = "πŸ•ΈοΈ" + # A single-codepoint emoji (like every other tool icon), not a VS16 sequence: the + # emoji-width calibration strips VS16 on terminals that render it narrow, which would + # measure a πŸ•ΈοΈ one cell short of how it paints and drift this row's help text right of + # the column the others align to. The wireframe globe reads as the logical topology, + # the geographic map's 🌍 counterpart. + icon = "🌐" help = "Draw the mesh's observed topology β€” links, SNR, hop rings" category = "Mesh" order = 32 # beside Map: the logical shape next to the geographic one diff --git a/meshterm/ui/braillechart.py b/meshterm/ui/braillechart.py index a4dbcaa..a702ff0 100644 --- a/meshterm/ui/braillechart.py +++ b/meshterm/ui/braillechart.py @@ -271,7 +271,7 @@ def axis_caption( label_at: Callable[[float], str], *, style: str = "faint", -) -> Text: +) -> tuple[Text, list[int]]: """The caption line under a timeline: edge labels plus whatever marks fit between. Every chart used to caption only its ends (``oldest … now``); this asks @@ -289,33 +289,40 @@ def axis_caption( style: Style the whole caption is drawn in. Returns: - A :class:`Text` exactly ``chars`` cells wide. + ``(caption, tick_cells)`` β€” the caption :class:`Text` exactly ``chars`` cells + wide, and the chart column each placed label points at, so the axis border can + notch a ``┬`` under it (see :func:`axis_chart`). """ for segments in (4, 2, 1): fractions = [i / segments for i in range(segments + 1)] labels = [label_at(f) for f in fractions] cells: list[str] = [" "] * chars taken: list[tuple[int, int]] = [] # placed [start, end) spans, in order + ticks: list[int] = [] # the chart column each label points at ok = True for frac, label in zip(fractions, labels): if frac == 0.0: start = 0 + ref = 0 elif frac == 1.0: start = chars - len(label) + ref = chars - 1 else: centre = round(frac * chars) start = min(chars - len(label), max(0, centre - len(label) // 2)) + ref = min(chars - 1, centre) end = start + len(label) if end > chars or any(start < e + 2 and s < end + 2 for s, e in taken): ok = False break taken.append((start, end)) + ticks.append(ref) cells[start:end] = label if ok: - return Text("".join(cells), style=style) + return Text("".join(cells), style=style), ticks # Even the two edge labels collide: keep the left one and let it stand alone. label = label_at(0.0)[:chars] - return Text(label.ljust(chars), style=style) + return Text(label.ljust(chars), style=style), [0] def y_axis_labels(peak: float, rows: int, *, lo: float = 0.0) -> list[str]: @@ -372,7 +379,7 @@ def _tick_axis( string, ready to indent under the gutter. """ cells = [" "] * chars - marked: set[int] = set() + marked: list[int] = [] last_end = -_TICK_GAP for cell, label in sorted(ticks): cell = max(0, min(chars - 1, cell)) @@ -380,11 +387,16 @@ def _tick_axis( if start < last_end + _TICK_GAP: continue # would crowd the label before it β€” drop this mark cells[start : start + len(label)] = list(label) - marked.add(cell) + marked.append(cell) last_end = start + len(label) + return _tick_border(chars, label_w, marked, style), "".join(cells) + + +def _tick_border(chars: int, label_w: int, tick_cells: Sequence[int], style: str) -> Text: + """The boxed bottom border, notched with a ``┬`` at each charted tick column.""" + marked = {max(0, min(chars - 1, c)) for c in tick_cells} bar = "".join("┬" if i in marked else "─" for i in range(chars)) - border = Text(" " * label_w + " β””" + bar + "β”˜", style=style) - return border, "".join(cells) + return Text(" " * label_w + " β””" + bar + "β”˜", style=style) def axis_chart( @@ -444,14 +456,17 @@ def axis_chart( out.append(line) if ticks is not None: border, caption_text = _tick_axis(chars, label_w, ticks, style) - out.append(border) caption = Text(" " * (label_w + 2)) caption.append(caption_text, style="faint") else: assert label_at is not None, "axis_chart needs label_at or ticks" - out.append(Text(" " * label_w + " β””" + "─" * chars + "β”˜", style=style)) + # A continuous axis notches the same ┬ ticks under its ends-and-quarters + # labels as a columnar one does under its bars β€” one axis grammar everywhere. + caption_body, tick_cells = axis_caption(chars, label_at) + border = _tick_border(chars, label_w, tick_cells, style) caption = Text(" " * (label_w + 2)) - caption.append_text(axis_caption(chars, label_at)) + caption.append_text(caption_body) + out.append(border) out.append(caption) return out diff --git a/meshterm/ui/config_editor.py b/meshterm/ui/config_editor.py index 3046188..222d954 100644 --- a/meshterm/ui/config_editor.py +++ b/meshterm/ui/config_editor.py @@ -784,17 +784,19 @@ async def send_advert(ctx: "AppContext") -> None: # No emoji in this floating dialog's title: a terminal that paints an emoji a cell # narrower than Rich measures it leaves the content-sized popup's title border short, # bleeding the backdrop through the frame. The menu row keeps its πŸ“‘ icon (drawn in the - # full-width base, where the miscount has nowhere to show). + # full-width base, where the miscount has nowhere to show). filterable=False too: a + # stray key must not narrow (and so resize) this fixed four-item list. choice = await ctx.ui.select( "Send advert", [ - Choice(title="Zero-hop β€” Announce directly to neighbours in range", value="zero"), + Choice(title="Zero-hop β€” Announce to direct neighbours", value="zero"), Choice(title="Flood β€” Repeaters rebroadcast it across the mesh", value="flood"), Choice(title="Share QR / URI β€” Show this node's contact card", value="share"), Separator(" "), Choice(title="Back", value=None), ], prompt="Announce this node to the mesh:", + filterable=False, ) if choice is None: return diff --git a/meshterm/ui/packet_viewer.py b/meshterm/ui/packet_viewer.py index 3cf846e..369974b 100644 --- a/meshterm/ui/packet_viewer.py +++ b/meshterm/ui/packet_viewer.py @@ -93,6 +93,14 @@ KIND_ICONS = { } DEFAULT_ICON = "❔" +#: The floating dialog is sized to its content, which otherwise shrinks and grows as you +#: page between a five-line advert and a telemetry frame's twenty β€” a jarring resize on +#: every keystroke. Padding a short packet's body up to this floor holds the box at a +#: steady minimum height so navigation stays put; a genuinely tall packet still grows past +#: it. Sized for the common overheard-packet layout (heard/from/reception/class/route/via) +#: so paging a burst of similar frames never resizes at all. +_MIN_BODY_ROWS = 10 + @dataclass(slots=True) class PacketEntry: @@ -365,6 +373,10 @@ class PacketViewer(Screen): grid.add_row(Text(label, style="muted"), value) lines = render_lines(grid, width) self._scroll_total = max(1, len(lines)) + # Hold the dialog at a steady minimum height so paging between a short packet and + # a tall one doesn't resize the box out from under the reader (see _MIN_BODY_ROWS). + if len(lines) < _MIN_BODY_ROWS: + lines += [""] * (_MIN_BODY_ROWS - len(lines)) return lines def _rows(self, entry: PacketEntry) -> list[tuple[str, RenderableType]]: diff --git a/meshterm/ui/surface.py b/meshterm/ui/surface.py index 5b050d3..64385c7 100644 --- a/meshterm/ui/surface.py +++ b/meshterm/ui/surface.py @@ -111,10 +111,13 @@ class Ui: prompt: str = "", default: Any = None, wrap: bool = True, + filterable: bool = True, ) -> Any: """Prompt the user to choose one item; return its value or ``None`` if cancelled. - ``prompt`` draws an instruction inside the popup, above the list. + ``prompt`` draws an instruction inside the popup, above the list. Pass + ``filterable=False`` for a short, fixed list so a stray key can't narrow (and + resize) it. """ raise NotImplementedError @@ -282,6 +285,7 @@ class PlainUi(Ui): prompt: str = "", default: Any = None, wrap: bool = True, + filterable: bool = True, ) -> Any: """Unsupported in scripted CLI mode.""" raise self._no_prompt() @@ -494,10 +498,11 @@ class TuiUi(Ui): prompt: str = "", default: Any = None, wrap: bool = True, + filterable: bool = True, ) -> Any: """Delegate to the session's select screen.""" return await self.session.select( - title, items, prompt=prompt, default=default, wrap=wrap + title, items, prompt=prompt, default=default, wrap=wrap, filterable=filterable ) async def select_startup( diff --git a/meshterm/ui/timemachine_screen.py b/meshterm/ui/timemachine_screen.py index b55dc53..8345a6b 100644 --- a/meshterm/ui/timemachine_screen.py +++ b/meshterm/ui/timemachine_screen.py @@ -22,7 +22,7 @@ transmits. from __future__ import annotations -from datetime import datetime, timedelta +from datetime import date, datetime, timedelta from statistics import median from typing import TYPE_CHECKING, Callable, Optional @@ -368,6 +368,43 @@ def _day_ticks(shown: list, chars: int) -> list[tuple[int, str]]: return ticks +def _fill_days( + active: list[tuple[str, int, int]], since: Optional[datetime], now: datetime +) -> list[tuple[str, int, int]]: + """Fill a day series' gaps so an empty day shows as an empty bar, not a skip. + + ``daily_activity`` returns only days with traffic, so a quiet day used to vanish and + its busy neighbours fused β€” a fortnight with two dead days reading as twelve adjacent + bars. This walks every calendar day of the window and emits ``(iso, 0, 0)`` for the + silent ones, so the chart's x-axis is real calendar time. The range runs from the + window's floor (but never earlier than the first day ever recorded β€” we don't invent + emptiness from before monitoring began) through today. + + Args: + active: ``(iso_day, packets, nodes)`` for days with activity, oldest first. + since: The window's start (``None`` = all of history). + now: The current time (the series ends on its calendar day). + + Returns: + ``(iso_day, packets, nodes)`` for every calendar day in range, oldest first. + """ + if not active: + return [] + by_iso = {iso: (packets, nodes) for iso, packets, nodes in active} + first = date.fromisoformat(active[0][0]) + floor = since.date() if since is not None else first + start = max(first, floor) + end = max(start, now.date()) + out: list[tuple[str, int, int]] = [] + day = start + while day <= end: + iso = day.isoformat() + packets, nodes = by_iso.get(iso, (0, 0)) + out.append((iso, packets, nodes)) + day += timedelta(days=1) + return out + + def _day_columns(values: list[int], chars: int) -> list: """Stretch per-day counts into day-wide bars that fill the chart's width exactly. @@ -436,10 +473,7 @@ def _mesh_sections( """ now = utcnow() since = now - window if window is not None else None - days = ctx.repo.daily_activity() - if since is not None: - floor = since.strftime("%Y-%m-%d") - days = [d for d in days if d[0] >= floor] + days = _fill_days(ctx.repo.daily_activity(), since, now) if not days: return [ Text(), @@ -447,10 +481,23 @@ def _mesh_sections( Text("Press w to widen it.", style="muted"), ] - # The y-axis gutter is sized from the whole window's peaks (not just the - # visible slice), shared by both day charts so their gutters line up and - # neither chart's date range shifts relative to the other's. - label_w = max(len(str(max(d[1] for d in days))), len(str(max(d[2] for d in days)))) + # The mesh-wide rhythm (charted below) folds the whole window into 96 fifteen-minute + # slices, so a busy slice's tally can top any single day's β€” compute it up front so its + # peak joins the day peaks in sizing one shared y-axis gutter. + offset_slots = round( + (datetime.now().astimezone().utcoffset() or timedelta()).total_seconds() / 900 + ) + utc_slots = ctx.repo.quarter_hour_activity(since=since) + slots = [utc_slots[(s - offset_slots) % 96] for s in range(96)] + + # 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 β€” + # line up. The rhythm keeps its own finer width; only the gutter is common. + label_w = max( + len(str(max(d[1] for d in days))), + len(str(max(d[2] for d in days))), + len(str(max(slots))), + ) chars = max(20, width - 2 * (label_w + 2)) shown = days[-chars * 2 :] out: list[RenderableType] = [] @@ -475,17 +522,17 @@ def _mesh_sections( ) # The node page's rhythm chart, mesh-wide and four times finer: when does this *mesh* - # talk? 15-minute slices are grouped by UTC in SQL and rotated here into local time by - # the current offset in quarter-hour units (see Repository.quarter_hour_activity for why - # one rotation is honest enough). The wider chart earns the finer resolution its width. - offset_slots = round( - (datetime.now().astimezone().utcoffset() or timedelta()).total_seconds() / 900 - ) - utc_slots = ctx.repo.quarter_hour_activity(since=since) - slots = [utc_slots[(s - offset_slots) % 96] for s in range(96)] + # talk? The 96 fifteen-minute slices (grouped by UTC in SQL, rotated into local time + # above) keep their own 48-cell width but share the day charts' gutter, so this chart's + # left edge lines up with the two above it. out.append(Text()) out.append(_heading("Rhythm", "packets by local time of day Β· 15-min slices")) - out.extend(axis_chart(timeline_rows(slots, rows=_CHART_ROWS), max(slots), 48, _quarter_axis)) + out.extend( + axis_chart( + timeline_rows(slots, rows=_CHART_ROWS), max(slots), 48, + _quarter_axis, label_w=label_w, + ) + ) arrivals = ctx.repo.first_seen(since=since) out.append(Text()) diff --git a/meshterm/ui/tui/select.py b/meshterm/ui/tui/select.py index bf7a9eb..3ec69e1 100644 --- a/meshterm/ui/tui/select.py +++ b/meshterm/ui/tui/select.py @@ -76,7 +76,7 @@ class SelectScreen(Screen): *, prompt: str = "", default: Any = None, - footer_hint: str = "↑↓ move Β· type to filter Β· Enter select Β· Esc back", + footer_hint: Optional[str] = None, filterable: bool = True, wrap: bool = True, ) -> None: @@ -88,7 +88,8 @@ class SelectScreen(Screen): prompt: An optional instruction shown inside the box, above the list β€” so a floating select reads like the other dialogs (a prompt above its controls). default: A choice value to pre-highlight, if present. - footer_hint: Footer key hint. + footer_hint: Footer key hint; defaults to one that mentions type-to-filter only + when ``filterable`` (a fixed list shouldn't advertise a filter it ignores). filterable: Whether typing narrows the list. Off for short, fixed lists (e.g. the startup device picker) where type-to-filter would only get in the way. wrap: Whether the highlight wraps around the ends (Down from the last row jumps @@ -97,6 +98,12 @@ class SelectScreen(Screen): """ super().__init__() self.title = title + if footer_hint is None: + footer_hint = ( + "↑↓ move Β· type to filter Β· Enter select Β· Esc back" + if filterable + else "↑↓ move Β· Enter select Β· Esc back" + ) self.footer_hint = footer_hint self._prompt = prompt self._filterable = filterable diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index c114368..126e62d 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -140,11 +140,20 @@ class TuiSession: """Pop ``screen`` (or the top) off the stack and repaint.""" if not self._stack: return + popped: Optional[Screen] = None if screen is None or self._stack[-1] is screen: - self._stack.pop() + popped = self._stack.pop() elif screen in self._stack: self._stack.remove(screen) + popped = screen self._expose_overlay() + # A floating dialog is drawn as a content-sized box over the screen beneath. If any + # of its cells held a glyph the terminal painted wider than prompt_toolkit tracks + # (an emoji or box-draw fallback the differential renderer can't see), that overhang + # would otherwise survive as stray characters in the dialog's wake. Force the frame + # beneath to rewrite every cell as the dialog is torn down so nothing of it lingers. + if popped is not None and getattr(popped, "floating", False): + self._invalidate_last_frame() self.invalidate() def reset(self) -> None: diff --git a/meshterm/ui/watchtower_screen.py b/meshterm/ui/watchtower_screen.py index 9323eb7..e9a1a77 100644 --- a/meshterm/ui/watchtower_screen.py +++ b/meshterm/ui/watchtower_screen.py @@ -242,6 +242,7 @@ async def _node_rules(ctx: "AppContext", key: str) -> None: Choice("πŸ“Ά SNR watch " + ("on" if entry.snr_watch else "off"), "snr"), Separator(""), Choice("βœ– Stop watching this node", "unwatch"), + Separator(""), Choice("← Close", None), ] picked = await session.select( diff --git a/tests/test_braillechart.py b/tests/test_braillechart.py index d7bbe00..6520377 100644 --- a/tests/test_braillechart.py +++ b/tests/test_braillechart.py @@ -253,6 +253,17 @@ def test_axis_chart_ticks_notch_the_border_and_centre_labels() -> None: assert out[2].plain == " A D" # labels centred under their ticks +def test_axis_chart_continuous_axis_notches_ticks_under_its_labels() -> None: + """A continuous (label_at) chart now notches ┬ ticks under its ends-and-quarters labels.""" + rows = timeline_rows([9] * 8, rows=1) + out = axis_chart(rows, 9, 20, lambda f: "now" if f >= 1.0 else str(round(f * 100))) + border, caption = out[1].plain, out[2].plain + assert "┬" in border # the continuous axis is ticked, not a plain rule + assert border.startswith(" β””") and border.endswith("β”˜") + assert border[-2] == "┬" # the rightmost tick sits at the 'now' edge + assert "now" in caption and "0" in caption + + def test_axis_chart_ticks_thin_a_label_that_would_collide() -> None: """A tick whose label would overprint the one before it is dropped, tick and all.""" rows = timeline_rows([9] * 16, rows=1) diff --git a/tests/test_packet_viewer.py b/tests/test_packet_viewer.py index 6ce7de3..d72c919 100644 --- a/tests/test_packet_viewer.py +++ b/tests/test_packet_viewer.py @@ -98,6 +98,15 @@ def test_packet_viewer_without_a_source_stays_a_snapshot() -> None: assert viewer.footer_hint == "Esc close" +def test_packet_viewer_holds_a_minimum_height() -> None: + """A short packet's body is padded to a floor, so paging never shrinks the dialog.""" + from meshterm.ui.packet_viewer import _MIN_BODY_ROWS + + tiny = PacketEntry(when=utcnow(), kind="ack", where="01c3") # a two-row packet + viewer = PacketViewer([tiny], 0, resolve=lambda h: "") + assert len(viewer.render_body(80)) >= _MIN_BODY_ROWS + + def test_packet_viewer_raw_dump_skips_fields_folded_into_flavoured_rows() -> None: """Fields already shown as class/route/via/channel rows don't also dump generically.""" entry = _grp_txt_entry({ diff --git a/tests/test_timemachine.py b/tests/test_timemachine.py index 14cd2db..ccefee4 100644 --- a/tests/test_timemachine.py +++ b/tests/test_timemachine.py @@ -170,6 +170,36 @@ def test_day_columns_always_hits_the_exact_width() -> None: assert len(cols) == chars * 2, (n, chars) +def test_fill_days_shows_gap_days_as_zero_bars() -> None: + """A quiet day between busy ones is emitted with zero counts, not skipped.""" + from datetime import datetime, timezone + + from meshterm.ui.timemachine_screen import _fill_days + + active = [("2026-07-02", 50, 5), ("2026-07-05", 80, 8)] + now = datetime(2026, 7, 6, 12, tzinfo=timezone.utc) + filled = _fill_days(active, datetime(2026, 7, 1, tzinfo=timezone.utc), now) + assert [iso for iso, _p, _n in filled] == [ + "2026-07-02", "2026-07-03", "2026-07-04", "2026-07-05", "2026-07-06", + ] + counts = {iso: packets for iso, packets, _n in filled} + assert counts["2026-07-03"] == 0 and counts["2026-07-04"] == 0 # the gap, now visible + assert counts["2026-07-02"] == 50 and counts["2026-07-05"] == 80 # the busy days intact + + +def test_fill_days_never_invents_days_before_recording_began() -> None: + """A window floor earlier than the first recorded day clamps to that day, not the floor.""" + from datetime import datetime, timezone + + from meshterm.ui.timemachine_screen import _fill_days + + active = [("2026-07-10", 10, 1)] + now = datetime(2026, 7, 12, tzinfo=timezone.utc) + filled = _fill_days(active, datetime(2026, 6, 12, tzinfo=timezone.utc), now) # a 30 d floor + assert filled[0][0] == "2026-07-10" # not the 2026-06-12 floor + assert filled[-1][0] == "2026-07-12" # …but still runs through today + + def test_day_centers_land_under_each_bar() -> None: """A day's centre cell sits within its own bar's span (so a tick points at it).""" chars = 60 @@ -339,6 +369,26 @@ def test_mesh_page_day_axis_ticks_sit_under_dated_columns(tmp_path: Path) -> Non repo.close() +def test_mesh_page_rhythm_left_edge_aligns_with_the_day_charts(tmp_path: Path) -> None: + """The rhythm shares the day charts' y-axis gutter, so all three left edges line up. + + The rhythm keeps its own narrower width (only the gutter is shared), so this checks + the border's opening ``β””`` column, not the whole width. + """ + repo = _seeded_repo(tmp_path) + ctx = SimpleNamespace(repo=repo) + lines = _plain(_mesh_sections(ctx, None, 90), width=90).split("\n") + + def border_col(heading: str) -> int: + start = next(i for i, line in enumerate(lines) if heading in line) + border = next(line for line in lines[start:] if "β””" in line) + return border.index("β””") + + assert border_col("Packets per day") == border_col("Rhythm") + assert border_col("Nodes per day") == border_col("Rhythm") + repo.close() + + def test_picker_row_lanes_align_under_the_header() -> None: """Picker rows lane up under the header; unknown nodes read as heat-coloured names.""" from meshterm.core.models import HeardNode