The weekly advert says where its week stands

A muted line under the Weekly advert row on the Preferences page, set in
the value lane: "next advert in 4d" while the week runs, "due — waiting
for a packet" and then "due — after 30 s of quiet" once it is due, "no
device connected", and "the week starts on Apply" while it is only staged
on. The line is a width-aware separator that reads the scheduler's new
status() on every paint, from state the loop already keeps, so it follows
the wait live without touching the file. It is drawn, even blank, for as
long as the preference is on, so the rows below never shift; every message
fits the PicoCalc's 53 columns, and a gallery specimen holds it there.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5.5 committed 2026-09-23 22:29:20 -04:00
1 parent 6b13755c2b
commit 5021ab8de5
5 files changed
+250 -3

No files matched your search

+60
View File
@@ -45,6 +45,8 @@ import asyncio
import random
import time
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from typing import TYPE_CHECKING
from ..core import transmit_gate
@@ -67,6 +69,32 @@ JITTER_S = 5.0
DUE_CHECK_S = 30.0
#: :attr:`AdvertStatus.state` while no device is connected: no week to count, nothing to send.
OFFLINE = "offline"
#: :attr:`AdvertStatus.state` while the connected device's week is still running.
COUNTING = "counting"
#: :attr:`AdvertStatus.state` once due, while this connection has yet to hear a packet.
LISTENING = "listening"
#: :attr:`AdvertStatus.state` once due and heard, while the air has yet to go quiet.
QUIET = "quiet"
@dataclass(frozen=True, slots=True)
class AdvertStatus:
"""Where the weekly advert stands, for a screen to say so.
Attributes:
state: :data:`OFFLINE`, :data:`COUNTING`, :data:`LISTENING`, or :data:`QUIET`.
due_at: When the connected device's advert falls due, while :data:`COUNTING`.
"""
state: str
due_at: datetime | None = None
class AdvertScheduler:
"""Owns the weekly-advert loop for an interactive session.
@@ -102,6 +130,7 @@ class AdvertScheduler:
self._device: Device | None = None
self._key = ""
self._due = False
self._due_at: datetime | None = None
self._checked_at: float | None = None
# Which connection last heard a packet, and when anything was last heard.
self._heard_on: Device | None = None
@@ -141,6 +170,34 @@ class AdvertScheduler:
"""Stop the loop at session end (an alias for :meth:`stop`)."""
await self.stop()
def status(self) -> AdvertStatus | None:
"""Where the weekly advert stands right now, or ``None`` when there is nothing to say.
``None`` while the scheduler is not running, while the preference is off, and in
the second between a connection and the first look at it. Read from what the loop
already keeps, so a screen can ask on every paint without touching the file; a
:meth:`recheck` pending leaves the last reading standing until the tick replaces it.
"""
ctx = self._ctx
if not self.active or not ctx.preferences.weekly_flood_advert:
return None
device = ctx._device
if device is None:
return AdvertStatus(OFFLINE)
if device is not self._device:
return None
if not self._due:
return AdvertStatus(COUNTING, self._due_at) if self._due_at is not None else None
return AdvertStatus(LISTENING if self._heard_on is not device else QUIET)
def recheck(self) -> None:
"""Re-read the preference and the store on the next tick, not the next due check.
For a screen about to report :meth:`status`, which would otherwise show what the
loop last read up to :data:`DUE_CHECK_S` ago — before a switch just applied.
"""
self._checked_at = None
def _on_event(self, _event: MeshEvent) -> None:
"""Note a packet heard: it breaks the silence, and proves this connection is live."""
self._last_heard = self._clock()
@@ -166,6 +223,7 @@ class AdvertScheduler:
return
if device is not self._device:
self._device, self._key, self._due, self._checked_at = device, "", False, None
self._due_at = None
if not self._key:
self._key = await self._public_key()
if not self._key:
@@ -192,6 +250,7 @@ class AdvertScheduler:
raise
ctx.advert_store.mark_flood(self._key)
self._due = False
self._checked_at = None # the next tick reads the new week in
ctx.log.info("advert scheduler: sent the weekly flood advert")
def _check_due(self) -> None:
@@ -199,6 +258,7 @@ class AdvertScheduler:
ctx = self._ctx
on = bool(ctx.preferences.weekly_flood_advert)
ctx.advert_store.sync_enabled(on)
self._due_at = ctx.advert_store.due_at(self._key) if on else None
due = on and ctx.advert_store.due(self._key)
if due and not self._due:
ctx.log.info(
+77 -3
View File
@@ -26,6 +26,7 @@ ever written by the one action at the bottom.
from __future__ import annotations
from collections.abc import Callable
from typing import TYPE_CHECKING, Any
from rich import box
@@ -33,6 +34,7 @@ from rich.cells import cell_len
from rich.table import Table
from rich.text import Text
from ..core.models import utcnow
from ..core.preferences import (
PREFERENCES,
PreferenceError,
@@ -57,6 +59,10 @@ from .tui import Choice, Separator
if TYPE_CHECKING:
from ..context import AppContext
from ..services.advert_scheduler import AdvertStatus
#: The preference whose row carries a live status line under it (see :func:`_advert_line`).
_WEEKLY_ADVERT = "weekly_flood_advert"
#: Menu action sentinels, distinct from the plain-string preference keys the rows carry.
_RESET = "__reset__"
@@ -102,11 +108,16 @@ async def edit_preferences(ctx: AppContext) -> dict[str, Any] | None:
if want != shown and consolefont.apply(want):
shown = want
# The weekly advert's status line reads the scheduler on every paint; ask it to re-read
# the store now, so the first paint does not report a week from before the last Apply.
ctx.adverts.recheck()
advert_status = ctx.adverts.status
# The rows *are* the data — each carries its own staged ``current → new`` value and
# the title counts what is staged — so they refresh in place after every round
# (``replace_items``) rather than being rebuilt as a new screen. One screen for the
# whole visit means the typed filter survives editing a preference, not just the cursor.
title, items = _menu_items(prefs, pending)
title, items = _menu_items(prefs, pending, advert_status)
menu = SelectScreen(
title,
items,
@@ -131,7 +142,7 @@ async def edit_preferences(ctx: AppContext) -> dict[str, Any] | None:
else: # a preference key
await _stage_preference(ctx, prefs, choice, pending)
preview()
title, items = _menu_items(prefs, pending)
title, items = _menu_items(prefs, pending, advert_status)
menu.replace_items(items, title=title)
@@ -200,11 +211,19 @@ def _preference_value(prefs: Preferences, spec: PrefSpec, pending: dict[str, Any
return value
def _menu_items(prefs: Preferences, pending: dict[str, Any]) -> tuple[str, list]:
def _menu_items(
prefs: Preferences,
pending: dict[str, Any],
advert_status: Callable[[], AdvertStatus | None] | None = None,
) -> tuple[str, list]:
"""Build the page's title and rows for the current values plus whatever is staged.
The rows sit in three aligned lanes — preference, current value (and any staged new
value), description — under one pinned header, so the page reads as the editor it is.
``advert_status`` is the scheduler's :meth:`~meshterm.services.advert_scheduler.
AdvertScheduler.status`; while the weekly advert is on (or staged on) its row gets a
muted line under it saying where the week stands (see :func:`_advert_line`).
"""
sections: list[tuple[str, list[tuple[str, Text, str, Any]]]] = []
for group, specs in _page_groups():
@@ -268,6 +287,21 @@ def _menu_items(prefs: Preferences, pending: dict[str, Any]) -> tuple[str, list]
hscroll_from=description_at,
)
)
if key == _WEEKLY_ADVERT and _effective(prefs, key, pending):
# A timer you cannot see is one you cannot trust: say where the week is. A
# callable, so every paint reads the scheduler afresh and the line counts
# down (and flips to "due") while the page is open. Set in the value lane,
# under the "on" it explains; drawn — even blank — for as long as the
# preference is on, so the rows below never move when the reading arrives.
# A separator has no "❯ " pointer column, so it pays those two cells itself.
indent = 2 + label_w + 2
items.append(
Separator(
lambda width, indent=indent: _advert_line(
prefs, pending, advert_status, indent, width
)
)
)
# Nothing at all while the page is clean — Esc leaves. With changes staged the pair
# appears below one blank line: Apply is the save action, and Back spells out what
@@ -278,6 +312,46 @@ def _menu_items(prefs: Preferences, pending: dict[str, Any]) -> tuple[str, list]
return title, items
def _advert_line(
prefs: Preferences,
pending: dict[str, Any],
advert_status: Callable[[], AdvertStatus | None] | None,
indent: int,
width: int,
) -> Text:
"""The weekly advert's status, muted and set in the value lane, fitted to ``width``.
Staged on but not yet saved, the week has not started, and the line says when it will.
Otherwise it reads the scheduler: how long until the connected device's advert is due,
and once it is, what the advert is waiting for. Blank when there is nothing to report.
"""
from ..services.advert_scheduler import COUNTING, LISTENING, OFFLINE, QUIET
from .widgets import format_age
if not prefs.weekly_flood_advert:
words = "the week starts on Apply"
else:
status = advert_status() if advert_status is not None else None
if status is None:
words = ""
elif status.state == OFFLINE:
words = "no device connected"
elif status.state == COUNTING and status.due_at is not None:
left = (status.due_at - utcnow()).total_seconds()
words = "next advert in " + (
"under a minute" if left < 60 else format_age(max(0.0, left))
)
elif status.state == LISTENING:
words = "due — waiting for a packet"
elif status.state == QUIET:
words = f"due — after {prefs.advert_quiet_s} s of quiet"
else:
words = ""
line = Text(" " * indent + words, style="muted")
line.truncate(max(0, width), overflow="ellipsis")
return line
#: Widest terminal that still can't hold the DESCRIPTION lane. The three lanes the table
#: can't do without — the key you would type into ``preferences set``, what it is set to,
#: and what it would be if you hadn't — take about eighty cells between them, and the
+39
View File
@@ -8,6 +8,7 @@ week: a flood advert sent by hand, and the preference being switched on.
from __future__ import annotations
import asyncio
import io
import json
import random
@@ -394,3 +395,41 @@ async def test_switching_the_preference_records_the_switch(ctx: AppContext) -> N
async def _record(sent: list[bool], flood: bool) -> None:
"""Stand-in ``send_advert`` recording each transmission's type."""
sent.append(flood)
# -- the status a screen reads -------------------------------------------------------
async def test_status_follows_the_wait(ctx: AppContext) -> None:
"""Counting, then due and listening, then due and waiting for quiet."""
from meshterm.services.advert_scheduler import COUNTING, LISTENING, QUIET
scheduler, clock, _sent = await _due_scheduler(ctx, 0.0)
scheduler._task = asyncio.get_running_loop().create_future() # reads as running
try:
await scheduler._pass()
assert scheduler.status().state == LISTENING # type: ignore[union-attr]
scheduler._on_event(None) # type: ignore[arg-type]
await scheduler._pass()
assert scheduler.status().state == QUIET # type: ignore[union-attr]
clock.t = 40.0
await scheduler._pass() # sent: a new week begins
clock.t = 80.0
await scheduler._pass()
status = scheduler.status()
assert status is not None and status.state == COUNTING
assert status.due_at is not None and status.due_at > utcnow() + WEEK - timedelta(minutes=1)
finally:
scheduler._task.cancel()
async def test_status_is_silent_while_off_or_stopped(ctx: AppContext) -> None:
"""Nothing to report while the preference is off, or before the loop runs."""
scheduler, _clock, _sent = await _due_scheduler(ctx, 0.0)
assert scheduler.status() is None # not running
scheduler._task = asyncio.get_running_loop().create_future()
try:
ctx.preferences.set("weekly_flood_advert", False)
assert scheduler.status() is None
finally:
scheduler._task.cancel()
+16
View File
@@ -957,6 +957,21 @@ def _preferences(cols: int, rows: int) -> Screen:
)
def _preferences_weekly_advert(cols: int, rows: int) -> Screen:
"""The Preferences page with the weekly advert on and its longest status line drawn."""
from meshterm.services.advert_scheduler import QUIET, AdvertStatus
prefs = Preferences()
prefs.set("weekly_flood_advert", True)
prefs.set("advert_quiet_s", 60)
title, items = _preference_items(prefs, {}, lambda: AdvertStatus(QUIET))
return SelectScreen(
title,
items,
footer_hint="↑↓ move · type to filter · Enter select · Esc back",
)
def _cooldown_countdown(cols: int, rows: int) -> Screen:
"""The transmit-cooldown countdown at its widest: a flood advert's wait and its reason.
@@ -1106,6 +1121,7 @@ _ENTRIES: list[_Entry] = [
_Entry("config_editor_revealed", _config_editor_revealed),
_Entry("repeater_admin", _repeater_admin),
_Entry("preferences", _preferences),
_Entry("preferences-weekly-advert", _preferences_weekly_advert),
_Entry("cooldown_countdown", _cooldown_countdown),
_Entry("about_meshterm", _about_meshterm),
_Entry("about_author", _about_author),
+58
View File
@@ -695,3 +695,61 @@ def test_the_last_column_preference_overrules_the_platform() -> None:
assert _reclaim_last_column() is False
finally:
install(Preferences())
# -- the weekly advert's status line ---------------------------------------------------
def _advert_rows(prefs: Preferences, pending: dict, status) -> list[str]:
"""The page's lines with a stub scheduler status."""
from meshterm.ui.tui import SelectScreen
title, items = _menu_items(prefs, pending, lambda: status)
screen = SelectScreen(title, items)
screen.note_viewport(len(items) + 4)
return [line.strip() for line in _plain(screen.render_body(_WIDE)).splitlines()]
def test_no_status_line_while_the_weekly_advert_is_off() -> None:
"""Off by default, the row stands alone."""
rows = _advert_rows(Preferences(), {}, None)
assert not any("advert in" in row or "due —" in row for row in rows)
def test_staged_on_says_the_week_starts_on_apply() -> None:
"""Before it is saved, no week is running yet."""
rows = _advert_rows(Preferences(), {"weekly_flood_advert": True}, None)
assert "the week starts on Apply" in rows
def test_the_status_line_reads_the_scheduler() -> None:
"""Counting shows the time left; due says what the advert is waiting for."""
from datetime import timedelta
from meshterm.core.models import utcnow
from meshterm.services.advert_scheduler import (
COUNTING,
LISTENING,
OFFLINE,
QUIET,
AdvertStatus,
)
prefs = Preferences()
prefs.set("weekly_flood_advert", True)
soon = AdvertStatus(COUNTING, utcnow() + timedelta(days=4, hours=2))
assert "next advert in 4d" in _advert_rows(prefs, {}, soon)
assert "no device connected" in _advert_rows(prefs, {}, AdvertStatus(OFFLINE))
assert "due — waiting for a packet" in _advert_rows(prefs, {}, AdvertStatus(LISTENING))
assert "due — after 30 s of quiet" in _advert_rows(prefs, {}, AdvertStatus(QUIET))
def test_the_status_line_sits_under_its_row() -> None:
"""The line follows the Weekly advert row directly, so it reads as that row's."""
from meshterm.services.advert_scheduler import QUIET, AdvertStatus
prefs = Preferences()
prefs.set("weekly_flood_advert", True)
rows = _advert_rows(prefs, {}, AdvertStatus(QUIET))
at = next(i for i, row in enumerate(rows) if row.startswith("Weekly advert"))
assert rows[at + 1].startswith("due —")