mirror of
https://github.com/kuhyx/steam-backlog-enforcer.git
synced 2026-11-22 16:42:21 +01:00
Drop gaming budget from 2026-11-16
Kuhy removed the daily gaming/leisure budget; only shutdown time (screen-locker) stays. One gate, _gaming_gate.gaming_enforced_on(day), wraps earned_time 0.22.0 gaming_enforced; resolve_budget carries it as BudgetResolution.enforced and rules_for as PlaytimeRules.gaming_enforced. Unlimited day: no warning, no cutoff, no kill, no leisure billing or leisure kill; a block left from an earlier day is lifted. Time is still billed for history. Backlog game choice and launch scope are untouched. MCP, CLI and /api/budget report unlimited with null numbers; the web UI paints the no-cap icon, no meter. Past-day history keeps working. Failure modes: switch unreadable or day key not a date -> fail OPEN (unlimited), logged ERROR once per cause, never raises, so the 5 h fallback is never enforced and the daemon never crashes. Demo runs stay enforced. The playtime_state.json schema is unchanged. Pins earned-time-v0.22.0 and leisure-watch-v0.2.8 (freshness gate; only golive.py changed, procscan untouched). DOCS-web-control-api notes null fields. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWViGJJaqBKGr1Hbppr
This commit is contained in:
parent
b1424a5bea
commit
e77814e0a7
@ -41,7 +41,7 @@ mirror is `web/src/api/contract.ts`; change both together or neither.
|
||||
| Method | Path | Body / query | Returns |
|
||||
|---|---|---|---|
|
||||
| GET | `/api/dataset` | – | `WebDataset` (exists) |
|
||||
| GET | `/api/budget` | `?demo=1` | `BudgetSnapshot` (exists) |
|
||||
| GET | `/api/budget` | `?demo=1` | `BudgetSnapshot` (exists); from 2026-11-16 `unlimited: true` and every budget/remaining/fraction field is `null` |
|
||||
| GET | `/api/status` | – | `StatusPayload` (`status_payload()`) |
|
||||
| GET | `/api/stats` | – | `StatsPayload` (as MCP `get_stats`) |
|
||||
| GET | `/api/installed` | – | `InstalledPayload` |
|
||||
|
||||
@ -16,11 +16,11 @@ dependencies = [
|
||||
"websockets==17.4",
|
||||
# The earner registry (gaming budget terms); stdlib-only, so the root
|
||||
# daemon imports it from the desktop user's site-packages.
|
||||
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time",
|
||||
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.22.0#subdirectory=earned_time",
|
||||
# The shared /proc game scan and the signed leisure facts (shadow budget,
|
||||
# contract C4); stdlib-only, imported by root from the user site like
|
||||
# earned-time.
|
||||
"leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.2.7",
|
||||
"leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.2.8",
|
||||
]
|
||||
|
||||
# Optional extras. The `mcp` group is ONLY needed by the MCP server
|
||||
|
||||
@ -5,9 +5,9 @@ aiohttp==3.14.5
|
||||
bandit==1.9.4
|
||||
codespell==2.4.3
|
||||
coverage==7.17.3
|
||||
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time
|
||||
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.22.0#subdirectory=earned_time
|
||||
howlongtobeatpy==1.0.24
|
||||
leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.2.7
|
||||
leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.2.8
|
||||
mcp==2.3.0
|
||||
mypy==2.4.1
|
||||
pre-commit==4.7.0
|
||||
|
||||
@ -48,6 +48,7 @@ from typing import TYPE_CHECKING, Final
|
||||
import earned_time
|
||||
|
||||
from steam_backlog_enforcer._gaming_days import gaming_day_key
|
||||
from steam_backlog_enforcer._gaming_gate import gaming_enforced_on
|
||||
from steam_backlog_enforcer._ledger_earners import (
|
||||
first_credits,
|
||||
ledger_answer,
|
||||
@ -108,6 +109,9 @@ class BudgetResolution:
|
||||
shadow_seconds: The same answers priced as leisure
|
||||
(``earned_time.resolve(leisure=True)``, contract C4). Shown, never
|
||||
enforced.
|
||||
enforced: Whether any budget applies on this gaming day. ``False`` from
|
||||
2026-11-16 (:mod:`_gaming_gate`): the numbers above are then
|
||||
history, never a limit.
|
||||
"""
|
||||
|
||||
seconds: float
|
||||
@ -118,6 +122,7 @@ class BudgetResolution:
|
||||
reading_seconds: float = 0.0
|
||||
earned_seconds: dict[str, float] = field(default_factory=dict)
|
||||
shadow_seconds: float = 0.0
|
||||
enforced: bool = True
|
||||
|
||||
|
||||
def _price(
|
||||
@ -180,8 +185,11 @@ def leisure_priced(now: datetime) -> bool:
|
||||
The same question billing asks (``_leisure_mode.leisure_on`` of the billed
|
||||
day), so 00:00-05:59 on the go-live date stays pre-leisure, like its bill.
|
||||
"""
|
||||
day = date.fromisoformat(gaming_day_key(now))
|
||||
return bool(earned_time.leisure_active(day, LEISURE_FROM_PATH))
|
||||
key = gaming_day_key(now)
|
||||
day = date.fromisoformat(key)
|
||||
return gaming_enforced_on(key) and bool(
|
||||
earned_time.leisure_active(day, LEISURE_FROM_PATH)
|
||||
)
|
||||
|
||||
|
||||
def resolve_budget(config: Config) -> BudgetResolution:
|
||||
@ -214,7 +222,11 @@ def resolve_budget(config: Config) -> BudgetResolution:
|
||||
parts = ", ".join(
|
||||
_describe(t.earner.name, t.earner.label, t.answer) for t in day.terms
|
||||
)
|
||||
enforced = gaming_enforced_on(gaming_day_key(now))
|
||||
reason = f"{total / _SECONDS_PER_HOUR:.1f}h: {parts}"
|
||||
if not enforced:
|
||||
# Priced for history and the shadow only; no number may read as a limit.
|
||||
reason = "unlimited (no gaming budget)"
|
||||
# The daemon resolves every tick (3 s): an unchanged answer logged each
|
||||
# time was 25k identical journal lines a day that buried everything else.
|
||||
if reason != _last_logged.get("reason"):
|
||||
@ -229,4 +241,5 @@ def resolve_budget(config: Config) -> BudgetResolution:
|
||||
reading_seconds=earned.get("reading", 0.0),
|
||||
earned_seconds=earned,
|
||||
shadow_seconds=shadow.gaming_minutes * _SECONDS_PER_MINUTE,
|
||||
enforced=enforced,
|
||||
)
|
||||
|
||||
57
steam_backlog_enforcer/_budget_state_access.py
Normal file
57
steam_backlog_enforcer/_budget_state_access.py
Normal file
@ -0,0 +1,57 @@
|
||||
"""Why the budget state file did or did not open, for the budget view.
|
||||
|
||||
Split from :mod:`_budget_view` (250-line cap); that module re-exports every name.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
READABLE: Final = "ok"
|
||||
MISSING: Final = "missing"
|
||||
DENIED: Final = "denied"
|
||||
CORRUPT: Final = "corrupt"
|
||||
|
||||
STATUS_MESSAGES: Final[dict[str, str]] = {
|
||||
DENIED: (
|
||||
"Cannot read the budget state file. It is owned by root, and only "
|
||||
"becomes world-readable once the enforcer has rewritten it — restart "
|
||||
"steam-backlog-enforcer.service."
|
||||
),
|
||||
MISSING: "No gaming time has been recorded yet today.",
|
||||
CORRUPT: (
|
||||
"The budget state file could not be parsed. The enforcer treats that "
|
||||
"as tampering and will start the day fail-closed."
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def state_access(path: Path) -> str:
|
||||
"""Classify why the state file did or did not open.
|
||||
|
||||
``load_state`` deliberately collapses "missing", "corrupt" and "unreadable"
|
||||
into ``None`` — its caller is the enforcer, whose recovery is the same for
|
||||
all three. A display needs to tell them apart, because "you have not gamed
|
||||
today" and "I am not allowed to look" are opposite messages.
|
||||
|
||||
The read is attempted rather than pre-checked with ``os.access``: the
|
||||
kernel's answer to the actual open is the only one that cannot disagree
|
||||
with what ``load_state`` just experienced. The file is a couple of hundred
|
||||
bytes, so reading it twice costs nothing.
|
||||
|
||||
Args:
|
||||
path: The state file.
|
||||
|
||||
Returns:
|
||||
``READABLE``, ``MISSING`` or ``DENIED``.
|
||||
"""
|
||||
try:
|
||||
path.read_bytes()
|
||||
except FileNotFoundError:
|
||||
return MISSING
|
||||
except OSError:
|
||||
return DENIED
|
||||
return READABLE
|
||||
@ -21,6 +21,14 @@ from steam_backlog_enforcer._budget_games import (
|
||||
today_games,
|
||||
)
|
||||
from steam_backlog_enforcer._budget_log_tail import last_verdict
|
||||
from steam_backlog_enforcer._budget_state_access import (
|
||||
CORRUPT,
|
||||
DENIED,
|
||||
MISSING,
|
||||
READABLE,
|
||||
STATUS_MESSAGES,
|
||||
state_access,
|
||||
)
|
||||
from steam_backlog_enforcer._ledger_earners import registry_for
|
||||
from steam_backlog_enforcer._playtime_block import mounted_targets
|
||||
from steam_backlog_enforcer._playtime_history import load_history
|
||||
@ -33,59 +41,24 @@ from steam_backlog_enforcer._shadow_view import shadow_view
|
||||
from steam_backlog_enforcer.config import Config, State
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
import earned_time
|
||||
|
||||
from steam_backlog_enforcer._playtime_state import PlaytimeRules, PlaytimeState
|
||||
|
||||
READABLE: Final = "ok"
|
||||
MISSING: Final = "missing"
|
||||
DENIED: Final = "denied"
|
||||
CORRUPT: Final = "corrupt"
|
||||
|
||||
_STATUS_MESSAGES: Final[dict[str, str]] = {
|
||||
DENIED: (
|
||||
"Cannot read the budget state file. It is owned by root, and only "
|
||||
"becomes world-readable once the enforcer has rewritten it — restart "
|
||||
"steam-backlog-enforcer.service."
|
||||
),
|
||||
MISSING: "No gaming time has been recorded yet today.",
|
||||
CORRUPT: (
|
||||
"The budget state file could not be parsed. The enforcer treats that "
|
||||
"as tampering and will start the day fail-closed."
|
||||
),
|
||||
}
|
||||
|
||||
_HISTORY_DAYS: Final = 14
|
||||
|
||||
|
||||
def state_access(path: Path) -> str:
|
||||
"""Classify why the state file did or did not open.
|
||||
|
||||
``load_state`` deliberately collapses "missing", "corrupt" and "unreadable"
|
||||
into ``None`` — its caller is the enforcer, whose recovery is the same for
|
||||
all three. A display needs to tell them apart, because "you have not gamed
|
||||
today" and "I am not allowed to look" are opposite messages.
|
||||
|
||||
The read is attempted rather than pre-checked with ``os.access``: the
|
||||
kernel's answer to the actual open is the only one that cannot disagree
|
||||
with what ``load_state`` just experienced. The file is a couple of hundred
|
||||
bytes, so reading it twice costs nothing.
|
||||
|
||||
Args:
|
||||
path: The state file.
|
||||
|
||||
Returns:
|
||||
``READABLE``, ``MISSING`` or ``DENIED``.
|
||||
"""
|
||||
try:
|
||||
path.read_bytes()
|
||||
except FileNotFoundError:
|
||||
return MISSING
|
||||
except OSError:
|
||||
return DENIED
|
||||
return READABLE
|
||||
# Re-exported: the status classifier moved to _budget_state_access (250-line cap).
|
||||
__all__ = [
|
||||
"CORRUPT",
|
||||
"DENIED",
|
||||
"MISSING",
|
||||
"READABLE",
|
||||
"build_budget_snapshot",
|
||||
"build_rules",
|
||||
"build_today",
|
||||
"next_warning",
|
||||
"state_access",
|
||||
]
|
||||
|
||||
|
||||
def next_warning(state: PlaytimeState, rules: PlaytimeRules) -> int | None:
|
||||
@ -125,19 +98,25 @@ def build_today(state: PlaytimeState, rules: PlaytimeRules) -> dict[str, Any]:
|
||||
"""
|
||||
remaining = max(0.0, rules.budget_seconds - state.seconds)
|
||||
fraction = state.seconds / rules.budget_seconds if rules.budget_seconds else 1.0
|
||||
unlimited = not rules.gaming_enforced
|
||||
return {
|
||||
"gaming_day": state.day_key,
|
||||
"day_starts_at": "06:00 local",
|
||||
"seconds_used": round(state.seconds, 1),
|
||||
"budget_seconds": rules.budget_seconds,
|
||||
"seconds_remaining": round(remaining, 1),
|
||||
"fraction_used": round(min(1.0, max(0.0, fraction)), 4),
|
||||
"blocked": state.is_blocked(),
|
||||
"blocked_at": state.blocked_at,
|
||||
"next_warning_seconds": next_warning(state, rules),
|
||||
"warned_seconds": list(state.warned_seconds),
|
||||
# No budget since 2026-11-16: the day is "unlimited" and carries no
|
||||
# number a reader could take for a limit. Past days keep their history.
|
||||
"unlimited": unlimited,
|
||||
"budget_seconds": None if unlimited else rules.budget_seconds,
|
||||
"seconds_remaining": None if unlimited else round(remaining, 1),
|
||||
"fraction_used": (
|
||||
None if unlimited else round(min(1.0, max(0.0, fraction)), 4)
|
||||
),
|
||||
"blocked": False if unlimited else state.is_blocked(),
|
||||
"blocked_at": 0.0 if unlimited else state.blocked_at,
|
||||
"next_warning_seconds": None if unlimited else next_warning(state, rules),
|
||||
"warned_seconds": [] if unlimited else list(state.warned_seconds),
|
||||
"games": today_games(state),
|
||||
"shadow": shadow_view(state),
|
||||
"shadow": shadow_view(state, unlimited=unlimited),
|
||||
}
|
||||
|
||||
|
||||
@ -158,11 +137,13 @@ def build_rules(rules: PlaytimeRules) -> dict[str, Any]:
|
||||
Returns:
|
||||
Serialisable rules block.
|
||||
"""
|
||||
unlimited = not rules.gaming_enforced
|
||||
return {
|
||||
"budget_seconds": rules.budget_seconds,
|
||||
"unlimited": unlimited,
|
||||
"budget_seconds": None if unlimited else rules.budget_seconds,
|
||||
"enforcement": rules.enforcement,
|
||||
"counts_launchers": rules.count_launchers,
|
||||
"warn_at": list(rules.warn_at),
|
||||
"warn_at": [] if unlimited else list(rules.warn_at),
|
||||
"demo": rules.demo,
|
||||
"masked_launchers": sorted(str(path) for path in mounted_targets()),
|
||||
# Read off the rules, never re-resolved: resolving a second time here
|
||||
@ -188,6 +169,8 @@ def build_rules(rules: PlaytimeRules) -> dict[str, Any]:
|
||||
"bonus_seconds": _most(earner) * 60,
|
||||
}
|
||||
for earner in registry_for(datetime.now().astimezone().date())
|
||||
# An earner's gaming pay is a budget term: none when unlimited.
|
||||
if not unlimited
|
||||
],
|
||||
}
|
||||
|
||||
@ -221,7 +204,7 @@ def build_budget_snapshot(*, demo: bool = False) -> dict[str, Any]:
|
||||
"ok": True,
|
||||
"readable": status == READABLE,
|
||||
"state_status": status,
|
||||
"error": _STATUS_MESSAGES.get(status),
|
||||
"error": STATUS_MESSAGES.get(status),
|
||||
"today": build_today(stored, rules) if stored is not None else None,
|
||||
"session": {
|
||||
# What the budget is actually charging — a different question from
|
||||
|
||||
@ -74,15 +74,19 @@ def cmd_gaming_status(config: Config, _state: State) -> None:
|
||||
continue
|
||||
_echo(f"{'Demo' if demo else 'Gaming'} budget:")
|
||||
_echo(f" state file: {state_path(demo=demo)}")
|
||||
_echo(f" budget_seconds: {rules.budget_seconds:.0f}")
|
||||
if rules.gaming_enforced:
|
||||
_echo(f" budget_seconds: {rules.budget_seconds:.0f}")
|
||||
else:
|
||||
_echo(" unlimited: no gaming budget (until shutdown)")
|
||||
if stored is None:
|
||||
_echo(" (no state recorded yet)")
|
||||
else:
|
||||
remaining = max(0.0, rules.budget_seconds - stored.seconds)
|
||||
_echo(f" gaming day: {stored.day_key} (starts 06:00 local)")
|
||||
_echo(f" used: {stored.seconds:.0f}s")
|
||||
_echo(f" remaining: {remaining:.0f}s")
|
||||
_echo(f" blocked: {stored.is_blocked()}")
|
||||
if rules.gaming_enforced:
|
||||
remaining = max(0.0, rules.budget_seconds - stored.seconds)
|
||||
_echo(f" remaining: {remaining:.0f}s")
|
||||
_echo(f" blocked: {stored.is_blocked()}")
|
||||
|
||||
masked = mounted_targets()
|
||||
_echo(f"Masked launchers: {len(masked)}/{len(block_targets())}")
|
||||
|
||||
59
steam_backlog_enforcer/_gaming_gate.py
Normal file
59
steam_backlog_enforcer/_gaming_gate.py
Normal file
@ -0,0 +1,59 @@
|
||||
"""The one switch that says whether a gaming budget exists on a gaming day.
|
||||
|
||||
kuhy removed the daily gaming (and leisure) budget on 2026-11-16: from then on
|
||||
games may run until shutdown, and shutdown time (screen-locker) is the only
|
||||
carrot. ``earned_time.gaming_enforced`` owns the date; every place that
|
||||
*applies* a budget (kill, block, warning, leisure kill, leisure billing) asks
|
||||
this wrapper, and every place that *reports* one prints "unlimited" instead of
|
||||
a number. Numbers stay resolvable for history and the shadow view.
|
||||
|
||||
**Fail open, loudly.** If the switch cannot be read (an old ``earned_time``
|
||||
without the function, a day key that is no date) the answer is "unlimited", not
|
||||
"enforce whatever the registry falls back to": from the switch the fallback is
|
||||
the 5 h base, a *lower* budget than kuhy lived under, and a crash here would
|
||||
take the root daemon down. The failure is logged at ERROR, once per distinct
|
||||
cause, because this runs every 3 s tick.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
import logging
|
||||
from typing import Final
|
||||
|
||||
import earned_time
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Failures already logged, so a permanent fault is one journal line, not 28k a day.
|
||||
_logged: Final[set[str]] = set()
|
||||
|
||||
|
||||
def reset_logged() -> None:
|
||||
"""Forget the failures already logged (tests, and a daemon reload)."""
|
||||
_logged.clear()
|
||||
|
||||
|
||||
def gaming_enforced_on(day_key: str) -> bool:
|
||||
"""Whether a gaming budget is enforced on the gaming day *day_key*.
|
||||
|
||||
Args:
|
||||
day_key: The 06:00-shifted gaming day, ``YYYY-MM-DD``.
|
||||
|
||||
Returns:
|
||||
``False`` from ``earned_time.GAMING_UNLIMITED_FROM`` (no budget), and
|
||||
``False`` when the switch cannot be read (fail open, logged).
|
||||
"""
|
||||
try:
|
||||
return bool(earned_time.gaming_enforced(date.fromisoformat(day_key)))
|
||||
except (AttributeError, TypeError, ValueError) as exc:
|
||||
cause = f"{type(exc).__name__}: {exc}"
|
||||
if cause not in _logged:
|
||||
_logged.add(cause)
|
||||
logger.exception(
|
||||
"Cannot read the gaming-budget switch for %r (%s); treating the "
|
||||
"day as unlimited so no lower budget is enforced.",
|
||||
day_key,
|
||||
cause,
|
||||
)
|
||||
return False
|
||||
@ -22,8 +22,7 @@ over; a reason carrying the start time it saw (leisure-watch 0.2.1 ``start``)
|
||||
names only that process, never a later one reusing the pid. Root/system
|
||||
processes, lockers and the enforcer itself are never signalled, nor --
|
||||
whatever ``now.json`` says -- the desktop session (:mod:`_leisure_never_kill`;
|
||||
each refusal logged once). Every SIGTERM and the first SIGKILL go to
|
||||
``budget.jsonl``.
|
||||
each refusal logged once). Every SIGTERM and the first SIGKILL go to ``budget.jsonl``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -154,7 +153,8 @@ class LeisureKiller:
|
||||
verdict: ShadowVerdict,
|
||||
stamp: float,
|
||||
) -> None:
|
||||
if not rules.leisure or rules.demo or not rules.enforcement:
|
||||
armed = rules.leisure and rules.enforcement and rules.gaming_enforced
|
||||
if rules.demo or not armed:
|
||||
return
|
||||
untrusted_for = self._untrusted_for(verdict, stamp)
|
||||
if state.seconds < rules.budget_seconds:
|
||||
|
||||
@ -20,6 +20,7 @@ from typing import TYPE_CHECKING, Final
|
||||
import earned_time
|
||||
from leisure_watch.procscan import attributed_key
|
||||
|
||||
from steam_backlog_enforcer._gaming_gate import gaming_enforced_on
|
||||
from steam_backlog_enforcer._playtime_budget import accumulate, bill
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@ -45,6 +46,9 @@ def leisure_on(day_key: str) -> bool:
|
||||
day = date.fromisoformat(day_key)
|
||||
except ValueError:
|
||||
return False
|
||||
# No gaming budget (2026-11-16) means no leisure budget either.
|
||||
if not gaming_enforced_on(day_key):
|
||||
return False
|
||||
return bool(earned_time.leisure_active(day, LEISURE_FROM_PATH))
|
||||
|
||||
|
||||
|
||||
@ -42,6 +42,7 @@ def get_gaming_time() -> dict[str, Any]:
|
||||
"ok": True,
|
||||
"recorded": False,
|
||||
"state_status": snapshot["state_status"],
|
||||
"unlimited": rules["unlimited"],
|
||||
"budget_seconds": rules["budget_seconds"],
|
||||
"enforcement": rules["enforcement"],
|
||||
"masked_launchers": masked,
|
||||
@ -54,6 +55,8 @@ def get_gaming_time() -> dict[str, Any]:
|
||||
"gaming_day": today["gaming_day"],
|
||||
"day_starts_at": today["day_starts_at"],
|
||||
"seconds_used": today["seconds_used"],
|
||||
# True from 2026-11-16: no budget, so no number below.
|
||||
"unlimited": today["unlimited"],
|
||||
"budget_seconds": today["budget_seconds"],
|
||||
"seconds_remaining": today["seconds_remaining"],
|
||||
# What earned budget_seconds.
|
||||
|
||||
@ -221,6 +221,11 @@ def _policy(
|
||||
Returns:
|
||||
The updated state.
|
||||
"""
|
||||
if not rules.gaming_enforced:
|
||||
# No gaming budget (2026-11-16): lift any block; time is still billed.
|
||||
reconcile_for(rules, should_block=False)
|
||||
return replace(state, blocked_at=0.0, warned_seconds=[])
|
||||
|
||||
if not rules.enforcement:
|
||||
# A kill switch must still release: leaving live mounts behind would
|
||||
# make "disabled" mean "permanently blocked".
|
||||
|
||||
@ -223,6 +223,7 @@ def _snapshot(
|
||||
"qualifying": sorted(qualifying),
|
||||
"day_key": state.day_key,
|
||||
"billed_seconds": round(state.seconds, 3),
|
||||
"gaming_enforced": rules.gaming_enforced,
|
||||
"budget_seconds": round(rules.budget_seconds, 3),
|
||||
"remaining_seconds": round(rules.budget_seconds - state.seconds, 3),
|
||||
}
|
||||
|
||||
@ -101,6 +101,9 @@ class PlaytimeRules:
|
||||
# Phase 2: the billed gaming day is on the leisure budget (set per tick by
|
||||
# _leisure_mode.leisure_billed, never by rules_for). Only wording and kills.
|
||||
leisure: bool = False
|
||||
# False from 2026-11-16 (_gaming_gate): no budget is enforced -- no kill, no
|
||||
# block, no warning. budget_seconds is then history, not a limit.
|
||||
gaming_enforced: bool = True
|
||||
|
||||
|
||||
def rules_for(config: Config, *, demo: bool) -> PlaytimeRules:
|
||||
@ -126,6 +129,7 @@ def rules_for(config: Config, *, demo: bool) -> PlaytimeRules:
|
||||
live = 0.0 if resolved is None else resolved.seconds
|
||||
held = held_today(stored, now)
|
||||
held_note = f"; held at {held / 3600:.1f}h (earned earlier today)"
|
||||
enforced = resolved is None or resolved.enforced
|
||||
return PlaytimeRules(
|
||||
budget_seconds=_DEMO_BUDGET_SECONDS if resolved is None else max(live, held),
|
||||
warn_at=_DEMO_WARN_AT if demo else _WARN_AT,
|
||||
@ -133,7 +137,8 @@ def rules_for(config: Config, *, demo: bool) -> PlaytimeRules:
|
||||
count_launchers=config.playtime.count_launcher_processes,
|
||||
enforcement=config.playtime.playtime_enforcement,
|
||||
demo=demo,
|
||||
breakdown=_breakdown(resolved, held_note if held > live else ""),
|
||||
gaming_enforced=enforced,
|
||||
breakdown=_breakdown(resolved, held_note if enforced and held > live else ""),
|
||||
shadow_budget_seconds=0.0
|
||||
if resolved is None
|
||||
else max(resolved.shadow_seconds, held_shadow_today(stored, now)),
|
||||
|
||||
@ -12,11 +12,12 @@ if TYPE_CHECKING:
|
||||
from steam_backlog_enforcer._playtime_state import PlaytimeState
|
||||
|
||||
|
||||
def shadow_view(state: PlaytimeState) -> dict[str, Any]:
|
||||
def shadow_view(state: PlaytimeState, *, unlimited: bool = False) -> dict[str, Any]:
|
||||
"""Compose the shadow block from stored state.
|
||||
|
||||
Args:
|
||||
state: Loaded accounting state.
|
||||
unlimited: No budget applies (2026-11-16): report no budget number.
|
||||
|
||||
Returns:
|
||||
Used/budget/remaining seconds, whether the leisure budget would block
|
||||
@ -25,9 +26,9 @@ def shadow_view(state: PlaytimeState) -> dict[str, Any]:
|
||||
remaining = max(0.0, state.shadow.budget_seconds - state.shadow.seconds)
|
||||
return {
|
||||
"seconds_used": round(state.shadow.seconds, 1),
|
||||
"budget_seconds": state.shadow.budget_seconds,
|
||||
"seconds_remaining": round(remaining, 1),
|
||||
"would_block": remaining <= 0.0,
|
||||
"budget_seconds": None if unlimited else state.shadow.budget_seconds,
|
||||
"seconds_remaining": None if unlimited else round(remaining, 1),
|
||||
"would_block": False if unlimited else remaining <= 0.0,
|
||||
"paused_seconds": round(state.shadow.paused_seconds, 1),
|
||||
"per_source": {k: round(v, 1) for k, v in state.shadow.per_source.items()},
|
||||
}
|
||||
|
||||
@ -27,8 +27,7 @@ from steam_backlog_enforcer.tests._no_workout_http import earned_budget, fixed_b
|
||||
|
||||
# Built at import time, so the autouse _no_workout_http fixture is not in
|
||||
# effect yet -- without this patch, collecting this module makes a real HTTP
|
||||
# call to the screen locker and pins RULES to whatever budget today happens to
|
||||
# have earned. Stub it explicitly so the constant is the earned budget always.
|
||||
# call to the screen locker and pins RULES to today's earned budget. Stub it.
|
||||
# The held budget is pinned for the same reason: conftest's redirects are not
|
||||
# active at import either, so rules_for would read the LIVE playtime_state.json
|
||||
# and hold RULES at whatever high-water mark it records today. Nor would the
|
||||
@ -238,6 +237,7 @@ class TestBuildBudgetSnapshot:
|
||||
snapshot = self._snapshot()
|
||||
assert "SEKRET" not in json.dumps(snapshot)
|
||||
assert set(snapshot["rules"]) == {
|
||||
"unlimited",
|
||||
"budget_seconds",
|
||||
"enforcement",
|
||||
"counts_launchers",
|
||||
|
||||
237
steam_backlog_enforcer/tests/test_gaming_unlimited.py
Normal file
237
steam_backlog_enforcer/tests/test_gaming_unlimited.py
Normal file
@ -0,0 +1,237 @@
|
||||
"""From 2026-11-16 the gaming budget is gone: no kill, no block, no warning.
|
||||
|
||||
Each test pairs the new behaviour (a day on or after the switch) with the old
|
||||
one (the day before it), so the gate is proven in both directions.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import ExitStack
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import DEFAULT, patch
|
||||
|
||||
from leisure_watch.facts import Reason
|
||||
import pytest
|
||||
|
||||
from steam_backlog_enforcer import _gaming_gate
|
||||
from steam_backlog_enforcer._budget_resolve import BudgetResolution, resolve_budget
|
||||
from steam_backlog_enforcer._gaming_gate import gaming_enforced_on
|
||||
from steam_backlog_enforcer._leisure_kill import LeisureKiller
|
||||
from steam_backlog_enforcer._leisure_mode import leisure_on
|
||||
from steam_backlog_enforcer._playtime import playtime_tick
|
||||
from steam_backlog_enforcer._playtime_state import (
|
||||
PlaytimeState,
|
||||
load_state,
|
||||
rules_for,
|
||||
save_state,
|
||||
)
|
||||
from steam_backlog_enforcer.config import Config
|
||||
from steam_backlog_enforcer.tests._budget_dates import pin_today
|
||||
from steam_backlog_enforcer.tests._budget_earners import (
|
||||
LEETCODE,
|
||||
READING,
|
||||
WORKOUT,
|
||||
)
|
||||
from steam_backlog_enforcer.tests._fake_session import fake_session
|
||||
from steam_backlog_enforcer.tests._leisure_kill_world import (
|
||||
RULES as LEISURE_RULES,
|
||||
)
|
||||
from steam_backlog_enforcer.tests._leisure_kill_world import (
|
||||
SPENT,
|
||||
StubLog,
|
||||
build_proc,
|
||||
now_with,
|
||||
verdict_of,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
PKG = "steam_backlog_enforcer._playtime"
|
||||
_RESOLVER = "steam_backlog_enforcer._playtime_state.resolve_budget"
|
||||
LOCAL = timezone(timedelta(hours=2))
|
||||
LAST_DAY = datetime(2026, 11, 15, 20, 0, tzinfo=LOCAL)
|
||||
FIRST_DAY = datetime(2026, 11, 17, 20, 0, tzinfo=LOCAL)
|
||||
_THREE_HOURS = 3 * 3600.0
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fresh_gate() -> Iterator[None]:
|
||||
"""Forget which failures were logged, so each test sees its own."""
|
||||
_gaming_gate.reset_logged()
|
||||
yield
|
||||
_gaming_gate.reset_logged()
|
||||
|
||||
|
||||
@pytest.fixture(name="effects")
|
||||
def fixture_effects() -> Iterator[dict[str, MagicMock]]:
|
||||
"""Neutralise and expose every side effect a cutoff can have."""
|
||||
with ExitStack() as stack:
|
||||
mocks: dict[str, MagicMock] = stack.enter_context(
|
||||
patch.multiple(
|
||||
"steam_backlog_enforcer._playtime_cutoff",
|
||||
reconcile=DEFAULT,
|
||||
request_steam_shutdown=DEFAULT,
|
||||
kill_gaming_processes=DEFAULT,
|
||||
notify_desktop_user=DEFAULT,
|
||||
)
|
||||
)
|
||||
stack.enter_context(patch(f"{PKG}.mounted_targets", return_value=set()))
|
||||
stack.enter_context(patch(f"{PKG}.is_total_block_active", return_value=False))
|
||||
stack.enter_context(patch(f"{PKG}.qualifying_pids", return_value={7: "app:1"}))
|
||||
yield mocks
|
||||
|
||||
|
||||
def _real_resolver(*, workout: bool = False) -> ExitStack:
|
||||
"""Patch ``rules_for`` to use the real ``resolve_budget``, earners fixed."""
|
||||
stack = ExitStack()
|
||||
stack.enter_context(patch(_RESOLVER, side_effect=resolve_budget))
|
||||
stack.enter_context(patch(WORKOUT, return_value=workout))
|
||||
stack.enter_context(patch(LEETCODE, return_value=False))
|
||||
stack.enter_context(patch(READING, return_value=False))
|
||||
return stack
|
||||
|
||||
|
||||
def _tick(now: datetime, key: str) -> PlaytimeState:
|
||||
"""Run one real-resolver tick at *now* with a day already past any budget."""
|
||||
save_state(
|
||||
PlaytimeState(
|
||||
day_key=key,
|
||||
seconds=12 * 3600.0,
|
||||
blocked_at=now.timestamp() - 60,
|
||||
warned_seconds=[3600],
|
||||
last_tick_at=now.timestamp() - 3.0,
|
||||
),
|
||||
demo=False,
|
||||
)
|
||||
with (
|
||||
_real_resolver(),
|
||||
pin_today(now.date()),
|
||||
patch(f"{PKG}.datetime") as clock,
|
||||
patch("steam_backlog_enforcer._playtime_state.datetime") as state_clock,
|
||||
):
|
||||
clock.now.return_value = now
|
||||
state_clock.now.return_value.astimezone.return_value = now
|
||||
playtime_tick(Config(), interval=3.0, session=fake_session())
|
||||
stored = load_state(demo=False)
|
||||
assert stored is not None
|
||||
return stored
|
||||
|
||||
|
||||
class TestGate:
|
||||
"""``gaming_enforced_on``: the date switch, failing open and loud."""
|
||||
|
||||
def test_enforced_the_day_before(self) -> None:
|
||||
"""2026-11-15 still has its budget."""
|
||||
assert gaming_enforced_on("2026-11-15") is True
|
||||
|
||||
@pytest.mark.parametrize("day", ["2026-11-16", "2026-11-17", "2027-03-01"])
|
||||
def test_unlimited_from_the_switch(self, day: str) -> None:
|
||||
"""The switch day and every later one have no budget."""
|
||||
assert gaming_enforced_on(day) is False
|
||||
|
||||
@pytest.mark.parametrize("failure", [AttributeError("old lib"), ValueError("x")])
|
||||
def test_failure_is_unlimited_and_logged_once(
|
||||
self, failure: Exception, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""An unreadable switch never re-imposes a budget; it logs, once."""
|
||||
with (
|
||||
patch("earned_time.gaming_enforced", side_effect=failure),
|
||||
caplog.at_level(logging.ERROR),
|
||||
):
|
||||
assert gaming_enforced_on("2026-11-20") is False
|
||||
assert gaming_enforced_on("2026-11-20") is False
|
||||
assert [r.levelno for r in caplog.records] == [logging.ERROR]
|
||||
|
||||
def test_a_key_that_is_no_date_is_unlimited_and_logged(
|
||||
self, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""A garbled day key cannot price a budget; it fails open, loudly."""
|
||||
with caplog.at_level(logging.ERROR):
|
||||
assert gaming_enforced_on("not-a-day") is False
|
||||
assert "not-a-day" in caplog.text
|
||||
|
||||
|
||||
class TestResolve:
|
||||
"""``resolve_budget`` marks the day unlimited from the switch."""
|
||||
|
||||
def test_unlimited_day_has_no_budget_to_enforce(self) -> None:
|
||||
"""On 2026-11-17 the resolution says unlimited, whatever the registry."""
|
||||
with _real_resolver(), pin_today(date(2026, 11, 17)):
|
||||
resolved = resolve_budget(Config())
|
||||
assert resolved.enforced is False
|
||||
assert "unlimited" in resolved.reason
|
||||
|
||||
def test_the_day_before_is_unchanged(self) -> None:
|
||||
"""On 2026-11-15 the budget is still a number to enforce."""
|
||||
with _real_resolver(), pin_today(date(2026, 11, 15)):
|
||||
resolved = resolve_budget(Config())
|
||||
assert resolved.enforced is True
|
||||
assert resolved.seconds > 0
|
||||
assert "unlimited" not in resolved.reason
|
||||
|
||||
def test_rules_carry_the_flag(self) -> None:
|
||||
"""``rules_for`` hands the gate to every consumer; a demo is always on."""
|
||||
off = BudgetResolution(0.0, 0.0, 0.0, 0.0, "unlimited", enforced=False)
|
||||
with patch(_RESOLVER, return_value=off):
|
||||
assert rules_for(Config(), demo=False).gaming_enforced is False
|
||||
assert rules_for(Config(), demo=True).gaming_enforced is True
|
||||
|
||||
|
||||
class TestTick:
|
||||
"""The enforce tick: zero credits, budget long spent."""
|
||||
|
||||
def test_unlimited_day_never_kills_and_lifts_the_block(
|
||||
self, effects: dict[str, MagicMock]
|
||||
) -> None:
|
||||
"""2026-11-17, 12 h billed, nothing earned: no kill, mounts off."""
|
||||
stored = _tick(FIRST_DAY, "2026-11-17")
|
||||
effects["kill_gaming_processes"].assert_not_called()
|
||||
effects["request_steam_shutdown"].assert_not_called()
|
||||
effects["notify_desktop_user"].assert_not_called()
|
||||
assert not stored.is_blocked()
|
||||
assert stored.warned_seconds == []
|
||||
effects["reconcile"].assert_called_with(should_block=False)
|
||||
|
||||
def test_the_day_before_still_cuts_off(self, effects: dict[str, MagicMock]) -> None:
|
||||
"""2026-11-15, same state: the old cutoff holds."""
|
||||
stored = _tick(LAST_DAY, "2026-11-15")
|
||||
effects["kill_gaming_processes"].assert_called()
|
||||
effects["request_steam_shutdown"].assert_not_called()
|
||||
assert stored.is_blocked()
|
||||
|
||||
def test_time_is_still_billed_for_history(
|
||||
self, effects: dict[str, MagicMock]
|
||||
) -> None:
|
||||
"""No budget does not stop the day's history from counting."""
|
||||
stored = _tick(FIRST_DAY, "2026-11-17")
|
||||
assert stored.seconds == pytest.approx(12 * 3600.0 + 3.0)
|
||||
del effects
|
||||
|
||||
|
||||
class TestLeisure:
|
||||
"""Leisure is a budget too: off from the switch."""
|
||||
|
||||
def test_leisure_never_on_from_the_switch(self) -> None:
|
||||
"""Even a live switch file cannot bill leisure on an unlimited day."""
|
||||
with patch("earned_time.leisure_active", return_value=True):
|
||||
assert leisure_on("2026-11-15") is True
|
||||
assert leisure_on("2026-11-16") is False
|
||||
|
||||
@pytest.mark.parametrize(("enforced", "kills"), [(True, 1), (False, 0)])
|
||||
def test_leisure_kill_stands_down(
|
||||
self, tmp_path: Path, *, enforced: bool, kills: int
|
||||
) -> None:
|
||||
"""A spent leisure budget kills mpv only while gaming is enforced."""
|
||||
build_proc(tmp_path)
|
||||
killer = LeisureKiller(StubLog())
|
||||
verdict = verdict_of(now_with(Reason("media", "app:mpv", 10, "mpv")))
|
||||
rules = replace(LEISURE_RULES, gaming_enforced=enforced)
|
||||
with patch("os.kill") as kill:
|
||||
killer.enforce(SPENT, rules, verdict=verdict, stamp=1000.0)
|
||||
assert kill.call_count == kills
|
||||
111
steam_backlog_enforcer/tests/test_gaming_unlimited_views.py
Normal file
111
steam_backlog_enforcer/tests/test_gaming_unlimited_views.py
Normal file
@ -0,0 +1,111 @@
|
||||
"""MCP, CLI and web report "unlimited" with no number once the budget is gone."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from steam_backlog_enforcer import _budget_view as view
|
||||
from steam_backlog_enforcer import _mcp_gaming_time as mcp_gaming_time
|
||||
from steam_backlog_enforcer._budget_resolve import BudgetResolution
|
||||
from steam_backlog_enforcer._cmd_playtime import cmd_gaming_status
|
||||
from steam_backlog_enforcer._playtime_state import PlaytimeState
|
||||
from steam_backlog_enforcer.config import Config, State
|
||||
from steam_backlog_enforcer.tests._cmd_playtime_patches import cli_as, echoed
|
||||
|
||||
_RESOLVER = "steam_backlog_enforcer._playtime_state.resolve_budget"
|
||||
_STORED = PlaytimeState(day_key="2026-11-17", seconds=40_000.0, budget_seconds=18_000.0)
|
||||
|
||||
|
||||
def _resolution(*, enforced: bool) -> BudgetResolution:
|
||||
"""A resolution that would be a 5 h budget if it were enforced."""
|
||||
return BudgetResolution(
|
||||
seconds=18_000.0,
|
||||
base_seconds=18_000.0,
|
||||
workout_seconds=0.0,
|
||||
leetcode_seconds=0.0,
|
||||
reason="5.0h: base" if enforced else "unlimited",
|
||||
enforced=enforced,
|
||||
)
|
||||
|
||||
|
||||
def _snapshot(*, enforced: bool) -> dict[str, Any]:
|
||||
with (
|
||||
patch(_RESOLVER, return_value=_resolution(enforced=enforced)),
|
||||
patch.object(view, "load_state", return_value=_STORED),
|
||||
patch.object(view, "mounted_targets", return_value=set()),
|
||||
):
|
||||
return view.build_budget_snapshot()
|
||||
|
||||
|
||||
class TestWebView:
|
||||
"""``/api/budget`` payload."""
|
||||
|
||||
def test_unlimited_has_no_number(self) -> None:
|
||||
"""No budget, remaining, fraction or warning; the flag says why."""
|
||||
snap = _snapshot(enforced=False)
|
||||
today, rules = snap["today"], snap["rules"]
|
||||
assert today["unlimited"] is True
|
||||
assert rules["unlimited"] is True
|
||||
for field in ("budget_seconds", "seconds_remaining", "fraction_used"):
|
||||
assert today[field] is None
|
||||
assert today["next_warning_seconds"] is None
|
||||
assert today["shadow"]["budget_seconds"] is None
|
||||
assert rules["budget_seconds"] is None
|
||||
assert rules["warn_at"] == []
|
||||
assert rules["earners"] == []
|
||||
assert today["seconds_used"] == 40_000.0
|
||||
|
||||
def test_enforced_day_keeps_its_numbers(self) -> None:
|
||||
"""Before the switch the payload is what it always was."""
|
||||
snap = _snapshot(enforced=True)
|
||||
today = snap["today"]
|
||||
assert today["unlimited"] is False
|
||||
assert snap["rules"]["unlimited"] is False
|
||||
assert today["budget_seconds"] == 18_000.0
|
||||
assert today["seconds_remaining"] == 0.0
|
||||
assert today["fraction_used"] == 1.0
|
||||
|
||||
|
||||
class TestMcp:
|
||||
"""``get_gaming_time`` tool."""
|
||||
|
||||
@pytest.mark.parametrize("recorded", [True, False])
|
||||
def test_unlimited(self, *, recorded: bool) -> None:
|
||||
"""Recorded or not, the reply says unlimited and carries no budget."""
|
||||
stored = _STORED if recorded else None
|
||||
with (
|
||||
patch(_RESOLVER, return_value=_resolution(enforced=False)),
|
||||
patch.object(view, "load_state", return_value=stored),
|
||||
patch.object(view, "mounted_targets", return_value=set()),
|
||||
):
|
||||
out = mcp_gaming_time.get_gaming_time()
|
||||
assert out["unlimited"] is True
|
||||
assert out["budget_seconds"] is None
|
||||
assert out.get("seconds_remaining") is None
|
||||
|
||||
|
||||
class TestCli:
|
||||
"""``gaming-status``."""
|
||||
|
||||
def test_unlimited_prints_no_budget_number(self) -> None:
|
||||
"""The status says unlimited, not a remaining count."""
|
||||
with (
|
||||
patch(_RESOLVER, return_value=_resolution(enforced=False)),
|
||||
patch(
|
||||
"steam_backlog_enforcer._cmd_playtime.load_state",
|
||||
side_effect=lambda demo: None if demo else _STORED,
|
||||
),
|
||||
patch(
|
||||
"steam_backlog_enforcer._cmd_playtime.mounted_targets",
|
||||
return_value=set(),
|
||||
),
|
||||
cli_as(None) as cli,
|
||||
):
|
||||
cmd_gaming_status(Config(), State())
|
||||
text = echoed(cli.echo)
|
||||
assert "unlimited" in text
|
||||
assert "budget_seconds" not in text
|
||||
assert "remaining" not in text
|
||||
@ -23,8 +23,10 @@ export function budget(demo: boolean): BudgetSnapshot {
|
||||
const budgetSeconds = demo ? 60 : 3 * 3600
|
||||
const base = demo ? 20 : 2 * 3600 + 10 * 60
|
||||
const since = resetAt ?? started
|
||||
const used = Math.min(budgetSeconds, (resetAt === null ? base : 0) + Math.floor((Date.now() - since) / 1000))
|
||||
const remaining = budgetSeconds - used
|
||||
// From 2026-11-16 the real backend has no budget (unlimited); the demo run still does.
|
||||
const unlimited = !demo
|
||||
const used = Math.min(unlimited ? Infinity : budgetSeconds, (resetAt === null ? base : 0) + Math.floor((Date.now() - since) / 1000))
|
||||
const remaining = unlimited ? null : budgetSeconds - used
|
||||
const today = new Date()
|
||||
const history = Array.from({ length: 14 }, (_, i) => {
|
||||
const d = new Date(today.getTime() - (13 - i) * 86_400_000)
|
||||
@ -49,19 +51,20 @@ export function budget(demo: boolean): BudgetSnapshot {
|
||||
gaming_day: today.toISOString().slice(0, 10),
|
||||
day_starts_at: '06:00 local',
|
||||
seconds_used: used,
|
||||
budget_seconds: budgetSeconds,
|
||||
unlimited,
|
||||
budget_seconds: unlimited ? null : budgetSeconds,
|
||||
seconds_remaining: remaining,
|
||||
fraction_used: used / budgetSeconds,
|
||||
blocked: remaining <= 0,
|
||||
blocked_at: remaining <= 0 ? Math.floor(Date.now() / 1000) : 0,
|
||||
next_warning_seconds: remaining > 1800 ? 1800 : remaining > 600 ? 600 : null,
|
||||
warned_seconds: remaining <= 3600 ? [3600] : [],
|
||||
fraction_used: unlimited ? null : used / budgetSeconds,
|
||||
blocked: remaining !== null && remaining <= 0,
|
||||
blocked_at: remaining !== null && remaining <= 0 ? Math.floor(Date.now() / 1000) : 0,
|
||||
next_warning_seconds: remaining === null ? null : remaining > 1800 ? 1800 : remaining > 600 ? 600 : null,
|
||||
warned_seconds: remaining !== null && remaining <= 3600 ? [3600] : [],
|
||||
games: used > 0 ? slices : [],
|
||||
},
|
||||
session: {
|
||||
available: true,
|
||||
observed_at: new Date().toISOString(),
|
||||
state: remaining > 0 ? 'engaged' : 'blocked',
|
||||
state: remaining === null || remaining > 0 ? 'engaged' : 'blocked',
|
||||
game_name: 'Hades',
|
||||
billing_label: 'Hades',
|
||||
qualifying_count: 2,
|
||||
@ -73,10 +76,11 @@ export function budget(demo: boolean): BudgetSnapshot {
|
||||
history,
|
||||
legend: LEGEND,
|
||||
rules: {
|
||||
budget_seconds: budgetSeconds,
|
||||
unlimited,
|
||||
budget_seconds: unlimited ? null : budgetSeconds,
|
||||
enforcement: true,
|
||||
counts_launchers: true,
|
||||
warn_at: [3600, 1800, 600, 300],
|
||||
warn_at: unlimited ? [] : [3600, 1800, 600, 300],
|
||||
demo,
|
||||
masked_launchers: ['heroic', 'lutris'],
|
||||
},
|
||||
|
||||
@ -35,6 +35,14 @@ describe('budgetHistorySvg', () => {
|
||||
expect(svg.querySelectorAll('line.grid')).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('draws no budget line and scales to the tallest day when there is no budget', () => {
|
||||
const svg = render(budgetHistorySvg([day()], LEGEND, null))
|
||||
expect(svg.querySelector('line.budget-line')).toBeNull()
|
||||
expect(svg.querySelectorAll('rect.seg')).toHaveLength(1)
|
||||
// The only day fills the plot: nothing to measure it against.
|
||||
expect(num(svg.querySelector('rect.seg') ?? undefined, 'height')).toBeGreaterThan(100)
|
||||
})
|
||||
|
||||
it('stacks one band per game and colours it by legend position', () => {
|
||||
const svg = render(
|
||||
budgetHistorySvg(
|
||||
|
||||
@ -24,11 +24,13 @@ export function esc(text: string): string {
|
||||
const n = (v: number): string => String(v)
|
||||
|
||||
/** The chart for `days` (non-empty; the caller shows the empty state). */
|
||||
export function budgetHistorySvg(days: readonly BudgetHistoryDay[], legend: readonly BudgetLegendEntry[], budgetSeconds: number): string {
|
||||
export function budgetHistorySvg(days: readonly BudgetHistoryDay[], legend: readonly BudgetLegendEntry[], budgetSeconds: number | null): string {
|
||||
// Scaled against the budget rather than the tallest bar, so a single day
|
||||
// reads as "most of the allowance" instead of a lone full-height bar that
|
||||
// means nothing on its own.
|
||||
const maxSeconds = Math.max(budgetSeconds, ...days.map((d) => d.seconds)) || 1
|
||||
// With no budget (unlimited days) there is no allowance to scale against: the
|
||||
// tallest day fills the plot and no dashed line is drawn.
|
||||
const maxSeconds = Math.max(budgetSeconds ?? 0, ...days.map((d) => d.seconds)) || 1
|
||||
const plotW = W - PAD.left - PAD.right
|
||||
const plotH = H - PAD.top - PAD.bottom
|
||||
const sy = (seconds: number) => PAD.top + plotH - (seconds / maxSeconds) * plotH
|
||||
@ -43,7 +45,10 @@ export function budgetHistorySvg(days: readonly BudgetHistoryDay[], legend: read
|
||||
`<g><line x1="${n(PAD.left)}" y1="${n(sy(s))}" x2="${n(W - PAD.right)}" y2="${n(sy(s))}" class="grid"/>` +
|
||||
`<text x="${n(PAD.left - 8)}" y="${n(sy(s) + 4)}" class="axis-label end">${esc(fmtDuration(s))}</text></g>`,
|
||||
)
|
||||
const budgetLine = `<line x1="${n(PAD.left)}" y1="${n(sy(budgetSeconds))}" x2="${n(W - PAD.right)}" y2="${n(sy(budgetSeconds))}" class="budget-line"/>`
|
||||
const budgetLine =
|
||||
budgetSeconds === null
|
||||
? ''
|
||||
: `<line x1="${n(PAD.left)}" y1="${n(sy(budgetSeconds))}" x2="${n(W - PAD.right)}" y2="${n(sy(budgetSeconds))}" class="budget-line"/>`
|
||||
|
||||
const bars = days.flatMap((d, i) => {
|
||||
// Bands stack upwards from the axis in legend order, so a game keeps the
|
||||
|
||||
@ -123,13 +123,18 @@ export class BudgetGlanceElement extends LiveElement {
|
||||
const t = data.today
|
||||
const body = t
|
||||
? [
|
||||
h(
|
||||
'p',
|
||||
{ class: 'hero-num' },
|
||||
`${fmtDuration(t.seconds_remaining)} `,
|
||||
h('span', { class: 'muted' }, said(`left of ${fmtDuration(t.budget_seconds)}`, `/ ${fmtDuration(t.budget_seconds)}`)),
|
||||
),
|
||||
progressBar(t.fraction_used, 'Budget used', budgetTone(t.blocked, t.fraction_used)),
|
||||
// From 2026-11-16 there is no budget: the mark replaces the countdown and the bar.
|
||||
t.unlimited || t.fraction_used === null || t.budget_seconds === null
|
||||
? h('p', { class: 'hero-num' }, glyph('filter.no-cap', 'No gaming limit'))
|
||||
: [
|
||||
h(
|
||||
'p',
|
||||
{ class: 'hero-num' },
|
||||
`${fmtDuration(t.seconds_remaining ?? 0)} `,
|
||||
h('span', { class: 'muted' }, said(`left of ${fmtDuration(t.budget_seconds)}`, `/ ${fmtDuration(t.budget_seconds)}`)),
|
||||
),
|
||||
progressBar(t.fraction_used, 'Budget used', budgetTone(t.blocked, t.fraction_used)),
|
||||
],
|
||||
billingLine(t.blocked, data.session.billing_label),
|
||||
]
|
||||
: h('p', { class: 'text-danger' }, data.error ?? glyph('state.warn', 'Budget state unavailable.'))
|
||||
|
||||
18
web/src/sections/dashboard.unlimited.test.ts
Normal file
18
web/src/sections/dashboard.unlimited.test.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { screen } from '@testing-library/dom'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { makeBudget, makeBudgetToday } from '../test/factories'
|
||||
import { mount, stubApi } from '../test/harness'
|
||||
import './dashboard'
|
||||
|
||||
// From 2026-11-16 the backend sends no budget number: the glance paints the
|
||||
// no-limit mark and no bar, and still says what is billing.
|
||||
describe('budget glance on an unlimited day', () => {
|
||||
it('shows the no-limit mark, no progress bar, and the billing line', async () => {
|
||||
const today = makeBudgetToday({ unlimited: true, budget_seconds: null, seconds_remaining: null, fraction_used: null })
|
||||
stubApi({ 'GET /api/budget': makeBudget({ today }) })
|
||||
mount('<budget-glance></budget-glance>')
|
||||
expect(await screen.findByText('∞')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('progressbar', { name: 'Budget used' })).toBeNull()
|
||||
expect(screen.getByText('Now: Hollow Knight')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@ -60,11 +60,28 @@ function warningLine(today: BudgetToday, maskedCount: number): HTMLElement {
|
||||
: said(`Next warning at ${fmtDuration(next)} remaining.`, iconInline('gaming.warning'), ' ', fmtDuration(next))
|
||||
}
|
||||
|
||||
/** The "no limit" mark: the registry's no-cap icon. */
|
||||
const unlimitedMark = (): HTMLElement => glyph('filter.no-cap', 'No gaming limit')
|
||||
|
||||
function usageLine(t: BudgetToday): HTMLElement {
|
||||
const used = `${fmtDuration(t.seconds_used)} / ${fmtDuration(t.budget_seconds)} · ${Math.round(t.fraction_used * 100)}%`
|
||||
if (t.unlimited) {
|
||||
return said(
|
||||
`${fmtDuration(t.seconds_used)} played · gaming day ${t.gaming_day} (starts ${t.day_starts_at})`,
|
||||
fmtDuration(t.seconds_used),
|
||||
' · ',
|
||||
iconInline('gaming.day'),
|
||||
' ',
|
||||
t.gaming_day,
|
||||
' · ',
|
||||
iconInline('gaming.day_start'),
|
||||
' ',
|
||||
t.day_starts_at.replace(/\s*local$/, ''),
|
||||
)
|
||||
}
|
||||
const used = `${fmtDuration(t.seconds_used)} / ${fmtDuration(t.budget_seconds ?? 0)} · ${Math.round((t.fraction_used ?? 0) * 100)}%`
|
||||
const spoken =
|
||||
`${fmtDuration(t.seconds_used)} of ${fmtDuration(t.budget_seconds)} used · ` +
|
||||
`${Math.round(t.fraction_used * 100)}% · gaming day ${t.gaming_day} (starts ${t.day_starts_at})`
|
||||
`${fmtDuration(t.seconds_used)} of ${fmtDuration(t.budget_seconds ?? 0)} used · ` +
|
||||
`${Math.round((t.fraction_used ?? 0) * 100)}% · gaming day ${t.gaming_day} (starts ${t.day_starts_at})`
|
||||
return said(
|
||||
spoken,
|
||||
used,
|
||||
@ -81,19 +98,25 @@ function usageLine(t: BudgetToday): HTMLElement {
|
||||
|
||||
export function todayCard(today: BudgetToday, legend: readonly BudgetLegendEntry[], maskedCount: number): HTMLElement {
|
||||
// Colour by the chart's legend position so a game reads the same in both
|
||||
// places; today can hold games the capped 14-day legend left out, and those
|
||||
// fall back to their own row order.
|
||||
// places; games the capped legend left out fall back to their row order.
|
||||
const indexFor = new Map(legend.map((e, i) => [e.key, i]))
|
||||
const fill = h('div', { class: 'budget-meter-fill' })
|
||||
fill.style.width = `${(today.fraction_used * 100).toFixed(1)}%`
|
||||
fill.style.width = `${((today.fraction_used ?? 0) * 100).toFixed(1)}%`
|
||||
const unlimited = today.unlimited
|
||||
return h(
|
||||
'section',
|
||||
{ class: 'budget-today' },
|
||||
h('h2', {}, glyph('gaming.today', 'Today')),
|
||||
h('p', { class: 'budget-hero' }, h('strong', {}, fmtDuration(today.seconds_remaining)), h('span', { class: 'sr-only' }, ' left')),
|
||||
h('div', { class: `budget-meter budget-meter--${meterState(today)}` }, fill),
|
||||
h(
|
||||
'p',
|
||||
{ class: 'budget-hero' },
|
||||
h('strong', {}, unlimited ? unlimitedMark() : fmtDuration(today.seconds_remaining ?? 0)),
|
||||
unlimited ? null : h('span', { class: 'sr-only' }, ' left'),
|
||||
),
|
||||
// No budget, no meter and no warnings: there is nothing to fill or warn of.
|
||||
unlimited ? null : h('div', { class: `budget-meter budget-meter--${meterState(today)}` }, fill),
|
||||
h('p', { class: 'hint' }, usageLine(today)),
|
||||
h('p', { class: 'hint' }, warningLine(today, maskedCount)),
|
||||
unlimited ? null : h('p', { class: 'hint' }, warningLine(today, maskedCount)),
|
||||
today.games.length > 0
|
||||
? [
|
||||
h('h3', { class: 'budget-subhead' }, glyph('gaming.by_game', 'Today by game')),
|
||||
@ -171,7 +194,7 @@ export function liveCard(session: BudgetSession): HTMLElement {
|
||||
)
|
||||
}
|
||||
|
||||
export function historyCard(days: readonly BudgetHistoryDay[], legend: readonly BudgetLegendEntry[], budgetSeconds: number): HTMLElement {
|
||||
export function historyCard(days: readonly BudgetHistoryDay[], legend: readonly BudgetLegendEntry[], budgetSeconds: number | null): HTMLElement {
|
||||
const title = h('h2', {}, glyph('gaming.history', 'Last 14 days'))
|
||||
if (days.length === 0) {
|
||||
return h(
|
||||
@ -216,10 +239,10 @@ export function rulesCard(rules: BudgetRules): HTMLElement {
|
||||
h(
|
||||
'dl',
|
||||
{ class: 'budget-rules-list' },
|
||||
row('gaming.budget', 'Daily budget', fmtDuration(rules.budget_seconds)),
|
||||
row('gaming.budget', 'Daily budget', rules.budget_seconds === null ? unlimitedMark() : fmtDuration(rules.budget_seconds)),
|
||||
row('gaming.enforcement', 'Enforcement', onOff(rules.enforcement, 'on', 'off')),
|
||||
row('gaming.launcher', 'Counts launchers', onOff(rules.counts_launchers, 'yes', 'no')),
|
||||
row('gaming.warning', 'Warnings at', said(`${warn} remaining`, warn)),
|
||||
rules.warn_at.length > 0 ? row('gaming.warning', 'Warnings at', said(`${warn} remaining`, warn)) : null,
|
||||
rules.demo ? row('gaming.mode', 'Mode', glyph('gaming.demo', 'demo (short budget, separate state)')) : null,
|
||||
rules.masked_launchers.length > 0 ? row('gaming.masked', 'Masked now', rules.masked_launchers.join(', ')) : null,
|
||||
),
|
||||
|
||||
47
web/src/sections/gaming/cards.unlimited.test.ts
Normal file
47
web/src/sections/gaming/cards.unlimited.test.ts
Normal file
@ -0,0 +1,47 @@
|
||||
import { screen } from '@testing-library/dom'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { makeBudgetRules, makeBudgetToday } from '../../test/factories'
|
||||
import { rulesCard, todayCard } from './cards'
|
||||
|
||||
const show = (el: HTMLElement) => {
|
||||
document.body.replaceChildren(el)
|
||||
}
|
||||
|
||||
// From 2026-11-16 the backend sends no budget number at all.
|
||||
const unlimitedToday = () =>
|
||||
makeBudgetToday({
|
||||
unlimited: true,
|
||||
budget_seconds: null,
|
||||
seconds_remaining: null,
|
||||
fraction_used: null,
|
||||
next_warning_seconds: null,
|
||||
seconds_used: 40_000,
|
||||
})
|
||||
|
||||
describe('unlimited day', () => {
|
||||
it('paints infinity, no meter, no warning line, no percentage', () => {
|
||||
show(todayCard(unlimitedToday(), [], 0))
|
||||
expect(screen.getByText('∞')).toBeInTheDocument()
|
||||
expect(document.querySelector('.budget-meter')).toBeNull()
|
||||
expect(document.body.textContent).not.toMatch(/warning/i)
|
||||
expect(document.querySelector('.budget-hero')?.textContent).not.toMatch(/%|left/)
|
||||
expect(document.querySelector('.hint')?.textContent).not.toMatch(/%/)
|
||||
expect(document.body.textContent).toContain('11h 6m')
|
||||
})
|
||||
|
||||
it('keeps showing what was billed, by game', () => {
|
||||
show(todayCard(unlimitedToday(), [], 0))
|
||||
expect(screen.getByText('Hollow Knight')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('rules: no daily budget and no warning thresholds', () => {
|
||||
show(rulesCard(makeBudgetRules({ unlimited: true, budget_seconds: null, warn_at: [] })))
|
||||
expect(screen.getByText('∞')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Warnings at')).toBeNull()
|
||||
})
|
||||
|
||||
it('an enforced day still has its meter', () => {
|
||||
show(todayCard(makeBudgetToday(), [], 0))
|
||||
expect(document.querySelector('.budget-meter')).not.toBeNull()
|
||||
})
|
||||
})
|
||||
@ -108,6 +108,7 @@ export function makeBudgetToday(over: Partial<BudgetToday> = {}): BudgetToday {
|
||||
gaming_day: '2026-08-28',
|
||||
day_starts_at: '06:00 local',
|
||||
seconds_used: 3600,
|
||||
unlimited: false,
|
||||
budget_seconds: 28800,
|
||||
seconds_remaining: 25200,
|
||||
fraction_used: 0.125,
|
||||
@ -137,6 +138,7 @@ export function makeBudgetSession(over: Partial<BudgetSession> = {}): BudgetSess
|
||||
|
||||
export function makeBudgetRules(over: Partial<BudgetRules> = {}): BudgetRules {
|
||||
return {
|
||||
unlimited: false,
|
||||
budget_seconds: 28800,
|
||||
enforcement: true,
|
||||
counts_launchers: true,
|
||||
|
||||
@ -104,10 +104,12 @@ export interface BudgetToday {
|
||||
gaming_day: string
|
||||
day_starts_at: string
|
||||
seconds_used: number
|
||||
budget_seconds: number
|
||||
seconds_remaining: number
|
||||
/** 0..1, already clamped by the backend. */
|
||||
fraction_used: number
|
||||
/** True from 2026-11-16: no gaming budget, so the three fields below are null. */
|
||||
unlimited: boolean
|
||||
budget_seconds: number | null
|
||||
seconds_remaining: number | null
|
||||
/** 0..1, already clamped by the backend; null when unlimited. */
|
||||
fraction_used: number | null
|
||||
blocked: boolean
|
||||
/** Epoch seconds; 0 means the cutoff has not engaged. */
|
||||
blocked_at: number
|
||||
@ -167,7 +169,8 @@ export interface BudgetLegendEntry {
|
||||
}
|
||||
|
||||
export interface BudgetRules {
|
||||
budget_seconds: number
|
||||
unlimited: boolean
|
||||
budget_seconds: number | null
|
||||
enforcement: boolean
|
||||
counts_launchers: boolean
|
||||
warn_at: number[]
|
||||
|
||||
Loading…
Reference in New Issue
Block a user