Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.
Swift apple-silicond3dmetaldxmtdxvkfexgame-porting-toolkitgamingmac-gamingmacosmetalmoltenvksteamswiftuivkd3d-protonwhisky-alternativewindows-gameswinewine-wrapper
Mac apps stay out of the way and cover launchers; a stuck Steam first start restarts itself
Gauthier Piarrette2b97e6faa697
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swiftindex 1465ad8..af7d77e 100644--- a/Sources/HighballApp/AppState.swift+++ b/Sources/HighballApp/AppState.swift@@ -770,6 +770,15 @@ final class AppState {func open(url: URL) {guard let request = PlayLink.parse(url) else { return }refresh()+ if case let .launcher(id) = request.target {+ // A launcher stub (issue #53). Only a link carrying this install's token opens it:+ // a web page cannot start an install through the scheme.+ guard request.token == PlayLink.token(in: paths) else {+ fail(HighballError.failed(L("That launcher link did not come from one of your Highball apps."))); return+ }+ openOrInstallLauncher(id, short: BottleView.launcherMeta.first { $0.id == id }?.short ?? id)+ return+ }resolvePlayLink(request)}@@ -801,6 +810,18 @@ final class AppState {} catch { fail(error) }}+ /// A Mac app for a launcher (Steam, Epic, …) that opens it, installing it first if needed+ /// (issue #53). Highball's own icon stands in for a cover.+ func makeMacApp(forLauncher id: String, short: String) {+ let url = PlayLink.url(for: .launcher(id: id), token: PlayLink.token(in: paths))+ let icon = Bundle.main.url(forResource: "AppIcon", withExtension: "png")+ do {+ let app = try MacAppStub.write(title: short, libraryID: "launcher:\(id)", url: url, cover: icon)+ appendLog("made \(app.lastPathComponent) in ~/Applications/Highball")+ NSWorkspace.shared.activateFileViewerSelecting([app])+ } catch { fail(error) }+ }+// MARK: Install funnel (UX plan 0.7)/// Local only. Nothing leaves the Mac unless the person reads the aggregate and sends it.@@ -838,11 +859,34 @@ final class AppState {let bottles = await MainActor.run { [self] in self.bottles }let running = Set(bottles.filter { WineRunner.steamIsRunning(inPrefix: $0.url) }.map(\.name))await MainActor.run { [self] in if self.steamClients != running { self.steamClients = running } }+ // A first start that deadlocked after its bootstrap (issue #9) is restarted once.+ for bottle in bottles where running.contains(bottle.name) {+ guard let root = SteamLibrary.steamRoot(of: bottle), SteamFirstStart.isHung(steamRoot: root) else { continue }+ await MainActor.run { [self] in self.restartHungFirstStart(bottle) }+ }try? await Task.sleep(for: .seconds(8))}}}+ /// Bottles whose stuck first start was already restarted this run: once is the deal, a+ /// second hang is something to report, not to loop on.+ @ObservationIgnored private var firstStartRestarted: Set<String> = []++ /// Steam's first start deadlocked after its bootstrap (issue #9): stop it and start it again,+ /// which is what fixes it; say so in the strip so the wait has a name.+ func restartHungFirstStart(_ bottle: Bottle) {+ guard !firstStartRestarted.contains(bottle.name), !busy else { return }+ firstStartRestarted.insert(bottle.name)+ appendLog("Steam's first start in \(bottle.name) got stuck after its update; restarting it once")+ stage = L("Steam's first start got stuck; restarting it")+ killBottle(bottle)+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in+ guard let self, let fresh = self.bottles.first(where: { $0.name == bottle.name }) else { return }+ self.showSteam(in: fresh)+ }+ }+/// Brings the bottle's Steam window forward (the running client is asked to show it; with/// none running this is a normal Steam start).func showSteam(in bottle: Bottle) {diff --git a/Sources/HighballApp/BottleView.swift b/Sources/HighballApp/BottleView.swiftindex a62d54b..71423d8 100644--- a/Sources/HighballApp/BottleView.swift+++ b/Sources/HighballApp/BottleView.swift@@ -113,6 +113,7 @@ struct BottleView: View {else { state.applyRecipe(meta.id, to: bottle) }}.contextMenu {+ Button(L("Make a Mac app…")) { state.makeMacApp(forLauncher: meta.id, short: meta.short) }if installed, let pin {Button(L("Open")) { state.launch(pin: pin, in: bottle) }Button(L("Program settings…")) { editingPin = pin }diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swiftindex b52695e..4e1fb8b 100644--- a/Sources/HighballApp/HighballApp.swift+++ b/Sources/HighballApp/HighballApp.swift@@ -14,6 +14,9 @@ struct HighballApp: App {// with only Settings open cannot come back as Settings alone (issue #58).WindowGroup("Highball", id: "main") {ContentView()+ // One library window handles every play link; without this SwiftUI opens a new+ // window per link, one per Mac-app stub started (issue #53).+ .handlesExternalEvents(preferring: ["*"], allowing: ["*"]).environment(state).tint(HB.amber).preferredColorScheme(.dark)@@ -99,8 +102,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {func applicationDidFinishLaunching(_ notification: Notification) {// Works as a bare SwiftPM executable during development: give it a real UI presence.- NSApp.setActivationPolicy(.regular)- NSApp.activate(ignoringOtherApps: true)+ // A bundled app is activated by macOS on its own; forcing it here would also drag+ // Highball in front of a game a Mac-app stub just started with `open -g` (issue #53).+ if Bundle.main.bundleURL.pathExtension != "app" {+ NSApp.setActivationPolicy(.regular)+ NSApp.activate(ignoringOtherApps: true)+ }if let iconURL = Bundle.main.url(forResource: "AppIcon", withExtension: "png"),let icon = NSImage(contentsOf: iconURL) {NSApp.applicationIconImage = icondiff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swiftindex 84c188b..835ff9a 100644--- a/Sources/HighballApp/L10n.swift+++ b/Sources/HighballApp/L10n.swift@@ -179,6 +179,8 @@ enum L10n {"Run and add to Programs": "Lancer et ajouter aux programmes","Keep current": "Garder l’actuel","Make a Mac app…": "Créer une app Mac…",+ "Steam's first start got stuck; restarting it": "Le premier démarrage de Steam s’est bloqué ; on le relance",+ "That launcher link did not come from one of your Highball apps.": "Ce lien de lanceur ne vient pas d’une de vos apps Highball.","Open %@ in Highball?": "Ouvrir %@ dans Highball ?","This link did not come from one of your Highball apps, so it asks first.": "Ce lien ne vient pas d'une de vos apps Highball, donc il demande d'abord.","Make a Mac app for this game in ~/Applications/Highball: open it from the Dock, Spotlight or Launchpad to play without opening Highball first.": "Crée une app Mac pour ce jeu dans ~/Applications/Highball : ouvrez-la depuis le Dock, Spotlight ou Launchpad pour jouer sans ouvrir Highball.",diff --git a/Sources/HighballKit/MacAppStub.swift b/Sources/HighballKit/MacAppStub.swiftindex 5a30df5..470ed5b 100644--- a/Sources/HighballKit/MacAppStub.swift+++ b/Sources/HighballKit/MacAppStub.swift@@ -37,9 +37,10 @@ public enum MacAppStub {}/// The launcher: opens the play URL and exits. `open` hands the URL to Highball whether it- /// is running or not.+ /// is running or not; `-g` keeps Highball in the background so the game, not the library,+ /// is what comes to the front (issue #53).public static func launchScript(url: URL) -> String {- "#!/bin/sh\nexec /usr/bin/open \"\(url.absoluteString)\"\n"+ "#!/bin/sh\nexec /usr/bin/open -g \"\(url.absoluteString)\"\n"}public static func bundleID(for libraryID: String) -> String {diff --git a/Sources/HighballKit/PlayLink.swift b/Sources/HighballKit/PlayLink.swiftindex 8019118..38cc626 100644--- a/Sources/HighballKit/PlayLink.swift+++ b/Sources/HighballKit/PlayLink.swift@@ -10,13 +10,18 @@ public enum PlayLink {case steam(appid: Int)case epic(appName: String)case pin(bottle: String, id: UUID)+ /// A launcher (Steam, Epic, …) by recipe id: `highball://open/launcher/steam`. Opens it,+ /// installing it first if needed (issue #53: Mac icons for launchers too).+ case launcher(id: String)- /// The library item id this target maps to ("steam:620", "epic:Duck", "pin:Gaming:<uuid>").+ /// The library item id this target maps to ("steam:620", "epic:Duck", "pin:Gaming:<uuid>");+ /// a launcher has no library item and maps to "launcher:<id>".public var libraryID: String {switch self {case let .steam(appid): return "steam:\(appid)"case let .epic(name): return "epic:\(name)"case let .pin(bottle, id): return "pin:\(bottle):\(id.uuidString)"+ case let .launcher(id): return "launcher:\(id)"}}}@@ -27,12 +32,18 @@ public enum PlayLink {}/// Parses `highball://play/steam/620?t=<token>`, `highball://play/epic/<name>?t=...`,- /// `highball://play/pin/<bottle>/<uuid>?t=...`. Anything else is nil: no other action- /// exists behind the scheme.+ /// `highball://play/pin/<bottle>/<uuid>?t=...` and `highball://open/launcher/<id>?t=...`.+ /// Anything else is nil: no other action exists behind the scheme.public static func parse(_ url: URL) -> Request? {- guard url.scheme?.lowercased() == scheme, url.host?.lowercased() == "play" else { return nil }+ guard url.scheme?.lowercased() == scheme else { return nil }let parts = url.pathComponents.filter { $0 != "/" }let token = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "t" }?.value+ if url.host?.lowercased() == "open" {+ guard parts.count == 2, parts[0] == "launcher", !parts[1].isEmpty,+ parts[1].range(of: "^[a-z0-9-]+$", options: .regularExpression) != nil else { return nil }+ return Request(target: .launcher(id: parts[1]), token: token)+ }+ guard url.host?.lowercased() == "play" else { return nil }switch parts.first {case "steam":guard parts.count == 2, let appid = Int(parts[1]), appid > 0 else { return nil }@@ -55,6 +66,7 @@ public enum PlayLink {case let .steam(appid): c.path = "/steam/\(appid)"case let .epic(name): c.path = "/epic/\(name)"case let .pin(bottle, id): c.path = "/pin/\(bottle)/\(id.uuidString)"+ case let .launcher(id): c.host = "open"; c.path = "/launcher/\(id)"}c.queryItems = [URLQueryItem(name: "t", value: token)]return c.url!diff --git a/Sources/HighballKit/SteamFirstStart.swift b/Sources/HighballKit/SteamFirstStart.swiftnew file mode 100644index 0000000..89627c8--- /dev/null+++ b/Sources/HighballKit/SteamFirstStart.swift@@ -0,0 +1,47 @@+import Foundation++/// Steam's first start on the bundled engine sometimes deadlocks right after its bootstrapper+/// finishes (the relaunched client never gets past DLL loading; issue #9, seen on the+/// 2026-09-05 from-scratch run): the process stays alive with only the updater box on screen+/// and no login window, for as long as you wait. A relaunch fixes it every time. Steam's own+/// logs tell that state apart from a live client: the bootstrap log says "Update complete,+/// launching Steam..." and the connection log then stays silent, whereas a live client+/// connects within seconds. No login has ever happened (no loginusers.vdf), so nothing is lost+/// by restarting it once.+public enum SteamFirstStart {+ /// How long a client may sit after its bootstrap without connecting before it counts as hung.+ public static let patience: TimeInterval = 240++ /// Pure decision: `bootstrapDone` is the "Update complete" moment, `lastConnection` the+ /// newest connection-log entry, `everLoggedIn` whether loginusers.vdf exists.+ public static func isHung(bootstrapDone: Date?, lastConnection: Date?, everLoggedIn: Bool, now: Date = Date()) -> Bool {+ guard !everLoggedIn, let done = bootstrapDone else { return false }+ if let last = lastConnection, last >= done { return false } // it connected after the bootstrap: alive+ return now.timeIntervalSince(done) >= patience+ }++ /// Reads the bottle's Steam logs and decides. Missing logs mean "not hung" (nothing to judge).+ public static func isHung(steamRoot: URL, now: Date = Date()) -> Bool {+ let logs = steamRoot.appending(path: "logs")+ let done = lastTimestamp(in: logs.appending(path: "bootstrap_log.txt"), matching: "Update complete")+ let conn = lastTimestamp(in: logs.appending(path: "connection_log.txt"), matching: nil)+ let loggedIn = FileManager.default.fileExists(atPath: steamRoot.appending(path: "config/loginusers.vdf").path)+ return isHung(bootstrapDone: done, lastConnection: conn, everLoggedIn: loggedIn, now: now)+ }++ /// The newest `[YYYY-MM-DD HH:MM:SS]` stamp in the file (on a line containing `matching`,+ /// when given). Steam writes local time without a zone.+ static func lastTimestamp(in file: URL, matching: String?) -> Date? {+ guard let text = try? String(contentsOf: file, encoding: .utf8) else { return nil }+ let f = DateFormatter()+ f.dateFormat = "yyyy-MM-dd HH:mm:ss"; f.locale = Locale(identifier: "en_US_POSIX"); f.timeZone = .current+ var newest: Date?+ for line in text.split(separator: "\n").reversed() {+ if let m = matching, !line.contains(m) { continue }+ guard line.hasPrefix("["), let close = line.firstIndex(of: "]") else { continue }+ let stamp = String(line[line.index(after: line.startIndex)..<close])+ if let d = f.date(from: stamp) { newest = d; break }+ }+ return newest+ }+}diff --git a/Tests/HighballKitTests/PlayLinkTests.swift b/Tests/HighballKitTests/PlayLinkTests.swiftnew file mode 100644index 0000000..3d8078d--- /dev/null+++ b/Tests/HighballKitTests/PlayLinkTests.swift@@ -0,0 +1,28 @@+import XCTest+@testable import HighballKit++final class PlayLinkTests: XCTestCase {+ func testPlayLinksStillParseAndRoundTrip() {+ let steam = PlayLink.parse(URL(string: "highball://play/steam/620?t=abc")!)+ XCTAssertEqual(steam, PlayLink.Request(target: .steam(appid: 620), token: "abc"))+ XCTAssertEqual(PlayLink.url(for: .steam(appid: 620), token: "abc").absoluteString, "highball://play/steam/620?t=abc")+ XCTAssertNil(PlayLink.parse(URL(string: "highball://play/steam/0")!))+ }++ /// Issue #53: a Mac app for a launcher opens it through `highball://open/launcher/<id>`.+ func testLauncherLinkParsesAndRoundTrips() {+ let url = PlayLink.url(for: .launcher(id: "steam"), token: "tok")+ XCTAssertEqual(url.absoluteString, "highball://open/launcher/steam?t=tok")+ XCTAssertEqual(PlayLink.parse(url), PlayLink.Request(target: .launcher(id: "steam"), token: "tok"))+ XCTAssertEqual(PlayLink.Target.launcher(id: "epic").libraryID, "launcher:epic")+ XCTAssertNil(PlayLink.parse(URL(string: "highball://open/steam")!))+ XCTAssertNil(PlayLink.parse(URL(string: "highball://open/launcher/../x")!))+ XCTAssertNil(PlayLink.parse(URL(string: "highball://open/launcher/Steam%20Client")!))+ }++ /// A stub must not drag Highball in front of the game it starts (issue #53).+ func testStubOpensTheLinkInTheBackground() {+ let script = MacAppStub.launchScript(url: URL(string: "highball://play/steam/620?t=x")!)+ XCTAssertTrue(script.contains("/usr/bin/open -g \"highball://play/steam/620?t=x\""))+ }+}diff --git a/Tests/HighballKitTests/RegressionTests.swift b/Tests/HighballKitTests/RegressionTests.swiftindex 01abe9b..afeaf4e 100644--- a/Tests/HighballKitTests/RegressionTests.swift+++ b/Tests/HighballKitTests/RegressionTests.swift@@ -1075,7 +1075,7 @@ extension RegressionTests {XCTAssertEqual(MacAppStub.appName(for: "Half-Life: Alyx"), "Half-Life Alyx")XCTAssertEqual(MacAppStub.appName(for: " "), "Highball game")XCTAssertEqual(MacAppStub.bundleID(for: "steam:620"), "app.highball.stub.steam-620")- XCTAssertTrue(MacAppStub.launchScript(url: u).contains("/usr/bin/open \"highball://play/steam/620?t=abc\""))+ XCTAssertTrue(MacAppStub.launchScript(url: u).contains("/usr/bin/open -g \"highball://play/steam/620?t=abc\""), "stubs open the link without bringing Highball forward (issue #53)")XCTAssertTrue(MacAppStub.infoPlist(appName: "Portal 2", bundleID: "x").contains("<key>LSUIElement</key><true/>"), "no Dock icon of its own, no window")}diff --git a/Tests/HighballKitTests/SteamFirstStartTests.swift b/Tests/HighballKitTests/SteamFirstStartTests.swiftnew file mode 100644index 0000000..ed94d28--- /dev/null+++ b/Tests/HighballKitTests/SteamFirstStartTests.swift@@ -0,0 +1,30 @@+import XCTest+@testable import HighballKit++final class SteamFirstStartTests: XCTestCase {+ func testHungOnlyAfterPatienceWithNoConnectionAndNoLogin() {+ let done = Date(timeIntervalSince1970: 1_000)+ let now = done.addingTimeInterval(SteamFirstStart.patience + 1)+ XCTAssertTrue(SteamFirstStart.isHung(bootstrapDone: done, lastConnection: nil, everLoggedIn: false, now: now))+ XCTAssertFalse(SteamFirstStart.isHung(bootstrapDone: done, lastConnection: nil, everLoggedIn: false, now: done.addingTimeInterval(30)), "give it time")+ XCTAssertFalse(SteamFirstStart.isHung(bootstrapDone: done, lastConnection: done.addingTimeInterval(20), everLoggedIn: false, now: now), "it connected: alive")+ XCTAssertTrue(SteamFirstStart.isHung(bootstrapDone: done, lastConnection: done.addingTimeInterval(-500), everLoggedIn: false, now: now), "a connection older than the bootstrap does not count")+ XCTAssertFalse(SteamFirstStart.isHung(bootstrapDone: done, lastConnection: nil, everLoggedIn: true, now: now), "a client that has logged in before is never restarted by this")+ XCTAssertFalse(SteamFirstStart.isHung(bootstrapDone: nil, lastConnection: nil, everLoggedIn: false, now: now), "no bootstrap record: nothing to judge")+ }++ func testReadsSteamsOwnLogs() throws {+ let root = FileManager.default.temporaryDirectory.appending(path: "steam-\(UUID().uuidString)")+ let logs = root.appending(path: "logs")+ try FileManager.default.createDirectory(at: logs, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let f = DateFormatter(); f.dateFormat = "yyyy-MM-dd HH:mm:ss"; f.locale = Locale(identifier: "en_US_POSIX"); f.timeZone = .current+ let done = Date().addingTimeInterval(-600)+ try "[\(f.string(from: done.addingTimeInterval(-5)))] Verifying installation...\n[\(f.string(from: done))] Update complete, launching Steam...\n[\(f.string(from: done))] Shutdown\n"+ .write(to: logs.appending(path: "bootstrap_log.txt"), atomically: true, encoding: .utf8)+ XCTAssertTrue(SteamFirstStart.isHung(steamRoot: root), "bootstrap done 10 min ago, never connected, never logged in")+ try "[\(f.string(from: done.addingTimeInterval(40)))] [Connecting, 0, 7] [U:1:0] Connect() starting connection\n"+ .write(to: logs.appending(path: "connection_log.txt"), atomically: true, encoding: .utf8)+ XCTAssertFalse(SteamFirstStart.isHung(steamRoot: root), "it connected after the bootstrap")+ }+}