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
Steam: say why a game did not start (#177)
Mikek7050efabdbb2
diff --git a/app/Library.swift b/app/Library.swiftindex 5abc471bd90..717a92f7a0c 100644--- a/app/Library.swift+++ b/app/Library.swift@@ -158,7 +158,8 @@ extension SojuModel {} else if process.terminationStatus != 0 {let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""let reason = text.split(separator: "\n").last(where: { $0.hasPrefix("soju: ") }).map { String($0.dropFirst(6)) }- self.issueTitle = "Couldn't start " + game.title+ // Steam waiting on the player or updating first is not a failure to start: name the game only.+ self.issueTitle = reason?.hasPrefix("Steam is ") == true ? game.title : "Couldn't start " + game.titleself.libraryIssue = reason ?? (game.platform.opensAWindow? "Use Diagnose or open " + game.platform.title + " to check its installation and login.": "Use Diagnose to check the game and your Xbox sign-in.")diff --git a/scripts/play-stats.py b/scripts/play-stats.pyindex c5984111a5f..7ec7601378e 100755--- a/scripts/play-stats.py+++ b/scripts/play-stats.py@@ -169,7 +169,10 @@ def log_marks(game, launcher):"""Where Soju's launch logs end now, so that only what a start adds to them is read afterwards."""logs = BASE / "logs"out = {}- for path in (logs / ("game-" + game.replace(":", "-") + ".log"), logs / ("desktop-" + launcher + ".log")):+ paths = [logs / ("game-" + game.replace(":", "-") + ".log"), logs / ("desktop-" + launcher + ".log")]+ if launcher == "steam": # Steam's own log of each start, in whichever bottle it runs from+ paths += [BASE / b / "drive_c/Program Files (x86)/Steam/logs/console_log.txt" for b in ("steam-bottle", "steam-gptk-bottle")]+ for path in paths:try:st = path.stat()out[str(path)] = (st.st_ino, st.st_size)@@ -234,11 +237,22 @@ def launcher_state(launcher, table=None):return "launcher_open" if exe in text else "launcher_closed"-def reason(started, minutes, marks, found, path, launcher=""):+def reason(started, minutes, marks, found, path, launcher="", game=""):"""What to add to a start that did not run; nothing for one that ran."""if outcome(started, minutes) == "ran":return {}- word, name = why(log_since(marks), found)+ text = log_since(marks)+ word, name = "", ""+ if launcher == "steam" and ":" in game:+ try:+ import steam_launch+ kind, step = steam_launch.outcome(text, game.split(":", 1)[1])+ if kind in ("error", "waiting", "updating"):+ word, name = "steam_" + kind, SAFE.sub("", step)[:40]+ except Exception:+ pass+ if not word:+ word, name = why(text, found)if not word and not started:word = launcher_state(launcher)out = {"why": word, "detail": name, "ac": anticheat(path)}@@ -341,7 +355,7 @@ def watch(clock=time.monotonic, sleep=time.sleep, poll=POLL, table=None, snapshodef finish(gid, st, poll, deliver):st["lock"].unlink(missing_ok=True)minutes = int((st["last"] - st["first"] + poll) // 60)- extra = reason(True, minutes, st.get("marks"), st.get("found") or (), st.get("path"))+ extra = reason(True, minutes, st.get("marks"), st.get("found") or (), st.get("path"), "steam", gid)if extra:deliver(gid, st["title"], "steam", True, minutes, "steam", extra)else:@@ -482,7 +496,7 @@ def main(argv):started, minutes = track_run(found, pid)finally:lock.unlink(missing_ok=True)- report(a.game, a.title, a.launcher, started, minutes, "soju", reason(started, minutes, marks, found, a.path, a.launcher))+ report(a.game, a.title, a.launcher, started, minutes, "soju", reason(started, minutes, marks, found, a.path, a.launcher, a.game))return 0diff --git a/scripts/play.sh b/scripts/play.shindex 4c62d431fbd..90f5ba7ae23 100755--- a/scripts/play.sh+++ b/scripts/play.sh@@ -335,6 +335,14 @@ case "$MODE" in# Count games started from Steam's own window too (play counts; does nothing when they are off,# and only one watcher runs however often Steam is opened).( nohup python3 "$(dirname "${BASH_SOURCE[0]}")/play-stats.py" watch >/dev/null 2>&1 & )+ # Play on a game while Steam is open: Steam takes the request and may refuse it (no licence, offline) or wait+ # for an answer in its window, which may be hidden. Follow Steam's own log for that game and say so+ # (scripts/steam_launch.py); a start that goes through ends quietly. A cold start is Steam itself, so not here.+ STEAM_WATCH=()+ STEAM_APP=$(printf '%s\n' "${@:2}" | sed -n 's#^steam://rungameid/\([0-9][0-9]*\)$#\1#p' | head -1)+ if [ -n "$STEAM_APP" ] && pgrep -f 'Steam.steam\.exe' >/dev/null 2>&1; then+ STEAM_WATCH=(python3 "$(dirname "${BASH_SOURCE[0]}")/steam_launch.py" watch "$WINEPREFIX/drive_c/Program Files (x86)/Steam" "$STEAM_APP" --)+ fiif [ "${SOJU_STEAM_GPTK:-0}" = 1 ]; then# Steam with Apple GPTK: the CX engine plus the cross-process winemac# (scripts/steam-gptk-engine.sh). Same wrapper and flags as below; games@@ -366,7 +374,7 @@ case "$MODE" in{ [ -x "$REAPER" ] && ( "$REAPER" "$WINEPREFIX" "$ENGINE/bin/wineserver" steam >/dev/null 2>&1 & ); }STEAM_CMD=("C:\\Program Files (x86)\\Steam\\steam.exe" -no-cef-sandbox -cef-single-process)[ -f "$WINEPREFIX/drive_c/Program Files (x86)/Steam/steamui.dll" ] && STEAM_CMD+=(-noverifyfiles)- exec "$ENGINE/bin/wine" "${STEAM_CMD[@]}" "${@:2}"+ exec ${STEAM_WATCH[@]+"${STEAM_WATCH[@]}"} "$ENGINE/bin/wine" "${STEAM_CMD[@]}" "${@:2}"fiWINESTABLE="$STEAM_WINE_ROOT/bin/wine"WINESTABLE_SERVER="$STEAM_WINE_ROOT/bin/wineserver"@@ -479,7 +487,7 @@ case "$MODE" in# rest of the bottle down so no Dock icon / winedevice lingers.pgrep -f "soju-reaper.sh $WINEPREFIX" >/dev/null 2>&1 || \{ [ -x "$REAPER" ] && ( "$REAPER" "$WINEPREFIX" "$WINESTABLE_SERVER" steam >/dev/null 2>&1 & ); }- "${STEAM_ENV[@]}" \+ exec ${STEAM_WATCH[@]+"${STEAM_WATCH[@]}"} "${STEAM_ENV[@]}" \WINEDLLOVERRIDES="bcrypt=b;ncrypt=b;gameoverlayrenderer,gameoverlayrenderer64=d" \WINE_NO_DOCK_ICON="steam.exe;steamservice.exe" \WINE_DOCK_REOPEN_CMD="'$WINESTABLE' 'C:\\Program Files (x86)\\Steam\\steam.exe' steam://open/main" \diff --git a/scripts/steam_launch.py b/scripts/steam_launch.pynew file mode 100644index 00000000000..8f863da872a--- /dev/null+++ b/scripts/steam_launch.py@@ -0,0 +1,111 @@+#!/usr/bin/env python3+"""What Steam did with a request to start a game, read from Steam's own console_log.txt.++Steam writes each step of a start there, per game:+ GameAction [AppID 1385950, ActionID 2] : LaunchApp changed task to CreatingProcess with ""+ GameAction [AppID 1385950, ActionID 2] : LaunchApp failed with AppError_18 with ""+ GameAction [AppID 1385950, ActionID 2] : LaunchApp waiting for user response to ShowEula ""++ steam_launch.py watch <Steam folder> <appid> -- <command that hands steam://rungameid/<appid> to Steam>+ Runs the command, then follows the log for up to a minute. A start that goes through ends quietly;+ one that Steam refused, or that waits for an answer in Steam's window, ends with a "soju: ..." line+ the app shows, and a non-zero status.++Also used by scripts/play-stats.py: outcome(text, appid) gives the reason sent with a start that did not run.+"""+import os+import re+import subprocess+import sys+import time++# Steps Steam passes through by itself; anything else it waits on is a question for the player.+AUTO = {"ShowInterstitials", "CreatingProcess"}+# Seen here: AppError_18 for a game in the library that is not installed in this Steam (2026-11-23).+HINTS = {+ "18": "Steam gives this when the game is not installed or not finished in this Steam. Open Steam, check the game in your Library, then press Play again.",+}+++def outcome(text, appid):+ """(kind, detail) for the last start of this game in the text: ("ok", ""), ("error", "AppError_18"),+ ("waiting", "<step>"), ("updating", "<step>"), ("busy", "<step>") or ("", "") when the start is not there."""+ tag = "[AppID %s," % appid+ kind, detail = "", ""+ for line in text.splitlines():+ if tag not in line or "LaunchApp" not in line:+ continue+ if "changed task to Completed" in line:+ kind, detail = "ok", ""+ elif (m := re.search(r"failed with (AppError_\d+)", line)):+ kind, detail = "error", m.group(1)+ elif kind == "error" and "changed task to Failed" in line:+ pass+ elif (m := re.search(r"waiting for user response to (\w+)", line)):+ if m.group(1) not in AUTO:+ kind, detail = "waiting", m.group(1)+ elif (m := re.search(r"continues with user response \"?(\w+)", line)):+ if kind == "waiting" and detail == m.group(1):+ kind, detail = "busy", detail+ elif (m := re.search(r"changed task to (\w+)", line)):+ step = m.group(1)+ kind, detail = ("updating" if "Update" in step and step != "UpdatingAppTicket" else "busy"), step+ return kind, detail+++def message(kind, detail):+ if kind == "error":+ number = detail.split("_")[-1]+ return "Steam could not start the game (" + detail + "). " + HINTS.get(number, "Open Steam to see why, then press Play again.")+ if kind == "waiting":+ return "Steam is waiting for you before it starts the game (" + detail + "). Click Steam in the Dock to see its window and answer; the game starts after that."+ if kind == "updating":+ return "Steam is updating the game first. It starts by itself when the download in Steam finishes."+ return ""+++def watch(steam_dir, appid, command, seconds=60, waiting_after=15, poll=1.0, clock=time.monotonic, sleep=time.sleep):+ log = os.path.join(steam_dir, "logs", "console_log.txt")+ try:+ start = os.path.getsize(log)+ except OSError:+ start = 0+ code = subprocess.call(command) if command else 0+ if code != 0:+ return code+ begun = clock()+ since = None+ while clock() - begun < seconds:+ sleep(poll)+ try:+ with open(log, "rb") as f:+ f.seek(start if os.path.getsize(log) >= start else 0)+ text = f.read().decode("utf-8", "replace")+ except OSError:+ continue+ kind, detail = outcome(text, appid)+ if kind == "ok":+ return 0+ if kind == "error":+ print("soju: " + message(kind, detail), flush=True)+ return 3+ if kind in ("waiting", "updating"):+ since = since or clock()+ if clock() - since >= waiting_after:+ print("soju: " + message(kind, detail), flush=True)+ return 4+ else:+ since = None+ return 0+++def main(argv):+ if len(argv) >= 3 and argv[0] == "watch":+ command = argv[argv.index("--") + 1:] if "--" in argv else []+ return watch(argv[1], argv[2], command)+ print("usage: steam_launch.py watch <Steam folder> <appid> -- <command>", file=sys.stderr)+ return 64+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/site-worker/stats.js b/site-worker/stats.jsindex 1865eee06cb..8dbc1b4549a 100644--- a/site-worker/stats.js+++ b/site-worker/stats.js@@ -22,7 +22,7 @@ const SCHEMA = [];const RESULTS = new Set(["ran", "quick_exit", "no_start"]);// Why a start did not run, as the Mac read it from its own launch log: one word, one name, and the game's anti-cheat.-const WHY = new Set(["crash", "missing_dll", "graphics", "memory", "dotnet", "launcher_open", "launcher_closed"]);+const WHY = new Set(["crash", "missing_dll", "graphics", "memory", "dotnet", "launcher_open", "launcher_closed", "steam_error", "steam_waiting", "steam_updating"]);const AC = new Set(["eac", "battleye", "vanguard", "gameguard", "xigncode", "punkbuster"]);const name = (v) => { const s = text(v, 40); return /^[A-Za-z0-9._+-]*$/.test(s) ? s : ""; };const HOW = new Set(["soju", "steam"]);diff --git a/tests/test_steam_launch.py b/tests/test_steam_launch.pynew file mode 100644index 00000000000..3340561ce98--- /dev/null+++ b/tests/test_steam_launch.py@@ -0,0 +1,57 @@+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(ROOT / "scripts"))+import steam_launch as sl # noqa: E402++OK = """[t] GameAction [AppID 70, ActionID 1] : LaunchApp changed task to ShowInterstitials with ""+[t] GameAction [AppID 70, ActionID 1] : LaunchApp waiting for user response to ShowInterstitials ""+[t] GameAction [AppID 70, ActionID 1] : LaunchApp continues with user response "ShowInterstitials"+[t] GameAction [AppID 70, ActionID 1] : LaunchApp changed task to CreatingProcess with ""+[t] GameAction [AppID 70, ActionID 1] : LaunchApp changed task to Completed with ""+"""+FAIL = """[t] GameAction [AppID 70, ActionID 2] : LaunchApp changed task to UpdatingAppTicket with ""+[t] GameAction [AppID 70, ActionID 2] : LaunchApp failed with AppError_18 with ""+[t] GameAction [AppID 70, ActionID 2] : LaunchApp changed task to Failed with ""+"""+ASK = '[t] GameAction [AppID 70, ActionID 3] : LaunchApp waiting for user response to ShowEula ""\n'+++def fake_time():+ t = [0.0]+ return (lambda: t[0]), (lambda s: t.__setitem__(0, t[0] + s))+++class SteamLaunchTests(unittest.TestCase):+ def test_reads_how_a_start_went(self):+ self.assertEqual(sl.outcome(OK, "70"), ("ok", ""))+ self.assertEqual(sl.outcome(FAIL, "70"), ("error", "AppError_18"))+ self.assertEqual(sl.outcome(ASK, "70"), ("waiting", "ShowEula"))+ self.assertEqual(sl.outcome(OK + FAIL, "71"), ("", "")) # another game's start says nothing+ self.assertIn("not installed", sl.message("error", "AppError_18"))++ def test_watch_says_why_and_stays_quiet_when_it_works(self):+ with tempfile.TemporaryDirectory() as d:+ logs = Path(d) / "logs"+ logs.mkdir()+ log = logs / "console_log.txt"+ log.write_text("earlier lines\n" + FAIL) # an older start of the same game is not read+ for body, code in ((OK, 0), (FAIL, 3), (ASK, 4)):+ cmd = [sys.executable, "-c", "open(%r,'a').write(%r)" % (str(log), body)]+ clock, sleep = fake_time()+ self.assertEqual(sl.watch(d, "70", cmd, clock=clock, sleep=sleep), code)+ # Nothing about the game within the minute: no message, no failure.+ clock, sleep = fake_time()+ self.assertEqual(sl.watch(d, "999", [sys.executable, "-c", "pass"], clock=clock, sleep=sleep), 0)++ def test_play_sh_follows_the_start_only_when_steam_is_open(self):+ text = (ROOT / "scripts/play.sh").read_text()+ self.assertIn('steam_launch.py" watch', text)+ self.assertEqual(text.count('${STEAM_WATCH[@]+"${STEAM_WATCH[@]}"}'), 2)+++if __name__ == "__main__":+ unittest.main()