From 291a5ed26f70c5f0181e0528234ecc71e1407098 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Wed, 11 Nov 2026 11:54:20 +0100 Subject: [PATCH] Desktop toasts paint glyphs and numbers only Guard test walks every toast call for literal words. Co-Authored-By: Claude Opus 5.5 --- steam_backlog_enforcer/_bonus_incident.py | 6 +- steam_backlog_enforcer/_cmd_done_finalize.py | 5 +- steam_backlog_enforcer/_enforce_guards.py | 6 +- steam_backlog_enforcer/_enforce_loop.py | 6 +- steam_backlog_enforcer/_enforce_steps.py | 2 +- steam_backlog_enforcer/_playtime_cutoff.py | 23 ++-- steam_backlog_enforcer/_playtime_notify.py | 17 +++ steam_backlog_enforcer/_scanning_tampering.py | 5 +- steam_backlog_enforcer/scanning.py | 5 +- .../tests/test_bonus_incident.py | 2 +- .../tests/test_leisure_tick.py | 27 ++--- .../tests/test_playtime_cutoff.py | 2 +- .../tests/test_playtime_notify.py | 13 +- .../tests/test_textgate_toasts.py | 111 ++++++++++++++++++ 14 files changed, 176 insertions(+), 54 deletions(-) create mode 100644 steam_backlog_enforcer/tests/test_textgate_toasts.py diff --git a/steam_backlog_enforcer/_bonus_incident.py b/steam_backlog_enforcer/_bonus_incident.py index 8ceed11..1c9541b 100644 --- a/steam_backlog_enforcer/_bonus_incident.py +++ b/steam_backlog_enforcer/_bonus_incident.py @@ -41,7 +41,7 @@ INCIDENT_LOG: Final = ( Path(__file__).resolve().parents[1] / "leetcode_bonus_incidents.log" ) -_TITLE: Final = "Gaming budget: LeetCode bonus not applied" +_TITLE: Final = "๐ŸงฉโŒ๐ŸŽฎ" # reason -> the local day it was last reported on. _reported: dict[str, str] = {} @@ -69,7 +69,9 @@ def report_leetcode_incident(reason: str, *, fix: str) -> None: body = f"{reason}. Budget is 1h lower until this is fixed. Try: {fix}" logger.warning("LeetCode bonus not applied - %s. Try: %s", reason, fix) - notify_desktop_user(_TITLE, body) + # Textgate: the toast paints the bonus glyph, the lost hour and the fix + # command (content kuhy runs); the sentence stays in the log and journal. + notify_desktop_user(_TITLE, f"-1h {fix}") _append_incident(f"{datetime.now().astimezone().isoformat()} {body}") diff --git a/steam_backlog_enforcer/_cmd_done_finalize.py b/steam_backlog_enforcer/_cmd_done_finalize.py index 697a568..cee1499 100644 --- a/steam_backlog_enforcer/_cmd_done_finalize.py +++ b/steam_backlog_enforcer/_cmd_done_finalize.py @@ -102,10 +102,7 @@ def _finalize_completion( use_steam_protocol=True, ) - send_notification( - "Moving on!", - f"New achievement in {game_name}! Now playing: {state.current_game_name}", - ) + send_notification("๐Ÿ†", f"{game_name} โ†’ {state.current_game_name}") _echo(f"\nAll done! Go play {state.current_game_name}!") diff --git a/steam_backlog_enforcer/_enforce_guards.py b/steam_backlog_enforcer/_enforce_guards.py index 8928442..802b884 100644 --- a/steam_backlog_enforcer/_enforce_guards.py +++ b/steam_backlog_enforcer/_enforce_guards.py @@ -60,9 +60,5 @@ def guard_installed_games(allowed: set[int]) -> int: ) if uninstall_game(app_id, name): count += 1 - send_notification( - "Game Removed!", - f"Uninstalled {name} (AppID={app_id}). " - f"Only your assigned game(s) are allowed.", - ) + send_notification("๐Ÿ—‘๏ธ", f"{name} ยท {app_id}") return count diff --git a/steam_backlog_enforcer/_enforce_loop.py b/steam_backlog_enforcer/_enforce_loop.py index 62223e5..c93de3d 100644 --- a/steam_backlog_enforcer/_enforce_loop.py +++ b/steam_backlog_enforcer/_enforce_loop.py @@ -142,11 +142,7 @@ def _enforce_loop_iteration( violations = enforce_allowed_game(allowed, kill_unauthorized=True) for pid, app_id in violations: _echo(f" Killed unauthorized game: AppID={app_id} (PID={pid})") - send_notification( - "Game Blocked!", - f"Killed unauthorized game (AppID={app_id}). " - f"Focus on {allowed_names(state)}!", - ) + send_notification("โ›”๐ŸŽฎ", f"{app_id} โ†’ ๐ŸŽฏ {allowed_names(state)}") # B) Remove any newly-installed unauthorized games. if config.uninstall_other_games: diff --git a/steam_backlog_enforcer/_enforce_steps.py b/steam_backlog_enforcer/_enforce_steps.py index 688f61a..5028d1e 100644 --- a/steam_backlog_enforcer/_enforce_steps.py +++ b/steam_backlog_enforcer/_enforce_steps.py @@ -100,7 +100,7 @@ def _enforce_auto_install(config: Config, state: State) -> None: config.steam_id, use_steam_protocol=True, ): - send_notification("Game Installing", f"{name} is being downloaded.") + send_notification("โฌ‡๏ธ", name) else: _echo(" Could not auto-install. Install manually from Steam.") diff --git a/steam_backlog_enforcer/_playtime_cutoff.py b/steam_backlog_enforcer/_playtime_cutoff.py index d541955..326bcab 100644 --- a/steam_backlog_enforcer/_playtime_cutoff.py +++ b/steam_backlog_enforcer/_playtime_cutoff.py @@ -24,7 +24,11 @@ from steam_backlog_enforcer._playtime_kill import ( request_steam_shutdown, steam_and_launcher_pids, ) -from steam_backlog_enforcer._playtime_notify import _humanise, notify_desktop_user +from steam_backlog_enforcer._playtime_notify import ( + _humanise, + notify_desktop_user, + short_duration, +) from steam_backlog_enforcer._playtime_state import ( _SHUTDOWN_GRACE_SECONDS, PlaytimeRules, @@ -53,12 +57,8 @@ def reconcile_for(rules: PlaytimeRules, *, should_block: bool) -> None: reconcile(should_block=should_block) -_CUTOFF_BODY = { - False: "Daily budget used up. Steam and games are shutting down. " - "Unblocks at 06:00.", - True: "Daily leisure budget used up. Steam, games and leisure apps are " - "shutting down. Unblocks at 06:00.", -} +# Toasts are textgated: a glyph per budget and the unblock time, no sentence. +_UNBLOCK_AT = "06:00" def _noun(rules: PlaytimeRules) -> str: @@ -66,6 +66,11 @@ def _noun(rules: PlaytimeRules) -> str: return "Leisure" if rules.leisure else "Gaming" +def _glyph(rules: PlaytimeRules) -> str: + """The toast glyph for the budget: ๐Ÿ›‹๏ธ leisure (Phase 2), ๐ŸŽฎ gaming.""" + return "๐Ÿ›‹๏ธ" if rules.leisure else "๐ŸŽฎ" + + def _warn(state: PlaytimeState, rules: PlaytimeRules) -> PlaytimeState: """Fire the due warning, if any, and record that it fired. @@ -89,7 +94,7 @@ def _warn(state: PlaytimeState, rules: PlaytimeRules) -> PlaytimeState: state.seconds, rules.budget_seconds, ) - notify_desktop_user(f"{noun} time running out", left) + notify_desktop_user(f"โณ{_glyph(rules)}", short_duration(threshold)) return replace(state, warned_seconds=[*state.warned_seconds, threshold]) @@ -116,7 +121,7 @@ def _begin_cutoff( logger.warning( "Daily %s budget exhausted; shutting Steam down.", _noun(rules).lower() ) - notify_desktop_user(f"{_noun(rules)} time is up", _CUTOFF_BODY[rules.leisure]) + notify_desktop_user(f"โ›”{_glyph(rules)}", f"๐Ÿ”“ {_UNBLOCK_AT}") request_steam_shutdown() kill_gaming_processes(_kill_set(rules), force=False) if rules.demo: diff --git a/steam_backlog_enforcer/_playtime_notify.py b/steam_backlog_enforcer/_playtime_notify.py index 0bfdeb5..7d3b929 100644 --- a/steam_backlog_enforcer/_playtime_notify.py +++ b/steam_backlog_enforcer/_playtime_notify.py @@ -18,6 +18,23 @@ _SECONDS_PER_MINUTE = 60 _MINUTES_PER_HOUR = 60 +def short_duration(seconds: int) -> str: + """Render a threshold as a toast-sized number + unit (textgate: no words). + + Args: + seconds: Seconds remaining. + + Returns: + ``"30s"``, ``"5m"``, ``"1h"`` or ``"1h 30m"``. + """ + if seconds < _SECONDS_PER_MINUTE: + return f"{seconds}s" + hours, minutes = divmod(seconds // _SECONDS_PER_MINUTE, _MINUTES_PER_HOUR) + if not hours: + return f"{minutes}m" + return f"{hours}h {minutes}m" if minutes else f"{hours}h" + + def notify_desktop_user(title: str, body: str) -> None: """Send a desktop notification into the real user's session. diff --git a/steam_backlog_enforcer/_scanning_tampering.py b/steam_backlog_enforcer/_scanning_tampering.py index 8e8e827..30b660b 100644 --- a/steam_backlog_enforcer/_scanning_tampering.py +++ b/steam_backlog_enforcer/_scanning_tampering.py @@ -187,7 +187,4 @@ def detect_tampering(config: Config, state: State) -> None: _echo("\n TAMPERING DETECTED:") for name, app_id, diff in suspicious: _echo(f" {name} (AppID={app_id}): +{diff} new achievements!") - send_notification( - "Tampering Detected!", - f"Achievements unlocked on {len(suspicious)} non-assigned games!", - ) + send_notification("๐Ÿ•ต๏ธ๐Ÿ†", f"๐ŸŽฎ {len(suspicious)}") diff --git a/steam_backlog_enforcer/scanning.py b/steam_backlog_enforcer/scanning.py index 8ee8bae..87dce2e 100644 --- a/steam_backlog_enforcer/scanning.py +++ b/steam_backlog_enforcer/scanning.py @@ -225,10 +225,7 @@ def do_check(config: Config, state: State) -> None: _echo(f"\n {verdict}") if released: release_game(state, game) - send_notification( - "Moving on!", - f"New achievement in {state.current_game_name}! Picking next game...", - ) + send_notification("๐Ÿ†", f"{state.current_game_name} โ†’ ๐ŸŽฒ") # Load snapshot and pick next. snapshot_data = load_snapshot() diff --git a/steam_backlog_enforcer/tests/test_bonus_incident.py b/steam_backlog_enforcer/tests/test_bonus_incident.py index 7feedab..f80eea3 100644 --- a/steam_backlog_enforcer/tests/test_bonus_incident.py +++ b/steam_backlog_enforcer/tests/test_bonus_incident.py @@ -57,7 +57,7 @@ class TestReporting: patch(f"{_PKG}.notify_desktop_user") as notify, ): report_leetcode_incident("ledger unreadable", fix="systemctl status x") - assert notify.call_count == 1 + notify.assert_called_once_with("๐ŸงฉโŒ๐ŸŽฎ", "-1h systemctl status x") assert "ledger unreadable" in caplog.text assert "systemctl status x" in log.read_text(encoding="utf-8") diff --git a/steam_backlog_enforcer/tests/test_leisure_tick.py b/steam_backlog_enforcer/tests/test_leisure_tick.py index 04ef582..06cac43 100644 --- a/steam_backlog_enforcer/tests/test_leisure_tick.py +++ b/steam_backlog_enforcer/tests/test_leisure_tick.py @@ -134,8 +134,7 @@ class TestLive: _go_live(tmp_path) state, spy = _tick({}, budget=3.0) assert state.is_blocked() - assert notify.call_args.args[0] == "Leisure time is up" - assert "leisure" in notify.call_args.args[1] + assert notify.call_args.args == ("โ›”๐Ÿ›‹๏ธ", "๐Ÿ”“ 06:00") assert spy.calls[0][0].seconds >= spy.calls[0][1].budget_seconds @@ -149,32 +148,26 @@ _RULES = PlaytimeRules( ) -class TestWording: - def test_warnings_say_gaming_while_dormant(self) -> None: +class TestToastGlyphs: + """Textgate: toasts paint glyphs and numbers, no words.""" + + def test_warnings_show_gaming_glyph_while_dormant(self) -> None: with patch(f"{_CUTOFF}.notify_desktop_user") as notify: _warn(PlaytimeState(day_key=_TODAY, seconds=10.0), _RULES) - notify.assert_called_once_with( - "Gaming time running out", "1 hour of today's gaming budget left." - ) + notify.assert_called_once_with("โณ๐ŸŽฎ", "1h") - def test_warnings_say_leisure_when_live(self) -> None: + def test_warnings_show_leisure_glyph_when_live(self) -> None: with patch(f"{_CUTOFF}.notify_desktop_user") as notify: _warn( PlaytimeState(day_key=_TODAY, seconds=10.0), replace(_RULES, leisure=True), ) - notify.assert_called_once_with( - "Leisure time running out", "1 hour of today's leisure budget left." - ) + notify.assert_called_once_with("โณ๐Ÿ›‹๏ธ", "1h") @pytest.mark.usefixtures("notify") - def test_the_dormant_cutoff_text_is_unchanged(self, notify: MagicMock) -> None: + def test_the_dormant_cutoff_shows_unblock_time(self, notify: MagicMock) -> None: _begin_cutoff(PlaytimeState(day_key=_TODAY), _RULES, now=_NOW) - notify.assert_called_once_with( - "Gaming time is up", - "Daily budget used up. Steam and games are shutting down. " - "Unblocks at 06:00.", - ) + notify.assert_called_once_with("โ›”๐ŸŽฎ", "๐Ÿ”“ 06:00") def test_new_session_kills_through_the_budget_log() -> None: diff --git a/steam_backlog_enforcer/tests/test_playtime_cutoff.py b/steam_backlog_enforcer/tests/test_playtime_cutoff.py index 34e7bd6..cac10bc 100644 --- a/steam_backlog_enforcer/tests/test_playtime_cutoff.py +++ b/steam_backlog_enforcer/tests/test_playtime_cutoff.py @@ -195,7 +195,7 @@ class TestWarn: ) as mock_notify: out = _warn(state, _rules()) assert out.warned_seconds == [3600, 1800, 600, 300] - assert "5 minutes" in mock_notify.call_args.args[1] + assert mock_notify.call_args.args == ("โณ๐ŸŽฎ", "5m") def test_a_fired_warning_is_logged(self, caplog: pytest.LogCaptureFixture) -> None: state = PlaytimeState(seconds=8 * 3600 - 300, warned_seconds=[3600, 1800, 600]) diff --git a/steam_backlog_enforcer/tests/test_playtime_notify.py b/steam_backlog_enforcer/tests/test_playtime_notify.py index 5b2efd0..62a84a8 100644 --- a/steam_backlog_enforcer/tests/test_playtime_notify.py +++ b/steam_backlog_enforcer/tests/test_playtime_notify.py @@ -2,7 +2,18 @@ from __future__ import annotations -from steam_backlog_enforcer._playtime_notify import _humanise +import pytest + +from steam_backlog_enforcer._playtime_notify import _humanise, short_duration + + +@pytest.mark.parametrize( + ("seconds", "shown"), + [(30, "30s"), (60, "1m"), (300, "5m"), (3600, "1h"), (5400, "1h 30m")], +) +def test_short_duration(seconds: int, shown: str) -> None: + """Toasts paint a number + unit, never a word.""" + assert short_duration(seconds) == shown class TestHumanise: diff --git a/steam_backlog_enforcer/tests/test_textgate_toasts.py b/steam_backlog_enforcer/tests/test_textgate_toasts.py new file mode 100644 index 0000000..6795536 --- /dev/null +++ b/steam_backlog_enforcer/tests/test_textgate_toasts.py @@ -0,0 +1,111 @@ +"""Textgate guard: desktop toasts paint glyphs and numbers, never words. + +Walks every ``send_notification`` / ``notify_desktop_user`` call in the +package and checks the literal parts of its arguments (string constants and +the constant pieces of f-strings). Interpolated values -- game names, app ids, +durations, shell commands -- are content and pass. A module-level constant +passed by name is resolved too, so ``_TITLE`` cannot hide a sentence. +""" + +from __future__ import annotations + +import ast +from pathlib import Path +import re + +_PKG = Path(__file__).resolve().parents[1] +_TOAST_CALLS = {"send_notification", "notify_desktop_user"} +_WORD = re.compile(r"[A-Za-z]{2,}") + + +def _literal_parts(node: ast.expr, consts: dict[str, ast.expr]) -> list[str]: + """The literal text an argument paints, following module constants. + + Args: + node: One call argument. + consts: Module-level ``NAME = `` assignments. + + Returns: + Every literal string fragment in the argument. + """ + if isinstance(node, ast.Constant) and isinstance(node.value, str): + return [node.value] + if isinstance(node, ast.JoinedStr): + return [ + v.value + for v in node.values + if isinstance(v, ast.Constant) and isinstance(v.value, str) + ] + if isinstance(node, ast.Name) and node.id in consts: + return _literal_parts(consts[node.id], consts) + if isinstance(node, ast.Subscript): + return _literal_parts(node.value, consts) + if isinstance(node, ast.Dict): + return [p for v in node.values for p in _literal_parts(v, consts)] + return [] + + +def _module_consts(tree: ast.Module) -> dict[str, ast.expr]: + """Map module-level simple assignments to their value expressions. + + Args: + tree: A parsed module. + + Returns: + ``{name: value}`` for ``NAME = value`` and ``NAME: T = value``. + """ + out: dict[str, ast.expr] = {} + for stmt in tree.body: + if isinstance(stmt, ast.Assign): + for target in stmt.targets: + if isinstance(target, ast.Name): + out[target.id] = stmt.value + elif ( + isinstance(stmt, ast.AnnAssign) + and isinstance(stmt.target, ast.Name) + and stmt.value is not None + ): + out[stmt.target.id] = stmt.value + return out + + +def _toast_words() -> list[str]: + """Every literal word passed to a toast, as ``file:line: text``. + + Returns: + The offending fragments; empty when every toast is word-free. + """ + hits: list[str] = [] + for path in sorted(_PKG.glob("*.py")): + tree = ast.parse(path.read_text(encoding="utf-8")) + consts = _module_consts(tree) + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + func = node.func + name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", "") + if name not in _TOAST_CALLS: + continue + for arg in node.args: + hits.extend( + f"{path.name}:{node.lineno}: {part}" + for part in _literal_parts(arg, consts) + if _WORD.search(part) + ) + return hits + + +def test_toasts_paint_no_words() -> None: + """No toast title or body carries a literal 2+ letter word.""" + assert _toast_words() == [] + + +def test_the_guard_finds_toast_calls() -> None: + """The walk is not vacuous: the package has toast call sites.""" + calls = 0 + for path in _PKG.glob("*.py"): + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): + func = getattr(node, "func", None) + name = getattr(func, "id", None) or getattr(func, "attr", "") + calls += isinstance(node, ast.Call) and name in _TOAST_CALLS + assert calls >= 8