diff --git a/meshterm/core/advert_store.py b/meshterm/core/advert_store.py index cd1f70b..3148036 100644 --- a/meshterm/core/advert_store.py +++ b/meshterm/core/advert_store.py @@ -30,10 +30,7 @@ DIRECT_CADENCE_HOURS = (1, 2, 3, 4) FLOOD_CADENCE_HOURS = (3, 6, 12, 24, 48, 168) #: Defaults applied when a device has no stored policy: announce to neighbours hourly, -#: flood the wider mesh daily. These are the *code's* defaults; the cadence a device -#: without a stored policy actually starts on is the ``advert_direct_hours`` / -#: ``advert_flood_hours`` preference, which defaults to these (see -#: :mod:`meshterm.core.preferences`). +#: flood the wider mesh daily. DEFAULT_DIRECT_HOURS = 1 DEFAULT_FLOOD_HOURS = 24 @@ -133,17 +130,12 @@ class AdvertStore: Returns: The device's :class:`AdvertPolicy`; defaults apply for anything unset. """ - from .preferences import current as current_preferences - - preferences = current_preferences() - direct = preferences.advert_direct_hours - flood = preferences.advert_flood_hours record = self._load_all().get(self._key(public_key)) if not isinstance(record, dict): - return AdvertPolicy(direct_hours=direct, flood_hours=flood) + return AdvertPolicy() return AdvertPolicy( - direct_hours=_as_hours(record.get("direct_hours"), direct), - flood_hours=_as_hours(record.get("flood_hours"), flood), + direct_hours=_as_hours(record.get("direct_hours"), DEFAULT_DIRECT_HOURS), + flood_hours=_as_hours(record.get("flood_hours"), DEFAULT_FLOOD_HOURS), last_direct=_as_time(record.get("last_direct")), last_flood=_as_time(record.get("last_flood")), ) diff --git a/meshterm/core/preferences.py b/meshterm/core/preferences.py index be6e6de..235bbd9 100644 --- a/meshterm/core/preferences.py +++ b/meshterm/core/preferences.py @@ -42,25 +42,16 @@ from dataclasses import dataclass from pathlib import Path from typing import Any, Optional -from .advert_store import ( - DEFAULT_DIRECT_HOURS, - DEFAULT_FLOOD_HOURS, - DIRECT_CADENCE_HOURS, - FLOOD_CADENCE_HOURS, - OFF, - cadence_label, -) -from .watch_store import DEFAULT_SILENCE_HOURS, SILENCE_CHOICES_H +from .watch_store import DEFAULT_SILENCE_HOURS, OFF, SILENCE_CHOICES_H #: Display groups, in the order the page and the file present them. The order is the -#: order a session happens in — what MeshTerm puts on the air, how loud, what it -#: announces, what it watches for, how it draws the world, what it keeps, and how it -#: paints. Nothing sorts alphabetically: a reader looking for "how long before I give up -#: on a message" should not have to know it starts with a D. +#: order a session happens in — what MeshTerm puts on the air, how loud, what it watches +#: for, how it draws the world, what it keeps, and how it paints. Nothing sorts +#: alphabetically: a reader looking for "how long before I give up on a message" should +#: not have to know it starts with a D. GROUPS: tuple[str, ...] = ( "Sending", "Transmit power", - "Background adverts", "Watchtower", "Map", "History kept", @@ -116,11 +107,6 @@ class PrefSpec: return f"{self.help} (next launch)" if self.relaunch else self.help -def _cadence_choices(hours: tuple[int, ...]) -> dict[int, str]: - """Advert-cadence choices as ``hours -> label``, ``off`` last (the editor's own order).""" - return {h: cadence_label(h) for h in (*hours, OFF)} - - #: The silence-rule choices, drawn from the Watchtower's own ring so the two never drift. _SILENCE_CHOICES: dict[int, str] = { **{h: f"{h} h" for h in SILENCE_CHOICES_H}, @@ -128,13 +114,11 @@ _SILENCE_CHOICES: dict[int, str] = { } #: How the terminal-width reclaim can be asked for: follow the platform's own verdict, or -#: overrule it in either direction. See :func:`meshterm.ui.tui.session._reclaim_last_column` -#: for why a terminal may need to disagree with its platform. -_WIDTH_CHOICES: dict[str, str] = { - "auto": "follow the platform", - "on": "reclaim the column", - "off": "never reclaim", -} +#: overrule it in either direction. The row's description asks a yes/no question ("use the +#: column ... ?"), so the values answer it in those words rather than naming the mechanism +#: twice. See :func:`meshterm.ui.tui.session._reclaim_last_column` for why a terminal may +#: need to disagree with its platform. +_WIDTH_CHOICES: dict[str, str] = {"auto": "auto", "yes": "yes", "no": "no"} #: Every preference MeshTerm has, in page order. Adding one here gives it a row on the #: Preferences page, a key in the YAML file, a ``preferences get``/``set`` CLI face, and a @@ -147,7 +131,7 @@ PREFERENCES: tuple[PrefSpec, ...] = ( help="Pause between our own transmissions, for duty-cycle safety", group="Sending", value_type="float", - default=1.0, + default=5.0, minimum=0.0, maximum=60.0, unit="s", @@ -196,25 +180,6 @@ PREFERENCES: tuple[PrefSpec, ...] = ( maximum=10.0, unit="dB", ), - # --- Background adverts ------------------------------------------------------ - PrefSpec( - key="advert_direct_hours", - label="Direct advert", - help="Cadence a newly seen device starts on for zero-hop announces", - group="Background adverts", - value_type="enum", - default=DEFAULT_DIRECT_HOURS, - choices=_cadence_choices(DIRECT_CADENCE_HOURS), - ), - PrefSpec( - key="advert_flood_hours", - label="Flood advert", - help="Cadence a newly seen device starts on for mesh-wide announces", - group="Background adverts", - value_type="enum", - default=DEFAULT_FLOOD_HOURS, - choices=_cadence_choices(FLOOD_CADENCE_HOURS), - ), # --- Watchtower -------------------------------------------------------------- PrefSpec( key="watch_silence_hours", @@ -372,12 +337,20 @@ def parse_value(spec: PrefSpec, raw: Any) -> Any: if spec.value_type == "enum": choices = spec.choices or {} - if raw in choices: + if raw in choices and not isinstance(raw, bool): return raw + if isinstance(raw, bool): + # YAML 1.1 reads a bare ``yes``/``no`` (and ``on``/``off``) as a *boolean*, so a + # hand-edited file hands us ``True`` where the choice is spelled "yes". We quote + # ours on the way out, but someone typing the obvious thing should still be + # understood: map the boolean back to whichever spelling this spec offers. + for choice in choices: + if str(choice).lower() in (_TRUE if raw else _FALSE): + return choice # Text arriving from the CLI or a hand-edited file: match a choice by its own - # spelling, so `preferences set advert_flood_hours 24` and a YAML `24` land alike. + # spelling, so `preferences set watch_silence_hours 6` and a YAML `6` land alike. for choice in choices: - if text == str(choice): + if text.lower() == str(choice).lower(): return choice allowed = ", ".join(str(c) for c in choices) raise PreferenceError(f"{spec.key}: must be one of {allowed}, got {raw!r}") diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index 468e4a1..5705c9c 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -232,8 +232,8 @@ def _reclaim_last_column() -> bool: Three sources, in confidence order, because the person at the keyboard can see the column and the platform can only guess at it: ``MESHTERM_FULL_WIDTH=0``/``=1`` for a - one-off, then the ``full_width`` preference (``auto`` — the default — steps aside), - then the platform's own verdict. + one-off, then the ``full_width`` preference (``yes``/``no``; ``auto`` — the default — + steps aside), then the platform's own verdict. Read fresh on every call (never cached at import time) so it reflects whichever platform :func:`~meshterm.platforms.set_platform` installed for this process — see that module's @@ -246,7 +246,7 @@ def _reclaim_last_column() -> bool: return override != "0" preferred = current_preferences().full_width if preferred != "auto": - return preferred == "on" + return preferred == "yes" return get_platform().width_reclaim #: How many stacked dialog layers the layout can float over the background at once. A fixed diff --git a/tests/test_preferences.py b/tests/test_preferences.py index 73cb4b9..484e171 100644 --- a/tests/test_preferences.py +++ b/tests/test_preferences.py @@ -18,7 +18,6 @@ from rich.console import Console from meshterm.context import AppContext from meshterm.core.admin_store import AdminStore -from meshterm.core.advert_store import AdvertStore from meshterm.core.config import Settings from meshterm.core.device_store import DeviceStore from meshterm.core.preferences import ( @@ -85,8 +84,8 @@ def test_an_unknown_key_fails_where_it_is_written() -> None: ("fast_render", "yes", True), ("trace_cooldown_s", "2.5", 2.5), ("history_days", "0", 0), - ("advert_flood_hours", "24", 24), # an enum named as text lands on its own value - ("full_width", "on", "on"), + ("watch_silence_hours", "6", 6), # an enum named as text lands on its own value + ("full_width", "yes", "yes"), ], ) def test_values_parse_from_text(key: str, raw: str, expected: Any) -> None: @@ -100,7 +99,7 @@ def test_values_parse_from_text(key: str, raw: str, expected: Any) -> None: ("direct_message_soft_retries", "9"), # over the maximum ("map_view_fraction", "0"), # under the minimum ("trace_cooldown_s", "soon"), # not a number at all - ("advert_flood_hours", "7"), # not one of the cadences + ("watch_silence_hours", "7"), # not one of the silence choices ("fast_render", "maybe"), ], ) @@ -115,8 +114,8 @@ def test_values_format_for_the_lane_they_are_drawn_in() -> None: """Booleans read as words, enums as their labels, numbers carry their unit.""" assert format_value(get_spec("fast_render"), True) == "on" assert format_value(get_spec("fast_render"), False) == "off" - assert format_value(get_spec("advert_flood_hours"), 24) == "daily" - assert format_value(get_spec("advert_flood_hours"), 0) == "off" + assert format_value(get_spec("watch_silence_hours"), 6) == "6 h" + assert format_value(get_spec("watch_silence_hours"), 0) == "off" assert format_value(get_spec("trace_cooldown_s"), 2.5) == "2.5 s" assert format_value(get_spec("history_days"), 365) == "365 days" @@ -175,6 +174,23 @@ def test_an_untouched_file_says_so(tmp_path: Path) -> None: ) +def test_a_yaml_boolean_still_reaches_a_yes_no_choice(tmp_path: Path) -> None: + """YAML reads a bare ``yes`` as ``True``; the obvious hand edit is understood anyway.""" + path = tmp_path / "preferences.yaml" + path.write_text("full_width: yes\n", encoding="utf-8") + assert Preferences.load(path).full_width == "yes" + + path.write_text("full_width: no\n", encoding="utf-8") + assert Preferences.load(path).full_width == "no" + + # And what we write ourselves is quoted, so it round-trips as the string it is. + prefs = Preferences(path) + prefs.set("full_width", "yes") + prefs.save() + assert "full_width: 'yes'" in path.read_text(encoding="utf-8") + assert Preferences.load(path).full_width == "yes" + + @pytest.mark.parametrize( "text", [ @@ -487,7 +503,7 @@ async def test_reset_stages_the_defaults_rather_than_writing_them(ctx: AppContex ("dialog", True), ("select", "__apply__"), ]) - assert await edit_preferences(ctx) == {"history_days": 365, "trace_cooldown_s": 1.0} + assert await edit_preferences(ctx) == {"history_days": 365, "trace_cooldown_s": 5.0} # Still only staged — the values in force are untouched until the tool applies them. assert ctx.preferences.history_days == 30 @@ -512,7 +528,7 @@ async def test_the_tool_writes_the_staged_values_once(ctx: AppContext) -> None: _install(ctx, []) tool = get_tool("preferences") - ops = [("set", "history_days", 30), ("set", "full_width", "on")] + ops = [("set", "history_days", 30), ("set", "full_width", "yes")] result = await tool.run(ctx, {"ops": ops}) assert result.summary == {"changes": 2} @@ -551,18 +567,6 @@ def test_a_newly_watched_node_takes_the_preferred_silence_rule(tmp_path: Path) - install(Preferences()) -def test_a_device_with_no_policy_starts_on_the_preferred_cadence(tmp_path: Path) -> None: - """The advert preferences are the cadence an unseen device is scheduled at.""" - prefs = Preferences() - prefs.set("advert_flood_hours", 168) - install(prefs) - try: - policy = AdvertStore(tmp_path / "adverts.json").load("ab" * 32) - assert policy.flood_hours == 168 - finally: - install(Preferences()) - - def test_the_last_column_preference_overrules_the_platform() -> None: """``full_width`` steps aside on ``auto`` and decides otherwise (env still wins over both).""" from meshterm.platforms import PICOCALC, set_platform @@ -573,9 +577,9 @@ def test_the_last_column_preference_overrules_the_platform() -> None: install(prefs) try: assert _reclaim_last_column() is False # auto: the platform's verdict stands - prefs.set("full_width", "on") + prefs.set("full_width", "yes") assert _reclaim_last_column() is True - prefs.set("full_width", "off") + prefs.set("full_width", "no") assert _reclaim_last_column() is False finally: install(Preferences())