Skip to content

Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.

Sessions: a running game is detected from its processes and the app stays free

Gauthier Piarretteac2645307a4f
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index 526a059..b8f2864 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -514,6 +514,55 @@ final class AppState {
/// wineserver under the live session (issue #13's crash sequence), so it's refused instead.
private var launchingPins: Set<UUID> = []
+ // MARK: Sessions (UX plan 0.6)
+
+ /// Games running right now, from their processes. The library shows them and offers Stop;
+ /// nothing here blocks the app while a game runs.
+ var runningSessions: [GameSession] = []
+ /// The last session that ended, for the post-play prompt to come.
+ var lastEndedSession: SessionRecord?
+ private var sessionWatchers: [UUID: Task<Void, Never>] = [:]
+
+ func session(forAppID appid: Int) -> GameSession? { runningSessions.first { $0.appid == appid } }
+
+ private func beginSession(_ session: GameSession) {
+ runningSessions.append(session)
+ appendLog("\(session.title) is running")
+ sessionWatchers[session.id] = Task { [weak self] in
+ // A game that is gone for two consecutive checks has ended; one miss can be a
+ // process table read racing a restart (some games relaunch themselves once).
+ var misses = 0
+ while !Task.isCancelled {
+ try? await Task.sleep(for: .seconds(5))
+ if SessionWatch.isAlive(markers: session.markers, ps: SessionWatch.currentProcessList()) { misses = 0; continue }
+ misses += 1
+ if misses >= 2 { break }
+ }
+ await MainActor.run { self?.endSession(session, reason: "ended") }
+ }
+ }
+
+ private func endSession(_ session: GameSession, reason: String) {
+ guard runningSessions.contains(session) else { return }
+ runningSessions.removeAll { $0.id == session.id }
+ sessionWatchers[session.id]?.cancel()
+ sessionWatchers[session.id] = nil
+ let record = SessionRecord(title: session.title, bottle: session.bottleName, appid: session.appid,
+ started: session.started, ended: Date(), reason: reason)
+ SessionWatch.append(record, to: paths.logs)
+ lastEndedSession = record
+ appendLog("\(session.title) \(reason) after \(record.seconds / 60) min")
+ }
+
+ /// Ends the game's own processes and leaves Steam and the server running, so the next
+ /// Play needs no cold start.
+ func stopSession(_ session: GameSession) {
+ guard let bottle = bottles.first(where: { $0.name == session.bottleName }) else { return }
+ let pids = SessionWatch.pids(ofPrefix: bottle.url, markers: session.markers)
+ _ = ProcessTable.terminate(pids)
+ endSession(session, reason: "stopped")
+ }
+
func launch(pin: Pin, in bottle: Bottle) {
guard let engine = engine(for: bottle) else { return }
guard !launchingPins.contains(pin.id) else {
@@ -650,25 +699,61 @@ final class AppState {
/// Launch a Steam game by appid through the bottle's Steam client.
func launchGame(_ game: SteamGame, in bottle: Bottle) {
guard let engine = engine(for: bottle) else { return }
+ if let running = session(forAppID: game.appid) {
+ fail(HighballError.failed("\(running.title) is already running."))
+ return
+ }
let steam = bottle.driveC.appending(path: "Program Files (x86)/Steam/steam.exe")
let entry = gameDB[game.appid]
let renderer = entry?.renderer
// Per-game launch args ride the db (e.g. windowed for legacy CS:GO on macOS 26, #21).
let extraArgs = entry?.effectiveLaunchArgs() ?? []
- runBusy("Running \(game.name)", showLogSheet: false) { [self] in
+ let markers = SessionWatch.markers(installdir: game.installdir)
+ // The busy sheet covers the start only: Steam's client outlives the game and its launch
+ // call says nothing about it, so the game's own processes decide when "starting" ends
+ // and a session begins, and the app is free while the game runs (UX plan 0.6).
+ runBusy("Starting \(game.name)", expected: L("a cold Steam client can take a couple of minutes"), showLogSheet: false,
+ done: DoneState(title: L("Running"), ctaTitle: nil, cta: nil)) { [self] in
let runner = WineRunner(paths: paths, engine: engine, bottle: bottle)
- let result = try await runner.start(steam, arguments: ["-silent", "-applaunch", String(game.appid)] + extraArgs, renderer: renderer) { line in
- Task { @MainActor in self.appendLog(line) }
+ let launch = Task {
+ try await runner.start(steam, arguments: ["-silent", "-applaunch", String(game.appid)] + extraArgs, renderer: renderer) { line in
+ Task { @MainActor in self.appendLog(line) }
+ }
}
- if result.crashedEarly {
- let current = renderer ?? bottle.settings.renderer
- await MainActor.run {
- self.crashSuggestion = CrashSuggestion(program: game.name, bottleName: bottle.name,
- renderer: Renderer.suggestion(after: current),
- logPath: result.log.path,
- alternateEngine: self.alternateEngine(for: bottle))
+ var waited = 0
+ while waited < 360 {
+ if SessionWatch.isAlive(markers: markers, ps: SessionWatch.currentProcessList()) {
+ await MainActor.run {
+ self.beginSession(GameSession(title: game.name, bottleName: bottle.name, appid: game.appid, markers: markers))
+ }
+ return
+ }
+ // The launch call returning early means the client died before handing off.
+ if launch.isCancelled { break }
+ if let result = await Self.finished(launch), result.crashedEarly {
+ let current = renderer ?? bottle.settings.renderer
+ await MainActor.run {
+ self.crashSuggestion = CrashSuggestion(program: game.name, bottleName: bottle.name,
+ renderer: Renderer.suggestion(after: current),
+ logPath: result.log.path,
+ alternateEngine: self.alternateEngine(for: bottle))
+ }
+ return
}
+ try await Task.sleep(for: .seconds(2)); waited += 2
}
+ throw HighballError.failed("\(game.name) never started. Steam accepted the launch but no game process appeared in six minutes; its log is in the bottle's Steam log.")
+ }
+ }
+
+ /// The launch result when the task has already finished, nil while it still runs.
+ private static func finished(_ task: Task<LaunchResult, Error>) async -> LaunchResult? {
+ await withTaskGroup(of: LaunchResult?.self) { group in
+ group.addTask { try? await task.value }
+ group.addTask { try? await Task.sleep(for: .milliseconds(50)); return nil }
+ let first = await group.next() ?? nil
+ group.cancelAll()
+ return first
}
}
diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swift
index 3b793c1..45deb71 100644
--- a/Sources/HighballApp/L10n.swift
+++ b/Sources/HighballApp/L10n.swift
@@ -178,6 +178,9 @@ enum L10n {
"Details": "Détails",
"Run and add to Programs": "Lancer et ajouter aux programmes",
"Keep current": "Garder l’actuel",
+ "Running": "En cours",
+ "Stop": "Arrêter",
+ "a cold Steam client can take a couple of minutes": "un client Steam à froid peut prendre quelques minutes",
"Try again": "Réessayer",
"Download again": "Retélécharger",
"Repair": "Réparer",
diff --git a/Sources/HighballApp/LibraryView.swift b/Sources/HighballApp/LibraryView.swift
index eb74b25..cab3847 100644
--- a/Sources/HighballApp/LibraryView.swift
+++ b/Sources/HighballApp/LibraryView.swift
@@ -178,6 +178,15 @@ struct LibraryTile: View {
SourceBadge(source: item.source)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.padding(6)
+ if let appid = item.steamAppID, state.session(forAppID: appid) != nil {
+ Text(L("Running"))
+ .font(.system(size: 9, weight: .bold))
+ .padding(.horizontal, 6).padding(.vertical, 3)
+ .background(HB.good.opacity(0.9), in: Capsule())
+ .foregroundStyle(.black)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
+ .padding(6)
+ }
if !item.installed {
Image(systemName: "arrow.down.circle.fill")
.foregroundStyle(.white.opacity(0.85))
@@ -209,7 +218,9 @@ struct LibraryTile: View {
.onHover { hovering = $0 }
.help(entry?.notes ?? item.title)
.contextMenu {
- if playable { Button(L("Play")) { state.play(item) } }
+ if let appid = item.steamAppID, let running = state.session(forAppID: appid) {
+ Button(L("Stop")) { state.stopSession(running) }
+ } else if playable { Button(L("Play")) { state.play(item) } }
Button(L("Choose cover image…")) { state.chooseCover(for: item) }
if state.coverStore.coverURL(for: item.id) != nil {
Button(L("Reset cover")) { state.resetCover(for: item) }
diff --git a/Sources/HighballKit/Sessions.swift b/Sources/HighballKit/Sessions.swift
new file mode 100644
index 0000000..61f5a1d
--- /dev/null
+++ b/Sources/HighballKit/Sessions.swift
@@ -0,0 +1,70 @@
+import Foundation
+
+/// A game that is running right now, detected from its processes rather than from an awaited
+/// launch. Steam games are started through a client that outlives them, so the launch call
+/// returning says nothing about the game; the process markers do (UX plan, Phase 0.6).
+public struct GameSession: Identifiable, Sendable, Equatable {
+ public let id: UUID
+ public let title: String
+ public let bottleName: String
+ public let appid: Int?
+ /// Substrings of the game's command line, in both path styles Wine reports.
+ public let markers: [String]
+ public let started: Date
+ public init(id: UUID = UUID(), title: String, bottleName: String, appid: Int?, markers: [String], started: Date = Date()) {
+ self.id = id; self.title = title; self.bottleName = bottleName; self.appid = appid; self.markers = markers; self.started = started
+ }
+}
+
+/// What a finished session leaves behind: the post-play prompt and the funnel's last event
+/// read this (UX plan §3.4, 0.6). Appended to `logs/sessions.jsonl`.
+public struct SessionRecord: Codable, Sendable, Equatable {
+ public var title: String
+ public var bottle: String
+ public var appid: Int?
+ public var started: Date
+ public var ended: Date
+ public var seconds: Int { Int(ended.timeIntervalSince(started)) }
+ /// "ended" when the game went away on its own, "stopped" when Highball ended it.
+ public var reason: String
+ public init(title: String, bottle: String, appid: Int?, started: Date, ended: Date, reason: String) {
+ self.title = title; self.bottle = bottle; self.appid = appid; self.started = started; self.ended = ended; self.reason = reason
+ }
+}
+
+public enum SessionWatch {
+ /// The markers a Steam game's processes carry: its install folder under steamapps/common,
+ /// in the Unix and the Windows spelling Wine uses in command lines.
+ public static func markers(installdir: String) -> [String] {
+ ["steamapps/common/\(installdir)/", "steamapps\\common\\\(installdir)\\"]
+ }
+
+ /// True when any process listing line carries one of the markers. `ps` is the text of
+ /// `ps axww`; kept as a parameter so the rule is testable without processes.
+ public static func isAlive(markers: [String], ps: String) -> Bool {
+ markers.contains { ps.contains($0) }
+ }
+
+ public static func currentProcessList() -> String {
+ (try? Shell.capture("/bin/ps", ["axww"])) ?? ""
+ }
+
+ /// Process ids of the game's own processes inside a prefix, by command line. Used by Stop;
+ /// Steam and the wineserver are left alone so a second game can follow without a cold start.
+ public static func pids(ofPrefix prefix: URL, markers: [String]) -> [pid_t] {
+ ProcessTable.processes(ofPrefix: prefix).filter { pid in
+ guard let cl = ProcessTable.commandLineAndEnvironment(of: pid) else { return false }
+ let joined = cl.arguments.joined(separator: " ")
+ return markers.contains { joined.contains($0) }
+ }
+ }
+
+ public static func append(_ record: SessionRecord, to logs: URL) {
+ let file = logs.appending(path: "sessions.jsonl")
+ let enc = JSONEncoder(); enc.dateEncodingStrategy = .iso8601
+ guard var data = try? enc.encode(record) else { return }
+ data.append(0x0A)
+ if let h = try? FileHandle(forWritingTo: file) { try? h.seekToEnd(); try? h.write(contentsOf: data); try? h.close() }
+ else { try? data.write(to: file) }
+ }
+}
diff --git a/Tests/HighballKitTests/RegressionTests.swift b/Tests/HighballKitTests/RegressionTests.swift
index bafca71..1cbf499 100644
--- a/Tests/HighballKitTests/RegressionTests.swift
+++ b/Tests/HighballKitTests/RegressionTests.swift
@@ -1044,6 +1044,19 @@ extension RegressionTests {
XCTAssertTrue(json.contains("\"formatVersion\":3"))
}
+ // Sessions are detected from processes, in both path spellings Wine reports (plan 0.6).
+ func testSessionMarkersAndLiveness() {
+ let m = SessionWatch.markers(installdir: "Portal 2")
+ let unix = "1234 ?? 0:01.00 Z:\\Program Files (x86)\\Steam\\steamapps\\common\\Portal 2\\portal2.exe -novid"
+ let win = "1234 ?? 0:01.00 /Users/me/Library/Application Support/Highball/bottles/Gaming/drive_c/Program Files (x86)/Steam/steamapps/common/Portal 2/portal2.exe"
+ XCTAssertTrue(SessionWatch.isAlive(markers: m, ps: unix))
+ XCTAssertTrue(SessionWatch.isAlive(markers: m, ps: win))
+ XCTAssertFalse(SessionWatch.isAlive(markers: m, ps: "1 ?? 0:00.00 steam.exe -silent"))
+ XCTAssertFalse(SessionWatch.isAlive(markers: m, ps: "steamapps/common/Portal 2 Fan Mod/x.exe"), "the trailing separator keeps a sibling folder out")
+ let r = SessionRecord(title: "Portal 2", bottle: "Gaming", appid: 620, started: Date(timeIntervalSince1970: 0), ended: Date(timeIntervalSince1970: 754), reason: "ended")
+ XCTAssertEqual(r.seconds, 754)
+ }
+
func testDefaultEnginePrefersBundledManifestID() throws {
func engine(_ id: String) throws -> InstalledEngine {
let json = #"{"id":"\#(id)","displayName":"e","arch":"x86_64","minMacOS":"14.0","components":{}}"#