Desktop toasts paint glyphs and numbers only

Guard test walks every toast call for literal words.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-11 11:54:20 +01:00
parent 138abc6ce9
commit 291a5ed26f
14 changed files with 176 additions and 54 deletions

View File

@ -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}")

View File

@ -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}!")

View File

@ -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

View File

@ -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:

View File

@ -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.")

View File

@ -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:

View File

@ -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.

View File

@ -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)}")

View File

@ -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()

View File

@ -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")

View File

@ -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:

View File

@ -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])

View File

@ -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:

View File

@ -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 = <expr>`` 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