Skip to content

Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit

feat(reports): one-tap compatibility reports from the app

raymondchins3c2775d8bc14
diff --git a/.github/ISSUE_TEMPLATE/game-report.yml b/.github/ISSUE_TEMPLATE/game-report.yml
index 2bd5ee6..600da3a 100644
--- a/.github/ISSUE_TEMPLATE/game-report.yml
+++ b/.github/ISSUE_TEMPLATE/game-report.yml
@@ -6,7 +6,9 @@ body:
- type: markdown
attributes:
value: |
- Played it with the Bridgeplay app? Fill in the fields and attach the game's `bridgeplay-run.log` (Prefixes page › the game › Open Log).
+ **Have Bridgeplay? You don't need this form.** After you play, the app asks how the game ran; one tap posts the report, log included, to [Compatibility reports](https://github.com/raymondchins/Bridgeplay/discussions/categories/compatibility-reports) and it counts on the [compatibility list](https://bridgeplay.dev/compatibility). Missed the question? Right-click the game on the Prefixes page and choose **Report This Game…**.
+
+ This form is for anyone reporting without the app. A maintainer checks it and adds the result to the list by hand.
Working from a Bridgeplay checkout? Run `scripts/np-test-game.sh <appid> --stop` instead and attach the zipped `compat/runs/<appid>-<timestamp>/` folder.
- type: input
@@ -70,11 +72,38 @@ body:
description: Shown at the bottom of the app's sidebar (for example 3.0.1 (35)), or `git rev-parse --short HEAD` in a checkout.
validations:
required: true
+ - type: dropdown
+ id: chip
+ attributes:
+ label: Mac chip
+ description: Apple menu › About This Mac.
+ options: [M1, M1 Pro, M1 Max, M1 Ultra, M2, M2 Pro, M2 Max, M2 Ultra, M3, M3 Pro, M3 Max, M3 Ultra, M4, M4 Pro, M4 Max, M5, M5 Pro, M5 Max, Other]
+ validations:
+ required: true
+ - type: dropdown
+ id: memory
+ attributes:
+ label: Memory (RAM)
+ options: ["8 GB", "16 GB", "18 GB", "24 GB", "32 GB", "36 GB", "48 GB", "64 GB", "96 GB", "128 GB", "192 GB", "256 GB", "512 GB", Other]
+ validations:
+ required: true
+ - type: input
+ id: macos
+ attributes:
+ label: macOS version
+ placeholder: macOS 26.1
+ validations:
+ required: true
+ - type: input
+ id: model
+ attributes:
+ label: Mac model
+ placeholder: MacBook Pro 14-inch, Mac mini, Mac Studio
- type: input
- id: hardware
+ id: settings
attributes:
- label: Mac model and macOS version
- placeholder: MacBook Pro M3 Pro, macOS 26.0
+ label: In-game settings and frame rate
+ placeholder: 1440p, High, MetalFX Quality, ~60 fps
- type: textarea
id: notes
attributes:
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 858a556..3b28ee8 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -5,7 +5,9 @@ is the easiest to review. An imperfect PR is still welcome: say what is unfinish
help.
1. **Open an issue first** for anything large, and check closed issues and PRs so work is not
- duplicated. Game reports use the "Game report" template, bugs the "Bug report" one.
+ duplicated. Bugs use the "Bug report" template. To say how a game runs, answer the app's
+ "How did it run?" after you play (or Prefix › Report Your Games… for all of them); without
+ the app, use the "Game report" template.
2. **Read [docs/DEVELOPING.md](docs/DEVELOPING.md)** for what machine you need, how to build,
how to try a change in Steam, and the checks. [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
says where new code goes.
diff --git a/README.md b/README.md
index fd876a2..7250da8 100644
--- a/README.md
+++ b/README.md
@@ -58,6 +58,12 @@ Also running on the same setup: Street Fighter 6, Mortal Kombat 1, The Last of U
<sub>Games with kernel-level anti-cheat do not run.</sub>
+### Compatibility list
+
+Every game tested so far, and the Mac it ran on, is at [bridgeplay.dev/compatibility](https://bridgeplay.dev/compatibility). It combines results a maintainer checked ([`compat/`](compat/)), one-tap reports from players, and CrossOver ratings from AppleGamingWiki for games nobody has tried with Bridgeplay yet.
+
+To add yours: after you play, Bridgeplay asks once per game *How did it run?* One tap posts the result, with your Mac and the game's log, to [Compatibility reports](https://github.com/raymondchins/Bridgeplay/discussions/categories/compatibility-reports). No GitHub account needed, and the log is stripped of your user, computer and Steam account details. **Report Your Games…** in the Prefix menu covers everything you've already played. Without the app, use the [Game report form](https://github.com/raymondchins/Bridgeplay/issues/new?template=game-report.yml).
+
## Install
1. **Download the installer** from [bridgeplay.dev](https://bridgeplay.dev). About 570 MB, with the engine and graphics already inside.
diff --git a/app/Sources/BridgeplayApp/App.swift b/app/Sources/BridgeplayApp/App.swift
index 87fad7c..cc60350 100644
--- a/app/Sources/BridgeplayApp/App.swift
+++ b/app/Sources/BridgeplayApp/App.swift
@@ -33,7 +33,9 @@ struct BridgeplayApp: App {
// look again whenever the user comes back and every few minutes.
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
checkSteamPatch("foreground")
+ PlayReports.shared.scan()
}
+ .task { PlayReports.shared.scan() }
.task {
while !Task.isCancelled {
try? await Task.sleep(for: SteamPatchKeeper.pollInterval)
@@ -157,6 +159,10 @@ struct BridgeplayApp: App {
.keyboardShortcut("r", modifiers: [.command, .shift])
.disabled(prefixes.selectedPrefix == nil)
+ Button("Report Your Games…") { PlayReports.shared.openBulk() }
+ Toggle("Share Play Reports Automatically", isOn: Binding(
+ get: { PlayReports.shared.autoShare }, set: { PlayReports.shared.setAutoShare($0) }))
+
Divider()
Button(PrefixPrompt.backUpButton(selectionTargets)) {
diff --git a/app/Sources/BridgeplayApp/Model/GameReport.swift b/app/Sources/BridgeplayApp/Model/GameReport.swift
new file mode 100644
index 0000000..d4f8d23
--- /dev/null
+++ b/app/Sources/BridgeplayApp/Model/GameReport.swift
@@ -0,0 +1,85 @@
+import Foundation
+import SystemConfiguration
+
+// What a compatibility report says about this Mac and the game's last launch, and the
+// redaction its public log copy goes through. Sent by PlayReports.
+enum GameReport {
+
+ // The options of the Mac chip and memory dropdowns in .github/ISSUE_TEMPLATE/game-report.yml,
+ // so reports from the app and from the form read the same.
+ static let chips = ["M1", "M1 Pro", "M1 Max", "M1 Ultra", "M2", "M2 Pro", "M2 Max", "M2 Ultra",
+ "M3", "M3 Pro", "M3 Max", "M3 Ultra", "M4", "M4 Pro", "M4 Max",
+ "M5", "M5 Pro", "M5 Max"]
+ static let memorySizes = [8, 16, 18, 24, 32, 36, 48, 64, 96, 128, 192, 256, 512]
+ static let backends = ["dxmt", "dxvk", "wined3d", "d3dmetal"]
+
+ struct Machine: Equatable {
+ var chip: String
+ var memoryBytes: UInt64
+ var macOS: String
+ var bridgeplay: String
+ }
+
+ static var thisMac: Machine {
+ Machine(chip: SetupChecks.chipName, memoryBytes: ProcessInfo.processInfo.physicalMemory,
+ macOS: SetupChecks.macOSDisplay,
+ bridgeplay: ProductVersion.build.map { "\(ProductVersion.short) (\($0))" } ?? ProductVersion.short)
+ }
+
+ // "Apple M5 Max" → "M5 Max"; a chip the form doesn't list is "Other".
+ static func chip(_ brand: String) -> String {
+ let name = brand.replacingOccurrences(of: "Apple ", with: "").trimmingCharacters(in: .whitespaces)
+ return chips.contains(name) ? name : "Other"
+ }
+
+ static func memory(_ bytes: UInt64) -> String {
+ let gb = Int((Double(bytes) / 1_073_741_824).rounded())
+ return memorySizes.contains(gb) ? "\(gb) GB" : "Other"
+ }
+
+ // The engine and backend of the most recent launch in bridgeplay-run.log:
+ // runner: build winecx-11.17 (WineCX 11.17 (msync, D3DMetal)) at /…
+ // graphics: backend=d3dmetal (carried over from the last launch)
+ static func lastLaunch(in log: String) -> (engine: String?, backend: String?) {
+ var engine: String?, backend: String?
+ for line in log.split(separator: "\n") {
+ if line.hasPrefix("runner: build "), let open = line.firstIndex(of: "("),
+ let close = line.range(of: ") at ", options: .backwards) {
+ engine = String(line[line.index(after: open)..<close.lowerBound])
+ } else if line.hasPrefix("graphics: backend=") {
+ let value = line.dropFirst("graphics: backend=".count).prefix { !$0.isWhitespace }
+ if backends.contains(String(value)) { backend = String(value) }
+ }
+ }
+ return (engine, backend)
+ }
+
+ // Reports are public. Besides the home folder, run logs carry the Steam account name
+ // and a video token in the passed-through Steam environment, the SteamID64 in Steam API
+ // lines, the macOS user name in lsof output, and external drive names in library paths.
+ static func redacted(_ log: String, home: String = NSHomeDirectory(), user: String = NSUserName(),
+ computerNames: [String] = thisMacNames) -> String {
+ var text = home.isEmpty ? log : log.replacingOccurrences(of: home, with: "~")
+ let rules: [(String, String)] = [
+ (#"(?m)^(SteamUser|SteamAppUser|STEAMVIDEOTOKEN|DSB_TOKEN)=.*$"#, "$1=<redacted>"),
+ (#"\b7656119\d{10}\b"#, "<steamid>"),
+ (#"\[U:1:\d+\]"#, "[U:1:<redacted>]"),
+ (#"[\w.+-]{1,64}@[\w-]{1,63}(\.[\w-]{1,63})+"#, "<email>"),
+ (#"/Volumes/(?!Preboot/|Macintosh HD/)[^/\n:]+"#, "/Volumes/<drive>"),
+ ]
+ for name in [user] + computerNames where name.count >= 3 {
+ text = text.replacingOccurrences(of: #"\b\#(NSRegularExpression.escapedPattern(for: name))\b"#,
+ with: name == user ? "<user>" : "<computer>",
+ options: [.regularExpression, .caseInsensitive])
+ }
+ for (pattern, template) in rules {
+ text = text.replacingOccurrences(of: pattern, with: template, options: .regularExpression)
+ }
+ return text
+ }
+
+ static var thisMacNames: [String] {
+ [SCDynamicStoreCopyComputerName(nil, nil), SCDynamicStoreCopyLocalHostName(nil)]
+ .compactMap { $0 as String? }
+ }
+}
diff --git a/app/Sources/BridgeplayApp/Model/GameSession.swift b/app/Sources/BridgeplayApp/Model/GameSession.swift
new file mode 100644
index 0000000..78bc665
--- /dev/null
+++ b/app/Sources/BridgeplayApp/Model/GameSession.swift
@@ -0,0 +1,96 @@
+import Foundation
+
+// The last game session in a prefix's bridgeplay-run.log. compat_run.sh starts each run
+// with "=== bridgeplay run <date> ===" and ends a game with "=== game exited status=N";
+// the log is only written to while the game runs, so its modification date is the end.
+struct GameSession: Equatable, Sendable {
+ let id: String
+ let started: Date?
+ let ended: Date
+ let exitStatus: Int
+ // Steam's Exit Game or the client quitting: a normal end, whatever the exit status.
+ let stoppedBySteam: Bool
+ // Asked for from the Prefixes page with no finished session in the log.
+ var byHand = false
+
+ var seconds: Int? { started.map { max(0, Int(ended.timeIntervalSince($0))) } }
+
+ static func last(in log: String, modified: Date) -> GameSession? {
+ let headers = ["=== bridgeplay run ", "=== notproton run "]
+ let starts = headers.compactMap { header -> String.Index? in
+ if let found = log.range(of: "\n" + header, options: .backwards) { return log.index(after: found.lowerBound) }
+ return log.hasPrefix(header) ? log.startIndex : nil
+ }
+ guard let start = starts.max() else { return nil }
+ let block = log[start...]
+ let header = block.prefix { $0 != "\n" }
+ guard let exited = block.range(of: "=== game exited status=", options: .backwards) else { return nil }
+ let status = Int(block[exited.upperBound...].prefix { $0.isNumber }) ?? 0
+ let date = header.range(of: " run ").map { header[$0.upperBound...] } ?? ""
+ let started = startDate(String(date.hasSuffix(" ===") ? date.dropLast(4) : date))
+ return GameSession(id: String(header), started: started, ended: modified, exitStatus: status,
+ stoppedBySteam: block.contains("=== termination signal received"))
+ }
+
+ // `date` output, "Wed Oct 21 14:03:22 WIB 2026". Zone abbreviations don't parse reliably,
+ // so the zone is dropped and the time read as local: the game ran on this Mac.
+ static func startDate(_ text: String) -> Date? {
+ var parts = text.split(separator: " ")
+ if parts.count == 6 { parts.remove(at: 4) }
+ guard parts.count == 5 else { return nil }
+ let format = DateFormatter()
+ format.locale = Locale(identifier: "en_US_POSIX")
+ format.timeZone = .current
+ format.dateFormat = "EEE MMM d HH:mm:ss yyyy"
+ return format.date(from: parts.joined(separator: " "))
+ }
+
+ // Wine prints these when a game dies on an exception it didn't handle.
+ static func wineCrashed(_ wineLog: String?) -> Bool {
+ guard let wineLog else { return false }
+ return wineLog.contains("Unhandled exception") || wineLog.contains("Unhandled page fault")
+ }
+
+ func crashed(wineLog: String?) -> Bool {
+ (exitStatus != 0 && !stoppedBySteam) || Self.wineCrashed(wineLog)
+ }
+
+ // What auto-share reports without asking: a crash within three minutes doesn't run, half
+ // an hour that ends cleanly is playable. Anything else waits for the player's answer.
+ func inferredStatus(wineLog: String?) -> ReportStatus? {
+ guard let seconds else { return nil }
+ let crashed = crashed(wineLog: wineLog)
+ if crashed, seconds < 180 { return .borked }
+ if !crashed, seconds >= 1800 { return .silver }
+ return nil
+ }
+
+ // Worth asking about: ended in the last three days, and not opened and closed at once.
+ func worthAsking(now: Date = Date(), wineLog: String?) -> Bool {
+ guard now.timeIntervalSince(ended) < 3 * 86400 else { return false }
+ return (seconds ?? 60) >= 60 || crashed(wineLog: wineLog)
+ }
+
+ static func byHand(now: Date = Date()) -> GameSession {
+ GameSession(id: "by hand", started: nil, ended: now, exitStatus: 0, stoppedBySteam: false, byHand: true)
+ }
+
+ // English on purpose: it goes into the public report.
+ func summary(wineLog: String?) -> String {
+ if byHand { return "Reported from the Prefixes page" }
+ var parts: [String] = []
+ if let seconds { parts.append("Session \(seconds / 60) min") }
+ if stoppedBySteam {
+ parts.append("stopped from Steam")
+ } else {
+ parts.append("exit status \(exitStatus)")
+ }
+ if Self.wineCrashed(wineLog) { parts.append("Wine reported an unhandled exception") }
+ return parts.joined(separator: ", ")
+ }
+}
+
+// Must match STATUS in bridgeplay-web/api/report.mjs.
+enum ReportStatus: String, Codable, Sendable {
+ case platinum, gold, silver, bronze, borked
+}
diff --git a/app/Sources/BridgeplayApp/Model/PlayReports.swift b/app/Sources/BridgeplayApp/Model/PlayReports.swift
new file mode 100644
index 0000000..1bd03a7
--- /dev/null
+++ b/app/Sources/BridgeplayApp/Model/PlayReports.swift
@@ -0,0 +1,430 @@
+import Foundation
+import Observation
+
+// One-tap compatibility reports. After a game session the app asks how it ran; the answer
+// goes to bridgeplay.dev/api/report, which posts it to GitHub Discussions for the player, so
+// no GitHub account is needed. With auto-share on, sessions whose outcome is clear from the
+// log are reported without asking.
+struct ReportPayload: Codable, Equatable, Sendable {
+ enum Source: String, Codable, Sendable { case tap, auto }
+
+ var appid: String
+ var status: ReportStatus
+ var install: String
+ var source: Source
+ var name: String
+ var chip: String
+ var memory: String
+ var macos: String
+ var version: String
+ var engine: String?
+ var backend: String?
+ var session: String
+ var log: String?
+ var wineLog: String?
+
+ // Together under the endpoint's 1 MB cap, newest lines kept.
+ static let logLimit = 550_000
+ static let wineLogLimit = 350_000
+
+ static func make(name: String, appID: String, status: ReportStatus, source: Source, session: GameSession,
+ log: String?, wineLog: String?, machine: GameReport.Machine, install: String) -> ReportPayload {
+ let launch: (engine: String?, backend: String?) = log.map(GameReport.lastLaunch) ?? (nil, nil)
+ var summary = session.summary(wineLog: wineLog)
+ if source == .auto { summary += ". Status inferred from the log" }
+ return ReportPayload(
+ appid: appID, status: status, install: install, source: source, name: name,
+ chip: GameReport.chip(machine.chip), memory: GameReport.memory(machine.memoryBytes),
+ macos: machine.macOS, version: machine.bridgeplay, engine: launch.engine, backend: launch.backend,
+ session: summary,
+ log: log.map { String(GameReport.redacted($0).suffix(logLimit)) },
+ wineLog: wineLog.map { String(GameReport.redacted($0).suffix(wineLogLimit)) })
+ }
+}
+
+// Sends reports, keeping each one on disk until the endpoint takes it, so a report made
+// offline goes out on a later scan.
+struct ReportSender: Sendable {
+
+ enum Outcome: Equatable { case sent, retryLater, dropped }
+
+ var endpoint: URL
+ var queue: URL
+ var session: URLSession = .shared
+ var retryAfter: TimeInterval = 15 * 60
+
+ static let defaultEndpoint = URL(string: "https://bridgeplay.dev/api/report")!
+
+ // `defaults write <bundle id> ReportEndpoint <url>` points a build at a test server.
+ static var standard: ReportSender {
+ let custom = UserDefaults.standard.string(forKey: "ReportEndpoint").flatMap(URL.init(string:))
+ return ReportSender(endpoint: custom ?? defaultEndpoint, queue: SupportPaths.support.appending(path: "reports-pending"))
+ }
+
+ func submit(_ payload: ReportPayload) async -> Outcome {
+ let file = queue.appending(path: "\(payload.appid)-\(UUID().uuidString).json")
+ do {
+ try FileManager.default.createDirectory(at: queue, withIntermediateDirectories: true)
+ try JSONEncoder().encode(payload).write(to: file, options: .atomic)
+ } catch {
+ AppLog.note("play report: could not queue the report: \(error.localizedDescription)")
+ return await post(try? JSONEncoder().encode(payload))
+ }
+ return await send(file)
+ }
+
+ // Queued reports whose last try is older than retryAfter.
+ func retryPending(now: Date = Date()) async {
+ let files = (try? FileManager.default.contentsOfDirectory(
+ at: queue, includingPropertiesForKeys: [.contentModificationDateKey])) ?? []
+ for file in files where file.pathExtension == "json" {
+ let tried = (try? file.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate
+ if let tried, now.timeIntervalSince(tried) < retryAfter { continue }
+ _ = await send(file)
+ }
+ }
+
+ private func send(_ file: URL) async -> Outcome {
+ let outcome = await post(try? Data(contentsOf: file))
+ switch outcome {
+ case .sent, .dropped:
+ try? FileManager.default.removeItem(at: file)
+ case .retryLater:
+ try? FileManager.default.setAttributes([.modificationDate: Date()], ofItemAtPath: file.path(percentEncoded: false))
+ }
+ return outcome
+ }
+
+ private func post(_ body: Data?) async -> Outcome {
+ guard let body else { return .dropped }
+ var request = URLRequest(url: endpoint, timeoutInterval: 30)
+ request.httpMethod = "POST"
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.httpBody = body
+ do {
+ let (_, response) = try await session.data(for: request)
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ switch code {
+ case 200..<300: return .sent
+ case 408, 429, 500...: return .retryLater
+ default:
+ AppLog.note("play report: the endpoint refused the report (HTTP \(code))")
+ return .dropped
+ }
+ } catch {
+ return .retryLater
+ }
+ }
+}
+
+@MainActor
+@Observable
+final class PlayReports {
+
+ static let shared = PlayReports()
+
+ struct Nudge: Equatable, Identifiable {
+ let prefix: WinePrefix
+ let session: GameSession
+ var id: String { PlayReports.key(prefix, session) }
+ }
+
+ // What the consent sheet is for: one answer, several from Report Your Games…, or
+ // turning auto-share on.
+ enum ConsentRequest: Equatable { case answer(ReportStatus), bulk([String], ReportStatus), autoShare }
+
+ private(set) var nudges: [Nudge] = []
+ var consentRequest: ConsentRequest?
+
+ var nudge: Nudge? { nudges.first }
+
+ // Report Your Games…: nil while the sheet is closed.
+ private(set) var bulk: [Found]?
+ private(set) var bulkLoading = false
+
+ // AppIDs a maintainer verified on a Mac with this Mac's chip (VerifiedGames).
+ var verifiedHere: Set<String> = []
+
+ // A few seconds of thanks after an answer. Sending happens in the background, and a
+ // report made offline goes out later, so it says the report is on its way.
+ private(set) var thanking = false
+ private var thanksGeneration = 0
+
+ private let defaults: UserDefaults
+ private let sender: @Sendable () -> ReportSender
+ private let version: String
+ private var scanning = false
+
+ private static let consentKey = "PlayReportsConsent"
+ private static let autoShareKey = "PlayReportsAutoShare"
+ private static let handledKey = "PlayReportsHandled"
+ private static let installKey = "PlayReportsInstallID"
+ private static let askedKey = "PlayReportsAskedVersion" // appID: Bridgeplay version
+ private static let answerKey = "PlayReportsLastAnswer" // appID: ReportStatus
+ private static let neverKey = "PlayReportsNeverAsk" // [appID]
+
+ init(defaults: UserDefaults = .standard, version: String = ProductVersion.short,
+ sender: @escaping @Sendable () -> ReportSender = { .standard }) {
+ self.defaults = defaults
+ self.version = version
+ self.sender = sender
+ autoShare = defaults.bool(forKey: Self.autoShareKey) && defaults.bool(forKey: Self.consentKey)
+ }
+
+ private(set) var autoShare: Bool
+
+ var hasConsent: Bool { defaults.bool(forKey: Self.consentKey) }
+
+ // Random and only used by the endpoint for rate limiting; it is not in the report.
+ var installID: String {
+ if let id = defaults.string(forKey: Self.installKey) { return id }
+ let id = UUID().uuidString
+ defaults.set(id, forKey: Self.installKey)
+ return id
+ }
+
+ nonisolated static func key(_ prefix: WinePrefix, _ session: GameSession) -> String {
+ "\(prefix.appID)|\(session.id)"
+ }
+
+ func isHandled(_ key: String) -> Bool {
+ defaults.stringArray(forKey: Self.handledKey)?.contains(key) ?? false
+ }
+
+ private func markHandled(_ key: String) {
+ var handled = defaults.stringArray(forKey: Self.handledKey) ?? []
+ handled.removeAll { $0 == key }
+ handled.append(key)
+ defaults.set(Array(handled.suffix(300)), forKey: Self.handledKey)
+ }
+
+ // A game is asked about (or auto-shared) once per Bridgeplay version, never after "Don't
+ // Ask About This Game", and once more in the same version if it crashed after the last
+ // answer was Smooth.
+ func shouldAsk(_ item: Found) -> Bool {
+ let appID = item.prefix.appID
+ if verifiedHere.contains(appID) { return false }
+ if (defaults.stringArray(forKey: Self.neverKey) ?? []).contains(appID) { return false }
+ if defaults.dictionary(forKey: Self.askedKey)?[appID] as? String != version { return true }
+ return lastAnswer(appID) == .platinum && item.session.crashed(wineLog: item.wineLog)
+ }
+
+ func lastAnswer(_ appID: String) -> ReportStatus? {
+ (defaults.dictionary(forKey: Self.answerKey)?[appID] as? String).flatMap(ReportStatus.init(rawValue:))
+ }
+
+ private func recordAsked(_ appID: String, answer: ReportStatus?) {
+ var asked = defaults.dictionary(forKey: Self.askedKey) ?? [:]
+ asked[appID] = version
+ defaults.set(asked, forKey: Self.askedKey)
+ guard let answer else { return }
+ var answers = defaults.dictionary(forKey: Self.answerKey) ?? [:]
+ answers[appID] = answer.rawValue
+ defaults.set(answers, forKey: Self.answerKey)
+ }
+
+ func setAutoShare(_ on: Bool) {
+ if on, !hasConsent {
+ consentRequest = .autoShare
+ return
+ }
+ autoShare = on
+ defaults.set(on, forKey: Self.autoShareKey)
+ }
+
+ // The player picked an answer on the card; the first one asks for consent.
+ func answer(_ status: ReportStatus) {
+ guard let nudge else { return }
+ guard hasConsent else {
+ consentRequest = .answer(status)
+ return
+ }
+ advance(past: nudge)
+ recordAsked(nudge.prefix.appID, answer: status)
+ send(nudge, status: status, source: .tap)
+ thanksGeneration += 1
+ let generation = thanksGeneration
+ thanking = true
+ Task {
+ try? await Task.sleep(for: .seconds(3))
+ if generation == thanksGeneration { thanking = false }
+ }
+ }
+
+ func consent(alsoAutoShare: Bool) {
+ defaults.set(true, forKey: Self.consentKey)
+ let request = consentRequest
+ consentRequest = nil
+ if alsoAutoShare || request == .autoShare { setAutoShare(true) }
+ if case .answer(let status) = request { answer(status) }
+ if case .bulk(let appIDs, let status) = request { answerBulk(appIDs, status) }
+ }
+
+ // Games for Report Your Games…: every game with a finished session in its log, however
+ // old, minus those answered for this version, Don't Ask games and verified ones.
+ func bulkCandidates(_ found: [Found]) -> [Found] {
+ let never = defaults.stringArray(forKey: Self.neverKey) ?? []
+ let asked = defaults.dictionary(forKey: Self.askedKey) ?? [:]
+ return found.filter { item in
+ let appID = item.prefix.appID
+ return !never.contains(appID) && asked[appID] as? String != version && !verifiedHere.contains(appID)
+ }
+ .sorted { $0.session.ended > $1.session.ended }
+ }
+
+ func openBulk() {
+ bulk = []
+ bulkLoading = true
+ Task {
+ let found = await Task.detached {
+ PlayReports.findSessions(prefixes: PrefixStore.all(), maxAge: nil, onlyWorthAsking: false)
+ }.value
+ if bulk != nil { showBulk(found) }
+ }
+ }
+
+ func showBulk(_ found: [Found]) {
+ bulk = bulkCandidates(found)
+ bulkLoading = false
+ }
+
+ func closeBulk() { bulk = nil }
+
+ // One answer for several games from the sheet; the first send asks for consent.
+ func answerBulk(_ appIDs: [String], _ status: ReportStatus) {
+ guard let list = bulk else { return }
+ let items = list.filter { appIDs.contains($0.prefix.appID) }
+ guard !items.isEmpty else { return }
+ guard hasConsent else {
+ consentRequest = .bulk(appIDs, status)
+ return
+ }
+ bulk = list.filter { !appIDs.contains($0.prefix.appID) }
+ for item in items {
+ recordAsked(item.prefix.appID, answer: status)
+ markHandled(Self.key(item.prefix, item.session))
+ nudges.removeAll { $0.prefix.appID == item.prefix.appID }
+ }
+ submitAll(items.map { ($0, status) }, source: .tap)
+ }
+
+ // Report This Game…: ask about the game now, from its last session if the log has one.
+ func ask(about prefix: WinePrefix) {
+ Task {
+ let found = await Task.detached { () -> GameSession? in
+ let url = PrefixLog.launch.url(for: prefix)
+ guard let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate,
+ let log = try? String(contentsOf: url, encoding: .utf8) else { return nil }
+ return GameSession.last(in: log, modified: modified)
+ }.value
+ nudges.removeAll { $0.prefix.id == prefix.id }
+ nudges.insert(Nudge(prefix: prefix, session: found ?? .byHand()), at: 0)
+ }
+ }
+
+ func dismiss() {
+ guard let nudge else { return }
+ advance(past: nudge)
+ recordAsked(nudge.prefix.appID, answer: nil)
+ }
+
+ // "Don't Ask About This Game". Report This Game… still works for it.
+ func neverAsk() {
+ guard let nudge else { return }
+ let appID = nudge.prefix.appID
+ var never = defaults.stringArray(forKey: Self.neverKey) ?? []
+ if !never.contains(appID) { never.append(appID) }
+ defaults.set(never, forKey: Self.neverKey)
+ advance(past: nudge)
+ nudges.removeAll { $0.prefix.appID == appID }
+ }
+
+ private func advance(past nudge: Nudge) {
+ markHandled(nudge.id)
+ nudges.removeAll { $0.id == nudge.id }
+ }
+
+ struct Found: Sendable {
+ let prefix: WinePrefix
+ let session: GameSession
+ let log: String
+ let wineLog: String?
+ }
+
+ // Reads every prefix's last session. Run off the main thread.
+ nonisolated static func findSessions(prefixes: [WinePrefix], now: Date = Date(),
+ maxAge: TimeInterval? = 3 * 86400, onlyWorthAsking: Bool = true) -> [Found] {
+ prefixes.compactMap { prefix in
+ let url = PrefixLog.launch.url(for: prefix)
+ guard let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate,
+ maxAge.map({ now.timeIntervalSince(modified) < $0 }) ?? true,
+ let log = try? String(contentsOf: url, encoding: .utf8),
+ let session = GameSession.last(in: log, modified: modified) else { return nil }
+ let wineLog = try? String(contentsOf: PrefixLog.wine.url(for: prefix), encoding: .utf8)
+ guard !onlyWorthAsking || session.worthAsking(now: now, wineLog: wineLog) else { return nil }
+ return Found(prefix: prefix, session: session, log: log, wineLog: wineLog)
+ }
+ .sorted { $0.session.ended > $1.session.ended }
+ }
+
+ // On launch and whenever the app comes forward. Never blocks the UI.
+ func scan() {
+ guard !scanning else { return }
+ scanning = true
+ let sender = sender()
+ Task {
+ defer { scanning = false }
+ let chip = GameReport.chip(GameReport.thisMac.chip)
+ verifiedHere = await Task.detached { await VerifiedGames.load(chip: chip) }.value
+ let found = await Task.detached { PlayReports.findSessions(prefixes: PrefixStore.all()) }.value
+ handle(found)
+ await sender.retryPending()
+ }
+ }
+
+ func handle(_ found: [Found]) {
+ for item in found {
+ let key = Self.key(item.prefix, item.session)
+ guard !isHandled(key), !nudges.contains(where: { $0.id == key }), shouldAsk(item) else { continue }
+ if autoShare, let status = item.session.inferredStatus(wineLog: item.wineLog) {
+ markHandled(key)
+ recordAsked(item.prefix.appID, answer: status)
+ submit(item, status: status, source: .auto)
+ } else {
+ // A newer session of the same game replaces the older question.
+ nudges.removeAll { $0.prefix.id == item.prefix.id }
+ nudges.append(Nudge(prefix: item.prefix, session: item.session))
+ }
+ }
+ }
+
+ private func send(_ nudge: Nudge, status: ReportStatus, source: ReportPayload.Source) {
+ let prefix = nudge.prefix, session = nudge.session
+ Task {
+ let logs = await Task.detached {
+ (try? String(contentsOf: PrefixLog.launch.url(for: prefix), encoding: .utf8),
+ try? String(contentsOf: PrefixLog.wine.url(for: prefix), encoding: .utf8))
+ }.value
+ submit(Found(prefix: prefix, session: session, log: logs.0 ?? "", wineLog: logs.1), status: status, source: source)
+ }
+ }
+
+ private func submit(_ item: Found, status: ReportStatus, source: ReportPayload.Source) {
+ submitAll([(item, status)], source: source)
+ }
+
+ // Redacting a large log takes a moment, so payloads are built off the main thread, and
+ // sent one after another so a batch stays within the endpoint's rate limits.
+ private func submitAll(_ items: [(Found, ReportStatus)], source: ReportPayload.Source) {
+ let sender = sender(), machine = GameReport.thisMac, install = installID
+ Task.detached {
+ for (item, status) in items {
+ let payload = ReportPayload.make(
+ name: item.prefix.title, appID: item.prefix.appID, status: status, source: source, session: item.session,
+ log: item.log.isEmpty ? nil : item.log, wineLog: item.wineLog, machine: machine, install: install)
+ let outcome = await sender.submit(payload)
+ AppLog.note("play report: \(payload.appid) \(payload.status.rawValue) (\(payload.source.rawValue)): \(outcome)")
+ }
+ }
+ }
+}
diff --git a/app/Sources/BridgeplayApp/Model/VerifiedGames.swift b/app/Sources/BridgeplayApp/Model/VerifiedGames.swift
new file mode 100644
index 0000000..7ec3381
--- /dev/null
+++ b/app/Sources/BridgeplayApp/Model/VerifiedGames.swift
@@ -0,0 +1,55 @@
+import Foundation
+
+// Games a maintainer already checked (compat/games.json in the Bridgeplay repository) on a
+// Mac with this Mac's chip: the app doesn't ask about those. The list is cached on disk and
+// fetched at most once a day; without it (offline, first launch) the app asks as before.
+enum VerifiedGames {
+
+ static let source = URL(string: "https://raw.githubusercontent.com/raymondchins/Bridgeplay/main/compat/games.json")!
+ static var cache: URL { SupportPaths.caches.appending(path: "compat-games.json") }
+
+ // "M5 Max", "M2", "M3 Ultra" out of free text such as "M5 Max · macOS 27".
+ static func chipFamilies(in text: String) -> Set<String> {
+ let pattern = /\bM\d+(?: (?:Pro|Max|Ultra))?\b/
+ return Set(text.matches(of: pattern).map { String($0.output) })
+ }
+
+ // AppIDs whose maintainer result (any status but untested) was recorded on `chip`.
+ static func verified(on chip: String, in data: Data) -> Set<String> {
+ guard chip != "Other",
+ let games = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { return [] }
+ var found = Set<String>()
+ for game in games {
+ guard let status = game["status"] as? String, status != "untested",
+ let appID = (game["appid"] as? Int).map(String.init) ?? game["appid"] as? String else { continue }
+ var texts = [game["tested_on"] as? String]
+ for report in game["reports"] as? [[String: Any]] ?? [] {
+ texts.append(report["chip"] as? String)
+ texts.append(report["device"] as? String)
+ }
+ if texts.compactMap({ $0 }).contains(where: { chipFamilies(in: $0).contains(chip) }) { found.insert(appID) }
+ }
+ return found
+ }
+
+ // The cached list, refreshed when it is a day old. Never throws; run off the main thread.
+ static func load(chip: String, cache: URL = cache, session: URLSession = .shared,
+ now: Date = Date()) async -> Set<String> {
+ let modified = (try? FileManager.default.attributesOfItem(atPath: cache.path(percentEncoded: false)))?[.modificationDate] as? Date
+ if modified.map({ now.timeIntervalSince($0) >= 86400 }) ?? true {
+ var request = URLRequest(url: source, timeoutInterval: 20)
+ request.cachePolicy = .reloadIgnoringLocalCacheData
+ if let (data, response) = try? await session.data(for: request),
+ (response as? HTTPURLResponse)?.statusCode == 200,
+ (try? JSONSerialization.jsonObject(with: data)) is [Any] {
+ try? FileManager.default.createDirectory(at: cache.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try? data.write(to: cache, options: .atomic)
+ } else if modified != nil {
+ // Failed: keep the old copy for another day rather than retry on every scan.
+ try? FileManager.default.setAttributes([.modificationDate: now], ofItemAtPath: cache.path(percentEncoded: false))
+ }
+ }
+ guard let data = try? Data(contentsOf: cache) else { return [] }
+ return verified(on: chip, in: data)
+ }
+}
diff --git a/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings b/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings
index 8e2345f..ab46264 100644
--- a/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings
+++ b/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings
@@ -1660,6 +1660,22 @@
}
}
},
+ "Automatic reports are sent only when the log makes the result clear. You can turn them off in the Prefix menu." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "I report automatici vengono inviati solo quando il log rende chiaro il risultato. Puoi disattivarli nel menu Prefisso."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "只有在日志能明确说明结果时才会自动发送报告。你可以在“前缀”菜单中关闭此功能。"
+ }
+ }
+ }
+ },
"Back" : {
"localizations" : {
"it" : {
@@ -3666,6 +3682,22 @@
}
}
},
+ "Didn't run" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Non partiva"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "无法运行"
+ }
+ }
+ }
+ },
"Disable hidraw" : {
"localizations" : {
"it" : {
@@ -3698,6 +3730,22 @@
}
}
},
+ "Don't Ask About This Game" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Non chiedere più per questo gioco"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "不再询问此游戏"
+ }
+ }
+ }
+ },
"Done" : {
"localizations" : {
"it" : {
@@ -4338,6 +4386,22 @@
}
}
},
+ "Has issues" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Con problemi"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "有问题"
+ }
+ }
+ }
+ },
"Hides raw HID devices from the game, so pads only show up through SDL. Try it if a game sees one controller twice or ignores yours." : {
"localizations" : {
"it" : {
@@ -4370,6 +4434,22 @@
}
}
},
+ "How did each game run? Games you already answered for this version of Bridgeplay, games you asked not to be asked about, and games already verified on a Mac like yours are left out." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Com'è andato ogni gioco? Sono esclusi i giochi a cui hai già risposto per questa versione di Bridgeplay, quelli per cui hai chiesto di non essere più interpellato e quelli già verificati su un Mac come il tuo."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "每个游戏运行得怎么样?已在此 Bridgeplay 版本中回答过的游戏、你要求不再询问的游戏,以及已在与你相同的 Mac 上验证过的游戏不会列出。"
+ }
+ }
+ }
+ },
"How finely motion is tracked between frames. Performance is the lightest, Quality the most precise, Balanced in between." : {
"localizations" : {
"it" : {
@@ -4866,6 +4946,38 @@
}
}
},
+ "Last played %@" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ultima partita %@"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "上次游玩:%@"
+ }
+ }
+ }
+ },
+ "Last played %@, for %@" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ultima partita %1$@, per %2$@"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "上次游玩:%1$@,时长 %2$@"
+ }
+ }
+ }
+ },
"Last used" : {
"localizations" : {
"it" : {
@@ -5570,6 +5682,22 @@
}
}
},
+ "Nothing left to report." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Non c'è altro da segnalare."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "没有需要报告的游戏了。"
+ }
+ }
+ }
+ },
"OK" : {
"localizations" : {
"it" : {
@@ -6818,6 +6946,70 @@
}
}
},
+ "Report This Game…" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Segnala questo gioco…"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "报告此游戏…"
+ }
+ }
+ }
+ },
+ "Report Your Games" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Segnala i tuoi giochi"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "报告你的游戏"
+ }
+ }
+ }
+ },
+ "Report Your Games…" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Segnala i tuoi giochi…"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "报告你的游戏…"
+ }
+ }
+ }
+ },
+ "Reports are posted publicly in Bridgeplay's GitHub Discussions and counted on the compatibility list. Each one has the game, how it ran, your Mac's chip and memory, the macOS and Bridgeplay versions, the engine and backend, and the game's logs. Your home folder, user and computer names, Steam account name, Steam ID and email addresses are removed from the logs first. You don't need a GitHub account." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "I report vengono pubblicati nelle GitHub Discussions di Bridgeplay e contati nell'elenco di compatibilità. Ognuno contiene il gioco, come è andato, chip e memoria del Mac, le versioni di macOS e Bridgeplay, motore e backend, e i log del gioco. Prima dell'invio vengono rimossi dai log la cartella Inizio, i nomi utente e computer, il nome dell'account Steam, lo Steam ID e gli indirizzi email. Non serve un account GitHub."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "报告会公开发布到 Bridgeplay 的 GitHub Discussions,并计入兼容性列表。每份报告包含游戏、运行情况、Mac 的芯片和内存、macOS 和 Bridgeplay 版本、引擎和后端,以及游戏日志。发送前会从日志中移除你的个人文件夹、用户名和电脑名称、Steam 账户名称、Steam ID 和电子邮件地址。不需要 GitHub 账户。"
+ }
+ }
+ }
+ },
"Reset" : {
"localizations" : {
"it" : {
@@ -7314,6 +7506,70 @@
}
}
},
+ "Share" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Condividi"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "分享"
+ }
+ }
+ }
+ },
+ "Share Play Reports Automatically" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Condividi automaticamente i report di gioco"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "自动分享游戏报告"
+ }
+ }
+ }
+ },
+ "Share automatically after each game" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Condividi automaticamente dopo ogni partita"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "每次游戏后自动分享"
+ }
+ }
+ }
+ },
+ "Share how your games run?" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Condividere come girano i tuoi giochi?"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "分享你的游戏运行情况?"
+ }
+ }
+ }
+ },
"Sharper on Retina displays, but games run slower." : {
"localizations" : {
"it" : {
@@ -7554,6 +7810,38 @@
}
}
},
+ "Smooth" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Fluido"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "流畅"
+ }
+ }
+ }
+ },
+ "Smooth for All Remaining" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Fluido per tutti i rimanenti"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "其余全部为流畅"
+ }
+ }
+ }
+ },
"Some files stayed in the old folders" : {
"localizations" : {
"it" : {
@@ -8325,6 +8613,22 @@
}
}
},
+ "Thanks! Your report is on its way." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Grazie! Il tuo report è in arrivo."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "谢谢!你的报告正在发送。"
+ }
+ }
+ }
+ },
"The %@" : {
"localizations" : {
"it" : {
@@ -9659,6 +9963,38 @@
}
}
},
+ "You played %@ for %@. How did it run?" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Hai giocato a %1$@ per %2$@. Com'è andato?"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "你玩了 %1$@ %2$@。运行得怎么样?"
+ }
+ }
+ }
+ },
+ "You played %@. How did it run?" : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Hai giocato a %@. Com'è andato?"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "你玩了 %@。运行得怎么样?"
+ }
+ }
+ }
+ },
"You will not lose saves by using this tool." : {
"localizations" : {
"it" : {
diff --git a/app/Sources/BridgeplayApp/Views/PlayReportCard.swift b/app/Sources/BridgeplayApp/Views/PlayReportCard.swift
new file mode 100644
index 0000000..70b5f31
--- /dev/null
+++ b/app/Sources/BridgeplayApp/Views/PlayReportCard.swift
@@ -0,0 +1,181 @@
+import SwiftUI
+
+// Asks how the last game session ran. One tap on an answer sends the report.
+struct PlayReportCard: View {
+ let nudge: PlayReports.Nudge
+ private var reports: PlayReports { .shared }
+
+ var body: some View {
+ HStack(alignment: .center, spacing: 12) {
+ Image(systemName: "gamecontroller.fill")
+ .foregroundStyle(BP.blue)
+ .accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: 4) {
+ Text(question).font(BP.sans(13, .semibold))
+ Toggle("Share automatically after each game", isOn: Binding(
+ get: { reports.autoShare }, set: { reports.setAutoShare($0) }))
+ .toggleStyle(.checkbox)
+ .font(BP.sans(12))
+ .foregroundStyle(BP.fg2)
+ }
+ Spacer(minLength: 12)
+ Button("Smooth") { reports.answer(.platinum) }
+ .buttonStyle(.borderedProminent)
+ Button("Has issues") { reports.answer(.bronze) }
+ Button("Didn't run") { reports.answer(.borked) }
+ // A click is Not Now; the menu also offers never asking about this game.
+ Menu {
+ Button("Not Now") { reports.dismiss() }
+ Button("Don't Ask About This Game") { reports.neverAsk() }
+ Divider()
+ Button("Report Your Games…") { reports.openBulk() }
+ } label: {
+ Image(systemName: "xmark")
+ } primaryAction: {
+ reports.dismiss()
+ }
+ .menuStyle(.borderlessButton)
+ .menuIndicator(.visible)
+ .fixedSize()
+ .help("Not Now")
+ .accessibilityLabel("Not Now")
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 10)
+ .background(.bar)
+ .overlay(alignment: .top) { Divider() }
+ }
+
+ private var question: String {
+ let name = nudge.prefix.title
+ guard let seconds = nudge.session.seconds, seconds >= 60 else {
+ return String(localized: "You played \(name). How did it run?")
+ }
+ let time = Duration.seconds(seconds).formatted(.units(allowed: [.hours, .minutes], width: .abbreviated))
+ return String(localized: "You played \(name) for \(time). How did it run?")
+ }
+}
+
+struct PlayReportThanks: View {
+ var body: some View {
+ HStack(spacing: 8) {
+ Image(systemName: "checkmark.circle.fill")
+ .foregroundStyle(BP.green)
+ .accessibilityHidden(true)
+ Text("Thanks! Your report is on its way.")
+ .font(BP.sans(13, .semibold))
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 10)
+ .background(.bar)
+ .overlay(alignment: .top) { Divider() }
+ .accessibilityElement(children: .combine)
+ }
+}
+
+// Shown once, before the first report leaves the Mac.
+struct PlayReportConsent: View {
+ @State private var alsoAutoShare = false
+ private var reports: PlayReports { .shared }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 14) {
+ Text("Share how your games run?")
+ .font(BP.sans(17, .semibold))
+ Text("Reports are posted publicly in Bridgeplay's GitHub Discussions and counted on the compatibility list. Each one has the game, how it ran, your Mac's chip and memory, the macOS and Bridgeplay versions, the engine and backend, and the game's logs. Your home folder, user and computer names, Steam account name, Steam ID and email addresses are removed from the logs first. You don't need a GitHub account.")
+ .foregroundStyle(BP.fg2)
+ .fixedSize(horizontal: false, vertical: true)
+ if reports.consentRequest != .autoShare {
+ Toggle("Share automatically after each game", isOn: $alsoAutoShare)
+ .toggleStyle(.checkbox)
+ }
+ Text("Automatic reports are sent only when the log makes the result clear. You can turn them off in the Prefix menu.")
+ .font(BP.sans(12))
+ .foregroundStyle(BP.fg3)
+ .fixedSize(horizontal: false, vertical: true)
+ HStack {
+ Spacer()
+ Button("Cancel", role: .cancel) { reports.consentRequest = nil }
+ .keyboardShortcut(.cancelAction)
+ Button("Share") { reports.consent(alsoAutoShare: alsoAutoShare) }
+ .keyboardShortcut(.defaultAction)
+ }
+ }
+ .padding(22)
+ .frame(width: 460)
+ }
+}
+
+// Report Your Games…: one row per game with a session in its log, newest first.
+struct BulkReportSheet: View {
+ private var reports: PlayReports { .shared }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ Text("Report Your Games")
+ .font(BP.sans(17, .semibold))
+ Text("How did each game run? Games you already answered for this version of Bridgeplay, games you asked not to be asked about, and games already verified on a Mac like yours are left out.")
+ .foregroundStyle(BP.fg2)
+ .fixedSize(horizontal: false, vertical: true)
+ let list = reports.bulk ?? []
+ if reports.bulkLoading {
+ ProgressView().frame(maxWidth: .infinity, minHeight: 120)
+ } else if list.isEmpty {
+ Text("Nothing left to report.")
+ .foregroundStyle(BP.fg3)
+ .frame(maxWidth: .infinity, minHeight: 120)
+ } else {
+ List(list, id: \.prefix.id) { item in
+ BulkReportRow(item: item)
+ }
+ .frame(minHeight: 260)
+ }
+ HStack {
+ if !list.isEmpty {
+ Button("Smooth for All Remaining") { reports.answerBulk(list.map(\.prefix.appID), .platinum) }
+ }
+ Spacer()
+ Button("Done") { reports.closeBulk() }
+ .keyboardShortcut(.defaultAction)
+ }
+ }
+ .padding(22)
+ .frame(width: 640, height: 520)
+ .sheet(isPresented: Binding(get: { reports.consentRequest != nil },
+ set: { if !$0 { reports.consentRequest = nil } })) {
+ PlayReportConsent()
+ }
+ }
+}
+
+private struct BulkReportRow: View {
+ let item: PlayReports.Found
+ private var reports: PlayReports { .shared }
+
+ var body: some View {
+ HStack(spacing: 10) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(item.prefix.title).font(BP.sans(13, .semibold)).lineLimit(1)
+ Text(detail).font(BP.sans(11)).foregroundStyle(BP.fg3).lineLimit(1)
+ }
+ Spacer(minLength: 8)
+ Button("Smooth") { send(.platinum) }
+ Button("Has issues") { send(.bronze) }
+ Button("Didn't run") { send(.borked) }
+ }
+ .controlSize(.small)
+ .padding(.vertical, 3)
+ }
+
+ private func send(_ status: ReportStatus) { reports.answerBulk([item.prefix.appID], status) }
+
+ private var detail: String {
+ let when = item.session.ended.formatted(.relative(presentation: .named))
+ guard let seconds = item.session.seconds, seconds >= 60 else {
+ return String(localized: "Last played \(when)")
+ }
+ let time = Duration.seconds(seconds).formatted(.units(allowed: [.hours, .minutes], width: .abbreviated))
+ return String(localized: "Last played \(when), for \(time)")
+ }
+}
diff --git a/app/Sources/BridgeplayApp/Views/PrefixesView.swift b/app/Sources/BridgeplayApp/Views/PrefixesView.swift
index 19c2e33..d55fce5 100644
--- a/app/Sources/BridgeplayApp/Views/PrefixesView.swift
+++ b/app/Sources/BridgeplayApp/Views/PrefixesView.swift
@@ -349,7 +349,9 @@ struct PrefixesView: View {
.disabled(!model.hasLog(log, for: prefix))
}
}
+ Button("Report This Game…") { PlayReports.shared.ask(about: prefix) }
}
+ Button("Report Your Games…") { PlayReports.shared.openBulk() }
if !targets.isEmpty {
Divider()
Button(PrefixPrompt.backUpButton(targets)) {
diff --git a/app/Sources/BridgeplayApp/Views/RootView.swift b/app/Sources/BridgeplayApp/Views/RootView.swift
index 1a53332..3077dda 100644
--- a/app/Sources/BridgeplayApp/Views/RootView.swift
+++ b/app/Sources/BridgeplayApp/Views/RootView.swift
@@ -87,10 +87,26 @@ struct RootView: View {
PatchBanner(banner: banner)
}
}
+ .safeAreaInset(edge: .bottom, spacing: 0) {
+ if let nudge = PlayReports.shared.nudge {
+ PlayReportCard(nudge: nudge)
+ } else if PlayReports.shared.thanking {
+ PlayReportThanks()
+ }
+ }
.scrollContentBackground(.hidden)
.background(BP.bg)
.toolbarBackground(BP.bg, for: .windowToolbar)
}
+ // While Report Your Games… is open, it presents the consent sheet itself.
+ .sheet(isPresented: Binding(get: { PlayReports.shared.consentRequest != nil && PlayReports.shared.bulk == nil },
+ set: { if !$0 { PlayReports.shared.consentRequest = nil } })) {
+ PlayReportConsent()
+ }
+ .sheet(isPresented: Binding(get: { PlayReports.shared.bulk != nil },
+ set: { if !$0 { PlayReports.shared.closeBulk() } })) {
+ BulkReportSheet()
+ }
.font(BP.sans(13))
.tint(BP.blue)
.preferredColorScheme(.dark)
diff --git a/app/Tests/BridgeplayAppTests/GameReportTests.swift b/app/Tests/BridgeplayAppTests/GameReportTests.swift
new file mode 100644
index 0000000..739828d
--- /dev/null
+++ b/app/Tests/BridgeplayAppTests/GameReportTests.swift
@@ -0,0 +1,66 @@
+import Foundation
+import Testing
+
+@testable import BridgeplayApp
+
+@Suite("Reports describe the Mac and the last launch")
+struct GameReportTests {
+
+ private let log = """
+ runner: build winecx-11.15 (WineCX 11.15 (msync, D3DMetal)) at /Users/tester/Library/Application Support/bridgeplay/runners/a
+ graphics: backend=dxmt
+ === launching (run): /Users/tester/Library/Application Support/bridgeplay/runners/a/wine
+ runner: build winecx-11.17 (WineCX 11.17 (msync, D3DMetal)) at /Users/tester/Library/Application Support/bridgeplay/runners/b
+ graphics: backend=d3dmetal (carried over from the last launch)
+ """
+
+ @Test("Chip and memory map onto the form's options")
+ func machineFields() {
+ #expect(GameReport.chip("Apple M5 Max") == "M5 Max")
+ #expect(GameReport.chip("Apple M9") == "Other")
+ #expect(GameReport.memory(64 * 1_073_741_824) == "64 GB")
+ #expect(GameReport.memory(20 * 1_073_741_824) == "Other")
+ }
+
+ @Test("The last launch in the log wins")
+ func lastLaunch() {
+ let launch = GameReport.lastLaunch(in: log)
+ #expect(launch.engine == "WineCX 11.17 (msync, D3DMetal)")
+ #expect(launch.backend == "d3dmetal")
+ }
+
+ @Test("The copied log hides the home folder")
+ func redaction() {
+ let text = GameReport.redacted(log, home: "/Users/tester")
+ #expect(!text.contains("/Users/tester"))
+ #expect(text.contains("~/Library/Application Support/bridgeplay"))
+ }
+
+ @Test("The copy hides Steam accounts, IDs, user, computer and drive names")
+ func privateDetails() {
+ let raw = """
+ SteamUser=player_one
+ SteamAppUser=player_one
+ STEAMVIDEOTOKEN=1002
+ SteamAppId=1245620
+ SteamInternal_SetMinidumpSteamID: Caching Steam ID: 76561198012345678 [API loaded no]
+ account [U:1:52079950] signed in
+ bash 76349 tester 8w REG 1,18 0 57027247 /Users/tester/Library/x.lock
+ STEAM_COMPAT_LIBRARY_PATHS=/Volumes/Tester's T7/SteamLibrary:/Volumes/Preboot/x
+ host Testers-MacBook-Pro wrote to [email protected]
+ C:/users/crossover/AppData
+ """
+ let text = GameReport.redacted(raw, home: "/Users/tester", user: "tester",
+ computerNames: ["Tester's MacBook Pro", "Testers-MacBook-Pro"])
+ for secret in ["player_one", "1002", "76561198012345678", "52079950", "tester", "Tester's T7",
+ "Testers-MacBook-Pro", "[email protected]"] {
+ #expect(!text.contains(secret), "\(secret) is still in the log")
+ }
+ #expect(text.contains("SteamUser=<redacted>"))
+ #expect(text.contains("SteamAppId=1245620"))
+ #expect(text.contains("bash 76349 <user> 8w"))
+ #expect(text.contains("/Volumes/<drive>/SteamLibrary:/Volumes/Preboot/x"))
+ #expect(text.contains("C:/users/crossover/AppData"))
+ #expect(text.contains("~/Library/x.lock"))
+ }
+}
diff --git a/app/Tests/BridgeplayAppTests/PlayReportsTests.swift b/app/Tests/BridgeplayAppTests/PlayReportsTests.swift
new file mode 100644
index 0000000..7800da9
--- /dev/null
+++ b/app/Tests/BridgeplayAppTests/PlayReportsTests.swift
@@ -0,0 +1,475 @@
+import Foundation
+import Testing
+
+@testable import BridgeplayApp
+
+@Suite("One-tap play reports")
+struct PlayReportsTests {
+
+ private static let run = """
+ === bridgeplay run Tue Oct 20 21:00:00 WIB 2026 ===
+ verb=waitforexitandrun
+ === game exited status=0, killing wine prefix ===
+ === wine prefix killed, session ending ===
+ === bridgeplay run Wed Oct 21 20:00:00 WIB 2026 ===
+ verb=waitforexitandrun
+ runner: build winecx-11.17 (WineCX 11.17 (msync, D3DMetal)) at /Users/tester/Library/Application Support/bridgeplay/runners/b
+ graphics: backend=d3dmetal
+ SteamUser=player_one
+ """
+
+ private static func log(_ ending: String) -> String { run + "\n" + ending + "\n" }
+
+ private static func local(_ text: String) -> Date { GameSession.startDate(text)! }
+
+ @Test("The last session is read from the newest run block")
+ func lastSession() throws {
+ let ended = Self.local("Wed Oct 21 22:05:00 2026")
+ let log = Self.log("=== termination signal received, killing wine prefix ===\n=== game exited status=143, killing wine prefix ===")
+ let session = try #require(GameSession.last(in: log, modified: ended))
+ #expect(session.id == "=== bridgeplay run Wed Oct 21 20:00:00 WIB 2026 ===")
+ #expect(session.seconds == 2 * 3600 + 5 * 60)
+ #expect(session.exitStatus == 143)
+ #expect(session.stoppedBySteam)
+ #expect(session.inferredStatus(wineLog: nil) == .silver)
+ }
+
+ @Test("A run that hasn't finished, or never reached the game, is not a session")
+ func unfinished() {
+ #expect(GameSession.last(in: Self.run, modified: Date()) == nil)
+ #expect(GameSession.last(in: "=== bridgeplay run x ===\n=== aborted during prefix lock (exit 1) before launch ===", modified: Date()) == nil)
+ #expect(GameSession.last(in: "no header at all", modified: Date()) == nil)
+ }
+
+ @Test("Legacy notproton headers and odd dates still parse")
+ func legacyHeader() throws {
+ let log = "=== notproton run Fri Oct 9 10:00:00 WIB 2026 ===\n=== game exited status=0, killing wine prefix ===\n"
+ let session = try #require(GameSession.last(in: log, modified: Self.local("Fri Oct 9 10:45:00 2026")))
+ #expect(session.seconds == 45 * 60)
+ let unknown = try #require(GameSession.last(in: "=== bridgeplay run 2026年10月9日 ===\n=== game exited status=0 ===",
+ modified: Date()))
+ #expect(unknown.started == nil)
+ #expect(unknown.inferredStatus(wineLog: nil) == nil)
+ }
+
+ @Test("Auto-share infers only clear outcomes")
+ func inference() {
+ func session(_ minutes: Double, status: Int, steam: Bool = false) -> GameSession {
+ let end = Date()
+ return GameSession(id: "x", started: end.addingTimeInterval(-minutes * 60), ended: end,
+ exitStatus: status, stoppedBySteam: steam)
+ }
+ #expect(session(1, status: 5).inferredStatus(wineLog: nil) == .borked)
+ #expect(session(1, status: 0).inferredStatus(wineLog: "wine: Unhandled page fault on read access") == .borked)
+ #expect(session(45, status: 0).inferredStatus(wineLog: nil) == .silver)
+ #expect(session(45, status: 143, steam: true).inferredStatus(wineLog: nil) == .silver)
+ #expect(session(45, status: 5).inferredStatus(wineLog: nil) == nil)
+ #expect(session(10, status: 0).inferredStatus(wineLog: nil) == nil)
+ #expect(!session(0.5, status: 0).worthAsking(wineLog: nil))
+ #expect(session(0.5, status: 5).worthAsking(wineLog: nil))
+ #expect(!session(60, status: 0).worthAsking(now: Date().addingTimeInterval(4 * 86400), wineLog: nil))
+ }
+
+ @Test("The payload carries the machine, launch and redacted logs")
+ func payload() throws {
+ let session = GameSession(id: "x", started: Date().addingTimeInterval(-3600), ended: Date(),
+ exitStatus: 0, stoppedBySteam: false)
+ let machine = GameReport.Machine(chip: "Apple M5 Max", memoryBytes: 64 * 1_073_741_824,
+ macOS: "macOS 27.0", bridgeplay: "3.3.1 (41)")
+ let payload = ReportPayload.make(name: "Elden Ring", appID: "1245620", status: .silver, source: .auto,
+ session: session, log: Self.run, wineLog: String(repeating: "w", count: 400_000),
+ machine: machine, install: "0F8FAD5B-D9CB-469F-A165-70867728950E")
+ #expect(payload.chip == "M5 Max")
+ #expect(payload.memory == "64 GB")
+ #expect(payload.engine == "WineCX 11.17 (msync, D3DMetal)")
+ #expect(payload.backend == "d3dmetal")
+ #expect(payload.session == "Session 60 min, exit status 0. Status inferred from the log")
+ #expect(payload.log?.contains("player_one") == false)
+ #expect(payload.wineLog?.count == ReportPayload.wineLogLimit)
+ let json = try JSONSerialization.jsonObject(with: JSONEncoder().encode(payload)) as? [String: Any]
+ #expect(json?["status"] as? String == "silver")
+ #expect(json?["source"] as? String == "auto")
+ }
+}
+
+// Answers https://report.invalid/<status> with that status; /offline fails like no network.
+final class FakeEndpoint: URLProtocol, @unchecked Sendable {
+ override class func canInit(with request: URLRequest) -> Bool { request.url?.host() == "report.invalid" }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+ override func stopLoading() {}
+
+ override func startLoading() {
+ let path = request.url!.lastPathComponent
+ guard let code = Int(path) else {
+ client?.urlProtocol(self, didFailWithError: URLError(.notConnectedToInternet))
+ return
+ }
+ let response = HTTPURLResponse(url: request.url!, statusCode: code, httpVersion: nil, headerFields: nil)!
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
+ client?.urlProtocol(self, didLoad: Data("{}".utf8))
+ client?.urlProtocolDidFinishLoading(self)
+ }
+
+ static func sender(_ path: String, queue: URL) -> ReportSender {
+ let config = URLSessionConfiguration.ephemeral
+ config.protocolClasses = [FakeEndpoint.self]
+ return ReportSender(endpoint: URL(string: "https://report.invalid/\(path)")!, queue: queue,
+ session: URLSession(configuration: config))
+ }
+}
+
+@Suite("Play reports reach the endpoint or wait for it")
+struct ReportSenderTests {
+
+ private let payload = ReportPayload(appid: "1245620", status: .platinum, install: UUID().uuidString, source: .tap,
+ name: "Elden Ring", chip: "M5 Max", memory: "64 GB", macos: "macOS 27.0",
+ version: "3.3.1 (41)", engine: nil, backend: nil, session: "Session 60 min",
+ log: "log", wineLog: nil)
+
+ private func queued(_ queue: URL) -> [URL] {
+ ((try? FileManager.default.contentsOfDirectory(at: queue, includingPropertiesForKeys: nil)) ?? [])
+ .filter { $0.pathExtension == "json" }
+ }
+
+ @Test("Sent and refused reports leave the queue; offline and server errors stay")
+ func outcomes() async throws {
+ let queue = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: queue) }
+ #expect(await FakeEndpoint.sender("201", queue: queue).submit(payload) == .sent)
+ #expect(await FakeEndpoint.sender("400", queue: queue).submit(payload) == .dropped)
+ #expect(queued(queue).isEmpty)
+ #expect(await FakeEndpoint.sender("offline", queue: queue).submit(payload) == .retryLater)
+ #expect(await FakeEndpoint.sender("503", queue: queue).submit(payload) == .retryLater)
+ #expect(await FakeEndpoint.sender("429", queue: queue).submit(payload) == .retryLater)
+ #expect(queued(queue).count == 3)
+ }
+
+ @Test("Pending reports are retried once the wait is over")
+ func retry() async throws {
+ let queue = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: queue) }
+ _ = await FakeEndpoint.sender("offline", queue: queue).submit(payload)
+ let online = FakeEndpoint.sender("201", queue: queue)
+ await online.retryPending()
+ #expect(queued(queue).count == 1, "retried before the wait was over")
+ await online.retryPending(now: Date().addingTimeInterval(16 * 60))
+ #expect(queued(queue).isEmpty)
+ }
+
+ // Hermetic end to end with bridgeplay-web's mock server:
+ // node test/mock-server.mjs 4322 & BRIDGEPLAY_REPORT_E2E=http://127.0.0.1:4322/api/report swift test …
+ @Test("End to end against the local mock endpoint",
+ .enabled(if: ProcessInfo.processInfo.environment["BRIDGEPLAY_REPORT_E2E"] != nil))
+ func endToEnd() async throws {
+ let queue = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: queue) }
+ let endpoint = try #require(ProcessInfo.processInfo.environment["BRIDGEPLAY_REPORT_E2E"].flatMap(URL.init(string:)))
+ let session = GameSession(id: "e2e", started: Date().addingTimeInterval(-7200), ended: Date(),
+ exitStatus: 0, stoppedBySteam: true)
+ let log = "SteamUser=player_one\nCaching Steam ID: 76561198012345678\n"
+ + "runner: build winecx-11.17 (WineCX 11.17 (msync, D3DMetal)) at \(NSHomeDirectory())/x\ngraphics: backend=dxmt\n"
+ let real = ReportPayload.make(name: "Elden Ring", appID: "1245620", status: .platinum, source: .tap, session: session,
+ log: log, wineLog: "wine ok", machine: GameReport.thisMac, install: UUID().uuidString)
+ let sender = ReportSender(endpoint: endpoint, queue: queue)
+ #expect(await sender.submit(real) == .sent)
+ #expect(queued(queue).isEmpty)
+ }
+}
+
+@MainActor
+@Suite("The nudge asks once per session")
+struct PlayReportsFlowTests {
+
+ private func model(_ path: String, queue: URL, version: String = "3.4.0",
+ defaults: UserDefaults? = nil) -> (PlayReports, UserDefaults) {
+ let defaults = defaults ?? UserDefaults(suiteName: "play-reports-\(UUID().uuidString)")!
+ return (PlayReports(defaults: defaults, version: version, sender: { FakeEndpoint.sender(path, queue: queue) }), defaults)
+ }
+
+ private func found(_ appID: String, minutes: Double, status: Int = 0, ago: Double = 0) -> PlayReports.Found {
+ let end = Date().addingTimeInterval(-ago)
+ let prefix = WinePrefix(appID: appID, name: "Game \(appID)", library: SteamLibrary(root: URL(filePath: "/tmp/lib")),
+ lastUsed: nil)
+ let session = GameSession(id: "run \(appID) \(ago)", started: end.addingTimeInterval(-minutes * 60), ended: end,
+ exitStatus: status, stoppedBySteam: false)
+ return PlayReports.Found(prefix: prefix, session: session, log: "log", wineLog: nil)
+ }
+
+ @Test("First answer asks for consent; Not Now and answers aren't asked again")
+ func consentAndDismiss() throws {
+ let queue = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: queue) }
+ let (reports, _) = model("201", queue: queue)
+ reports.handle([found("10", minutes: 90), found("20", minutes: 20)])
+ #expect(reports.nudges.count == 2)
+ reports.answer(.platinum)
+ #expect(reports.consentRequest == .answer(.platinum))
+ #expect(reports.nudges.count == 2, "nothing is sent before consent")
+ reports.consentRequest = nil
+ reports.dismiss()
+ #expect(reports.nudge?.prefix.appID == "20")
+ reports.handle([found("10", minutes: 90), found("20", minutes: 20)])
+ #expect(reports.nudges.count == 1, "a dismissed session came back")
+ }
+
+ @Test("With consent, one tap sends, moves on and says thanks")
+ func oneTap() throws {
+ let queue = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: queue) }
+ let (reports, _) = model("201", queue: queue)
+ reports.handle([found("10", minutes: 90)])
+ reports.answer(.bronze)
+ reports.consent(alsoAutoShare: false)
+ #expect(reports.nudges.isEmpty)
+ #expect(reports.thanking)
+ #expect(!reports.autoShare)
+ }
+
+ @Test("A game is asked about once per Bridgeplay version, answered or not")
+ func oncePerVersion() throws {
+ let queue = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: queue) }
+ let (reports, defaults) = model("201", queue: queue)
+ reports.consent(alsoAutoShare: false)
+ reports.handle([found("10", minutes: 90, ago: 7200), found("20", minutes: 90, ago: 7300)])
+ reports.answer(.platinum)
+ reports.dismiss()
+ #expect(reports.nudges.isEmpty)
+ // Played both again, same version: no question.
+ reports.handle([found("10", minutes: 60), found("20", minutes: 60)])
+ #expect(reports.nudges.isEmpty)
+ // After an update both are asked about again.
+ let (updated, _) = model("201", queue: queue, version: "3.5.0", defaults: defaults)
+ updated.handle([found("10", minutes: 60), found("20", minutes: 60)])
+ #expect(Set(updated.nudges.map(\.prefix.appID)) == ["10", "20"])
+ #expect(updated.nudge?.prefix.appID == "10", "one card at a time, newest session first")
+ }
+
+ @Test("A crash after a Smooth answer asks again in the same version")
+ func crashAfterSmooth() throws {
+ let queue = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: queue) }
+ let (reports, _) = model("201", queue: queue)
+ reports.consent(alsoAutoShare: false)
+ reports.handle([found("10", minutes: 90, ago: 7200), found("20", minutes: 90, ago: 7300)])
+ reports.answer(.platinum)
+ reports.answer(.bronze)
+ #expect(reports.lastAnswer("10") == .platinum && reports.lastAnswer("20") == .bronze)
+ reports.handle([found("10", minutes: 1, status: 5), found("20", minutes: 1, status: 5, ago: 10)])
+ #expect(reports.nudges.map(\.prefix.appID) == ["10"], "only the game that was Smooth is asked again")
+ reports.answer(.borked)
+ reports.handle([found("10", minutes: 1, status: 5, ago: 20)])
+ #expect(reports.nudges.isEmpty, "a second crash after answering Didn't run is not asked")
+ }
+
+ @Test("Don't Ask About This Game is permanent, but Report This Game… still asks")
+ func neverAsk() async throws {
+ let queue = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: queue) }
+ let (reports, defaults) = model("201", queue: queue)
+ reports.handle([found("10", minutes: 90, ago: 100), found("10", minutes: 90, ago: 200)])
+ reports.neverAsk()
+ #expect(reports.nudges.isEmpty)
+ let (updated, _) = model("201", queue: queue, version: "9.0.0", defaults: defaults)
+ updated.handle([found("10", minutes: 90, status: 5)])
+ #expect(updated.nudges.isEmpty)
+ let prefix = found("10", minutes: 1).prefix
+ updated.ask(about: prefix)
+ for _ in 0..<50 where updated.nudges.isEmpty { try await Task.sleep(for: .milliseconds(20)) }
+ #expect(updated.nudge?.prefix.appID == "10")
+ }
+
+ @Test("Auto-share sends once per version, again only for a crash after Smooth")
+ func autoShareOncePerVersion() async throws {
+ let queue = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: queue) }
+ let (reports, _) = model("503", queue: queue)
+ reports.consent(alsoAutoShare: true)
+ reports.handle([found("10", minutes: 90, ago: 7200)])
+ reports.handle([found("10", minutes: 90, ago: 3600)])
+ #expect(reports.nudges.isEmpty)
+ #expect(reports.lastAnswer("10") == .silver)
+ func queued() -> Int { ((try? FileManager.default.contentsOfDirectory(atPath: queue.path)) ?? []).count }
+ for _ in 0..<50 where queued() < 1 { try await Task.sleep(for: .milliseconds(20)) }
+ try await Task.sleep(for: .milliseconds(200))
+ #expect(queued() == 1, "the second session in the same version was sent too")
+ }
+
+ @Test("Verified games are neither asked about nor auto-shared; Report This Game… still asks")
+ func verifiedSkipped() throws {
+ let queue = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: queue) }
+ let (reports, _) = model("503", queue: queue)
+ reports.verifiedHere = ["10"]
+ reports.handle([found("10", minutes: 90), found("20", minutes: 10)])
+ #expect(reports.nudges.map(\.prefix.appID) == ["20"])
+ reports.consent(alsoAutoShare: true)
+ reports.handle([found("10", minutes: 90, ago: 50)])
+ #expect(reports.lastAnswer("10") == nil, "a verified game was auto-shared")
+ reports.showBulk([found("10", minutes: 90), found("20", minutes: 10)])
+ #expect(reports.bulk?.map(\.prefix.appID) == ["20"])
+ }
+
+ @Test("Report Your Games… lists every session, newest first, minus answered, Don't Ask and verified")
+ func bulkList() throws {
+ let queue = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: queue) }
+ let (reports, _) = model("201", queue: queue)
+ reports.consent(alsoAutoShare: false)
+ reports.handle([found("1", minutes: 90, ago: 10)])
+ reports.answer(.platinum) // answered for this version
+ reports.handle([found("2", minutes: 90, ago: 20)])
+ reports.neverAsk() // Don't Ask
+ reports.verifiedHere = ["3"]
+ reports.showBulk([found("5", minutes: 0.2, ago: 30 * 86400), found("1", minutes: 9), found("2", minutes: 9),
+ found("3", minutes: 9), found("4", minutes: 9, ago: 86400)])
+ #expect(reports.bulk?.map(\.prefix.appID) == ["4", "5"], "old and short sessions belong in the list too")
+ }
+
+ @Test("Bulk answers wait for consent, then go out one by one and count as asked")
+ func bulkAnswer() async throws {
+ let queue = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: queue) }
+ let (reports, _) = model("503", queue: queue)
+ let games = (1...12).map { found(String($0), minutes: 30, ago: Double($0)) }
+ reports.handle([games[0]])
+ reports.showBulk(games)
+ reports.answerBulk(["1"], .bronze)
+ #expect(reports.consentRequest == .bulk(["1"], .bronze))
+ #expect(reports.bulk?.count == 12)
+ reports.consent(alsoAutoShare: false)
+ #expect(reports.bulk?.count == 11)
+ #expect(reports.nudges.isEmpty, "the card for a game answered in the sheet stays open")
+ reports.answerBulk((reports.bulk ?? []).map(\.prefix.appID), .platinum)
+ #expect(reports.bulk?.isEmpty == true)
+ #expect(reports.lastAnswer("1") == .bronze && reports.lastAnswer("12") == .platinum)
+ func queued() -> Int { ((try? FileManager.default.contentsOfDirectory(atPath: queue.path)) ?? []).count }
+ for _ in 0..<100 where queued() < 12 { try await Task.sleep(for: .milliseconds(20)) }
+ #expect(queued() == 12)
+ reports.showBulk(games)
+ #expect(reports.bulk?.isEmpty == true, "answered games came back in the same version")
+ }
+
+ @Test("A newer session of the same game replaces the older question")
+ func newerSession() throws {
+ let queue = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: queue) }
+ let (reports, _) = model("201", queue: queue)
+ reports.handle([found("10", minutes: 90, ago: 3600)])
+ reports.handle([found("10", minutes: 30)])
+ #expect(reports.nudges.count == 1)
+ #expect(reports.nudge?.session.id == "run 10 0.0")
+ }
+
+ @Test("Report This Game… asks now, from the log's last session or by hand")
+ func askByHand() async throws {
+ let dir = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let (reports, _) = model("201", queue: dir.appending(path: "queue"))
+ let library = SteamLibrary(root: dir)
+ let played = WinePrefix(appID: "10", name: "Played", library: library, lastUsed: nil)
+ let never = WinePrefix(appID: "20", name: "Never", library: library, lastUsed: nil)
+ try FileManager.default.createDirectory(at: played.root, withIntermediateDirectories: true)
+ try "=== bridgeplay run Wed Oct 21 20:00:00 WIB 2026 ===\n=== game exited status=0, killing wine prefix ===\n"
+ .write(to: PrefixLog.launch.url(for: played), atomically: true, encoding: .utf8)
+ reports.ask(about: never)
+ reports.ask(about: played)
+ for _ in 0..<50 where reports.nudges.count < 2 { try await Task.sleep(for: .milliseconds(20)) }
+ let fromLog = try #require(reports.nudges.first { $0.prefix.appID == "10" })
+ #expect(fromLog.session.id == "=== bridgeplay run Wed Oct 21 20:00:00 WIB 2026 ===")
+ let byHand = try #require(reports.nudges.first { $0.prefix.appID == "20" })
+ #expect(byHand.session.byHand)
+ #expect(byHand.session.summary(wineLog: nil) == "Reported from the Prefixes page")
+ }
+
+ @Test("Auto-share needs consent, then reports clear sessions and asks about the rest")
+ func autoShare() async throws {
+ let queue = try scratchDirectory("reports")
+ defer { try? FileManager.default.removeItem(at: queue) }
+ let (reports, _) = model("503", queue: queue)
+ reports.setAutoShare(true)
+ #expect(reports.consentRequest == .autoShare)
+ #expect(!reports.autoShare)
+ reports.consent(alsoAutoShare: false)
+ #expect(reports.autoShare && reports.hasConsent)
+
+ reports.handle([found("10", minutes: 90), found("20", minutes: 10)])
+ #expect(reports.nudges.map(\.prefix.appID) == ["20"], "the unclear session should still be asked about")
+ // The endpoint answers 503, so the auto report waits in the queue.
+ for _ in 0..<50 where (try? FileManager.default.contentsOfDirectory(atPath: queue.path))?.isEmpty ?? true {
+ try await Task.sleep(for: .milliseconds(50))
+ }
+ let files = try FileManager.default.contentsOfDirectory(at: queue, includingPropertiesForKeys: nil)
+ let sent = try JSONDecoder().decode(ReportPayload.self, from: Data(contentsOf: try #require(files.first)))
+ #expect(sent.appid == "10" && sent.status == .silver && sent.source == .auto)
+ }
+}
+
+// Answers every request with a copy of compat/games.json, or fails like no network.
+final class FakeRawOK: URLProtocol, @unchecked Sendable {
+ static let body = """
+ [{"appid": 1245620, "status": "platinum", "tested_on": "M5 Max · macOS 27"},
+ {"appid": 10, "status": "borked", "reports": [{"chip": "M2", "status": "borked"}, {"device": "M5 Max · macOS 27.0"}]},
+ {"appid": 20, "status": "untested", "tested_on": "M5 Max · macOS 27"},
+ {"appid": 30, "status": "gold", "tested_on": "M5 · macOS 26"}]
+ """
+ override class func canInit(with request: URLRequest) -> Bool { true }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+ override func stopLoading() {}
+ override func startLoading() {
+ let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
+ client?.urlProtocol(self, didLoad: Data(Self.body.utf8))
+ client?.urlProtocolDidFinishLoading(self)
+ }
+}
+
+final class FakeRawDown: URLProtocol, @unchecked Sendable {
+ override class func canInit(with request: URLRequest) -> Bool { true }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+ override func stopLoading() {}
+ override func startLoading() { client?.urlProtocol(self, didFailWithError: URLError(.notConnectedToInternet)) }
+}
+
+@Suite("Games a maintainer verified on a Mac like this one are not asked about")
+struct VerifiedGamesTests {
+
+ private func session(_ type: URLProtocol.Type) -> URLSession {
+ let config = URLSessionConfiguration.ephemeral
+ config.protocolClasses = [type]
+ return URLSession(configuration: config)
+ }
+
+ @Test("Chip families come out of free text")
+ func chips() {
+ #expect(VerifiedGames.chipFamilies(in: "M5 Max · macOS 27") == ["M5 Max"])
+ #expect(VerifiedGames.chipFamilies(in: "M2 · 16 GB") == ["M2"])
+ #expect(VerifiedGames.chipFamilies(in: "MacBook Pro M3 Ultra") == ["M3 Ultra"])
+ }
+
+ @Test("A verified status on the same chip family counts; untested and other chips don't")
+ func matching() {
+ let data = Data(FakeRawOK.body.utf8)
+ #expect(VerifiedGames.verified(on: "M5 Max", in: data) == ["1245620", "10"])
+ #expect(VerifiedGames.verified(on: "M5", in: data) == ["30"])
+ #expect(VerifiedGames.verified(on: "M2", in: data) == ["10"])
+ #expect(VerifiedGames.verified(on: "Other", in: data).isEmpty)
+ #expect(VerifiedGames.verified(on: "M5 Max", in: Data("not json".utf8)).isEmpty)
+ }
+
+ @Test("Fetched once a day, the cache covers offline, nothing at all means ask as before")
+ func cache() async throws {
+ let dir = try scratchDirectory("verified")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let cache = dir.appending(path: "compat-games.json")
+ #expect(await VerifiedGames.load(chip: "M5 Max", cache: cache, session: session(FakeRawDown.self)).isEmpty)
+ #expect(await VerifiedGames.load(chip: "M5 Max", cache: cache, session: session(FakeRawOK.self)) == ["1245620", "10"])
+ // Fresh: not fetched again, so a dead network changes nothing.
+ #expect(await VerifiedGames.load(chip: "M5 Max", cache: cache, session: session(FakeRawDown.self)) == ["1245620", "10"])
+ // A day old and the fetch fails: the old copy is used and kept another day.
+ let later = Date().addingTimeInterval(2 * 86400)
+ #expect(await VerifiedGames.load(chip: "M5 Max", cache: cache, session: session(FakeRawDown.self), now: later) == ["1245620", "10"])
+ let touched = try #require(try FileManager.default.attributesOfItem(atPath: cache.path(percentEncoded: false))[.modificationDate] as? Date)
+ #expect(abs(touched.timeIntervalSince(later)) < 2)
+ }
+}