From 4d5dbc6acc5d5533900d3afe5e8cf3ab251df229 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 22:37:11 -0600 Subject: [PATCH 01/20] docs: fix pack v2 format - the contract for Diagnose rules Diagnose needs fixes that match on a log line and on the machine, not only on an App ID, and that cannot turn pack data into shell text. This is the schema the loader and its test will enforce; the code follows. Co-Authored-By: Claude Fable 5.2 --- docs/fix-pack.md | 176 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 docs/fix-pack.md diff --git a/docs/fix-pack.md b/docs/fix-pack.md new file mode 100644 index 0000000..a6eccd5 --- /dev/null +++ b/docs/fix-pack.md @@ -0,0 +1,176 @@ +# Fix pack format (version 2) + +The fix pack is the knowledge behind Diagnose: a list of rules, each of which +recognises one situation (a line in the Proton log, a setting, a known game) +and says what it means and what to change. This document is the contract for +that file. `protonshift/core/fix_pack.py` loads and validates it, and +`tests/test_fix_pack.py` fails the build when the bundled pack breaks any rule +written here. Change this document first, then the code. + +The bundled pack is `protonshift/core/data/fix_pack.json`. Fixes a user adds +for themselves stay in `~/.config/protonshift/fixes/.json` in the +version 1 shape (see "User fixes" below). + +## Why the format is strict + +Steam hands a game's launch options to a shell. A rule that could write any +text into them would be a way to run any command the next time the game +starts. So a rule cannot contain free text that reaches the launch options: +it can only name an environment variable, a value from a narrow character +set, a single game argument, or a wrapper to remove. Everything a rule would +change is shown to the user before it is applied, and a snapshot is saved so +it can be undone. + +The same rules apply to the bundled pack as to any pack loaded later from +elsewhere. Nothing here is relaxed because the file ships with the app. + +## File shape + +```json +{ + "format": "protonshift-fix-pack", + "version": 2, + "revision": "2026.11.1", + "rules": [ { "...": "one rule, see below" } ] +} +``` + +- `format` must be exactly `protonshift-fix-pack`. +- `version` is the schema version, an integer. A pack with a higher version + than the app understands is rejected whole. +- `revision` names this edition of the data: `YYYY.MM.N`. +- `rules` is a list. A rule that fails validation is dropped and reported; + the other rules still load. (The test suite is stricter than the loader: + for the bundled pack, any invalid rule fails the build.) + +## A rule + +```json +{ + "id": "wrapper-gamemoderun-missing", + "title": "GameMode is in the launch options but is not installed", + "cause": "Steam runs the game through gamemoderun, which was not found, so the game never starts.", + "severity": "blocking", + "match": { + "app_ids": ["1091500"], + "log": ["wine: could not load kernel32\\.dll"], + "when": { "gpu_vendor": ["nvidia"], "session": ["wayland"] } + }, + "actions": [ + { "type": "env", "key": "PROTON_ENABLE_NVAPI", "value": "1" } + ], + "source": "https://github.com/ValveSoftware/Proton/issues/0000", + "verified": "2026-11-16" +} +``` + +| field | required | meaning | +|---|---|---| +| `id` | yes | Unique in the pack. Lowercase letters, digits and hyphens, 3 to 64 characters. | +| `title` | yes | What is wrong, in plain words, at most 100 characters. | +| `cause` | yes | One or two sentences a player can follow, at most 400 characters. | +| `severity` | yes | `blocking` (the game will not start), `likely` (probably the reason for the trouble), or `advice` (a known tweak; nothing is wrong). | +| `match` | yes | When the rule applies. See "Matching". | +| `actions` | yes | What to change. May be empty for a rule that only explains. See "Actions". | +| `source` | yes | An `https://` URL where the situation and the remedy can be checked: upstream source code, a public issue, or project documentation. | +| `verified` | yes | The date (`YYYY-MM-DD`) someone last checked the rule against its source. | + +Titles and causes are plain text. They are shown as text, never as markup. + +## Matching + +`match` holds up to three parts. Every part that is present must hold. +At least one of `app_ids` and `log`, or a `when` that uses `launch_has` or +`env_set`, must be present: a rule that matches every game on every machine +is not a rule. + +- `app_ids`: a list of Steam App IDs (decimal digits only). The rule applies + to those games. Absent means any game. +- `log`: a list of regular expressions (Python `re` syntax). The rule matches + when any one of them is found in any single line of the log tail. Each + expression must compile, must be at most 300 characters, and must contain + at least 8 literal characters in a row, so that it is anchored on real text + and not on a pattern that fits half the log. Matching is case sensitive. + With no log on disk, a rule that has a `log` part does not match. +- `when`: conditions on the machine and the game's settings. All listed + conditions must hold. + +| condition | value | holds when | +|---|---|---| +| `gpu_vendor` | list of `nvidia`, `amd`, `intel` | any GPU of a listed vendor is present | +| `session` | list of `wayland`, `x11` | the desktop session is of a listed type | +| `proton_family` | list of `valve`, `ge`, `cachyos`, `other` | the game's Proton build belongs to a listed family | +| `proton_major_min` | integer | the build's major version is at least this | +| `proton_major_max` | integer | the build's major version is at most this | +| `launch_has` | list of words | every listed word is in the launch options before `%command%`, as a command name (`gamemoderun`) | +| `env_set` | list of variable names | every listed variable is set in the launch options | +| `env_unset` | list of variable names | none of the listed variables is set in the launch options | + +A fact the app could not find out never satisfies a condition. A game on +Steam's default Proton has no known family or version, so a rule with +`proton_major_max` does not match it. Diagnose prefers a missed finding to a +false one. + +A rule with `app_ids` and no `log` is a known tweak for that game. It must +have severity `advice`. + +## Actions + +Each action is one small, reversible change to the game's settings, or an +instruction for the user. A rule may list several; they are applied together +and undone together. + +| `type` | fields | effect | +|---|---|---| +| `env` | `key`, `value` | Set `KEY=value` in the launch options, before `%command%`. Replaces an existing assignment of the same key. | +| `unset_env` | `key` | Remove the assignment of `KEY` from the launch options. | +| `game_arg` | `value` | Add one argument for the game, after `%command%`. | +| `remove_word` | `value` | Remove a wrapper command (for example `gamemoderun`) from before `%command%`. | +| `default_proton` | none | Stop forcing a Proton build for this game; Steam picks one. | +| `manual` | `text` | Nothing is changed. The text tells the user what to do (install a package, verify game files). At most 300 characters. | + +Limits, enforced by the loader: + +- `key` matches `^[A-Za-z_][A-Za-z0-9_]*$`. +- `value` for `env` matches `^[A-Za-z0-9_.,:=/+@%-]{0,200}$`. No spaces, no + quotes, no shell characters. +- `value` for `game_arg` matches `^[-+][A-Za-z0-9_.=:-]{1,60}$` (one switch, + such as `-vulkan` or `+fps_max=0`). +- `value` for `remove_word` matches `^[A-Za-z0-9_.-]{1,40}$`. +- A rule has at most 6 actions. +- These variables may never be set or unset by a rule, because they decide + what code a process loads or runs: `LD_PRELOAD`, `LD_LIBRARY_PATH`, + `LD_AUDIT`, `PATH`, `PYTHONPATH`, `STEAM_COMPAT_LAUNCHER_SERVICE`, + `WINEDLLPATH`, and any name starting with `STEAM_COMPAT_`. + +A game argument can only be placed after `%command%`; there is no action +that puts text in front of it other than `env`. This is by construction, so a +rule cannot repeat the version 1 mistake of writing `-vulkan %command%`. + +## User fixes + +A file under `~/.config/protonshift/fixes/.json` is a list of +version 1 entries: + +```json +[ { "title": "...", "description": "...", "type": "env", "key": "DXVK_HUD", "value": "fps" } ] +``` + +`type` is `env` (uses `key` and `value`) or `launch_arg` (uses `value`). +Each entry is shown in Diagnose as an `advice` finding marked as the user's +own. A user entry is the user's own text on the user's own machine, so its +value is not held to the character limits above; the key still must match +the key pattern, and the change is still shown before it is applied. A +`launch_arg` value that contains `%command%` is merged the way the app merges +any snippet; one without it is treated as game arguments. + +## Adding a rule + +1. Find the source: the line in upstream code that prints the message, a + public issue where the fix was confirmed, or a documentation page. +2. Write the narrowest match that fits. For a log rule, copy the fixed part + of the message; do not match on `err:` or `fixme:` alone. +3. Check that the line does not also appear in the log of a game that runs + fine. Many `fixme:` and some `err:` lines do. +4. Add the rule to `fix_pack.json`, set `verified` to today, bump `revision`. +5. Run `pytest tests/test_fix_pack.py`. From 03dcc89888059265db8f0d780cebc5741cc7025d Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 22:37:56 -0600 Subject: [PATCH 02/20] docs: fix pack - bound the cost of a log expression Co-Authored-By: Claude Fable 5.2 --- docs/fix-pack.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/fix-pack.md b/docs/fix-pack.md index a6eccd5..75c80b8 100644 --- a/docs/fix-pack.md +++ b/docs/fix-pack.md @@ -90,7 +90,10 @@ is not a rule. when any one of them is found in any single line of the log tail. Each expression must compile, must be at most 300 characters, and must contain at least 8 literal characters in a row, so that it is anchored on real text - and not on a pattern that fits half the log. Matching is case sensitive. + and not on a pattern that fits half the log. An expression must not repeat + a group that itself contains a repeat (for example `(a+)+`), because such + a pattern can take a very long time on a long line. Matching is case + sensitive, and only the first 2000 characters of a line are looked at. With no log on disk, a rule that has a `log` part does not match. - `when`: conditions on the machine and the game's settings. All listed conditions must hold. From 1430b6a49a579d3da0d376ed9f5aeb394211e927 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 22:42:56 -0600 Subject: [PATCH 03/20] docs: fix pack - log_also, for lines that only mean trouble together Upstream source shows several Wine and DXVK error lines are printed by healthy runs as well. A rule needs a way to require the confirming line. Co-Authored-By: Claude Fable 5.2 --- docs/fix-pack.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/fix-pack.md b/docs/fix-pack.md index 75c80b8..30b1f68 100644 --- a/docs/fix-pack.md +++ b/docs/fix-pack.md @@ -79,7 +79,7 @@ Titles and causes are plain text. They are shown as text, never as markup. ## Matching -`match` holds up to three parts. Every part that is present must hold. +`match` holds up to four parts. Every part that is present must hold. At least one of `app_ids` and `log`, or a `when` that uses `launch_has` or `env_set`, must be present: a rule that matches every game on every machine is not a rule. @@ -95,6 +95,14 @@ is not a rule. a pattern can take a very long time on a long line. Matching is case sensitive, and only the first 2000 characters of a line are looked at. With no log on disk, a rule that has a `log` part does not match. +- `log_also`: a list of regular expressions under the same limits. Every one + of them must also be found somewhere in the log tail, each in any line. + It is only allowed together with `log`. Use it for a line that healthy + games print too and that means trouble only next to another line: Wine + reports a missing library for helper processes of games that run fine, so + the missing-library rule also requires the line that says the game's own + start failed. The line quoted to the user as evidence is the one `log` + matched. - `when`: conditions on the machine and the game's settings. All listed conditions must hold. From 673c7d2656187406aabce244e5b9a2c730ace6f7 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 22:46:11 -0600 Subject: [PATCH 04/20] feat(core): system checks and the snapshot store behind Undo Diagnose needs two things no module had: facts about the machine that explain a game not starting (Vulkan, a 32-bit Vulkan driver, free disk), and a record of every change it makes so Undo can put a game back exactly, even after a restart. Each check has three states. One that cannot be carried out says so and never reports ok on a guess: inside the Flatpak the host's /etc is not visible, vulkaninfo may be missing, and Flatpak Steam brings its own drivers. The snapshot store treats the app id as untrusted, since it becomes a file name, and discards entries with newlines on read as well as on write, because Undo feeds them to Steam's config. Co-Authored-By: Claude Fable 5.2 --- protonshift/core/snapshots.py | 257 ++++++++++++++++ protonshift/core/system_checks.py | 481 ++++++++++++++++++++++++++++++ tests/test_snapshots.py | 237 +++++++++++++++ tests/test_system_checks.py | 458 ++++++++++++++++++++++++++++ 4 files changed, 1433 insertions(+) create mode 100644 protonshift/core/snapshots.py create mode 100644 protonshift/core/system_checks.py create mode 100644 tests/test_snapshots.py create mode 100644 tests/test_system_checks.py diff --git a/protonshift/core/snapshots.py b/protonshift/core/snapshots.py new file mode 100644 index 0000000..f2bdca2 --- /dev/null +++ b/protonshift/core/snapshots.py @@ -0,0 +1,257 @@ +"""Snapshots: the before and after of every change Diagnose makes, so Undo can put it back. + +Before a one-click fix touches a game's launch options or compatibility tool, the +caller records a snapshot here; Undo reads the latest one, restores ``before`` +and drops it. Snapshots live on disk (one JSON file per game under +``~/.config/protonshift/snapshots``) so Undo still works after a restart. + +``record`` raising means the snapshot was not saved, and the caller must then +refuse to apply the fix: a change that cannot be undone is not one-click. + +Security boundary: ``app_id`` becomes a file name. Steam app ids and non-Steam +shortcut ids are decimal, so only ``^[0-9]{1,20}$`` is accepted and the final +path is verified to stay inside the snapshot folder. Values read back are fed +to Steam's config by Undo, so entries carrying newlines or NULs are discarded +on read as well as refused on write. +""" + +from __future__ import annotations + +import json +import re +import secrets +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path + +from .fsutil import atomic_write_text +from .paths import PathValidationError, validate_within + +MAX_PER_GAME = 20 +FORMAT = "protonshift-snapshots" +VERSION = 1 +LABEL_MAX = 200 + +_APP_ID_RE = re.compile(r"[0-9]{1,20}") +_BAD_CHARS = ("\n", "\r", "\x00") +# A full history is a few kilobytes; a file far past this is not ours. +_MAX_FILE_BYTES = 1 << 20 + + +@dataclass(frozen=True) +class GameState: + launch_options: str + compat_tool: str # "" means Steam's default + + +@dataclass(frozen=True) +class Snapshot: + id: str + taken_at: str + app_id: str + label: str + finding_id: str + before: GameState + after: GameState + + +def snapshot_dir() -> Path: + # Resolved per call, not at import, so tests can point HOME somewhere else. + return Path.home() / ".config" / "protonshift" / "snapshots" + + +def _valid_app_id(app_id: object) -> bool: + return isinstance(app_id, str) and _APP_ID_RE.fullmatch(app_id) is not None + + +def _snapshot_file(app_id: object) -> Path | None: + """The game's snapshot file, or ``None`` when ``app_id`` is not a safe decimal id.""" + if not _valid_app_id(app_id): + return None + base = snapshot_dir() + name = f"{app_id}.json" + try: + path = validate_within(base, base / name) + except (PathValidationError, OSError, RuntimeError): + return None + # A symlink to another game's file would stay inside the folder yet mix two histories. + return path if path.name == name else None + + +def _clean(value: object) -> bool: + return isinstance(value, str) and not any(c in value for c in _BAD_CHARS) + + +def _state_to_dict(state: GameState) -> dict[str, str]: + return {"launch_options": state.launch_options, "compat_tool": state.compat_tool} + + +def _state_from_dict(raw: object) -> GameState | None: + if not isinstance(raw, dict): + return None + lo, ct = raw.get("launch_options"), raw.get("compat_tool") + if not (_clean(lo) and _clean(ct)): + return None + return GameState(launch_options=lo, compat_tool=ct) + + +def _to_dict(s: Snapshot) -> dict[str, object]: + return { + "id": s.id, + "taken_at": s.taken_at, + "app_id": s.app_id, + "label": s.label, + "finding_id": s.finding_id, + "before": _state_to_dict(s.before), + "after": _state_to_dict(s.after), + } + + +def _from_dict(raw: object, app_id: str) -> Snapshot | None: + """One entry, or ``None`` when any part of it is missing, mistyped or unsafe.""" + if not isinstance(raw, dict): + return None + fields = {k: raw.get(k) for k in ("id", "taken_at", "app_id", "label", "finding_id")} + if not all(_clean(v) for v in fields.values()): + return None + # An entry filed under another game's id must never be applied to this one. + if fields["app_id"] != app_id or not fields["id"]: + return None + before, after = _state_from_dict(raw.get("before")), _state_from_dict(raw.get("after")) + if before is None or after is None: + return None + return Snapshot( + id=fields["id"], + taken_at=fields["taken_at"], + app_id=app_id, + label=fields["label"][:LABEL_MAX], + finding_id=fields["finding_id"], + before=before, + after=after, + ) + + +class _BadFile(Exception): + """The snapshot file exists but is not a snapshot file we can read.""" + + +def _load(path: Path, app_id: str) -> list[Snapshot]: + """Entries oldest first. ``[]`` when there is no file; ``_BadFile`` when it's unusable.""" + try: + if not path.exists(): + return [] + if path.stat().st_size > _MAX_FILE_BYTES: + raise _BadFile + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise _BadFile from exc + if ( + not isinstance(data, dict) + or data.get("format") != FORMAT + or data.get("version") != VERSION + or not isinstance(data.get("entries"), list) + ): + raise _BadFile + out: list[Snapshot] = [] + for raw in data["entries"]: + snap = _from_dict(raw, app_id) + if snap is not None: + out.append(snap) + return out + + +def _save(path: Path, entries: list[Snapshot]) -> None: + payload = {"format": FORMAT, "version": VERSION, "entries": [_to_dict(s) for s in entries]} + atomic_write_text(path, json.dumps(payload, indent=2, ensure_ascii=False) + "\n") + + +def _now() -> datetime: + return datetime.now(UTC).replace(microsecond=0) + + +def _set_aside(path: Path) -> None: + """Rename an unreadable file out of the way, keeping it for the user to inspect.""" + stamp = _now().strftime("%Y%m%dT%H%M%SZ") + target = path.with_name(f"{path.name}.corrupt-{stamp}") + if target.exists(): + target = path.with_name(f"{path.name}.corrupt-{stamp}-{secrets.token_hex(3)}") + path.rename(target) + + +def record(app_id: str, label: str, finding_id: str, before: GameState, after: GameState) -> Snapshot: + """Save a snapshot and return it. ValueError on bad input, OSError when it can't be written.""" + path = _snapshot_file(app_id) + if path is None: + raise ValueError(f"not a valid app id: {app_id!r}") + for name, value in ( + ("label", label), + ("finding_id", finding_id), + ("before.launch_options", getattr(before, "launch_options", None)), + ("before.compat_tool", getattr(before, "compat_tool", None)), + ("after.launch_options", getattr(after, "launch_options", None)), + ("after.compat_tool", getattr(after, "compat_tool", None)), + ): + if not isinstance(value, str): + # ValueError, not TypeError: callers treat every refused input the same way. + raise ValueError(f"{name} must be a string") # noqa: TRY004 + if not _clean(value): + raise ValueError(f"{name} must not contain a newline, carriage return or NUL") + + try: + entries = _load(path, app_id) + except _BadFile: + # Refusing here would block every fix for this game, and overwriting would + # lose whatever the file held, so it is kept beside the new one instead. + _set_aside(path) + entries = [] + + now = _now() + snap = Snapshot( + id=f"{now.strftime('%Y%m%dT%H%M%SZ')}-{secrets.token_hex(3)}", + taken_at=now.isoformat(), + app_id=app_id, + label=label[:LABEL_MAX], + finding_id=finding_id, + before=GameState(before.launch_options, before.compat_tool), + after=GameState(after.launch_options, after.compat_tool), + ) + entries.append(snap) + _save(path, entries[-MAX_PER_GAME:]) + return snap + + +def history(app_id: str) -> list[Snapshot]: + """The game's snapshots, newest first. ``[]`` for a bad id or an unreadable file.""" + path = _snapshot_file(app_id) + if path is None: + return [] + try: + entries = _load(path, app_id) + except _BadFile: + return [] + # File order is recording order; timestamps tie within a second, so they don't decide. + return list(reversed(entries)) + + +def latest(app_id: str) -> Snapshot | None: + entries = history(app_id) + return entries[0] if entries else None + + +def drop(app_id: str, snapshot_id: str) -> bool: + """Remove one snapshot (after its undo worked). False when there was nothing to remove.""" + path = _snapshot_file(app_id) + if path is None or not isinstance(snapshot_id, str): + return False + try: + entries = _load(path, app_id) + except _BadFile: + return False + kept = [s for s in entries if s.id != snapshot_id] + if len(kept) == len(entries): + return False + try: + _save(path, kept) + except OSError: + return False + return True diff --git a/protonshift/core/system_checks.py b/protonshift/core/system_checks.py new file mode 100644 index 0000000..1c22930 --- /dev/null +++ b/protonshift/core/system_checks.py @@ -0,0 +1,481 @@ +"""System checks for Diagnose: facts about this computer that explain a game not starting. + +Launch check looks at one game's settings; these look at the machine under every +game: is there a working Vulkan driver, is there a 32-bit one for 32-bit games and +launchers, is there free space where the game and its Proton prefix live. + +Every check answers in three states: ``ok``, ``problem`` or ``unknown``. The rule +that shapes all of them: a check that could not actually be carried out says +``unknown`` and why. It never says ``ok`` on a guess, because a green tick that +is wrong sends the user looking everywhere except the real cause. Functions here +never raise; whatever goes wrong becomes an ``unknown`` result. + +Host commands go through :func:`host.host_run` so they reach the host from inside +the Flatpak, and the host's files are read under ``/run/host`` there. The runner +is injectable so tests never start a real process. +""" + +from __future__ import annotations + +import json +import os +import re +import shutil +import subprocess +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from pathlib import Path + +from .host import host_run, in_flatpak +from .steam import FLATPAK_HOST_ROOT, host_display_path + +Runner = Callable[..., subprocess.CompletedProcess] + +OK = "ok" +PROBLEM = "problem" +UNKNOWN = "unknown" + +_TIMEOUT = 5 +_FLATPAK_STEAM_PARTS = (".var", "app", "com.valvesoftware.Steam") +# Driver manifests are a few hundred bytes; anything far larger is not one. +_MAX_MANIFEST_BYTES = 64 * 1024 + + +@dataclass(frozen=True) +class Check: + id: str + state: str + title: str + detail: str + fix: str + + +# --------------------------------------------------------------------------- # +# Steam +# --------------------------------------------------------------------------- # + +def _has_flatpak_steam_parts(path: Path) -> bool: + parts = path.parts + n = len(_FLATPAK_STEAM_PARTS) + return any(parts[i:i + n] == _FLATPAK_STEAM_PARTS for i in range(len(parts) - n + 1)) + + +def steam_flavor(steam_root: Path | None) -> str: + """``"flatpak"`` for Flathub's Steam, ``"native"`` for any other existing root, else ``"unknown"``.""" + if steam_root is None: + return "unknown" + try: + root = Path(steam_root) + if not root.exists(): + return "unknown" + # ~/.steam/steam is often a symlink, so the resolved path decides as well. + if _has_flatpak_steam_parts(root) or _has_flatpak_steam_parts(root.resolve()): + return "flatpak" + return "native" + except (OSError, RuntimeError, TypeError, ValueError): + return "unknown" + + +def steam_running(run: Runner = host_run) -> bool | None: + """Whether Steam is running; ``None`` when that could not be found out.""" + try: + proc = run(["pgrep", "-x", "steam"], capture_output=True, text=True, timeout=_TIMEOUT) + except (OSError, subprocess.SubprocessError, ValueError): + return None + if proc.returncode == 0: + return True + if proc.returncode == 1: + return False + return None + + +# --------------------------------------------------------------------------- # +# Vulkan +# --------------------------------------------------------------------------- # + +def _host_path(path: Path) -> Path: + """``path`` as seen from here: under ``/run/host`` inside the Flatpak.""" + if in_flatpak() and path.is_absolute(): + return FLATPAK_HOST_ROOT / path.relative_to("/") + return path + + +def default_icd_dirs() -> list[Path]: + system = [Path("/usr/share/vulkan/icd.d"), Path("/etc/vulkan/icd.d")] + return [_host_path(d) for d in system] + [Path.home() / ".local/share/vulkan/icd.d"] + + +def _icd_manifests(icd_dirs: Sequence[Path]) -> list[Path]: + found: list[Path] = [] + for d in icd_dirs: + try: + found.extend(sorted(p for p in Path(d).glob("*.json") if p.is_file())) + except OSError: + continue + return found + + +def _could_look(icd_dirs: Sequence[Path]) -> bool: + """True when the main ICD folder's parent tree (the first in the list) is visible to us. + + Inside a sandbox without the host-os permission, ``/run/host/usr/share`` is + simply absent; finding no manifests there is not evidence that none exist. + Only the first folder counts: ``~/.local/share`` always exists, so it would + vouch for a search that never saw the system's drivers. + """ + if not icd_dirs: + return False + try: + return Path(icd_dirs[0]).parent.parent.is_dir() + except OSError: + return False + + +_SOFTWARE_NAMES = ("llvmpipe", "lavapipe", "softpipe", "swiftshader") +_HARDWARE_TYPES = ( + "PHYSICAL_DEVICE_TYPE_DISCRETE_GPU", + "PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU", + "PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU", +) +_GPU_HEADER_RE = re.compile(r"^\s*GPU\s*(\d+)\s*:\s*$") +_FIELD_RE = re.compile(r"^\s*(deviceType|deviceName)\s*=\s*(.+?)\s*$") + +# Loader and vulkaninfo wording when Vulkan itself cannot start (no driver, or a +# driver that does not load). Matched case-insensitively. +_DRIVER_FAILURE_MARKERS = ( + "error_incompatible_driver", + "error_initialization_failed", + "found no drivers", + "cannot create vulkan instance", + "vkenumeratephysicaldevices failed", + "failed to find a physical device", +) +# How a missing host tool shows up through flatpak-spawn (it exists, the host tool doesn't). +_TOOL_MISSING_MARKERS = ( + "failed to execute child process", + "failed to start command", + "command not found", +) + + +def _parse_devices(text: str) -> list[tuple[str, str]]: + """``(deviceType, deviceName)`` per ``GPUn:`` block of ``vulkaninfo --summary``. + + Only the ``Devices:`` section's ``GPUn:`` blocks are read, and only two keys + in them; both have been stable across vulkaninfo versions for years. A missing + key comes back as ``""`` so the caller can refuse to judge that device. + """ + devices: list[list[str]] = [] + for line in text.splitlines(): + if _GPU_HEADER_RE.match(line): + devices.append(["", ""]) + continue + if not devices: + continue + m = _FIELD_RE.match(line) + if m: + idx = 0 if m.group(1) == "deviceType" else 1 + if not devices[-1][idx]: + devices[-1][idx] = m.group(2) + return [(t, n) for t, n in devices] + + +def _is_software(dev_type: str, name: str) -> bool: + return "TYPE_CPU" in dev_type or any(s in name.lower() for s in _SOFTWARE_NAMES) + + +def _is_hardware(dev_type: str, name: str) -> bool: + return dev_type in _HARDWARE_TYPES and bool(name) and not _is_software(dev_type, name) + + +def _first_line(text: str, markers: Sequence[str]) -> str: + for line in text.splitlines(): + low = line.lower() + if any(m in low for m in markers): + return line.strip()[:200] + return "" + + +_VULKAN_UNKNOWN = "Couldn't check Vulkan" + + +def _vulkan_from_manifests(icd_dirs: Sequence[Path]) -> Check: + manifests = _icd_manifests(icd_dirs) + if manifests: + return Check( + "vulkan", UNKNOWN, _VULKAN_UNKNOWN, + "Vulkan driver files were found, but the tool that tests them (vulkaninfo, usually in " + "the vulkan-tools package) is not installed, so ProtonShift can't tell whether they work.", + "Install vulkan-tools from your distribution if you want this checked.", + ) + if not _could_look(icd_dirs): + return Check( + "vulkan", UNKNOWN, _VULKAN_UNKNOWN, + "ProtonShift can't see the folders where Vulkan drivers are installed, and vulkaninfo " + "isn't available to ask instead.", + "", + ) + return Check( + "vulkan", PROBLEM, "No Vulkan driver is installed", + "No Vulkan driver files were found on this computer. Games that run through Proton need " + "Vulkan, so they won't start without one.", + "Install the Vulkan driver for your graphics card from your distribution (Mesa's Vulkan " + "drivers for AMD and Intel, the NVIDIA driver for NVIDIA cards), then restart the computer.", + ) + + +def check_vulkan(run: Runner = host_run, icd_dirs: Sequence[Path] | None = None) -> Check: + """Does Vulkan work on a real graphics card? Asks ``vulkaninfo``, else reads driver manifests.""" + dirs = list(icd_dirs) if icd_dirs is not None else default_icd_dirs() + try: + proc = run(["vulkaninfo", "--summary"], capture_output=True, text=True, timeout=_TIMEOUT) + except FileNotFoundError: + return _vulkan_from_manifests(dirs) + except subprocess.TimeoutExpired: + return Check( + "vulkan", UNKNOWN, _VULKAN_UNKNOWN, + "The Vulkan test (vulkaninfo) took longer than 5 seconds and was stopped, so there is " + "no answer.", + "", + ) + except (OSError, subprocess.SubprocessError, ValueError) as exc: + return Check("vulkan", UNKNOWN, _VULKAN_UNKNOWN, f"The Vulkan test could not be run ({exc}).", "") + + out = proc.stdout if isinstance(proc.stdout, str) else "" + err = proc.stderr if isinstance(proc.stderr, str) else "" + both = out + "\n" + err + + if proc.returncode != 0: + reason = _first_line(both, _DRIVER_FAILURE_MARKERS) + if reason: + return Check( + "vulkan", PROBLEM, "No Vulkan driver was found", + f"Vulkan could not start on this computer (\"{reason}\"). Games that run through " + "Proton need Vulkan, so they won't start.", + "Install or reinstall the Vulkan driver for your graphics card from your distribution, " + "then restart the computer.", + ) + if proc.returncode == 127 or _first_line(both, _TOOL_MISSING_MARKERS): + return _vulkan_from_manifests(dirs) + return Check( + "vulkan", UNKNOWN, _VULKAN_UNKNOWN, + f"The Vulkan test (vulkaninfo) stopped with error code {proc.returncode} without saying " + "why, so there is no answer.", + "", + ) + + devices = _parse_devices(out) + hardware = [n for t, n in devices if _is_hardware(t, n)] + if hardware: + names = ", ".join(dict.fromkeys(hardware)) + return Check("vulkan", OK, "Vulkan works", f"Vulkan is running on {names}.", "") + if devices and all(_is_software(t, n) for t, n in devices): + name = devices[0][1] or "a software renderer" + return Check( + "vulkan", PROBLEM, "Vulkan only works in software mode", + f"The only Vulkan device is {name}, which draws on the processor instead of the graphics " + "card. Games will be very slow or refuse to start.", + "Install the Vulkan driver for your graphics card from your distribution (Mesa's Vulkan " + "drivers for AMD and Intel, the NVIDIA driver for NVIDIA cards), then restart the computer.", + ) + return Check( + "vulkan", UNKNOWN, _VULKAN_UNKNOWN, + "The Vulkan test ran, but ProtonShift couldn't make sense of what it printed.", + "", + ) + + +# --------------------------------------------------------------------------- # +# 32-bit Vulkan +# --------------------------------------------------------------------------- # + +def default_lib32_dirs() -> list[Path]: + dirs = [Path("/usr/lib32"), Path("/usr/lib/i386-linux-gnu"), Path("/usr/lib/i686-linux-gnu")] + lib64 = _host_path(Path("/usr/lib64")) + try: + # Fedora keeps 32-bit libraries in /usr/lib and 64-bit ones in a real /usr/lib64. + # On Arch /usr/lib64 is a symlink to lib, and /usr/lib holds the 64-bit ones. + fedora = lib64.is_dir() and not lib64.is_symlink() + except OSError: + fedora = False + if fedora: + dirs.append(Path("/usr/lib")) + return [_host_path(d) for d in dirs] + + +def default_lib64_dirs() -> list[Path]: + dirs = [Path("/usr/lib64"), Path("/usr/lib/x86_64-linux-gnu"), Path("/usr/lib")] + return [_host_path(d) for d in dirs] + + +def elf_class(path: Path) -> int | None: + """32 or 64 from the ELF header's EI_CLASS byte; ``None`` when not a readable ELF file.""" + try: + with open(path, "rb") as f: + head = f.read(5) + except OSError: + return None + if len(head) < 5 or head[:4] != b"\x7fELF": + return None + return {1: 32, 2: 64}.get(head[4]) + + +def _manifest_library(manifest: Path) -> str | None: + try: + if manifest.stat().st_size > _MAX_MANIFEST_BYTES: + return None + data = json.loads(manifest.read_text(encoding="utf-8", errors="replace")) + except (OSError, ValueError): + return None + icd = data.get("ICD") if isinstance(data, dict) else None + lib = icd.get("library_path") if isinstance(icd, dict) else None + if isinstance(lib, str) and lib and "\x00" not in lib: + return lib + return None + + +def _library_candidates(manifest: Path, lib: str, search: Sequence[Path]) -> list[Path]: + # Same rules as the Vulkan loader: an absolute path is used as is, a path with + # a slash is relative to the manifest, a bare name is looked up like dlopen does. + if lib.startswith("/"): + return [_host_path(Path(lib))] + if "/" in lib: + return [manifest.parent / lib] + return [Path(d) / lib for d in search] + + +def check_vulkan_32bit( + flavor: str, + icd_dirs: Sequence[Path] | None = None, + lib_dirs: Sequence[Path] | None = None, + lib64_dirs: Sequence[Path] | None = None, +) -> Check: + """Is there a 32-bit Vulkan driver? Judged from the driver libraries' ELF headers. + + ``lib_dirs`` are the 32-bit library folders, ``lib64_dirs`` the 64-bit ones. + Both are searched for bare library names and the ELF class decides, since a + folder's name alone doesn't say which kind it holds on every distribution. + """ + title_unknown = "Couldn't check for a 32-bit Vulkan driver" + if flavor == "flatpak": + return Check( + "vulkan-32bit", UNKNOWN, title_unknown, + "Steam runs as a Flatpak and brings its own drivers, so the ones installed on this " + "computer don't decide this.", + "", + ) + try: + dirs = list(icd_dirs) if icd_dirs is not None else default_icd_dirs() + lib32 = list(lib_dirs) if lib_dirs is not None else default_lib32_dirs() + lib64 = list(lib64_dirs) if lib64_dirs is not None else default_lib64_dirs() + search = lib32 + [d for d in lib64 if d not in lib32] + + manifests = _icd_manifests(dirs) + found32: list[str] = [] + found64: list[str] = [] + for manifest in manifests: + lib = _manifest_library(manifest) + if lib is None: + continue + for candidate in _library_candidates(manifest, lib, search): + cls = elf_class(candidate) + if cls == 32: + found32.append(lib) + elif cls == 64: + found64.append(lib) + except (OSError, RuntimeError, ValueError) as exc: + return Check("vulkan-32bit", UNKNOWN, title_unknown, f"The driver files could not be read ({exc}).", "") + + if found32: + names = ", ".join(dict.fromkeys(found32)) + return Check( + "vulkan-32bit", OK, "A 32-bit Vulkan driver is installed", + f"32-bit games and launchers can use Vulkan through {names}.", "", + ) + if manifests and found64: + return Check( + "vulkan-32bit", PROBLEM, "No 32-bit Vulkan driver was found", + "The Vulkan driver on this computer is only installed for 64-bit programs. Many Windows " + "games and their launchers are 32-bit and won't start without the 32-bit driver.", + "Install the 32-bit Vulkan driver for your GPU from your distribution " + "(often named lib32-... or ...:i386).", + ) + if not manifests: + detail = "No Vulkan driver files were found, so there was nothing to check for a 32-bit version." + else: + detail = ( + "Vulkan driver files were found, but ProtonShift couldn't find the driver libraries they " + "point to, so it can't tell whether a 32-bit one is installed." + ) + return Check("vulkan-32bit", UNKNOWN, title_unknown, detail, "") + + +# --------------------------------------------------------------------------- # +# Disk space +# --------------------------------------------------------------------------- # + +_DISK_WORDING = { + "library": ("disk-library", "the drive holding the game"), + "prefix": ("disk-prefix", "the drive holding the game's Proton prefix"), +} + + +def check_disk(path: Path | None, which: str, min_free_bytes: int = 1 << 30) -> Check: + """Free space on the drive under ``path``; ``which`` is ``"library"`` or ``"prefix"``.""" + check_id, where = _DISK_WORDING.get(which, _DISK_WORDING["library"]) + title_unknown = f"Couldn't check free space on {where}" + if path is None: + return Check(check_id, UNKNOWN, title_unknown, f"ProtonShift doesn't know where {where} is.", "") + shown = host_display_path(path) + try: + free = shutil.disk_usage(path).free + except (OSError, ValueError, TypeError): + return Check( + check_id, UNKNOWN, title_unknown, + f"The folder {shown} couldn't be read, so its free space is unknown.", "", + ) + gib = f"{free / (1 << 30):.1f} GiB" + if free < min_free_bytes: + return Check( + check_id, PROBLEM, f"{where[0].upper()}{where[1:]} is almost full", + f"Only {gib} is free on {where} ({shown}). Games can fail to start or crash when they " + "can't write saves, shader caches or updates.", + "Free up space on that drive, for example by deleting files you no longer need or moving " + "a game to another drive.", + ) + return Check( + check_id, OK, f"Enough free space on {where}", + f"{gib} is free on {where} ({shown}).", "", + ) + + +def _same_device(a: Path | None, b: Path | None) -> bool: + if a is None or b is None: + return False + try: + return os.stat(a).st_dev == os.stat(b).st_dev + except (OSError, ValueError, TypeError): + return False + + +# --------------------------------------------------------------------------- # +# All together +# --------------------------------------------------------------------------- # + +def run_checks( + *, + steam_root: Path | None, + install_path: Path | None, + prefix_path: Path | None, + run: Runner = host_run, +) -> list[Check]: + """Every system check for one game, in display order.""" + checks = [ + check_vulkan(run), + check_vulkan_32bit(steam_flavor(steam_root)), + check_disk(install_path, "library"), + ] + # One drive, one answer: the same free space twice reads like two problems. + if not _same_device(install_path, prefix_path): + checks.append(check_disk(prefix_path, "prefix")) + return checks diff --git a/tests/test_snapshots.py b/tests/test_snapshots.py new file mode 100644 index 0000000..40c920d --- /dev/null +++ b/tests/test_snapshots.py @@ -0,0 +1,237 @@ +"""Snapshots for Diagnose's Undo: round trip, order, cap, drop, damaged files, path safety. + +HOME points at ``tmp_path`` for every test, so nothing touches the real +``~/.config``. Qt-free. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from protonshift.core import snapshots as snap +from protonshift.core.snapshots import GameState + +BEFORE = GameState(launch_options="gamemoderun %command%", compat_tool="proton_9") +AFTER = GameState(launch_options="%command%", compat_tool="") + + +@pytest.fixture(autouse=True) +def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + monkeypatch.setenv("HOME", str(tmp_path)) + return tmp_path + + +def file_for(app_id: str) -> Path: + return snap.snapshot_dir() / f"{app_id}.json" + + +def test_snapshot_dir_follows_home_at_call_time(home: Path, monkeypatch: pytest.MonkeyPatch) -> None: + assert snap.snapshot_dir() == home / ".config" / "protonshift" / "snapshots" + other = home / "other" + monkeypatch.setenv("HOME", str(other)) + assert snap.snapshot_dir() == other / ".config" / "protonshift" / "snapshots" + + +def test_round_trip() -> None: + s = snap.record("570", "Removed gamemoderun", "wrapper-missing", BEFORE, AFTER) + assert s.app_id == "570" and s.label == "Removed gamemoderun" and s.finding_id == "wrapper-missing" + assert s.before == BEFORE and s.after == AFTER + assert s.taken_at.endswith("+00:00") and "." not in s.taken_at + assert snap.history("570") == [s] + assert snap.latest("570") == s + data = json.loads(file_for("570").read_text()) + assert data["format"] == "protonshift-snapshots" and data["version"] == 1 + assert data["entries"][0]["before"] == {"launch_options": "gamemoderun %command%", "compat_tool": "proton_9"} + + +def test_history_newest_first_and_ids_unique() -> None: + made = [snap.record("10", f"fix {i}", "f", BEFORE, AFTER) for i in range(5)] + got = snap.history("10") + assert [s.label for s in got] == ["fix 4", "fix 3", "fix 2", "fix 1", "fix 0"] + assert len({s.id for s in made}) == 5 + assert snap.latest("10").label == "fix 4" + + +def test_games_are_kept_apart() -> None: + snap.record("1", "a", "f", BEFORE, AFTER) + snap.record("2", "b", "f", BEFORE, AFTER) + assert [s.label for s in snap.history("1")] == ["a"] + assert [s.label for s in snap.history("2")] == ["b"] + + +def test_cap_keeps_newest() -> None: + for i in range(snap.MAX_PER_GAME + 5): + snap.record("20", f"fix {i}", "f", BEFORE, AFTER) + got = snap.history("20") + assert len(got) == snap.MAX_PER_GAME + assert got[0].label == f"fix {snap.MAX_PER_GAME + 4}" + assert got[-1].label == "fix 5" + + +def test_drop() -> None: + a = snap.record("30", "a", "f", BEFORE, AFTER) + b = snap.record("30", "b", "f", BEFORE, AFTER) + assert snap.drop("30", b.id) is True + assert snap.history("30") == [a] + assert snap.drop("30", b.id) is False + assert snap.drop("30", "no-such-id") is False + assert snap.drop("31", a.id) is False # no file for that game + assert snap.drop("30", a.id) is True + assert snap.history("30") == [] and snap.latest("30") is None + + +def test_label_is_capped() -> None: + s = snap.record("40", "x" * 500, "f", BEFORE, AFTER) + assert len(s.label) == snap.LABEL_MAX + assert len(snap.latest("40").label) == snap.LABEL_MAX + + +@pytest.mark.parametrize("bad", ["a\nb", "a\rb", "a\x00b"]) +@pytest.mark.parametrize("where", ["label", "finding_id", "before_lo", "before_ct", "after_lo", "after_ct"]) +def test_record_rejects_control_characters(bad: str, where: str) -> None: + label, finding = "ok", "ok" + before, after = BEFORE, AFTER + if where == "label": + label = bad + elif where == "finding_id": + finding = bad + elif where == "before_lo": + before = GameState(bad, "") + elif where == "before_ct": + before = GameState("", bad) + elif where == "after_lo": + after = GameState(bad, "") + else: + after = GameState("", bad) + with pytest.raises(ValueError): + snap.record("50", label, finding, before, after) + assert not file_for("50").exists() + + +def test_record_rejects_non_strings() -> None: + with pytest.raises(ValueError): + snap.record("51", None, "f", BEFORE, AFTER) # type: ignore[arg-type] + with pytest.raises(ValueError): + snap.record("51", "l", "f", GameState(None, ""), AFTER) # type: ignore[arg-type] + + +@pytest.mark.parametrize("content", [ + "{ not json", + "[]", + json.dumps({"format": "something-else", "version": 1, "entries": []}), + json.dumps({"format": "protonshift-snapshots", "version": 2, "entries": []}), + json.dumps({"format": "protonshift-snapshots", "version": 1, "entries": {}}), + "\udcff", +]) +def test_unreadable_file_is_set_aside_not_lost(content: str) -> None: + path = file_for("60") + path.parent.mkdir(parents=True) + raw = content.encode("utf-8", "surrogateescape") + path.write_bytes(raw) + assert snap.history("60") == [] + assert snap.latest("60") is None + assert snap.drop("60", "x") is False + assert path.read_bytes() == raw # readers never touch it + + s = snap.record("60", "after damage", "f", BEFORE, AFTER) + assert snap.history("60") == [s] + kept = list(path.parent.glob("60.json.corrupt-*")) + assert len(kept) == 1 + assert kept[0].read_bytes() == raw + + +def test_two_corrupt_files_in_one_second_both_survive() -> None: + path = file_for("61") + path.parent.mkdir(parents=True) + path.write_text("first bad") + snap.record("61", "a", "f", BEFORE, AFTER) + path.write_text("second bad") + snap.record("61", "b", "f", BEFORE, AFTER) + kept = sorted(p.read_text() for p in path.parent.glob("61.json.corrupt-*")) + assert kept == ["first bad", "second bad"] + + +def test_malformed_entries_are_skipped() -> None: + good = snap.record("70", "good", "f", BEFORE, AFTER) + path = file_for("70") + data = json.loads(path.read_text()) + entry = data["entries"][0] + data["entries"] = [ + "not a dict", + {**entry, "id": 5}, + {**entry, "label": None}, + {k: v for k, v in entry.items() if k != "finding_id"}, + {**entry, "before": {"launch_options": "x"}}, + {**entry, "after": "nope"}, + {**entry, "before": {"launch_options": "a\nb", "compat_tool": ""}}, + {**entry, "app_id": "71"}, + {**entry, "id": ""}, + entry, + {**entry, "extra": "ignored"}, + ] + path.write_text(json.dumps(data)) + got = snap.history("70") + assert got == [good, good] + + +def test_record_raises_oserror_when_it_cannot_write(home: Path) -> None: + # A file where the folder should be: nothing can be written under it. + (home / ".config" / "protonshift").mkdir(parents=True) + (home / ".config" / "protonshift" / "snapshots").write_text("in the way") + with pytest.raises(OSError): + snap.record("80", "l", "f", BEFORE, AFTER) + + +BAD_IDS = ["..", "../x", "1/2", "", "1" * 21, "12a", "12\x0034", "/etc/passwd", "-1", " 12", "12\n", + "١٢"] + + +@pytest.mark.parametrize("bad", BAD_IDS) +def test_bad_app_ids_are_refused(bad: str, home: Path) -> None: + with pytest.raises(ValueError): + snap.record(bad, "l", "f", BEFORE, AFTER) + assert snap.history(bad) == [] + assert snap.latest(bad) is None + assert snap.drop(bad, "x") is False + assert not (home / ".config" / "protonshift" / "snapshots").exists() + + +@pytest.mark.parametrize("bad", [None, 570, b"570"]) +def test_non_string_app_ids_are_refused(bad: object) -> None: + with pytest.raises(ValueError): + snap.record(bad, "l", "f", BEFORE, AFTER) # type: ignore[arg-type] + assert snap.history(bad) == [] # type: ignore[arg-type] + + +def test_twenty_digit_id_is_accepted() -> None: + big = "1" * 20 + s = snap.record(big, "l", "f", BEFORE, AFTER) + assert snap.latest(big) == s + + +def test_symlink_out_of_the_folder_is_refused(home: Path) -> None: + outside = home / "outside.json" + outside.write_text("precious") + folder = snap.snapshot_dir() + folder.mkdir(parents=True) + (folder / "90.json").symlink_to(outside) + with pytest.raises(ValueError): + snap.record("90", "l", "f", BEFORE, AFTER) + assert snap.history("90") == [] + assert outside.read_text() == "precious" + + +def test_symlink_to_another_game_is_refused() -> None: + other = snap.record("91", "other game", "f", BEFORE, AFTER) + (snap.snapshot_dir() / "92.json").symlink_to("91.json") + with pytest.raises(ValueError): + snap.record("92", "l", "f", BEFORE, AFTER) + assert snap.history("91") == [other] + + +def test_no_long_dashes_in_source() -> None: + source = Path(snap.__file__).read_text(encoding="utf-8") + assert chr(0x2014) not in source and chr(0x2013) not in source diff --git a/tests/test_system_checks.py b/tests/test_system_checks.py new file mode 100644 index 0000000..1a3c493 --- /dev/null +++ b/tests/test_system_checks.py @@ -0,0 +1,458 @@ +"""System checks for Diagnose: every state of every check, with fake runners and fake folders. + +No real subprocess, no real /usr: runners return a ``CompletedProcess`` or raise, +and ICD manifests, driver libraries and ELF headers are built under ``tmp_path``. +Qt-free. +""" + +from __future__ import annotations + +import json +import os +import subprocess +from collections import namedtuple +from pathlib import Path + +import pytest + +from protonshift.core import system_checks as sc + +# Trimmed from `vulkaninfo --summary` (Vulkan Instance Version 1.4.363) on an +# Arch laptop with an NVIDIA RTX 4080 Laptop GPU and the proprietary driver. +REAL_SUMMARY = """\ +========== +VULKANINFO +========== + +Vulkan Instance Version: 1.4.363 + + +Instance Extensions: count = 27 +------------------------------- +VK_EXT_acquire_drm_display : extension revision 1 +VK_KHR_surface : extension revision 25 + +Instance Layers: count = 11 +--------------------------- +VK_LAYER_MESA_device_select Linux device selection layer 1.4.303 version 1 +VK_LAYER_VALVE_steam_overlay_64 Steam Overlay Layer 1.3.207 version 1 + +Devices: +======== +GPU0: +\tapiVersion = 1.4.351 +\tdriverVersion = 615.78.8.0 +\tvendorID = 0x10de +\tdeviceID = 0x27e0 +\tdeviceType = PHYSICAL_DEVICE_TYPE_DISCRETE_GPU +\tdeviceName = NVIDIA GeForce RTX 4080 Laptop GPU +\tdriverID = DRIVER_ID_NVIDIA_PROPRIETARY +\tdriverName = NVIDIA +\tdriverInfo = 615.78.08 +\tconformanceVersion = 1.4.3.3 +""" + +LLVMPIPE_ONLY = """\ +Devices: +======== +GPU0: +\tapiVersion = 1.3.289 +\tdeviceType = PHYSICAL_DEVICE_TYPE_CPU +\tdeviceName = llvmpipe (LLVM 18.1.8, 256 bits) +\tdriverID = DRIVER_ID_MESA_LLVMPIPE +""" + +GPU_PLUS_LLVMPIPE = """\ +Devices: +======== +GPU0: +\tdeviceType = PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU +\tdeviceName = AMD Radeon Graphics (RADV RENOIR) +GPU1: +\tdeviceType = PHYSICAL_DEVICE_TYPE_CPU +\tdeviceName = llvmpipe (LLVM 18.1.8, 256 bits) +""" + +NO_DRIVER_STDERR = """\ +ERROR: [Loader Message] Code 0 : vkCreateInstance: Found no drivers! +Cannot create Vulkan instance. +This problem is often caused by a faulty installation of the Vulkan driver or attempting to use a GPU \ +that does not support Vulkan. +ERROR at ./vulkaninfo/vulkaninfo.h:573:vkCreateInstance failed with ERROR_INCOMPATIBLE_DRIVER +""" + + +def runner(returncode: int = 0, stdout: str = "", stderr: str = ""): + calls: list[tuple[list[str], dict]] = [] + + def run(argv, **kwargs): + calls.append((argv, kwargs)) + return subprocess.CompletedProcess(argv, returncode, stdout, stderr) + + run.calls = calls # type: ignore[attr-defined] + return run + + +def raising(exc: BaseException): + def run(argv, **kwargs): + raise exc + + return run + + +def write_manifest(folder: Path, name: str, library_path: object) -> Path: + folder.mkdir(parents=True, exist_ok=True) + path = folder / name + path.write_text(json.dumps({"file_format_version": "1.0.1", "ICD": {"library_path": library_path}})) + return path + + +def write_elf(path: Path, ei_class: int) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"\x7fELF" + bytes([ei_class]) + b"\x01\x01" + b"\x00" * 9) + return path + + +@pytest.fixture(autouse=True) +def not_sandboxed(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sc, "in_flatpak", lambda: False) + + +# --------------------------------------------------------------------------- # +# steam_flavor / steam_running +# --------------------------------------------------------------------------- # + +def test_steam_flavor_flatpak(tmp_path: Path) -> None: + root = tmp_path / ".var" / "app" / "com.valvesoftware.Steam" / ".local" / "share" / "Steam" + root.mkdir(parents=True) + assert sc.steam_flavor(root) == "flatpak" + + +def test_steam_flavor_flatpak_through_symlink(tmp_path: Path) -> None: + real = tmp_path / ".var" / "app" / "com.valvesoftware.Steam" / "data" / "Steam" + real.mkdir(parents=True) + link = tmp_path / ".steam-steam" + link.symlink_to(real) + assert sc.steam_flavor(link) == "flatpak" + + +def test_steam_flavor_native(tmp_path: Path) -> None: + root = tmp_path / ".local" / "share" / "Steam" + root.mkdir(parents=True) + assert sc.steam_flavor(root) == "native" + + +def test_steam_flavor_unknown(tmp_path: Path) -> None: + assert sc.steam_flavor(None) == "unknown" + assert sc.steam_flavor(tmp_path / "missing") == "unknown" + + +def test_steam_running_states() -> None: + run = runner(0) + assert sc.steam_running(run) is True + argv, kwargs = run.calls[0] + assert argv == ["pgrep", "-x", "steam"] + assert kwargs["timeout"] == 5 + assert sc.steam_running(runner(1)) is False + assert sc.steam_running(runner(2)) is None + assert sc.steam_running(raising(FileNotFoundError())) is None + assert sc.steam_running(raising(subprocess.TimeoutExpired(["pgrep"], 5))) is None + + +# --------------------------------------------------------------------------- # +# check_vulkan +# --------------------------------------------------------------------------- # + +def test_vulkan_ok_on_real_output(tmp_path: Path) -> None: + run = runner(0, REAL_SUMMARY) + c = sc.check_vulkan(run, icd_dirs=[tmp_path / "icd.d"]) + assert c.id == "vulkan" + assert c.state == "ok" + assert "NVIDIA GeForce RTX 4080 Laptop GPU" in c.detail + assert c.fix == "" + argv, kwargs = run.calls[0] + assert argv == ["vulkaninfo", "--summary"] + assert kwargs["timeout"] == 5 and kwargs["text"] is True + + +def test_vulkan_ok_when_a_gpu_sits_beside_llvmpipe(tmp_path: Path) -> None: + c = sc.check_vulkan(runner(0, GPU_PLUS_LLVMPIPE), icd_dirs=[tmp_path]) + assert c.state == "ok" + assert "RADV" in c.detail and "llvmpipe" not in c.detail + + +def test_vulkan_problem_when_only_software(tmp_path: Path) -> None: + c = sc.check_vulkan(runner(0, LLVMPIPE_ONLY), icd_dirs=[tmp_path]) + assert c.state == "problem" + assert "llvmpipe" in c.detail + assert c.fix + + +def test_vulkan_problem_when_lavapipe_has_no_type_line(tmp_path: Path) -> None: + out = "Devices:\n========\nGPU0:\n\tdeviceName = lavapipe\n\tdeviceType = PHYSICAL_DEVICE_TYPE_CPU\n" + assert sc.check_vulkan(runner(0, out), icd_dirs=[tmp_path]).state == "problem" + + +def test_vulkan_problem_on_driver_failure(tmp_path: Path) -> None: + c = sc.check_vulkan(runner(1, "", NO_DRIVER_STDERR), icd_dirs=[tmp_path]) + assert c.state == "problem" + assert c.title == "No Vulkan driver was found" + assert c.fix + + +def test_vulkan_nonzero_without_driver_wording_is_unknown(tmp_path: Path) -> None: + c = sc.check_vulkan(runner(3, REAL_SUMMARY, "Segmentation fault"), icd_dirs=[tmp_path]) + # A crash after printing a GPU still isn't a working Vulkan. + assert c.state == "unknown" + assert "3" in c.detail + + +def test_vulkan_unrecognised_output_is_unknown(tmp_path: Path) -> None: + assert sc.check_vulkan(runner(0, "something else entirely\n"), icd_dirs=[tmp_path]).state == "unknown" + assert sc.check_vulkan(runner(0, ""), icd_dirs=[tmp_path]).state == "unknown" + + +def test_vulkan_device_of_unknown_type_is_not_ok(tmp_path: Path) -> None: + out = "Devices:\n========\nGPU0:\n\tdeviceType = PHYSICAL_DEVICE_TYPE_OTHER\n\tdeviceName = Mystery\n" + assert sc.check_vulkan(runner(0, out), icd_dirs=[tmp_path]).state == "unknown" + out = "Devices:\n========\nGPU0:\n\tdeviceName = Some GPU\n" + assert sc.check_vulkan(runner(0, out), icd_dirs=[tmp_path]).state == "unknown" + + +def test_vulkan_timeout_is_unknown(tmp_path: Path) -> None: + c = sc.check_vulkan(raising(subprocess.TimeoutExpired(["vulkaninfo"], 5)), icd_dirs=[tmp_path]) + assert c.state == "unknown" + assert "5 seconds" in c.detail + + +def test_vulkan_other_oserror_is_unknown(tmp_path: Path) -> None: + assert sc.check_vulkan(raising(PermissionError("denied")), icd_dirs=[tmp_path]).state == "unknown" + + +def test_vulkan_missing_tool_with_manifests_is_unknown(tmp_path: Path) -> None: + icd = tmp_path / "share" / "vulkan" / "icd.d" + write_manifest(icd, "radeon_icd.x86_64.json", "/usr/lib/libvulkan_radeon.so") + c = sc.check_vulkan(raising(FileNotFoundError()), icd_dirs=[icd]) + assert c.state == "unknown" + assert "vulkaninfo" in c.detail and "vulkan-tools" in c.detail + + +def test_vulkan_missing_tool_without_manifests_is_problem(tmp_path: Path) -> None: + icd = tmp_path / "share" / "vulkan" / "icd.d" + icd.parent.mkdir(parents=True) + c = sc.check_vulkan(raising(FileNotFoundError()), icd_dirs=[icd, tmp_path / "etc" / "vulkan" / "icd.d"]) + assert c.state == "problem" + assert c.title == "No Vulkan driver is installed" + + +def test_vulkan_missing_tool_and_folders_out_of_sight_is_unknown(tmp_path: Path) -> None: + # A sandbox without host-os: /run/host/usr/share is not there at all. + unseen = tmp_path / "run" / "host" / "usr" / "share" / "vulkan" / "icd.d" + c = sc.check_vulkan(raising(FileNotFoundError()), icd_dirs=[unseen]) + assert c.state == "unknown" + + +def test_vulkan_missing_host_tool_inside_sandbox_falls_back(tmp_path: Path) -> None: + icd = tmp_path / "share" / "vulkan" / "icd.d" + write_manifest(icd, "intel_icd.json", "libvulkan_intel.so") + stderr = 'Failed to start command: Failed to execute child process "vulkaninfo" (No such file or directory)' + c = sc.check_vulkan(runner(1, "", stderr), icd_dirs=[icd]) + assert c.state == "unknown" + assert "vulkan-tools" in c.detail + assert sc.check_vulkan(runner(127), icd_dirs=[icd]).state == "unknown" + + +def test_default_icd_dirs_use_host_root_in_sandbox(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sc, "in_flatpak", lambda: True) + dirs = [str(d) for d in sc.default_icd_dirs()] + assert "/run/host/usr/share/vulkan/icd.d" in dirs + assert "/run/host/etc/vulkan/icd.d" in dirs + assert "/usr/share/vulkan/icd.d" not in dirs + monkeypatch.setattr(sc, "in_flatpak", lambda: False) + assert "/usr/share/vulkan/icd.d" in [str(d) for d in sc.default_icd_dirs()] + + +# --------------------------------------------------------------------------- # +# check_vulkan_32bit +# --------------------------------------------------------------------------- # + +def test_elf_class(tmp_path: Path) -> None: + assert sc.elf_class(write_elf(tmp_path / "a.so", 1)) == 32 + assert sc.elf_class(write_elf(tmp_path / "b.so", 2)) == 64 + assert sc.elf_class(write_elf(tmp_path / "c.so", 7)) is None + (tmp_path / "d.so").write_bytes(b"not an elf") + assert sc.elf_class(tmp_path / "d.so") is None + assert sc.elf_class(tmp_path / "missing.so") is None + + +def test_32bit_flatpak_steam_is_unknown(tmp_path: Path) -> None: + c = sc.check_vulkan_32bit("flatpak", icd_dirs=[tmp_path], lib_dirs=[tmp_path]) + assert c.id == "vulkan-32bit" + assert c.state == "unknown" + assert "Flatpak" in c.detail + + +def test_32bit_ok_with_bare_name_in_lib32(tmp_path: Path) -> None: + icd, lib32, lib64 = tmp_path / "icd.d", tmp_path / "lib32", tmp_path / "lib" + write_manifest(icd, "nvidia_icd.json", "libGLX_nvidia.so.0") + write_elf(lib32 / "libGLX_nvidia.so.0", 1) + write_elf(lib64 / "libGLX_nvidia.so.0", 2) + c = sc.check_vulkan_32bit("native", icd_dirs=[icd], lib_dirs=[lib32], lib64_dirs=[lib64]) + assert c.state == "ok" + assert "libGLX_nvidia.so.0" in c.detail + + +def test_32bit_ok_with_absolute_paths(tmp_path: Path) -> None: + icd = tmp_path / "icd.d" + lib64 = write_elf(tmp_path / "x86_64-linux-gnu" / "libvulkan_radeon.so", 2) + lib32 = write_elf(tmp_path / "i386-linux-gnu" / "libvulkan_radeon.so", 1) + write_manifest(icd, "radeon_icd.x86_64.json", str(lib64)) + write_manifest(icd, "radeon_icd.i686.json", str(lib32)) + assert sc.check_vulkan_32bit("native", icd_dirs=[icd], lib_dirs=[], lib64_dirs=[]).state == "ok" + + +def test_32bit_ok_with_path_relative_to_manifest(tmp_path: Path) -> None: + icd = tmp_path / "icd.d" + write_elf(tmp_path / "lib" / "libvk32.so", 1) + write_manifest(icd, "vk.json", "../lib/libvk32.so") + assert sc.check_vulkan_32bit("native", icd_dirs=[icd], lib_dirs=[], lib64_dirs=[]).state == "ok" + + +def test_32bit_problem_when_only_64bit(tmp_path: Path) -> None: + icd, lib32, lib64 = tmp_path / "icd.d", tmp_path / "lib32", tmp_path / "lib" + lib32.mkdir() + write_manifest(icd, "intel_icd.json", "libvulkan_intel.so") + write_elf(lib64 / "libvulkan_intel.so", 2) + c = sc.check_vulkan_32bit("native", icd_dirs=[icd], lib_dirs=[lib32], lib64_dirs=[lib64]) + assert c.state == "problem" + assert c.fix == ( + "Install the 32-bit Vulkan driver for your GPU from your distribution " + "(often named lib32-... or ...:i386)." + ) + for manager in ("pacman", "apt", "dnf", "zypper"): + assert manager not in c.fix + + +def test_32bit_problem_with_absolute_64bit_path(tmp_path: Path) -> None: + icd = tmp_path / "icd.d" + write_manifest(icd, "radeon_icd.x86_64.json", str(write_elf(tmp_path / "libvulkan_radeon.so", 2))) + assert sc.check_vulkan_32bit("unknown", icd_dirs=[icd], lib_dirs=[], lib64_dirs=[]).state == "problem" + + +def test_32bit_unknown_without_manifests(tmp_path: Path) -> None: + c = sc.check_vulkan_32bit("native", icd_dirs=[tmp_path / "none"], lib_dirs=[tmp_path], lib64_dirs=[]) + assert c.state == "unknown" + + +def test_32bit_unknown_when_libraries_cannot_be_identified(tmp_path: Path) -> None: + icd = tmp_path / "icd.d" + write_manifest(icd, "a.json", "libnowhere.so") + write_manifest(icd, "b.json", str(tmp_path / "missing.so")) + (tmp_path / "not-elf.so").write_bytes(b"#!/bin/sh\n") + write_manifest(icd, "c.json", str(tmp_path / "not-elf.so")) + write_manifest(icd, "d.json", 42) + (icd / "e.json").write_text("{ broken") + (icd / "f.json").write_text('["not", "a", "manifest"]') + c = sc.check_vulkan_32bit("native", icd_dirs=[icd], lib_dirs=[tmp_path], lib64_dirs=[]) + assert c.state == "unknown" + + +def test_default_lib_dirs_follow_layout(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + # Fake the host root so the Fedora check looks at a tmp layout, not this machine. + host = tmp_path / "host" + monkeypatch.setattr(sc, "in_flatpak", lambda: True) + monkeypatch.setattr(sc, "FLATPAK_HOST_ROOT", host) + (host / "usr" / "lib").mkdir(parents=True) + (host / "usr" / "lib64").symlink_to("lib") # Arch + assert host / "usr" / "lib" not in sc.default_lib32_dirs() + (host / "usr" / "lib64").unlink() + (host / "usr" / "lib64").mkdir() # Fedora + dirs = sc.default_lib32_dirs() + assert host / "usr" / "lib" in dirs + assert host / "usr" / "lib32" in dirs + assert all(str(d).startswith(str(host)) for d in dirs + sc.default_lib64_dirs()) + + +# --------------------------------------------------------------------------- # +# check_disk +# --------------------------------------------------------------------------- # + +Usage = namedtuple("Usage", "total used free") + + +def test_disk_ok(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sc.shutil, "disk_usage", lambda p: Usage(100 << 30, 50 << 30, 50 << 30)) + c = sc.check_disk(tmp_path, "library") + assert (c.id, c.state, c.fix) == ("disk-library", "ok", "") + assert "50.0 GiB" in c.detail + + +def test_disk_problem_reports_gib_and_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sc.shutil, "disk_usage", lambda p: Usage(100 << 30, 99 << 30, 400 << 20)) + c = sc.check_disk(tmp_path, "prefix") + assert (c.id, c.state) == ("disk-prefix", "problem") + assert "0.4 GiB" in c.detail + assert str(tmp_path) in c.detail + assert "Proton prefix" in c.detail + assert c.fix + + +def test_disk_threshold_is_configurable(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sc.shutil, "disk_usage", lambda p: Usage(10, 5, 5 << 30)) + assert sc.check_disk(tmp_path, "library", min_free_bytes=10 << 30).state == "problem" + assert sc.check_disk(tmp_path, "library", min_free_bytes=5 << 30).state == "ok" + + +def test_disk_unknown(tmp_path: Path) -> None: + assert sc.check_disk(None, "library").state == "unknown" + c = sc.check_disk(tmp_path / "missing", "prefix") + assert (c.id, c.state) == ("disk-prefix", "unknown") + + +def test_disk_real_tmp_path_does_not_raise(tmp_path: Path) -> None: + assert sc.check_disk(tmp_path, "library", min_free_bytes=0).state == "ok" + + +# --------------------------------------------------------------------------- # +# run_checks +# --------------------------------------------------------------------------- # + +def test_run_checks_order_and_shared_drive(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sc, "default_icd_dirs", lambda: [tmp_path / "icd.d"]) + install, prefix = tmp_path / "game", tmp_path / "pfx" + install.mkdir() + prefix.mkdir() + checks = sc.run_checks(steam_root=None, install_path=install, prefix_path=prefix, + run=runner(0, REAL_SUMMARY)) + assert [c.id for c in checks] == ["vulkan", "vulkan-32bit", "disk-library"] + + +def test_run_checks_separate_drives(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sc, "default_icd_dirs", lambda: [tmp_path / "icd.d"]) + real_stat = os.stat + install, prefix = tmp_path / "game", tmp_path / "pfx" + install.mkdir() + prefix.mkdir() + + class FakeStat: + def __init__(self, dev: int) -> None: + self.st_dev = dev + + monkeypatch.setattr(sc.os, "stat", lambda p: FakeStat(1 if Path(p) == install else 2) + if Path(p) in (install, prefix) else real_stat(p)) + checks = sc.run_checks(steam_root=None, install_path=install, prefix_path=prefix, + run=runner(0, REAL_SUMMARY)) + assert [c.id for c in checks] == ["vulkan", "vulkan-32bit", "disk-library", "disk-prefix"] + + +def test_run_checks_missing_paths_never_raise(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sc, "default_icd_dirs", lambda: [tmp_path / "icd.d"]) + checks = sc.run_checks(steam_root=None, install_path=None, prefix_path=tmp_path / "missing", + run=raising(FileNotFoundError())) + assert [c.id for c in checks] == ["vulkan", "vulkan-32bit", "disk-library", "disk-prefix"] + assert [c.state for c in checks[2:]] == ["unknown", "unknown"] + + +def test_text_has_no_long_dashes(tmp_path: Path) -> None: + source = Path(sc.__file__).read_text(encoding="utf-8") + assert chr(0x2014) not in source and chr(0x2013) not in source From 558a0ae7fa5054b282a6f96a3b18225448955072 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 22:49:23 -0600 Subject: [PATCH 05/20] docs: fix pack - write down the loader's strictness The loader was built to the stricter reading wherever the format left room. The contract now says so, and caps open-ended repeats in a log expression. Co-Authored-By: Claude Fable 5.2 --- docs/fix-pack.md | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/docs/fix-pack.md b/docs/fix-pack.md index 30b1f68..762fb47 100644 --- a/docs/fix-pack.md +++ b/docs/fix-pack.md @@ -75,7 +75,16 @@ elsewhere. Nothing here is relaxed because the file ships with the app. | `source` | yes | An `https://` URL where the situation and the remedy can be checked: upstream source code, a public issue, or project documentation. | | `verified` | yes | The date (`YYYY-MM-DD`) someone last checked the rule against its source. | -Titles and causes are plain text. They are shown as text, never as markup. +Titles and causes are plain text. They are shown as text, never as markup, +and may not be blank or contain line breaks or other control characters; the +same goes for the text of a `manual` action. + +The loader is strict throughout. A key it does not know (in the pack, a +rule, `match`, `when` or an action) rejects that rule, so a typo cannot +silently produce a rule with defaults. A value of the wrong type is rejected, +never converted. An empty list is rejected. An id may not start with `user-`, +which is kept for the user's own fixes. A file with the same key twice in one +object is rejected whole. ## Matching @@ -91,9 +100,17 @@ is not a rule. expression must compile, must be at most 300 characters, and must contain at least 8 literal characters in a row, so that it is anchored on real text and not on a pattern that fits half the log. An expression must not repeat - a group that itself contains a repeat (for example `(a+)+`), because such - a pattern can take a very long time on a long line. Matching is case - sensitive, and only the first 2000 characters of a line are looked at. + a group that itself contains a repeat (for example `(a+)+`), and may hold + at most two open-ended repeats (`*`, `+`, `{n,}`), because such patterns + can take a very long time on a long line. An optional group (`?`) does not + count as repeating what is inside it. Inline flags, back-references and + conditionals are not allowed. Matching is case sensitive, and only the + first 2000 characters of a line are looked at. + + What counts toward the 8 literal characters: plain and escaped characters + (`\.`), also through a group that is not repeated. A character class, `.`, + an anchor, a repeat that may match zero times, and a lookaround end the + run. An alternation counts as its shortest branch. With no log on disk, a rule that has a `log` part does not match. - `log_also`: a list of regular expressions under the same limits. Every one of them must also be found somewhere in the log tail, each in any line. @@ -111,9 +128,9 @@ is not a rule. | `gpu_vendor` | list of `nvidia`, `amd`, `intel` | any GPU of a listed vendor is present | | `session` | list of `wayland`, `x11` | the desktop session is of a listed type | | `proton_family` | list of `valve`, `ge`, `cachyos`, `other` | the game's Proton build belongs to a listed family | -| `proton_major_min` | integer | the build's major version is at least this | -| `proton_major_max` | integer | the build's major version is at most this | -| `launch_has` | list of words | every listed word is in the launch options before `%command%`, as a command name (`gamemoderun`) | +| `proton_major_min` | integer, 0 or more | the build's major version is at least this | +| `proton_major_max` | integer, not below the minimum | the build's major version is at most this | +| `launch_has` | list of words (same characters as `remove_word`) | every listed word is in the launch options before `%command%`, as a command name (`gamemoderun`) | | `env_set` | list of variable names | every listed variable is set in the launch options | | `env_unset` | list of variable names | none of the listed variables is set in the launch options | @@ -148,7 +165,10 @@ Limits, enforced by the loader: - `value` for `game_arg` matches `^[-+][A-Za-z0-9_.=:-]{1,60}$` (one switch, such as `-vulkan` or `+fps_max=0`). - `value` for `remove_word` matches `^[A-Za-z0-9_.-]{1,40}$`. -- A rule has at most 6 actions. +- An `env` value may not contain `%command%`: Steam replaces it wherever it + appears, also inside an assignment. +- A rule has at most 6 actions. No action is listed twice, and no two + actions of one rule touch the same variable. - These variables may never be set or unset by a rule, because they decide what code a process loads or runs: `LD_PRELOAD`, `LD_LIBRARY_PATH`, `LD_AUDIT`, `PATH`, `PYTHONPATH`, `STEAM_COMPAT_LAUNCHER_SERVICE`, From 19577b42c55e3f77249517b1ed4a6932d0a12f8c Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 22:51:01 -0600 Subject: [PATCH 06/20] docs: fix pack - literal run and empty-when wording match the loader Co-Authored-By: Claude Fable 5.2 --- docs/fix-pack.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/docs/fix-pack.md b/docs/fix-pack.md index 762fb47..aaa69ee 100644 --- a/docs/fix-pack.md +++ b/docs/fix-pack.md @@ -79,10 +79,11 @@ Titles and causes are plain text. They are shown as text, never as markup, and may not be blank or contain line breaks or other control characters; the same goes for the text of a `manual` action. -The loader is strict throughout. A key it does not know (in the pack, a -rule, `match`, `when` or an action) rejects that rule, so a typo cannot -silently produce a rule with defaults. A value of the wrong type is rejected, -never converted. An empty list is rejected. An id may not start with `user-`, +The loader is strict throughout. A key it does not know in a rule, `match`, +`when` or an action rejects that rule, so a typo cannot silently produce a +rule with defaults; an unknown key at the top of the file rejects the whole +pack. A value of the wrong type is rejected, never converted. An empty list +and an empty `when` are rejected. An id may not start with `user-`, which is kept for the user's own fixes. A file with the same key twice in one object is rejected whole. @@ -109,8 +110,11 @@ is not a rule. What counts toward the 8 literal characters: plain and escaped characters (`\.`), also through a group that is not repeated. A character class, `.`, - an anchor, a repeat that may match zero times, and a lookaround end the - run. An alternation counts as its shortest branch. + an anchor, a lookaround, any repeat and any alternation end the run. What + is inside a repeat that must match at least once is measured on its own, + and an alternation is measured as its shortest branch on its own; neither + joins the text around it. So `kernel(?:32|64)` has 6 in a row and is + rejected, while `kernel32\.dll` is fine. With no log on disk, a rule that has a `log` part does not match. - `log_also`: a list of regular expressions under the same limits. Every one of them must also be found somewhere in the log tail, each in any line. From 4f0a54badde43d2cf17a382616bcbde85a2a1f97 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 22:51:13 -0600 Subject: [PATCH 07/20] feat(core): fix pack v2 loader and validator The loader for the format in docs/fix-pack.md. It is strict on purpose: launch options reach a shell, so a rule may only name an environment variable and a value from a narrow character set, one game switch, or a wrapper word to remove, and anything it does not recognise rejects the rule instead of loading with defaults. Log expressions are checked for a real literal anchor and for shapes that can run away on a long line. The user's own v1 fixes load as advice rules marked as theirs. The bundled pack starts empty; test_bundled_pack_is_clean keeps what is added honest (source URL, verified date, unique ids, no rejected rule). Co-Authored-By: Claude Fable 5.2 --- protonshift/core/data/fix_pack.json | 6 + protonshift/core/fix_pack.py | 695 +++++++++++++++++ tests/test_core_safety.py | 66 +- tests/test_fix_pack.py | 1078 +++++++++++++++++++++++++++ 4 files changed, 1844 insertions(+), 1 deletion(-) create mode 100644 protonshift/core/data/fix_pack.json create mode 100644 protonshift/core/fix_pack.py create mode 100644 tests/test_fix_pack.py diff --git a/protonshift/core/data/fix_pack.json b/protonshift/core/data/fix_pack.json new file mode 100644 index 0000000..bd9c270 --- /dev/null +++ b/protonshift/core/data/fix_pack.json @@ -0,0 +1,6 @@ +{ + "format": "protonshift-fix-pack", + "version": 2, + "revision": "2026.11.0", + "rules": [] +} diff --git a/protonshift/core/fix_pack.py b/protonshift/core/fix_pack.py new file mode 100644 index 0000000..b16f7a4 --- /dev/null +++ b/protonshift/core/fix_pack.py @@ -0,0 +1,695 @@ +"""Load and validate the fix pack, the rule file behind Diagnose. + +``docs/fix-pack.md`` is the contract. Steam hands a game's launch options to a +shell, so a rule that could carry free text into them would run a command the +next time the game starts. Every check here keeps a pack, bundled or not, down +to the narrow shapes the contract allows: anything unknown, mistyped or out of +range is a rejection, never a default or a coercion. A bad rule is dropped and +reported; the rest of the pack still loads. + +The user's own version 1 fixes (``fixes.py``) are turned into rules here too, +so Diagnose sees one list. They are the user's text on the user's machine and +are held to looser value limits, as the contract's "User fixes" section says. + +Pure Python, stdlib only - exercised in tests/test_fix_pack.py and +tests/test_core_safety.py. +""" + +from __future__ import annotations + +import json +import os +import re +import stat +import unicodedata +from collections.abc import Iterable +from dataclasses import dataclass +from datetime import date +from pathlib import Path +from typing import Any +from urllib.parse import urlsplit + +from . import fixes as _fixes + +PACK_FORMAT = "protonshift-fix-pack" +PACK_VERSION = 2 +SEVERITIES = ("blocking", "likely", "advice") + +_BUNDLED_PATH = Path(__file__).parent / "data" / "fix_pack.json" +_MAX_PACK_BYTES = 2 * 1024 * 1024 +_MAX_ACTIONS = 6 +_MAX_LOG_PATTERN = 300 +_MIN_LITERAL_RUN = 8 +_MAX_OPEN_REPEATS = 2 +_MAX_LINE = 2000 +_MAX_USER_SNIPPET = 500 + +# Always used with fullmatch: ``$`` would also accept a trailing newline, and +# ``\d`` accepts digits from any script. +_ID_RE = re.compile(r"[a-z0-9-]{3,64}") +_REVISION_RE = re.compile(r"[0-9]{4}\.(0[1-9]|1[0-2])\.[0-9]+") +_DATE_RE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}") +_APP_ID_RE = re.compile(r"[0-9]+") +_KEY_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") +_ENV_VALUE_RE = re.compile(r"[A-Za-z0-9_.,:=/+@%-]{0,200}") +_GAME_ARG_RE = re.compile(r"[-+][A-Za-z0-9_.=:-]{1,60}") +_WORD_RE = re.compile(r"[A-Za-z0-9_.-]{1,40}") + +# These decide what code a process loads or runs. +_FORBIDDEN_VARS = frozenset({ + "LD_PRELOAD", + "LD_LIBRARY_PATH", + "LD_AUDIT", + "PATH", + "PYTHONPATH", + "STEAM_COMPAT_LAUNCHER_SERVICE", + "WINEDLLPATH", +}) +_FORBIDDEN_PREFIX = "STEAM_COMPAT_" +# ``user_rules`` hands out ``user-``; a pack rule with that id could be +# mistaken for (or shadow) one of the user's own. +_USER_ID_PREFIX = "user-" + +_PACK_KEYS = frozenset({"format", "version", "revision", "rules"}) +_RULE_KEYS = ("id", "title", "cause", "severity", "match", "actions", "source", "verified") +_MATCH_KEYS = frozenset({"app_ids", "log", "log_also", "when"}) +_WHEN_CHOICES = { + "gpu_vendor": ("nvidia", "amd", "intel"), + "session": ("wayland", "x11"), + "proton_family": ("valve", "ge", "cachyos", "other"), +} +_WHEN_INTS = ("proton_major_min", "proton_major_max") +_WHEN_KEYS = frozenset({*_WHEN_CHOICES, *_WHEN_INTS, "launch_has", "env_set", "env_unset"}) +# Every field listed for a type is required; any other field is a rejection. +_ACTION_FIELDS: dict[str, tuple[str, ...]] = { + "env": ("key", "value"), + "unset_env": ("key",), + "game_arg": ("value",), + "remove_word": ("value",), + "default_proton": (), + "manual": ("text",), +} + + +class PackError(ValueError): + """A pack or rule that does not meet the contract. The message is a short reason.""" + + +@dataclass(frozen=True) +class Action: + type: str # env | unset_env | game_arg | remove_word | default_proton | manual | user_snippet + key: str = "" + value: str = "" + text: str = "" + + +@dataclass(frozen=True) +class When: + gpu_vendor: tuple[str, ...] = () + session: tuple[str, ...] = () + proton_family: tuple[str, ...] = () + proton_major_min: int | None = None + proton_major_max: int | None = None + launch_has: tuple[str, ...] = () + env_set: tuple[str, ...] = () + env_unset: tuple[str, ...] = () + + +@dataclass(frozen=True) +class Rule: + id: str + title: str + cause: str + severity: str + app_ids: tuple[str, ...] + log: tuple[re.Pattern[str], ...] + log_also: tuple[re.Pattern[str], ...] + when: When + actions: tuple[Action, ...] + source: str + verified: str + origin: str = "pack" # "pack" or "user" + + +@dataclass +class Pack: + revision: str + rules: list[Rule] + rejected: list[tuple[str, str]] # (rule id, or "#" when it has no usable id, reason) + + +# --------------------------------------------------------------------------- # +# small field checks +# --------------------------------------------------------------------------- # + +def _check_keys(raw: dict[Any, Any], allowed: Iterable[str], where: str) -> None: + allowed = frozenset(allowed) + for key in raw: + if key not in allowed: + raise PackError(f"{where}: unknown field {key!r}") + + +def _has_control(text: str) -> bool: + return any(unicodedata.category(ch) == "Cc" for ch in text) + + +def _text(value: object, where: str, max_len: int) -> str: + if not isinstance(value, str): + raise PackError(f"{where}: must be a string") + if not value.strip(): + raise PackError(f"{where}: must not be empty") + if len(value) > max_len: + raise PackError(f"{where}: longer than {max_len} characters") + if _has_control(value): + raise PackError(f"{where}: contains a control character") + return value + + +def _str_list(value: object, where: str) -> list[str]: + # An empty list is refused: ``launch_has: []`` would hold vacuously and + # let a rule pass the "not every game" check while matching every game. + if not isinstance(value, list): + raise PackError(f"{where}: must be a list") + if not value: + raise PackError(f"{where}: must not be empty") + for item in value: + if not isinstance(item, str): + raise PackError(f"{where}: every entry must be a string") + return value + + +def _env_key(value: object, where: str) -> str: + if not isinstance(value, str) or not _KEY_RE.fullmatch(value): + raise PackError(f"{where}: not a valid variable name") + if value in _FORBIDDEN_VARS or value.startswith(_FORBIDDEN_PREFIX): + raise PackError(f"{where}: {value} may not be changed by a rule") + return value + + +def _source(value: object) -> str: + if not isinstance(value, str): + raise PackError("source: must be a string") + if not value.startswith("https://"): + raise PackError("source: must start with https://") + if len(value) > 300: + raise PackError("source: longer than 300 characters") + if any(ch.isspace() for ch in value) or _has_control(value): + raise PackError("source: must not contain whitespace") + try: + host = urlsplit(value).hostname + except ValueError: + host = None + if not host: + raise PackError("source: not a URL with a host") + return value + + +def _verified(value: object) -> str: + if not isinstance(value, str) or not _DATE_RE.fullmatch(value): + raise PackError("verified: must be a date as YYYY-MM-DD") + try: + date.fromisoformat(value) + except ValueError: + raise PackError("verified: not a real calendar date") from None + return value + + +# --------------------------------------------------------------------------- # +# log expressions +# --------------------------------------------------------------------------- # + +def _regex_tree(pattern: str) -> list[tuple[Any, ...]] | None: + """A neutral tree of ``pattern``, or None when it cannot be checked. + + The one use of ``re._parser``, the stdlib's private regex parser + (importable on Python 3.11 and 3.12, the versions CI runs). Being private + it can change, so its tree is translated here into a small shape the checks + below own, and any surprise - the module missing, an opcode or layout this + code does not know - returns None, which the caller turns into a rejection + rather than a crash or a silent pass. + + Node kinds: ``("lit",)`` one literal character, ``("char",)`` one + character that is not a literal, ``("zero",)`` a zero-width anchor, + ``("alt", [seq, ...])``, ``("rep", min, seq, max)`` (max None when + open-ended) and ``("look", seq)``. + Groups are spliced into their parent: an unquantified group matches its + contents exactly once (the parser already does this for ``(?:...)``). + Back-references and conditionals are not translated, so they are refused. + """ + try: + from re import _constants as c + from re import _parser + + class_items = (c.LITERAL, c.RANGE, c.CATEGORY, c.NEGATE) + repeats = (c.MAX_REPEAT, c.MIN_REPEAT, c.POSSESSIVE_REPEAT) + + def convert(sub: Any) -> list[tuple[Any, ...]]: + out: list[tuple[Any, ...]] = [] + for op, av in sub: + if op == c.LITERAL: + out.append(("lit",)) + elif op in (c.NOT_LITERAL, c.ANY): + out.append(("char",)) + elif op == c.IN: + if any(item_op not in class_items for item_op, _ in av): + raise ValueError("unknown class item") + out.append(("char",)) + elif op == c.AT: + out.append(("zero",)) + elif op == c.SUBPATTERN: + _group, add_flags, del_flags, body = av + if add_flags or del_flags: + raise ValueError("scoped flags") + out.extend(convert(body)) + elif op == c.ATOMIC_GROUP: + out.extend(convert(av)) + elif op == c.BRANCH: + out.append(("alt", [convert(branch) for branch in av[1]])) + elif op in repeats: + low, high, body = av + top = None if high == c.MAXREPEAT else int(high) + out.append(("rep", int(low), convert(body), top)) + elif op in (c.ASSERT, c.ASSERT_NOT): + out.append(("look", convert(av[1]))) + else: + raise ValueError("unknown opcode") + return out + + return convert(_parser.parse(pattern)) + except Exception: # noqa: BLE001 - any surprise from a private module means "cannot check" + return None + + +def _children(node: tuple[Any, ...]) -> list[list[tuple[Any, ...]]]: + if node[0] == "alt": + return node[1] + if node[0] == "rep": + return [node[2]] + if node[0] == "look": + return [node[1]] + return [] + + +def _contains_repeat(seq: list[tuple[Any, ...]]) -> bool: + return any(n[0] == "rep" or any(_contains_repeat(s) for s in _children(n)) for n in seq) + + +def _has_nested_repeat(seq: list[tuple[Any, ...]]) -> bool: + # An outer quantifier that can match at most once (``?``, ``{0,1}``) does + # not repeat its group, so it cannot multiply the ways the inner repeat + # splits a line; any quantifier inside a real repeat counts, ``?`` too, + # since ``(a?)+`` style patterns backtrack as badly as ``(a+)+``. + return any( + (n[0] == "rep" and (n[3] is None or n[3] > 1) and _contains_repeat(n[2])) + or any(_has_nested_repeat(s) for s in _children(n)) + for n in seq + ) + + +def _open_repeats(seq: list[tuple[Any, ...]]) -> int: + # Summed over alternation branches too: simpler than finding the worst + # branch, and never lower than it. + return sum( + (n[0] == "rep" and n[3] is None) + sum(_open_repeats(s) for s in _children(n)) for n in seq + ) + + +def _literal_run(seq: list[tuple[Any, ...]]) -> int: + """The longest run of literal characters that every match must contain.""" + best = run = 0 + for node in seq: + if node[0] == "lit": + run += 1 + best = max(best, run) + continue + run = 0 + if node[0] == "alt": + # Only text that every branch has is guaranteed. + best = max(best, min(_literal_run(branch) for branch in node[1])) + elif node[0] == "rep" and node[1] >= 1: + best = max(best, _literal_run(node[2])) + return best + + +def _compile_log(pattern: object, where: str) -> re.Pattern[str]: + if not isinstance(pattern, str): + raise PackError(f"{where}: every entry must be a string") + if len(pattern) > _MAX_LOG_PATTERN: + raise PackError(f"{where}: expression longer than {_MAX_LOG_PATTERN} characters") + try: + compiled = re.compile(pattern) + except re.error as exc: + raise PackError(f"{where}: expression does not compile ({exc.msg})") from None + except (RecursionError, OverflowError, ValueError): + raise PackError(f"{where}: expression does not compile") from None + # The contract says matching is case sensitive; inline flags would change + # what a rule means without it being visible in the plain syntax. + if compiled.flags & ~re.UNICODE: + raise PackError(f"{where}: expression must not set flags") + tree = _regex_tree(pattern) + if tree is None: + raise PackError(f"{where}: expression uses a construct that cannot be checked") + if _has_nested_repeat(tree): + raise PackError(f"{where}: expression repeats a group that contains a repeat") + if _open_repeats(tree) > _MAX_OPEN_REPEATS: + raise PackError(f"{where}: expression has more than {_MAX_OPEN_REPEATS} open-ended repeats") + if _literal_run(tree) < _MIN_LITERAL_RUN: + raise PackError(f"{where}: expression needs {_MIN_LITERAL_RUN} literal characters in a row") + return compiled + + +def _compile_log_list(raw: object, where: str) -> tuple[re.Pattern[str], ...]: + if not isinstance(raw, list) or not raw: + raise PackError(f"{where}: must be a non-empty list") + return tuple(_compile_log(p, where) for p in raw) + + +def match_log(rule: Rule, lines: Iterable[str]) -> str | None: + """The first line a ``log`` expression is found in, stripped, or None. + + With ``log_also``, that line counts only if every ``log_also`` expression + is also found in some line (the same line included). One pass, so a + one-shot iterable over a long log tail is fine; it stops as soon as the + answer is known. + """ + if not rule.log: + return None + evidence: str | None = None + missing = list(rule.log_also) + for line in lines: + text = line.rstrip("\r\n")[:_MAX_LINE] + if evidence is None and any(pattern.search(text) for pattern in rule.log): + evidence = text.strip() + if missing: + missing = [pattern for pattern in missing if not pattern.search(text)] + if evidence is not None and not missing: + return evidence + return None + + +# --------------------------------------------------------------------------- # +# rules +# --------------------------------------------------------------------------- # + +def _parse_when(raw: object) -> When: + if not isinstance(raw, dict): + raise PackError("when: must be an object") + _check_keys(raw, _WHEN_KEYS, "when") + if not raw: + raise PackError("when: has no conditions") + fields: dict[str, Any] = {} + for name, choices in _WHEN_CHOICES.items(): + if name in raw: + items = _str_list(raw[name], f"when.{name}") + for item in items: + if item not in choices: + raise PackError(f"when.{name}: {item!r} is not one of {', '.join(choices)}") + fields[name] = tuple(items) + for name in _WHEN_INTS: + if name in raw: + value = raw[name] + if type(value) is not int or value < 0: # bool is an int subclass; refuse it + raise PackError(f"when.{name}: must be a whole number") + fields[name] = value + low, high = fields.get("proton_major_min"), fields.get("proton_major_max") + if low is not None and high is not None and low > high: + raise PackError("when: proton_major_min is above proton_major_max") + if "launch_has" in raw: + words = _str_list(raw["launch_has"], "when.launch_has") + for word in words: + if not _WORD_RE.fullmatch(word): + raise PackError(f"when.launch_has: {word!r} is not a command name") + fields["launch_has"] = tuple(words) + for name in ("env_set", "env_unset"): + if name in raw: + names = _str_list(raw[name], f"when.{name}") + for var in names: + if not _KEY_RE.fullmatch(var): + raise PackError(f"when.{name}: {var!r} is not a valid variable name") + fields[name] = tuple(names) + return When(**fields) + + +def _parse_action(raw: object, where: str) -> Action: + if not isinstance(raw, dict): + raise PackError(f"{where}: must be an object") + kind = raw.get("type") + if kind == "user_snippet": + raise PackError(f"{where}: user_snippet is not a pack action") + if not isinstance(kind, str) or kind not in _ACTION_FIELDS: + raise PackError(f"{where}: unknown action type {kind!r}") + needed = _ACTION_FIELDS[kind] + _check_keys(raw, ("type", *needed), where) + for name in needed: + if name not in raw: + raise PackError(f"{where}: {kind} needs {name}") + if kind == "env": + key = _env_key(raw["key"], f"{where}.key") + value = raw["value"] + if not isinstance(value, str) or not _ENV_VALUE_RE.fullmatch(value): + raise PackError(f"{where}.value: not allowed for env (letters, digits and _.,:=/+@%- only)") + # Steam substitutes %command% wherever it appears, so a value holding + # it would splice the game's command line into the assignment. + if "%command%" in value: + raise PackError(f"{where}.value: must not contain %command%") + return Action("env", key=key, value=value) + if kind == "unset_env": + return Action("unset_env", key=_env_key(raw["key"], f"{where}.key")) + if kind == "game_arg": + value = raw["value"] + if not isinstance(value, str) or not _GAME_ARG_RE.fullmatch(value): + raise PackError(f"{where}.value: not a single game switch such as -vulkan") + return Action("game_arg", value=value) + if kind == "remove_word": + value = raw["value"] + if not isinstance(value, str) or not _WORD_RE.fullmatch(value): + raise PackError(f"{where}.value: not a command name") + return Action("remove_word", value=value) + if kind == "manual": + return Action("manual", text=_text(raw["text"], f"{where}.text", 300)) + return Action("default_proton") + + +def _parse_actions(raw: object) -> tuple[Action, ...]: + if not isinstance(raw, list): + raise PackError("actions: must be a list") + if len(raw) > _MAX_ACTIONS: + raise PackError(f"actions: more than {_MAX_ACTIONS}") + actions = tuple(_parse_action(item, f"actions[{i}]") for i, item in enumerate(raw)) + # Actions are applied and undone together; two that touch the same + # variable (or repeat each other) leave the result order-dependent. + keys = [a.key for a in actions if a.type in ("env", "unset_env")] + if len(keys) != len(set(keys)): + raise PackError("actions: two actions change the same variable") + if len(actions) != len(set(actions)): + raise PackError("actions: the same action is listed twice") + return actions + + +def parse_rule(raw: object) -> Rule: + """Validate one rule from a pack. Raises :class:`PackError` with the first problem found.""" + if not isinstance(raw, dict): + raise PackError("rule: must be an object") + _check_keys(raw, _RULE_KEYS, "rule") + for name in _RULE_KEYS: + if name not in raw: + raise PackError(f"rule: missing {name}") + + rule_id = raw["id"] + if not isinstance(rule_id, str) or not _ID_RE.fullmatch(rule_id): + raise PackError("id: 3 to 64 lowercase letters, digits and hyphens") + if rule_id.startswith(_USER_ID_PREFIX): + raise PackError(f"id: the {_USER_ID_PREFIX} prefix is kept for the user's own fixes") + title = _text(raw["title"], "title", 100) + cause = _text(raw["cause"], "cause", 400) + severity = raw["severity"] + if severity not in SEVERITIES: + raise PackError(f"severity: must be one of {', '.join(SEVERITIES)}") + + match = raw["match"] + if not isinstance(match, dict): + raise PackError("match: must be an object") + _check_keys(match, _MATCH_KEYS, "match") + app_ids: tuple[str, ...] = () + if "app_ids" in match: + ids = _str_list(match["app_ids"], "match.app_ids") + for app_id in ids: + if not _APP_ID_RE.fullmatch(app_id): + raise PackError(f"match.app_ids: {app_id!r} is not a Steam App ID") + app_ids = tuple(ids) + log = _compile_log_list(match["log"], "match.log") if "log" in match else () + if "log_also" in match and "log" not in match: + raise PackError("match.log_also: only allowed together with log") + log_also = _compile_log_list(match["log_also"], "match.log_also") if "log_also" in match else () + when = _parse_when(match["when"]) if "when" in match else When() + if not (app_ids or log or when.launch_has or when.env_set): + raise PackError("match: needs app_ids, log, or a when with launch_has or env_set") + if app_ids and not log and severity != "advice": + raise PackError("severity: a rule with app_ids and no log must be advice") + + return Rule( + id=rule_id, + title=title, + cause=cause, + severity=severity, + app_ids=app_ids, + log=log, + log_also=log_also, + when=when, + actions=_parse_actions(raw["actions"]), + source=_source(raw["source"]), + verified=_verified(raw["verified"]), + ) + + +# --------------------------------------------------------------------------- # +# packs +# --------------------------------------------------------------------------- # + +def _usable_id(raw: object) -> str | None: + if isinstance(raw, dict): + rule_id = raw.get("id") + if isinstance(rule_id, str) and _ID_RE.fullmatch(rule_id): + return rule_id + return None + + +def parse_pack(data: object) -> Pack: + """Validate a decoded pack. + + Raises :class:`PackError` when ``data`` is not a pack at all or is a + version this app does not understand; a rule that fails is reported in + ``rejected`` and the others still load. + """ + if not isinstance(data, dict) or data.get("format") != PACK_FORMAT: + raise PackError(f"not a fix pack (format is not {PACK_FORMAT})") + version = data.get("version") + if type(version) is not int: + raise PackError("version must be a whole number") + if version > PACK_VERSION: + raise PackError(f"pack version {version} is newer than this app understands") + if version != PACK_VERSION: + raise PackError(f"pack version {version} is not supported") + _check_keys(data, _PACK_KEYS, "pack") + revision = data.get("revision") + if not isinstance(revision, str) or not _REVISION_RE.fullmatch(revision): + raise PackError("revision must look like YYYY.MM.N") + raw_rules = data.get("rules") + if not isinstance(raw_rules, list): + raise PackError("rules must be a list") + + rules: list[Rule] = [] + rejected: list[tuple[str, str]] = [] + # Every id seen so far, accepted or not: a later rule never takes the + # place of an earlier one, whatever happened to the earlier one. + seen: set[str] = set() + for index, raw in enumerate(raw_rules): + rule_id = _usable_id(raw) + label = rule_id or f"#{index}" + if rule_id is not None and rule_id in seen: + rejected.append((label, "duplicate id")) + continue + if rule_id is not None: + seen.add(rule_id) + try: + rules.append(parse_rule(raw)) + except PackError as exc: + rejected.append((label, str(exc))) + return Pack(revision, rules, rejected) + + +def _no_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + # json keeps the last of two equal keys silently; in a rule that would + # let one reading of the file differ from another. + out: dict[str, Any] = {} + for key, value in pairs: + if key in out: + raise PackError(f"duplicate key {key!r}") + out[key] = value + return out + + +def load_pack(path: Path) -> Pack: + """Read, decode and validate the pack at ``path``. Raises :class:`PackError`.""" + try: + with open(path, "rb") as fh: + if not stat.S_ISREG(os.fstat(fh.fileno()).st_mode): + raise PackError("pack is not a regular file") + raw = fh.read(_MAX_PACK_BYTES + 1) + except OSError as exc: + raise PackError(f"cannot read the pack ({exc.strerror or exc})") from None + if len(raw) > _MAX_PACK_BYTES: + raise PackError("pack file is larger than 2 MB") + try: + data = json.loads(raw.decode("utf-8"), object_pairs_hook=_no_duplicate_keys) + except PackError: + raise + except UnicodeDecodeError: + raise PackError("pack is not UTF-8 text") from None + except (ValueError, RecursionError): + raise PackError("pack is not valid JSON") from None + return parse_pack(data) + + +def load_bundled_pack() -> Pack: + """The pack shipped with the app. Never raises; a failure is one ``("pack", reason)`` entry.""" + try: + return load_pack(_BUNDLED_PATH) + except PackError as exc: + return Pack("", [], [("pack", str(exc))]) + except Exception: # noqa: BLE001 - Diagnose must still open with an empty pack + return Pack("", [], [("pack", "the bundled pack could not be loaded")]) + + +# --------------------------------------------------------------------------- # +# the user's own fixes +# --------------------------------------------------------------------------- # + +def _user_action(entry: dict[Any, Any]) -> Action | None: + value = entry.get("value", "") + # A line break or NUL would end the launch-options line or the string + # carrying it; nothing else about the user's own value is limited. + if not isinstance(value, str) or any(ch in value for ch in "\n\r\0"): + return None + kind = entry.get("type") + if kind == "env": + key = entry.get("key", "") + if not isinstance(key, str) or not _KEY_RE.fullmatch(key): + return None + return Action("env", key=key, value=value) + if kind == "launch_arg": + snippet = value.strip() + if not snippet or len(snippet) > _MAX_USER_SNIPPET: + return None + return Action("user_snippet", value=snippet) + return None + + +def user_rules(app_id: str) -> list[Rule]: + """The user's version 1 fixes for ``app_id`` as advice rules; unusable entries are skipped.""" + rules: list[Rule] = [] + for position, entry in enumerate(_fixes._load_user_fixes(app_id), start=1): + if not isinstance(entry, dict): + continue + title = entry.get("title", "") + description = entry.get("description", "") + if not isinstance(title, str) or not isinstance(description, str): + continue + action = _user_action(entry) + if action is None: + continue + rules.append(Rule( + id=f"{_USER_ID_PREFIX}{position}", + title=title.strip()[:100] or "Your own fix", + cause=description.strip()[:400], + severity="advice", + app_ids=(app_id,), + log=(), + log_also=(), + when=When(), + actions=(action,), + source="", + verified="", + origin="user", + )) + return rules diff --git a/tests/test_core_safety.py b/tests/test_core_safety.py index 4589e40..31b0bc1 100644 --- a/tests/test_core_safety.py +++ b/tests/test_core_safety.py @@ -3,7 +3,8 @@ Pure-core tests: no Qt imports, everything runs against tmp_path. Covers the audit fixes: app_id path traversal (shader cache), bash-key injection (ScopeBuddy), tolerant decoding, fail-closed JSON writes -(Heroic, user fixes), VDF Apps/apps merge, and backup filename uniqueness. +(Heroic, user fixes), VDF Apps/apps merge, backup filename uniqueness, and +fix pack rules that cannot carry shell text into launch options. """ from __future__ import annotations @@ -18,6 +19,7 @@ from protonshift.core import fixes as fixes_mod from protonshift.core import heroic_config, saves from protonshift.core import paths as paths_mod +from protonshift.core.fix_pack import PackError, parse_rule from protonshift.core.mangohud import read_mangohud_config from protonshift.core.prefix import delete_prefix from protonshift.core.scopebuddy import parse_scb_conf, write_scb_conf @@ -332,3 +334,65 @@ def test_delete_prefix_refuses_permitted_root( monkeypatch.setattr(paths_mod, "_USER_PATH_ROOTS", (home,)) assert delete_prefix(str(home)) is False assert home.is_dir() + + +# --------------------------------------------------------------------------- # +# fix pack: a rule cannot smuggle shell text into launch options +# --------------------------------------------------------------------------- # + +def _pack_rule(*actions: dict) -> dict: + return { + "id": "smuggle-test", + "title": "t", + "cause": "c", + "severity": "blocking", + "match": {"log": [r"wine: could not load kernel32\.dll"]}, + "actions": list(actions), + "source": "https://example.org/issue/1", + "verified": "2026-11-16", + } + + +def test_fix_pack_safe_rule_parses() -> None: + parsed = parse_rule(_pack_rule( + {"type": "env", "key": "PROTON_ENABLE_NVAPI", "value": "1"}, + {"type": "game_arg", "value": "-vulkan"}, + {"type": "remove_word", "value": "gamemoderun"}, + )) + assert len(parsed.actions) == 3 + + +@pytest.mark.parametrize( + "value", + ["1 2", "1;reboot", "$(reboot)", "`reboot`", "'1'", '"1"', "1\nreboot", "1\rreboot", "1&&x", "1|x", "%command%"], +) +def test_fix_pack_env_value_rejects_shell_text(value: str) -> None: + with pytest.raises(PackError): + parse_rule(_pack_rule({"type": "env", "key": "DXVK_HUD", "value": value})) + + +@pytest.mark.parametrize("value", ["vulkan", "%command%", "-a b", "-vulkan;reboot", "-x$(id)", "-a\n"]) +def test_fix_pack_game_arg_must_be_one_switch(value: str) -> None: + with pytest.raises(PackError): + parse_rule(_pack_rule({"type": "game_arg", "value": value})) + + +@pytest.mark.parametrize("value", ["/usr/bin/gamemoderun", "../gamemoderun", "game moderun", "a;b", "%command%"]) +def test_fix_pack_remove_word_rejects_paths_and_spaces(value: str) -> None: + with pytest.raises(PackError): + parse_rule(_pack_rule({"type": "remove_word", "value": value})) + + +@pytest.mark.parametrize("key", ["LD_PRELOAD", "PATH", "STEAM_COMPAT_DATA_PATH", "LD_LIBRARY_PATH", "WINEDLLPATH"]) +@pytest.mark.parametrize("kind", ["env", "unset_env"]) +def test_fix_pack_rejects_loader_variables(kind: str, key: str) -> None: + action = {"type": kind, "key": key} + if kind == "env": + action["value"] = "/tmp/x" + with pytest.raises(PackError): + parse_rule(_pack_rule(action)) + + +def test_fix_pack_rejects_user_snippet_action() -> None: + with pytest.raises(PackError): + parse_rule(_pack_rule({"type": "user_snippet", "value": "reboot; %command%"})) diff --git a/tests/test_fix_pack.py b/tests/test_fix_pack.py new file mode 100644 index 0000000..1280bff --- /dev/null +++ b/tests/test_fix_pack.py @@ -0,0 +1,1078 @@ +"""Tests for protonshift.core.fix_pack - the Diagnose rule file loader. + +docs/fix-pack.md is the contract these tests hold the loader to. Pure core: +no Qt, no network, no real home directory. +""" + +from __future__ import annotations + +import copy +import json +import re +from pathlib import Path +from typing import Any + +import pytest + +from protonshift.core import fix_pack +from protonshift.core import fixes as fixes_mod +from protonshift.core.fix_pack import ( + PACK_FORMAT, + PACK_VERSION, + Action, + PackError, + load_bundled_pack, + load_pack, + match_log, + parse_pack, + parse_rule, + user_rules, +) + +LOG_LINE = r"wine: could not load kernel32\.dll" + + +def rule(**overrides: Any) -> dict[str, Any]: + """A minimal valid rule; keyword overrides replace top-level fields.""" + base: dict[str, Any] = { + "id": "kernel32-missing", + "title": "Wine could not load kernel32", + "cause": "The prefix is broken.", + "severity": "blocking", + "match": {"log": [LOG_LINE]}, + "actions": [], + "source": "https://github.com/ValveSoftware/Proton/issues/1", + "verified": "2026-11-16", + } + base.update(overrides) + return base + + +def with_match(**match: Any) -> dict[str, Any]: + return rule(match=match) + + +def with_actions(*actions: dict[str, Any]) -> dict[str, Any]: + return rule(actions=list(actions)) + + +def pack(*rules: Any, **overrides: Any) -> dict[str, Any]: + base: dict[str, Any] = { + "format": PACK_FORMAT, + "version": PACK_VERSION, + "revision": "2026.11.1", + "rules": list(rules), + } + base.update(overrides) + return base + + +def rejects(raw: Any, fragment: str = "") -> str: + with pytest.raises(PackError) as info: + parse_rule(raw) + assert fragment in str(info.value), str(info.value) + return str(info.value) + + +# --------------------------------------------------------------------------- # +# a valid rule +# --------------------------------------------------------------------------- # + +def test_minimal_rule_parses() -> None: + r = parse_rule(rule()) + assert r.id == "kernel32-missing" + assert r.severity == "blocking" + assert r.app_ids == () + assert [p.pattern for p in r.log] == [LOG_LINE] + assert r.log_also == () + assert r.actions == () + assert r.origin == "pack" + + +def test_full_rule_parses() -> None: + r = parse_rule(rule( + match={ + "app_ids": ["1091500", "570"], + "log": [LOG_LINE], + "log_also": [r"err:module:import_dll"], + "when": { + "gpu_vendor": ["nvidia", "amd"], + "session": ["wayland"], + "proton_family": ["ge"], + "proton_major_min": 8, + "proton_major_max": 9, + "launch_has": ["gamemoderun"], + "env_set": ["DXVK_HUD"], + "env_unset": ["PROTON_LOG"], + }, + }, + actions=[ + {"type": "env", "key": "PROTON_ENABLE_NVAPI", "value": "1"}, + {"type": "unset_env", "key": "DXVK_ASYNC"}, + {"type": "game_arg", "value": "-vulkan"}, + {"type": "remove_word", "value": "gamemoderun"}, + {"type": "default_proton"}, + {"type": "manual", "text": "Verify the game files in Steam."}, + ], + )) + assert r.app_ids == ("1091500", "570") + assert r.when.gpu_vendor == ("nvidia", "amd") + assert r.when.proton_major_min == 8 and r.when.proton_major_max == 9 + assert r.when.launch_has == ("gamemoderun",) + assert [a.type for a in r.actions] == [ + "env", "unset_env", "game_arg", "remove_word", "default_proton", "manual", + ] + assert r.actions[0] == Action("env", key="PROTON_ENABLE_NVAPI", value="1") + assert r.actions[5].text == "Verify the game files in Steam." + + +def test_rule_is_frozen() -> None: + r = parse_rule(rule()) + with pytest.raises(AttributeError): + r.title = "changed" # type: ignore[misc] + + +# --------------------------------------------------------------------------- # +# top-level fields +# --------------------------------------------------------------------------- # + +@pytest.mark.parametrize("raw", [None, [], "rule", 3]) +def test_rule_must_be_an_object(raw: Any) -> None: + rejects(raw, "must be an object") + + +@pytest.mark.parametrize("missing", ["id", "title", "cause", "severity", "match", "actions", "source", "verified"]) +def test_every_field_is_required(missing: str) -> None: + raw = rule() + del raw[missing] + rejects(raw, f"missing {missing}") + + +def test_unknown_rule_field_is_rejected() -> None: + raw = rule() + raw["serverity"] = "advice" + rejects(raw, "unknown field 'serverity'") + + +@pytest.mark.parametrize( + "bad_id", + ["ab", "a" * 65, "Upper-case", "under_score", "spa ce", "dot.ted", "", 7, None, "kernel\n"], +) +def test_bad_ids(bad_id: Any) -> None: + rejects(rule(id=bad_id), "id:") + + +@pytest.mark.parametrize("good_id", ["abc", "a" * 64, "0-9", "wrapper-gamemoderun-missing"]) +def test_good_ids(good_id: str) -> None: + assert parse_rule(rule(id=good_id)).id == good_id + + +def test_user_prefix_is_reserved() -> None: + rejects(rule(id="user-1"), "user-") + + +@pytest.mark.parametrize("field,limit", [("title", 100), ("cause", 400)]) +def test_text_limits(field: str, limit: int) -> None: + assert getattr(parse_rule(rule(**{field: "x" * limit})), field) == "x" * limit + rejects(rule(**{field: "x" * (limit + 1)}), f"longer than {limit}") + + +@pytest.mark.parametrize("field", ["title", "cause"]) +@pytest.mark.parametrize("bad", ["", " ", 5, None, ["text"], "two\nlines", "tab\there", "nul\0"]) +def test_text_rejections(field: str, bad: Any) -> None: + rejects(rule(**{field: bad}), f"{field}:") + + +@pytest.mark.parametrize("severity", ["blocking", "likely", "advice"]) +def test_severities(severity: str) -> None: + assert parse_rule(rule(severity=severity)).severity == severity + + +@pytest.mark.parametrize("bad", ["Blocking", "error", "", None, 1, ["advice"]]) +def test_bad_severity(bad: Any) -> None: + rejects(rule(severity=bad), "severity:") + + +@pytest.mark.parametrize( + "good", + [ + "https://github.com/ValveSoftware/Proton/issues/1", + "https://gitlab.winehq.org/wine/wine/-/blob/master/dlls/ntdll/loader.c#L100", + "https://example.org/" + "a" * (300 - len("https://example.org/")), + ], +) +def test_good_sources(good: str) -> None: + assert parse_rule(rule(source=good)).source == good + + +@pytest.mark.parametrize( + "bad", + [ + "http://github.com/x", + "github.com/x", + "ftp://x.org/y", + "https://", + "https:///path", + "https://ex ample.org/", + "https://example.org/\n", + "https://example.org/\ttab", + "https://example.org/" + "a" * 281, + "HTTPS://example.org/", + "", + None, + 3, + ], +) +def test_bad_sources(bad: Any) -> None: + rejects(rule(source=bad), "source:") + + +@pytest.mark.parametrize("good", ["2026-11-16", "2024-02-29", "1999-01-01"]) +def test_good_verified(good: str) -> None: + assert parse_rule(rule(verified=good)).verified == good + + +@pytest.mark.parametrize( + "bad", + ["2026-02-30", "2025-02-29", "2026-13-01", "2026-1-16", "20261116", "2026-11-16T00:00", + "16-11-2026", "2026-11-16\n", "", None, 20261116], +) +def test_bad_verified(bad: Any) -> None: + rejects(rule(verified=bad), "verified:") + + +# --------------------------------------------------------------------------- # +# match +# --------------------------------------------------------------------------- # + +def test_match_must_be_an_object() -> None: + rejects(rule(match=["570"]), "match: must be an object") + + +def test_unknown_match_field_is_rejected() -> None: + rejects(with_match(log=[LOG_LINE], apps=["570"]), "unknown field 'apps'") + + +def test_empty_match_is_rejected() -> None: + rejects(with_match(), "match: needs") + + +@pytest.mark.parametrize( + "match", + [ + {"app_ids": ["570"]}, + {"log": [LOG_LINE]}, + {"when": {"launch_has": ["gamemoderun"]}}, + {"when": {"env_set": ["DXVK_HUD"]}}, + ], +) +def test_match_presence_rule_accepts(match: dict[str, Any]) -> None: + parse_rule(rule(match=match, severity="advice")) + + +@pytest.mark.parametrize( + "when", + [ + {"gpu_vendor": ["nvidia"]}, + {"session": ["wayland"]}, + {"proton_family": ["ge"], "proton_major_min": 8}, + {"env_unset": ["DXVK_HUD"]}, + ], +) +def test_match_presence_rule_rejects_machine_only_when(when: dict[str, Any]) -> None: + rejects(rule(match={"when": when}, severity="advice"), "match: needs") + + +def test_app_ids_without_log_must_be_advice() -> None: + assert parse_rule(rule(match={"app_ids": ["570"]}, severity="advice")).severity == "advice" + for severity in ("blocking", "likely"): + rejects(rule(match={"app_ids": ["570"]}, severity=severity), "must be advice") + + +def test_app_ids_with_log_may_be_blocking() -> None: + assert parse_rule(with_match(app_ids=["570"], log=[LOG_LINE])).severity == "blocking" + + +@pytest.mark.parametrize( + "bad", + ["570", 570, [], [570], ["57 0"], ["-570"], ["abc"], ["570\n"], ["٥٧٠"], [None]], +) +def test_bad_app_ids(bad: Any) -> None: + rejects(rule(match={"app_ids": bad, "log": [LOG_LINE]}), "match.app_ids") + + +@pytest.mark.parametrize("bad", ["just a string", [], None, {"a": 1}]) +def test_bad_log_container(bad: Any) -> None: + rejects(with_match(log=bad), "match.log") + + +def test_log_entries_must_be_strings() -> None: + rejects(with_match(log=[LOG_LINE, 7]), "must be a string") + + +# --------------------------------------------------------------------------- # +# when +# --------------------------------------------------------------------------- # + +def when_rule(**when: Any) -> dict[str, Any]: + return rule(match={"log": [LOG_LINE], "when": when}) + + +def test_when_must_be_an_object() -> None: + rejects(rule(match={"log": [LOG_LINE], "when": ["nvidia"]}), "when: must be an object") + + +def test_empty_when_is_rejected() -> None: + rejects(when_rule(), "no conditions") + + +def test_unknown_when_field_is_rejected() -> None: + rejects(when_rule(gpu_vendors=["nvidia"]), "unknown field 'gpu_vendors'") + + +@pytest.mark.parametrize( + "name,good,bad", + [ + ("gpu_vendor", ["nvidia", "amd", "intel"], ["NVIDIA"]), + ("session", ["wayland", "x11"], ["xorg"]), + ("proton_family", ["valve", "ge", "cachyos", "other"], ["proton-ge"]), + ], +) +def test_when_choice_lists(name: str, good: list[str], bad: list[str]) -> None: + assert getattr(parse_rule(when_rule(**{name: good})).when, name) == tuple(good) + rejects(when_rule(**{name: bad}), f"when.{name}") + rejects(when_rule(**{name: []}), "must not be empty") + rejects(when_rule(**{name: good[0]}), "must be a list") + + +@pytest.mark.parametrize("name", ["proton_major_min", "proton_major_max"]) +@pytest.mark.parametrize("bad", ["9", 9.0, True, False, -1, None, [9]]) +def test_when_ints_reject(name: str, bad: Any) -> None: + rejects(when_rule(**{name: bad}), f"when.{name}") + + +@pytest.mark.parametrize("name", ["proton_major_min", "proton_major_max"]) +def test_when_ints_accept(name: str) -> None: + assert getattr(parse_rule(when_rule(**{name: 0})).when, name) == 0 + assert getattr(parse_rule(when_rule(**{name: 10})).when, name) == 10 + + +def test_when_min_above_max_is_rejected() -> None: + assert parse_rule(when_rule(proton_major_min=9, proton_major_max=9)).when.proton_major_max == 9 + rejects(when_rule(proton_major_min=10, proton_major_max=9), "above") + + +@pytest.mark.parametrize("bad", [["game moderun"], ["gamemoderun;"], ["a/b"], [""], ["x" * 41], [1]]) +def test_when_launch_has_rejects(bad: list[Any]) -> None: + rejects(when_rule(launch_has=bad), "when.launch_has") + + +@pytest.mark.parametrize("name", ["env_set", "env_unset"]) +@pytest.mark.parametrize("bad", [["1ABC"], ["A-B"], ["A B"], ["A\n"], [""], "DXVK_HUD", []]) +def test_when_env_names_reject(name: str, bad: Any) -> None: + rejects(when_rule(**{name: bad}), f"when.{name}") + + +def test_when_env_lists_do_not_use_the_forbidden_list() -> None: + # Conditions only read the launch options; checking for PATH is harmless. + assert parse_rule(when_rule(env_set=["LD_PRELOAD"])).when.env_set == ("LD_PRELOAD",) + + +# --------------------------------------------------------------------------- # +# actions +# --------------------------------------------------------------------------- # + +@pytest.mark.parametrize("bad", [None, {}, "env", {"type": "env"}]) +def test_actions_must_be_a_list(bad: Any) -> None: + rejects(rule(actions=bad), "actions: must be a list") + + +def test_at_most_six_actions() -> None: + six = [{"type": "game_arg", "value": f"-a{i}"} for i in range(6)] + assert len(parse_rule(rule(actions=six)).actions) == 6 + seven = [{"type": "game_arg", "value": f"-a{i}"} for i in range(7)] + rejects(rule(actions=seven), "more than 6") + + +@pytest.mark.parametrize("bad", ["remove", "", None, 3, "ENV", "user_snippet"]) +def test_unknown_action_types(bad: Any) -> None: + rejects(with_actions({"type": bad, "value": "x"}), "actions[0]") + + +def test_action_without_type() -> None: + rejects(with_actions({"key": "A", "value": "1"}), "unknown action type") + + +def test_action_must_be_an_object() -> None: + rejects(with_actions("env"), "actions[0]: must be an object") # type: ignore[arg-type] + + +@pytest.mark.parametrize( + "action", + [ + {"type": "env", "key": "A", "value": "1", "text": "x"}, + {"type": "unset_env", "key": "A", "value": ""}, + {"type": "game_arg", "value": "-vulkan", "key": "A"}, + {"type": "remove_word", "value": "gamemoderun", "position": "before"}, + {"type": "default_proton", "value": "GE-Proton9-1"}, + {"type": "manual", "text": "Do it.", "url": "https://x.org"}, + ], +) +def test_unknown_action_fields(action: dict[str, Any]) -> None: + rejects(with_actions(action), "unknown field") + + +@pytest.mark.parametrize( + "action", + [ + {"type": "env", "key": "A"}, + {"type": "env", "value": "1"}, + {"type": "unset_env"}, + {"type": "game_arg"}, + {"type": "remove_word"}, + {"type": "manual"}, + ], +) +def test_missing_action_fields(action: dict[str, Any]) -> None: + rejects(with_actions(action), "needs") + + +@pytest.mark.parametrize( + "value", + ["", "1", "fps,frametime", "/tmp/dxvk.log", "a=b", "user@host", "50%", "1.5:2+3-4_x", "x" * 200], +) +def test_env_values_accepted(value: str) -> None: + (action,) = parse_rule(with_actions({"type": "env", "key": "DXVK_HUD", "value": value})).actions + assert action.value == value + + +@pytest.mark.parametrize( + "value", + ["a b", "x" * 201, "a;b", "$(id)", "`id`", "'q'", '"q"', "a\nb", "a|b", "a&b", "~", "a*", "%command%", + "x%command%y", 1, None, True], +) +def test_env_values_rejected(value: Any) -> None: + rejects(with_actions({"type": "env", "key": "DXVK_HUD", "value": value}), "value") + + +@pytest.mark.parametrize("key", ["A", "_", "_a1", "DXVK_HUD", "mesa_glthread"]) +@pytest.mark.parametrize("kind", ["env", "unset_env"]) +def test_env_keys_accepted(kind: str, key: str) -> None: + action: dict[str, Any] = {"type": kind, "key": key} + if kind == "env": + action["value"] = "1" + assert parse_rule(with_actions(action)).actions[0].key == key + + +@pytest.mark.parametrize( + "key", + ["", "1A", "A-B", "A B", "A=", "A\n", "ÉTÉ", None, 5, + "LD_PRELOAD", "LD_LIBRARY_PATH", "LD_AUDIT", "PATH", "PYTHONPATH", + "STEAM_COMPAT_LAUNCHER_SERVICE", "WINEDLLPATH", "STEAM_COMPAT_DATA_PATH", "STEAM_COMPAT_"], +) +@pytest.mark.parametrize("kind", ["env", "unset_env"]) +def test_env_keys_rejected(kind: str, key: Any) -> None: + action: dict[str, Any] = {"type": kind, "key": key} + if kind == "env": + action["value"] = "1" + rejects(with_actions(action), "key") + + +def test_forbidden_list_is_case_sensitive() -> None: + # Variables are case sensitive: ``path`` is not ``PATH``. + assert parse_rule(with_actions({"type": "env", "key": "path", "value": "1"})).actions[0].key == "path" + rejects(with_actions({"type": "unset_env", "key": "STEAM_COMPAT_CLIENT_INSTALL_PATH"}), "may not") + + +@pytest.mark.parametrize("value", ["-vulkan", "+fps_max=0", "-dx11", "-a", "+x:y.z", "-" + "a" * 60]) +def test_game_arg_accepted(value: str) -> None: + assert parse_rule(with_actions({"type": "game_arg", "value": value})).actions[0].value == value + + +@pytest.mark.parametrize( + "value", + ["vulkan", "-", "+", "-a b", "-" + "a" * 61, "-a;b", "-$(id)", "-a/b", "%command%", "--x\n", "", 1, None], +) +def test_game_arg_rejected(value: Any) -> None: + rejects(with_actions({"type": "game_arg", "value": value}), "value") + + +@pytest.mark.parametrize("value", ["gamemoderun", "mangohud", "obs-gamecapture", "a.b_c", "x" * 40]) +def test_remove_word_accepted(value: str) -> None: + assert parse_rule(with_actions({"type": "remove_word", "value": value})).actions[0].value == value + + +@pytest.mark.parametrize( + "value", + ["", "x" * 41, "/usr/bin/gamemoderun", "a b", "%command%", "A=1", "a;b", "a\n", 1, None], +) +def test_remove_word_rejected(value: Any) -> None: + rejects(with_actions({"type": "remove_word", "value": value}), "value") + + +def test_manual_text_limits() -> None: + assert parse_rule(with_actions({"type": "manual", "text": "x" * 300})).actions[0].text == "x" * 300 + rejects(with_actions({"type": "manual", "text": "x" * 301}), "longer than 300") + rejects(with_actions({"type": "manual", "text": ""}), "empty") + rejects(with_actions({"type": "manual", "text": 5}), "string") + + +def test_default_proton_has_no_fields() -> None: + assert parse_rule(with_actions({"type": "default_proton"})).actions == (Action("default_proton"),) + + +@pytest.mark.parametrize( + "actions", + [ + [{"type": "env", "key": "A", "value": "1"}, {"type": "env", "key": "A", "value": "2"}], + [{"type": "env", "key": "A", "value": "1"}, {"type": "unset_env", "key": "A"}], + [{"type": "default_proton"}, {"type": "default_proton"}], + [{"type": "game_arg", "value": "-vulkan"}, {"type": "game_arg", "value": "-vulkan"}], + ], +) +def test_conflicting_or_repeated_actions(actions: list[dict[str, Any]]) -> None: + rejects(rule(actions=actions), "actions:") + + +# --------------------------------------------------------------------------- # +# log expressions +# --------------------------------------------------------------------------- # + +@pytest.mark.parametrize( + "pattern", + [ + LOG_LINE, + r"\.\.\.\.\.\.\.\.", # escaped characters are literals + r"[.][.][.][.][.][.][.][.]", # a one-member class is that literal + r"(kern)el32", # an unquantified group is part of the run + r"(?:kernel32\.dll)+", # a repeat that happens at least once guarantees its text + r"kernel32\.dll|kernel32\.sys", # both branches share the run + r"^err:module:import_dll Library \S+ not found$", + r"(?:\d+ )?err:module:", # an optional group may hold a repeat + r"(?=x)kernel32dll", + r"x{0,1}abcdefgh", + r"(?>vkCreate)Instance failed", + ], +) +def test_log_expressions_accepted(pattern: str) -> None: + assert parse_rule(with_match(log=[pattern])).log[0].pattern == pattern + + +def test_log_expression_length_limit() -> None: + exact = "kernel32" + "x" * 292 + assert len(exact) == 300 + parse_rule(with_match(log=[exact])) + rejects(with_match(log=[exact + "x"]), "longer than 300") + + +@pytest.mark.parametrize( + "pattern", + [ + r"err:", + r"kernel3", + r"kernel3.dll", # . is not a literal + r"[kK]ernel32", # a class of two is not a literal + r"\bkernel\b32dll", # an anchor breaks the run + r"abcdefg|abcdefgh", # one branch is too short + r"(?:kernel32\.dll)*", # may not happen at all + r"(?:kernel32\.dll)?", + r"(?=kernel32\.dll)", # lookaround text is not consumed + r"a{8}", + r".*", + r"", + ], +) +def test_log_expressions_without_a_literal_run(pattern: str) -> None: + rejects(with_match(log=[pattern]), "8 literal characters") + + +@pytest.mark.parametrize( + "pattern", + [ + r"(a+)+kernel32dll", + r"(?:a*)*kernel32dll", + r"(a|b+)*kernel32dll", + r"(a?)+kernel32dll", + r"(a{2}){3}kernel32dll", + r"(?:x(?:y+z)+)+kernel32dll", + r"(\d+\s)++kernel32dll", + r"kernel32dll(?=(a+)+)", + ], +) +def test_log_expressions_with_nested_repeats(pattern: str) -> None: + rejects(with_match(log=[pattern]), "repeats a group") + + +@pytest.mark.parametrize("pattern", [r"kernel32(", r"kernel32[", "kernel32\\", r"*kernel32", r"kernel32{2,1}"]) +def test_log_expressions_that_do_not_compile(pattern: str) -> None: + rejects(with_match(log=[pattern]), "does not compile") + + +@pytest.mark.parametrize( + "pattern", + [ + r"Library (\S+) \(which is needed by .+\) not found", # two open-ended repeats + r"kernel32\.dll.*x{2,5}y{0,9}z?", # bounded repeats do not count + r"kernel32\.dll(?:a|b)+c*", + ], +) +def test_log_expressions_with_two_open_repeats(pattern: str) -> None: + assert parse_rule(with_match(log=[pattern])).log[0].pattern == pattern + + +@pytest.mark.parametrize( + "pattern", + [ + r"aaaaaaaa.*b.*c.*d", + r"kernel32\.dll x{3,} y+ z*", # {n,} is open-ended + r"kernel32\.dll(?:a+|b*|c+)", # alternation branches are summed + r"kernel32\.dll(?=a+b+)c*", # lookarounds count + r"kernel32\.dll(x+)(y+)(z+?)", # inside groups, lazy too + ], +) +def test_log_expressions_with_three_open_repeats(pattern: str) -> None: + rejects(with_match(log=[pattern]), "open-ended repeats") + + +def test_log_also_open_repeat_limit() -> None: + rejects(with_match(log=[LOG_LINE], log_also=[r"aaaaaaaa.*b.*c.*d"]), "match.log_also") + + +@pytest.mark.parametrize("pattern", [r"(?i)kernel32\.dll", r"(?s)kernel32\.dll", r"(?a)kernel32\.dll"]) +def test_log_expressions_with_flags(pattern: str) -> None: + rejects(with_match(log=[pattern]), "flags") + + +@pytest.mark.parametrize( + "pattern", + [r"(?i:k)ernel32\.dll", r"(a)\1kernel32dll", r"(?Px)(?(a)y|z)kernel32dll"], +) +def test_log_expressions_that_cannot_be_checked(pattern: str) -> None: + rejects(with_match(log=[pattern]), "cannot be checked") + + +def test_regex_parser_unavailable_is_a_rejection(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(fix_pack, "_regex_tree", lambda pattern: None) + rejects(rule(), "cannot be checked") + + +def test_regex_parser_surprise_is_a_rejection(monkeypatch: pytest.MonkeyPatch) -> None: + import re._parser as real_parser + + def boom(*args: Any, **kwargs: Any) -> Any: + raise RuntimeError("new layout") + + monkeypatch.setattr(real_parser, "parse", boom) + assert fix_pack._regex_tree(LOG_LINE) is None + + +# --------------------------------------------------------------------------- # +# log_also +# --------------------------------------------------------------------------- # + +def test_log_also_needs_log() -> None: + rejects(rule(match={"app_ids": ["570"], "log_also": [LOG_LINE]}, severity="advice"), "together with log") + + +def test_log_also_parses() -> None: + r = parse_rule(with_match(log=[LOG_LINE], log_also=[r"err:module:import_dll", r"Game start failed"])) + assert [p.pattern for p in r.log_also] == [r"err:module:import_dll", r"Game start failed"] + + +@pytest.mark.parametrize( + "bad,fragment", + [ + ([], "non-empty list"), + ("err:module:import_dll", "non-empty list"), + ([7], "must be a string"), + (["err:"], "8 literal characters"), + (["(a+)+kernel32dll"], "repeats a group"), + (["kernel32("], "does not compile"), + (["kernel32" + "x" * 293], "longer than 300"), + (["(?i)kernel32dll"], "flags"), + ], +) +def test_log_also_limits(bad: Any, fragment: str) -> None: + msg = rejects(with_match(log=[LOG_LINE], log_also=bad), fragment) + assert msg.startswith("match.log_also") + + +# --------------------------------------------------------------------------- # +# match_log +# --------------------------------------------------------------------------- # + +def test_match_log_returns_first_matching_line_stripped() -> None: + r = parse_rule(with_match(log=[LOG_LINE, r"err:module:import_dll"])) + lines = ["fixme:heap:x\n", " 0024:err:module:import_dll Library foo\n", "wine: could not load kernel32.dll\n"] + assert match_log(r, lines) == "0024:err:module:import_dll Library foo" + + +def test_match_log_none_without_a_match() -> None: + r = parse_rule(rule()) + assert match_log(r, ["fixme:heap:x", "all good"]) is None + assert match_log(r, []) is None + + +def test_match_log_without_log_part() -> None: + r = parse_rule(rule(match={"app_ids": ["570"]}, severity="advice")) + assert match_log(r, ["wine: could not load kernel32.dll"]) is None + + +def test_match_log_is_case_sensitive() -> None: + assert match_log(parse_rule(rule()), ["WINE: COULD NOT LOAD KERNEL32.DLL"]) is None + + +def test_match_log_looks_at_first_2000_characters_only() -> None: + r = parse_rule(rule()) + hit = "wine: could not load kernel32.dll" + assert match_log(r, ["x" * (2000 - len(hit)) + hit]) is not None + assert match_log(r, ["x" * (2001 - len(hit)) + hit]) is None + long_line = hit + "y" * 5000 + found = match_log(r, [long_line]) + assert found is not None and len(found) == 2000 + + +def test_match_log_end_anchor_ignores_line_ending() -> None: + r = parse_rule(with_match(log=[r"kernel32\.dll$"])) + assert match_log(r, ["wine: could not load kernel32.dll\r\n"]) == "wine: could not load kernel32.dll" + + +def test_match_log_with_log_also_satisfied() -> None: + r = parse_rule(with_match(log=[LOG_LINE], log_also=[r"Game start failed", r"err:module:import_dll"])) + lines = iter([ + "err:module:import_dll Library x not found", + "wine: could not load kernel32.dll", + "noise", + "Game start failed: 5", + ]) # a one-shot iterable, and the log_also lines come before and after the evidence + assert match_log(r, lines) == "wine: could not load kernel32.dll" + + +def test_match_log_with_log_also_on_the_same_line() -> None: + r = parse_rule(with_match(log=[LOG_LINE], log_also=[r"could not load"])) + assert match_log(r, ["wine: could not load kernel32.dll"]) == "wine: could not load kernel32.dll" + + +def test_match_log_with_log_also_unsatisfied() -> None: + r = parse_rule(with_match(log=[LOG_LINE], log_also=[r"Game start failed", r"err:module:import_dll"])) + lines = ["wine: could not load kernel32.dll", "err:module:import_dll Library x not found"] + assert match_log(r, lines) is None + # log_also alone is never evidence + assert match_log(r, ["Game start failed", "err:module:import_dll"]) is None + + +def test_match_log_stops_once_answered() -> None: + r = parse_rule(rule()) + seen: list[str] = [] + + def lines() -> Any: + for line in ["a", "wine: could not load kernel32.dll", "b", "c"]: + seen.append(line) + yield line + + assert match_log(r, lines()) is not None + assert seen == ["a", "wine: could not load kernel32.dll"] + + +# --------------------------------------------------------------------------- # +# packs +# --------------------------------------------------------------------------- # + +def test_parse_pack_minimal() -> None: + p = parse_pack(pack(rule())) + assert p.revision == "2026.11.1" + assert [r.id for r in p.rules] == ["kernel32-missing"] + assert p.rejected == [] + + +@pytest.mark.parametrize( + "data", + [ + None, + [], + "pack", + {"version": 2, "revision": "2026.11.1", "rules": []}, + pack(format="protonshift-fixes"), + pack(format=None), + ], +) +def test_not_a_pack(data: Any) -> None: + with pytest.raises(PackError, match="not a fix pack"): + parse_pack(data) + + +def test_newer_version_rejected_whole() -> None: + with pytest.raises(PackError, match="newer"): + parse_pack(pack(rule(), version=PACK_VERSION + 1)) + + +@pytest.mark.parametrize("version", [1, 0, -1, "2", 2.0, True, None]) +def test_other_versions_rejected(version: Any) -> None: + with pytest.raises(PackError, match="version"): + parse_pack(pack(rule(), version=version)) + + +def test_missing_version_rejected() -> None: + data = pack(rule()) + del data["version"] + with pytest.raises(PackError, match="version"): + parse_pack(data) + + +@pytest.mark.parametrize( + "revision", + ["2026.11", "2026.13.1", "2026.00.1", "26.11.1", "2026.1.1", "2026.11.x", "2026.11.1\n", "", None, 2026], +) +def test_bad_revision(revision: Any) -> None: + with pytest.raises(PackError, match="revision"): + parse_pack(pack(revision=revision)) + + +@pytest.mark.parametrize("revision", ["2026.11.0", "2026.01.12", "2027.12.300"]) +def test_good_revision(revision: str) -> None: + assert parse_pack(pack(revision=revision)).revision == revision + + +@pytest.mark.parametrize("rules", [None, {}, "rules", 3]) +def test_rules_must_be_a_list(rules: Any) -> None: + with pytest.raises(PackError, match="rules"): + parse_pack(pack(rules=rules)) + + +def test_unknown_pack_field_rejected() -> None: + with pytest.raises(PackError, match="unknown field 'revison'"): + parse_pack(pack(revison="2026.11.1")) + + +def test_bad_rule_does_not_take_good_ones_down() -> None: + good_a = rule(id="good-a") + bad = rule(id="bad-one", severity="fatal") + nameless = {"title": "no id at all"} + good_b = rule(id="good-b") + p = parse_pack(pack(good_a, bad, nameless, "not a rule", good_b)) + assert [r.id for r in p.rules] == ["good-a", "good-b"] + assert [rid for rid, _ in p.rejected] == ["bad-one", "#2", "#3"] + assert "severity" in dict(p.rejected)["bad-one"] + + +def test_duplicate_id_later_one_rejected() -> None: + first = rule(title="First") + second = rule(title="Second") + p = parse_pack(pack(first, second)) + assert [r.title for r in p.rules] == ["First"] + assert p.rejected == [("kernel32-missing", "duplicate id")] + + +def test_duplicate_id_of_a_rejected_rule_is_still_a_duplicate() -> None: + p = parse_pack(pack(rule(severity="fatal"), rule())) + assert p.rules == [] + assert [reason for _, reason in p.rejected][1] == "duplicate id" + + +def test_parse_pack_does_not_mutate_input() -> None: + data = pack(rule(), rule(id="other-rule")) + before = copy.deepcopy(data) + parse_pack(data) + assert data == before + + +# --------------------------------------------------------------------------- # +# load_pack / load_bundled_pack +# --------------------------------------------------------------------------- # + +def write(tmp_path: Path, content: str | bytes, name: str = "pack.json") -> Path: + path = tmp_path / name + if isinstance(content, bytes): + path.write_bytes(content) + else: + path.write_text(content, encoding="utf-8") + return path + + +def test_load_pack_reads_a_file(tmp_path: Path) -> None: + p = load_pack(write(tmp_path, json.dumps(pack(rule())))) + assert [r.id for r in p.rules] == ["kernel32-missing"] + + +def test_load_pack_missing_file(tmp_path: Path) -> None: + with pytest.raises(PackError, match="cannot read"): + load_pack(tmp_path / "nope.json") + + +def test_load_pack_directory(tmp_path: Path) -> None: + with pytest.raises(PackError): + load_pack(tmp_path) + + +@pytest.mark.parametrize("content", ["{ not json", "", "[1, 2"]) +def test_load_pack_bad_json(tmp_path: Path, content: str) -> None: + with pytest.raises(PackError, match="not valid JSON"): + load_pack(write(tmp_path, content)) + + +def test_load_pack_deeply_nested_json(tmp_path: Path) -> None: + with pytest.raises(PackError): + load_pack(write(tmp_path, "[" * 200_000 + "]" * 200_000)) + + +def test_load_pack_not_utf8(tmp_path: Path) -> None: + with pytest.raises(PackError, match="UTF-8"): + load_pack(write(tmp_path, b'{"format": "\xff"}')) + + +def test_load_pack_duplicate_keys(tmp_path: Path) -> None: + text = json.dumps(pack(rule())).replace('"severity": "blocking"', '"severity": "advice", "severity": "blocking"') + with pytest.raises(PackError, match="duplicate key 'severity'"): + load_pack(write(tmp_path, text)) + + +def test_load_pack_size_limit(tmp_path: Path) -> None: + body = json.dumps(pack(rule())) + limit = 2 * 1024 * 1024 + at_limit = body[:-1] + " " * (limit - len(body)) + "}" + assert len(at_limit.encode()) == limit + assert load_pack(write(tmp_path, at_limit, "at.json")).rules + with pytest.raises(PackError, match="2 MB"): + load_pack(write(tmp_path, at_limit + " ", "over.json")) + + +def test_load_pack_newer_version(tmp_path: Path) -> None: + with pytest.raises(PackError, match="newer"): + load_pack(write(tmp_path, json.dumps(pack(version=3)))) + + +def test_load_bundled_pack_never_raises(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + monkeypatch.setattr(fix_pack, "_BUNDLED_PATH", tmp_path / "missing.json") + p = load_bundled_pack() + assert p.revision == "" and p.rules == [] + assert len(p.rejected) == 1 and p.rejected[0][0] == "pack" + + monkeypatch.setattr(fix_pack, "_BUNDLED_PATH", write(tmp_path, json.dumps(pack(version=9)))) + p = load_bundled_pack() + assert p.rejected[0][0] == "pack" and "newer" in p.rejected[0][1] + + +def test_bundled_pack_is_clean() -> None: + """CI's guard on the shipped data: every rule in fix_pack.json must load.""" + p = load_bundled_pack() + problems = [f"{rule_id}: {reason}" for rule_id, reason in p.rejected] + assert not problems, "bundled fix pack has rejected rules:\n" + "\n".join(problems) + assert re.fullmatch(r"[0-9]{4}\.[0-9]{2}\.[0-9]+", p.revision), f"bad revision {p.revision!r}" + for r in p.rules: + assert r.source.startswith("https://") and len(r.source) > len("https://"), ( + f"{r.id}: source must be an https URL, got {r.source!r}" + ) + assert r.verified, f"{r.id}: verified date missing" + assert r.origin == "pack", f"{r.id}: origin {r.origin!r}" + ids = [r.id for r in p.rules] + dupes = sorted({i for i in ids if ids.count(i) > 1}) + assert not dupes, f"bundled fix pack has duplicate ids: {', '.join(dupes)}" + + +# --------------------------------------------------------------------------- # +# user_rules +# --------------------------------------------------------------------------- # + +@pytest.fixture +def user_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + monkeypatch.setattr(fixes_mod, "_USER_FIXES_DIR", tmp_path) + return tmp_path + + +def write_user(user_dir: Path, app_id: str, entries: Any) -> None: + (user_dir / f"{app_id}.json").write_text(json.dumps(entries), encoding="utf-8") + + +def test_user_rules_none_without_a_file(user_dir: Path) -> None: + assert user_rules("570") == [] + + +def test_user_rules_corrupt_file(user_dir: Path) -> None: + (user_dir / "570.json").write_text("[ broken", encoding="utf-8") + assert user_rules("570") == [] + + +def test_user_rules_env_and_launch_arg(user_dir: Path) -> None: + write_user(user_dir, "570", [ + {"title": "HUD", "description": "Shows fps", "type": "env", "key": "DXVK_HUD", "value": "fps"}, + {"title": "Vulkan", "description": "", "type": "launch_arg", "key": "", "value": " -vulkan "}, + ]) + first, second = user_rules("570") + assert first.id == "user-1" and second.id == "user-2" + assert first.origin == second.origin == "user" + assert first.severity == "advice" + assert first.app_ids == ("570",) + assert first.title == "HUD" and first.cause == "Shows fps" + assert first.source == "" and first.verified == "" + assert first.log == () and first.log_also == () + assert first.actions == (Action("env", key="DXVK_HUD", value="fps"),) + assert second.actions == (Action("user_snippet", value="-vulkan"),) + + +def test_user_rules_ids_follow_file_position(user_dir: Path) -> None: + write_user(user_dir, "570", [ + {"title": "bad", "type": "env", "key": "1BAD", "value": "x"}, + "not an entry", + {"title": "ok", "type": "env", "key": "GOOD", "value": "x"}, + ]) + assert [r.id for r in user_rules("570")] == ["user-3"] + + +def test_user_rules_values_are_not_held_to_pack_limits(user_dir: Path) -> None: + write_user(user_dir, "570", [ + {"title": "t", "type": "env", "key": "LD_PRELOAD", "value": "/usr/lib/lib x.so"}, + {"title": "t", "type": "launch_arg", "value": "gamemoderun %command% -dx11"}, + ]) + env, snippet = user_rules("570") + assert env.actions[0] == Action("env", key="LD_PRELOAD", value="/usr/lib/lib x.so") + assert snippet.actions[0].value == "gamemoderun %command% -dx11" + + +@pytest.mark.parametrize( + "entry", + [ + {"title": "t", "type": "env", "key": "A", "value": "a\nb"}, + {"title": "t", "type": "env", "key": "A", "value": "a\rb"}, + {"title": "t", "type": "env", "key": "A", "value": "a\0b"}, + {"title": "t", "type": "env", "key": "A B", "value": "1"}, + {"title": "t", "type": "env", "key": "", "value": "1"}, + {"title": "t", "type": "env", "value": "1"}, + {"title": "t", "type": "env", "key": 5, "value": "1"}, + {"title": "t", "type": "env", "key": "A", "value": 1}, + {"title": "t", "type": "launch_arg", "value": "-a\n-b"}, + {"title": "t", "type": "launch_arg", "value": "-a\0"}, + {"title": "t", "type": "launch_arg", "value": "x" * 501}, + {"title": "t", "type": "launch_arg", "value": " "}, + {"title": "t", "type": "wrapper", "value": "gamemoderun"}, + {"title": "t", "value": "1", "key": "A"}, + {"title": 5, "type": "env", "key": "A", "value": "1"}, + {"title": "t", "description": ["x"], "type": "env", "key": "A", "value": "1"}, + ["not", "a", "dict"], + None, + ], +) +def test_user_rules_skip_unusable_entries(user_dir: Path, entry: Any) -> None: + write_user(user_dir, "570", [entry]) + assert user_rules("570") == [] + + +def test_user_rules_snippet_cap(user_dir: Path) -> None: + write_user(user_dir, "570", [{"title": "t", "type": "launch_arg", "value": "x" * 500}]) + assert len(user_rules("570")[0].actions[0].value) == 500 + + +def test_user_rules_text_truncation_and_default_title(user_dir: Path) -> None: + write_user(user_dir, "570", [ + {"title": "T" * 150, "description": "D" * 500, "type": "env", "key": "A", "value": "1"}, + {"title": " ", "type": "env", "key": "A", "value": "1"}, + {"type": "env", "key": "A", "value": "1"}, + ]) + long_one, blank, missing = user_rules("570") + assert long_one.title == "T" * 100 and long_one.cause == "D" * 400 + assert blank.title == missing.title == "Your own fix" + assert missing.cause == "" + + +def test_user_rules_only_for_that_game(user_dir: Path) -> None: + write_user(user_dir, "570", [{"title": "t", "type": "env", "key": "A", "value": "1"}]) + assert user_rules("730") == [] From dfd68f0d3267bba86d968e478765155a58f5d059 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 23:12:35 -0600 Subject: [PATCH 08/20] fix(core): Steam's real names for its own Proton builds The built-in list offered proton_9_0, proton_8_0 and proton_7_0. Steam's names are proton_9, proton_8 and proton_7 (read from appinfo.vdf), so the picker wrote a build Steam does not know, and the launch check called a game on a real Valve build "gone". The list now holds the real names, including Proton 10, 11 and Hotfix, each with a label in the picker. Co-Authored-By: Claude Fable 5.2 --- protonshift/core/steam.py | 17 +++++++++++------ protonshift/qml/GamesPage.qml | 9 ++++++--- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/protonshift/core/steam.py b/protonshift/core/steam.py index 922efe6..45fd85f 100644 --- a/protonshift/core/steam.py +++ b/protonshift/core/steam.py @@ -327,15 +327,20 @@ def read_tool_manifest(tool_dir: Path) -> tuple[str, str]: return fallback -# Built-in Steam Proton tool IDs. Source of truth is Steam itself; this list is -# best-effort for the dropdown and may lag a release. Newer Proton tools are -# discovered via `compatibilitytools.d` so users always see GE-Proton/etc. +# Built-in Steam Proton tool IDs: Steam's internal names (as in appinfo.vdf and +# CompatToolMapping), not the display names. Source of truth is Steam itself; +# this list is best-effort for the dropdown and may lag a release. Builds older +# than 7 are left out of the offer. Newer Proton tools are discovered via +# `compatibilitytools.d` so users always see GE-Proton/etc. _BUILTIN_PROTON: tuple[str, ...] = ( "", "proton_experimental", - "proton_9_0", - "proton_8_0", - "proton_7_0", + "proton_hotfix", + "proton_11", + "proton_10", + "proton_9", + "proton_8", + "proton_7", ) diff --git a/protonshift/qml/GamesPage.qml b/protonshift/qml/GamesPage.qml index d66faa3..dbd6009 100644 --- a/protonshift/qml/GamesPage.qml +++ b/protonshift/qml/GamesPage.qml @@ -508,9 +508,12 @@ RowLayout { displayMap: ({ "": "Steam default", "proton_experimental": "Proton Experimental", - "proton_9_0": "Proton 9.0 (Beta)", - "proton_8_0": "Proton 8.0", - "proton_7_0": "Proton 7.0" + "proton_hotfix": "Proton Hotfix", + "proton_11": "Proton 11", + "proton_10": "Proton 10", + "proton_9": "Proton 9", + "proton_8": "Proton 8", + "proton_7": "Proton 7" }) onChosen: launch.setProton(value) function syncCurrent() { From af623eb7d2a7d5329cc844cf225c9485eeb5f9b4 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 23:12:35 -0600 Subject: [PATCH 09/20] test: system checks pass on Python 3.11 and 3.12 One test replaced os.stat with a one-argument lambda. pytest's own calls pass follow_symlinks on 3.11 and 3.12, so the run died there; it only passed on 3.14. The patch now forwards everything to the real function. Co-Authored-By: Claude Fable 5.2 --- tests/test_system_checks.py | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/tests/test_system_checks.py b/tests/test_system_checks.py index 1a3c493..54b6d4b 100644 --- a/tests/test_system_checks.py +++ b/tests/test_system_checks.py @@ -381,14 +381,14 @@ def test_default_lib_dirs_follow_layout(monkeypatch: pytest.MonkeyPatch, tmp_pat def test_disk_ok(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(sc.shutil, "disk_usage", lambda p: Usage(100 << 30, 50 << 30, 50 << 30)) + monkeypatch.setattr(sc.shutil, "disk_usage", lambda *_a, **_kw: Usage(100 << 30, 50 << 30, 50 << 30)) c = sc.check_disk(tmp_path, "library") assert (c.id, c.state, c.fix) == ("disk-library", "ok", "") assert "50.0 GiB" in c.detail def test_disk_problem_reports_gib_and_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(sc.shutil, "disk_usage", lambda p: Usage(100 << 30, 99 << 30, 400 << 20)) + monkeypatch.setattr(sc.shutil, "disk_usage", lambda *_a, **_kw: Usage(100 << 30, 99 << 30, 400 << 20)) c = sc.check_disk(tmp_path, "prefix") assert (c.id, c.state) == ("disk-prefix", "problem") assert "0.4 GiB" in c.detail @@ -398,7 +398,7 @@ def test_disk_problem_reports_gib_and_path(tmp_path: Path, monkeypatch: pytest.M def test_disk_threshold_is_configurable(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(sc.shutil, "disk_usage", lambda p: Usage(10, 5, 5 << 30)) + monkeypatch.setattr(sc.shutil, "disk_usage", lambda *_a, **_kw: Usage(10, 5, 5 << 30)) assert sc.check_disk(tmp_path, "library", min_free_bytes=10 << 30).state == "problem" assert sc.check_disk(tmp_path, "library", min_free_bytes=5 << 30).state == "ok" @@ -433,13 +433,28 @@ def test_run_checks_separate_drives(tmp_path: Path, monkeypatch: pytest.MonkeyPa install, prefix = tmp_path / "game", tmp_path / "pfx" install.mkdir() prefix.mkdir() + devices = {install: 1, prefix: 2} - class FakeStat: - def __init__(self, dev: int) -> None: - self.st_dev = dev + class OtherDevice: + """The real stat result, on another device; everything but ``st_dev`` is untouched.""" - monkeypatch.setattr(sc.os, "stat", lambda p: FakeStat(1 if Path(p) == install else 2) - if Path(p) in (install, prefix) else real_stat(p)) + def __init__(self, real: os.stat_result, dev: int) -> None: + self._real, self.st_dev = real, dev + + def __getattr__(self, name: str) -> object: + return getattr(self._real, name) + + # sc.os is the os module itself, so anything else calling os.stat during + # the test (pytest included, with follow_symlinks=) must get the real thing. + def fake_stat(path: object, *args: object, **kwargs: object) -> object: + real = real_stat(path, *args, **kwargs) + try: + dev = devices.get(Path(path)) + except TypeError: # a file descriptor + dev = None + return real if dev is None else OtherDevice(real, dev) + + monkeypatch.setattr(sc.os, "stat", fake_stat) checks = sc.run_checks(steam_root=None, install_path=install, prefix_path=prefix, run=runner(0, REAL_SUMMARY)) assert [c.id for c in checks] == ["vulkan", "vulkan-32bit", "disk-library", "disk-prefix"] From 533b13f7aabd3ac4e3d8dced19864d414ead9b64 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 23:12:35 -0600 Subject: [PATCH 10/20] feat(core): the Diagnose engine One list of findings for a game, built from the launch check, the Proton log, the fix pack and the system checks, ranked by how likely each is to be the reason the game will not start. A finding carries its evidence and, where a fix is mechanical, the actions that make it. Applying is planned as a pure before/after first, so the user sees the exact change. The write happens only if Steam's files still match what was checked, a snapshot is saved before it, a failed second write puts the first one back, and Undo refuses to overwrite later edits unless told to. Launch check findings gained ids and actions; the gathering that sat in its controller now lives in core, where disk work belongs. A game still set to an old proton_9_0 name gets a blocking finding with a one-click fix back to Steam's default. Co-Authored-By: Claude Fable 5.2 --- protonshift/core/diagnose.py | 582 ++++++++++++++++++++++++++++++ protonshift/core/fix_apply.py | 335 ++++++++++++++++++ protonshift/core/launch_check.py | 100 ++++-- protonshift/core/launch_merge.py | 271 ++++++++++++++ tests/test_diagnose.py | 589 +++++++++++++++++++++++++++++++ tests/test_fix_apply.py | 339 ++++++++++++++++++ tests/test_launch_check.py | 60 ++++ tests/test_launch_merge.py | 183 +++++++++- 8 files changed, 2427 insertions(+), 32 deletions(-) create mode 100644 protonshift/core/diagnose.py create mode 100644 protonshift/core/fix_apply.py create mode 100644 tests/test_diagnose.py create mode 100644 tests/test_fix_apply.py diff --git a/protonshift/core/diagnose.py b/protonshift/core/diagnose.py new file mode 100644 index 0000000..08edc85 --- /dev/null +++ b/protonshift/core/diagnose.py @@ -0,0 +1,582 @@ +"""Diagnose: one ranked list of the reasons a game may not start or run well. + +Four sources feed it, in this order: the launch check (the game's own +settings), the Proton log, the fix pack's rules (and the user's own fixes), +and the system checks (the machine under every game). Each becomes a +:class:`Finding` with a severity from :data:`SEVERITY_ORDER`, evidence where +there is some, and the actions of a one-click fix where one is known. + +Everything down to :func:`to_row` is pure and works on a :class:`Facts`, so +tests never need Steam or a display. :func:`collect` is the one function that +reads the disk; the controller calls it on a worker thread. It reads only, and +never starts the game. + +Diagnose prefers a missed finding to a false one: a fact that could not be +found out never satisfies a rule's condition (``docs/fix-pack.md``). +""" + +from __future__ import annotations + +import os +import re +from collections.abc import Callable, Iterable, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any, TypeVar + +from . import compat_tool, fix_pack, gpu, host, launch_check, proton_log, steam, system_checks, tool_check +from .display import _is_wayland +from .fix_apply import read_state +from .fix_pack import Action, Rule, When, match_log +from .gpu import GPUInfo +from .launch_merge import prefix_commands, prefix_env, split_line +from .snapshots import GameState +from .system_checks import Check +from .vdf_config import read_launch_options + +SEVERITY_ORDER = ("blocking", "likely", "advice", "context", "ok") + +_LEVELS = {"error": "blocking", "warn": "likely", "info": "context", "ok": "ok"} +# Launch check findings about Proton itself, which a native game does not use. +_PROTON_ONLY_IDS = ("proton-", "prefix-", "anticheat-") +_LAUNCH_ACTIONS = frozenset({"env", "unset_env", "game_arg", "remove_word", "single_command", "add_command", + "user_snippet"}) +_MAX_EVIDENCE = 300 + +T = TypeVar("T") + + +@dataclass(frozen=True) +class Facts: + app_id: str + steam_app: bool # False for a Non-Steam shortcut + native: bool # a native Linux game: no Proton involved + launch_options: str + launch_options_readable: bool + compat_tool: str # "" = Steam's default + proton_family: str # "valve" | "ge" | "cachyos" | "other" | "" (unknown) + proton_major: int | None + gpu_vendors: frozenset[str] # subset of {"nvidia","amd","intel"}; empty = unknown + session: str # "wayland" | "x11" | "" (unknown) + log_lines: tuple[str, ...] | None # None = no log file + log_modified: str # "" when no log + log_path: str = "" # the log file as the user knows the path; "" when none + + +@dataclass(frozen=True) +class Finding: + id: str + severity: str # one of SEVERITY_ORDER + title: str + cause: str + evidence: str # the log line or the setting that triggered it; "" when none + fix: str # prose: what to do + source: str # URL, "" when none + origin: str # "check" | "log" | "system" | "pack" | "user" + actions: tuple[Action, ...] + + +# --------------------------------------------------------------------------- # +# facts +# --------------------------------------------------------------------------- # + +# Steam's own names carry no minor part. ``proton_9_0`` and the like are not +# Valve names: older ProtonShift builds wrote them, and Steam does not know them. +_VALVE_RE = re.compile(r"proton_([0-9]+)") +_VALVE_NAMED = frozenset({"proton_experimental", "proton_hotfix"}) +_GE_RE = re.compile(r"GE-Proton([0-9]+)-[0-9]+") +_GE_OLD_RE = re.compile(r"Proton-([0-9]+)\.[0-9]+-GE-[0-9]+(?:-[A-Za-z]+)?") +# Distro packages register GE without a version in the name (Arch's +# proton-ge-custom-bin calls itself "Proton-GE"). +_GE_UNVERSIONED = frozenset({"proton-ge", "proton-ge-custom", "ge-proton"}) +_CACHYOS_VERSION_RE = re.compile(r"cachyos[-_]v?([0-9]+)\.[0-9]+") + + +def _valve_major(digits: str) -> int | None: + if digits.startswith("0"): + return None + if len(digits) == 1: + return int(digits) + # Up to 6.3 Valve ran major and minor together (proton_513 is 5.13, + # proton_63 is 6.3); from 7 on the name is the major alone (proton_10). + if digits[0] in "3456": + return int(digits[0]) + if len(digits) == 2 and digits[0] in "12": + return int(digits) + return None + + +def proton_build(tool_name: str) -> tuple[str, int | None]: + """``(family, major)`` of a compatibility tool's internal name. + + The version is only ever read off the name; a name that does not carry one + in a known shape gives ``None``, never a guess. + """ + name = (tool_name or "").strip() + if not name: + return "", None + if name in _VALVE_NAMED: + return "valve", None + m = _VALVE_RE.fullmatch(name) + if m: + return "valve", _valve_major(m.group(1)) + m = _GE_RE.fullmatch(name) or _GE_OLD_RE.fullmatch(name) + if m: + return "ge", int(m.group(1)) + lower = name.lower() + if lower in _GE_UNVERSIONED: + return "ge", None + if "cachyos" in lower: + m = _CACHYOS_VERSION_RE.search(lower) + return "cachyos", int(m.group(1)) if m else None + return "other", None + + +# Kernel driver names (what gpu.py reports from sysfs) and words in the +# product names nvidia-smi reports. +_DRIVER_VENDORS = { + "amdgpu": "amd", "radeon": "amd", + "i915": "intel", "xe": "intel", + "nvidia": "nvidia", "nouveau": "nvidia", +} +_NAME_WORDS = { + "nvidia": "nvidia", "geforce": "nvidia", "quadro": "nvidia", + "amd": "amd", "radeon": "amd", + "intel": "intel", +} + + +def gpu_vendors(gpus: Iterable[GPUInfo]) -> frozenset[str]: + """The vendors of ``gpus``; a name or driver that says nothing adds nothing.""" + found: set[str] = set() + for info in gpus: + for text in (getattr(info, "name", ""), getattr(info, "driver", "")): + if not isinstance(text, str): + continue + lower = text.strip().lower() + if lower in _DRIVER_VENDORS: + found.add(_DRIVER_VENDORS[lower]) + continue + for word in re.split(r"[^a-z0-9]+", lower): + if word in _NAME_WORDS: + found.add(_NAME_WORDS[word]) + return frozenset(found) + + +def session_type() -> str: + """``"wayland"``, ``"x11"`` or ``""`` when the session does not say.""" + if _is_wayland(): + return "wayland" + # DISPLAY alone is not enough: an X11-only sandbox on Wayland has it too. + if os.environ.get("XDG_SESSION_TYPE", "").strip().lower() == "x11": + return "x11" + return "" + + +# --------------------------------------------------------------------------- # +# rules +# --------------------------------------------------------------------------- # + +def _prefix(facts: Facts) -> list[str] | None: + # Read as launch_check reads it: with no %command% every word is a game + # argument, so nothing is "before" it and no word or variable counts. + if not facts.launch_options_readable: + return None + return split_line(facts.launch_options)[0] + + +def _basename(word: str) -> str: + return word.rsplit("/", 1)[-1] + + +def _uses_proton(when: When) -> bool: + return bool(when.proton_family) or when.proton_major_min is not None or when.proton_major_max is not None + + +def when_holds(when: When, facts: Facts) -> bool: + """True when every condition set in ``when`` holds; an unset one holds, an unknown fact never does.""" + if when.gpu_vendor and not facts.gpu_vendors & set(when.gpu_vendor): + return False + if when.session and facts.session not in when.session: + return False + if when.proton_family and facts.proton_family not in when.proton_family: + return False + major = facts.proton_major + if when.proton_major_min is not None and (major is None or major < when.proton_major_min): + return False + if when.proton_major_max is not None and (major is None or major > when.proton_major_max): + return False + if when.launch_has or when.env_set or when.env_unset: + prefix = _prefix(facts) + if prefix is None: + return False + words = {_basename(w) for w in prefix_commands(prefix)} + keys = {w.split("=", 1)[0] for w in prefix_env(prefix)} + if not all(word in words for word in when.launch_has): + return False + if not all(key in keys for key in when.env_set): + return False + if any(key in keys for key in when.env_unset): + return False + return True + + +def _setting_evidence(when: When, facts: Facts) -> str: + """The setting that satisfied a rule that matched without a log line.""" + prefix = _prefix(facts) or [] + shown = [w for w in prefix_commands(prefix) if _basename(w) in when.launch_has] + shown += [w for w in prefix_env(prefix) if w.split("=", 1)[0] in when.env_set] + if shown: + return " ".join(dict.fromkeys(shown)) + if _uses_proton(when): + return facts.compat_tool + return "" + + +def rule_finding(rule: Rule, facts: Facts) -> Finding | None: + """The finding ``rule`` gives for ``facts``, or None when any part of its match fails.""" + if rule.app_ids and facts.app_id not in rule.app_ids: + return None + if facts.native and (rule.log or _uses_proton(rule.when)): + return None + if not when_holds(rule.when, facts): + return None + if rule.log: + if facts.log_lines is None: + return None + line = match_log(rule, facts.log_lines) + if line is None: + return None + evidence, origin = line[:_MAX_EVIDENCE], "log" + else: + evidence, origin = _setting_evidence(rule.when, facts), "pack" + if rule.origin == "user": + origin = "user" + return Finding( + id=rule.id, + severity=rule.severity, + title=rule.title, + cause=rule.cause, + evidence=evidence, + fix="", + source=rule.source, + origin=origin, + actions=tuple(rule.actions), + ) + + +# --------------------------------------------------------------------------- # +# the list +# --------------------------------------------------------------------------- # + +def _check_evidence(actions: Sequence[Action], facts: Facts) -> str: + kinds = {a.type for a in actions} + if kinds & _LAUNCH_ACTIONS: + return facts.launch_options + if "default_proton" in kinds: + return facts.compat_tool + return "" + + +def _launch_rows(launch_findings: Sequence[dict[str, Any]], facts: Facts) -> list[Finding]: + rows: list[Finding] = [] + for index, raw in enumerate(launch_findings): + fid = str(raw.get("id") or f"check-{index}") + if facts.native and fid.startswith(_PROTON_ONLY_IDS): + continue + actions = tuple(raw.get("actions") or ()) + rows.append(Finding( + id=fid, + severity=_LEVELS.get(str(raw.get("level", "")), "context"), + title=str(raw.get("title", "")), + cause=str(raw.get("detail", "")), + evidence=_check_evidence(actions, facts), + fix=str(raw.get("fix", "")), + source="", + origin="check", + actions=actions, + )) + return rows + + +def _context( + fid: str, title: str, cause: str, evidence: str = "", actions: tuple[Action, ...] = (), +) -> Finding: + return Finding(fid, "context", title, cause, evidence, "", "", "log", actions) + + +def _log_rows(facts: Facts, rule_matched_log: bool) -> list[Finding]: + if facts.native: + return [] + readable = facts.launch_options_readable + logging_on = readable and proton_log.logging_enabled(facts.launch_options) + if facts.log_lines is None: + if not facts.steam_app: + return [] + if logging_on: + return [_context( + "log-waiting", "There is no Proton log for this game yet", + "Proton logging is on, but no log has been written yet. Run the game once, then diagnose " + "again.", + )] + return [_context( + "log-off", "There is no Proton log for this game", + "Proton writes a log of what happens while the game starts only when logging is on. Turn it on, " + "run the game once, then diagnose again, so Diagnose can recognise more problems.", + actions=(Action("env", key="PROTON_LOG", value="1"),) if readable else (), + )] + + rows: list[Finding] = [] + where = facts.log_path or "the Proton log" + when = f", last written {facts.log_modified}" if facts.log_modified else "" + cause = (f"Diagnose read the end of {where}{when}. If the game has failed since then, run it again and " + "diagnose again so the log is current.") + if readable and not logging_on: + cause += " Logging is off now, so this log is from an earlier run." + title = "Read the Proton log" + if facts.log_modified: + title += f" written {facts.log_modified}" + rows.append(_context("log-read", title, cause, evidence=facts.log_path)) + + if not rule_matched_log: + problems = [line.strip() for line in facts.log_lines if proton_log.is_problem_line(line)] + if problems: + count = len(problems) + if count == 1: + title = "1 line in the log looks like a problem ProtonShift does not recognise" + else: + title = f"{count} lines in the log look like problems ProtonShift does not recognise" + rows.append(_context( + "log-unrecognised", title, + "They may still explain the trouble. Read them in the log, or search the web for them " + "together with the game's name.", + evidence=problems[0][:_MAX_EVIDENCE], + )) + return rows + + +def _system_rows(checks: Sequence[Check], facts: Facts) -> list[Finding]: + rows: list[Finding] = [] + for check in checks: + if facts.native and check.id == "disk-prefix": + continue # a native game has no Proton prefix + if check.state == system_checks.PROBLEM: + # Proton needs Vulkan to start at all; a native game may still run on OpenGL. + severity = "blocking" if check.id == "vulkan" and not facts.native else "likely" + elif check.state == system_checks.OK: + severity = "ok" + else: + severity = "context" + rows.append(Finding(check.id, severity, check.title, check.detail, "", check.fix, "", "system", ())) + return rows + + +def _rank(finding: Finding) -> int: + try: + return SEVERITY_ORDER.index(finding.severity) + except ValueError: + return len(SEVERITY_ORDER) + + +def diagnose( + facts: Facts, + *, + rules: Sequence[Rule], + launch_findings: Sequence[dict[str, Any]], + checks: Sequence[Check], +) -> list[Finding]: + """Every finding for one game, most serious first. + + Built in origin order (launch check, log, rules, system), deduplicated by + id with the first one kept, then sorted by severity; the sort is stable, so + origin order holds within a severity. + """ + rule_rows = [f for f in (rule_finding(rule, facts) for rule in rules) if f is not None] + rule_matched_log = any(f.origin == "log" for f in rule_rows) + built = [ + *_launch_rows(launch_findings, facts), + *_log_rows(facts, rule_matched_log), + *rule_rows, + *_system_rows(checks, facts), + ] + seen: set[str] = set() + unique: list[Finding] = [] + for finding in built: + if finding.id in seen: + continue + seen.add(finding.id) + unique.append(finding) + return sorted(unique, key=_rank) + + +def _count(n: int, one: str, many: str) -> str: + return f"{n} {one if n == 1 else many}" + + +def summarize(findings: Sequence[Finding]) -> str: + """One sentence for the top of the dialog, the most serious count first.""" + blocking = sum(1 for f in findings if f.severity == "blocking") + likely = sum(1 for f in findings if f.severity == "likely") + advice = sum(1 for f in findings if f.severity == "advice") + if blocking: + text = _count(blocking, "problem", "problems") + " that will stop the game from starting" + if likely: + text += f", {likely} more worth a look" + return text + "." + if likely: + return f"Nothing blocks the launch. {_count(likely, 'thing', 'things')} worth a look." + if advice: + return f"No problems found. {_count(advice, 'suggestion', 'suggestions')} you can try." + return "No problems found." + + +def to_row(f: Finding) -> dict[str, object]: + """A finding as plain str/bool/list values, safe to hand to QML.""" + return { + "id": f.id, + "severity": f.severity, + "title": f.title, + "cause": f.cause, + "evidence": f.evidence, + "fix": f.fix, + "source": f.source, + "origin": f.origin, + "manual": [a.text for a in f.actions if a.type == "manual"], + "canApply": any(a.type != "manual" for a in f.actions), + } + + +# --------------------------------------------------------------------------- # +# gathering (disk) +# --------------------------------------------------------------------------- # + +@dataclass(frozen=True) +class Report: + app_id: str + findings: list[Finding] + summary: str + state: GameState | None # current settings, None when unreadable or a shortcut + can_apply: bool # False for shortcuts and unreadable configs + steam_running: bool | None + log_path: str + paths: tuple[Path | None, Path | None] # (localconfig.vdf, config.vdf) for apply/undo + + +def _quiet(read: Callable[[], T], fallback: T) -> T: + # Diagnose has to open whatever is broken on this machine; a failed read + # becomes an unknown fact, which the rules already treat as "does not hold". + try: + return read() + except Exception: # noqa: BLE001 + return fallback + + +def _installed_runtimes(root: Path | None) -> list[str]: + # Tools (Proton builds, runtimes) are hidden from the game list, so their + # manifests are looked for directly. + if root is None: + return [] + found: list[str] = [] + for lib in steam._find_libraryfolders(root): + for runtime_id, _name in launch_check.ANTICHEAT_RUNTIMES.values(): + if (lib / "steamapps" / f"appmanifest_{runtime_id}.acf").exists(): + found.append(runtime_id) + return found + + +def collect( + app_id: str, + *, + install_path: str, + prefix_path: str, + shortcut_options: str | None, + native: bool, + protondb_tier: str, +) -> Report: + """Gather everything about one game and diagnose it. Reads only; never raises for missing data. + + ``shortcut_options`` not None means a Non-Steam shortcut whose launch + options are given (Steam keeps them in the shortcut, not in localconfig). + """ + steam_app = shortcut_options is None + root = _quiet(lambda: steam.discover_games()[0], None) + localconfig = _quiet(lambda: steam.get_localconfig_path(root), None) if root else None + config_vdf = compat_tool.get_config_vdf_path(root) if root else None + + if steam_app: + readable, options = (False, "") + if localconfig: + readable, options = _quiet(lambda: read_launch_options(localconfig, app_id), (False, "")) + else: + readable, options = True, shortcut_options or "" + if not isinstance(options, str): + readable, options = False, "" + ok, tool = (False, "") + if config_vdf: + ok, tool = _quiet(lambda: compat_tool.read_compat_tool(config_vdf, app_id), (False, "")) + tool = tool if ok and isinstance(tool, str) else "" + + install = Path(install_path) if install_path else None + prefix = Path(prefix_path) if prefix_path else None + family, major = ("", None) if native else proton_build(tool) + available = list(_quiet(lambda: steam.get_available_proton_tools(root), [""])) + runtimes = _quiet(lambda: _installed_runtimes(root), []) + if family == "valve" and tool not in available: + # Steam downloads its own Proton builds when a game needs one, and + # their internal names are not on disk to compare with, so a Valve + # build is never reported as gone. + available.append(tool) + launch_findings = _quiet(lambda: launch_check.check_launch( + launch_options=options, + launch_options_readable=readable, + compat_tool=tool, + available_tools=available, + install_path=install, + prefix_path=prefix, + installed_app_ids=runtimes, + tool_exists=tool_check.is_tool_available, + protondb_tier=protondb_tier, + ), []) + + log_file = None if native else proton_log.log_path(app_id) + log_lines: tuple[str, ...] | None = None + log_modified = "" + if log_file is not None: + try: + log_lines = tuple(proton_log.read_tail(log_file).text.splitlines()) + log_modified = proton_log.modified_label(log_file) + except (OSError, ValueError): + log_lines = None + + facts = Facts( + app_id=app_id, + steam_app=steam_app, + native=native, + launch_options=options, + launch_options_readable=readable, + compat_tool=tool, + proton_family=family, + proton_major=major, + gpu_vendors=_quiet(lambda: gpu_vendors(gpu.get_gpu_info()), frozenset()), + session=_quiet(session_type, ""), + log_lines=log_lines, + log_modified=log_modified, + log_path=steam.host_display_path(log_file) if log_lines is not None and log_file else "", + ) + checks = _quiet(lambda: system_checks.run_checks( + steam_root=root, install_path=install, prefix_path=prefix, run=host.host_run, + ), []) + rules = [*fix_pack.load_bundled_pack().rules, *_quiet(lambda: fix_pack.user_rules(app_id), [])] + findings = diagnose(facts, rules=rules, launch_findings=launch_findings, checks=checks) + + state = read_state(localconfig, config_vdf, app_id) if steam_app else None + return Report( + app_id=app_id, + findings=findings, + summary=summarize(findings), + state=state, + can_apply=steam_app and state is not None, + steam_running=_quiet(lambda: system_checks.steam_running(host.host_run), None), + log_path=str(log_file) if log_file else "", + paths=(localconfig, config_vdf), + ) diff --git a/protonshift/core/fix_apply.py b/protonshift/core/fix_apply.py new file mode 100644 index 0000000..d44051b --- /dev/null +++ b/protonshift/core/fix_apply.py @@ -0,0 +1,335 @@ +"""Apply a Diagnose fix to a game's Steam settings, and undo it. + +:func:`plan` is pure: it works out, from a finding's actions and the game's +current settings, what the settings would become, without touching anything. +The dialog shows that before and after to the user, and only then calls +:func:`apply_change` with the very same plan. + +The disk part keeps three promises: + +- It never writes over something the user did not see. The settings are read + again right before writing, and a plan made from older settings is refused. +- It never makes a change that cannot be undone. The snapshot is saved first; + if that fails, nothing is written. +- It never leaves half a change behind. When the second of two writes fails, + the first is put back. + +Paths are passed in, never looked up here, so tests run against VDF files in a +temporary folder. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from pathlib import Path + +from . import snapshots +from .compat_tool import read_compat_tool, set_compat_tool +from .fix_pack import ( + _ENV_VALUE_RE, + _FORBIDDEN_PREFIX, + _FORBIDDEN_VARS, + _GAME_ARG_RE, + _KEY_RE, + _WORD_RE, + Action, +) +from .launch_merge import ( + COMMAND, + add_command, + add_game_arg, + merge_launch_snippet, + remove_word, + set_env, + single_command, + unset_env, +) +from .snapshots import GameState, Snapshot +from .vdf_config import read_launch_options, set_launch_options + +_BAD_CHARS = ("\n", "\r", "\x00") + +_VALUE_REFUSED = ( + "The value has characters ProtonShift will not write into launch options for you, " + "so add it by hand if you want it." +) +_KEY_REFUSED = "{key} is not a variable name ProtonShift can set, so add it by hand if you want it." +_LOADER_REFUSED = ( + "{key} decides what code the game loads, so ProtonShift will not change it for you. " + "Add it by hand if you are sure." +) +_UNKNOWN_ACTION = "ProtonShift does not know how to make this change for you." +_LINE_BREAK = "The new launch options would contain a line break, which Steam cannot store." +_STATE_MOVED = "The settings changed since the check. Run Diagnose again." +_UNREADABLE = "Steam's settings for this game could not be read, so nothing was changed." + + +@dataclass(frozen=True) +class Change: + before: GameState + after: GameState + manual: tuple[str, ...] # instructions from manual actions, in order + blocked: str # "" or a plain reason why this cannot be applied automatically + + @property + def changed(self) -> bool: + return self.after != self.before + + +@dataclass(frozen=True) +class ApplyResult: + ok: bool + message: str # plain sentence for the user + snapshot_id: str # "" when nothing was recorded + state: GameState | None # the state now on disk, when known + + +# --------------------------------------------------------------------------- # +# planning +# --------------------------------------------------------------------------- # + +def _key_problem(key: str) -> str: + if not isinstance(key, str) or not _KEY_RE.fullmatch(key): + return _KEY_REFUSED.format(key=key or "The name") + # The pack loader already refuses these; a user's own fix is not loaded + # through it, and one click should not be able to set them either way. + if key in _FORBIDDEN_VARS or key.startswith(_FORBIDDEN_PREFIX): + return _LOADER_REFUSED.format(key=key) + return "" + + +def _user_snippet(text: str, value: str) -> str: + # The contract: a user's launch_arg with %command% is merged like any + # snippet; without it, it is game arguments (merge_launch_snippet alone + # would put it in front of the game). + snippet = value if COMMAND in value else f"{COMMAND} {value}" + return merge_launch_snippet(text, snippet) + + +def _step(action: Action, text: str) -> tuple[str, str]: + """``(new_text, refusal)`` for one launch-options action.""" + kind = action.type + if kind in ("env", "unset_env"): + problem = _key_problem(action.key) + if problem: + return text, problem + if kind == "unset_env": + return unset_env(text, action.key), "" + value = action.value + if not isinstance(value, str) or not _ENV_VALUE_RE.fullmatch(value) or COMMAND in value: + return text, _VALUE_REFUSED + return set_env(text, action.key, value), "" + if kind == "game_arg": + if not isinstance(action.value, str) or not _GAME_ARG_RE.fullmatch(action.value): + return text, _VALUE_REFUSED + return add_game_arg(text, action.value), "" + if kind == "remove_word": + if not isinstance(action.value, str) or not _WORD_RE.fullmatch(action.value): + return text, _VALUE_REFUSED + return remove_word(text, action.value), "" + simple: dict[str, Callable[[str], str]] = {"single_command": single_command, "add_command": add_command} + if kind in simple: + return simple[kind](text), "" + if kind == "user_snippet": + if not isinstance(action.value, str) or not action.value.strip(): + return text, _VALUE_REFUSED + return _user_snippet(text, action.value.strip()), "" + return text, _UNKNOWN_ACTION + + +def plan(actions: Sequence[Action], state: GameState) -> Change: + """What ``actions`` would do to ``state``. Pure: nothing is read or written. + + Actions apply in order. A blocked plan changes nothing (``after`` is + ``before``), but still lists every manual instruction so the user can + follow them by hand. + """ + text, tool = state.launch_options, state.compat_tool + manual: list[str] = [] + blocked = "" + for action in actions: + if action.type == "manual": + manual.append(action.text) + continue + if blocked: + continue + if action.type == "default_proton": + tool = "" + continue + # Splitting would quietly turn a bare line break into a space; the user + # should see the value refused rather than changed. + if any(ch in str(action.value) + str(action.key) for ch in _BAD_CHARS): + blocked = _LINE_BREAK + continue + text, blocked = _step(action, text) + if not blocked and any(ch in text or ch in tool for ch in _BAD_CHARS): + blocked = _LINE_BREAK + after = state if blocked else GameState(launch_options=text, compat_tool=tool) + return Change(before=state, after=after, manual=tuple(manual), blocked=blocked) + + +# --------------------------------------------------------------------------- # +# disk +# --------------------------------------------------------------------------- # + +def read_state(localconfig: Path | None, config_vdf: Path | None, app_id: str) -> GameState | None: + """The game's launch options and Proton build as Steam has them, or None. + + None when either file is missing or cannot be parsed. A missing file is + refused too: writing would create a new one in a place Steam may not read, + and the user would see a fix that did nothing. + """ + if localconfig is None or config_vdf is None: + return None + try: + if not localconfig.is_file() or not config_vdf.is_file(): + return None + ok_lo, options = read_launch_options(localconfig, app_id) + ok_ct, tool = read_compat_tool(config_vdf, app_id) + except Exception: # noqa: BLE001 - an unreadable config is an answer, not a crash + return None + if not (ok_lo and ok_ct and isinstance(options, str) and isinstance(tool, str)): + return None + return GameState(launch_options=options, compat_tool=tool) + + +def _safe(write: Callable[[], bool]) -> bool: + try: + return bool(write()) + except Exception: # noqa: BLE001 - a write that raised did not happen as far as the caller knows + return False + + +def _shown(text: str) -> str: + return f'"{text}"' if text else "empty" + + +def _write( + localconfig: Path, + config_vdf: Path, + app_id: str, + current: GameState, + target: GameState, + *, + unchanged: str, +) -> str: + """Move the files from ``current`` to ``target``. ``""`` on success, else a sentence for the user. + + ``unchanged`` finishes the sentence when nothing ended up changed + ("nothing was changed", "the fix is still in place"). + """ + write_lo = target.launch_options != current.launch_options + write_ct = target.compat_tool != current.compat_tool + if write_lo and not _safe(lambda: set_launch_options(localconfig, app_id, target.launch_options)): + return f"Steam's launch options could not be written, so {unchanged}." + if write_ct and not _safe(lambda: set_compat_tool(config_vdf, app_id, target.compat_tool)): + if not write_lo: + return f"Steam's Proton setting could not be written, so {unchanged}." + if _safe(lambda: set_launch_options(localconfig, app_id, current.launch_options)): + return ("Steam's Proton setting could not be written, so the launch options were put back " + f"as they were and {unchanged}.") + return ("Steam's Proton setting could not be written, and the launch options could not be put " + f"back either. They are now {_shown(target.launch_options)}; they were " + f"{_shown(current.launch_options)}.") + return "" + + +def apply_change( + localconfig: Path | None, + config_vdf: Path | None, + app_id: str, + change: Change, + *, + label: str, + finding_id: str, +) -> ApplyResult: + """Write ``change.after`` to Steam's files, after saving a snapshot to undo it.""" + if change.blocked: + return ApplyResult(False, change.blocked, "", None) + if not change.changed: + return ApplyResult(False, "This fix would not change anything.", "", None) + current = read_state(localconfig, config_vdf, app_id) + if current is None or localconfig is None or config_vdf is None: + return ApplyResult(False, _UNREADABLE, "", None) + if current != change.before: + return ApplyResult(False, _STATE_MOVED, "", current) + try: + snap = snapshots.record(app_id, label, finding_id, change.before, change.after) + except (OSError, ValueError): + return ApplyResult( + False, "ProtonShift could not save a way to undo this fix, so nothing was changed.", "", current, + ) + + failure = _write(localconfig, config_vdf, app_id, current, change.after, unchanged="nothing was changed") + if failure: + snapshots.drop(app_id, snap.id) + return ApplyResult(False, failure, "", read_state(localconfig, config_vdf, app_id)) + + now = read_state(localconfig, config_vdf, app_id) + if now != change.after: + # The undo point stays: whatever did land can still be put back with Undo. + return ApplyResult( + False, + "The fix was written, but Steam's files do not show it now. Close Steam and run Diagnose again.", + snap.id, now, + ) + return ApplyResult(True, "The fix was applied. You can undo it from Diagnose.", snap.id, now) + + +def undo_latest( + localconfig: Path | None, + config_vdf: Path | None, + app_id: str, + *, + force: bool = False, +) -> ApplyResult: + """Put back the settings from before the latest fix, then forget that fix. + + When the settings were changed after the fix was applied, Undo would + overwrite those changes, so it refuses unless ``force`` is set. The + result's ``snapshot_id`` is the snapshot Undo acted on; it is dropped only + when the settings are back as they were before the fix. + """ + snap = snapshots.latest(app_id) + if snap is None: + return ApplyResult(False, "There is no fix to undo for this game.", "", None) + current = read_state(localconfig, config_vdf, app_id) + if current is None or localconfig is None or config_vdf is None: + return ApplyResult(False, _UNREADABLE, snap.id, None) + if current == snap.before: + snapshots.drop(app_id, snap.id) + return ApplyResult( + True, "The settings were already back to how they were before the fix.", snap.id, current, + ) + if current != snap.after and not force: + message = ( + "The settings were changed after the fix was applied, so Undo would overwrite those changes. " + f"The launch options are now {_shown(current.launch_options)}; before the fix they were " + f"{_shown(snap.before.launch_options)}." + ) + if current.compat_tool != snap.before.compat_tool: + message += (f" The Proton build is now {_shown(current.compat_tool)}; before the fix it was " + f"{_shown(snap.before.compat_tool)}.") + return ApplyResult(False, message, snap.id, current) + + failure = _write( + localconfig, config_vdf, app_id, current, snap.before, unchanged="the fix is still in place", + ) + if failure: + return ApplyResult(False, failure, snap.id, read_state(localconfig, config_vdf, app_id)) + now = read_state(localconfig, config_vdf, app_id) + if now != snap.before: + return ApplyResult( + False, + "The old settings were written, but Steam's files do not show them now. " + "Close Steam and try Undo again.", + snap.id, now, + ) + snapshots.drop(app_id, snap.id) + return ApplyResult(True, "The fix was undone.", snap.id, now) + + +def undo_available(app_id: str) -> Snapshot | None: + """The fix Undo would take back, or None when there is none.""" + return snapshots.latest(app_id) diff --git a/protonshift/core/launch_check.py b/protonshift/core/launch_check.py index ecb159b..a550605 100644 --- a/protonshift/core/launch_check.py +++ b/protonshift/core/launch_check.py @@ -3,34 +3,37 @@ ``check_launch`` is pure: it is handed everything it needs to know (the launch-options line, the chosen compatibility tool, what is installed) and returns a list of findings, so it runs without Steam, a display or a disk in -tests. ``LaunchCheckController`` gathers the inputs on a worker thread. +tests. ``diagnose.collect`` gathers the inputs. Each finding is a dict with ``level`` (``error`` stops the game from starting, ``warn`` probably matters, ``info`` is context, ``ok`` is a passed check), -``title``, ``detail`` and ``fix`` (what to do about it; empty when nothing). +``title``, ``detail``, ``fix`` (what to do about it; empty when nothing), +``id`` (stable kebab-case, the same finding has the same id on every run) and +``actions`` (a tuple of ``fix_pack.Action``: the one-click fix where one is +mechanical, empty otherwise). ``single_command`` and ``add_command`` actions +exist only here; a fix pack cannot name them. """ from __future__ import annotations import re -from collections.abc import Callable, Iterable +from collections.abc import Callable, Iterable, Sequence from pathlib import Path +from typing import Any -from .launch_merge import COMMAND, _tokens +from .fix_pack import Action +from .launch_merge import ( + COMMAND, + KNOWN_COMMANDS, + _tokens, + add_command, + remove_word, + single_command, + unset_env, +) _ENV_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=") -# Wrapper commands people put in launch options -> the name to show. -KNOWN_COMMANDS: dict[str, str] = { - "gamemoderun": "GameMode", - "mangohud": "MangoHud", - "gamescope": "gamescope", - "scb": "ScopeBuddy", - "scopebuddy": "ScopeBuddy", - "obs-gamecapture": "OBS game capture", - "prime-run": "prime-run", - "strangle": "libstrangle", -} # Environment switches that only do something when a tool is installed. ENV_NEEDS: dict[str, tuple[str, str]] = { "MANGOHUD": ("mangohud", "MangoHud"), @@ -47,8 +50,22 @@ } -def finding(level: str, title: str, detail: str = "", fix: str = "") -> dict[str, str]: - return {"level": level, "title": title, "detail": detail, "fix": fix} +def finding( + level: str, + title: str, + detail: str = "", + fix: str = "", + *, + id: str = "", + actions: Sequence[Action] = (), +) -> dict[str, Any]: + """One finding. ``id`` is stable across runs; ``actions`` is the one-click fix, if there is one.""" + return {"level": level, "title": title, "detail": detail, "fix": fix, "id": id, "actions": tuple(actions)} + + +def _if_it_changes(text: str, edit: Callable[[str], str], action: Action) -> tuple[Action, ...]: + # An action that would leave the line as it is would offer a button that does nothing. + return (action,) if edit(text) != text else () def detect_anticheat(install_path: Path | None, max_depth: int = 3) -> set[str]: @@ -77,14 +94,15 @@ def detect_anticheat(install_path: Path | None, max_depth: int = 3) -> set[str]: return found -def check_launch_options(text: str, tool_exists: Callable[[str], bool]) -> list[dict[str, str]]: +def check_launch_options(text: str, tool_exists: Callable[[str], bool]) -> list[dict[str, Any]]: """Findings about the launch-options line alone.""" text = text.strip() if not text: - return [finding("ok", "Launch options are empty", "The game starts with Steam's defaults.")] + return [finding("ok", "Launch options are empty", "The game starts with Steam's defaults.", + id="launch-empty")] tokens = _tokens(text) count = tokens.count(COMMAND) - out: list[dict[str, str]] = [] + out: list[dict[str, Any]] = [] before = tokens[: tokens.index(COMMAND)] if count else [] if count > 1: @@ -92,6 +110,8 @@ def check_launch_options(text: str, tool_exists: Callable[[str], bool]) -> list[ "error", "%command% appears more than once", "Steam replaces every %command% with the game, so it would be started inside itself.", "Keep a single %command% in the launch options.", + id="command-twice", + actions=_if_it_changes(text, single_command, Action("single_command")), )) if count == 0: # Without %command% the whole line is handed to the game as arguments. @@ -102,6 +122,8 @@ def check_launch_options(text: str, tool_exists: Callable[[str], bool]) -> list[ f"Without it, {', '.join(stray[:3])} {'is' if len(stray) == 1 else 'are'} passed to the game " "as arguments instead of wrapping it, so nothing they are meant to do happens.", "Add %command% after them, for example: " + " ".join(stray[:3]) + " %command%", + id="command-missing", + actions=_if_it_changes(text, add_command, Action("add_command")), )) seen: set[str] = set() @@ -115,6 +137,10 @@ def check_launch_options(text: str, tool_exists: Callable[[str], bool]) -> list[ "warn", f"{need[1]} isn't installed", f"{token} is set, but without {need[1]} it does nothing.", f"Install {need[1]} from your package manager, or remove {token}.", + id=f"env-needs-{key.lower().replace('_', '-')}", + actions=_if_it_changes( + text, lambda t, k=key: unset_env(t, k), Action("unset_env", key=key), + ), )) continue name = token.rsplit("/", 1)[-1] @@ -126,9 +152,13 @@ def check_launch_options(text: str, tool_exists: Callable[[str], bool]) -> list[ f"The launch options run the game through `{name}`, which wasn't found. " "Steam then fails to start the game at all, usually without a message.", f"Install {KNOWN_COMMANDS[name]}, or remove `{name}` from the launch options.", + id=f"wrapper-missing-{name}", + actions=_if_it_changes( + text, lambda t, n=name: remove_word(t, n), Action("remove_word", value=name), + ), )) if not out: - out.append(finding("ok", "Launch options look right", text)) + out.append(finding("ok", "Launch options look right", text, id="launch-ok")) return out @@ -143,9 +173,9 @@ def check_launch( installed_app_ids: Iterable[str], tool_exists: Callable[[str], bool], protondb_tier: str = "", -) -> list[dict[str, str]]: +) -> list[dict[str, Any]]: """All findings for one Steam game, most serious first.""" - out: list[dict[str, str]] = [] + out: list[dict[str, Any]] = [] # --- the game's files --- if install_path is None or not install_path.is_dir(): @@ -153,9 +183,10 @@ def check_launch( "error", "The install folder is missing", str(install_path) if install_path else "Steam lists the game, but its folder isn't on disk.", "Let Steam verify the game files (Properties, Installed Files), or reinstall it.", + id="install-missing", )) else: - out.append(finding("ok", "Game files are present", str(install_path))) + out.append(finding("ok", "Game files are present", str(install_path), id="install-ok")) # --- launch options --- if launch_options_readable: @@ -164,6 +195,7 @@ def check_launch( out.append(finding( "warn", "Couldn't read the launch options", "Steam's localconfig.vdf could not be parsed, so they were not checked.", + id="launch-unreadable", )) # --- compatibility tool --- @@ -173,33 +205,37 @@ def check_launch( "error", f"The chosen Proton build is gone: {compat_tool}", "It is still selected for this game but is no longer installed, so Steam can't start the game.", "Pick another build under Proton version, or reinstall this one from the Proton builds tab.", + id="proton-gone", + actions=(Action("default_proton"),), )) elif compat_tool: - out.append(finding("ok", f"Proton build is installed: {compat_tool}")) + out.append(finding("ok", f"Proton build is installed: {compat_tool}", id="proton-ok")) else: out.append(finding("info", "Using Steam's default Proton", - "No build is forced for this game; Steam picks one itself.")) + "No build is forced for this game; Steam picks one itself.", id="proton-default")) # --- anti-cheat runtimes --- installed = set(installed_app_ids) for kind in sorted(detect_anticheat(install_path)): app_id, name = ANTICHEAT_RUNTIMES[kind] if app_id in installed: - out.append(finding("ok", f"{name} is installed")) + out.append(finding("ok", f"{name} is installed", id=f"anticheat-ok-{kind}")) else: out.append(finding( "warn", f"{name} isn't installed", "This game ships that anti-cheat. Without the runtime it usually starts and then " "refuses to connect or closes.", f"Install \"{name}\" from your Steam library (enable Tools in the library filter).", + id=f"anticheat-missing-{kind}", )) # --- prefix --- if prefix_path is None or not prefix_path.is_dir(): out.append(finding("info", "No Proton prefix yet", - "Steam creates it the first time the game runs. A first launch takes longer.")) + "Steam creates it the first time the game runs. A first launch takes longer.", + id="prefix-none")) else: - out.append(finding("ok", "Proton prefix exists", str(prefix_path))) + out.append(finding("ok", "Proton prefix exists", str(prefix_path), id="prefix-ok")) # --- what other players report --- tier = protondb_tier.strip().lower() @@ -208,17 +244,19 @@ def check_launch( "warn", "ProtonDB rates this game Borked", "Most players report it does not run under Proton at all, whatever the settings.", "Read the recent reports on ProtonDB before spending time on it.", + id="protondb-borked", )) elif tier == "bronze": out.append(finding("info", "ProtonDB rates this game Bronze", - "It runs for some players, often with crashes or missing features.")) + "It runs for some players, often with crashes or missing features.", + id="protondb-bronze")) order = {"error": 0, "warn": 1, "info": 2, "ok": 3} out.sort(key=lambda f: order.get(f["level"], 4)) # stable: keeps the order within a level return out -def summarize(findings: list[dict[str, str]]) -> str: +def summarize(findings: list[dict[str, Any]]) -> str: errors = sum(1 for f in findings if f["level"] == "error") warns = sum(1 for f in findings if f["level"] == "warn") if errors: diff --git a/protonshift/core/launch_merge.py b/protonshift/core/launch_merge.py index ab51e32..0a54a65 100644 --- a/protonshift/core/launch_merge.py +++ b/protonshift/core/launch_merge.py @@ -8,6 +8,25 @@ wrapping it. :func:`merge_launch_snippet` places each kind of snippet where it belongs and always leaves exactly one ``%command%``. +The edit helpers below (:func:`set_env`, :func:`unset_env`, :func:`remove_word`, +:func:`add_game_arg`, :func:`single_command`, :func:`add_command`) are what a +Diagnose fix applies. They share these rules: + +- A helper with nothing to do returns the line exactly as it was given, so a + fix that changes nothing is seen as no change at all. +- Otherwise the result has exactly one ``%command%``, or is the empty string + when nothing is left before or after it (never a bare ``%command%``). +- A line without ``%command%`` is read the way Steam reads it: every word is a + game argument and nothing comes before the game. So :func:`unset_env`, + :func:`remove_word` and :func:`single_command` find nothing to do on it, + :func:`set_env` and :func:`add_game_arg` add ``%command%`` in front of the + existing words (which stay game arguments), and :func:`add_command` is the + one helper that moves words in front of the game. +- Words are split by :func:`split_words`, which keeps ``KEY='a b'`` together + as one word. A line with an unbalanced quote falls back to plain whitespace + splitting, as ``_tokens`` does, so no text is lost. +- Applying a helper twice gives the same line as applying it once. + Pure Python - exercised in tests/test_launch_merge.py. """ @@ -19,8 +38,24 @@ COMMAND = "%command%" _ENV_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=") +_KEY_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") # Programs that take over the launch and end their own arguments with ``--``. _WRAPPERS = ("gamescope", "scb", "scopebuddy") +# What a word right after a removed command looks like when it is that +# command's own option or number (``mangohud --dlsym``, ``strangle 60``). +_OPTION_RE = re.compile(r"-\S*|[0-9][0-9.:]*") + +# Wrapper commands people put in launch options -> the name to show. +KNOWN_COMMANDS: dict[str, str] = { + "gamemoderun": "GameMode", + "mangohud": "MangoHud", + "gamescope": "gamescope", + "scb": "ScopeBuddy", + "scopebuddy": "ScopeBuddy", + "obs-gamecapture": "OBS game capture", + "prime-run": "prime-run", + "strangle": "libstrangle", +} def _tokens(text: str) -> list[str]: @@ -93,3 +128,239 @@ def merge_launch_snippet(text: str, snippet: str) -> str: after = after + [t for t in add_after if t not in after] return " ".join([*before, COMMAND, *after]) + + +# --------------------------------------------------------------------------- # +# edit helpers +# --------------------------------------------------------------------------- # + +def split_words(text: str) -> list[str]: + """Split on whitespace like a shell would, keeping quotes and escapes inside their word. + + Unlike ``_tokens`` (``shlex`` in non-POSIX mode), a quote in the middle of + a word does not end it, so ``KEY='a b'`` is one word. With an unbalanced + quote the line is split on whitespace alone rather than losing text. + """ + words: list[str] = [] + current: list[str] = [] + in_word = False + quote = "" + escaped = False + for ch in text: + if escaped: + current.append(ch) + escaped = False + continue + if quote: + current.append(ch) + if ch == quote: + quote = "" + elif ch == "\\" and quote == '"': + escaped = True + continue + if ch.isspace(): + if in_word: + words.append("".join(current)) + current = [] + in_word = False + continue + current.append(ch) + in_word = True + if ch in "'\"": + quote = ch + elif ch == "\\": + escaped = True + if quote: + return text.split() + if in_word: + words.append("".join(current)) + return words + + +def split_line(text: str) -> tuple[list[str], list[str], int]: + """``(prefix, game_args, command_count)`` of a launch-options line. + + The prefix is what comes before the first ``%command%``; with no + ``%command%`` it is empty and every word is a game argument, which is how + Steam reads such a line. Later ``%command%`` words are left out of both. + """ + words = split_words(text.strip()) + before, after, _ = _split_command(words) + return before, after, words.count(COMMAND) + + +def _join(before: list[str], after: list[str]) -> str: + if not before and not after: + return "" + return " ".join([*before, COMMAND, *after]) + + +def _basename(word: str) -> str: + return word.rsplit("/", 1)[-1] + + +def _is_env(word: str) -> bool: + return _ENV_RE.match(word) is not None + + +def _env_key(word: str) -> str: + return word.split("=", 1)[0] + + +def _dashdash(prefix: list[str], start: int) -> int | None: + return next((i for i in range(start + 1, len(prefix)) if prefix[i] == "--"), None) + + +def prefix_env(prefix: list[str]) -> list[str]: + """The environment assignments (``KEY=value``) in a prefix, in order.""" + return [w for w in prefix if _is_env(w)] + + +def prefix_commands(prefix: list[str]) -> list[str]: + """The command words in a prefix: not assignments, not a wrapper's own options before its ``--``.""" + out: list[str] = [] + i = 0 + while i < len(prefix): + word = prefix[i] + if _is_env(word): + i += 1 + continue + out.append(word) + end = _dashdash(prefix, i) if _basename(word) in _WRAPPERS else None + i = end + 1 if end is not None else i + 1 + return out + + +def _check_key(key: str) -> None: + if not isinstance(key, str) or not _KEY_RE.fullmatch(key): + raise ValueError(f"not a valid variable name: {key!r}") + + +def set_env(text: str, key: str, value: str) -> str: + """Set ``KEY=value`` before ``%command%``. + + An existing assignment of the same key is replaced where it stands (a later + duplicate is dropped, since the shell would let it win); otherwise the + assignment goes to the front of the prefix. + """ + _check_key(key) + before, after, count = split_line(text) + new = f"{key}={value}" + out: list[str] = [] + placed = False + for word in before: + if _is_env(word) and _env_key(word) == key: + if not placed: + out.append(new) + placed = True + continue + out.append(word) + if not placed: + out.insert(0, new) + if count and out == before: + return text + return _join(out, after) + + +def unset_env(text: str, key: str) -> str: + """Remove every assignment of ``KEY`` from before ``%command%``.""" + _check_key(key) + before, after, count = split_line(text) + out = [w for w in before if not (_is_env(w) and _env_key(w) == key)] + if not count or out == before: + return text + return _join(out, after) + + +def remove_word(text: str, word: str) -> str: + """Remove the command ``word`` (compared by basename) from before ``%command%``. + + A wrapper that carries its own options up to ``--`` (gamescope, scb, + scopebuddy) goes together with those options and the ``--``. Without a + ``--`` there is no telling where its options end, so every word after it + up to ``%command%`` goes too: a leftover option would otherwise become the + command Steam runs. Any other command takes the option-like words right + after it (``mangohud --dlsym``, ``strangle 60``) with it, for the same + reason. Environment assignments and game arguments are never removed. + """ + before, after, count = split_line(text) + if not count: + return text + out: list[str] = [] + changed = False + i = 0 + while i < len(before): + current = before[i] + if _is_env(current): + out.append(current) + i += 1 + continue + name = _basename(current) + if name in _WRAPPERS: + end = _dashdash(before, i) + if name == word: + changed = True + if end is None: + out.extend(w for w in before[i + 1:] if _is_env(w)) + break + i = end + 1 + continue + stop = end + 1 if end is not None else i + 1 + out.extend(before[i:stop]) + i = stop + continue + if name == word: + changed = True + i += 1 + while i < len(before) and _OPTION_RE.fullmatch(before[i]): + i += 1 + continue + out.append(current) + i += 1 + if not changed: + return text + return _join(out, after) + + +def add_game_arg(text: str, arg: str) -> str: + """Add ``arg`` after ``%command%`` unless the game already gets it.""" + before, after, _count = split_line(text) + if arg in after: + return text + return _join(before, [*after, arg]) + + +def single_command(text: str) -> str: + """Keep the first ``%command%`` and drop the others.""" + before, after, count = split_line(text) + if count <= 1: + return text + return _join(before, after) + + +def add_command(text: str) -> str: + """Insert ``%command%`` after the leading assignments and known wrapper commands. + + For a line with no ``%command%`` such as ``PROTON_LOG=1 gamemoderun -novid``: + the leading run (``PROTON_LOG=1 gamemoderun``) becomes the prefix and the + rest stays game arguments. A wrapper in the run keeps its options up to its + ``--``. A line that already has ``%command%``, or that does not start with + such words, is returned as it was. + """ + words = split_words(text.strip()) + if COMMAND in words: + return text + i = 0 + while i < len(words): + word = words[i] + if _is_env(word): + i += 1 + continue + name = _basename(word) + if name not in KNOWN_COMMANDS: + break + end = _dashdash(words, i) if name in _WRAPPERS else None + i = end + 1 if end is not None else i + 1 + if i == 0: + return text + return _join(words[:i], words[i:]) diff --git a/tests/test_diagnose.py b/tests/test_diagnose.py new file mode 100644 index 0000000..fe0754e --- /dev/null +++ b/tests/test_diagnose.py @@ -0,0 +1,589 @@ +"""Tests for Diagnose: facts, rule matching, the ranked list, and collect against a tiny fake Steam tree.""" + +from __future__ import annotations + +import dataclasses +import json +import subprocess +from pathlib import Path +from typing import Any + +import pytest +import vdf + +from protonshift.core import diagnose as dg +from protonshift.core import fix_pack, fixes, gpu, host, steam, system_checks, tool_check +from protonshift.core.diagnose import Facts, Finding, diagnose, proton_build, rule_finding, summarize, to_row +from protonshift.core.fix_pack import Action, parse_rule +from protonshift.core.gpu import GPUInfo +from protonshift.core.launch_check import finding as launch_finding +from protonshift.core.snapshots import GameState +from protonshift.core.system_checks import Check + +LOG_LINE = "0024:err:module:import_dll Library d3dcompiler_47.dll not found" +START_FAILED = "0024:err:module:loader_init Importing dlls for L\"C:\\\\game.exe\" failed" + + +BASE = Facts( + app_id="100", steam_app=True, native=False, launch_options="%command%", launch_options_readable=True, + compat_tool="GE-Proton10-12", proton_family="ge", proton_major=10, gpu_vendors=frozenset({"amd"}), + session="wayland", log_lines=None, log_modified="", log_path="", +) + + +def facts(**overrides: Any) -> Facts: + return dataclasses.replace(BASE, **overrides) + + +def rule(**overrides: Any) -> fix_pack.Rule: + raw: dict[str, Any] = { + "id": "test-rule", "title": "A test rule", "cause": "Because of a test.", "severity": "advice", + "match": {"app_ids": ["100"]}, "actions": [], "source": "https://example.org/issue/1", + "verified": "2026-11-16", + } + raw.update(overrides) + return parse_rule(raw) + + +def when_rule(when: dict[str, Any]) -> fix_pack.Rule: + return rule(match={"app_ids": ["100"], "when": when}) + + +def ids(findings: list[Finding]) -> list[str]: + return [f.id for f in findings] + + +# --- proton_build / gpu_vendors / session -------------------------------------------------- + + +@pytest.mark.parametrize( + ("name", "expected"), + [ + # found on the machine this was written on: the Arch proton-ge-custom-bin package + # (also the CompatToolMapping entries in config.vdf) + ("Proton-GE", ("ge", None)), + # Steam's own internal names, every one listed in that machine's appinfo.vdf + ("proton_experimental", ("valve", None)), + ("proton_hotfix", ("valve", None)), + ("proton_11", ("valve", 11)), + ("proton_10", ("valve", 10)), + ("proton_9", ("valve", 9)), + ("proton_8", ("valve", 8)), + ("proton_7", ("valve", 7)), + ("proton_63", ("valve", 6)), + ("proton_513", ("valve", 5)), + ("proton_5", ("valve", 5)), + ("proton_42", ("valve", 4)), + ("proton_411", ("valve", 4)), + ("proton_37", ("valve", 3)), + ("proton_316", ("valve", 3)), + # what older ProtonShift builds offered: not a name Steam knows + ("proton_9_0", ("other", None)), + ("proton_8_0", ("other", None)), + # GE builds + ("GE-Proton10-12", ("ge", 10)), + ("GE-Proton9-20", ("ge", 9)), + ("Proton-6.21-GE-2", ("ge", 6)), + ("proton-ge-custom", ("ge", None)), + # CachyOS + ("proton-cachyos-10.0-20250807-slr", ("cachyos", 10)), + ("proton-cachyos-9.0-20241220-slr-x86_64_v3", ("cachyos", 9)), + ("proton-cachyos", ("cachyos", None)), + # never a guessed number + ("proton_71", ("valve", None)), + ("proton_07", ("valve", None)), + ("proton_next", ("other", None)), + ("GE-Proton9-20-rtsp15", ("other", None)), + ("luxtorpeda", ("other", None)), + ("steamlinuxruntime_sniper", ("other", None)), + ("", ("", None)), + (" ", ("", None)), + ], +) +def test_proton_build(name: str, expected: tuple[str, int | None]) -> None: + assert proton_build(name) == expected + + +def test_every_offered_builtin_is_a_valve_name() -> None: + offered = steam.get_available_proton_tools(None) + builtin = [name for name in offered if name.startswith("proton_")] + assert builtin == [ + "proton_experimental", "proton_hotfix", "proton_11", "proton_10", "proton_9", "proton_8", "proton_7", + ] + assert all(proton_build(name)[0] == "valve" for name in builtin) + + +def gpu_info(name: str, driver: str = "") -> GPUInfo: + return GPUInfo(name=name, driver=driver, vram_mb=None, temperature=None) + + +def test_gpu_vendors() -> None: + # nvidia-smi path: product name and a driver version + assert dg.gpu_vendors([gpu_info("NVIDIA GeForce RTX 4080 Laptop GPU", "615.78.08")]) == {"nvidia"} + assert dg.gpu_vendors([gpu_info("NVIDIA GPU")]) == {"nvidia"} + # sysfs path: the kernel driver as the name + assert dg.gpu_vendors([gpu_info("amdgpu"), gpu_info("i915")]) == {"amd", "intel"} + mixed = [gpu_info("xe"), gpu_info("nouveau"), gpu_info("radeon")] + assert dg.gpu_vendors(mixed) == {"intel", "nvidia", "amd"} + # nothing telling + assert dg.gpu_vendors([gpu_info("Unknown GPU"), gpu_info("virtio_gpu"), gpu_info("")]) == frozenset() + assert dg.gpu_vendors([]) == frozenset() + + +@pytest.mark.parametrize( + ("env", "expected"), + [ + ({"XDG_SESSION_TYPE": "wayland"}, "wayland"), + ({"WAYLAND_DISPLAY": "wayland-1", "DISPLAY": ":0"}, "wayland"), + ({"XDG_SESSION_TYPE": "x11", "DISPLAY": ":0"}, "x11"), + ({"DISPLAY": ":0"}, ""), + ({}, ""), + ], +) +def test_session_type(monkeypatch: pytest.MonkeyPatch, env: dict[str, str], expected: str) -> None: + for key in ("XDG_SESSION_TYPE", "WAYLAND_DISPLAY", "DISPLAY"): + monkeypatch.delenv(key, raising=False) + for key, value in env.items(): + monkeypatch.setenv(key, value) + assert dg.session_type() == expected + + +# --- when ------------------------------------------------------------------------------------------ + + +@pytest.mark.parametrize( + ("when", "overrides", "expected"), + [ + ({"gpu_vendor": ["nvidia"]}, {"gpu_vendors": frozenset({"amd", "nvidia"})}, True), + ({"gpu_vendor": ["nvidia"]}, {"gpu_vendors": frozenset({"amd"})}, False), + ({"gpu_vendor": ["nvidia"]}, {"gpu_vendors": frozenset()}, False), + ({"session": ["x11"]}, {"session": "x11"}, True), + ({"session": ["x11"]}, {"session": "wayland"}, False), + ({"session": ["x11", "wayland"]}, {"session": ""}, False), + ({"proton_family": ["ge", "cachyos"]}, {"proton_family": "ge"}, True), + ({"proton_family": ["valve"]}, {"proton_family": "ge"}, False), + ({"proton_family": ["other"]}, {"proton_family": ""}, False), + ({"proton_major_min": 10}, {"proton_major": 10}, True), + ({"proton_major_min": 10}, {"proton_major": 9}, False), + ({"proton_major_min": 0}, {"proton_major": None}, False), + ({"proton_major_max": 9}, {"proton_major": 9}, True), + ({"proton_major_max": 9}, {"proton_major": 10}, False), + ({"proton_major_max": 99}, {"proton_major": None}, False), + ({"launch_has": ["gamemoderun"]}, {"launch_options": "MANGOHUD=1 gamemoderun %command%"}, True), + ({"launch_has": ["gamemoderun"]}, {"launch_options": "/usr/bin/gamemoderun %command%"}, True), + ({"launch_has": ["gamemoderun", "mangohud"]}, {"launch_options": "gamemoderun %command%"}, False), + ({"launch_has": ["gamemoderun"]}, {"launch_options": "%command% gamemoderun"}, False), + ({"launch_has": ["gamemoderun"]}, {"launch_options": "gamemoderun"}, False), # no %command% + ({"launch_has": ["gamemoderun"]}, {"launch_options": "gamemoderun=1 %command%"}, False), + ({"launch_has": ["gamemoderun"]}, {"launch_options": "gamemoderun %command%", + "launch_options_readable": False}, False), + ({"env_set": ["PROTON_LOG"]}, {"launch_options": "PROTON_LOG=1 %command%"}, True), + ({"env_set": ["PROTON_LOG"]}, {"launch_options": "%command% PROTON_LOG=1"}, False), + ({"env_set": ["PROTON_LOG"]}, {"launch_options": "PROTON_LOG=1"}, False), # no %command% + ({"env_set": ["PROTON_LOG"]}, {"launch_options": "PROTON_LOG=1 %command%", + "launch_options_readable": False}, False), + ({"env_unset": ["PROTON_LOG"]}, {"launch_options": "gamemoderun %command%"}, True), + ({"env_unset": ["PROTON_LOG"]}, {"launch_options": "PROTON_LOG=1 %command%"}, False), + ({"env_unset": ["PROTON_LOG"]}, {"launch_options": "PROTON_LOG=1"}, True), # an argument, not set + ({"env_unset": ["PROTON_LOG"]}, {"launch_options_readable": False}, False), + # every listed condition must hold + ({"gpu_vendor": ["amd"], "session": ["x11"]}, {}, False), + ({"gpu_vendor": ["amd"], "session": ["wayland"], "proton_family": ["ge"]}, {}, True), + ], +) +def test_when_holds(when: dict[str, Any], overrides: dict[str, Any], expected: bool) -> None: + assert dg.when_holds(when_rule(when).when, facts(**overrides)) is expected + + +def test_an_unset_when_holds() -> None: + assert dg.when_holds(fix_pack.When(), facts(gpu_vendors=frozenset(), session="", proton_family="")) + + +# --- rule_finding ----------------------------------------------------------------------------------- + + +def test_app_ids() -> None: + r = rule(match={"app_ids": ["100", "200"]}, actions=[{"type": "game_arg", "value": "-dx11"}]) + found = rule_finding(r, facts(app_id="200")) + assert found is not None + assert (found.id, found.severity, found.origin, found.evidence) == ("test-rule", "advice", "pack", "") + assert found.actions == (Action("game_arg", value="-dx11"),) + assert found.source == "https://example.org/issue/1" + assert rule_finding(r, facts(app_id="300")) is None + + +def test_log_rule() -> None: + r = rule(severity="likely", match={"log": [r"Library d3dcompiler_47\.dll not found"]}) + assert rule_finding(r, facts(log_lines=None)) is None + assert rule_finding(r, facts(log_lines=("nothing here",))) is None + found = rule_finding(r, facts(log_lines=("start", " " + LOG_LINE + " ", "end"))) + assert found is not None + assert (found.origin, found.evidence, found.severity) == ("log", LOG_LINE, "likely") + + +def test_log_also() -> None: + r = rule(severity="blocking", match={ + "log": [r"Library d3dcompiler_47\.dll not found"], "log_also": [r"loader_init Importing dlls"], + }) + assert rule_finding(r, facts(log_lines=(LOG_LINE,))) is None + found = rule_finding(r, facts(log_lines=(LOG_LINE, START_FAILED))) + assert found is not None and found.evidence == LOG_LINE + + +def test_log_rule_with_when_and_app_ids() -> None: + r = rule(severity="likely", match={ + "app_ids": ["100"], + "log": [r"Library d3dcompiler_47\.dll not found"], + "when": {"gpu_vendor": ["amd"]}, + }) + lines = (LOG_LINE,) + assert rule_finding(r, facts(log_lines=lines)) is not None + assert rule_finding(r, facts(log_lines=lines, gpu_vendors=frozenset({"intel"}))) is None + assert rule_finding(r, facts(log_lines=lines, app_id="1")) is None + + +def test_native_games_skip_proton_rules() -> None: + lines = (LOG_LINE,) + log_rule = rule(severity="likely", match={"log": [r"Library d3dcompiler_47\.dll not found"]}) + proton_rule = rule(match={"app_ids": ["100"], "when": {"proton_family": ["ge"]}}) + word_rule = rule(match={"when": {"launch_has": ["gamemoderun"]}}) + native = {"native": True, "log_lines": lines, "launch_options": "gamemoderun %command%"} + assert rule_finding(log_rule, facts(**native)) is None + assert rule_finding(proton_rule, facts(**native)) is None + assert rule_finding(word_rule, facts(**native)) is not None + assert rule_finding(proton_rule, facts()) is not None + + +def test_evidence_is_the_setting_that_matched() -> None: + word = rule(match={"when": {"launch_has": ["gamemoderun"], "env_set": ["PROTON_LOG"]}}) + line = "PROTON_LOG=1 /usr/bin/gamemoderun mangohud %command% -x" + found = rule_finding(word, facts(launch_options=line)) + assert found is not None and found.evidence == "/usr/bin/gamemoderun PROTON_LOG=1" + build = rule(match={"app_ids": ["100"], "when": {"proton_major_max": 10}}) + found = rule_finding(build, facts()) + assert found is not None and found.evidence == "GE-Proton10-12" + + +def test_user_rules(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + monkeypatch.setattr(fixes, "_USER_FIXES_DIR", tmp_path) + (tmp_path / "100.json").write_text(json.dumps([ + {"title": "Use DX11", "description": "Runs better for me.", "type": "launch_arg", "value": "-dx11"}, + {"title": "HUD", "description": "", "type": "env", "key": "DXVK_HUD", "value": "fps"}, + ]), encoding="utf-8") + found = [rule_finding(r, facts()) for r in fix_pack.user_rules("100")] + assert [(f.id, f.origin, f.severity) for f in found if f] == [("user-1", "user", "advice"), + ("user-2", "user", "advice")] + assert found[0] is not None and found[0].actions == (Action("user_snippet", value="-dx11"),) + assert all(rule_finding(r, facts(app_id="7")) is None for r in fix_pack.user_rules("100")) + + +# --- diagnose ------------------------------------------------------------------------------------------- + + +def check(cid: str, state: str) -> Check: + fix = f"fix for {cid}" if state == "problem" else "" + return Check(cid, state, f"{cid} {state}", f"detail of {cid}", fix) + + +def test_severity_mapping_and_order() -> None: + launch = [ + launch_finding("ok", "Game files are present", id="install-ok"), + launch_finding("info", "Using Steam's default Proton", id="proton-default"), + launch_finding("warn", "MangoHud isn't installed", "MANGOHUD=1 is set.", "Install it.", + id="env-needs-mangohud", actions=(Action("unset_env", key="MANGOHUD"),)), + launch_finding("error", "%command% appears more than once", id="command-twice", + actions=(Action("single_command"),)), + launch_finding("error", "The chosen Proton build is gone", id="proton-gone", + actions=(Action("default_proton"),)), + ] + checks = [check("vulkan", "problem"), check("vulkan-32bit", "problem"), check("disk-library", "ok"), + check("disk-prefix", "unknown")] + rules = [rule(id="advice-one"), rule(id="likely-one", severity="likely", + match={"when": {"launch_has": ["gamemoderun"]}})] + found = diagnose(facts(launch_options="MANGOHUD=1 gamemoderun %command% %command%"), + rules=rules, launch_findings=launch, checks=checks) + assert [(f.id, f.severity, f.origin) for f in found] == [ + ("command-twice", "blocking", "check"), + ("proton-gone", "blocking", "check"), + ("vulkan", "blocking", "system"), + ("env-needs-mangohud", "likely", "check"), + ("likely-one", "likely", "pack"), + ("vulkan-32bit", "likely", "system"), + ("advice-one", "advice", "pack"), + ("proton-default", "context", "check"), + ("log-off", "context", "log"), + ("disk-prefix", "context", "system"), + ("install-ok", "ok", "check"), + ("disk-library", "ok", "system"), + ] + by_id = {f.id: f for f in found} + assert by_id["env-needs-mangohud"].cause == "MANGOHUD=1 is set." + assert by_id["env-needs-mangohud"].fix == "Install it." + assert by_id["env-needs-mangohud"].evidence == "MANGOHUD=1 gamemoderun %command% %command%" + assert by_id["proton-gone"].evidence == "GE-Proton10-12" + assert by_id["vulkan"].fix == "fix for vulkan" + assert by_id["likely-one"].evidence == "gamemoderun" + assert summarize(found) == "3 problems that will stop the game from starting, 3 more worth a look." + + +def test_native_games() -> None: + launch = [ + launch_finding("error", "The chosen Proton build is gone", id="proton-gone"), + launch_finding("info", "No Proton prefix yet", id="prefix-none"), + launch_finding("warn", "Proton EasyAntiCheat Runtime isn't installed", id="anticheat-missing-eac"), + launch_finding("ok", "Game files are present", id="install-ok"), + ] + checks = [check("vulkan", "problem"), check("disk-prefix", "problem"), check("disk-library", "ok")] + found = diagnose(facts(native=True, proton_family="", proton_major=None, log_lines=("err: x",)), + rules=[], launch_findings=launch, checks=checks) + assert [(f.id, f.severity) for f in found] == [("vulkan", "likely"), ("install-ok", "ok"), + ("disk-library", "ok")] + + +def test_dedup_keeps_the_first() -> None: + launch = [launch_finding("error", "From the check", id="command-twice")] + rules = [rule(id="command-twice", severity="advice"), rule(id="twice-here", title="first"), + rule(id="twice-here", title="second")] + found = diagnose(facts(), rules=rules, launch_findings=launch, checks=[]) + assert ids(found).count("command-twice") == 1 + assert next(f for f in found if f.id == "command-twice").origin == "check" + assert [f.title for f in found if f.id == "twice-here"] == ["first"] + + +def test_a_launch_finding_without_id_still_gets_one() -> None: + found = diagnose(facts(), rules=[], launch_findings=[{"level": "warn", "title": "Old style"}], checks=[]) + assert "check-0" in ids(found) + + +# --- log rows --------------------------------------------------------------------------------------------- + + +def log_rows(f: Facts, rules: list[fix_pack.Rule] | None = None) -> list[Finding]: + found = diagnose(f, rules=rules or [], launch_findings=[], checks=[]) + return [x for x in found if x.id.startswith("log-")] + + +def test_no_log_offers_to_turn_logging_on() -> None: + (row,) = log_rows(facts(launch_options="gamemoderun %command%")) + assert (row.id, row.severity, row.origin) == ("log-off", "context", "log") + assert row.actions == (Action("env", key="PROTON_LOG", value="1"),) + (row,) = log_rows(facts(launch_options_readable=False)) + assert row.id == "log-off" and row.actions == () + + +def test_no_log_while_logging_is_on() -> None: + (row,) = log_rows(facts(launch_options="PROTON_LOG=1 %command%")) + assert row.id == "log-waiting" + assert "run the game once, then diagnose again" in row.cause.lower() + assert row.actions == () + + +def test_no_log_rows_for_shortcuts_without_a_log_or_native_games() -> None: + assert log_rows(facts(steam_app=False)) == [] + assert log_rows(facts(native=True)) == [] + assert log_rows(facts(native=True, log_lines=("err: x",))) == [] + + +def test_a_log_says_which_and_when() -> None: + f = facts(log_lines=("all fine",), log_modified="2026-11-16 01:23", log_path="/home/u/steam-100.log", + launch_options="PROTON_LOG=1 %command%") + (row,) = log_rows(f) + assert row.id == "log-read" and row.severity == "context" + assert "/home/u/steam-100.log" in row.cause and "2026-11-16 01:23" in row.cause + assert "2026-11-16 01:23" in row.title + assert row.evidence == "/home/u/steam-100.log" + assert "earlier run" not in row.cause + (row,) = log_rows(dataclasses.replace(f, launch_options="%command%")) + assert "Logging is off now" in row.cause + + +def test_unrecognised_problem_lines() -> None: + lines = ("fine", LOG_LINE, "wine: Unhandled page fault on read access", "fine again") + rows = log_rows(facts(log_lines=lines)) + assert ids(rows) == ["log-read", "log-unrecognised"] + assert rows[1].title.startswith("2 lines in the log look like problems") + assert rows[1].evidence == LOG_LINE + one = log_rows(facts(log_lines=(LOG_LINE,))) + assert one[1].title.startswith("1 line in the log looks like a problem") + # a log rule that recognised a line takes its place + known = rule(severity="likely", match={"log": [r"Library d3dcompiler_47\.dll not found"]}) + assert ids(log_rows(facts(log_lines=lines), [known])) == ["log-read"] + # nothing that looks like a problem: no row + assert ids(log_rows(facts(log_lines=("fine",)))) == ["log-read"] + + +# --- rows and summary --------------------------------------------------------------------------------------- + + +def test_to_row() -> None: + f = Finding("x", "likely", "T", "C", "E", "F", "https://example.org", "pack", + (Action("manual", text="Install it."), Action("env", key="A", value="1"))) + row = to_row(f) + assert row == { + "id": "x", "severity": "likely", "title": "T", "cause": "C", "evidence": "E", "fix": "F", + "source": "https://example.org", "origin": "pack", "manual": ["Install it."], "canApply": True, + } + assert all(isinstance(v, (str, bool, list)) for v in row.values()) + manual_only = to_row(dataclasses.replace(f, actions=(Action("manual", text="Do it."),))) + assert manual_only["canApply"] is False and manual_only["manual"] == ["Do it."] + assert to_row(dataclasses.replace(f, actions=()))["canApply"] is False + + +def sev(*severities: str) -> list[Finding]: + return [Finding(str(i), s, "", "", "", "", "", "pack", ()) for i, s in enumerate(severities)] + + +@pytest.mark.parametrize( + ("severities", "expected"), + [ + (("blocking", "blocking", "likely", "ok"), + "2 problems that will stop the game from starting, 1 more worth a look."), + (("blocking",), "1 problem that will stop the game from starting."), + (("likely", "context"), "Nothing blocks the launch. 1 thing worth a look."), + (("likely", "likely"), "Nothing blocks the launch. 2 things worth a look."), + (("advice", "ok"), "No problems found. 1 suggestion you can try."), + (("context", "ok"), "No problems found."), + ((), "No problems found."), + ], +) +def test_summarize(severities: tuple[str, ...], expected: str) -> None: + assert summarize(sev(*severities)) == expected + + +# --- collect ---------------------------------------------------------------------------------------------- + + +APP = "100" + + +@pytest.fixture +def fake_steam(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, Path]: + home = tmp_path / "home" + root = tmp_path / "steam" + (root / "steamapps").mkdir(parents=True) + (root / "config").mkdir() + (root / "userdata" / "12345" / "config").mkdir(parents=True) + game = tmp_path / "game" + game.mkdir() + logs = tmp_path / "logs" + logs.mkdir() + user_fixes = tmp_path / "fixes" + user_fixes.mkdir() + localconfig = root / "userdata" / "12345" / "config" / "localconfig.vdf" + config_vdf = root / "config" / "config.vdf" + write_steam(localconfig, config_vdf, "gamemoderun %command%", "GE-Proton9-20") + + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("PROTON_LOG_DIR", str(logs)) + monkeypatch.setenv("XDG_DATA_DIRS", "") + monkeypatch.setattr(steam, "STEAM_ROOTS", [root]) + steam.invalidate_discovery_cache() + monkeypatch.setattr(fixes, "_USER_FIXES_DIR", user_fixes) + monkeypatch.setattr(tool_check, "is_tool_available", lambda _name: False) + monkeypatch.setattr(gpu, "get_gpu_info", lambda: [gpu_info("amdgpu")]) + monkeypatch.setattr(system_checks, "run_checks", lambda **_kw: [check("vulkan", "ok")]) + monkeypatch.setattr(host, "host_run", lambda *_a, **_kw: subprocess.CompletedProcess([], 1, "", "")) + yield {"root": root, "game": game, "logs": logs, "fixes": user_fixes, + "localconfig": localconfig, "config_vdf": config_vdf} + steam.invalidate_discovery_cache() + + +def write_steam(localconfig: Path, config_vdf: Path, options: str, tool: str) -> None: + apps = {APP: {"LaunchOptions": options}} + local = {"UserLocalConfigStore": {"Software": {"Valve": {"Steam": {"apps": apps}}}}} + mapping = {APP: {"name": tool, "config": "", "priority": "250"}} if tool else {} + config = {"InstallConfigStore": {"Software": {"Valve": {"Steam": {"CompatToolMapping": mapping}}}}} + localconfig.write_text(vdf.dumps(local, pretty=True), encoding="utf-8") + config_vdf.write_text(vdf.dumps(config, pretty=True), encoding="utf-8") + + +def test_collect_a_steam_game(fake_steam: dict[str, Path]) -> None: + (fake_steam["logs"] / f"steam-{APP}.log").write_text(f"start\n{LOG_LINE}\nend\n", encoding="utf-8") + (fake_steam["fixes"] / f"{APP}.json").write_text(json.dumps( + [{"title": "Use DX11", "description": "", "type": "launch_arg", "value": "-dx11"}]), encoding="utf-8") + report = dg.collect(APP, install_path=str(fake_steam["game"]), prefix_path="", shortcut_options=None, + native=False, protondb_tier="") + found = {f.id: f for f in report.findings} + assert {"wrapper-missing-gamemoderun", "proton-gone", "log-read", "log-unrecognised", "user-1", + "prefix-none", "vulkan"} <= set(found) + assert found["wrapper-missing-gamemoderun"].actions == (Action("remove_word", value="gamemoderun"),) + assert found["log-unrecognised"].evidence == LOG_LINE + assert report.summary.startswith("2 problems that will stop the game from starting") + assert report.state == GameState("gamemoderun %command%", "GE-Proton9-20") + assert report.can_apply is True + assert report.steam_running is False + assert report.log_path == str(fake_steam["logs"] / f"steam-{APP}.log") + assert report.paths == (fake_steam["localconfig"], fake_steam["config_vdf"]) + assert report.findings[0].severity == "blocking" + + +def test_collect_never_reports_a_valve_build_as_gone(fake_steam: dict[str, Path]) -> None: + write_steam(fake_steam["localconfig"], fake_steam["config_vdf"], "", "proton_9") + report = dg.collect(APP, install_path=str(fake_steam["game"]), prefix_path="", shortcut_options=None, + native=False, protondb_tier="") + found = {f.id for f in report.findings} + assert "proton-ok" in found and "proton-gone" not in found + assert "log-off" in found + + +@pytest.mark.parametrize("tool", ["proton_9", "proton_experimental", "proton_hotfix", "proton_63"]) +def test_collect_counts_any_valve_build_as_available(fake_steam: dict[str, Path], tool: str) -> None: + write_steam(fake_steam["localconfig"], fake_steam["config_vdf"], "", tool) + report = dg.collect(APP, install_path=str(fake_steam["game"]), prefix_path="", shortcut_options=None, + native=False, protondb_tier="") + assert "proton-gone" not in {f.id for f in report.findings} + + +def test_collect_reports_a_name_steam_does_not_know(fake_steam: dict[str, Path]) -> None: + # Older ProtonShift builds wrote proton_9_0, which Steam never used. + write_steam(fake_steam["localconfig"], fake_steam["config_vdf"], "", "proton_9_0") + report = dg.collect(APP, install_path=str(fake_steam["game"]), prefix_path="", shortcut_options=None, + native=False, protondb_tier="") + gone = next(f for f in report.findings if f.id == "proton-gone") + assert gone.severity == "blocking" + assert gone.actions == (Action("default_proton"),) + + +def test_collect_a_shortcut(fake_steam: dict[str, Path]) -> None: + report = dg.collect("3000000000", install_path=str(fake_steam["game"]), prefix_path="", + shortcut_options="mangohud %command%", native=False, protondb_tier="") + assert report.state is None and report.can_apply is False + found = {f.id for f in report.findings} + assert "wrapper-missing-mangohud" in found + assert not any(fid.startswith("log-") for fid in found) + + +def test_collect_a_native_game(fake_steam: dict[str, Path]) -> None: + (fake_steam["logs"] / f"steam-{APP}.log").write_text(LOG_LINE + "\n", encoding="utf-8") + report = dg.collect(APP, install_path=str(fake_steam["game"]), prefix_path="", shortcut_options=None, + native=True, protondb_tier="") + found = {f.id for f in report.findings} + assert not any(fid.startswith(("proton-", "prefix-", "anticheat-", "log-")) for fid in found) + assert report.log_path == "" + assert report.can_apply is True + + +def test_collect_without_steam(fake_steam: dict[str, Path], monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(steam, "STEAM_ROOTS", []) + steam.invalidate_discovery_cache() + report = dg.collect(APP, install_path="", prefix_path="", shortcut_options=None, native=False, + protondb_tier="") + found = {f.id for f in report.findings} + assert {"launch-unreadable", "install-missing"} <= found + assert report.state is None and report.can_apply is False + assert report.paths == (None, None) + + +def test_collect_survives_failing_helpers( + fake_steam: dict[str, Path], monkeypatch: pytest.MonkeyPatch, +) -> None: + def boom(*_a: object, **_kw: object) -> None: + raise RuntimeError("broken") + + monkeypatch.setattr(gpu, "get_gpu_info", boom) + monkeypatch.setattr(system_checks, "run_checks", boom) + monkeypatch.setattr(host, "host_run", boom) + report = dg.collect(APP, install_path=str(fake_steam["game"]), prefix_path="", shortcut_options=None, + native=False, protondb_tier="") + assert report.steam_running is None + assert "wrapper-missing-gamemoderun" in {f.id for f in report.findings} diff --git a/tests/test_fix_apply.py b/tests/test_fix_apply.py new file mode 100644 index 0000000..7cae89a --- /dev/null +++ b/tests/test_fix_apply.py @@ -0,0 +1,339 @@ +"""Tests for planning, applying and undoing Diagnose fixes (pure logic plus VDF files under tmp_path).""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +import vdf + +from protonshift.core import fix_apply, snapshots +from protonshift.core.fix_apply import Change, apply_change, plan, read_state, undo_available, undo_latest +from protonshift.core.fix_pack import Action +from protonshift.core.snapshots import GameState + +APP = "1091500" + + +def state(options: str = "", tool: str = "") -> GameState: + return GameState(launch_options=options, compat_tool=tool) + + +# --- plan ----------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("action", "before", "after"), + [ + (Action("env", key="PROTON_LOG", value="1"), state("gamemoderun %command%"), + state("PROTON_LOG=1 gamemoderun %command%")), + (Action("unset_env", key="MANGOHUD"), state("MANGOHUD=1 %command% -novid"), + state("%command% -novid")), + (Action("game_arg", value="-vulkan"), state(""), state("%command% -vulkan")), + (Action("remove_word", value="gamemoderun"), state("gamemoderun mangohud %command%"), + state("mangohud %command%")), + (Action("default_proton"), state("%command% -x", "GE-Proton9-20"), state("%command% -x", "")), + (Action("single_command"), state("%command% %command% -x"), state("%command% -x")), + (Action("add_command"), state("gamemoderun -novid"), state("gamemoderun %command% -novid")), + # the user's own launch_arg: with %command% it is merged like any snippet ... + (Action("user_snippet", value="gamemoderun %command%"), state("%command% -novid"), + state("gamemoderun %command% -novid")), + # ... and without it, it is game arguments + (Action("user_snippet", value="-dx11 -windowed"), state("gamemoderun %command%"), + state("gamemoderun %command% -dx11 -windowed")), + ], +) +def test_plan_each_action(action: Action, before: GameState, after: GameState) -> None: + change = plan([action], before) + assert change == Change(before=before, after=after, manual=(), blocked="") + assert change.changed + + +def test_plan_manual_changes_nothing() -> None: + change = plan([Action("manual", text="Install the 32-bit Vulkan driver."), + Action("manual", text="Then restart the computer.")], state("%command%")) + assert not change.changed + assert change.manual == ("Install the 32-bit Vulkan driver.", "Then restart the computer.") + assert change.blocked == "" + + +def test_plan_applies_actions_in_order() -> None: + change = plan([ + Action("remove_word", value="gamemoderun"), + Action("env", key="DXVK_ASYNC", value="1"), + Action("manual", text="Verify the game files."), + Action("default_proton"), + ], state("gamemoderun %command%", "GE-Proton9-1")) + assert change.after == state("DXVK_ASYNC=1 %command%", "") + assert change.manual == ("Verify the game files.",) + + +def test_plan_that_changes_nothing() -> None: + change = plan([Action("env", key="A", value="1")], state("A=1 %command%")) + assert not change.changed + assert change.blocked == "" + + +@pytest.mark.parametrize( + "value", + ["a b", "'x'", '"x"', "a;b", "$(id)", "`id`", "a|b", "%command%", "x%command%y", "a" * 201], +) +def test_plan_refuses_an_env_value_outside_the_pack_characters(value: str) -> None: + before = state("%command%") + actions = [Action("env", key="DXVK_HUD", value=value), Action("manual", text="Or do it by hand.")] + change = plan(actions, before) + assert "characters ProtonShift will not write" in change.blocked + assert change.after == before and not change.changed + assert change.manual == ("Or do it by hand.",) + + +@pytest.mark.parametrize("key", ["LD_PRELOAD", "PATH", "STEAM_COMPAT_DATA_PATH", "A B", "", "1A"]) +def test_plan_refuses_keys_it_must_not_touch(key: str) -> None: + for kind in ("env", "unset_env"): + change = plan([Action(kind, key=key, value="1")], state("%command%")) + assert change.blocked + assert not change.changed + + +def test_plan_refuses_unknown_and_malformed_actions() -> None: + assert "does not know" in plan([Action("run_script", value="x")], state()).blocked + assert plan([Action("game_arg", value="-a -b")], state()).blocked + assert plan([Action("remove_word", value="../x")], state()).blocked + assert plan([Action("user_snippet", value=" ")], state()).blocked + + +def test_plan_refuses_a_line_break() -> None: + for value in ("-a\n-b", '-a "x\ny"', "-a\r", "-a\x00"): + change = plan([Action("user_snippet", value=value)], state("%command%")) + assert "line break" in change.blocked + assert not change.changed + assert plan([Action("env", key="A", value="a\nb")], state("%command%")).blocked + # one already inside a quoted part of the line survives splitting, and is refused too + change = plan([Action("game_arg", value="-x")], state('FOO="a\nb" %command%')) + assert "line break" in change.blocked + # A blocked step stops later steps, so the result is never a half-applied plan. + change = plan([Action("env", key="A", value="b c"), Action("default_proton")], state("%command%", "x")) + assert change.after == state("%command%", "x") + + +# --- disk helpers ------------------------------------------------------------------------ + + +@pytest.fixture +def files(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, Path]: + monkeypatch.setenv("HOME", str(tmp_path / "home")) + localconfig = tmp_path / "localconfig.vdf" + config_vdf = tmp_path / "config.vdf" + write_files(localconfig, config_vdf, state("gamemoderun %command%", "GE-Proton9-20")) + return localconfig, config_vdf + + +def write_files(localconfig: Path, config_vdf: Path, st: GameState, app_id: str = APP) -> None: + apps = { + app_id: {"LaunchOptions": st.launch_options, "LastPlayed": "1"}, + "10": {"LaunchOptions": "-other"}, + } + local = {"UserLocalConfigStore": {"Software": {"Valve": {"Steam": {"apps": apps}}}}} + mapping: dict[str, dict[str, str]] = {"10": {"name": "proton_9", "config": "", "priority": "250"}} + if st.compat_tool: + mapping[app_id] = {"name": st.compat_tool, "config": "", "priority": "250"} + config = {"InstallConfigStore": {"Software": {"Valve": {"Steam": {"CompatToolMapping": mapping}}}}} + localconfig.write_text(vdf.dumps(local, pretty=True), encoding="utf-8") + config_vdf.write_text(vdf.dumps(config, pretty=True), encoding="utf-8") + + +def test_read_state(files: tuple[Path, Path], tmp_path: Path) -> None: + localconfig, config_vdf = files + assert read_state(localconfig, config_vdf, APP) == state("gamemoderun %command%", "GE-Proton9-20") + assert read_state(localconfig, config_vdf, "999") == state() + assert read_state(tmp_path / "missing.vdf", config_vdf, APP) is None + assert read_state(None, config_vdf, APP) is None + broken = tmp_path / "broken.vdf" + broken.write_text('"UserLocalConfigStore"\n{\n "Software"\n', encoding="utf-8") + assert read_state(broken, config_vdf, APP) is None + assert read_state(localconfig, broken, APP) is None + + +# --- apply ---------------------------------------------------------------------------------- + + +def test_apply_writes_the_change_and_records_a_snapshot(files: tuple[Path, Path]) -> None: + localconfig, config_vdf = files + before = read_state(localconfig, config_vdf, APP) + assert before is not None + change = plan([Action("remove_word", value="gamemoderun"), Action("default_proton")], before) + result = apply_change(localconfig, config_vdf, APP, change, label="GameMode is missing", + finding_id="wrapper-missing-gamemoderun") + assert result.ok, result.message + assert result.state == state("", "") + assert read_state(localconfig, config_vdf, APP) == state("", "") + snap = undo_available(APP) + assert snap is not None and snap.id == result.snapshot_id + assert (snap.before, snap.after, snap.finding_id) == (before, change.after, "wrapper-missing-gamemoderun") + # Other games' entries are left alone. + assert read_state(localconfig, config_vdf, "10") == state("-other", "proton_9") + + +def test_apply_writes_only_what_changed(files: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch) -> None: + localconfig, config_vdf = files + + def no_compat_write(*_args: object) -> bool: + raise AssertionError("config.vdf must not be written for a launch-options change") + + monkeypatch.setattr(fix_apply, "set_compat_tool", no_compat_write) + change = plan([Action("env", key="PROTON_LOG", value="1")], read_state(localconfig, config_vdf, APP)) + assert apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="log-off").ok + + +def test_apply_refuses_when_the_settings_moved(files: tuple[Path, Path]) -> None: + localconfig, config_vdf = files + change = plan([Action("env", key="PROTON_LOG", value="1")], read_state(localconfig, config_vdf, APP)) + write_files(localconfig, config_vdf, state("mangohud %command%", "GE-Proton9-20")) + result = apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="log-off") + assert not result.ok + assert result.message == "The settings changed since the check. Run Diagnose again." + assert result.state == state("mangohud %command%", "GE-Proton9-20") + assert read_state(localconfig, config_vdf, APP) == state("mangohud %command%", "GE-Proton9-20") + assert undo_available(APP) is None + + +def test_apply_refuses_blocked_unchanged_and_unreadable(files: tuple[Path, Path], tmp_path: Path) -> None: + localconfig, config_vdf = files + current = read_state(localconfig, config_vdf, APP) + blocked = plan([Action("env", key="A", value="a b")], current) + result = apply_change(localconfig, config_vdf, APP, blocked, label="x", finding_id="y") + assert result.message == blocked.blocked + same = plan([Action("manual", text="Do it.")], current) + assert not apply_change(localconfig, config_vdf, APP, same, label="x", finding_id="y").ok + change = plan([Action("env", key="A", value="1")], current) + result = apply_change(tmp_path / "missing.vdf", config_vdf, APP, change, label="x", finding_id="y") + assert not result.ok and "could not be read" in result.message + assert undo_available(APP) is None + + +def test_snapshot_failure_blocks_the_write(files: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch) -> None: + localconfig, config_vdf = files + original = localconfig.read_bytes(), config_vdf.read_bytes() + + def fail(*_args: object) -> None: + raise OSError("disk full") + + monkeypatch.setattr(snapshots, "record", fail) + both = [Action("env", key="A", value="1"), Action("default_proton")] + change = plan(both, read_state(localconfig, config_vdf, APP)) + result = apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y") + assert not result.ok + assert "undo" in result.message and "nothing was changed" in result.message + assert (localconfig.read_bytes(), config_vdf.read_bytes()) == original + + +def test_second_write_failure_puts_the_first_back( + files: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch, +) -> None: + localconfig, config_vdf = files + before = read_state(localconfig, config_vdf, APP) + monkeypatch.setattr(fix_apply, "set_compat_tool", lambda *_a: False) + change = plan([Action("env", key="A", value="1"), Action("default_proton")], before) + result = apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y") + assert not result.ok + assert "put back" in result.message + assert read_state(localconfig, config_vdf, APP) == before + assert result.snapshot_id == "" and undo_available(APP) is None + + +def test_failed_rollback_says_what_the_options_are( + files: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch, +) -> None: + localconfig, config_vdf = files + real = fix_apply.set_launch_options + calls: list[str] = [] + + def first_only(path: Path, app_id: str, options: str) -> bool: + calls.append(options) + return real(path, app_id, options) if len(calls) == 1 else False + + monkeypatch.setattr(fix_apply, "set_launch_options", first_only) + monkeypatch.setattr(fix_apply, "set_compat_tool", lambda *_a: (_ for _ in ()).throw(OSError("boom"))) + both = [Action("env", key="A", value="1"), Action("default_proton")] + change = plan(both, read_state(localconfig, config_vdf, APP)) + result = apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y") + assert not result.ok + assert '"A=1 gamemoderun %command%"' in result.message and '"gamemoderun %command%"' in result.message + assert undo_available(APP) is None + + +def test_apply_checks_what_landed(files: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch) -> None: + localconfig, config_vdf = files + monkeypatch.setattr(fix_apply, "set_launch_options", lambda *_a: True) # says yes, writes nothing + change = plan([Action("env", key="A", value="1")], read_state(localconfig, config_vdf, APP)) + result = apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y") + assert not result.ok and "do not show it" in result.message + # The undo point stays, so whatever did land can still be put back. + assert result.snapshot_id and undo_available(APP) is not None + + +# --- undo -------------------------------------------------------------------------------------- + + +def test_undo_round_trip_restores_the_exact_text(files: tuple[Path, Path]) -> None: + localconfig, config_vdf = files + original = state('FOO="a b" X=c\\d gamemoderun %command% -novid', "GE-Proton9-20") + write_files(localconfig, config_vdf, original) + change = plan([Action("remove_word", value="gamemoderun"), Action("default_proton")], original) + assert apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y").ok + assert read_state(localconfig, config_vdf, APP) == change.after + + result = undo_latest(localconfig, config_vdf, APP) + assert result.ok, result.message + assert read_state(localconfig, config_vdf, APP) == original + assert result.state == original + assert undo_available(APP) is None + assert not undo_latest(localconfig, config_vdf, APP).ok # nothing left to undo + + +def test_undo_refuses_to_overwrite_later_changes(files: tuple[Path, Path]) -> None: + localconfig, config_vdf = files + before = read_state(localconfig, config_vdf, APP) + change = plan([Action("env", key="PROTON_LOG", value="1")], before) + assert apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="log-off").ok + write_files(localconfig, config_vdf, state("PROTON_LOG=1 mangohud %command%", "GE-Proton9-20")) + + result = undo_latest(localconfig, config_vdf, APP) + assert not result.ok + assert "changed after the fix was applied" in result.message + assert '"PROTON_LOG=1 mangohud %command%"' in result.message + assert '"gamemoderun %command%"' in result.message + later = state("PROTON_LOG=1 mangohud %command%", "GE-Proton9-20") + assert read_state(localconfig, config_vdf, APP) == later + assert undo_available(APP) is not None + + forced = undo_latest(localconfig, config_vdf, APP, force=True) + assert forced.ok + assert read_state(localconfig, config_vdf, APP) == before + assert undo_available(APP) is None + + +def test_undo_when_already_back(files: tuple[Path, Path]) -> None: + localconfig, config_vdf = files + before = read_state(localconfig, config_vdf, APP) + change = plan([Action("env", key="A", value="1")], before) + assert apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y").ok + write_files(localconfig, config_vdf, before) + result = undo_latest(localconfig, config_vdf, APP) + assert result.ok and "already back" in result.message + assert undo_available(APP) is None + + +def test_undo_write_failure_keeps_the_snapshot( + files: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch, +) -> None: + localconfig, config_vdf = files + before = read_state(localconfig, config_vdf, APP) + change = plan([Action("env", key="A", value="1"), Action("default_proton")], before) + assert apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y").ok + monkeypatch.setattr(fix_apply, "set_compat_tool", lambda *_a: False) + result = undo_latest(localconfig, config_vdf, APP) + assert not result.ok + assert "the fix is still in place" in result.message + assert read_state(localconfig, config_vdf, APP) == change.after + assert undo_available(APP) is not None diff --git a/tests/test_launch_check.py b/tests/test_launch_check.py index 092d1f5..bf6f78a 100644 --- a/tests/test_launch_check.py +++ b/tests/test_launch_check.py @@ -7,6 +7,7 @@ import pytest from protonshift.core import proton_log +from protonshift.core.fix_pack import Action from protonshift.core.launch_check import check_launch, check_launch_options, detect_anticheat, summarize @@ -120,6 +121,65 @@ def test_protondb_and_unreadable_options(tmp_path: Path) -> None: assert levels(found) == sorted(levels(found), key=["error", "warn", "info", "ok"].index) +# --- ids and actions ------------------------------------------------------------- + + +def by_id(findings: list[dict]) -> dict[str, dict]: + return {f["id"]: f for f in findings} + + +@pytest.mark.parametrize( + ("options", "exists", "fid", "actions"), + [ + ("", lacks, "launch-empty", ()), + ("-novid", lacks, "launch-ok", ()), + ("gamemoderun %command% %command%", has, "command-twice", (Action("single_command"),)), + ("gamemoderun -novid", has, "command-missing", (Action("add_command"),)), + # no leading wrapper to put %command% after: no button that would do nothing + ("-novid gamemoderun", has, "command-missing", ()), + ("gamemoderun %command%", lacks, "wrapper-missing-gamemoderun", + (Action("remove_word", value="gamemoderun"),)), + ("/usr/bin/prime-run %command%", lacks, "wrapper-missing-prime-run", + (Action("remove_word", value="prime-run"),)), + ("MANGOHUD=1 %command%", lacks, "env-needs-mangohud", (Action("unset_env", key="MANGOHUD"),)), + ], +) +def test_option_findings_have_ids_and_actions(options: str, exists, fid: str, actions: tuple) -> None: + found = by_id(check_launch_options(options, exists)) + assert fid in found + assert found[fid]["actions"] == actions + + +def test_every_finding_has_a_stable_id(tmp_path: Path) -> None: + install = tmp_path / "game" + (install / "EasyAntiCheat").mkdir(parents=True) + prefix = tmp_path / "pfx" + prefix.mkdir() + found = run(tmp_path, compat_tool="GE-Proton9-20", prefix_path=prefix, protondb_tier="bronze", + launch_options="gamemoderun %command% %command%", tool_exists=lacks) + ids = [f["id"] for f in found] + assert all(ids) and len(ids) == len(set(ids)) + assert {"install-ok", "proton-gone", "anticheat-missing-eac", "prefix-ok", "protondb-bronze", + "command-twice", "wrapper-missing-gamemoderun"} <= set(ids) + assert by_id(found)["proton-gone"]["actions"] == (Action("default_proton"),) + again = run(tmp_path, compat_tool="GE-Proton9-20", prefix_path=prefix, protondb_tier="bronze", + launch_options="gamemoderun %command% %command%", tool_exists=lacks) + assert ids == [f["id"] for f in again] + + other = by_id(run(tmp_path, install_path=tmp_path / "gone", compat_tool="GE-Proton10-1", + launch_options_readable=False, protondb_tier="borked", installed_app_ids=["1826330"])) + expected = {"install-missing", "launch-unreadable", "proton-ok", "prefix-none", "protondb-borked"} + assert expected <= set(other) + assert by_id(run(tmp_path))["proton-default"]["actions"] == () + assert "anticheat-ok-eac" in by_id(run(tmp_path, installed_app_ids=["1826330"])) + + +def test_findings_keep_their_old_keys(tmp_path: Path) -> None: + for f in run(tmp_path, compat_tool="GE-Proton9-20"): + assert {"level", "title", "detail", "fix", "id", "actions"} <= set(f) + assert isinstance(f["actions"], tuple) + + # --- Proton log -------------------------------------------------------------------- diff --git a/tests/test_launch_merge.py b/tests/test_launch_merge.py index cf17668..96f6d46 100644 --- a/tests/test_launch_merge.py +++ b/tests/test_launch_merge.py @@ -1,9 +1,19 @@ -"""Tests for merging snippets into a Steam launch-options line.""" +"""Tests for merging snippets into a Steam launch-options line, and the edit helpers.""" from __future__ import annotations import pytest +from protonshift.core.launch_merge import ( + add_command, + add_game_arg, + remove_word, + set_env, + single_command, + split_line, + split_words, + unset_env, +) from protonshift.core.launch_merge import merge_launch_snippet as merge @@ -59,3 +69,174 @@ def test_merge_twice_equals_once() -> None: once = merge("-novid", "gamescope -f --") assert merge(once, "gamescope -f --") == once assert once.count("%command%") == 1 + + +# --- edit helpers ------------------------------------------------------------------ + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ("KEY='a b' %command%", ["KEY='a b'", "%command%"]), + ('FOO="a b" gamemoderun %command%', ['FOO="a b"', "gamemoderun", "%command%"]), + ('A="x \\" y" %command%', ['A="x \\" y"', "%command%"]), + ("A=a\\ b %command%", ["A=a\\ b", "%command%"]), + (" gamemoderun %command% -novid ", ["gamemoderun", "%command%", "-novid"]), + # unbalanced quote: plain whitespace split, nothing lost + ("FOO='a b %command%", ["FOO='a", "b", "%command%"]), + ("", []), + ], +) +def test_split_words(text: str, expected: list[str]) -> None: + assert split_words(text) == expected + + +def test_split_line_reads_a_line_without_command_as_arguments() -> None: + assert split_line("gamemoderun -novid") == ([], ["gamemoderun", "-novid"], 0) + assert split_line("A=1 %command% -x %command% -y") == (["A=1"], ["-x", "-y"], 2) + + +@pytest.mark.parametrize( + ("text", "key", "value", "expected"), + [ + ("", "PROTON_LOG", "1", "PROTON_LOG=1 %command%"), + ("gamemoderun %command%", "PROTON_LOG", "1", "PROTON_LOG=1 gamemoderun %command%"), + # replaced where it stands + ("A=1 PROTON_LOG=0 gamemoderun %command% -novid", "PROTON_LOG", "1", + "A=1 PROTON_LOG=1 gamemoderun %command% -novid"), + # a later duplicate would win in the shell, so it goes + ("X=1 gamemoderun X=2 %command%", "X", "3", "X=3 gamemoderun %command%"), + # a quoted value is one word and is replaced whole + ("DXVK_HUD='fps, gpuload' %command%", "DXVK_HUD", "fps", "DXVK_HUD=fps %command%"), + # no %command%: the words stay game arguments + ("-novid -fullscreen", "A", "1", "A=1 %command% -novid -fullscreen"), + ("gamemoderun", "A", "1", "A=1 %command% gamemoderun"), + # already set: the line comes back exactly as given + ("A=1 %command%", "A", "1", "A=1 %command%"), + # gamescope's options are not touched + ("gamescope -f -- %command%", "A", "1", "A=1 gamescope -f -- %command%"), + ], +) +def test_set_env(text: str, key: str, value: str, expected: str) -> None: + assert set_env(text, key, value) == expected + assert set_env(expected, key, value) == expected + + +def test_set_env_refuses_a_bad_key() -> None: + with pytest.raises(ValueError): + set_env("%command%", "A B", "1") + with pytest.raises(ValueError): + unset_env("%command%", "") + + +@pytest.mark.parametrize( + ("text", "key", "expected"), + [ + ("MANGOHUD=1 %command%", "MANGOHUD", ""), + ("MANGOHUD=1 gamemoderun %command% -novid", "MANGOHUD", "gamemoderun %command% -novid"), + ("A=1 MANGOHUD=1 MANGOHUD=0 %command%", "MANGOHUD", "A=1 %command%"), + ("FOO='a b' MANGOHUD=1 %command%", "MANGOHUD", "FOO='a b' %command%"), + # nothing to remove + ("A=1 %command%", "MANGOHUD", "A=1 %command%"), + # after %command% it is a game argument, never an assignment + ("%command% MANGOHUD=1", "MANGOHUD", "%command% MANGOHUD=1"), + # no %command%: nothing is before the game + ("MANGOHUD=1", "MANGOHUD", "MANGOHUD=1"), + # MY_MANGOHUD is another variable + ("MY_MANGOHUD=1 %command%", "MANGOHUD", "MY_MANGOHUD=1 %command%"), + ], +) +def test_unset_env(text: str, key: str, expected: str) -> None: + assert unset_env(text, key) == expected + assert unset_env(expected, key) == expected + + +@pytest.mark.parametrize( + ("text", "word", "expected"), + [ + ("gamemoderun %command%", "gamemoderun", ""), + ("MANGOHUD=1 gamemoderun mangohud %command% -novid", "gamemoderun", + "MANGOHUD=1 mangohud %command% -novid"), + ("/usr/bin/gamemoderun %command%", "gamemoderun", ""), + # a wrapper goes with its options and its -- + ("gamescope -W 1920 -H 1080 -f -- gamemoderun %command%", "gamescope", "gamemoderun %command%"), + ("SCB_AUTO_RES=1 scb -- %command% -dx11", "scb", "SCB_AUTO_RES=1 %command% -dx11"), + # without -- nobody can tell where its options end, so they all go + ("A=1 gamescope -f -W 1920 gamemoderun B=2 %command%", "gamescope", "A=1 B=2 %command%"), + # option-like words right after a plain command are its own + ("mangohud --dlsym gamemoderun %command%", "mangohud", "gamemoderun %command%"), + ("strangle 60 %command%", "strangle", ""), + # a word inside gamescope's options is not a command + ("gamescope -o gamemoderun -- %command%", "gamemoderun", "gamescope -o gamemoderun -- %command%"), + # but one after its -- is + ("gamescope -f -- gamemoderun %command%", "gamemoderun", "gamescope -f -- %command%"), + # never an assignment, never a game argument + ("gamemoderun=1 %command% gamemoderun", "gamemoderun", "gamemoderun=1 %command% gamemoderun"), + # no %command%: nothing to remove + ("gamemoderun", "gamemoderun", "gamemoderun"), + ("prime-run %command%", "gamemoderun", "prime-run %command%"), + ], +) +def test_remove_word(text: str, word: str, expected: str) -> None: + assert remove_word(text, word) == expected + assert remove_word(expected, word) == expected + + +@pytest.mark.parametrize( + ("text", "arg", "expected"), + [ + ("", "-vulkan", "%command% -vulkan"), + ("gamemoderun %command%", "-vulkan", "gamemoderun %command% -vulkan"), + ("%command% -novid", "-vulkan", "%command% -novid -vulkan"), + ("%command% -vulkan", "-vulkan", "%command% -vulkan"), + # no %command%: the line was game arguments and still is + ("-novid", "-vulkan", "%command% -novid -vulkan"), + ("-vulkan", "-vulkan", "-vulkan"), + # in front of the game is not the game's argument + ("gamescope -vulkan -- %command%", "-vulkan", "gamescope -vulkan -- %command% -vulkan"), + ], +) +def test_add_game_arg(text: str, arg: str, expected: str) -> None: + assert add_game_arg(text, arg) == expected + assert add_game_arg(expected, arg) == expected + + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ("gamemoderun %command% %command%", "gamemoderun %command%"), + ("%command% -a %command% -b", "%command% -a -b"), + ("%command% %command%", ""), + ("gamemoderun %command%", "gamemoderun %command%"), + ("-novid", "-novid"), + ], +) +def test_single_command(text: str, expected: str) -> None: + assert single_command(text) == expected + assert single_command(expected) == expected + + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ("gamemoderun", "gamemoderun %command%"), + ("PROTON_LOG=1", "PROTON_LOG=1 %command%"), + ("PROTON_LOG=1 gamemoderun -novid", "PROTON_LOG=1 gamemoderun %command% -novid"), + ("FOO='a b' mangohud", "FOO='a b' mangohud %command%"), + ("gamescope -f -b -- -novid", "gamescope -f -b -- %command% -novid"), + ("/usr/bin/gamemoderun -novid", "/usr/bin/gamemoderun %command% -novid"), + # nothing at the start that belongs before the game + ("-novid gamemoderun", "-novid gamemoderun"), + # already there + ("gamemoderun %command%", "gamemoderun %command%"), + ("", ""), + ], +) +def test_add_command(text: str, expected: str) -> None: + assert add_command(text) == expected + assert add_command(expected) == expected + + +def test_unbalanced_quote_keeps_every_word() -> None: + text = "FOO='a b gamemoderun %command% -novid" + assert remove_word(text, "gamemoderun") == "FOO='a b %command% -novid" + assert set_env(text, "A", "1") == "A=1 FOO='a b gamemoderun %command% -novid" From b25bf864d5f473b7639df6362ec077616c750192 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 23:16:24 -0600 Subject: [PATCH 11/20] feat(core): the first fix pack - 26 rules, each checked against its source 18 rules read the Proton log, 6 look at launch options, 2 are tweaks for one game. Every log string was confirmed in the upstream commit Proton 11 pins (Wine, DXVK, VKD3D-Proton) or in Proton's own script, and every remedy in the issue or documentation page the rule links to. Six planned rules were dropped while checking. Most of them matched lines that Proton prints through its log() helper, which goes to stderr and never reaches steam-.log, so they could not have fired. One needed a GE-Proton point release the format cannot express, and one matched a line that only appears in the Steam Linux Runtime's own log. tests/test_fix_pack_rules.py holds a real sample line for every log rule and a set of lines from healthy runs that no rule may match. Co-Authored-By: Claude Fable 5.2 --- protonshift/core/data/fix_pack.json | 560 +++++++++++++++++++++++++++- tests/test_fix_pack_rules.py | 370 ++++++++++++++++++ 2 files changed, 928 insertions(+), 2 deletions(-) create mode 100644 tests/test_fix_pack_rules.py diff --git a/protonshift/core/data/fix_pack.json b/protonshift/core/data/fix_pack.json index bd9c270..98d20cc 100644 --- a/protonshift/core/data/fix_pack.json +++ b/protonshift/core/data/fix_pack.json @@ -1,6 +1,562 @@ { "format": "protonshift-fix-pack", "version": 2, - "revision": "2026.11.0", - "rules": [] + "revision": "2026.11.1", + "rules": [ + { + "id": "prefix-not-owned", + "title": "The game's Wine prefix belongs to another user", + "cause": "Wine refuses to use a prefix folder that is not owned by you. This usually happens when the Steam library is on an NTFS or other Windows drive, which Linux mounts so that its files belong to someone else.", + "severity": "blocking", + "match": { + "log": [ + "\\bwine(?:server)?: .+ is not owned by you" + ] + }, + "actions": [ + { + "type": "manual", + "text": "Move this game's Steam library to a drive with a Linux file system such as ext4 or Btrfs. If the drive has to stay as it is, mount it with your user as the owner (the uid and gid mount options)." + } + ], + "source": "https://github.com/ValveSoftware/Proton/issues/4512", + "verified": "2026-11-16" + }, + { + "id": "prefix-wrong-arch", + "title": "The game's Wine prefix was made for a different architecture", + "cause": "This prefix was created as a 32-bit or 64-bit Windows install that does not match the Wine build running the game, so Wine stops before the game starts.", + "severity": "blocking", + "match": { + "log": [ + "is a 32-bit installation, it cannot support 64-bit applications", + "is a 64-bit installation, it cannot be used with a 32-bit wineserver" + ] + }, + "actions": [ + { + "type": "manual", + "text": "Back up any saves kept inside the prefix, then delete this game's prefix (Wine prefix, Delete) and start the game again so Steam builds a new one. Saves stored only in the prefix are lost." + } + ], + "source": "https://github.com/ValveSoftware/wine/blob/e60892cc2398b0a83c332a2078c7b85e47bdb42b/dlls/ntdll/unix/server.c#L1736", + "verified": "2026-11-16" + }, + { + "id": "prefix-registry-corrupt", + "title": "A registry file in the game's Wine prefix is damaged", + "cause": "Wine could not read one of the prefix's registry files (system.reg, user.reg or userdef.reg), so the game starts without its Windows settings and usually fails. A crash or a full disk while the file was being written can cause this.", + "severity": "blocking", + "match": { + "log": [ + "\\.reg is not a valid registry file" + ] + }, + "actions": [ + { + "type": "manual", + "text": "Back up any saves kept inside the prefix, then delete this game's prefix (Wine prefix, Delete) and start the game again so Steam builds a new one. Saves stored only in the prefix are lost." + } + ], + "source": "https://github.com/ValveSoftware/wine/blob/e60892cc2398b0a83c332a2078c7b85e47bdb42b/server/registry.c#L1828", + "verified": "2026-11-16" + }, + { + "id": "prefix-write-failed", + "title": "Wine could not save the game's prefix settings", + "cause": "Wine failed to write a registry file in the game's prefix. The drive that holds the prefix is usually full or mounted read-only.", + "severity": "likely", + "match": { + "log": [ + "wineserver: could not save registry branch to " + ] + }, + "actions": [ + { + "type": "manual", + "text": "Free some space on the drive that holds this game's Steam library, or check that the drive is mounted with write access, then start the game again." + } + ], + "source": "https://github.com/ValveSoftware/wine/blob/e60892cc2398b0a83c332a2078c7b85e47bdb42b/server/registry.c#L2236", + "verified": "2026-11-16" + }, + { + "id": "prefix-broken-kernel32", + "title": "Wine could not load its own core Windows files", + "cause": "Wine could not load kernel32.dll, one of its own core files, so nothing could start. Players have seen this with a damaged game prefix and with a damaged Proton install.", + "severity": "blocking", + "match": { + "log": [ + "wine: could not load kernel32\\.dll, status c0000135" + ] + }, + "actions": [ + { + "type": "manual", + "text": "Back up any saves kept inside the prefix, then delete this game's prefix (Wine prefix, Delete) and start the game again so Steam builds a new one. Saves stored only in the prefix are lost." + }, + { + "type": "manual", + "text": "If that does not help, verify this Proton build's files in Steam (it is listed under Tools in your library), or switch the game to a different build with Proton version." + } + ], + "source": "https://github.com/ValveSoftware/Proton/issues/4269", + "verified": "2026-11-16" + }, + { + "id": "wineserver-stuck", + "title": "A leftover Wine process is blocking the game", + "cause": "Wine found a Wine server still running for this prefix but could not connect to it. It is usually left behind by an earlier game session that did not exit cleanly.", + "severity": "blocking", + "match": { + "log": [ + "a wine server seems to be running, but I cannot connect to it" + ] + }, + "actions": [ + { + "type": "manual", + "text": "Quit Steam completely (Steam menu, Exit) so the leftover process ends, or restart the computer, then start the game again." + } + ], + "source": "https://github.com/ValveSoftware/wine/blob/e60892cc2398b0a83c332a2078c7b85e47bdb42b/dlls/ntdll/unix/server.c#L1396", + "verified": "2026-11-16" + }, + { + "id": "sync-stale-server", + "title": "An old Wine process with different settings is still running", + "cause": "The game and the Wine server still running for this prefix disagree about the fast sync mode (esync or fsync), so Wine stops the game. The server is usually left over from an earlier session or another game.", + "severity": "likely", + "match": { + "log": [ + "err:[ef]sync:[ef]sync_init Failed to open [ef]sync shared memory file", + "err:[ef]sync:[ef]sync_init Server is running with WINE[EF]SYNC but this process is not" + ] + }, + "actions": [ + { + "type": "manual", + "text": "Quit Steam completely (Steam menu, Exit) so the leftover process ends, or restart the computer, then start the game again." + } + ], + "source": "https://github.com/ValveSoftware/wine/blob/e60892cc2398b0a83c332a2078c7b85e47bdb42b/dlls/ntdll/unix/fsync.c#L478", + "verified": "2026-11-16" + }, + { + "id": "open-files-limit", + "title": "The game ran out of open files", + "cause": "The game hit the limit on how many files a program may have open at once. Many games need more than the default limit on some systems, and fail or crash when they reach it.", + "severity": "likely", + "match": { + "log": [ + "err:winediag:NtCreateFile Too many open files, ulimit -n probably needs to be increased" + ] + }, + "actions": [ + { + "type": "manual", + "text": "Raise the hard limit on open files to 524288 or more. Systems with systemd 240 or newer already use this; otherwise set it in /etc/security/limits.conf as the Proton wiki explains, then log out and back in." + } + ], + "source": "https://github.com/ValveSoftware/Proton/wiki/File-Descriptors", + "verified": "2026-11-16" + }, + { + "id": "low-file-limit-warning", + "title": "The limit on open files is lower than Proton needs", + "cause": "Proton warned that the hard limit on open files is below 524288. Games that open many files can then crash or fail to load.", + "severity": "likely", + "match": { + "log": [ + "^WARNING: Low file descriptor limit: [0-9]+" + ] + }, + "actions": [ + { + "type": "manual", + "text": "Raise the hard limit on open files to 524288 or more. Systems with systemd 240 or newer already use this; otherwise set it in /etc/security/limits.conf as the Proton wiki explains, then log out and back in." + } + ], + "source": "https://github.com/ValveSoftware/Proton/wiki/File-Descriptors", + "verified": "2026-11-16" + }, + { + "id": "low-max-map-count", + "title": "The memory map limit is lower than Proton needs", + "cause": "Proton warned that vm.max_map_count is below 1048576. Some large games run out of memory maps at a lower value and crash or never finish loading.", + "severity": "likely", + "match": { + "log": [ + "^WARNING: Low /proc/sys/vm/max_map_count: [0-9]+ will prevent some games from working" + ] + }, + "actions": [ + { + "type": "manual", + "text": "Set vm.max_map_count to 1048576: create a file in /etc/sysctl.d, for example 90-max-map-count.conf, containing the line vm.max_map_count = 1048576, then restart the computer." + } + ], + "source": "https://github.com/ValveSoftware/Proton/issues/8360#issuecomment-2567242733", + "verified": "2026-11-16" + }, + { + "id": "missing-library", + "title": "The game could not start because a Windows library is missing", + "cause": "Wine could not find a DLL the game needs, so the game stopped before it opened. The line shown names the missing file; it may belong to the game itself or to a runtime the game expects.", + "severity": "likely", + "match": { + "log": [ + "err:module:import_dll Library \\S+ \\(which is needed by .+\\) not found" + ], + "log_also": [ + "err:module:[A-Za-z_]+ Importing dlls for .+ failed, status c0000135" + ] + }, + "actions": [ + { + "type": "manual", + "text": "Verify the game's files in Steam (Properties, Installed Files, Verify integrity of game files)." + }, + { + "type": "manual", + "text": "If it still fails, look up the library named in the line shown in this game's ProtonDB reports to see what other players did about it." + } + ], + "source": "https://github.com/ValveSoftware/wine/blob/e60892cc2398b0a83c332a2078c7b85e47bdb42b/dlls/ntdll/loader.c#L1219", + "verified": "2026-11-16" + }, + { + "id": "wrong-kind-of-library", + "title": "A Windows library the game needs is the wrong kind", + "cause": "Wine found a DLL the game needs but could not load it: the file is for the wrong architecture (32-bit instead of 64-bit, or the other way round) or is damaged. A DLL copied into the game folder by hand or by a mod is a common cause.", + "severity": "likely", + "match": { + "log": [ + "err:module:import_dll Loading library \\S+ \\(which is needed by .+\\) failed \\(error c000007b\\)" + ], + "log_also": [ + "err:module:[A-Za-z_]+ Importing dlls for .+ failed, status c[0-9a-f]{7}" + ] + }, + "actions": [ + { + "type": "manual", + "text": "If you copied DLL files into the game folder yourself, for a mod or a fix, move them out. Then verify the game's files in Steam (Properties, Installed Files, Verify integrity of game files)." + } + ], + "source": "https://github.com/ValveSoftware/wine/blob/e60892cc2398b0a83c332a2078c7b85e47bdb42b/dlls/ntdll/loader.c#L1222", + "verified": "2026-11-16" + }, + { + "id": "no-display-driver", + "title": "Wine could not open a window on your desktop", + "cause": "Wine could not load a display driver, so the game cannot open a window. A broken Proton build has caused this before, and so have graphics driver trouble and starting the game without access to your desktop session.", + "severity": "likely", + "match": { + "log": [ + "err:winediag:nodrv_CreateWindow Application tried to create a window, but no driver could be loaded" + ] + }, + "actions": [ + { + "type": "manual", + "text": "Switch the game to a different Proton build (Proton version) and try again. If you start Steam in an unusual way, such as over SSH or from a script, start it from your desktop session instead." + } + ], + "source": "https://github.com/GloriousEggroll/proton-ge-custom/issues/445", + "verified": "2026-11-16" + }, + { + "id": "vulkan-loader-missing", + "title": "The Vulkan loader is missing", + "cause": "Wine could not load libvulkan, the library that connects games to the graphics driver, so games that draw with Vulkan, DXVK or VKD3D-Proton cannot start.", + "severity": "blocking", + "match": { + "log": [ + "err:vulkan:vulkan_init_once Failed to load libvulkan" + ] + }, + "actions": [ + { + "type": "manual", + "text": "Install the Vulkan loader (libvulkan) from your distribution, both the 64-bit and the 32-bit package, then start the game again." + } + ], + "source": "https://github.com/ValveSoftware/wine/blob/e60892cc2398b0a83c332a2078c7b85e47bdb42b/dlls/win32u/vulkan.c#L4105", + "verified": "2026-11-16" + }, + { + "id": "vulkan-no-driver", + "title": "DXVK found no graphics card it can use", + "cause": "DXVK, which turns DirectX into Vulkan, found no graphics card with a working Vulkan driver. The driver is usually missing or too old, or a DXVK device filter hides every card.", + "severity": "blocking", + "match": { + "log": [ + "DXVK: No adapters found\\." + ] + }, + "actions": [ + { + "type": "manual", + "text": "Install or update the Vulkan driver for your graphics card from your distribution, including the 32-bit driver. If you set DXVK_FILTER_DEVICE_NAME for this game, remove it." + } + ], + "source": "https://github.com/doitsujin/dxvk/blob/a6764047e587178283fcde4073ae6e1410af594f/src/dxvk/dxvk_instance.cpp#L348", + "verified": "2026-11-16" + }, + { + "id": "vulkan-loader-no-drivers", + "title": "Vulkan found no graphics driver", + "cause": "The Vulkan loader looked for graphics drivers and found none it could use, so Vulkan cannot start and games that need it fail.", + "severity": "likely", + "match": { + "log": [ + "(?:terminator_CreateInstance|vkCreateInstance): Found no drivers!" + ] + }, + "actions": [ + { + "type": "manual", + "text": "Install or update the Vulkan driver for your graphics card from your distribution, including the 32-bit driver." + } + ], + "source": "https://github.com/KhronosGroup/Vulkan-Loader/blob/18eca82e1dd3e3925ffcd9e76dcb87afad94b0ba/loader/loader.c#L5526", + "verified": "2026-11-16" + }, + { + "id": "dxvk-init-failed", + "title": "DXVK could not start Vulkan for this game", + "cause": "DXVK, which turns DirectX into Vulkan, could not start Vulkan, so the game cannot draw anything. The graphics driver is usually missing, too old or broken.", + "severity": "blocking", + "match": { + "log": [ + "err: Failed to initialize DXVK\\." + ] + }, + "actions": [ + { + "type": "manual", + "text": "Update the graphics driver from your distribution, including its 32-bit part. The Vulkan check in this list says whether Vulkan works on this computer at all." + } + ], + "source": "https://github.com/doitsujin/dxvk/blob/a6764047e587178283fcde4073ae6e1410af594f/src/dxvk/dxvk_instance.cpp#L57", + "verified": "2026-11-16" + }, + { + "id": "d3d12-driver-lacks-feature", + "title": "The graphics driver lacks a feature DirectX 12 games need", + "cause": "VKD3D-Proton, which runs DirectX 12 games on Vulkan, needs a Vulkan feature or version that your graphics driver or Vulkan loader does not offer. The driver is usually too old for DirectX 12 games.", + "severity": "likely", + "match": { + "log": [ + ":err:(?:vkd3d-proton:)?vkd3d_check_extensions: Required (?:instance|device) extension \\S+ is not supported\\.", + ":err:(?:vkd3d-proton:)?vkd3d_instance_init: Vulkan [0-9]+\\.[0-9]+ not supported by loader\\." + ] + }, + "actions": [ + { + "type": "manual", + "text": "Update the graphics driver from your distribution. Some games can also be switched to DirectX 11 in their own settings or launcher." + } + ], + "source": "https://github.com/HansKristian-Work/vkd3d-proton/blob/212991fc2c266bc0d59f4c4ce8f80f7126508d71/libs/vkd3d/device.c#L220", + "verified": "2026-11-16" + }, + { + "id": "mangohud-inside-gamescope", + "title": "MangoHud is used inside gamescope, which does not support it", + "cause": "MangoHud and gamescope are both in the launch options. MangoHud is not supported inside gamescope and can cause swapchain errors or a missing overlay; gamescope's own --mangoapp option shows the overlay on top instead.", + "severity": "likely", + "match": { + "when": { + "launch_has": [ + "mangohud", + "gamescope" + ] + } + }, + "actions": [ + { + "type": "remove_word", + "value": "mangohud" + }, + { + "type": "manual", + "text": "To keep the overlay, open the Gamescope page, add --mangoapp under Advanced, and add the new launch command to this game." + } + ], + "source": "https://wiki.archlinux.org/title/Gamescope#Mangoapp", + "verified": "2026-11-16" + }, + { + "id": "esync-switch-obsolete", + "title": "PROTON_NO_ESYNC does nothing in this Proton version", + "cause": "Proton 11.0 and newer no longer read PROTON_NO_ESYNC, so this setting has no effect and can be removed.", + "severity": "advice", + "match": { + "when": { + "proton_family": [ + "valve" + ], + "proton_major_min": 11, + "env_set": [ + "PROTON_NO_ESYNC" + ] + } + }, + "actions": [ + { + "type": "unset_env", + "key": "PROTON_NO_ESYNC" + } + ], + "source": "https://github.com/ValveSoftware/Proton/blob/1f089f5610a882c8bfcb4b58a3c86ee88bb4b9f1/README.md#L347", + "verified": "2026-11-16" + }, + { + "id": "d9vk-switch-obsolete", + "title": "PROTON_USE_D9VK does nothing in this Proton version", + "cause": "Proton 5.0 and newer no longer read PROTON_USE_D9VK, so this setting has no effect and can be removed.", + "severity": "advice", + "match": { + "when": { + "proton_family": [ + "valve" + ], + "proton_major_min": 5, + "env_set": [ + "PROTON_USE_D9VK" + ] + } + }, + "actions": [ + { + "type": "unset_env", + "key": "PROTON_USE_D9VK" + } + ], + "source": "https://github.com/ValveSoftware/Proton/blob/1f089f5610a882c8bfcb4b58a3c86ee88bb4b9f1/README.md#L346", + "verified": "2026-11-16" + }, + { + "id": "seccomp-switch-obsolete", + "title": "PROTON_USE_SECCOMP does nothing in this Proton version", + "cause": "Proton 5.13 and newer no longer read PROTON_USE_SECCOMP, so this setting has no effect and can be removed.", + "severity": "advice", + "match": { + "when": { + "proton_family": [ + "valve" + ], + "proton_major_min": 6, + "env_set": [ + "PROTON_USE_SECCOMP" + ] + } + }, + "actions": [ + { + "type": "unset_env", + "key": "PROTON_USE_SECCOMP" + } + ], + "source": "https://github.com/ValveSoftware/Proton/blob/1f089f5610a882c8bfcb4b58a3c86ee88bb4b9f1/README.md#L345", + "verified": "2026-11-16" + }, + { + "id": "nvapi-switch-wrong-build", + "title": "PROTON_ENABLE_NVAPI does nothing in this Proton version", + "cause": "Proton 9.0 and newer do not read PROTON_ENABLE_NVAPI. Proton turns NVAPI, used for DLSS and other NVIDIA features, on by itself for most games, and PROTON_DISABLE_NVAPI is the setting that turns it off.", + "severity": "advice", + "match": { + "when": { + "proton_family": [ + "valve" + ], + "proton_major_min": 9, + "env_set": [ + "PROTON_ENABLE_NVAPI" + ] + } + }, + "actions": [ + { + "type": "unset_env", + "key": "PROTON_ENABLE_NVAPI" + } + ], + "source": "https://github.com/ValveSoftware/Proton/blob/1f089f5610a882c8bfcb4b58a3c86ee88bb4b9f1/README.md#L328", + "verified": "2026-11-16" + }, + { + "id": "gamescope-blocks-wayland-game", + "title": "PROTON_ENABLE_WAYLAND has no effect inside gamescope", + "cause": "Gamescope does not accept Wayland windows unless it is started with --expose-wayland, so GE-Proton runs the game through X11 inside gamescope and PROTON_ENABLE_WAYLAND changes nothing.", + "severity": "advice", + "match": { + "when": { + "proton_family": [ + "ge" + ], + "launch_has": [ + "gamescope" + ], + "env_set": [ + "PROTON_ENABLE_WAYLAND" + ] + } + }, + "actions": [ + { + "type": "manual", + "text": "If you want the game to use Wayland, add --expose-wayland to the gamescope options on the Gamescope page (Advanced). Otherwise remove PROTON_ENABLE_WAYLAND from the launch options." + } + ], + "source": "https://wiki.archlinux.org/title/Gamescope#Wayland_support", + "verified": "2026-11-16" + }, + { + "id": "cyberpunk-2077-camera-jumps", + "title": "Camera or mouse jumps in Cyberpunk 2077 while keys are held", + "cause": "Players on recent Proton builds report the camera snapping or the mouse jumping when they move it while holding movement keys. Turning off Wine's raw access to input devices (hidraw) fixed it for them. Controllers that rely on hidraw may lose some features while it is off.", + "severity": "advice", + "match": { + "app_ids": [ + "1091500" + ], + "when": { + "proton_major_min": 10 + } + }, + "actions": [ + { + "type": "env", + "key": "PROTON_DISABLE_HIDRAW", + "value": "1" + } + ], + "source": "https://github.com/ValveSoftware/Proton/issues/4450#issuecomment-6830749508", + "verified": "2026-11-16" + }, + { + "id": "elden-ring-many-threads", + "title": "Elden Ring stops with an anti-cheat error on processors with 24 or more threads", + "cause": "Easy Anti-Cheat in Elden Ring refuses to start when the game sees too many processor threads: players with 24, 28 and 32 threads got Unexpected error (#1). Showing the game 16 threads fixed it for them. Only use this if your processor has 24 threads or more.", + "severity": "advice", + "match": { + "app_ids": [ + "1245620" + ] + }, + "actions": [ + { + "type": "env", + "key": "WINE_CPU_TOPOLOGY", + "value": "16:0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15" + } + ], + "source": "https://github.com/ValveSoftware/Proton/issues/5613#issuecomment-3704892525", + "verified": "2026-11-16" + } + ] } diff --git a/tests/test_fix_pack_rules.py b/tests/test_fix_pack_rules.py new file mode 100644 index 0000000..23973ba --- /dev/null +++ b/tests/test_fix_pack_rules.py @@ -0,0 +1,370 @@ +"""The rules in the bundled fix pack, checked against real log lines. + +``tests/test_fix_pack.py`` checks that the pack is well formed. This file +checks what the rules mean: every log rule matches the lines it was written +for (taken from public reports, or built from the upstream format string with +realistic values) and none of them matches lines that healthy games print. +Settings and per-game rules are checked through ``fix_pack`` only. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from urllib.parse import urlsplit + +import pytest + +from protonshift.core import fix_pack +from protonshift.core.fix_pack import Action, Rule, load_bundled_pack, match_log + +PACK_PATH = Path(fix_pack.__file__).parent / "data" / "fix_pack.json" +PACK = load_bundled_pack() +RULES: dict[str, Rule] = {r.id: r for r in PACK.rules} + +PFX = "/home/user/.local/share/Steam/steamapps/compatdata/1245620/pfx" +EXE = 'L"C:\\\\Program Files\\\\Game\\\\Game.exe"' + +# --------------------------------------------------------------------------- # +# lines each rule must match +# --------------------------------------------------------------------------- # + +# (rule id, line). The line must be the evidence match_log returns. +MATCHES: list[tuple[str, str]] = [ + # https://github.com/ValveSoftware/Proton/issues/4512 (older Wine, no quotes) + ("prefix-not-owned", + "wine: /mount/WindowsDrives/512/SteamLibrary/steamapps/compatdata/397540/pfx is not owned by you"), + # wine dlls/ntdll/unix/server.c fatal_error("'%s' is not owned by you\n") + ("prefix-not-owned", f"wine: '{PFX}' is not owned by you"), + # wine server/request.c fatal_error("%s is not owned by you\n") + ("prefix-not-owned", f"wineserver: {PFX} is not owned by you"), + ("prefix-wrong-arch", + f"wine: '{PFX}' is a 32-bit installation, it cannot support 64-bit applications."), + ("prefix-wrong-arch", + f"wine: '{PFX}' is a 64-bit installation, it cannot be used with a 32-bit wineserver."), + # wine server/registry.c prints the file name relative to the prefix + ("prefix-registry-corrupt", "system.reg is not a valid registry file"), + ("prefix-registry-corrupt", "user.reg is not a valid registry file"), + # fprintf("wineserver: could not save registry branch to %s") + perror(" ") + ("prefix-write-failed", "wineserver: could not save registry branch to user.reg : No space left on device"), + # https://github.com/ValveSoftware/Proton/issues/4269 + ("prefix-broken-kernel32", "wine: could not load kernel32.dll, status c0000135"), + ("wineserver-stuck", "wine: a wine server seems to be running, but I cannot connect to it."), + ("sync-stale-server", + ("0024:err:esync:esync_init Failed to open esync shared memory file; make sure no stale wineserver " + "instances are running without WINEESYNC.")), + ("sync-stale-server", + ("1234.567:0024:0028:err:fsync:fsync_init Failed to open fsync shared memory file; make sure no stale " + "wineserver instances are running without WINEFSYNC.")), + ("sync-stale-server", + ("0024:err:esync:esync_init Server is running with WINEESYNC but this process is not, please enable " + "WINEESYNC or restart wineserver.")), + ("sync-stale-server", + ("0024:err:fsync:fsync_init Server is running with WINEFSYNC but this process is not, please enable " + "WINEFSYNC or restart wineserver.")), + ("open-files-limit", + "0130:err:winediag:NtCreateFile Too many open files, ulimit -n probably needs to be increased"), + # Proton script, log header + ("low-file-limit-warning", + "WARNING: Low file descriptor limit: 4096 (see https://github.com/ValveSoftware/Proton/wiki/File-Descriptors)"), + # https://github.com/ValveSoftware/Proton/issues/8360#issuecomment-2567242733 + ("low-max-map-count", "WARNING: Low /proc/sys/vm/max_map_count: 65530 will prevent some games from working"), + ("missing-library", + f"0130:err:module:import_dll Library MSVCP140.dll (which is needed by {EXE}) not found"), + ("wrong-kind-of-library", + f"0130:err:module:import_dll Loading library d3d9.dll (which is needed by {EXE}) failed (error c000007b)."), + # https://github.com/GloriousEggroll/proton-ge-custom/issues/445 (log in a comment) + ("no-display-driver", + "0558:err:winediag:nodrv_CreateWindow Application tried to create a window, but no driver could be loaded."), + ("vulkan-loader-missing", "0024:err:vulkan:vulkan_init_once Failed to load libvulkan.so.1"), + # DXVK 3.x logs this as a warning, the first line of a multi-line message + ("vulkan-no-driver", "warn: DXVK: No adapters found. Please check your device filter settings"), + ("vulkan-loader-no-drivers", + "[Vulkan Loader] ERROR | DRIVER: terminator_CreateInstance: Found no drivers!"), + ("vulkan-loader-no-drivers", "ERROR: [Loader Message] Code 0 : vkCreateInstance: Found no drivers!"), + # https://github.com/GloriousEggroll/proton-ge-custom/issues/445 (log in a comment) + ("dxvk-init-failed", "err: Failed to initialize DXVK."), + ("d3d12-driver-lacks-feature", + ('16063.015:0150:0154:err:vkd3d-proton:vkd3d_check_extensions: Required device extension ' + '"VK_KHR_dynamic_rendering" is not supported.')), + ("d3d12-driver-lacks-feature", + "16063.015:0150:0154:err:vkd3d-proton:vkd3d_instance_init: Vulkan 1.3 not supported by loader."), + # vkd3d-proton's own format when it does not write through Wine + ("d3d12-driver-lacks-feature", + '0154:err:vkd3d_check_extensions: Required instance extension "VK_KHR_surface" is not supported.'), +] + +# Lines that must also be in the log for a rule with ``log_also``. +CONTEXT: dict[str, list[str]] = { + "missing-library": [f"0130:err:module:loader_init Importing dlls for {EXE} failed, status c0000135"], + "wrong-kind-of-library": [f"0130:err:module:loader_init Importing dlls for {EXE} failed, status c0000135"], +} + + +@pytest.mark.parametrize(("rule_id", "line"), MATCHES) +def test_rule_matches_its_line(rule_id: str, line: str) -> None: + rule = RULES[rule_id] + lines = ["======================", "fsync: up and running.", line, *CONTEXT.get(rule_id, [])] + assert match_log(rule, lines) == line.strip() + + +@pytest.mark.parametrize("rule_id", sorted(CONTEXT)) +def test_log_also_rules_need_the_confirming_line(rule_id: str) -> None: + line = next(text for rid, text in MATCHES if rid == rule_id) + assert match_log(RULES[rule_id], [line]) is None + + +def test_confirming_line_may_come_first() -> None: + line = next(text for rid, text in MATCHES if rid == "missing-library") + assert match_log(RULES["missing-library"], [*CONTEXT["missing-library"], line]) == line + + +def test_missing_library_uses_older_loader_function_names() -> None: + line = next(text for rid, text in MATCHES if rid == "missing-library") + older = f"0009:err:module:LdrInitializeThunk Importing dlls for {EXE} failed, status c0000135" + assert match_log(RULES["missing-library"], [line, older]) == line + + +# --------------------------------------------------------------------------- # +# lines no rule may match +# --------------------------------------------------------------------------- # + +HEALTHY: list[str] = [ + "======================", + "Proton: 1789520217 GE-Proton11-7", + "Proton: Upgrading prefix from 10.0-100 to 11.0-100 (/home/user/.local/share/Steam/steamapps/compatdata/570/)", + "System WINEDEBUG: 0", + "Effective WINEDEBUG: 0", + "fsync: up and running.", + "esync: up and running.", + "ntsync: up and running.", + # A helper process can miss a library while the game runs fine. + f"0130:err:module:import_dll Library MSVCP140.dll (which is needed by {EXE}) not found", + f"0130:err:module:import_dll Loading library d3d9.dll (which is needed by {EXE}) failed (error c000007b).", + "info: Game: Game.exe", + "info: DXVK: v3.1-19-g601930949d111ed0", + "info: Vulkan: Found vkGetInstanceProcAddr in winevulkan.dll @ 0x6ffffc768a80", + "info: Found device: AMD Radeon 780M (RADV PHOENIX)", + "info: Skipping: Device does not support required feature 'shaderInt64'", + "info: Skipping: Software driver", + "warn: OpenXR: Unable to get required Vulkan instance extensions size", + "0024:fixme:winediag:loader_init wine-staging 11.0 is a testing version containing experimental patches.", + "0024:fixme:winediag:loader_init Please mention your exact version when filing bug reports on winehq.org.", + "0130:fixme:ntdll:NtQuerySystemInformation info_class SYSTEM_PERFORMANCE_INFORMATION", + "0130:fixme:file:NtLockFile I/O completion on lock not implemented yet", + "0154:err:openxr:get_vulkan_extensions Error getting openxr_vulkan_instance_extensions, status 0x2.", + "015c:err:service:device_notify_proc failed to get event, error 1726", + ('00a4:err:ntoskrnl:ZwLoadDriver failed to create driver L"\\\\Registry\\\\Machine\\\\System\\\\' + 'CurrentControlSet\\\\Services\\\\winebth": c0000142'), + "16063.156:0150:0154:warn:vkd3d-proton:vkd3d_create_device: Invalid feature level 0x1000.", + "16063.147:0150:0154:info:vkd3d-proton:vkd3d_instance_init: vkd3d-proton - build: af89350cc2eacd9+.", + "16063.015:0150:0154:warn:vkd3d-proton:openvr_instance_extensions: Failed to wait for VR registry key ready.", + "16062.599:0150:0154:info:nvapi64:<-NvAPI_Initialize: OK", + "gamemodeauto: dlopen failed - libgamemode.so: cannot open shared object file: No such file or directory", + "[2026-09-19 23:33:58.843] [MANGOHUD] [error] [cpu.cpp:794] Failed to initialize CPU power data", + "pid 336968 != 336956, skipping destruction (fork without exec?)", +] + +# A line close to a rule's own that means something else. +NEAR_MISSES: list[tuple[str, str]] = [ + ("dxvk-init-failed", "err: Failed to initialize DXVK device."), + # Proton 11's fsync: the kernel lacks futex_waitv, not a stale server + ("sync-stale-server", + "0024:err:fsync:fsync_init Server is running with WINEFSYNC but this process can't use __NR_futex_waitv."), + ("d3d12-driver-lacks-feature", + ('16063.015:0150:0154:warn:vkd3d-proton:vkd3d_check_extensions: Optional user device extension ' + '"VK_EXT_foo" is not supported.')), + ("missing-library", + f"0130:err:module:import_dll Loading library d3d9.dll (which is needed by {EXE}) failed (error c000007b)."), + ("prefix-not-owned", "Proton: the folder is not owned by you"), + ("vulkan-no-driver", "info: Found device: llvmpipe (LLVM 19.1.7, 256 bits)"), +] + + +def test_no_rule_matches_a_healthy_log() -> None: + hits = [(r.id, match_log(r, HEALTHY)) for r in PACK.rules if r.log] + assert [h for h in hits if h[1] is not None] == [] + + +@pytest.mark.parametrize("line", HEALTHY) +def test_no_rule_matches_a_healthy_line(line: str) -> None: + assert [r.id for r in PACK.rules if match_log(r, [line])] == [] + + +@pytest.mark.parametrize(("rule_id", "line"), NEAR_MISSES) +def test_rule_skips_a_near_miss(rule_id: str, line: str) -> None: + lines = [line, *CONTEXT.get(rule_id, [])] + assert match_log(RULES[rule_id], lines) is None + + +def test_log_rules_ignore_the_settings_alone() -> None: + # A log rule never matches without a log. + for r in PACK.rules: + if r.log: + assert match_log(r, []) is None, r.id + + +# --------------------------------------------------------------------------- # +# settings and per-game rules (no log) +# --------------------------------------------------------------------------- # + +def unset(key: str) -> Action: + return Action("unset_env", key=key) + + +# rule id -> (app_ids, when fields that must be set, actions without manual text) +SETTINGS: dict[str, tuple[tuple[str, ...], dict[str, object], tuple[Action, ...]]] = { + "mangohud-inside-gamescope": ( + (), {"launch_has": ("mangohud", "gamescope")}, + (Action("remove_word", value="mangohud"),), + ), + "esync-switch-obsolete": ( + (), {"env_set": ("PROTON_NO_ESYNC",), "proton_family": ("valve",), "proton_major_min": 11}, + (unset("PROTON_NO_ESYNC"),), + ), + "d9vk-switch-obsolete": ( + (), {"env_set": ("PROTON_USE_D9VK",), "proton_family": ("valve",), "proton_major_min": 5}, + (unset("PROTON_USE_D9VK"),), + ), + "seccomp-switch-obsolete": ( + (), {"env_set": ("PROTON_USE_SECCOMP",), "proton_family": ("valve",), "proton_major_min": 6}, + (unset("PROTON_USE_SECCOMP"),), + ), + "nvapi-switch-wrong-build": ( + (), {"env_set": ("PROTON_ENABLE_NVAPI",), "proton_family": ("valve",), "proton_major_min": 9}, + (unset("PROTON_ENABLE_NVAPI"),), + ), + "gamescope-blocks-wayland-game": ( + (), {"env_set": ("PROTON_ENABLE_WAYLAND",), "launch_has": ("gamescope",), "proton_family": ("ge",)}, + (), + ), + "cyberpunk-2077-camera-jumps": ( + ("1091500",), {"proton_major_min": 10}, + (Action("env", key="PROTON_DISABLE_HIDRAW", value="1"),), + ), + "elden-ring-many-threads": ( + ("1245620",), {}, + (Action("env", key="WINE_CPU_TOPOLOGY", value="16:0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15"),), + ), +} + + +@pytest.mark.parametrize("rule_id", sorted(SETTINGS)) +def test_settings_rule_shape(rule_id: str) -> None: + app_ids, when, changes = SETTINGS[rule_id] + rule = RULES[rule_id] + assert rule.log == () and rule.log_also == () + assert rule.app_ids == app_ids + for name, value in when.items(): + assert getattr(rule.when, name) == value, name + unset_fields = {"gpu_vendor", "session", "proton_family", "proton_major_min", "proton_major_max", + "launch_has", "env_set", "env_unset"} - set(when) + for name in unset_fields: + assert getattr(rule.when, name) in ((), None), name + assert tuple(a for a in rule.actions if a.type != "manual") == changes + + +@pytest.mark.parametrize("rule_id", sorted(SETTINGS)) +def test_settings_rules_are_advice_unless_they_change_a_broken_setup(rule_id: str) -> None: + rule = RULES[rule_id] + expected = "likely" if rule_id == "mangohud-inside-gamescope" else "advice" + assert rule.severity == expected + + +def test_settings_rule_actions_parse_again() -> None: + # The actions survive a round trip through the loader. + raw = json.loads(PACK_PATH.read_text(encoding="utf-8")) + for item in raw["rules"]: + if item["id"] in SETTINGS: + assert fix_pack.parse_rule(item) == RULES[item["id"]] + + +def test_mangohud_rule_tells_how_to_keep_the_overlay() -> None: + texts = [a.text for a in RULES["mangohud-inside-gamescope"].actions if a.type == "manual"] + assert len(texts) == 1 and "--mangoapp" in texts[0] + + +def test_wayland_rule_names_both_choices() -> None: + (action,) = RULES["gamescope-blocks-wayland-game"].actions + assert action.type == "manual" + assert "--expose-wayland" in action.text and "PROTON_ENABLE_WAYLAND" in action.text + + +def test_elden_ring_rule_names_the_thread_count() -> None: + rule = RULES["elden-ring-many-threads"] + assert "24" in rule.title and "24" in rule.cause + + +# --------------------------------------------------------------------------- # +# the pack as a whole +# --------------------------------------------------------------------------- # + +ALLOWED_HOSTS = { + "github.com", "wiki.archlinux.org", "docs.bazzite.gg", "gitlab.steamos.cloud", "gitlab.winehq.org", +} + + +def test_pack_loads_every_rule() -> None: + assert PACK.rejected == [] + assert PACK.revision == "2026.11.1" + assert len(RULES) == len(PACK.rules) + + +@pytest.mark.parametrize("rule", PACK.rules, ids=lambda r: r.id) +def test_source_host_is_allowed(rule: Rule) -> None: + assert urlsplit(rule.source).hostname in ALLOWED_HOSTS + + +@pytest.mark.parametrize("rule", PACK.rules, ids=lambda r: r.id) +def test_source_code_links_are_pinned(rule: Rule) -> None: + parts = urlsplit(rule.source) + if "/blob/" in parts.path: + ref = parts.path.split("/blob/", 1)[1].split("/", 1)[0] + assert re.fullmatch(r"[0-9a-f]{40}", ref), f"{rule.id}: {ref} is not a commit" + assert re.fullmatch(r"L[0-9]+", parts.fragment), f"{rule.id}: no line anchor" + + +def test_every_rule_has_a_test() -> None: + covered = {rid for rid, _ in MATCHES} | set(SETTINGS) + assert sorted(set(RULES) - covered) == [] + assert sorted(covered - set(RULES)) == [] + + +def test_every_log_rule_has_a_matching_sample() -> None: + sampled = {rid for rid, _ in MATCHES} + assert sorted(r.id for r in PACK.rules if r.log and r.id not in sampled) == [] + assert sorted(r.id for r in PACK.rules if not r.log and r.id not in SETTINGS) == [] + + +def _texts(rule: Rule) -> list[str]: + return [rule.title, rule.cause, *(a.text for a in rule.actions if a.type == "manual")] + + +@pytest.mark.parametrize("rule", PACK.rules, ids=lambda r: r.id) +def test_text_is_plain(rule: Rule) -> None: + for text in _texts(rule): + assert "\u2014" not in text and "\u2013" not in text, text + assert "!" not in text, text + assert not re.search(r"\bsimply\b", text, re.IGNORECASE), text + assert text == text.strip() and " " not in text, text + + +def test_file_has_no_dashes_and_is_indented_by_two() -> None: + text = PACK_PATH.read_text(encoding="utf-8") + assert "\u2014" not in text and "\u2013" not in text + data = json.loads(text) + assert text == json.dumps(data, indent=2, ensure_ascii=False) + "\n" + + +def test_keys_are_in_contract_order() -> None: + data = json.loads(PACK_PATH.read_text(encoding="utf-8")) + assert list(data) == ["format", "version", "revision", "rules"] + match_order = ["app_ids", "log", "log_also", "when"] + for item in data["rules"]: + assert list(item) == list(fix_pack._RULE_KEYS), item["id"] + keys = list(item["match"]) + assert keys == [k for k in match_order if k in keys], item["id"] + for action in item["actions"]: + assert next(iter(action)) == "type", item["id"] + assert item["verified"] == "2026-11-16", item["id"] From fe7f49c9bc9229175d94539bf1e9fb25b98601ca Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 23:16:35 -0600 Subject: [PATCH 12/20] docs: fix pack - log_none, so one failure gives one finding Co-Authored-By: Claude Fable 5.2 --- docs/fix-pack.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/fix-pack.md b/docs/fix-pack.md index aaa69ee..258358e 100644 --- a/docs/fix-pack.md +++ b/docs/fix-pack.md @@ -89,7 +89,7 @@ object is rejected whole. ## Matching -`match` holds up to four parts. Every part that is present must hold. +`match` holds up to five parts. Every part that is present must hold. At least one of `app_ids` and `log`, or a `when` that uses `launch_has` or `env_set`, must be present: a rule that matches every game on every machine is not a rule. @@ -124,6 +124,12 @@ is not a rule. the missing-library rule also requires the line that says the game's own start failed. The line quoted to the user as evidence is the one `log` matched. +- `log_none`: a list of regular expressions under the same limits. None of + them may be found anywhere in the log tail. It is only allowed together + with `log`. Use it when a more exact rule covers the same failure, so the + user gets one finding and not two: DXVK prints "Failed to initialize DXVK" + after "No adapters found", and the rule for the first leaves the case to + the rule for the second. - `when`: conditions on the machine and the game's settings. All listed conditions must hold. From 43fe59eac0e7158307f1298fe44c415e8897d4e8 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 23:18:32 -0600 Subject: [PATCH 13/20] feat(core): fix pack log_none, and two warnings stop overclaiming A rule can now stand down when a line shows that a more exact rule covers the same failure. DXVK prints "Failed to initialize DXVK" after "No adapters found", so a missing driver gave two findings; it gives one. Proton prints its low open-files and low max_map_count warnings on every run where the value is low, also for games that work. They are advice now, not "probably the cause". Co-Authored-By: Claude Fable 5.2 --- protonshift/core/data/fix_pack.json | 13 ++-- protonshift/core/fix_pack.py | 22 +++++-- tests/test_fix_pack.py | 94 ++++++++++++++++++++++++++++- tests/test_fix_pack_rules.py | 28 ++++++++- 4 files changed, 143 insertions(+), 14 deletions(-) diff --git a/protonshift/core/data/fix_pack.json b/protonshift/core/data/fix_pack.json index 98d20cc..15d2cc1 100644 --- a/protonshift/core/data/fix_pack.json +++ b/protonshift/core/data/fix_pack.json @@ -1,7 +1,7 @@ { "format": "protonshift-fix-pack", "version": 2, - "revision": "2026.11.1", + "revision": "2026.11.2", "rules": [ { "id": "prefix-not-owned", @@ -164,8 +164,8 @@ { "id": "low-file-limit-warning", "title": "The limit on open files is lower than Proton needs", - "cause": "Proton warned that the hard limit on open files is below 524288. Games that open many files can then crash or fail to load.", - "severity": "likely", + "cause": "Proton warned that the hard limit on open files is below 524288. Games that open many files can then crash or fail to load; if this game does, raising the limit is worth trying.", + "severity": "advice", "match": { "log": [ "^WARNING: Low file descriptor limit: [0-9]+" @@ -183,8 +183,8 @@ { "id": "low-max-map-count", "title": "The memory map limit is lower than Proton needs", - "cause": "Proton warned that vm.max_map_count is below 1048576. Some large games run out of memory maps at a lower value and crash or never finish loading.", - "severity": "likely", + "cause": "Proton warned that vm.max_map_count is below 1048576. Some large games run out of memory maps at a lower value; if this game crashes or never finishes loading, raising it is worth trying.", + "severity": "advice", "match": { "log": [ "^WARNING: Low /proc/sys/vm/max_map_count: [0-9]+ will prevent some games from working" @@ -331,6 +331,9 @@ "match": { "log": [ "err: Failed to initialize DXVK\\." + ], + "log_none": [ + "DXVK: No adapters found\\." ] }, "actions": [ diff --git a/protonshift/core/fix_pack.py b/protonshift/core/fix_pack.py index b16f7a4..b3757fa 100644 --- a/protonshift/core/fix_pack.py +++ b/protonshift/core/fix_pack.py @@ -72,7 +72,7 @@ _PACK_KEYS = frozenset({"format", "version", "revision", "rules"}) _RULE_KEYS = ("id", "title", "cause", "severity", "match", "actions", "source", "verified") -_MATCH_KEYS = frozenset({"app_ids", "log", "log_also", "when"}) +_MATCH_KEYS = frozenset({"app_ids", "log", "log_also", "log_none", "when"}) _WHEN_CHOICES = { "gpu_vendor": ("nvidia", "amd", "intel"), "session": ("wayland", "x11"), @@ -124,6 +124,7 @@ class Rule: app_ids: tuple[str, ...] log: tuple[re.Pattern[str], ...] log_also: tuple[re.Pattern[str], ...] + log_none: tuple[re.Pattern[str], ...] when: When actions: tuple[Action, ...] source: str @@ -368,9 +369,11 @@ def match_log(rule: Rule, lines: Iterable[str]) -> str | None: """The first line a ``log`` expression is found in, stripped, or None. With ``log_also``, that line counts only if every ``log_also`` expression - is also found in some line (the same line included). One pass, so a - one-shot iterable over a long log tail is fine; it stops as soon as the - answer is known. + is also found in some line (the same line included). With ``log_none``, + any line holding a ``log_none`` expression, before or after the evidence, + means no match. One pass, so a one-shot iterable over a long log tail is + fine; it stops as soon as the answer is known, which with ``log_none`` is + only at the end or on an excluding line. """ if not rule.log: return None @@ -378,13 +381,15 @@ def match_log(rule: Rule, lines: Iterable[str]) -> str | None: missing = list(rule.log_also) for line in lines: text = line.rstrip("\r\n")[:_MAX_LINE] + if rule.log_none and any(pattern.search(text) for pattern in rule.log_none): + return None if evidence is None and any(pattern.search(text) for pattern in rule.log): evidence = text.strip() if missing: missing = [pattern for pattern in missing if not pattern.search(text)] - if evidence is not None and not missing: + if evidence is not None and not missing and not rule.log_none: return evidence - return None + return evidence if not missing else None # --------------------------------------------------------------------------- # @@ -521,6 +526,9 @@ def parse_rule(raw: object) -> Rule: if "log_also" in match and "log" not in match: raise PackError("match.log_also: only allowed together with log") log_also = _compile_log_list(match["log_also"], "match.log_also") if "log_also" in match else () + if "log_none" in match and "log" not in match: + raise PackError("match.log_none: only allowed together with log") + log_none = _compile_log_list(match["log_none"], "match.log_none") if "log_none" in match else () when = _parse_when(match["when"]) if "when" in match else When() if not (app_ids or log or when.launch_has or when.env_set): raise PackError("match: needs app_ids, log, or a when with launch_has or env_set") @@ -535,6 +543,7 @@ def parse_rule(raw: object) -> Rule: app_ids=app_ids, log=log, log_also=log_also, + log_none=log_none, when=when, actions=_parse_actions(raw["actions"]), source=_source(raw["source"]), @@ -686,6 +695,7 @@ def user_rules(app_id: str) -> list[Rule]: app_ids=(app_id,), log=(), log_also=(), + log_none=(), when=When(), actions=(action,), source="", diff --git a/tests/test_fix_pack.py b/tests/test_fix_pack.py index 1280bff..29f46d8 100644 --- a/tests/test_fix_pack.py +++ b/tests/test_fix_pack.py @@ -774,6 +774,98 @@ def lines() -> Any: assert seen == ["a", "wine: could not load kernel32.dll"] +# --------------------------------------------------------------------------- # +# log_none +# --------------------------------------------------------------------------- # + +NONE_LINE = r"DXVK: No adapters found\." +HIT = "wine: could not load kernel32.dll" +EXCLUDED = "warn: DXVK: No adapters found." + + +def test_log_none_needs_log() -> None: + rejects(rule(match={"app_ids": ["570"], "log_none": [NONE_LINE]}, severity="advice"), "together with log") + + +def test_log_none_parses() -> None: + r = parse_rule(with_match(log=[LOG_LINE], log_none=[NONE_LINE])) + assert [p.pattern for p in r.log_none] == [NONE_LINE] + assert parse_rule(rule()).log_none == () + + +@pytest.mark.parametrize( + "bad,fragment", + [ + ([], "non-empty list"), + (NONE_LINE, "non-empty list"), + ([7], "must be a string"), + (["DXVK"], "8 literal characters"), + (["(a+)+kernel32dll"], "repeats a group"), + (["aaaaaaaa.*b.*c.*d"], "open-ended repeats"), + (["kernel32("], "does not compile"), + (["kernel32" + "x" * 293], "longer than 300"), + (["(?i)kernel32dll"], "flags"), + ], +) +def test_log_none_limits(bad: Any, fragment: str) -> None: + msg = rejects(with_match(log=[LOG_LINE], log_none=bad), fragment) + assert msg.startswith("match.log_none") + + +@pytest.mark.parametrize( + "lines", + [ + [EXCLUDED, HIT], + [HIT, "noise", EXCLUDED], + [HIT + " / " + EXCLUDED], + ], + ids=["before", "after", "same-line"], +) +def test_log_none_excludes(lines: list[str]) -> None: + r = parse_rule(with_match(log=[LOG_LINE], log_none=[NONE_LINE])) + assert match_log(r, iter(lines)) is None + + +def test_log_none_absent_keeps_the_match() -> None: + r = parse_rule(with_match(log=[LOG_LINE], log_none=[NONE_LINE])) + assert match_log(r, iter(["noise", HIT, "more noise"])) == HIT + assert match_log(r, iter(["noise"])) is None + + +def test_log_none_any_of_several() -> None: + r = parse_rule(with_match(log=[LOG_LINE], log_none=[NONE_LINE, r"Game start failed"])) + assert match_log(r, [HIT, "Game start failed"]) is None + + +def test_log_none_stops_on_the_excluding_line() -> None: + r = parse_rule(with_match(log=[LOG_LINE], log_none=[NONE_LINE])) + seen: list[str] = [] + + def lines() -> Any: + for line in [HIT, EXCLUDED, "after"]: + seen.append(line) + yield line + + assert match_log(r, lines()) is None + assert seen == [HIT, EXCLUDED] + + +@pytest.mark.parametrize( + "lines,expected", + [ + (["Game start failed", HIT], HIT), + ([HIT, "Game start failed"], HIT), + ([HIT], None), # log_also missing + (["Game start failed", HIT, EXCLUDED], None), # excluded after both + ([EXCLUDED, "Game start failed", HIT], None), # excluded before both + ([HIT, EXCLUDED, "Game start failed"], None), # excluded in between + ], +) +def test_log_none_with_log_also(lines: list[str], expected: str | None) -> None: + r = parse_rule(with_match(log=[LOG_LINE], log_also=[r"Game start failed"], log_none=[NONE_LINE])) + assert match_log(r, iter(lines)) == expected + + # --------------------------------------------------------------------------- # # packs # --------------------------------------------------------------------------- # @@ -1004,7 +1096,7 @@ def test_user_rules_env_and_launch_arg(user_dir: Path) -> None: assert first.app_ids == ("570",) assert first.title == "HUD" and first.cause == "Shows fps" assert first.source == "" and first.verified == "" - assert first.log == () and first.log_also == () + assert first.log == () and first.log_also == () and first.log_none == () assert first.actions == (Action("env", key="DXVK_HUD", value="fps"),) assert second.actions == (Action("user_snippet", value="-vulkan"),) diff --git a/tests/test_fix_pack_rules.py b/tests/test_fix_pack_rules.py index 23973ba..6975f34 100644 --- a/tests/test_fix_pack_rules.py +++ b/tests/test_fix_pack_rules.py @@ -120,6 +120,30 @@ def test_confirming_line_may_come_first() -> None: assert match_log(RULES["missing-library"], [*CONTEXT["missing-library"], line]) == line +def test_missing_vulkan_driver_gives_one_finding() -> None: + # DXVK prints "No adapters found" and then "Failed to initialize DXVK"; + # the exact rule wins and the general one stands aside. + no_adapters = next(text for rid, text in MATCHES if rid == "vulkan-no-driver") + init_failed = next(text for rid, text in MATCHES if rid == "dxvk-init-failed") + log = ["======================", no_adapters, "err: DXVK: Failed to create instance", init_failed] + hits = [r.id for r in PACK.rules if r.log and match_log(r, log) is not None] + assert "vulkan-no-driver" in hits + assert "dxvk-init-failed" not in hits + + +def test_dxvk_init_failed_alone_still_matches() -> None: + line = "err: Failed to initialize DXVK." + assert match_log(RULES["dxvk-init-failed"], ["fsync: up and running.", line]) == line + + +@pytest.mark.parametrize("rule_id", ["low-file-limit-warning", "low-max-map-count"]) +def test_proton_startup_warnings_are_advice(rule_id: str) -> None: + # Proton prints these on every run when the value is low, games that work included. + rule = RULES[rule_id] + assert rule.severity == "advice" + assert "worth trying" in rule.cause + + def test_missing_library_uses_older_loader_function_names() -> None: line = next(text for rid, text in MATCHES if rid == "missing-library") older = f"0009:err:module:LdrInitializeThunk Importing dlls for {EXE} failed, status c0000135" @@ -307,7 +331,7 @@ def test_elden_ring_rule_names_the_thread_count() -> None: def test_pack_loads_every_rule() -> None: assert PACK.rejected == [] - assert PACK.revision == "2026.11.1" + assert PACK.revision == "2026.11.2" assert len(RULES) == len(PACK.rules) @@ -360,7 +384,7 @@ def test_file_has_no_dashes_and_is_indented_by_two() -> None: def test_keys_are_in_contract_order() -> None: data = json.loads(PACK_PATH.read_text(encoding="utf-8")) assert list(data) == ["format", "version", "revision", "rules"] - match_order = ["app_ids", "log", "log_also", "when"] + match_order = ["app_ids", "log", "log_also", "log_none", "when"] for item in data["rules"]: assert list(item) == list(fix_pack._RULE_KEYS), item["id"] keys = list(item["match"]) From 24af389b88404ed826718f66d4f8163ae400733a Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 23:32:14 -0600 Subject: [PATCH 14/20] feat: Diagnose - one list of what is wrong with a game, with fixes you can undo The game pane's Launch check and Known fixes buttons become one Diagnose button. Its dialog lists findings by how likely they are to be the reason the game will not start, each with its evidence and where the knowledge comes from. "Fix this" shows the launch options and Proton build before and after, applies in one click, and the last fix can be undone, also after a restart. Diagnose says when Steam is running (it rewrites its settings on exit), when the launch editor has unsaved edits, and for a Non-Steam shortcut offers the new line to copy, since the app cannot write shortcuts. The dialog is its own QML file. The launch check and fixes controllers and known_fixes.json are gone; the gathering they did lives in core. Co-Authored-By: Claude Fable 5.2 --- ARCHITECTURE.md | 12 +- protonshift/app.py | 13 +- protonshift/controllers/__init__.py | 6 +- .../controllers/diagnose_controller.py | 450 +++++++++++ protonshift/controllers/fixes_controller.py | 106 --- .../controllers/launch_check_controller.py | 107 --- protonshift/controllers/launch_controller.py | 16 + protonshift/core/data/known_fixes.json | 113 --- protonshift/core/fixes.py | 36 +- protonshift/qml/DiagnoseDialog.qml | 763 ++++++++++++++++++ protonshift/qml/GamesPage.qml | 293 +------ 11 files changed, 1271 insertions(+), 644 deletions(-) create mode 100644 protonshift/controllers/diagnose_controller.py delete mode 100644 protonshift/controllers/fixes_controller.py delete mode 100644 protonshift/controllers/launch_check_controller.py delete mode 100644 protonshift/core/data/known_fixes.json create mode 100644 protonshift/qml/DiagnoseDialog.qml diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 6557cf4..682959f 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -39,10 +39,14 @@ Roughly one module per integration or feature: SDL mapping, force-feedback rumble via raw `ioctl`/`struct` packing), `host.py` (host command execution, see "Flatpak sandboxing" below). - **Game maintenance**: `shader_cache.py`, `saves.py` (backup/restore), - `prefix.py`, `protontricks.py`, `fixes.py` (known-fixes DB, backed by - `core/data/known_fixes.json`), `launch_presets.py`, `profiles_storage.py`, - `compat_tool.py`, `launch_check.py` (why a game won't start; pure, fed by - its controller), `proton_log.py` (tail of `steam-.log`). + `prefix.py`, `protontricks.py`, `fixes.py` (the user's own fixes), + `launch_presets.py`, `profiles_storage.py`, `compat_tool.py`, + `proton_log.py` (tail of `steam-.log`). +- **Diagnose**: `diagnose.py` (one ranked list of findings; `collect` reads, + the rest is pure), fed by `launch_check.py`, `proton_log.py`, `fix_pack.py` + (the bundled `core/data/fix_pack.json` plus the user's fixes) and + `system_checks.py`; `fix_apply.py` plans, applies and undoes a fix, with + `snapshots.py` keeping what Undo needs. - **The app itself**: `appearance.py` (styles, mode, accent), `sounds.py` (sound sets and stored settings), `updates.py` (manual update check). - **Shared low-level helpers**: `fsutil.py` (atomic writes, dir sizing), diff --git a/protonshift/app.py b/protonshift/app.py index 440ca6b..19c06f1 100644 --- a/protonshift/app.py +++ b/protonshift/app.py @@ -17,16 +17,15 @@ from . import __version__ from .controllers import ( AboutController, + DiagnoseController, DisplayController, EnvController, - FixesController, GamepadController, GamesController, GamescopeController, GameToolsController, GeProtonController, HeroicController, - LaunchCheckController, LaunchOptionsController, MangoHudController, PerAppScopeBuddyController, @@ -75,7 +74,6 @@ def main() -> int: game_tools = GameToolsController() profiles = ProfilesController() saves = SavesController() - fixes = FixesController() scb_envvars = ScopeBuddyEnvvarsController() heroic = HeroicController() gamepad = GamepadController() @@ -83,7 +81,7 @@ def main() -> int: ge_proton = GeProtonController() sounds = SoundController() about = AboutController() - launch_check = LaunchCheckController() + diagnose = DiagnoseController() proton_log = ProtonLogController() # Outcome chimes for work that finishes on a worker thread. (Saves that # finish at once chime from their Save button in QML.) Where the control @@ -102,6 +100,10 @@ def main() -> int: ge_proton._installDone.connect(lambda _name: sounds.chime(True)) ge_proton._installFailed.connect(lambda _msg, cancelled: cancelled or sounds.chime(False)) ge_proton._removeDone.connect(lambda _name, error: sounds.chime(not error)) + # A Diagnose fix or its undo chimes like a save, and the launch options + # editor re-reads Steam so it shows the line and Proton build now saved. + diagnose.settingsWritten.connect(lambda _app, ok: sounds.chime(ok)) + diagnose.settingsWritten.connect(lambda app_id, ok: ok and launch.reloadFromSteam(app_id)) # installed/removed builds should show up in the per-game Proton picker ge_proton.toolsChanged.connect(launch.reloadProton) ctx = engine.rootContext() @@ -120,7 +122,6 @@ def main() -> int: ctx.setContextProperty("gameTools", game_tools) ctx.setContextProperty("profiles", profiles) ctx.setContextProperty("saves", saves) - ctx.setContextProperty("fixes", fixes) ctx.setContextProperty("scbEnvvars", scb_envvars) ctx.setContextProperty("heroic", heroic) ctx.setContextProperty("gamepad", gamepad) @@ -128,7 +129,7 @@ def main() -> int: ctx.setContextProperty("geProton", ge_proton) ctx.setContextProperty("sounds", sounds) ctx.setContextProperty("about", about) - ctx.setContextProperty("launchCheck", launch_check) + ctx.setContextProperty("diagnose", diagnose) ctx.setContextProperty("protonLog", proton_log) ctx.setContextProperty("appVersion", __version__) diff --git a/protonshift/controllers/__init__.py b/protonshift/controllers/__init__.py index 8544ff4..0686d83 100644 --- a/protonshift/controllers/__init__.py +++ b/protonshift/controllers/__init__.py @@ -6,16 +6,15 @@ """ from .about_controller import AboutController +from .diagnose_controller import DiagnoseController from .display_controller import DisplayController from .env_controller import EnvController -from .fixes_controller import FixesController from .game_tools_controller import GameToolsController from .gamepad_controller import GamepadController from .games_controller import GamesController from .gamescope_controller import GamescopeController from .ge_proton_controller import GeProtonController from .heroic_controller import HeroicController -from .launch_check_controller import LaunchCheckController from .launch_controller import LaunchOptionsController from .mangohud_controller import MangoHudController from .per_app_scopebuddy_controller import PerAppScopeBuddyController @@ -33,16 +32,15 @@ __all__ = [ "AboutController", + "DiagnoseController", "DisplayController", "EnvController", - "FixesController", "GameToolsController", "GamepadController", "GamesController", "GamescopeController", "GeProtonController", "HeroicController", - "LaunchCheckController", "LaunchOptionsController", "MangoHudController", "PerAppScopeBuddyController", diff --git a/protonshift/controllers/diagnose_controller.py b/protonshift/controllers/diagnose_controller.py new file mode 100644 index 0000000..2a066f5 --- /dev/null +++ b/protonshift/controllers/diagnose_controller.py @@ -0,0 +1,450 @@ +"""QObject bridge for Diagnose: one ranked list of reasons a game may not start or run well. + +``run`` gathers everything on a worker thread (``core.diagnose.collect``) and +keeps the :class:`~protonshift.core.diagnose.Report` and its findings here; +QML only ever sees plain rows (``to_row``) and maps. A result from an older run +(another game, or a run that was started again) is dropped, so switching games +never shows the previous game's findings. + +A fix goes preview first, then apply: ``openPreview`` plans it on the GUI +thread (``fix_apply.plan`` is pure), ``apply`` plans it again from the same +report and writes it on a worker. ``apply_change`` itself refuses a plan made +from settings that changed on disk since, so the user is never surprised. +After a write that worked, ``settingsWritten`` fires (``app.py`` reloads the +launch options editor and plays the chime) and the diagnosis runs again. +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +from PySide6.QtCore import Property, QObject, Signal, Slot +from PySide6.QtGui import QGuiApplication + +from ..core import diagnose, fix_apply +from ..core.snapshots import GameState, Snapshot +from ._worker import start_worker + +_SEVERITIES = diagnose.SEVERITY_ORDER + + +def _when_label(taken_at: str) -> str: + """A snapshot's ISO time as the user's local clock reads it ("today at 14:05").""" + try: + moment = datetime.fromisoformat(taken_at).astimezone() + except (TypeError, ValueError): + return "" + clock = moment.strftime("%H:%M") + today = datetime.now().astimezone().date() + if moment.date() == today: + return f"today at {clock}" + if moment.date() == today - timedelta(days=1): + return f"yesterday at {clock}" + return f"{moment.day} {moment.strftime('%b %Y')} at {clock}" + + +def _checked_line(report: diagnose.Report, shortcut: bool, native: bool) -> str: + parts = ["the shortcut's launch options" if shortcut else "the launch options saved in Steam"] + if not native: + parts.append("the Proton build") + if any(f.id == "log-read" for f in report.findings): + parts.append("the Proton log") + parts.append("the problems ProtonShift knows about") + parts.append("this PC") + listed = ", ".join(parts[:-1]) + " and " + parts[-1] + return f"Checked {listed}. Diagnose only reads; it does not start the game." + + +class DiagnoseController(QObject): + runningChanged = Signal() + reportChanged = Signal() # findings / summary / counts / canApply / steamRunning / logPath / checked + busyChanged = Signal() + statusChanged = Signal() + undoChanged = Signal() # undoAvailable / undoLabel / undoWhen / undoConflict + previewChanged = Signal() + + # A fix or its undo was written (app_id, ok). app.py chimes on it and, when + # ok, reloads the launch options editor so it shows what Steam now has. + settingsWritten = Signal(str, bool) + + _runResult = Signal(int, object, object) # run token, Report, Snapshot | None + _runError = Signal(int, str) # run token, message + _writeResult = Signal(str, object, object, bool) # app_id, ApplyResult, Snapshot | None, undo conflict + _writeError = Signal(str, str) # app_id, message + + def __init__(self, parent: QObject | None = None) -> None: + super().__init__(parent) + self._app_id = "" + self._run_args: tuple | None = None + self._run_token = 0 + self._running = False + self._report: diagnose.Report | None = None + self._findings: dict[str, diagnose.Finding] = {} + self._rows: list[dict] = [] + self._summary = "" + self._checked = "" + self._error = "" + self._shortcut_options: str | None = None + self._busy = False + self._status = "" + self._status_ok = True + self._undo: Snapshot | None = None + self._undo_conflict = "" + self._preview: dict = {} + self._runResult.connect(self._on_run_result) + self._runError.connect(self._on_run_error) + self._writeResult.connect(self._on_write_result) + self._writeError.connect(self._on_write_error) + + # --- state ------------------------------------------------------------------ + + @Property(str, notify=reportChanged) + def appId(self) -> str: + return self._app_id + + @Property(bool, notify=runningChanged) + def running(self) -> bool: + return self._running + + @Property("QVariantList", notify=reportChanged) + def findings(self) -> list: + return self._rows + + @Property(str, notify=reportChanged) + def summary(self) -> str: + return self._summary + + @Property(str, notify=reportChanged) + def checked(self) -> str: + """A quiet line naming what the diagnosis looked at.""" + return self._checked + + @Property(str, notify=reportChanged) + def error(self) -> str: + """Why the diagnosis itself failed; "" when it ran.""" + return self._error + + @Property("QVariantMap", notify=reportChanged) + def counts(self) -> dict: + """Findings per severity, every severity present (0 when none).""" + out = dict.fromkeys(_SEVERITIES, 0) + for row in self._rows: + out[row["severity"]] = out.get(row["severity"], 0) + 1 + return out + + @Property(bool, notify=reportChanged) + def hasBlocking(self) -> bool: + return any(row["severity"] == "blocking" for row in self._rows) + + @Property(bool, notify=reportChanged) + def canApply(self) -> bool: + """False for Non-Steam shortcuts and for Steam settings that could not be read.""" + return bool(self._report and self._report.can_apply) + + @Property(bool, notify=reportChanged) + def isShortcut(self) -> bool: + return self._shortcut_options is not None + + @Property(str, notify=reportChanged) + def steamRunning(self) -> str: + """``"yes"``, ``"no"`` or ``"unknown"``.""" + running = self._report.steam_running if self._report else None + return "unknown" if running is None else ("yes" if running else "no") + + @Property(str, notify=reportChanged) + def logPath(self) -> str: + return self._report.log_path if self._report else "" + + @Property(bool, notify=busyChanged) + def busy(self) -> bool: + """An apply or an undo is being written.""" + return self._busy + + @Property(str, notify=statusChanged) + def status(self) -> str: + return self._status + + @Property(bool, notify=statusChanged) + def statusOk(self) -> bool: + return self._status_ok + + @Property(bool, notify=undoChanged) + def undoAvailable(self) -> bool: + return self._undo is not None + + @Property(str, notify=undoChanged) + def undoLabel(self) -> str: + return self._undo.label if self._undo else "" + + @Property(str, notify=undoChanged) + def undoWhen(self) -> str: + return _when_label(self._undo.taken_at) if self._undo else "" + + @Property(str, notify=undoChanged) + def undoConflict(self) -> str: + """Why Undo refused (the settings changed after the fix); "" otherwise.""" + return self._undo_conflict + + @Property("QVariantMap", notify=previewChanged) + def preview(self) -> dict: + """The fix being previewed; empty when none is open.""" + return self._preview + + # --- running ------------------------------------------------------------------ + + @Slot(str, str, str, bool, str, bool, str) + def run(self, app_id: str, install_path: str, prefix_path: str, is_shortcut: bool, + shortcut_options: str, native: bool, protondb_tier: str) -> None: + """Diagnose one game. ``shortcut_options`` is used only for a Non-Steam shortcut.""" + self._start(app_id, (install_path, prefix_path, shortcut_options if is_shortcut else None, + native, protondb_tier)) + + def _start(self, app_id: str, args: tuple) -> None: + if app_id != self._app_id: + # Another game: nothing from the previous one may stay on screen. + self._report = None + self._findings = {} + self._rows = [] + self._summary = "" + self._checked = "" + self._undo = None + self._undo_conflict = "" + self._set_status("", True) + self.undoChanged.emit() + self._app_id = app_id + self._run_args = args + self._shortcut_options = args[2] + self._error = "" + self._run_token += 1 + token = self._run_token + self._running = True + self._clear_preview() + self.runningChanged.emit() + self.reportChanged.emit() + if not app_id: + self._on_run_error(token, "No game is selected.") + return + start_worker(self._run_work, token, app_id, *args, + on_error=lambda message: self._runError.emit(token, message)) + + def _run_work(self, token: int, app_id: str, install_path: str, prefix_path: str, + shortcut_options: str | None, native: bool, protondb_tier: str) -> None: + report = diagnose.collect( + app_id, + install_path=install_path, + prefix_path=prefix_path, + shortcut_options=shortcut_options, + native=native, + protondb_tier=protondb_tier, + ) + undo = fix_apply.undo_available(app_id) if shortcut_options is None else None + self._runResult.emit(token, report, undo) + + def _on_run_result(self, token: int, report: diagnose.Report, undo: Snapshot | None) -> None: + if token != self._run_token or report.app_id != self._app_id: + return # an older run, or a game the user has moved on from + args = self._run_args or ("", "", None, False, "") + self._report = report + self._findings = {f.id: f for f in report.findings} + self._rows = [diagnose.to_row(f) for f in report.findings] + self._summary = report.summary + self._checked = _checked_line(report, shortcut=args[2] is not None, native=bool(args[3])) + self._error = "" + self._undo = undo + self._running = False + self.reportChanged.emit() + self.undoChanged.emit() + self.runningChanged.emit() + + def _on_run_error(self, token: int, message: str) -> None: + if token != self._run_token: + return + self._report = None + self._findings = {} + self._rows = [] + self._summary = "" + self._checked = "" + self._error = f"Diagnose could not finish: {message}" + self._running = False + self.reportChanged.emit() + self.runningChanged.emit() + + def _rerun(self) -> None: + if self._run_args is not None and self._app_id: + self._start(self._app_id, self._run_args) + + # --- preview ------------------------------------------------------------------ + + def _planning_state(self) -> tuple[GameState | None, str]: + """The settings a plan starts from, or ``(None, reason)`` when there are none to plan on.""" + if self._shortcut_options is not None: + # Steam keeps a shortcut's launch options in the shortcut; its Proton + # choice is not something ProtonShift can change for it. + return GameState(launch_options=self._shortcut_options, compat_tool=""), "" + if self._report is not None and self._report.state is not None: + return self._report.state, "" + return None, ("Steam's settings for this game could not be read, so ProtonShift cannot work out " + "the change. Follow the steps above by hand.") + + def _plan(self, finding_id: str) -> tuple[diagnose.Finding | None, fix_apply.Change | None, str]: + finding = self._findings.get(finding_id) + if finding is None: + return None, None, "" + state, reason = self._planning_state() + if state is None: + return finding, None, reason + return finding, fix_apply.plan(finding.actions, state), "" + + @Slot(str) + def openPreview(self, finding_id: str) -> None: + """Work out what a fix would change and show it (pure: nothing is written).""" + finding, change, reason = self._plan(finding_id) + if finding is None: + self._clear_preview() + return + manual = [a.text for a in finding.actions if a.type == "manual"] + preview = { + "findingId": finding.id, + "title": finding.title, + "beforeLaunch": "", "afterLaunch": "", "launchChanged": False, + "beforeProton": "", "afterProton": "", "protonChanged": False, + "manual": manual, + "blocked": reason, + "changed": False, + "mode": "none", # "apply" | "copy" | "none" + } + if change is not None: + launch_changed = change.after.launch_options != change.before.launch_options + proton_changed = change.after.compat_tool != change.before.compat_tool + preview.update({ + "beforeLaunch": change.before.launch_options, + "afterLaunch": change.after.launch_options, + "launchChanged": launch_changed, + "beforeProton": change.before.compat_tool, + "afterProton": change.after.compat_tool, + "protonChanged": proton_changed, + "manual": list(change.manual), + "blocked": change.blocked, + "changed": change.changed, + }) + if not change.blocked and change.changed: + if self.canApply: + preview["mode"] = "apply" + elif self._shortcut_options is not None and launch_changed: + preview["mode"] = "copy" + self._preview = preview + self.previewChanged.emit() + + @Slot() + def clearPreview(self) -> None: + self._clear_preview() + + def _clear_preview(self) -> None: + if self._preview: + self._preview = {} + self.previewChanged.emit() + + @Slot(str, result=bool) + def copyProposed(self, finding_id: str) -> bool: + """Copy the launch options a fix would give (for shortcuts, which ProtonShift cannot write).""" + _finding, change, _reason = self._plan(finding_id) + clipboard = QGuiApplication.clipboard() + if change is None or change.blocked or clipboard is None: + self._set_status("There is nothing to copy for this fix.", False) + return False + clipboard.setText(change.after.launch_options) + self._set_status("Copied the new launch options. Paste them into the shortcut's properties in Steam.", + True) + return True + + # --- writing ------------------------------------------------------------------ + + @Slot(str) + def apply(self, finding_id: str) -> None: + """Write one fix to Steam's files, after saving a snapshot so it can be undone.""" + if self._busy or self._running: + return + report = self._report + finding = self._findings.get(finding_id) + if report is None or finding is None or not report.can_apply or report.state is None: + self._set_status("This fix cannot be applied here.", False) + return + localconfig, config_vdf = report.paths + self._begin_write() + app_id = report.app_id + start_worker(self._apply_work, app_id, localconfig, config_vdf, finding, report.state, + on_error=lambda message: self._writeError.emit(app_id, message)) + + def _apply_work(self, app_id, localconfig, config_vdf, finding, state) -> None: + change = fix_apply.plan(finding.actions, state) + result = fix_apply.apply_change(localconfig, config_vdf, app_id, change, + label=finding.title, finding_id=finding.id) + self._writeResult.emit(app_id, result, fix_apply.undo_available(app_id), False) + + @Slot(bool) + def undo(self, force: bool) -> None: + """Put back the settings from before the latest fix. ``force`` overwrites later changes.""" + if self._busy or self._running: + return + report = self._report + if report is None or self._undo is None: + self._set_status("There is no fix to undo for this game.", False) + return + localconfig, config_vdf = report.paths + self._begin_write() + app_id = report.app_id + start_worker(self._undo_work, app_id, localconfig, config_vdf, force, + on_error=lambda message: self._writeError.emit(app_id, message)) + + def _undo_work(self, app_id, localconfig, config_vdf, force: bool) -> None: + snap = fix_apply.undo_available(app_id) + current = fix_apply.read_state(localconfig, config_vdf, app_id) + # The same test undo_latest refuses on: settings that are neither the + # fix's before nor its after were changed by someone since. + conflict = (not force and snap is not None and current is not None + and current not in (snap.before, snap.after)) + result = fix_apply.undo_latest(localconfig, config_vdf, app_id, force=force) + self._writeResult.emit(app_id, result, fix_apply.undo_available(app_id), conflict and not result.ok) + + @Slot() + def dismissUndoConflict(self) -> None: + """Keep the settings as they are now; the fix stays undoable.""" + if self._undo_conflict: + self._undo_conflict = "" + self.undoChanged.emit() + + def _begin_write(self) -> None: + self._busy = True + self._undo_conflict = "" + self.busyChanged.emit() + self.undoChanged.emit() + + def _on_write_result(self, app_id: str, result: fix_apply.ApplyResult, undo: Snapshot | None, + conflict: bool) -> None: + self._busy = False + self.busyChanged.emit() + if app_id == self._app_id: + self._undo = undo + self._undo_conflict = result.message if conflict else "" + self.undoChanged.emit() + if not conflict: + self._set_status(result.message, result.ok) + self.settingsWritten.emit(app_id, result.ok) + # The list has to show the settings as they are now; a plan refused + # because the settings moved needs a fresh report too. + if app_id == self._app_id and not conflict and (result.ok or result.state is not None): + self._rerun() + + def _on_write_error(self, app_id: str, message: str) -> None: + self._busy = False + self.busyChanged.emit() + self.settingsWritten.emit(app_id, False) + if app_id == self._app_id: + self._set_status(f"Something went wrong, so the change may not be complete: {message}", False) + self._rerun() + + def _set_status(self, text: str, ok: bool) -> None: + if text != self._status or ok != self._status_ok: + self._status = text + self._status_ok = ok + self.statusChanged.emit() diff --git a/protonshift/controllers/fixes_controller.py b/protonshift/controllers/fixes_controller.py deleted file mode 100644 index 913c354..0000000 --- a/protonshift/controllers/fixes_controller.py +++ /dev/null @@ -1,106 +0,0 @@ -"""QObject bridge for the game-specific fixes database. - -Surfaces built-in + user fixes for a game. Each fix carries a ready-made -``snippet`` (``KEY=value`` for env fixes, the raw value for launch args); the UI -applies it by appending to the launch-options editor, so the user reviews and -saves through the same fail-closed path as any hand-typed option. -""" - -from __future__ import annotations - -from PySide6.QtCore import Property, QObject, Signal, Slot - -from ._worker import start_worker - - -class FixesController(QObject): - appIdChanged = Signal() - fixesChanged = Signal() - statusChanged = Signal() - - _listResult = Signal(str, list) - _workError = Signal(str) # unexpected worker exception -> status - - def __init__(self, parent: QObject | None = None) -> None: - super().__init__(parent) - self._app_id = "" - self._fixes: list[dict] = [] - self._status = "" - self._listResult.connect(self._on_list) - self._workError.connect(self._on_work_error) - - @Property(str, notify=appIdChanged) - def appId(self) -> str: - return self._app_id - - @appId.setter - def appId(self, value: str) -> None: - if value == self._app_id: - return - self._app_id = value - self.appIdChanged.emit() - if value: - self.refresh() - - @Property("QVariantList", notify=fixesChanged) - def fixes(self) -> list: - return self._fixes - - @Property(str, notify=statusChanged) - def status(self) -> str: - return self._status - - @Slot(str) - def addUserFix(self, args_json: str) -> None: - """Add a user fix from a JSON blob {title,description,type,key,value}.""" - import json - - from ..core.fixes import add_user_fix - - try: - d = json.loads(args_json) - except (ValueError, TypeError): - self._status = "Invalid fix." - self.statusChanged.emit() - return - ok = add_user_fix( - self._app_id, - d.get("title", ""), - d.get("description", ""), - d.get("type", "env"), - d.get("key", ""), - d.get("value", ""), - ) - self._status = "Fix added." if ok else "Couldn't add fix." - self.statusChanged.emit() - self.refresh() - - @Slot() - def refresh(self) -> None: - if not self._app_id: - return - start_worker(self._list_work, self._app_id, on_error=self._workError.emit) - - def _list_work(self, app_id: str) -> None: - from ..core.fixes import get_fixes - - rows = [] - for f in get_fixes(app_id): - snippet = f"{f.key}={f.value}" if f.fix_type == "env" and f.key else f.value - rows.append({ - "title": f.title, - "description": f.description, - "source": f.source, - "snippet": snippet, - }) - self._listResult.emit(app_id, rows) - - def _on_list(self, app_id: str, rows: list) -> None: - if app_id != self._app_id: - return - self._fixes = rows - self.fixesChanged.emit() - - def _on_work_error(self, message: str) -> None: - self._status = f"Unexpected error: {message}" - self.statusChanged.emit() diff --git a/protonshift/controllers/launch_check_controller.py b/protonshift/controllers/launch_check_controller.py deleted file mode 100644 index 9da2644..0000000 --- a/protonshift/controllers/launch_check_controller.py +++ /dev/null @@ -1,107 +0,0 @@ -"""QObject bridge for the per-game launch check. - -``run`` gathers what the pure check needs (launch options, the chosen Proton -build, installed tools and runtimes) on a worker thread and reports the -findings back through a queued signal. -""" - -from __future__ import annotations - -from pathlib import Path - -from PySide6.QtCore import Property, QObject, Signal, Slot - -from ._worker import start_worker - - -class LaunchCheckController(QObject): - changed = Signal() # running / findings / summary / appId - - _result = Signal(str, list, str) # app_id, findings, summary - - def __init__(self, parent: QObject | None = None) -> None: - super().__init__(parent) - self._app_id = "" - self._running = False - self._findings: list[dict] = [] - self._summary = "" - self._result.connect(self._on_result) - - @Property(bool, notify=changed) - def running(self) -> bool: - return self._running - - @Property("QVariantList", notify=changed) - def findings(self) -> list: - return self._findings - - @Property(str, notify=changed) - def summary(self) -> str: - return self._summary - - @Property(bool, notify=changed) - def hasProblems(self) -> bool: - return any(f["level"] in ("error", "warn") for f in self._findings) - - @Slot(str, str, str, str, str) - def run(self, app_id: str, install_path: str, prefix_path: str, - shortcut_options: str, protondb_tier: str) -> None: - """Check one game. ``shortcut_options`` carries a Non-Steam shortcut's - launch options (Steam keeps those in the shortcut, not in localconfig); - pass ``"\\x00"`` for a store game so they are read from Steam.""" - self._app_id = app_id - self._running = True - self._findings = [] - self._summary = "" - self.changed.emit() - start_worker( - self._work, app_id, install_path, prefix_path, shortcut_options, protondb_tier, - on_error=lambda m: self._result.emit(app_id, [], f"The check failed: {m}"), - ) - - def _work(self, app_id: str, install_path: str, prefix_path: str, - shortcut_options: str, protondb_tier: str) -> None: - from ..core.compat_tool import get_config_vdf_path, read_compat_tool - from ..core.launch_check import check_launch, summarize - from ..core.steam import discover_games, get_available_proton_tools, get_localconfig_path - from ..core.tool_check import is_tool_available - from ..core.vdf_config import read_launch_options - - root, _games = discover_games() - if shortcut_options == "\x00": - config = get_localconfig_path(root) if root else None - readable, options = read_launch_options(config, app_id) if config else (False, "") - else: - readable, options = True, shortcut_options - ok, tool = read_compat_tool(get_config_vdf_path(root), app_id) if root else (False, "") - # Tools (Proton builds, runtimes) are hidden from the game list, so - # look for their manifests directly. - installed: list[str] = [] - if root: - from ..core.launch_check import ANTICHEAT_RUNTIMES - from ..core.steam import _find_libraryfolders - - for lib in _find_libraryfolders(root): - for runtime_id, _name in ANTICHEAT_RUNTIMES.values(): - if (lib / "steamapps" / f"appmanifest_{runtime_id}.acf").exists(): - installed.append(runtime_id) - findings = check_launch( - launch_options=options, - launch_options_readable=readable, - compat_tool=tool if ok else "", - available_tools=get_available_proton_tools(root), - install_path=Path(install_path) if install_path else None, - prefix_path=Path(prefix_path) if prefix_path else None, - installed_app_ids=installed, - tool_exists=is_tool_available, - protondb_tier=protondb_tier, - ) - self._result.emit(app_id, findings, summarize(findings)) - - def _on_result(self, app_id: str, findings: list, summary: str) -> None: - if app_id != self._app_id: - return # the user moved on to another game - self._running = False - self._findings = findings - self._summary = summary - self.changed.emit() diff --git a/protonshift/controllers/launch_controller.py b/protonshift/controllers/launch_controller.py index 972418b..aaf543d 100644 --- a/protonshift/controllers/launch_controller.py +++ b/protonshift/controllers/launch_controller.py @@ -229,6 +229,22 @@ def reloadProton(self) -> None: """Re-read the Proton tool list (e.g. after the GE-Proton page installs a build).""" self._reload_proton() + @Slot(str) + def reloadFromSteam(self, app_id: str) -> None: + """Re-read the saved launch options and Proton choice when ``app_id`` is the game shown. + + For a change written behind the editor (a Diagnose fix or its undo): + the editor then shows what Steam has, replacing any unsaved edit. + """ + if not app_id or app_id != self._app_id: + return + self._status = "" + self._proton_status = "" + self.statusChanged.emit() + self.protonStatusChanged.emit() + self._reload() + self._reload_proton() + def _reload_proton(self) -> None: if not self._app_id: self._proton_tools = [] diff --git a/protonshift/core/data/known_fixes.json b/protonshift/core/data/known_fixes.json deleted file mode 100644 index c7c40e6..0000000 --- a/protonshift/core/data/known_fixes.json +++ /dev/null @@ -1,113 +0,0 @@ -{ - "12210": [ - { - "title": "Use OpenGL instead of DirectX", - "description": "Grand Theft Auto IV performs better with OpenGL on some GPUs", - "type": "env", - "key": "PROTON_USE_WINED3D", - "value": "1" - } - ], - "292030": [ - { - "title": "Enable NVIDIA DLSS", - "description": "The Witcher 3 supports DLSS on NVIDIA GPUs via Proton", - "type": "env", - "key": "PROTON_ENABLE_NVAPI", - "value": "1" - }, - { - "title": "Hide NVIDIA GPU info", - "description": "Some anti-cheat may flag NVAPI. Hide GPU info if needed.", - "type": "env", - "key": "PROTON_HIDE_NVIDIA_GPU", - "value": "0" - } - ], - "1091500": [ - { - "title": "Enable large address aware", - "description": "Cyberpunk 2077 can benefit from large address aware mode", - "type": "launch_arg", - "value": "PROTON_LARGE_ADDRESS_AWARE=1 %command%" - }, - { - "title": "Enable NVIDIA DLSS / RTX", - "description": "Enable NVAPI for DLSS and ray tracing support", - "type": "env", - "key": "PROTON_ENABLE_NVAPI", - "value": "1" - } - ], - "1174180": [ - { - "title": "Force Vulkan renderer", - "description": "Red Dead Redemption 2 may crash with DX12; force Vulkan", - "type": "launch_arg", - "value": "-vulkan %command%" - } - ], - "1245620": [ - { - "title": "Enable EAC runtime", - "description": "Elden Ring uses Easy Anti-Cheat which needs Proton EAC runtime", - "type": "env", - "key": "PROTON_EAC_RUNTIME", - "value": "1" - } - ], - "413150": [ - { - "title": "Enable BattlEye runtime", - "description": "Stardew Valley multiplayer may need BattlEye compatibility", - "type": "env", - "key": "PROTON_BATTLEYE_RUNTIME", - "value": "1" - } - ], - "570": [ - { - "title": "Disable Steam overlay", - "description": "Dota 2 overlay can cause rendering issues on some systems", - "type": "launch_arg", - "value": "-nooverlay %command%" - } - ], - "_common": [ - { - "title": "Disable Esync", - "description": "Fixes crashes in games that don't support Esync properly", - "type": "env", - "key": "PROTON_NO_ESYNC", - "value": "1" - }, - { - "title": "Disable Fsync", - "description": "Fixes crashes in games that don't support Fsync properly", - "type": "env", - "key": "PROTON_NO_FSYNC", - "value": "1" - }, - { - "title": "Enable Proton debug log", - "description": "Write detailed Proton log to /tmp/proton_/", - "type": "env", - "key": "PROTON_LOG", - "value": "1" - }, - { - "title": "Use system Wine D3D", - "description": "Use Wine's OpenGL-based D3D instead of DXVK Vulkan", - "type": "env", - "key": "PROTON_USE_WINED3D", - "value": "1" - }, - { - "title": "Enable NVIDIA NVAPI", - "description": "Required for DLSS and some NVIDIA-specific features", - "type": "env", - "key": "PROTON_ENABLE_NVAPI", - "value": "1" - } - ] -} diff --git a/protonshift/core/fixes.py b/protonshift/core/fixes.py index dac86af..ea437af 100644 --- a/protonshift/core/fixes.py +++ b/protonshift/core/fixes.py @@ -1,4 +1,8 @@ -"""Game-specific fixes database - built-in and user-contributed.""" +"""The user's own fixes per game, stored in ``~/.config/protonshift/fixes/.json``. + +The bundled knowledge lives in the fix pack (``fix_pack.py``); these are +turned into Diagnose rules by ``fix_pack.user_rules``. +""" from __future__ import annotations @@ -10,7 +14,6 @@ from .fsutil import atomic_write_text from .paths import sanitize_filename -_DATA_DIR = Path(__file__).parent / "data" _USER_FIXES_DIR = Path.home() / ".config" / "protonshift" / "fixes" @@ -25,17 +28,7 @@ class GameFix: fix_type: str # "env" or "launch_arg" key: str # env var key (empty for launch_arg) value: str - source: str # "builtin" or "user" - - -def _load_builtin_fixes() -> dict[str, list[dict[str, Any]]]: - path = _DATA_DIR / "known_fixes.json" - if not path.exists(): - return {} - try: - return json.loads(path.read_text(encoding="utf-8")) - except (json.JSONDecodeError, OSError): - return {} + source: str # always "user" def _load_user_fixes_strict(app_id: str) -> list[dict[str, Any]]: @@ -76,21 +69,8 @@ def _dict_to_fix(d: dict[str, Any], source: str) -> GameFix: def get_fixes(app_id: str) -> list[GameFix]: - """Get all applicable fixes for a game (built-in + user + common).""" - builtin = _load_builtin_fixes() - - fixes: list[GameFix] = [] - - for entry in builtin.get(app_id, []): - fixes.append(_dict_to_fix(entry, "builtin")) - - for entry in builtin.get("_common", []): - fixes.append(_dict_to_fix(entry, "builtin")) - - for entry in _load_user_fixes(app_id): - fixes.append(_dict_to_fix(entry, "user")) - - return fixes + """The user's own fixes for a game.""" + return [_dict_to_fix(entry, "user") for entry in _load_user_fixes(app_id)] def add_user_fix( diff --git a/protonshift/qml/DiagnoseDialog.qml b/protonshift/qml/DiagnoseDialog.qml new file mode 100644 index 0000000..f4c813a --- /dev/null +++ b/protonshift/qml/DiagnoseDialog.qml @@ -0,0 +1,763 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Controls.Basic +import QtQuick.Layouts +import App + +// Diagnose: one ranked list of the reasons a game may not start or run well, +// each with its evidence and, where the fix is mechanical, a previewed +// one-click fix that can be undone. The page hands in the game, the +// controller (`diagnose`) and the sound player; everything else is read from +// the controller, which only ever gives plain rows and maps. +PsDialog { + id: dlg + objectName: "diagnoseDialog" + title: "Diagnose" + subtitle: dlg.game.name || "" + width: Overlay.overlay ? Math.min(720, Overlay.overlay.width - 2 * Theme.spaceLg) : 720 + focus: true + + // --- set by the page ------------------------------------------------------ + property var controller: null // DiagnoseController + property var soundPlayer: null // SoundController + property var game: ({}) // the selected library row + property bool launchDirty: false // the launch options editor has unsaved edits + property string protondbTier: "" // "" when unknown or lookups are off + + signal openLogRequested() + + // --- derived -------------------------------------------------------------- + readonly property string gameId: dlg.game.appId || "" + readonly property bool isShortcut: (dlg.game.source || "") === "shortcut" + readonly property bool isNative: (dlg.game.prefixKind || "") === "none" + readonly property bool ready: dlg.controller !== null + readonly property bool running: dlg.ready && dlg.controller.running + readonly property bool busy: dlg.ready && dlg.controller.busy + readonly property bool steamRunning: dlg.ready && dlg.controller.steamRunning === "yes" + readonly property var preview: dlg.ready ? dlg.controller.preview : ({}) + // a result sound for a run the user started (not the re-run after a fix) + property bool announce: false + property bool showOk: false + + readonly property var order: ["blocking", "likely", "advice", "context", "ok"] + readonly property var headings: ({ + "blocking": "Stops the game from starting", + "likely": "Probably the cause", + "advice": "Worth trying", + "context": "For context", + "ok": "Checked and fine" + }) + readonly property var groups: { + var rows = dlg.ready ? dlg.controller.findings : [] + var out = [] + for (var s = 0; s < dlg.order.length; s++) { + var items = [] + for (var i = 0; i < rows.length; i++) + if (rows[i].severity === dlg.order[s]) items.push(rows[i]) + if (items.length > 0) + out.push({ severity: dlg.order[s], items: items }) + } + return out + } + + function toneFor(severity) { + if (severity === "blocking") return Theme.danger + if (severity === "likely") return Theme.warning + if (severity === "advice") return Theme.primary + if (severity === "ok") return Theme.success + return Theme.muted + } + function glyphFor(severity) { + if (severity === "blocking") return "✕" + if (severity === "likely") return "!" + if (severity === "advice") return "›" + if (severity === "ok") return "✓" + return "i" + } + function play(name) { + if (dlg.soundPlayer) dlg.soundPlayer.play(name) + } + function runDiagnosis() { + if (!dlg.ready || dlg.gameId.length === 0) + return + dlg.announce = true + dlg.controller.run(dlg.gameId, dlg.game.installPath || "", dlg.game.compatdataPath || "", + dlg.isShortcut, dlg.isShortcut ? (dlg.game.launchOptions || "") : "", + dlg.isNative, dlg.protondbTier) + } + + onOpened: { dlg.showOk = false; dlg.runDiagnosis() } + // another game selected while open: diagnose that one, never show the old list + onGameIdChanged: if (dlg.opened) { dlg.showOk = false; dlg.runDiagnosis() } + onClosed: if (dlg.ready) dlg.controller.clearPreview() + + Connections { + target: dlg.controller + function onRunningChanged() { + if (dlg.controller.running || !dlg.announce) + return + dlg.announce = false + if (!dlg.opened) + return + var counts = dlg.controller.counts + if (dlg.controller.error.length > 0 || counts.blocking > 0) dlg.play("error") + else if (counts.likely > 0) dlg.play("notification") + else dlg.play("success") + } + } + + // A one-line notice with a tone. Used for the "before you start" banners. + component Banner: Rectangle { + id: banner + property alias text: bannerText.text + property color tone: Theme.warning + property color fill: Theme.warningSurface + Layout.fillWidth: true + implicitHeight: bannerText.implicitHeight + 2 * Theme.spaceSm + radius: Theme.radiusSm + color: banner.fill + border.width: 1 + border.color: banner.tone + Accessible.role: Accessible.AlertMessage + Accessible.name: bannerText.text + Text { + id: bannerText + anchors.fill: parent + anchors.margins: Theme.spaceSm + wrapMode: Text.WordWrap + color: banner.tone + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } + } + + // A selectable monospace block that wraps anywhere, so a long log line + // never widens the dialog. + component MonoBlock: Rectangle { + id: mono + property alias text: monoText.text + property bool quiet: false + Layout.fillWidth: true + implicitHeight: monoText.implicitHeight + 2 * Theme.spaceXs + radius: Theme.radiusSm + color: Theme.bgDeep + border.width: 1 + border.color: Theme.border + TextEdit { + id: monoText + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: Theme.spaceXs + readOnly: true + selectByMouse: true + activeFocusOnTab: false + wrapMode: TextEdit.WrapAnywhere + color: mono.quiet ? Theme.faint : Theme.text + selectionColor: Theme.primary + selectedTextColor: Theme.onPrimary + font.family: Theme.monoFamily + font.pixelSize: Theme.fsCaption + } + } + + // A small text link that opens in the browser, by mouse or keyboard. + component LinkText: Text { + id: link + property string url: "" + function activate() { if (link.url.length > 0) Qt.openUrlExternally(link.url) } + color: Theme.primaryBright + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + font.underline: linkHover.hovered || link.activeFocus + activeFocusOnTab: true + Accessible.role: Accessible.Link + Accessible.name: link.text + Accessible.description: link.url + Accessible.onPressAction: link.activate() + Keys.onReturnPressed: link.activate() + Keys.onEnterPressed: link.activate() + Keys.onSpacePressed: link.activate() + HoverHandler { id: linkHover; cursorShape: Qt.PointingHandCursor } + TapHandler { onTapped: link.activate() } + } + + ColumnLayout { + id: content + width: parent.width + spacing: Theme.space + + // ===== 1. summary ====================================================== + ColumnLayout { + id: top + Layout.fillWidth: true + spacing: Theme.spaceSm + + RowLayout { + Layout.fillWidth: true + spacing: Theme.spaceSm + BusyIndicator { + running: dlg.running + visible: dlg.running + implicitWidth: 20 + implicitHeight: 20 + } + Text { + Layout.fillWidth: true + wrapMode: Text.WordWrap + text: dlg.running ? "Diagnosing…" + : (dlg.ready && dlg.controller.error.length > 0 ? dlg.controller.error + : (dlg.ready ? dlg.controller.summary : "")) + color: dlg.running ? Theme.muted + : (dlg.ready && dlg.controller.error.length > 0 ? Theme.danger + : (dlg.ready && dlg.controller.hasBlocking ? Theme.danger + : (dlg.ready && dlg.controller.counts.likely > 0 ? Theme.text : Theme.success))) + font.family: Theme.fontFamily + font.pixelSize: Theme.fsBody + font.weight: Font.DemiBold + Accessible.role: Accessible.StaticText + Accessible.name: text + } + } + Text { + Layout.fillWidth: true + visible: text.length > 0 + wrapMode: Text.WordWrap + text: dlg.ready ? dlg.controller.checked : "" + color: Theme.faint + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } + + // ===== 2. banners ================================================== + Banner { + visible: dlg.steamRunning && dlg.ready && dlg.controller.canApply + text: "Steam is running. It rewrites its settings when it closes, so a fix applied now can be lost. Quit Steam first." + } + Banner { + visible: dlg.launchDirty && !dlg.isShortcut + text: "You have unsaved launch options. Diagnose looked at what is saved in Steam." + } + Banner { + visible: dlg.isShortcut + tone: Theme.muted + fill: Theme.bgDeep + text: "ProtonShift can't write a Non-Steam shortcut's launch options. Use Copy and paste the line into the shortcut's properties in Steam." + } + } + + // ===== 3. findings, grouped by severity ================================ + Flickable { + id: listFlick + Layout.fillWidth: true + // Never taller than what the window leaves, so the undo bar and the + // footer stay in view and the list scrolls inside the dialog. + readonly property real budget: { + var avail = Overlay.overlay ? Overlay.overlay.height : 900 + // PsDialog's own margins, header and divider, then everything here but the list + var chrome = 2 * Theme.spaceLg + Theme.spaceLg + Theme.space + Theme.fsTitle * 1.6 + + (dlg.subtitle.length > 0 ? Theme.fsCaption * 1.5 : 0) + 1 + 2 * Theme.spaceLg + var rest = top.implicitHeight + undoBar.implicitHeight * (undoBar.visible ? 1 : 0) + + footer.implicitHeight + 3 * content.spacing + return Math.max(160, avail - chrome - rest) + } + Layout.preferredHeight: Math.min(findingsCol.implicitHeight, budget) + visible: dlg.groups.length > 0 + contentWidth: width + contentHeight: findingsCol.implicitHeight + clip: true + boundsBehavior: Flickable.StopAtBounds + ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded } + + ColumnLayout { + id: findingsCol + // room on the right for the scroll bar + width: listFlick.width - Theme.spaceSm + spacing: Theme.space + + Repeater { + model: dlg.groups + delegate: ColumnLayout { + id: group + required property var modelData + readonly property bool isOk: group.modelData.severity === "ok" + readonly property bool expanded: !group.isOk || dlg.showOk + readonly property color tone: dlg.toneFor(group.modelData.severity) + Layout.fillWidth: true + spacing: Theme.spaceXs + + // group heading; the "fine" group is a button that folds it open + AbstractButton { + id: heading + Layout.fillWidth: true + implicitHeight: headingRow.implicitHeight + 4 + enabled: group.isOk + focusPolicy: group.isOk ? Qt.StrongFocus : Qt.NoFocus + text: dlg.headings[group.modelData.severity] + + (group.isOk ? " (" + group.modelData.items.length + ")" : "") + Accessible.role: group.isOk ? Accessible.Button : Accessible.Heading + Accessible.name: heading.text + Accessible.description: group.isOk ? (dlg.showOk ? "Shown, press to hide" : "Hidden, press to show") : "" + onClicked: { dlg.play("click"); dlg.showOk = !dlg.showOk } + HoverHandler { enabled: group.isOk; cursorShape: Qt.PointingHandCursor } + background: Rectangle { + radius: Theme.radiusSm + color: "transparent" + border.width: 2 + border.color: Theme.accentBright + visible: heading.activeFocus + } + contentItem: RowLayout { + id: headingRow + spacing: Theme.spaceXs + Rectangle { + implicitWidth: 3 + implicitHeight: 14 + radius: 2 + color: group.tone + } + Text { + visible: group.isOk + text: dlg.showOk ? "\u25be" : "\u25b8" + color: Theme.muted + font.family: Theme.fontFamily + font.pixelSize: Theme.fsSmall + } + Text { + Layout.fillWidth: true + elide: Text.ElideRight + text: heading.text + color: Theme.text + font.family: Theme.fontFamily + font.pixelSize: Theme.fsSmall + font.weight: Font.Bold + font.capitalization: Font.AllUppercase + font.letterSpacing: 0.8 + } + } + } + + Repeater { + model: group.expanded ? group.modelData.items : [] + delegate: Rectangle { + id: row + required property var modelData + readonly property var finding: row.modelData + readonly property bool previewing: dlg.preview.findingId === row.finding.id + Layout.fillWidth: true + implicitHeight: rowLayout.implicitHeight + 2 * Theme.spaceSm + radius: Theme.radiusSm + color: Theme.bgDeep + border.width: row.previewing ? 2 : 1 + border.color: row.previewing ? Theme.primary + : ((row.finding.severity === "blocking" || row.finding.severity === "likely") + ? group.tone : Theme.border) + Accessible.role: Accessible.ListItem + Accessible.name: dlg.headings[row.finding.severity] + ": " + row.finding.title + Accessible.description: row.finding.cause + + RowLayout { + id: rowLayout + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: Theme.spaceSm + spacing: Theme.spaceSm + + // tone marker + Rectangle { + Layout.alignment: Qt.AlignTop + implicitWidth: 20 + implicitHeight: 20 + radius: 10 + color: "transparent" + border.width: 1 + border.color: group.tone + Text { + anchors.centerIn: parent + text: dlg.glyphFor(row.finding.severity) + color: group.tone + font.family: Theme.fontFamily + font.pixelSize: 11 + font.bold: true + } + } + + ColumnLayout { + Layout.fillWidth: true + spacing: Theme.spaceXs + + RowLayout { + Layout.fillWidth: true + spacing: Theme.spaceXs + Text { + Layout.fillWidth: true + text: row.finding.title + wrapMode: Text.WordWrap + color: Theme.text + font.family: Theme.fontFamily + font.pixelSize: Theme.fsSmall + font.weight: Font.DemiBold + } + Rectangle { + visible: row.finding.origin === "user" + Layout.alignment: Qt.AlignTop + implicitWidth: yoursText.implicitWidth + 12 + implicitHeight: 18 + radius: 9 + color: Theme.surfaceElevated + border.width: 1 + border.color: Theme.primary + Accessible.role: Accessible.StaticText + Accessible.name: "Your own fix" + Text { + id: yoursText + anchors.centerIn: parent + text: "yours" + color: Theme.primaryBright + font.family: Theme.fontFamily + font.pixelSize: 10 + font.weight: Font.DemiBold + } + } + } + Text { + Layout.fillWidth: true + visible: row.finding.cause.length > 0 + text: row.finding.cause + wrapMode: Text.Wrap + color: Theme.muted + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } + MonoBlock { + visible: row.finding.evidence.length > 0 + text: row.finding.evidence + } + Text { + Layout.fillWidth: true + visible: row.finding.fix.length > 0 + text: "What to do: " + row.finding.fix + wrapMode: Text.Wrap + color: Theme.text + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } + // manual steps (shown here unless the preview below lists them) + Repeater { + model: row.previewing ? [] : row.finding.manual + delegate: Text { + required property string modelData + Layout.fillWidth: true + text: "• " + modelData + wrapMode: Text.Wrap + color: Theme.text + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } + } + + RowLayout { + Layout.fillWidth: true + visible: row.finding.source.length > 0 || (row.finding.canApply && !row.previewing) + spacing: Theme.spaceSm + LinkText { + visible: row.finding.source.length > 0 + text: "Where this comes from" + url: row.finding.source + } + Item { Layout.fillWidth: true } + PsButton { + visible: row.finding.canApply && !row.previewing + text: "Fix this" + primary: false + implicitHeight: 32 + enabled: !dlg.running && !dlg.busy + Accessible.name: "Fix this: " + row.finding.title + onClicked: dlg.controller.openPreview(row.finding.id) + } + } + + // ===== 5. the fix, before and after ====== + Rectangle { + id: previewPanel + visible: row.previewing + Layout.fillWidth: true + implicitHeight: row.previewing ? previewCol.implicitHeight + 2 * Theme.spaceSm : 0 + radius: Theme.radiusSm + color: Theme.surface + border.width: 1 + border.color: Theme.borderStrong + + ColumnLayout { + id: previewCol + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: Theme.spaceSm + spacing: Theme.spaceXs + + Text { + Layout.fillWidth: true + text: "What this fix changes" + color: Theme.text + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + font.weight: Font.Bold + } + + // launch options before and after + Text { + visible: row.previewing && dlg.preview.launchChanged === true + text: "Launch options now" + color: Theme.faint + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } + MonoBlock { + visible: row.previewing && dlg.preview.launchChanged === true + quiet: (dlg.preview.beforeLaunch || "").length === 0 + text: (dlg.preview.beforeLaunch || "").length > 0 ? dlg.preview.beforeLaunch : "Nothing set" + } + Text { + visible: row.previewing && dlg.preview.launchChanged === true + text: "After the fix" + color: Theme.faint + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } + MonoBlock { + visible: row.previewing && dlg.preview.launchChanged === true + quiet: (dlg.preview.afterLaunch || "").length === 0 + text: (dlg.preview.afterLaunch || "").length > 0 ? dlg.preview.afterLaunch : "Nothing set" + } + + // Proton build before and after + Text { + Layout.fillWidth: true + visible: row.previewing && dlg.preview.protonChanged === true + wrapMode: Text.Wrap + text: "Proton build: " + ((dlg.preview.beforeProton || "").length > 0 ? dlg.preview.beforeProton : "Steam's default") + + " → " + ((dlg.preview.afterProton || "").length > 0 ? dlg.preview.afterProton : "Steam's default") + color: Theme.text + font.family: Theme.monoFamily + font.pixelSize: Theme.fsCaption + } + + Text { + Layout.fillWidth: true + visible: row.previewing && dlg.preview.changed !== true && (dlg.preview.blocked || "").length === 0 + wrapMode: Text.Wrap + text: "This fix is already in place, so there is nothing to change." + color: Theme.muted + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } + Text { + Layout.fillWidth: true + visible: row.previewing && (dlg.preview.blocked || "").length > 0 + wrapMode: Text.Wrap + text: dlg.preview.blocked || "" + color: Theme.danger + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } + + // what is left for the user to do + Text { + Layout.fillWidth: true + visible: row.previewing && (dlg.preview.manual || []).length > 0 + wrapMode: Text.Wrap + text: "You still need to do this yourself:" + color: Theme.text + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } + Repeater { + model: row.previewing ? (dlg.preview.manual || []) : [] + delegate: Text { + required property string modelData + Layout.fillWidth: true + text: "• " + modelData + wrapMode: Text.Wrap + color: Theme.text + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } + } + + Text { + Layout.fillWidth: true + visible: row.previewing && dlg.preview.mode === "apply" + && dlg.preview.launchChanged === true && dlg.launchDirty + wrapMode: Text.Wrap + text: "Applying replaces the unsaved launch options in the editor with the line above." + color: Theme.warning + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } + + RowLayout { + Layout.fillWidth: true + Layout.topMargin: Theme.spaceXs + spacing: Theme.spaceSm + Item { Layout.fillWidth: true } + PsButton { + text: "Cancel" + primary: false + implicitHeight: 32 + sound: "back" + Accessible.name: "Cancel this fix" + onClicked: dlg.controller.clearPreview() + } + PsButton { + visible: dlg.preview.mode === "copy" + text: "Copy new launch options" + implicitHeight: 32 + sound: "" + onClicked: dlg.play(dlg.controller.copyProposed(row.finding.id) ? "success" : "error") + } + PsButton { + visible: dlg.preview.mode === "apply" + text: dlg.steamRunning ? "Apply anyway" : "Apply" + implicitHeight: 32 + enabled: !dlg.busy && !dlg.running + sound: "" // the result chimes when the write finishes + Accessible.name: text + ": " + row.finding.title + onClicked: dlg.controller.apply(row.finding.id) + } + } + } + } + } + } + } + } + } + } + } + } + + // ===== 6. undo the last fix ============================================ + Rectangle { + id: undoBar + Layout.fillWidth: true + visible: dlg.ready && (dlg.controller.undoAvailable || dlg.controller.undoConflict.length > 0) + implicitHeight: undoCol.implicitHeight + 2 * Theme.spaceSm + radius: Theme.radiusSm + color: dlg.ready && dlg.controller.undoConflict.length > 0 ? Theme.warningSurface : Theme.surfaceElevated + border.width: 1 + border.color: dlg.ready && dlg.controller.undoConflict.length > 0 ? Theme.warningBorder : Theme.border + + ColumnLayout { + id: undoCol + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.margins: Theme.spaceSm + spacing: Theme.spaceXs + + RowLayout { + Layout.fillWidth: true + visible: dlg.ready && dlg.controller.undoConflict.length === 0 + spacing: Theme.spaceSm + Text { + Layout.fillWidth: true + wrapMode: Text.Wrap + text: dlg.ready ? "Last fix: " + dlg.controller.undoLabel + + (dlg.controller.undoWhen.length > 0 ? ", " + dlg.controller.undoWhen : "") : "" + color: Theme.text + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } + PsButton { + text: "Undo" + primary: false + implicitHeight: 32 + sound: "" + enabled: !dlg.busy && !dlg.running + Accessible.name: "Undo the last fix" + onClicked: dlg.controller.undo(false) + } + } + + Text { + Layout.fillWidth: true + visible: dlg.ready && dlg.controller.undoConflict.length > 0 + wrapMode: Text.Wrap + text: dlg.ready ? dlg.controller.undoConflict : "" + color: Theme.warning + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } + RowLayout { + Layout.fillWidth: true + visible: dlg.ready && dlg.controller.undoConflict.length > 0 + spacing: Theme.spaceSm + Item { Layout.fillWidth: true } + PsButton { + text: "Keep" + primary: false + implicitHeight: 32 + Accessible.name: "Keep the settings as they are now" + onClicked: dlg.controller.dismissUndoConflict() + } + PsButton { + text: "Undo anyway" + primary: false + danger: true + implicitHeight: 32 + sound: "" + enabled: !dlg.busy && !dlg.running + Accessible.name: "Undo anyway and overwrite the later changes" + onClicked: dlg.controller.undo(true) + } + } + } + } + + // ===== 7. footer ======================================================= + RowLayout { + id: footer + Layout.fillWidth: true + spacing: Theme.spaceSm + BusyIndicator { + running: dlg.busy + visible: dlg.busy + implicitWidth: 20 + implicitHeight: 20 + } + Text { + Layout.fillWidth: true + wrapMode: Text.Wrap + text: dlg.ready ? dlg.controller.status : "" + color: dlg.ready && dlg.controller.statusOk ? Theme.success : Theme.danger + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + Accessible.role: Accessible.StaticText + Accessible.name: text + } + PsButton { + text: "Check again" + primary: false + enabled: !dlg.running && !dlg.busy + Accessible.name: "Diagnose this game again" + onClicked: dlg.runDiagnosis() + } + PsButton { + text: "Open log" + primary: false + visible: !dlg.isShortcut && !dlg.isNative + Accessible.name: "Open the Proton log for this game" + onClicked: dlg.openLogRequested() + } + PsButton { + text: "Close" + sound: "back" + Accessible.name: "Close Diagnose" + onClicked: dlg.close() + } + } + } +} diff --git a/protonshift/qml/GamesPage.qml b/protonshift/qml/GamesPage.qml index dbd6009..24ce8c1 100644 --- a/protonshift/qml/GamesPage.qml +++ b/protonshift/qml/GamesPage.qml @@ -19,27 +19,6 @@ RowLayout { if (source === "shortcut") return "Non-Steam" return "Steam" } - function runLaunchCheck() { - var g = library.selected - // "\u0000" = read the saved launch options from Steam; a Non-Steam - // shortcut carries its own, which Steam keeps inside the shortcut. - launchCheck.run(g.appId, g.installPath || "", g.compatdataPath || "", - g.source === "shortcut" ? (g.launchOptions || "") : "\u0000", - (g.source === "steam" && protondb.enabled && protondb.loaded) ? protondb.tierLabel : "") - } - function levelColor(level) { - if (level === "error") return Theme.danger - if (level === "warn") return Theme.warning - if (level === "ok") return Theme.success - return Theme.muted - } - function levelGlyph(level) { - if (level === "error") return "✕" - if (level === "warn") return "!" - if (level === "ok") return "✓" - return "i" - } - // Selecting another game reloads the launch options, which would drop // unsaved edits without a word. Ask first. function requestSelect(appId) { @@ -108,7 +87,6 @@ RowLayout { profiles.appId = library.selectedAppId saves.appId = library.selectedAppId saves.prefixPath = library.selected.compatdataPath || "" - fixes.appId = library.selectedAppId heroic.appId = (library.selected.source === "heroic") ? library.selectedAppId : "" if (library.selectedAppId.length > 0) gameTools.refresh() } @@ -960,16 +938,16 @@ RowLayout { PsSectionHeader { Layout.fillWidth: true text: "Per-game tools" - subtitle: detailCard.isSteam ? "Launch check, Proton log, overrides, Winetricks, known fixes, profiles and save backups" - : "Check why it won't start, or install Windows components into its prefix" + subtitle: detailCard.isSteam ? "Diagnose, Proton log, overrides, Winetricks, profiles and save backups" + : "Diagnose why it won't start, or install Windows components into its prefix" } Flow { Layout.fillWidth: true spacing: Theme.spaceSm PsButton { - text: "Launch check…" - primary: false - onClicked: { launchCheckDialog.open(); page.runLaunchCheck() } + text: "Diagnose" + Accessible.name: "Diagnose why this game may not start or run well" + onClicked: diagnoseDialog.open() } PsButton { text: "Proton log…" @@ -1004,12 +982,6 @@ RowLayout { protontricksDialog.open() } } - PsButton { - text: "Known fixes…" - primary: false - visible: detailCard.isSteam - onClicked: { fixes.appId = library.selected.appId; fixesDialog.open() } - } PsButton { text: "Profiles…" primary: false @@ -1563,89 +1535,6 @@ RowLayout { } } - // ============================ KNOWN FIXES DIALOG ======================= - PsDialog { - id: fixesDialog - objectName: "fixesDialog" - width: 680 - title: "Known fixes" - subtitle: (library.selected.name || "") + " · adds to the launch options, saved when you press Save to Steam" - - ColumnLayout { - width: parent.width - spacing: Theme.space - - Text { - Layout.fillWidth: true - visible: fixes.fixes.length === 0 - text: "No known fixes for this game yet." - color: Theme.faint - font.family: Theme.fontFamily; font.pixelSize: Theme.fsSmall - } - - ListView { - Layout.fillWidth: true - Layout.preferredHeight: Math.min(Math.max(contentHeight, 40), 320) - clip: true; spacing: 8 - model: fixes.fixes - boundsBehavior: Flickable.StopAtBounds - ScrollBar.vertical: ScrollBar {} - delegate: Rectangle { - required property var modelData - width: ListView.view.width - implicitHeight: fxCol.implicitHeight + 2 * Theme.spaceSm - radius: Theme.radiusSm - color: Theme.bgDeep - border.color: Theme.border; border.width: 1 - ColumnLayout { - id: fxCol - anchors.fill: parent - anchors.margins: Theme.spaceSm - spacing: 3 - RowLayout { - Layout.fillWidth: true - Text { - Layout.fillWidth: true - text: modelData.title - color: Theme.text - font.family: Theme.fontFamily; font.pixelSize: Theme.fsSmall; font.weight: Font.DemiBold - } - Rectangle { - implicitWidth: srcLbl.implicitWidth + 12; implicitHeight: 16; radius: 8 - color: Theme.surfaceElevated - Text { id: srcLbl; anchors.centerIn: parent; text: modelData.source; color: Theme.muted; font.pixelSize: 9; font.family: Theme.fontFamily } - } - PsButton { - text: "Add to launch options"; primary: false - enabled: launch.loaded - onClicked: { launch.appendPreset(modelData.snippet); fixesDialog.close() } - } - } - Text { - Layout.fillWidth: true - text: modelData.description - wrapMode: Text.WordWrap - color: Theme.muted - font.family: Theme.fontFamily; font.pixelSize: Theme.fsCaption - } - Text { - text: modelData.snippet - color: Theme.primaryBright - font.family: Theme.monoFamily; font.pixelSize: 10 - } - } - } - } - Text { - Layout.fillWidth: true - visible: !launch.loaded - text: "The launch options are still loading. Fixes can be added once they are." - color: Theme.faint; wrapMode: Text.WordWrap - font.family: Theme.fontFamily; font.pixelSize: Theme.fsCaption - } - } - } - // ============================ PROFILES DIALOG ========================== PsDialog { id: profilesDialog @@ -1913,166 +1802,18 @@ RowLayout { } } - // ============================ LAUNCH CHECK DIALOG ======================= - PsDialog { - id: launchCheckDialog - objectName: "launchCheckDialog" - width: 660 - title: "Launch check" - subtitle: (library.selected.name || "") + " · the usual reasons a game won't start" - - // one chime when a run finishes - property bool wasRunning: false - Connections { - target: launchCheck - function onChanged() { - if (launchCheckDialog.wasRunning && !launchCheck.running && launchCheckDialog.opened) { - var worst = "ok" - for (var i = 0; i < launchCheck.findings.length; i++) { - var l = launchCheck.findings[i].level - if (l === "error") worst = "error" - else if (l === "warn" && worst !== "error") worst = "warn" - } - sounds.play(worst === "error" ? "error" : (worst === "warn" ? "notification" : "success")) - } - launchCheckDialog.wasRunning = launchCheck.running - } - } - - ColumnLayout { - width: parent.width - spacing: Theme.space - - RowLayout { - Layout.fillWidth: true - spacing: Theme.spaceSm - BusyIndicator { - running: launchCheck.running; visible: launchCheck.running - implicitWidth: 20; implicitHeight: 20 - } - Text { - Layout.fillWidth: true - wrapMode: Text.WordWrap - text: launchCheck.running ? "Checking…" : launchCheck.summary - color: launchCheck.running ? Theme.muted - : (launchCheck.hasProblems ? Theme.text : Theme.success) - font.family: Theme.fontFamily - font.pixelSize: Theme.fsBody - font.weight: Font.DemiBold - } - } - Text { - Layout.fillWidth: true - visible: detailCard.isSteam && launch.dirty - wrapMode: Text.WordWrap - text: "This checks the launch options saved in Steam. Your unsaved edits are not included." - color: Theme.warning - font.family: Theme.fontFamily - font.pixelSize: Theme.fsCaption - } - - ListView { - Layout.fillWidth: true - Layout.preferredHeight: Math.min(Math.max(contentHeight, 40), 380) - clip: true - spacing: 6 - model: launchCheck.findings - boundsBehavior: Flickable.StopAtBounds - ScrollBar.vertical: ScrollBar {} - delegate: Rectangle { - id: findingRow - required property var modelData - readonly property color tone: page.levelColor(modelData.level) - width: ListView.view.width - implicitHeight: findingCol.implicitHeight + 2 * Theme.spaceSm - radius: Theme.radiusSm - color: Theme.bgDeep - border.width: 1 - border.color: (modelData.level === "error" || modelData.level === "warn") ? tone : Theme.border - Accessible.role: Accessible.ListItem - Accessible.name: modelData.level + ": " + modelData.title - Accessible.description: modelData.detail + " " + modelData.fix - RowLayout { - anchors.fill: parent - anchors.margins: Theme.spaceSm - spacing: Theme.spaceSm - Rectangle { - Layout.alignment: Qt.AlignTop - implicitWidth: 20; implicitHeight: 20; radius: 10 - color: "transparent" - border.width: 1 - border.color: findingRow.tone - Text { - anchors.centerIn: parent - text: page.levelGlyph(findingRow.modelData.level) - color: findingRow.tone - font.family: Theme.fontFamily - font.pixelSize: 11 - font.bold: true - } - } - ColumnLayout { - id: findingCol - Layout.fillWidth: true - spacing: 2 - Text { - Layout.fillWidth: true - text: findingRow.modelData.title - wrapMode: Text.WordWrap - color: Theme.text - font.family: Theme.fontFamily - font.pixelSize: Theme.fsSmall - font.weight: Font.DemiBold - } - Text { - Layout.fillWidth: true - visible: findingRow.modelData.detail.length > 0 - text: findingRow.modelData.detail - wrapMode: Text.Wrap - color: Theme.muted - font.family: Theme.fontFamily - font.pixelSize: Theme.fsCaption - } - Text { - Layout.fillWidth: true - visible: findingRow.modelData.fix.length > 0 - text: "What to do: " + findingRow.modelData.fix - wrapMode: Text.Wrap - color: Theme.text - font.family: Theme.fontFamily - font.pixelSize: Theme.fsCaption - } - } - } - } - } - - RowLayout { - Layout.fillWidth: true - spacing: Theme.spaceSm - Text { - Layout.fillWidth: true - wrapMode: Text.WordWrap - text: "Checks files and settings on this PC. It does not start the game." - color: Theme.faint - font.family: Theme.fontFamily - font.pixelSize: Theme.fsCaption - } - PsButton { - text: "Proton log…"; primary: false - visible: detailCard.isSteam - onClicked: { - launchCheckDialog.close() - protonLog.open(library.selected.appId) - protonLogDialog.open() - } - } - PsButton { - text: "Check again" - enabled: !launchCheck.running - onClicked: page.runLaunchCheck() - } - } + // ============================ DIAGNOSE DIALOG =========================== + DiagnoseDialog { + id: diagnoseDialog + controller: diagnose + soundPlayer: sounds + game: library.selected + launchDirty: launch.dirty + protondbTier: (library.selected.source === "steam" && protondb.enabled && protondb.loaded) ? protondb.tierLabel : "" + onOpenLogRequested: { + diagnoseDialog.close() + protonLog.open(library.selected.appId) + protonLogDialog.open() } } From cd235a84ed5ce969d97a98da0b793028723aebd5 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 23:32:51 -0600 Subject: [PATCH 15/20] fix: Diagnose wording - old build names, a shorter log row, evidence wraps at words A game still set to proton_9_0 was told the build was "no longer installed" and to reinstall it. Steam never had that name; an older ProtonShift wrote it. The finding says so. The row that states which log was read repeated the path in its sentence and again as evidence. Evidence lines now wrap at word boundaries when they can. Co-Authored-By: Claude Fable 5.2 --- protonshift/core/diagnose.py | 6 +++--- protonshift/core/launch_check.py | 17 ++++++++++++++--- protonshift/qml/DiagnoseDialog.qml | 2 +- tests/test_diagnose.py | 3 ++- tests/test_launch_check.py | 11 +++++++++++ 5 files changed, 31 insertions(+), 8 deletions(-) diff --git a/protonshift/core/diagnose.py b/protonshift/core/diagnose.py index 08edc85..e3412b1 100644 --- a/protonshift/core/diagnose.py +++ b/protonshift/core/diagnose.py @@ -327,10 +327,10 @@ def _log_rows(facts: Facts, rule_matched_log: bool) -> list[Finding]: )] rows: list[Finding] = [] - where = facts.log_path or "the Proton log" + # The path is the row's evidence; repeating it in the sentence only made the row longer. when = f", last written {facts.log_modified}" if facts.log_modified else "" - cause = (f"Diagnose read the end of {where}{when}. If the game has failed since then, run it again and " - "diagnose again so the log is current.") + cause = (f"Diagnose read the end of the Proton log{when}. If the game has failed since then, run it " + "again and diagnose again so the log is current.") if readable and not logging_on: cause += " Logging is off now, so this log is from an earlier run." title = "Read the Proton log" diff --git a/protonshift/core/launch_check.py b/protonshift/core/launch_check.py index a550605..7119dd3 100644 --- a/protonshift/core/launch_check.py +++ b/protonshift/core/launch_check.py @@ -50,6 +50,10 @@ } +# Names an older ProtonShift wrote for Valve's builds; Steam's are proton_9, not proton_9_0. +_OLD_BUILTIN_NAME_RE = re.compile(r"proton_[0-9]+_0") + + def finding( level: str, title: str, @@ -201,10 +205,17 @@ def check_launch( # --- compatibility tool --- tools = set(available_tools) if compat_tool and compat_tool not in tools: + if _OLD_BUILTIN_NAME_RE.fullmatch(compat_tool): + # ProtonShift up to 1.3.2 offered Valve's builds under names Steam never used + # (proton_9_0 for proton_9), so there is nothing to reinstall: the name itself is wrong. + detail = ("Steam has no build with this name. Older versions of ProtonShift wrote it by mistake, " + "so Steam can't start the game with it.") + fix = "Pick the build you want under Proton version, or let Steam choose with its default." + else: + detail = "It is still selected for this game but is no longer installed, so Steam can't start the game." + fix = "Pick another build under Proton version, or reinstall this one from the Proton builds tab." out.append(finding( - "error", f"The chosen Proton build is gone: {compat_tool}", - "It is still selected for this game but is no longer installed, so Steam can't start the game.", - "Pick another build under Proton version, or reinstall this one from the Proton builds tab.", + "error", f"The chosen Proton build is gone: {compat_tool}", detail, fix, id="proton-gone", actions=(Action("default_proton"),), )) diff --git a/protonshift/qml/DiagnoseDialog.qml b/protonshift/qml/DiagnoseDialog.qml index f4c813a..31518e8 100644 --- a/protonshift/qml/DiagnoseDialog.qml +++ b/protonshift/qml/DiagnoseDialog.qml @@ -153,7 +153,7 @@ PsDialog { readOnly: true selectByMouse: true activeFocusOnTab: false - wrapMode: TextEdit.WrapAnywhere + wrapMode: TextEdit.Wrap color: mono.quiet ? Theme.faint : Theme.text selectionColor: Theme.primary selectedTextColor: Theme.onPrimary diff --git a/tests/test_diagnose.py b/tests/test_diagnose.py index fe0754e..45ea298 100644 --- a/tests/test_diagnose.py +++ b/tests/test_diagnose.py @@ -389,7 +389,8 @@ def test_a_log_says_which_and_when() -> None: launch_options="PROTON_LOG=1 %command%") (row,) = log_rows(f) assert row.id == "log-read" and row.severity == "context" - assert "/home/u/steam-100.log" in row.cause and "2026-11-16 01:23" in row.cause + # The path is the evidence; the sentence names only when the log was written. + assert "/home/u/steam-100.log" not in row.cause and "2026-11-16 01:23" in row.cause assert "2026-11-16 01:23" in row.title assert row.evidence == "/home/u/steam-100.log" assert "earlier run" not in row.cause diff --git a/tests/test_launch_check.py b/tests/test_launch_check.py index bf6f78a..785cdfc 100644 --- a/tests/test_launch_check.py +++ b/tests/test_launch_check.py @@ -228,3 +228,14 @@ def test_read_tail(tmp_path: Path) -> None: def test_read_tail_missing_file(tmp_path: Path) -> None: with pytest.raises(OSError): proton_log.read_tail(tmp_path / "absent.log") + + +def test_old_protonshift_build_name_is_explained_not_called_uninstalled(tmp_path): + # proton_9_0 is a name ProtonShift up to 1.3.2 wrote; Steam's is proton_9. + rows = run(tmp_path, compat_tool="proton_9_0", available_tools=["", "proton_9"]) + gone = next(f for f in rows if f["id"] == "proton-gone") + assert "Older versions of ProtonShift" in gone["detail"] + assert "reinstall" not in gone["fix"] + removed = next(f for f in run(tmp_path, compat_tool="GE-Proton9-1", available_tools=[""]) + if f["id"] == "proton-gone") + assert "no longer installed" in removed["detail"] From 37c3e316c8be59c00362d5d90353b2ae0c7ab706 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 23:36:27 -0600 Subject: [PATCH 16/20] fix: a Proton build name Steam never had is not called "gone" Co-Authored-By: Claude Fable 5.2 --- protonshift/core/launch_check.py | 4 +++- tests/test_launch_check.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/protonshift/core/launch_check.py b/protonshift/core/launch_check.py index 7119dd3..3976e4b 100644 --- a/protonshift/core/launch_check.py +++ b/protonshift/core/launch_check.py @@ -211,11 +211,13 @@ def check_launch( detail = ("Steam has no build with this name. Older versions of ProtonShift wrote it by mistake, " "so Steam can't start the game with it.") fix = "Pick the build you want under Proton version, or let Steam choose with its default." + title = f"Steam has no Proton build named {compat_tool}" else: detail = "It is still selected for this game but is no longer installed, so Steam can't start the game." fix = "Pick another build under Proton version, or reinstall this one from the Proton builds tab." + title = f"The chosen Proton build is gone: {compat_tool}" out.append(finding( - "error", f"The chosen Proton build is gone: {compat_tool}", detail, fix, + "error", title, detail, fix, id="proton-gone", actions=(Action("default_proton"),), )) diff --git a/tests/test_launch_check.py b/tests/test_launch_check.py index 785cdfc..f1a508b 100644 --- a/tests/test_launch_check.py +++ b/tests/test_launch_check.py @@ -234,7 +234,7 @@ def test_old_protonshift_build_name_is_explained_not_called_uninstalled(tmp_path # proton_9_0 is a name ProtonShift up to 1.3.2 wrote; Steam's is proton_9. rows = run(tmp_path, compat_tool="proton_9_0", available_tools=["", "proton_9"]) gone = next(f for f in rows if f["id"] == "proton-gone") - assert "Older versions of ProtonShift" in gone["detail"] + assert "Older versions of ProtonShift" in gone["detail"] and "gone" not in gone["title"] assert "reinstall" not in gone["fix"] removed = next(f for f in run(tmp_path, compat_tool="GE-Proton9-1", available_tools=[""]) if f["id"] == "proton-gone") From d67d16e2225922c51519c5bd2bbf8e894defb550 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 23:38:54 -0600 Subject: [PATCH 17/20] docs: Diagnose in the changelog, README, architecture and store description The README's lead feature is now Diagnose; the Launch check and fixes database sections are gone with the features. The System section no longer claims live temperatures: GPU data is read at start and on Refresh. The store description listed four things and left out most of what the app does. Co-Authored-By: Claude Fable 5.2 --- ARCHITECTURE.md | 44 ++++++++++++++- CHANGELOG.md | 54 +++++++++++++++++++ README.md | 34 ++++++------ ...io.github.i4ctime.protonshift.metainfo.xml | 9 ++-- 4 files changed, 120 insertions(+), 21 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 682959f..e19a00b 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -33,7 +33,8 @@ Roughly one module per integration or feature: - **Config editors**: `gamescope.py` (command building), `mangohud.py`, `scopebuddy.py`, `env_vars.py`, `vdf_config.py` (Steam launch options), `launch_merge.py` (places a snippet around `%command%` instead of - appending it). + appending it, plus the single edits a Diagnose fix makes: set or unset a + variable, add a game argument, remove a wrapper word). - **System**: `display.py` (xrandr/wlr-randr/kscreen-doctor), `gpu.py` (nvidia-smi/sysfs + power profiles), `input_devices.py` (gamepad detection, SDL mapping, force-feedback rumble via raw `ioctl`/`struct` packing), @@ -101,6 +102,42 @@ example): exception-routing behavior is covered by a plain pytest test with no Qt runtime involved. +### Diagnose flow + +`DiagnoseController` follows the same pattern, with the reading and the +writing kept apart: + +1. **Collect on a worker.** `run` starts `diagnose.collect`, which reads + Steam's config, the Proton log tail, the system checks (host commands go + through `host_run`), the bundled fix pack and the user's fixes, and passes + a `Facts` to the pure `diagnose()`, which ranks the findings. Each run + carries a token; a result from an older run or another game is dropped. +2. **Plan, pure.** "Fix this" calls `fix_apply.plan(actions, state)` on the + GUI thread. It reads nothing and returns the before and after `GameState` + (launch options and compatibility tool), which the dialog shows. +3. **Snapshot, then write.** Apply plans again on a worker and calls + `apply_change`, which re-reads Steam's files and refuses if they no longer + match the plan's `before`, records a snapshot + (`~/.config/protonshift/snapshots/.json`, last 20 per game) and + writes nothing if that fails, then writes `localconfig.vdf` and + `config.vdf`, putting the first back if the second write fails. +4. **Undo.** `undo_latest` writes the latest snapshot's `before` back and + drops it. If the settings are neither that snapshot's `before` nor its + `after`, someone changed them since, and it refuses unless forced. + Snapshots are on disk, so Undo survives a restart. + +After a write, `settingsWritten` makes `app.py` reload the launch options +editor and the diagnosis runs again. Non-Steam shortcuts get findings but no +apply: there is no writer for the binary `shortcuts.vdf`. + +The fix pack (`core/data/fix_pack.json`) is data, not code. Its actions are +a closed set (set or unset one variable, add one game argument, remove one +wrapper word, use Steam's default Proton, or an instruction for the user), +so no rule can put free text into launch options, which Steam hands to a +shell. The format, the loader's limits and how to add a rule are in +[docs/fix-pack.md](docs/fix-pack.md); `tests/test_fix_pack.py` enforces them +for the bundled pack. + ## `qml/` - pages and design system `qml/App/` is a local QML module (see `qmldir`) providing: @@ -163,7 +200,10 @@ runtime: - `test_core_safety.py` - path-traversal, command-injection, tolerant-decoding, and fail-closed-write regressions across `shader_cache`, `scopebuddy`, - `heroic_config`, `saves`, `vdf_config`. + `heroic_config`, `saves`, `vdf_config`, and the fix pack's action limits. +- `test_fix_pack.py` and `test_fix_pack_rules.py` - the pack loader against + [docs/fix-pack.md](docs/fix-pack.md), and a real sample line for every log + rule plus lines from healthy runs that no rule may match. - `test_input_devices_structs.py` - pins the 64-bit kernel force-feedback ABI (`struct ff_effect` layout, `input_event` size) that `input_devices.py` packs by hand. diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ff3c40..d81b9d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,60 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- **Diagnose** (Library, Per-game tools). One list of what is wrong with a + game, ranked as "Stops the game from starting", "Probably the cause", + "Worth trying", "For context" and "Checked and fine". It looks at the + game's launch options, its Proton build, its install folder, the end of its + Proton log, this PC (a working Vulkan driver, a 32-bit Vulkan driver, free + space on the drives holding the game and its prefix) and a pack of 26 rules + that ships with the app: 18 recognise a line in the Proton log, 6 look at + launch options, and 2 are tweaks for one game. Each finding shows the log + line or the setting it is based on, and a rule from the pack links to where + its knowledge comes from. A check that could not run says so instead of + reporting the PC as fine. With no Proton log, Diagnose offers to turn + logging on. It reads files and settings only and never starts the game. +- **Fix this, and Undo.** "Fix this" shows the launch options and Proton + build before and after, then applies the change in one click. A snapshot is + saved first, and if that fails nothing is written. Undo puts back the last + fix, also after restarting the app, and asks before overwriting changes + made since. Diagnose warns when Steam is running, because Steam rewrites + its settings when it closes and a fix applied now can be lost, and when the + launch options editor has unsaved changes. +- Diagnose works for Steam games and Non-Steam shortcuts. For a shortcut it + shows the findings and a "Copy new launch options" button but cannot apply + a fix, because ProtonShift cannot write Steam's shortcuts file. Heroic and + Lutris games are not covered yet, and the rule pack does not update by + itself yet; new rules arrive with app updates. + +### Changed +- The game pane's "Launch check" and "Known fixes…" buttons are replaced by + the one "Diagnose" button. Every check Launch check made is now a finding in + Diagnose. "Proton log…" stays, and Diagnose has an "Open log" button. +- Your own fixes under `~/.config/protonshift/fixes/` still load. They show + in Diagnose under "Worth trying", marked "yours". + +### Removed +- **The 14 built-in known fixes**, because on checking, none was both + sourced and still correct: several had no source, some used variable + names Proton does not document or no longer reads, two put a game argument + in front of `%command%`, and one turned on BattlEye for a game that does + not use it. Cyberpunk 2077 and Elden Ring get a sourced tweak in the new + rule pack instead. +- The five switches the old Known fixes dialog listed for every game + (disable esync, disable fsync, Proton log, WineD3D, NVAPI), because they + are not fixes for anything Diagnose can detect. Proton logging is still a + launch-option preset, and Diagnose offers it when there is no log. + +### Fixed +- **The Proton version picker used names Steam does not know.** It offered + Valve's builds as `proton_9_0`, `proton_8_0` and `proton_7_0`, but Steam + calls them `proton_9`, `proton_8` and `proton_7`. Choosing one wrote a + build Steam did not recognise, and Launch check called a game on a real + Valve build "gone". The picker now lists Steam's own names, including + Proton 10, Proton 11 and Proton Hotfix. A game still set to an old name + gets a finding in Diagnose with a one-click fix back to Steam's default. + ## [1.3.2] - 2026-10-13 ### Fixed diff --git a/README.md b/README.md index b47e004..9c58808 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,21 @@ locally from the manifest; full variants and options are in ## Features +### Diagnose + +One button per game that lists what is wrong with it, most serious first: +"Stops the game from starting", "Probably the cause", "Worth trying", "For +context" and "Checked and fine". It looks at the game's launch options, +Proton build and install folder, the end of its Proton log, this PC (Vulkan, +a 32-bit Vulkan driver, free disk space) and a bundled pack of 26 rules, each +linked to where its knowledge comes from. Every finding shows the log line or +setting behind it. "Fix this" shows the launch options and Proton build +before and after, saves a snapshot, then applies the change; Undo puts it +back, also after a restart. Diagnose reads files and settings only and never +starts the game. It covers Steam games and Non-Steam shortcuts; for a +shortcut it copies the new launch options instead of writing them. The rule +format is in [docs/fix-pack.md](docs/fix-pack.md). + ### Your entire library, unified Pulls games from **Steam** (including Non-Steam shortcuts you added by hand), @@ -83,14 +98,6 @@ if the underlying tool isn't found. Snippets are placed around `%command%` for you, so a preset never ends up as a stray game argument, and switching games with unsaved edits asks before dropping them. -### Launch check - -One button per game that lists the usual reasons it won't start, each with -what to do about it: launch options with no `%command%` (or two), wrapper -tools that aren't installed, a Proton build that was removed, a missing -anti-cheat runtime, a missing install folder, and ProtonDB's rating as -context. It reads files and settings only; it never starts the game. - ### Proton log viewer Turn on Proton's debug log for a game and read it in the app: the end of @@ -174,12 +181,6 @@ a different one. Export all profiles (or one) to a JSON bundle and import it on another machine; imports are validated entry by entry and never overwrite an existing profile unless you ask. -### Game-specific fixes database - -A built-in, extensible database of known fixes (environment variables and/or -launch arguments) matched per App ID or applied universally, with one-click -apply. User-contributed fixes live under `~/.config/protonshift/fixes/`. - ### Protontricks Run Protontricks without leaving the app - open its GUI for a game, or @@ -187,8 +188,9 @@ quick-run common verbs. Supports native and Flatpak Protontricks installs. ### System info & display management -GPU detection (NVIDIA via `nvidia-smi`, AMD/Intel via sysfs) with live temps, -power-profile switching (`system76-power`, `power-profiles-daemon`), and +GPU detection, read when the app starts and on Refresh (NVIDIA via +`nvidia-smi` with name, driver, VRAM and temperature; AMD/Intel via sysfs +with the kernel driver and temperature), power-profile switching (`system76-power`, `power-profiles-daemon`), and per-monitor resolution/refresh-rate control over `xrandr`, `hyprctl`, `wlr-randr`, or `kscreen-doctor`, depending on your session. A mode change asks "keep it?" and goes back on its own after 15 seconds if you don't. diff --git a/flatpak/io.github.i4ctime.protonshift.metainfo.xml b/flatpak/io.github.i4ctime.protonshift.metainfo.xml index e9bd070..35c7b7d 100644 --- a/flatpak/io.github.i4ctime.protonshift.metainfo.xml +++ b/flatpak/io.github.i4ctime.protonshift.metainfo.xml @@ -14,10 +14,13 @@ UI for the things that usually mean editing config files by hand:

    +
  • Diagnose a game that won't start: one ranked list of findings from its settings, its Proton log, your PC and a bundled set of rules, with fixes you can preview and undo
  • +
  • Read a game's Proton log, filtered to the lines that look like problems
  • +
  • Install and remove GE-Proton builds, and pick the Proton build for each game
  • Build gamescope launch commands (resolution, FSR, HDR, frame limits)
  • -
  • Manage MangoHud overlays
  • -
  • Wrap games with ScopeBuddy
  • -
  • Inspect Proton prefixes and per-game settings
  • +
  • Manage MangoHud overlays and wrap games with ScopeBuddy
  • +
  • Save a game's settings as a profile and apply it to any game
  • +
  • Inspect Proton prefixes and shader caches, and back up saves

Built with Qt Quick and Python. Runs well on the desktop and on the From 809b615c18119a7192ac31589e159d83a1bd2087 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 16 Nov 2026 23:38:54 -0600 Subject: [PATCH 18/20] docs: CLAUDE.md - the fix pack limits and the snapshot id are security boundaries Co-Authored-By: Claude Fable 5.2 --- CLAUDE.md | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 8f5a9a6..513cc51 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -56,8 +56,21 @@ is conventions and constraints only. unvalidated key would be persistent command injection into that shell. `write_scb_conf` raises before writing a byte if any key fails this check. Keep it that way. -- If you touch either regex, add/update the corresponding case in - `tests/test_core_safety.py` in the same change. +- `core/fix_pack.py`'s action limits (`_KEY_RE`, `_ENV_VALUE_RE`, + `_GAME_ARG_RE`, `_WORD_RE`, the forbidden-variable list) are load-bearing: + Diagnose writes a rule's actions into Steam launch options, and Steam hands + those to a shell at every launch, so a looser pattern is command injection + by data file. `core/fix_apply.plan` holds the user's own fixes to the same + value limits. `docs/fix-pack.md` is the contract for the format; change it + first, in its own commit, then the code. +- `core/snapshots.py`'s `app_id` check (decimal digits only, plus + `validate_within`) is the same kind of boundary as the shader cache's: the + id becomes a file name. Entries holding a newline or NUL are dropped on + read as well as refused on write, because Undo writes them into Steam's + config. +- If you touch any of these, add/update the corresponding case in + `tests/test_core_safety.py` (`tests/test_snapshots.py` for the snapshot + store) in the same change. ## Conventions From e6893f7c2d594c3a09b9463df6d97d384af17883 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 17 Nov 2026 00:12:29 -0600 Subject: [PATCH 19/20] docs: fix pack - three limits the code review showed were too loose or wrong A repeat may now only repeat a single character or class: the nested repeat rule let a repeated alternation with overlapping branches through, and that backtracks exponentially. A pack may only set variables from named families. A list of forbidden names missed BASH_ENV, GCONV_PATH and others, and can never be complete. The user's own fixes were documented as free of the value limits but the code refused them, which broke values such as WINEDLLOVERRIDES. They are written single-quoted now, and the doc says what is still refused. Co-Authored-By: Claude Fable 5.2 --- CLAUDE.md | 8 +++++--- docs/fix-pack.md | 49 ++++++++++++++++++++++++++++++++---------------- 2 files changed, 38 insertions(+), 19 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 513cc51..fff5b74 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -60,9 +60,11 @@ is conventions and constraints only. `_GAME_ARG_RE`, `_WORD_RE`, the forbidden-variable list) are load-bearing: Diagnose writes a rule's actions into Steam launch options, and Steam hands those to a shell at every launch, so a looser pattern is command injection - by data file. `core/fix_apply.plan` holds the user's own fixes to the same - value limits. `docs/fix-pack.md` is the contract for the format; change it - first, in its own commit, then the code. + by data file. A pack may only set variables from a short list of name + families; the user's own fixes may set any variable, and `core/fix_apply` + writes their values single-quoted and refuses what quoting cannot make + safe. `docs/fix-pack.md` is the contract for the format; change it first, + in its own commit, then the code. - `core/snapshots.py`'s `app_id` check (decimal digits only, plus `validate_within`) is the same kind of boundary as the shader cache's: the id becomes a file name. Entries holding a newline or NUL are dropped on diff --git a/docs/fix-pack.md b/docs/fix-pack.md index 258358e..c36c111 100644 --- a/docs/fix-pack.md +++ b/docs/fix-pack.md @@ -100,13 +100,15 @@ is not a rule. when any one of them is found in any single line of the log tail. Each expression must compile, must be at most 300 characters, and must contain at least 8 literal characters in a row, so that it is anchored on real text - and not on a pattern that fits half the log. An expression must not repeat - a group that itself contains a repeat (for example `(a+)+`), and may hold - at most two open-ended repeats (`*`, `+`, `{n,}`), because such patterns - can take a very long time on a long line. An optional group (`?`) does not - count as repeating what is inside it. Inline flags, back-references and - conditionals are not allowed. Matching is case sensitive, and only the - first 2000 characters of a line are looked at. + and not on a pattern that fits half the log. A repeat (`*`, `+`, `{n}`, + `{n,m}`, `{n,}`) may only repeat a single character, an escaped character, + a character class or `.`: `.+`, `\S+` and `[0-9a-f]{7}` are fine, a + repeated group such as `(a+)+` or `(?:ab|abab)+` is not. An expression may + hold at most two open-ended repeats (`*`, `+`, `{n,}`). Both limits are + there because such patterns can take a very long time on a long line. An + optional group (`(?:...)?`) is allowed; it is not a repeat. Inline flags, + back-references and conditionals are not allowed. Matching is case + sensitive, and only the first 2000 characters of a line are looked at. What counts toward the 8 literal characters: plain and escaped characters (`\.`), also through a group that is not repeated. A character class, `.`, @@ -179,10 +181,17 @@ Limits, enforced by the loader: appears, also inside an assignment. - A rule has at most 6 actions. No action is listed twice, and no two actions of one rule touch the same variable. -- These variables may never be set or unset by a rule, because they decide - what code a process loads or runs: `LD_PRELOAD`, `LD_LIBRARY_PATH`, - `LD_AUDIT`, `PATH`, `PYTHONPATH`, `STEAM_COMPAT_LAUNCHER_SERVICE`, - `WINEDLLPATH`, and any name starting with `STEAM_COMPAT_`. +- A rule may only set (`env`) a variable whose name starts with one of + `PROTON_`, `WINE_`, `DXVK_`, `VKD3D_`, `MESA_`, `RADV_`, `__GL_`, `__NV_`, + `SDL_` or `MANGOHUD`. These are the families that tune Proton, Wine, the + graphics drivers and the overlay. A list of forbidden names can never be + complete, so setting anything else is refused: a variable ProtonShift does + not know may decide what code a process loads. +- Inside those families, and for `unset_env` with any name, these may never + be set or unset, because they decide what code a process loads or runs: + `PROTON_REMOTE_DEBUG_CMD`, `SDL_DYNAMIC_API`, `LD_PRELOAD`, + `LD_LIBRARY_PATH`, `LD_AUDIT`, `PATH`, `PYTHONPATH`, `WINEDLLPATH`, + `WINEDLLOVERRIDES`, and any name starting with `STEAM_COMPAT_`. A game argument can only be placed after `%command%`; there is no action that puts text in front of it other than `env`. This is by construction, so a @@ -199,11 +208,19 @@ version 1 entries: `type` is `env` (uses `key` and `value`) or `launch_arg` (uses `value`). Each entry is shown in Diagnose as an `advice` finding marked as the user's -own. A user entry is the user's own text on the user's own machine, so its -value is not held to the character limits above; the key still must match -the key pattern, and the change is still shown before it is applied. A -`launch_arg` value that contains `%command%` is merged the way the app merges -any snippet; one without it is treated as game arguments. +own. An entry with no `type` is read as `env`, as version 1 did. + +A user entry is the user's own text on the user's own machine, so it is not +held to the pack's limits: any variable name that matches the key pattern may +be set, and the value may hold spaces and punctuation +(`WINEDLLOVERRIDES=d3d9=n;dinput8=n,b`). ProtonShift writes such a value in +single quotes so the shell takes it as one word and runs none of it. Three +things are still refused, because quoting cannot make them safe: a value +with a single quote, with a line break or NUL, or with `%command%` (Steam +replaces that before the shell sees the line). The change is shown before it +is applied, like any other. A `launch_arg` value that contains `%command%` +is merged the way the app merges any snippet; one without it is treated as +game arguments. ## Adding a rule From 91ceb640859cdbde17590d82f2dd82fcc06cae1b Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 17 Nov 2026 00:29:27 -0600 Subject: [PATCH 20/20] fix: Diagnose - the ten findings from the code review of #93 A one-click fix must not leave the game broken. Adding a missing %command% put it after a wrapper's name, so its options became game arguments (strangle 60 -> strangle %command% 60). It now goes after the options of the wrappers that take them, after -- for gamescope and ScopeBuddy, and straight after commands that take none. Diagnose called a game set to a Steam Linux Runtime tool a missing Proton build, a native Linux game a Proton game, and a missing host driver a blocker for Flatpak Steam, which brings its own. All three now say what is true. Undo and Proton-only fixes replaced unsaved launch-option edits without a word; the editor text is kept unless the launch options changed, and Undo warns first. A write that failed twice no longer deletes the record that Undo needs. A shortcut with a missing Proton build is pointed to the picker, not told the fix is in place. The pack's limits were looser than the contract claimed. A repeat may only repeat one character or class (a repeated alternation backtracked exponentially), and a rule may only set variables from named families (the forbidden list missed BASH_ENV and others). The user's own fixes were refused for values the docs allowed; they are written single-quoted and only what quoting cannot hold is refused. The two per-game tweaks stop being offered once applied. Co-Authored-By: Claude Fable 5.2 --- ARCHITECTURE.md | 21 +- protonshift/app.py | 9 +- .../controllers/diagnose_controller.py | 70 +++--- protonshift/controllers/launch_controller.py | 22 +- protonshift/core/compat_tool.py | 10 + protonshift/core/data/fix_pack.json | 14 +- protonshift/core/diagnose.py | 95 +++++++- protonshift/core/fix_apply.py | 141 +++++++++--- protonshift/core/fix_pack.py | 81 ++++--- protonshift/core/fixes.py | 27 --- protonshift/core/launch_check.py | 21 +- protonshift/core/launch_merge.py | 94 ++++++-- protonshift/core/system_checks.py | 26 ++- protonshift/qml/DiagnoseDialog.qml | 19 ++ tests/test_core_safety.py | 67 +++++- tests/test_diagnose.py | 127 ++++++++++- tests/test_fix_apply.py | 214 ++++++++++++++++-- tests/test_fix_pack.py | 58 ++++- tests/test_fix_pack_rules.py | 27 ++- tests/test_launch_check.py | 36 ++- tests/test_launch_merge.py | 65 ++++++ tests/test_system_checks.py | 36 +++ 22 files changed, 1060 insertions(+), 220 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index e19a00b..74fe7bd 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -112,22 +112,27 @@ writing kept apart: through `host_run`), the bundled fix pack and the user's fixes, and passes a `Facts` to the pure `diagnose()`, which ranks the findings. Each run carries a token; a result from an older run or another game is dropped. -2. **Plan, pure.** "Fix this" calls `fix_apply.plan(actions, state)` on the - GUI thread. It reads nothing and returns the before and after `GameState` +2. **Plan, pure.** "Fix this" calls `fix_apply.plan(actions, state, user=...)` + on the GUI thread (`user` for the user's own fixes, which may set any + variable, single-quoted; everything else is held to the pack's limits). + It reads nothing and returns the before and after `GameState` (launch options and compatibility tool), which the dialog shows. 3. **Snapshot, then write.** Apply plans again on a worker and calls `apply_change`, which re-reads Steam's files and refuses if they no longer match the plan's `before`, records a snapshot (`~/.config/protonshift/snapshots/.json`, last 20 per game) and writes nothing if that fails, then writes `localconfig.vdf` and - `config.vdf`, putting the first back if the second write fails. + `config.vdf`, putting the first back if the second write fails. The + snapshot is dropped after a failed write only when the files read back as + `before`; otherwise it stays for Undo. 4. **Undo.** `undo_latest` writes the latest snapshot's `before` back and - drops it. If the settings are neither that snapshot's `before` nor its - `after`, someone changed them since, and it refuses unless forced. - Snapshots are on disk, so Undo survives a restart. + drops it once the files read back as `before`. If a setting is neither + that snapshot's `before` nor its `after`, someone changed it since, and it + refuses unless forced. Snapshots are on disk, so Undo survives a restart. -After a write, `settingsWritten` makes `app.py` reload the launch options -editor and the diagnosis runs again. Non-Steam shortcuts get findings but no +After a write, `settingsWritten` makes `app.py` refresh the launch options +editor (its text only when the launch options on disk changed or nothing is +unsaved) and the diagnosis runs again. Non-Steam shortcuts get findings but no apply: there is no writer for the binary `shortcuts.vdf`. The fix pack (`core/data/fix_pack.json`) is data, not code. Its actions are diff --git a/protonshift/app.py b/protonshift/app.py index 19c06f1..d9711f5 100644 --- a/protonshift/app.py +++ b/protonshift/app.py @@ -101,9 +101,12 @@ def main() -> int: ge_proton._installFailed.connect(lambda _msg, cancelled: cancelled or sounds.chime(False)) ge_proton._removeDone.connect(lambda _name, error: sounds.chime(not error)) # A Diagnose fix or its undo chimes like a save, and the launch options - # editor re-reads Steam so it shows the line and Proton build now saved. - diagnose.settingsWritten.connect(lambda _app, ok: sounds.chime(ok)) - diagnose.settingsWritten.connect(lambda app_id, ok: ok and launch.reloadFromSteam(app_id)) + # editor re-reads Steam so it shows the Proton build now saved, and the + # line too when the write changed it (or the editor has nothing unsaved). + # Also after a failed write: part of it may have landed. + diagnose.settingsWritten.connect(lambda _app, ok, _launch_changed: sounds.chime(ok)) + diagnose.settingsWritten.connect( + lambda app_id, _ok, launch_changed: launch.reloadFromSteam(app_id, launch_changed)) # installed/removed builds should show up in the per-game Proton picker ge_proton.toolsChanged.connect(launch.reloadProton) ctx = engine.rootContext() diff --git a/protonshift/controllers/diagnose_controller.py b/protonshift/controllers/diagnose_controller.py index 2a066f5..3c1d04a 100644 --- a/protonshift/controllers/diagnose_controller.py +++ b/protonshift/controllers/diagnose_controller.py @@ -10,8 +10,9 @@ thread (``fix_apply.plan`` is pure), ``apply`` plans it again from the same report and writes it on a worker. ``apply_change`` itself refuses a plan made from settings that changed on disk since, so the user is never surprised. -After a write that worked, ``settingsWritten`` fires (``app.py`` reloads the -launch options editor and plays the chime) and the diagnosis runs again. +After a write, ``settingsWritten`` fires (``app.py`` plays the chime and +refreshes the launch options editor, whose unsaved text is replaced only when +the write changed the launch options on disk) and the diagnosis runs again. """ from __future__ import annotations @@ -26,6 +27,7 @@ from ._worker import start_worker _SEVERITIES = diagnose.SEVERITY_ORDER +_SHORTCUT_PROTON = "ProtonShift can't apply this to a shortcut from here. Pick a build under Proton version." def _when_label(taken_at: str) -> str: @@ -57,19 +59,21 @@ def _checked_line(report: diagnose.Report, shortcut: bool, native: bool) -> str: class DiagnoseController(QObject): runningChanged = Signal() - reportChanged = Signal() # findings / summary / counts / canApply / steamRunning / logPath / checked + reportChanged = Signal() # findings / summary / counts / canApply / steamRunning / checked busyChanged = Signal() statusChanged = Signal() - undoChanged = Signal() # undoAvailable / undoLabel / undoWhen / undoConflict + undoChanged = Signal() # undoAvailable / undoLabel / undoWhen / undoConflict / undoChangesLaunch previewChanged = Signal() - # A fix or its undo was written (app_id, ok). app.py chimes on it and, when - # ok, reloads the launch options editor so it shows what Steam now has. - settingsWritten = Signal(str, bool) + # A fix or its undo was written (app_id, ok, launch options changed on + # disk). app.py chimes on it and refreshes the launch options editor; its + # text is reloaded only when the launch options on disk changed, so a + # Proton-only fix keeps the user's unsaved edits. + settingsWritten = Signal(str, bool, bool) _runResult = Signal(int, object, object) # run token, Report, Snapshot | None _runError = Signal(int, str) # run token, message - _writeResult = Signal(str, object, object, bool) # app_id, ApplyResult, Snapshot | None, undo conflict + _writeResult = Signal(str, object, object) # app_id, ApplyResult, Snapshot | None _writeError = Signal(str, str) # app_id, message def __init__(self, parent: QObject | None = None) -> None: @@ -151,10 +155,6 @@ def steamRunning(self) -> str: running = self._report.steam_running if self._report else None return "unknown" if running is None else ("yes" if running else "no") - @Property(str, notify=reportChanged) - def logPath(self) -> str: - return self._report.log_path if self._report else "" - @Property(bool, notify=busyChanged) def busy(self) -> bool: """An apply or an undo is being written.""" @@ -180,6 +180,12 @@ def undoLabel(self) -> str: def undoWhen(self) -> str: return _when_label(self._undo.taken_at) if self._undo else "" + @Property(bool, notify=undoChanged) + def undoChangesLaunch(self) -> bool: + """Undo would change the launch options (so it would replace unsaved edits in the editor).""" + snap = self._undo + return snap is not None and snap.before.launch_options != snap.after.launch_options + @Property(str, notify=undoChanged) def undoConflict(self) -> str: """Why Undo refused (the settings changed after the fix); "" otherwise.""" @@ -248,7 +254,7 @@ def _on_run_result(self, token: int, report: diagnose.Report, undo: Snapshot | N self._findings = {f.id: f for f in report.findings} self._rows = [diagnose.to_row(f) for f in report.findings] self._summary = report.summary - self._checked = _checked_line(report, shortcut=args[2] is not None, native=bool(args[3])) + self._checked = _checked_line(report, shortcut=args[2] is not None, native=report.native) self._error = "" self._undo = undo self._running = False @@ -276,11 +282,11 @@ def _rerun(self) -> None: # --- preview ------------------------------------------------------------------ def _planning_state(self) -> tuple[GameState | None, str]: - """The settings a plan starts from, or ``(None, reason)`` when there are none to plan on.""" - if self._shortcut_options is not None: - # Steam keeps a shortcut's launch options in the shortcut; its Proton - # choice is not something ProtonShift can change for it. - return GameState(launch_options=self._shortcut_options, compat_tool=""), "" + """The settings a plan starts from, or ``(None, reason)`` when there are none to plan on. + + For a shortcut the report's state holds its launch options and its real + Proton build, so a "use Steam's default" fix is not planned as done. + """ if self._report is not None and self._report.state is not None: return self._report.state, "" return None, ("Steam's settings for this game could not be read, so ProtonShift cannot work out " @@ -293,7 +299,7 @@ def _plan(self, finding_id: str) -> tuple[diagnose.Finding | None, fix_apply.Cha state, reason = self._planning_state() if state is None: return finding, None, reason - return finding, fix_apply.plan(finding.actions, state), "" + return finding, fix_apply.plan(finding.actions, state, user=finding.origin == "user"), "" @Slot(str) def openPreview(self, finding_id: str) -> None: @@ -310,6 +316,7 @@ def openPreview(self, finding_id: str) -> None: "beforeProton": "", "afterProton": "", "protonChanged": False, "manual": manual, "blocked": reason, + "note": "", # a plain sentence for what the user has to do instead "changed": False, "mode": "none", # "apply" | "copy" | "none" } @@ -332,6 +339,9 @@ def openPreview(self, finding_id: str) -> None: preview["mode"] = "apply" elif self._shortcut_options is not None and launch_changed: preview["mode"] = "copy" + elif self._shortcut_options is not None and proton_changed: + # No launch line to copy; the Proton picker sets a shortcut's build. + preview["note"] = _SHORTCUT_PROTON self._preview = preview self.previewChanged.emit() @@ -376,10 +386,10 @@ def apply(self, finding_id: str) -> None: on_error=lambda message: self._writeError.emit(app_id, message)) def _apply_work(self, app_id, localconfig, config_vdf, finding, state) -> None: - change = fix_apply.plan(finding.actions, state) + change = fix_apply.plan(finding.actions, state, user=finding.origin == "user") result = fix_apply.apply_change(localconfig, config_vdf, app_id, change, label=finding.title, finding_id=finding.id) - self._writeResult.emit(app_id, result, fix_apply.undo_available(app_id), False) + self._writeResult.emit(app_id, result, fix_apply.undo_available(app_id)) @Slot(bool) def undo(self, force: bool) -> None: @@ -397,14 +407,8 @@ def undo(self, force: bool) -> None: on_error=lambda message: self._writeError.emit(app_id, message)) def _undo_work(self, app_id, localconfig, config_vdf, force: bool) -> None: - snap = fix_apply.undo_available(app_id) - current = fix_apply.read_state(localconfig, config_vdf, app_id) - # The same test undo_latest refuses on: settings that are neither the - # fix's before nor its after were changed by someone since. - conflict = (not force and snap is not None and current is not None - and current not in (snap.before, snap.after)) result = fix_apply.undo_latest(localconfig, config_vdf, app_id, force=force) - self._writeResult.emit(app_id, result, fix_apply.undo_available(app_id), conflict and not result.ok) + self._writeResult.emit(app_id, result, fix_apply.undo_available(app_id)) @Slot() def dismissUndoConflict(self) -> None: @@ -419,8 +423,8 @@ def _begin_write(self) -> None: self.busyChanged.emit() self.undoChanged.emit() - def _on_write_result(self, app_id: str, result: fix_apply.ApplyResult, undo: Snapshot | None, - conflict: bool) -> None: + def _on_write_result(self, app_id: str, result: fix_apply.ApplyResult, undo: Snapshot | None) -> None: + conflict = result.conflict self._busy = False self.busyChanged.emit() if app_id == self._app_id: @@ -429,7 +433,7 @@ def _on_write_result(self, app_id: str, result: fix_apply.ApplyResult, undo: Sna self.undoChanged.emit() if not conflict: self._set_status(result.message, result.ok) - self.settingsWritten.emit(app_id, result.ok) + self.settingsWritten.emit(app_id, result.ok, result.launch_changed) # The list has to show the settings as they are now; a plan refused # because the settings moved needs a fresh report too. if app_id == self._app_id and not conflict and (result.ok or result.state is not None): @@ -438,7 +442,9 @@ def _on_write_result(self, app_id: str, result: fix_apply.ApplyResult, undo: Sna def _on_write_error(self, app_id: str, message: str) -> None: self._busy = False self.busyChanged.emit() - self.settingsWritten.emit(app_id, False) + # Whether anything reached the disk is unknown, so the editor keeps + # unsaved text rather than losing it; its Proton choice is refreshed. + self.settingsWritten.emit(app_id, False, False) if app_id == self._app_id: self._set_status(f"Something went wrong, so the change may not be complete: {message}", False) self._rerun() diff --git a/protonshift/controllers/launch_controller.py b/protonshift/controllers/launch_controller.py index aaf543d..aa8bfa1 100644 --- a/protonshift/controllers/launch_controller.py +++ b/protonshift/controllers/launch_controller.py @@ -229,21 +229,25 @@ def reloadProton(self) -> None: """Re-read the Proton tool list (e.g. after the GE-Proton page installs a build).""" self._reload_proton() - @Slot(str) - def reloadFromSteam(self, app_id: str) -> None: - """Re-read the saved launch options and Proton choice when ``app_id`` is the game shown. - - For a change written behind the editor (a Diagnose fix or its undo): - the editor then shows what Steam has, replacing any unsaved edit. + @Slot(str, bool) + def reloadFromSteam(self, app_id: str, launch_changed: bool) -> None: + """Re-read what Steam has for ``app_id`` after a change written behind the editor. + + For a Diagnose fix or its undo. The Proton choice is always re-read. + The launch options text is re-read only when that write changed the + launch options on disk, or when the editor has no unsaved edit: a fix + that changed only the Proton build must not throw away what the user + typed. (Diagnose warns before a write that will replace it.) """ if not app_id or app_id != self._app_id: return - self._status = "" self._proton_status = "" - self.statusChanged.emit() self.protonStatusChanged.emit() - self._reload() self._reload_proton() + if launch_changed or not self._dirty: + self._status = "" + self.statusChanged.emit() + self._reload() def _reload_proton(self) -> None: if not self._app_id: diff --git a/protonshift/core/compat_tool.py b/protonshift/core/compat_tool.py index bc3711f..8620a70 100644 --- a/protonshift/core/compat_tool.py +++ b/protonshift/core/compat_tool.py @@ -22,6 +22,16 @@ from .vdf_config import VdfParseError, _load_vdf_strict +def is_steam_runtime(tool_name: str) -> bool: + """True for Steam's own Linux runtimes (``steamlinuxruntime_sniper``, ``legacysteamruntime``, ...). + + A game forced to one of these runs natively inside Steam's container, not + through Proton. Steam provides them, so they are never "gone". + """ + name = (tool_name or "").strip() + return name.startswith("steamlinuxruntime") or name == "legacysteamruntime" + + def get_config_vdf_path(steam_root: Path) -> Path: return steam_root / "config" / "config.vdf" diff --git a/protonshift/core/data/fix_pack.json b/protonshift/core/data/fix_pack.json index 15d2cc1..e00e040 100644 --- a/protonshift/core/data/fix_pack.json +++ b/protonshift/core/data/fix_pack.json @@ -1,7 +1,7 @@ { "format": "protonshift-fix-pack", "version": 2, - "revision": "2026.11.2", + "revision": "2026.11.3", "rules": [ { "id": "prefix-not-owned", @@ -528,7 +528,10 @@ "1091500" ], "when": { - "proton_major_min": 10 + "proton_major_min": 10, + "env_unset": [ + "PROTON_DISABLE_HIDRAW" + ] } }, "actions": [ @@ -549,7 +552,12 @@ "match": { "app_ids": [ "1245620" - ] + ], + "when": { + "env_unset": [ + "WINE_CPU_TOPOLOGY" + ] + } }, "actions": [ { diff --git a/protonshift/core/diagnose.py b/protonshift/core/diagnose.py index e3412b1..5d69492 100644 --- a/protonshift/core/diagnose.py +++ b/protonshift/core/diagnose.py @@ -25,6 +25,7 @@ from typing import Any, TypeVar from . import compat_tool, fix_pack, gpu, host, launch_check, proton_log, steam, system_checks, tool_check +from .compat_tool import is_steam_runtime from .display import _is_wayland from .fix_apply import read_state from .fix_pack import Action, Rule, When, match_log @@ -106,6 +107,71 @@ def _valve_major(digits: str) -> int | None: return None +def steam_provides(tool_name: str) -> bool: + """True for a tool Steam itself downloads when a game needs it: Valve's Proton or a Steam runtime.""" + return proton_build(tool_name)[0] == "valve" or is_steam_runtime(tool_name) + + +def proton_facts(tool_name: str, native: bool) -> tuple[str, int | None]: + """``(family, major)`` for :class:`Facts`: unknown for a native game or a Steam runtime. + + Neither runs the game through Proton, so no ``proton_*`` rule condition + may hold for them, ``proton_family: ["other"]`` included. + """ + if native or is_steam_runtime(tool_name): + return "", None + return proton_build(tool_name) + + +# How deep guess_native looks for a Windows program, and how many entries it +# reads at most, so the guess stays quick on a 100 GB install. +_NATIVE_SCAN_DEPTH = 3 # the install folder and two levels of folders below it +_NATIVE_SCAN_ENTRIES = 20000 + + +def guess_native(compat_tool: str | None, prefix_path: Path | None, install_path: Path | None) -> bool: + """A conservative guess that a Steam game is a native Linux game. + + True only when all hold: no compatibility tool is forced for it + (``compat_tool`` is ``""``) or the forced one is a Steam runtime, its + compatdata prefix folder does not exist, and its install folder holds no + ``.exe`` file within two folder levels. Anything that could not be found + out (``compat_tool`` None, a path unknown or unreadable, too many entries) + gives False. The guess errs toward "Proton" on purpose: a native game + hides the Proton checks, the log and the prefix, so a wrong "native" would + hide the very findings a Windows game needs. + """ + if compat_tool is None or (compat_tool and not is_steam_runtime(compat_tool)): + return False + if prefix_path is None or install_path is None: + return False + try: + if prefix_path.exists() or not install_path.is_dir(): + return False + except OSError: + return False + pending: list[tuple[Path, int]] = [(install_path, 0)] + seen = 0 + while pending: + folder, depth = pending.pop() + try: + entries = list(folder.iterdir()) + except OSError: + return False + seen += len(entries) + if seen > _NATIVE_SCAN_ENTRIES: + return False + for entry in entries: + if entry.name.lower().endswith(".exe"): + return False + try: + if depth + 1 < _NATIVE_SCAN_DEPTH and entry.is_dir() and not entry.is_symlink(): + pending.append((entry, depth + 1)) + except OSError: + return False + return True + + def proton_build(tool_name: str) -> tuple[str, int | None]: """``(family, major)`` of a compatibility tool's internal name. @@ -455,11 +521,14 @@ class Report: app_id: str findings: list[Finding] summary: str - state: GameState | None # current settings, None when unreadable or a shortcut + # Current settings, None when unreadable. For a shortcut: its launch + # options and the Proton build forced for it, for planning only. + state: GameState | None can_apply: bool # False for shortcuts and unreadable configs steam_running: bool | None log_path: str paths: tuple[Path | None, Path | None] # (localconfig.vdf, config.vdf) for apply/undo + native: bool = False # diagnosed as a native Linux game (guess_native, or the caller said so) def _quiet(read: Callable[[], T], fallback: T) -> T: @@ -514,17 +583,21 @@ def collect( ok, tool = (False, "") if config_vdf: ok, tool = _quiet(lambda: compat_tool.read_compat_tool(config_vdf, app_id), (False, "")) - tool = tool if ok and isinstance(tool, str) else "" + tool_known = ok and isinstance(tool, str) + tool = tool if tool_known else "" install = Path(install_path) if install_path else None prefix = Path(prefix_path) if prefix_path else None - family, major = ("", None) if native else proton_build(tool) + if steam_app and not native: + # The library has no native flag for Steam games, so it is guessed here. + native = _quiet(lambda: guess_native(tool if tool_known else None, prefix, install), False) + family, major = proton_facts(tool, native) available = list(_quiet(lambda: steam.get_available_proton_tools(root), [""])) runtimes = _quiet(lambda: _installed_runtimes(root), []) - if family == "valve" and tool not in available: - # Steam downloads its own Proton builds when a game needs one, and - # their internal names are not on disk to compare with, so a Valve - # build is never reported as gone. + if steam_provides(tool) and tool not in available: + # Steam downloads its own Proton builds and runtimes when a game needs + # one, and their internal names are not on disk to compare with, so + # they are never reported as gone. available.append(tool) launch_findings = _quiet(lambda: launch_check.check_launch( launch_options=options, @@ -569,7 +642,12 @@ def collect( rules = [*fix_pack.load_bundled_pack().rules, *_quiet(lambda: fix_pack.user_rules(app_id), [])] findings = diagnose(facts, rules=rules, launch_findings=launch_findings, checks=checks) - state = read_state(localconfig, config_vdf, app_id) if steam_app else None + if steam_app: + state = read_state(localconfig, config_vdf, app_id) + else: + # ProtonShift cannot write a shortcut, but a plan still has to start + # from its real Proton build, or "use Steam's default" looks done. + state = GameState(launch_options=options, compat_tool=tool) return Report( app_id=app_id, findings=findings, @@ -579,4 +657,5 @@ def collect( steam_running=_quiet(lambda: system_checks.steam_running(host.host_run), None), log_path=str(log_file) if log_file else "", paths=(localconfig, config_vdf), + native=native, ) diff --git a/protonshift/core/fix_apply.py b/protonshift/core/fix_apply.py index d44051b..cf15393 100644 --- a/protonshift/core/fix_apply.py +++ b/protonshift/core/fix_apply.py @@ -12,7 +12,9 @@ - It never makes a change that cannot be undone. The snapshot is saved first; if that fails, nothing is written. - It never leaves half a change behind. When the second of two writes fails, - the first is put back. + the first is put back. When even that fails, the snapshot stays, so Undo can + still put the old settings back; a snapshot is only ever dropped once the + files are read back as they were before the fix. Paths are passed in, never looked up here, so tests run against VDF files in a temporary folder. @@ -34,6 +36,7 @@ _KEY_RE, _WORD_RE, Action, + env_key_problem, ) from .launch_merge import ( COMMAND, @@ -59,6 +62,17 @@ "{key} decides what code the game loads, so ProtonShift will not change it for you. " "Add it by hand if you are sure." ) +_FAMILY_REFUSED = ( + "{key} is not one of the variables ProtonShift sets for you, so add it by hand if you want it." +) +_QUOTE_REFUSED = ( + "The value has a single quote, which ProtonShift cannot write safely into launch options, " + "so add it by hand if you want it." +) +_COMMAND_REFUSED = ( + "The value contains %command%, which Steam would replace with the game's command line, " + "so add it by hand if you want it." +) _UNKNOWN_ACTION = "ProtonShift does not know how to make this change for you." _LINE_BREAK = "The new launch options would contain a line break, which Steam cannot store." _STATE_MOVED = "The settings changed since the check. Run Diagnose again." @@ -83,22 +97,47 @@ class ApplyResult: message: str # plain sentence for the user snapshot_id: str # "" when nothing was recorded state: GameState | None # the state now on disk, when known + # The launch options on disk differ from what they were before this call. + # The launch options editor reloads its text only then, so a fix that + # changed only the Proton build keeps the user's unsaved edits. + launch_changed: bool = False + # Undo refused because the settings were changed after the fix. + conflict: bool = False # --------------------------------------------------------------------------- # # planning # --------------------------------------------------------------------------- # -def _key_problem(key: str) -> str: +def _key_problem(key: str, *, setting: bool, user: bool) -> str: if not isinstance(key, str) or not _KEY_RE.fullmatch(key): return _KEY_REFUSED.format(key=key or "The name") - # The pack loader already refuses these; a user's own fix is not loaded - # through it, and one click should not be able to set them either way. + if user: + # docs/fix-pack.md, "User fixes": the user's own fix may name any + # variable; it is their text on their machine. + return "" + # The pack loader already refuses these. Checked again here so a pack + # action that reached the plan some other way still cannot set them. if key in _FORBIDDEN_VARS or key.startswith(_FORBIDDEN_PREFIX): return _LOADER_REFUSED.format(key=key) + if env_key_problem(key, setting=setting): + return _FAMILY_REFUSED.format(key=key) return "" +def _value_problem(value: object, *, user: bool) -> str: + if not isinstance(value, str): + return _VALUE_REFUSED + # Steam substitutes %command% wherever it appears, quoted or not. + if COMMAND in value: + return _COMMAND_REFUSED if user else _VALUE_REFUSED + if user: + # Anything else is written single-quoted (launch_merge.env_word); a + # quote would end the quoting. Line breaks are refused by plan(). + return _QUOTE_REFUSED if "'" in value else "" + return "" if _ENV_VALUE_RE.fullmatch(value) else _VALUE_REFUSED + + def _user_snippet(text: str, value: str) -> str: # The contract: a user's launch_arg with %command% is merged like any # snippet; without it, it is game arguments (merge_launch_snippet alone @@ -107,19 +146,19 @@ def _user_snippet(text: str, value: str) -> str: return merge_launch_snippet(text, snippet) -def _step(action: Action, text: str) -> tuple[str, str]: +def _step(action: Action, text: str, user: bool) -> tuple[str, str]: """``(new_text, refusal)`` for one launch-options action.""" kind = action.type if kind in ("env", "unset_env"): - problem = _key_problem(action.key) + problem = _key_problem(action.key, setting=kind == "env", user=user) if problem: return text, problem if kind == "unset_env": return unset_env(text, action.key), "" - value = action.value - if not isinstance(value, str) or not _ENV_VALUE_RE.fullmatch(value) or COMMAND in value: - return text, _VALUE_REFUSED - return set_env(text, action.key, value), "" + problem = _value_problem(action.value, user=user) + if problem: + return text, problem + return set_env(text, action.key, action.value), "" if kind == "game_arg": if not isinstance(action.value, str) or not _GAME_ARG_RE.fullmatch(action.value): return text, _VALUE_REFUSED @@ -131,19 +170,24 @@ def _step(action: Action, text: str) -> tuple[str, str]: simple: dict[str, Callable[[str], str]] = {"single_command": single_command, "add_command": add_command} if kind in simple: return simple[kind](text), "" - if kind == "user_snippet": + if kind == "user_snippet" and user: if not isinstance(action.value, str) or not action.value.strip(): return text, _VALUE_REFUSED return _user_snippet(text, action.value.strip()), "" return text, _UNKNOWN_ACTION -def plan(actions: Sequence[Action], state: GameState) -> Change: +def plan(actions: Sequence[Action], state: GameState, *, user: bool = False) -> Change: """What ``actions`` would do to ``state``. Pure: nothing is read or written. Actions apply in order. A blocked plan changes nothing (``after`` is ``before``), but still lists every manual instruction so the user can follow them by hand. + + ``user`` is True for the user's own fix (a finding of origin ``"user"``). + Only then may an ``env`` action name any variable and carry any value + that single quotes make safe, and only then is ``user_snippet`` allowed; + everything else is held to the fix pack's limits, whatever produced it. """ text, tool = state.launch_options, state.compat_tool manual: list[str] = [] @@ -162,7 +206,7 @@ def plan(actions: Sequence[Action], state: GameState) -> Change: if any(ch in str(action.value) + str(action.key) for ch in _BAD_CHARS): blocked = _LINE_BREAK continue - text, blocked = _step(action, text) + text, blocked = _step(action, text, user) if not blocked and any(ch in text or ch in tool for ch in _BAD_CHARS): blocked = _LINE_BREAK after = state if blocked else GameState(launch_options=text, compat_tool=tool) @@ -262,19 +306,55 @@ def apply_change( ) failure = _write(localconfig, config_vdf, app_id, current, change.after, unchanged="nothing was changed") + now = read_state(localconfig, config_vdf, app_id) + moved = _launch_moved(current, now, change.after) if failure: - snapshots.drop(app_id, snap.id) - return ApplyResult(False, failure, "", read_state(localconfig, config_vdf, app_id)) + if now == change.before: + snapshots.drop(app_id, snap.id) + return ApplyResult(False, failure, "", now, launch_changed=moved) + # Half a change may be on disk and the snapshot is the only record of + # the settings before it, so it stays. + if failure.endswith("nothing was changed."): + # The write said no, yet the files are not as they were: the + # sentence must not claim otherwise. + failure = "Steam's settings could not all be written, and they are no longer as they were." + return ApplyResult( + False, f"{failure} Use Undo in Diagnose to put the old settings back.", snap.id, now, + launch_changed=moved, + ) - now = read_state(localconfig, config_vdf, app_id) if now != change.after: # The undo point stays: whatever did land can still be put back with Undo. return ApplyResult( False, "The fix was written, but Steam's files do not show it now. Close Steam and run Diagnose again.", - snap.id, now, + snap.id, now, launch_changed=moved, ) - return ApplyResult(True, "The fix was applied. You can undo it from Diagnose.", snap.id, now) + return ApplyResult(True, "The fix was applied. You can undo it from Diagnose.", snap.id, now, + launch_changed=moved) + + +def _launch_moved(old: GameState, now: GameState | None, target: GameState) -> bool: + """Whether the launch options on disk changed from ``old``. + + When the files cannot be read back, a launch-options write that was + attempted counts as a change. + """ + if now is None: + return target.launch_options != old.launch_options + return now.launch_options != old.launch_options + + +def _only_fix_values(current: GameState, snap: Snapshot) -> bool: + """True when every setting is either as before the fix or as the fix left it. + + Such a state holds nothing anyone wrote after the fix, so putting + ``before`` back loses nothing. It is also what a half-finished apply or + undo leaves (the launch options written, the Proton build not), which Undo + must be able to finish without asking. + """ + return (current.launch_options in (snap.before.launch_options, snap.after.launch_options) + and current.compat_tool in (snap.before.compat_tool, snap.after.compat_tool)) def undo_latest( @@ -287,9 +367,11 @@ def undo_latest( """Put back the settings from before the latest fix, then forget that fix. When the settings were changed after the fix was applied, Undo would - overwrite those changes, so it refuses unless ``force`` is set. The - result's ``snapshot_id`` is the snapshot Undo acted on; it is dropped only - when the settings are back as they were before the fix. + overwrite those changes, so it refuses unless ``force`` is set (the result + then has ``conflict``). A setting that is as before the fix or as the fix + left it is not a later change. The result's ``snapshot_id`` is the + snapshot Undo acted on; it is dropped only when the settings are read back + as they were before the fix. """ snap = snapshots.latest(app_id) if snap is None: @@ -302,7 +384,7 @@ def undo_latest( return ApplyResult( True, "The settings were already back to how they were before the fix.", snap.id, current, ) - if current != snap.after and not force: + if not force and not _only_fix_values(current, snap): message = ( "The settings were changed after the fix was applied, so Undo would overwrite those changes. " f"The launch options are now {_shown(current.launch_options)}; before the fix they were " @@ -311,23 +393,28 @@ def undo_latest( if current.compat_tool != snap.before.compat_tool: message += (f" The Proton build is now {_shown(current.compat_tool)}; before the fix it was " f"{_shown(snap.before.compat_tool)}.") - return ApplyResult(False, message, snap.id, current) + return ApplyResult(False, message, snap.id, current, conflict=True) failure = _write( localconfig, config_vdf, app_id, current, snap.before, unchanged="the fix is still in place", ) - if failure: - return ApplyResult(False, failure, snap.id, read_state(localconfig, config_vdf, app_id)) now = read_state(localconfig, config_vdf, app_id) + moved = _launch_moved(current, now, snap.before) + if failure: + # Never dropped here: the snapshot is the only record of "before". + if failure.endswith("the fix is still in place.") and now != snap.after: + failure = ("Steam's settings could not all be written, so the fix is only partly undone. " + "Try Undo again.") + return ApplyResult(False, failure, snap.id, now, launch_changed=moved) if now != snap.before: return ApplyResult( False, "The old settings were written, but Steam's files do not show them now. " "Close Steam and try Undo again.", - snap.id, now, + snap.id, now, launch_changed=moved, ) snapshots.drop(app_id, snap.id) - return ApplyResult(True, "The fix was undone.", snap.id, now) + return ApplyResult(True, "The fix was undone.", snap.id, now, launch_changed=moved) def undo_available(app_id: str) -> Snapshot | None: diff --git a/protonshift/core/fix_pack.py b/protonshift/core/fix_pack.py index b3757fa..7b7a603 100644 --- a/protonshift/core/fix_pack.py +++ b/protonshift/core/fix_pack.py @@ -55,15 +55,23 @@ _GAME_ARG_RE = re.compile(r"[-+][A-Za-z0-9_.=:-]{1,60}") _WORD_RE = re.compile(r"[A-Za-z0-9_.-]{1,40}") -# These decide what code a process loads or runs. +# The only families an ``env`` action may set: the ones that tune Proton, +# Wine, the graphics drivers and the overlay. A list of forbidden names can +# never be complete, and a variable ProtonShift does not know (BASH_ENV, +# GCONV_PATH, VK_ICD_FILENAMES, ...) may decide what code a process loads. +ENV_FAMILIES = ("PROTON_", "WINE_", "DXVK_", "VKD3D_", "MESA_", "RADV_", "__GL_", "__NV_", "SDL_", "MANGOHUD") +# These decide what code a process loads or runs, so a rule may neither set +# nor unset them, inside the families or not. _FORBIDDEN_VARS = frozenset({ + "PROTON_REMOTE_DEBUG_CMD", + "SDL_DYNAMIC_API", "LD_PRELOAD", "LD_LIBRARY_PATH", "LD_AUDIT", "PATH", "PYTHONPATH", - "STEAM_COMPAT_LAUNCHER_SERVICE", "WINEDLLPATH", + "WINEDLLOVERRIDES", }) _FORBIDDEN_PREFIX = "STEAM_COMPAT_" # ``user_rules`` hands out ``user-``; a pack rule with that id could be @@ -179,12 +187,27 @@ def _str_list(value: object, where: str) -> list[str]: return value -def _env_key(value: object, where: str) -> str: - if not isinstance(value, str) or not _KEY_RE.fullmatch(value): - raise PackError(f"{where}: not a valid variable name") - if value in _FORBIDDEN_VARS or value.startswith(_FORBIDDEN_PREFIX): - raise PackError(f"{where}: {value} may not be changed by a rule") - return value +def env_key_problem(key: object, *, setting: bool) -> str: + """Why a rule may not change the variable ``key``; ``""`` when it may. + + ``setting`` is True for an ``env`` action, which is held to + :data:`ENV_FAMILIES`; ``unset_env`` is not, since removing a variable the + user set adds nothing. The forbidden list holds for both. + """ + if not isinstance(key, str) or not _KEY_RE.fullmatch(key): + return "not a valid variable name" + if key in _FORBIDDEN_VARS or key.startswith(_FORBIDDEN_PREFIX): + return f"{key} may not be changed by a rule" + if setting and not key.startswith(ENV_FAMILIES): + return f"{key} is not in a family a rule may set ({', '.join(ENV_FAMILIES)})" + return "" + + +def _env_key(value: object, where: str, *, setting: bool) -> str: + problem = env_key_problem(value, setting=setting) + if problem: + raise PackError(f"{where}: {problem}") + return str(value) def _source(value: object) -> str: @@ -291,20 +314,25 @@ def _children(node: tuple[Any, ...]) -> list[list[tuple[Any, ...]]]: return [] -def _contains_repeat(seq: list[tuple[Any, ...]]) -> bool: - return any(n[0] == "rep" or any(_contains_repeat(s) for s in _children(n)) for n in seq) - +def _has_repeated_group(seq: list[tuple[Any, ...]]) -> bool: + """True when a repeat that can match more than once repeats anything but one character. -def _has_nested_repeat(seq: list[tuple[Any, ...]]) -> bool: - # An outer quantifier that can match at most once (``?``, ``{0,1}``) does - # not repeat its group, so it cannot multiply the ways the inner repeat - # splits a line; any quantifier inside a real repeat counts, ``?`` too, - # since ``(a?)+`` style patterns backtrack as badly as ``(a+)+``. - return any( - (n[0] == "rep" and (n[3] is None or n[3] > 1) and _contains_repeat(n[2])) - or any(_has_nested_repeat(s) for s in _children(n)) - for n in seq - ) + The contract allows a repeat of a single character, an escaped character, + a character class or ``.``, all of which are one ``lit`` or ``char`` node + here. A repeated group is refused even without a repeat inside: + ``(?:a{8}|a{16})+$`` style alternations of different lengths backtrack + exponentially on a line that almost matches. A quantifier that matches at + most once (``?``, ``{0,1}``) does not repeat, so its group is allowed and + only its contents are checked. + """ + for n in seq: + if n[0] == "rep" and (n[3] is None or n[3] > 1): + body = n[2] + if len(body) != 1 or body[0][0] not in ("lit", "char"): + return True + if any(_has_repeated_group(s) for s in _children(n)): + return True + return False def _open_repeats(seq: list[tuple[Any, ...]]) -> int: @@ -350,8 +378,8 @@ def _compile_log(pattern: object, where: str) -> re.Pattern[str]: tree = _regex_tree(pattern) if tree is None: raise PackError(f"{where}: expression uses a construct that cannot be checked") - if _has_nested_repeat(tree): - raise PackError(f"{where}: expression repeats a group that contains a repeat") + if _has_repeated_group(tree): + raise PackError(f"{where}: expression repeats a group; only one character, a class or . may repeat") if _open_repeats(tree) > _MAX_OPEN_REPEATS: raise PackError(f"{where}: expression has more than {_MAX_OPEN_REPEATS} open-ended repeats") if _literal_run(tree) < _MIN_LITERAL_RUN: @@ -449,7 +477,7 @@ def _parse_action(raw: object, where: str) -> Action: if name not in raw: raise PackError(f"{where}: {kind} needs {name}") if kind == "env": - key = _env_key(raw["key"], f"{where}.key") + key = _env_key(raw["key"], f"{where}.key", setting=True) value = raw["value"] if not isinstance(value, str) or not _ENV_VALUE_RE.fullmatch(value): raise PackError(f"{where}.value: not allowed for env (letters, digits and _.,:=/+@%- only)") @@ -459,7 +487,7 @@ def _parse_action(raw: object, where: str) -> Action: raise PackError(f"{where}.value: must not contain %command%") return Action("env", key=key, value=value) if kind == "unset_env": - return Action("unset_env", key=_env_key(raw["key"], f"{where}.key")) + return Action("unset_env", key=_env_key(raw["key"], f"{where}.key", setting=False)) if kind == "game_arg": value = raw["value"] if not isinstance(value, str) or not _GAME_ARG_RE.fullmatch(value): @@ -660,7 +688,8 @@ def _user_action(entry: dict[Any, Any]) -> Action | None: # carrying it; nothing else about the user's own value is limited. if not isinstance(value, str) or any(ch in value for ch in "\n\r\0"): return None - kind = entry.get("type") + # Version 1 read an entry without a type as env. + kind = entry.get("type", "env") if kind == "env": key = entry.get("key", "") if not isinstance(key, str) or not _KEY_RE.fullmatch(key): diff --git a/protonshift/core/fixes.py b/protonshift/core/fixes.py index ea437af..6f51fb2 100644 --- a/protonshift/core/fixes.py +++ b/protonshift/core/fixes.py @@ -7,7 +7,6 @@ from __future__ import annotations import json -from dataclasses import dataclass from pathlib import Path from typing import Any @@ -21,16 +20,6 @@ def _user_fixes_path(app_id: str) -> Path: return _USER_FIXES_DIR / f"{sanitize_filename(app_id, fallback='unknown')}.json" -@dataclass -class GameFix: - title: str - description: str - fix_type: str # "env" or "launch_arg" - key: str # env var key (empty for launch_arg) - value: str - source: str # always "user" - - def _load_user_fixes_strict(app_id: str) -> list[dict[str, Any]]: """Load user fixes, raising on a corrupt file. @@ -57,22 +46,6 @@ def _load_user_fixes(app_id: str) -> list[dict[str, Any]]: return [] -def _dict_to_fix(d: dict[str, Any], source: str) -> GameFix: - return GameFix( - title=d.get("title", ""), - description=d.get("description", ""), - fix_type=d.get("type", "env"), - key=d.get("key", ""), - value=d.get("value", ""), - source=source, - ) - - -def get_fixes(app_id: str) -> list[GameFix]: - """The user's own fixes for a game.""" - return [_dict_to_fix(entry, "user") for entry in _load_user_fixes(app_id)] - - def add_user_fix( app_id: str, title: str, diff --git a/protonshift/core/launch_check.py b/protonshift/core/launch_check.py index 3976e4b..ec214d3 100644 --- a/protonshift/core/launch_check.py +++ b/protonshift/core/launch_check.py @@ -21,14 +21,15 @@ from pathlib import Path from typing import Any +from .compat_tool import is_steam_runtime from .fix_pack import Action from .launch_merge import ( COMMAND, KNOWN_COMMANDS, - _tokens, add_command, remove_word, single_command, + split_words, unset_env, ) @@ -104,7 +105,9 @@ def check_launch_options(text: str, tool_exists: Callable[[str], bool]) -> list[ if not text: return [finding("ok", "Launch options are empty", "The game starts with Steam's defaults.", id="launch-empty")] - tokens = _tokens(text) + # Split as the edit helpers and the shell split it, so KEY='a b;c' is one + # assignment and none of its value is read as a command. + tokens = split_words(text) count = tokens.count(COMMAND) out: list[dict[str, Any]] = [] before = tokens[: tokens.index(COMMAND)] if count else [] @@ -221,6 +224,10 @@ def check_launch( id="proton-gone", actions=(Action("default_proton"),), )) + elif compat_tool and is_steam_runtime(compat_tool): + # A Steam Linux Runtime is not a Proton build; the id stays so the row + # is still hidden for a native game like any Proton row. + out.append(finding("ok", f"Compatibility tool is provided by Steam: {compat_tool}", id="proton-ok")) elif compat_tool: out.append(finding("ok", f"Proton build is installed: {compat_tool}", id="proton-ok")) else: @@ -268,13 +275,3 @@ def check_launch( out.sort(key=lambda f: order.get(f["level"], 4)) # stable: keeps the order within a level return out - -def summarize(findings: list[dict[str, Any]]) -> str: - errors = sum(1 for f in findings if f["level"] == "error") - warns = sum(1 for f in findings if f["level"] == "warn") - if errors: - return (f"{errors} problem{'s' if errors != 1 else ''} that will stop the game from starting" - + (f", {warns} warning{'s' if warns != 1 else ''}" if warns else "") + ".") - if warns: - return f"Nothing blocks the launch. {warns} thing{'s' if warns != 1 else ''} worth a look." - return "No problems found." diff --git a/protonshift/core/launch_merge.py b/protonshift/core/launch_merge.py index 0a54a65..4f5c2ca 100644 --- a/protonshift/core/launch_merge.py +++ b/protonshift/core/launch_merge.py @@ -24,7 +24,9 @@ one helper that moves words in front of the game. - Words are split by :func:`split_words`, which keeps ``KEY='a b'`` together as one word. A line with an unbalanced quote falls back to plain whitespace - splitting, as ``_tokens`` does, so no text is lost. + splitting, so no text is lost. :func:`merge_launch_snippet` and the launch + check split the same way, so every part of the app sees one assignment + where the shell sees one. - Applying a helper twice gives the same line as applying it once. Pure Python - exercised in tests/test_launch_merge.py. @@ -33,7 +35,6 @@ from __future__ import annotations import re -import shlex COMMAND = "%command%" @@ -44,8 +45,17 @@ # What a word right after a removed command looks like when it is that # command's own option or number (``mangohud --dlsym``, ``strangle 60``). _OPTION_RE = re.compile(r"-\S*|[0-9][0-9.:]*") +# What ProtonShift writes as a bare ``KEY=value``: the fix pack's own value set +# (docs/fix-pack.md), none of which means anything to the shell. Any other +# value, from the user's own fixes, is written in single quotes. +_BARE_VALUE_RE = re.compile(r"[A-Za-z0-9_.,:=/+@%-]*") +# What single quotes cannot make safe: a quote ends them, a line break or NUL +# ends the line or the string, and Steam replaces %command% before the shell +# sees the line. +_UNQUOTABLE = ("'", "\n", "\r", "\x00", COMMAND) # Wrapper commands people put in launch options -> the name to show. +# (TAKES_OPTIONS below says which of them read options of their own.) KNOWN_COMMANDS: dict[str, str] = { "gamemoderun": "GameMode", "mangohud": "MangoHud", @@ -56,14 +66,28 @@ "prime-run": "prime-run", "strangle": "libstrangle", } +# The known commands that read options of their own before the program they +# run: ``strangle 60`` (its FPS limit and flags), ``mangohud --dlsym``. The +# others (gamemoderun, prime-run, obs-gamecapture) run the next word as the +# program, so a word like ``-novid`` after them is the game's, and add_command +# must not pull it in front of %command%. The ``--`` wrappers (_WRAPPERS) are +# handled on their own. +TAKES_OPTIONS = frozenset({"strangle", "mangohud"}) +# What their options look like: a number (strangle's FPS limit, ``60`` or +# ``60:30``), a one-letter flag (``-k``) or a long one (``--dlsym``). Narrower +# than _OPTION_RE on purpose: a game switch such as ``-novid`` or ``-dx11`` is +# a single dash and several letters, so it stays the game's. +_OWN_OPTION_RE = re.compile(r"[0-9][0-9.:]*|-[A-Za-z]|--[A-Za-z][A-Za-z0-9-]*(?:=\S*)?") def _tokens(text: str) -> list[str]: - """Split on whitespace, keeping quoted segments (and their quotes) intact.""" - try: - return shlex.split(text, posix=False) - except ValueError: # unbalanced quote: fall back rather than lose the text - return text.split() + """Split on whitespace, keeping quoted segments (and their quotes) intact. + + The same split as :func:`split_words`. ``shlex`` in non-POSIX mode, used + here before, cut ``KEY='a b'`` in two, so a merge could move half of an + assignment behind a wrapper. + """ + return split_words(text) def _split_command(tokens: list[str]) -> tuple[list[str], list[str], bool]: @@ -137,9 +161,9 @@ def merge_launch_snippet(text: str, snippet: str) -> str: def split_words(text: str) -> list[str]: """Split on whitespace like a shell would, keeping quotes and escapes inside their word. - Unlike ``_tokens`` (``shlex`` in non-POSIX mode), a quote in the middle of - a word does not end it, so ``KEY='a b'`` is one word. With an unbalanced - quote the line is split on whitespace alone rather than losing text. + A quote in the middle of a word does not end it, so ``KEY='a b;c'`` is one + word. With an unbalanced quote the line is split on whitespace alone + rather than losing text. """ words: list[str] = [] current: list[str] = [] @@ -236,16 +260,31 @@ def _check_key(key: str) -> None: raise ValueError(f"not a valid variable name: {key!r}") +def env_word(key: str, value: str) -> str: + """The assignment as written into launch options: ``KEY=value``, or ``KEY='value'``. + + A value outside the fix pack's character set (only the user's own fixes + have one) is single-quoted, so the shell takes it as one word and runs none + of it. Raises ``ValueError`` for a bad key, or for a value that quoting + cannot make safe (a single quote, a line break, NUL, ``%command%``). + """ + _check_key(key) + if not isinstance(value, str) or any(bad in value for bad in _UNQUOTABLE): + raise ValueError(f"not a value that can be written for {key}") + if _BARE_VALUE_RE.fullmatch(value): + return f"{key}={value}" + return f"{key}='{value}'" + + def set_env(text: str, key: str, value: str) -> str: - """Set ``KEY=value`` before ``%command%``. + """Set ``KEY=value`` before ``%command%``, quoted as :func:`env_word` says. An existing assignment of the same key is replaced where it stands (a later duplicate is dropped, since the shell would let it win); otherwise the assignment goes to the front of the prefix. """ - _check_key(key) + new = env_word(key, value) before, after, count = split_line(text) - new = f"{key}={value}" out: list[str] = [] placed = False for word in before: @@ -341,11 +380,18 @@ def single_command(text: str) -> str: def add_command(text: str) -> str: """Insert ``%command%`` after the leading assignments and known wrapper commands. - For a line with no ``%command%`` such as ``PROTON_LOG=1 gamemoderun -novid``: - the leading run (``PROTON_LOG=1 gamemoderun``) becomes the prefix and the - rest stays game arguments. A wrapper in the run keeps its options up to its - ``--``. A line that already has ``%command%``, or that does not start with - such words, is returned as it was. + For a line with no ``%command%`` such as ``PROTON_LOG=1 strangle 60 +x``: + the leading run (``PROTON_LOG=1 strangle 60``) becomes the prefix and the + rest stays game arguments. A command that reads options of its own + (:data:`TAKES_OPTIONS`) keeps the words right after it that look like its + options (``strangle 60``, ``mangohud --dlsym``), since putting the game + between it and its options would hand them to the game. A game switch + (``-novid``) after it, and any word after another command + (``gamemoderun -novid``), stays the game's. A wrapper that ends + its options with ``--`` (gamescope, scb, scopebuddy) keeps them up to that + ``--``; without one, every word after it is its own and the line ends with + ``-- %command%``. A line that already has ``%command%``, or that does not + start with such words, is returned as it was. """ words = split_words(text.strip()) if COMMAND in words: @@ -359,8 +405,16 @@ def add_command(text: str) -> str: name = _basename(word) if name not in KNOWN_COMMANDS: break - end = _dashdash(words, i) if name in _WRAPPERS else None - i = end + 1 if end is not None else i + 1 + if name in _WRAPPERS: + end = _dashdash(words, i) + if end is None: + return _join([*words, "--"], []) + i = end + 1 + continue + i += 1 + if name in TAKES_OPTIONS: + while i < len(words) and _OWN_OPTION_RE.fullmatch(words[i]): + i += 1 if i == 0: return text return _join(words[:i], words[i:]) diff --git a/protonshift/core/system_checks.py b/protonshift/core/system_checks.py index 1c22930..bcffaa6 100644 --- a/protonshift/core/system_checks.py +++ b/protonshift/core/system_checks.py @@ -224,8 +224,25 @@ def _vulkan_from_manifests(icd_dirs: Sequence[Path]) -> Check: ) -def check_vulkan(run: Runner = host_run, icd_dirs: Sequence[Path] | None = None) -> Check: - """Does Vulkan work on a real graphics card? Asks ``vulkaninfo``, else reads driver manifests.""" +def check_vulkan( + run: Runner = host_run, icd_dirs: Sequence[Path] | None = None, flavor: str = "", +) -> Check: + """Does Vulkan work on a real graphics card? Asks ``vulkaninfo``, else reads driver manifests. + + ``flavor`` is :func:`steam_flavor`'s answer. With Flatpak Steam the games + use the drivers of Steam's Flatpak runtime, not this computer's, so the + answer is ``unknown`` and nothing is run. That holds for a working host + driver too: a host that passes says nothing about the runtime's drivers + (the NVIDIA one, for example, must match the host driver's version), and a + green tick on a guess is what these checks never give. + """ + if flavor == "flatpak": + return Check( + "vulkan", UNKNOWN, _VULKAN_UNKNOWN, + "Steam runs as a Flatpak and brings its own drivers, so a check of the drivers installed on " + "this computer does not apply to its games.", + "", + ) dirs = list(icd_dirs) if icd_dirs is not None else default_icd_dirs() try: proc = run(["vulkaninfo", "--summary"], capture_output=True, text=True, timeout=_TIMEOUT) @@ -470,9 +487,10 @@ def run_checks( run: Runner = host_run, ) -> list[Check]: """Every system check for one game, in display order.""" + flavor = steam_flavor(steam_root) checks = [ - check_vulkan(run), - check_vulkan_32bit(steam_flavor(steam_root)), + check_vulkan(run, flavor=flavor), + check_vulkan_32bit(flavor), check_disk(install_path, "library"), ] # One drive, one answer: the same free space twice reads like two problems. diff --git a/protonshift/qml/DiagnoseDialog.qml b/protonshift/qml/DiagnoseDialog.qml index 31518e8..130e3aa 100644 --- a/protonshift/qml/DiagnoseDialog.qml +++ b/protonshift/qml/DiagnoseDialog.qml @@ -554,6 +554,15 @@ PsDialog { font.family: Theme.fontFamily font.pixelSize: Theme.fsCaption } + Text { + Layout.fillWidth: true + visible: row.previewing && (dlg.preview.note || "").length > 0 + wrapMode: Text.Wrap + text: dlg.preview.note || "" + color: Theme.text + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } Text { Layout.fillWidth: true visible: row.previewing && (dlg.preview.blocked || "").length > 0 @@ -681,6 +690,16 @@ PsDialog { onClicked: dlg.controller.undo(false) } } + Text { + Layout.fillWidth: true + visible: dlg.ready && dlg.controller.undoConflict.length === 0 + && dlg.controller.undoChangesLaunch && dlg.launchDirty + wrapMode: Text.Wrap + text: "Undoing replaces the unsaved launch options in the editor with the ones from before the fix." + color: Theme.warning + font.family: Theme.fontFamily + font.pixelSize: Theme.fsCaption + } Text { Layout.fillWidth: true diff --git a/tests/test_core_safety.py b/tests/test_core_safety.py index 31b0bc1..34f9372 100644 --- a/tests/test_core_safety.py +++ b/tests/test_core_safety.py @@ -10,6 +10,7 @@ from __future__ import annotations import json +import shlex from datetime import UTC, datetime from pathlib import Path @@ -19,11 +20,13 @@ from protonshift.core import fixes as fixes_mod from protonshift.core import heroic_config, saves from protonshift.core import paths as paths_mod -from protonshift.core.fix_pack import PackError, parse_rule +from protonshift.core.fix_apply import plan +from protonshift.core.fix_pack import Action, PackError, parse_rule from protonshift.core.mangohud import read_mangohud_config from protonshift.core.prefix import delete_prefix from protonshift.core.scopebuddy import parse_scb_conf, write_scb_conf from protonshift.core.shader_cache import clear_shader_cache, get_shader_cache_info +from protonshift.core.snapshots import GameState from protonshift.core.steam import get_userdata_dir from protonshift.core.vdf_config import read_launch_options, set_launch_options @@ -383,7 +386,11 @@ def test_fix_pack_remove_word_rejects_paths_and_spaces(value: str) -> None: parse_rule(_pack_rule({"type": "remove_word", "value": value})) -@pytest.mark.parametrize("key", ["LD_PRELOAD", "PATH", "STEAM_COMPAT_DATA_PATH", "LD_LIBRARY_PATH", "WINEDLLPATH"]) +@pytest.mark.parametrize( + "key", + ["LD_PRELOAD", "PATH", "STEAM_COMPAT_DATA_PATH", "LD_LIBRARY_PATH", "WINEDLLPATH", "LD_AUDIT", + "PROTON_REMOTE_DEBUG_CMD", "SDL_DYNAMIC_API", "WINEDLLOVERRIDES"], +) @pytest.mark.parametrize("kind", ["env", "unset_env"]) def test_fix_pack_rejects_loader_variables(kind: str, key: str) -> None: action = {"type": kind, "key": key} @@ -396,3 +403,59 @@ def test_fix_pack_rejects_loader_variables(kind: str, key: str) -> None: def test_fix_pack_rejects_user_snippet_action() -> None: with pytest.raises(PackError): parse_rule(_pack_rule({"type": "user_snippet", "value": "reboot; %command%"})) + + +# A list of forbidden names is never complete, so a rule may only set +# variables in the families that tune Proton, Wine, the drivers and the overlay. +@pytest.mark.parametrize( + "key", + ["BASH_ENV", "GCONV_PATH", "VK_ICD_FILENAMES", "VK_ADD_LAYER_PATH", "LD_AUDIT", "SDL_DYNAMIC_API", + "PROTON_REMOTE_DEBUG_CMD", "WINEDLLOVERRIDES"], +) +def test_fix_pack_env_outside_the_families_or_forbidden_is_rejected(key: str) -> None: + with pytest.raises(PackError): + parse_rule(_pack_rule({"type": "env", "key": key, "value": "1"})) + # plan() refuses the same action when it is not the user's own + assert plan([Action("env", key=key, value="1")], GameState("%command%", "")).blocked + + +@pytest.mark.parametrize("key", ["PROTON_LOG", "WINE_CPU_TOPOLOGY", "DXVK_HUD", "MANGOHUD"]) +def test_fix_pack_env_in_the_families_is_accepted(key: str) -> None: + (action,) = parse_rule(_pack_rule({"type": "env", "key": key, "value": "1"})).actions + assert action == Action("env", key=key, value="1") + + +def test_engine_logging_row_still_plans() -> None: + change = plan([Action("env", "PROTON_LOG", "1")], GameState("", "")) + assert change.blocked == "" and change.after.launch_options == "PROTON_LOG=1 %command%" + + +# --------------------------------------------------------------------------- # +# user fixes: any value, written so the shell takes it as one word +# --------------------------------------------------------------------------- # + +@pytest.mark.parametrize( + "value", + ["x; rm -rf ~", "$(id)", "`id`", "a b", "x && reboot", "a|b > /tmp/x", "$HOME", '"q"', "\\ ;"], +) +@pytest.mark.parametrize("start", ["", "gamemoderun %command% -novid", "KEY='old value' %command%"]) +def test_user_env_value_is_one_shell_word(value: str, start: str) -> None: + change = plan([Action("env", key="KEY", value=value)], GameState(start, ""), user=True) + assert change.blocked == "", change.blocked + line = change.after.launch_options + words = shlex.split(line) + # Exactly one assignment of KEY, holding the value untouched, and nothing + # else in front of the game: no extra command, no extra word. + before = words[: words.index("%command%")] + assert before[0] == f"KEY={value}" + assert [w for w in before if w.startswith("KEY=")] == [f"KEY={value}"] + assert before[1:] == (["gamemoderun"] if start.startswith("gamemoderun") else []) + # A second apply changes nothing. + assert not plan([Action("env", key="KEY", value=value)], change.after, user=True).changed + + +@pytest.mark.parametrize("value", ["it's", "a\nreboot", "a\x00b", "x %command% y"]) +def test_user_env_value_that_quoting_cannot_hold_is_refused(value: str) -> None: + change = plan([Action("env", key="KEY", value=value)], GameState("%command%", ""), user=True) + assert change.blocked + assert change.after.launch_options == "%command%" diff --git a/tests/test_diagnose.py b/tests/test_diagnose.py index 45ea298..3072e07 100644 --- a/tests/test_diagnose.py +++ b/tests/test_diagnose.py @@ -12,7 +12,7 @@ import vdf from protonshift.core import diagnose as dg -from protonshift.core import fix_pack, fixes, gpu, host, steam, system_checks, tool_check +from protonshift.core import fix_apply, fix_pack, fixes, gpu, host, steam, system_checks, tool_check from protonshift.core.diagnose import Facts, Finding, diagnose, proton_build, rule_finding, summarize, to_row from protonshift.core.fix_pack import Action, parse_rule from protonshift.core.gpu import GPUInfo @@ -548,12 +548,135 @@ def test_collect_reports_a_name_steam_does_not_know(fake_steam: dict[str, Path]) def test_collect_a_shortcut(fake_steam: dict[str, Path]) -> None: report = dg.collect("3000000000", install_path=str(fake_steam["game"]), prefix_path="", shortcut_options="mangohud %command%", native=False, protondb_tier="") - assert report.state is None and report.can_apply is False + # A state to plan on, but nothing ProtonShift may write. + assert report.state == GameState("mangohud %command%", "") and report.can_apply is False found = {f.id for f in report.findings} assert "wrapper-missing-mangohud" in found assert not any(fid.startswith("log-") for fid in found) +def test_collect_plans_a_shortcut_against_its_real_proton_build(fake_steam: dict[str, Path]) -> None: + shortcut = "3000000000" + mapping = {shortcut: {"name": "GE-Proton8-1", "config": "", "priority": "250"}} + config = {"InstallConfigStore": {"Software": {"Valve": {"Steam": {"CompatToolMapping": mapping}}}}} + fake_steam["config_vdf"].write_text(vdf.dumps(config, pretty=True), encoding="utf-8") + report = dg.collect(shortcut, install_path=str(fake_steam["game"]), prefix_path="", + shortcut_options="%command%", native=False, protondb_tier="") + gone = next(f for f in report.findings if f.id == "proton-gone") + assert report.state == GameState("%command%", "GE-Proton8-1") and not report.can_apply + change = fix_apply.plan(gone.actions, report.state) + assert change.changed and change.after == GameState("%command%", "") + + +STEAM_RUNTIMES = ["steamlinuxruntime", "steamlinuxruntime_sniper", "steamlinuxruntime_soldier", + "steamlinuxruntime_4", "legacysteamruntime"] + + +@pytest.mark.parametrize("tool", STEAM_RUNTIMES) +def test_collect_counts_a_steam_runtime_as_available(fake_steam: dict[str, Path], tool: str) -> None: + write_steam(fake_steam["localconfig"], fake_steam["config_vdf"], "", tool) + report = dg.collect(APP, install_path=str(fake_steam["game"]), prefix_path="", shortcut_options=None, + native=False, protondb_tier="") + assert "proton-gone" not in {f.id for f in report.findings} + + +@pytest.mark.parametrize("tool", STEAM_RUNTIMES) +def test_a_steam_runtime_is_not_proton(tool: str) -> None: + assert dg.is_steam_runtime(tool) and dg.steam_provides(tool) + assert proton_build(tool) == ("other", None) + family, major = dg.proton_facts(tool, native=False) + assert (family, major) == ("", None) + runtime = facts(compat_tool=tool, proton_family=family, proton_major=major) + for when in ({"proton_family": ["other"]}, {"proton_family": ["valve", "ge", "cachyos", "other"]}, + {"proton_major_min": 0}, {"proton_major_max": 99}): + assert rule_finding(when_rule(when), runtime) is None, when + + +def test_steam_runtime_names_are_exact() -> None: + for name in ("proton_9_0", "GE-Proton9-20", "my-steamlinuxruntime", "legacysteamruntime2", ""): + assert not dg.is_steam_runtime(name), name + assert dg.proton_facts("GE-Proton9-20", native=False) == ("ge", 9) + assert dg.proton_facts("GE-Proton9-20", native=True) == ("", None) + + +# --- guess_native ------------------------------------------------------------------------------------------- + + +@pytest.fixture +def linux_game(tmp_path: Path) -> tuple[Path, Path]: + install = tmp_path / "common" / "Game" + (install / "bin" / "x86_64").mkdir(parents=True) + (install / "bin" / "x86_64" / "game").write_bytes(b"\x7fELF") + (install / "game.sh").write_text("#!/bin/sh\n", encoding="utf-8") + return install, tmp_path / "compatdata" / "100" + + +def test_guess_native_for_a_linux_install(linux_game: tuple[Path, Path]) -> None: + install, prefix = linux_game + assert dg.guess_native("", prefix, install) is True + for tool in STEAM_RUNTIMES: + assert dg.guess_native(tool, prefix, install) is True, tool + + +@pytest.mark.parametrize("where", ["Game.exe", "bin/Launcher.EXE", "bin/x86_64/game.exe"]) +def test_guess_native_an_exe_means_proton(linux_game: tuple[Path, Path], where: str) -> None: + install, prefix = linux_game + (install / where).write_bytes(b"MZ") + assert dg.guess_native("", prefix, install) is False + + +def test_guess_native_looks_only_two_levels_down(linux_game: tuple[Path, Path]) -> None: + install, prefix = linux_game + deep = install / "a" / "b" / "c" + deep.mkdir(parents=True) + (deep / "tool.exe").write_bytes(b"MZ") + assert dg.guess_native("", prefix, install) is True + + +def test_guess_native_errs_toward_proton(linux_game: tuple[Path, Path], tmp_path: Path) -> None: + install, prefix = linux_game + assert dg.guess_native("GE-Proton9-20", prefix, install) is False # a forced Proton build + assert dg.guess_native("proton_9", prefix, install) is False + assert dg.guess_native(None, prefix, install) is False # the forced tool is unknown + assert dg.guess_native("", prefix, tmp_path / "missing") is False + assert dg.guess_native("", None, install) is False + assert dg.guess_native("", prefix, None) is False + prefix.mkdir(parents=True) # a prefix: Proton ran it + assert dg.guess_native("", prefix, install) is False + + +def test_guess_native_unreadable_folder_is_not_native( + linux_game: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch, +) -> None: + install, prefix = linux_game + real = Path.iterdir + + def deny(self: Path): # type: ignore[no-untyped-def] + if self.name == "bin": + raise PermissionError("no") + return real(self) + + monkeypatch.setattr(Path, "iterdir", deny) + assert dg.guess_native("", prefix, install) is False + + +def test_collect_guesses_a_native_steam_game(fake_steam: dict[str, Path], tmp_path: Path) -> None: + write_steam(fake_steam["localconfig"], fake_steam["config_vdf"], "", "") + (fake_steam["game"] / "game.x86_64").write_bytes(b"\x7fELF") + prefix = tmp_path / "compatdata" / APP + report = dg.collect(APP, install_path=str(fake_steam["game"]), prefix_path=str(prefix), + shortcut_options=None, native=False, protondb_tier="") + assert report.native is True + found = {f.id for f in report.findings} + assert not any(fid.startswith(("proton-", "prefix-", "anticheat-", "log-")) for fid in found) + # The same game with a Windows program in it is diagnosed as a Proton game. + (fake_steam["game"] / "game.exe").write_bytes(b"MZ") + report = dg.collect(APP, install_path=str(fake_steam["game"]), prefix_path=str(prefix), + shortcut_options=None, native=False, protondb_tier="") + assert report.native is False + assert "log-off" in {f.id for f in report.findings} + + def test_collect_a_native_game(fake_steam: dict[str, Path]) -> None: (fake_steam["logs"] / f"steam-{APP}.log").write_text(LOG_LINE + "\n", encoding="utf-8") report = dg.collect(APP, install_path=str(fake_steam["game"]), prefix_path="", shortcut_options=None, diff --git a/tests/test_fix_apply.py b/tests/test_fix_apply.py index 7cae89a..e52ec36 100644 --- a/tests/test_fix_apply.py +++ b/tests/test_fix_apply.py @@ -44,7 +44,7 @@ def state(options: str = "", tool: str = "") -> GameState: ], ) def test_plan_each_action(action: Action, before: GameState, after: GameState) -> None: - change = plan([action], before) + change = plan([action], before, user=action.type == "user_snippet") assert change == Change(before=before, after=after, manual=(), blocked="") assert change.changed @@ -69,7 +69,7 @@ def test_plan_applies_actions_in_order() -> None: def test_plan_that_changes_nothing() -> None: - change = plan([Action("env", key="A", value="1")], state("A=1 %command%")) + change = plan([Action("env", key="DXVK_ASYNC", value="1")], state("DXVK_ASYNC=1 %command%")) assert not change.changed assert change.blocked == "" @@ -99,20 +99,70 @@ def test_plan_refuses_unknown_and_malformed_actions() -> None: assert "does not know" in plan([Action("run_script", value="x")], state()).blocked assert plan([Action("game_arg", value="-a -b")], state()).blocked assert plan([Action("remove_word", value="../x")], state()).blocked - assert plan([Action("user_snippet", value=" ")], state()).blocked + assert plan([Action("user_snippet", value=" ")], state(), user=True).blocked + # A snippet of free text only ever comes from the user's own fix. + assert "does not know" in plan([Action("user_snippet", value="-dx11")], state()).blocked + + +# --- the user's own fixes (docs/fix-pack.md, "User fixes") ---------------------------------- + + +@pytest.mark.parametrize( + ("key", "value", "expected"), + [ + ("DXVK_HUD", "fps", "DXVK_HUD=fps %command%"), + ("WINEDLLOVERRIDES", "d3d9=n;dinput8=n,b", "WINEDLLOVERRIDES='d3d9=n;dinput8=n,b' %command%"), + ("MY_VAR", "a b", "MY_VAR='a b' %command%"), + ("LD_PRELOAD", "/usr/lib/lib x.so", "LD_PRELOAD='/usr/lib/lib x.so' %command%"), + ("A", "$(id)", "A='$(id)' %command%"), + ("A", "", "A= %command%"), + ], +) +def test_plan_user_env_is_single_quoted(key: str, value: str, expected: str) -> None: + change = plan([Action("env", key=key, value=value)], state(""), user=True) + assert change.blocked == "" + assert change.after == state(expected) + # Applying it again changes nothing. + assert not plan([Action("env", key=key, value=value)], change.after, user=True).changed + + +@pytest.mark.parametrize( + ("value", "fragment"), + [("it's", "single quote"), ("a\nb", "line break"), ("a\x00b", "line break"), + ("x %command% y", "%command%")], +) +def test_plan_user_env_refuses_what_quoting_cannot_make_safe(value: str, fragment: str) -> None: + change = plan([Action("env", key="DXVK_HUD", value=value)], state("%command%"), user=True) + assert fragment in change.blocked + assert not change.changed + + +def test_plan_holds_actions_that_are_not_the_users_to_the_pack_limits() -> None: + # The pack loader refuses these too; plan() refuses them again for any + # action that is not the user's own (defence in depth). + for key in ("BASH_ENV", "WINEDLLOVERRIDES", "SDL_DYNAMIC_API", "A"): + assert plan([Action("env", key=key, value="1")], state("%command%")).blocked, key + assert "characters" in plan([Action("env", key="DXVK_HUD", value="a b")], state("%command%")).blocked + # unset_env is not limited to the families, only by the forbidden list. + assert plan([Action("unset_env", key="MY_VAR")], state("MY_VAR=1 %command%")).after == state("") + assert plan([Action("unset_env", key="WINEDLLOVERRIDES")], state("%command%")).blocked + # The engine's own "turn logging on" row still plans. + change = plan([Action("env", key="PROTON_LOG", value="1")], state("")) + assert change.blocked == "" and change.after == state("PROTON_LOG=1 %command%") def test_plan_refuses_a_line_break() -> None: for value in ("-a\n-b", '-a "x\ny"', "-a\r", "-a\x00"): - change = plan([Action("user_snippet", value=value)], state("%command%")) + change = plan([Action("user_snippet", value=value)], state("%command%"), user=True) assert "line break" in change.blocked assert not change.changed - assert plan([Action("env", key="A", value="a\nb")], state("%command%")).blocked + assert plan([Action("env", key="DXVK_ASYNC", value="a\nb")], state("%command%")).blocked # one already inside a quoted part of the line survives splitting, and is refused too change = plan([Action("game_arg", value="-x")], state('FOO="a\nb" %command%')) assert "line break" in change.blocked # A blocked step stops later steps, so the result is never a half-applied plan. - change = plan([Action("env", key="A", value="b c"), Action("default_proton")], state("%command%", "x")) + change = plan([Action("env", key="DXVK_ASYNC", value="b c"), Action("default_proton")], + state("%command%", "x")) assert change.after == state("%command%", "x") @@ -200,12 +250,12 @@ def test_apply_refuses_when_the_settings_moved(files: tuple[Path, Path]) -> None def test_apply_refuses_blocked_unchanged_and_unreadable(files: tuple[Path, Path], tmp_path: Path) -> None: localconfig, config_vdf = files current = read_state(localconfig, config_vdf, APP) - blocked = plan([Action("env", key="A", value="a b")], current) + blocked = plan([Action("env", key="DXVK_ASYNC", value="a b")], current) result = apply_change(localconfig, config_vdf, APP, blocked, label="x", finding_id="y") assert result.message == blocked.blocked same = plan([Action("manual", text="Do it.")], current) assert not apply_change(localconfig, config_vdf, APP, same, label="x", finding_id="y").ok - change = plan([Action("env", key="A", value="1")], current) + change = plan([Action("env", key="DXVK_ASYNC", value="1")], current) result = apply_change(tmp_path / "missing.vdf", config_vdf, APP, change, label="x", finding_id="y") assert not result.ok and "could not be read" in result.message assert undo_available(APP) is None @@ -219,7 +269,7 @@ def fail(*_args: object) -> None: raise OSError("disk full") monkeypatch.setattr(snapshots, "record", fail) - both = [Action("env", key="A", value="1"), Action("default_proton")] + both = [Action("env", key="DXVK_ASYNC", value="1"), Action("default_proton")] change = plan(both, read_state(localconfig, config_vdf, APP)) result = apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y") assert not result.ok @@ -233,7 +283,7 @@ def test_second_write_failure_puts_the_first_back( localconfig, config_vdf = files before = read_state(localconfig, config_vdf, APP) monkeypatch.setattr(fix_apply, "set_compat_tool", lambda *_a: False) - change = plan([Action("env", key="A", value="1"), Action("default_proton")], before) + change = plan([Action("env", key="DXVK_ASYNC", value="1"), Action("default_proton")], before) result = apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y") assert not result.ok assert "put back" in result.message @@ -241,31 +291,81 @@ def test_second_write_failure_puts_the_first_back( assert result.snapshot_id == "" and undo_available(APP) is None -def test_failed_rollback_says_what_the_options_are( +def test_failed_rollback_keeps_the_snapshot_so_undo_can_finish( files: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch, ) -> None: localconfig, config_vdf = files - real = fix_apply.set_launch_options + before = read_state(localconfig, config_vdf, APP) + real_lo, real_ct = fix_apply.set_launch_options, fix_apply.set_compat_tool calls: list[str] = [] def first_only(path: Path, app_id: str, options: str) -> bool: calls.append(options) - return real(path, app_id, options) if len(calls) == 1 else False + return real_lo(path, app_id, options) if len(calls) == 1 else False monkeypatch.setattr(fix_apply, "set_launch_options", first_only) monkeypatch.setattr(fix_apply, "set_compat_tool", lambda *_a: (_ for _ in ()).throw(OSError("boom"))) - both = [Action("env", key="A", value="1"), Action("default_proton")] - change = plan(both, read_state(localconfig, config_vdf, APP)) + both = [Action("env", key="DXVK_ASYNC", value="1"), Action("default_proton")] + change = plan(both, before) result = apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y") assert not result.ok - assert '"A=1 gamemoderun %command%"' in result.message and '"gamemoderun %command%"' in result.message + assert '"DXVK_ASYNC=1 gamemoderun %command%"' in result.message + assert '"gamemoderun %command%"' in result.message + assert "Undo" in result.message + half = state("DXVK_ASYNC=1 gamemoderun %command%", "GE-Proton9-20") + assert result.state == half and read_state(localconfig, config_vdf, APP) == half + assert result.launch_changed + # The only record of "before" is kept ... + snap = undo_available(APP) + assert snap is not None and snap.id == result.snapshot_id and snap.before == before + # ... and Undo finishes the job without asking, since nothing in the + # half state was written by anyone but the fix. + monkeypatch.setattr(fix_apply, "set_launch_options", real_lo) + monkeypatch.setattr(fix_apply, "set_compat_tool", real_ct) + undone = undo_latest(localconfig, config_vdf, APP) + assert undone.ok and not undone.conflict, undone.message + assert read_state(localconfig, config_vdf, APP) == before assert undo_available(APP) is None +def test_failed_first_write_drops_the_snapshot( + files: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch, +) -> None: + localconfig, config_vdf = files + before = read_state(localconfig, config_vdf, APP) + monkeypatch.setattr(fix_apply, "set_launch_options", lambda *_a: False) + change = plan([Action("env", key="DXVK_ASYNC", value="1"), Action("default_proton")], before) + result = apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y") + assert not result.ok and "nothing was changed" in result.message + # Read back as before, so the snapshot has nothing left to undo. + assert read_state(localconfig, config_vdf, APP) == before + assert result.snapshot_id == "" and undo_available(APP) is None + assert not result.launch_changed + + +def test_a_write_that_says_no_but_landed_keeps_the_snapshot( + files: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch, +) -> None: + localconfig, config_vdf = files + before = read_state(localconfig, config_vdf, APP) + real = fix_apply.set_launch_options + + def writes_then_fails(path: Path, app_id: str, options: str) -> bool: + real(path, app_id, options) + return False + + monkeypatch.setattr(fix_apply, "set_launch_options", writes_then_fails) + change = plan([Action("env", key="DXVK_ASYNC", value="1")], before) + result = apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y") + assert not result.ok + assert "nothing was changed" not in result.message and "Undo" in result.message + assert result.snapshot_id and undo_available(APP) is not None + + def test_apply_checks_what_landed(files: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch) -> None: localconfig, config_vdf = files monkeypatch.setattr(fix_apply, "set_launch_options", lambda *_a: True) # says yes, writes nothing - change = plan([Action("env", key="A", value="1")], read_state(localconfig, config_vdf, APP)) + change = plan([Action("env", key="DXVK_ASYNC", value="1")], read_state(localconfig, config_vdf, APP)) result = apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y") assert not result.ok and "do not show it" in result.message # The undo point stays, so whatever did land can still be put back. @@ -299,7 +399,7 @@ def test_undo_refuses_to_overwrite_later_changes(files: tuple[Path, Path]) -> No write_files(localconfig, config_vdf, state("PROTON_LOG=1 mangohud %command%", "GE-Proton9-20")) result = undo_latest(localconfig, config_vdf, APP) - assert not result.ok + assert not result.ok and result.conflict assert "changed after the fix was applied" in result.message assert '"PROTON_LOG=1 mangohud %command%"' in result.message assert '"gamemoderun %command%"' in result.message @@ -308,7 +408,7 @@ def test_undo_refuses_to_overwrite_later_changes(files: tuple[Path, Path]) -> No assert undo_available(APP) is not None forced = undo_latest(localconfig, config_vdf, APP, force=True) - assert forced.ok + assert forced.ok and not forced.conflict assert read_state(localconfig, config_vdf, APP) == before assert undo_available(APP) is None @@ -316,7 +416,7 @@ def test_undo_refuses_to_overwrite_later_changes(files: tuple[Path, Path]) -> No def test_undo_when_already_back(files: tuple[Path, Path]) -> None: localconfig, config_vdf = files before = read_state(localconfig, config_vdf, APP) - change = plan([Action("env", key="A", value="1")], before) + change = plan([Action("env", key="DXVK_ASYNC", value="1")], before) assert apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y").ok write_files(localconfig, config_vdf, before) result = undo_latest(localconfig, config_vdf, APP) @@ -324,12 +424,84 @@ def test_undo_when_already_back(files: tuple[Path, Path]) -> None: assert undo_available(APP) is None +def test_undo_first_write_failure_keeps_the_snapshot( + files: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch, +) -> None: + localconfig, config_vdf = files + change = plan([Action("env", key="DXVK_ASYNC", value="1")], read_state(localconfig, config_vdf, APP)) + assert apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y").ok + monkeypatch.setattr(fix_apply, "set_launch_options", lambda *_a: False) + result = undo_latest(localconfig, config_vdf, APP) + assert not result.ok and "the fix is still in place" in result.message + assert read_state(localconfig, config_vdf, APP) == change.after + assert not result.launch_changed + assert undo_available(APP) is not None + + +def test_undo_failed_rollback_keeps_the_snapshot( + files: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch, +) -> None: + localconfig, config_vdf = files + before = read_state(localconfig, config_vdf, APP) + change = plan([Action("env", key="DXVK_ASYNC", value="1"), Action("default_proton")], before) + assert apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y").ok + real_lo, real_ct = fix_apply.set_launch_options, fix_apply.set_compat_tool + calls: list[str] = [] + + def first_only(path: Path, app_id: str, options: str) -> bool: + calls.append(options) + return real_lo(path, app_id, options) if len(calls) == 1 else False + + monkeypatch.setattr(fix_apply, "set_launch_options", first_only) + monkeypatch.setattr(fix_apply, "set_compat_tool", lambda *_a: False) + result = undo_latest(localconfig, config_vdf, APP) + assert not result.ok and "could not be put back" in result.message + half = state("gamemoderun %command%", "") + assert read_state(localconfig, config_vdf, APP) == half + assert result.launch_changed + # Not at "before", so the snapshot stays, and a second Undo finishes. + assert undo_available(APP) is not None + monkeypatch.setattr(fix_apply, "set_launch_options", real_lo) + monkeypatch.setattr(fix_apply, "set_compat_tool", real_ct) + again = undo_latest(localconfig, config_vdf, APP) + assert again.ok and not again.conflict, again.message + assert read_state(localconfig, config_vdf, APP) == before + assert undo_available(APP) is None + + +def test_undo_that_does_not_land_keeps_the_snapshot( + files: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch, +) -> None: + localconfig, config_vdf = files + change = plan([Action("env", key="DXVK_ASYNC", value="1")], read_state(localconfig, config_vdf, APP)) + assert apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y").ok + monkeypatch.setattr(fix_apply, "set_launch_options", lambda *_a: True) # says yes, writes nothing + result = undo_latest(localconfig, config_vdf, APP) + assert not result.ok and "do not show them" in result.message + assert undo_available(APP) is not None + + +def test_results_say_whether_the_launch_options_changed(files: tuple[Path, Path]) -> None: + localconfig, config_vdf = files + before = read_state(localconfig, config_vdf, APP) + proton_only = plan([Action("default_proton")], before) + applied = apply_change(localconfig, config_vdf, APP, proton_only, label="x", finding_id="y") + assert applied.ok and not applied.launch_changed + undone = undo_latest(localconfig, config_vdf, APP) + assert undone.ok and not undone.launch_changed + launch = plan([Action("env", key="PROTON_LOG", value="1")], before) + applied = apply_change(localconfig, config_vdf, APP, launch, label="x", finding_id="y") + assert applied.ok and applied.launch_changed + undone = undo_latest(localconfig, config_vdf, APP) + assert undone.ok and undone.launch_changed + + def test_undo_write_failure_keeps_the_snapshot( files: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch, ) -> None: localconfig, config_vdf = files before = read_state(localconfig, config_vdf, APP) - change = plan([Action("env", key="A", value="1"), Action("default_proton")], before) + change = plan([Action("env", key="DXVK_ASYNC", value="1"), Action("default_proton")], before) assert apply_change(localconfig, config_vdf, APP, change, label="x", finding_id="y").ok monkeypatch.setattr(fix_apply, "set_compat_tool", lambda *_a: False) result = undo_latest(localconfig, config_vdf, APP) diff --git a/tests/test_fix_pack.py b/tests/test_fix_pack.py index 29f46d8..7caedd4 100644 --- a/tests/test_fix_pack.py +++ b/tests/test_fix_pack.py @@ -455,7 +455,11 @@ def test_env_values_rejected(value: Any) -> None: rejects(with_actions({"type": "env", "key": "DXVK_HUD", "value": value}), "value") -@pytest.mark.parametrize("key", ["A", "_", "_a1", "DXVK_HUD", "mesa_glthread"]) +@pytest.mark.parametrize( + "key", + ["PROTON_LOG", "WINE_CPU_TOPOLOGY", "DXVK_HUD", "VKD3D_CONFIG", "MESA_GLTHREAD", "RADV_PERFTEST", + "__GL_SHADER_DISK_CACHE", "__NV_PRIME_RENDER_OFFLOAD", "SDL_VIDEODRIVER", "MANGOHUD", "MANGOHUD_CONFIG"], +) @pytest.mark.parametrize("kind", ["env", "unset_env"]) def test_env_keys_accepted(kind: str, key: str) -> None: action: dict[str, Any] = {"type": kind, "key": key} @@ -464,11 +468,19 @@ def test_env_keys_accepted(kind: str, key: str) -> None: assert parse_rule(with_actions(action)).actions[0].key == key +@pytest.mark.parametrize("key", ["A", "_", "_a1", "mesa_glthread", "MY_VAR", "DXVK", "proton_log"]) +def test_env_keys_outside_the_families(key: str) -> None: + # Setting is limited to the families; removing is not. + rejects(with_actions({"type": "env", "key": key, "value": "1"}), "not in a family") + assert parse_rule(with_actions({"type": "unset_env", "key": key})).actions[0].key == key + + @pytest.mark.parametrize( "key", ["", "1A", "A-B", "A B", "A=", "A\n", "ÉTÉ", None, 5, "LD_PRELOAD", "LD_LIBRARY_PATH", "LD_AUDIT", "PATH", "PYTHONPATH", - "STEAM_COMPAT_LAUNCHER_SERVICE", "WINEDLLPATH", "STEAM_COMPAT_DATA_PATH", "STEAM_COMPAT_"], + "STEAM_COMPAT_LAUNCHER_SERVICE", "WINEDLLPATH", "STEAM_COMPAT_DATA_PATH", "STEAM_COMPAT_", + "PROTON_REMOTE_DEBUG_CMD", "SDL_DYNAMIC_API", "WINEDLLOVERRIDES"], ) @pytest.mark.parametrize("kind", ["env", "unset_env"]) def test_env_keys_rejected(kind: str, key: Any) -> None: @@ -480,7 +492,7 @@ def test_env_keys_rejected(kind: str, key: Any) -> None: def test_forbidden_list_is_case_sensitive() -> None: # Variables are case sensitive: ``path`` is not ``PATH``. - assert parse_rule(with_actions({"type": "env", "key": "path", "value": "1"})).actions[0].key == "path" + assert parse_rule(with_actions({"type": "unset_env", "key": "path"})).actions[0].key == "path" rejects(with_actions({"type": "unset_env", "key": "STEAM_COMPAT_CLIENT_INSTALL_PATH"}), "may not") @@ -524,8 +536,8 @@ def test_default_proton_has_no_fields() -> None: @pytest.mark.parametrize( "actions", [ - [{"type": "env", "key": "A", "value": "1"}, {"type": "env", "key": "A", "value": "2"}], - [{"type": "env", "key": "A", "value": "1"}, {"type": "unset_env", "key": "A"}], + [{"type": "env", "key": "DXVK_HUD", "value": "1"}, {"type": "env", "key": "DXVK_HUD", "value": "2"}], + [{"type": "env", "key": "DXVK_HUD", "value": "1"}, {"type": "unset_env", "key": "DXVK_HUD"}], [{"type": "default_proton"}, {"type": "default_proton"}], [{"type": "game_arg", "value": "-vulkan"}, {"type": "game_arg", "value": "-vulkan"}], ], @@ -545,7 +557,10 @@ def test_conflicting_or_repeated_actions(actions: list[dict[str, Any]]) -> None: r"\.\.\.\.\.\.\.\.", # escaped characters are literals r"[.][.][.][.][.][.][.][.]", # a one-member class is that literal r"(kern)el32", # an unquantified group is part of the run - r"(?:kernel32\.dll)+", # a repeat that happens at least once guarantees its text + r"(?:kernel32\.dll){1}", # a repeat that happens at least once guarantees its text + r"\S+ kernel32\.dll", # a repeated class + r"[0-9a-f]{7} kernel32dll", + r"(a)+kernel32dll", # a group of one character is one character r"kernel32\.dll|kernel32\.sys", # both branches share the run r"^err:module:import_dll Library \S+ not found$", r"(?:\d+ )?err:module:", # an optional group may hold a repeat @@ -574,7 +589,7 @@ def test_log_expression_length_limit() -> None: r"[kK]ernel32", # a class of two is not a literal r"\bkernel\b32dll", # an anchor breaks the run r"abcdefg|abcdefgh", # one branch is too short - r"(?:kernel32\.dll)*", # may not happen at all + r"(?:kernel32\.dll){0,1}", # may not happen at all r"(?:kernel32\.dll)?", r"(?=kernel32\.dll)", # lookaround text is not consumed r"a{8}", @@ -597,12 +612,31 @@ def test_log_expressions_without_a_literal_run(pattern: str) -> None: r"(?:x(?:y+z)+)+kernel32dll", r"(\d+\s)++kernel32dll", r"kernel32dll(?=(a+)+)", + # a repeated group without a repeat inside is refused too + r"(?:aaaaaaaa|aaaaaaaaaaaaaaaa)+$", + r"(?:ab){2,50}kernel32dll", + r"(a|aa){3}kernel32dll", + r"(?:kernel32\.dll)+", + r"(?:kernel32\.dll)*", + r"kernel32dll(?:\.so)?(?:ab)+", + r"(?:(?:ab)+)?kernel32dll", # inside an optional group, checked all the same ], ) -def test_log_expressions_with_nested_repeats(pattern: str) -> None: +def test_log_expressions_with_repeated_groups(pattern: str) -> None: rejects(with_match(log=[pattern]), "repeats a group") +def test_backtracking_pattern_is_refused_before_it_ever_runs() -> None: + # The review's example takes exponential time on a line of a's that does + # not end where $ wants. Asserting the time would flake; what matters is + # that the loader refuses it, so match_log never gets to run it. + pattern = r"(?:aaaaaaaa|aaaaaaaaaaaaaaaa)+$" + msg = rejects(with_match(log=[pattern]), "repeats a group") + assert msg.startswith("match.log") + loaded = parse_pack(pack(rule(match={"log": [pattern]}))) + assert loaded.rules == [] and "repeats a group" in loaded.rejected[0][1] + + @pytest.mark.parametrize("pattern", [r"kernel32(", r"kernel32[", "kernel32\\", r"*kernel32", r"kernel32{2,1}"]) def test_log_expressions_that_do_not_compile(pattern: str) -> None: rejects(with_match(log=[pattern]), "does not compile") @@ -1136,7 +1170,6 @@ def test_user_rules_values_are_not_held_to_pack_limits(user_dir: Path) -> None: {"title": "t", "type": "launch_arg", "value": "x" * 501}, {"title": "t", "type": "launch_arg", "value": " "}, {"title": "t", "type": "wrapper", "value": "gamemoderun"}, - {"title": "t", "value": "1", "key": "A"}, {"title": 5, "type": "env", "key": "A", "value": "1"}, {"title": "t", "description": ["x"], "type": "env", "key": "A", "value": "1"}, ["not", "a", "dict"], @@ -1148,6 +1181,13 @@ def test_user_rules_skip_unusable_entries(user_dir: Path, entry: Any) -> None: assert user_rules("570") == [] +def test_user_rules_entry_without_a_type_is_env(user_dir: Path) -> None: + # Version 1 read an entry with no type as env. + write_user(user_dir, "570", [{"title": "t", "key": "DXVK_HUD", "value": "fps"}]) + (only,) = user_rules("570") + assert only.actions == (Action("env", key="DXVK_HUD", value="fps"),) + + def test_user_rules_snippet_cap(user_dir: Path) -> None: write_user(user_dir, "570", [{"title": "t", "type": "launch_arg", "value": "x" * 500}]) assert len(user_rules("570")[0].actions[0].value) == 500 diff --git a/tests/test_fix_pack_rules.py b/tests/test_fix_pack_rules.py index 6975f34..7c90920 100644 --- a/tests/test_fix_pack_rules.py +++ b/tests/test_fix_pack_rules.py @@ -9,6 +9,7 @@ from __future__ import annotations +import dataclasses import json import re from pathlib import Path @@ -17,6 +18,7 @@ import pytest from protonshift.core import fix_pack +from protonshift.core.diagnose import Facts, rule_finding from protonshift.core.fix_pack import Action, Rule, load_bundled_pack, match_log PACK_PATH = Path(fix_pack.__file__).parent / "data" / "fix_pack.json" @@ -264,11 +266,11 @@ def unset(key: str) -> Action: (), ), "cyberpunk-2077-camera-jumps": ( - ("1091500",), {"proton_major_min": 10}, + ("1091500",), {"proton_major_min": 10, "env_unset": ("PROTON_DISABLE_HIDRAW",)}, (Action("env", key="PROTON_DISABLE_HIDRAW", value="1"),), ), "elden-ring-many-threads": ( - ("1245620",), {}, + ("1245620",), {"env_unset": ("WINE_CPU_TOPOLOGY",)}, (Action("env", key="WINE_CPU_TOPOLOGY", value="16:0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15"),), ), } @@ -315,6 +317,25 @@ def test_wayland_rule_names_both_choices() -> None: assert "--expose-wayland" in action.text and "PROTON_ENABLE_WAYLAND" in action.text +@pytest.mark.parametrize( + ("rule_id", "app_id", "key"), + [("cyberpunk-2077-camera-jumps", "1091500", "PROTON_DISABLE_HIDRAW"), + ("elden-ring-many-threads", "1245620", "WINE_CPU_TOPOLOGY")], +) +def test_game_tweak_is_no_longer_offered_once_applied(rule_id: str, app_id: str, key: str) -> None: + facts = Facts( + app_id=app_id, steam_app=True, native=False, launch_options="%command%", launch_options_readable=True, + compat_tool="proton_10", proton_family="valve", proton_major=10, gpu_vendors=frozenset({"amd"}), + session="wayland", log_lines=None, log_modified="", + ) + rule = RULES[rule_id] + assert rule_finding(rule, facts) is not None + # The line its own fix writes: the finding is gone. + (action,) = (a for a in rule.actions if a.type == "env") + applied = f"{key}={action.value} %command%" + assert rule_finding(rule, dataclasses.replace(facts, launch_options=applied)) is None + + def test_elden_ring_rule_names_the_thread_count() -> None: rule = RULES["elden-ring-many-threads"] assert "24" in rule.title and "24" in rule.cause @@ -331,7 +352,7 @@ def test_elden_ring_rule_names_the_thread_count() -> None: def test_pack_loads_every_rule() -> None: assert PACK.rejected == [] - assert PACK.revision == "2026.11.2" + assert PACK.revision == "2026.11.3" assert len(RULES) == len(PACK.rules) diff --git a/tests/test_launch_check.py b/tests/test_launch_check.py index f1a508b..e0bf8fa 100644 --- a/tests/test_launch_check.py +++ b/tests/test_launch_check.py @@ -8,7 +8,8 @@ from protonshift.core import proton_log from protonshift.core.fix_pack import Action -from protonshift.core.launch_check import check_launch, check_launch_options, detect_anticheat, summarize +from protonshift.core.launch_check import check_launch, check_launch_options, detect_anticheat +from protonshift.core.launch_merge import add_command def levels(findings: list[dict[str, str]]) -> list[str]: @@ -56,6 +57,26 @@ def test_missing_tools() -> None: assert "gamescope isn't installed" in titles(found) +def test_quoted_assignment_is_one_word() -> None: + # The scan splits as the shell does: a command name inside a value is not a command. + assert levels(check_launch_options("KEY='a gamemoderun;b' %command%", lacks)) == ["ok"] + + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ("strangle 60", "strangle 60 %command%"), + ("mangohud --dlsym", "mangohud --dlsym %command%"), + ("gamescope -W 1920 -H 1080 -f", "gamescope -W 1920 -H 1080 -f -- %command%"), + ], +) +def test_missing_command_fix_keeps_wrapper_options(text: str, expected: str) -> None: + (found,) = check_launch_options(text, has) + assert found["id"] == "command-missing" + assert found["actions"] == (Action("add_command"),) + assert add_command(text) == expected + + def test_tool_named_after_command_is_a_game_argument() -> None: # after %command% everything belongs to the game, whatever it is called assert levels(check_launch_options("%command% gamescope", lacks)) == ["ok"] @@ -79,17 +100,24 @@ def test_healthy_game(tmp_path: Path) -> None: found = run(tmp_path) assert "error" not in levels(found) assert "warn" not in levels(found) - assert summarize(found) == "No problems found." def test_removed_proton_build(tmp_path: Path) -> None: found = run(tmp_path, compat_tool="GE-Proton9-20") assert found[0]["level"] == "error" assert "GE-Proton9-20" in found[0]["title"] - assert "1 problem that will stop" in summarize(found) + assert levels(found).count("error") == 1 assert "Proton build is installed" in titles(run(tmp_path, compat_tool="GE-Proton10-1")) +def test_steam_runtime_row_is_not_called_a_proton_build(tmp_path: Path) -> None: + tool = "steamlinuxruntime_sniper" + found = by_id(run(tmp_path, compat_tool=tool, available_tools=["", tool])) + assert found["proton-ok"]["title"] == f"Compatibility tool is provided by Steam: {tool}" + proton = by_id(run(tmp_path, compat_tool="GE-Proton10-1")) + assert proton["proton-ok"]["title"] == "Proton build is installed: GE-Proton10-1" + + def test_missing_install_folder(tmp_path: Path) -> None: assert "install folder is missing" in titles(run(tmp_path, install_path=tmp_path / "gone")) @@ -102,7 +130,7 @@ def test_anticheat_runtime(tmp_path: Path) -> None: found = run(tmp_path) assert "Proton EasyAntiCheat Runtime isn't installed" in titles(found) assert "Proton BattlEye Runtime isn't installed" in titles(found) - assert "2 things worth a look" in summarize(found) + assert levels(found).count("warn") == 2 fixed = run(tmp_path, installed_app_ids=["1826330", "1161040"]) assert "warn" not in levels(fixed) diff --git a/tests/test_launch_merge.py b/tests/test_launch_merge.py index 96f6d46..b380bea 100644 --- a/tests/test_launch_merge.py +++ b/tests/test_launch_merge.py @@ -7,6 +7,9 @@ from protonshift.core.launch_merge import ( add_command, add_game_arg, + env_word, + prefix_commands, + prefix_env, remove_word, set_env, single_command, @@ -44,6 +47,9 @@ ("%command%", "%command% -dx11", "%command% -dx11"), # quoted values survive ('FOO="a b" %command%', "gamemoderun", 'FOO="a b" gamemoderun %command%'), + # a quoted assignment stays one word and stays in front of a new wrapper + ("KEY='a b;c' gamemoderun %command%", "gamescope -f --", + "KEY='a b;c' gamescope -f -- gamemoderun %command%"), ], ) def test_merge(text: str, snippet: str, expected: str) -> None: @@ -77,6 +83,7 @@ def test_merge_twice_equals_once() -> None: ("text", "expected"), [ ("KEY='a b' %command%", ["KEY='a b'", "%command%"]), + ("KEY='a b;c' gamemoderun %command%", ["KEY='a b;c'", "gamemoderun", "%command%"]), ('FOO="a b" gamemoderun %command%', ['FOO="a b"', "gamemoderun", "%command%"]), ('A="x \\" y" %command%', ['A="x \\" y"', "%command%"]), ("A=a\\ b %command%", ["A=a\\ b", "%command%"]), @@ -114,6 +121,13 @@ def test_split_line_reads_a_line_without_command_as_arguments() -> None: ("A=1 %command%", "A", "1", "A=1 %command%"), # gamescope's options are not touched ("gamescope -f -- %command%", "A", "1", "A=1 gamescope -f -- %command%"), + # a value outside the pack's characters (a user's own) is single-quoted ... + ("gamemoderun %command%", "WINEDLLOVERRIDES", "d3d9=n;dinput8=n,b", + "WINEDLLOVERRIDES='d3d9=n;dinput8=n,b' gamemoderun %command%"), + ("%command%", "A", "a b", "A='a b' %command%"), + # ... and replaces an existing quoted assignment of the key as one word + ("A='x y' B=1 %command%", "A", "a b;c", "A='a b;c' B=1 %command%"), + ('A="x y" %command%', "A", "1", "A=1 %command%"), ], ) def test_set_env(text: str, key: str, value: str, expected: str) -> None: @@ -121,6 +135,31 @@ def test_set_env(text: str, key: str, value: str, expected: str) -> None: assert set_env(expected, key, value) == expected +@pytest.mark.parametrize("value", ["it's", "a\nb", "a\rb", "a\x00b", "%command%", "x%command%y"]) +def test_env_word_refuses_what_quoting_cannot_make_safe(value: str) -> None: + with pytest.raises(ValueError): + env_word("A", value) + with pytest.raises(ValueError): + set_env("%command%", "A", value) + + +def test_env_word_quotes_only_when_needed() -> None: + assert env_word("A", "fps,frametime") == "A=fps,frametime" + assert env_word("A", "") == "A=" + assert env_word("A", "a b") == "A='a b'" + assert env_word("A", "$HOME") == "A='$HOME'" + + +def test_a_quoted_assignment_is_one_assignment_everywhere() -> None: + line = "KEY='a b;c gamemoderun' mangohud %command%" + prefix = split_line(line)[0] + assert prefix_env(prefix) == ["KEY='a b;c gamemoderun'"] + assert prefix_commands(prefix) == ["mangohud"] + assert unset_env(line, "KEY") == "mangohud %command%" + # gamemoderun inside the value is not a command to remove + assert remove_word(line, "gamemoderun") == line + + def test_set_env_refuses_a_bad_key() -> None: with pytest.raises(ValueError): set_env("%command%", "A B", "1") @@ -221,9 +260,35 @@ def test_single_command(text: str, expected: str) -> None: ("gamemoderun", "gamemoderun %command%"), ("PROTON_LOG=1", "PROTON_LOG=1 %command%"), ("PROTON_LOG=1 gamemoderun -novid", "PROTON_LOG=1 gamemoderun %command% -novid"), + ("PROTON_LOG=1 gamemoderun +connect", "PROTON_LOG=1 gamemoderun %command% +connect"), ("FOO='a b' mangohud", "FOO='a b' mangohud %command%"), ("gamescope -f -b -- -novid", "gamescope -f -b -- %command% -novid"), ("/usr/bin/gamemoderun -novid", "/usr/bin/gamemoderun %command% -novid"), + # a command keeps its own option-like words, as remove_word reads them + ("strangle 60", "strangle 60 %command%"), + ("mangohud --dlsym", "mangohud --dlsym %command%"), + ("strangle 60 +fps_max=0", "strangle 60 %command% +fps_max=0"), + # a command that takes no options runs the next word, so the game goes right after it + ("gamemoderun -novid", "gamemoderun %command% -novid"), + ("prime-run -novid 60", "prime-run %command% -novid 60"), + ("obs-gamecapture --x", "obs-gamecapture %command% --x"), + ("gamemoderun strangle 60 -novid", "gamemoderun strangle 60 %command% -novid"), + ("/usr/bin/mangohud --dlsym -novid", "/usr/bin/mangohud --dlsym %command% -novid"), + ("strangle -k 60:30 -dx11", "strangle -k 60:30 %command% -dx11"), + # a wrapper without -- owns every word after it + ("gamescope -W 1920 -H 1080 -f", "gamescope -W 1920 -H 1080 -f -- %command%"), + ("gamescope", "gamescope -- %command%"), + ("SCB_AUTO_RES=1 scb", "SCB_AUTO_RES=1 scb -- %command%"), + # with a --, the game goes right after it and the rest stays the game's + ("gamescope -W 1920 -- -novid +x", "gamescope -W 1920 -- %command% -novid +x"), + # env assignments first, then two commands + ("A=1 B=2 strangle 60 mangohud --dlsym +connect", + "A=1 B=2 strangle 60 mangohud --dlsym %command% +connect"), + ("PROTON_LOG=1 gamemoderun gamescope -f", "PROTON_LOG=1 gamemoderun gamescope -f -- %command%"), + ("gamescope -f -- gamemoderun +x", "gamescope -f -- gamemoderun %command% +x"), + # a quoted argument stays one word, for the game or the wrapper + ("FOO='a b' strangle 60 'my arg'", "FOO='a b' strangle 60 %command% 'my arg'"), + ("gamescope --cursor 'a b.png'", "gamescope --cursor 'a b.png' -- %command%"), # nothing at the start that belongs before the game ("-novid gamemoderun", "-novid gamemoderun"), # already there diff --git a/tests/test_system_checks.py b/tests/test_system_checks.py index 54b6d4b..c0fe3d5 100644 --- a/tests/test_system_checks.py +++ b/tests/test_system_checks.py @@ -468,6 +468,42 @@ def test_run_checks_missing_paths_never_raise(tmp_path: Path, monkeypatch: pytes assert [c.state for c in checks[2:]] == ["unknown", "unknown"] +def flatpak_root(tmp_path: Path) -> Path: + root = tmp_path / ".var" / "app" / "com.valvesoftware.Steam" / ".local" / "share" / "Steam" + root.mkdir(parents=True) + return root + + +@pytest.mark.parametrize( + "run", + [runner(1, "", NO_DRIVER_STDERR), runner(0, LLVMPIPE_ONLY), raising(FileNotFoundError()), + runner(0, REAL_SUMMARY)], + ids=["no-driver", "software-only", "no-vulkaninfo", "host-ok"], +) +def test_flatpak_steam_vulkan_is_unknown( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run: object, +) -> None: + # Flatpak Steam's games use the runtime's drivers: whatever the host says, + # it is not the answer, so it is never a problem (or a tick). + monkeypatch.setattr(sc, "default_icd_dirs", lambda: [tmp_path / "icd.d"]) + checks = sc.run_checks(steam_root=flatpak_root(tmp_path), install_path=None, prefix_path=None, run=run) + vulkan = next(c for c in checks if c.id == "vulkan") + assert vulkan.state == "unknown" + assert "Flatpak" in vulkan.detail and "its own drivers" in vulkan.detail + assert next(c for c in checks if c.id == "vulkan-32bit").state == "unknown" + + +def test_flatpak_steam_vulkan_runs_nothing() -> None: + assert sc.check_vulkan(raising(AssertionError("must not run")), flavor="flatpak").state == "unknown" + + +def test_native_steam_vulkan_problem_stays_a_problem(tmp_path: Path) -> None: + root = tmp_path / "steam" + root.mkdir() + checks = sc.run_checks(steam_root=root, install_path=None, prefix_path=None, run=runner(0, LLVMPIPE_ONLY)) + assert next(c for c in checks if c.id == "vulkan").state == "problem" + + def test_text_has_no_long_dashes(tmp_path: Path) -> None: source = Path(sc.__file__).read_text(encoding="utf-8") assert chr(0x2014) not in source and chr(0x2013) not in source