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
fix: address game page review and share Steam caches
Matias G.8b21e48c8060
diff --git a/Sources/HighballApp/CachedGalleryImageLoader.swift b/Sources/HighballApp/CachedGalleryImageLoader.swiftnew file mode 100644index 0000000..a78813c--- /dev/null+++ b/Sources/HighballApp/CachedGalleryImageLoader.swift@@ -0,0 +1,41 @@+import AppKit+import Foundation++/// Decoded images survive thumbnail/full-image view changes; URLCache also persists HTTP data.+/// Both caches are bounded so browsing galleries does not retain an entire library in memory.+@MainActor+final class CachedGalleryImageLoader {+ static let shared = CachedGalleryImageLoader()+ private let images = NSCache<NSURL, NSImage>()+ private var pending: [URL: Task<NSImage?, Never>] = [:]+ private let session: URLSession++ private init() {+ images.totalCostLimit = 64 * 1024 * 1024+ images.countLimit = 40+ let configuration = URLSessionConfiguration.default+ configuration.urlCache = URLCache(memoryCapacity: 8 * 1024 * 1024, diskCapacity: 64 * 1024 * 1024,+ diskPath: "HighballGallery")+ configuration.requestCachePolicy = .returnCacheDataElseLoad+ configuration.timeoutIntervalForRequest = 15+ configuration.timeoutIntervalForResource = 20+ session = URLSession(configuration: configuration)+ }++ func image(at url: URL) async -> NSImage? {+ if let image = images.object(forKey: url as NSURL) { return image }+ if let task = pending[url] { return await task.value }+ let task = Task<NSImage?, Never> {+ guard let (data, response) = try? await session.data(from: url),+ (response as? HTTPURLResponse)?.statusCode == 200,+ data.count <= 15 * 1024 * 1024, let image = NSImage(data: data) else { return nil }+ let pixels = image.representations.map { $0.pixelsWide * $0.pixelsHigh * 4 }.max() ?? data.count+ images.setObject(image, forKey: url as NSURL, cost: pixels)+ return image+ }+ pending[url] = task+ let image = await task.value+ pending[url] = nil+ return image+ }+}diff --git a/Sources/HighballApp/GameDetailView.swift b/Sources/HighballApp/GameDetailView.swiftindex 313a41c..faefb58 100644--- a/Sources/HighballApp/GameDetailView.swift+++ b/Sources/HighballApp/GameDetailView.swift@@ -7,7 +7,7 @@ struct GameDetailView: View {let passedItem: LibraryItem@Environment(\.accessibilityReduceMotion) private var reduceMotion@State private var storeDetails: SteamGameDetails?- @State private var loadingDetails = false+ @State private var loadingDetails = true@State private var expandedDescription = false@State private var selectedGalleryURL: URL?@State private var choseGalleryImage = false@@ -46,7 +46,7 @@ struct GameDetailView: View {}private var engineName: String? { bottle.flatMap { state.engine(for: $0) }?.displayName }- private var storeAppID: Int? { item.steamAppID ?? entry?.steam_appid }+ private var storeAppID: Int? { item.steamAppID }var body: some View {GeometryReader { geometry in@@ -63,9 +63,9 @@ struct GameDetailView: View {.frame(maxWidth: .infinity, alignment: .leading)}} else {+ overview(scroll: scroll)GameMediaGallery(item: item, details: storeDetails, width: width,selectedURL: $selectedGalleryURL, choseImage: $choseGalleryImage)- overview(scroll: scroll)}aboutGameif bottle != nil {@@ -99,6 +99,8 @@ struct GameDetailView: View {.font(.system(size: 30, weight: .bold, design: .rounded)).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)+ if let macBuild { macBlock(macBuild) }+ verdictBlockHStack(alignment: .top, spacing: 10) {playRow.frame(maxWidth: .infinity, alignment: .leading)if bottle != nil {@@ -116,10 +118,8 @@ struct GameDetailView: View {.help(L("Game settings"))}}- verdictBlockif item.installed, !blocked { willDoCard }libraryInfo- if let macBuild { macBlock(macBuild) }}}@@ -134,8 +134,8 @@ struct GameDetailView: View {}}.padding(18).frame(maxWidth: .infinity, alignment: .leading)- .background(HB.card, in: RoundedRectangle(cornerRadius: 16))- .overlay(RoundedRectangle(cornerRadius: 16).stroke(HB.cardStroke))+ .background(HB.card, in: RoundedRectangle(cornerRadius: 12))+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(HB.cardStroke))}@ViewBuilder private var aboutGame: some View {@@ -169,17 +169,14 @@ struct GameDetailView: View {Text(L("Game information and screenshots from Steam.")).font(.caption).foregroundStyle(.tertiary)}.padding(24).frame(maxWidth: .infinity, alignment: .leading)- .background(HB.card, in: RoundedRectangle(cornerRadius: 18))- .overlay(RoundedRectangle(cornerRadius: 18).stroke(HB.cardStroke))+ .background(HB.card, in: RoundedRectangle(cornerRadius: 12))+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(HB.cardStroke))} else if storeAppID != nil {HStack(spacing: 10) {if loadingDetails {ProgressView().controlSize(.small)Text(L("Loading game information…")).font(.callout).foregroundStyle(.secondary)} else {- Text(L("Steam information is unavailable. You can still play and manage this game."))- .font(.callout).foregroundStyle(.secondary)- Spacer()if let appID = storeAppID, let url = URL(string: "https://store.steampowered.com/app/\(appID)/") {Link(L("View on Steam"), destination: url).font(.callout)}@@ -339,6 +336,17 @@ struct GameDetailView: View {}}+ private func localizedWillDo(_ line: GamePageCopy.WillDo) -> String {+ guard let recipe = fixRecipe, recipe.isOptIn else { return line.text }+ if line.text == "Keep the \(recipe.title) fix you applied under Game settings" {+ return String(format: L("Keep the %@ fix you applied under Game settings"), recipe.title)+ }+ if line.text == "Leave the optional \(recipe.title) fix alone; it is under Game settings for when the notes say your Mac needs it" {+ return String(format: L("Leave the optional %@ fix alone; it is under Game settings for when the notes say your Mac needs it"), recipe.title)+ }+ return line.text+ }+private var willDoCard: some View {VStack(alignment: .leading, spacing: 8) {// Next to Play on Mac, "Play" alone would read as the Mac build's.@@ -349,7 +357,7 @@ struct GameDetailView: View {.font(.caption.weight(.bold)).foregroundStyle(line.cost == nil || line.done ? HB.good : HB.amber).frame(width: 14)- Text(line.text).font(.callout)+ Text(localizedWillDo(line)).font(.callout)if let cost = line.cost {Text(cost).font(.caption.monospacedDigit()).foregroundStyle(.secondary)}@@ -377,8 +385,8 @@ struct GameDetailView: View {}.padding(18).frame(maxWidth: .infinity, alignment: .leading)- .background(RoundedRectangle(cornerRadius: 16).fill(HB.card))- .overlay(RoundedRectangle(cornerRadius: 16).stroke(HB.cardStroke))+ .background(RoundedRectangle(cornerRadius: 12).fill(HB.card))+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(HB.cardStroke))}/// The explanation, and the way out: the environment's own settings are one click away.diff --git a/Sources/HighballApp/GameMediaGallery.swift b/Sources/HighballApp/GameMediaGallery.swiftindex bd4f314..2828c2d 100644--- a/Sources/HighballApp/GameMediaGallery.swift+++ b/Sources/HighballApp/GameMediaGallery.swift@@ -11,6 +11,7 @@ struct GameMediaGallery: View {@Binding var selectedURL: URL?@Binding var choseImage: Bool@State private var coverDropTargeted = false+ @FocusState private var galleryFocused: Boolprivate var screenshots: [SteamGameDetails.Screenshot] { details?.screenshots ?? [] }private var customCover: NSImage? {@@ -35,11 +36,11 @@ struct GameMediaGallery: View {if !screenshots.isEmpty {HStack(spacing: 10) {Button { select((selection + screenshots.count) % (screenshots.count + 1)) } label: {- Image(systemName: "chevron.left").frame(width: 28, height: 28)+ Image(systemName: "chevron.left").frame(width: 44, height: 44).contentShape(Rectangle())}.accessibilityLabel(L("Previous image"))Text("\(selection + 1) / \(screenshots.count + 1)").font(.caption.monospacedDigit())Button { select((selection + 1) % (screenshots.count + 1)) } label: {- Image(systemName: "chevron.right").frame(width: 28, height: 28)+ Image(systemName: "chevron.right").frame(width: 44, height: 44).contentShape(Rectangle())}.accessibilityLabel(L("Next image"))}.buttonStyle(.plain).foregroundStyle(.white)@@ -48,8 +49,8 @@ struct GameMediaGallery: View {.padding(14)}}- .clipShape(RoundedRectangle(cornerRadius: 20))- .overlay(RoundedRectangle(cornerRadius: 20)+ .clipShape(RoundedRectangle(cornerRadius: 12))+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(coverDropTargeted ? HB.amber : HB.cardStroke, lineWidth: coverDropTargeted ? 2 : 1)).onDrop(of: [.image], isTargeted: $coverDropTargeted) { providers inlet accepted = state.acceptCoverDrop(providers, for: item)@@ -74,6 +75,18 @@ struct GameMediaGallery: View {}}}+ .focusable()+ .focused($galleryFocused)+ .onKeyPress(.leftArrow) {+ guard !screenshots.isEmpty else { return .ignored }+ select((selection + screenshots.count) % (screenshots.count + 1))+ return .handled+ }+ .onKeyPress(.rightArrow) {+ guard !screenshots.isEmpty else { return .ignored }+ select((selection + 1) % (screenshots.count + 1))+ return .handled+ }.onAppear { pickInitialImage() }.onChange(of: details?.appID) { _, _ inpickInitialImage()@@ -90,8 +103,8 @@ struct GameMediaGallery: View {Color.black.opacity(0.24).frame(width: 128, height: 72).overlay { GalleryImage(url: url, local: local, thumbnail: true) }- .clipShape(RoundedRectangle(cornerRadius: 9))- .overlay(RoundedRectangle(cornerRadius: 9).stroke(index == selection ? HB.amber : HB.cardStroke, lineWidth: index == selection ? 2 : 1))+ .clipShape(RoundedRectangle(cornerRadius: 10))+ .overlay(RoundedRectangle(cornerRadius: 10).stroke(index == selection ? HB.amber : HB.cardStroke, lineWidth: index == selection ? 2 : 1))}.buttonStyle(.plain).id(index)@@ -101,6 +114,7 @@ struct GameMediaGallery: View {private func select(_ index: Int) {choseImage = true+ galleryFocused = truewithAnimation(reduceMotion ? nil : .easeInOut(duration: 0.18)) {selectedURL = index == 0 ? nil : screenshots[index - 1].full}@@ -111,18 +125,25 @@ private struct GalleryImage: View {let url: URL?var local: NSImage? = nilvar thumbnail = false+ @State private var remoteImage: NSImage?+ @State private var loading = truevar body: some View {if let local = local ?? url.flatMap({ $0.isFileURL ? NSImage(contentsOf: $0) : nil }) {Image(nsImage: local).resizable().scaledToFit()} else if let url {- AsyncImage(url: url) { phase in- switch phase {- case .success(let image): image.resizable().scaledToFit()- case .empty:- if thumbnail { placeholder } else { ProgressView().controlSize(.small) }- default: placeholder- }+ Group {+ if let remoteImage { Image(nsImage: remoteImage).resizable().scaledToFit() }+ else if loading, !thumbnail { ProgressView().controlSize(.small) }+ else { placeholder }+ }+ .task(id: url) {+ remoteImage = nil+ loading = true+ let image = await CachedGalleryImageLoader.shared.image(at: url)+ guard !Task.isCancelled else { return }+ remoteImage = image+ loading = false}} else { placeholder }}diff --git a/Sources/HighballApp/HighballApp.swift b/Sources/HighballApp/HighballApp.swiftindex e7ceff5..ffddf70 100644--- a/Sources/HighballApp/HighballApp.swift+++ b/Sources/HighballApp/HighballApp.swift@@ -443,7 +443,7 @@ private extension View {}Button(L("Not now"), role: .cancel) { state.rendererTrial = nil }} message: { trial in- Text(String(format: L("It ran with %@. Another mode often suits a game better on this Mac, and old DirectX 9 games in particular do badly on Wine's own Direct3D. This changes the mode for this game only; the environment keeps its own. Undo it any time under Advanced on the game's page."), GamePageCopy.plainName(trial.current)))+ Text(String(format: L("It ran with %@. Another mode often suits a game better on this Mac, and old DirectX 9 games in particular do badly on Wine's own Direct3D. This changes the mode for this game only; the environment keeps its own. Undo it any time under Game settings on the game's page."), GamePageCopy.plainName(trial.current)))}}/// The offer that follows a "had problems" on a game whose log shows a fullscreen mode@@ -456,7 +456,7 @@ private extension View {Button(L("Scale it to the screen")) { state.acceptModesetTrial() }Button(L("Not now"), role: .cancel) { state.modesetTrial = nil }} message: { _ in- Text(L("Its last run asked Windows for a fullscreen size this Mac did not switch to. That is what leaves a game small in a corner, or with the mouse landing away from what it draws. Highball can have Wine report the change as done and scale the game to the screen instead. This game only; undo it under Advanced on its page."))+ Text(L("Its last run asked Windows for a fullscreen size this Mac did not switch to. That is what leaves a game small in a corner, or with the mouse landing away from what it draws. Highball can have Wine report the change as done and scale the game to the screen instead. This game only; undo it under Game settings on its page."))}}diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swiftindex 66b4d2f..ff93d6c 100644--- a/Sources/HighballApp/L10n.swift+++ b/Sources/HighballApp/L10n.swift@@ -10,6 +10,8 @@ func L(_ en: String) -> String {enum L10n {static let fr: [String: String] = ["Game settings": "Réglages du jeu",+ "Keep the %@ fix you applied under Game settings": "Conserver le correctif %@ appliqué dans Réglages du jeu",+ "Leave the optional %@ fix alone; it is under Game settings for when the notes say your Mac needs it": "Laisser le correctif facultatif %@ désactivé ; il se trouve dans Réglages du jeu si les notes indiquent que votre Mac en a besoin","About this game": "À propos de ce jeu","View on Steam": "Voir sur Steam","Read more": "Lire la suite",@@ -18,7 +20,6 @@ enum L10n {"Release date": "Date de sortie","Game information and screenshots from Steam.": "Informations et captures d’écran fournies par Steam.","Loading game information…": "Chargement des informations du jeu…",- "Steam information is unavailable. You can still play and manage this game.": "Les informations Steam sont indisponibles. Vous pouvez toujours jouer et gérer ce jeu.","Previous image": "Image précédente","Next image": "Image suivante","Game artwork": "Visuel du jeu",@@ -222,7 +223,7 @@ enum L10n {"Use %@ for this game": "Utiliser %@ pour ce jeu","Try %@ for %@ next time?": "Essayer %@ pour %@ la prochaine fois ?","Report how it went…": "Signaler comment ça s'est passé…",- "It ran with %@. Another mode often suits a game better on this Mac, and old DirectX 9 games in particular do badly on Wine's own Direct3D. This changes the mode for this game only; the environment keeps its own. Undo it any time under Advanced on the game's page.": "Il a tourné avec %@. Un autre mode convient souvent mieux à un jeu sur ce Mac, et les vieux jeux DirectX 9 en particulier tournent mal avec le Direct3D de Wine. Cela change le mode pour ce jeu seulement, l'environnement garde le sien. Annulable à tout moment dans Avancé sur la page du jeu.",+ "It ran with %@. Another mode often suits a game better on this Mac, and old DirectX 9 games in particular do badly on Wine's own Direct3D. This changes the mode for this game only; the environment keeps its own. Undo it any time under Game settings on the game's page.": "Il a tourné avec %@. Un autre mode convient souvent mieux à un jeu sur ce Mac, et les vieux jeux DirectX 9 en particulier tournent mal avec le Direct3D de Wine. Cela change le mode pour ce jeu seulement, l'environnement garde le sien. Annulable à tout moment dans Réglages du jeu sur la page du jeu.","Does not apply: this game draws with Vulkan directly, not through any Direct3D layer.": "Sans effet : ce jeu dessine directement avec Vulkan, sans couche Direct3D.","%@ needs the %@ engine": "%@ a besoin du moteur %@","%@ needs a newer Highball": "%@ a besoin d'un Highball plus récent",@@ -524,7 +525,6 @@ enum L10n {"That usually means the graphics mode doesn't suit it on this Mac. Highball can switch this bottle to %@, or move it to engine %@.": "Cela veut généralement dire que le mode graphique ne lui convient pas sur ce Mac. Highball peut passer cet environnement en %@, ou le déplacer sur le moteur %@.","That usually means the graphics mode doesn't suit it on this Mac. Highball can switch this bottle to %@.": "Cela veut généralement dire que le mode graphique ne lui convient pas sur ce Mac. Highball peut passer cet environnement en %@.","The engine is the Wine build and graphics layers Highball runs games with. Highball picks it; an update never moves an environment to a different Wine build on its own.": "Le moteur est la version de Wine et les couches graphiques avec lesquelles Highball fait tourner les jeux. Highball le choisit ; une mise à jour ne déplace jamais un environnement vers une autre version de Wine toute seule.",- "To play with the environment's own graphics mode instead, change it under Advanced below; Highball then leaves it alone for every game in that environment.": "Pour jouer avec le mode graphique propre à l'environnement, changez-le sous Avancé ci-dessous ; Highball n'y touchera plus pour aucun jeu de cet environnement.","Troubleshooting": "Dépannage","Turn it on and play": "L'activer et jouer","Verified with": "Vérifié avec",@@ -568,7 +568,7 @@ enum L10n {"Installing engine %@ again": "Réinstallation du moteur %@","Scale %@ to the screen next time?": "Adapter %@ à l'écran la prochaine fois ?","Scale it to the screen": "L'adapter à l'écran",- "Its last run asked Windows for a fullscreen size this Mac did not switch to. That is what leaves a game small in a corner, or with the mouse landing away from what it draws. Highball can have Wine report the change as done and scale the game to the screen instead. This game only; undo it under Advanced on its page.": "Sa dernière session a demandé à Windows une résolution plein écran que ce Mac n'a pas appliquée. C'est ce qui laisse un jeu petit dans un coin, ou avec la souris qui tombe à côté de ce qui est dessiné. Highball peut faire répondre à Wine que le changement a eu lieu et adapter l'image à l'écran. Pour ce jeu seulement, annulable dans Avancé sur sa page.",+ "Its last run asked Windows for a fullscreen size this Mac did not switch to. That is what leaves a game small in a corner, or with the mouse landing away from what it draws. Highball can have Wine report the change as done and scale the game to the screen instead. This game only; undo it under Game settings on its page.": "Sa dernière session a demandé à Windows une résolution plein écran que ce Mac n'a pas appliquée. C'est ce qui laisse un jeu petit dans un coin, ou avec la souris qui tombe à côté de ce qui est dessiné. Highball peut faire répondre à Wine que le changement a eu lieu et adapter l'image à l'écran. Pour ce jeu seulement, annulable dans Réglages du jeu sur sa page.","Remove %@?": "Supprimer %@ ?","Remove": "Supprimer","Removing %@": "Suppression de %@",diff --git a/Sources/HighballKit/GamePageCopy.swift b/Sources/HighballKit/GamePageCopy.swiftindex 2b81c3d..e1db7fc 100644--- a/Sources/HighballKit/GamePageCopy.swift+++ b/Sources/HighballKit/GamePageCopy.swift@@ -128,8 +128,8 @@ public enum GamePageCopy {// Play does not touch an opt-in fix; the page says so rather than listing steps// Play will not take.items.append(WillDo(text: applied- ? "Keep the \(recipe.title) fix you applied under Advanced"- : "Leave the optional \(recipe.title) fix alone; it is under Advanced for when the notes say your Mac needs it",+ ? "Keep the \(recipe.title) fix you applied under Game settings"+ : "Leave the optional \(recipe.title) fix alone; it is under Game settings for when the notes say your Mac needs it",done: applied))} else if let recipe {for step in recipe.steps {diff --git a/Sources/HighballKit/MacSteamBuild.swift b/Sources/HighballKit/MacSteamBuild.swiftindex 6feaec2..0e361e0 100644--- a/Sources/HighballKit/MacSteamBuild.swift+++ b/Sources/HighballKit/MacSteamBuild.swift@@ -49,9 +49,10 @@ public struct NativeMacInfo: Codable, Sendable, Equatable {}/// Store `platforms.mac` flags, cached in `mac-flags.json` for two weeks. Only Steam games whose-/// appinfo lists macOS are asked about (worthAsking), one request each: the store API takes one-/// appid per `platforms` request and allows about 200 requests per five minutes. A failed or-/// refused request is "don't know", never "no Mac version", so it's asked again next time.+/// appinfo lists macOS are asked about (worthAsking), using the shared full appdetails response: the store API takes one+/// appid per request and allows about 200 requests per five minutes. A failed or+/// refused request is "don't know", never "no Mac version". The shared appdetails client+/// remembers failures for a day and stops both consumers when Steam refuses requests.public struct MacFlagStore: Sendable {public struct Record: Codable, Sendable, Equatable {public var mac: Bool@@ -91,21 +92,15 @@ public struct MacFlagStore: Sendable {}/// Asks the store about the appids not cached yet and returns every known flag.- public func refresh(_ appids: [Int], now: Date = Date()) async -> [Int: Bool] {+ public func refresh(_ appids: [Int], now: Date = Date(), client: SteamAppDetailsClient = .shared) async -> [Int: Bool] {var known = load(now: now)let missing = appids.filter { known[$0] == nil }guard !missing.isEmpty else { return known }- let cfg = URLSessionConfiguration.ephemeral- cfg.timeoutIntervalForRequest = 15- let session = URLSession(configuration: cfg)var fetched: [Int: Bool] = [:]for appid in missing {if Task.isCancelled { break }- let url = URL(string: "https://store.steampowered.com/api/appdetails?appids=\(appid)&filters=platforms")!- guard let (data, response) = try? await session.data(from: url) else { continue }- let status = (response as? HTTPURLResponse)?.statusCode- if status == 429 || status == 403 { break } // rate limited: the rest wait for next session- guard status == 200, let mac = Self.parse(data) else { continue }+ guard let data = await client.appDetails(appID: appid, now: now),+ let mac = Self.parse(data) else { continue }fetched[appid] = mac}if !fetched.isEmpty { save(fetched, now: now) }diff --git a/Sources/HighballKit/SteamAppDetailsClient.swift b/Sources/HighballKit/SteamAppDetailsClient.swiftnew file mode 100644index 0000000..5199323--- /dev/null+++ b/Sources/HighballKit/SteamAppDetailsClient.swift@@ -0,0 +1,81 @@+import Foundation++/// Shared store appdetails transport for native Mac flags and game-page information.+/// Full responses are cached once per language; unavailable pages persist for a day.+public actor SteamAppDetailsClient {+ public enum Language: String, Sendable { case english, french }+ public static let shared = SteamAppDetailsClient()+ static let maxAge: TimeInterval = 7 * 24 * 3600+ static let failureAge: TimeInterval = 24 * 3600+ private struct Record: Codable {+ let version: Int+ let checked: Date+ let data: Data?+ let failed: Date?+ }+ private let directory: URL+ private let fetch: @Sendable (URL) async throws -> (Data, Int)+ private var pending: [String: Task<Data?, Never>] = [:]+ // One refusal stops both consumers, rather than continuing through the owned library.+ private var stoppedUntil: Date?++ public init(directory: URL? = nil) {+ self.directory = directory ?? FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]+ .appending(path: "Highball/SteamAppDetails", directoryHint: .isDirectory)+ let configuration = URLSessionConfiguration.ephemeral+ configuration.timeoutIntervalForRequest = 15+ configuration.timeoutIntervalForResource = 20+ let session = URLSession(configuration: configuration)+ fetch = { url in+ let (data, response) = try await session.data(from: url)+ return (data, (response as? HTTPURLResponse)?.statusCode ?? 0)+ }+ }++ init(directory: URL, fetch: @escaping @Sendable (URL) async throws -> (Data, Int)) {+ self.directory = directory; self.fetch = fetch+ }++ public func appDetails(appID: Int, language: Language = .english, now: Date = Date()) async -> Data? {+ guard appID > 0 else { return nil }+ let key = "\(appID)-\(language.rawValue)"+ let file = directory.appending(path: "\(key).json")+ let record = (try? Data(contentsOf: file)).flatMap { try? JSONDecoder().decode(Record.self, from: $0) }+ let cached = record?.version == 1 ? record : nil+ if let data = cached?.data, let checked = cached?.checked, now.timeIntervalSince(checked) < Self.maxAge { return data }+ if let failed = cached?.failed, now.timeIntervalSince(failed) < Self.failureAge { return cached?.data }+ if let stoppedUntil, now < stoppedUntil { return cached?.data }+ if let task = pending[key] { return await task.value }+ // The task includes cache writes and refusal handling before other callers resume.+ let task = Task { await self.load(appID: appID, language: language, file: file, cached: cached, now: now) }+ pending[key] = task+ let result = await task.value+ pending[key] = nil+ return result+ }++ private func load(appID: Int, language: Language, file: URL, cached: Record?, now: Date) async -> Data? {+ let url = URL(string: "https://store.steampowered.com/api/appdetails?appids=\(appID)&l=\(language.rawValue)")!+ let response = try? await fetch(url)+ if response?.1 == 429 || response?.1 == 403 { stoppedUntil = now.addingTimeInterval(Self.failureAge) }+ if let (data, status) = response, status == 200, data.count <= 2_000_000, Self.valid(data, appID: appID) {+ save(Record(version: 1, checked: now, data: data, failed: nil), to: file)+ return data+ }+ save(Record(version: 1, checked: cached?.checked ?? now, data: cached?.data, failed: now), to: file)+ return cached?.data+ }++ private static func valid(_ data: Data, appID: Int) -> Bool {+ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let app = json[String(appID)] as? [String: Any], app["success"] as? Bool == true,+ let fields = app["data"] as? [String: Any], fields["steam_appid"] as? Int == appID else { return false }+ return true+ }++ private func save(_ record: Record, to file: URL) {+ guard let data = try? JSONEncoder().encode(record) else { return }+ try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ try? data.write(to: file, options: .atomic)+ }+}diff --git a/Sources/HighballKit/SteamGameDetails.swift b/Sources/HighballKit/SteamGameDetails.swiftindex a534017..bbce7fa 100644--- a/Sources/HighballKit/SteamGameDetails.swift+++ b/Sources/HighballKit/SteamGameDetails.swift@@ -75,62 +75,21 @@ public struct SteamGameDetails: Codable, Sendable, Equatable {}}-/// One request when a page is opened, cached for a week. A failed refresh retains the old copy;-/// failures are backed off for five minutes and overlapping requests share one task.-public actor SteamGameDetailsStore {- public enum Language: String, Sendable { case english, french }- public static let shared = SteamGameDetailsStore()- static let maxAge: TimeInterval = 7 * 24 * 3600- private struct Record: Codable { let version: Int; let checked: Date; let details: SteamGameDetails }- private let directory: URL- private let fetch: @Sendable (URL) async throws -> (Data, Int)- private var pending: [String: Task<SteamGameDetails?, Never>] = [:]- private var failed: [String: Date] = [:]+/// Presentation decoder over the same appdetails client used by native Mac detection.+public struct SteamGameDetailsStore: Sendable {+ public typealias Language = SteamAppDetailsClient.Language+ public static let shared = SteamGameDetailsStore(client: .shared)+ static let maxAge = SteamAppDetailsClient.maxAge+ private let client: SteamAppDetailsClient- public init(directory: URL? = nil) {- self.directory = directory ?? FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]- .appending(path: "Highball/SteamDetails", directoryHint: .isDirectory)- let configuration = URLSessionConfiguration.ephemeral- configuration.timeoutIntervalForRequest = 15- configuration.timeoutIntervalForResource = 20- let session = URLSession(configuration: configuration)- fetch = { url in- let (data, response) = try await session.data(from: url)- return (data, (response as? HTTPURLResponse)?.statusCode ?? 0)- }- }+ public init(client: SteamAppDetailsClient = .shared) { self.client = client }init(directory: URL, fetch: @escaping @Sendable (URL) async throws -> (Data, Int)) {- self.directory = directory; self.fetch = fetch+ client = SteamAppDetailsClient(directory: directory, fetch: fetch)}public func details(appID: Int, language: Language = .english, now: Date = Date()) async -> SteamGameDetails? {- guard appID > 0 else { return nil }- let key = "\(appID)-\(language.rawValue)"- let file = directory.appending(path: "\(key).json")- let record = (try? Data(contentsOf: file)).flatMap { try? JSONDecoder().decode(Record.self, from: $0) }- let cached = record?.version == 1 && record?.details.appID == appID ? record : nil- if let cached, now.timeIntervalSince(cached.checked) < Self.maxAge { return cached.details }- if let failure = failed[key], now.timeIntervalSince(failure) < 300 { return cached?.details }- if let task = pending[key] { return await task.value ?? cached?.details }- let url = URL(string: "https://store.steampowered.com/api/appdetails?appids=\(appID)&l=\(language.rawValue)")!- let fetch = self.fetch- let task = Task<SteamGameDetails?, Never> {- guard let (data, status) = try? await fetch(url), status == 200, data.count <= 2_000_000 else { return nil }- return SteamGameDetails.parse(data, appID: appID)- }- pending[key] = task- let result = await task.value- pending[key] = nil- if let result {- failed[key] = nil- if let data = try? JSONEncoder().encode(Record(version: 1, checked: now, details: result)) {- try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- try? data.write(to: file, options: .atomic)- }- return result- }- failed[key] = now- return cached?.details+ guard let data = await client.appDetails(appID: appID, language: language, now: now) else { return nil }+ return SteamGameDetails.parse(data, appID: appID)}}diff --git a/Tests/HighballKitTests/GamePageCopyTests.swift b/Tests/HighballKitTests/GamePageCopyTests.swiftindex 46072ce..0df3b5e 100644--- a/Tests/HighballKitTests/GamePageCopyTests.swift+++ b/Tests/HighballKitTests/GamePageCopyTests.swift@@ -62,10 +62,10 @@ final class GamePageCopyTests: XCTestCase {let items = GamePageCopy.willDo(e, recipe: recipe, applied: false, bottleRenderer: .dxvk, osMajor: 26)XCTAssertEqual(items.map(\.text), ["Use DXVK (Vulkan on Metal), the way it was verified",- "Leave the optional Modern Direct3D 9 fix alone; it is under Advanced for when the notes say your Mac needs it",+ "Leave the optional Modern Direct3D 9 fix alone; it is under Game settings for when the notes say your Mac needs it",])let done = GamePageCopy.willDo(e, recipe: recipe, applied: true, bottleRenderer: .dxvk, osMajor: 26)- XCTAssertEqual(done[1].text, "Keep the Modern Direct3D 9 fix you applied under Advanced")+ XCTAssertEqual(done[1].text, "Keep the Modern Direct3D 9 fix you applied under Game settings")XCTAssertTrue(done[1].done)let json = #"{"id":"x","kind":"game","title":"t","optIn":true,"steps":[{"type":"note","text":"n"}]}"#let decoded = try JSONDecoder.highball.decode(Recipe.self, from: Data(json.utf8))diff --git a/Tests/HighballKitTests/SteamGameDetailsTests.swift b/Tests/HighballKitTests/SteamGameDetailsTests.swiftindex fbabcda..13232bb 100644--- a/Tests/HighballKitTests/SteamGameDetailsTests.swift+++ b/Tests/HighballKitTests/SteamGameDetailsTests.swift@@ -4,7 +4,7 @@ import XCTestfinal class SteamGameDetailsTests: XCTestCase {private let sample = Data(#"""{"42":{"success":true,"data":{"steam_appid":42,- "short_description":"Explore & survive — together.",+ "platforms":{"mac":true},"short_description":"Explore & survive — together.","about_the_game":"<h2>A world</h2><p>Play <your way>.</p><script>hidden()</script><ul><li>Explore</li><li>Build</li></ul>","header_image":"https://shared.akamai.steamstatic.com/header.jpg","screenshots":[@@ -88,7 +88,7 @@ final class SteamGameDetailsTests: XCTestCase {let calls = await probe.callsXCTAssertEqual(calls.count, 2)await probe.setStatus(200)- let recovered = await store.details(appID: 42, now: later.addingTimeInterval(301))+ let recovered = await store.details(appID: 42, now: later.addingTimeInterval(SteamAppDetailsClient.failureAge + 1))XCTAssertEqual(recovered, original)let afterRetry = await probe.callsXCTAssertEqual(afterRetry.count, 3)@@ -106,6 +106,56 @@ final class SteamGameDetailsTests: XCTestCase {XCTAssertEqual(calls.count, 1)}+ func testUnavailablePageFailureSurvivesRelaunchForADay() async throws {+ let directory = try cacheDirectory(), now = Date(timeIntervalSince1970: 1000)+ let probe = FetchProbe(data: Data(#"{"42":{"success":false}}"#.utf8))+ let store = SteamGameDetailsStore(directory: directory, fetch: { await probe.fetch($0) })+ let missing = await store.details(appID: 42, now: now)+ XCTAssertNil(missing)+ let relaunched = SteamGameDetailsStore(directory: directory, fetch: { await probe.fetch($0) })+ _ = await relaunched.details(appID: 42, now: now.addingTimeInterval(23 * 3600))+ let beforeExpiry = await probe.calls+ XCTAssertEqual(beforeExpiry.count, 1)+ _ = await relaunched.details(appID: 42, now: now.addingTimeInterval(24 * 3600 + 1))+ let afterExpiry = await probe.calls+ XCTAssertEqual(afterExpiry.count, 2)+ }++ func testMacFlagsAndGameDetailsShareOneResponseInEitherOrder() async throws {+ for flagsFirst in [false, true] {+ let directory = try cacheDirectory(), now = Date(timeIntervalSince1970: 1000)+ let probe = FetchProbe(data: sample)+ let client = SteamAppDetailsClient(directory: directory, fetch: { await probe.fetch($0) })+ let details = SteamGameDetailsStore(client: client)+ let flags = MacFlagStore(file: directory.appending(path: "mac-flags.json"))+ if flagsFirst { _ = await flags.refresh([42], now: now, client: client) }+ let game = await details.details(appID: 42, now: now)+ let mac = await flags.refresh([42], now: now, client: client)+ XCTAssertNotNil(game)+ XCTAssertEqual(mac[42], true)+ let calls = await probe.calls+ XCTAssertEqual(calls.count, 1)+ }+ }++ func testRateLimitStopsBothConsumersAndDoesNotInventNegativeMacFlags() async throws {+ let directory = try cacheDirectory(), now = Date(timeIntervalSince1970: 1000)+ let probe = FetchProbe(data: sample)+ await probe.setStatus(429)+ let client = SteamAppDetailsClient(directory: directory, fetch: { await probe.fetch($0) })+ let flags = MacFlagStore(file: directory.appending(path: "mac-flags.json"))+ let mac = await flags.refresh([42, 43, 44], now: now, client: client)+ XCTAssertTrue(mac.isEmpty)+ let game = await SteamGameDetailsStore(client: client).details(appID: 45, now: now)+ XCTAssertNil(game)+ let calls = await probe.calls+ XCTAssertEqual(calls.count, 1)+ let relaunched = SteamAppDetailsClient(directory: directory, fetch: { await probe.fetch($0) })+ _ = await relaunched.appDetails(appID: 42, now: now.addingTimeInterval(60))+ let afterRelaunch = await probe.calls+ XCTAssertEqual(afterRelaunch.count, 1)+ }+func testCorruptCacheRefetchesAndInvalidAppDoesNotRequest() async throws {let directory = try cacheDirectory()try Data("bad cache".utf8).write(to: directory.appending(path: "42-english.json"))