Play Windows games on Apple Silicon Macs. Free, open-source app that installs the official Battle.net, Steam, Epic and GOG launchers and lists your games in one library.
HTML apple-siliconbattle-netcrossover-alternatived3dmetaldiablo-ii-resurrecteddxmtea-appepic-gamesgame-porting-toolkitgogmac-gamingmacosmacos-gamingrockstar-gamessteamubisoft-connectwhisky-alternativewindows-gameswinewine-wrapper
Fix Steam runtime recovery and safe uninstall (#39)
Mikek4ad0f40ad2f3
diff --git a/README.md b/README.mdindex 8a00a39f734..154401440b0 100644--- a/README.md+++ b/README.md@@ -24,7 +24,7 @@ CodeWeavers' published sources; Steam uses a separate private Wine 11 setup.Apple's proprietary GPTK/D3DMetal is downloaded separately. Games and storeclients are not included.-**Current release: [v1.6.4](https://github.com/BCD1210/soju/releases/tag/v1.6.4).**+**Current release: [v1.6.5](https://github.com/BCD1210/soju/releases/tag/v1.6.5).**The compatibility examples below were verified on M4 Pro / macOS 26.5.D2R and Hogwarts Legacy are examples of supported games, not the scope of the project.@@ -94,7 +94,7 @@ soju install # then: soju battlenet / soju d2r / soju steam / soju epic / soThe installer asks which launchers you want **before downloading anything**. Steam-only installs skip the CX engine and Apple GPTK. Steam rendering components are downloaded with SHA-256 verification and installed in a Soju-owned Wine 11.0 runtime. Battle.net, Epic and GOG use the shared CX engine and your separately downloaded Apple GPTK. Each official client keeps its own bottle and shortcut in `~/Applications`.-[Download Soju for Mac](https://github.com/BCD1210/soju/releases/download/v1.6.4/Soju-1.6.4-macos-arm64.zip) — the native desktop preview includes installed and owned games, store search, favorites, game launching and platform management. See [desktop setup and requirements](docs/DESKTOP.md).+[Download Soju for Mac](https://github.com/BCD1210/soju/releases/download/v1.6.5/Soju-1.6.5-macos-arm64.zip) — the native desktop preview includes installed and owned games, store search, favorites, game launching and platform management. See [desktop setup and requirements](docs/DESKTOP.md).## Everyday commandsdiff --git a/VERSION b/VERSIONindex 9edc58bb1dd..9f05f9f2ce1 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.6.4+1.6.5diff --git a/docs/DESKTOP.md b/docs/DESKTOP.mdindex 910301c261c..4413e69e2e3 100644--- a/docs/DESKTOP.md+++ b/docs/DESKTOP.md@@ -1,6 +1,6 @@# Soju for Mac-[Download v1.6.4](https://github.com/BCD1210/soju/releases/download/v1.6.4/Soju-1.6.4-macos-arm64.zip)+[Download v1.6.5](https://github.com/BCD1210/soju/releases/download/v1.6.5/Soju-1.6.5-macos-arm64.zip)1. Unzip and move **Soju.app** into Applications or ~/Applications.2. Open **Platforms** to install or open Battle.net, Steam, Epic Games or GOG GALAXY.diff --git a/docs/STEAM-GAMES.md b/docs/STEAM-GAMES.mdindex e994028649c..73350f90fb8 100644--- a/docs/STEAM-GAMES.md+++ b/docs/STEAM-GAMES.md@@ -91,3 +91,16 @@ scripts/create-steam-bottle.sh # private Wine 11 + wrapper + Steamscripts/setup-steam-games.sh # verified download + private DXMT/winemac runtimescripts/play.sh steam # play```+++### Repairing and removing Steam++Run `soju steam-install` again to repair the Wine runtime for an existing Steam+installation. Existing games remain in place. Close Windows Steam and its games+before repairing or changing the renderer.++`soju uninstall` resolves the same Steam runtime used for launching, waits for the+bottle to stop, and aborts if that fails. The separate Steam runtime category+includes the downloaded Wine build, prepared renderer and their rollback copies.+Declining bottle removal keeps installed games; separately installed Wine apps and+external `SOJU_STEAM_WINE` directories are preserved.diff --git a/docs/index.html b/docs/index.htmlindex fa9dd1e5bf3..c54617c5670 100644--- a/docs/index.html+++ b/docs/index.html@@ -102,7 +102,7 @@ its own login, purchases, downloads and game updates.</p><section id="install" aria-labelledby="install-title"><h2 id="install-title">Choose your launchers. Get set up.</h2>-<p><a class="btn" href="https://github.com/BCD1210/soju/releases/download/v1.6.4/Soju-1.6.4-macos-arm64.zip">Download Soju for Mac</a></p>+<p><a class="btn" href="https://github.com/BCD1210/soju/releases/download/v1.6.5/Soju-1.6.5-macos-arm64.zip">Download Soju for Mac</a></p><p>The native desktop preview combines installed and imported owned games, searches stores and manages all four launchers.Apple Silicon · app UI: macOS 14+ · Steam component build: macOS 26+.<a href="https://github.com/BCD1210/soju/blob/main/docs/DESKTOP.md">Setup and signing notes</a>.</p>diff --git a/install.sh b/install.shindex 45bf5279c53..1d02186012a 100644--- a/install.sh+++ b/install.sh@@ -199,12 +199,8 @@ for p in $PLATFORMS; doWINEPREFIX="$BOTTLE" bash "$SOJU_DIR/scripts/create-bottle.sh"fi ;;steam)- if [ -f "$BASE/steam-bottle/drive_c/Program Files (x86)/Steam/steam.exe" ]; then- say "Steam already installed - skipping"- else- say "Steam: verified Wine runtime + Steam installer"- WINEPREFIX="$BASE/steam-bottle" bash "$SOJU_DIR/scripts/create-steam-bottle.sh"- fi+ say "Steam: checking runtime and client (existing games are preserved)"+ WINEPREFIX="$BASE/steam-bottle" bash "$SOJU_DIR/scripts/create-steam-bottle.sh"WINEPREFIX="$BASE/steam-bottle" bash "$SOJU_DIR/scripts/setup-steam-games.sh" ;;epic)if [ -f "$BASE/epic-bottle/drive_c/Program Files/Epic Games/Launcher/Portal/Binaries/Win64/EpicGamesLauncher.exe" ]; thendiff --git a/scripts/create-steam-bottle.sh b/scripts/create-steam-bottle.shindex ae0c817b867..6dac1c15975 100755--- a/scripts/create-steam-bottle.sh+++ b/scripts/create-steam-bottle.sh@@ -20,19 +20,13 @@ if version(platform.mac_ver()[0]) < version(m['minimum_macos']):PYVERSIONunset DYLD_FALLBACK_LIBRARY_PATH WINEDLLOVERRIDES WINEMSYNC ROSETTA_ADVERTISE_AVXunset CX_ACTIVE_GRAPHICS_BACKEND CX_GRAPHICS_BACKEND CX_APPLEGPTK_LIBD3DSHARED_PATH WINE_SIMULATE_WRITECOPY+soju_ensure_steam_runtime "$REPO_ROOT"WINE="$STEAM_WINE_ROOT/bin/wine"-if [ ! -x "$WINE" ] || [ "$("$WINE" --version 2>/dev/null || true)" != wine-11.0 ]; then- if [ -n "${SOJU_STEAM_WINE:-}" ]; then- echo "SOJU_STEAM_WINE must point to a working Wine 11.0 runtime."; exit 1- fi- python3 "$REPO_ROOT/scripts/fetch-steam-wine.py"- source "$REPO_ROOT/scripts/steam-runtime.sh"- WINE="$STEAM_WINE_ROOT/bin/wine"-fi"$WINE" --version# ---------- 2. Verified wrapper and rendering components ----------python3 "$REPO_ROOT/scripts/fetch-steam-support.py"+python3 "$REPO_ROOT/scripts/steam-session.py" idle "$STEAM_WINE_ROOT"if [ -f "$WINEPREFIX/drive_c/Program Files (x86)/Steam/steam.exe" ]; thenpython3 "$REPO_ROOT/scripts/bootstrap-steam.py" "$WINE"echo "Steam already installed."diff --git a/scripts/setup-steam-games.sh b/scripts/setup-steam-games.shindex 1d978c7f848..5dce0e435a4 100755--- a/scripts/setup-steam-games.sh+++ b/scripts/setup-steam-games.sh@@ -38,26 +38,21 @@ python3 "$ROOT/scripts/fetch-steam-support.py"B="$WINEPREFIX/drive_c/windows"[ -d "$B/system32" ] || { echo "Install Steam first: soju steam-install"; exit 1; }unset DYLD_FALLBACK_LIBRARY_PATH WINEDLLOVERRIDES WINEMSYNC ROSETTA_ADVERTISE_AVX-unset CX_ACTIVE_GRAPHICS_BACKEND CX_GRAPHICS_BACKEND CX_APPLEGPTK_LIBD3DSHARED_PATH+unset CX_ACTIVE_GRAPHICS_BACKEND CX_GRAPHICS_BACKEND CX_APPLEGPTK_LIBD3DSHARED_PATH WINE_SIMULATE_WRITECOPYexport WINEDEBUG=-allVERSION=$(cat "$SUP/.soju-support-version")TARGET="$BASE/steam-runtime"-if [ "${1:-}" != --repair ] && [ -f "$TARGET/.soju-runtime" ] && \+if [ "${1:-}" != --repair ] && soju_steam_runtime_ready && \+ [ "$STEAM_WINE_ROOT" = "$TARGET" ] && [ -f "$TARGET/.soju-runtime" ] && \[ "$(cat "$WINEPREFIX/.soju-steam-games" 2>/dev/null || true)" = "$VERSION" ] && \[ "$(cat "$TARGET/.soju-runtime")" = "$VERSION" ]; thenecho "Steam rendering is ready ($VERSION)."exit 0fi+# Check before downloading/replacing Wine or editing the prefix.+python3 "$ROOT/scripts/steam-session.py" idle "$STEAM_WINE_ROOT"+soju_ensure_steam_runtime "$ROOT"SOURCE="$STEAM_WINE_ROOT"-[ -x "$SOURCE/bin/wine" ] || { echo "Prepare the Steam runtime first: soju steam-install"; exit 1; }-[ "$("$SOURCE/bin/wine" --version)" = wine-11.0 ] || {- echo "This Steam component release requires Wine 11.0. Existing runtime unchanged."; exit 1;-}-# Never migrate a live Wine Stable / private Steam session to another server.-if ps -axo comm= | grep -E '(Wine Stable.app|/steam-runtime)/.*wineserver$' >/dev/null; then- echo "Close Windows Steam and its games, then run soju steam-games again."- exit 1-fiNEW=$(mktemp -d "$BASE/.steam-runtime.XXXXXX")BACKUP=""; BACKUP_READY=0rollback(){diff --git a/scripts/steam-runtime.sh b/scripts/steam-runtime.shindex 8af1bfd994d..d80911e4623 100755--- a/scripts/steam-runtime.sh+++ b/scripts/steam-runtime.sh@@ -11,3 +11,23 @@ if [ -z "${SOJU_STEAM_WINE:-}" ]; thenfiSTEAM_SUPPORT="$SOJU_STEAM_BASE/steam-support"if [ -d "$STEAM_SUPPORT/prebuilt" ]; then STEAM_SUPPORT="$STEAM_SUPPORT/prebuilt"; fi++# Installation paths call this even when the Steam client already exists.+# Selection alone remains read-only for play/doctor/uninstall.+soju_steam_runtime_ready() {+ [ -x "$STEAM_WINE_ROOT/bin/wine" ] && [ -x "$STEAM_WINE_ROOT/bin/wineserver" ] &&+ [ "$("$STEAM_WINE_ROOT/bin/wine" --version 2>/dev/null || true)" = wine-11.0 ]+}+soju_ensure_steam_runtime() {+ local repo_root="$1"+ soju_steam_runtime_ready && return 0+ if [ -n "${SOJU_STEAM_WINE:-}" ]; then+ echo "SOJU_STEAM_WINE must point to a working Wine 11.0 runtime." >&2+ return 1+ fi+ python3 "$repo_root/scripts/steam-session.py" idle "$STEAM_WINE_ROOT" || return 1+ python3 "$repo_root/scripts/fetch-steam-wine.py" || return 1+ # Do not select an incompatible prepared renderer again after downloading.+ STEAM_WINE_ROOT="$SOJU_STEAM_BASE/steam-wine"+ soju_steam_runtime_ready || { echo "Steam Wine runtime validation failed." >&2; return 1; }+}diff --git a/scripts/steam-session.py b/scripts/steam-session.pynew file mode 100644index 00000000000..7ce66f0335d--- /dev/null+++ b/scripts/steam-session.py@@ -0,0 +1,63 @@+#!/usr/bin/env python3+"""Guard Steam runtime changes and stop only the requested Wine prefix."""+import argparse+import os+from pathlib import Path+import subprocess+import sys+++def server_paths():+ result = subprocess.run(["ps", "-axo", "comm="], check=True,+ capture_output=True, text=True, timeout=10)+ return [Path(line.strip()) for line in result.stdout.splitlines()+ if Path(line.strip()).name in ("wineserver", "wineserver64")]+++def is_steam_server(path, runtime):+ if path.resolve() == (runtime / "bin" / path.name).resolve():+ return True+ return any(part in ("Wine Stable.app", "steam-runtime", "steam-wine",+ "steam-runtime.previous", "steam-wine.previous")+ or part.startswith(".steam-runtime.") for part in path.parts)+++def require_idle(runtime):+ if any(is_steam_server(path, runtime) for path in server_paths()):+ raise RuntimeError("Close Windows Steam and its games before changing the Steam runtime.")+++def stop(prefix, runtime, timeout=30):+ if not prefix.is_dir():+ return+ server = runtime / "bin/wineserver"+ if not os.access(server, os.X_OK):+ # A missing engine is harmless only when no Wine server is running.+ # Without its executable we cannot reliably stop or identify its prefix.+ if server_paths():+ raise RuntimeError("Cannot stop this bottle: its Wine runtime is missing. Close Wine launchers and games, then retry.")+ return+ env = {key: value for key, value in os.environ.items()+ if not key.startswith(("DYLD_", "WINE", "CX_", "ROSETTA_"))}+ env.update(WINEPREFIX=str(prefix.resolve()), WINEDEBUG="-all")+ for flag in ("-k", "-w"):+ subprocess.run([str(server), flag], env=env, check=True,+ capture_output=True, text=True, timeout=timeout)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("action", choices=("idle", "stop"))+ parser.add_argument("runtime", type=Path)+ parser.add_argument("prefix", type=Path, nargs="?")+ args = parser.parse_args()+ try:+ if args.action == "idle":+ require_idle(args.runtime)+ else:+ if args.prefix is None:+ parser.error("stop requires a prefix")+ stop(args.prefix, args.runtime)+ except (OSError, RuntimeError, subprocess.SubprocessError) as error:+ print("Steam runtime: " + str(error), file=sys.stderr)+ sys.exit(1)diff --git a/scripts/uninstall.sh b/scripts/uninstall.shindex b89c5379d8f..1fd15863082 100755--- a/scripts/uninstall.sh+++ b/scripts/uninstall.sh@@ -6,6 +6,8 @@ set -euo pipefailBASE="${SOJU_BASE:-$HOME/.battlenet-macos}"ENGINE="${ENGINE:-$BASE/cx26-engine}"+ROOT="$(cd "$(dirname "$0")/.." && pwd)"+source "$ROOT/scripts/steam-runtime.sh"TTY=/dev/ttyREMOVED=0YES=0; [ "${1:-}" = "--yes" ] && YES=1@@ -21,11 +23,14 @@ echo "soju uninstall: this removes things soju created. Nothing is touched witho# Stop only after this bottle's removal (or engine removal) was accepted.stop_bottle() {local b="$1" ws="$ENGINE/bin/wineserver"- [ "$b" != steam-bottle ] || ws="/Applications/Wine Stable.app/Contents/Resources/wine/bin/wineserver"[ -d "$BASE/$b" ] || return 0+ if [ "$b" = steam-bottle ]; then+ # This resolves private, legacy and explicit runtimes exactly as play does.+ # A failed stop/wait aborts uninstall before any bottle files are removed.+ python3 "$ROOT/scripts/steam-session.py" stop "$STEAM_WINE_ROOT" "$BASE/$b"+ return+ fiWINEPREFIX="$BASE/$b" DYLD_FALLBACK_LIBRARY_PATH="$ENGINE/lib:/usr/lib" "$ws" -k 2>/dev/null || true- # -k only asks; wait for the server to be gone before rm -rf, otherwise- # shutdown-time writes race the delete and can leave half a bottle behind.WINEPREFIX="$BASE/$b" DYLD_FALLBACK_LIBRARY_PATH="$ENGINE/lib:/usr/lib" "$ws" -w 2>/dev/null || true}@@ -53,6 +58,20 @@ for b in bottle steam-bottle epic-bottle gog-bottle; dofidone+# Steam engines have their own category, including rollback copies.+runtimes=()+for d in steam-runtime steam-runtime.previous steam-wine steam-wine.previous; do+ [ -e "$BASE/$d" ] && runtimes+=("$BASE/$d")+done+if [ "${#runtimes[@]}" -gt 0 ]; then+ printf 'Steam runtimes: %s\n' "${runtimes[@]}"+ if ask "Remove these Steam runtimes (can be downloaded again)?"; then+ stop_bottle steam-bottle+ python3 "$ROOT/scripts/steam-session.py" idle "$STEAM_WINE_ROOT"+ rm -rf "${runtimes[@]}"; REMOVED=1; echo " removed"+ fi+fi+# 4. Engine (+ the GPTK payload inside it).if [ -d "$ENGINE" ]; thensz=$(du -sh "$ENGINE" 2>/dev/null | cut -f1)@@ -87,7 +106,7 @@ cat <<'EOT'Not removed by this script (they are Homebrew's):brew uninstall soju the soju CLI itself, if installed via brew- brew uninstall --cask wine-stable the Steam engine+ brew uninstall --cask wine-stable legacy Wine, only if separately installedbrew uninstall mingw-w64 the wrapper build dependencyEOTecho "Done."diff --git a/tests/test_regressions.py b/tests/test_regressions.pyindex 51c42ef09a1..2532981ead9 100644--- a/tests/test_regressions.py+++ b/tests/test_regressions.py@@ -192,7 +192,10 @@ class UninstallTests(unittest.TestCase):# Keep one descriptor open so consecutive read calls advance.src = src.replace("TTY=/dev/tty","exec 9<" + shlex.quote(str(answer_file)) + "\nTTY=/dev/fd/9")- script = d / "uninstall.sh"+ script = d / "scripts/uninstall.sh"+ script.parent.mkdir()+ for helper in ("steam-runtime.sh", "steam-session.py"):+ (script.parent / helper).write_text((ROOT / "scripts" / helper).read_text())script.write_text(src)x = subprocess.run([BASH, str(script), *(["--yes"] if yes else [])],env={**os.environ, "SOJU_BASE": str(base), "ENGINE": str(engine)},diff --git a/tests/test_steam_lifecycle.py b/tests/test_steam_lifecycle.pynew file mode 100644index 00000000000..90d02463ad7--- /dev/null+++ b/tests/test_steam_lifecycle.py@@ -0,0 +1,233 @@+"""Steam lifecycle regressions. Only temporary prefixes and fake OS tools are used."""+import importlib.util+import os+from pathlib import Path+import shlex+import subprocess+import tempfile+import unittest+from unittest.mock import patch++ROOT = Path(__file__).resolve().parents[1]+spec = importlib.util.spec_from_file_location("steam_session", ROOT / "scripts/steam-session.py")+session = importlib.util.module_from_spec(spec)+spec.loader.exec_module(session)+++def executable(path, text):+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("#!/bin/bash\n" + text)+ path.chmod(0o755)+++class SteamSessionTests(unittest.TestCase):+ def test_all_managed_and_explicit_server_paths_block_migration(self):+ for path in ["/Applications/Wine Stable.app/Contents/Resources/wine/bin/wineserver",+ "/private/tmp/soju/steam-wine/bin/wineserver",+ "/tmp/soju/steam-runtime/bin/wineserver",+ "/tmp/soju/steam-runtime.previous/bin/wineserver",+ "/tmp/soju/steam-wine.previous/bin/wineserver",+ "/tmp/soju/.steam-runtime.ABC/bin/wineserver",+ "/custom/wine/bin/wineserver64"]:+ with self.subTest(path=path), patch.object(session, "server_paths", return_value=[Path(path)]):+ with self.assertRaisesRegex(RuntimeError, "Close Windows Steam"):+ session.require_idle(Path("/custom/wine"))++ def test_other_platform_server_does_not_block_steam(self):+ with patch.object(session, "server_paths", return_value=[Path("/tmp/soju/cx26-engine/bin/wineserver")]):+ session.require_idle(Path("/tmp/soju/steam-runtime"))++ def test_failed_process_query_aborts_migration(self):+ with patch.object(session.subprocess, "run", side_effect=subprocess.CalledProcessError(1, "ps")):+ with self.assertRaises(subprocess.CalledProcessError):+ session.require_idle(Path("/tmp/wine"))++ def test_stop_scopes_and_cleans_environment_and_waits(self):+ with tempfile.TemporaryDirectory() as t:+ root = Path(t); prefix = root / "prefix"; prefix.mkdir()+ runtime = root / "runtime"; executable(runtime / "bin/wineserver", "exit 0\n")+ with patch.dict(os.environ, {"WINEPREFIX": "/unrelated", "WINESERVER": "/wrong",+ "DYLD_FALLBACK_LIBRARY_PATH": "/wrong", "CX_TEST": "bad"}), \+ patch.object(session.subprocess, "run") as run:+ session.stop(prefix, runtime)+ self.assertEqual([c.args[0][-1] for c in run.call_args_list], ["-k", "-w"])+ for call in run.call_args_list:+ env = call.kwargs["env"]+ self.assertEqual(env["WINEPREFIX"], str(prefix.resolve()))+ self.assertNotIn("WINESERVER", env)+ self.assertNotIn("DYLD_FALLBACK_LIBRARY_PATH", env)+ self.assertNotIn("CX_TEST", env)+ self.assertTrue(call.kwargs["check"])+ self.assertEqual(call.kwargs["timeout"], 30)++ def test_timeout_propagates_instead_of_allowing_delete(self):+ with tempfile.TemporaryDirectory() as t:+ root = Path(t); prefix = root / "prefix"; prefix.mkdir()+ executable(root / "runtime/bin/wineserver", "exit 0\n")+ with patch.object(session.subprocess, "run", side_effect=subprocess.TimeoutExpired("wineserver", 30)):+ with self.assertRaises(subprocess.TimeoutExpired):+ session.stop(prefix, root / "runtime")+++class SteamInstallRecoveryTests(unittest.TestCase):+ def test_existing_client_still_runs_runtime_preparation_before_renderer(self):+ stage = (ROOT / "install.sh").read_text().split("# ---------- 3. Launchers ----------")[1].split("# ---------- 4. App bundles")[0]+ with tempfile.TemporaryDirectory() as t:+ d = Path(t)+ client = d / "steam-bottle/drive_c/Program Files (x86)/Steam/steam.exe"+ client.parent.mkdir(parents=True); client.touch()+ executable(d / "scripts/create-steam-bottle.sh", 'touch "$SOJU_BASE/prepared"\n')+ executable(d / "scripts/setup-steam-games.sh", 'test -f "$SOJU_BASE/prepared"\n')+ pre = 'set -euo pipefail\nBASE="$SOJU_BASE"\nSOJU_DIR="$BASE"\nPLATFORMS=steam\nsay(){ :; }\n'+ result = subprocess.run(["/bin/bash", "-c", pre + stage],+ env={**os.environ, "SOJU_BASE": t}, capture_output=True, text=True)+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertTrue((d / "prepared").exists())++ def test_missing_incompatible_or_damaged_runtime_is_repaired_for_existing_client(self):+ for existing in ("missing", "wrong-version", "missing-server"):+ with self.subTest(existing=existing), tempfile.TemporaryDirectory() as t:+ d = Path(t); base = d / "base"; project = d / "project"; stubs = d / "stubs"+ (project / "scripts").mkdir(parents=True)+ for name in ("steam-runtime.sh", "create-steam-bottle.sh", "steam-session.py"):+ (project / "scripts" / name).write_text((ROOT / "scripts" / name).read_text())+ client = base / "steam-bottle/drive_c/Program Files (x86)/Steam/steam.exe"+ client.parent.mkdir(parents=True); client.write_text("existing client")+ # Use a missing legacy path even on developer Macs with Wine installed.+ p = project / "scripts/steam-runtime.sh"+ p.write_text(p.read_text().replace("/Applications/Wine Stable.app/Contents/Resources/wine",+ str(d / "missing-legacy")))+ if existing != "missing":+ runtime = base / "steam-runtime"+ executable(runtime / "bin/wine", "echo wine-12.0\n" if existing == "wrong-version" else "echo wine-11.0\n")+ (runtime / ".soju-runtime").touch()+ if existing != "missing-server":+ executable(runtime / "bin/wineserver", "exit 0\n")+ executable(stubs / "ps", "exit 0\n")+ executable(stubs / "python3", r'''+case "$1" in+ -) cat >/dev/null;;+ */fetch-steam-wine.py)+ mkdir -p "$SOJU_BASE/steam-wine/bin"+ printf '#!/bin/bash\necho wine-11.0\n' > "$SOJU_BASE/steam-wine/bin/wine"+ printf '#!/bin/bash\nexit 0\n' > "$SOJU_BASE/steam-wine/bin/wineserver"+ chmod +x "$SOJU_BASE/steam-wine/bin/"*+ touch "$SOJU_BASE/steam-wine/.soju-wine"+ echo fetch >> "$SOJU_BASE/events";;+ */fetch-steam-support.py) :;;+ */bootstrap-steam.py) printf '%s\n' "$2" >> "$SOJU_BASE/events";;+ *) exec /usr/bin/python3 "$@";;+esac+''')+ env = {k: v for k, v in os.environ.items() if k not in ("SOJU_STEAM_WINE", "WINEPREFIX")}+ env.update(SOJU_BASE=str(base), PATH=str(stubs)+":/usr/bin:/bin")+ result = subprocess.run(["/bin/bash", str(project / "scripts/create-steam-bottle.sh")],+ env=env, capture_output=True, text=True)+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertEqual((base / "events").read_text().splitlines(),+ ["fetch", str(base / "steam-wine/bin/wine")])+ self.assertEqual(client.read_text(), "existing client")++ def test_invalid_explicit_override_never_downloads_or_replaces_it(self):+ with tempfile.TemporaryDirectory() as t:+ d = Path(t); executable(d / "stubs/python3", 'echo unexpected-download; exit 88\n')+ env = {**os.environ, "SOJU_STEAM_WINE": str(d / "custom"),+ "PATH": str(d / "stubs") + ":/usr/bin:/bin"}+ result = subprocess.run(["/bin/bash", "-c",+ 'source "$1"; soju_ensure_steam_runtime "$2"', "test",+ str(ROOT / "scripts/steam-runtime.sh"), str(ROOT)], env=env, capture_output=True, text=True)+ self.assertNotEqual(result.returncode, 0)+ self.assertNotIn("unexpected-download", result.stdout)+ self.assertFalse((d / "custom").exists())+++class SteamUninstallTests(unittest.TestCase):+ def scenario(self, failure="", answers=None, missing=False, live=False, custom=False, ps_failure=False):+ temp = tempfile.TemporaryDirectory()+ self.addCleanup(temp.cleanup)+ d = Path(temp.name); base = d / "base"; project = d / "project"; stubs = d / "stubs"+ prefix = base / "steam-bottle"; prefix.mkdir(parents=True)+ (prefix / "saved-game").write_text("keep until stopped")+ (d / "other-install").mkdir(); (d / "other-install/game").write_text("untouched")+ for name, marker in [("steam-runtime", ".soju-runtime"), ("steam-wine", ".soju-wine")]:+ executable(base / name / "bin/wine", "echo wine-11.0\n")+ (base / name / marker).touch()+ if not missing:+ executable(base / name / "bin/wineserver", r'''+printf '%s %s\n' "$WINEPREFIX" "$1" >> "$SOJU_TEST/events"+test "$1" != "$SOJU_TEST_FAILURE" || exit 7+test -f "$WINEPREFIX/saved-game" || exit 8+# Model a final shutdown write while -w waits.+if [ "$1" = -w ]; then echo final > "$WINEPREFIX/shutdown-write"; fi+''')+ for name in ("steam-runtime.previous", "steam-wine.previous"):+ (base / name).mkdir()+ if custom:+ import shutil+ shutil.copytree(base / "steam-runtime", d / "custom-runtime")+ executable(stubs / "ps", ("exit 2\n" if ps_failure else+ 'echo "/tmp/live/steam-wine/bin/wineserver"\n' if live else "exit 0\n"))+ (project / "scripts").mkdir(parents=True)+ for name in ("steam-runtime.sh", "steam-session.py", "uninstall.sh"):+ (project / "scripts" / name).write_text((ROOT / "scripts" / name).read_text())+ args = ["--yes"]+ if answers is not None:+ answer_file = d / "answers"; answer_file.write_text(answers)+ p = project / "scripts/uninstall.sh"+ p.write_text(p.read_text().replace("TTY=/dev/tty",+ "exec 9<" + shlex.quote(str(answer_file)) + "\nTTY=/dev/fd/9"))+ args = []+ env = {k: v for k, v in os.environ.items() if k not in ("SOJU_STEAM_WINE", "ENGINE", "WINEPREFIX")}+ env.update(SOJU_BASE=str(base), SOJU_TEST=str(d), SOJU_TEST_FAILURE=failure,+ PATH=str(stubs)+":/usr/bin:/bin")+ if custom: env["SOJU_STEAM_WINE"] = str(d / "custom-runtime")+ result = subprocess.run(["/bin/bash", str(project / "scripts/uninstall.sh"), *args],+ env=env, capture_output=True, text=True, timeout=15)+ self.assertEqual((d / "other-install/game").read_text(), "untouched")+ return d, base, result++ def test_yes_waits_then_removes_prefix_and_all_managed_runtimes(self):+ d, base, result = self.scenario()+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertFalse(base.exists())+ self.assertEqual([line.rsplit(" ", 1)[1] for line in (d / "events").read_text().splitlines()], ["-k", "-w"])++ def test_failed_kill_or_wait_preserves_game_and_runtime(self):+ for failure in ("-k", "-w"):+ with self.subTest(failure=failure):+ d, base, result = self.scenario(failure=failure)+ self.assertNotEqual(result.returncode, 0)+ self.assertTrue((base / "steam-bottle/saved-game").exists())+ self.assertTrue((base / "steam-runtime/bin/wine").exists())++ def test_declining_all_does_not_stop_or_remove_anything(self):+ d, base, result = self.scenario(answers="n\nn\n")+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertTrue((base / "steam-bottle/saved-game").exists())+ self.assertTrue((base / "steam-wine").exists())+ self.assertFalse((d / "events").exists())++ def test_runtime_only_removal_stops_retained_prefix_first(self):+ d, base, result = self.scenario(answers="n\ny\n")+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertTrue((base / "steam-bottle/shutdown-write").exists())+ self.assertFalse((base / "steam-runtime").exists())+ self.assertEqual(len((d / "events").read_text().splitlines()), 2)++ def test_missing_engine_can_be_cleaned_when_no_servers_exist(self):+ d, base, result = self.scenario(missing=True)+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertFalse(base.exists())++ def test_missing_engine_with_live_or_unknown_server_preserves_prefix(self):+ for kwargs in ({"live": True}, {"ps_failure": True}):+ with self.subTest(kwargs=kwargs):+ d, base, result = self.scenario(missing=True, **kwargs)+ self.assertNotEqual(result.returncode, 0)+ self.assertTrue((base / "steam-bottle/saved-game").exists())++ def test_explicit_external_runtime_is_used_but_never_deleted(self):+ d, base, result = self.scenario(custom=True)+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertFalse(base.exists())+ self.assertTrue((d / "custom-runtime/bin/wineserver").exists())