Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit
Swift apple-silicond3dmetaldxmtdxvkgame-porting-toolkitgptkmac-gamingmacosmetalfxrosetta-2steamsteam-playwinewinecx
fix(steam): see every account's Steam, ask it to quit instead of killing it
raymondchins0cec7267294c
diff --git a/app/Sources/BridgeplayApp/Model/SteamBundle.swift b/app/Sources/BridgeplayApp/Model/SteamBundle.swiftindex d3a5cab..2cabf9b 100644--- a/app/Sources/BridgeplayApp/Model/SteamBundle.swift+++ b/app/Sources/BridgeplayApp/Model/SteamBundle.swift@@ -27,8 +27,15 @@ enum SteamBundle {FileManager.default.fileExists(atPath: SupportPaths.Steam.app.path(percentEncoded: false))}+ // Any account's Steam: they all run the same Steam.app, so one open in another account+ // still holds the bundle Bridgeplay re-signs.static var isRunning: Bool {+ Shell.processIsRunning(named: "steam_osx", allUsers: true)+ }+ // This account's Steam, the only one that writes this account's config.vdf and the+ // only one steam://exit reaches.+ static var isRunningForThisUser: Bool {Shell.processIsRunning(named: "steam_osx")}@@ -79,40 +86,56 @@ enum SteamBundle {return text.isEmpty ? nil : text}+ // What stopClient looks at and does, so tests can stand in for Steam.+ struct Client: Sendable {+ var runningAnywhere: @Sendable () -> Bool = { SteamBundle.isRunning }+ var runningHere: @Sendable () -> Bool = { SteamBundle.isRunningForThisUser }+ var askToQuit: @Sendable () -> Void = { _ = try? Shell.run("/usr/bin/open", ["-g", "steam://exit"]) }+ var sweep: @Sendable (String) -> Void = { _ = try? Shell.run("/usr/bin/pkill", ["-f", $0]) }+ var pause: @Sendable () -> Void = { Thread.sleep(forTimeInterval: 0.5) }+ var attempts = 60+ }++ // Asks this account's Steam to quit and waits up to 30 seconds. Steam is never killed:+ // it may be writing its config or an update, so a Steam that stays open is reported+ // instead. A Steam another account runs is out of reach and reported as such.static func stopClient(app: URL = SupportPaths.Steam.app,helpers: [URL] = [SupportPaths.Steam.innerApp],step: String,+ client: Client = Client(),onStopping: () -> Void = {}) throws -> Bool {- guard isRunning else { return false }- onStopping()-- _ = try? Shell.run("/usr/bin/open", ["-g", "steam://exit"])- for _ in 0..<60 where isRunning {- Thread.sleep(forTimeInterval: 0.5)+ guard client.runningAnywhere() else { return false }+ guard client.runningHere() else {+ throw StepFailure(step: step, detail: otherAccountRunning)}+ onStopping()- if isRunning {- _ = try? Shell.run("/usr/bin/pkill", ["-9", "-x", "steam_osx"])- for _ in 0..<10 where isRunning {- Thread.sleep(forTimeInterval: 0.5)- }+ client.askToQuit()+ for _ in 0..<client.attempts where client.runningHere() {+ client.pause()}- guard !isRunning else {+ guard !client.runningHere() else {throw StepFailure(step: step,- detail: String(localized: "Steam is running, please close Steam.")+ detail: String(localized: "Steam did not quit. Quit Steam, then try again."))}+ guard !client.runningAnywhere() else {+ throw StepFailure(step: step, detail: otherAccountRunning)+ }for pattern in sweepPatterns(app: app, helpers: helpers) {- _ = try? Shell.run("/usr/bin/pkill", ["-f", pattern])+ client.sweep(pattern)}return true}+ static let otherAccountRunning =+ String(localized: "Steam is open in another account on this Mac. Quit Steam in that account, then try again.")+static func sweepPatterns(app: URL, helpers: [URL]) -> [String] {([app] + helpers).map { url in(url.path(percentEncoded: false) + "/").reduce(into: "") { pattern, character indiff --git a/app/Sources/BridgeplayApp/Model/SteamInstaller.swift b/app/Sources/BridgeplayApp/Model/SteamInstaller.swiftindex 87edc41..f5db99e 100644--- a/app/Sources/BridgeplayApp/Model/SteamInstaller.swift+++ b/app/Sources/BridgeplayApp/Model/SteamInstaller.swift@@ -53,6 +53,19 @@ enum SteamInstaller {try SteamBundle.stopClient(app: app, step: step, onStopping: onStopping)}+ // For an install nobody asked for: it was decided while Steam was closed, and checking+ // again here, under the installation lock, keeps a Steam opened since then running.+ static let leaveTheClient: ClientStopper = { _, _ in+ if SteamBundle.isRunning { throw ClientStarted() }+ return false+ }++ struct ClientStarted: LocalizedError {+ var errorDescription: String? {+ String(localized: "Steam opened while Bridgeplay was getting ready to update it, so Steam was left alone.")+ }+ }+static func run(payload suppliedPayload: InstallPayload.Located? = nil,bridgePayload suppliedBridge: BridgePayload.Located? = nil,diff --git a/app/Sources/BridgeplayApp/Support/PostUpdateRefresh.swift b/app/Sources/BridgeplayApp/Support/PostUpdateRefresh.swiftindex 0a529da..a3f0e2a 100644--- a/app/Sources/BridgeplayApp/Support/PostUpdateRefresh.swift+++ b/app/Sources/BridgeplayApp/Support/PostUpdateRefresh.swift@@ -54,14 +54,16 @@ enum PostUpdateRefresh {handled = truelet build = ProductVersion.build- let workloadRunning = await Task.detached(priority: .utility) {- RunnerStore.clonedBuilds().contains {- RunnerInstaller.isRunning(from: SupportPaths.runnerRoot(forBuild: $0))- }+ // pgrep and ps can take seconds, so neither runs on the main actor.+ let (steamRunning, workloadRunning) = await Task.detached(priority: .utility) {+ (SteamBundle.isRunning,+ RunnerStore.clonedBuilds().contains {+ RunnerInstaller.isRunning(from: SupportPaths.runnerRoot(forBuild: $0))+ })}.valuelet decision = decide(steam: snapshot.steam,- steamRunning: snapshot.steamRunning || SteamBundle.isRunning,+ steamRunning: snapshot.steamRunning || steamRunning,workloadRunning: workloadRunning,contentBlocks: snapshot.installContent.blocksInstallation,hasRunner: snapshot.runner != .none,@@ -77,7 +79,7 @@ enum PostUpdateRefresh {case .install:AppLog.note("post-update: re-applying the Steam patch for \(ProductVersion.display)")if let build { defaults.set(build, forKey: lastBuildKey) }- await status.requestInstall()+ await status.requestInstall(unattended: true)}}}diff --git a/app/Sources/BridgeplayApp/Support/Shell.swift b/app/Sources/BridgeplayApp/Support/Shell.swiftindex b434a03..e7a2718 100644--- a/app/Sources/BridgeplayApp/Support/Shell.swift+++ b/app/Sources/BridgeplayApp/Support/Shell.swift@@ -147,11 +147,14 @@ enum Shell {return process.terminationStatus}+ // This account's processes only, unless allUsers: Steam.app is shared by every account+ // on the Mac, so a Steam another account runs still holds the bundle open.static func processIsRunning(- named name: String, pgrep: String = "/usr/bin/pgrep",+ named name: String, allUsers: Bool = false, pgrep: String = "/usr/bin/pgrep",drainTimeout: DispatchTimeInterval = outputDrainTimeout) -> Bool {- guard let result = try? run(pgrep, ["-x", "-U", String(getuid()), name], drainTimeout: drainTimeout)+ let owner = allUsers ? [] : ["-U", String(getuid())]+ guard let result = try? run(pgrep, ["-x"] + owner + [name], drainTimeout: drainTimeout)else { return false }return result.succeeded}diff --git a/app/Sources/BridgeplayApp/SystemStatus.swift b/app/Sources/BridgeplayApp/SystemStatus.swiftindex 589a7bd..949541e 100644--- a/app/Sources/BridgeplayApp/SystemStatus.swift+++ b/app/Sources/BridgeplayApp/SystemStatus.swift@@ -157,7 +157,11 @@ final class SystemStatus {AppLog.note("run end\(failure == nil ? "" : " (failed)")")}+ // What the last run threw, for callers that treat some failures as something else.+ @ObservationIgnored private(set) var lastRunError: Error?+private func record(_ error: Error) {+ lastRunError = errorsetFailure(error)if let refusal = error as? WriteRefused {AppLog.note("run failed: cannot write \(refusal.path)")@@ -242,7 +246,7 @@ final class SystemStatus {}}- func requestInstall() async {+ func requestInstall(unattended: Bool = false) async {guard canInstall else { return }checkingLicense = truedefer { checkingLicense = false }@@ -253,7 +257,7 @@ final class SystemStatus {) {pendingConfirmation = question} else {- await installIntoSteam()+ await installIntoSteam(unattended: unattended)}}@@ -442,6 +446,7 @@ final class SystemStatus {clearFailure()outcome = nil+ lastRunError = nillet run = beginRun(first)defer { endRun() }@@ -593,13 +598,17 @@ final class SystemStatus {}}- func installIntoSteam() async {+ // unattended: nobody pressed anything, so a Steam that opened since the decision to+ // install is left running and the install stops instead.+ func installIntoSteam(unattended: Bool = false) async {var failedInputResets: [String]?await perform(from: InstallPhase.checkingPayload.label) { progress inlet lock = try DeploymentContent.acquireInstallationLock()defer { lock.release() }+ let stopClient = unattended ? SteamInstaller.leaveTheClient : SteamInstaller.stopTheClientlet result = try await Task.detached(priority: .userInitiated) {- try SteamInstaller.run(holdingInstallationLock: true, report: { progress($0.label) })+ try SteamInstaller.run(holdingInstallationLock: true, stopClient: stopClient,+ report: { progress($0.label) })}.valuevar parts = [String(localized: "Bridgeplay successfully installed.")]@@ -732,7 +741,14 @@ final class SystemStatus {guard isIdle else { return }AppLog.note("patch keeper (\(trigger)): re-applying on its own, \(kind)")lastAutoReapply = now- await installIntoSteam()+ await installIntoSteam(unattended: true)+ if lastRunError is SteamInstaller.ClientStarted {+ // Not a failure: Steam opened in the meantime, so ask as if it had been open.+ AppLog.note("patch keeper (\(trigger)): Steam opened before re-applying, asking instead")+ clearFailure()+ patchBanner = SteamPatchKeeper.Banner(kind: kind, blocker: .steamRunning)+ return+ }settleReapply(kind)}}diff --git a/app/Tests/BridgeplayAppTests/ShellTests.swift b/app/Tests/BridgeplayAppTests/ShellTests.swiftindex d7ceea2..5818679 100644--- a/app/Tests/BridgeplayAppTests/ShellTests.swift+++ b/app/Tests/BridgeplayAppTests/ShellTests.swift@@ -119,6 +119,12 @@ struct ShellTests {#expect(Shell.processIsRunning(named: "WindowServer") == false)}+ // Steam.app is shared, so the check that guards changing it has to see every account.+ @Test("A process another account runs counts when asking about all accounts")+ func anotherAccountsProcessCountsForAllUsers() {+ #expect(Shell.processIsRunning(named: "WindowServer", allUsers: true))+ }+@Test("Nothing matching reports nothing running")func noMatchReportsNothingRunning() throws {let (pgrep, dir) = try stubPgrep(body: "exit 1")diff --git a/app/Tests/BridgeplayAppTests/SteamBundleTests.swift b/app/Tests/BridgeplayAppTests/SteamBundleTests.swiftindex eff803b..e50c2fe 100644--- a/app/Tests/BridgeplayAppTests/SteamBundleTests.swift+++ b/app/Tests/BridgeplayAppTests/SteamBundleTests.swift@@ -46,6 +46,83 @@ struct SteamBundleTests {#expect(patterns == [#"/Volumes/Games \(SSD\)\+/Steam\.app/"#])}+ // MARK: Stopping Steam++ // A stand-in Steam: running here and in another account, and whether it quits when asked.+ private final class FakeSteam: @unchecked Sendable {+ private let lock = NSLock()+ private var here: Bool+ private var elsewhere: Bool+ private let quits: Bool+ private(set) var asked = 0+ private(set) var swept: [String] = []++ init(here: Bool, elsewhere: Bool = false, quits: Bool = true) {+ self.here = here+ self.elsewhere = elsewhere+ self.quits = quits+ }++ var client: SteamBundle.Client {+ SteamBundle.Client(+ runningAnywhere: { self.lock.withLock { self.here || self.elsewhere } },+ runningHere: { self.lock.withLock { self.here } },+ askToQuit: { self.lock.withLock { self.asked += 1; if self.quits { self.here = false } } },+ sweep: { pattern in self.lock.withLock { self.swept.append(pattern) } },+ pause: {},+ attempts: 3)+ }+ }++ private func stop(_ steam: FakeSteam) throws -> Bool {+ try SteamBundle.stopClient(+ app: URL(filePath: "/tmp/Steam.app"), helpers: [], step: "Test", client: steam.client)+ }++ @Test("A closed Steam is left alone")+ func closedSteamIsLeftAlone() throws {+ let steam = FakeSteam(here: false)+ #expect(try stop(steam) == false)+ #expect(steam.asked == 0)+ #expect(steam.swept.isEmpty)+ }++ @Test("Steam that quits when asked is reported stopped, and its helpers are swept")+ func steamThatQuitsIsStopped() throws {+ let steam = FakeSteam(here: true)+ #expect(try stop(steam))+ #expect(steam.asked == 1)+ #expect(steam.swept == [#"/tmp/Steam\.app/"#])+ }++ // It used to be killed with SIGKILL after 30 seconds, mid-write or mid-update.+ @Test("Steam that does not quit is reported, never killed")+ func steamThatStaysIsReported() {+ let steam = FakeSteam(here: true, quits: false)+ let failure = #expect(throws: StepFailure.self) { try stop(steam) }+ #expect(failure?.detail.contains("did not quit") == true)+ #expect(steam.asked == 1)+ #expect(steam.swept.isEmpty)+ }++ // steam://exit only reaches this account's Steam; another account's keeps the bundle open.+ @Test("Steam open in another account stops the change without asking this one")+ func otherAccountsSteamIsReported() {+ let steam = FakeSteam(here: false, elsewhere: true)+ let failure = #expect(throws: StepFailure.self) { try stop(steam) }+ #expect(failure?.detail == SteamBundle.otherAccountRunning)+ #expect(steam.asked == 0)+ }++ @Test("Steam open in two accounts is reported once this one has quit")+ func bothAccountsSteamIsReported() {+ let steam = FakeSteam(here: true, elsewhere: true)+ let failure = #expect(throws: StepFailure.self) { try stop(steam) }+ #expect(failure?.detail == SteamBundle.otherAccountRunning)+ #expect(steam.asked == 1)+ #expect(steam.swept.isEmpty)+ }+private enum Insert {case absentcase own