) -> Bool { slot.map(slots.contains) ?? true }
async let wikidata = wants([.logo, .cover, .background]) ? WikidataArt.find(names: names, client: client)
@@ -47,7 +47,7 @@ public enum OnlineArtwork {
async let xbox = wants([.cover, .background, .icon]) ? XboxStoreArt.find(names: names, client: client) : []
async let gog = wants([.logo, .cover, .background]) ? GOGArt.find(names: names, client: client) : []
async let europe = wants([.background, .icon]) ? NintendoEuropeArt.find(names: names, client: client) : []
- async let gamesDB = wants([.logo, .cover, .background]) ? TheGamesDBArt.find(names: names, client: client) : []
+ async let gamesDB = wants([.logo, .cover, .background]) ? TheGamesDBArt.find(names: names, platform: platform, client: client) : []
async let commons = wants([.logo]) ? MediaWikiLogos.commons.candidates(names: names, client: client) : []
async let wikis = wants([.logo]) ? fanWikiLogos(names: names, client: client) : []
async let wallhaven = wants([.background]) ? WallhavenGameArt.find(names: names, client: client) : []
@@ -331,31 +331,8 @@ public enum WikidataArt {
}
/// TheGamesDB, the community database: clear logos, box fronts, fan art and
-/// screenshots for Switch games, read from its public pages.
+/// screenshots for the requested game platform, read from its public pages.
public enum TheGamesDBArt {
- static let switchPlatform = "4971"
-
- public static func searchURL(for name: String) -> URL? {
- let term = SteamStoreArt.plain(name)
- guard !term.isEmpty else { return nil }
- var components = URLComponents(string: "https://thegamesdb.net/search.php")!
- components.queryItems = [.init(name: "name", value: term), .init(name: "platform_id[]", value: switchPlatform)]
- return components.url
- }
-
- /// The first result card whose title is the game's.
- public static func gameID(in html: String, matching names: [String]) -> Int? {
- for card in html.components(separatedBy: "game.php?id=").dropFirst() {
- let id = Int(card.prefix { $0.isNumber })
- guard let id, let footer = card.range(of: "card-footer"),
- let open = card.range(of: "", range: footer.upperBound..", range: open.upperBound.. URL {
URL(string: "https://thegamesdb.net/game.php?id=\(id)")!
}
@@ -378,12 +355,26 @@ public enum TheGamesDBArt {
+ OnlineArtwork.screenshots(byKind["screenshot"] ?? [], source: "TheGamesDB screenshot")
}
- public static func find(names: [String], client: ArtworkHTTPClient) async -> [ArtworkCandidate] {
- guard let name = names.first, let url = searchURL(for: name),
- let data = await OnlineArtworkRequest.data(url, client: client),
- let id = gameID(in: String(decoding: data, as: UTF8.self), matching: names),
- let page = await OnlineArtworkRequest.data(gameURL(id: id), client: client) else { return [] }
- return candidates(in: String(decoding: page, as: UTF8.self), id: id)
+ public static func find(names: [String], platform: CriticRatingQuery.Platform = .switch, client: ArtworkHTTPClient) async -> [ArtworkCandidate] {
+ guard let name = names.first else { return [] }
+ let query = CriticRatingQuery(name: name, platform: platform)
+ for platformName in MetadataDatabase.theGamesDB.platforms(for: query) {
+ guard !Task.isCancelled, let url = DatabaseMetadataParser.gamesDBSearch(query: query, platform: platformName),
+ let data = await OnlineArtworkRequest.data(url, client: client) else { continue }
+ let html = String(decoding: data, as: UTF8.self)
+ let matches = Set(names.flatMap { alias in
+ DatabaseMetadataParser.gamesDBCandidates(in: html, query: CriticRatingQuery(name: alias, platform: platform), platform: platformName)
+ })
+ guard matches.count <= 1 else { return [] }
+ guard let match = matches.first else { continue }
+ guard !Task.isCancelled, let data = await OnlineArtworkRequest.data(match.url, client: client) else { return [] }
+ let page = String(decoding: data, as: UTF8.self)
+ let verified = DatabaseMetadataParser.theGamesDB(in: page, query: CriticRatingQuery(name: match.title, platform: platform), page: match.url)
+ guard verified.preview?.platform == platformName,
+ let id = URLComponents(url: match.url, resolvingAgainstBaseURL: false)?.queryItems?.first(where: { $0.name == "id" })?.value.flatMap(Int.init) else { return [] }
+ return candidates(in: page, id: id)
+ }
+ return []
}
private static func decodeEntities(_ text: String) -> String {
diff --git a/Sources/NXLibraryCore/Services/NUPSourceCatalog.swift b/Sources/NXLibraryCore/Services/NUPSourceCatalog.swift
index f769cc32..6e591e7b 100644
--- a/Sources/NXLibraryCore/Services/NUPSourceCatalog.swift
+++ b/Sources/NXLibraryCore/Services/NUPSourceCatalog.swift
@@ -55,6 +55,9 @@ try:
name = raw.decode('utf-8', 'replace'); break
if name: break
print(f'title {app:016X}')
+ if getattr(n, 'application', None) is not None:
+ print(f'application {n.application:016X}')
+ print(f'aoc_base {n.aoc_base:016X}')
print('name ' + name.encode().hex())
if base is not None: print(f'base {n.tree_bytes(base.root)}')
for v, k in sorted(vers.items()): print(f'update {v} {n.tree_bytes(k.root)}')
@@ -86,13 +89,37 @@ except pack_nup.Error as e:
var updates: [DetectedSource] = []
var dlcs: [DetectedSource] = []
let lines = output.split(separator: "\n").map { $0.split(separator: " ").map(String.init) }
+ guard lines.filter({ $0.first == "title" }).count == 1 else {
+ throw EngineSourceError.invalidContainer("invalid program title ID")
+ }
for fields in lines where fields.first == "title" {
- guard fields.count == 2, let id = UInt64(fields[1], radix: 16), id != 0, id & 0xFFF == 0 else {
+ guard fields.count == 2, fields[1].count == 16, let id = UInt64(fields[1], radix: 16), id != 0 else {
throw EngineSourceError.invalidContainer("invalid base title ID")
}
title = id
}
guard let title else { throw EngineSourceError.invalidContainer("no base title ID") }
+ let applications = lines.filter { $0.first == "application" }
+ let aocBases = lines.filter { $0.first == "aoc_base" }
+ let selection: NUPProgramSelection?
+ if !applications.isEmpty || !aocBases.isEmpty {
+ guard applications.count == 1, aocBases.count == 1,
+ applications[0].count == 2, aocBases[0].count == 2,
+ applications[0][1].count == 16, aocBases[0][1].count == 16,
+ let application = UInt64(applications[0][1], radix: 16),
+ let aocBase = UInt64(aocBases[0][1], radix: 16) else {
+ throw EngineSourceError.invalidContainer("invalid program metadata")
+ }
+ let program = NUPProgramSelection(programID: title, applicationID: application, addOnContentBaseID: aocBase)
+ guard program.isValid else { throw EngineSourceError.invalidContainer("invalid program metadata") }
+ selection = program
+ } else {
+ guard title & 0xFFF == 0 else { throw EngineSourceError.invalidContainer("invalid base title ID") }
+ selection = nil
+ }
+ let (legacyAOCBase, aocOverflow) = title.addingReportingOverflow(0x1000)
+ guard selection != nil || !aocOverflow else { throw EngineSourceError.invalidContainer("invalid DLC base") }
+ let aocBase = selection?.addOnContentBaseID ?? legacyAOCBase
for fields in lines {
switch fields.first {
case "name":
@@ -103,14 +130,16 @@ except pack_nup.Error as e:
guard fields.count == 3, let version = Int(fields[1]), version > 0, let bytes = Int64(fields[2]) else {
throw EngineSourceError.invalidContainer("invalid update record")
}
- updates.append(DetectedSource(url: nup, kind: .update, titleId: title + 0x800, version: version,
- sizeBytes: bytes, layout: .container))
+ let (updateID, overflow) = title.addingReportingOverflow(0x800)
+ guard !overflow else { throw EngineSourceError.invalidContainer("invalid update record") }
+ updates.append(DetectedSource(url: nup, kind: .update, titleId: updateID, version: version,
+ sizeBytes: bytes, layout: .container, nupProgram: selection))
case "dlc":
- guard fields.count == 3, let id = UInt64(fields[1], radix: 16), id > title + 0x1000,
- id - title - 0x1000 <= 2000, let bytes = Int64(fields[2]) else {
+ guard fields.count == 3, let id = UInt64(fields[1], radix: 16), id > aocBase,
+ id - aocBase <= 2000, let bytes = Int64(fields[2]) else {
throw EngineSourceError.invalidContainer("invalid DLC record")
}
- dlcs.append(DetectedSource(url: nup, kind: .dlc, titleId: id, sizeBytes: bytes, layout: .container))
+ dlcs.append(DetectedSource(url: nup, kind: .dlc, titleId: id, sizeBytes: bytes, layout: .container, nupProgram: selection))
default:
break
}
@@ -124,7 +153,7 @@ except pack_nup.Error as e:
let profileName = profile?.split(separator: "\n").first(where: { $0.hasPrefix("name\t") }).map { String($0.dropFirst(5)) }
let name = profileName ?? (nacpName.isEmpty ? identity : nacpName)
let base = hasBase
- ? DetectedSource(url: nup, kind: .base, titleId: title, version: 0, sizeBytes: fileSize, layout: .container)
+ ? DetectedSource(url: nup, kind: .base, titleId: title, version: 0, sizeBytes: fileSize, layout: .container, nupProgram: selection)
: nil
return DetectedGame(baseTitleId: title, name: name, base: base,
updates: updates.sorted { ($0.version ?? 0) < ($1.version ?? 0) }, dlcs: dlcs)
diff --git a/Sources/NXLibraryCore/Services/NXNativeGameSettings.swift b/Sources/NXLibraryCore/Services/NXNativeGameSettings.swift
index 6d57c84d..26f9eb35 100644
--- a/Sources/NXLibraryCore/Services/NXNativeGameSettings.swift
+++ b/Sources/NXLibraryCore/Services/NXNativeGameSettings.swift
@@ -56,7 +56,7 @@ public struct NXNativeGameSettings {
store: SavedChoicesStore = SystemSavedChoices(),
supportDirectory: URL = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Library/Application Support/nxnative"),
- preferences: UserDefaults = .standard) -> NXNativeGameSettings? {
+ preferences: UserDefaults = AppData.preferences) -> NXNativeGameSettings? {
guard let titleId = game.titleId, !titleId.isEmpty else { return nil }
let plist = game.url.appendingPathComponent("Contents/Info.plist")
guard let data = try? Data(contentsOf: plist),
diff --git a/Sources/NXLibraryCore/Services/NXNativeLibraryMerge.swift b/Sources/NXLibraryCore/Services/NXNativeLibraryMerge.swift
new file mode 100644
index 00000000..52f4ac99
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/NXNativeLibraryMerge.swift
@@ -0,0 +1,70 @@
+import Foundation
+
+/// The established nxnative scan merge, shared with the legacy store. It only
+/// handles nxnative payloads; other catalog integrations never enter this path.
+enum NXNativeLibraryMerge {
+ static func merge(scanned: [PortedGame], into existing: [PortedGame], replacingSources: Bool = false,
+ fileManager fm: FileManager = .default) -> [PortedGame] {
+ var games = existing
+ for game in scanned {
+ if let index = games.firstIndex(where: { existing in
+ if existing.id == game.id { return true }
+ guard let target = game.titleId else { return false }
+ return existing.titleId?.caseInsensitiveCompare(target) == .orderedSame
+ }) {
+ let old = games[index]
+ // Scans refresh disk observations. Application-owned state survives a scan.
+ var merged = old
+ merged.name = game.name
+ merged.url = game.url
+ merged.platform = game.platform
+ merged.sizeBytes = game.sizeBytes
+ merged.modificationDate = game.modificationDate
+ merged.bundleId = game.bundleId
+ merged.titleId = game.titleId
+ merged.versionString = game.versionString
+ merged.status = game.status
+ merged.toolchain = game.toolchain
+ merged.lastBuild = game.lastBuild
+ let explicitSources = replacingSources && !game.sources.isEmpty
+ if explicitSources || old.sources.isEmpty {
+ merged.sources = game.sources
+ } else {
+ let oldSourcesExist = old.sources.allSatisfy {
+ fm.fileExists(atPath: $0.url.path)
+ }
+ merged.sources = (oldSourcesExist || game.sources.isEmpty)
+ ? old.sources : game.sources
+ }
+ merged.workspacePath = explicitSources ? game.workspacePath ?? old.workspacePath : old.workspacePath ?? game.workspacePath
+ merged.buildCachePath = explicitSources ? game.buildCachePath ?? old.buildCachePath : old.buildCachePath ?? game.buildCachePath
+ if (old.status == .built || old.status == .builtSourcesMissing
+ || old.status == .needsRebuild),
+ old.url.pathExtension.lowercased() == "app",
+ fm.fileExists(atPath: old.url.path) {
+ merged.url = old.url
+ merged.sizeBytes = old.sizeBytes
+ merged.bundleId = old.bundleId ?? merged.bundleId
+ merged.versionString = old.versionString ?? merged.versionString
+ }
+ if old.status == .built || old.status == .builtSourcesMissing
+ || old.status == .needsRebuild {
+ if merged.sources.isEmpty {
+ merged.status = game.status == .built ? .built : .builtSourcesMissing
+ } else {
+ let sourcesExist = merged.sources.allSatisfy {
+ fm.fileExists(atPath: $0.url.path)
+ }
+ merged.status = sourcesExist ? .built : .builtSourcesMissing
+ }
+ merged.toolchain = old.toolchain
+ merged.lastBuild = old.lastBuild
+ }
+ games[index] = merged
+ } else {
+ games.append(game)
+ }
+ }
+ return games
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/NewestEngine.swift b/Sources/NXLibraryCore/Services/NewestEngine.swift
index 3397513c..e9600f37 100644
--- a/Sources/NXLibraryCore/Services/NewestEngine.swift
+++ b/Sources/NXLibraryCore/Services/NewestEngine.swift
@@ -1,6 +1,6 @@
import Foundation
-/// The player's choice to build with nxnative main before NX Library has tested it (Settings → Engine,
+/// The player's choice to build with nxnative main before NX Library has tested it (Settings → Setup and engine,
/// Newest engine). NX Library never follows main by itself: the choice is explicit, turns the untested-toolchain
/// override on, and records every build it makes as untested.
public struct NewestEngineChoice: Codable, Equatable, Sendable {
@@ -30,7 +30,7 @@ public enum NewestEngineReadiness: Equatable, Sendable {
case unknown
}
-/// A button on Settings → Engine's Newest engine row.
+/// A button on Settings → Setup and engine's Newest engine row.
public enum NewestEngineAction: Equatable, Sendable {
case useNewest, update, backToTested
}
@@ -43,29 +43,29 @@ public enum UpstreamCommitMark: Equatable, Sendable {
/// The words every screen uses for the newest engine, so Settings and Setup say the same thing.
public enum NewestEngineCopy {
public static var note: String {
- L10n.text("Newest nxnative, not yet tested by NX Library. It usually works, but something may not. ")
- + L10n.text("Its new features reach NX Library in a future version.")
+ L10n.text("Newest nxnative, not yet tested by Arcane. It usually works, but something may not. ")
+ + L10n.text("Its new features reach Arcane in a future version.")
}
public static func ahead(_ count: Int) -> String {
L10n.count("%lld commits ahead", count, arguments: [])
}
- /// Settings → Engine, Newest engine row, while the tested engine is in use.
+ /// Settings → Setup and engine, Newest engine row, while the tested engine is in use.
public static func offer(commit: String, aheadBy: Int) -> String {
- L10n.format("Build with nxnative main (%@, %@) before NX Library has tested it.", [String(describing: (commit.prefix(7))), String(describing: (ahead(aheadBy)))])
+ L10n.format("Build with nxnative main (%@, %@) before Arcane has tested it.", [String(describing: (commit.prefix(7))), String(describing: (ahead(aheadBy)))])
}
public static func needsNewerApp(metal: String) -> String {
- L10n.format("The newest nxnative needs Metal %@, so it needs a newer NX Library.", [String(describing: (metal))])
+ L10n.format("The newest nxnative needs Metal %@, so it needs a newer Arcane.", [String(describing: (metal))])
}
/// Setup's engine card while the newest engine is in use (the note is its description).
public static func setupDetail(choice: NewestEngineChoice, tested: String) -> String {
- L10n.format("At %@, %@ of the tested %@, chosen in Settings → Engine.", [String(describing: (choice.shortCommit)), String(describing: (ahead(choice.aheadBy))), String(describing: (tested.prefix(7)))])
+ L10n.format("At %@, %@ of the tested %@, chosen in Settings → Setup and engine.", [String(describing: (choice.shortCommit)), String(describing: (ahead(choice.aheadBy))), String(describing: (tested.prefix(7)))])
}
- /// Settings → Engine, Newest engine row, while main is past the commit in use. `aheadBy` counts from the pin,
+ /// Settings → Setup and engine, Newest engine row, while main is past the commit in use. `aheadBy` counts from the pin,
/// like the choice's own count; a rewritten main (not further ahead) gets no count.
public static func update(choice: NewestEngineChoice, main: String, aheadBy: Int) -> String {
let newer = aheadBy - choice.aheadBy
@@ -74,7 +74,7 @@ public enum NewestEngineCopy {
}
public static var info: String {
- L10n.text("Builds games with nxnative main instead of the engine this NX Library is tested with. ")
+ L10n.text("Builds games with nxnative main instead of the engine this version of Arcane is tested with. ")
+ L10n.text("Builds are recorded as untested and the untested-toolchain override stays on. ")
+ L10n.text("Back to tested returns to the tested engine; games you built keep playing.")
}
@@ -89,7 +89,7 @@ public enum NewestEngineError: Error, Equatable, LocalizedError {
public var errorDescription: String? {
switch self {
case .localChanges:
- return L10n.text("The engine folder has changed files. NX Library never touches them: put them aside, then try again.")
+ return L10n.text("The engine folder has changed files. Arcane never touches them: put them aside, then try again.")
case .downloadFailed:
return L10n.text("The newest nxnative could not be downloaded. Check the connection, then try again.")
case .needsNewerApp(let metal):
@@ -128,7 +128,7 @@ public enum NewestEngine {
guard let url = lockURL(commit: commit) else { return nil }
var request = URLRequest(url: url)
request.timeoutInterval = 20
- request.setValue("NXLibrary/0.1", forHTTPHeaderField: "User-Agent")
+ request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent")
guard let (data, http) = try? await client.data(for: request), (200..<300).contains(http.statusCode) else {
return nil
}
@@ -155,7 +155,7 @@ public enum NewestEngine {
return (primary, actions.dropFirst().first)
}
- /// Tags for Settings → Engine's upstream list (newest first): the commit the newest engine is at is In use,
+ /// Tags for Settings → Setup and engine's upstream list (newest first): the commit the newest engine is at is In use,
/// those above it New. Nothing on the tested engine, or when the commit in use is not in the list.
public static func marks(_ commits: [UpstreamCommit], inUse: String?) -> [String: UpstreamCommitMark] {
guard let inUse, let index = commits.firstIndex(where: { $0.sha == inUse }) else { return [:] }
diff --git a/Sources/NXLibraryCore/Services/NintendoStoreMetadata.swift b/Sources/NXLibraryCore/Services/NintendoStoreMetadata.swift
index 9315284e..da0d1c89 100644
--- a/Sources/NXLibraryCore/Services/NintendoStoreMetadata.swift
+++ b/Sources/NXLibraryCore/Services/NintendoStoreMetadata.swift
@@ -132,8 +132,7 @@ public final class NintendoStoreMetadataService: @unchecked Sendable {
public init(
client: NintendoStoreHTTPClient = URLSessionNintendoStoreClient(),
- cacheDirectory: URL = FileManager.default.homeDirectoryForCurrentUser
- .appendingPathComponent("Library/Application Support/NXLibrary/metadata"),
+ cacheDirectory: URL = AppData.supportRoot.appendingPathComponent("metadata"),
fileManager: FileManager = .default
) {
self.client = client
@@ -476,7 +475,7 @@ public final class NintendoStoreMetadataService: @unchecked Sendable {
request.setValue(Self.appID, forHTTPHeaderField: "X-Algolia-Application-Id")
request.setValue(key, forHTTPHeaderField: "X-Algolia-API-Key")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
- request.setValue("NXLibrary/0.1 (macOS; personal app)", forHTTPHeaderField: "User-Agent")
+ request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent")
request.httpBody = try JSONEncoder().encode(body)
let (data, http) = try await client.data(for: request)
guard (200..<300).contains(http.statusCode) else {
@@ -490,7 +489,7 @@ public final class NintendoStoreMetadataService: @unchecked Sendable {
private func fetchProductPage(_ url: URL) async throws -> PageProduct {
var request = URLRequest(url: url)
request.timeoutInterval = 15
- request.setValue("NXLibrary/0.1 (macOS; personal app)", forHTTPHeaderField: "User-Agent")
+ request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent")
let (data, http) = try await client.data(for: request)
guard (200..<300).contains(http.statusCode) else {
throw NintendoStoreError.http(http.statusCode)
diff --git a/Sources/NXLibraryCore/Services/OnlineArtworkSources.swift b/Sources/NXLibraryCore/Services/OnlineArtworkSources.swift
index 2685e901..da40895b 100644
--- a/Sources/NXLibraryCore/Services/OnlineArtworkSources.swift
+++ b/Sources/NXLibraryCore/Services/OnlineArtworkSources.swift
@@ -180,7 +180,7 @@ enum OnlineArtworkRequest {
static func data(_ url: URL, client: ArtworkHTTPClient) async -> Data? {
var request = URLRequest(url: url)
request.timeoutInterval = 15
- request.setValue("NXLibrary/0.1 (macOS; personal app)", forHTTPHeaderField: "User-Agent")
+ request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent")
guard let (data, http) = try? await client.data(for: request), (200..<300).contains(http.statusCode) else {
return nil
}
diff --git a/Sources/NXLibraryCore/Services/PlaySessionStore.swift b/Sources/NXLibraryCore/Services/PlaySessionStore.swift
index d4ab5d81..4fb30886 100644
--- a/Sources/NXLibraryCore/Services/PlaySessionStore.swift
+++ b/Sources/NXLibraryCore/Services/PlaySessionStore.swift
@@ -7,7 +7,14 @@ public final class PlaySessionStore: ObservableObject, PlayHistory {
/// Play time and last start of sessions trimmed from `sessions`, per game,
/// so totals and last-played survive trimming.
@Published public private(set) var carried: [UUID: CarriedPlaytime] = [:]
+ /// Another launcher's own total for a game (Steam's), with when it was seen. Not persisted here.
+ @Published public private(set) var external: [UUID: ExternalPlaytime] = [:]
+ /// When each game's external value was seen, kept while its total is hidden (source off, another
+ /// account, launch), so trimming still keeps the part after it.
+ public private(set) var trimReferences: [UUID: Date] = [:]
public static let maxSessions = 200
+ /// Each game whose session just started (not a duplicate start).
+ public let starts = PassthroughSubject()
public private(set) var loadError: String?
/// Recent sessions, a bare `[PlaySession]` array as in every earlier version,
@@ -31,8 +38,7 @@ public final class PlaySessionStore: ObservableObject, PlayHistory {
}
public static func defaultURL() -> URL {
- FileManager.default.homeDirectoryForCurrentUser
- .appendingPathComponent("Library/Application Support/NXLibrary/play-sessions.json")
+ AppData.supportRoot.appendingPathComponent("play-sessions.json")
}
@discardableResult
@@ -49,6 +55,23 @@ public final class PlaySessionStore: ObservableObject, PlayHistory {
sessions.append(session)
let folded = trim()
save(totals: folded)
+ starts.send(game.id)
+ return true
+ }
+
+ /// A session for a game of another integration, which observes its own process. `sourceID` is the
+ /// qualified identity ("steam-570"), never a made-up Nintendo title ID. The session is ended by its
+ /// owner, and a restart closes it at its last heartbeat. A game found already
+ /// running when its owner starts watching is not a new start: `announces: false` keeps it off `starts`.
+ @discardableResult
+ public func start(gameID: UUID, sourceID: String, announces: Bool = true) -> Bool {
+ if isRunning(gameID: gameID) { return false }
+ let date = now()
+ sessions.append(PlaySession(gameID: gameID, titleID: sourceID, bundleID: nil,
+ startedAt: date, lastHeartbeatAt: date))
+ let folded = trim()
+ save(totals: folded)
+ if announces { starts.send(gameID) }
return true
}
@@ -58,15 +81,18 @@ public final class PlaySessionStore: ObservableObject, PlayHistory {
save()
}
- public func end(gameID: UUID) {
+ /// Ends the game's running sessions and returns them, ended.
+ @discardableResult
+ public func end(gameID: UUID) -> [PlaySession] {
let date = now()
- var changed = false
+ var ended: [PlaySession] = []
for index in sessions.indices where sessions[index].gameID == gameID && sessions[index].isActive {
sessions[index].endedAt = date
sessions[index].lastHeartbeatAt = date
- changed = true
+ ended.append(sessions[index])
}
- if changed { save() }
+ if !ended.isEmpty { save() }
+ return ended
}
/// Ends the game's running sessions and returns them, ended.
@@ -101,18 +127,39 @@ public final class PlaySessionStore: ObservableObject, PlayHistory {
if changed { save() }
}
+ /// Sets the external totals; publishes only a change.
+ public func setExternal(_ values: [UUID: ExternalPlaytime]) {
+ if values != external { external = values }
+ }
+
+ public func setTrimReferences(_ values: [UUID: Date]) { trimReferences = values }
+
+ /// With an external total: that total plus the part of this store's sessions after it was seen
+ /// (it already counts what came before), including trimmed sessions' part after that same value.
+ /// Without one: carried time plus every session.
public func totalDuration(for gameID: UUID) -> TimeInterval {
+ totalDuration(for: gameID, with: external[gameID])
+ }
+
+ /// The total under a given external value (nil: none), whatever is published.
+ public func totalDuration(for gameID: UUID, with external: ExternalPlaytime?) -> TimeInterval {
let date = now()
- return sessions
- .filter { $0.gameID == gameID }
- .reduce(carried[gameID]?.duration ?? 0) { total, session in
+ let own = sessions.filter { $0.gameID == gameID }
+ guard let base = external else {
+ return own.reduce(carried[gameID]?.duration ?? 0) { total, session in
total + max(0, (session.endedAt ?? date).timeIntervalSince(session.startedAt))
}
+ }
+ let trimmed = carried[gameID].flatMap { $0.externalSince == base.since ? $0.afterExternal : nil } ?? 0
+ return own.reduce(base.duration + trimmed) { total, session in
+ let end = min(session.endedAt ?? date, date)
+ return total + max(0, end.timeIntervalSince(max(session.startedAt, base.since)))
+ }
}
public func lastPlayed(for gameID: UUID) -> Date? {
let recent = sessions.filter { $0.gameID == gameID }.map(\.startedAt).max()
- return [recent, carried[gameID]?.lastPlayed].compactMap { $0 }.max()
+ return [recent, carried[gameID]?.lastPlayed, external[gameID]?.lastPlayed].compactMap { $0 }.max()
}
public func isRunning(gameID: UUID) -> Bool {
@@ -132,6 +179,12 @@ public final class PlaySessionStore: ObservableObject, PlayHistory {
var entry = carried[session.gameID] ?? CarriedPlaytime(duration: 0, lastPlayed: session.startedAt)
entry.duration += session.duration ?? 0
entry.lastPlayed = max(entry.lastPlayed, session.startedAt)
+ // The part after an external value was seen is not in that value yet: keep it, tied to that value.
+ if let since = external[session.gameID]?.since ?? trimReferences[session.gameID] {
+ if entry.externalSince != since { entry.externalSince = since; entry.afterExternal = 0 }
+ let end = session.endedAt ?? session.lastHeartbeatAt
+ entry.afterExternal += max(0, end.timeIntervalSince(max(session.startedAt, since)))
+ }
carried[session.gameID] = entry
}
let droppedIDs = Set(dropped.map(\.id))
@@ -192,14 +245,41 @@ public final class PlaySessionStore: ObservableObject, PlayHistory {
}
}
-/// Play time folded out of the recent-session list for one game.
+/// A game's total as another launcher keeps it, and when NX Library first saw that value.
+public struct ExternalPlaytime: Equatable, Sendable {
+ public let duration: TimeInterval
+ public let lastPlayed: Date?
+ public let since: Date
+
+ public init(duration: TimeInterval, lastPlayed: Date?, since: Date) {
+ self.duration = duration
+ self.lastPlayed = lastPlayed
+ self.since = since
+ }
+}
+
+/// Play time folded out of the recent-session list for one game. `afterExternal` is the part of it after
+/// the external value seen at `externalSince` (Steam's), which that value does not count yet.
public struct CarriedPlaytime: Codable, Equatable {
public var duration: TimeInterval
public var lastPlayed: Date
+ public var externalSince: Date?
+ public var afterExternal: TimeInterval
- public init(duration: TimeInterval, lastPlayed: Date) {
+ public init(duration: TimeInterval, lastPlayed: Date, externalSince: Date? = nil, afterExternal: TimeInterval = 0) {
self.duration = duration
self.lastPlayed = lastPlayed
+ self.externalSince = externalSince
+ self.afterExternal = afterExternal
+ }
+
+ private enum CodingKeys: String, CodingKey { case duration, lastPlayed, externalSince, afterExternal }
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ duration = try c.decode(TimeInterval.self, forKey: .duration)
+ lastPlayed = try c.decode(Date.self, forKey: .lastPlayed)
+ externalSince = try c.decodeIfPresent(Date.self, forKey: .externalSince)
+ afterExternal = try c.decodeIfPresent(TimeInterval.self, forKey: .afterExternal) ?? 0
}
}
diff --git a/Sources/NXLibraryCore/Services/SaveFileIO.swift b/Sources/NXLibraryCore/Services/SaveFileIO.swift
index 64c8213a..0051ac92 100644
--- a/Sources/NXLibraryCore/Services/SaveFileIO.swift
+++ b/Sources/NXLibraryCore/Services/SaveFileIO.swift
@@ -72,7 +72,7 @@ extension SaveFiles {
}
return portableAttributes(result)
}
- static func inventory(_ directory: URL, slot: SaveSlot) throws -> [SaveInventoryEntry] {
+ static func inventory(_ directory: URL, slot: SaveSlot, componentRoot: Bool = true) throws -> [SaveInventoryEntry] {
try safePath(directory)
guard exists(directory) else { return [] }
var entries: [SaveInventoryEntry] = []
@@ -82,6 +82,10 @@ extension SaveFiles {
guard lstat(url.path, &st) == 0 else { throw SaveFailure.changed }
let kind = st.st_mode & S_IFMT
guard kind == S_IFDIR || kind == S_IFREG else { throw SaveFailure.unsafePath }
+ if relative.isEmpty && componentRoot {
+ guard (kind == S_IFDIR) == slot.isDirectory else { throw SaveFailure.unsafePath }
+ if slot == .users, st.st_size > 64 * 1024 { throw SaveFailure.invalidSnapshot }
+ }
guard relative.isEmpty || validRelative(relative) else { throw SaveFailure.unsafePath }
var digest = ""
if kind == S_IFREG {
@@ -101,7 +105,6 @@ extension SaveFiles {
}
}
try visit(directory, relative: "")
- guard entries.first?.isDirectory == true else { throw SaveFailure.unsafePath }
return entries
}
static func inventory(_ location: SaveLocation) throws -> [SaveInventoryEntry] {
diff --git a/Sources/NXLibraryCore/Services/SaveRestorePreview.swift b/Sources/NXLibraryCore/Services/SaveRestorePreview.swift
index cd751426..76d9cbd4 100644
--- a/Sources/NXLibraryCore/Services/SaveRestorePreview.swift
+++ b/Sources/NXLibraryCore/Services/SaveRestorePreview.swift
@@ -13,7 +13,7 @@ extension SaveSnapshotStore {
do {
let source = try directory(snapshotID: snapshot.id, titleID: location.titleID)
for slot in SaveSlot.allCases where snapshot.presentSlots.contains(slot) {
- let name = slot == .account ? "save" : "save_device"
+ let name = slot.fileName
try io.copy(source.appendingPathComponent(name), staging.appendingPathComponent(name))
}
try verifyContents(snapshot, directory: staging)
diff --git a/Sources/NXLibraryCore/Services/SaveSnapshotStore.swift b/Sources/NXLibraryCore/Services/SaveSnapshotStore.swift
index a727b959..9b36a0f6 100644
--- a/Sources/NXLibraryCore/Services/SaveSnapshotStore.swift
+++ b/Sources/NXLibraryCore/Services/SaveSnapshotStore.swift
@@ -54,10 +54,12 @@ public final class SaveSnapshotStore {
defer { try? SaveFiles.remove(temp) }
let slots = Set(before.map(\.slot))
for slot in SaveSlot.allCases where slots.contains(slot) {
- try io.copy(location.directory(slot), temp.appendingPathComponent(slot == .account ? "save" : "save_device"))
+ try io.copy(location.directory(slot), temp.appendingPathComponent(slot.fileName))
}
guard try SaveFiles.inventory(location) == before else { throw SaveFailure.changed }
- let snapshot = SaveSnapshot(id: id, identity: identity, created: created, reason: reason, presentSlots: slots, entries: before)
+ let version = slots.allSatisfy(\.isLegacy) ? 1 : 2
+ let snapshot = SaveSnapshot(schemaVersion: version, id: id, identity: identity, created: created,
+ reason: reason, presentSlots: slots, entries: before)
try verifyContents(snapshot, directory: temp)
try SaveFiles.syncTree(temp)
try SaveFiles.durableWrite(snapshot, to: temp.appendingPathComponent("manifest.json"))
@@ -92,7 +94,7 @@ public final class SaveSnapshotStore {
try SaveFiles.safePath(file)
guard let data = try? SaveFiles.readRegular(file, limit: 32 * 1024 * 1024),
let snapshot = try? JSONDecoder().decode(SaveSnapshot.self, from: data),
- snapshot.schemaVersion == 1, snapshot.identity.titleID == titleID.uppercased(),
+ snapshot.hasSupportedSchema, snapshot.identity.titleID == titleID.uppercased(),
snapshot.entries.allSatisfy({ ($0.path.isEmpty || SaveFiles.validRelative($0.path)) && $0.byteCount >= 0 && $0.byteCount < Int64.max / Int64(max(1, snapshot.entries.count)) }) else { throw SaveFailure.invalidSnapshot }
// Read older schema-1 backups portably too: provenance is assigned by macOS to a copy.
var portable = snapshot
@@ -102,12 +104,13 @@ public final class SaveSnapshotStore {
internal func verifyContents(_ snapshot: SaveSnapshot, directory: URL) throws {
var actual: [SaveInventoryEntry] = []
for slot in SaveSlot.allCases {
- actual += try SaveFiles.inventory(directory.appendingPathComponent(slot == .account ? "save" : "save_device"), slot: slot)
+ actual += try SaveFiles.inventory(directory.appendingPathComponent(slot.fileName), slot: slot)
}
guard actual == snapshot.entries, Set(actual.map(\.slot)) == snapshot.presentSlots else { throw SaveFailure.invalidSnapshot }
}
public func currentInventory(location: SaveLocation) throws -> [SaveInventoryEntry] { try SaveFiles.inventory(location) }
public func stageImport(source: URL, slot: SaveSlot, location: SaveLocation) throws -> SaveImportPreview {
+ guard slot.isLegacy else { throw SaveFailure.unsafePath }
try location.validate()
try SaveFiles.safePath(source)
let source = try RyujinxSaveFolder.payload(for: source, titleID: location.titleID)
@@ -133,6 +136,7 @@ public final class SaveSnapshotStore {
try SaveFiles.inventory(location) == preview.currentEntries else { throw SaveFailure.changed }
}
private func validateStaging(_ preview: SaveImportPreview, location: SaveLocation) throws {
+ guard preview.slot.isLegacy else { throw SaveFailure.unsafePath }
guard preview.staging.path == location.root.appendingPathComponent(".nxlibrary-save-preview-\(preview.id)").path else { throw SaveFailure.unsafePath }
try location.validate(); try SaveFiles.safePath(preview.staging)
}
diff --git a/Sources/NXLibraryCore/Services/SaveTransaction.swift b/Sources/NXLibraryCore/Services/SaveTransaction.swift
index 6bf69da2..8c55789f 100644
--- a/Sources/NXLibraryCore/Services/SaveTransaction.swift
+++ b/Sources/NXLibraryCore/Services/SaveTransaction.swift
@@ -12,7 +12,29 @@ public final class SaveTransaction {
let titleID: String
let before: UUID
let after: [SaveInventoryEntry]
+ /// Missing in historical journals, which mutate the two legacy slots.
+ var mutatedSlots: Set?
+ /// Durable deletion intent: remaining staging entries must be a subset of these verified trees.
+ var cleanupArtifacts: [String: [SaveInventoryEntry]]? = nil
var committed: Bool
+
+ var observedSlots: [SaveSlot] { version == 1 ? SaveSlot.legacyCases : SaveSlot.allCases }
+ var mutationOrder: [SaveSlot] { observedSlots.filter { mutatedSlots?.contains($0) ?? true } }
+ var isValid: Bool {
+ guard version == 1 || version == 2, version == 1 || mutatedSlots != nil,
+ !mutationOrder.isEmpty else { return false }
+ let allowed = Set(observedSlots)
+ guard mutatedSlots?.isSubset(of: allowed) ?? true,
+ after.allSatisfy({ allowed.contains($0.slot) && ($0.path.isEmpty || SaveFiles.validRelative($0.path))
+ && $0.byteCount >= 0 && ($0.slot != .users || (!$0.isDirectory && $0.path.isEmpty && $0.byteCount <= 65536)) })
+ else { return false }
+ guard Set(after.map { $0.slot.rawValue + ":" + $0.path }).count == after.count else { return false }
+ for (name, entries) in cleanupArtifacts ?? [:] {
+ guard let slot = mutationOrder.first(where: { name == $0.rawValue || name == "rollback-" + $0.rawValue }),
+ entries.allSatisfy({ $0.slot == slot && ($0.path.isEmpty || SaveFiles.validRelative($0.path)) }) else { return false }
+ }
+ return true
+ }
}
public init(store: SaveSnapshotStore, isRunning: @escaping () -> Bool,
validateAccess: @escaping () throws -> Void = {}) {
@@ -34,9 +56,8 @@ public final class SaveTransaction {
public func importSave(_ preview: SaveImportPreview, location: SaveLocation, identity: SaveIdentity) throws -> SaveSnapshot {
try check(location)
try store.validate(preview, location: location)
- return try replace(location: location, identity: identity, reason: .beforeImport,
- desired: { slot in slot == preview.slot ? preview.staging : location.directory(slot) },
- revalidate: { try self.store.validate(preview, location: location) })
+ return try replace(location: location, identity: identity, reason: .beforeImport, slots: [preview.slot],
+ desired: { _ in preview.staging }, revalidate: { try self.store.validate(preview, location: location) })
}
@discardableResult
public func restore(_ snapshot: SaveSnapshot, location: SaveLocation, identity: SaveIdentity) throws -> SaveSnapshot {
@@ -50,22 +71,24 @@ public final class SaveTransaction {
try check(location)
guard identity.titleID == location.titleID else { throw SaveFailure.invalidSnapshot }
try store.validateRestore(preview, location: location)
- return try replace(location: location, identity: identity, reason: .beforeRestore,
- desired: { preview.staging.appendingPathComponent($0 == .account ? "save" : "save_device") },
+ let slots = preview.snapshot.schemaVersion == 1 ? SaveSlot.legacyCases : SaveSlot.allCases
+ return try replace(location: location, identity: identity, reason: .beforeRestore, slots: slots,
+ desired: { preview.staging.appendingPathComponent($0.fileName) },
revalidate: { try self.store.validateRestore(preview, location: location) })
}
- private func replace(location: SaveLocation, identity: SaveIdentity, reason: SaveSnapshotReason,
+ private func replace(location: SaveLocation, identity: SaveIdentity, reason: SaveSnapshotReason, slots: [SaveSlot],
desired: (SaveSlot) -> URL, revalidate: () throws -> Void) throws -> SaveSnapshot {
guard !Self.needsRecovery(location: location) else { throw SaveFailure.recoveryRequired }
guard !SaveFiles.exists(location.cloudPullJournal) else { throw SaveFailure.cloudPullPending }
try check(location)
let previous = try SaveFiles.inventory(location)
- let id = UUID(); let stage = staging(id, location)
+ let id = UUID(), stage = staging(id, location)
try SaveFiles.makeDirectory(stage)
var journalWritten = false
defer { if !journalWritten { try? SaveFiles.remove(stage) } }
var after: [SaveInventoryEntry] = []
for slot in SaveSlot.allCases {
+ guard slots.contains(slot) else { after += previous.filter { $0.slot == slot }; continue }
let source = desired(slot)
let entries = try SaveFiles.inventory(source, slot: slot)
after += entries
@@ -76,32 +99,45 @@ public final class SaveTransaction {
try SaveFiles.syncTree(next)
}
}
+ try SaveFiles.syncDirectory(stage)
try revalidate(); try check(location)
guard try SaveFiles.inventory(location) == previous else { throw SaveFailure.changed }
let safety = try store.create(location: location, identity: identity, reason: reason)
guard safety.entries == previous else { throw SaveFailure.changed }
try revalidate(); try check(location)
guard try SaveFiles.inventory(location) == previous else { throw SaveFailure.changed }
- var journal = Journal(id: id, titleID: location.titleID, before: safety.id, after: after, committed: false)
+ let version = previous.allSatisfy({ $0.slot.isLegacy }) && after.allSatisfy({ $0.slot.isLegacy })
+ && slots.allSatisfy(\.isLegacy) ? 1 : 2
+ var journal = Journal(version: version, id: id, titleID: location.titleID, before: safety.id,
+ after: after, mutatedSlots: Set(slots), committed: false)
try SaveFiles.durableWrite(journal, to: journalURL(location))
journalWritten = true
do {
try io.afterMutation("journal")
- for slot in SaveSlot.allCases {
+ for slot in journal.mutationOrder {
try check(location)
- try swap(stage.appendingPathComponent(slot.rawValue), into: location.directory(slot))
+ try io.afterMutation("before-" + slot.rawValue)
+ let next = stage.appendingPathComponent(slot.rawValue)
+ guard try SaveFiles.inventory(location.directory(slot), slot: slot) == previous.filter({ $0.slot == slot }),
+ try SaveFiles.inventory(next, slot: slot) == after.filter({ $0.slot == slot }) else { throw SaveFailure.changed }
+ try swap(next, into: location.directory(slot))
try SaveFiles.syncDirectory(location.root)
+ try SaveFiles.syncDirectory(stage)
+ // A writer holding an old inode may change it even after the path is exchanged.
+ guard try SaveFiles.inventory(next, slot: slot) == previous.filter({ $0.slot == slot }) else { throw SaveFailure.changed }
try io.afterMutation(slot.rawValue)
}
+ try check(location)
guard try SaveFiles.inventory(location) == after else { throw SaveFailure.recoveryRequired }
+ try validateArtifacts(journal, location, before: previous)
journal.committed = true
try SaveFiles.durableWrite(journal, to: journalURL(location))
try io.afterMutation("committed")
- try cleanup(journal, location)
+ try cleanup(journal, location, before: previous, expected: after)
return safety
} catch { throw SaveFailure.recoveryRequired }
}
- /// Moves a next tree in, retaining the old one in staging. An absent next tree means restore absence.
+ /// Moves a next tree/file in, retaining the old one in staging. Absence restores absence.
private func swap(_ next: URL, into destination: URL) throws {
try SaveFiles.safePath(next); try SaveFiles.safePath(destination)
if SaveFiles.exists(next) && SaveFiles.exists(destination) {
@@ -112,6 +148,26 @@ public final class SaveTransaction {
try FileManager.default.moveItem(at: destination, to: next)
}
}
+ private func observedInventory(_ journal: Journal, _ location: SaveLocation) throws -> [SaveInventoryEntry] {
+ try location.validate()
+ return try journal.observedSlots.flatMap { try SaveFiles.inventory(location.directory($0), slot: $0) }
+ }
+ /// Never delete unrecognized or externally changed data from a managed transaction folder.
+ private func validateArtifacts(_ journal: Journal, _ location: SaveLocation, before: [SaveInventoryEntry]) throws {
+ let stage = staging(journal.id, location)
+ try SaveFiles.safePath(stage)
+ guard SaveFiles.exists(stage) else { return }
+ let portableAfter = journal.after.map(\.portable)
+ for child in try FileManager.default.contentsOfDirectory(at: stage, includingPropertiesForKeys: nil) {
+ guard let slot = journal.mutationOrder.first(where: {
+ child.lastPathComponent == $0.rawValue || child.lastPathComponent == "rollback-" + $0.rawValue
+ }) else { throw SaveFailure.recoveryRequired }
+ let entries = try SaveFiles.inventory(child, slot: slot)
+ guard entries == before.filter({ $0.slot == slot }) || entries == portableAfter.filter({ $0.slot == slot }) else {
+ throw SaveFailure.recoveryRequired
+ }
+ }
+ }
public func recover(location: SaveLocation) throws {
guard Self.needsRecovery(location: location) else { return }
// Recovery is local rollback, not a new import: cloud settings do not prevent it.
@@ -119,43 +175,118 @@ public final class SaveTransaction {
try location.validate()
let file = journalURL(location)
try SaveFiles.safePath(file)
- guard let data = try? SaveFiles.readRegular(file, limit: 32 * 1024 * 1024),
- let journal = try? JSONDecoder().decode(Journal.self, from: data), journal.version == 1,
- journal.titleID == location.titleID,
- journal.after.allSatisfy({ $0.path.isEmpty || SaveFiles.validRelative($0.path) }) else { throw SaveFailure.recoveryRequired }
+ guard let data = try? SaveFiles.readRegular(file, limit: 96 * 1024 * 1024),
+ let journal = try? JSONDecoder().decode(Journal.self, from: data), journal.isValid,
+ journal.titleID == location.titleID else { throw SaveFailure.recoveryRequired }
let original = try store.verify(snapshotID: journal.before, titleID: location.titleID)
+ guard journal.version != 1 || original.schemaVersion == 1 else { throw SaveFailure.recoveryRequired }
let expectedAfter = journal.after.map(\.portable)
- if journal.committed {
- guard try SaveFiles.inventory(location) == expectedAfter else { throw SaveFailure.recoveryRequired }
- } else {
+ let before = original.entries.filter { journal.observedSlots.contains($0.slot) }
+ if journal.cleanupArtifacts != nil || journal.committed {
+ try cleanup(journal, location, before: before, expected: journal.committed ? expectedAfter : before)
+ return
+ }
+ if try observedInventory(journal, location) == before {
+ try cleanup(journal, location, before: before, expected: before)
+ return
+ }
+ try validateArtifacts(journal, location, before: before)
+ do {
let backup = try store.directory(snapshotID: journal.before, titleID: location.titleID)
let stage = staging(journal.id, location)
try SaveFiles.makeDirectory(stage)
- for slot in SaveSlot.allCases {
+ for slot in journal.mutationOrder {
guard !isRunning() else { throw SaveFailure.running }
let current = try SaveFiles.inventory(location.directory(slot), slot: slot)
- let before = original.entries.filter { $0.slot == slot }
+ let previous = before.filter { $0.slot == slot }
let after = expectedAfter.filter { $0.slot == slot }
- if current == before { continue }
- // Never destroy a save modified outside this transaction.
+ if current == previous { continue }
guard current == after else { throw SaveFailure.recoveryRequired }
- let rollback = stage.appendingPathComponent("rollback-\(slot.rawValue)")
+ let rollback = stage.appendingPathComponent("rollback-" + slot.rawValue)
+ try validateArtifacts(journal, location, before: before)
try SaveFiles.remove(rollback)
if original.presentSlots.contains(slot) {
- try io.copy(backup.appendingPathComponent(slot == .account ? "save" : "save_device"), rollback)
- guard try SaveFiles.inventory(rollback, slot: slot) == before else { throw SaveFailure.invalidSnapshot }
+ try io.copy(backup.appendingPathComponent(slot.fileName), rollback)
+ guard try SaveFiles.inventory(rollback, slot: slot) == previous else { throw SaveFailure.invalidSnapshot }
try SaveFiles.syncTree(rollback)
}
try location.validate()
+ guard try SaveFiles.inventory(location.directory(slot), slot: slot) == after else { throw SaveFailure.recoveryRequired }
try swap(rollback, into: location.directory(slot))
try SaveFiles.syncDirectory(location.root)
+ try SaveFiles.syncDirectory(stage)
+ guard try SaveFiles.inventory(rollback, slot: slot) == after else { throw SaveFailure.recoveryRequired }
+ try io.afterMutation("recovery-" + slot.rawValue)
}
- guard try SaveFiles.inventory(location) == original.entries else { throw SaveFailure.recoveryRequired }
+ guard try observedInventory(journal, location) == before else { throw SaveFailure.recoveryRequired }
+ }
+ try cleanup(journal, location, before: before, expected: before)
+ }
+
+ private func isSubset(_ actual: [SaveInventoryEntry], of expected: [SaveInventoryEntry]) -> Bool {
+ var byPath: [String: SaveInventoryEntry] = [:]
+ for entry in expected.map(\.portable) {
+ guard byPath.updateValue(entry, forKey: entry.path) == nil else { return false }
}
- try cleanup(journal, location)
+ return actual.allSatisfy { byPath[$0.path] == $0 }
}
- private func cleanup(_ journal: Journal, _ location: SaveLocation) throws {
- try SaveFiles.remove(staging(journal.id, location))
+
+ private func cleanupRecord(_ journal: Journal, _ location: SaveLocation, before: [SaveInventoryEntry]) throws -> [String: [SaveInventoryEntry]] {
+ let stage = staging(journal.id, location)
+ try SaveFiles.safePath(stage)
+ guard SaveFiles.exists(stage) else { return [:] }
+ var records: [String: [SaveInventoryEntry]] = [:]
+ for child in try FileManager.default.contentsOfDirectory(at: stage, includingPropertiesForKeys: nil) {
+ guard let slot = journal.mutationOrder.first(where: {
+ child.lastPathComponent == $0.rawValue || child.lastPathComponent == "rollback-" + $0.rawValue
+ }) else { throw SaveFailure.recoveryRequired }
+ let actual = try SaveFiles.inventory(child, slot: slot)
+ let candidates = [before.filter { $0.slot == slot }, journal.after.filter { $0.slot == slot }.map(\.portable)]
+ guard let known = candidates.first(where: { isSubset(actual, of: $0) }) else { throw SaveFailure.recoveryRequired }
+ records[child.lastPathComponent] = known
+ }
+ return records
+ }
+
+ private func removeCleanupArtifacts(_ journal: Journal, _ location: SaveLocation) throws {
+ let stage = staging(journal.id, location)
+ try SaveFiles.safePath(stage)
+ guard SaveFiles.exists(stage), let records = journal.cleanupArtifacts else { return }
+ let children = try FileManager.default.contentsOfDirectory(at: stage, includingPropertiesForKeys: nil)
+ guard children.allSatisfy({ records[$0.lastPathComponent] != nil }) else { throw SaveFailure.recoveryRequired }
+ for child in children {
+ let expected = records[child.lastPathComponent]!
+ guard let slot = journal.mutationOrder.first(where: { child.lastPathComponent == $0.rawValue || child.lastPathComponent == "rollback-" + $0.rawValue }),
+ isSubset(try SaveFiles.inventory(child, slot: slot), of: expected) else { throw SaveFailure.recoveryRequired }
+ // Reverse preorder: children before their parent. unlink/rmdir never recursively delete surprises.
+ for entry in expected.reversed() {
+ guard !isRunning() else { throw SaveFailure.running }
+ let url = entry.path.isEmpty ? child : child.appendingPathComponent(entry.path)
+ try SaveFiles.safePath(url)
+ guard SaveFiles.exists(url) else { continue }
+ var actual = try SaveFiles.inventory(url, slot: slot, componentRoot: false)
+ guard actual.count == 1 else { throw SaveFailure.recoveryRequired }
+ actual[0].path = entry.path
+ guard actual[0] == entry.portable else { throw SaveFailure.recoveryRequired }
+ let result = entry.isDirectory ? rmdir(url.path) : unlink(url.path)
+ guard result == 0 else { throw SaveFailure.recoveryRequired }
+ try io.afterMutation("cleanup-item")
+ }
+ }
+ guard rmdir(stage.path) == 0 else { throw SaveFailure.recoveryRequired }
+ try io.afterMutation("cleanup-stage")
+ }
+
+ private func cleanup(_ journal: Journal, _ location: SaveLocation, before: [SaveInventoryEntry], expected: [SaveInventoryEntry]) throws {
+ guard !isRunning(), try observedInventory(journal, location) == expected else { throw SaveFailure.recoveryRequired }
+ var cleaning = journal
+ if cleaning.cleanupArtifacts == nil {
+ cleaning.cleanupArtifacts = try cleanupRecord(journal, location, before: before)
+ try SaveFiles.durableWrite(cleaning, to: journalURL(location))
+ try io.afterMutation("cleanup")
+ }
+ try removeCleanupArtifacts(cleaning, location)
+ try SaveFiles.syncDirectory(location.root)
try SaveFiles.remove(journalURL(location))
try SaveFiles.syncDirectory(location.root)
}
@@ -164,16 +295,17 @@ public final class SaveTransaction {
extension SaveFiles {
static func syncTree(_ directory: URL) throws {
try safePath(directory)
- let children = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.isDirectoryKey])
- for child in children {
- if try child.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true { try syncTree(child) }
- else {
- let fd = open(child.path, O_RDONLY | O_NOFOLLOW)
- guard fd >= 0 else { throw SaveFailure.io("Could not persist the staged save.") }
- let result = fsync(fd); close(fd)
- guard result == 0 else { throw SaveFailure.io("Could not persist the staged save.") }
- }
+ var info = stat()
+ guard lstat(directory.path, &info) == 0 else { throw SaveFailure.changed }
+ if (info.st_mode & S_IFMT) == S_IFREG {
+ let fd = open(directory.path, O_RDONLY | O_NOFOLLOW)
+ guard fd >= 0 else { throw SaveFailure.io("Could not persist the staged save.") }
+ defer { close(fd) }
+ guard fsync(fd) == 0 else { throw SaveFailure.io("Could not persist the staged save.") }
+ } else {
+ guard (info.st_mode & S_IFMT) == S_IFDIR else { throw SaveFailure.unsafePath }
+ for child in try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) { try syncTree(child) }
+ try syncDirectory(directory)
}
- try syncDirectory(directory)
}
}
diff --git a/Sources/NXLibraryCore/Services/ScreenshotFallback.swift b/Sources/NXLibraryCore/Services/ScreenshotFallback.swift
index bb6b413d..7f76cd0f 100644
--- a/Sources/NXLibraryCore/Services/ScreenshotFallback.swift
+++ b/Sources/NXLibraryCore/Services/ScreenshotFallback.swift
@@ -19,8 +19,7 @@ public struct ScreenshotFallbackStore: Sendable {
public let directory: URL
- public init(directory: URL = FileManager.default.homeDirectoryForCurrentUser
- .appendingPathComponent("Library/Application Support/NXLibrary/metadata/launchbox-screenshots")) {
+ public init(directory: URL = AppData.supportRoot.appendingPathComponent("metadata/launchbox-screenshots")) {
self.directory = directory
}
diff --git a/Sources/NXLibraryCore/Services/SeleneImporter.swift b/Sources/NXLibraryCore/Services/SeleneImporter.swift
index 496b85f9..13f7b12d 100644
--- a/Sources/NXLibraryCore/Services/SeleneImporter.swift
+++ b/Sources/NXLibraryCore/Services/SeleneImporter.swift
@@ -70,8 +70,7 @@ public struct SeleneImporter {
"activation", "CloseAdditionalView", "Alert"]
public static var defaultDestination: URL {
- URL(fileURLWithPath: NSHomeDirectory())
- .appendingPathComponent("Library/Application Support/NXLibrary/SeleneImports")
+ AppData.supportRoot.appendingPathComponent("SeleneImports")
}
public let destination: URL
diff --git a/Sources/NXLibraryCore/Services/SourceCatalog.swift b/Sources/NXLibraryCore/Services/SourceCatalog.swift
index a962f7d3..4f6bb9ec 100644
--- a/Sources/NXLibraryCore/Services/SourceCatalog.swift
+++ b/Sources/NXLibraryCore/Services/SourceCatalog.swift
@@ -9,10 +9,11 @@ public struct DetectedSource: Identifiable, Equatable {
public var sizeBytes: Int64
public var layout: SourceLayout
public var requiresTitleSelection: Bool
+ public var nupProgram: NUPProgramSelection?
public init(id: UUID = UUID(), url: URL, kind: SourceKind,
titleId: UInt64, version: Int? = nil, sizeBytes: Int64, layout: SourceLayout = .package,
- requiresTitleSelection: Bool = false) {
+ requiresTitleSelection: Bool = false, nupProgram: NUPProgramSelection? = nil) {
self.id = id
self.url = url
self.kind = kind
@@ -21,6 +22,7 @@ public struct DetectedSource: Identifiable, Equatable {
self.sizeBytes = sizeBytes
self.layout = layout
self.requiresTitleSelection = requiresTitleSelection
+ self.nupProgram = nupProgram
}
}
diff --git a/Sources/NXLibraryCore/Services/Steam/InstallationDirectorySnapshot.swift b/Sources/NXLibraryCore/Services/Steam/InstallationDirectorySnapshot.swift
new file mode 100644
index 00000000..cf74591f
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/InstallationDirectorySnapshot.swift
@@ -0,0 +1,50 @@
+import Foundation
+import Darwin
+
+typealias InstallationDirectoryReader = @Sendable (URL, Int, () -> Bool) throws -> InstallationDirectorySnapshot
+
+/// One directory-read boundary shared by library inventory and app discovery.
+struct InstallationDirectorySnapshot: Sendable {
+ let entries: [URL]
+ let isComplete: Bool
+ let observation: InstallationFileObservation
+
+ static func read(at url: URL, maximumEntries: Int, cancelled: () -> Bool) throws -> Self {
+ if cancelled() { throw CancellationError() }
+ let fd = Darwin.open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK | O_DIRECTORY)
+ guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
+ guard let directory = fdopendir(fd) else {
+ let failure = errno
+ Darwin.close(fd)
+ throw POSIXError(POSIXErrorCode(rawValue: failure) ?? .EIO)
+ }
+ defer { closedir(directory) }
+ let observation = try InstallationFileObservation.capture(fileDescriptor: fd, url: url, expectedType: mode_t(S_IFDIR))
+ let budget = min(max(0, maximumEntries), 10_000)
+ var entries: [URL] = []
+ var examined = 0
+ var complete = true
+ while true {
+ if cancelled() { throw CancellationError() }
+ errno = 0
+ guard let entry = readdir(directory) else {
+ guard errno == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
+ break
+ }
+ let count = Int(entry.pointee.d_namlen)
+ let name = withUnsafePointer(to: &entry.pointee.d_name) { pointer in
+ pointer.withMemoryRebound(to: UInt8.self, capacity: count) {
+ String(bytes: UnsafeBufferPointer(start: $0, count: count), encoding: .utf8)
+ }
+ }
+ guard let name, !name.isEmpty else { throw InstallationFileReadError.invalidText }
+ if name == "." || name == ".." { continue }
+ guard examined < budget else { complete = false; break }
+ examined += 1
+ if name.hasPrefix(".") { continue }
+ entries.append(url.appendingPathComponent(name))
+ }
+ try observation.verifyUnchanged()
+ return Self(entries: entries, isComplete: complete, observation: observation)
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/InstallationFileSnapshot.swift b/Sources/NXLibraryCore/Services/Steam/InstallationFileSnapshot.swift
new file mode 100644
index 00000000..ae0d5de9
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/InstallationFileSnapshot.swift
@@ -0,0 +1,101 @@
+import Foundation
+import Darwin
+
+enum InstallationFileReadError: Error { case tooLarge, unsafeFile, sourceChanged, invalidText }
+
+/// Retain only this small identity after parsing, not all source-file contents.
+struct InstallationFileObservation: Equatable, Sendable {
+ let url: URL
+ private let identity: Identity?
+ private let fileType: mode_t
+
+ fileprivate struct Identity: Equatable, Sendable {
+ let device: Int32
+ let inode: UInt64
+ let size: Int64
+ let modifiedSeconds: Int
+ let modifiedNanoseconds: Int
+ let changedSeconds: Int
+ let changedNanoseconds: Int
+
+ init(_ status: stat) {
+ device = status.st_dev
+ inode = status.st_ino
+ size = status.st_size
+ modifiedSeconds = status.st_mtimespec.tv_sec
+ modifiedNanoseconds = status.st_mtimespec.tv_nsec
+ changedSeconds = status.st_ctimespec.tv_sec
+ changedNanoseconds = status.st_ctimespec.tv_nsec
+ }
+ }
+
+ private init(url: URL, status: stat) {
+ self.url = url
+ identity = Identity(status)
+ fileType = status.st_mode & mode_t(S_IFMT)
+ }
+ private init(absentURL: URL) { url = absentURL; identity = nil; fileType = 0 }
+ var byteCount: Int64 { identity?.size ?? 0 }
+
+ static func capture(fileDescriptor: Int32, url: URL, expectedType: mode_t = mode_t(S_IFREG)) throws -> Self {
+ var status = stat()
+ guard fstat(fileDescriptor, &status) == 0, status.st_mode & mode_t(S_IFMT) == expectedType else {
+ throw InstallationFileReadError.unsafeFile
+ }
+ return Self(url: url, status: status)
+ }
+
+ static func absent(at url: URL) throws -> Self {
+ var status = stat()
+ if lstat(url.path, &status) == 0 { throw InstallationFileReadError.sourceChanged }
+ guard errno == ENOENT else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
+ return Self(absentURL: url)
+ }
+
+ func verifyUnchanged() throws {
+ var current = stat()
+ let result = lstat(url.path, ¤t)
+ if identity == nil {
+ guard result == -1, errno == ENOENT else { throw InstallationFileReadError.sourceChanged }
+ return
+ }
+ guard result == 0, current.st_mode & mode_t(S_IFMT) == fileType, Identity(current) == identity else {
+ throw InstallationFileReadError.sourceChanged
+ }
+ }
+}
+
+/// Bounded read from a regular file with no final symlink following.
+/// The same identity is checked after the read and again before scan publication.
+struct InstallationFileSnapshot {
+ let data: Data
+ let observation: InstallationFileObservation
+
+ static func read(at url: URL, maximumBytes: Int) throws -> Self {
+ guard maximumBytes >= 0, maximumBytes < Int.max else { throw InstallationFileReadError.tooLarge }
+ let handle = try openReadOnly(url)
+ defer { try? handle.close() }
+ let observation = try InstallationFileObservation.capture(fileDescriptor: handle.fileDescriptor, url: url)
+ guard observation.byteCount >= 0, observation.byteCount <= Int64(maximumBytes) else { throw InstallationFileReadError.tooLarge }
+ let bytes = try handle.read(upToCount: maximumBytes + 1) ?? Data()
+ guard bytes.count <= maximumBytes else { throw InstallationFileReadError.tooLarge }
+ try observation.verifyUnchanged()
+ guard Int64(bytes.count) == observation.byteCount else { throw InstallationFileReadError.sourceChanged }
+ return Self(data: bytes, observation: observation)
+ }
+
+ static func openReadOnly(_ url: URL) throws -> FileHandle {
+ let fd = Darwin.open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK)
+ guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
+ return FileHandle(fileDescriptor: fd, closeOnDealloc: true)
+ }
+
+ func verifyUnchanged() throws { try observation.verifyUnchanged() }
+
+ var text: String {
+ get throws {
+ guard let result = String(data: data, encoding: .utf8) else { throw InstallationFileReadError.invalidText }
+ return result
+ }
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/NativeMacApplication.swift b/Sources/NXLibraryCore/Services/Steam/NativeMacApplication.swift
new file mode 100644
index 00000000..81abceff
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/NativeMacApplication.swift
@@ -0,0 +1,144 @@
+import Foundation
+
+public enum MacExecutableArchitecture: String, Hashable, Codable, Sendable { case arm64, x86_64 }
+
+public enum NativeMacApplicationError: Error, Equatable {
+ case invalidBundle, unsafePath, invalidExecutable, metadataTooLarge
+}
+
+/// Evidence about an installed app, independent of Steam and of any launch operation.
+public struct NativeMacApplication: Equatable, Sendable {
+ public let url: URL
+ public let executableURL: URL
+ public let bundleIdentifier: String?
+ public let name: String
+ public let architectures: Set
+ public let isDeclaredGame: Bool
+ let fileObservations: [InstallationFileObservation]
+
+ public static func inspect(at app: URL, within root: URL) throws -> Self {
+ let fm = FileManager.default
+ let root = root.resolvingSymlinksInPath().standardizedFileURL
+ let app = app.resolvingSymlinksInPath().standardizedFileURL
+ guard app.pathExtension.lowercased() == "app", isWithin(app, root: root) else {
+ throw NativeMacApplicationError.unsafePath
+ }
+ let plist = app.appendingPathComponent("Contents/Info.plist").resolvingSymlinksInPath().standardizedFileURL
+ guard isWithin(plist, root: app) else { throw NativeMacApplicationError.unsafePath }
+ let metadata: InstallationFileSnapshot
+ do { metadata = try InstallationFileSnapshot.read(at: plist, maximumBytes: 1024 * 1024) }
+ catch InstallationFileReadError.tooLarge { throw NativeMacApplicationError.metadataTooLarge }
+ let data = metadata.data
+ guard let info = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],
+ info["CFBundlePackageType"] as? String == "APPL",
+ info["LSRequiresIPhoneOS"] as? Bool != true,
+ let executable = info["CFBundleExecutable"] as? String,
+ !executable.isEmpty, executable != ".", executable != "..",
+ !executable.contains("/"), !executable.contains("\\") else { throw NativeMacApplicationError.invalidBundle }
+ if let platforms = info["CFBundleSupportedPlatforms"] as? [String],
+ !platforms.isEmpty, !platforms.contains("MacOSX") { throw NativeMacApplicationError.invalidBundle }
+ let executableURL = app.appendingPathComponent("Contents/MacOS").appendingPathComponent(executable)
+ .resolvingSymlinksInPath().standardizedFileURL
+ guard isWithin(executableURL, root: app) else { throw NativeMacApplicationError.unsafePath }
+ guard fm.isExecutableFile(atPath: executableURL.path) else { throw NativeMacApplicationError.invalidExecutable }
+ let executableEvidence = try MacExecutableHeader.inspect(at: executableURL)
+ let bundleID = (info["CFBundleIdentifier"] as? String).flatMap { $0.isEmpty ? nil : $0 }
+ let name = [info["CFBundleDisplayName"] as? String, info["CFBundleName"] as? String]
+ .compactMap { $0 }.first { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
+ ?? app.deletingPathExtension().lastPathComponent
+ let category = info["LSApplicationCategoryType"] as? String ?? ""
+ try metadata.verifyUnchanged()
+ return Self(url: app, executableURL: executableURL, bundleIdentifier: bundleID, name: name,
+ architectures: executableEvidence.architectures, isDeclaredGame: gameCategories.contains(category),
+ fileObservations: [metadata.observation, executableEvidence.observation])
+ }
+
+ static func isWithin(_ url: URL, root: URL) -> Bool {
+ url.path == root.path || url.path.hasPrefix(root.path.hasSuffix("/") ? root.path : root.path + "/")
+ }
+
+ private static let gameCategories: Set = Set([
+ "games", "action-games", "adventure-games", "arcade-games", "board-games", "card-games",
+ "casino-games", "dice-games", "educational-games", "family-games", "kids-games", "music-games",
+ "puzzle-games", "racing-games", "role-playing-games", "simulation-games", "sports-games",
+ "strategy-games", "trivia-games", "word-games"
+ ].map { "public.app-category." + $0 })
+}
+
+/// Reads only bounded Mach-O headers and fat architecture tables, never executable contents.
+private enum MacExecutableHeader {
+ static func inspect(at url: URL) throws -> (architectures: Set, observation: InstallationFileObservation) {
+ let file = try InstallationFileSnapshot.openReadOnly(url)
+ defer { try? file.close() }
+ let observation = try InstallationFileObservation.capture(fileDescriptor: file.fileDescriptor, url: url)
+ let size = try file.seekToEnd()
+ let result = try architectures(file: file, size: size)
+ try observation.verifyUnchanged()
+ return (result, observation)
+ }
+
+ private static func architectures(file: FileHandle, size: UInt64) throws -> Set {
+ func read(_ offset: UInt64, _ count: Int) throws -> Data {
+ guard offset <= size, UInt64(count) <= size - offset else { throw NativeMacApplicationError.invalidExecutable }
+ try file.seek(toOffset: offset)
+ guard let bytes = try file.read(upToCount: count), bytes.count == count else {
+ throw NativeMacApplicationError.invalidExecutable
+ }
+ return bytes
+ }
+ let first = try read(0, 8)
+ let magic = word(first, 0, bigEndian: true)
+ let isFat64 = magic == 0xcafebabf || magic == 0xbfbafeca
+ let isFat = isFat64 || magic == 0xcafebabe || magic == 0xbebafeca
+ if !isFat { return [try thin(try read(0, 32), expectedCPU: nil)] }
+ let bigEndian = magic == 0xcafebabe || magic == 0xcafebabf
+ let count = Int(word(first, 4, bigEndian: bigEndian))
+ guard (1...64).contains(count) else { throw NativeMacApplicationError.invalidExecutable }
+ let stride = isFat64 ? 32 : 20
+ let table = try read(8, count * stride)
+ let tableEnd = UInt64(8 + count * stride)
+ var result: Set = []
+ for index in 0..= tableEnd, offset <= size, length >= 32, length <= size - offset else {
+ throw NativeMacApplicationError.invalidExecutable
+ }
+ if cpu == 0x01000007 || cpu == 0x0100000c {
+ result.insert(try thin(try read(offset, 32), expectedCPU: cpu))
+ }
+ }
+ guard !result.isEmpty else { throw NativeMacApplicationError.invalidExecutable }
+ return result
+ }
+
+ private static func thin(_ data: Data, expectedCPU: UInt32?) throws -> MacExecutableArchitecture {
+ let magic = word(data, 0, bigEndian: true)
+ guard magic == 0xcffaedfe || magic == 0xfeedfacf else { throw NativeMacApplicationError.invalidExecutable }
+ let bigEndian = magic == 0xfeedfacf
+ let cpu = word(data, 4, bigEndian: bigEndian)
+ guard word(data, 12, bigEndian: bigEndian) == 2, expectedCPU == nil || cpu == expectedCPU else {
+ throw NativeMacApplicationError.invalidExecutable
+ }
+ switch cpu {
+ case 0x01000007: return .x86_64
+ case 0x0100000c: return .arm64
+ default: throw NativeMacApplicationError.invalidExecutable
+ }
+ }
+
+ private static func word(_ data: Data, _ offset: Int, bigEndian: Bool) -> UInt32 {
+ let shifts = bigEndian ? [24, 16, 8, 0] : [0, 8, 16, 24]
+ return (0..<4).reduce(0) { $0 | UInt32(data[offset + $1]) << shifts[$1] }
+ }
+
+ private static func longWord(_ data: Data, _ offset: Int, bigEndian: Bool) -> UInt64 {
+ let first = UInt64(word(data, offset, bigEndian: bigEndian))
+ let second = UInt64(word(data, offset + 4, bigEndian: bigEndian))
+ return bigEndian ? (first << 32) | second : first | (second << 32)
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamAchievementRarity.swift b/Sources/NXLibraryCore/Services/Steam/SteamAchievementRarity.swift
new file mode 100644
index 00000000..dd8cbed4
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamAchievementRarity.swift
@@ -0,0 +1,60 @@
+import Foundation
+
+/// Steam's public achievement data that needs no key: how many players have each achievement
+/// (`GetGlobalAchievementPercentagesForApp`) and the icons on Steam's CDN. Fetched and cached by
+/// `SteamMetadataService.achievementPercents` and `.achievementIcon`.
+public enum SteamAchievementRarity {
+ static let host = "api.steampowered.com"
+ static let path = "/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/"
+ /// How long the percentages are reused before Steam is asked again.
+ public static let freshFor: TimeInterval = 86_400
+
+ public static func url(appID: UInt32) -> URL {
+ URL(string: "https://\(host)\(path)?gameid=\(appID)")!
+ }
+
+ /// `achievementpercentages.achievements[{name, percent}]`, the percent as a number or a numeric string.
+ public static func decode(_ data: Data) throws -> [String: Double] {
+ struct Body: Decodable {
+ struct Inner: Decodable { let achievements: [Entry] }
+ struct Entry: Decodable {
+ let name: String
+ let percent: Double
+ enum Keys: String, CodingKey { case name, percent }
+ init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: Keys.self)
+ name = try container.decode(String.self, forKey: .name)
+ if let number = try? container.decode(Double.self, forKey: .percent) {
+ percent = number
+ } else if let number = Double(try container.decode(String.self, forKey: .percent)) {
+ percent = number
+ } else {
+ throw DecodingError.dataCorruptedError(forKey: .percent, in: container, debugDescription: "percent")
+ }
+ }
+ }
+ let achievementpercentages: Inner
+ }
+ let entries = try JSONDecoder().decode(Body.self, from: data).achievementpercentages.achievements
+ // "nan" and "inf" parse as numbers but are no rarity; clamping would keep NaN and turn infinity into 100.
+ return Dictionary(entries.filter { $0.percent.isFinite }.map { ($0.name, min(max($0.percent, 0), 100)) },
+ uniquingKeysWith: { first, _ in first })
+ }
+
+ /// An icon's address on Steam's CDN, for a plain file name from Steam's schema (`.jpg`); anything else is refused.
+ /// Steam's community-assets host: the older `steamcommunity/public/images` path answers 404 for icons added
+ /// recently (17 of Crimson Desert's 82, 16 Nov 2026), and this one serves both those and older games' icons.
+ public static func iconURL(appID: UInt32, file: String) -> URL? {
+ let lower = file.lowercased()
+ guard file.count > 4, file.count <= 128, !file.contains("/"), !file.contains("\\"), !file.hasPrefix("."),
+ file.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "." || $0 == "_" || $0 == "-") }),
+ lower.hasSuffix(".jpg") || lower.hasSuffix(".png") else { return nil }
+ return SteamMetadata.safeImage(URL(string: "https://shared.akamai.steamstatic.com/community_assets/images/apps/\(appID)/\(file)"))
+ }
+}
+
+/// The percentages as cached on disk.
+struct SteamAchievementPercentsCache: Codable {
+ let fetchedAt: Date
+ let percents: [String: Double]
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamAchievementReader.swift b/Sources/NXLibraryCore/Services/Steam/SteamAchievementReader.swift
new file mode 100644
index 00000000..8f57a8e1
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamAchievementReader.swift
@@ -0,0 +1,94 @@
+import Foundation
+
+/// One Steam achievement as this Mac's Steam cache knows it, for the current account.
+public struct SteamAchievement: Equatable, Sendable {
+ /// Steam's API name (`ACH_0039`), the key for its rarity.
+ public let apiName: String
+ public let name: String
+ public let description: String
+ public let hidden: Bool
+ /// File names on Steam's CDN (`.jpg`), color and gray.
+ public let icon: String?
+ public let grayIcon: String?
+ public let unlockedAt: Date?
+
+ public init(apiName: String, name: String, description: String, hidden: Bool, icon: String?, grayIcon: String?, unlockedAt: Date?) {
+ self.apiName = apiName; self.name = name; self.description = description; self.hidden = hidden
+ self.icon = icon; self.grayIcon = grayIcon; self.unlockedAt = unlockedAt
+ }
+}
+
+/// Reads a game's achievements from Steam's cache in `appcache/stats`: the schema (`UserGameStatsSchema_.bin`:
+/// names and descriptions in every language, hidden, icons) and the current account's stats
+/// (`UserGameStats__.bin`), of which only `AchievementTimes` is read. Nothing is written, logged
+/// or kept beyond the returned values. The format is Valve's and undocumented: anything unexpected throws.
+public enum SteamAchievementReader {
+ public static func schemaURL(root: URL, appID: UInt32) -> URL {
+ root.appendingPathComponent("appcache/stats/UserGameStatsSchema_\(appID).bin")
+ }
+
+ public static func statsURL(root: URL, account: UInt32, appID: UInt32) -> URL {
+ root.appendingPathComponent("appcache/stats/UserGameStats_\(account)_\(appID).bin")
+ }
+
+ /// The game's achievements, or nil when there is no schema, no signed-in account, or no stats file for that
+ /// account (it never loaded this game's stats here: the numbers would be wrong). Throws on unreadable files.
+ public static func read(root: URL, appID: UInt32, language: String) throws -> [SteamAchievement]? {
+ let schema = schemaURL(root: root, appID: appID)
+ guard FileManager.default.fileExists(atPath: schema.path),
+ let account = try SteamPlaytimeReader.accountID(root: root) else { return nil }
+ let stats = statsURL(root: root, account: account, appID: appID)
+ guard FileManager.default.fileExists(atPath: stats.path) else { return nil }
+ return try achievements(schema: SteamBinaryKeyValues.parse(data(at: schema)),
+ stats: SteamBinaryKeyValues.parse(data(at: stats)), appID: appID, language: language)
+ }
+
+ static func achievements(schema: [KeyValuesEntry], stats: [KeyValuesEntry], appID: UInt32, language: String) throws -> [SteamAchievement] {
+ let times = unlockTimes(stats)
+ guard let game = schema.firstObject(for: "\(appID)"), let statList = game.firstObject(for: "stats") else { return [] }
+ var result: [(stat: Int, bit: Int, achievement: SteamAchievement)] = []
+ for stat in statList {
+ guard case .object(let statFields) = stat.value, let bits = statFields.firstObject(for: "bits"),
+ let statNumber = Int(stat.key) else { continue }
+ for bit in bits {
+ guard case .object(let fields) = bit.value, let bitNumber = Int(bit.key),
+ let api = fields.firstString(for: "name") else { continue }
+ let display = fields.firstObject(for: "display") ?? []
+ let names = display.firstObject(for: "name") ?? []
+ let descs = display.firstObject(for: "desc") ?? []
+ let seconds = times[stat.key]?[bit.key].flatMap { Int64($0) } ?? 0
+ result.append((statNumber, bitNumber, SteamAchievement(
+ apiName: api,
+ name: localized(names, language) ?? api,
+ description: localized(descs, language) ?? "",
+ hidden: display.firstString(for: "hidden") == "1",
+ icon: display.firstString(for: "icon").flatMap { $0.isEmpty ? nil : $0 },
+ grayIcon: display.firstString(for: "icon_gray").flatMap { $0.isEmpty ? nil : $0 },
+ unlockedAt: seconds > 0 ? Date(timeIntervalSince1970: TimeInterval(seconds)) : nil)))
+ }
+ }
+ return result.sorted { ($0.stat, $0.bit) < ($1.stat, $1.bit) }.map(\.achievement)
+ }
+
+ /// `cache › › AchievementTimes › `; nothing else of the stats file is read.
+ private static func unlockTimes(_ stats: [KeyValuesEntry]) -> [String: [String: String]] {
+ guard let cache = stats.firstObject(for: "cache") else { return [:] }
+ var times: [String: [String: String]] = [:]
+ for stat in cache {
+ guard case .object(let fields) = stat.value, let list = fields.firstObject(for: "AchievementTimes") else { continue }
+ for entry in list { if case .string(let value) = entry.value { times[stat.key, default: [:]][entry.key] = value } }
+ }
+ return times
+ }
+
+ private static func localized(_ entries: [KeyValuesEntry], _ language: String) -> String? {
+ for key in [language, "english"] {
+ if let text = entries.firstString(for: key), !text.isEmpty { return text }
+ }
+ return nil
+ }
+
+ private static func data(at url: URL) throws -> Data {
+ try InstallationFileSnapshot.read(at: url, maximumBytes: SteamBinaryKeyValues.maximumBytes).data
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamArtworkRequest.swift b/Sources/NXLibraryCore/Services/Steam/SteamArtworkRequest.swift
new file mode 100644
index 00000000..39d8d3a3
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamArtworkRequest.swift
@@ -0,0 +1,55 @@
+import Foundation
+
+/// What a Steam game's tile asks for in one layout role. Personal picks always come
+/// first. A square then uses the installed app's own icon file, never the portrait
+/// cover; other roles have no local default and go to the Steam store art.
+public struct SteamArtworkRequest: Equatable {
+ public let game: CatalogGame
+ public let role: LibraryArtworkRole
+
+ public init(game: CatalogGame, role: LibraryArtworkRole) {
+ self.game = game; self.role = role
+ }
+
+ public var slot: ArtworkSlot { role.slot }
+ public var appID: UInt32? { game.steamGame?.appID }
+ /// The installed app this game launches, as the rest of the library reads it.
+ public var application: CatalogNativeApplication? {
+ game.steamGame?.firstAvailableInstallation?.primaryApplication
+ }
+
+ /// A square with no app to take the icon from (Steam still installing the game): it asks for an automatic
+ /// icon (`ArtworkStore.automaticSteamIcon`, LaunchBox's Square), never another image cropped to a square.
+ public var wantsAutomaticIcon: Bool { role == .square && application == nil }
+
+ /// A file on this Mac for the role: the player's pick, else (square only) the app's own icon.
+ public func localURL(picks: SteamPersonalizationStore) -> URL? {
+ if let picked = picks.url(titleID: game.personalizationReference.key, slot: slot),
+ FileManager.default.fileExists(atPath: picked.path) { return picked }
+ return automaticLocalURL
+ }
+
+ /// What the role shows with no pick: the app's own icon for the square, nothing else on this Mac.
+ public var automaticLocalURL: URL? {
+ guard role == .square, let application else { return nil }
+ return Self.bundleIcon(of: application.url)
+ }
+
+ /// `CFBundleIconFile` inside the bundle's own Resources folder. A name that points
+ /// elsewhere (a path, or a link that leaves the folder) is not followed.
+ static func bundleIcon(of app: URL) -> URL? {
+ let plist = app.appendingPathComponent("Contents/Info.plist")
+ guard let data = try? InstallationFileSnapshot.read(at: plist, maximumBytes: 1_048_576).data,
+ let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],
+ let name = (info["CFBundleIconFile"] as? String)?.trimmingCharacters(in: .whitespaces),
+ !name.isEmpty, !name.hasPrefix("."), name == URL(fileURLWithPath: name).lastPathComponent else { return nil }
+ let resources = app.appendingPathComponent("Contents/Resources")
+ let file = resources.appendingPathComponent(name.hasSuffix(".icns") ? name : name + ".icns")
+ let folder = resources.resolvingSymlinksInPath().standardizedFileURL.path + "/"
+ let resolved = file.resolvingSymlinksInPath().standardizedFileURL
+ var isDirectory: ObjCBool = false
+ guard resolved.path.hasPrefix(folder),
+ FileManager.default.fileExists(atPath: resolved.path, isDirectory: &isDirectory), !isDirectory.boolValue else { return nil }
+ return file
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamBackdropChoice.swift b/Sources/NXLibraryCore/Services/Steam/SteamBackdropChoice.swift
new file mode 100644
index 00000000..fd5ea6c9
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamBackdropChoice.swift
@@ -0,0 +1,74 @@
+import Foundation
+import ImageIO
+
+/// The automatic full-screen background of a Steam game. Steam's library hero is a wide banner
+/// (about 3:1) made for the top of Steam's own page: filling a 16:9 screen enlarges and crops it.
+/// So clean 16:9 art comes first: the stores' hero backgrounds found by the game's name (Xbox,
+/// GOG Galaxy, TheGamesDB fan art, each matched by `ArtworkNames`), then Steam's own first
+/// screenshot for the exact AppID, and the library hero only when nothing else fits.
+/// The player's own pick always comes before all of this, outside this type.
+public enum SteamBackdropChoice {
+ /// Screen-shaped: between 3:2 and 2:1, and wide enough not to be blown up on a large display.
+ public static func suits(width: Int, height: Int) -> Bool {
+ guard width >= 1280, height > 0 else { return false }
+ let ratio = Double(width) / Double(height)
+ return ratio >= 1.5 && ratio <= 2.0
+ }
+
+ /// Candidates in trial order. Only each store's own clean hero is taken (not titled heroes,
+ /// wide covers or their screenshots); Steam's art is the exact AppID's, never a name match.
+ public static func ordered(storeArt: [ArtworkCandidate], screenshots: [URL], libraryHero: URL?) -> [URL] {
+ func first(_ source: String) -> [URL] {
+ storeArt.first { $0.slot == .background && $0.source == source }.map { [$0.url] } ?? []
+ }
+ // LaunchBox's fan art for the game's computer entry, at full size: only one whose stated size suits a
+ // screen (a size it does not state is checked by `choose`).
+ let fanart = storeArt.first { candidate in
+ guard candidate.slot == .background, candidate.source.hasPrefix(LaunchBoxArt.fanartSource) else { return false }
+ guard let width = candidate.width, let height = candidate.height else { return true }
+ return suits(width: width, height: height)
+ }.map { $0.full ?? $0.url }
+ var urls = first("Xbox Store") + first("GOG") + first("TheGamesDB fan art") + (fanart.map { [$0] } ?? [])
+ urls += screenshots.prefix(1)
+ if let libraryHero { urls.append(libraryHero) }
+ var seen: Set = []
+ return urls.filter { seen.insert($0).inserted }
+ }
+
+ /// The first candidate whose image suits a full screen. When none does: `fallback` (Steam's library
+ /// banner, shown cropped), else the first candidate that loaded at all. Nothing is kept here: the caller
+ /// caches the choice.
+ public static func choose(_ urls: [URL], fallback: URL?, data: (URL) async -> Data?) async -> URL? {
+ var loaded: URL?
+ for url in urls {
+ guard !Task.isCancelled else { return nil }
+ guard let bytes = await data(url), let size = pixelSize(bytes) else { continue }
+ if suits(width: size.width, height: size.height) { return url }
+ if loaded == nil { loaded = url }
+ }
+ return fallback ?? loaded
+ }
+
+ /// Store art for the name, from the sources that publish clean 16:9 heroes, and LaunchBox's fan art for
+ /// the game's Mac or Windows entry (never a console's).
+ public static func storeArt(names: [String], client: ArtworkHTTPClient = URLSessionArtworkClient()) async -> [ArtworkCandidate] {
+ async let xbox = XboxStoreArt.find(names: names, client: client)
+ async let gog = GOGArt.find(names: names, client: client)
+ async let gamesDB = TheGamesDBArt.find(names: names, client: client)
+ async let launchBox = LaunchBoxArt.game(names: names, switch2: false, computer: true, client: client)
+ return await xbox + gog + gamesDB + (launchBox?.candidates ?? [])
+ }
+
+ /// Fetches a candidate for `choose`.
+ public static func download(_ url: URL, client: ArtworkHTTPClient = URLSessionArtworkClient()) async -> Data? {
+ await OnlineArtworkRequest.data(url, client: client)
+ }
+
+ static func pixelSize(_ data: Data) -> (width: Int, height: Int)? {
+ guard let source = CGImageSourceCreateWithData(data as CFData, nil),
+ let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
+ let width = properties[kCGImagePropertyPixelWidth] as? Int,
+ let height = properties[kCGImagePropertyPixelHeight] as? Int else { return nil }
+ return (width, height)
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamBackgroundLaunch.swift b/Sources/NXLibraryCore/Services/Steam/SteamBackgroundLaunch.swift
new file mode 100644
index 00000000..12d7f385
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamBackgroundLaunch.swift
@@ -0,0 +1,47 @@
+import Foundation
+
+/// The waiting screen and silent launch arguments for Steam games started from Play.
+/// A closed Steam can start with `-silent` and `-nofriendsui`. Past the wait's `patience` without the
+/// game, the launch screen makes way for Steam so the player can check sign-in, updates or a cloud conflict.
+public enum SteamBackgroundLaunch {
+ /// The wait with Steam already open.
+ public static let attentionDelay: TimeInterval = 15
+ /// The wait when Play has to start Steam, which takes a while before it even looks at the request.
+ public static let coldStartDelay: TimeInterval = 45
+
+ public static func patience(steamWasRunning: Bool) -> TimeInterval {
+ steamWasRunning ? attentionDelay : coldStartDelay
+ }
+
+ /// Arguments for a Steam that Play itself starts; an open Steam ignores launch arguments.
+ public static func arguments(enabled: Bool, steamRunning: Bool) -> [String] {
+ enabled && !steamRunning ? ["-silent", "-nofriendsui"] : []
+ }
+
+ /// The game is late: Steam is back in view and the head says to check it.
+ public static func mayNeedPlayer(phase: SteamPlayState.Phase, now: Date,
+ patience: TimeInterval = attentionDelay) -> Bool {
+ guard case .starting(let since) = phase else { return false }
+ return now.timeIntervalSince(since) > patience
+ }
+
+ /// Where the launch screen of a Steam game stands.
+ public enum LaunchScreen: Equatable, Sendable {
+ /// The game is on its way: the waiting screen stays up.
+ case waiting
+ /// The game's app is running: the screen leaves once its window is up.
+ case gameStarted
+ /// No game within the patience: the screen gives way to Steam.
+ case late
+ /// Play was cancelled or failed.
+ case over
+ }
+
+ public static func launchScreen(phase: SteamPlayState.Phase, now: Date, patience: TimeInterval) -> LaunchScreen {
+ switch phase {
+ case .starting(let since): return now.timeIntervalSince(since) > patience ? .late : .waiting
+ case .running: return .gameStarted
+ case .idle, .failed: return .over
+ }
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamBinaryKeyValues.swift b/Sources/NXLibraryCore/Services/Steam/SteamBinaryKeyValues.swift
new file mode 100644
index 00000000..90504c95
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamBinaryKeyValues.swift
@@ -0,0 +1,63 @@
+import Foundation
+
+/// Steam's binary KeyValues (the `appcache/stats/*.bin` files), read into the same entries as the text format.
+/// Each entry is a type byte, a NUL-terminated key and a value: 0 a subtree ending at 8, 1 a NUL-terminated string,
+/// 2, 4 and 6 an int32, 3 a float32, 7 a uint64, all little-endian. Numbers become their decimal text. Every level,
+/// the top one too, ends at 8 (Steam's files do). Anything else, or data that ends before that, is malformed.
+public enum SteamBinaryKeyValues {
+ public static let maximumBytes = 8 * 1024 * 1024
+
+ public static func parse(_ data: Data, maximumDepth: Int = 32, maximumEntries: Int = 200_000) throws -> [KeyValuesEntry] {
+ guard data.count <= maximumBytes else { throw KeyValuesError.limitExceeded }
+ var cursor = Cursor(bytes: Array(data), maximumDepth: maximumDepth, maximumEntries: maximumEntries)
+ return try cursor.object(depth: 0)
+ }
+
+ private struct Cursor {
+ let bytes: [UInt8]
+ let maximumDepth: Int
+ let maximumEntries: Int
+ var offset = 0
+ var count = 0
+
+ mutating func object(depth: Int) throws -> [KeyValuesEntry] {
+ guard depth <= maximumDepth else { throw KeyValuesError.limitExceeded }
+ var entries: [KeyValuesEntry] = []
+ while true {
+ // Every level, the top one too, ends with its terminator: data that stops before it is a file
+ // cut while Steam wrote it, never a shorter file (an empty stats file would read as no unlocks).
+ guard offset < bytes.count else { throw KeyValuesError.malformed }
+ let type = bytes[offset]
+ offset += 1
+ if type == 8 { return entries }
+ count += 1
+ guard count <= maximumEntries else { throw KeyValuesError.limitExceeded }
+ let key = try string()
+ let value: KeyValuesValue
+ switch type {
+ case 0: value = .object(try object(depth: depth + 1))
+ case 1: value = .string(try string())
+ case 2, 4, 6: value = .string(String(Int32(bitPattern: UInt32(try integer(4)))))
+ case 3: value = .string(String(Float(bitPattern: UInt32(try integer(4)))))
+ case 7: value = .string(String(try integer(8)))
+ default: throw KeyValuesError.malformed
+ }
+ entries.append(KeyValuesEntry(key: key, value: value))
+ }
+ }
+
+ private mutating func string() throws -> String {
+ guard let end = bytes[offset...].firstIndex(of: 0) else { throw KeyValuesError.malformed }
+ defer { offset = end + 1 }
+ return String(decoding: bytes[offset.. UInt64 {
+ guard offset + size <= bytes.count else { throw KeyValuesError.malformed }
+ var value: UInt64 = 0
+ for index in 0.. KeyValuesValue? {
+ matchingEntries(for: key).first?.value
+ }
+
+ /// The first matching string, skipping same-named values of another type (Steam achievement data).
+ func firstString(for key: String) -> String? {
+ for entry in matchingEntries(for: key) {
+ if case .string(let value) = entry.value { return value }
+ }
+ return nil
+ }
+
+ /// The first matching object, skipping same-named values of another type (Steam achievement data).
+ func firstObject(for key: String) -> [KeyValuesEntry]? {
+ for entry in matchingEntries(for: key) {
+ if case .object(let value) = entry.value { return value }
+ }
+ return nil
+ }
+
+ /// Missing is nil; duplicate keys of any type are ambiguous and fail.
+ func uniqueValue(for key: String) throws -> KeyValuesValue? {
+ var result: KeyValuesValue?
+ for entry in matchingEntries(for: key) {
+ guard result == nil else { throw KeyValuesError.duplicateField(key) }
+ result = entry.value
+ }
+ return result
+ }
+
+ /// A single string or nil when absent; duplicates and a value of another type fail.
+ func uniqueString(for key: String) throws -> String? {
+ guard let value = try uniqueValue(for: key) else { return nil }
+ guard case .string(let text) = value else { throw KeyValuesError.malformed }
+ return text
+ }
+
+ private func matchingEntries(for key: String) -> LazyFilterSequence<[KeyValuesEntry]> {
+ lazy.filter { $0.key.caseInsensitiveCompare(key) == .orderedSame }
+ }
+}
+
+/// The bounded text subset used by Steam's local indexes and manifests.
+/// Entries retain order and duplicates; unique lookups reject ambiguous fields.
+/// Directives never cause filesystem access: a `#` key is refused, or with `rejectsDirectives`
+/// off (for files that only hold data, such as `localconfig.vdf`) read as an ordinary key.
+public struct KeyValuesDocument: Sendable {
+ public let entries: [KeyValuesEntry]
+
+ public init(text: String, maximumDepth: Int = 32, maximumEntries: Int = 20_000, rejectsDirectives: Bool = true) throws {
+ guard text.utf8.count <= 8 * 1024 * 1024, maximumDepth >= 0, maximumEntries >= 0 else {
+ throw KeyValuesError.limitExceeded
+ }
+ var reader = Reader(bytes: Array(text.utf8), maximumDepth: maximumDepth, maximumEntries: maximumEntries,
+ rejectsDirectives: rejectsDirectives)
+ entries = try reader.object(depth: 0)
+ }
+
+ public func uniqueValue(for key: String) throws -> KeyValuesValue? {
+ try entries.uniqueValue(for: key)
+ }
+}
+
+private struct Reader {
+ let bytes: [UInt8]
+ let maximumDepth: Int
+ let maximumEntries: Int
+ let rejectsDirectives: Bool
+ private var offset = 0
+ private var count = 0
+
+ init(bytes: [UInt8], maximumDepth: Int, maximumEntries: Int, rejectsDirectives: Bool) {
+ self.bytes = bytes
+ self.maximumDepth = maximumDepth
+ self.maximumEntries = maximumEntries
+ self.rejectsDirectives = rejectsDirectives
+ if bytes.starts(with: [0xef, 0xbb, 0xbf]) { offset = 3 }
+ }
+
+ private enum Token { case scalar(String), open, close }
+
+ mutating func object(depth: Int) throws -> [KeyValuesEntry] {
+ var entries: [KeyValuesEntry] = []
+ while let token = try readToken() {
+ if case .close = token {
+ guard depth > 0 else { throw KeyValuesError.malformed }
+ return entries
+ }
+ guard case .scalar(let key) = token, !key.isEmpty else { throw KeyValuesError.malformed }
+ guard !rejectsDirectives || !key.hasPrefix("#") else { throw KeyValuesError.unsupportedDirective(key) }
+ guard count < maximumEntries else { throw KeyValuesError.limitExceeded }
+ count += 1
+ let value: KeyValuesValue
+ switch try readToken() {
+ case .scalar(let text): value = .string(text)
+ case .open:
+ guard depth < maximumDepth else { throw KeyValuesError.limitExceeded }
+ value = .object(try object(depth: depth + 1))
+ default: throw KeyValuesError.malformed
+ }
+ entries.append(KeyValuesEntry(key: key, value: value))
+ }
+ guard depth == 0 else { throw KeyValuesError.malformed }
+ return entries
+ }
+
+ private mutating func readToken() throws -> Token? {
+ skipTrivia()
+ guard offset < bytes.count else { return nil }
+ let first = bytes[offset]
+ offset += 1
+ if first == 123 { return .open }
+ if first == 125 { return .close }
+ if first == 34 { return .scalar(try quoted()) }
+ guard first != 0 else { throw KeyValuesError.malformed }
+ let start = offset - 1
+ while offset < bytes.count {
+ let byte = bytes[offset]
+ if isWhitespace(byte) || byte == 123 || byte == 125 || isComment { break }
+ guard byte != 0, byte != 34 else { throw KeyValuesError.malformed }
+ offset += 1
+ }
+ return .scalar(String(decoding: bytes[start.. String {
+ var result: [UInt8] = []
+ while offset < bytes.count {
+ let byte = bytes[offset]
+ offset += 1
+ if byte == 34 { return String(decoding: result, as: UTF8.self) }
+ guard byte != 0 else { throw KeyValuesError.malformed }
+ if byte == 92 {
+ guard offset < bytes.count else { throw KeyValuesError.malformed }
+ let escaped = bytes[offset]
+ offset += 1
+ switch escaped {
+ case 34, 92: result.append(escaped)
+ case 110: result.append(10)
+ case 116: result.append(9)
+ case 114: result.append(13)
+ default: throw KeyValuesError.malformed
+ }
+ } else { result.append(byte) }
+ }
+ throw KeyValuesError.malformed
+ }
+
+ private var isComment: Bool {
+ offset + 1 < bytes.count && bytes[offset] == 47 && bytes[offset + 1] == 47
+ }
+
+ private func isWhitespace(_ byte: UInt8) -> Bool { byte == 32 || (9...13).contains(byte) }
+
+ private mutating func skipTrivia() {
+ while offset < bytes.count {
+ if isWhitespace(bytes[offset]) { offset += 1 }
+ else if isComment {
+ while offset < bytes.count && bytes[offset] != 10 && bytes[offset] != 13 { offset += 1 }
+ } else { return }
+ }
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamLaunchQuestions.swift b/Sources/NXLibraryCore/Services/Steam/SteamLaunchQuestions.swift
new file mode 100644
index 00000000..d93cb5c5
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamLaunchQuestions.swift
@@ -0,0 +1,117 @@
+import Foundation
+
+/// A launch Steam holds until the player answers it: Steam writes `GameAction [AppID , …] : LaunchApp waiting
+/// for user response to ` to its console log when a launch stops on a question (the game is playing on
+/// another device, a cloud conflict, …), and a later `GameAction` line for that game once it moves on.
+/// `ShowInterstitials` is a generic startup step that can use the same wording during a cold start.
+/// Other questions count only after `grace`.
+/// Only `GameAction` lines are read; nothing is kept but which games wait and since when.
+public struct SteamLaunchQuestions: Equatable, Sendable {
+ public static let grace: TimeInterval = 1
+
+ /// Games whose launch waits on a question, with when NX Library first read it.
+ private var pending: [UInt32: Date] = [:]
+
+ public init() {}
+
+ /// Reads complete log lines, in order (`SteamConsoleLog` keeps unfinished lines). `now` is when read.
+ public mutating func read(_ text: String, now: Date) {
+ for line in text.split(separator: "\n") { take(line, now: now) }
+ }
+
+ /// Steam started a new log: what the old one said no longer holds.
+ public mutating func reset() {
+ pending = [:]
+ }
+
+ /// Steam has been waiting on the player for this game's launch for at least `grace`.
+ public func isAsking(appID: UInt32, now: Date) -> Bool {
+ guard let since = pending[appID] else { return false }
+ return now.timeIntervalSince(since) >= Self.grace
+ }
+
+ private static let action = "GameAction [AppID "
+ private static let question = "LaunchApp waiting for user response to "
+
+ private mutating func take(_ line: Substring, now: Date) {
+ guard let start = line.range(of: Self.action)?.upperBound,
+ let end = line[start...].firstIndex(where: { !$0.isNumber }),
+ let appID = UInt32(line[start../logs/console_log.txt`), read from where the last read stopped, whole lines only: a
+/// line Steam is still writing is read once it ends. Steam starts a new file each time it starts; a different or
+/// shorter file is read again from the top.
+public struct SteamConsoleLog: Sendable {
+ public let fileURL: URL
+ private var file: (number: UInt64, offset: UInt64)?
+
+ public init(steamRoot: URL) {
+ fileURL = steamRoot.appendingPathComponent("logs/console_log.txt")
+ }
+
+ /// The whole lines written since the last read, or nil without a log. `isNewFile` on the first read, for a new
+ /// file and when more than `limit` bytes arrived at once: only the last `limit` bytes are read then, from their
+ /// first whole line, and what came before is lost.
+ public mutating func readNew(limit: Int = 1 << 20) -> (text: String, isNewFile: Bool)? {
+ guard let attributes = try? FileManager.default.attributesOfItem(atPath: fileURL.path),
+ let size = (attributes[.size] as? NSNumber)?.uint64Value,
+ let number = (attributes[.systemFileNumber] as? NSNumber)?.uint64Value,
+ let handle = try? FileHandle(forReadingFrom: fileURL) else { return nil }
+ defer { try? handle.close() }
+ let limit = UInt64(max(limit, 1))
+ var start: UInt64 = 0
+ var isNewFile = true
+ if let file, file.number == number, file.offset <= size {
+ start = file.offset
+ isNewFile = false
+ }
+ var cut = false
+ if size - start > limit {
+ start = size - limit
+ cut = true
+ isNewFile = true
+ }
+ guard (try? handle.seek(toOffset: start)) != nil,
+ let data = try? handle.read(upToCount: Int(size - start)) ?? Data() else { return nil }
+ let newline = UInt8(ascii: "\n")
+ var lines = data[...]
+ // A cut first line starts after its newline.
+ if cut, start > 0 {
+ lines = lines.firstIndex(of: newline).map { lines[lines.index(after: $0)...] } ?? lines[lines.endIndex...]
+ }
+ let end = lines.lastIndex(of: newline).map { lines.index(after: $0) } ?? lines.startIndex
+ lines = lines[.. Bool {
+ if let new = log.readNew() {
+ if new.isNewFile { questions.reset() }
+ questions.read(new.text, now: now)
+ }
+ return questions.isAsking(appID: appID, now: now)
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamLibrarySource.swift b/Sources/NXLibraryCore/Services/Steam/SteamLibrarySource.swift
new file mode 100644
index 00000000..03511d78
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamLibrarySource.swift
@@ -0,0 +1,312 @@
+import Foundation
+
+public struct SteamScanLimits: Sendable {
+ public var maximumTextBytes = 8 * 1024 * 1024
+ public var maximumLibraries = 64
+ public var maximumManifests = 10_000
+ public var maximumDirectoriesPerInstall = 256
+ public var maximumInstallDepth = 4
+ public var maximumDirectoryEntries = 10_000
+ public static let standard = Self()
+ public init() {}
+}
+
+public struct SteamScanIssue: Equatable, Sendable {
+ public enum Reason: Equatable, Sendable {
+ case unavailableLibrary, invalidIndex, oversizedIndex, invalidManifest, oversizedManifest
+ case conflictingIdentity, unsafePath, directoryLimit, unreadableAppMetadata, libraryLimit, manifestLimit
+ }
+ public let url: URL
+ public let appID: UInt32?
+ public let reason: Reason
+}
+
+public struct SteamLibraryObservation: Equatable, Sendable {
+ public let root: URL
+ public let isReadable: Bool
+ public var isComplete: Bool
+}
+
+public struct SteamGameObservation: Equatable, Sendable {
+ /// `downloading`: Steam has not marked the game fully installed yet (StateFlags without bit 4); its folder is
+ /// not read, since Steam is still writing it.
+ public enum State: Equatable, Sendable { case nativeReady, requiresReview, unavailable, downloading }
+ public let appID: UInt32
+ public let name: String
+ public let installationURL: URL
+ public let libraryURL: URL
+ public let reportedSizeBytes: Int64?
+ public let buildID: String?
+ public let nativeApps: [NativeMacApplication]
+ public var state: State
+}
+
+public struct SteamLibrarySnapshot: Sendable {
+ public let libraries: [SteamLibraryObservation]
+ public let games: [SteamGameObservation]
+ public let issues: [SteamScanIssue]
+ /// A partial source must never authorize pruning unseen libraries or games.
+ public var isComplete: Bool { issues.isEmpty && libraries.allSatisfy(\.isComplete) }
+}
+
+public enum SteamSourceError: Error, Equatable { case sourceChanged }
+
+/// Reads only Steam's declared libraries. No scan starts until explicitly requested;
+/// this source owns no persistence, process launch, credentials or user opt-in.
+public struct SteamLibrarySource: Sendable {
+ private let root: URL
+ private let limits: SteamScanLimits
+ private let directoryReader: InstallationDirectoryReader
+ public init(root: URL, limits: SteamScanLimits = .standard) {
+ self.init(root: root, limits: limits, directoryReader: { url, budget, cancelled in
+ try InstallationDirectorySnapshot.read(at: url, maximumEntries: budget, cancelled: cancelled)
+ })
+ }
+
+ init(root: URL, limits: SteamScanLimits = .standard, directoryReader: @escaping InstallationDirectoryReader) {
+ self.root = root
+ self.limits = limits
+ self.directoryReader = directoryReader
+ }
+
+ public func scan(cancelled: @escaping () -> Bool = { false }) throws -> SteamLibrarySnapshot {
+ var scan = Scan(root: root, limits: limits, cancelled: cancelled, directoryReader: directoryReader)
+ do { return try scan.run() }
+ catch InstallationFileReadError.sourceChanged { throw SteamSourceError.sourceChanged }
+ }
+}
+
+private struct Scan {
+ let root: URL
+ let limits: SteamScanLimits
+ let cancelled: () -> Bool
+ let directoryReader: InstallationDirectoryReader
+ private let fm = FileManager.default
+ private var observations: [InstallationFileObservation] = []
+ private var issues: [SteamScanIssue] = []
+ private var games: [SteamGameObservation] = []
+
+ init(root: URL, limits: SteamScanLimits, cancelled: @escaping () -> Bool, directoryReader: @escaping InstallationDirectoryReader) {
+ self.root = root.resolvingSymlinksInPath().standardizedFileURL
+ self.limits = limits
+ self.cancelled = cancelled
+ self.directoryReader = directoryReader
+ }
+
+ mutating func run() throws -> SteamLibrarySnapshot {
+ try checkCancellation()
+ let paths = try libraryPaths()
+ var libraries: [SteamLibraryObservation] = []
+ var manifestsSeen = 0
+ for library in paths {
+ try checkCancellation()
+ let before = issues.count
+ let steamapps = library.appendingPathComponent("steamapps").resolvingSymlinksInPath().standardizedFileURL
+ guard NativeMacApplication.isWithin(steamapps, root: library) else {
+ issue(.unsafePath, at: steamapps)
+ libraries.append(.init(root: library, isReadable: false, isComplete: false))
+ continue
+ }
+ let files: [URL]
+ do { files = try readDirectory(steamapps) }
+ catch is CancellationError { throw CancellationError() }
+ catch InstallationFileReadError.sourceChanged { throw InstallationFileReadError.sourceChanged }
+ catch {
+ issue(.unavailableLibrary, at: library)
+ libraries.append(.init(root: library, isReadable: false, isComplete: false))
+ continue
+ }
+ let manifests = files.filter { $0.lastPathComponent.hasPrefix("appmanifest_") && $0.pathExtension == "acf" }
+ .sorted { $0.path < $1.path }
+ for file in manifests {
+ try checkCancellation()
+ guard manifestsSeen < max(0, limits.maximumManifests) else {
+ issue(.manifestLimit, at: library)
+ break
+ }
+ manifestsSeen += 1
+ try readManifest(file, library: library)
+ }
+ libraries.append(.init(root: library, isReadable: true, isComplete: issues.count == before))
+ }
+ let conflicting = Dictionary(grouping: games.indices, by: { games[$0].appID }).values.filter { $0.count > 1 }
+ for indices in conflicting {
+ for index in indices {
+ games[index].state = .requiresReview
+ issue(.conflictingIdentity, at: games[index].installationURL, appID: games[index].appID)
+ if let library = libraries.firstIndex(where: { $0.root.path == games[index].libraryURL.path }) {
+ libraries[library].isComplete = false
+ }
+ }
+ }
+ // Errors reading the index may hide entire libraries, so source-level completeness matters too.
+ if issues.contains(where: { [.invalidIndex, .oversizedIndex, .libraryLimit].contains($0.reason) }) {
+ for index in libraries.indices { libraries[index].isComplete = false }
+ }
+ for observation in observations { try checkCancellation(); try observation.verifyUnchanged() }
+ games.sort { $0.appID == $1.appID ? $0.libraryURL.path < $1.libraryURL.path : $0.appID < $1.appID }
+ return SteamLibrarySnapshot(libraries: libraries, games: games, issues: issues)
+ }
+
+ private mutating func libraryPaths() throws -> [URL] {
+ var paths = [root]
+ let steamapps = root.appendingPathComponent("steamapps").resolvingSymlinksInPath().standardizedFileURL
+ guard NativeMacApplication.isWithin(steamapps, root: root) else {
+ issue(.unsafePath, at: steamapps)
+ return paths
+ }
+ let index = root.appendingPathComponent("steamapps/libraryfolders.vdf")
+ if fm.fileExists(atPath: index.path) {
+ do {
+ let document = try readDocument(index)
+ guard case .object(let entries)? = try document.uniqueValue(for: "libraryfolders") else { throw KeyValuesError.malformed }
+ for entry in entries where Self.numeric(entry.key) != nil || entry.key == "0" {
+ let path: String
+ switch entry.value {
+ case .string(let value): path = value
+ case .object(let children):
+ guard let value = try children.uniqueString(for: "path") else { throw KeyValuesError.malformed }
+ path = value
+ }
+ guard path.hasPrefix("/"), !path.contains("\0") else { issue(.unsafePath, at: index); continue }
+ let url = URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL
+ if !paths.contains(where: { $0.path == url.path }) {
+ guard paths.count < max(1, limits.maximumLibraries) else { issue(.libraryLimit, at: index); continue }
+ paths.append(url)
+ }
+ }
+ } catch InstallationFileReadError.sourceChanged { throw InstallationFileReadError.sourceChanged }
+ catch InstallationFileReadError.tooLarge { issue(.oversizedIndex, at: index) }
+ catch { issue(.invalidIndex, at: index) }
+ } else {
+ do { observations.append(try InstallationFileObservation.absent(at: index)) }
+ catch InstallationFileReadError.sourceChanged { throw InstallationFileReadError.sourceChanged }
+ catch { issue(.invalidIndex, at: index) }
+ }
+ return paths
+ }
+
+ private mutating func readManifest(_ file: URL, library: URL) throws {
+ let stem = file.deletingPathExtension().lastPathComponent
+ let filenameID = Self.numeric(String(stem.dropFirst("appmanifest_".count)))
+ do {
+ guard let filenameID else { throw KeyValuesError.malformed }
+ let document = try readDocument(file)
+ guard case .object(let fields)? = try document.uniqueValue(for: "AppState"),
+ let idText = try fields.uniqueString(for: "appid"), let id = Self.numeric(idText) else { throw KeyValuesError.malformed }
+ guard id == filenameID else { issue(.conflictingIdentity, at: file, appID: filenameID); return }
+ guard let name = try fields.uniqueString(for: "name"), !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
+ let directory = try fields.uniqueString(for: "installdir"), !directory.isEmpty else { throw KeyValuesError.malformed }
+ let components = directory.split(separator: "/", omittingEmptySubsequences: false)
+ guard !directory.hasPrefix("/"), !directory.contains("\\"), !directory.contains("\0"),
+ !components.contains(where: { $0 == ".." || $0 == "." || $0.isEmpty }) else {
+ issue(.unsafePath, at: file, appID: id); return
+ }
+ let common = library.appendingPathComponent("steamapps/common").resolvingSymlinksInPath().standardizedFileURL
+ let install = common.appendingPathComponent(directory).resolvingSymlinksInPath().standardizedFileURL
+ guard NativeMacApplication.isWithin(common, root: library), NativeMacApplication.isWithin(install, root: common), install.path != common.path else {
+ issue(.unsafePath, at: file, appID: id); return
+ }
+ let size = try fields.uniqueString(for: "SizeOnDisk").flatMap(Self.nonnegativeSize)
+ let build = try fields.uniqueString(for: "buildid")
+ // Bit 4 is FullyInstalled. Missing or unreadable flags keep the folder check alone, as before.
+ if let flags = try fields.uniqueString(for: "StateFlags").flatMap({ UInt64($0) }), flags & 4 == 0 {
+ games.append(.init(appID: id, name: name, installationURL: install, libraryURL: library,
+ reportedSizeBytes: size, buildID: build, nativeApps: [], state: .downloading))
+ return
+ }
+ let before = issues.count
+ let apps = try nativeApps(in: install, appID: id)
+ let mainApps = apps.filter(\.isDeclaredGame)
+ let state: SteamGameObservation.State = mainApps.count == 1 && issues.count == before ? .nativeReady
+ : (apps.isEmpty && issues.count == before ? .unavailable : .requiresReview)
+ games.append(.init(appID: id, name: name, installationURL: install, libraryURL: library,
+ reportedSizeBytes: size, buildID: build, nativeApps: apps, state: state))
+ } catch is CancellationError { throw CancellationError() }
+ catch InstallationFileReadError.sourceChanged { throw InstallationFileReadError.sourceChanged }
+ catch InstallationFileReadError.tooLarge { issue(.oversizedManifest, at: file, appID: filenameID) }
+ catch { issue(.invalidManifest, at: file, appID: filenameID) }
+ }
+
+ private mutating func nativeApps(in install: URL, appID: UInt32) throws -> [NativeMacApplication] {
+ guard fm.fileExists(atPath: install.path) else { return [] }
+ var level = [install]
+ var depth = 0
+ var visited = 0
+ var apps: [NativeMacApplication] = []
+ var seen: Set = []
+ let keys: Set = [.isDirectoryKey, .isSymbolicLinkKey, .isPackageKey]
+ while !level.isEmpty {
+ try checkCancellation()
+ var nextLevel: [URL] = []
+ var truncated = false
+ let remaining = max(0, max(1, limits.maximumDirectoriesPerInstall) - visited - level.count)
+ for directory in level {
+ let files: [URL]
+ do { files = try readDirectory(directory, appID: appID) }
+ catch is CancellationError { throw CancellationError() }
+ catch InstallationFileReadError.sourceChanged { throw InstallationFileReadError.sourceChanged }
+ catch { issue(.unreadableAppMetadata, at: directory, appID: appID); continue }
+ for file in files.sorted(by: { $0.path < $1.path }) {
+ try checkCancellation()
+ if file.pathExtension.lowercased() == "app" {
+ do {
+ let app = try NativeMacApplication.inspect(at: file, within: install)
+ observations.append(contentsOf: app.fileObservations)
+ if seen.insert(app.url.path).inserted { apps.append(app) }
+ } catch InstallationFileReadError.sourceChanged { throw InstallationFileReadError.sourceChanged }
+ catch { issue(.unreadableAppMetadata, at: file, appID: appID) }
+ continue // Every bundle is a boundary, including an invalid one.
+ }
+ let values: URLResourceValues
+ do { values = try file.resourceValues(forKeys: keys) }
+ catch { issue(.unreadableAppMetadata, at: file, appID: appID); continue }
+ guard values.isDirectory == true, values.isSymbolicLink != true, values.isPackage != true else { continue }
+ if nextLevel.count < remaining { nextLevel.append(file) }
+ else { truncated = true }
+ }
+ }
+ visited += level.count
+ // Compare all apps at this depth. Once game candidates exist, deeper
+ // loose-data trees do not decide which top-level application is primary.
+ if apps.contains(where: \.isDeclaredGame) { return apps }
+ if truncated || (!nextLevel.isEmpty && depth >= max(0, limits.maximumInstallDepth)) {
+ issue(.directoryLimit, at: level[0], appID: appID)
+ return apps
+ }
+ level = nextLevel
+ depth += 1
+ }
+ return apps
+ }
+
+ private mutating func readDocument(_ url: URL) throws -> KeyValuesDocument {
+ let snapshot = try InstallationFileSnapshot.read(at: url, maximumBytes: min(max(0, limits.maximumTextBytes), 8 * 1024 * 1024))
+ let document = try KeyValuesDocument(text: snapshot.text)
+ observations.append(snapshot.observation)
+ return document
+ }
+
+ private mutating func readDirectory(_ url: URL, appID: UInt32? = nil) throws -> [URL] {
+ let snapshot = try directoryReader(url, limits.maximumDirectoryEntries, cancelled)
+ observations.append(snapshot.observation)
+ if !snapshot.isComplete { issue(.directoryLimit, at: url, appID: appID) }
+ return snapshot.entries
+ }
+
+ private mutating func issue(_ reason: SteamScanIssue.Reason, at url: URL, appID: UInt32? = nil) {
+ issues.append(SteamScanIssue(url: url, appID: appID, reason: reason))
+ }
+
+ private func checkCancellation() throws { if cancelled() { throw CancellationError() } }
+
+ private static func numeric(_ text: String) -> UInt32? {
+ guard !text.isEmpty, text.utf8.allSatisfy({ (48...57).contains($0) }), let value = UInt32(text), value > 0 else { return nil }
+ return value
+ }
+
+ private static func nonnegativeSize(_ text: String) -> Int64? {
+ guard !text.isEmpty, text.utf8.allSatisfy({ (48...57).contains($0) }), let value = Int64(text) else { return nil }
+ return value
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamManifestWatcher.swift b/Sources/NXLibraryCore/Services/Steam/SteamManifestWatcher.swift
new file mode 100644
index 00000000..1ffb9c34
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamManifestWatcher.swift
@@ -0,0 +1,108 @@
+import Foundation
+import CoreServices
+
+/// Tells NX Library when Steam rewrites a manifest (a download starts, pauses or finishes, a game is installed,
+/// removed or launched) or the library index, so the Steam source can rescan without a Refresh. One FSEvents
+/// stream over the `steamapps` folders of the libraries the last scan read. FSEvents is recursive, so a download's
+/// writes under `downloading/` reach the callback too: its 2 s latency batches them and only the paths are
+/// compared, nothing is read. `CatalogSourcesModel.steamFilesChanged` paces the rescans.
+@MainActor
+public final class SteamManifestWatcher {
+ /// Called on the main thread, at most once per batch of events.
+ public var onChange: (@MainActor () -> Void)?
+
+ private var stream: FSEventStreamRef?
+ private var watched: [String] = []
+ private var libraries: [String] = []
+ private var root: String?
+
+ public init(onChange: (@MainActor () -> Void)? = nil) { self.onChange = onChange }
+
+ /// Watches these libraries (the scan's, the source's root among them). Rechecks available folders even for
+ /// the same set, so a library returning on an external drive joins the stream. None stops watching.
+ public func watch(_ libraries: [URL], root: URL?) {
+ let paths = libraries.map { $0.resolvingSymlinksInPath().standardizedFileURL.path }
+ let rootPath = root.map { $0.resolvingSymlinksInPath().standardizedFileURL.path }
+ let folders = paths.map { $0 + "/steamapps" }.filter { FileManager.default.fileExists(atPath: $0) }
+ guard paths != self.libraries || rootPath != self.root || folders != watched else { return }
+ stop()
+ guard !folders.isEmpty else { return }
+ // The stream holds the watcher until it is released in `stop`, so a callback already queued on the main
+ // queue never reaches a freed watcher.
+ var context = FSEventStreamContext(version: 0, info: Unmanaged.passUnretained(self).toOpaque(),
+ retain: { info in
+ guard let info else { return nil }
+ _ = Unmanaged.fromOpaque(info).retain()
+ return info
+ },
+ release: { info in
+ guard let info else { return }
+ Unmanaged.fromOpaque(info).release()
+ },
+ copyDescription: nil)
+ let flags = FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagUseCFTypes
+ | kFSEventStreamCreateFlagNoDefer)
+ guard let stream = FSEventStreamCreate(nil, Self.callback, &context, folders as CFArray,
+ FSEventStreamEventId(kFSEventStreamEventIdSinceNow), 2, flags) else { return }
+ FSEventStreamSetDispatchQueue(stream, DispatchQueue.main)
+ guard FSEventStreamStart(stream) else {
+ FSEventStreamInvalidate(stream); FSEventStreamRelease(stream)
+ return
+ }
+ self.stream = stream
+ self.libraries = paths
+ self.root = rootPath
+ watched = folders
+ }
+
+ public func stop() {
+ if let stream {
+ FSEventStreamStop(stream); FSEventStreamInvalidate(stream); FSEventStreamRelease(stream)
+ }
+ stream = nil; watched = []; libraries = []; root = nil
+ }
+
+ /// An event that may change the library. With `dropped` (the system lost events under `path` and asks for a
+ /// rescan of it), only a drop at a `steamapps` folder or above counts: one inside `downloading/` or `common/`
+ /// says nothing about the manifests, and a long download could otherwise rescan every batch.
+ public nonisolated static func isRelevant(_ path: String, dropped: Bool, libraries: [String], root: String?) -> Bool {
+ guard dropped else { return isRelevant(path, libraries: libraries, root: root) }
+ let folder = path.hasSuffix("/") ? String(path.dropLast()) : path
+ return libraries.contains { library in
+ let steamapps = library + "/steamapps"
+ return steamapps == folder || steamapps.hasPrefix(folder + "/")
+ }
+ }
+
+ /// `/steamapps/appmanifest_.acf`, or the root's `steamapps/libraryfolders.vdf`.
+ public nonisolated static func isRelevant(_ path: String, libraries: [String], root: String?) -> Bool {
+ if let root, path == root + "/steamapps/libraryfolders.vdf" { return true }
+ for library in libraries {
+ let prefix = library + "/steamapps/"
+ guard path.hasPrefix(prefix) else { continue }
+ let name = path.dropFirst(prefix.count)
+ guard name.hasPrefix("appmanifest_"), name.hasSuffix(".acf") else { return false }
+ let digits = name.dropFirst("appmanifest_".count).dropLast(".acf".count)
+ return !digits.isEmpty && digits.utf8.allSatisfy { (48...57).contains($0) }
+ }
+ return false
+ }
+
+ private func received(_ paths: [String], flags: [FSEventStreamEventFlags]) {
+ let mustScan = FSEventStreamEventFlags(kFSEventStreamEventFlagMustScanSubDirs)
+ let changed = zip(paths, flags).contains { path, flag in
+ // FSEvents can spell /var and /tmp with /private; compare in the same form as `watch`.
+ let canonical = URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.path
+ return Self.isRelevant(canonical, dropped: flag & mustScan != 0, libraries: libraries, root: root)
+ }
+ if changed { onChange?() }
+ }
+
+ private static let callback: FSEventStreamCallback = { _, info, count, eventPaths, eventFlags, _ in
+ guard let info else { return }
+ let paths = (unsafeBitCast(eventPaths, to: NSArray.self) as? [String]) ?? []
+ let flags = Array(UnsafeBufferPointer(start: eventFlags, count: count))
+ let watcher = Unmanaged.fromOpaque(info).takeUnretainedValue()
+ MainActor.assumeIsolated { watcher.received(paths, flags: flags) }
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamMetadata.swift b/Sources/NXLibraryCore/Services/Steam/SteamMetadata.swift
new file mode 100644
index 00000000..9912b8d8
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamMetadata.swift
@@ -0,0 +1,58 @@
+import Foundation
+
+/// Store facts are distinct from installation observations and personal choices.
+public struct SteamMetadata: Codable, Equatable, Sendable {
+ public let appID: UInt32
+ public let language: String
+ public let description: String
+ public let genres: [String]
+ public let developers: [String]
+ public let publishers: [String]
+ public let releaseDate: String?
+ public let screenshots: [URL]
+ public let fetchedAt: Date
+
+ public static func language(_ language: AppLanguage) -> String {
+ switch language {
+ case .italian: return "italian"
+ case .french: return "french"
+ case .german: return "german"
+ case .spanish: return "spanish"
+ case .portugueseBrazil: return "brazilian"
+ default: return "english"
+ }
+ }
+ public static func safeImage(_ url: URL?) -> URL? {
+ guard let url, url.scheme == "https", url.user == nil, url.password == nil,
+ url.port == nil || url.port == 443, let host = url.host?.lowercased(),
+ ["steamstatic.com", "steamusercontent.com"].contains(where: { host == $0 || host.hasSuffix("." + $0) }) else { return nil }
+ return url
+ }
+ public static func decode(_ data: Data, appID: UInt32, language: String) throws -> Self {
+ struct Envelope: Decodable {
+ struct Body: Decodable {
+ struct Genre: Decodable { let description: String }
+ struct Shot: Decodable { let path_full: URL }
+ struct Release: Decodable { let date: String? }
+ let steam_appid: UInt32
+ let short_description: String?
+ let genres: [Genre]?
+ let developers: [String]?
+ let publishers: [String]?
+ let release_date: Release?
+ let screenshots: [Shot]?
+ }
+ let success: Bool
+ let data: Body?
+ }
+ guard data.count <= 2_097_152, appID > 0,
+ let envelope = try JSONDecoder().decode([String: Envelope].self, from: data)[String(appID)],
+ envelope.success, let body = envelope.data, body.steam_appid == appID else { throw URLError(.cannotParseResponse) }
+ return Self(appID: appID, language: language,
+ description: GameBananaAPI.plainText(fromHTML: body.short_description ?? ""),
+ genres: Array((body.genres ?? []).prefix(24)).map(\.description),
+ developers: Array((body.developers ?? []).prefix(12)), publishers: Array((body.publishers ?? []).prefix(12)),
+ releaseDate: body.release_date?.date,
+ screenshots: Array((body.screenshots ?? []).compactMap { safeImage($0.path_full) }.prefix(12)), fetchedAt: Date())
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamMetadataService.swift b/Sources/NXLibraryCore/Services/Steam/SteamMetadataService.swift
new file mode 100644
index 00000000..84f62462
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamMetadataService.swift
@@ -0,0 +1,212 @@
+import Foundation
+import CryptoKit
+
+/// Bounded, source-specific enrichment. Failures preserve disk cache; no catalog
+/// writes, credentials, game-content reads or Nintendo lookups.
+public actor SteamMetadataService {
+ public typealias Transport = @Sendable (URL) async throws -> Data
+ public static let shared = SteamMetadataService()
+ private let directory: URL
+ private let transport: Transport
+ private struct Flight {
+ let id: UUID
+ let task: Task
+ var waiters: Set
+ }
+ private var pending: [URL: Flight] = [:]
+ private var failedAt: [URL: Date] = [:]
+ /// At most this many downloads at once; later requests wait for a free one (a screen of achievement
+ /// icons asks for dozens together: refused, they stayed blank until their row was drawn again).
+ static let concurrentDownloads = 6
+ private var slotWaiters: [UUID: CheckedContinuation] = [:]
+ public static let resourceDeadline: TimeInterval = 20
+ final class NoRedirects: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
+ func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
+ newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) }
+ }
+ private static let session: URLSession = {
+ let config = URLSessionConfiguration.ephemeral
+ config.timeoutIntervalForResource = resourceDeadline
+ config.timeoutIntervalForRequest = 10
+ config.httpMaximumConnectionsPerHost = 4
+ return URLSession(configuration: config, delegate: NoRedirects(), delegateQueue: nil)
+ }()
+ public static func allowed(_ url: URL) -> Bool {
+ guard url.scheme == "https", url.user == nil, url.password == nil, url.port == nil || url.port == 443 else { return false }
+ // `URL.path` drops the trailing slash; the components keep it.
+ if url.host == SteamAchievementRarity.host {
+ return URLComponents(url: url, resolvingAgainstBaseURL: false)?.path == SteamAchievementRarity.path
+ }
+ return url.host == "store.steampowered.com" || SteamMetadata.safeImage(url) != nil
+ }
+
+ public init(directory: URL = AppData.supportRoot.appendingPathComponent("integrations/steam/enrichment"),
+ transport: @escaping Transport = { try await SteamMetadataService.download($0) }) {
+ self.directory = directory; self.transport = transport
+ }
+ public static func download(_ url: URL) async throws -> Data {
+ guard allowed(url) else { throw URLError(.badURL) }
+ var request = URLRequest(url: url); request.timeoutInterval = 15
+ request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent")
+ let limit = url.host == "store.steampowered.com" || url.host == SteamAchievementRarity.host ? 2_097_152 : 12_582_912
+ let (data, response) = try await BoundedDownload.data(for: request, session: session, limit: limit)
+ guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode),
+ let final = http.url, allowed(final) else { throw URLError(.badServerResponse) }
+ return data
+ }
+ private func release(_ url: URL, flightID: UUID, waiter: UUID) {
+ guard var flight = pending[url], flight.id == flightID else { return }
+ flight.waiters.remove(waiter)
+ if flight.waiters.isEmpty { flight.task.cancel(); pending[url] = nil; wakeSlotWaiters() }
+ else { pending[url] = flight }
+ }
+ /// Every waiter looks again: one may now share a flight that started meanwhile, or take the free slot.
+ private func wakeSlotWaiters() {
+ let waiting = slotWaiters.values
+ slotWaiters.removeAll()
+ waiting.forEach { $0.resume() }
+ }
+ private func waitForSlot() async throws {
+ let id = UUID()
+ try await withTaskCancellationHandler(operation: {
+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in
+ // Runs on the actor before `cancelWait` can: a cancellation before this point shows here.
+ if Task.isCancelled { continuation.resume(throwing: CancellationError()) }
+ else { slotWaiters[id] = continuation }
+ }
+ }, onCancel: { Task { await self.cancelWait(id) } })
+ }
+ private func cancelWait(_ id: UUID) {
+ slotWaiters.removeValue(forKey: id)?.resume(throwing: CancellationError())
+ }
+ private func refuseIfFailedRecently(_ url: URL) throws {
+ if let failed = failedAt[url], Date().timeIntervalSince(failed) < 60 { throw URLError(.resourceUnavailable) }
+ }
+ private func fetch(_ url: URL) async throws -> Data {
+ try Task.checkCancellation()
+ // A recent failure answers at once, before and after waiting for a slot (it may fail meanwhile).
+ try refuseIfFailedRecently(url)
+ while pending[url] == nil && pending.count >= Self.concurrentDownloads { try await waitForSlot() }
+ try refuseIfFailedRecently(url)
+ let waiter = UUID()
+ var flight: Flight
+ if let existing = pending[url] { flight = existing; flight.waiters.insert(waiter) }
+ else {
+ let transport = transport
+ flight = Flight(id: UUID(), task: Task { try await transport(url) }, waiters: [waiter])
+ }
+ pending[url] = flight
+ let id = flight.id, task = flight.task
+ return try await withTaskCancellationHandler(operation: {
+ defer { release(url, flightID: id, waiter: waiter) }
+ do { let data = try await task.value; try Task.checkCancellation(); return data }
+ catch {
+ if !Task.isCancelled && !(error is CancellationError) { failedAt[url] = Date() }
+ throw error
+ }
+ }, onCancel: { Task { await self.release(url, flightID: id, waiter: waiter) } })
+ }
+ private static let metadataLanguages: Set = ["english", "italian", "french", "german", "spanish", "brazilian"]
+
+ private func metadataFile(appID: UInt32, language: String) -> URL {
+ directory.appendingPathComponent("\(appID)/\(language).json")
+ }
+
+ private func cachedMetadata(appID: UInt32, language: String) -> SteamMetadata? {
+ let file = metadataFile(appID: appID, language: language)
+ let cached = (try? InstallationFileSnapshot.read(at: file, maximumBytes: 2_097_152).data).flatMap { try? JSONDecoder().decode(SteamMetadata.self, from: $0) }
+ return cached.flatMap { $0.appID == appID && $0.language == language ? $0 : nil }
+ }
+
+ /// The game's related row needs only scoring traits. Read existing entries and leave other games off the network.
+ public func cachedRelatedTraits(appIDs: Set, language: String) -> [UInt32: MoreLikeThis.Traits] {
+ guard Self.metadataLanguages.contains(language) else { return [:] }
+ var traits: [UInt32: MoreLikeThis.Traits] = [:]
+ for appID in appIDs where appID > 0 {
+ guard !Task.isCancelled else { return [:] }
+ if let cached = cachedMetadata(appID: appID, language: language) { traits[appID] = .init(steam: cached) }
+ }
+ return traits
+ }
+
+ public func metadata(appID: UInt32, language: String, refresh: Bool = false) async -> SteamMetadata? {
+ guard appID > 0, Self.metadataLanguages.contains(language) else { return nil }
+ let file = metadataFile(appID: appID, language: language)
+ let valid = cachedMetadata(appID: appID, language: language)
+ if let valid, !refresh, Date().timeIntervalSince(valid.fetchedAt) < 604800 { return valid }
+ let url = URL(string: "https://store.steampowered.com/api/appdetails?appids=\(appID)&l=\(language)")!
+ do {
+ let bytes = try await fetch(url)
+ try Task.checkCancellation()
+ let result: SteamMetadata
+ do { result = try SteamMetadata.decode(bytes, appID: appID, language: language) }
+ catch { failedAt[url] = Date(); throw error }
+ try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try JSONEncoder().encode(result).write(to: file, options: .atomic)
+ return result
+ } catch { return valid }
+ }
+ /// How many of Steam's players have each achievement (`SteamAchievementRarity`), by API name, kept for a day.
+ /// Offline or on a bad answer, the last percentages known, or nil.
+ public func achievementPercents(appID: UInt32) async -> [String: Double]? {
+ guard appID > 0 else { return nil }
+ let file = directory.appendingPathComponent("\(appID)/achievement-percents.json")
+ let cached = (try? InstallationFileSnapshot.read(at: file, maximumBytes: 2_097_152).data)
+ .flatMap { try? JSONDecoder().decode(SteamAchievementPercentsCache.self, from: $0) }
+ if let cached, Date().timeIntervalSince(cached.fetchedAt) < SteamAchievementRarity.freshFor { return cached.percents }
+ let url = SteamAchievementRarity.url(appID: appID)
+ do {
+ let bytes = try await fetch(url)
+ try Task.checkCancellation()
+ let percents: [String: Double]
+ do { percents = try SteamAchievementRarity.decode(bytes) }
+ catch { failedAt[url] = Date(); throw error }
+ try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try JSONEncoder().encode(SteamAchievementPercentsCache(fetchedAt: Date(), percents: percents)).write(to: file, options: .atomic)
+ return percents
+ } catch { return cached?.percents }
+ }
+
+ /// An achievement's icon from Steam's CDN, kept on disk as long as it reads as an image.
+ public func achievementIcon(appID: UInt32, file name: String) async -> URL? {
+ guard appID > 0, !Task.isCancelled, let url = SteamAchievementRarity.iconURL(appID: appID, file: name) else { return nil }
+ let file = directory.appendingPathComponent("\(appID)/achievements/\(name)")
+ let limit = 2_097_152
+ if let data = try? InstallationFileSnapshot.read(at: file, maximumBytes: limit).data,
+ ArtworkStore.downsample(data, maxPixelSize: 256) != nil { return file }
+ guard let data = try? await fetch(url), !Task.isCancelled else { return nil }
+ guard data.count <= limit, ArtworkStore.downsample(data, maxPixelSize: 256) != nil else { failedAt[url] = Date(); return nil }
+ do {
+ try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try data.write(to: file, options: .atomic)
+ return file
+ } catch { return nil }
+ }
+
+ public func image(appID: UInt32, slot: ArtworkSlot, remote: URL? = nil) async -> URL? {
+ guard appID > 0, !Task.isCancelled else { return nil }
+ // Screenshots use their full URL in the cache key; no basename collisions.
+ let token = remote.map { SHA256.hash(data: Data($0.absoluteString.utf8)).map { String(format: "%02x", $0) }.joined() }
+ let file = directory.appendingPathComponent("\(appID)/images/\(token ?? slot.rawValue).png")
+ let cached = try? InstallationFileSnapshot.read(at: file, maximumBytes: 12_582_912).data
+ let validCache = cached.flatMap { ArtworkStore.downsample($0, maxPixelSize: slot.kind.maxPixelSize, png: true) } != nil
+ let modified = try? file.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
+ if validCache, let modified, Date().timeIntervalSince(modified) < 604800 { return file }
+ let candidates = remote.map { [ArtworkCandidate(slot: slot, source: "Steam", url: $0)] }
+ ?? SteamStoreArt.candidates(appID: Int(appID), slot: slot)
+ for candidate in candidates {
+ for url in [candidate.url, candidate.fallback].compactMap({ $0 }).compactMap(SteamMetadata.safeImage) {
+ guard !Task.isCancelled else { return validCache ? file : nil }
+ guard let data = try? await fetch(url) else { continue }
+ guard !Task.isCancelled else { return validCache ? file : nil }
+ guard data.count <= 12_582_912,
+ let image = ArtworkStore.downsample(data, maxPixelSize: slot.kind.maxPixelSize, png: true) else { failedAt[url] = Date(); continue }
+ do {
+ try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try image.write(to: file, options: .atomic); return file
+ } catch { return nil }
+ }
+ }
+ return validCache ? file : nil
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamPersonalizationStore.swift b/Sources/NXLibraryCore/Services/Steam/SteamPersonalizationStore.swift
new file mode 100644
index 00000000..378fe4d0
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamPersonalizationStore.swift
@@ -0,0 +1,63 @@
+import Foundation
+import Combine
+
+/// One manifest publishes a complete title draft. New image files are prepared
+/// first; a failed manifest commit leaves every previous reference untouched.
+public final class SteamPersonalizationStore: ObservableObject {
+ private struct Entry: Codable { var fields: [String: String]; var art: [String: String] }
+ @Published public private(set) var revision = 0
+ private let directory: URL
+ private let publish: (Data, URL) throws -> Void
+ private let invalidManifest: Bool
+ private var entries: [String: Entry]
+ public init(directory: URL, publish: @escaping (Data, URL) throws -> Void = { try $0.write(to: $1, options: .atomic) }) {
+ self.directory = directory; self.publish = publish
+ let decoded = (try? InstallationFileSnapshot.read(at: directory.appendingPathComponent("personal.json"), maximumBytes: 16_777_216).data)
+ .flatMap { try? JSONDecoder().decode([String: Entry].self, from: $0) }
+ entries = decoded ?? [:]
+ invalidManifest = FileManager.default.fileExists(atPath: directory.appendingPathComponent("personal.json").path) && decoded == nil
+ }
+ public func value(titleID: String, field: MetadataField) -> String? { entries[titleID]?.fields[field.rawValue] }
+ public func url(titleID: String, slot: ArtworkSlot) -> URL? {
+ guard let name = entries[titleID]?.art[slot.rawValue], name == URL(fileURLWithPath: name).lastPathComponent else { return nil }
+ return directory.appendingPathComponent("assets").appendingPathComponent(name)
+ }
+ public func save(fields: [MetadataField: String], images: [ArtworkSlot: Data], automatic: Set, titleID: String) throws {
+ guard !invalidManifest else { throw URLError(.cannotParseResponse) }
+ var draft = entries
+ var entry = entries[titleID] ?? Entry(fields: [:], art: [:])
+ var created: [URL] = []
+ do {
+ for (field, raw) in fields {
+ guard raw.utf8.count <= 100_000 else { throw URLError(.dataLengthExceedsMaximum) }
+ let text = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ entry.fields[field.rawValue] = text.isEmpty ? nil : text
+ }
+ for (slot, data) in images {
+ guard data.count <= 12_582_912,
+ let normalized = ArtworkStore.downsample(data, maxPixelSize: slot.kind.maxPixelSize, png: true) else { throw URLError(.cannotDecodeContentData) }
+ let name = UUID().uuidString + ".png"
+ let file = directory.appendingPathComponent("assets").appendingPathComponent(name)
+ try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try normalized.write(to: file, options: .atomic); created.append(file); entry.art[slot.rawValue] = name
+ }
+ for slot in automatic { entry.art[slot.rawValue] = nil }
+ draft[titleID] = entry
+ let data = try JSONEncoder().encode(draft)
+ guard data.count <= 16_777_216 else { throw URLError(.dataLengthExceedsMaximum) }
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ try publish(data, directory.appendingPathComponent("personal.json"))
+ } catch {
+ for file in created { try? FileManager.default.removeItem(at: file) }
+ throw error
+ }
+ let retained = Set(draft.values.flatMap { $0.art.values })
+ let old = Set(entries.values.flatMap { $0.art.values }).subtracting(retained)
+ entries = draft; revision += 1
+ // Only obsolete generated copies, after successful publication. Automatic
+ // is removal of a manifest reference, so a file deletion cannot undo it.
+ for name in old where name == URL(fileURLWithPath: name).lastPathComponent {
+ try? FileManager.default.removeItem(at: directory.appendingPathComponent("assets").appendingPathComponent(name))
+ }
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamPlayState.swift b/Sources/NXLibraryCore/Services/Steam/SteamPlayState.swift
new file mode 100644
index 00000000..764f74e4
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamPlayState.swift
@@ -0,0 +1,151 @@
+import Foundation
+
+/// One live process as the system reports it, reduced to what identifies an installed app.
+public struct NativeProcessObservation: Equatable, Sendable {
+ public let pid: Int32
+ public let bundleURL: URL?
+ public let executableURL: URL?
+ public init(pid: Int32, bundleURL: URL?, executableURL: URL?) {
+ self.pid = pid; self.bundleURL = bundleURL; self.executableURL = executableURL
+ }
+
+ /// The same process with its paths resolved (symlinks, `..`), the form `SteamPlayState` compares.
+ /// A process's paths don't change while it lives, so callers resolve each pid once.
+ public func canonical() -> NativeProcessObservation {
+ NativeProcessObservation(pid: pid, bundleURL: bundleURL.map(SteamPlayState.canonical),
+ executableURL: executableURL.map(SteamPlayState.canonical))
+ }
+}
+
+public enum SteamPlayFailure: Equatable, Sendable {
+ /// No single available, recognized installation in an enabled source.
+ case unavailable
+ /// No Steam client registered on this Mac.
+ case clientMissing
+ /// The system did not hand the request to Steam.
+ case handoffRejected
+ /// Steam took the request but the game's own app never appeared in time.
+ case notStarted
+}
+
+/// A Steam game's Play and its real session, as pure state. Handing the request to Steam
+/// starts nothing: the session starts when the installation's own app is seen running and
+/// ends when that process goes, whatever Steam itself does. A game started from Steam
+/// directly is followed the same way. Requests carry a generation, so a late answer to an
+/// older Play never changes a newer one.
+public struct SteamPlayState: Equatable, Sendable {
+ public enum Phase: Equatable, Sendable {
+ case idle
+ /// Waiting for the game's app; a rejected hand-off changes this to `.failed`.
+ case starting(since: Date)
+ case running(pid: Int32)
+ case failed(SteamPlayFailure)
+ }
+
+ public enum Request: Equatable, Sendable {
+ case handOff(URL, generation: Int)
+ case resume(pid: Int32)
+ /// Play pressed again while the first request is still on its way: nothing new is sent.
+ case wait
+ case refuse(SteamPlayFailure)
+ }
+
+ public enum Change: Equatable, Sendable {
+ case started(pid: Int32)
+ case ended(pid: Int32)
+ }
+
+ /// Steam may install an update or show its own window before the game starts.
+ public static let startDeadline: TimeInterval = 300
+
+ public private(set) var phase: Phase = .idle
+ public private(set) var generation = 0
+ /// The app the running session saw start: it lasts while that process lives, whatever the catalog
+ /// says about the installation since (removed in a refresh, or now named at another path).
+ private var runningBundle: URL?
+
+ public init() {}
+
+ /// Steam's Downloads page, for a game Steam is still installing. With `launchURL`, the only URLs NX Library sends.
+ public static let downloadsURL = URL(string: "steam://open/downloads")!
+
+ /// Built from a validated numeric AppID, nothing else.
+ public static func launchURL(appID: UInt32) -> URL? {
+ appID > 0 ? URL(string: "steam://run/\(appID)") : nil
+ }
+
+ public mutating func requestPlay(target: CatalogLaunchTarget?, clientAvailable: Bool, now: Date) -> Request {
+ switch phase {
+ case .running(let pid): return .resume(pid: pid)
+ case .starting: return .wait
+ case .idle, .failed: break
+ }
+ guard case .steam(let appID)? = target, let url = Self.launchURL(appID: appID) else {
+ phase = .failed(.unavailable); return .refuse(.unavailable)
+ }
+ guard clientAvailable else { phase = .failed(.clientMissing); return .refuse(.clientMissing) }
+ generation += 1
+ phase = .starting(since: now)
+ return .handOff(url, generation: generation)
+ }
+
+ /// The system's answer to the hand-off. Only the current request's answer counts.
+ public mutating func handoffFinished(accepted: Bool, generation: Int) {
+ guard generation == self.generation, case .starting = phase else { return }
+ if !accepted { phase = .failed(.handoffRejected) }
+ }
+
+ /// The player gave up waiting, or dismissed a failure.
+ public mutating func cancel() {
+ switch phase {
+ case .starting, .failed: phase = .idle; generation += 1
+ case .idle, .running: break
+ }
+ }
+
+ /// Reads the process list, given in `canonical()` form. A running session ends when its process is
+ /// gone; otherwise the installation's own app, once seen, starts one. Waiting too long fails without a session.
+ public mutating func observe(_ processes: [NativeProcessObservation], application: CatalogNativeApplication?,
+ now: Date) -> Change? {
+ if case .running(let pid) = phase {
+ // Same pid and still the app it started as: a pid the system reused for another program is not the game.
+ if processes.contains(where: { process in
+ process.pid == pid && (runningBundle.map { bundle in process.bundleURL.map { Self.same($0, bundle) } ?? false } ?? true)
+ }) { return nil }
+ phase = .idle
+ runningBundle = nil
+ return .ended(pid: pid)
+ }
+ // The installation's paths are resolved once here, not once per process.
+ if let target = application.map(Target.init), let match = processes.first(where: target.matches) {
+ phase = .running(pid: match.pid)
+ runningBundle = match.bundleURL
+ return .started(pid: match.pid)
+ }
+ if case .starting(let since) = phase, now.timeIntervalSince(since) > Self.startDeadline {
+ phase = .failed(.notStarted)
+ }
+ return nil
+ }
+
+ /// An installation's app with its paths resolved, for comparing against canonical processes.
+ private struct Target {
+ let bundle: String
+ let executable: String
+ init(_ application: CatalogNativeApplication) {
+ bundle = SteamPlayState.canonical(application.url).path
+ executable = SteamPlayState.canonical(application.executableURL).path
+ }
+ func matches(_ process: NativeProcessObservation) -> Bool {
+ guard let url = process.bundleURL, url.standardizedFileURL.path == bundle else { return false }
+ guard let executableURL = process.executableURL else { return true }
+ return executableURL.standardizedFileURL.path == executable
+ }
+ }
+
+ /// Symlinks and `..` resolved: two names for one app compare equal.
+ public static func canonical(_ url: URL) -> URL { url.resolvingSymlinksInPath().standardizedFileURL }
+
+ /// Both URLs are canonical already: no filesystem access.
+ static func same(_ a: URL, _ b: URL) -> Bool { a.standardizedFileURL.path == b.standardizedFileURL.path }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeBaselines.swift b/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeBaselines.swift
new file mode 100644
index 00000000..3082677b
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeBaselines.swift
@@ -0,0 +1,94 @@
+import Foundation
+
+/// Steam's total for one game and when NX Library first saw that value. `carry` is time NX Library had
+/// already shown beyond Steam's new whole minutes (at most `maximumCarry`), so a rising value never
+/// makes the total step back.
+public struct SteamPlaytimeBaseline: Codable, Equatable, Sendable {
+ public static let maximumCarry: TimeInterval = 60
+ public let appID: UInt32
+ public let minutes: Int
+ public let lastPlayed: Date?
+ public let seenAt: Date
+ public let carry: TimeInterval
+ public init(appID: UInt32, minutes: Int, lastPlayed: Date?, seenAt: Date, carry: TimeInterval = 0) {
+ self.appID = appID; self.minutes = minutes; self.lastPlayed = lastPlayed; self.seenAt = seenAt; self.carry = carry
+ }
+
+ private enum CodingKeys: String, CodingKey { case appID, minutes, lastPlayed, seenAt, carry }
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ appID = try c.decode(UInt32.self, forKey: .appID)
+ minutes = try c.decode(Int.self, forKey: .minutes)
+ lastPlayed = try c.decodeIfPresent(Date.self, forKey: .lastPlayed)
+ seenAt = try c.decode(Date.self, forKey: .seenAt)
+ carry = try c.decodeIfPresent(TimeInterval.self, forKey: .carry) ?? 0
+ }
+}
+
+/// The current account's Steam totals, each with when its value was first seen. NX Library adds only
+/// its own play after `seenAt`: Steam's value already counts what came before. A new value (up or down)
+/// or another account starts over; Steam is the source of truth.
+public struct SteamPlaytimeBaselines: Equatable, Sendable {
+ public let fileURL: URL
+ public private(set) var accountID: UInt32?
+ public private(set) var byAppID: [UInt32: SteamPlaytimeBaseline] = [:]
+
+ private struct File: Codable { var accountID: UInt32; var baselines: [SteamPlaytimeBaseline] }
+
+ /// Loads the saved baselines; a missing or broken file means none.
+ public init(fileURL: URL) {
+ self.fileURL = fileURL
+ guard let data = try? Data(contentsOf: fileURL),
+ let file = try? JSONDecoder().decode(File.self, from: data) else { return }
+ accountID = file.accountID
+ byAppID = Dictionary(file.baselines.map { ($0.appID, $0) }, uniquingKeysWith: { first, _ in first })
+ }
+
+ /// Takes a new reading. `previousTotals` are the totals shown until now, by AppID: when Steam's value
+ /// rises, what they showed beyond it (up to a minute) is carried. Returns whether anything changed.
+ @discardableResult
+ public mutating func apply(_ snapshot: SteamPlaytimeSnapshot, now: Date,
+ previousTotals: [UInt32: TimeInterval] = [:]) -> Bool {
+ let previous = snapshot.accountID == accountID ? byAppID : [:]
+ var next: [UInt32: SteamPlaytimeBaseline] = [:]
+ for (appID, entry) in snapshot.entries {
+ let old = previous[appID]
+ var seenAt = now, carry: TimeInterval = 0
+ if let old, old.minutes == entry.minutes {
+ seenAt = old.seenAt; carry = old.carry
+ } else if let old, entry.minutes > old.minutes, let shown = previousTotals[appID] {
+ carry = min(SteamPlaytimeBaseline.maximumCarry, max(0, shown - TimeInterval(entry.minutes) * 60))
+ }
+ next[appID] = SteamPlaytimeBaseline(appID: appID, minutes: entry.minutes, lastPlayed: entry.lastPlayed,
+ seenAt: seenAt, carry: carry)
+ }
+ let changed = snapshot.accountID != accountID || next != byAppID
+ accountID = snapshot.accountID
+ byAppID = next
+ return changed
+ }
+
+ /// Writes atomically; the directory is created when missing.
+ public func save() throws {
+ guard let accountID else { return }
+ let file = File(accountID: accountID, baselines: byAppID.values.sorted { $0.appID < $1.appID })
+ try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try JSONEncoder().encode(file).write(to: fileURL, options: .atomic)
+ }
+
+ /// When each catalog Steam game's value was seen, for `PlaySessionStore.setTrimReferences`.
+ public func references(for games: [CatalogGame]) -> [UUID: Date] {
+ external(for: games).mapValues(\.since)
+ }
+
+ /// The catalog's Steam games with a baseline, by game UUID, for `PlaySessionStore.setExternal`.
+ public func external(for games: [CatalogGame]) -> [UUID: ExternalPlaytime] {
+ var result: [UUID: ExternalPlaytime] = [:]
+ for game in games {
+ guard let appID = game.steamGame?.appID, let baseline = byAppID[appID] else { continue }
+ result[game.id] = ExternalPlaytime(duration: TimeInterval(baseline.minutes) * 60 + baseline.carry,
+ lastPlayed: baseline.lastPlayed, since: baseline.seenAt)
+ }
+ return result
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeReader.swift b/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeReader.swift
new file mode 100644
index 00000000..f3d344d0
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeReader.swift
@@ -0,0 +1,84 @@
+import Foundation
+
+/// One game's playtime as Steam keeps it for an account: minutes on every computer, and the last start.
+public struct SteamPlaytimeEntry: Codable, Equatable, Sendable {
+ public let minutes: Int
+ public let lastPlayed: Date?
+ public init(minutes: Int, lastPlayed: Date?) { self.minutes = minutes; self.lastPlayed = lastPlayed }
+}
+
+/// The current account's playtime, by AppID.
+public struct SteamPlaytimeSnapshot: Equatable, Sendable {
+ public let accountID: UInt32
+ public let entries: [UInt32: SteamPlaytimeEntry]
+ public init(accountID: UInt32, entries: [UInt32: SteamPlaytimeEntry]) { self.accountID = accountID; self.entries = entries }
+}
+
+/// Reads Steam's own playtime from `userdata//config/localconfig.vdf`. Only `Playtime` and
+/// `LastPlayed` under `UserLocalConfigStore › Software › Valve › Steam › apps` leave this type: the file
+/// also holds app tickets and other private blocks, which are parsed in passing and never kept.
+/// Nothing is written to Steam.
+public enum SteamPlaytimeReader {
+ static let maximumBytes = 8 * 1024 * 1024
+ private static let steamID64Base: UInt64 = 76_561_197_960_265_728
+
+ /// The account signed in most recently on this Mac, or nil when none has.
+ /// An unreadable `loginusers.vdf` throws: Steam may be rewriting it, which is not "no account".
+ public static func accountID(root: URL) throws -> UInt32? {
+ let users = root.appendingPathComponent("config/loginusers.vdf")
+ guard FileManager.default.fileExists(atPath: users.path) else { return nil }
+ return try accountID(loginUsers: text(at: users))
+ }
+
+ public static func localConfigURL(root: URL, account: UInt32) -> URL {
+ root.appendingPathComponent("userdata/\(account)/config/localconfig.vdf")
+ }
+
+ public static func read(config: URL, account: UInt32) throws -> SteamPlaytimeSnapshot {
+ SteamPlaytimeSnapshot(accountID: account, entries: try entries(localConfig: text(at: config)))
+ }
+
+ /// The account marked `MostRecent`, else the latest `timestamp`.
+ public static func accountID(loginUsers text: String) throws -> UInt32? {
+ guard case .object(let users)? = try KeyValuesDocument(text: text).uniqueValue(for: "users") else { return nil }
+ var best: (account: UInt32, recent: Bool, timestamp: Int)?
+ for user in users {
+ guard case .object(let fields) = user.value, let id = UInt64(user.key), id >= steamID64Base,
+ let account = UInt32(exactly: id - steamID64Base) else { continue }
+ let recent = (try? fields.uniqueString(for: "MostRecent")) == "1"
+ let timestamp = (try? fields.uniqueString(for: "timestamp")).flatMap { Int($0) } ?? 0
+ if let current = best, current.recent != recent ? current.recent : current.timestamp >= timestamp { continue }
+ best = (account, recent, timestamp)
+ }
+ return best?.account
+ }
+
+ /// Every app with a numeric `Playtime`; a `LastPlayed` of 0 or none is no date. A file without its
+ /// root (empty, or mid-rewrite) throws; an account that never played anything has no entries.
+ /// The file only holds data, so `#` keys are ordinary keys, and a repeated block on the path is
+ /// read from its first copy: nothing outside the two fields can fail the read.
+ public static func entries(localConfig text: String) throws -> [UInt32: SteamPlaytimeEntry] {
+ let document = try KeyValuesDocument(text: text, maximumEntries: 500_000, rejectsDirectives: false)
+ guard var node = document.entries.firstValue(for: "UserLocalConfigStore") else { throw KeyValuesError.malformed }
+ for key in ["Software", "Valve", "Steam", "apps"] {
+ guard case .object(let children) = node, let child = children.firstValue(for: key) else { return [:] }
+ node = child
+ }
+ guard case .object(let apps) = node else { return [:] }
+ var result: [UInt32: SteamPlaytimeEntry] = [:]
+ for app in apps {
+ guard let appID = UInt32(app.key), appID > 0, case .object(let fields) = app.value,
+ let minutes = (try? fields.uniqueString(for: "Playtime")).flatMap({ Int($0) }), minutes >= 0 else { continue }
+ let seconds = (try? fields.uniqueString(for: "LastPlayed")).flatMap { TimeInterval($0) } ?? 0
+ result[appID] = SteamPlaytimeEntry(minutes: minutes,
+ lastPlayed: seconds > 0 ? Date(timeIntervalSince1970: seconds) : nil)
+ }
+ return result
+ }
+
+ private static func text(at url: URL) throws -> String {
+ let data = try InstallationFileSnapshot.read(at: url, maximumBytes: maximumBytes).data
+ guard let text = String(data: data, encoding: .utf8) else { throw KeyValuesError.malformed }
+ return text
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeSync.swift b/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeSync.swift
new file mode 100644
index 00000000..00c576c7
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeSync.swift
@@ -0,0 +1,127 @@
+import Foundation
+
+/// Which `localconfig.vdf` was read, and its modification date then.
+public struct SteamFileStamp: Equatable, Sendable {
+ public let file: URL
+ public let modified: Date
+ public init(file: URL, modified: Date) { self.file = file; self.modified = modified }
+}
+
+/// One look at Steam's files, taken off the main thread.
+public enum SteamPlaytimeReading: Equatable, Sendable {
+ /// No account has signed in on this Mac, or the account has no `localconfig.vdf`.
+ case noAccount
+ /// The file has not changed since `known`.
+ case unchanged(accountID: UInt32)
+ /// A file could not be read or parsed (Steam may be rewriting it); the account when known.
+ case failed(accountID: UInt32?)
+ case read(SteamPlaytimeSnapshot, SteamFileStamp)
+
+ /// Reads only when the file's modification date moved since `known`.
+ public static func take(root: URL, known: SteamFileStamp?) -> Self {
+ let account: UInt32
+ do {
+ guard let found = try SteamPlaytimeReader.accountID(root: root) else { return .noAccount }
+ account = found
+ } catch { return .failed(accountID: nil) }
+ let file = SteamPlaytimeReader.localConfigURL(root: root, account: account)
+ guard FileManager.default.fileExists(atPath: file.path) else { return .noAccount }
+ guard let modified = try? file.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
+ else { return .failed(accountID: account) }
+ let stamp = SteamFileStamp(file: file, modified: modified)
+ if stamp == known { return .unchanged(accountID: account) }
+ do { return .read(try SteamPlaytimeReader.read(config: file, account: account), stamp) }
+ catch { return .failed(accountID: account) }
+ }
+}
+
+/// What each reading does to the saved baselines and to the totals shown. A failure keeps the last good
+/// totals, unless they belong to another account; only "no account" clears them.
+public struct SteamPlaytimeSync: Equatable, Sendable {
+ public enum Result: Equatable, Sendable {
+ /// Totals for `PlaySessionStore.setExternal`; `save` when the baselines changed.
+ case publish([UUID: ExternalPlaytime], save: Bool)
+ case clear
+ }
+
+ public private(set) var baselines: SteamPlaytimeBaselines
+ /// The last file read in full; a failed reading leaves it, so the next one tries again.
+ public private(set) var stamp: SteamFileStamp?
+ /// The account the last reading named, so a reading that cannot name one does not bring back
+ /// totals already hidden for another account.
+ private var lastAccount: UInt32?
+
+ public init(baselines: SteamPlaytimeBaselines) { self.baselines = baselines }
+
+ /// The Steam folder changed: the next reading reads in full.
+ public mutating func resetStamp() { stamp = nil }
+
+ /// `shownTotal(game, old)` is the game's total under its old baseline (`PlaySessionStore.totalDuration(for:with:)`),
+ /// so a rising Steam value can carry what that baseline showed (`SteamPlaytimeBaseline.carry`), whatever is
+ /// published at the moment.
+ public mutating func handle(_ reading: SteamPlaytimeReading, games: [CatalogGame],
+ shownTotal: (UUID, ExternalPlaytime) -> TimeInterval, now: Date) -> Result {
+ switch reading {
+ case .noAccount:
+ stamp = nil
+ lastAccount = nil
+ return .clear
+ case .unchanged(let account), .failed(let account?):
+ lastAccount = account
+ guard baselines.accountID == account else { return .clear }
+ return .publish(baselines.external(for: games), save: false)
+ case .failed(nil):
+ guard lastAccount == nil || lastAccount == baselines.accountID else { return .clear }
+ return .publish(baselines.external(for: games), save: false)
+ case .read(let snapshot, let newStamp):
+ lastAccount = snapshot.accountID
+ var shown: [UInt32: TimeInterval] = [:]
+ if snapshot.accountID == baselines.accountID {
+ let old = baselines.external(for: games)
+ for game in games {
+ if let appID = game.steamGame?.appID, let base = old[game.id] { shown[appID] = shownTotal(game.id, base) }
+ }
+ }
+ let changed = baselines.apply(snapshot, now: now, previousTotals: shown)
+ stamp = newStamp
+ return .publish(baselines.external(for: games), save: changed)
+ }
+ }
+}
+
+/// One read of Steam's files at a time. A request during a read is served by one more read when it
+/// finishes; a read whose purpose no longer holds (another Steam folder) is not applied and is read
+/// again; after `stop` nothing is applied or read again.
+public struct SteamPlaytimeReadQueue: Equatable, Sendable {
+ public private(set) var isReading = false
+ private var generation = 0
+ private var again = false
+
+ public init() {}
+
+ /// The ticket to start a read, or nil while one runs.
+ public mutating func request() -> Int? {
+ if isReading { again = true; return nil }
+ isReading = true
+ return generation
+ }
+
+ /// A read in progress no longer applies; one more read follows it.
+ public mutating func invalidate() {
+ generation += 1
+ again = isReading
+ }
+
+ /// Nothing more is wanted: the read in progress is not applied and no read follows.
+ public mutating func stop() {
+ generation += 1
+ again = false
+ }
+
+ /// Whether to apply the finished read's result, and whether to read again.
+ public mutating func finish(_ ticket: Int) -> (apply: Bool, readAgain: Bool) {
+ isReading = false
+ defer { again = false }
+ return (ticket == generation, again)
+ }
+}
diff --git a/Sources/NXLibraryCore/Services/SteamGridDBArt.swift b/Sources/NXLibraryCore/Services/SteamGridDBArt.swift
index b3511810..2b6ebf53 100644
--- a/Sources/NXLibraryCore/Services/SteamGridDBArt.swift
+++ b/Sources/NXLibraryCore/Services/SteamGridDBArt.swift
@@ -9,8 +9,7 @@ public struct SteamGridDBKey {
public init(url: URL = SteamGridDBKey.defaultURL()) { self.url = url }
public static func defaultURL() -> URL {
- FileManager.default.homeDirectoryForCurrentUser
- .appendingPathComponent("Library/Application Support/NXLibrary/steamgriddb-api-key")
+ AppData.supportRoot.appendingPathComponent("steamgriddb-api-key")
}
/// A key as SteamGridDB writes it: letters and digits only (its keys are 32 hex digits).
@@ -71,7 +70,7 @@ public enum SteamGridDBArt {
var request = URLRequest(url: url)
request.timeoutInterval = 15
request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
- request.setValue("NXLibrary/0.1 (macOS; personal app)", forHTTPHeaderField: "User-Agent")
+ request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent")
return request
}
diff --git a/Sources/NXLibraryCore/Services/StorageManager.swift b/Sources/NXLibraryCore/Services/StorageManager.swift
index 608f0868..670928a9 100644
--- a/Sources/NXLibraryCore/Services/StorageManager.swift
+++ b/Sources/NXLibraryCore/Services/StorageManager.swift
@@ -34,8 +34,7 @@ public final class StorageManager {
private let fm: FileManager
public init(
- supportRoot: URL = FileManager.default.homeDirectoryForCurrentUser
- .appendingPathComponent("Library/Application Support/NXLibrary"),
+ supportRoot: URL = AppData.supportRoot,
applicationsRoot: URL = URL(fileURLWithPath: NSHomeDirectory())
.appendingPathComponent("Applications"),
logsRoot: URL = FileManager.default.homeDirectoryForCurrentUser
diff --git a/Sources/NXLibraryCore/Services/UpstreamChecker.swift b/Sources/NXLibraryCore/Services/UpstreamChecker.swift
index f169eb23..887d69f7 100644
--- a/Sources/NXLibraryCore/Services/UpstreamChecker.swift
+++ b/Sources/NXLibraryCore/Services/UpstreamChecker.swift
@@ -120,7 +120,7 @@ public final class UpstreamChecker {
request.timeoutInterval = 20
request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")
request.setValue("2022-11-28", forHTTPHeaderField: "X-GitHub-Api-Version")
- request.setValue("NXLibrary/0.1", forHTTPHeaderField: "User-Agent")
+ request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent")
let (data, http) = try await client.data(for: request)
let message = (try? JSONDecoder().decode(APIError.self, from: data))?.message
diff --git a/Sources/NXLibraryCore/Services/WikidataRatings.swift b/Sources/NXLibraryCore/Services/WikidataRatings.swift
new file mode 100644
index 00000000..94f1e176
--- /dev/null
+++ b/Sources/NXLibraryCore/Services/WikidataRatings.swift
@@ -0,0 +1,130 @@
+import Foundation
+
+/// Narrow Wikidata contract: exact video-game identity and referenced /100 critic aggregates.
+/// Source/metric IDs come from the inspected P444/P447/P459 statements, not label guesses.
+public enum WikidataRatings {
+ static func isItemID(_ value: String) -> Bool {
+ value.first == "Q" && value.count > 1 && value.dropFirst().allSatisfy { $0.isASCII && $0.isNumber }
+ }
+ private static func normalized(_ value: String) -> String {
+ String(value.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: Locale(identifier: "en_US_POSIX"))
+ .unicodeScalars.filter { CharacterSet.alphanumerics.contains($0) })
+ }
+ public static func searchURL(name: String) -> URL? {
+ guard !name.isEmpty, name.count <= 300 else { return nil }
+ // Store trademarks prevent wbsearchentities from finding an otherwise exact title.
+ // Keep edition/sequel words: those carry identity, unlike the trademark marks.
+ let clean = ["™", "®", "©"].reduce(name) { $0.replacingOccurrences(of: $1, with: "") }
+ .split(whereSeparator: \.isWhitespace).joined(separator: " ")
+ guard !clean.isEmpty else { return nil }
+ return url(["action": "wbsearchentities", "search": clean, "language": "en", "type": "item", "limit": "5"])
+ }
+ public static func steamSearchURL(appID: UInt32) -> URL? {
+ guard appID > 0 else { return nil }
+ return url(["action": "query", "list": "search", "srsearch": "haswbstatement:P1733=\(appID)",
+ "srnamespace": "0", "srlimit": "5", "srprop": ""])
+ }
+ public static func steamIDs(in data: Data) throws -> [String] {
+ let root = try object(data)
+ guard let query = root["query"] as? [String: Any], let search = query["search"] as? [[String: Any]]
+ else { throw URLError(.cannotParseResponse) }
+ return Array(Set(search.compactMap { item -> String? in
+ guard let id = item["title"] as? String, isItemID(id), item["ns"] as? Int == 0 else { return nil }
+ return id
+ })).sorted()
+ }
+ public static func entitiesURL(ids: [String]) -> URL? {
+ guard !ids.isEmpty, ids.count <= 5, ids.allSatisfy(isItemID) else { return nil }
+ return url(["action": "wbgetentities", "ids": ids.joined(separator: "|"), "props": "claims"])
+ }
+ private static func url(_ values: [String: String]) -> URL? {
+ var components = URLComponents(string: "https://www.wikidata.org/w/api.php")!
+ components.queryItems = (values.merging(["format": "json", "maxlag": "5"], uniquingKeysWith: { _, b in b }))
+ .sorted { $0.key < $1.key }.map { .init(name: $0.key, value: $0.value) }
+ return components.url
+ }
+ public static func ids(in data: Data, name: String) throws -> [String] {
+ let root = try object(data)
+ guard let search = root["search"] as? [[String: Any]] else { throw URLError(.cannotParseResponse) }
+ let target = normalized(name)
+ guard !target.isEmpty else { return [] }
+ return Array(Set(search.compactMap { item -> String? in
+ guard let id = item["id"] as? String, isItemID(id) else { return nil }
+ var names = [item["label"] as? String].compactMap { $0 } + (item["aliases"] as? [String] ?? [])
+ if let match = item["match"] as? [String: String], match["type"] == "alias", let text = match["text"] {
+ names.append(text)
+ }
+ return names.contains { normalized($0) == target } ? id : nil
+ })).sorted()
+ }
+ public static func rating(in data: Data, ids: [String], query: CriticRatingQuery,
+ requireSteamID: Bool = false) throws -> CriticRating? {
+ let root = try object(data)
+ guard let entities = root["entities"] as? [String: [String: Any]],
+ ids.allSatisfy({ entities[$0] != nil }) else { throw URLError(.cannotParseResponse) }
+ let matched = ids.filter { id in
+ guard let claims = entities[id]?["claims"] as? [String: [[String: Any]]],
+ claimItems(claims["P31"] ?? []).contains("Q7889") else { return false }
+ let steam = (claims["P1733"] ?? []).filter { ($0["rank"] as? String) != "deprecated" }
+ .compactMap { ($0["mainsnak"] as? [String: Any]).flatMap(value) as? String }
+ if let expected = query.steamAppID, requireSteamID || !steam.isEmpty { return steam.contains(String(expected)) }
+ return true
+ }
+ guard matched.count == 1, let id = matched.first,
+ let claims = entities[id]?["claims"] as? [String: [[String: Any]]] else { return nil }
+ let ratings = (claims["P444"] ?? []).compactMap { parse($0, entityID: id, platform: query.platform.wikidataID) }
+ return ratings.sorted { a, b in
+ if a.platforms.isEmpty != b.platforms.isEmpty { return !a.platforms.isEmpty }
+ if a.source.priority != b.source.priority { return a.source.priority < b.source.priority }
+ if a.scoreDate != b.scoreDate { return (a.scoreDate ?? "") > (b.scoreDate ?? "") }
+ return (a.statementID ?? "") < (b.statementID ?? "")
+ }.first
+ }
+ private static func parse(_ claim: [String: Any], entityID: String, platform: String) -> CriticRating? {
+ guard claim["rank"] as? String != "deprecated",
+ let raw = (claim["mainsnak"] as? [String: Any]).flatMap(value) as? String,
+ let statement = claim["id"] as? String, statement.hasPrefix(entityID + "$"),
+ let quals = claim["qualifiers"] as? [String: [[String: Any]]] else { return nil }
+ let issuerSnaks = quals["P447"] ?? []
+ let issuers = issuerSnaks.compactMap(item)
+ guard issuerSnaks.count == 1, issuers.count == 1 else { return nil }
+ let source: CriticRating.Source
+ let metric: String
+ switch issuers[0] {
+ case "Q21039459": source = .openCritic; metric = "Q114712322"
+ case "Q150248": source = .metacritic; metric = "Q106515043"
+ case "Q131917281": source = .criticDB; metric = "Q132178503"
+ default: return nil
+ }
+ let methods = (quals["P459"] ?? []).compactMap(item)
+ guard methods.count == (quals["P459"] ?? []).count else { return nil }
+ guard methods == [metric] || (methods.isEmpty && source == .metacritic) else { return nil }
+ let parts = raw.split(separator: "/", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
+ guard parts.count == 2, let score = Double(parts[0]), Double(parts[1]) == 100,
+ score.isFinite, (0...100).contains(score) else { return nil }
+ let platforms = (quals["P400"] ?? []).compactMap(item)
+ guard platforms.count == (quals["P400"] ?? []).count else { return nil }
+ guard platforms.isEmpty || platforms.contains(platform) else { return nil }
+ let refs = (claim["references"] as? [[String: Any]] ?? []).compactMap { $0["snaks"] as? [String: [[String: Any]]] }
+ let urls = refs.flatMap { $0["P854"] ?? [] }.compactMap { value($0) as? String }.compactMap(URL.init(string:))
+ .filter { $0.scheme == "https" && $0.host != nil && $0.user == nil && $0.password == nil }
+ let items = refs.flatMap { $0["P248"] ?? [] }.compactMap(item)
+ guard !urls.isEmpty || !items.isEmpty else { return nil }
+ let date = (quals["P585"] ?? []).compactMap { value($0) as? [String: Any] }.compactMap { $0["time"] as? String }.sorted().last
+ return CriticRating(score: score, source: source, entityID: entityID, statementID: statement,
+ referenceURLs: urls, referenceItems: items, scoreDate: date, platforms: platforms)
+ }
+ private static func value(_ snak: [String: Any]) -> Any? { (snak["datavalue"] as? [String: Any])?["value"] }
+ private static func item(_ snak: [String: Any]) -> String? {
+ guard let id = (value(snak) as? [String: Any])?["id"] as? String, isItemID(id) else { return nil }
+ return id
+ }
+ private static func claimItems(_ claims: [[String: Any]]) -> [String] {
+ claims.filter { $0["rank"] as? String != "deprecated" }.compactMap { ($0["mainsnak"] as? [String: Any]).flatMap(item) }
+ }
+ private static func object(_ data: Data) throws -> [String: Any] {
+ guard data.count <= 4_194_304, let root = try JSONSerialization.jsonObject(with: data) as? [String: Any],
+ root["error"] == nil else { throw URLError(.cannotParseResponse) }
+ return root
+ }
+}
diff --git a/Tests/CatalogAppChecks/NoticeHost.swift b/Tests/CatalogAppChecks/NoticeHost.swift
new file mode 100644
index 00000000..a230b4d6
--- /dev/null
+++ b/Tests/CatalogAppChecks/NoticeHost.swift
@@ -0,0 +1,54 @@
+import Foundation
+@testable import NXLibraryCore
+
+struct SettingsNotice { var retry: (() -> Void)?; var onDismiss: (() -> Void)? = nil }
+final class AppViewModel {
+ let catalogRepository: CatalogRepository
+ var personalizations = CatalogPersonalizations.empty
+ var catalogBuildRecoveries = CatalogBuildRecoveries()
+ var logs: [LogEntry] = []
+ var alertMessage: String?
+ var settingsNotice: SettingsNotice?
+ var isBuilding = false
+ init(_ repository: CatalogRepository) { catalogRepository = repository }
+ func reportLibrarySaveFailure(_ error: Error) { alertMessage = error.localizedDescription }
+ func showSettingsNotice(title: String, message: String, actionTitle: String = "Retry", cancelTitle: String = "Back", retry: (() -> Void)? = nil) {
+ settingsNotice = SettingsNotice(retry: retry)
+ }
+ func applyCatalog(_ document: CatalogDocument) {}
+ func presentInstallFailure(for: PortedGame, error: String) {}
+}
+func require(_ ok: @autoclosure () -> Bool, _ message: String) throws {
+ if !ok() { throw NSError(domain: "NoticeProbe", code: 1, userInfo: [NSLocalizedDescriptionKey: message]) }
+}
+func run() throws {
+let root = FileManager.default.temporaryDirectory.appendingPathComponent("CatalogNotice-" + UUID().uuidString)
+try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+defer { try? FileManager.default.removeItem(at: root) }
+let store = CatalogStore(directory: root)
+var catalog = try store.loadOrMigrate()
+let game = PortedGame(name: "Generated fixture", url: root.appendingPathComponent("Game.app"), platform: .macApp, sizeBytes: 1, modificationDate: Date())
+catalog.games = [.init(nxnative: game)]
+_ = try store.save(catalog, expectedRevision: catalog.revision)
+let failing = CatalogStore(directory: root, publication: .init { _, _, _, _ in throw POSIXError(.ENOSPC) })
+let model = AppViewModel(CatalogRepository(store: failing))
+model.reportCatalogFailure(POSIXError(.ENOSPC))
+try require(model.alertMessage == nil, "Catalog failure published legacy alert and can replace its Retry notice")
+try require(model.settingsNotice?.retry != nil, "Catalog reload Retry missing")
+_ = model.persistBuildOutcome(game)
+try require(model.alertMessage == nil, "Build failure published legacy alert and can replace its save Retry")
+try require(model.settingsNotice?.retry != nil, "Build save Retry missing")
+try require(model.catalogBuildRecoveries[game.id] != nil, "Build recovery missing")
+// Deliver a previously queued legacy alert after the retry notice exists.
+model.alertMessage = "An earlier, unrelated alert"
+let host = LegacyNoticeHost(viewModel: model)
+host.deliver()
+try require(model.settingsNotice?.retry != nil, "Queued legacy alert replaced the structured save Retry")
+try require(model.alertMessage != nil, "Queued legacy alert was lost")
+host.dismiss()
+try require(model.alertMessage == nil, "Deferred legacy alert was not presented after dismissal")
+try require(model.settingsNotice?.retry == nil, "Expected the deferred generic notice after dismissal")
+print("Actual catalog helpers and legacy bridge preserve Retry and defer unrelated alerts.")
+
+}
+do { try run() } catch { FileHandle.standardError.write(Data((error.localizedDescription + "\n").utf8)); exit(1) }
diff --git a/Tests/CatalogAppChecks/run_achievement_scroll.py b/Tests/CatalogAppChecks/run_achievement_scroll.py
new file mode 100644
index 00000000..74c088c3
--- /dev/null
+++ b/Tests/CatalogAppChecks/run_achievement_scroll.py
@@ -0,0 +1,166 @@
+#!/usr/bin/env python3
+"""Exercise actual achievement list/model lifecycle in an offscreen SwiftUI host.
+
+No windows, screenshots or UI automation. Graphics and external data use small
+stand-ins; the list, selection model, scroll model and geometry group are real.
+Run after swift test on macOS.
+"""
+from pathlib import Path
+import os
+import subprocess
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[2]
+BIN = ROOT / '.build/debug'
+source = (ROOT / 'Sources/NXLibrary/Views/Spotlight/AchievementsScreen.swift').read_text()
+start = source.index('private struct AchievementsList: View')
+end = source.index('\n/// The trophies,', start)
+
+host = r'''
+import AppKit
+import SwiftUI
+import NXLibraryCore
+
+struct ProbeCanvas {
+ var scale: CGFloat = 1
+ func u(_ value: CGFloat) -> CGFloat { value * scale }
+}
+private struct CanvasKey: EnvironmentKey { static let defaultValue = ProbeCanvas() }
+private struct MotionKey: EnvironmentKey { static let defaultValue = true }
+extension EnvironmentValues {
+ var seleneCanvas: ProbeCanvas {
+ get { self[CanvasKey.self] } set { self[CanvasKey.self] = newValue }
+ }
+ var seleneReduceMotion: Bool {
+ get { self[MotionKey.self] } set { self[MotionKey.self] = newValue }
+ }
+}
+extension View {
+ func seleneFont(_ size: CGFloat) -> some View { font(.system(size: size)) }
+}
+enum SeleneTheme { static let ink60 = Color.gray }
+enum DetailScroll { static let glide = Animation.spring(response: 0.3, dampingFraction: 1) }
+enum AchievementsScreen {
+ static let rowHeight: CGFloat = 96, rowSpacing: CGFloat = 16, ring: CGFloat = 6
+ static let listWidth: CGFloat = 1700, topFade: CGFloat = 40
+ static let bottomFade: CGFloat = 110, hintsBand: CGFloat = 84, bottomRoom: CGFloat = 194
+}
+struct AchievementsScreenRow: View {
+ let row: AchievementRow
+ let appID: UInt32
+ let focused: Bool
+ var body: some View { Text(row.name).frame(width: 1700, height: 96) }
+}
+let summary = AchievementSummary(achievements: (0..<41).map {
+ SteamAchievement(apiName: "generated-\($0)", name: "Row \($0)", description: "Generated fixture",
+ hidden: false, icon: nil, grayIcon: nil, unlockedAt: nil)
+}, percents: [:])
+let rows = summary.rows(.all)
+
+@MainActor final class Owner: ObservableObject {
+ @Published var model: AchievementsScreenModel? = AchievementsScreenModel(ids: rows.map(\.id))
+ @Published var reducedMotion = false
+ @Published var height: CGFloat = 400
+}
+struct ScreenHost: View {
+ @ObservedObject var model: AchievementsScreenModel
+ var body: some View {
+ ZStack {
+ AchievementsList(scroll: model.scroll, model: model, rows: rows, focused: model.state.index,
+ appID: 42, onFocus: { model.focus($0) })
+ if model.state.isDetailOpen { Color.black.opacity(0.5).transition(.opacity) }
+ }
+ .animation(.easeOut(duration: 0.2), value: model.state.isDetailOpen)
+ }
+}
+struct Probe: View {
+ @ObservedObject var owner: Owner
+ var body: some View {
+ ZStack {
+ if let model = owner.model { ScreenHost(model: model).transition(.opacity) }
+ }
+ .frame(width: 1712, height: owner.height)
+ .environment(\.seleneReduceMotion, owner.reducedMotion)
+ .animation(.timingCurve(0.32, 0.72, 0, 1, duration: 0.32), value: owner.model != nil)
+ }
+}
+
+@main struct Check {
+ @MainActor static func main() {
+ NSApplication.shared.setActivationPolicy(.prohibited)
+ var failures = 0
+ func require(_ condition: Bool, _ message: String) {
+ if !condition { failures += 1; print("FAIL: " + message) }
+ }
+ for reducedMotion in [false, true] {
+ let owner = Owner()
+ owner.reducedMotion = reducedMotion
+ let host = NSHostingView(rootView: Probe(owner: owner))
+ host.frame = CGRect(x: 0, y: 0, width: 1712, height: 400)
+ func settle(_ steps: Int = 10) {
+ for _ in 0.. 4000 && model.scroll.state.visible == owner.height,
+ label + ": current list receives its geometry")
+ require(model.scroll.state.offset > 1000, label + ": viewport follows selection")
+ }
+ settle()
+ walk("First open")
+
+ owner.model!.focus(0)
+ for _ in 0..<5 {
+ _ = owner.model!.handle(.confirm, summary: summary)
+ settle(1)
+ _ = owner.model!.handle(.cancel, summary: summary)
+ settle(1)
+ }
+ walk("Repeated first-row details")
+
+ // The outgoing view is still in its 320 ms transition when the new model arrives.
+ for index in 0..<3 {
+ owner.model = nil
+ settle(1)
+ owner.model = AchievementsScreenModel(ids: rows.map(\.id))
+ settle()
+ walk("Rapid reopening \(index), reduced motion \(reducedMotion)")
+ }
+
+ owner.model = nil
+ settle(40)
+ owner.model = AchievementsScreenModel(ids: rows.map(\.id))
+ settle()
+ walk("Reopening after transition")
+ owner.height = 320
+ host.frame.size.height = 320
+ settle()
+ require(owner.model!.scroll.state.visible == 320, "Resizing reports the new viewport")
+ require(host.window == nil, "Probe must never display a window")
+ }
+ if failures > 0 { exit(1) }
+ print("Achievement scroll checks passed: first-row details, rapid/settled reopening, resize and reduced motion. No windows displayed.")
+ }
+}
+''' + source[start:end]
+
+with tempfile.TemporaryDirectory(prefix='achievement-scroll-check-') as folder:
+ scratch = Path(folder)
+ swift = scratch / 'check.swift'
+ swift.write_text(host)
+ executable = scratch / 'check'
+ subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(swift),
+ str(ROOT / 'Sources/NXLibrary/Models/GamepadType.swift'),
+ str(ROOT / 'Sources/NXLibrary/ViewModels/AchievementsScreenModel.swift'),
+ str(ROOT / 'Sources/NXLibrary/ViewModels/ListScroll.swift'),
+ str(ROOT / 'Sources/NXLibrary/Views/Components/GlideGroup.swift'),
+ str(BIN / 'NXLibraryCore.o'), '-o', str(executable)], cwd=ROOT, check=True)
+ subprocess.run([str(executable)], check=True,
+ env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN)))
diff --git a/Tests/CatalogAppChecks/run_artwork_return.py b/Tests/CatalogAppChecks/run_artwork_return.py
new file mode 100644
index 00000000..d6aed328
--- /dev/null
+++ b/Tests/CatalogAppChecks/run_artwork_return.py
@@ -0,0 +1,369 @@
+#!/usr/bin/env python3
+"""Check the artwork chosen by a recreated view before its first async task.
+
+Compiles the actual artwork views and task bodies. An Image value records its
+input instead of rendering; no window, screenshot or UI automation. Uses real
+decoding and generated files, isolated picks and no network/player data.
+"""
+from pathlib import Path
+import os
+import plistlib
+import struct
+import subprocess
+import tempfile
+import zlib
+import argparse
+
+ROOT = Path(__file__).resolve().parents[2]
+BIN = ROOT / '.build/debug'
+parser = argparse.ArgumentParser()
+parser.add_argument('--source-root', type=Path, default=ROOT,
+ help='Optional source snapshot for regression checks; Core stays in the main checkout.')
+SOURCE = parser.parse_args().source_root
+
+
+def task_body(source):
+ start = source.index('.task(id:')
+ opening = source.index('{', start)
+ depth, end = 1, opening + 1
+ while depth:
+ depth += (source[end] == '{') - (source[end] == '}')
+ end += 1
+ return source[opening + 1:end - 1]
+
+
+with tempfile.TemporaryDirectory(prefix='arcane-artwork-return-') as temporary:
+ scratch = Path(temporary)
+ for filename, path, old, new in (
+ ('Native.swift', 'Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift',
+ 'ArtworkPicks.shared', 'Fixture.nativePicks'),
+ ('Steam.swift', 'Sources/NXLibrary/Views/Catalog/SteamArtwork.swift',
+ 'SteamPersonalizations.shared.artwork', 'Fixture.steamPicks'),
+ ):
+ source = (SOURCE / path).read_text().replace(old, new).replace('private ', '')
+ typename = 'SpotlightTileArtwork' if filename == 'Native.swift' else 'SteamArtwork'
+ source += '\nextension ' + typename + ' { func loadForCheck() async {\n' + task_body(source) + '\n} }\n'
+ (scratch / filename).write_text(source)
+ def chunk(kind, data):
+ return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
+ pixels = (b'\0' + b'\xe0\x30\x90\xff' * 16) * 16
+ png = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 16, 16, 8, 6, 0, 0, 0))
+ png += chunk(b'IDAT', zlib.compress(pixels)) + chunk(b'IEND', b'')
+ (scratch / 'image.png').write_bytes(png)
+ pixels2 = (b'\0' + b'\x10\xe0\x10\xff' * 16) * 16
+ png2 = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 16, 16, 8, 6, 0, 0, 0))
+ png2 += chunk(b'IDAT', zlib.compress(pixels2)) + chunk(b'IEND', b'')
+ (scratch / 'image2.png').write_bytes(png2)
+ pixels3 = (b'\0' + b'\x20\x40\xf0\xff' * 16) * 16
+ png3 = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 16, 16, 8, 6, 0, 0, 0))
+ png3 += chunk(b'IDAT', zlib.compress(pixels3)) + chunk(b'IEND', b'')
+ (scratch / 'image3.png').write_bytes(png3)
+ app = scratch / 'Fixture.app'
+ (app / 'Contents/Resources').mkdir(parents=True)
+ (app / 'Contents/Resources/Icon.icns').write_bytes(png)
+ (app / 'Contents/Info.plist').write_bytes(plistlib.dumps({'CFBundleIconFile': 'Icon'}))
+ automatic = scratch / 'artwork/0100000000001000/square.png'
+ automatic.parent.mkdir(parents=True)
+ automatic.write_bytes(png)
+ host = scratch / 'check.swift'
+ host.write_text(r'''
+import SwiftUI
+import AppKit
+@testable import NXLibraryCore
+
+@MainActor enum Fixture {
+ static let root = URL(fileURLWithPath: CommandLine.arguments[1])
+ static let nativePicks = ArtworkPicks(directory: root.appendingPathComponent("native-picks"))
+ static let steamPicks = SteamPersonalizationStore(directory: root.appendingPathComponent("steam-picks"))
+ static let artwork = ArtworkStore(cacheDirectory: root.appendingPathComponent("artwork"))
+}
+@MainActor enum Capture { static var image: NSImage? }
+struct Image: View {
+ init(nsImage: NSImage) { Capture.image = nsImage }
+ init(systemName: String) { Capture.image = nil }
+ func resizable() -> Self { self }
+ func interpolation(_ value: SwiftUI.Image.Interpolation) -> Self { self }
+ var body: some View { Color.clear }
+}
+enum SeleneTheme { static var glassSolid: Color { .gray } }
+struct Canvas { func u(_ value: CGFloat) -> CGFloat { value } }
+struct CanvasKey: EnvironmentKey { static let defaultValue = Canvas() }
+extension EnvironmentValues {
+ var seleneCanvas: Canvas { get { self[CanvasKey.self] } set { self[CanvasKey.self] = newValue } }
+}
+@MainActor enum GameIconProvider {
+ static let generic = NSImage(size: NSSize(width: 32, height: 32))
+ static var own: NSImage?
+ static func squareArt(for game: PortedGame) -> NSImage? { own }
+ static func icon(for game: PortedGame) -> NSImage { generic }
+}
+@MainActor enum AppViewModel { static var automaticIconArtwork: ArtworkStore { Fixture.artwork } }
+@MainActor enum OnlineArtwork {
+ static func find(names: [String], slot: ArtworkSlot? = nil,
+ platform: CriticRatingQuery.Platform = .switch) async -> [ArtworkCandidate] { [] }
+}
+@main struct Check {
+ @MainActor static func main() async throws {
+ var failures = 0
+ func require(_ value: Bool, _ message: String) {
+ if value { print("PASS: " + message) }
+ else { failures += 1; print("FAIL: " + message) }
+ }
+ func draw(_ view: V) -> NSImage? {
+ Capture.image = nil
+ _ = view.body
+ return Capture.image
+ }
+ let root = Fixture.root
+ let png = try Data(contentsOf: root.appendingPathComponent("image.png"))
+ var native = PortedGame(name: "Fixture", url: root.appendingPathComponent("not-built"),
+ platform: .macApp, sizeBytes: 0, modificationDate: Date())
+ native.titleId = "0100000000001000"
+ let automatic = SpotlightTileArtwork(game: native, side: 160, artwork: Fixture.artwork, ownIconFirst: true)
+ await automatic.loadForCheck()
+ let returned = SpotlightTileArtwork(game: native, side: 160, artwork: Fixture.artwork, ownIconFirst: true)
+ require(draw(returned).map { $0 !== GameIconProvider.generic } == true,
+ "nxnative automatic art is present before the recreated view's task")
+
+ try Fixture.nativePicks.save(png, titleID: native.titleId!, slot: .icon)
+ let personal = SpotlightTileArtwork(game: native, side: 160, artwork: Fixture.artwork, ownIconFirst: true)
+ await personal.loadForCheck()
+ let personalReturn = SpotlightTileArtwork(game: native, side: 160, artwork: Fixture.artwork, ownIconFirst: true)
+ let personalImage = draw(personalReturn)
+ require(personalImage.map { $0 !== GameIconProvider.generic } == true,
+ "nxnative personal art is present before the recreated view's task")
+ Fixture.nativePicks.remove(titleID: native.titleId!, slot: .icon)
+ let noPick = SpotlightTileArtwork(game: native, side: 160, artwork: Fixture.artwork, ownIconFirst: true)
+ require(personalImage == nil || draw(noPick) !== personalImage,
+ "removing a pick does not reuse its decoded image")
+
+ let app = root.appendingPathComponent("Fixture.app")
+ let observed = NativeMacApplication(url: app, executableURL: app.appendingPathComponent("Contents/MacOS/main"),
+ bundleIdentifier: "fixture", name: "Fixture", architectures: [.arm64], isDeclaredGame: true, fileObservations: [])
+ var steam = SteamCatalogGame(appID: 10, name: "Fixture")
+ steam.installations = [.init(libraryURL: root, contentURL: root,
+ applications: [CatalogNativeApplication(observed)], availability: .available)]
+ let game = CatalogGame(steam: steam)
+ let square = SteamArtwork(game: game, slot: .icon)
+ await square.loadForCheck()
+ let squareReturn = SteamArtwork(game: game, slot: .icon)
+ require(draw(squareReturn) != nil, "Steam app artwork is present before the recreated view's task")
+
+ func color(_ image: NSImage?) -> String? {
+ guard let data = image?.tiffRepresentation, let bitmap = NSBitmapImageRep(data: data),
+ let pixel = bitmap.colorAt(x: 0, y: 0)?.usingColorSpace(.deviceRGB) else { return nil }
+ return "\(Int((pixel.redComponent * 255).rounded())),\(Int((pixel.greenComponent * 255).rounded())),\(Int((pixel.blueComponent * 255).rounded()))"
+ }
+ let iconFile = app.appendingPathComponent("Contents/Resources/Icon.icns")
+ let replacement = try Data(contentsOf: root.appendingPathComponent("image2.png"))
+ try replacement.write(to: iconFile, options: .atomic)
+ var updatedSteam = steam
+ updatedSteam.installations[0].buildID = "updated-build"
+ let updatedGame = CatalogGame(steam: updatedSteam)
+ await SteamArtwork(game: updatedGame, slot: .icon).loadForCheck()
+ let freshFile = await GameArtLoader.decode(at: iconFile, maxPixelSize: 512)
+ require(color(draw(SteamArtwork(game: updatedGame, slot: .icon))) == color(freshFile),
+ "Steam update at the same app path replaces the decoded icon")
+ // Even a file replaced without a new build ID is revalidated behind the warm first frame.
+ try Data(contentsOf: root.appendingPathComponent("image3.png")).write(to: iconFile, options: .atomic)
+ await SteamArtwork(game: updatedGame, slot: .icon).loadForCheck()
+ let resetFile = await GameArtLoader.decode(at: iconFile, maxPixelSize: 512)
+ require(color(draw(SteamArtwork(game: updatedGame, slot: .icon))) == color(resetFile),
+ "an unchanged build ID cannot keep stale pixels indefinitely")
+
+ try Fixture.steamPicks.save(fields: [:], images: [.icon: png], automatic: [], titleID: game.personalizationReference.key)
+ let steamPick = SteamArtwork(game: game, slot: .icon)
+ await steamPick.loadForCheck()
+ let steamPickReturn = SteamArtwork(game: game, slot: .icon)
+ let steamPersonal = draw(steamPickReturn)
+ require(steamPersonal != nil, "Steam personal artwork is present before the recreated view's task")
+ try Fixture.steamPicks.save(fields: [:], images: [:], automatic: [.icon], titleID: game.personalizationReference.key)
+ let steamReset = SteamArtwork(game: game, slot: .icon)
+ require(steamPersonal == nil || draw(steamReset) !== steamPersonal,
+ "Steam Automatic does not reuse the removed personal image")
+ let remoteChanged = SteamArtwork(game: game, slot: .icon, remote: URL(string: "https://fixture.invalid/other.png"))
+ require(steamPersonal == nil || draw(remoteChanged) !== steamPersonal,
+ "a different request cannot borrow the previous request's decoded image")
+ exit(failures == 0 ? 0 : 1)
+ }
+}
+''')
+ executable = scratch / 'check'
+ subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(host),
+ str(scratch / 'Native.swift'), str(scratch / 'Steam.swift'),
+ str(ROOT / 'Sources/NXLibrary/Views/Spotlight/GameArtLoader.swift'),
+ str(ROOT / 'Sources/NXLibrary/Views/Theme/CatalogPersonalizationsEnvironment.swift'),
+ str(BIN / 'NXLibraryCore.o'), '-o', str(executable)], check=True)
+ view_result = subprocess.run([str(executable), str(scratch)],
+ env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN)))
+
+ mods = scratch / 'ModsCheck.swift'
+ mods.write_text(r'''
+import Foundation
+import AppKit
+import Combine
+import NXLibraryCore
+
+enum AppData { static let cacheRoot = URL(fileURLWithPath: CommandLine.arguments[1]) }
+struct NoHTTP: ArtworkHTTPClient {
+ func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) { fatalError("Network forbidden") }
+}
+final class GameBananaServices {
+ static let shared = GameBananaServices()
+ let matches = GameBananaMatchStore(file: AppData.cacheRoot.appendingPathComponent("matches.json"))
+ let client = GameBananaClient(http: NoHTTP(), cacheFolder: AppData.cacheRoot.appendingPathComponent("api"), userAgent: "fixture")
+}
+@MainActor final class AppViewModel {
+ let fixtureStore: ModStore
+ var storeMetadata: [UUID: NintendoStoreMetadata] = [:]
+ init(_ store: ModStore) { fixtureStore = store }
+ func modStore(for game: PortedGame) -> ModStore? { fixtureStore }
+}
+@MainActor final class ModsBandHost: ObservableObject {
+ let gameBanana = GameBananaBandModel(client: GameBananaServices.shared.client, matches: GameBananaServices.shared.matches, userAgent: "fixture")
+ var isPanelOpen = false
+ func reloadRecords(viewModel: AppViewModel) {}
+ func stop() { gameBanana.stop(); isPanelOpen = false }
+ func openStoreDetail(_ mod: AvailableMod, game: PortedGame, viewModel: AppViewModel) {}
+}
+enum GameBananaImageView {
+ static func prepare(_ urls: [URL], maxPixelSize: Int) async {}
+ static func prewarm(_ urls: [URL], maxPixelSize: Int) {}
+}
+enum ModsCardCover { static let pixelSize = 700 }
+enum GameBananaBlur {
+ static let bannerRadius = 10.0
+ static func image(for url: URL, radius: Double) async {}
+}
+struct SoundEffectService {
+ enum Cue { case click, error }
+ static let shared = Self()
+ func play(_ cue: Cue) {}
+}
+struct CheckFailure: Error {}
+enum CoverReadGate {
+ static let captured = DispatchSemaphore(value: 0)
+ static let resume = DispatchSemaphore(value: 0)
+ static let completed = DispatchSemaphore(value: 0)
+ static let lock = NSLock()
+ private static var armed = false
+ private static var held: UUID?
+ static func arm() { lock.lock(); armed = true; lock.unlock() }
+ static func didRead(_ id: UUID) {
+ lock.lock()
+ let hold = armed
+ if hold { armed = false; held = id }
+ lock.unlock()
+ if hold {
+ captured.signal()
+ precondition(resume.wait(timeout: .now() + 5) == .success)
+ }
+ }
+ static func finished(_ id: UUID) {
+ lock.lock(); let matches = held == id; lock.unlock()
+ if matches { completed.signal() }
+ }
+}
+@main struct ModsCheck {
+ @MainActor static func waitFor(_ message: String = "async fixture becomes ready", _ condition: () -> Bool) async throws {
+ let deadline = Date().addingTimeInterval(5)
+ while !condition() {
+ guard Date() < deadline else { print("FAIL: " + message); throw CheckFailure() }
+ try await Task.sleep(nanoseconds: 5_000_000)
+ }
+ }
+ static func require(_ condition: Bool, _ message: String) throws {
+ guard condition else { print("FAIL: " + message); throw CheckFailure() }
+ print("PASS: " + message)
+ }
+ @MainActor static func main() async {
+ do { try await check() }
+ catch { print("FAIL: Mods fixture: \(error)"); exit(1) }
+ }
+ @MainActor static func check() async throws {
+ let root = AppData.cacheRoot
+ let tid = "0100000000010000"
+ let mod = AvailableMod(id: 10, rank: 0, name: "Fixture mod", author: "Fixture", avatarURL: nil,
+ images: [URL(string: "https://images.gamebanana.com/img/ss/mods/fixture.png")!], thumbnailURL: nil,
+ version: "", updated: Date(), pageURL: URL(string: "https://gamebanana.com/mods/10")!, description: "", likes: 0, downloads: 0,
+ files: [GameBananaFile(id: 100, name: "fixture.zip", size: 1, downloadURL: URL(string: "https://gamebanana.com/dl/100"), md5: "fixture")])
+ let matches = GameBananaServices.shared.matches
+ try matches.set(.game(id: 1, name: "Fixture", profileURL: URL(string: "https://gamebanana.com/games/1")!), titleID: tid)
+ let snapshots = ModCatalogSnapshots(folder: root.appendingPathComponent("gamebanana/store"))
+ try snapshots.save([mod], gameName: "Fixture", titleID: tid, gameBananaID: 1)
+ let store = ModStore(supportFolder: root.appendingPathComponent("support"), recordsFile: root.appendingPathComponent("records.json"), titleID: tid,
+ canWrite: { true }, trash: { _ in fatalError("Trash forbidden") }, allowsAutomaticMaintenance: false)
+ let folder = store.modsFolder.appendingPathComponent("fixture")
+ try FileManager.default.createDirectory(at: folder.appendingPathComponent("romfs"), withIntermediateDirectories: true)
+ try Data([0]).write(to: folder.appendingPathComponent("romfs/a.bin"))
+ try JSONEncoder().encode([ModRecord(folderName: "fixture", isOn: true, gameBananaModID: 10, gameBananaFileID: 100, md5: "fixture")]).write(to: store.recordsFile)
+ let model = AppViewModel(store)
+ var game = PortedGame(name: "Fixture", url: root.appendingPathComponent("Fixture.app"), platform: .macApp, sizeBytes: 0, modificationDate: Date())
+ game.titleId = tid
+ let host = ModStoreHost()
+ host.loadCover(titleIDs: [tid]); host.open([game], viewModel: model)
+ try await waitFor { host.records[tid]?[10] != nil && !host.cover.isEmpty }
+ let prepared = host.cover
+ host.close()
+ await withCheckedContinuation { continuation in DispatchQueue.main.async { continuation.resume() } }
+ for _ in 0..<10 { await Task.yield() }
+ try require(host.cover == prepared, "closing the store keeps its prepared cover")
+ try FileManager.default.removeItem(at: folder)
+ host.open([game], viewModel: model)
+ try await waitFor("reopening refreshes records after external removal") { host.records[tid]?.isEmpty == true }
+ try require(host.chip(for: ModCatalogEntry(mod: mod, titleID: tid, gameName: "Fixture")) == nil,
+ "reopening refreshes badges after a mod was removed elsewhere")
+ host.close()
+ try matches.set(.noPage, titleID: tid)
+ host.loadCover(titleIDs: [tid])
+ try await waitFor { host.cover.isEmpty }
+ try require(host.cover.isEmpty, "None of these removes a retained cover")
+ try matches.set(.game(id: 1, name: "Fixture", profileURL: URL(string: "https://gamebanana.com/games/1")!), titleID: tid)
+ host.loadCover(titleIDs: [tid])
+ try await waitFor { !host.cover.isEmpty }
+ try matches.set(.game(id: 2, name: "Other", profileURL: URL(string: "https://gamebanana.com/games/2")!), titleID: tid)
+ host.loadCover(titleIDs: [tid])
+ try await waitFor { host.cover.isEmpty }
+ try require(host.cover.isEmpty, "a changed match rejects a snapshot of another GameBanana page")
+
+ try matches.set(.game(id: 1, name: "Fixture", profileURL: URL(string: "https://gamebanana.com/games/1")!), titleID: tid)
+ CoverReadGate.arm()
+ host.loadCover(titleIDs: [tid])
+ try await waitFor { CoverReadGate.captured.wait(timeout: .now()) == .success }
+ let fresh = AvailableMod(id: 20, rank: 0, name: "Fresh", author: "Fixture", avatarURL: nil,
+ images: [URL(string: "https://images.gamebanana.com/img/ss/mods/fresh.png")!], thumbnailURL: nil,
+ version: "", updated: Date(), pageURL: URL(string: "https://gamebanana.com/mods/20")!,
+ description: "", likes: 0, downloads: 0, files: mod.files)
+ try snapshots.save([fresh], gameName: "Fixture", titleID: tid, gameBananaID: 1)
+ host.open([game], viewModel: model)
+ try await waitFor { host.cover == fresh.images }
+ CoverReadGate.resume.signal()
+ try await waitFor { CoverReadGate.completed.wait(timeout: .now()) == .success }
+ try require(host.cover == fresh.images && host.catalog.games.first?.mods.first?.id == 20,
+ "an older snapshot cannot replace a newer catalog cover")
+ host.close()
+ }
+}
+''')
+ mods_executable = scratch / 'mods-check'
+ model_source = (SOURCE / 'Sources/NXLibrary/ViewModels/ModStoreHost.swift').read_text()
+ assert model_source.count('return ModStoreLayout.coverArt(games: games)') == 1
+ # Control only the filesystem-read completion, leaving the production
+ # publication/generation checks and all model callbacks intact.
+ model_source = model_source.replace('return ModStoreLayout.coverArt(games: games)',
+ 'CoverReadGate.didRead(requestID); return ModStoreLayout.coverArt(games: games)')
+ assert model_source.count(' guard let self, self.coverTitleIDs') == 1
+ model_source = model_source.replace(' guard let self, self.coverTitleIDs',
+ ' defer { CoverReadGate.finished(requestID) }\n guard let self, self.coverTitleIDs')
+ assert model_source.count(' self.show(cover: urls)') == 1
+ model_source = model_source.replace(' self.show(cover: urls)',
+ ' self.show(cover: urls)\n _ = await self.coverTask?.value')
+ controlled_host = scratch / 'ControlledHost.swift'
+ controlled_host.write_text(model_source)
+ subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(mods),
+ str(controlled_host),
+ str(ROOT / 'Sources/NXLibrary/Models/GamepadType.swift'),
+ str(BIN / 'NXLibraryCore.o'), '-o', str(mods_executable)], check=True)
+ mods_result = subprocess.run([str(mods_executable), str(scratch)],
+ env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN)))
+ raise SystemExit(view_result.returncode or mods_result.returncode)
diff --git a/Tests/CatalogAppChecks/run_entrance.py b/Tests/CatalogAppChecks/run_entrance.py
new file mode 100644
index 00000000..8e43ba7a
--- /dev/null
+++ b/Tests/CatalogAppChecks/run_entrance.py
@@ -0,0 +1,180 @@
+#!/usr/bin/env python3
+"""Exercise entrance input and drawable readiness with no windows, GPU or player data.
+
+Compile the actual receiver, input prelude and render/reveal methods. Only their
+surrounding view state and Metal submission/presentation boundary are substituted.
+"""
+from pathlib import Path
+import os
+import subprocess
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[2]
+BIN = ROOT / '.build/debug'
+
+
+def declaration(path, signature):
+ source = (ROOT / path).read_text()
+ start = source.index(signature)
+ opening = source.index('{', start)
+ depth, end = 1, opening + 1
+ while depth:
+ depth += (source[end] == '{') - (source[end] == '}')
+ end += 1
+ return source[start:end]
+
+
+host = r'''
+import Foundation
+import NXLibraryCore
+
+typealias CFTimeInterval = Double
+func CACurrentMediaTime() -> Double { 0 }
+@MainActor enum LaunchReveal {
+ static var frames = 0
+ static func moonlightShown() { frames += 1 }
+}
+final class CAMetalDrawable {
+ private var handlers: [(CAMetalDrawable) -> Void] = []
+ func addPresentedHandler(_ handler: @escaping (CAMetalDrawable) -> Void) { handlers.append(handler) }
+ func present() { let callbacks = handlers; handlers = []; callbacks.forEach { $0(self) } }
+}
+final class CAMetalLayer {
+ var drawableSize = CGSize(width: 1920, height: 1080)
+ var next: CAMetalDrawable?
+ func nextDrawable() -> CAMetalDrawable? { next }
+}
+final class MoonlightEngine {
+ static let breathPeriod = 1.0
+ static func uniforms(width: Int, height: Int, time: Float, breath: Float, colors: Int) -> Int { 0 }
+ var submissions = 0
+ func render(into drawable: CAMetalDrawable, uniforms: Int) { submissions += 1 }
+ func render(into layer: CAMetalLayer, uniforms: Int) {
+ guard let drawable = layer.nextDrawable() else { return }
+ render(into: drawable, uniforms: uniforms)
+ }
+}
+final class MoonlightHost {
+ struct State {
+ var moving = false
+ var lastTick: Double?
+ var lastFrame: Double?
+ var clock = 0.0
+ var from: Int?
+ var stillPending = false
+ }
+ var state = State()
+ let lock = NSLock()
+ let metalLayer = CAMetalLayer()
+ let engine = MoonlightEngine()
+ static var firstFrameAnnounced = false
+ static let firstFrameLock = NSLock()
+ static func blended(_ state: State, at now: Double) -> Int { 0 }
+ func blending(at now: Double) -> Bool { false }
+ func updateLink() {}
+ func traceFirstPresentation(_ drawable: CAMetalDrawable) {}
+ func draw(_ drawable: CAMetalDrawable? = nil) { renderFrame(at: 1, drawable: drawable) }
+ // ACTUAL_RENDER
+ // ACTUAL_READY
+}
+final class InputState {
+ var alertMessage: String?
+ var settingsNotice: Int?
+ var isWelcomeOpen = false
+ var showSetupCheck = false
+ var isWindowSettling = true
+}
+final class InputHost {
+ let viewModel = InputState()
+ var entrance = SpotlightEntrance.Phase.covered
+ var handled: [GamepadAction] = []
+ // ACTUAL_OVERLAID
+ // ACTUAL_COVERED
+ func landEntrance() { entrance.land() }
+ func handle(_ action: GamepadAction) {
+ // ACTUAL_INPUT_PRELUDE
+ handled.append(action)
+ }
+ func receive(_ note: Notification) {
+ // ACTUAL_RECEIVER
+ }
+}
+
+@main struct Check {
+ @MainActor static func main() async {
+ var failures = 0
+ func require(_ ok: @autoclosure () -> Bool, _ message: String) {
+ if !ok() { failures += 1; print("FAIL: " + message) }
+ }
+ for phase: SpotlightEntrance.Phase in [.covered, .waiting, .playing] {
+ let input = InputHost()
+ input.entrance = phase
+ input.receive(Notification(name: .init("fixture"), object: GamepadAction.confirm))
+ require(input.handled.isEmpty && input.entrance == phase,
+ "A press during the entrance must neither act nor skip it (phase \(phase))")
+ }
+ let landed = InputHost()
+ landed.entrance = .landed
+ landed.receive(Notification(name: .init("fixture"), object: GamepadAction.confirm))
+ require(landed.handled == [.confirm], "Once landed, a press acts as usual")
+ for setup in [false, true] {
+ let input = InputHost()
+ input.viewModel.showSetupCheck = setup
+ input.viewModel.isWelcomeOpen = !setup
+ input.receive(Notification(name: .init("fixture"), object: GamepadAction.confirm))
+ require(input.handled.isEmpty && input.entrance == .covered,
+ "A real welcome/Setup cover must still block Spotlight input")
+ }
+ for supplied in [false, true] {
+ MoonlightHost.firstFrameAnnounced = false
+ LaunchReveal.frames = 0
+ let renderer = MoonlightHost()
+ renderer.draw()
+ for _ in 0..<20 { await Task.yield() }
+ require(LaunchReveal.frames == 0 && renderer.engine.submissions == 0,
+ "A missing drawable must not announce a ready frame")
+ let drawable = CAMetalDrawable()
+ if supplied { renderer.draw(drawable) }
+ else { renderer.metalLayer.next = drawable; renderer.draw() }
+ for _ in 0..<20 { await Task.yield() }
+ require(renderer.engine.submissions == 1 && LaunchReveal.frames == 0,
+ "Submitting a frame must not announce presentation (supplied=\(supplied))")
+ drawable.present()
+ for _ in 0..<100 where LaunchReveal.frames == 0 { await Task.yield() }
+ require(LaunchReveal.frames == 1, "The first presented drawable must release the reveal gate")
+ let another = CAMetalDrawable()
+ renderer.draw(another)
+ another.present()
+ for _ in 0..<20 { await Task.yield() }
+ require(LaunchReveal.frames == 1, "Later frames must not release the reveal gate twice")
+ }
+ if failures > 0 { exit(1) }
+ print("Entrance checks passed: no skip during the entrance, covers, missing drawable and presentation readiness on both render paths.")
+ }
+}
+'''
+entrance = 'Sources/NXLibrary/Views/Spotlight/SpotlightView+Entrance.swift'
+renderer = 'Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift'
+for marker, path, signature in (
+ ('// ACTUAL_OVERLAID', entrance, ' var isOverlaid:'),
+ ('// ACTUAL_COVERED', entrance, ' var isCovered:'),
+ ('// ACTUAL_RENDER', renderer, ' private func renderFrame('),
+ ('// ACTUAL_READY', renderer, ' private static func announceFirstFrame('),
+):
+ host = host.replace(marker, declaration(path, signature))
+receiver = declaration('Sources/NXLibrary/Views/Spotlight/SpotlightView.swift',
+ ' .onReceive(NotificationCenter.default.publisher(for: .nxSpotlightGamepadAction))')
+host = host.replace('// ACTUAL_RECEIVER', receiver.split('{ note in', 1)[1].rsplit('}', 1)[0])
+handler = declaration('Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift',
+ ' func handle(_ action: GamepadAction)')
+prelude = handler[handler.index('{') + 1:handler.index(' if viewer != nil')]
+host = host.replace('// ACTUAL_INPUT_PRELUDE', prelude)
+with tempfile.TemporaryDirectory(prefix='entrance-check-') as folder:
+ scratch = Path(folder)
+ swift = scratch / 'check.swift'
+ swift.write_text(host)
+ executable = scratch / 'check'
+ subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(swift),
+ str(ROOT / 'Sources/NXLibrary/Models/GamepadType.swift'),
+ str(BIN / 'NXLibraryCore.o'), '-o', str(executable)], cwd=ROOT, check=True)
+ subprocess.run([str(executable)], env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN)), check=True)
diff --git a/Tests/CatalogAppChecks/run_game_header.py b/Tests/CatalogAppChecks/run_game_header.py
new file mode 100644
index 00000000..2c339e68
--- /dev/null
+++ b/Tests/CatalogAppChecks/run_game_header.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python3
+"""Evaluate actual common header bodies without a window or app stores."""
+from pathlib import Path
+import subprocess,tempfile,os
+ROOT=Path(__file__).resolve().parents[2]
+BIN=ROOT/'.build/debug'
+files=[ROOT/'Sources/NXLibrary/Views/Components/GameLogoArea.swift', ROOT/'Sources/NXLibrary/Views/Components/GamePrimaryActions.swift']
+actual='\n'.join(p.read_text() for p in files)
+host='''import SwiftUI
+import NXLibraryCore
+struct HeaderCanvas { func u(_ value: CGFloat) -> CGFloat { value } }
+private struct CanvasKey: EnvironmentKey { static let defaultValue = HeaderCanvas() }
+extension EnvironmentValues { var seleneCanvas: HeaderCanvas { get { self[CanvasKey.self] } set { self[CanvasKey.self] = newValue } } }
+extension View { func seleneFont(_ size: CGFloat, _ weight: Font.Weight = .regular) -> some View { font(.system(size: size, weight: weight)) } }
+enum SeleneTheme { static let ink = Color.white }
+struct SelenePillButton: View {
+ let title: String?; var icon: MaterialIcon? = nil; var iconSize: CGFloat = 26
+ var minWidth: CGFloat = 180; var height: CGFloat = 60; var horizontalPadding: CGFloat = 36
+ let focused: Bool; var enabled: Bool = true; var waveDots = false; let action: () -> Void
+ var body: some View { Color.clear }
+}
+'''+actual+'''
+@main struct Check {
+ @MainActor static func main() {
+ for collection in [true,false] {
+ withExtendedLifetime(GameLogoArea(title: "Fixture", logo: nil, collection: collection).body) {}
+ }
+ for enabled in [true,false] {
+ withExtendedLifetime(GamePrimaryActions(primaryTitle: "Play", secondaryTitle: "Options", isFavorite: true, focused: 0, primaryEnabled: enabled, onAction: {_ in}).body) {}
+ }
+ print("Actual shared game header bodies work without injected stores, for both layouts/action states.")
+ }
+}
+'''
+with tempfile.TemporaryDirectory(prefix='game-header-check-') as folder:
+ folder=Path(folder);swift=folder/'check.swift';swift.write_text(host);binary=folder/'check'
+ subprocess.run(['xcrun','swiftc','-parse-as-library','-I',str(BIN),str(swift),str(BIN/'NXLibraryCore.o'),'-o',str(binary)],check=True)
+ subprocess.run([str(binary)],check=True,env=dict(os.environ,PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN)))
diff --git a/Tests/CatalogAppChecks/run_icon_cache.py b/Tests/CatalogAppChecks/run_icon_cache.py
new file mode 100644
index 00000000..6f2ca740
--- /dev/null
+++ b/Tests/CatalogAppChecks/run_icon_cache.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python3
+"""Check the square icon art lookup with no windows or player data.
+
+Compile the actual GameIconProvider: a game with no icon on disk is not read again on every
+draw of its tile, and an icon that arrives later shows once the game is forgotten or built.
+"""
+from pathlib import Path
+import os
+import subprocess
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[2]
+BIN = ROOT / '.build/debug'
+
+host = r'''
+import AppKit
+import NXLibraryCore
+
+@main struct Check {
+ static func main() throws {
+ var failures = 0
+ func require(_ ok: Bool, _ message: String) {
+ if !ok { failures += 1; print("FAIL: " + message) }
+ }
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("icon-cache-\(UUID().uuidString)")
+ let workspace = root.appendingPathComponent("workspace")
+ let titleID = "0100000000001000"
+ let iconFolder = workspace.appendingPathComponent("\(titleID)_build/extract/v0")
+ try FileManager.default.createDirectory(at: iconFolder, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ var game = PortedGame(name: "Fixture", url: root.appendingPathComponent("not-built"),
+ platform: .macApp, sizeBytes: 0, modificationDate: Date(), titleId: titleID)
+ game.workspacePath = workspace.path
+ require(GameIconProvider.squareArt(for: game) == nil, "no icon on disk gives no square art")
+
+ let image = NSImage(size: NSSize(width: 4, height: 4))
+ image.lockFocus(); NSColor.red.setFill(); NSRect(x: 0, y: 0, width: 4, height: 4).fill(); image.unlockFocus()
+ let png = NSBitmapImageRep(data: image.tiffRepresentation!)!.representation(using: .png, properties: [:])!
+ try png.write(to: iconFolder.appendingPathComponent("icon.jpg"))
+ require(GameIconProvider.squareArt(for: game) == nil,
+ "a game with no icon is not read from disk again on the next draw")
+
+ GameIconProvider.forget(game)
+ require(GameIconProvider.squareArt(for: game) != nil, "forgetting the game reads its new icon")
+
+ var other = PortedGame(name: "Other", url: root.appendingPathComponent("other-not-built"),
+ platform: .macApp, sizeBytes: 0, modificationDate: Date(), titleId: "0100000000002000")
+ other.workspacePath = root.appendingPathComponent("other").path
+ require(GameIconProvider.squareArt(for: other) == nil, "a second game with no icon gives no square art")
+ let otherFolder = root.appendingPathComponent("other/0100000000002000_build/extract/v0")
+ try FileManager.default.createDirectory(at: otherFolder, withIntermediateDirectories: true)
+ try png.write(to: otherFolder.appendingPathComponent("icon.jpg"))
+ other.url = root.appendingPathComponent("Other.app")
+ require(GameIconProvider.squareArt(for: other) != nil, "a game that moved to its built app is looked up again")
+
+ if failures > 0 { exit(1) }
+ print("Icon cache checks passed: missing icons are remembered, forgetting and building look again.")
+ }
+}
+'''
+with tempfile.TemporaryDirectory(prefix='icon-cache-check-') as folder:
+ scratch = Path(folder)
+ swift = scratch / 'check.swift'
+ swift.write_text(host)
+ executable = scratch / 'check'
+ subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(swift),
+ str(ROOT / 'Sources/NXLibrary/Views/Components/GameIconProvider.swift'),
+ str(BIN / 'NXLibraryCore.o'), '-o', str(executable)], cwd=ROOT, check=True)
+ subprocess.run([str(executable)], env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN)), check=True)
diff --git a/Tests/CatalogAppChecks/run_nested_bundles.py b/Tests/CatalogAppChecks/run_nested_bundles.py
new file mode 100644
index 00000000..d1d7a969
--- /dev/null
+++ b/Tests/CatalogAppChecks/run_nested_bundles.py
@@ -0,0 +1,223 @@
+#!/usr/bin/env python3
+"""Exercise installation and icon changes on signed, synthetic nested data bundles.
+
+Uses the nxnative data-bundle layout and relative Resources links, real codesign
+and the production Swift installer/icon writer. No UI, engine checkout, keys or
+game data. The cross-volume branch is forced on the temporary fixture volume;
+this does not replace a real external-volume or engine-build check.
+Run after swift test.
+"""
+from pathlib import Path
+import os
+import plistlib
+import struct
+import subprocess
+import tempfile
+import zlib
+
+ROOT = Path(__file__).resolve().parents[2]
+BIN = ROOT / '.build/debug'
+
+
+def run(*args):
+ result = subprocess.run([str(a) for a in args], capture_output=True, text=True)
+ if result.returncode:
+ raise SystemExit(result.stderr or result.stdout or f'Command failed: {args[0]}')
+ return result
+
+
+def plist(path, values):
+ path.write_bytes(plistlib.dumps(values))
+
+
+def signed_app(path, executable, version):
+ contents = path / 'Contents'
+ resources = contents / 'Resources'
+ resources.mkdir(parents=True)
+ (contents / 'MacOS').mkdir()
+ for target in (contents / 'MacOS/nxnative', contents / 'MacOS/dmhost'):
+ target.write_bytes(executable.read_bytes())
+ target.chmod(0o755)
+ run('/usr/bin/codesign', '--force', '--sign', '-', target)
+ plist(contents / 'Info.plist', {
+ 'CFBundleIdentifier': 'org.arcane.contractfixture', 'CFBundleName': 'Fixture',
+ 'CFBundleExecutable': 'nxnative', 'CFBundlePackageType': 'APPL',
+ 'CFBundleVersion': str(version), 'CFBundleShortVersionString': str(version),
+ })
+ for name, top in (
+ ('GameData', 'romfs.img'), ('ShaderLibraries', 'msl'),
+ ('PipelineArchive', 'pso'), ('AddOnContent', 'aoc'),
+ ('GameDataPrograms', 'romfs_programs'), ('GameData1', 'p1/romfs.img'),
+ ):
+ bundle = contents / 'PlugIns' / (name + '.bundle')
+ inner = bundle / 'Contents/Resources'
+ inner.mkdir(parents=True)
+ plist(bundle / 'Contents/Info.plist', {
+ 'CFBundleIdentifier': 'org.arcane.contractfixture.data.' + name.lower(),
+ 'CFBundleName': name, 'CFBundlePackageType': 'BNDL', 'CFBundleVersion': '1',
+ })
+ payload = inner / top
+ if top.endswith('.img'):
+ payload.parent.mkdir(parents=True, exist_ok=True)
+ else:
+ payload.mkdir()
+ payload /= 'synthetic.bin'
+ payload.write_bytes(f'{name}:version:{version}'.encode())
+ link = resources / top
+ link.parent.mkdir(parents=True, exist_ok=True)
+ link.symlink_to(os.path.relpath(inner / top, link.parent))
+ run('/usr/bin/codesign', '--force', '--sign', '-', bundle)
+ run('/usr/bin/codesign', '--force', '--sign', '-', path)
+ run('/usr/bin/codesign', '--verify', '--deep', '--strict', path)
+
+
+with tempfile.TemporaryDirectory(prefix='arcane-nested-check-') as temporary:
+ scratch = Path(temporary)
+ code = scratch / 'fixture.c'
+ code.write_text('int main(void) { return 0; }\n')
+ executable = scratch / 'fixture'
+ run('xcrun', 'clang', code, '-o', executable)
+ signed_app(scratch / 'old.app', executable, 1)
+ signed_app(scratch / 'rebuilt.app', executable, 2)
+
+ def chunk(kind, data):
+ return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
+
+ # A generated 32 x 32 solid-colour PNG; no external artwork.
+ pixels = (b'\0' + b'\x40\x80\xc0\xff' * 32) * 32
+ (scratch / 'icon.png').write_bytes(
+ b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 32, 32, 8, 6, 0, 0, 0))
+ + chunk(b'IDAT', zlib.compress(pixels)) + chunk(b'IEND', b''))
+ main = scratch / 'main.swift'
+ main.write_text(r'''
+import Foundation
+import CryptoKit
+@testable import NXLibraryCore
+
+struct CheckFailure: Error {}
+func require(_ condition: @autoclosure () throws -> Bool) throws {
+ if try !condition() { throw CheckFailure() }
+}
+let root = URL(fileURLWithPath: CommandLine.arguments[1])
+let fm = FileManager.default
+let runner = SystemCommandRunner()
+let codesign = URL(fileURLWithPath: "/usr/bin/codesign")
+func verify(_ app: URL) throws {
+ let result = try runner.run(codesign, ["--verify", "--deep", "--strict", app.path],
+ environment: nil, currentDirectory: nil)
+ try require(result.status == 0)
+}
+func digest(_ folder: URL) throws -> String {
+ let paths = try fm.subpathsOfDirectory(atPath: folder.path).sorted()
+ var hash = SHA256()
+ for path in paths {
+ let file = folder.appendingPathComponent(path)
+ let attributes = try fm.attributesOfItem(atPath: file.path)
+ hash.update(data: Data(path.utf8))
+ if attributes[.type] as? FileAttributeType == .typeRegular {
+ hash.update(data: try Data(contentsOf: file))
+ }
+ }
+ return hash.finalize().map { String(format: "%02x", $0) }.joined()
+}
+func links(_ app: URL) throws -> [String: String] {
+ let res = app.appendingPathComponent("Contents/Resources")
+ let tops = ["romfs.img", "msl", "pso", "aoc", "romfs_programs", "p1/romfs.img"]
+ return try Dictionary(uniqueKeysWithValues: tops.map { top in
+ let file = res.appendingPathComponent(top)
+ let link = try fm.destinationOfSymbolicLink(atPath: file.path)
+ try require(!link.hasPrefix("/"))
+ try require(fm.fileExists(atPath: file.path))
+ let resolved = file.resolvingSymlinksInPath().path
+ try require(resolved.hasPrefix(app.appendingPathComponent("Contents/PlugIns").path + "/"))
+ return (top, link)
+ })
+}
+func dataSeal(_ app: URL) throws -> String {
+ try digest(app.appendingPathComponent("Contents/PlugIns"))
+}
+func hostBytes(_ app: URL) throws -> Data {
+ try Data(contentsOf: app.appendingPathComponent("Contents/MacOS/dmhost"))
+}
+let source = root.appendingPathComponent("old.app")
+let destination = root.appendingPathComponent("Installed/Game.app")
+let originalSeal = try dataSeal(source)
+let originalLinks = try links(source)
+let originalHost = try hostBytes(source)
+try BuildOutputInstaller.install(tempApp: source, finalApp: destination)
+try verify(destination)
+try require(try dataSeal(destination) == originalSeal)
+try require(try links(destination) == originalLinks)
+try require(try hostBytes(destination) == originalHost)
+print("Same-volume install preserves nested signatures and relative links: PASS")
+
+let writer = AppIconWriter(backups: root.appendingPathComponent("backups"))
+let png = try Data(contentsOf: root.appendingPathComponent("icon.png"))
+try writer.apply(image: png, to: destination, key: "fixture")
+try verify(destination)
+try require(writer.showsWrittenIcon(destination))
+try require(try dataSeal(destination) == originalSeal)
+try require(try hostBytes(destination) == originalHost)
+try writer.restore(destination, key: "fixture")
+try verify(destination)
+try require(!writer.showsWrittenIcon(destination))
+try require(try dataSeal(destination) == originalSeal)
+try require(try links(destination) == originalLinks)
+try require(try hostBytes(destination) == originalHost)
+print("Real icon write and restore preserve nested signatures: PASS")
+
+struct FailVerification: CommandRunning {
+ func run(_ executable: URL, _ arguments: [String], environment: [String: String]?,
+ currentDirectory: URL?) throws -> CommandResult {
+ if executable.lastPathComponent == "codesign" && arguments.contains("--verify") {
+ return CommandResult(status: 1, stdout: "", stderr: "synthetic verification failure")
+ }
+ return try SystemCommandRunner().run(executable, arguments, environment: environment,
+ currentDirectory: currentDirectory)
+ }
+}
+let beforeFailure = try digest(destination)
+let failing = AppIconWriter(backups: root.appendingPathComponent("rollback-backups"), runner: FailVerification())
+do {
+ try failing.apply(image: png, to: destination, key: "fixture")
+ throw CheckFailure()
+} catch AppIconWriter.Failure.signingFailed { }
+try verify(destination)
+try require(try digest(destination) == beforeFailure)
+print("Failed verification restores the original signed app: PASS")
+
+let rebuilt = root.appendingPathComponent("rebuilt.app")
+let rebuiltSeal = try dataSeal(rebuilt)
+let rebuiltLinks = try links(rebuilt)
+let rebuiltHost = try hostBytes(rebuilt)
+var io = BuildInstallIO()
+io.sameVolume = { _, _ in false }
+io.afterPublish = { throw CocoaError(.userCancelled) }
+do {
+ try BuildOutputInstaller.install(tempApp: rebuilt, finalApp: destination, io: io)
+ throw CheckFailure()
+} catch let error as CocoaError where error.code == .userCancelled { }
+try verify(destination)
+io.afterPublish = {}
+try BuildOutputInstaller.install(tempApp: rebuilt, finalApp: destination, io: io)
+try verify(destination)
+try require(try dataSeal(destination) == rebuiltSeal)
+try require(try links(destination) == rebuiltLinks)
+try require(try hostBytes(destination) == rebuiltHost)
+try require(BuildOutputInstaller.version(of: destination) == "2")
+print("Copied rebuild and interrupted-publication retry preserve the new app: PASS")
+
+let payload = destination.appendingPathComponent("Contents/Resources/romfs.img")
+let original = try Data(contentsOf: payload)
+try Data("tampered".utf8).write(to: payload)
+let rejected = try runner.run(codesign, ["--verify", "--deep", "--strict", destination.path],
+ environment: nil, currentDirectory: nil)
+try require(rejected.status != 0)
+try original.write(to: payload)
+try verify(destination)
+print("Deep verification rejects changed nested payloads: PASS")
+''')
+ host = scratch / 'check'
+ run('xcrun', 'swiftc', '-I', BIN, main, BIN / 'NXLibraryCore.o', '-o', host)
+ result = run(host, scratch)
+ print(result.stdout, end='')
diff --git a/Tests/CatalogAppChecks/run_notices.py b/Tests/CatalogAppChecks/run_notices.py
new file mode 100644
index 00000000..293d6ced
--- /dev/null
+++ b/Tests/CatalogAppChecks/run_notices.py
@@ -0,0 +1,43 @@
+#!/usr/bin/env python3
+"""Exercise actual app notice helpers/bridge without constructing SwiftUI or AppKit.
+
+Run after swift test on macOS. Core I/O uses generated temporary data only.
+The host substitutes the surrounding view model, not the methods being checked.
+"""
+from pathlib import Path
+import os
+import subprocess
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[2]
+BIN = ROOT / '.build/debug'
+
+def method(source, signature):
+ start = source.index(signature)
+ opening = source.index('{', start)
+ depth = 1
+ end = opening + 1
+ while depth:
+ depth += (source[end] == '{') - (source[end] == '}')
+ end += 1
+ return source[start:end]
+
+with tempfile.TemporaryDirectory(prefix='catalog-notice-check-') as scratch:
+ scratch = Path(scratch)
+ view = (ROOT / 'Sources/NXLibrary/Views/Shell/AppShellView.swift').read_text()
+ bridge = '\n'.join(method(view, signature) for signature in (
+ ' private func finishSettingsNotice(choice: Int)', ' private func presentLegacyNotice()'))
+ host = (ROOT / 'Tests/CatalogAppChecks/NoticeHost.swift').read_text()
+ host += '\nstruct LegacyNoticeHost {\n let viewModel: AppViewModel\n'
+ host += ' func deliver() { presentLegacyNotice() }\n func dismiss() { finishSettingsNotice(choice: 0) }\n'
+ host += bridge + '\n}\n'
+ main = scratch / 'main.swift'
+ main.write_text(host)
+ executable = scratch / 'notices'
+ command = ['xcrun', 'swiftc', '-I', str(BIN), str(main),
+ str(ROOT / 'Sources/NXLibrary/Models/LogEntry.swift'),
+ str(ROOT / 'Sources/NXLibrary/ViewModels/AppViewModel+Catalog.swift'),
+ str(BIN / 'NXLibraryCore.o'), '-o', str(executable)]
+ subprocess.run(command, cwd=ROOT, check=True)
+ env = dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN))
+ subprocess.run([str(executable)], env=env, check=True)
diff --git a/Tests/CatalogAppChecks/run_nup_programs.py b/Tests/CatalogAppChecks/run_nup_programs.py
new file mode 100644
index 00000000..1c8c38a1
--- /dev/null
+++ b/Tests/CatalogAppChecks/run_nup_programs.py
@@ -0,0 +1,89 @@
+#!/usr/bin/env python3
+"""Check real NUP probe/converters, persistence and rebuild arguments without app UI.
+
+An optional immutable engine snapshot runs its synthetic edition fixture through
+Arcane's actual embedded Python probe. No checkout, game content or keys are used.
+"""
+from pathlib import Path
+import argparse
+import os
+import subprocess
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[2]
+parser = argparse.ArgumentParser()
+parser.add_argument('--engine-snapshot', type=Path)
+parser.add_argument('--python', default='python3')
+args = parser.parse_args()
+source = (ROOT / 'Sources/NXLibrary/ViewModels/AppViewModel.swift').read_text()
+
+
+def declaration(signature):
+ start = source.index(signature)
+ opening = source.index('{', start)
+ depth, end = 1, opening + 1
+ while depth:
+ depth += (source[end] == '{') - (source[end] == '}')
+ end += 1
+ return source[start:end].replace('private static func', 'static func', 1)
+
+
+with tempfile.TemporaryDirectory(prefix='arcane-nup-check-') as scratch:
+ scratch = Path(scratch)
+ output = 'title 0400F00000010001\napplication 0100F00000010000\naoc_base 0100F00000011000\nbase 272\ndlc 0100F00000011001 2\n'
+ if args.engine_snapshot:
+ bridge = (ROOT / 'Sources/NXLibraryCore/Services/NUPSourceCatalog.swift').read_text()
+ probe = bridge.split('let script = #"""', 1)[1].split('"""#', 1)[0]
+ generator = """
+import pathlib,sys
+repo=pathlib.Path(sys.argv[1])
+sys.path.insert(0,str(repo/'dm/tools/tests'))
+import test_nsp_nup as fixture
+fixture.write_nup(pathlib.Path(sys.argv[2]),fixture.edition())
+"""
+ nup = scratch / 'synthetic.nup'
+ subprocess.run([args.python, '-I', '-B', '-c', generator, str(args.engine_snapshot), str(nup)], check=True)
+ result = subprocess.run([args.python, '-I', '-B', '-c', probe, str(args.engine_snapshot), str(nup)],
+ check=True, text=True, capture_output=True, timeout=20)
+ output = result.stdout
+ wire = scratch / 'probe.txt'
+ wire.write_text(output)
+ host = '''
+import Foundation
+@testable import NXLibraryCore
+struct Host {
+ // CONVERTERS
+}
+let scratch = URL(fileURLWithPath: CommandLine.arguments[1])
+let wire = try String(contentsOf: scratch.appendingPathComponent("probe.txt"), encoding: .utf8)
+let nup = scratch.appendingPathComponent("synthetic.nup")
+let game = try NUPSourceCatalog.parse(wire, nup: nup, fileSize: 400,
+ profiles: scratch.appendingPathComponent("profiles"), provisional: true)
+precondition(game.baseTitleId == 0x0400F00000010001)
+let ui = Host.selectableGame(from: game)
+precondition(ui.titleId == "0400F00000010001")
+let persisted = try JSONEncoder().encode(ui.files)
+let restored = try JSONDecoder().decode([GameFileItem].self, from: persisted)
+let detected = restored.compactMap { Host.detectedSource(from: $0) }
+precondition(detected.count == game.allSources.count)
+precondition(detected.allSatisfy { $0.nupProgram?.applicationID == 0x0100F00000010000 && $0.nupProgram?.index == 1 })
+precondition(detected.first(where: { $0.kind == .dlc })?.titleId == 0x0100F00000011001)
+precondition(SourceSelection.supported(restored, titleSelection: true, extractedFolders: true,
+ nupContainers: true, nupPrograms: true))
+let command = BuildCommandBuilder.make(repo: scratch, toolchain: EngineToolchain(python: scratch.appendingPathComponent("python"),
+ extraPath: [], isBundled: true), workspace: scratch, keys: nil, output: scratch.appendingPathComponent("Game.app"),
+ developerDir: scratch, titleId: ui.titleId,
+ programIndex: SourceSelection.programIndex(for: restored, titleID: ui.titleId!, nupPrograms: true))
+precondition(command.arguments[command.arguments.firstIndex(of: "--program")! + 1] == "1")
+print("NUP probe → real UI converters → persisted sources → rebuild program: PASS")
+'''
+ methods = '\n'.join(declaration(signature) for signature in (
+ ' private static func selectableGame(from game:', ' private static func detectedSource(from file:'))
+ main = scratch / 'main.swift'
+ main.write_text(host.replace('// CONVERTERS', methods))
+ library = ROOT / '.build/debug'
+ executable = scratch / 'nup-check'
+ subprocess.run(['xcrun', 'swiftc', '-I', str(library), str(main),
+ str(ROOT / 'Sources/NXLibrary/Models/SelectableGame.swift'),
+ str(library / 'NXLibraryCore.o'), '-o', str(executable)], check=True)
+ subprocess.run([str(executable), str(scratch)], env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(library)), check=True)
diff --git a/Tests/CatalogAppChecks/run_onboarding.py b/Tests/CatalogAppChecks/run_onboarding.py
new file mode 100644
index 00000000..c00a7eea
--- /dev/null
+++ b/Tests/CatalogAppChecks/run_onboarding.py
@@ -0,0 +1,227 @@
+#!/usr/bin/env python3
+"""Exercise the real setup persistence and notification request sites without windows.
+
+Only the surrounding app and notification transport are substituted. Preferences
+use a unique synthetic domain; no player profile or game data is read.
+"""
+from pathlib import Path
+import os
+import subprocess
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[2]
+source = (ROOT / 'Sources/NXLibrary/ViewModels/AppViewModel.swift').read_text()
+
+
+def declaration(signature, text=None):
+ text = source if text is None else text
+ start = text.index(signature)
+ opening = text.index('{', start)
+ depth, end = 1, opening + 1
+ while depth:
+ depth += (text[end] == '{') - (text[end] == '}')
+ end += 1
+ return text[start:end]
+
+
+initial = declaration(' public init(settingsStore:')
+restore = initial[initial.index(' let didCompleteSetup = '):initial.index(' // 1. Resolve safe root')]
+startup_requests = '\n'.join(line for line in initial.splitlines() if 'NotificationService.shared' in line)
+build = declaration(' private func beginBuild(for game:')
+accepted = build[build.index(' isBuilding = true'):build.index(' buildState = .running')]
+shell = (ROOT / 'Sources/NXLibrary/Views/Shell/AppShellView.swift').read_text()
+start = shell.index('.onChange(of: viewModel.setupCompleted)')
+opening = shell.index('{ done in', start)
+depth, end = 1, opening + 1
+while depth:
+ depth += (shell[end] == '{') - (shell[end] == '}')
+ end += 1
+finish = shell[opening + len('{ done in'):end - 1]
+found = (ROOT / 'Sources/NXLibrary/Views/Setup/FoundGamesSetupView.swift').read_text()
+start = found.index('.onChange(of: findings)')
+opening = found.index('{ found in', start)
+depth, end = 1, opening + 1
+while depth:
+ depth += (found[end] == '{') - (found[end] == '}')
+ end += 1
+findings_changed = found[opening + len('{ found in'):end - 1]
+
+host = '''
+import Foundation
+import Combine
+import NXLibraryCore
+
+enum AppData {
+ static let domain = "local.nxlibrary.validation." + UUID().uuidString
+ static let preferences = UserDefaults(suiteName: domain)!
+}
+enum NotificationRegistration { static var registered = false }
+final class NotificationService {
+ static let shared = NotificationService()
+ var requests = 0
+ init() { NotificationRegistration.registered = true }
+ func requestAuthorization() { requests += 1 }
+}
+final class Host {
+ // KEYS
+ // SETUP
+ var showSetupCheck = false
+ var isBuilding = false
+ var isCancellingBuild = false
+ let gameAppsFolder = URL(fileURLWithPath: "/synthetic/apps")
+ init() {
+ // RESTORE
+ // STARTUP_REQUESTS
+ }
+ func chooseSteamOnFound(_ value: Bool) { firstRunSetup.chooseSteam(value) }
+ func choose(_ value: Bool) { firstRunSetup.chooseSteam(value) }
+ func openPorting() { firstRunSetup.openPorting() }
+ func openPortingFromFound() { firstRunSetup.openPorting() }
+ func finish() { firstRunSetup.finish() }
+ func acceptBuild() {
+ // ACCEPTED_BUILD
+ }
+}
+final class Sources {
+ struct Configuration { var isEnabled: Bool }
+ var configuration: Configuration
+ let discoveryRoot: URL
+ var applied: [(Bool, URL?)] = []
+ init(enabled: Bool, root: URL) { configuration = .init(isEnabled: enabled); discoveryRoot = root }
+ func configure(enabled: Bool, root: URL?) { applied.append((enabled, root)); configuration.isEnabled = enabled }
+}
+final class Settings { var settings = AppSettings() }
+final class Shell {
+ let viewModel: Host
+ let sources: Sources
+ let settings = Settings()
+ var showsWelcome = false
+ init(model: Host, sources: Sources) { viewModel = model; self.sources = sources }
+ func complete(_ done: Bool) {
+ // FINISH
+ }
+}
+struct NativeApp { var modalWindow: Int? }
+var NSApp = NativeApp()
+final class SoundEffectService {
+ enum Cue { case click, key, error }
+ static let shared = SoundEffectService()
+ func play(_ cue: Cue) {}
+}
+final class FindingsReader {
+ var cancellations = 0
+ func cancel() { cancellations += 1 }
+ func start(steamRoot: URL, appsFolder: URL) {}
+}
+final class FoundHost {
+ let viewModel: Host
+ var findings: FirstRunFindings?
+ var focus = FirstRunSetup.Focus.steamToggle
+ let reader = FindingsReader()
+ let steamRoot = URL(fileURLWithPath: "/synthetic/Steam")
+ var opened: [(ported: Bool, cancelled: Bool)] = []
+ var steamCount: Int? { findings?.steamGameCount }
+ var steamOn: Bool { viewModel.firstRunSetup.steamChoice ?? true }
+ var portedCount: Int { findings?.portedAppCount ?? 0 }
+ var isReading: Bool { findings == nil }
+ func onOpenLibrary(_ ported: Bool) { opened.append((ported, reader.cancellations > 0)) }
+ // ACTIVATE_FOUND
+ var hasSteam: Bool { findings?.steamGameCount != nil || findings?.steamReadFailed == true }
+ init(_ viewModel: Host) { self.viewModel = viewModel }
+ func move(to next: FirstRunSetup.Focus) { focus = next }
+ func receive(_ found: FirstRunFindings?) {
+ findings = found
+ // FINDINGS_CHANGED
+ }
+}
+var failures = 0
+func require(_ ok: @autoclosure () -> Bool, _ message: String) {
+ if !ok() { failures += 1; print("FAIL: " + message) }
+}
+defer { AppData.preferences.removePersistentDomain(forName: AppData.domain) }
+let initialBoot = Host()
+require(NotificationRegistration.registered, "Startup registers notification click handling without requesting authorization")
+for value in [true, false] {
+ AppData.preferences.removePersistentDomain(forName: AppData.domain)
+ let before = Host()
+ before.choose(value)
+ before.openPorting()
+ let resumed = Host()
+ require(resumed.firstRunSetup.steamChoice == value, "Steam choice survives quit: \\(value)")
+ require(resumed.firstRunSetup.page == .requirements, "Porting page survives quit")
+ resumed.finish()
+ require(resumed.firstRunSetup.steamChoice == value, "Shell can still apply the finishing choice")
+ require(AppData.preferences.object(forKey: "NXLibrary_SetupSteamChoice") == nil, "Finishing removes saved choice")
+ require(Host().firstRunSetup.steamChoice == nil, "Completed setup does not inherit a stale choice")
+}
+for enabled in [true, false] {
+ for choice: Bool? in [true, false, nil] {
+ AppData.preferences.removePersistentDomain(forName: AppData.domain)
+ let model = Host()
+ if let choice { model.choose(choice) }
+ let custom = URL(fileURLWithPath: "/synthetic/Custom Steam")
+ let sources = Sources(enabled: enabled, root: custom)
+ let shell = Shell(model: model, sources: sources)
+ shell.complete(false)
+ require(sources.applied.isEmpty, "Incomplete setup does not apply the switch")
+ model.finish()
+ shell.complete(true)
+ require(sources.configuration.isEnabled == (choice ?? enabled), "Finishing applies on and off, nil preserves the source")
+ require(sources.applied.allSatisfy { $0.1 == custom }, "Opt-in uses the same custom root as discovery")
+ }
+}
+AppData.preferences.removePersistentDomain(forName: AppData.domain)
+let retryModel = Host()
+retryModel.choose(false)
+let retry = FoundHost(retryModel)
+retry.receive(FirstRunFindings(steamGameCount: nil, portedAppCount: 0, steamReadFailed: true))
+require(retry.focus == .steamToggle, "Retry row keeps focus while the read is incomplete")
+retry.receive(nil)
+retry.receive(FirstRunFindings(steamGameCount: nil, portedAppCount: 0))
+require(retry.focus == .openLibrary, "Retry that finds no Steam leaves no invisible focused row")
+retry.receive(FirstRunFindings(steamGameCount: 2, portedAppCount: 0))
+require(retryModel.firstRunSetup.steamChoice == false, "Retry never resets an explicit off choice")
+AppData.preferences.removePersistentDomain(forName: AppData.domain)
+let waitingModel = Host()
+waitingModel.showSetupCheck = true
+let waiting = FoundHost(waitingModel)
+waiting.activate(.openLibrary)
+require(waiting.opened.count == 1 && waiting.opened.first?.ported == false,
+ "A pending read does not block Open library or invent ported results")
+require(waiting.opened.first?.cancelled == true, "Cancel the pending request before leaving the found page")
+require(waitingModel.firstRunSetup.steamChoice == nil, "No unread source is opted in")
+waiting.receive(FirstRunFindings(steamGameCount: 2, portedAppCount: 3))
+waiting.activate(.openLibrary)
+require(waiting.opened.last?.ported == true, "A completed read still imports found apps")
+NSApp.modalWindow = 1
+waiting.activate(.openLibrary)
+require(waiting.opened.count == 2, "A native modal still owns input")
+NSApp.modalWindow = nil
+waitingModel.showSetupCheck = false
+waiting.activate(.openLibrary)
+require(waiting.opened.count == 2, "A departed setup does not finish again")
+NotificationService.shared.requests = 0
+let steamOnly = Host()
+require(NotificationService.shared.requests == 0, "Startup and Steam-only use never request notifications")
+NotificationService.shared.requests = 0
+steamOnly.acceptBuild()
+require(NotificationService.shared.requests == 1, "Accepted porting requests notifications")
+if failures > 0 { exit(1) }
+print("Onboarding persistence and notification timing: PASS")
+'''
+host = host.replace('// ACTIVATE_FOUND', declaration(' func activate(', (ROOT / 'Sources/NXLibrary/Views/Setup/FoundGamesSetupView+Input.swift').read_text()))
+host = host.replace('// KEYS', declaration(' private enum StorageKeys'))
+host = host.replace('// SETUP', declaration(' @Published public private(set) var firstRunSetup ='))
+host = host.replace('// FINDINGS_CHANGED', findings_changed)
+host = host.replace('// FINISH', finish)
+host = host.replace('// RESTORE', restore).replace('// STARTUP_REQUESTS', startup_requests)
+host = host.replace('// ACCEPTED_BUILD', accepted)
+with tempfile.TemporaryDirectory(prefix='arcane-onboarding-check-') as scratch:
+ scratch = Path(scratch)
+ main = scratch / 'main.swift'
+ main.write_text(host)
+ binary = scratch / 'onboarding'
+ library = ROOT / '.build/debug'
+ subprocess.run(['xcrun', 'swiftc', '-I', str(library), str(main),
+ str(library / 'NXLibraryCore.o'), '-o', str(binary)], check=True)
+ subprocess.run([str(binary)], env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(library)), check=True)
diff --git a/Tests/CatalogAppChecks/run_review.py b/Tests/CatalogAppChecks/run_review.py
new file mode 100644
index 00000000..db7a4c7e
--- /dev/null
+++ b/Tests/CatalogAppChecks/run_review.py
@@ -0,0 +1,438 @@
+#!/usr/bin/env python3
+"""Exercise the review regressions without opening the app or touching player data.
+
+Compiles the actual store/loader and focus/menu methods. Replaces only their
+surrounding UI state and external services; Core readers use generated files.
+Run after swift test, like run_notices.py.
+"""
+from pathlib import Path
+import os
+import struct
+import subprocess
+import tempfile
+import re
+
+ROOT = Path(__file__).resolve().parents[2]
+BIN = ROOT / '.build/debug'
+
+
+def declaration(path, signature):
+ source = (ROOT / path).read_text()
+ start = source.index(signature)
+ opening = source.index('{', start)
+ depth, end = 1, opening + 1
+ while depth:
+ depth += (source[end] == '{') - (source[end] == '}')
+ end += 1
+ return source[start:end]
+
+
+def binary_kv(entries):
+ data = bytearray()
+ for key, value in entries:
+ data.append(0 if isinstance(value, list) else 2 if isinstance(value, int) else 1)
+ data.extend(key.encode() + b'\0')
+ if isinstance(value, list):
+ data.extend(binary_kv(value))
+ elif isinstance(value, int):
+ data.extend(struct.pack(' Bool, _ message: String) {
+ if !ok() { failures += 1; print("FAIL: " + message) }
+}
+
+// Only external enrichment is replaced: no network or player cache writes.
+actor SteamMetadataService {
+ static let shared = SteamMetadataService()
+ func achievementPercents(appID: UInt32) -> [String: Double]? { [:] }
+}
+@MainActor final class ArtworkStore {
+ enum Kind { case hero, logo }
+ func cachedURL(titleID: String, kind: Kind) -> URL? { nil }
+ func fetch(titleID: String, remoteURL: URL?, kind: Kind) async -> URL? { nil }
+}
+struct ArtworkPicks {
+ static let shared = Self()
+ func url(titleID: String, slot: ArtworkSlot) -> URL? { nil }
+}
+@MainActor enum OnlineArtwork {
+ static var platforms: [CriticRatingQuery.Platform] = []
+ static func find(names: [String], slot: ArtworkSlot? = nil,
+ platform: CriticRatingQuery.Platform = .switch) async -> [ArtworkCandidate] {
+ platforms.append(platform)
+ return []
+ }
+}
+
+struct SpotlightPageModel { var links = [1]; var more: [Int] = [] }
+@MainActor final class ModsHost {
+ var localMods: Int?
+ var game: PortedGame?
+ var reloads: [UUID] = []
+ func reload(_ game: PortedGame, viewModel: ViewModel) {
+ self.game = game
+ reloads.append(game.id)
+ }
+ func stop() {}
+ func clearGame() { game = nil }
+}
+@MainActor final class ViewModel {
+ var spotlight = SpotlightState(focus: .actions)
+ var showSetupCheck = false
+ var isGameOptionsOpen = false
+ var alertMessage: String?
+ var gameToClose: Int?
+ var gameToRemove: Int?
+ var launchOverlay: Int?
+ var isBuilding = false
+ var catalogBuildRecoveries: [Int] = []
+ var currentFocusedCatalogGame: CatalogGame?
+ var currentFocusedGame: PortedGame? { currentFocusedCatalogGame?.nxnativeGame }
+}
+@MainActor final class SoundEffectService {
+ enum Cue { case focus }
+ static let shared = SoundEffectService()
+ var count = 0
+ func play(_ cue: Cue) { count += 1 }
+}
+@MainActor final class ScrollHost {
+ let viewModel = ViewModel()
+ var currentPage: SpotlightPageModel? = SpotlightPageModel()
+ var screenshotCount = 0
+ var selectedAchievements: Int? = 1
+ var selectedGame: PortedGame?
+ let modsHost = ModsHost()
+ var scroll: Double = -200
+ var holdScroll = false
+ func offset(for area: SpotlightFocusArea) -> Double {
+ [.pills: 0, .strip: -100, .achievements: -200, .actions: -300, .mods: -400, .more: -500][area]!
+ }
+ func mutate(_ change: (inout SpotlightState) -> Void) { change(&viewModel.spotlight) }
+ func settle() { settleFocusOnScroll() }
+ // ACTUAL_SCROLL
+ // ACTUAL_MODS_RELOAD
+}
+
+@MainActor final class RowGlideHost {
+ let viewModel = ViewModel()
+ let items: [SpotlightItem] = [.card(.collection), .card(.surprise)]
+ func mutate(_ change: (inout SpotlightState) -> Void) { change(&viewModel.spotlight) }
+ // ACTUAL_ROW_GLIDE
+}
+
+enum LaunchCoverTrace { static func event(_ message: String) {} }
+@MainActor final class CoverHandoffHost {
+ struct LaunchScreen { let gameID: UUID }
+ struct State { let generation: Int; var phase: SteamPlayState.Phase }
+ final class SteamClient {
+ var isHidden = false
+ var hides = 0
+ func hide() { hides += 1; isHidden = true }
+ }
+ static let steamApplication: SteamClient? = SteamClient()
+ private static func showSteam() { steamApplication?.isHidden = false }
+ var states: [UUID: State] = [:]
+ var launchScreen: LaunchScreen?
+ var backgrounds: [UUID: Bool] = [:]
+ var late: Set = []
+ private var patience: [UUID: TimeInterval] = [:]
+ private var pendingHandOff: PendingHandOff?
+ private var handOffDeadline: Task?
+ private static let coverWait: UInt64 = 30_000_000
+ // ACTUAL_PENDING_HANDOFF
+ // ACTUAL_PREPARE_HANDOFF
+ // ACTUAL_COVER_PREPARED
+ // ACTUAL_SUBMIT_HANDOFF
+ // ACTUAL_FOLLOW_BACKGROUND
+ private func phase(ofID id: UUID) -> SteamPlayState.Phase { states[id]?.phase ?? .idle }
+ private func followLaunchScreen(now: Date) {}
+ func observe(at now: Date) { followBackground(now: now) }
+ func prepare(_ id: UUID, send: @escaping () -> Void) {
+ states[id] = .init(generation: 1, phase: .starting(since: Date()))
+ prepareHandOff(for: id, generation: 1, send: send)
+ }
+
+ func waitForCoverDeadline() async {
+ await handOffDeadline?.value
+ }
+}
+
+final class Router {
+ var route = AppRoute.library
+ var isScreenshotViewerOpen = false
+ var isSearchPresented = false
+ var isMenuPresented = false
+ func openSettings(_ section: SettingsSection) { route = .settings(section) }
+}
+final class WindowState { var attachedSheet: Int?; var isSheet = false }
+final class ApplicationState {
+ var modalWindow: Int?
+ var keyWindow: WindowState?
+ var mainWindow: WindowState?
+}
+let NSApp = ApplicationState()
+final class NativeMenus { var isTracking = false }
+@MainActor final class GameControllerService {
+ static let shared = GameControllerService()
+ var onAction: ((GamepadAction) -> Void)?
+}
+@MainActor final class InputRecorder { var actions: [GamepadAction] = [] }
+// ACTUAL_ACTION_NAMES
+@MainActor struct SteamPlayCoordinator {
+ static let shared = Self()
+ func canPlay(_ game: CatalogGame) -> Bool { true }
+}
+// ACTUAL_AVAILABILITY_TYPE
+@MainActor final class MenuHost {
+ let router = Router()
+ let viewModel = ViewModel()
+ let nativeMenus = NativeMenus()
+ var isCloseGameOpen = false
+ var showsWelcome = false
+ var showsSettingsNotice = false
+ var showsInstallFailure = false
+ var showsUpdateOffer = false
+ var dialogActions: [GamepadAction] = []
+ var isHomeRoute: Bool { router.route == .library || router.route == .collection }
+ func availability() -> NativeMenuAvailability { nativeMenuAvailability }
+ func connectController() {
+ let viewModel = viewModel
+ let router = router
+ // ACTUAL_CONTROLLER
+ }
+ func settingsNoticeInput(_ action: GamepadAction) { dialogActions.append(action) }
+ func installFailureInput(_ action: GamepadAction) { dialogActions.append(action) }
+ func closeGameInput(_ action: GamepadAction) { dialogActions.append(action) }
+ func removeGameInput(_ action: GamepadAction) { dialogActions.append(action) }
+ func updateOfferInput(_ action: GamepadAction) { dialogActions.append(action) }
+ func menuInput(_ action: GamepadAction) { dialogActions.append(action) }
+ // ACTUAL_DIALOG
+ // ACTUAL_MENU
+}
+
+@main struct Check {
+ @MainActor static func main() async {
+ let root = URL(fileURLWithPath: CommandLine.arguments[1])
+ let store = SteamAchievementsStore()
+ store.load(appID: 42, language: "english")
+ store.setSources([.init(integration: .steam, isEnabled: true, rootURL: root)])
+ for _ in 0..<200 where store.summaries[42] == nil {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ require(store.summaries[42]?.total == 1,
+ "Selection requested before Steam sources must load when the source arrives")
+ store.stop()
+
+ for title in ["0100000000000001", "0400000000000001"] {
+ let game = PortedGame(name: "Generated fixture", url: root.appendingPathComponent(title + ".app"),
+ platform: .macApp, sizeBytes: 1, modificationDate: Date(), titleId: title)
+ _ = await GameArtLoader.shared.logo(for: game, metadata: nil, artwork: ArtworkStore(), personalizations: .empty)
+ }
+ require(OnlineArtwork.platforms == [.switch, .switch2], "Automatic logo search must use each game's console")
+
+ let scroll = ScrollHost()
+ scroll.settle()
+ require(scroll.viewModel.spotlight.focus == .achievements, "Wheel settling must reach the visible achievements card")
+ let cues = SoundEffectService.shared.count
+ scroll.settle()
+ require(SoundEffectService.shared.count == cues, "Settling on the focused card must not play another focus cue")
+ scroll.selectedAchievements = nil
+ scroll.settle()
+ require(scroll.viewModel.spotlight.focus == .actions, "A missing achievements card must not take focus")
+
+ let menu = MenuHost()
+ menu.viewModel.currentFocusedCatalogGame = .init(nxnative: PortedGame(name: "Fixture", url: root.appendingPathComponent("Game.app"),
+ platform: .macApp, sizeBytes: 1, modificationDate: Date()))
+ require(menu.availability().details, "Details must remain available for the selected game")
+ let firstModsGame = menu.viewModel.currentFocusedGame!
+ let nextModsGame = PortedGame(name: "Next fixture", url: root.appendingPathComponent("Next.app"),
+ platform: .macApp, sizeBytes: 1, modificationDate: Date())
+ scroll.selectedGame = firstModsGame
+ scroll.reloadMods()
+ scroll.viewModel.spotlight.focus = .row
+ scroll.selectedGame = nextModsGame
+ scroll.reloadMods()
+ require(scroll.modsHost.reloads == [firstModsGame.id] && scroll.modsHost.game == nil,
+ "Switching games on the Spotlight row must clear the old Mods band without reading the next one")
+ scroll.viewModel.spotlight.focus = .pills
+ scroll.reloadMods()
+ require(scroll.modsHost.reloads == [firstModsGame.id, nextModsGame.id],
+ "The selected game's Mods band must load once the game page is open")
+
+ let row = RowGlideHost()
+ row.viewModel.spotlight = SpotlightState(selectedKey: row.items[0].key)
+ require(row.handleRowGlide(.navigateRight), "The row must handle Right using only the row items")
+ require(row.viewModel.spotlight.selectedKey == row.items[1].key, "Right selects the next tile")
+ let rowCues = SoundEffectService.shared.count
+ require(row.handleRowGlide(.navigateRight) && SoundEffectService.shared.count == rowCues,
+ "Right at the row's edge is handled without playing a move cue")
+ row.viewModel.spotlight.focus = .pills
+ require(!row.handleRowGlide(.navigateLeft), "Page focus continues to use page navigation")
+
+ let handoff = CoverHandoffHost()
+ let pending = UUID()
+ var handoffs = 0
+ handoff.prepare(pending) { handoffs += 1 }
+ require(handoff.launchScreen?.gameID == pending && handoffs == 0,
+ "Steam must wait for the cover while its state is being published")
+ handoff.launchCoverPrepared(for: UUID())
+ require(handoffs == 0, "Another cover cannot release this launch")
+ handoff.launchCoverPrepared(for: pending)
+ handoff.launchCoverPrepared(for: pending)
+ require(handoffs == 1, "The current cover releases Steam exactly once")
+ handoff.prepare(pending) { handoffs += 1 }
+ handoff.states[pending]?.phase = .idle
+ handoff.launchCoverPrepared(for: pending)
+ require(handoffs == 1, "Closing the launch state must prevent a stale cover from sending Play")
+ handoff.prepare(pending) { handoffs += 1 }
+ // The deadline task starts when the main actor schedules it.
+ await handoff.waitForCoverDeadline()
+ require(handoffs == 2, "Without a visible cover the deadline still lets Play proceed")
+
+ let steam = CoverHandoffHost.steamApplication!
+ let start = Date(timeIntervalSince1970: 1_000)
+ handoff.states[pending]?.phase = .starting(since: start)
+ handoff.backgrounds[pending] = true
+ for attempt in 1...10 {
+ steam.isHidden = false // Steam reappears while processing Play.
+ handoff.observe(at: start.addingTimeInterval(Double(attempt) / 5))
+ }
+ require(steam.hides == 0 && !steam.isHidden,
+ "Startup must let the cover handle Steam coming forward without hiding Steam")
+ steam.isHidden = true
+ handoff.observe(at: start.addingTimeInterval(16))
+ require(handoff.late.contains(pending) && !steam.isHidden,
+ "A stalled launch must still show Steam after the wait")
+ let overlays: [(MenuHost, Bool) -> Void] = [
+ { $0.router.isSearchPresented = $1 }, { $0.router.isScreenshotViewerOpen = $1 },
+ { $0.viewModel.isGameOptionsOpen = $1 }, { $0.router.isMenuPresented = $1 },
+ { $0.viewModel.showSetupCheck = $1 },
+ { $0.isCloseGameOpen = $1 }, { $0.viewModel.launchOverlay = $1 ? 1 : nil }
+ ]
+ for (index, overlay) in overlays.enumerated() {
+ overlay(menu, true)
+ require(!menu.availability().details, "Details must be disabled under overlay \(index)")
+ overlay(menu, false)
+ }
+ menu.viewModel.currentFocusedCatalogGame = .init(steam: .init(appID: 42, name: "Fixture"))
+ require(menu.availability().details, "Steam Details must remain available in Spotlight")
+ menu.router.route = .collection
+ require(!menu.availability().details, "Steam must not acquire a separate Details screen in Collection")
+
+ let input = MenuHost()
+ input.connectController()
+ let received = InputRecorder()
+ let watch = NotificationCenter.default.addObserver(forName: .nxSpotlightGamepadAction,
+ object: nil, queue: nil) { note in
+ MainActor.assumeIsolated {
+ if let action = note.object as? GamepadAction { received.actions.append(action) }
+ }
+ }
+ defer { NotificationCenter.default.removeObserver(watch); GameControllerService.shared.onAction = nil }
+ GameControllerService.shared.onAction?(.confirm)
+ require(received.actions == [.confirm], "An uncovered library must receive controller actions")
+ received.actions = []
+ let blockers: [(String, (Bool) -> Void)] = [
+ ("pending alert", { input.viewModel.alertMessage = $0 ? "Fixture alert" : nil }),
+ ("modal dialog", { NSApp.modalWindow = $0 ? 1 : nil }),
+ ("key sheet", { NSApp.keyWindow = $0 ? WindowState() : nil; NSApp.keyWindow?.isSheet = $0 }),
+ ("sheet on key window", { NSApp.keyWindow = $0 ? WindowState() : nil; NSApp.keyWindow?.attachedSheet = $0 ? 1 : nil }),
+ ("sheet on main window, no key window", { NSApp.mainWindow = $0 ? WindowState() : nil; NSApp.mainWindow?.attachedSheet = $0 ? 1 : nil }),
+ ("native menu", { input.nativeMenus.isTracking = $0 })
+ ]
+ for (name, block) in blockers {
+ block(true)
+ for action: GamepadAction in [.navigateRight, .confirm, .cancel, .menu, .menuHold] {
+ GameControllerService.shared.onAction?(action)
+ }
+ require(received.actions.isEmpty && input.router.route == .library && !input.router.isMenuPresented,
+ "Controller must not navigate or launch underneath \(name)")
+ if name != "native menu" {
+ require(!input.availability().general, "Native menu commands must yield to \(name)")
+ }
+ // An internal update confirmation is also below the native window.
+ input.showsUpdateOffer = true
+ input.isCloseGameOpen = true
+ GameControllerService.shared.onAction?(.confirm)
+ require(input.dialogActions.isEmpty, "The update dialog must not receive input underneath \(name)")
+ input.showsUpdateOffer = false
+ input.isCloseGameOpen = false
+ block(false)
+ input.router.route = .library
+ input.router.isMenuPresented = false
+ received.actions = []
+ GameControllerService.shared.onAction?(.navigateLeft)
+ require(received.actions == [.navigateLeft], "Closing \(name) must restore fresh input without replaying blocked actions")
+ received.actions = []
+ input.dialogActions = []
+ }
+ input.showsUpdateOffer = true
+ input.isCloseGameOpen = true
+ GameControllerService.shared.onAction?(.confirm)
+ require(input.dialogActions == [.confirm] && received.actions.isEmpty,
+ "An internal update dialog must still receive input when no native window is open")
+ if failures > 0 { exit(1) }
+ print("Actual app review checks passed: achievement startup, logo platform, wheel focus, Mods reads, Steam launch, native dialogs and input routing.")
+ }
+}
+'''
+
+host = host.replace('// ACTUAL_SCROLL', declaration(
+ 'Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift', ' private func settleFocusOnScroll()'))
+host = host.replace('// ACTUAL_MODS_RELOAD', declaration(
+ 'Sources/NXLibrary/Views/Spotlight/SpotlightView.swift', ' func reloadMods()'))
+host = host.replace('// ACTUAL_ROW_GLIDE', declaration(
+ 'Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift', ' func handleRowGlide('))
+coordinator = 'Sources/NXLibrary/Services/SteamPlayCoordinator.swift'
+for marker, signature in (
+ ('// ACTUAL_PENDING_HANDOFF', ' private struct PendingHandOff'),
+ ('// ACTUAL_PREPARE_HANDOFF', ' private func prepareHandOff('),
+ ('// ACTUAL_COVER_PREPARED', ' func launchCoverPrepared('),
+ ('// ACTUAL_SUBMIT_HANDOFF', ' private func submitHandOff('),
+ ('// ACTUAL_FOLLOW_BACKGROUND', ' private func followBackground('),
+):
+ host = host.replace(marker, declaration(coordinator, signature))
+host = host.replace('// ACTUAL_AVAILABILITY_TYPE', declaration(
+ 'Sources/NXLibrary/Services/NativeMenuCommands.swift', 'struct NativeMenuAvailability'))
+host = host.replace('// ACTUAL_MENU', declaration(
+ 'Sources/NXLibrary/Views/Shell/AppShellView.swift', ' private var nativeMenuAvailability:'))
+host = host.replace('// ACTUAL_DIALOG', declaration(
+ 'Sources/NXLibrary/Views/Shell/AppShellView.swift', ' private var nativeDialogOwnsInput:'))
+controller = declaration('Sources/NXLibrary/Views/Shell/AppShellView.swift',
+ ' GameControllerService.shared.onAction =')
+host = host.replace('// ACTUAL_CONTROLLER', controller.replace('[weak viewModel, weak router]', '[self, weak viewModel, weak router]'))
+names = sorted(set(re.findall(r'name: \.(nx\w+)', controller)))
+host = host.replace('// ACTUAL_ACTION_NAMES', 'extension Notification.Name {\n' + '\n'.join(
+ f' static let {name} = Notification.Name("{name}")' for name in names) + '\n}')
+
+with tempfile.TemporaryDirectory(prefix='catalog-review-check-') as folder:
+ scratch = Path(folder)
+ (scratch / 'config').mkdir()
+ (scratch / 'config/loginusers.vdf').write_text('"users" { "76561197960265735" { "MostRecent" "1" } }')
+ stats = scratch / 'appcache/stats'
+ stats.mkdir(parents=True)
+ schema = [('42', [('stats', [('1', [('bits', [('0', [
+ ('name', 'FIRST'), ('display', [('name', [('english', 'First')])])])])])])])]
+ (stats / 'UserGameStatsSchema_42.bin').write_bytes(binary_kv(schema))
+ (stats / 'UserGameStats_7_42.bin').write_bytes(binary_kv([('cache', [('1', [('AchievementTimes', [('0', 10)])])])]))
+ swift = scratch / 'check.swift'
+ swift.write_text(host)
+ executable = scratch / 'check'
+ subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(swift),
+ str(ROOT / 'Sources/NXLibrary/Services/SteamAchievementsStore.swift'),
+ str(ROOT / 'Sources/NXLibrary/Views/Spotlight/GameArtLoader.swift'),
+ str(ROOT / 'Sources/NXLibrary/Models/GamepadType.swift'),
+ str(BIN / 'NXLibraryCore.o'), '-o', str(executable)], cwd=ROOT, check=True)
+ subprocess.run([str(executable), str(scratch)], check=True,
+ env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN)))
diff --git a/Tests/CatalogAppChecks/run_save_restart.py b/Tests/CatalogAppChecks/run_save_restart.py
new file mode 100644
index 00000000..8447be0e
--- /dev/null
+++ b/Tests/CatalogAppChecks/run_save_restart.py
@@ -0,0 +1,176 @@
+#!/usr/bin/env python3
+"""Crash/restart the real save transaction against generated temporary data only.
+
+Run after Core is ready and built with testing enabled. This script only compiles
+its helper against .build/debug/NXLibraryCore.o; it never builds or opens the app.
+"""
+from pathlib import Path
+import os
+import subprocess
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[2]
+LIBRARY = ROOT / '.build/debug'
+SLOTS = ['account', 'device', *[f'user{i}' for i in range(2, 9)], 'users']
+CRASH = 86
+
+HOST = r'''
+import Foundation
+import Darwin
+@testable import NXLibraryCore
+
+let fm = FileManager.default
+let slots: [SaveSlot] = [.account, .device, .user2, .user3, .user4,
+ .user5, .user6, .user7, .user8, .users]
+let names = ["save", "save_device"] + (2...8).map { "save_user\($0)" } + ["save.users"]
+let identity = SaveIdentity(titleID: "0100000000000001", gameName: "Restart fixture",
+ version: "fixture-1", buildID: "synthetic-build")
+func require(_ ok: Bool, _ message: String) throws {
+ if !ok { throw NSError(domain: "SaveRestartCheck", code: 1,
+ userInfo: [NSLocalizedDescriptionKey: message]) }
+}
+func write(_ data: Data, to url: URL) throws {
+ try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try data.write(to: url)
+}
+func payload(_ prefix: String, _ slot: SaveSlot) -> Data {
+ Data((slot == .users ? "nxnative-users-1\n\(prefix)\n" : "\(prefix)-\(slot.rawValue)\n").utf8)
+}
+func content(_ root: URL, _ slot: SaveSlot, _ name: String) -> URL {
+ let piece = root.appendingPathComponent(name)
+ return slot == .users ? piece : piece.appendingPathComponent("nested/progress")
+}
+func seed(_ location: SaveLocation, _ prefix: String) throws {
+ for (slot, name) in zip(slots, names) {
+ try require(location.directory(slot).lastPathComponent == name, "Incorrect path: \(slot)")
+ try write(payload(prefix, slot), to: content(location.root, slot, name))
+ }
+}
+func checkGroup(_ root: URL, _ prefix: String) throws {
+ for (slot, name) in zip(slots, names) {
+ let piece = root.appendingPathComponent(name)
+ let kind = try fm.attributesOfItem(atPath: piece.path)[.type] as? FileAttributeType
+ try require(kind == (slot == .users ? .typeRegular : .typeDirectory), "Incorrect type: \(name)")
+ try require(try Data(contentsOf: content(root, slot, name)) == payload(prefix, slot),
+ "Wrong \(prefix) payload: \(name)")
+ }
+}
+do {
+ try require(CommandLine.arguments.count == 4, "Expected mode, fixture path and checkpoint/state")
+ let mode = CommandLine.arguments[1], argument = CommandLine.arguments[3]
+ let base = URL(fileURLWithPath: CommandLine.arguments[2]).resolvingSymlinksInPath()
+ let location = try SaveLocation.defaultLocation(titleID: identity.titleID,
+ home: base.appendingPathComponent("home"))
+ let store = SaveSnapshotStore(root: base.appendingPathComponent("backups"))
+ let targetFile = base.appendingPathComponent("target-id")
+ try require(SaveSlot.allCases == slots, "Expected all users, with registry last")
+ if mode == "setup" {
+ try seed(location, "target")
+ let target = try store.create(location: location, identity: identity, reason: .manual)
+ try write(Data(target.id.uuidString.utf8), to: targetFile)
+ try seed(location, "original")
+ try write(Data("working".utf8), to: location.root.appendingPathComponent("save_user2.work/progress"))
+ try write(Data("sync".utf8), to: location.root.appendingPathComponent("save.sync"))
+ } else {
+ guard let targetID = UUID(uuidString: try String(contentsOf: targetFile, encoding: .utf8)) else {
+ throw SaveFailure.invalidSnapshot
+ }
+ if mode == "fail" {
+ let target = try store.verify(snapshotID: targetID, titleID: identity.titleID)
+ var io = SaveFileIO()
+ io.afterMutation = { if $0 == argument { _exit(86) } }
+ try SaveTransaction(store: store, isRunning: { false }, io: io)
+ .restore(target, location: location, identity: identity)
+ try require(false, "Forward checkpoint was not reached: \(argument)")
+ } else if mode == "recover" {
+ try require(SaveTransaction.needsRecovery(location: location), "Crash left no recovery journal")
+ var io = SaveFileIO()
+ io.afterMutation = { if $0 == argument { _exit(86) } }
+ let transaction = SaveTransaction(store: store, isRunning: { false }, io: io)
+ try transaction.recover(location: location)
+ try require(argument == "-", "Recovery checkpoint was not reached: \(argument)")
+ let once = try store.currentInventory(location: location)
+ try transaction.recover(location: location)
+ try require(try store.currentInventory(location: location) == once, "Second recovery changed saves")
+ try require(!SaveTransaction.needsRecovery(location: location), "Recovery left its journal")
+ } else if mode == "check" {
+ try require(argument == "target" || argument == "original", "Unknown expected state")
+ try require(!SaveTransaction.needsRecovery(location: location), "Recovery is still pending")
+ let snapshots = try store.list(titleID: identity.titleID)
+ try require(snapshots.count == 2 && snapshots.contains(where: { $0.id == targetID }), "Missing backup")
+ for snapshot in snapshots {
+ let verified = try store.verify(snapshotID: snapshot.id, titleID: identity.titleID)
+ let isTarget = snapshot.id == targetID
+ try require(verified == snapshot && verified.identity == identity, "Backup metadata changed")
+ try require(verified.schemaVersion == 2 && verified.presentSlots == Set(slots), "Incomplete backup")
+ try require(verified.reason == (isTarget ? .manual : .beforeRestore), "Wrong backup reason")
+ try checkGroup(try store.directory(snapshotID: snapshot.id, titleID: identity.titleID),
+ isTarget ? "target" : "original")
+ }
+ let expected = snapshots.first { ($0.id == targetID) == (argument == "target") }!
+ try checkGroup(location.root, argument)
+ try require(try store.currentInventory(location: location) == expected.entries, "Mixed save group")
+ try require(try String(contentsOf: location.root.appendingPathComponent("save_user2.work/progress"), encoding: .utf8)
+ == "working", "Working save changed")
+ try require(try String(contentsOf: location.root.appendingPathComponent("save.sync"), encoding: .utf8)
+ == "sync", "Sync sentinel changed")
+ } else {
+ try require(false, "Unknown helper mode: \(mode)")
+ }
+ }
+} catch {
+ fputs("Save restart check failed: \(error)\n", stderr)
+ exit(1)
+}
+'''
+
+
+def backup_bytes(fixture):
+ root = fixture / 'backups'
+ return {str(path.relative_to(root)): path.read_bytes()
+ for path in root.rglob('*') if path.is_file()}
+
+
+def main():
+ if not (LIBRARY / 'NXLibraryCore.o').is_file():
+ raise SystemExit('Core is not ready: build it with testing enabled before running this harness.')
+ with tempfile.TemporaryDirectory(prefix='arcane-save-restart-') as scratch:
+ scratch = Path(scratch)
+ source, binary = scratch / 'main.swift', scratch / 'save-restart'
+ source.write_text(HOST)
+ subprocess.run(['xcrun', 'swiftc', '-I', str(LIBRARY), str(source),
+ str(LIBRARY / 'NXLibraryCore.o'), '-o', str(binary)],
+ cwd=ROOT, check=True, timeout=60)
+ env = dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(LIBRARY))
+
+ def run(mode, fixture, argument='-', expected=0):
+ result = subprocess.run([str(binary), mode, str(fixture), argument],
+ env=env, capture_output=True, text=True, timeout=30)
+ if result.returncode != expected:
+ raise RuntimeError(f'{mode} {argument}: exit {result.returncode}, expected {expected}\n'
+ f'{result.stdout}{result.stderr}')
+
+ cases = [(checkpoint, None) for checkpoint in ['journal', *SLOTS, 'committed', 'cleanup', 'cleanup-item', 'cleanup-stage']]
+ # All pieces have been swapped at "users", but the journal is not committed.
+ cases += [('users', f'recovery-{slot}') for slot in SLOTS]
+ cases += [('users', checkpoint) for checkpoint in ['cleanup', 'cleanup-item', 'cleanup-stage']]
+ for checkpoint, recovery_crash in cases:
+ label = recovery_crash or checkpoint
+ with tempfile.TemporaryDirectory(prefix=f'{label}-', dir=scratch) as fixture:
+ fixture = Path(fixture)
+ run('setup', fixture)
+ run('fail', fixture, checkpoint, expected=CRASH)
+ backups = backup_bytes(fixture)
+ if recovery_crash:
+ run('recover', fixture, recovery_crash, expected=CRASH)
+ # A fresh process resumes, including after a crash inside rollback.
+ run('recover', fixture)
+ run('check', fixture, 'target' if checkpoint in ['committed', 'cleanup', 'cleanup-item', 'cleanup-stage'] else 'original')
+ if backup_bytes(fixture) != backups:
+ raise RuntimeError(f'{label}: recovery changed backup files')
+ print(f'Save restart {label}: PASS', flush=True)
+ print(f'Save restart checks: PASS ({len(cases)} crash/restart cases)')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/Tests/CatalogAppChecks/run_source_access.py b/Tests/CatalogAppChecks/run_source_access.py
new file mode 100644
index 00000000..23de23bf
--- /dev/null
+++ b/Tests/CatalogAppChecks/run_source_access.py
@@ -0,0 +1,155 @@
+#!/usr/bin/env python3
+"""Check source-access triggers using the real startup block, observer and pickers.
+
+No AppKit windows or player data: replace the picker and the scanner I/O boundary,
+then count requests made by the actual AppViewModel code, as in run_review.py.
+"""
+from pathlib import Path
+import subprocess
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[2]
+source = (ROOT / 'Sources/NXLibrary/ViewModels/AppViewModel.swift').read_text()
+
+
+def declaration(signature):
+ start = source.index(signature)
+ opening = source.index('{', start)
+ depth, end = 1, opening + 1
+ while depth:
+ depth += (source[end] == '{') - (source[end] == '}')
+ end += 1
+ return source[start:end]
+
+
+startup = source[source.index(' restoreBuildInputs(automatic: true)'):
+ source.index(' recoverSavesAtStartup()')]
+host = r'''
+import Foundation
+import Combine
+import UniformTypeIdentifiers
+
+final class Preferences {
+ var values: [String: String] = [:]
+ func string(forKey key: String) -> String? { values[key] }
+ func set(_ value: String, forKey key: String) { values[key] = value }
+ func removeObject(forKey key: String) { values[key] = nil }
+}
+enum AppData {
+ static let preferences = Preferences()
+ struct Profile { var isDevelopment = false }
+ static var profile = Profile()
+}
+enum StorageKeys { static let savedGameFolder = "fixture-folder" }
+struct Startup { var checkEngineAtLaunch = true; var refreshLibraryAtLaunch = true }
+struct GameRuntimeConfig {}
+enum GameFoldersCopy {
+ static func sourcesPickerMessage(extractedFolders: Bool) -> String { "Fixture picker" }
+}
+
+// Only the system picker is substituted. The production methods configure it
+// and choose which scan to request; no permissions or real windows are involved.
+final class NSOpenPanel {
+ enum Response { case OK, cancel }
+ static var response = Response.cancel
+ static var picked: [URL] = []
+ static var openedAt: URL?
+ var canChooseFiles = false
+ var canChooseDirectories = false
+ var allowsMultipleSelection = false
+ var directoryURL: URL?
+ var prompt = ""
+ var message = ""
+ var allowedContentTypes: [UTType] = []
+ var urls: [URL] { Self.picked }
+ var url: URL? { urls.first }
+ func runModal() -> Response { Self.openedAt = directoryURL; return Self.response }
+}
+
+final class SourceHost {
+ private var keepsRememberedGameFolder = false
+ private var restoringGameFolder = false
+ private var selectedPackageURLs: [URL]?
+ var scanGeneration = UUID()
+ var detectedGames: [Int] = []
+ var selectedGame: Int?
+ var selectedSourceIDs: Set = []
+ var scanError: String?
+ var isScanningGameFolder = false
+ var engineSourceCapabilities = (extractedFolders: true, unused: false)
+ var scans: [(folder: URL, files: [URL]?)] = []
+ // ACTUAL_FOLDER
+ // ACTUAL_REMEMBERED_FOLDER
+ // ACTUAL_FOLDER_PICKER
+ // ACTUAL_FILE_PICKER
+ func restoreBuildInputs(automatic: Bool) {}
+ func refreshCompatibility() {}
+ func startNewAddGame(defaults: GameRuntimeConfig) { selectedGameFolder = nil }
+ func scanGameFolder(_ folder: URL) { scans.append((folder, selectedPackageURLs)) }
+ func boot(_ startup: Startup) {
+ let didCompleteSetup = true
+ // ACTUAL_STARTUP
+ }
+}
+
+@main struct Check {
+ static func main() {
+ var failures = 0
+ func require(_ ok: @autoclosure () -> Bool, _ message: String) {
+ if !ok() { failures += 1; print("FAIL: " + message) }
+ }
+ let folder = URL(fileURLWithPath: CommandLine.arguments[1]).appendingPathComponent("Downloads")
+ AppData.preferences.set(folder.path, forKey: StorageKeys.savedGameFolder)
+ for development in [false, true] {
+ AppData.profile.isDevelopment = development
+ for refresh in [false, true] {
+ let model = SourceHost()
+ model.boot(Startup(refreshLibraryAtLaunch: refresh))
+ require(model.scans.isEmpty, "Launch must not scan remembered sources (refresh=\(refresh), dev=\(development))")
+ require(model.selectedGameFolder == nil, "Launch must leave the Add game draft empty")
+ require(model.gameFilesFolder == folder, "Launch must keep the remembered folder preference")
+ }
+ }
+
+ let model = SourceHost()
+ model.boot(Startup())
+ NSOpenPanel.response = .cancel
+ require(!model.selectGameFolder(), "Cancelling the picker must return false")
+ require(model.scans.isEmpty, "Cancelling the picker must not scan sources")
+ require(NSOpenPanel.openedAt == folder, "The folder picker must start at the remembered folder")
+
+ NSOpenPanel.response = .OK
+ NSOpenPanel.picked = [folder]
+ require(model.selectGameFolder(), "An explicit folder choice must be accepted")
+ require(model.scans.count == 1 && model.scans.last?.folder == folder,
+ "An explicit folder choice must request one scan")
+
+ let otherFolder = folder.deletingLastPathComponent().appendingPathComponent("Other inputs")
+ let files = [otherFolder.appendingPathComponent("chosen.nsp"), otherFolder.appendingPathComponent("update.nsp")]
+ let filesModel = SourceHost()
+ filesModel.boot(Startup())
+ NSOpenPanel.picked = files
+ require(filesModel.selectGameFiles(), "Explicit file choices must be accepted")
+ require(filesModel.scans.count == 1 && filesModel.scans.last?.files == files,
+ "Explicit files must request one scan limited to those files")
+ require(filesModel.gameFilesFolder == folder, "File picks must preserve the remembered folder")
+ if failures > 0 { exit(1) }
+ print("Source access checks passed: no launch scan, remembered picker, cancel, explicit folder and files.")
+ }
+}
+'''
+for marker, signature in (
+ ('// ACTUAL_FOLDER', ' @Published public var selectedGameFolder:'),
+ ('// ACTUAL_REMEMBERED_FOLDER', ' public var gameFilesFolder:'),
+ ('// ACTUAL_FOLDER_PICKER', ' public func selectGameFolder('),
+ ('// ACTUAL_FILE_PICKER', ' public func selectGameFiles('),
+):
+ host = host.replace(marker + '\n', declaration(signature) + '\n')
+host = host.replace('// ACTUAL_STARTUP', startup)
+with tempfile.TemporaryDirectory(prefix='source-access-check-') as folder:
+ scratch = Path(folder)
+ swift = scratch / 'check.swift'
+ swift.write_text(host)
+ executable = scratch / 'check'
+ subprocess.run(['xcrun', 'swiftc', '-parse-as-library', str(swift), '-o', str(executable)], check=True)
+ subprocess.run([str(executable), str(scratch)], check=True)
diff --git a/Tests/CatalogAppChecks/run_startup_recovery.py b/Tests/CatalogAppChecks/run_startup_recovery.py
new file mode 100644
index 00000000..8ee63cf0
--- /dev/null
+++ b/Tests/CatalogAppChecks/run_startup_recovery.py
@@ -0,0 +1,105 @@
+#!/usr/bin/env python3
+"""Exercise the actual startup recovery coordinator with isolated catalogs, no windows.
+
+Only profile selection/preparation and shell construction are substituted. The
+catalog, conflict candidates, archives and recovery operations are real Core I/O.
+"""
+from pathlib import Path
+import os
+import subprocess
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[2]
+BIN = ROOT / '.build/debug'
+source = (ROOT / 'Sources/NXLibrary/Views/Launch/DevelopmentStartupView.swift').read_text()
+start = source.index('@MainActor\nfinal class DevelopmentStartup:')
+end = source.index('\nprivate enum DevelopmentStartupFailure:', start)
+coordinator = source[start:end]
+
+host = r'''
+import Foundation
+import AppKit
+import Combine
+import NXLibraryCore
+import os
+
+enum AppData {
+ static var supportRoot = URL(fileURLWithPath: "/unused")
+ static var rejectPreparation = false
+ struct Profile { var isDevelopment = false }
+ static let profile = Profile()
+ static func prepare() throws {
+ if rejectPreparation { throw CocoaError(.fileReadNoPermission) }
+ }
+}
+struct AppSettingsStore {}
+final class AppShellState {
+ let catalog: CatalogDocument
+ init(settings: AppSettingsStore, catalog: CatalogDocument, repository: CatalogRepository) {
+ self.catalog = catalog
+ }
+}
+enum DevelopmentStartupFailure: Error { case otherCopyRunning }
+// ACTUAL_COORDINATOR
+
+@main struct Check {
+ @MainActor static func main() async throws {
+ let root = URL(fileURLWithPath: CommandLine.arguments[1])
+ AppData.supportRoot = root
+ let store = CatalogStore(directory: root)
+ var mixed = try store.loadOrMigrate()
+ mixed.games.append(.init(steam: SteamCatalogGame(appID: 42, name: "Fixture")))
+ mixed = try store.save(mixed, expectedRevision: mixed.revision)
+ let legacy = root.appendingPathComponent("library.json")
+ // Older app creates a legacy library after an initially empty migration.
+ try Data("older-app bytes".utf8).write(to: legacy)
+
+ let startup = DevelopmentStartup()
+ await startup.prepare()
+ precondition(startup.shell == nil && startup.failure != nil)
+ precondition(startup.legacyConflict != nil && startup.recovery == nil && !startup.working)
+ await startup.keepCurrentLibrary()
+ precondition(startup.shell?.catalog.games == mixed.games)
+ precondition(startup.failure == nil && startup.legacyConflict == nil && !startup.working)
+ let unchangedLegacy = try Data(contentsOf: legacy)
+ precondition(unchangedLegacy == Data("older-app bytes".utf8))
+
+ try Data("second edit".utf8).write(to: legacy)
+ let stale = DevelopmentStartup()
+ await stale.prepare()
+ precondition(stale.legacyConflict != nil && stale.shell == nil)
+ try Data("third edit".utf8).write(to: legacy)
+ await stale.keepCurrentLibrary()
+ precondition(stale.shell == nil && stale.legacyConflict == nil && !stale.working)
+ precondition(stale.failure != nil)
+ await stale.prepare()
+ precondition(stale.legacyConflict != nil)
+ await stale.keepCurrentLibrary()
+ precondition(stale.shell?.catalog.games == mixed.games)
+
+ let healthy = DevelopmentStartup()
+ await healthy.prepare()
+ precondition(healthy.shell != nil && healthy.legacyConflict == nil && healthy.recovery == nil)
+
+ AppData.rejectPreparation = true
+ let blocked = DevelopmentStartup()
+ await blocked.prepare()
+ precondition(blocked.shell == nil && blocked.failure != nil && !blocked.working)
+ precondition(blocked.legacyConflict == nil && blocked.recovery == nil)
+ AppData.rejectPreparation = false
+ await blocked.prepare()
+ precondition(blocked.shell != nil && blocked.failure == nil)
+ print("Actual startup recovery checks passed: conflict, explicit keep, stale offer, retry, healthy startup and preparation failure.")
+ }
+}
+'''.replace('// ACTUAL_COORDINATOR', coordinator)
+
+with tempfile.TemporaryDirectory(prefix='catalog-startup-recovery-') as folder:
+ scratch = Path(folder)
+ swift = scratch / 'check.swift'
+ swift.write_text(host)
+ executable = scratch / 'check'
+ subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(swift),
+ str(BIN / 'NXLibraryCore.o'), '-o', str(executable)], cwd=ROOT, check=True)
+ subprocess.run([str(executable), str(scratch / 'profile')], check=True,
+ env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN)))
diff --git a/Tests/CatalogAppChecks/run_theme.py b/Tests/CatalogAppChecks/run_theme.py
new file mode 100644
index 00000000..5f73e9d6
--- /dev/null
+++ b/Tests/CatalogAppChecks/run_theme.py
@@ -0,0 +1,307 @@
+#!/usr/bin/env python3
+"""Actual theme input, soft particles and offscreen Metal contracts.
+
+No windows, player data, screenshots or UI automation. Metal checks are skipped
+when the host has no device; Core and actual input checks still run.
+"""
+from pathlib import Path
+import os
+import subprocess
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[2]
+BIN = ROOT / '.build/debug'
+
+
+def declaration(path, signature):
+ source = (ROOT / path).read_text()
+ start = source.index(signature)
+ opening = source.index('{', start)
+ depth, end = 1, opening + 1
+ while depth:
+ depth += (source[end] == '{') - (source[end] == '}')
+ end += 1
+ return source[start:end]
+
+
+# Controller/keyboard order must match the actual rows, not a second manual list.
+import re
+look_source = (ROOT / 'Sources/NXLibrary/Views/Settings/SettingsLookSection.swift').read_text()
+look_body = look_source[look_source.index(' var body:'):look_source.index(' private func publishActions')]
+visible_rows = re.findall(r'Selene(?:Cycle|Toggle)Row\("([^"]+)"', look_body)
+actions = declaration('Sources/NXLibrary/Views/Settings/SettingsLookSection.swift', ' private func publishActions(')
+action_rows = [a or b for a, b in re.findall(
+ r'\.value\("[^"]+", "([^"]+)"|\.init\(id: "[^"]+", title: "([^"]+)"', actions)]
+assert visible_rows == action_rows, ('Look navigation order differs from visible rows', visible_rows, action_rows)
+
+
+host = r'''
+import Foundation
+import AppKit
+import SwiftUI
+import Metal
+import NXLibraryCore
+
+@MainActor enum LaunchReveal { static func moonlightShown() {} }
+@MainActor final class SoundEffectService {
+ enum Cue { case focus, key, click }
+ static let shared = SoundEffectService()
+ func play(_ cue: Cue) {}
+}
+final class PaletteController {
+ var applied: [String] = []
+ func apply(id: String) { applied.append(id) }
+}
+struct BrowseCategory { var isSearch = false }
+struct BrowseState { var focusedItem: Int?; var category = BrowseCategory() }
+final class Browser { var state: BrowseState? }
+@MainActor final class Host {
+ var state = ThemePickerState(themeIndex: 0, backgroundIndex: 0)
+ let palettes: [SelenePalette]
+ let settings: AppSettingsStore
+ let theme = PaletteController()
+ let browser = Browser()
+ var searchFocused = false
+ var placements: [String?] = []
+ var backgrounds: [ThemeBackgroundChoice] { [.none] }
+ var focusedBackground: ThemeBackgroundChoice { .none }
+ init(palettes: [SelenePalette], settings: AppSettingsStore) { self.palettes = palettes; self.settings = settings }
+ func focusSetting(themeID: String) { state.backgroundIndex = 0 }
+ func choose(_ item: Int) {}
+ func addOwn() {}
+ func askPlacement(_ id: String?) { placements.append(id) }
+ func openSource(_ id: BackgroundSourceID) {}
+ // ACTUAL_METHODS
+ func key(_ direction: GridDirection) { move(direction) }
+ func next() { accept() }
+ func click(_ index: Int) { tap(index) }
+}
+// ACTUAL_STEPPING
+
+// ACTUAL_BACKDROP_STYLE
+// ACTUAL_BACKDROP_REQUEST
+// ACTUAL_BACKDROP_KEY
+final class BackdropTheme {
+ var palette: SelenePalette
+ let palettes: [SelenePalette]
+ init(_ palettes: [SelenePalette]) { self.palettes=palettes; palette=palettes[0] }
+ func wallpaper(for id: String?) -> Wallpaper? { nil }
+ // ACTUAL_APPLY
+}
+final class BackdropViewModel {
+ var showSetupCheck = false
+ var isGameOptionsOpen = false
+}
+@MainActor final class BackdropHost {
+ let theme: BackdropTheme
+ let settings: AppSettingsStore
+ let viewModel = BackdropViewModel()
+ let router = AppRouter()
+ var showsWelcome = false
+ // ACTUAL_COVER_POLICY
+ // ACTUAL_COVER_PRIORITY
+ // ACTUAL_BLUR_POLICY
+ var covered: Bool { fullScreenCover }
+ var blur: CGFloat { contentBlur }
+ var sharedBackdrop: SeleneBackdropRequest?
+ init(theme: BackdropTheme, settings: AppSettingsStore) { self.theme=theme; self.settings=settings }
+ // ACTUAL_SHARED_UPDATE
+ func accept(_ request: SeleneBackdropRequest?) { updateSharedBackdrop(request) }
+ // ACTUAL_SHELL_STYLE
+ var snapshot: SeleneBackdropStyle { backdropStyle }
+}
+
+@main struct Check {
+ @MainActor static func main() throws {
+ let scratch = URL(fileURLWithPath: CommandLine.arguments[1])
+ let settingsURL = scratch.appendingPathComponent("settings.json")
+ let settings = AppSettingsStore(fileURL: settingsURL)
+ let palettes = SelenePaletteCatalog.pickerOrder(try SelenePaletteCatalog.load(from:
+ URL(fileURLWithPath: "Resources/Selene/palettes.json")))
+ precondition(palettes[0].name == AppIdentity.name && palettes[0].id == "selene")
+ precondition(palettes[0].surface == .classic && SelenePalette.fallback.surface == .classic)
+ precondition(palettes.first { $0.id == "arcane-crystal" }?.surface == .arcane)
+ precondition(palettes.first { $0.id == "arcane-flow" }?.surface == .flow)
+ let backdropTheme = BackdropTheme(palettes)
+ let backdropHost = BackdropHost(theme: backdropTheme, settings: settings)
+ precondition(!backdropHost.covered && backdropHost.blur == 0)
+ backdropHost.showsWelcome = true; precondition(backdropHost.covered)
+ backdropHost.showsWelcome = false
+ backdropHost.viewModel.showSetupCheck = true; precondition(backdropHost.covered)
+ backdropHost.viewModel.showSetupCheck = false
+ backdropHost.router.isMenuPresented = true; precondition(!backdropHost.covered)
+ backdropHost.router.isThemePickerOpen = true; precondition(backdropHost.covered)
+ backdropHost.router.closeMenu(); precondition(!backdropHost.covered)
+ backdropHost.router.openAddGame(); precondition(backdropHost.blur == 10)
+ backdropHost.router.back(); precondition(backdropHost.blur == 0)
+ backdropHost.viewModel.isGameOptionsOpen = true; precondition(backdropHost.blur == 10)
+ backdropHost.viewModel.isGameOptionsOpen = false
+ let originalBackdrop = backdropHost.snapshot
+ let homeRequest = SeleneBackdropRequest(style: originalBackdrop)
+ var stacked: SeleneBackdropRequest? = homeRequest
+ var mods = homeRequest; mods.modsTint = true
+ SeleneBackdropRequestKey.reduce(value: &stacked, nextValue: { mods })
+ SeleneBackdropRequestKey.reduce(value: &stacked, nextValue: { nil })
+ precondition(stacked?.modsTint == true)
+ SeleneBackdropRequestKey.reduce(value: &stacked, nextValue: { homeRequest })
+ precondition(stacked == homeRequest, "the top page replaces the underlying Mods background request")
+ var setupRequest = homeRequest; setupRequest.priority = 2.5
+ var menuRequest = mods; menuRequest.priority = 1
+ SeleneBackdropRequestKey.reduce(value: &stacked, nextValue: { setupRequest })
+ SeleneBackdropRequestKey.reduce(value: &stacked, nextValue: { menuRequest })
+ precondition(stacked == setupRequest, "a lower overlay visited later cannot take Setup's background")
+ backdropHost.accept(homeRequest)
+ backdropHost.accept(nil)
+ precondition(backdropHost.sharedBackdrop?.style == originalBackdrop && backdropHost.sharedBackdrop?.still == true,
+ "a temporary gap retains the background and pauses its clock")
+ backdropHost.accept(homeRequest)
+ precondition(backdropHost.sharedBackdrop == homeRequest, "same-wallpaper Settings reuses the same request")
+
+ backdropTheme.apply(id: "arcane-crystal")
+ let crystalBackdrop = backdropHost.snapshot
+ precondition(originalBackdrop != crystalBackdrop,
+ "palette-only changes must update the shared backdrop even with the same wallpaper and selection")
+ backdropTheme.apply(id: "arcane-flow")
+ precondition(backdropHost.snapshot != crystalBackdrop)
+ backdropTheme.apply(id: "selene")
+ precondition(backdropHost.snapshot == originalBackdrop)
+ print("Shared backdrop: palette-only changes propagate without moving the selected card: PASS")
+ let host = Host(palettes: palettes, settings: settings)
+ host.state.themeIndex = palettes.count - 1
+ host.key(.down)
+ host.key(.right)
+ precondition(host.state.step == .theme && host.state.themeIndex == palettes.count - 1)
+ host.state.themeIndex = 4
+ host.key(.right)
+ precondition(host.state.themeIndex == 4)
+ host.click(0)
+ precondition(host.state.themeIndex == 0 && host.state.step == .theme)
+ host.next()
+ precondition(host.state.step == .background && settings.settings.colorThemeID == "selene")
+ precondition(host.theme.applied == ["selene"] && host.placements.isEmpty)
+ host.next()
+ precondition(host.placements == [WallpaperCatalog.none])
+ print("Theme input: grid edges, mouse refocus and Next to background without a particle row: PASS")
+
+ guard MTLCreateSystemDefaultDevice() != nil else {
+ print("Metal unavailable: offscreen rendering checks skipped.")
+ return
+ }
+ guard let engine = MoonlightEngine.shared else { fatalError("Moonlight shaders failed to initialize") }
+ let soft = MoonlightColors(accent: .blue, ink: .white)
+ let arcane = MoonlightColors(accent: .blue, ink: .white, surface: .arcane)
+ let flow = MoonlightColors(accent: .blue, ink: .white, surface: .flow)
+ let gold = MoonlightColors(accent: .yellow, ink: .white, tint: 1)
+ let s = MoonlightEngine.uniforms(width: 640, height: 360, time: 24, breath: 0.75, colors: soft)
+ let a = MoonlightEngine.uniforms(width: 640, height: 360, time: 24, breath: 0.75, colors: arcane)
+ let g = MoonlightEngine.uniforms(width: 640, height: 360, time: 24, breath: 0.75, colors: gold)
+ precondition(s.look.z == 0 && s.look.w == 0 && a.look.z == 0 && a.look.w == 1)
+ precondition(g.look.w == 0 && g.tintTop.w == 1 && g.look.z == 0)
+ func pixels(_ colors: MoonlightColors, _ time: Float = 24) -> Data {
+ let frame = engine.snapshot(width: 640, height: 360, colors: colors, time: time)!
+ return frame.dataProvider!.data! as Data
+ }
+ let fixed = pixels(arcane)
+ precondition(fixed == pixels(arcane), "a still frame keeps both motion and colour fixed")
+ precondition(fixed != pixels(arcane, 27))
+ let flowPixels = pixels(flow)
+ precondition(flowPixels != fixed && flowPixels != pixels(flow, 44))
+ precondition(flowPixels == pixels(flow))
+ var blended = flow
+ blended.flow = 0.5; blended.arcane = 0.5; blended.tint = 0.5
+ precondition(pixels(blended) != fixed && pixels(blended) != flowPixels)
+ for var hidden in [arcane, flow, blended] {
+ hidden.presence = 0
+ precondition(pixels(hidden).allSatisfy { $0 == 0 }, "covered surfaces and particles must remain transparent")
+ }
+ precondition(MoonlightEngine.uniforms(width: 640, height: 360, time: 24, breath: 0.75, colors: flow).look.z == 1)
+ precondition(fixed != pixels(soft), "the colour field reaches soft particles too")
+ precondition(pixels(gold) != fixed)
+
+ // Exercise the very function the real fragment/vertex entry points call.
+ let source = MoonlightShaders.source + """
+ kernel void sampleArcane(device float4 *out [[buffer(0)]], uint i [[thread_position_in_grid]]) {
+ out[i] = float4(arcaneSpectrum(float2(float(i) * 0.13, 0.3 + float(i) * 0.05), float(i) * 35.3, 0.0), 1.0);
+ }
+ kernel void sampleWind(device float4 *out [[buffer(0)]], uint i [[thread_position_in_grid]]) {
+ float phase = float(i)*0.4;
+ out[i] = float4(filamentY(0.5,float2(0.1,0.3),float2(0.9,0.7),0.0,phase,0.0),
+ filamentProfile(0.0), filamentProfile(1.0),
+ filamentY(0.7,float2(0.1,0.3),float2(0.9,0.7),0.0,phase,0.0));
+ }
+ """
+ let device = engine.device
+ let library = try device.makeLibrary(source: source, options: nil)
+ let pipeline = try device.makeComputePipelineState(function: library.makeFunction(name: "sampleArcane")!)
+ let buffer = device.makeBuffer(length: 6 * MemoryLayout>.stride, options: .storageModeShared)!
+ let command = device.makeCommandQueue()!.makeCommandBuffer()!
+ let encoder = command.makeComputeCommandEncoder()!
+ encoder.setComputePipelineState(pipeline); encoder.setBuffer(buffer, offset: 0, index: 0)
+ encoder.dispatchThreads(MTLSize(width: 6, height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 6, height: 1, depth: 1))
+ encoder.endEncoding(); command.commit(); command.waitUntilCompleted()
+ precondition(command.status == .completed)
+ let values = buffer.contents().bindMemory(to: SIMD4.self, capacity: 6)
+ for i in 0..<6 {
+ let expected = MoonlightChromatics.sample(x: Float(i) * 0.13, y: 0.3 + Float(i) * 0.05, time: Float(i) * 35.3)
+ for k in 0..<3 { precondition(abs(values[i][k] - expected[k]) < 0.00002) }
+ }
+ let windPipeline = try device.makeComputePipelineState(function: library.makeFunction(name: "sampleWind")!)
+ let windBuffer = device.makeBuffer(length: 16 * MemoryLayout>.stride, options: .storageModeShared)!
+ let windCommand = device.makeCommandQueue()!.makeCommandBuffer()!
+ let windEncoder = windCommand.makeComputeCommandEncoder()!
+ windEncoder.setComputePipelineState(windPipeline)
+ windEncoder.setBuffer(windBuffer, offset: 0, index: 0)
+ windEncoder.dispatchThreads(MTLSize(width: 16,height: 1,depth: 1), threadsPerThreadgroup: MTLSize(width: 16,height: 1,depth: 1))
+ windEncoder.endEncoding(); windCommand.commit(); windCommand.waitUntilCompleted()
+ precondition(windCommand.status == .completed)
+ let wind = windBuffer.contents().bindMemory(to: SIMD4.self, capacity: 16)
+ let heights = (0..<16).map { wind[$0].x }
+ precondition(heights.max()! - heights.min()! > 0.025 && heights.max()! - heights.min()! < 0.08,
+ "wind must bend the curve visibly, within a small part of the height")
+ precondition(wind[0].z < wind[0].y * 0.2, "one pixel from the core, light must be faint")
+ precondition(abs((wind[3].x-wind[0].x)-(wind[3].w-wind[0].w)) > 0.001,
+ "wind deforms the curve instead of translating a rigid line")
+ for i in 1..<16 { precondition(abs(wind[i].x-wind[i-1].x) < 0.025) }
+ print("Actual Metal: thin core and bounded travelling wind deformation: PASS")
+ print("Actual Metal: local colour parity, distinct moving surfaces, soft particles, fixed frame and distinct Mods uniforms: PASS")
+ }
+}
+'''
+
+path = 'Sources/NXLibrary/Views/Theme/ThemePickerView.swift'
+methods = '\n'.join(declaration(path, signature) for signature in (
+ ' private func move(', ' private func tap(', ' private func accept('))
+host = host.replace('// ACTUAL_METHODS', methods)
+host = host.replace('// ACTUAL_BACKDROP_STYLE', declaration(
+ 'Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift', 'struct SeleneBackdropStyle:'))
+host = host.replace('// ACTUAL_BACKDROP_REQUEST', declaration(
+ 'Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift', 'struct SeleneBackdropRequest:'))
+host = host.replace('// ACTUAL_SHARED_UPDATE', declaration(
+ 'Sources/NXLibrary/Views/Shell/AppShellView.swift', ' private func updateSharedBackdrop('))
+host = host.replace('// ACTUAL_BACKDROP_KEY', declaration(
+ 'Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift', 'struct SeleneBackdropRequestKey:'))
+host = host.replace('// ACTUAL_COVER_POLICY', declaration(
+ 'Sources/NXLibrary/Views/Shell/AppShellView.swift', ' private var fullScreenCover:'))
+host = host.replace('// ACTUAL_COVER_PRIORITY', declaration(
+ 'Sources/NXLibrary/Views/Shell/AppShellView.swift', ' private var currentBackdropCover:'))
+host = host.replace('// ACTUAL_BLUR_POLICY', declaration(
+ 'Sources/NXLibrary/Views/Shell/AppShellView.swift', ' private var contentBlur:'))
+host = host.replace('// ACTUAL_APPLY', declaration(
+ 'Sources/NXLibrary/Views/Theme/ThemeStore.swift', ' public func apply('))
+host = host.replace('// ACTUAL_SHELL_STYLE', declaration(
+ 'Sources/NXLibrary/Views/Shell/AppShellView.swift', ' private var backdropStyle:'))
+
+host = host.replace('// ACTUAL_STEPPING', declaration(
+ 'Sources/NXLibrary/Views/Components/SeleneSettingsRow.swift', 'extension CaseIterable where Self: Equatable'))
+
+with tempfile.TemporaryDirectory(prefix='arcane-theme-check-') as folder:
+ scratch = Path(folder)
+ swift = scratch / 'check.swift'
+ swift.write_text(host)
+ executable = scratch / 'check'
+ subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(swift),
+ str(ROOT / 'Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift'),
+ str(ROOT / 'Sources/NXLibrary/Views/Theme/MoonlightShaders.swift'),
+ str(BIN / 'NXLibraryCore.o'), '-o', str(executable)], cwd=ROOT, check=True)
+ subprocess.run([str(executable), str(scratch)], cwd=ROOT, check=True,
+ env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN)))
diff --git a/Tests/NXLibraryCoreTests/AchievementSummaryTests.swift b/Tests/NXLibraryCoreTests/AchievementSummaryTests.swift
new file mode 100644
index 00000000..2da84065
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/AchievementSummaryTests.swift
@@ -0,0 +1,125 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class AchievementSummaryTests: XCTestCase {
+ private func a(_ api: String, at: TimeInterval? = nil, hidden: Bool = false) -> SteamAchievement {
+ SteamAchievement(apiName: api, name: "N-\(api)", description: "D-\(api)", hidden: hidden,
+ icon: "\(api).jpg", grayIcon: "\(api)-g.jpg", unlockedAt: at.map { Date(timeIntervalSince1970: $0) })
+ }
+
+ func testCountsAndPercentage() {
+ let list = (0..<50).map { a("A\($0)", at: $0 < 17 ? TimeInterval($0 + 1) : nil) }
+ let summary = AchievementSummary(achievements: list, percents: [:])
+ XCTAssertEqual(summary.total, 50)
+ XCTAssertEqual(summary.unlocked, 17)
+ XCTAssertEqual(summary.percentComplete, 34)
+ }
+
+ func testCompleteOnlyWithEveryAchievementUnlocked() {
+ XCTAssertTrue(AchievementSummary(achievements: [a("A", at: 1), a("B", at: 2)], percents: [:]).isComplete)
+ XCTAssertFalse(AchievementSummary(achievements: [a("A", at: 1), a("B")], percents: [:]).isComplete)
+ XCTAssertFalse(AchievementSummary(achievements: [], percents: [:]).isComplete)
+ }
+
+ func testEmptyIsZeroPercent() {
+ XCTAssertEqual(AchievementSummary(achievements: [], percents: [:]).percentComplete, 0)
+ }
+
+ func testAllOrdersUnlockedNewestThenLockedMostCommon() {
+ let summary = AchievementSummary(achievements: [a("L1"), a("U1", at: 10), a("L2"), a("U2", at: 20)],
+ percents: ["L1": 5, "L2": 50, "U1": 1, "U2": 2])
+ XCTAssertEqual(summary.rows(.all).map(\.id), ["U2", "U1", "L2", "L1"])
+ }
+
+ func testUnknownRarityGoesLast() {
+ let summary = AchievementSummary(achievements: [a("X"), a("Y"), a("Z")], percents: ["Z": 3])
+ XCTAssertEqual(summary.rows(.locked).map(\.id), ["Z", "X", "Y"])
+ XCTAssertEqual(summary.rows(.all, order: .rarest).map(\.id), ["Z", "X", "Y"])
+ XCTAssertEqual(summary.rows(.all, order: .commonest).map(\.id), ["Z", "X", "Y"])
+ }
+
+ func testFiltersSplitUnlockedAndLocked() {
+ let summary = AchievementSummary(achievements: [a("L"), a("U", at: 1)], percents: [:])
+ XCTAssertEqual(summary.rows(.unlocked).map(\.id), ["U"])
+ XCTAssertEqual(summary.rows(.locked).map(\.id), ["L"])
+ }
+
+ func testRarestFirstIsAscendingRarity() {
+ let summary = AchievementSummary(achievements: [a("A", at: 1), a("B"), a("C")], percents: ["A": 40, "B": 2, "C": 90])
+ XCTAssertEqual(summary.rows(.all, order: .rarest).map(\.id), ["B", "A", "C"])
+ }
+
+ func testMostCommonFirstIsDescendingRarity() {
+ let summary = AchievementSummary(achievements: [a("A", at: 1), a("B"), a("C")], percents: ["A": 40, "B": 2, "C": 90])
+ XCTAssertEqual(summary.rows(.all, order: .commonest).map(\.id), ["C", "A", "B"])
+ }
+
+ /// An order sorts inside the filter: Unlocked stays the unlocked ones.
+ func testOrderAppliesWithinTheFilter() {
+ let summary = AchievementSummary(achievements: [a("U1", at: 1), a("U2", at: 2), a("L")],
+ percents: ["U1": 3, "U2": 60, "L": 1])
+ XCTAssertEqual(summary.rows(.unlocked, order: .rarest).map(\.id), ["U1", "U2"])
+ XCTAssertEqual(summary.rows(.unlocked, order: .commonest).map(\.id), ["U2", "U1"])
+ XCTAssertEqual(summary.rows(.unlocked).map(\.id), ["U2", "U1"], "default: newest first")
+ }
+
+ /// Equal rarity keeps the default order, so a re-read never shuffles ties.
+ func testTiesKeepTheDefaultOrder() {
+ let summary = AchievementSummary(achievements: [a("A", at: 1), a("B", at: 2), a("C")],
+ percents: ["A": 10, "B": 10, "C": 10])
+ XCTAssertEqual(summary.rows(.all, order: .rarest).map(\.id), ["B", "A", "C"])
+ XCTAssertEqual(summary.rows(.all, order: .commonest).map(\.id), ["B", "A", "C"])
+ }
+
+ func testFiltersAreAllUnlockedLocked() {
+ XCTAssertEqual(AchievementFilter.allCases, [.all, .unlocked, .locked])
+ XCTAssertEqual(AchievementOrder.allCases, [.default, .rarest, .commonest])
+ }
+
+ func testHiddenLockedIsMaskedAndUnlockedHiddenIsNot() {
+ let summary = AchievementSummary(achievements: [a("H", hidden: true), a("V", at: 1, hidden: true)], percents: [:])
+ let locked = summary.rows(.locked)[0]
+ XCTAssertTrue(locked.isMasked)
+ XCTAssertEqual(locked.name, L10n.text("Hidden achievement"))
+ XCTAssertEqual(locked.description, L10n.text("Keep playing to reveal it."))
+ XCTAssertEqual(locked.icon, "H-g.jpg")
+ let unlocked = summary.rows(.unlocked)[0]
+ XCTAssertFalse(unlocked.isMasked)
+ XCTAssertEqual(unlocked.name, "N-V")
+ XCTAssertEqual(unlocked.icon, "V.jpg")
+ }
+
+ func testHiddenLockedWithoutGrayIconShowsNoIcon() {
+ let hidden = SteamAchievement(apiName: "H", name: "N", description: "D", hidden: true,
+ icon: "color.jpg", grayIcon: nil, unlockedAt: nil)
+ let summary = AchievementSummary(achievements: [hidden], percents: [:])
+ XCTAssertNil(summary.rows(.locked)[0].icon, "the color icon would give the secret away")
+ XCTAssertTrue(summary.recentIcons.isEmpty)
+ }
+
+ /// The card locks and blurs a secret among its gray icons, as the list does.
+ func testRecentIconsSayWhichAreSecret() {
+ let summary = AchievementSummary(achievements: [a("A"), a("H", hidden: true)], percents: [:])
+ XCTAssertEqual(summary.recentIcons.map(\.icon), ["A-g.jpg", "H-g.jpg"])
+ XCTAssertEqual(summary.recentIcons.map(\.isMasked), [false, true])
+ }
+
+ func testRecentIconsFallBackToLockedGray() {
+ let none = AchievementSummary(achievements: [a("A"), a("B"), a("C"), a("D")], percents: [:])
+ XCTAssertEqual(none.recentIcons.map(\.icon), ["A-g.jpg", "B-g.jpg", "C-g.jpg"])
+ let some = AchievementSummary(achievements: [a("A", at: 1), a("B", at: 3), a("C"), a("D", at: 2), a("E", at: 4)], percents: [:])
+ XCTAssertEqual(some.recentIcons.map(\.icon), ["E.jpg", "B.jpg", "D.jpg"])
+ }
+
+ func testRecentUnlockedIconsNewestFirstCapped() {
+ let list = (0..<15).map { a("U\($0)", at: TimeInterval($0 + 1)) } + [a("L")]
+ let summary = AchievementSummary(achievements: list, percents: [:])
+ XCTAssertEqual(summary.recentUnlockedIcons(limit: 12).count, 12)
+ XCTAssertEqual(summary.recentUnlockedIcons(limit: 3), ["U14.jpg", "U13.jpg", "U12.jpg"])
+ }
+
+ func testRecentUnlockedIconsEmptyBeforeAnyUnlock() {
+ let summary = AchievementSummary(achievements: [a("A"), a("B")], percents: [:])
+ XCTAssertTrue(summary.recentUnlockedIcons(limit: 12).isEmpty, "locked gray icons are not 'recently unlocked'")
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/AchievementTierTests.swift b/Tests/NXLibraryCoreTests/AchievementTierTests.swift
new file mode 100644
index 00000000..0e51b6a4
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/AchievementTierTests.swift
@@ -0,0 +1,145 @@
+import XCTest
+import AVFoundation
+import ImageIO
+@testable import NXLibraryCore
+
+final class AchievementTierTests: XCTestCase {
+ private func a(_ api: String, at: TimeInterval? = nil) -> SteamAchievement {
+ SteamAchievement(apiName: api, name: "N-\(api)", description: "D-\(api)", hidden: false,
+ icon: nil, grayIcon: nil, unlockedAt: at.map { Date(timeIntervalSince1970: $0) })
+ }
+
+ func testThresholds() {
+ XCTAssertEqual(AchievementTier.forPercent(0), .gold)
+ XCTAssertEqual(AchievementTier.forPercent(9.94), .gold)
+ XCTAssertEqual(AchievementTier.forPercent(10), .silver)
+ XCTAssertEqual(AchievementTier.forPercent(29.94), .silver)
+ XCTAssertEqual(AchievementTier.forPercent(30), .bronze)
+ XCTAssertEqual(AchievementTier.forPercent(100), .bronze)
+ XCTAssertNil(AchievementTier.forPercent(nil))
+ }
+
+ /// The screen prints one decimal: the tier follows the number the player reads.
+ func testTierFollowsTheShownPercent() {
+ XCTAssertEqual(AchievementTier.forPercent(9.96), .silver, "shown as 10.0%")
+ XCTAssertEqual(AchievementTier.forPercent(9.94), .gold, "shown as 9.9%")
+ XCTAssertEqual(AchievementTier.forPercent(29.96), .bronze, "shown as 30.0%")
+ }
+
+ func testBoardOrderIsRarestFirst() {
+ XCTAssertEqual(AchievementTier.allCases, [.arcane, .gold, .silver, .bronze])
+ }
+
+ func testRowTierFollowsPercent() {
+ let summary = AchievementSummary(achievements: [a("G"), a("X")], percents: ["G": 4])
+ let rows = Dictionary(uniqueKeysWithValues: summary.rows(.all).map { ($0.id, $0) })
+ XCTAssertEqual(rows["G"]?.tier, .gold)
+ XCTAssertNil(rows["X"]?.tier)
+ }
+
+ func testCountsPerTier() {
+ let summary = AchievementSummary(achievements: [a("U1", at: 1), a("L1"), a("U2", at: 2), a("L2")],
+ percents: ["U1": 5, "L1": 5, "U2": 20, "L2": 50])
+ XCTAssertEqual(summary.tierCounts[.gold], TierCount(unlocked: 1, total: 2))
+ XCTAssertEqual(summary.tierCounts[.silver], TierCount(unlocked: 1, total: 1))
+ XCTAssertEqual(summary.tierCounts[.bronze], TierCount(unlocked: 0, total: 1))
+ XCTAssertEqual(summary.tierCounts[.arcane], TierCount(unlocked: 0, total: 1))
+ XCTAssertTrue(summary.hasRarity)
+ }
+
+ func testArcaneOnlyAtHundredPercent() {
+ let summary = AchievementSummary(achievements: [a("A", at: 1), a("B", at: 2)], percents: ["A": 50])
+ XCTAssertEqual(summary.tierCounts[.arcane], TierCount(unlocked: 1, total: 1))
+ }
+
+ func testNoAchievementsNoArcane() {
+ let summary = AchievementSummary(achievements: [], percents: [:])
+ for tier in AchievementTier.allCases {
+ XCTAssertEqual(summary.tierCounts[tier], TierCount(unlocked: 0, total: 0), "\(tier)")
+ }
+ XCTAssertNil(summary.lastUnlockedAt)
+ }
+
+ // MARK: The page card's crystal: the best one earned
+
+ /// Everything unlocked: Arcane, even before Steam's rarity arrives.
+ func testBestTierIsArcaneAtHundredPercent() {
+ let summary = AchievementSummary(achievements: [a("A", at: 1), a("B", at: 2)], percents: [:])
+ XCTAssertEqual(summary.bestTier, .arcane)
+ }
+
+ /// Otherwise the rarest tier among the unlocked ones; a rarer one still locked doesn't count.
+ func testBestTierIsTheRarestUnlocked() {
+ let summary = AchievementSummary(achievements: [a("B", at: 1), a("S", at: 2), a("G")],
+ percents: ["B": 60, "S": 20, "G": 3])
+ XCTAssertEqual(summary.bestTier, .silver)
+ let gold = AchievementSummary(achievements: [a("B", at: 1), a("G", at: 2), a("L")],
+ percents: ["B": 60, "G": 3, "L": 1])
+ XCTAssertEqual(gold.bestTier, .gold)
+ }
+
+ func testBestTierNilWithNothingUnlocked() {
+ let summary = AchievementSummary(achievements: [a("G"), a("B")], percents: ["G": 3, "B": 60])
+ XCTAssertNil(summary.bestTier)
+ XCTAssertNil(AchievementSummary(achievements: [], percents: [:]).bestTier)
+ }
+
+ /// Unlocked achievements whose rarity hasn't arrived give no crystal yet: the card keeps its percent.
+ func testBestTierNilWhileRarityUnknown() {
+ let summary = AchievementSummary(achievements: [a("A", at: 1), a("B")], percents: ["B": 3])
+ XCTAssertNil(summary.bestTier)
+ }
+
+ func testUnknownRarityHasNoTierAndNoCounts() {
+ let summary = AchievementSummary(achievements: [a("A", at: 1), a("B")], percents: [:])
+ XCTAssertTrue(summary.rows(.all).allSatisfy { $0.tier == nil })
+ for tier in [AchievementTier.gold, .silver, .bronze] {
+ XCTAssertEqual(summary.tierCounts[tier], TierCount(unlocked: 0, total: 0), "\(tier)")
+ }
+ XCTAssertEqual(summary.tierCounts[.arcane], TierCount(unlocked: 0, total: 1))
+ XCTAssertFalse(summary.hasRarity)
+ }
+
+ func testLastUnlockedIsNewest() {
+ let summary = AchievementSummary(achievements: [a("A", at: 10), a("B", at: 20), a("C")], percents: [:])
+ XCTAssertEqual(summary.lastUnlockedAt, Date(timeIntervalSince1970: 20))
+ }
+
+ /// The completion tier is Arcane (violet), no longer Platinum; the rarity tiers keep their classic names.
+ func testDisplayNames() {
+ let english = AppLocale(language: .english, region: "US")
+ XCTAssertEqual(AchievementTier.allCases.map { $0.displayName(context: english) },
+ ["Arcane", "Gold", "Silver", "Bronze"])
+ let italian = AppLocale(language: .italian, region: "IT")
+ XCTAssertEqual(AchievementTier.allCases.map { $0.displayName(context: italian) },
+ ["Arcano", "Oro", "Argento", "Bronzo"])
+ }
+
+ /// 1024 px: the detail shows the crystal about 540 px tall on a Retina screen; 512 px art was upscaled there
+ /// and looked soft.
+ func testOnlyArcaneHasALoopingAlphaVideo() async throws {
+ for tier in [AchievementTier.gold, .silver, .bronze] { XCTAssertNil(tier.videoURL, "\(tier)") }
+ let url = try XCTUnwrap(AchievementTier.arcane.videoURL)
+ let asset = AVURLAsset(url: url)
+ let tracks = try await asset.loadTracks(withMediaType: .video)
+ let track = try XCTUnwrap(tracks.first)
+ let formats = try await track.load(.formatDescriptions)
+ let format = try XCTUnwrap(formats.first)
+ XCTAssertEqual(CMFormatDescriptionGetExtension(format, extensionKey: kCMFormatDescriptionExtension_ContainsAlphaChannel) as? Bool, true)
+ XCTAssertEqual(CMFormatDescriptionGetMediaSubType(format), kCMVideoCodecType_HEVC) // hvc1: decoded by the media engine
+ let size = try await track.load(.naturalSize)
+ XCTAssertEqual(size, CGSize(width: 384, height: 384))
+ let seconds = try await asset.load(.duration).seconds
+ XCTAssertGreaterThanOrEqual(seconds, 7); XCTAssertLessThanOrEqual(seconds, 8)
+ }
+
+ func testEveryTierHasArt() throws {
+ for tier in AchievementTier.allCases {
+ let url = try XCTUnwrap(tier.imageURL, "\(tier)")
+ let source = try XCTUnwrap(CGImageSourceCreateWithURL(url as CFURL, nil), "\(tier)")
+ let props = try XCTUnwrap(CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any])
+ XCTAssertGreaterThanOrEqual(props[kCGImagePropertyPixelWidth] as? Int ?? 0, 1024, "\(tier)")
+ XCTAssertGreaterThanOrEqual(props[kCGImagePropertyPixelHeight] as? Int ?? 0, 1024, "\(tier)")
+ }
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/AchievementsScreenStateTests.swift b/Tests/NXLibraryCoreTests/AchievementsScreenStateTests.swift
new file mode 100644
index 00000000..15493215
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/AchievementsScreenStateTests.swift
@@ -0,0 +1,163 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class AchievementsScreenStateTests: XCTestCase {
+ private func ids(_ count: Int) -> [String] { (0.. URL {
+ let url = dir.appendingPathComponent(name)
+ try FileManager.default.createDirectory(at: url.appendingPathComponent("Contents"), withIntermediateDirectories: true)
+ return url
+ }
+
+ private func target(_ bundle: URL, isRelease: Bool = true, isTranslocated: Bool = false,
+ isBusy: Bool = false) -> URL? {
+ AppBundleRename.target(bundleURL: bundle, isRelease: isRelease, isTranslocated: isTranslocated, isBusy: isBusy)
+ }
+
+ func testOldNameInWritableFolderBecomesArcane() throws {
+ let bundle = try makeBundle("NX Library.app")
+ let renamed = try XCTUnwrap(target(bundle))
+ XCTAssertEqual(renamed.lastPathComponent, "Arcane.app")
+ XCTAssertEqual(renamed.deletingLastPathComponent().standardizedFileURL, dir.standardizedFileURL)
+
+ try AppBundleRename.perform(bundleURL: bundle, to: renamed)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: bundle.path))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: renamed.appendingPathComponent("Contents").path))
+ }
+
+ func testExistingArcaneBlocksRename() throws {
+ let bundle = try makeBundle("NX Library.app")
+ try makeBundle("Arcane.app")
+ XCTAssertNil(target(bundle))
+ }
+
+ func testReadOnlyFolderBlocksRename() throws {
+ let bundle = try makeBundle("NX Library.app")
+ try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: dir.path)
+ XCTAssertNil(target(bundle))
+ }
+
+ func testDevelopmentCopyNeverRenames() throws {
+ XCTAssertNil(target(try makeBundle("NX Library.app"), isRelease: false))
+ }
+
+ func testTranslocatedCopyNeverRenames() throws {
+ XCTAssertNil(target(try makeBundle("NX Library.app"), isTranslocated: true))
+ }
+
+ func testBusyAppNeverRenames() throws {
+ XCTAssertNil(target(try makeBundle("NX Library.app"), isBusy: true))
+ }
+
+ func testAnyOtherNameIsLeftAlone() throws {
+ XCTAssertNil(target(try makeBundle("My Games.app")))
+ XCTAssertNil(target(try makeBundle("Arcane.app")))
+ }
+
+ func testFailedMoveLeavesTheOldBundle() throws {
+ let bundle = try makeBundle("NX Library.app")
+ let renamed = try XCTUnwrap(target(bundle))
+ try makeBundle("Arcane.app")
+ XCTAssertThrowsError(try AppBundleRename.perform(bundleURL: bundle, to: renamed))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: bundle.appendingPathComponent("Contents").path))
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/AppIconPreferenceTests.swift b/Tests/NXLibraryCoreTests/AppIconPreferenceTests.swift
index c6e2289e..e3bcb766 100644
--- a/Tests/NXLibraryCoreTests/AppIconPreferenceTests.swift
+++ b/Tests/NXLibraryCoreTests/AppIconPreferenceTests.swift
@@ -65,11 +65,12 @@ final class AppIconPreferenceTests: XCTestCase {
func testLibraryRescanPreservesOnlyHereRatherThanTakingScannedDefaults() throws {
let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
defer { try? FileManager.default.removeItem(at: dir) }
- let store = LibraryStore(directory: dir)
+ let store = CatalogRepository(store: CatalogStore(directory: dir))
+ try store.configureSource(.nxnative, enabled: true, root: nil)
var saved = game()
saved.appIconOnMac = false
- try store.save(LibraryFile(games: [saved]))
- let merged = try XCTUnwrap(try store.merge(scanned: [game()]).games.first)
+ try store.updateNXNativeGames { $0 = [saved] }
+ let merged = try XCTUnwrap(try store.mergeNXNative(scanned: [game()]).nxnativeGames.first)
XCTAssertEqual(merged.appIconOnMac, false)
XCTAssertFalse(merged.wantsPickedAppIcon(hasPick: true, hasOriginalIcon: false))
}
diff --git a/Tests/NXLibraryCoreTests/AppLocaleTests.swift b/Tests/NXLibraryCoreTests/AppLocaleTests.swift
index 44269999..16408dde 100644
--- a/Tests/NXLibraryCoreTests/AppLocaleTests.swift
+++ b/Tests/NXLibraryCoreTests/AppLocaleTests.swift
@@ -9,9 +9,9 @@ final class AppLocaleTests: XCTestCase {
let identities = SettingsSection.allCases.map(\.id)
let italian = AppLocale(language: .italian, region: "IT")
let french = AppLocale(language: .french, region: "FR")
- XCTAssertEqual(SettingsSection.games.title(in: italian), "Giochi")
- XCTAssertEqual(SettingsSection.games.title(in: french), "Jeux")
- XCTAssertEqual(SettingsSection.games.title, "Games")
+ XCTAssertEqual(SettingsSection.libraryGames.title(in: italian), "Giochi")
+ XCTAssertEqual(SettingsSection.libraryGames.title(in: french), "Jeux")
+ XCTAssertEqual(SettingsSection.libraryGames.title, "Games")
XCTAssertEqual(SettingsSection.allCases.map(\.id), identities)
XCTAssertEqual(SettingsSection.startUp.id, "startUp")
}
@@ -128,6 +128,9 @@ final class AppLocaleTests: XCTestCase {
L10n.setContext(AppLocale(language: language, region: "CH"))
let warning = BuildWarningCopy.text(stage: "Pipeline archive", summary: "RAW_INTERNAL_SENTINEL")
XCTAssertFalse(warning.contains("RAW_INTERNAL_SENTINEL"), language.rawValue)
+ let prewarm = BuildWarningCopy.text(stage: "Prewarm pipelines", summary: "RAW_INTERNAL_SENTINEL")
+ XCTAssertFalse(prewarm.contains("RAW_INTERNAL_SENTINEL"), language.rawValue)
+ XCTAssertFalse(prewarm.contains("Some pipelines could not be prepared"), language.rawValue)
let missingTicket = PortingFailureReason(kind: .keys, detail: "missing-common-ticket")
XCTAssertEqual(missingTicket.action, .none)
let game = PortedGame(name: "Play", url: URL(fileURLWithPath: "/tmp/Play.app"), platform: .macApp,
diff --git a/Tests/NXLibraryCoreTests/AppRouterTests.swift b/Tests/NXLibraryCoreTests/AppRouterTests.swift
index 9cc12948..e26a2ab6 100644
--- a/Tests/NXLibraryCoreTests/AppRouterTests.swift
+++ b/Tests/NXLibraryCoreTests/AppRouterTests.swift
@@ -2,6 +2,25 @@ import XCTest
@testable import NXLibraryCore
final class AppRouterTests: XCTestCase {
+ func testFullScreenBackdropCoverFollowsTheVisibleLayerPriority() {
+ XCTAssertEqual(ShellBackdropCover.resolve(setup: true, welcome: true, themePicker: true), .setup)
+ XCTAssertEqual(ShellBackdropCover.resolve(setup: false, welcome: true, themePicker: true), .welcome)
+ XCTAssertEqual(ShellBackdropCover.resolve(setup: false, welcome: false, themePicker: true), .themePicker)
+ XCTAssertEqual(ShellBackdropCover.resolve(setup: false, welcome: false, themePicker: false), .none)
+ for priority in [0.0, 0.5, 0.8, 1, 2, 2.4] {
+ XCTAssertTrue(ShellBackdropCover.setup.covers(priority))
+ }
+ XCTAssertFalse(ShellBackdropCover.setup.covers(2.5))
+ XCTAssertFalse(ShellBackdropCover.setup.covers(3))
+ XCTAssertFalse(ShellBackdropCover.setup.covers(4))
+ XCTAssertTrue(ShellBackdropCover.welcome.covers(2))
+ XCTAssertFalse(ShellBackdropCover.welcome.covers(2.5))
+ XCTAssertTrue(ShellBackdropCover.themePicker.covers(0.8))
+ XCTAssertFalse(ShellBackdropCover.themePicker.covers(1))
+ XCTAssertFalse(ShellBackdropCover.themePicker.covers(2))
+ XCTAssertFalse(ShellBackdropCover.none.covers(0))
+ }
+
func testInitialRoute() {
let router = AppRouter()
XCTAssertEqual(router.route, .library)
@@ -78,7 +97,7 @@ final class AppRouterTests: XCTestCase {
router.movePowerMenu(by: 1)
XCTAssertEqual(router.menuSelection.power, .hide)
router.moveMenu(by: -1)
- XCTAssertEqual(router.menuSelection.selected, .setupCheck)
+ XCTAssertEqual(router.menuSelection.selected, .manageSources)
}
func testCloseMenuClosesPowerPills() {
@@ -94,9 +113,9 @@ final class AppRouterTests: XCTestCase {
final class MenuSelectionModelTests: XCTestCase {
func testMenuOrder() {
XCTAssertEqual(MenuAction.allCases,
- [.addGame, .refreshLibrary, .settings, .theme, .console, .setupCheck, .power])
+ [.addGame, .refreshLibrary, .settings, .theme, .console, .setupCheck, .manageSources, .power])
XCTAssertEqual(MenuAction.allCases.map(\.title),
- ["Add Game", "Library refresh", "Settings", "Theme", "Console", "Setup check", "Power"])
+ ["Add Game", "Library refresh", "Settings", "Theme", "Console", "Setup check", "Manage sources", "Power"])
XCTAssertEqual(PowerAction.allCases, [.quit, .hide, .relaunch])
XCTAssertEqual(PowerAction.allCases.map(\.title), ["Quit", "Hide", "Restart app"])
}
diff --git a/Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift b/Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift
index 166d3113..480873d4 100644
--- a/Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift
+++ b/Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift
@@ -72,6 +72,51 @@ final class AppSettingsStoreTests: XCTestCase {
XCTAssertTrue(reloaded.settings.gameDefaults.enableMetalFXUpscale)
}
+ @MainActor
+ func testSelectingAGamePersistsOffTheMainThread() async throws {
+ let url = tempURL()
+ let written = expectation(description: "selection written off the main thread")
+ let fileManager = ObserveSettingsWrite { onMain in
+ XCTAssertFalse(onMain)
+ written.fulfill()
+ }
+ let store = AppSettingsStore(fileURL: url, fileManager: fileManager)
+ let id = UUID()
+ store.rememberLastSelectedGame(id)
+ XCTAssertEqual(store.lastSelectedGameID, id)
+ await fulfillment(of: [written], timeout: 3)
+ XCTAssertEqual(AppSettingsStore(fileURL: url).lastSelectedGameID, id)
+ }
+
+ @MainActor
+ func testSelectingAGameDoesNotInvalidateSettingsObservers() {
+ let store = AppSettingsStore(fileURL: tempURL())
+ var publications = 0
+ let observation = store.objectWillChange.sink { publications += 1 }
+ store.rememberLastSelectedGame(UUID())
+ store.flushPendingSelection()
+ XCTAssertEqual(publications, 0, "A row move must not invalidate views observing settings")
+ withExtendedLifetime(observation) {}
+ }
+
+ @MainActor
+ func testQuittingAndExplicitSettingsWritesKeepTheLatestSelection() {
+ let url = tempURL()
+ let store = AppSettingsStore(fileURL: url)
+ let first = UUID(), second = UUID(), third = UUID()
+ store.rememberLastSelectedGame(first)
+ store.rememberLastSelectedGame(second)
+ store.flushPendingSelection()
+ XCTAssertEqual(AppSettingsStore(fileURL: url).settings.lastSelectedGameID, second)
+
+ store.rememberLastSelectedGame(third)
+ store.settings.showClock = false
+ store.flushPendingSelection()
+ let saved = AppSettingsStore(fileURL: url).settings
+ XCTAssertEqual(saved.lastSelectedGameID, third)
+ XCTAssertFalse(saved.showClock)
+ }
+
func testCorruptFileFallsBackToDefaultsAndKeepsError() throws {
let url = tempURL()
try Data("{ not json".utf8).write(to: url)
@@ -231,15 +276,43 @@ private final class RejectSettingsWrite: FileManager, @unchecked Sendable {
}
}
+private final class ObserveSettingsWrite: FileManager, @unchecked Sendable {
+ let onWrite: (Bool) -> Void
+
+ init(onWrite: @escaping (Bool) -> Void) { self.onWrite = onWrite }
+
+ override func moveItem(at srcURL: URL, to dstURL: URL) throws {
+ try super.moveItem(at: srcURL, to: dstURL)
+ onWrite(Thread.isMainThread)
+ }
+}
+
final class SettingsSectionTests: XCTestCase {
func testAllSectionsArePresent() {
XCTAssertEqual(SettingsSection.allCases.map(\.title), [
- "Search", "Changed", "Start-up", "Navigation", "Spotlight", "Sound & music",
- "Look", "Games", "Controllers", "Library", "Storage", "Engine", "About"
+ "Search", "Changed", "Start-up", "Navigation", "Spotlight", "Sound & music", "Look", "Controllers",
+ "Online services", "Sources", "Games", "Storage", "Setup and engine", "Keys", "Library", "New games",
+ "Cloud saves", "Storage", "About", "Console"
])
XCTAssertTrue(SettingsSection.allCases.allSatisfy { !$0.icon.rawValue.isEmpty })
}
+ func testSidebarGroupsInScreenOrder() {
+ XCTAssertEqual(SettingsSidebarGroup.all.map(\.title), [nil, "General", "Library", "Porting", "System"])
+ // The sidebar's Up/Down follows the groups as drawn, and every section is in exactly one group.
+ XCTAssertEqual(SettingsSidebarGroup.all.flatMap(\.sections), SettingsSection.allCases)
+ XCTAssertEqual(SettingsSection.sources.group.title, "Library")
+ }
+
+ func testPortingSectionsAreNamedWithTheirGroupWhereSearchListsThem() {
+ XCTAssertEqual(SettingsSection.library.place, "Porting · Library")
+ XCTAssertEqual(SettingsSection.games.place, "Porting · New games")
+ XCTAssertEqual(SettingsSection.portingStorage.place, "Porting · Storage")
+ XCTAssertEqual(SettingsSection.sources.place, "Sources")
+ XCTAssertEqual(SettingsSection.look.place, "Look")
+ XCTAssertEqual(SettingsSection.storage.place, "Storage")
+ }
+
func testStartScreenDefaultsAndDecode() throws {
let settings = AppSettings()
XCTAssertEqual(settings.startOn, .spotlight)
diff --git a/Tests/NXLibraryCoreTests/AppUpdateTests.swift b/Tests/NXLibraryCoreTests/AppUpdateTests.swift
index c2a2fd27..f29bf0ea 100644
--- a/Tests/NXLibraryCoreTests/AppUpdateTests.swift
+++ b/Tests/NXLibraryCoreTests/AppUpdateTests.swift
@@ -116,6 +116,21 @@ final class AppUpdateTests: XCTestCase {
}
}
+ private let successorURL = "https://github.com/Bium23/Arcane/releases/download/v0.3.0/NXLibrary-0.3.0.zip"
+
+ func testSuccessorRepositoryAssetIsAccepted() throws {
+ let json = try changingAsset { $0["browser_download_url"] = successorURL }
+ let release = try XCTUnwrap(AppUpdate.parseRelease(json, successor: "Bium23/Arcane"))
+ XCTAssertEqual(release.zipURL.absoluteString, successorURL)
+ XCTAssertNotNil(AppUpdate.parseRelease(Data(releaseJSON.utf8), successor: "Bium23/Arcane"))
+ }
+
+ func testWithoutSuccessorOnlyTheConfiguredPathIsAccepted() throws {
+ let json = try changingAsset { $0["browser_download_url"] = successorURL }
+ XCTAssertNil(AppUpdate.parseRelease(json, successor: nil))
+ XCTAssertNil(AppUpdate.successorRepository)
+ }
+
func testDownloadBudgetAndGitHubRedirectBoundary() {
XCTAssertTrue(AppUpdate.downloadWithinLimit(received: 1024, expected: 1024))
XCTAssertFalse(AppUpdate.downloadWithinLimit(received: 1025, expected: 1024))
@@ -240,6 +255,16 @@ final class AppUpdateTests: XCTestCase {
version: "0.2.0", runningOS: os), .noInfo)
}
+ func testDevelopmentDataMarkerCannotShipAsAnUpdate() throws {
+ let app = try makeApp("Mixed.app")
+ let file = app.appendingPathComponent("Contents/Info.plist")
+ var info = try XCTUnwrap(PropertyListSerialization.propertyList(from: Data(contentsOf: file), format: nil) as? [String: Any])
+ info["NXLibraryDevelopmentProfile"] = true
+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: file)
+ XCTAssertEqual(AppUpdate.bundleProblem(app, expectedID: "local.nxlibrary", version: "0.2.0", runningOS: os), .notRelease)
+ XCTAssertEqual(AppUpdate.installability(app), .developer)
+ }
+
func testBundleWithoutMarkerIsRefused() throws {
let dev = try makeApp("Dev.app", release: false)
XCTAssertEqual(AppUpdate.bundleProblem(dev, expectedID: "local.nxlibrary", version: "0.2.0", runningOS: os),
@@ -284,6 +309,96 @@ final class AppUpdateTests: XCTestCase {
XCTAssertTrue(exe.contains("old"))
}
+ func testUpdatePreservesUserCopiesBesideTheCurrentApp() throws {
+ for name in ["Arcane", "NX Library"] {
+ let installed = dir.appendingPathComponent(UUID().uuidString)
+ let current = try makeApp(name + ".app", in: installed, marker: "current")
+ let keptNew = try makeApp(name + " (new).app", in: installed, marker: "user-new")
+ let keptOld = try makeApp(name + " (old).app", in: installed, marker: "user-old")
+ let staged = try makeApp(in: dir.appendingPathComponent(UUID().uuidString), marker: "candidate")
+ let placed = try AppUpdate.install(staged, over: current, trashOld: false)
+ XCTAssertEqual(placed, current)
+ XCTAssertTrue(try String(contentsOf: keptNew.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("user-new"))
+ XCTAssertTrue(try String(contentsOf: keptOld.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("user-old"))
+ XCTAssertTrue(try String(contentsOf: current.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("candidate"))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: staged.path), "the verified download remains available")
+ }
+ }
+
+ func testMissingCandidatePreservesUserCopies() throws {
+ let current = try makeApp("Arcane.app", marker: "current")
+ let keptNew = try makeApp("Arcane (new).app", marker: "user-new")
+ let keptOld = try makeApp("Arcane (old).app", marker: "user-old")
+ XCTAssertThrowsError(try AppUpdate.install(dir.appendingPathComponent("missing.app"), over: current, trashOld: false))
+ for kept in [keptNew, keptOld, current] {
+ XCTAssertTrue(FileManager.default.fileExists(atPath: kept.appendingPathComponent("Contents/Info.plist").path))
+ }
+ }
+
+ func testPartialCopyFailureKeepsCurrentAndCleansOwnedStage() throws {
+ let installed = dir.appendingPathComponent("Applications")
+ let current = try makeApp(in: installed, marker: "current")
+ let staged = try makeApp(in: dir.appendingPathComponent("download"))
+ XCTAssertThrowsError(try AppUpdate.install(staged, over: current, trashOld: false,
+ fileManager: UpdateCopyFailure(), io: BuildInstallIO()))
+ XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: installed.path), ["NXLibrary.app"])
+ XCTAssertTrue(try String(contentsOf: current.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("current"))
+ }
+
+ func testPublicationFailureKeepsCurrentAndCandidate() throws {
+ let installed = dir.appendingPathComponent("Applications")
+ let current = try makeApp(in: installed, marker: "current")
+ let staged = try makeApp(in: dir.appendingPathComponent("download"))
+ var io = BuildInstallIO()
+ io.publish = { _, _, _ in throw CocoaError(.fileWriteUnknown) }
+ XCTAssertThrowsError(try AppUpdate.install(staged, over: current, trashOld: false, fileManager: .default, io: io))
+ XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: installed.path), ["NXLibrary.app"])
+ XCTAssertTrue(try String(contentsOf: current.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("current"))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: staged.path))
+ }
+
+ func testErrorAfterAtomicSwapFinishesTheInstalledUpdate() throws {
+ let current = try makeApp("Arcane.app", marker: "current")
+ let staged = try makeApp(in: dir.appendingPathComponent("download"), marker: "candidate")
+ var io = BuildInstallIO()
+ io.afterPublish = { throw CocoaError(.fileWriteUnknown) }
+ XCTAssertEqual(try AppUpdate.install(staged, over: current, trashOld: false, fileManager: .default, io: io), current)
+ XCTAssertTrue(try String(contentsOf: current.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("candidate"))
+ }
+
+ func testTrashFailureRetainsPreviousAppWithoutFailingSuccessfulInstall() throws {
+ let installed = dir.appendingPathComponent("Applications")
+ let current = try makeApp("Arcane.app", in: installed, marker: "current")
+ let staged = try makeApp(in: dir.appendingPathComponent("download"), marker: "candidate")
+ let fm = UpdateTrashFailure()
+ XCTAssertEqual(try AppUpdate.install(staged, over: current, trashOld: true, fileManager: fm, io: BuildInstallIO()), current)
+ let retained = try XCTUnwrap(fm.retained)
+ XCTAssertTrue(try String(contentsOf: retained.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("current"))
+ XCTAssertEqual(retained.deletingLastPathComponent().deletingLastPathComponent().path, installed.path)
+ XCTAssertTrue(try String(contentsOf: current.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("candidate"))
+ XCTAssertEqual(try fm.attributesOfItem(atPath: retained.path)[.systemNumber] as? NSNumber,
+ try fm.attributesOfItem(atPath: current.path)[.systemNumber] as? NSNumber)
+ let next = try makeApp(in: dir.appendingPathComponent("next-download"), marker: "next")
+ try AppUpdate.install(next, over: current, trashOld: true, fileManager: fm, io: BuildInstallIO())
+ let second = try XCTUnwrap(fm.retained)
+ XCTAssertNotEqual(second.deletingLastPathComponent(), retained.deletingLastPathComponent())
+ XCTAssertTrue(try String(contentsOf: retained.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("current"))
+ XCTAssertTrue(try String(contentsOf: second.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("candidate"))
+ }
+
+ func testAppChangedDuringCopyIsNotReplaced() throws {
+ let current = try makeApp("Arcane.app", marker: "current")
+ let staged = try makeApp(in: dir.appendingPathComponent("download"), marker: "candidate")
+ let moved = dir.appendingPathComponent("moved.app")
+ let fm = UpdateCopyHook {
+ try FileManager.default.moveItem(at: current, to: moved)
+ try FileManager.default.createDirectory(at: current, withIntermediateDirectories: false)
+ }
+ XCTAssertThrowsError(try AppUpdate.install(staged, over: current, trashOld: false, fileManager: fm, io: BuildInstallIO()))
+ XCTAssertTrue(try String(contentsOf: moved.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("current"))
+ XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: current.path), [])
+ }
+
func testLaterIsPerVersion() {
let now = Date(timeIntervalSince1970: 1_000_000)
let hourAgo = now.addingTimeInterval(-3600)
@@ -311,3 +426,28 @@ final class AppUpdateTests: XCTestCase {
XCTAssertEqual(AppUpdate.repository(defaults: defaults), AppUpdate.defaultRepository)
}
}
+
+private final class UpdateCopyFailure: FileManager, @unchecked Sendable {
+ override func copyItem(at source: URL, to destination: URL) throws {
+ try createDirectory(at: destination, withIntermediateDirectories: false)
+ try Data("partial".utf8).write(to: destination.appendingPathComponent("partial"))
+ throw CocoaError(.fileWriteUnknown)
+ }
+}
+
+private final class UpdateTrashFailure: FileManager, @unchecked Sendable {
+ var retained: URL?
+ override func trashItem(at url: URL, resultingItemURL: AutoreleasingUnsafeMutablePointer?) throws {
+ retained = url
+ throw CocoaError(.fileWriteNoPermission)
+ }
+}
+
+private final class UpdateCopyHook: FileManager, @unchecked Sendable {
+ let afterCopy: () throws -> Void
+ init(afterCopy: @escaping () throws -> Void) { self.afterCopy = afterCopy; super.init() }
+ override func copyItem(at source: URL, to destination: URL) throws {
+ try super.copyItem(at: source, to: destination)
+ try afterCopy()
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/ArcaneNameTests.swift b/Tests/NXLibraryCoreTests/ArcaneNameTests.swift
new file mode 100644
index 00000000..1037f12c
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/ArcaneNameTests.swift
@@ -0,0 +1,38 @@
+import XCTest
+@testable import NXLibraryCore
+
+/// The app shows itself as Arcane everywhere a person or a web service can see a name.
+final class ArcaneNameTests: XCTestCase {
+ private var repository: URL {
+ URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ }
+
+ func testCatalogShowsNoOldAppName() throws {
+ let url = repository.appendingPathComponent("Sources/NXLibraryCore/Resources/Localizable.xcstrings")
+ let catalog = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]
+ let strings = try XCTUnwrap(catalog?["strings"] as? [String: Any])
+ var found: [String] = []
+ for (key, entry) in strings {
+ if key.contains("NX Library") { found.append(key) }
+ let localizations = (entry as? [String: Any])?["localizations"] as? [String: Any] ?? [:]
+ for (language, value) in localizations {
+ let text = ((value as? [String: Any])?["stringUnit"] as? [String: Any])?["value"] as? String ?? ""
+ if text.contains("NX Library") { found.append("\(language): \(key)") }
+ }
+ }
+ XCTAssertEqual(found.sorted(), [])
+ }
+
+ func testUserAgentNamesArcane() {
+ XCTAssertEqual(AppIdentity.userAgent(version: "0.2"), "Arcane/0.2 (macOS; +https://github.com/Bium23/NxLibrary)")
+ }
+
+ func testNoSourceSendsTheOldUserAgent() throws {
+ let sources = repository.appendingPathComponent("Sources")
+ let files = FileManager.default.enumerator(at: sources, includingPropertiesForKeys: nil)?
+ .compactMap { $0 as? URL }.filter { $0.pathExtension == "swift" } ?? []
+ let offenders = try files.filter { try String(contentsOf: $0, encoding: .utf8).contains("\"NXLibrary/") }
+ .map(\.lastPathComponent)
+ XCTAssertEqual(offenders, [])
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/ArcaneWelcomeTests.swift b/Tests/NXLibraryCoreTests/ArcaneWelcomeTests.swift
new file mode 100644
index 00000000..28a2d69b
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/ArcaneWelcomeTests.swift
@@ -0,0 +1,63 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class ArcaneWelcomeTests: XCTestCase {
+ func testShowsOnceAfterUpdate() {
+ XCTAssertTrue(ArcaneWelcome.shouldShow(setupCompleted: true, shown: false, hasPendingRecovery: false))
+ XCTAssertFalse(ArcaneWelcome.shouldShow(setupCompleted: true, shown: true, hasPendingRecovery: false))
+ }
+
+ func testUnfinishedSetupNeverShows() {
+ XCTAssertFalse(ArcaneWelcome.shouldShow(setupCompleted: false, shown: false, hasPendingRecovery: false))
+ }
+
+ func testNewInstallNeverShows() {
+ let finished = ArcaneWelcome.markShown(AppSettings())
+ XCTAssertTrue(finished.welcomeArcaneShown)
+ XCTAssertFalse(ArcaneWelcome.shouldShow(setupCompleted: true, shown: finished.welcomeArcaneShown,
+ hasPendingRecovery: false))
+ }
+
+ func testWaitsForPendingRecovery() {
+ XCTAssertFalse(ArcaneWelcome.shouldShow(setupCompleted: true, shown: false, hasPendingRecovery: true))
+ }
+
+ func testOldSettingsFileDecodesAsNotShown() throws {
+ let old = Data(#"{"showClock": false}"#.utf8)
+ let settings = try JSONDecoder().decode(AppSettings.self, from: old)
+ XCTAssertFalse(settings.welcomeArcaneShown)
+ XCTAssertFalse(settings.showClock)
+ var shown = settings
+ shown.welcomeArcaneShown = true
+ let back = try JSONDecoder().decode(AppSettings.self, from: JSONEncoder().encode(shown))
+ XCTAssertTrue(back.welcomeArcaneShown)
+ }
+
+ func testOfferOnlyWhenSteamFoundAndOff() {
+ XCTAssertEqual(ArcaneWelcome.offer(steamEnabled: false, steamGameCount: 12), .steam(gameCount: 12))
+ XCTAssertNil(ArcaneWelcome.offer(steamEnabled: true, steamGameCount: 12))
+ XCTAssertNil(ArcaneWelcome.offer(steamEnabled: false, steamGameCount: 0))
+ XCTAssertNil(ArcaneWelcome.offer(steamEnabled: false, steamGameCount: nil))
+ }
+
+ func testFocusOrder() {
+ let offer = ArcaneWelcome.Offer.steam(gameCount: 3)
+ XCTAssertEqual(ArcaneWelcome.Focus.order(offer: offer), [.add, .notNow, .openLibrary])
+ XCTAssertEqual(ArcaneWelcome.Focus.order(offer: nil), [.openLibrary])
+ XCTAssertEqual(ArcaneWelcome.Focus.initial(offer: offer), .add)
+ XCTAssertEqual(ArcaneWelcome.Focus.initial(offer: nil), .openLibrary)
+ XCTAssertEqual(ArcaneWelcome.Focus.add.moved(.right, offer: offer), .notNow)
+ XCTAssertEqual(ArcaneWelcome.Focus.notNow.moved(.left, offer: offer), .add)
+ XCTAssertEqual(ArcaneWelcome.Focus.add.moved(.down, offer: offer), .openLibrary)
+ XCTAssertEqual(ArcaneWelcome.Focus.notNow.moved(.down, offer: offer), .openLibrary)
+ XCTAssertEqual(ArcaneWelcome.Focus.openLibrary.moved(.up, offer: offer), .add)
+ XCTAssertEqual(ArcaneWelcome.Focus.openLibrary.moved(.up, offer: nil), .openLibrary)
+ XCTAssertEqual(ArcaneWelcome.Focus.add.moved(.up, offer: offer), .add)
+ }
+
+ func testDismissingMarksShown() {
+ for exit in ArcaneWelcome.Exit.allCases {
+ XCTAssertTrue(ArcaneWelcome.settings(after: exit, from: AppSettings()).welcomeArcaneShown, "\(exit)")
+ }
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/BoundedDownloadTests.swift b/Tests/NXLibraryCoreTests/BoundedDownloadTests.swift
new file mode 100644
index 00000000..61075e33
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/BoundedDownloadTests.swift
@@ -0,0 +1,82 @@
+import XCTest
+@testable import NXLibraryCore
+
+/// Serves a fixed body in several chunks, or a redirect, without the network.
+private final class ChunkedStub: URLProtocol {
+ nonisolated(unsafe) static var chunks: [Data] = []
+ nonisolated(unsafe) static var declaredLength: Int?
+ nonisolated(unsafe) static var redirect: URL?
+ override class func canInit(with request: URLRequest) -> Bool { true }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+ override func startLoading() {
+ let url = request.url!
+ if let target = Self.redirect, url != target {
+ // A refused redirect leaves the 302 as the final response; followed, the target would load with 200.
+ let response = HTTPURLResponse(url: url, statusCode: 302, httpVersion: nil, headerFields: ["Location": target.absoluteString])!
+ client?.urlProtocol(self, wasRedirectedTo: URLRequest(url: target), redirectResponse: response)
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
+ client?.urlProtocolDidFinishLoading(self)
+ return
+ }
+ var headers: [String: String] = [:]
+ if let length = Self.declaredLength { headers["Content-Length"] = String(length) }
+ let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: headers)!
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
+ for chunk in Self.chunks { client?.urlProtocol(self, didLoad: chunk) }
+ client?.urlProtocolDidFinishLoading(self)
+ }
+ override func stopLoading() {}
+}
+
+final class BoundedDownloadTests: XCTestCase {
+ private let url = URL(string: "https://example.invalid/page")!
+ private func session() -> URLSession {
+ let config = URLSessionConfiguration.ephemeral
+ config.protocolClasses = [ChunkedStub.self]
+ return URLSession(configuration: config)
+ }
+ override func setUp() {
+ ChunkedStub.chunks = []; ChunkedStub.declaredLength = nil; ChunkedStub.redirect = nil
+ }
+
+ func testCollectsEveryChunkUpToTheLimit() async throws {
+ ChunkedStub.chunks = [Data(repeating: 1, count: 4), Data(repeating: 2, count: 4), Data(repeating: 3, count: 2)]
+ let (data, response) = try await BoundedDownload.data(for: URLRequest(url: url), session: session(), limit: 10)
+ XCTAssertEqual(data, Data([1, 1, 1, 1, 2, 2, 2, 2, 3, 3]))
+ XCTAssertEqual((response as? HTTPURLResponse)?.statusCode, 200)
+ XCTAssertEqual(response.url, url)
+ }
+
+ func testStopsWhenTheBodyGrowsPastTheLimit() async {
+ ChunkedStub.chunks = [Data(repeating: 1, count: 6), Data(repeating: 2, count: 6)]
+ do {
+ _ = try await BoundedDownload.data(for: URLRequest(url: url), session: session(), limit: 10)
+ XCTFail("An oversized body must not be returned")
+ } catch { XCTAssertEqual((error as? URLError)?.code, .dataLengthExceedsMaximum) }
+ }
+
+ func testRefusesADeclaredLengthPastTheLimit() async {
+ ChunkedStub.chunks = [Data(repeating: 1, count: 4)]
+ ChunkedStub.declaredLength = 11
+ do {
+ _ = try await BoundedDownload.data(for: URLRequest(url: url), session: session(), limit: 10)
+ XCTFail("A declared oversized body must not be read")
+ } catch { XCTAssertEqual((error as? URLError)?.code, .dataLengthExceedsMaximum) }
+ }
+
+ func testNeverFollowsARedirect() async throws {
+ ChunkedStub.redirect = URL(string: "https://elsewhere.invalid/")!
+ let (_, response) = try await BoundedDownload.data(for: URLRequest(url: url), session: session(), limit: 10)
+ XCTAssertEqual((response as? HTTPURLResponse)?.statusCode, 302)
+ XCTAssertEqual(response.url, url)
+ }
+
+ func testCancellationStopsTheRead() async {
+ ChunkedStub.chunks = [Data(repeating: 1, count: 4)]
+ let session = session()
+ let task = Task { try await BoundedDownload.data(for: URLRequest(url: self.url), session: session, limit: 10) }
+ task.cancel()
+ do { _ = try await task.value; XCTFail("A cancelled read must not return data") }
+ catch { XCTAssertTrue(error is CancellationError) }
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/BoxArtServiceTests.swift b/Tests/NXLibraryCoreTests/BoxArtServiceTests.swift
index 88c9273a..223cbd60 100644
--- a/Tests/NXLibraryCoreTests/BoxArtServiceTests.swift
+++ b/Tests/NXLibraryCoreTests/BoxArtServiceTests.swift
@@ -82,17 +82,20 @@ final class BoxArtServiceTests: XCTestCase {
func testTheGamesDBCoverWhenGameTDBHasNone() async throws {
let client = RoutedClient()
- let search = TheGamesDBArt.searchURL(for: "Donkey Kong Bananza")!.absoluteString
+ let search = "https://thegamesdb.net/search.php?name=Donkey%20Kong%20Bananza&platform_id%5B%5D=5021"
client.routes[search] = Data("""
+ Donkey Kong Bananza
Nintendo Switch 2
""".utf8)
client.routes[TheGamesDBArt.gameURL(id: 132468).absoluteString] = Data("""
+ Donkey Kong Bananza
Platform: Nintendo Switch 2
""".utf8)
client.routes["https://cdn.thegamesdb.net/images/original/boxart/front/132468-1.jpg"] = jpeg(width: 500, height: 500)
let (boxArt, artwork, index) = try service(client)
try index.save([zelda])
+ let oldKey = ["tgdb", "040074A01BF12000", GameTDB.normalize("Donkey Kong Bananza")].joined(separator: "|")
+ try JSONEncoder().encode([oldKey: Date()]).write(to: index.directory.appendingPathComponent("boxart-misses.json"))
let url = await boxArt.boxArt(titleID: "040074A01BF12000", names: ["Donkey Kong Bananza"])
XCTAssertNotNil(url)
diff --git a/Tests/NXLibraryCoreTests/BuildServiceTests.swift b/Tests/NXLibraryCoreTests/BuildServiceTests.swift
index ec76fb89..b0c54a4b 100644
--- a/Tests/NXLibraryCoreTests/BuildServiceTests.swift
+++ b/Tests/NXLibraryCoreTests/BuildServiceTests.swift
@@ -3,6 +3,31 @@ import Darwin
@testable import NXLibraryCore
final class BuildServiceTests: XCTestCase {
+ /// A build that cannot even start (here: its working folder is gone) closes its log and its output pipes.
+ func testBuildThatCannotStartLeavesNoFilesOpen() throws {
+ let fm = FileManager.default
+ let root = fm.temporaryDirectory.appendingPathComponent("NXNoStart-\(UUID())")
+ try fm.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? fm.removeItem(at: root) }
+ func openFiles() -> Int { (try? fm.contentsOfDirectory(atPath: "/dev/fd").count) ?? 0 }
+ let service = BuildService()
+ func failOnce() throws -> BuildResult? {
+ let done = expectation(description: "launch failure reported")
+ var result: BuildResult?
+ service.start(command: BuildCommand(executable: URL(fileURLWithPath: "/bin/sh"), arguments: ["-c", "true"],
+ environment: [:], workingDirectory: root.appendingPathComponent("missing")),
+ logURL: root.appendingPathComponent("build.log"), tempApp: root.appendingPathComponent("t.app"),
+ finalApp: root.appendingPathComponent("f.app"), eventHandler: { _ in },
+ completion: { result = $0; done.fulfill() })
+ wait(for: [done], timeout: 10)
+ return result
+ }
+ XCTAssertEqual(try failOnce()?.success, false)
+ let before = openFiles()
+ for _ in 0..<20 { _ = try failOnce() }
+ XCTAssertLessThan(openFiles() - before, 5, "each failed start must close its log file and both pipes")
+ }
+
func testDestinationDisconnectedDuringBuildKeepsTheReadyAppWithoutRecreatingTheFolder() throws {
let fm = FileManager.default
let root = fm.temporaryDirectory.appendingPathComponent("NXDisconnected-\(UUID())")
@@ -129,9 +154,10 @@ final class BuildServiceTests: XCTestCase {
PendingInstaller.hold(pending, for: &game)
XCTAssertThrowsError(try PendingInstaller.install(&game, fileManager: denied))
XCTAssertEqual(game.pendingInstall, pending)
- let store = LibraryStore(directory: root.appendingPathComponent("catalog"))
- try store.save(LibraryFile(games: [game]))
- game = try XCTUnwrap(store.load().games.first)
+ let store = CatalogRepository(store: CatalogStore(directory: root.appendingPathComponent("catalog")))
+ try store.configureSource(.nxnative, enabled: true, root: nil)
+ try store.updateNXNativeGames { $0 = [game] }
+ game = try XCTUnwrap(store.load().nxnativeGames.first)
XCTAssertEqual(game.pendingInstall, pending)
XCTAssertEqual(try PendingInstaller.install(&game), .installed)
XCTAssertNil(game.pendingInstall)
diff --git a/Tests/NXLibraryCoreTests/CatalogBuildRecoveryTests.swift b/Tests/NXLibraryCoreTests/CatalogBuildRecoveryTests.swift
new file mode 100644
index 00000000..668786ce
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/CatalogBuildRecoveryTests.swift
@@ -0,0 +1,51 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class CatalogBuildRecoveryTests: XCTestCase {
+ private func generation(_ name: String, basedOn original: PortedGame) -> PortedGame {
+ var result = original
+ var record = original.lastBuild!
+ record.outputPath = "/tmp/" + name + ".app"
+ result.pendingInstall = PendingInstall(tempApp: URL(fileURLWithPath: "/tmp/held/" + name + ".app"), finalApp: original.url,
+ record: record, toolchain: original.toolchain)
+ result.lastBuild = record
+ return result
+ }
+
+ func testRetainedNewerBuildSuspendsAutomaticInstallAndExplicitRetryUsesIt() throws {
+ let a = generation("A", basedOn: CatalogTestSupport.completeLegacyGame())
+ let b = generation("B", basedOn: a)
+ var recoveries = CatalogBuildRecoveries()
+ recoveries.retain(b)
+ XCTAssertNil(try recoveries.pendingCandidate(persisted: a, explicitRetry: false))
+ var latest = a; latest.isFavorite = false; latest.settings.language = "de"
+ let candidate = try XCTUnwrap(recoveries.pendingCandidate(persisted: latest, explicitRetry: true))
+ XCTAssertEqual(candidate.pendingInstall?.tempApp.path, "/tmp/held/B.app")
+ XCTAssertEqual(candidate.lastBuild, b.lastBuild)
+ XCTAssertFalse(candidate.isFavorite)
+ XCTAssertEqual(candidate.settings.language, "de")
+ }
+
+ func testCommittingOldGenerationCannotDiscardNewerRecovery() throws {
+ let a = generation("A", basedOn: CatalogTestSupport.completeLegacyGame())
+ let b = generation("B", basedOn: a)
+ var recoveries = CatalogBuildRecoveries()
+ recoveries.retain(a); recoveries.retain(b)
+ recoveries.acknowledge(id: a.id, matching: a)
+ XCTAssertEqual(recoveries[a.id], b)
+ recoveries.acknowledge(id: a.id, matching: nil)
+ XCTAssertEqual(recoveries[a.id], b)
+ recoveries.acknowledge(id: a.id, matching: b)
+ XCTAssertNil(recoveries[a.id])
+ }
+
+ func testRetainedInstalledResultDoesNotResurrectOlderPendingInstallation() throws {
+ let a = generation("A", basedOn: CatalogTestSupport.completeLegacyGame())
+ var b = generation("B", basedOn: a); b.pendingInstall = nil; b.status = .built
+ var recoveries = CatalogBuildRecoveries(); recoveries.retain(b)
+ let candidate = try XCTUnwrap(recoveries.pendingCandidate(persisted: a, explicitRetry: true))
+ XCTAssertNil(candidate.pendingInstall)
+ XCTAssertEqual(candidate.lastBuild, b.lastBuild)
+ XCTAssertNil(try recoveries.pendingCandidate(persisted: a, explicitRetry: false))
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/CatalogLibraryQueryTests.swift b/Tests/NXLibraryCoreTests/CatalogLibraryQueryTests.swift
new file mode 100644
index 00000000..cdabe951
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/CatalogLibraryQueryTests.swift
@@ -0,0 +1,49 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class CatalogLibraryQueryTests: XCTestCase {
+ private func games() -> [CatalogGame] {
+ var nx = CatalogTestSupport.completeLegacyGame(); nx.isHidden = false; nx.isFavorite = false
+ var steam = SteamCatalogGame(appID: 10, name: "Árena"); steam.hasBeenRecognized = true; steam.isFavorite = true
+ return [.init(nxnative: nx), .init(steam: steam)]
+ }
+ func testMixedProjectionRespectsEnabledHiddenAndRecognizedStates() throws {
+ var records = games()
+ let enabled: [CatalogSourceConfiguration] = [.init(integration: .nxnative, isEnabled: true), .init(integration: .steam, isEnabled: true, rootURL: URL(fileURLWithPath: "/tmp/Steam"))]
+ XCTAssertEqual(CatalogLibraryProjection.visible(games: records, sources: enabled).count, 2)
+ XCTAssertEqual(CatalogLibraryProjection.visible(games: records, sources: [.init(integration: .nxnative, isEnabled: true)]).count, 1)
+ records[1].setHidden(true)
+ XCTAssertEqual(CatalogLibraryProjection.visible(games: records, sources: enabled).count, 1)
+ records.append(.init(steam: SteamCatalogGame(appID: 20, name: "Unclassified")))
+ XCTAssertEqual(CatalogLibraryProjection.visible(games: records, sources: enabled).count, 1)
+ }
+ func testSearchAndFavoriteFilterUseSharedCatalogSemantics() {
+ let records = games()
+ XCTAssertEqual(LibraryQuery(searchText: "arena").applyCatalog(to: records, history: NoPlayHistory()).map(\.integration), [.steam])
+ XCTAssertEqual(LibraryQuery(filter: .favorites).applyCatalog(to: records, history: NoPlayHistory()).map(\.integration), [.steam])
+ XCTAssertEqual(LibraryQuery(searchText: "10").applyCatalog(to: records, history: NoPlayHistory()).map(\.integration), [.steam, .nxnative]) // both external IDs contain 10
+ }
+ func testCatalogSelectionAndSpotlightOrderKeepSteamIdentity() {
+ let records = games()
+ var selection = LibrarySelectionState(selectedGameID: records[1].id)
+ _ = selection.reconcileCatalog(with: records, history: NoPlayHistory())
+ XCTAssertEqual(selection.selectedGameID, records[1].id)
+ let row = SpotlightRow.build(gameIDs: records.map(\.id), enabledCards: [], order: [SpotlightItem.game(records[1].id).key])
+ XCTAssertEqual(Set(row), Set(records.map { SpotlightItem.game($0.id) }))
+ _ = selection.reconcileCatalog(with: [records[0]], history: NoPlayHistory())
+ XCTAssertEqual(selection.selectedGameID, records[0].id)
+ }
+ func testInstalledAndHistoryFiltersDoNotInferSteamPlayFromDiscovery() {
+ let records = games()
+ struct History: PlayHistory {
+ let played: UUID
+ func lastPlayed(for id: UUID) -> Date? { id == played ? Date(timeIntervalSince1970: 100) : nil }
+ }
+ let history = History(played: records[1].id)
+ XCTAssertEqual(LibraryQuery(filter: .installed).applyCatalog(to: records, history: history).map(\.integration), [.nxnative])
+ XCTAssertEqual(LibraryQuery(filter: .recentlyPlayed).applyCatalog(to: records, history: history).map(\.integration), [.steam])
+ XCTAssertEqual(LibraryQuery(filter: .notPlayed).applyCatalog(to: records, history: history).map(\.integration), [.nxnative])
+ XCTAssertTrue(LibraryQuery(filter: .recentlyPlayed).applyCatalog(to: records, history: NoPlayHistory()).isEmpty)
+ }
+
+}
diff --git a/Tests/NXLibraryCoreTests/CatalogModelTests.swift b/Tests/NXLibraryCoreTests/CatalogModelTests.swift
new file mode 100644
index 00000000..6acec0b9
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/CatalogModelTests.swift
@@ -0,0 +1,122 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class CatalogModelTests: XCTestCase {
+ func testCompleteLegacyRecordRoundTripsWithoutLosingAnyField() throws {
+ let original = CatalogTestSupport.completeLegacyGame()
+ let game = CatalogGame(nxnative: original)
+ XCTAssertEqual(game.id, original.id)
+ XCTAssertEqual(game.nxnativeGame, original)
+ XCTAssertEqual(game.personalizationKey, "0100000000000001")
+ let data = try JSONEncoder().encode(game)
+ let loaded = try JSONDecoder().decode(CatalogGame.self, from: data)
+ XCTAssertEqual(loaded, game)
+ XCTAssertEqual(loaded.nxnativeGame, original)
+ XCTAssertNil(loaded.steamGame)
+ }
+
+ func testLegacyKeyFallbackAndProviderNamespacesRemainDistinct() throws {
+ var legacy = CatalogTestSupport.completeLegacyGame()
+ legacy.titleId = nil
+ legacy.bundleId = "fixture.bundle"
+ let game = CatalogGame(nxnative: legacy)
+ XCTAssertEqual(game.personalizationKey, "fixture.bundle")
+ let steam = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "Same name"))
+ XCTAssertNotEqual(game.personalizationReference.namespace, steam.personalizationReference.namespace)
+ XCTAssertNil(steam.nxnativeGame)
+ }
+
+ func testCommonUserStateHasOneOwnerAndSurvivesSerialization() throws {
+ var game = CatalogGame(nxnative: CatalogTestSupport.completeLegacyGame())
+ game.setFavorite(false)
+ game.setHidden(false)
+ XCTAssertFalse(try XCTUnwrap(game.nxnativeGame).isFavorite)
+ XCTAssertFalse(try XCTUnwrap(game.nxnativeGame).isHidden)
+ var steam = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "G"))
+ steam.setFavorite(true)
+ steam.setHidden(true)
+ let result = try JSONDecoder().decode(CatalogGame.self, from: JSONEncoder().encode(steam))
+ XCTAssertTrue(result.isFavorite)
+ XCTAssertTrue(result.isHidden)
+ XCTAssertEqual(result.id, steam.id)
+ }
+
+ func testUpdatesRejectIntegrationOrIdentityChangesAndKeepPersonalLookupReference() throws {
+ let original = CatalogTestSupport.completeLegacyGame()
+ var game = CatalogGame(nxnative: original)
+ var update = original
+ update.titleId = "0100000000000002"
+ try game.updateNXNative(update)
+ XCTAssertEqual(game.personalizationKey, "0100000000000001")
+ XCTAssertEqual(game.nxnativeGame?.titleId, "0100000000000002")
+ update.id = UUID()
+ XCTAssertThrowsError(try game.updateNXNative(update))
+ var steam = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "G"))
+ XCTAssertThrowsError(try steam.updateNXNative(original))
+ XCTAssertNil(steam.nxnativeGame)
+ }
+
+ func testSteamDoesNotSupportEngineOrDestructiveOperations() throws {
+ let game = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "Steam game"))
+ let shown = CatalogGamePresentation(game: game, sourceEnabled: true)
+ var record = game
+ XCTAssertThrowsError(try record.updateNXNative(CatalogTestSupport.completeLegacyGame())) { error in
+ XCTAssertEqual(error as? CatalogModelError, .wrongIntegration)
+ }
+ XCTAssertNil(shown.launchTarget)
+ XCTAssertFalse(shown.isListedNormally)
+ }
+
+ func testLegacyPresentationPreservesPlaySemanticsWithoutConsultingTheFilesystem() throws {
+ var original = CatalogTestSupport.completeLegacyGame()
+ original.isHidden = false
+ let shown = CatalogGamePresentation(game: CatalogGame(nxnative: original), sourceEnabled: true)
+ XCTAssertEqual(shown.launchTarget, .nxnative(appURL: original.url))
+ XCTAssertTrue(shown.isListedNormally)
+ XCTAssertEqual(shown.installations.first?.contentURL, original.url)
+ original.status = .appMissing
+ XCTAssertNil(CatalogGamePresentation(game: CatalogGame(nxnative: original), sourceEnabled: true).launchTarget)
+ original.status = .notBuilt
+ original.url = URL(fileURLWithPath: "/tmp/catalog-fixture/workspace")
+ XCTAssertTrue(CatalogGamePresentation(game: CatalogGame(nxnative: original), sourceEnabled: true).installations.isEmpty)
+ }
+
+ func testUnknownIntegrationTagCannotBeDecodedAsAnEmptyOrLegacyGame() throws {
+ let game = CatalogGame(nxnative: CatalogTestSupport.completeLegacyGame())
+ var json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(game)) as? [String: Any])
+ json["integration"] = "unknown-future-source"
+ let data = try JSONSerialization.data(withJSONObject: json)
+ XCTAssertThrowsError(try JSONDecoder().decode(CatalogGame.self, from: data))
+ }
+
+ func testDownloadingSteamGameIsListedWithoutLaunchOrReview() throws {
+ var steam = SteamCatalogGame(appID: 10, name: "Downloading")
+ steam.installations = [.init(libraryURL: URL(fileURLWithPath: "/tmp/steam"),
+ contentURL: URL(fileURLWithPath: "/tmp/steam/steamapps/common/G"),
+ availability: .unavailable, isDownloading: true)]
+ let shown = CatalogGamePresentation(game: CatalogGame(steam: steam), sourceEnabled: true)
+ XCTAssertTrue(shown.isListedNormally)
+ XCTAssertTrue(shown.isDownloading)
+ XCTAssertFalse(shown.requiresReview)
+ XCTAssertNil(shown.launchTarget)
+ let disabled = CatalogGamePresentation(game: CatalogGame(steam: steam), sourceEnabled: false)
+ XCTAssertFalse(disabled.isListedNormally)
+ XCTAssertFalse(disabled.isDownloading)
+ steam.isHidden = true
+ let hidden = CatalogGamePresentation(game: CatalogGame(steam: steam), sourceEnabled: true)
+ XCTAssertFalse(hidden.isListedNormally)
+ XCTAssertFalse(hidden.isDownloading)
+ }
+
+ func testInstallationWithoutDownloadingKeyDecodesAsNotDownloading() throws {
+ let installation = SteamCatalogInstallation(libraryURL: URL(fileURLWithPath: "/tmp/steam"),
+ contentURL: URL(fileURLWithPath: "/tmp/steam/steamapps/common/G"),
+ availability: .available, isDownloading: true)
+ var object = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(installation)) as? [String: Any])
+ XCTAssertEqual(object["isDownloading"] as? Bool, true)
+ object["isDownloading"] = nil
+ let old = try JSONDecoder().decode(SteamCatalogInstallation.self, from: JSONSerialization.data(withJSONObject: object))
+ XCTAssertFalse(old.isDownloading)
+ XCTAssertEqual(old.availability, .available)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/CatalogPersonalizationTests.swift b/Tests/NXLibraryCoreTests/CatalogPersonalizationTests.swift
new file mode 100644
index 00000000..adb07e41
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/CatalogPersonalizationTests.swift
@@ -0,0 +1,30 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class CatalogPersonalizationTests: XCTestCase {
+ func testPersonalKeySurvivesRenameOfATitleWithoutTitleID() throws {
+ var payload = CatalogTestSupport.completeLegacyGame()
+ payload.titleId = nil; payload.bundleId = nil; payload.name = "Old name"
+ var entry = CatalogGame(nxnative: payload)
+ payload.name = "New name"
+ try entry.updateNXNative(payload)
+ let context = CatalogPersonalizations(document: CatalogDocument(games: [entry]))
+ XCTAssertEqual(context.nxnativeKey(for: payload), "Old name")
+ XCTAssertEqual(CatalogPersonalizations.empty.nxnativeKey(for: payload), "New name", "Unpersisted previews retain their existing fallback")
+ }
+
+ func testSameTextKeyInDifferentIntegrationsCannotOverwritePersonalMetadata() throws {
+ let root = try SteamTestFixture.temporary(in: self).root
+ var payload = CatalogTestSupport.completeLegacyGame()
+ payload.titleId = nil; payload.bundleId = "steam-10"
+ let nx = CatalogGame(nxnative: payload).personalizationReference
+ let steam = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "Steam")).personalizationReference
+ let nxStore = MetadataPicks(directory: nx.supportRoot(in: root))
+ let steamStore = MetadataPicks(directory: steam.supportRoot(in: root))
+ nxStore.set("Switch text", titleID: nx.key, field: .description)
+ steamStore.set("Steam text", titleID: steam.key, field: .description)
+ XCTAssertEqual(MetadataPicks(directory: root).value(titleID: "steam-10", field: .description), "Switch text")
+ XCTAssertEqual(MetadataPicks(directory: steam.supportRoot(in: root)).value(titleID: "steam-10", field: .description), "Steam text")
+ XCTAssertNotEqual(nx.supportRoot(in: root), steam.supportRoot(in: root))
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/CatalogRecoveryTests.swift b/Tests/NXLibraryCoreTests/CatalogRecoveryTests.swift
new file mode 100644
index 00000000..55cddadc
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/CatalogRecoveryTests.swift
@@ -0,0 +1,233 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class CatalogRecoveryTests: XCTestCase {
+ private func prepared() throws -> (URL, CatalogStore, CatalogDocument, Data) {
+ let root = try SteamTestFixture.temporary(in: self).root
+ let legacy = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root)
+ let store = CatalogStore(directory: root)
+ return (root, store, try store.loadOrMigrate(), legacy)
+ }
+ private func file(_ root: URL, _ name: String) -> URL { root.appendingPathComponent(name) }
+
+ func testExplicitRestorePreservesDamagedMainBackupAndOriginalLegacy() throws {
+ let (root, store, original, legacy) = try prepared()
+ let backup = try Data(contentsOf: file(root, "catalog.json.bak"))
+ let damaged = Data("incomplete document".utf8)
+ try damaged.write(to: file(root, "catalog.json"))
+ let candidate = try XCTUnwrap(store.recoveryCandidate())
+ XCTAssertEqual(candidate.gameCount, 1)
+ XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json")), damaged, "Offering recovery alone must not repair anything")
+ let restored = try store.restoreBackup(candidate)
+ XCTAssertEqual(restored.games, original.games)
+ XCTAssertNotEqual(restored.revision, original.revision)
+ XCTAssertEqual(try store.loadOrMigrate(), restored)
+ let archives = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
+ .filter { $0.lastPathComponent.hasPrefix("catalog.json.recovered-") }
+ XCTAssertEqual(archives.count, 1)
+ XCTAssertEqual(try Data(contentsOf: archives[0]), damaged)
+ XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json.bak")), backup)
+ XCTAssertEqual(try Data(contentsOf: file(root, "library.json")), legacy)
+ }
+
+ func testMissingMainCanBeRestoredExplicitlyAndHealthyMainHasNoOffer() throws {
+ let (root, store, original, _) = try prepared()
+ XCTAssertNil(try store.recoveryCandidate())
+ try FileManager.default.removeItem(at: file(root, "catalog.json"))
+ let candidate = try XCTUnwrap(store.recoveryCandidate())
+ XCTAssertFalse(FileManager.default.fileExists(atPath: file(root, "catalog.json").path))
+ XCTAssertEqual(try store.restoreBackup(candidate).games, original.games)
+ XCTAssertNil(try store.recoveryCandidate())
+ }
+
+ func testStaleRecoveryOfferCannotReplaceChangedMainOrBackup() throws {
+ for changed in ["catalog.json", "catalog.json.bak"] {
+ let (root, store, _, _) = try prepared()
+ try Data("damaged".utf8).write(to: file(root, "catalog.json"))
+ let candidate = try XCTUnwrap(store.recoveryCandidate())
+ let later = Data("later edit".utf8)
+ try later.write(to: file(root, changed))
+ XCTAssertThrowsError(try store.restoreBackup(candidate)) { XCTAssertEqual($0 as? CatalogStoreError, .staleRevision) }
+ XCTAssertEqual(try Data(contentsOf: file(root, changed)), later)
+ }
+ }
+
+ func testChangedLegacyAndUnsafeBackupCannotBeRestored() throws {
+ let (root, store, _, legacy) = try prepared()
+ try Data("damaged".utf8).write(to: file(root, "catalog.json"))
+ let candidate = try XCTUnwrap(store.recoveryCandidate())
+ try (legacy + Data(" ".utf8)).write(to: file(root, "library.json"))
+ XCTAssertThrowsError(try store.restoreBackup(candidate))
+ XCTAssertThrowsError(try store.recoveryCandidate())
+ try FileManager.default.removeItem(at: file(root, "catalog.json.bak"))
+ try FileManager.default.createSymbolicLink(at: file(root, "catalog.json.bak"), withDestinationURL: file(root, "library.json"))
+ XCTAssertThrowsError(try store.recoveryCandidate())
+ XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json")), Data("damaged".utf8))
+ }
+
+ func testRecoveryPublicationFailureLeavesAllInputsAvailable() throws {
+ let (root, store, _, _) = try prepared()
+ let damaged = Data("damaged".utf8)
+ try damaged.write(to: file(root, "catalog.json"))
+ let backup = try Data(contentsOf: file(root, "catalog.json.bak"))
+ let candidate = try XCTUnwrap(store.recoveryCandidate())
+ let failing = CatalogStore(directory: root, publication: .init { _, _, _, _ in throw POSIXError(.ENOSPC) })
+ XCTAssertThrowsError(try failing.restoreBackup(candidate))
+ XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json")), damaged)
+ XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json.bak")), backup)
+ }
+
+ func testFreshDevCopiesTheMixedCatalogAndReadyDevIsNeverReimported() throws {
+ let home = try SteamTestFixture.temporary(in: self).root
+ let profile = AppDataProfile(home: home, isDevelopment: true)
+ _ = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: profile.stableSupportRoot)
+ let store = CatalogStore(directory: profile.stableSupportRoot)
+ var mixed = try store.loadOrMigrate()
+ mixed.games.append(.init(steam: SteamCatalogGame(appID: 10, name: "Steam game")))
+ mixed = try store.save(mixed, expectedRevision: mixed.revision)
+ let importer = DevelopmentProfileImporter()
+ XCTAssertTrue(try importer.prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in }))
+ XCTAssertEqual(try CatalogStore(directory: profile.supportRoot).loadOrMigrate(), mixed)
+ let sourceBytes = try Data(contentsOf: profile.stableSupportRoot.appendingPathComponent("catalog.json"))
+ try Data("later source damage".utf8).write(to: profile.stableSupportRoot.appendingPathComponent("catalog.json"))
+ XCTAssertFalse(try importer.prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in XCTFail() }))
+ XCTAssertEqual(try Data(contentsOf: profile.supportRoot.appendingPathComponent("catalog.json")), sourceBytes)
+ }
+
+ func testFreshDevRejectsUnsupportedOrMalformedCatalogBeforeActivation() throws {
+ for bytes in [Data("{\"schemaVersion\":99}".utf8), Data("{\"valid_json_wrong_document\":true}".utf8)] {
+ let profile = AppDataProfile(home: try SteamTestFixture.temporary(in: self).root, isDevelopment: true)
+ try FileManager.default.createDirectory(at: profile.stableSupportRoot, withIntermediateDirectories: true)
+ try bytes.write(to: profile.stableSupportRoot.appendingPathComponent("catalog.json"))
+ XCTAssertThrowsError(try DevelopmentProfileImporter().prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in XCTFail() }))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: profile.supportRoot.path))
+ }
+ }
+
+ func testKeepCurrentLibraryArchivesBothVersionsWithoutMergingLegacyChanges() throws {
+ let (root, store, original, _) = try prepared()
+ var mixed = original
+ mixed.games.append(.init(steam: SteamCatalogGame(appID: 10, name: "Arcane addition")))
+ mixed = try store.save(mixed, expectedRevision: mixed.revision)
+ let main = try Data(contentsOf: file(root, "catalog.json"))
+ let backup = try Data(contentsOf: file(root, "catalog.json.bak"))
+ let changed = try CatalogTestSupport.writeLegacy([], to: root)
+ let legacyBackup = Data("legacy backup bytes".utf8)
+ try legacyBackup.write(to: file(root, "library.json.bak"))
+ XCTAssertThrowsError(try store.loadOrMigrate()) { XCTAssertEqual($0 as? CatalogStoreError, .legacyChanged) }
+ let candidate = try XCTUnwrap(store.legacyConflictCandidate())
+ XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json")), main, "The offer does not modify either library")
+ let kept = try store.keepCurrentLibrary(candidate)
+ XCTAssertEqual(kept.games, mixed.games)
+ XCTAssertEqual(kept.sources, mixed.sources)
+ XCTAssertNotEqual(kept.revision, mixed.revision)
+ XCTAssertEqual(try store.loadOrMigrate(), kept)
+ let archive = try XCTUnwrap(conflictArchives(root).first)
+ for (name, bytes) in [("catalog.json", main), ("catalog.json.bak", backup), ("library.json", changed), ("library.json.bak", legacyBackup)] {
+ XCTAssertEqual(try Data(contentsOf: archive.appendingPathComponent(name)), bytes)
+ }
+ XCTAssertEqual(try Data(contentsOf: file(root, "library.json")), changed)
+ XCTAssertEqual(try Data(contentsOf: file(root, "library.json.bak")), legacyBackup)
+ XCTAssertNil(try store.legacyConflictCandidate())
+ XCTAssertNoThrow(try store.save(kept, expectedRevision: kept.revision))
+ XCTAssertThrowsError(try store.save(mixed, expectedRevision: mixed.revision))
+ }
+
+ func testStaleConflictCannotAcknowledgeLaterWritesToAnyInput() throws {
+ for name in ["catalog.json", "catalog.json.bak", "library.json", "library.json.bak"] {
+ let (root, store, _, _) = try prepared()
+ _ = try CatalogTestSupport.writeLegacy([], to: root)
+ let candidate = try XCTUnwrap(store.legacyConflictCandidate())
+ let later = Data("later write".utf8)
+ try later.write(to: file(root, name))
+ let before = try Data(contentsOf: file(root, "catalog.json"))
+ XCTAssertThrowsError(try store.keepCurrentLibrary(candidate)) { XCTAssertEqual($0 as? CatalogStoreError, .staleRevision) }
+ XCTAssertEqual(try Data(contentsOf: file(root, name)), later)
+ XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json")), before)
+ XCTAssertEqual(try conflictArchives(root).count, 0)
+ }
+ }
+
+ func testAcceptedLegacyBaselineAlsoAppliesToTheRestorePoint() throws {
+ let (root, store, original, _) = try prepared()
+ _ = try CatalogTestSupport.writeLegacy([], to: root)
+ let candidate = try XCTUnwrap(store.legacyConflictCandidate())
+ let kept = try store.keepCurrentLibrary(candidate)
+ try Data("damaged main".utf8).write(to: file(root, "catalog.json"))
+ let recovery = try XCTUnwrap(store.recoveryCandidate())
+ let restored = try store.restoreBackup(recovery)
+ XCTAssertEqual(restored.games, original.games)
+ XCTAssertEqual(restored.legacyOrigin, kept.legacyOrigin)
+ XCTAssertEqual(try store.loadOrMigrate(), restored)
+ }
+
+ func testArchiveAndPublicationFailuresKeepCurrentAndLegacyBytes() throws {
+ for failure in ["archive", "catalog.json", "archive sync"] {
+ let (root, store, _, _) = try prepared()
+ let changed = try CatalogTestSupport.writeLegacy([], to: root)
+ let main = try Data(contentsOf: file(root, "catalog.json"))
+ let candidate = try XCTUnwrap(store.legacyConflictCandidate())
+ let failing = CatalogStore(directory: root, publication: .init(syncDirectory: { _ in
+ if failure == "archive sync" { throw POSIXError(.ENOSPC) }
+ }) { stage, target, replace, validate in
+ if failure == "archive" || target == root.appendingPathComponent(failure) { throw POSIXError(.ENOSPC) }
+ try CatalogPublication.atomic.publish(stage, target, replace, validate)
+ })
+ XCTAssertThrowsError(try failing.keepCurrentLibrary(candidate))
+ XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json")), main)
+ XCTAssertEqual(try Data(contentsOf: file(root, "library.json")), changed)
+ // A retry rechecks the actual backup too, rather than reusing a stale offer.
+ XCTAssertNoThrow(try store.keepCurrentLibrary(XCTUnwrap(store.legacyConflictCandidate())))
+ }
+ }
+
+ func testLegacyEditAtPublicationCannotBeAcknowledgedByAnOlderOffer() throws {
+ let (root, store, _, _) = try prepared()
+ let changed = try CatalogTestSupport.writeLegacy([], to: root)
+ let candidate = try XCTUnwrap(store.legacyConflictCandidate())
+ let main = try Data(contentsOf: file(root, "catalog.json"))
+ let later = Data("an older app wrote again".utf8)
+ let racing = CatalogStore(directory: root, publication: .init { stage, target, replace, validate in
+ if target == root.appendingPathComponent("catalog.json") {
+ try later.write(to: root.appendingPathComponent("library.json"))
+ }
+ try CatalogPublication.atomic.publish(stage, target, replace, validate)
+ })
+ XCTAssertThrowsError(try racing.keepCurrentLibrary(candidate))
+ XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json")), main)
+ XCTAssertEqual(try Data(contentsOf: file(root, "library.json")), later)
+ let archive = try XCTUnwrap(conflictArchives(root).first)
+ XCTAssertEqual(try Data(contentsOf: archive.appendingPathComponent("library.json")), changed)
+ }
+
+ func testUnsafeLegacyInputNeverOffersAnAcknowledgement() throws {
+ for name in ["library.json", "library.json.bak"] {
+ let (root, store, _, _) = try prepared()
+ _ = try CatalogTestSupport.writeLegacy([], to: root)
+ try? FileManager.default.removeItem(at: file(root, name))
+ try FileManager.default.createSymbolicLink(at: file(root, name), withDestinationURL: file(root, "catalog.json"))
+ XCTAssertThrowsError(try store.legacyConflictCandidate())
+ }
+ }
+
+ func testMissingAndBackupOnlyLegacyBaselinesCanBeAcceptedExplicitly() throws {
+ for backupOnly in [false, true] {
+ let (root, store, original, _) = try prepared()
+ try FileManager.default.removeItem(at: file(root, "library.json"))
+ if backupOnly { try Data("legacy backup".utf8).write(to: file(root, "library.json.bak")) }
+ let candidate = try XCTUnwrap(store.legacyConflictCandidate())
+ let kept = try store.keepCurrentLibrary(candidate)
+ XCTAssertEqual(kept.legacyOrigin.kind, backupOnly ? .backup : .absent)
+ XCTAssertEqual(kept.games, original.games)
+ XCTAssertEqual(try store.loadOrMigrate(), kept)
+ _ = try CatalogTestSupport.writeLegacy([], to: root)
+ XCTAssertThrowsError(try store.loadOrMigrate())
+ XCTAssertNotNil(try store.legacyConflictCandidate())
+ }
+ }
+
+ private func conflictArchives(_ root: URL) throws -> [URL] {
+ try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
+ .filter { $0.lastPathComponent.hasPrefix("catalog-conflict-") }
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/CatalogRepositoryTests.swift b/Tests/NXLibraryCoreTests/CatalogRepositoryTests.swift
new file mode 100644
index 00000000..972bc48e
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/CatalogRepositoryTests.swift
@@ -0,0 +1,159 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class CatalogRepositoryTests: XCTestCase {
+ private func mixed() throws -> (SteamTestFixture, CatalogStore, CatalogDocument) {
+ let f = try SteamTestFixture.temporary(in: self)
+ _ = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: f.root)
+ let store = CatalogStore(directory: f.root)
+ var document = try store.loadOrMigrate()
+ var steam = SteamCatalogGame(appID: 10, name: "Fixture Switch game")
+ steam.isFavorite = true; steam.isHidden = true
+ document.games.append(.init(steam: steam))
+ return (f, store, try store.save(document, expectedRevision: document.revision))
+ }
+
+ func testNXNativeUpdateRetainsWholePayloadPersonalReferenceAndSteamRecord() throws {
+ let (_, store, original) = try mixed()
+ let repository = CatalogRepository(store: store)
+ let id = original.games[0].id
+ let updated = try repository.updateNXNative(id: id) { $0.titleId = "0100000000000002"; $0.isFavorite = false }
+ var expected = try XCTUnwrap(original.games[0].nxnativeGame)
+ expected.titleId = "0100000000000002"; expected.isFavorite = false
+ XCTAssertEqual(updated.games[0].nxnativeGame, expected)
+ XCTAssertEqual(updated.games[0].personalizationReference, original.games[0].personalizationReference)
+ XCTAssertEqual(updated.games[1], original.games[1])
+ XCTAssertEqual(try repository.load(), updated)
+ }
+
+ func testScanUsesLatestFlagsAndDoesNotReplaceSteamOrLegacyBytes() throws {
+ let (fixture, store, original) = try mixed()
+ let bytes = try Data(contentsOf: fixture.root.appendingPathComponent("library.json"))
+ let repository = CatalogRepository(store: store)
+ var scanned = try XCTUnwrap(original.games[0].nxnativeGame)
+ scanned.name = "Renamed"; scanned.isFavorite = true; scanned.isHidden = true
+ _ = try repository.updateNXNative(id: scanned.id) { $0.isFavorite = false; $0.isHidden = false; $0.appIconOnMac = true }
+ let result = try repository.mergeNXNative(scanned: [scanned], observedFrom: original.nxnativeGames)
+ XCTAssertEqual(result.games[0].name, "Renamed")
+ XCTAssertFalse(result.games[0].isFavorite); XCTAssertFalse(result.games[0].isHidden)
+ XCTAssertEqual(result.nxnativeGames[0].appIconOnMac, true)
+ XCTAssertEqual(result.games[1], original.games[1])
+ XCTAssertEqual(try Data(contentsOf: fixture.root.appendingPathComponent("library.json")), bytes)
+ }
+
+ func testWrongIntegrationAndMissingIDRejectBeforeOperationEffects() throws {
+ let (_, store, original) = try mixed()
+ let repository = CatalogRepository(store: store)
+ var calls = 0
+ XCTAssertThrowsError(try repository.updateNXNative(id: original.games[1].id) { _ in calls += 1 })
+ XCTAssertThrowsError(try repository.updateNXNative(id: UUID()) { _ in calls += 1 })
+ XCTAssertEqual(calls, 0)
+ XCTAssertEqual(try repository.load(), original)
+ }
+
+ func testMutationDoesNotReplayEffectsWhenPublicationFails() throws {
+ let (fixture, store, original) = try mixed()
+ let failing = CatalogStore(directory: fixture.root, publication: .init { _, _, _, _ in throw POSIXError(.ENOSPC) })
+ let repository = CatalogRepository(store: failing)
+ var calls = 0
+ XCTAssertThrowsError(try repository.updateNXNative(id: original.games[0].id) { game in calls += 1; game.isFavorite = false })
+ XCTAssertEqual(calls, 1)
+ XCTAssertEqual(try store.loadOrMigrate(), original)
+ }
+
+ func testConcurrentChangeIsNotOverwrittenAndOperationIsNotReplayed() throws {
+ let (fixture, store, original) = try mixed()
+ let repository = CatalogRepository(store: store)
+ var calls = 0
+ XCTAssertThrowsError(try repository.updateNXNative(id: original.games[0].id) { game in
+ calls += 1
+ var other = try CatalogStore(directory: fixture.root).loadOrMigrate()
+ other.games[1].setHidden(false)
+ _ = try CatalogStore(directory: fixture.root).save(other, expectedRevision: other.revision)
+ game.isFavorite = false
+ }) { XCTAssertEqual($0 as? CatalogStoreError, .staleRevision) }
+ XCTAssertEqual(calls, 1)
+ let actual = try repository.load()
+ XCTAssertFalse(actual.games[1].isHidden)
+ XCTAssertTrue(actual.games[0].isFavorite)
+ }
+
+ func testSourceLessRecordsUseUUIDAndCannotMergeOnMissingTitleID() throws {
+ let (_, store, _) = try mixed()
+ let repository = CatalogRepository(store: store)
+ var a = CatalogTestSupport.completeLegacyGame(id: UUID()), b = CatalogTestSupport.completeLegacyGame(id: UUID())
+ a.titleId = nil; b.titleId = nil
+ a.name = "A"; b.name = "B"
+ let added = try repository.mergeNXNative(scanned: [a, b])
+ XCTAssertEqual(added.nxnativeGames.count, 3)
+ a.name = "A changed"
+ let refreshed = try repository.mergeNXNative(scanned: [a])
+ XCTAssertEqual(refreshed.nxnativeGames.count, 3)
+ XCTAssertEqual(refreshed.nxnativeGames.first { $0.id == a.id }?.name, "A changed")
+ XCTAssertEqual(refreshed.nxnativeGames.first { $0.id == b.id }?.name, "B")
+ }
+
+ func testBatchPatchPreservesOtherIntegrationAndRejectsDuplicateIDs() throws {
+ let (_, store, original) = try mixed()
+ let repository = CatalogRepository(store: store)
+ let updated = try repository.updateNXNativeGames { $0[0].status = .needsRebuild }
+ XCTAssertEqual(updated.games[1], original.games[1])
+ XCTAssertEqual(updated.nxnativeGames[0].status, .needsRebuild)
+ XCTAssertThrowsError(try repository.updateNXNativeGames { $0.append($0[0]) })
+ XCTAssertEqual(try repository.load(), updated)
+ }
+ func testBuildOutcomeUpdatesBuildOwnedFieldsAndKeepsCurrentPersonalAndSourceChoices() throws {
+ let (_, store, original) = try mixed()
+ let repository = CatalogRepository(store: store)
+ var outcome = try XCTUnwrap(original.games[0].nxnativeGame)
+ outcome.url = URL(fileURLWithPath: "/tmp/Finished.app")
+ outcome.status = .built; outcome.sizeBytes = 9000; outcome.versionString = "3.0"
+ outcome.appIconPending = true; outcome.pendingInstall = nil
+ outcome.portingFailure = nil; outcome.portingFailureReason = nil
+ _ = try repository.updateNXNative(id: outcome.id) {
+ $0.isFavorite = false; $0.isHidden = false; $0.appIconOnMac = true
+ $0.settings.language = "fr"; $0.name = "User choice"
+ }
+ let updated = try repository.recordNXNativeBuild(outcome)
+ let game = try XCTUnwrap(updated.games[0].nxnativeGame)
+ XCTAssertFalse(game.isFavorite); XCTAssertFalse(game.isHidden)
+ XCTAssertEqual(game.settings.language, "fr"); XCTAssertEqual(game.name, "User choice")
+ XCTAssertEqual(game.appIconOnMac, true)
+ XCTAssertEqual(game.url.path, "/tmp/Finished.app"); XCTAssertEqual(game.sizeBytes, 9000)
+ XCTAssertEqual(game.status, .built); XCTAssertEqual(game.versionString, "3.0")
+ XCTAssertNil(game.pendingInstall); XCTAssertNil(game.portingFailureReason)
+ XCTAssertEqual(game.sources, original.nxnativeGames[0].sources)
+ XCTAssertEqual(updated.games[1], original.games[1])
+ }
+
+ func testOldScanCannotResetAnInProgressBuild() throws {
+ let (_, store, original) = try mixed()
+ let repository = CatalogRepository(store: store)
+ let id = original.games[0].id
+ _ = try repository.updateNXNative(id: id) { $0.status = .building }
+ let refreshed = try repository.mergeNXNative(scanned: original.nxnativeGames, observedFrom: original.nxnativeGames)
+ XCTAssertEqual(refreshed.nxnativeGames[0].status, .building)
+ }
+
+ func testOldScanCannotRevertACompletedBuildOrRunItsReconcileCallbackForThatGame() throws {
+ let (_, store, original) = try mixed()
+ let repository = CatalogRepository(store: store)
+ var outcome = original.nxnativeGames[0]
+ outcome.modificationDate = Date(timeIntervalSince1970: 1000)
+ outcome.versionString = "3.0"; outcome.sizeBytes = 9000
+ outcome.pendingInstall = nil; outcome.status = .built
+ outcome.lastBuild = BuildRecord(startedAt: Date(timeIntervalSince1970: 900), endedAt: Date(timeIntervalSince1970: 1000), exitCode: 0)
+ _ = try repository.recordNXNativeBuild(outcome)
+ var accepted = Set()
+ let refreshed = try repository.mergeNXNative(scanned: original.nxnativeGames, observedFrom: original.nxnativeGames) { games, ids in
+ accepted = ids
+ for index in games.indices where ids.contains(games[index].id) { games[index].sizeBytes = 1234 }
+ }
+ XCTAssertFalse(accepted.contains(outcome.id))
+ XCTAssertEqual(refreshed.nxnativeGames[0].versionString, "3.0")
+ XCTAssertEqual(refreshed.nxnativeGames[0].sizeBytes, 9000)
+ XCTAssertEqual(refreshed.nxnativeGames[0].modificationDate, Date(timeIntervalSince1970: 1000))
+ XCTAssertEqual(refreshed.nxnativeGames[0].lastBuild, outcome.lastBuild)
+ }
+
+}
diff --git a/Tests/NXLibraryCoreTests/CatalogSourcesModelTests.swift b/Tests/NXLibraryCoreTests/CatalogSourcesModelTests.swift
new file mode 100644
index 00000000..39404cbc
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/CatalogSourcesModelTests.swift
@@ -0,0 +1,277 @@
+import XCTest
+import Combine
+@testable import NXLibraryCore
+
+@MainActor
+final class CatalogSourcesModelTests: XCTestCase {
+ private static let rescanSpacing: TimeInterval = 0.2
+
+ func testDiscoveryUsesTheSavedSteamRootEvenWhenDisabled() throws {
+ let (fixture, repository, _) = try prepared()
+ let custom = fixture.root.appendingPathComponent("Custom Steam")
+ let configuration = try repository.configureSource(.steam, enabled: false, root: custom).source(.steam)!
+ let model = CatalogSourcesModel(repository: repository, initialConfiguration: configuration) { _ in }
+ XCTAssertFalse(model.configuration.isEnabled)
+ XCTAssertEqual(model.discoveryRoot, custom)
+ }
+
+ func testDiscoveryWithoutASavedRootUsesTheDefault() throws {
+ let (_, repository, initial) = try prepared()
+ let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial) { _ in }
+ XCTAssertEqual(model.discoveryRoot, CatalogSourcesModel.defaultSteamRoot)
+ }
+
+ private func prepared() throws -> (SteamTestFixture, CatalogRepository, CatalogSourceConfiguration) {
+ let f = try SteamTestFixture.temporary(in: self)
+ _ = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: f.root)
+ let repository = CatalogRepository(store: CatalogStore(directory: f.root))
+ return (f, repository, try repository.load().source(.steam)!)
+ }
+ private func snapshot(_ root: URL, id: UInt32 = 10, partial: Bool = false) -> SteamLibrarySnapshot {
+ let content = root.appendingPathComponent("steamapps/common/Game")
+ let app = content.appendingPathComponent("Game.app")
+ let native = NativeMacApplication(url: app, executableURL: app.appendingPathComponent("Contents/MacOS/game"),
+ bundleIdentifier: "test.steam", name: "Steam game", architectures: [.arm64],
+ isDeclaredGame: true, fileObservations: [])
+ return .init(libraries: [.init(root: root, isReadable: true, isComplete: !partial)],
+ games: [.init(appID: id, name: "Steam game", installationURL: content, libraryURL: root,
+ reportedSizeBytes: 1, buildID: nil, nativeApps: [native], state: .nativeReady)],
+ issues: partial ? [.init(url: root, appID: nil, reason: .invalidManifest)] : [])
+ }
+ func testDisabledInitializationDoesNotScanAndEnableCommitsDiscovery() async throws {
+ let (f, repository, initial) = try prepared()
+ let done = expectation(description: "discovered")
+ let calls = SourceCallCounter()
+ let scan = snapshot(f.root)
+ let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, scanner: { _, _ in calls.increment(); return scan }) { doc in
+ if doc.games.contains(where: { $0.steamGame != nil }) { done.fulfill() }
+ }
+ XCTAssertEqual(calls.value, 0); XCTAssertEqual(model.status, .disabled)
+ model.configure(enabled: true, root: f.root)
+ await fulfillment(of: [done], timeout: 3)
+ XCTAssertEqual(calls.value, 1); XCTAssertEqual(model.status, .ready)
+ XCTAssertEqual(model.observedGameCount, 1)
+ XCTAssertEqual(try repository.load().source(.steam)?.isEnabled, true)
+ }
+ func testDisableCancelsAndIgnoredWorkerCancellationStillCannotCommit() async throws {
+ let (f, repository, initial) = try prepared()
+ let entered = expectation(description: "worker")
+ let gate = DispatchSemaphore(value: 0)
+ let scan = snapshot(f.root)
+ let rejected = expectation(description: "must not discover"); rejected.isInverted = true
+ let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, scanner: { _, _ in
+ entered.fulfill(); _ = gate.wait(timeout: .now() + 2); return scan
+ }) { if $0.games.contains(where: { $0.steamGame != nil }) { rejected.fulfill() } }
+ model.configure(enabled: true, root: f.root)
+ await fulfillment(of: [entered], timeout: 3)
+ model.configure(enabled: false, root: nil)
+ gate.signal()
+ await fulfillment(of: [rejected], timeout: 0.15)
+ XCTAssertEqual(model.status, .disabled)
+ XCTAssertEqual(try repository.load().games.count, 1)
+ }
+ func testCancelKeepsOptInAndExistingRecords() async throws {
+ let (f, repository, initial) = try prepared()
+ let entered = expectation(description: "worker")
+ let gate = DispatchSemaphore(value: 0)
+ let scan = snapshot(f.root)
+ let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, scanner: { _, _ in
+ entered.fulfill(); _ = gate.wait(timeout: .now() + 2); return scan
+ }, onCommit: { _ in })
+ model.configure(enabled: true, root: f.root)
+ await fulfillment(of: [entered], timeout: 3)
+ model.cancel(); gate.signal()
+ XCTAssertEqual(model.status, .cancelled)
+ XCTAssertEqual(try repository.load().source(.steam)?.isEnabled, true)
+ XCTAssertEqual(try repository.load().games.count, 1)
+ }
+ func testNewRootWinsWhenOldWorkerReturnsLater() async throws {
+ let (f, repository, initial) = try prepared()
+ let entered = expectation(description: "old worker"), done = expectation(description: "new worker")
+ let gate = DispatchSemaphore(value: 0), other = f.root.appendingPathComponent("Other")
+ let oldCommitted = expectation(description: "old source must not commit"); oldCommitted.isInverted = true
+ let old = snapshot(f.root, id: 10), new = snapshot(other, id: 20)
+ let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, scanner: { root, _ in
+ if root.path == f.root.path { entered.fulfill(); _ = gate.wait(timeout: .now() + 2); return old }
+ return new
+ }) {
+ if $0.games.contains(where: { $0.steamGame?.appID == 20 }) { done.fulfill() }
+ if $0.games.contains(where: { $0.steamGame?.appID == 10 }) { oldCommitted.fulfill() }
+ }
+ model.configure(enabled: true, root: f.root)
+ await fulfillment(of: [entered], timeout: 3)
+ model.configure(enabled: true, root: other)
+ await fulfillment(of: [done], timeout: 3)
+ gate.signal()
+ await fulfillment(of: [oldCommitted], timeout: 0.15)
+ XCTAssertEqual(try repository.load().games.compactMap { $0.steamGame?.appID }, [20])
+ XCTAssertEqual(model.configuration.rootURL?.path, other.path)
+ XCTAssertEqual(model.status, .ready)
+ }
+ func testFavoriteChangeWhileWorkerRunsIsRetained() async throws {
+ let (f, repository, initial) = try prepared()
+ let entered = expectation(description: "worker"), done = expectation(description: "committed")
+ let gate = DispatchSemaphore(value: 0), scan = snapshot(f.root)
+ let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, scanner: { _, _ in
+ entered.fulfill(); _ = gate.wait(timeout: .now() + 2); return scan
+ }) { if $0.games.contains(where: { $0.steamGame != nil }) { done.fulfill() } }
+ model.configure(enabled: true, root: f.root)
+ await fulfillment(of: [entered], timeout: 3)
+ let id = try repository.load().games[0].id
+ _ = try repository.setFavorite(false, for: id)
+ gate.signal()
+ await fulfillment(of: [done], timeout: 3)
+ XCTAssertFalse(try repository.load().games[0].isFavorite)
+ XCTAssertEqual(model.status, .ready)
+ }
+ func testFailedSourceCanRefreshIntoPartialSnapshotWithoutDroppingKnownData() async throws {
+ let (f, repository, initial) = try prepared()
+ let failed = expectation(description: "failure"), partial = expectation(description: "partial")
+ let counter = SourceCallCounter(), scan = snapshot(f.root, partial: true)
+ let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, scanner: { _, _ in
+ if counter.increment() == 1 { throw POSIXError(.EACCES) }; return scan
+ }, onCommit: { _ in })
+ let observation = model.$status.sink { status in
+ if status == .failed { failed.fulfill() }; if status == .partial { partial.fulfill() }
+ }
+ model.configure(enabled: true, root: f.root)
+ await fulfillment(of: [failed], timeout: 3)
+ XCTAssertEqual(try repository.load().games.count, 1)
+ model.refresh()
+ await fulfillment(of: [partial], timeout: 3)
+ XCTAssertEqual(try repository.load().games.count, 2)
+ XCTAssertEqual(model.issues.count, 1)
+ withExtendedLifetime(observation) {}
+ }
+
+ func testDownloadingGameIsNotCountedForReview() async throws {
+ let (f, repository, initial) = try prepared()
+ let done = expectation(description: "committed")
+ let content = f.root.appendingPathComponent("steamapps/common/Game")
+ let scan = SteamLibrarySnapshot(libraries: [.init(root: f.root, isReadable: true, isComplete: true)],
+ games: [.init(appID: 10, name: "Steam game", installationURL: content, libraryURL: f.root,
+ reportedSizeBytes: 0, buildID: nil, nativeApps: [], state: .downloading)],
+ issues: [])
+ let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, scanner: { _, _ in scan }) { doc in
+ if doc.games.contains(where: { $0.steamGame != nil }) { done.fulfill() }
+ }
+ model.configure(enabled: true, root: f.root)
+ await fulfillment(of: [done], timeout: 3)
+ XCTAssertEqual(model.observedGameCount, 1)
+ XCTAssertEqual(model.reviewCount, 0)
+ }
+
+ // MARK: - Rescans when Steam rewrites a manifest
+
+ func testEveryScanRechecksWatchedFoldersEvenWithTheSameLibraryPaths() async throws {
+ let (f, repository, initial) = try prepared()
+ let root = try f.library()
+ let library = f.root.appendingPathComponent("Later")
+ let scan = SteamLibrarySnapshot(libraries: [.init(root: root, isReadable: true, isComplete: true),
+ .init(root: library, isReadable: true, isComplete: true)],
+ games: [], issues: [])
+ let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial,
+ scanner: { _, _ in scan }, onCommit: { _ in })
+ let watcher = SteamManifestWatcher()
+ defer { watcher.stop() }
+ let observation = model.$libraryRoots.sink { watcher.watch($0, root: root) }
+ defer { withExtendedLifetime(observation) {} }
+ model.configure(enabled: true, root: root)
+ await settled(model)
+ XCTAssertEqual(model.status, .ready)
+ _ = try f.library("Later")
+ model.refresh()
+ await settled(model)
+ XCTAssertEqual(model.status, .ready)
+ let changed = expectation(description: "Watcher retries an unchanged path after the scan")
+ watcher.onChange = { changed.fulfill() }
+ try f.manifest(in: library)
+ await fulfillment(of: [changed], timeout: 6)
+ }
+
+ private func settled(_ model: CatalogSourcesModel) async {
+ for _ in 0..<200 where model.status == .scanning || model.status == .idle { try? await Task.sleep(nanoseconds: 10_000_000) }
+ }
+ private func watching(delay: TimeInterval = 0, extraLibraries: [URL] = []) async throws -> (CatalogSourcesModel, SourceCallCounter, URL) {
+ let (f, repository, initial) = try prepared()
+ let calls = SourceCallCounter()
+ let base = snapshot(f.root)
+ let scan: SteamLibrarySnapshot
+ if !extraLibraries.isEmpty {
+ scan = .init(libraries: ([f.root] + extraLibraries).map { .init(root: $0, isReadable: true, isComplete: true) },
+ games: base.games, issues: [])
+ } else { scan = base }
+ let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial,
+ scanner: { _, _ in calls.increment(); if delay > 0 { Thread.sleep(forTimeInterval: delay) }; return scan },
+ rescanQuiet: 0.05, rescanSpacing: Self.rescanSpacing) { _ in }
+ model.configure(enabled: true, root: f.root)
+ await settled(model)
+ return (model, calls, f.root)
+ }
+
+ func testLibraryRootsFollowTheCommittedScan() async throws {
+ let external = URL(fileURLWithPath: "/tmp/catalog-external-library")
+ let (model, _, root) = try await watching(extraLibraries: [external])
+ XCTAssertEqual(model.libraryRoots, [root, external])
+ }
+
+ func testBurstOfChangesRescansOnce() async throws {
+ let (model, calls, _) = try await watching()
+ XCTAssertEqual(calls.value, 1)
+ for _ in 0..<5 { model.steamFilesChanged(); try await Task.sleep(nanoseconds: 10_000_000) }
+ try await Task.sleep(nanoseconds: 600_000_000)
+ await settled(model)
+ XCTAssertEqual(calls.value, 2)
+ }
+
+ func testChangeDuringScanRescansOnceAfterIt() async throws {
+ let (model, calls, _) = try await watching(delay: 0.3)
+ XCTAssertEqual(calls.value, 1)
+ model.refresh()
+ try await Task.sleep(nanoseconds: 30_000_000)
+ XCTAssertEqual(model.status, .scanning)
+ for _ in 0..<3 { model.steamFilesChanged() }
+ try await Task.sleep(nanoseconds: 1_200_000_000)
+ await settled(model)
+ XCTAssertEqual(calls.value, 3)
+ }
+
+ func testRescansAreSpacedApart() async throws {
+ let (model, calls, _) = try await watching()
+ let rescans = expectation(description: "both rescans start")
+ rescans.expectedFulfillmentCount = 2
+ var starts: [Date] = []
+ let observation = model.$status.sink { status in
+ guard status == .scanning else { return }
+ starts.append(Date())
+ if starts.count == 1 { model.steamFilesChanged() }
+ rescans.fulfill()
+ }
+ defer { observation.cancel() }
+ model.steamFilesChanged()
+ await fulfillment(of: [rescans], timeout: 5)
+ await settled(model)
+ XCTAssertEqual(calls.value, 3)
+ guard starts.count == 2 else { return XCTFail("Expected two rescan starts") }
+ // Status publishes just after the model records the start time.
+ XCTAssertGreaterThanOrEqual(starts[1].timeIntervalSince(starts[0]), Self.rescanSpacing - 0.01)
+ }
+
+ func testDisablingDropsAPendingRescanAndClearsLibraries() async throws {
+ let (model, calls, root) = try await watching()
+ XCTAssertEqual(model.libraryRoots, [root])
+ model.steamFilesChanged()
+ model.configure(enabled: false, root: root)
+ XCTAssertEqual(model.libraryRoots, [])
+ try await Task.sleep(nanoseconds: 500_000_000)
+ XCTAssertEqual(calls.value, 1)
+ }
+}
+
+
+private final class SourceCallCounter: @unchecked Sendable {
+ private let lock = NSLock()
+ private var stored = 0
+ @discardableResult func increment() -> Int { lock.lock(); defer { lock.unlock() }; stored += 1; return stored }
+ var value: Int { lock.lock(); defer { lock.unlock() }; return stored }
+}
diff --git a/Tests/NXLibraryCoreTests/CatalogSourcesRepositoryTests.swift b/Tests/NXLibraryCoreTests/CatalogSourcesRepositoryTests.swift
new file mode 100644
index 00000000..f94244bc
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/CatalogSourcesRepositoryTests.swift
@@ -0,0 +1,100 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class CatalogSourcesRepositoryTests: XCTestCase {
+ private func prepared() throws -> (SteamTestFixture, CatalogRepository) {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ _ = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: fixture.root)
+ return (fixture, CatalogRepository(store: CatalogStore(directory: fixture.root)))
+ }
+ private func snapshot(_ root: URL) -> SteamLibrarySnapshot {
+ let content = root.appendingPathComponent("steamapps/common/Fixture")
+ let app = content.appendingPathComponent("Fixture.app")
+ let native = NativeMacApplication(url: app, executableURL: app.appendingPathComponent("Contents/MacOS/game"),
+ bundleIdentifier: "test.steam", name: "Fixture Steam", architectures: [.arm64],
+ isDeclaredGame: true, fileObservations: [])
+ return .init(libraries: [.init(root: root, isReadable: true, isComplete: true)],
+ games: [.init(appID: 10, name: "Fixture Steam", installationURL: content, libraryURL: root,
+ reportedSizeBytes: 200, buildID: "1", nativeApps: [native], state: .nativeReady)], issues: [])
+ }
+
+ func testOldSchemaOneWithoutSourceGenerationDecodesDeterministically() throws {
+ let (_, repository) = try prepared()
+ let document = try repository.load()
+ var json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(document)) as? [String: Any])
+ var sources = try XCTUnwrap(json["sources"] as? [[String: Any]])
+ for index in sources.indices { sources[index].removeValue(forKey: "generation") }
+ json["sources"] = sources
+ let old = try JSONSerialization.data(withJSONObject: json)
+ let a = try CatalogStore.decode(old), b = try CatalogStore.decode(old)
+ XCTAssertEqual(a, b)
+ XCTAssertEqual(try CatalogStore.decode(JSONEncoder().encode(a)), a)
+ XCTAssertEqual(a.games, document.games)
+ }
+
+ func testPersonalEditsDuringAScanArePreservedWhenSnapshotCommits() throws {
+ let (fixture, repository) = try prepared()
+ let enabled = try repository.configureSource(.steam, enabled: true, root: fixture.root)
+ let source = try XCTUnwrap(enabled.source(.steam))
+ _ = try repository.setFavorite(false, for: enabled.games[0].id)
+ let merged = try repository.applySteam(snapshot(fixture.root), expectedSource: source)
+ XCTAssertFalse(merged.games[0].isFavorite)
+ XCTAssertEqual(merged.games.count, 2)
+ XCTAssertEqual(merged.games[1].steamGame?.appID, 10)
+ let id = merged.games[1].id
+ _ = try repository.setFavorite(true, for: id)
+ _ = try repository.setHidden(true, for: id)
+ let again = try repository.applySteam(snapshot(fixture.root), expectedSource: source)
+ XCTAssertEqual(again.games[1].id, id)
+ XCTAssertTrue(again.games[1].isFavorite); XCTAssertTrue(again.games[1].isHidden)
+ }
+
+ func testDisableReenableAtSameRootInvalidatesOlderSourceGeneration() throws {
+ let (fixture, repository) = try prepared()
+ let initial = try repository.configureSource(.steam, enabled: true, root: fixture.root)
+ let old = try XCTUnwrap(initial.source(.steam))
+ _ = try repository.configureSource(.steam, enabled: false, root: fixture.root)
+ let enabled = try repository.configureSource(.steam, enabled: true, root: fixture.root)
+ XCTAssertNotEqual(enabled.source(.steam)?.generation, old.generation)
+ XCTAssertThrowsError(try repository.applySteam(snapshot(fixture.root), expectedSource: old))
+ XCTAssertEqual(try repository.load(), enabled)
+ }
+
+ func testChangingRootOrDisablingNeverAppliesOldSnapshot() throws {
+ let (fixture, repository) = try prepared()
+ let initial = try repository.configureSource(.steam, enabled: true, root: fixture.root)
+ let source = try XCTUnwrap(initial.source(.steam))
+ _ = try repository.configureSource(.steam, enabled: true, root: fixture.root.appendingPathComponent("Other"))
+ XCTAssertThrowsError(try repository.applySteam(snapshot(fixture.root), expectedSource: source))
+ _ = try repository.configureSource(.steam, enabled: false, root: fixture.root)
+ XCTAssertThrowsError(try repository.applySteam(snapshot(fixture.root), expectedSource: source))
+ XCTAssertEqual(try repository.load().games.count, 1)
+ }
+ func testExplicitNXAdoptionEnablesItsExperienceWhilePassiveScanStaysDisabled() throws {
+ let root = try SteamTestFixture.temporary(in: self).root
+ let repository = CatalogRepository(store: CatalogStore(directory: root))
+ let game = CatalogTestSupport.completeLegacyGame()
+ XCTAssertFalse(try repository.load().source(.nxnative)!.isEnabled)
+ XCTAssertThrowsError(try repository.mergeNXNative(scanned: [game]))
+ let adopted = try repository.mergeNXNative(scanned: [game], enableSource: true)
+ XCTAssertTrue(adopted.source(.nxnative)!.isEnabled)
+ XCTAssertEqual(adopted.games.first?.id, game.id)
+ XCTAssertFalse(adopted.source(.steam)!.isEnabled)
+ }
+
+ func testRepeatedFavoriteCommandUsesLatestPersistedValue() throws {
+ let (fixture, repository) = try prepared()
+ let enabled = try repository.configureSource(.steam, enabled: true, root: fixture.root)
+ let scanned = try repository.applySteam(snapshot(fixture.root), expectedSource: enabled.source(.steam)!)
+ let captured = try XCTUnwrap(scanned.games.first { $0.integration == .steam })
+ XCTAssertFalse(captured.isFavorite)
+ // The keyboard can retain one Details view/ID across both commands.
+ let favorite = try repository.toggleFavorite(for: captured.id)
+ XCTAssertTrue(favorite.games.first { $0.id == captured.id }!.isFavorite)
+ let unfavorite = try repository.toggleFavorite(for: captured.id)
+ XCTAssertFalse(unfavorite.games.first { $0.id == captured.id }!.isFavorite)
+ XCTAssertEqual(try repository.load(), unfavorite)
+ XCTAssertEqual(unfavorite.source(.steam), scanned.source(.steam))
+ }
+
+}
diff --git a/Tests/NXLibraryCoreTests/CatalogStoreTests.swift b/Tests/NXLibraryCoreTests/CatalogStoreTests.swift
new file mode 100644
index 00000000..25b34912
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/CatalogStoreTests.swift
@@ -0,0 +1,237 @@
+import XCTest
+import Darwin
+@testable import NXLibraryCore
+
+final class CatalogStoreTests: XCTestCase {
+ private func fixture() throws -> SteamTestFixture { try .temporary(in: self) }
+ private func url(_ root: URL, _ name: String) -> URL { root.appendingPathComponent(name) }
+ private func assertNoCatalog(_ root: URL, file: StaticString = #filePath, line: UInt = #line) {
+ XCTAssertFalse(FileManager.default.fileExists(atPath: url(root, "catalog.json").path), file: file, line: line)
+ }
+
+ func testMigrationPreservesAllLegacyFieldsKeysAndBytesAndIsNotRepeated() throws {
+ let root = try fixture().root
+ let original = CatalogTestSupport.completeLegacyGame()
+ let bytes = try CatalogTestSupport.writeLegacy([original], to: root)
+ let store = CatalogStore(directory: root)
+ let migrated = try store.loadOrMigrate()
+ XCTAssertEqual(migrated.games.map(\.nxnativeGame), [original])
+ XCTAssertEqual(migrated.games[0].personalizationKey, "0100000000000001")
+ XCTAssertEqual(migrated.source(.nxnative)?.isEnabled, true)
+ XCTAssertEqual(migrated.source(.steam)?.isEnabled, false)
+ var draft = migrated
+ draft.games[0].setFavorite(false)
+ let saved = try store.save(draft, expectedRevision: migrated.revision)
+ XCTAssertNotEqual(saved.revision, migrated.revision)
+ XCTAssertEqual(try store.loadOrMigrate(), saved)
+ XCTAssertFalse(saved.games[0].isFavorite)
+ XCTAssertEqual(try Data(contentsOf: url(root, "library.json")), bytes)
+ XCTAssertEqual(try CatalogStore.decode(Data(contentsOf: url(root, "catalog.json.bak"))), migrated)
+ }
+
+ func testNewProfileDoesNotEnableAnIntegration() throws {
+ let root = try fixture().root
+ let result = try CatalogStore(directory: root).loadOrMigrate()
+ XCTAssertTrue(result.games.isEmpty)
+ XCTAssertEqual(Set(result.sources.map(\.integration)), [.steam, .nxnative])
+ XCTAssertTrue(result.sources.allSatisfy { !$0.isEnabled })
+ XCTAssertFalse(FileManager.default.fileExists(atPath: url(root, "library.json").path))
+ XCTAssertEqual(try CatalogStore.decode(Data(contentsOf: url(root, "catalog.json.bak"))), result)
+ }
+
+ func testOnlyAbsentLegacyMainAllowsItsValidBackup() throws {
+ let root = try fixture().root
+ let original = CatalogTestSupport.completeLegacyGame()
+ let bytes = try CatalogTestSupport.writeLegacy([original], to: root)
+ try FileManager.default.moveItem(at: url(root, "library.json"), to: url(root, "library.json.bak"))
+ let store = CatalogStore(directory: root)
+ let result = try store.loadOrMigrate()
+ XCTAssertEqual(result.games.first?.nxnativeGame, original)
+ XCTAssertEqual(try Data(contentsOf: url(root, "library.json.bak")), bytes)
+ try bytes.write(to: url(root, "library.json"))
+ XCTAssertThrowsError(try store.loadOrMigrate()) { XCTAssertEqual($0 as? CatalogStoreError, .legacyChanged) }
+ }
+
+ func testCorruptLegacyMainDoesNotSilentlyUseGoodBackup() throws {
+ let root = try fixture().root
+ let bytes = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root)
+ try bytes.write(to: url(root, "library.json.bak"))
+ let corrupt = Data("not-json".utf8)
+ try corrupt.write(to: url(root, "library.json"))
+ XCTAssertThrowsError(try CatalogStore(directory: root).loadOrMigrate())
+ assertNoCatalog(root)
+ XCTAssertEqual(try Data(contentsOf: url(root, "library.json")), corrupt)
+ XCTAssertEqual(try Data(contentsOf: url(root, "library.json.bak")), bytes)
+ }
+
+ func testUnknownLegacySchemaAndDuplicateUUIDsAreRejected() throws {
+ for (schema, count) in [(99, 1), (1, 2)] {
+ let root = try fixture().root
+ let bytes = try CatalogTestSupport.writeLegacy(Array(repeating: CatalogTestSupport.completeLegacyGame(), count: count), to: root, schemaVersion: schema)
+ XCTAssertThrowsError(try CatalogStore(directory: root).loadOrMigrate())
+ assertNoCatalog(root)
+ XCTAssertEqual(try Data(contentsOf: url(root, "library.json")), bytes)
+ }
+ }
+
+ func testLegacySymlinkAndFIFOAreRejectedWithoutFollowingOrBlocking() throws {
+ for special in ["symlink", "fifo"] {
+ let root = try fixture().root
+ let target = url(root, "library.json")
+ if special == "symlink" {
+ let external = url(root, "external.json")
+ try Data("untouched".utf8).write(to: external)
+ try FileManager.default.createSymbolicLink(at: target, withDestinationURL: external)
+ } else { XCTAssertEqual(mkfifo(target.path, 0o600), 0) }
+ XCTAssertThrowsError(try CatalogStore(directory: root).loadOrMigrate())
+ assertNoCatalog(root)
+ }
+ }
+
+ func testOversizedLegacyFileIsRejected() throws {
+ let root = try fixture().root
+ try Data(repeating: 0x20, count: 16 * 1024 * 1024 + 1).write(to: url(root, "library.json"))
+ XCTAssertThrowsError(try CatalogStore(directory: root).loadOrMigrate())
+ assertNoCatalog(root)
+ }
+
+ func testChangedLegacyMainBlocksReadsAndWritesButBackupRotationDoesNot() throws {
+ let root = try fixture().root
+ let bytes = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root)
+ let store = CatalogStore(directory: root)
+ let first = try store.loadOrMigrate()
+ try Data("an obsolete backup".utf8).write(to: url(root, "library.json.bak"))
+ XCTAssertEqual(try store.loadOrMigrate(), first)
+ try (bytes + Data(" ".utf8)).write(to: url(root, "library.json"))
+ XCTAssertThrowsError(try store.loadOrMigrate()) { XCTAssertEqual($0 as? CatalogStoreError, .legacyChanged) }
+ XCTAssertThrowsError(try store.save(first, expectedRevision: first.revision))
+ XCTAssertEqual(try CatalogStore.decode(Data(contentsOf: url(root, "catalog.json"))), first)
+ }
+
+ func testNewLegacyFileAfterEmptyMigrationCannotBeIgnored() throws {
+ let root = try fixture().root
+ let store = CatalogStore(directory: root)
+ _ = try store.loadOrMigrate()
+ _ = try CatalogTestSupport.writeLegacy([], to: root)
+ XCTAssertThrowsError(try store.loadOrMigrate()) { XCTAssertEqual($0 as? CatalogStoreError, .legacyChanged) }
+ }
+
+ func testTwoStoresCannotSaveTheSameRevisionTwice() throws {
+ let root = try fixture().root
+ _ = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root)
+ let a = CatalogStore(directory: root), b = CatalogStore(directory: root)
+ let old = try a.loadOrMigrate()
+ var draft = old
+ draft.games[0].setHidden(false)
+ let committed = try a.save(draft, expectedRevision: old.revision)
+ XCTAssertThrowsError(try b.save(old, expectedRevision: old.revision)) { XCTAssertEqual($0 as? CatalogStoreError, .staleRevision) }
+ XCTAssertEqual(try b.loadOrMigrate(), committed)
+ }
+
+ func testAWriterHoldingTheLockRefusesAnotherWriterInsteadOfWaiting() throws {
+ let root = try fixture().root
+ let store = CatalogStore(directory: root)
+ let initial = try store.loadOrMigrate()
+ let competing = CatalogStore(directory: root, publication: .init { staged, target, replace, validate in
+ XCTAssertThrowsError(try store.loadOrMigrate()) { XCTAssertEqual($0 as? CatalogStoreError, .busy) }
+ try CatalogPublication.atomic.publish(staged, target, replace, validate)
+ })
+ _ = try competing.save(initial, expectedRevision: initial.revision)
+ }
+
+ func testPublicationFailurePreservesReadableMainBackupAndLegacyBytes() throws {
+ let root = try fixture().root
+ let bytes = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root)
+ let initial = try CatalogStore(directory: root).loadOrMigrate()
+ let failing = CatalogStore(directory: root, publication: .init { _, _, _, _ in throw POSIXError(.ENOSPC) })
+ XCTAssertThrowsError(try failing.save(initial, expectedRevision: initial.revision))
+ XCTAssertEqual(try CatalogStore(directory: root).loadOrMigrate(), initial)
+ XCTAssertEqual(try CatalogStore.decode(Data(contentsOf: url(root, "catalog.json.bak"))), initial)
+ XCTAssertEqual(try Data(contentsOf: url(root, "library.json")), bytes)
+ XCTAssertFalse(try FileManager.default.contentsOfDirectory(atPath: root.path).contains { $0.hasPrefix(".catalog-stage-") })
+ }
+
+ func testLegacyChangeDuringPublicationRejectsThePreparedCandidate() throws {
+ let root = try fixture().root
+ let legacy = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root)
+ let initial = try CatalogStore(directory: root).loadOrMigrate()
+ let changing = CatalogStore(directory: root, publication: .init { staged, target, replace, validate in
+ try (legacy + Data(" ".utf8)).write(to: self.url(root, "library.json"))
+ try CatalogPublication.atomic.publish(staged, target, replace, validate)
+ })
+ XCTAssertThrowsError(try changing.save(initial, expectedRevision: initial.revision))
+ XCTAssertEqual(try CatalogStore.decode(Data(contentsOf: url(root, "catalog.json"))), initial)
+ }
+
+ func testDamagedOrUnsupportedCatalogNeverActivatesEmptyOrOverwritesGoodBackup() throws {
+ for replacement in [Data("broken".utf8), Data("{\"schemaVersion\":99}".utf8)] {
+ let root = try fixture().root
+ let store = CatalogStore(directory: root)
+ let initial = try store.loadOrMigrate()
+ let backup = try Data(contentsOf: url(root, "catalog.json.bak"))
+ try replacement.write(to: url(root, "catalog.json"))
+ XCTAssertThrowsError(try store.loadOrMigrate()) { XCTAssertEqual($0 as? CatalogStoreError, .invalidCatalog(backupAvailable: true)) }
+ XCTAssertThrowsError(try store.save(initial, expectedRevision: initial.revision))
+ XCTAssertEqual(try Data(contentsOf: url(root, "catalog.json.bak")), backup)
+ XCTAssertEqual(try Data(contentsOf: url(root, "catalog.json")), replacement)
+ }
+ }
+
+ func testMissingCatalogWithValidBackupRequiresRecoveryRatherThanNewMigration() throws {
+ let root = try fixture().root
+ let store = CatalogStore(directory: root)
+ _ = try store.loadOrMigrate()
+ try FileManager.default.removeItem(at: url(root, "catalog.json"))
+ XCTAssertThrowsError(try store.loadOrMigrate()) { XCTAssertEqual($0 as? CatalogStoreError, .invalidCatalog(backupAvailable: true)) }
+ assertNoCatalog(root)
+ }
+
+ func testInvalidDraftCannotReplaceTheValidCatalog() throws {
+ let root = try fixture().root
+ _ = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root)
+ let store = CatalogStore(directory: root)
+ let initial = try store.loadOrMigrate()
+ var duplicate = initial
+ duplicate.games.append(initial.games[0])
+ XCTAssertThrowsError(try store.save(duplicate, expectedRevision: initial.revision))
+ var invalidSource = initial
+ invalidSource.sources = [.init(integration: .steam, isEnabled: true)]
+ XCTAssertThrowsError(try store.save(invalidSource, expectedRevision: initial.revision))
+ XCTAssertEqual(try store.loadOrMigrate(), initial)
+ }
+
+ func testFractionalDatesSurviveNewCatalogWrites() throws {
+ let root = try fixture().root
+ let store = CatalogStore(directory: root)
+ var draft = try store.loadOrMigrate()
+ var legacy = CatalogTestSupport.completeLegacyGame()
+ legacy.modificationDate = Date(timeIntervalSinceReferenceDate: 12345.678901)
+ draft.games = [.init(nxnative: legacy)]
+ let saved = try store.save(draft, expectedRevision: draft.revision)
+ XCTAssertEqual(try store.loadOrMigrate().games[0].nxnativeGame?.modificationDate, legacy.modificationDate)
+ XCTAssertEqual(saved.games[0].nxnativeGame, legacy)
+ }
+ func testFinalDirectorySyncFailureReportsUncertainCommitAndAllowsExplicitReload() throws {
+ let root = try fixture().root
+ _ = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root)
+ let store = CatalogStore(directory: root)
+ let initial = try store.loadOrMigrate()
+ var draft = initial
+ draft.games[0].setFavorite(false)
+ let failing = CatalogStore(directory: root, publication: .init(syncDirectory: { _ in throw POSIXError(.EIO) },
+ publish: CatalogPublication.atomic.publish))
+ XCTAssertThrowsError(try failing.save(draft, expectedRevision: initial.revision)) {
+ XCTAssertEqual($0 as? CatalogStoreError, .commitUncertain)
+ }
+ // Publication already happened; the caller must reload, not assume
+ // the old revision still owns the file or retry as an empty library.
+ let reloaded = try store.loadOrMigrate()
+ XCTAssertNotEqual(reloaded.revision, initial.revision)
+ XCTAssertFalse(reloaded.games[0].isFavorite)
+ XCTAssertEqual(try CatalogStore.decode(Data(contentsOf: url(root, "catalog.json.bak"))), initial)
+ XCTAssertThrowsError(try store.save(draft, expectedRevision: initial.revision)) {
+ XCTAssertEqual($0 as? CatalogStoreError, .staleRevision)
+ }
+ }
+
+}
diff --git a/Tests/NXLibraryCoreTests/CatalogTestSupport.swift b/Tests/NXLibraryCoreTests/CatalogTestSupport.swift
new file mode 100644
index 00000000..1e462876
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/CatalogTestSupport.swift
@@ -0,0 +1,41 @@
+import Foundation
+import XCTest
+@testable import NXLibraryCore
+
+enum CatalogTestSupport {
+ static func completeLegacyGame(id: UUID = UUID(uuidString: "11111111-1111-1111-1111-111111111111")!) -> PortedGame {
+ var game = PortedGame(id: id, name: "Fixture Switch game", url: URL(fileURLWithPath: "/tmp/catalog-fixture/Game.app"),
+ platform: .macApp, sizeBytes: 1234, modificationDate: Date(timeIntervalSince1970: 100),
+ bundleId: "org.nxnative.0100000000000001", titleId: "0100000000000001", versionString: "2.0")
+ game.status = .builtSourcesMissing
+ game.sources = [GameFileItem(url: URL(fileURLWithPath: "/tmp/catalog-fixture/base.nsp"), kind: .base,
+ titleId: "0100000000000001", sizeBytes: 456)]
+ game.workspacePath = "/tmp/catalog-fixture/workspace"
+ game.buildCachePath = "/tmp/catalog-fixture/workspace/cache"
+ game.settings.language = "it"
+ game.settings.metalHUD = true
+ game.toolchain = ToolchainInfo(engineCommit: "fixture123", metalVersion: "32023.922", xcodeVersion: "27.2", verified: true)
+ game.lastBuild = BuildRecord(startedAt: Date(timeIntervalSince1970: 10), endedAt: Date(timeIntervalSince1970: 20),
+ exitCode: 0, outputPath: game.url.path, toolchainVerified: true)
+ game.pendingInstall = PendingInstall(tempApp: URL(fileURLWithPath: "/tmp/catalog-fixture/held/Game.app"), finalApp: game.url,
+ record: game.lastBuild!, toolchain: game.toolchain)
+ game.portingFailure = .failed
+ game.portingFailureReason = PortingFailureReason(kind: .diskFull, detail: "Synthetic failure")
+ game.isFavorite = true
+ game.isHidden = true
+ game.usesPickedAppIcon = true
+ game.appIconOnMac = false
+ game.appIconPending = true
+ return game
+ }
+
+ static func writeLegacy(_ games: [PortedGame], to directory: URL, schemaVersion: Int = 1) throws -> Data {
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .iso8601
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ let data = try encoder.encode(LibraryFile(schemaVersion: schemaVersion, games: games))
+ try data.write(to: directory.appendingPathComponent("library.json"))
+ return data
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/CriticRatingTests.swift b/Tests/NXLibraryCoreTests/CriticRatingTests.swift
new file mode 100644
index 00000000..d9ee3ebc
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/CriticRatingTests.swift
@@ -0,0 +1,240 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class CriticRatingTests: XCTestCase {
+ private let query = CriticRatingQuery(name: "Fixture", platform: .mac, steamAppID: 42)
+
+ private func snak(_ value: Any) -> [String: Any] { ["datavalue": ["value": value]] }
+ private func item(_ id: String) -> [String: Any] { snak(["id": id]) }
+ private func claim(_ value: Any) -> [String: Any] { ["mainsnak": snak(value)] }
+ private func score(_ value: String = "78/100", issuer: String = "Q21039459",
+ method: String = "Q114712322", platform: String? = nil,
+ referenced: Bool = true) -> [String: Any] {
+ var quals: [String: Any] = ["P447": [item(issuer)], "P459": [item(method)]]
+ if let platform { quals["P400"] = [item(platform)] }
+ var value = claim(value)
+ value["id"] = "Q10$statement"
+ value["qualifiers"] = quals
+ if referenced { value["references"] = [["snaks": ["P248": [item(issuer)]]]] }
+ return value
+ }
+ private func payload(_ scores: [[String: Any]], steam: String = "42", second: Bool = false) throws -> Data {
+ let entity: [String: Any] = ["claims": ["P31": [claim(["id": "Q7889"])],
+ "P1733": [claim(steam)], "P444": scores]]
+ var entities = ["Q10": entity]
+ if second { entities["Q11"] = entity }
+ return try JSONSerialization.data(withJSONObject: ["entities": entities])
+ }
+ func testReferencedAverageAndProportionalStars() throws {
+ let rating = try XCTUnwrap(WikidataRatings.rating(in: payload([score()]), ids: ["Q10"], query: query))
+ XCTAssertEqual(rating.score, 78)
+ XCTAssertEqual(rating.source, .openCritic)
+ XCTAssertEqual(rating.starFills.count, 5)
+ XCTAssertEqual(rating.starFills.reduce(0, +), 3.9, accuracy: 0.0001)
+ XCTAssertEqual(rating.starFills[3], 0.9, accuracy: 0.0001)
+ XCTAssertEqual(rating.starFills[4], 0)
+ XCTAssertEqual(rating.statementID, "Q10$statement")
+ XCTAssertEqual(rating.sourceURL.absoluteString, "https://www.wikidata.org/wiki/Q10#Q10$statement")
+ }
+ func testRecommendationIndividualReviewsAndUnreferencedValuesAreNotCriticAverages() throws {
+ for entry in [score("78%"), score(method: "Q119576498"), score(issuer: "Q207708"),
+ score(referenced: false), score("101/100"), score("-1/100"), score("4/5")] {
+ XCTAssertNil(try WikidataRatings.rating(in: payload([entry]), ids: ["Q10"], query: query))
+ }
+ var multiple = score()
+ multiple["qualifiers"] = ["P447": [item("Q21039459"), item("Q150248")]]
+ XCTAssertNil(try WikidataRatings.rating(in: payload([multiple]), ids: ["Q10"], query: query))
+ var unknownPlatform = score()
+ unknownPlatform["qualifiers"] = ["P447": [item("Q21039459")], "P459": [item("Q114712322")],
+ "P400": [["snaktype": "somevalue"]]]
+ XCTAssertNil(try WikidataRatings.rating(in: payload([unknownPlatform]), ids: ["Q10"], query: query))
+ }
+ func testPlatformSpecificScoreWinsAndForeignPlatformsAreNeverBorrowed() throws {
+ let mac = score("81/100", issuer: "Q150248", method: "Q106515043", platform: "Q14116")
+ let windows = score("92/100", issuer: "Q150248", method: "Q106515043", platform: "Q1406")
+ XCTAssertEqual(try WikidataRatings.rating(in: payload([score(), mac, windows]), ids: ["Q10"], query: query)?.score, 81)
+ XCTAssertNil(try WikidataRatings.rating(in: payload([windows]), ids: ["Q10"], query: query))
+ XCTAssertEqual(try WikidataRatings.rating(in: payload([score(), windows]), ids: ["Q10"], query: query)?.score, 78)
+ }
+ func testConflictingIdentityAmbiguityAndMalformedResponsesDoNotBecomeRatings() throws {
+ XCTAssertNil(try WikidataRatings.rating(in: payload([score()], steam: "99"), ids: ["Q10"], query: query))
+ XCTAssertNil(try WikidataRatings.rating(in: payload([score()], second: true), ids: ["Q10", "Q11"], query: query))
+ XCTAssertThrowsError(try WikidataRatings.rating(in: Data("{\"error\":{\"code\":\"maxlag\"}}".utf8), ids: ["Q10"], query: query))
+ }
+
+ func testSwitch2FallbackUsesItsOwnPlatformWithoutBorrowingSwitchScores() throws {
+ let switch2 = CriticRatingQuery(name: "Fixture", platform: .switch2)
+ let data = try payload([score("81/100", platform: "Q122761124"),
+ score("92/100", platform: "Q19610114")])
+ XCTAssertEqual(try WikidataRatings.rating(in: data, ids: ["Q10"], query: switch2)?.score, 81)
+ XCTAssertNil(try WikidataRatings.rating(in: payload([score(platform: "Q19610114")]),
+ ids: ["Q10"], query: switch2))
+ }
+ func testSearchRequiresExactTitleOrAliasNeverAnEditionOrSequel() throws {
+ let data = Data("""
+ {"search":[{"id":"Q10","label":"Fixture"},{"id":"Q11","label":"Fixture II"},
+ {"id":"Q12","label":"Fixture Deluxe Edition"},{"id":"Q13","label":"Other","aliases":["Fixture"]}]}
+ """.utf8)
+ XCTAssertEqual(try WikidataRatings.ids(in: data, name: "Fixture"), ["Q10", "Q13"])
+ XCTAssertThrowsError(try WikidataRatings.ids(in: Data("{}".utf8), name: "Fixture"))
+ }
+
+ func testSearchRemovesStoreTrademarkSymbolsWithoutRemovingEditionWords() throws {
+ let url = try XCTUnwrap(WikidataRatings.searchURL(name: "Fixture™: Test® Deluxe Edition"))
+ let params = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems
+ XCTAssertEqual(params?.first { $0.name == "search" }?.value, "Fixture: Test Deluxe Edition")
+ }
+
+ func testSearchReadsTheRealAliasMatchField() throws {
+ let data = Data("""
+ {"search":[{"id":"Q10","label":"Official name","match":{"type":"alias","text":"Fixture"}},
+ {"id":"Q11","label":"Other","match":{"type":"description","text":"Fixture"}}]}
+ """.utf8)
+ XCTAssertEqual(try WikidataRatings.ids(in: data, name: "Fixture"), ["Q10"])
+ }
+
+ func testSteamIdentifierFindsARenamedGameWithoutGuessingItsTitle() async throws {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let body = try payload([score()])
+ let service = CriticRatingService(directory: dir, transport: { url in
+ let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
+ if items.contains(where: { $0.name == "srsearch" && $0.value == "haswbstatement:P1733=42" }) {
+ return Data("{\"query\":{\"search\":[{\"title\":\"Q10\",\"ns\":0}]}}".utf8)
+ }
+ if url.query?.contains("wbgetentities") == true { return body }
+ return Data("{\"search\":[]}".utf8)
+ })
+ let result = await service.load(CriticRatingQuery(name: "My renamed title", platform: .mac, steamAppID: 42))
+ XCTAssertEqual(result.rating?.score, 78)
+ }
+
+ func testOldMissingCacheIsRetriedAfterResolverFix() async throws {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let query = CriticRatingQuery(name: "Fixture™", platform: .switch)
+ let old = CriticRatingService(directory: dir, transport: { _ in Data("{\"search\":[]}".utf8) })
+ _ = await old.load(query)
+ let file = try XCTUnwrap(FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil).first)
+ var cache = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any])
+ cache.removeValue(forKey: "resolverVersion")
+ try JSONSerialization.data(withJSONObject: cache).write(to: file)
+ let body = try payload([score()])
+ let fixed = CriticRatingService(directory: dir, transport: { url in
+ url.query?.contains("wbgetentities") == true ? body : Data("{\"search\":[{\"id\":\"Q10\",\"label\":\"Fixture\"}]}".utf8)
+ })
+ let result = await fixed.load(query)
+ XCTAssertEqual(result.rating?.score, 78)
+ }
+
+ func testSteamIndexCandidatesMustStillCarryTheRequestedIdentifier() throws {
+ var root = try XCTUnwrap(JSONSerialization.jsonObject(with: payload([score()])) as? [String: Any])
+ var entities = try XCTUnwrap(root["entities"] as? [String: [String: Any]])
+ var entity = try XCTUnwrap(entities["Q10"])
+ var claims = try XCTUnwrap(entity["claims"] as? [String: Any])
+ claims.removeValue(forKey: "P1733")
+ entity["claims"] = claims; entities["Q10"] = entity; root["entities"] = entities
+ let body = try JSONSerialization.data(withJSONObject: root)
+ XCTAssertNil(try WikidataRatings.rating(in: body, ids: ["Q10"], query: query, requireSteamID: true))
+ XCTAssertNotNil(try WikidataRatings.rating(in: body, ids: ["Q10"], query: query))
+ let search = Data("{\"query\":{\"search\":[{\"title\":\"Q10\",\"ns\":0},{\"title\":\"Property:P1733\",\"ns\":120}]}}".utf8)
+ XCTAssertEqual(try WikidataRatings.steamIDs(in: search), ["Q10"])
+ }
+ func testCacheAndOfflineFallbackKeepTheOriginalValue() async throws {
+ let query = CriticRatingQuery(name: "Fixture", platform: .switch)
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let body = try payload([score()])
+ let service = CriticRatingService(directory: dir, transport: { url in
+ url.query?.contains("wbsearchentities") == true ? Data("{\"search\":[{\"id\":\"Q10\",\"label\":\"Fixture\"}]}".utf8) : body
+ })
+ let first = await service.load(query)
+ XCTAssertEqual(first.rating?.score, 78)
+ let offline = CriticRatingService(directory: dir, transport: { _ in throw URLError(.notConnectedToInternet) })
+ let cached = await offline.load(query)
+ XCTAssertEqual(cached.rating, first.rating)
+ let stale = await offline.load(query, now: Date().addingTimeInterval(8 * 86400))
+ XCTAssertEqual(stale.rating, first.rating)
+ XCTAssertTrue(stale.isStale)
+ let other = await offline.load(CriticRatingQuery(name: "Different", platform: .mac, steamAppID: 7))
+ XCTAssertNil(other.rating)
+ }
+ func testMissingAnswersAreCachedAndConcurrentReadersShareRequests() async throws {
+ let query = CriticRatingQuery(name: "Fixture", platform: .switch)
+ actor Calls { var value = 0; func bump() { value += 1 } }
+ let calls = Calls(), dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let service = CriticRatingService(directory: dir, transport: { _ in
+ await calls.bump(); try await Task.sleep(nanoseconds: 20_000_000)
+ return Data("{\"search\":[]}".utf8)
+ })
+ async let a = service.load(query)
+ async let b = service.load(query)
+ let results = await (a, b)
+ XCTAssertNil(results.0.rating); XCTAssertNil(results.1.rating)
+ _ = await service.load(query)
+ let count = await calls.value
+ XCTAssertEqual(count, 1)
+ }
+
+ func testCancellingLookupStopsTransportWithoutCachingAbsence() async throws {
+ let started = expectation(description: "network request started")
+ let stopped = expectation(description: "network request cancelled")
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let service = CriticRatingService(directory: dir, transport: { _ in
+ started.fulfill()
+ do { try await Task.sleep(nanoseconds: 10_000_000_000); return Data() }
+ catch { stopped.fulfill(); throw error }
+ })
+ let task = Task { await service.load(query) }
+ await fulfillment(of: [started], timeout: 2)
+ task.cancel()
+ await fulfillment(of: [stopped], timeout: 2)
+ let answer = await task.value
+ XCTAssertNil(answer.rating)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: dir.path))
+ }
+
+ func testAPIErrorBacksOffRatherThanPersistingAMissingScore() async throws {
+ actor Calls { var count = 0; func bump() { count += 1 } }
+ let calls = Calls(), dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let service = CriticRatingService(directory: dir, transport: { _ in
+ await calls.bump(); return Data("{\"error\":{\"code\":\"maxlag\"}}".utf8)
+ })
+ _ = await service.load(query)
+ _ = await service.load(query)
+ let count = await calls.count
+ XCTAssertEqual(count, 1)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: dir.path))
+ }
+
+ func testZeroIsARealScoreAndFormattingUsesTheRequestedRegion() throws {
+ let zero = try XCTUnwrap(WikidataRatings.rating(in: payload([score("0/100")]), ids: ["Q10"], query: query))
+ XCTAssertEqual(zero.starFills, [0, 0, 0, 0, 0])
+ let decimal = try XCTUnwrap(WikidataRatings.rating(in: payload([score("78.5/100")]), ids: ["Q10"], query: query))
+ XCTAssertEqual(decimal.number(locale: Locale(identifier: "it_IT")), "78,5/100")
+ }
+
+ func testDifferentGamesRequestThePublicAPIInSeries() async throws {
+ actor Activity {
+ var active = 0, maximum = 0
+ func start() { active += 1; maximum = max(maximum, active) }
+ func stop() { active -= 1 }
+ }
+ let activity = Activity(), dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let service = CriticRatingService(directory: dir, transport: { _ in
+ await activity.start()
+ try await Task.sleep(nanoseconds: 20_000_000)
+ await activity.stop()
+ return Data("{\"search\":[]}".utf8)
+ })
+ async let a = service.load(CriticRatingQuery(name: "Fixture", platform: .switch))
+ async let b = service.load(CriticRatingQuery(name: "Other", platform: .switch))
+ _ = await (a, b)
+ let maximum = await activity.maximum
+ XCTAssertEqual(maximum, 1)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/DatabaseMetadataTests.swift b/Tests/NXLibraryCoreTests/DatabaseMetadataTests.swift
new file mode 100644
index 00000000..a5640c7b
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/DatabaseMetadataTests.swift
@@ -0,0 +1,170 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class DatabaseMetadataTests: XCTestCase {
+ private let query = CriticRatingQuery(name: "Fixture™", platform: .switch2)
+ private let page = URL(string: "https://gamesdb.launchbox-app.com/games/details/10-fixture")!
+
+ private func launchBoxPage(platform: String = "Nintendo Switch 2", name: String = "Fixture", id: Int = 10) throws -> String {
+ var graph: [Any] = []
+ func add(_ value: Any) -> Int { graph.append(value); return graph.count - 1 }
+ let platformName = add(platform), platformObject = add(["name": platformName])
+ let genre = add("Adventure"), genreObject = add(["name": genre]), genres = add([genreObject])
+ let developer = add("Studio"), developerObject = add(["name": developer]), developers = add([developerObject])
+ let title = add(name), key = add(id), overview = add("A description."), date = add("2026-11-05")
+ _ = add(["gameKey": key, "name": title, "platform": platformObject, "overview": overview,
+ "gameGenres": genres, "gameDevelopers": developers, "gamePublishers": developers, "releaseDate": date])
+ let json = String(decoding: try JSONSerialization.data(withJSONObject: graph), as: UTF8.self)
+ return ""
+ }
+ private func card(_ id: Int, title: String = "Fixture", platform: String = "Nintendo Switch 2") -> String {
+ "\(title)
\(platform)
"
+ }
+
+ func testLaunchBoxChecksTheFinalIdentityAndOffersFiveFields() throws {
+ let result = try DatabaseMetadataParser.launchBox(in: launchBoxPage(), query: query, page: page)
+ let preview = try XCTUnwrap(result.preview)
+ XCTAssertEqual(preview.option(for: .description)?.value, "A description.")
+ XCTAssertEqual(preview.option(for: .genres)?.value, "Adventure")
+ XCTAssertEqual(preview.option(for: .developer)?.value, "Studio")
+ XCTAssertEqual(preview.option(for: .publisher)?.value, "Studio")
+ XCTAssertEqual(preview.option(for: .releaseDate)?.value, "2026-11-05")
+ XCTAssertEqual(preview.option(for: .description)?.source, "LaunchBox · Nintendo Switch 2")
+ XCTAssertEqual(try DatabaseMetadataParser.launchBox(in: launchBoxPage(id: 99), query: query, page: page).issue, .unavailable)
+ XCTAssertEqual(try DatabaseMetadataParser.launchBox(in: launchBoxPage(name: "Fixture II"), query: query, page: page).issue, .notFound)
+ }
+
+ func testMatchingKeepsEditionsAndPrefersMacButLabelsPCWithoutBorrowingItsDate() throws {
+ let mac = CriticRatingQuery(name: "Fixture", platform: .mac)
+ let html = card(1, platform: "Windows") + card(2, platform: "Apple Mac OS") + card(3, title: "Fixture Deluxe Edition", platform: "Apple Mac OS")
+ XCTAssertEqual(DatabaseMetadataParser.launchBoxCandidates(in: html, query: mac).map(\.url.lastPathComponent), ["2-fixture"])
+ let result = try DatabaseMetadataParser.launchBox(in: launchBoxPage(platform: "Windows"), query: mac, page: page)
+ XCTAssertEqual(result.preview?.option(for: .description)?.source, "LaunchBox · Windows")
+ XCTAssertNil(result.preview?.option(for: .releaseDate))
+ let foreign = try DatabaseMetadataParser.launchBox(in: launchBoxPage(platform: "Nintendo Switch"), query: query, page: page)
+ XCTAssertEqual(foreign.issue, .notFound)
+ }
+
+ func testTheGamesDBChecksTitlePlatformAndDateInsteadOfAnyParagraph() throws {
+ let html = """
+ Fixture
Platform: PC
+ Developer(s): Studio
Publishers(s): Publisher
+ ReleaseDate: 2026-11-05
Genre(s): Adventure | Puzzle
+ A & B description.
+ """
+ let mac = CriticRatingQuery(name: "Fixture", platform: .mac)
+ let url = URL(string: "https://thegamesdb.net/game.php?id=10")!
+ let result = DatabaseMetadataParser.theGamesDB(in: html, query: mac, page: url)
+ XCTAssertEqual(result.preview?.option(for: .description)?.value, "A & B description.")
+ XCTAssertEqual(result.preview?.option(for: .developer)?.value, "Studio")
+ XCTAssertEqual(result.preview?.option(for: .genres)?.value, "Adventure, Puzzle")
+ XCTAssertNil(result.preview?.option(for: .releaseDate))
+ XCTAssertEqual(DatabaseMetadataParser.theGamesDB(in: html, query: query, page: url).issue, .notFound)
+ }
+
+ func testOneFetchPerPageThenNoRequestsAcrossFieldsOrFreshReopenAndStaleWorksOffline() async throws {
+ actor Calls { var urls: [URL] = []; func add(_ url: URL) { urls.append(url) } }
+ let calls = Calls(), search = card(10), detail = try launchBoxPage()
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = DatabaseMetadataService(database: .launchBox, directory: root, transport: { request in
+ await calls.add(request.url!)
+ let html = request.url!.path.contains("/results/") ? search : detail
+ return (Data(html.utf8), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
+ })
+ let first = await service.load(query)
+ XCTAssertNotNil(first.preview)
+ for field in MetadataField.allCases { _ = first.preview?.option(for: field) }
+ let next = await service.load(query)
+ XCTAssertEqual(next.preview, first.preview)
+ let urls = await calls.urls
+ XCTAssertEqual(urls.count, 2)
+ let offline = DatabaseMetadataService(database: .launchBox, directory: root, transport: { _ in throw URLError(.notConnectedToInternet) })
+ let stale = await offline.load(query, now: Date().addingTimeInterval(8 * 86400))
+ XCTAssertEqual(stale.preview, first.preview)
+ XCTAssertTrue(stale.isStale)
+ }
+
+ func testAmbiguousSearchNeverDownloadsAnArbitraryGamePage() async {
+ let search = card(10) + card(11)
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = DatabaseMetadataService(database: .launchBox, directory: root, transport: { request in
+ XCTAssertTrue(request.url!.path.contains("/results/"))
+ return (Data(search.utf8), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
+ })
+ let result = await service.load(query)
+ XCTAssertEqual(result.issue, .ambiguous)
+ XCTAssertNil(result.preview)
+ }
+
+ func testConcurrentReadersShareTheLookup() async throws {
+ actor Calls { var count = 0; func add() { count += 1 } }
+ let calls = Calls(), search = card(10), detail = try launchBoxPage()
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = DatabaseMetadataService(database: .launchBox, directory: root, transport: { request in
+ await calls.add()
+ try await Task.sleep(nanoseconds: 10_000_000)
+ return (Data((request.url!.path.contains("/results/") ? search : detail).utf8),
+ HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
+ })
+ async let first = service.load(query)
+ async let second = service.load(query)
+ let results = await (first, second)
+ XCTAssertEqual(results.0.preview, results.1.preview)
+ let count = await calls.count
+ XCTAssertEqual(count, 2)
+ }
+
+ func testCancellationStopsTheRequestAndDoesNotCacheAnAbsence() async throws {
+ let started = expectation(description: "request starts"), stopped = expectation(description: "request cancels")
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = DatabaseMetadataService(database: .launchBox, directory: root, transport: { _ in
+ started.fulfill()
+ do { try await Task.sleep(nanoseconds: 10_000_000_000); throw URLError(.timedOut) }
+ catch { stopped.fulfill(); throw error }
+ })
+ let query = query
+ let task = Task { await service.load(query) }
+ await fulfillment(of: [started], timeout: 2)
+ task.cancel()
+ await fulfillment(of: [stopped], timeout: 2)
+ let cancelled = await task.value
+ XCTAssertEqual(cancelled.issue, .cancelled)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: root.path))
+ }
+
+ func testOversizedOrRedirectedResponsesNeverBecomeMetadataOrNegativeCache() async {
+ for redirected in [false, true] {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = DatabaseMetadataService(database: .launchBox, directory: root, transport: { request in
+ let url = redirected ? URL(string: "https://other.example/unexpected")! : request.url!
+ return (redirected ? Data() : Data(repeating: 65, count: 2_097_153),
+ HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil)!)
+ })
+ let result = await service.load(query)
+ XCTAssertEqual(result.issue, .unavailable)
+ XCTAssertNil(result.preview)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: root.path))
+ }
+ }
+
+ func testFailedRefreshCanRetryWithoutANegativeCacheBlockingIt() async throws {
+ actor Calls { var count = 0; func next() -> Int { count += 1; return count } }
+ let calls = Calls(), search = card(10), detail = try launchBoxPage()
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = DatabaseMetadataService(database: .launchBox, directory: root, transport: { request in
+ let attempt = await calls.next()
+ return (Data((request.url!.path.contains("/results/") ? search : detail).utf8),
+ HTTPURLResponse(url: request.url!, statusCode: attempt == 1 ? 503 : 200, httpVersion: nil, headerFields: nil)!)
+ })
+ let failed = await service.load(query)
+ XCTAssertEqual(failed.issue, .unavailable)
+ let retried = await service.load(query)
+ XCTAssertNotNil(retried.preview)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/DetailsFactsTests.swift b/Tests/NXLibraryCoreTests/DetailsFactsTests.swift
new file mode 100644
index 00000000..cfb82ecf
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/DetailsFactsTests.swift
@@ -0,0 +1,83 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class DetailsFactsTests: XCTestCase {
+ private let en = Locale(identifier: "en_US")
+
+ private func switchGame(version: String? = "1.2.0", size: Int64 = 4_000_000_000) -> PortedGame {
+ PortedGame(name: "Zelda", url: URL(fileURLWithPath: "/tmp/Applications/Zelda.app"), platform: .macApp,
+ sizeBytes: size, modificationDate: Date(timeIntervalSince1970: 0), versionString: version)
+ }
+
+ private func meta(developers: [String], publishers: [String]) -> NintendoStoreMetadata {
+ NintendoStoreMetadata(titleId: "0100", name: "X", description: "", developers: developers,
+ publishers: publishers, genres: [], releaseDate: nil,
+ storeURL: URL(string: "https://example.com")!, imageURL: nil,
+ headerImageURL: nil, nsuid: nil, fetchedAt: Date(timeIntervalSince1970: 0))
+ }
+
+ private func steamFacts(appID: UInt32 = 440, developers: [String] = ["Pearl Abyss"],
+ publishers: [String] = ["Pearl Abyss"]) -> SteamMetadata {
+ SteamMetadata(appID: appID, language: "english", description: "", genres: [], developers: developers,
+ publishers: publishers, releaseDate: nil, screenshots: [], fetchedAt: Date(timeIntervalSince1970: 0))
+ }
+
+ private func steamGame(availability: CatalogInstallationAvailability = .available, size: Int64? = 140_000_000_000,
+ downloading: Bool = false) -> CatalogGame {
+ var game = SteamCatalogGame(appID: 440, name: "Crimson Desert")
+ let root = URL(fileURLWithPath: "/tmp/steam")
+ game.installations = [SteamCatalogInstallation(libraryURL: root, contentURL: root, availability: availability,
+ reportedSizeBytes: size, buildID: "123",
+ isDownloading: downloading)]
+ return CatalogGame(steam: game)
+ }
+
+ func testSwitchShowsEveryRowInOrder() {
+ let rows = DetailsFacts.switchGame(switchGame(), metadata: meta(developers: ["Nintendo EPD"], publishers: ["Nintendo"]),
+ folderName: "Applications", locale: en)
+ XCTAssertEqual(rows.map(\.kind), [.developer, .publisher, .version, .size, .location])
+ XCTAssertEqual(rows.map(\.value), ["Nintendo EPD", "Nintendo", "1.2.0", "4 GB", "Applications"])
+ }
+
+ func testSwitchHidesMissingValues() {
+ let rows = DetailsFacts.switchGame(switchGame(version: nil, size: 0), metadata: nil, folderName: nil, locale: en)
+ XCTAssertEqual(rows, [])
+ }
+
+ func testBlankNamesAndVersionAreHidden() {
+ let rows = DetailsFacts.switchGame(switchGame(version: " "), metadata: meta(developers: [" "], publishers: ["", "Sega"]),
+ folderName: nil, locale: en)
+ XCTAssertEqual(rows.map(\.kind), [.publisher, .size])
+ XCTAssertEqual(rows.first?.value, "Sega")
+ }
+
+ func testSteamInstalledShowsSizeAndVolumeNeverVersion() {
+ let rows = DetailsFacts.steamGame(steamGame(), metadata: steamFacts(), volumeName: "Macintosh HD", locale: en)
+ XCTAssertEqual(rows.map(\.kind), [.developer, .publisher, .size, .location])
+ XCTAssertEqual(rows.first { $0.kind == .size }?.value, "140 GB")
+ XCTAssertEqual(rows.first { $0.kind == .location }?.value, "Steam · Macintosh HD")
+ }
+
+ func testSteamWithoutVolumeNameSaysSteam() {
+ let rows = DetailsFacts.steamGame(steamGame(), metadata: steamFacts(), volumeName: nil, locale: en)
+ XCTAssertEqual(rows.first { $0.kind == .location }?.value, "Steam")
+ }
+
+ func testSteamDownloadingShowsOnlyCredits() {
+ let rows = DetailsFacts.steamGame(steamGame(availability: .unavailable, downloading: true), metadata: steamFacts(),
+ volumeName: "Macintosh HD", locale: en)
+ XCTAssertEqual(rows.map(\.kind), [.developer, .publisher])
+ }
+
+ func testSteamOverridesWinAndForeignFactsAreIgnored() {
+ let rows = DetailsFacts.steamGame(steamGame(size: nil), metadata: steamFacts(appID: 999, developers: ["Other"]),
+ overrides: [.developer: "Mine"], volumeName: nil, locale: en)
+ XCTAssertEqual(rows.map(\.kind), [.developer, .location])
+ XCTAssertEqual(rows.first?.value, "Mine")
+ }
+
+ func testRowsCarryTheirSymbols() {
+ XCTAssertEqual(DetailsFact.Kind.allCases.map { DetailsFact(kind: $0, value: "x").symbol },
+ ["hammer", "building.2", "number", "internaldrive", "folder"])
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/DetailsFocusTests.swift b/Tests/NXLibraryCoreTests/DetailsFocusTests.swift
index b1dd483c..ef45016f 100644
--- a/Tests/NXLibraryCoreTests/DetailsFocusTests.swift
+++ b/Tests/NXLibraryCoreTests/DetailsFocusTests.swift
@@ -66,6 +66,22 @@ final class DetailsFocusTests: XCTestCase {
XCTAssertEqual(focus.action, 0)
}
+ /// The Details links: three at most, one row. Down and Up leave the band; Right stops at the end.
+ func testThreeLinksFormOneRow() {
+ let links = DetailsFocus.Bands(screenshots: 2, actions: 3, more: 1)
+ var focus = DetailsFocus()
+ focus.zone = DetailsFocus.actionsZone
+ for _ in 0..<2 { XCTAssertTrue(focus.right(in: links)) }
+ XCTAssertEqual(focus.action, 2)
+ XCTAssertFalse(focus.right(in: links))
+ XCTAssertEqual(focus.action, 2)
+ XCTAssertTrue(focus.down(in: links))
+ XCTAssertEqual(focus.zone, DetailsFocus.moreZone)
+ XCTAssertTrue(focus.up(in: links))
+ XCTAssertEqual(focus.zone, DetailsFocus.actionsZone)
+ XCTAssertEqual(focus.action, 2)
+ }
+
func testActionGridLeavesBandFromLastRow() {
var focus = DetailsFocus()
focus.zone = DetailsFocus.actionsZone
diff --git a/Tests/NXLibraryCoreTests/DetailsReviewFixTests.swift b/Tests/NXLibraryCoreTests/DetailsReviewFixTests.swift
new file mode 100644
index 00000000..b8634e2b
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/DetailsReviewFixTests.swift
@@ -0,0 +1,24 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class DetailsReviewFixTests: XCTestCase {
+ /// Play on a game not built yet builds it when its sources are there; the page has no Build button any more.
+ func testPrimaryStepBuildsAnUnbuiltGameWithSources() {
+ XCTAssertEqual(GamePrimaryStep.decide(unavailable: false, playable: true, sourcesAvailable: false), .play)
+ XCTAssertEqual(GamePrimaryStep.decide(unavailable: false, playable: false, sourcesAvailable: true), .build)
+ XCTAssertEqual(GamePrimaryStep.decide(unavailable: false, playable: false, sourcesAvailable: false), .refuse)
+ XCTAssertEqual(GamePrimaryStep.decide(unavailable: true, playable: true, sourcesAvailable: true), .refuse)
+ }
+
+ /// A folder or volume name is read once per URL, not on every render (a sleeping disk would block each time).
+ @MainActor
+ func testDisplayNameCacheResolvesEachURLOnce() {
+ var calls: [String] = []
+ let cache = DisplayNameCache { url in calls.append(url.path); return url.path == "/a" ? "A" : nil }
+ XCTAssertEqual(cache.name(for: URL(fileURLWithPath: "/a")), "A")
+ XCTAssertEqual(cache.name(for: URL(fileURLWithPath: "/a")), "A")
+ XCTAssertNil(cache.name(for: URL(fileURLWithPath: "/b")))
+ XCTAssertNil(cache.name(for: URL(fileURLWithPath: "/b")))
+ XCTAssertEqual(calls, ["/a", "/b"])
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/DevelopmentProfileEffectTests.swift b/Tests/NXLibraryCoreTests/DevelopmentProfileEffectTests.swift
new file mode 100644
index 00000000..7b471b77
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/DevelopmentProfileEffectTests.swift
@@ -0,0 +1,114 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class DevelopmentProfileEffectTests: XCTestCase {
+ private func root() throws -> URL {
+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("NXEffects-\(UUID())")
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ addTeardownBlock { try? FileManager.default.removeItem(at: url) }
+ return url
+ }
+ func testAutomaticModSyncCannotOverwriteRealOverlayFromCopiedRecords() throws {
+ let root = try root()
+ let game = root.appendingPathComponent("real-game")
+ try FileManager.default.createDirectory(at: game.appendingPathComponent("mods/Foo/romfs"), withIntermediateDirectories: true)
+ let env = game.appendingPathComponent("env.txt")
+ let original = "DM_ROMFS_OVERLAY=/current-stable-choice\n"
+ try Data(original.utf8).write(to: env)
+ let records = root.appendingPathComponent("development-records.json")
+ try JSONEncoder().encode([ModRecord(folderName: "Foo", isOn: true)]).write(to: records)
+ let store = ModStore(supportFolder: game, recordsFile: records, titleID: "0100000000000000", canWrite: { true }, trash: { _ in XCTFail() }, allowsAutomaticMaintenance: false)
+ try store.sync()
+ XCTAssertEqual(try String(contentsOf: env), original)
+ try store.sync(automatic: false)
+ XCTAssertNotEqual(try String(contentsOf: env), original, "Explicit changes must remain possible")
+ }
+
+ func testModSyncPreservesRecordsAndOverlayWhenFolderCannotBeListed() throws {
+ let game = try root()
+ try Data("not a directory".utf8).write(to: game.appendingPathComponent("mods"))
+ let (store, records, overlay) = try modSyncFixture(game: game)
+ XCTAssertThrowsError(try store.sync())
+ XCTAssertEqual(try Data(contentsOf: store.recordsFile), records)
+ XCTAssertEqual(try Data(contentsOf: store.envFile), overlay)
+ }
+
+ func testModSyncPreservesAnUnreadableRecordFileAndTheOverlay() throws {
+ let game = try root()
+ try FileManager.default.createDirectory(at: game.appendingPathComponent("mods"), withIntermediateDirectories: true)
+ let (store, _, overlay) = try modSyncFixture(game: game)
+ let broken = Data("incomplete json".utf8)
+ try broken.write(to: store.recordsFile)
+ XCTAssertThrowsError(try store.sync())
+ XCTAssertEqual(try Data(contentsOf: store.recordsFile), broken)
+ XCTAssertEqual(try Data(contentsOf: store.envFile), overlay)
+ }
+
+ func testModSyncRemovesAnEntryAbsentFromAReadableFolder() throws {
+ let game = try root()
+ try FileManager.default.createDirectory(at: game.appendingPathComponent("mods"), withIntermediateDirectories: true)
+ let (store, _, _) = try modSyncFixture(game: game)
+ try store.sync()
+ XCTAssertEqual(try JSONDecoder().decode([ModRecord].self, from: Data(contentsOf: store.recordsFile)), [])
+ XCTAssertFalse(try String(contentsOf: store.envFile).contains(ModStore.overlayKey))
+ }
+
+ private func modSyncFixture(game: URL) throws -> (ModStore, Data, Data) {
+ let store = ModStore(supportFolder: game, recordsFile: game.appendingPathComponent("records.json"),
+ titleID: "0100000000000000", canWrite: { true }, trash: { _ in XCTFail() })
+ let records = try JSONEncoder().encode([ModRecord(folderName: "Foo", isOn: true)])
+ let overlay = Data("DM_ROMFS_OVERLAY=/current-selection\n".utf8)
+ try records.write(to: store.recordsFile)
+ try overlay.write(to: store.envFile)
+ return (store, records, overlay)
+ }
+
+ func testBrowsingUsesActualOverlayAndKeepsOtherProfilesInstallStaging() throws {
+ let root = try root()
+ let game = root.appendingPathComponent("game")
+ for name in ["Foo", "Bar", ".installing-other-profile"] {
+ try FileManager.default.createDirectory(at: game.appendingPathComponent("mods/" + name + "/romfs"), withIntermediateDirectories: true)
+ }
+ let env = game.appendingPathComponent("env.txt")
+ try Data(("DM_ROMFS_OVERLAY=" + game.appendingPathComponent("mods/Bar/romfs").path + "\n").utf8).write(to: env)
+ let records = root.appendingPathComponent("copied-records.json")
+ let original = try JSONEncoder().encode([ModRecord(folderName: "Foo", isOn: true), ModRecord(folderName: "Bar", isOn: false)])
+ try original.write(to: records)
+ let store = ModStore(supportFolder: game, recordsFile: records, titleID: "0100000000000000", canWrite: { true }, trash: { _ in XCTFail() }, allowsAutomaticMaintenance: false)
+ XCTAssertEqual(store.mods().filter(\.isOn).map(\.folderName), ["Bar"])
+ store.removeLeftoverInstalls()
+ XCTAssertTrue(FileManager.default.fileExists(atPath: game.appendingPathComponent("mods/.installing-other-profile").path))
+ XCTAssertEqual(try Data(contentsOf: records), original)
+ }
+
+ func testDevelopmentStartupDoesNotSweepSharedStaging() throws {
+ let home = try root()
+ let folder = home.appendingPathComponent("Games")
+ let dev = AppDataProfile(home: home, isDevelopment: true)
+ XCTAssertEqual(dev.automaticStagingFolders(appFolders: [folder]), [dev.supportRoot.appendingPathComponent("Temp")])
+ let stable = AppDataProfile(home: home, isDevelopment: false)
+ XCTAssertTrue(stable.automaticStagingFolders(appFolders: [folder]).contains(folder.appendingPathComponent(".nxlibrary-build/Temp")))
+ }
+ func testOnlyExplicitDevelopmentOperationsSurviveRestart() throws {
+ let root = try root()
+ let file = root.appendingPathComponent("operations.json")
+ let imported = UUID(), requested = UUID()
+ let first = DevelopmentOperationStore(file: file, isDevelopment: true)
+ XCTAssertFalse(first.permits(.build, gameID: imported))
+ try first.authorize(.build, gameID: requested)
+ try first.authorize(.icon, gameID: requested)
+ let restarted = DevelopmentOperationStore(file: file, isDevelopment: true)
+ XCTAssertTrue(restarted.permits(.build, gameID: requested))
+ XCTAssertTrue(restarted.permits(.icon, gameID: requested))
+ XCTAssertFalse(restarted.permits(.build, gameID: imported))
+ XCTAssertFalse(restarted.permits(.icon, gameID: imported))
+ }
+ func testCorruptAuthorizationFailsClosedWithoutReplacingIt() throws {
+ let file = try root().appendingPathComponent("operations.json")
+ try Data("broken".utf8).write(to: file)
+ let store = DevelopmentOperationStore(file: file, isDevelopment: true)
+ XCTAssertFalse(store.permits(.icon, gameID: UUID()))
+ XCTAssertThrowsError(try store.authorize(.icon, gameID: UUID()))
+ XCTAssertEqual(try String(contentsOf: file), "broken")
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/DevelopmentProfileTests.swift b/Tests/NXLibraryCoreTests/DevelopmentProfileTests.swift
new file mode 100644
index 00000000..d2ed1383
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/DevelopmentProfileTests.swift
@@ -0,0 +1,151 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class DevelopmentProfileTests: XCTestCase {
+ private func fixture() throws -> (URL, AppDataProfile) {
+ let home = FileManager.default.temporaryDirectory.appendingPathComponent("NXProfile-\(UUID())")
+ try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
+ addTeardownBlock { try? FileManager.default.removeItem(at: home) }
+ return (home, AppDataProfile(home: home, isDevelopment: true))
+ }
+ private func put(_ data: String, _ name: String, profile: AppDataProfile) throws {
+ let file = profile.stableSupportRoot.appendingPathComponent(name)
+ try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(data.utf8).write(to: file)
+ }
+ func testBuildIdentityMustSelectExactlyOneMatchingProfile() throws {
+ XCTAssertNoThrow(try AppData.validateBuildIdentity(["CFBundleIdentifier": "local.nxlibrary", "NXLibraryRelease": true]))
+ XCTAssertNoThrow(try AppData.validateBuildIdentity(["CFBundleIdentifier": "local.nxlibrary.development", "NXLibraryDevelopmentProfile": true]))
+ for invalid: [String: Any] in [[:], ["CFBundleIdentifier": "local.nxlibrary.development"],
+ ["CFBundleIdentifier": "local.nxlibrary", "NXLibraryDevelopmentProfile": true],
+ ["CFBundleIdentifier": "local.nxlibrary.development", "NXLibraryRelease": true],
+ ["CFBundleIdentifier": "local.nxlibrary", "NXLibraryRelease": true, "NXLibraryDevelopmentProfile": true]] {
+ XCTAssertThrowsError(try AppData.validateBuildIdentity(invalid))
+ }
+ }
+ func testProfileSeparatesSupportCachesAndPreferenceDomain() throws {
+ let (home, dev) = try fixture()
+ let stable = AppDataProfile(home: home, isDevelopment: false)
+ XCTAssertNotEqual(dev.supportRoot, stable.supportRoot)
+ XCTAssertNotEqual(dev.cacheRoot, stable.cacheRoot)
+ XCTAssertNotEqual(dev.preferencesDomain, stable.preferencesDomain)
+ XCTAssertEqual(stable.supportRoot, dev.stableSupportRoot)
+ }
+ func testCopiesOnlyLauncherDataAndPreservesSourceAndIdentity() throws {
+ let (_, profile) = try fixture()
+ let id = UUID()
+ let game = PortedGame(id: id, name: "Personal game", url: URL(fileURLWithPath: "/Applications/Game.app"), platform: .macApp, sizeBytes: 1, modificationDate: Date())
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .iso8601
+ let encoded = try encoder.encode(LibraryFile(games: [game]))
+ try FileManager.default.createDirectory(at: profile.stableSupportRoot, withIntermediateDirectories: true)
+ try encoded.write(to: profile.stableSupportRoot.appendingPathComponent("library.json"))
+ try put("{}", "settings.json", profile: profile)
+ try put("personal", "artwork-picks/own.png", profile: profile)
+ try put("do not copy", "keys/prod.keys", profile: profile)
+ try put("do not copy", "workspaces/game_build/content", profile: profile)
+ try put("do not copy", "steamgriddb-api-key", profile: profile)
+ var saved: [String: Any] = [:]
+ let importer = DevelopmentProfileImporter()
+ XCTAssertTrue(try importer.prepare(profile: profile, sourcePreferences: { ["NXLibrary_SetupCompleted": true, "NXNative_GameConfig_game": Data([1]), "AppleLanguages": ["en"], "NXLibrary_AuthToken": "synthetic"] }, savePreferences: { saved = $0 }))
+ XCTAssertEqual(saved["NXLibrary_SetupCompleted"] as? Bool, true)
+ XCTAssertNil(saved["AppleLanguages"])
+ XCTAssertNil(saved["NXLibrary_AuthToken"])
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .iso8601
+ let copied = try decoder.decode(LibraryFile.self, from: Data(contentsOf: profile.supportRoot.appendingPathComponent("library.json")))
+ XCTAssertEqual(copied.games.first?.id, id)
+ XCTAssertEqual(copied.games.first?.url, game.url)
+ XCTAssertEqual(try Data(contentsOf: profile.stableSupportRoot.appendingPathComponent("library.json")), encoded)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: profile.supportRoot.appendingPathComponent("keys").path))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: profile.supportRoot.appendingPathComponent("workspaces").path))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: profile.supportRoot.appendingPathComponent("steamgriddb-api-key").path))
+ }
+ func testSecondImportDoesNotOverwriteDevelopmentChanges() throws {
+ let (_, profile) = try fixture()
+ try put("{}", "settings.json", profile: profile)
+ let importer = DevelopmentProfileImporter()
+ _ = try importer.prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in })
+ let file = profile.supportRoot.appendingPathComponent("settings.json")
+ try Data(#"{"showClock":false}"#.utf8).write(to: file)
+ XCTAssertFalse(try importer.prepare(profile: profile, sourcePreferences: { XCTFail("must not reread source preferences"); return [:] }, savePreferences: { _ in XCTFail("must not reimport preferences") }))
+ XCTAssertEqual(try String(contentsOf: file), #"{"showClock":false}"#)
+ }
+ func testMalformedSourceIsNotRepairedOrActivated() throws {
+ let (_, profile) = try fixture()
+ try put("broken", "library.json", profile: profile)
+ XCTAssertThrowsError(try DevelopmentProfileImporter().prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in XCTFail() }))
+ XCTAssertEqual(try String(contentsOf: profile.stableSupportRoot.appendingPathComponent("library.json")), "broken")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: profile.supportRoot.path))
+ }
+ func testSymlinkDoesNotCopyExternalGameData() throws {
+ let (home, profile) = try fixture()
+ let external = home.appendingPathComponent("actual-game")
+ try FileManager.default.createDirectory(at: external, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: profile.stableSupportRoot, withIntermediateDirectories: true)
+ try FileManager.default.createSymbolicLink(at: profile.stableSupportRoot.appendingPathComponent("artwork-picks"), withDestinationURL: external)
+ XCTAssertThrowsError(try DevelopmentProfileImporter().prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in }))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: profile.supportRoot.path))
+ }
+ func testPreferenceFailureCanResumeWithoutOverwritingSource() throws {
+ let (_, profile) = try fixture()
+ try put("{}", "settings.json", profile: profile)
+ let importer = DevelopmentProfileImporter()
+ XCTAssertThrowsError(try importer.prepare(profile: profile, sourcePreferences: { ["NXLibrary_SetupCompleted": true] }, savePreferences: { _ in throw CocoaError(.fileWriteNoPermission) }))
+ var saved: [String: Any] = [:]
+ XCTAssertTrue(try importer.prepare(profile: profile, sourcePreferences: { XCTFail("resume uses captured preferences"); return [:] }, savePreferences: { saved = $0 }))
+ XCTAssertEqual(saved["NXLibrary_SetupCompleted"] as? Bool, true)
+ XCTAssertEqual(try String(contentsOf: profile.stableSupportRoot.appendingPathComponent("settings.json")), "{}")
+ }
+ func testRefusesAnExistingUnownedDestination() throws {
+ let (_, profile) = try fixture()
+ try FileManager.default.createDirectory(at: profile.supportRoot, withIntermediateDirectories: true)
+ XCTAssertThrowsError(try DevelopmentProfileImporter().prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in XCTFail() }))
+ }
+ func testChangedSourceDoesNotActivatePartialCopy() throws {
+ let (_, profile) = try fixture()
+ try put("{}", "settings.json", profile: profile)
+ var reads = 0
+ XCTAssertThrowsError(try DevelopmentProfileImporter().prepare(profile: profile, sourcePreferences: {
+ reads += 1
+ return ["NXLibrary_SetupCompleted": reads == 1]
+ }, savePreferences: { _ in XCTFail("must not activate") }))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: profile.supportRoot.path))
+ }
+ func testUnfinishedCopiedSessionEndsAtLastHeartbeatWithoutChangingTheOriginal() throws {
+ let (_, profile) = try fixture()
+ let session = PlaySession(gameID: UUID(), titleID: "fixture", bundleID: nil,
+ startedAt: Date(timeIntervalSince1970: 100), lastHeartbeatAt: Date(timeIntervalSince1970: 160))
+ let data = try JSONEncoder().encode([session])
+ try FileManager.default.createDirectory(at: profile.stableSupportRoot, withIntermediateDirectories: true)
+ let original = profile.stableSupportRoot.appendingPathComponent("play-sessions.json")
+ try data.write(to: original)
+ _ = try DevelopmentProfileImporter().prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in })
+ let copied = try JSONDecoder().decode([PlaySession].self, from: Data(contentsOf: profile.supportRoot.appendingPathComponent("play-sessions.json")))
+ XCTAssertEqual(copied.first?.id, session.id)
+ XCTAssertEqual(copied.first?.endedAt, session.lastHeartbeatAt)
+ XCTAssertEqual(copied.first?.duration, 60)
+ XCTAssertEqual(try Data(contentsOf: original), data)
+ }
+ func testRootsAreFoldersWhetherOrNotTheyExistYet() {
+ let home = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ for development in [false, true] {
+ let profile = AppDataProfile(home: home, isDevelopment: development)
+ for root in [profile.stableSupportRoot, profile.supportRoot, profile.cacheRoot] {
+ XCTAssertTrue(root.hasDirectoryPath, root.path)
+ XCTAssertEqual(root.appendingPathComponent("settings.json").deletingLastPathComponent(), root)
+ }
+ }
+ }
+ func testSharedAndScopedDefaultPathsAreConsistent() {
+ XCTAssertEqual(AppSettingsStore.defaultURL().deletingLastPathComponent(), AppData.supportRoot)
+ XCTAssertEqual(PlaySessionStore.defaultURL().deletingLastPathComponent(), AppData.supportRoot)
+ XCTAssertEqual(MetadataPicks().directory, AppData.supportRoot)
+ XCTAssertEqual(ArtworkStore.defaultDirectory(), AppData.supportRoot.appendingPathComponent("artwork"))
+ XCTAssertEqual(SteamGridDBKey.defaultURL(), AppData.supportRoot.appendingPathComponent("steamgriddb-api-key"))
+ }
+ func testReleaseProfileNeverImports() throws {
+ let (home, _) = try fixture()
+ XCTAssertFalse(try DevelopmentProfileImporter().prepare(profile: AppDataProfile(home: home, isDevelopment: false), sourcePreferences: { XCTFail(); return [:] }, savePreferences: { _ in XCTFail() }))
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/FirstRunFindingsTests.swift b/Tests/NXLibraryCoreTests/FirstRunFindingsTests.swift
new file mode 100644
index 00000000..253916c6
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/FirstRunFindingsTests.swift
@@ -0,0 +1,113 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class FirstRunFindingsTests: XCTestCase {
+ private func emptyApps() throws -> URL {
+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("FirstRunApps-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ addTeardownBlock { try? FileManager.default.removeItem(at: url) }
+ return url
+ }
+
+ func testMissingSteamFolderCountsNothing() throws {
+ let absent = FileManager.default.temporaryDirectory.appendingPathComponent("NoSteam-\(UUID().uuidString)")
+ let findings = FirstRunFindings.read(steamRoot: absent, appsFolder: try emptyApps(), cancelled: { false })
+ XCTAssertFalse(findings.steamReadFailed)
+ XCTAssertNil(findings.steamGameCount)
+ XCTAssertEqual(findings.portedAppCount, 0)
+ XCTAssertTrue(findings.isEmpty)
+ }
+
+ func testOnlyNativeReadyGamesCount() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ try f.manifest(in: root, id: "20", name: "Second game", directory: "Second")
+ try f.app(at: "Steam/steamapps/common/Second/Game.app")
+ try f.manifest(in: root, id: "30", name: "Downloading", directory: "Third", stateFlags: "1026")
+ try f.manifest(in: root, id: "40", name: "Windows only", directory: "Fourth")
+ try FileManager.default.createDirectory(at: root.appendingPathComponent("steamapps/common/Fourth"),
+ withIntermediateDirectories: true)
+ let snapshot = try SteamLibrarySource(root: root).scan()
+ XCTAssertTrue(snapshot.games.contains { $0.state == .downloading })
+ XCTAssertTrue(snapshot.games.contains { $0.state != .nativeReady && $0.state != .downloading })
+ XCTAssertTrue(snapshot.isComplete)
+
+ let findings = FirstRunFindings.read(steamRoot: root, appsFolder: try emptyApps(), cancelled: { false })
+ XCTAssertEqual(findings.steamGameCount, 2)
+ XCTAssertFalse(findings.isEmpty)
+ }
+
+ func testSteamWithNoMacGamesCountsZero() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ let findings = FirstRunFindings.read(steamRoot: root, appsFolder: try emptyApps(), cancelled: { false })
+ XCTAssertEqual(findings.steamGameCount, 0)
+ }
+
+ func testUnreadableOrPartialSteamCountsNothing() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ let broken = try f.manifest(in: root, id: "20", name: "Broken", directory: "Second")
+ try Data("AppState {".utf8).write(to: broken)
+ let partial = FirstRunFindings.read(steamRoot: root, appsFolder: try emptyApps(), cancelled: { false })
+ XCTAssertNil(partial.steamGameCount)
+ XCTAssertTrue(partial.steamReadFailed)
+ XCTAssertFalse(partial.isEmpty, "An incomplete read cannot establish that no games exist")
+
+ let unreadable = try f.library("Locked")
+ try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: unreadable.path)
+ addTeardownBlock { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: unreadable.path) }
+ let failed = FirstRunFindings.read(steamRoot: unreadable, appsFolder: try emptyApps(), cancelled: { false })
+ XCTAssertNil(failed.steamGameCount)
+ XCTAssertTrue(failed.steamReadFailed)
+ XCTAssertFalse(failed.isEmpty)
+ }
+
+ func testCancelledReadStops() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ let findings = FirstRunFindings.read(steamRoot: root, appsFolder: try emptyApps(), cancelled: { true })
+ XCTAssertEqual(findings, FirstRunFindings(steamGameCount: nil, portedAppCount: 0))
+ }
+
+ func testInaccessibleAncestorIsAFailedReadRatherThanAbsentSteam() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library("Hidden/Steam")
+ let parent = root.deletingLastPathComponent()
+ try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: parent.path)
+ addTeardownBlock { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: parent.path) }
+ let findings = FirstRunFindings.read(steamRoot: root, appsFolder: try emptyApps(), cancelled: { false })
+ XCTAssertTrue(findings.steamReadFailed)
+ XCTAssertFalse(findings.isEmpty)
+ }
+
+ func testSymlinkToASteamFolderIsStillReadable() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ let link = f.root.appendingPathComponent("Steam link")
+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: root)
+ let findings = FirstRunFindings.read(steamRoot: link, appsFolder: try emptyApps(), cancelled: { false })
+ XCTAssertEqual(findings.steamGameCount, 0)
+ XCTAssertFalse(findings.steamReadFailed)
+ }
+
+ func testPortedAppsAreCounted() throws {
+ let apps = try emptyApps()
+ let contents = apps.appendingPathComponent("Zelda.app/Contents")
+ try FileManager.default.createDirectory(at: contents, withIntermediateDirectories: true)
+ try PropertyListSerialization.data(fromPropertyList: [
+ "CFBundleName": "Ported", "CFBundleIdentifier": "org.nxnative.01007ef00011e000",
+ "CFBundleShortVersionString": "1.0", "DMTitleID": "01007EF00011E000",
+ ], format: .xml, options: 0).write(to: contents.appendingPathComponent("Info.plist"))
+ let absent = FileManager.default.temporaryDirectory.appendingPathComponent("NoSteam-\(UUID().uuidString)")
+ let findings = FirstRunFindings.read(steamRoot: absent, appsFolder: apps, cancelled: { false })
+ XCTAssertEqual(findings.portedAppCount, 1)
+ XCTAssertFalse(findings.isEmpty)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/FirstRunSetupTests.swift b/Tests/NXLibraryCoreTests/FirstRunSetupTests.swift
index 39ee1ba5..9570427c 100644
--- a/Tests/NXLibraryCoreTests/FirstRunSetupTests.swift
+++ b/Tests/NXLibraryCoreTests/FirstRunSetupTests.swift
@@ -2,6 +2,28 @@ import XCTest
@testable import NXLibraryCore
final class FirstRunSetupTests: XCTestCase {
+ func testSteamChoiceRestoresBothOnAndOffAfterInterruptedPorting() {
+ for choice in [true, false] {
+ var first = FirstRunSetup()
+ first.chooseSteam(choice)
+ first.openPorting()
+ let resumed = FirstRunSetup(completed: false, savedPage: first.pageToRemember,
+ savedSteamChoice: first.steamChoiceToRemember)
+ XCTAssertEqual(resumed.page, .requirements)
+ XCTAssertEqual(resumed.steamChoice, choice)
+ XCTAssertEqual(resumed.steamChoiceToRemember, choice)
+ }
+ }
+
+ func testCompletedSetupDropsSavedChoiceButKeepsItUntilTheShellAppliesIt() {
+ var flow = FirstRunSetup(savedSteamChoice: true)
+ flow.finish()
+ XCTAssertEqual(flow.steamChoice, true)
+ XCTAssertNil(flow.steamChoiceToRemember)
+ XCTAssertNil(FirstRunSetup(completed: true, savedSteamChoice: true).steamChoice)
+ XCTAssertNil(FirstRunSetup().steamChoiceToRemember)
+ }
+
func testSourceReviewWaitsForASingleReadyTitleAndConsumesEachArrivalOnce() {
var entry = FirstRunSetup.ReviewEntry()
let id = UUID()
@@ -20,8 +42,53 @@ final class FirstRunSetupTests: XCTestCase {
XCTAssertFalse(entry.consume(second, isReady: true, titleCount: 1))
}
- func testNewUserContinuesToGamesBeforeSetupIsCompleted() {
+ func testNewUserStartsOnFound() {
+ let flow = FirstRunSetup(completed: false)
+ XCTAssertEqual(flow.page, .found)
+ XCTAssertEqual(flow.pageToRemember, "found")
+ }
+
+ func testInterruptedOldSetupResumesWhereItWas() {
+ XCTAssertEqual(FirstRunSetup(completed: false, savedPage: "games").page, .games)
+ XCTAssertEqual(FirstRunSetup(completed: false, savedPage: "requirements").page, .requirements)
+ }
+
+ func testUnknownSavedPageStartsOnFound() {
+ XCTAssertEqual(FirstRunSetup(completed: false, savedPage: "unknown").page, .found)
+ XCTAssertEqual(FirstRunSetup(completed: false, savedPage: nil).page, .found)
+ }
+
+ func testPortingCardOpensRequirements() {
var flow = FirstRunSetup(completed: false)
+ flow.openPorting()
+ XCTAssertEqual(flow.page, .requirements)
+ XCTAssertEqual(flow.pageToRemember, "requirements")
+ flow.returnToFound()
+ XCTAssertEqual(flow.page, .found)
+ }
+
+ func testCompletedSetupNeverReturnsToFound() {
+ var flow = FirstRunSetup(completed: true)
+ XCTAssertEqual(flow.page, .requirements, "Settings → Open Setup starts on the requirements")
+ flow.returnToFound()
+ XCTAssertEqual(flow.page, .requirements)
+ }
+
+ func testFocusMovesThroughFoundRows() {
+ typealias F = FirstRunSetup.Focus
+ XCTAssertEqual(F.initialOnFound, .openLibrary)
+ XCTAssertEqual(F.openLibrary.movedOnFound(.up, hasSteam: true), .portingCard)
+ XCTAssertEqual(F.portingCard.movedOnFound(.up, hasSteam: true), .steamToggle)
+ XCTAssertEqual(F.portingCard.movedOnFound(.up, hasSteam: false), .portingCard)
+ XCTAssertEqual(F.steamToggle.movedOnFound(.down, hasSteam: true), .portingCard)
+ XCTAssertEqual(F.portingCard.movedOnFound(.down, hasSteam: true), .openLibrary)
+ XCTAssertEqual(F.openLibrary.movedOnFound(.down, hasSteam: true), .openLibrary)
+ XCTAssertEqual(F.steamToggle.movedOnFound(.up, hasSteam: true), .steamToggle)
+ XCTAssertEqual(F.steamToggle.movedOnFound(.left, hasSteam: true), .steamToggle)
+ }
+
+ func testNewUserContinuesToGamesBeforeSetupIsCompleted() {
+ var flow = FirstRunSetup(completed: false, savedPage: "requirements")
XCTAssertEqual(flow.page, .requirements)
flow.advance()
XCTAssertEqual(flow.page, .games)
@@ -63,7 +130,7 @@ final class FirstRunSetupTests: XCTestCase {
func testExistingUsersIgnoreStaleOrUnknownProgress() {
XCTAssertTrue(FirstRunSetup(completed: true, savedPage: "games").isCompleted)
- XCTAssertEqual(FirstRunSetup(completed: false, savedPage: "unknown").page, .requirements)
+ XCTAssertEqual(FirstRunSetup(completed: false, savedPage: "unknown").page, .found)
}
func testBackReturnsToRequirementsWithoutCompletingSetup() {
@@ -107,4 +174,25 @@ final class FirstRunSetupTests: XCTestCase {
let folder = SetupItem(id: .library, title: "Game apps", state: .warning, chip: "", about: "", detail: "")
XCTAssertFalse(SetupCheck.shouldReopen(previous: [.library: .ready], current: [folder]))
}
+
+ func testSteamChoiceSurvivesThePortingPath() {
+ var setup = FirstRunSetup()
+ XCTAssertNil(setup.steamChoice)
+ setup.chooseSteam(true)
+ setup.openPorting()
+ setup.advance()
+ setup.goBack()
+ setup.returnToFound()
+ XCTAssertEqual(setup.steamChoice, true)
+ setup.chooseSteam(false)
+ setup.openPorting()
+ setup.finish()
+ XCTAssertEqual(setup.steamChoice, false)
+ }
+
+ func testFinishedSetupTakesNoSteamChoice() {
+ var setup = FirstRunSetup(completed: true)
+ setup.chooseSteam(true)
+ XCTAssertNil(setup.steamChoice)
+ }
}
diff --git a/Tests/NXLibraryCoreTests/GameBananaClientTests.swift b/Tests/NXLibraryCoreTests/GameBananaClientTests.swift
index 95429e02..55851877 100644
--- a/Tests/NXLibraryCoreTests/GameBananaClientTests.swift
+++ b/Tests/NXLibraryCoreTests/GameBananaClientTests.swift
@@ -78,7 +78,7 @@ final class GameBananaClientTests: XCTestCase {
http.serve("Mod/5/ProfilePage", profile)
_ = try await client().profile(modID: 5)
let request = try XCTUnwrap(http.requests.first)
- XCTAssertEqual(request.value(forHTTPHeaderField: "User-Agent"), "NXLibrary/0.1.4 (macOS; personal app)")
+ XCTAssertEqual(request.value(forHTTPHeaderField: "User-Agent"), "Arcane/0.1.4 (macOS; +https://github.com/Bium23/NxLibrary)")
XCTAssertEqual(request.timeoutInterval, 15)
}
diff --git a/Tests/NXLibraryCoreTests/GameOptionsPresentationTests.swift b/Tests/NXLibraryCoreTests/GameOptionsPresentationTests.swift
index 29722843..a1666b04 100644
--- a/Tests/NXLibraryCoreTests/GameOptionsPresentationTests.swift
+++ b/Tests/NXLibraryCoreTests/GameOptionsPresentationTests.swift
@@ -24,10 +24,10 @@ final class GameOptionsPresentationTests: XCTestCase {
private func presentation(renderScale: Bool = true, playable: Bool = true,
detached: Bool = false, blocked: Bool = false,
- store: Bool = false, bundle: Bool = false) -> GameOptionsPresentation {
+ store: Bool = false, search: Bool = false, bundle: Bool = false) -> GameOptionsPresentation {
GameOptionsPresentation(supportsRenderScale: renderScale, isPlayable: playable,
sourcesDetached: detached, toolchainBlocked: blocked,
- hasStorePage: store, gameName: "Game",
+ hasStorePage: store, offersStoreSearch: search, gameName: "Game",
appPath: "/Applications/Game.app", canDeleteBundle: bundle)
}
@@ -131,6 +131,18 @@ final class GameOptionsPresentationTests: XCTestCase {
.storePage)
}
+ func testEditDetailsOffersStoreSearchWhenAsked() {
+ let rows = presentation(search: true).focusableRows(level: .editDetails, origin: .details)
+ XCTAssertEqual(rows, [.changeArtwork, .changeMetadata, .searchStore, .attachSources, .openLog, .removeSources])
+ XCTAssertEqual(GameOptionsRow.searchStore.title, "Search Nintendo Store")
+ XCTAssertEqual(presentation(store: true, search: true).focusableRows(level: .editDetails, origin: .details)
+ .prefix(4), [.changeArtwork, .changeMetadata, .storePage, .searchStore])
+ }
+
+ func testEditDetailsHasNoStoreSearchByDefault() {
+ XCTAssertFalse(presentation().focusableRows(level: .editDetails, origin: .details).contains(.searchStore))
+ }
+
func testEditDetailsEndsWithRemoveSources() {
let rows = presentation().focusableRows(level: .editDetails, origin: .details)
XCTAssertEqual(rows, [.changeArtwork, .changeMetadata, .attachSources, .openLog, .removeSources])
@@ -145,7 +157,7 @@ final class GameOptionsPresentationTests: XCTestCase {
for origin in [GameOptionsOrigin.spotlight, .collection, .details] {
for store in [false, true] {
for renderScale in [false, true] {
- let p = presentation(renderScale: renderScale, store: store)
+ let p = presentation(renderScale: renderScale, store: store, search: store)
seen.formUnion(p.focusableRows(level: .main, origin: origin))
seen.formUnion(p.focusableRows(level: .editDetails, origin: origin))
seen.formUnion(savedChoices(full: true).focusableRows(level: .main, origin: origin))
@@ -187,11 +199,11 @@ final class GameOptionsPresentationTests: XCTestCase {
XCTAssertEqual(presentation(detached: true).rebuildAbout,
"Game files are missing or not attached. Attach sources in Edit details.")
XCTAssertEqual(presentation(blocked: true).rebuildAbout,
- "Blocked by the Metal gate. See Settings → Engine.")
+ "Blocked by the Metal gate. See Settings → Setup and engine.")
let newer = GameOptionsPresentation(supportsRenderScale: true, isPlayable: true, sourcesDetached: false,
toolchainBlocked: true,
- toolchainHint: "Newer Metal: turn on the override in Settings → Engine")
- XCTAssertEqual(newer.rebuildAbout, "Newer Metal: turn on the override in Settings → Engine.")
+ toolchainHint: "Newer Metal: turn on the override in Settings → Setup and engine")
+ XCTAssertEqual(newer.rebuildAbout, "Newer Metal: turn on the override in Settings → Setup and engine.")
XCTAssertEqual(presentation(detached: true).attachAbout,
"Game files are missing or not attached. Attach them to rebuild.")
XCTAssertEqual(presentation().attachAbout,
diff --git a/Tests/NXLibraryCoreTests/GridListLayoutTests.swift b/Tests/NXLibraryCoreTests/GridListLayoutTests.swift
new file mode 100644
index 00000000..d7e27e85
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/GridListLayoutTests.swift
@@ -0,0 +1,51 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class GridListLayoutTests: XCTestCase {
+ /// Two columns of 100-point rows, 20 apart, 6 above the first and 130 kept free after the last.
+ private let layout = GridListLayout(columns: 2, rowHeight: 100, spacing: 20, topPad: 6, bottomRoom: 130)
+
+ func testContentHeightCountsWholeLinesAndTheRoomAfterThem() {
+ XCTAssertEqual(layout.lines(count: 5), 3)
+ XCTAssertEqual(layout.contentHeight(count: 5), 6 + 3 * 100 + 2 * 20 + 130)
+ XCTAssertEqual(layout.contentHeight(count: 0), 6 + 130)
+ }
+
+ func testAnIndexSitsOnItsLine() {
+ XCTAssertEqual(layout.top(of: 0), 6)
+ XCTAssertEqual(layout.top(of: 1), 6)
+ XCTAssertEqual(layout.top(of: 4), 6 + 2 * 120)
+ }
+
+ func testRevealSpanKeepsMarginsAroundTheRow() {
+ XCTAssertEqual(layout.revealSpan(of: 2, above: 40, below: 130), (126 - 40)...(226 + 130))
+ }
+
+ func testVisibleLinesCoverTheWindowAndABuffer() {
+ // Offset 300, window 400: lines touching 300...700 are 2...5; a 120 buffer adds one each side.
+ XCTAssertEqual(layout.visibleLines(count: 20, offset: 300, visible: 400, buffer: 120), 1...6)
+ XCTAssertNil(layout.visibleLines(count: 0, offset: 0, visible: 400, buffer: 120))
+ XCTAssertEqual(layout.visibleLines(count: 3, offset: 0, visible: 400, buffer: 120), 0...1)
+ }
+
+ func testAFocusLeftOutOfViewMovesToTheNearestVisibleLineInItsColumn() {
+ // Window 300...700 with margins 40 / 130: lines whole inside 340...570 are line 3 (366...466) only.
+ XCTAssertEqual(layout.nearestVisible(index: 1, count: 20, offset: 300, visible: 400, above: 40, below: 130), 7)
+ XCTAssertEqual(layout.nearestVisible(index: 18, count: 20, offset: 300, visible: 400, above: 40, below: 130), 6)
+ XCTAssertNil(layout.nearestVisible(index: 6, count: 20, offset: 300, visible: 400, above: 40, below: 130))
+ }
+
+ func testANarrowWindowKeepsTheFocus() {
+ // No line fits whole between the margins: the focus stays and the next move reveals it.
+ XCTAssertNil(layout.nearestVisible(index: 0, count: 20, offset: 900, visible: 150, above: 40, below: 130))
+ }
+
+ func testAFocusInViewUnderTheMarginsKeepsTheFocus() {
+ // The first row at the top (6...106) sits under the top margin but in view: Up must not move the focus down.
+ XCTAssertNil(layout.nearestVisible(index: 0, count: 20, offset: 0, visible: 400, above: 52, below: 130))
+ // A row revealed against the margin, with rounding left in the offset, is in view too.
+ XCTAssertNil(layout.nearestVisible(index: 6, count: 20, offset: 366 - 52 + 0.0001, visible: 400, above: 52, below: 130))
+ // Half under the bottom fade, still in view.
+ XCTAssertNil(layout.nearestVisible(index: 8, count: 20, offset: 0, visible: 600, above: 52, below: 130))
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/IGDBMetadataTests.swift b/Tests/NXLibraryCoreTests/IGDBMetadataTests.swift
new file mode 100644
index 00000000..35305bda
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/IGDBMetadataTests.swift
@@ -0,0 +1,143 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class IGDBMetadataTests: XCTestCase {
+ private let query = CriticRatingQuery(name: "Fixture™", platform: .switch2)
+ private let credentials = IGDBCredentials(clientID: "fixtureClient123456", clientSecret: "fixtureSecret123456")!
+ private let token = Data(#"{"access_token":"fixtureToken","expires_in":3600,"token_type":"bearer"}"#.utf8)
+ private let game = Data("""
+ [{"id":10,"name":"Fixture","platforms":[508],"url":"https://www.igdb.com/games/fixture",
+ "summary":" A description. ","genres":[{"name":"Adventure"},{"name":"Puzzle"}],
+ "involved_companies":[{"company":{"name":"Developer"},"developer":true,"publisher":false},
+ {"company":{"name":"Publisher"},"developer":false,"publisher":true},
+ {"company":{"name":"Support"},"developer":false,"publisher":false}],
+ "release_dates":[{"platform":130,"date":1704412800,"date_format":{"format":"YYYYMMDD"}},
+ {"platform":508,"date":1793836800,"date_format":{"format":"YYYYMMDD"}}]}]
+ """.utf8)
+
+ func testFieldsRolesAndExactPlatformDateBecomeIndividualPreviewOptions() throws {
+ let result = try IGDBMetadataParser.result(in: game, query: query)
+ let metadata = try XCTUnwrap(result.metadata)
+ XCTAssertEqual(metadata.id, 10)
+ XCTAssertEqual(metadata.option(for: .description)?.value, "A description.")
+ XCTAssertEqual(metadata.option(for: .description)?.source, "IGDB")
+ XCTAssertEqual(metadata.option(for: .genres)?.value, "Adventure, Puzzle")
+ XCTAssertEqual(metadata.option(for: .developer)?.value, "Developer")
+ XCTAssertEqual(metadata.option(for: .publisher)?.value, "Publisher")
+ XCTAssertEqual(metadata.option(for: .releaseDate)?.value, "2026-11-05")
+ XCTAssertEqual(try JSONDecoder().decode(IGDBMetadata.self, from: JSONEncoder().encode(metadata)), metadata)
+ }
+
+ func testPartialDatesForeignPlatformsAndOtherEditionsAreNotInvented() throws {
+ let partial = Data(String(decoding: game, as: UTF8.self).replacingOccurrences(of: "YYYYMMDD", with: "YYYYMM").utf8)
+ XCTAssertNil(try IGDBMetadataParser.result(in: partial, query: query).metadata?.option(for: .releaseDate))
+ let foreign = CriticRatingQuery(name: "Fixture", platform: .switch)
+ XCTAssertEqual(try IGDBMetadataParser.result(in: game, query: foreign).issue, .notFound)
+ XCTAssertEqual(try IGDBMetadataParser.result(in: game, query: .init(name: "Fixture II", platform: .switch2)).issue, .notFound)
+ let duplicate = Data(("[" + String(decoding: game, as: UTF8.self).dropFirst().dropLast() + "," + String(decoding: game, as: UTF8.self).dropFirst().dropLast() + "]").utf8)
+ XCTAssertEqual(try IGDBMetadataParser.result(in: duplicate, query: query).issue, .ambiguous)
+ let empty = Data(#"[{"id":10,"name":"Fixture","platforms":[508],"url":"https://www.igdb.com/games/fixture"}]"#.utf8)
+ XCTAssertNil(try IGDBMetadataParser.result(in: empty, query: query).metadata?.option(for: .description))
+ XCTAssertThrowsError(try IGDBMetadataParser.result(in: Data("{}".utf8), query: query))
+ }
+
+ func testSteamIdentityUsesTheExternalIDWithoutBorrowingAPortsReleaseDate() throws {
+ let nested = String(decoding: game, as: UTF8.self).dropFirst().dropLast()
+ let external = Data(("[{\"uid\":\"42\",\"external_game_source\":{\"name\":\"Steam\"},\"game\":" + nested + "}]").utf8)
+ let steam = CriticRatingQuery(name: "Personal name", platform: .mac, steamAppID: 42)
+ let result = try IGDBMetadataParser.steamResult(in: external, query: steam)
+ XCTAssertEqual(result.metadata?.option(for: .description)?.value, "A description.")
+ XCTAssertNil(result.metadata?.option(for: .releaseDate))
+ XCTAssertEqual(try IGDBMetadataParser.steamResult(in: external, query: .init(name: "Fixture", platform: .mac, steamAppID: 99)).issue, .notFound)
+ }
+
+ func testCacheRemainsAvailableOfflineAndNeverChangesPersonalPicks() async throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let token = token, game = game
+ let service = IGDBMetadataService(directory: root, transport: { request in
+ if request.url!.host == "api.igdb.com" {
+ let body = String(decoding: request.httpBody ?? Data(), as: UTF8.self)
+ XCTAssertTrue(body.contains("involved_companies.developer"))
+ XCTAssertTrue(body.contains("release_dates.date_format.format"))
+ }
+ return (request.url!.host == "id.twitch.tv" ? token : game,
+ HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
+ })
+ let found = await service.load(query, credentials: credentials)
+ XCTAssertEqual(found.metadata?.id, 10)
+ let offline = IGDBMetadataService(directory: root, transport: { _ in throw URLError(.notConnectedToInternet) })
+ let retained = await offline.load(query, credentials: credentials, now: Date().addingTimeInterval(8 * 86400))
+ XCTAssertEqual(retained.metadata, found.metadata)
+ XCTAssertTrue(retained.isStale)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("metadata-picks.json").path))
+ }
+
+ func testCancellationDoesNotSaveAMissingMatch() async throws {
+ let started = expectation(description: "request starts"), stopped = expectation(description: "request stops")
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = IGDBMetadataService(directory: root, transport: { _ in
+ started.fulfill()
+ do { try await Task.sleep(nanoseconds: 10_000_000_000); throw URLError(.timedOut) }
+ catch { stopped.fulfill(); throw error }
+ })
+ let query = query, credentials = credentials
+ let task = Task { await service.load(query, credentials: credentials) }
+ await fulfillment(of: [started], timeout: 2)
+ task.cancel()
+ await fulfillment(of: [stopped], timeout: 2)
+ let result = await task.value
+ XCTAssertNil(result.metadata)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: root.path))
+ }
+
+ func testFailureDoesNotBecomeANegativeCacheAndCanBeRetried() async throws {
+ actor Calls {
+ var games = 0
+ func next() -> Int { games += 1; return games }
+ }
+ let calls = Calls(), token = token, game = game
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = IGDBMetadataService(directory: root, transport: { request in
+ if request.url!.host == "id.twitch.tv" {
+ return (token, HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
+ }
+ let count = await calls.next()
+ return (count == 1 ? Data("private server details".utf8) : game,
+ HTTPURLResponse(url: request.url!, statusCode: count == 1 ? 503 : 200, httpVersion: nil, headerFields: nil)!)
+ })
+ let failed = await service.load(query, credentials: credentials)
+ XCTAssertEqual(failed.issue, .unavailable)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: root.path))
+ let retried = await service.load(query, credentials: credentials)
+ XCTAssertEqual(retried.metadata?.id, 10)
+ }
+
+ func testSharedClientSerializesDifferentLookupsAndReusesOneToken() async throws {
+ actor Calls {
+ var tokens = 0, active = 0, maximum = 0
+ func begin(_ token: Bool) {
+ if token { tokens += 1 }
+ active += 1; maximum = max(maximum, active)
+ }
+ func end() { active -= 1 }
+ }
+ let calls = Calls(), token = token
+ let client = IGDBClient(transport: { request in
+ let isToken = request.url!.host == "id.twitch.tv"
+ await calls.begin(isToken)
+ try await Task.sleep(nanoseconds: 10_000_000)
+ await calls.end()
+ return (isToken ? token : Data("[]".utf8),
+ HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
+ })
+ async let games = client.request("games", body: "fields id; limit 1;", credentials: credentials)
+ async let external = client.request("external_games", body: "fields id; limit 1;", credentials: credentials)
+ _ = try await (games, external)
+ let tokens = await calls.tokens, maximum = await calls.maximum
+ XCTAssertEqual(tokens, 1)
+ XCTAssertEqual(maximum, 1)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/IGDBRatingTests.swift b/Tests/NXLibraryCoreTests/IGDBRatingTests.swift
new file mode 100644
index 00000000..7716db18
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/IGDBRatingTests.swift
@@ -0,0 +1,343 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class IGDBRatingTests: XCTestCase {
+ private let credentials = IGDBCredentials(clientID: "fixtureClient123456", clientSecret: "fixtureSecret123456")!
+ private let query = CriticRatingQuery(name: "Fixture™", platform: .switch)
+ private let token = Data("{\"access_token\":\"fixtureToken\",\"expires_in\":3600,\"token_type\":\"bearer\"}".utf8)
+ private let game = Data("""
+ [{"id":10,"name":"Fixture","aggregated_rating":83.5,"aggregated_rating_count":12,
+ "rating":99,"total_rating":96,"platforms":[130],"url":"https://www.igdb.com/games/fixture"}]
+ """.utf8)
+ private func response(_ request: URLRequest, _ data: Data, status: Int = 200) -> (Data, HTTPURLResponse) {
+ (data, HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!)
+ }
+ func testPersonalCredentialsStayPrivateAndAreNotSettings() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let store = IGDBCredentialsStore(url: root.appendingPathComponent("igdb.json"))
+ XCTAssertNil(store.load())
+ try store.save(credentials)
+ XCTAssertEqual(store.load(), credentials)
+ let permissions = try FileManager.default.attributesOfItem(atPath: store.url.path)[.posixPermissions] as? Int
+ XCTAssertEqual(permissions, 0o600)
+ XCTAssertNil(IGDBCredentials(clientID: " bad id ", clientSecret: "secret"))
+ XCTAssertNil(IGDBCredentials(clientID: "valid123", clientSecret: "Bearer token"))
+ try store.remove()
+ XCTAssertNil(store.load())
+ }
+ func testSavingTightensAnExistingCredentialsFolder() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let folder = root.appendingPathComponent("credentials")
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o755])
+ let store = IGDBCredentialsStore(url: folder.appendingPathComponent("igdb.json"))
+ try store.save(credentials)
+ let permissions = try FileManager.default.attributesOfItem(atPath: folder.path)[.posixPermissions] as? Int
+ XCTAssertEqual(permissions, 0o700)
+ }
+
+ func testCriticAverageWinsWithoutMixingCommunityScores() throws {
+ let rating = try XCTUnwrap(IGDBRatings.rating(in: game, query: query))
+ XCTAssertEqual(rating.source, .igdb)
+ XCTAssertEqual(rating.score, 83.5)
+ XCTAssertEqual(rating.reviewCount, 12)
+ XCTAssertEqual(rating.sourceURL.absoluteString, "https://www.igdb.com/games/fixture")
+ XCTAssertEqual(rating.starFills.reduce(0,+), 4.175, accuracy: 0.0001)
+ XCTAssertNil(rating.entityID)
+ XCTAssertFalse(rating.isCommunity)
+ let userOnly = Data("[{\"id\":10,\"name\":\"Fixture\",\"rating\":99,\"rating_count\":100,\"platforms\":[130]}]".utf8)
+ XCTAssertNil(try IGDBRatings.rating(in: userOnly, query: query))
+ }
+
+ func testCriticAverageNeedsThreeReviews() throws {
+ // Two critics are not a critic consensus: fall back to the explicit user average, or to nothing.
+ let few = Data("""
+ [{"id":10,"name":"Fixture","aggregated_rating":95,"aggregated_rating_count":2,
+ "rating":71,"rating_count":40,"platforms":[130],"url":"https://www.igdb.com/games/fixture"}]
+ """.utf8)
+ let rating = try XCTUnwrap(IGDBRatings.rating(in: few, query: query))
+ XCTAssertTrue(rating.isCommunity)
+ XCTAssertEqual(rating.score, 71)
+ let criticsOnly = Data("""
+ [{"id":10,"name":"Fixture","aggregated_rating":95,"aggregated_rating_count":2,
+ "platforms":[130],"url":"https://www.igdb.com/games/fixture"}]
+ """.utf8)
+ XCTAssertNil(try IGDBRatings.rating(in: criticsOnly, query: query))
+ let three = Data(String(decoding: criticsOnly, as: UTF8.self)
+ .replacingOccurrences(of: "\"aggregated_rating_count\":2", with: "\"aggregated_rating_count\":3").utf8)
+ XCTAssertEqual(try IGDBRatings.rating(in: three, query: query)?.isCommunity, false)
+ // A critic score saved before the minimum is no longer a valid cache entry.
+ let saved = CriticRating(score: 95, source: .igdb, igdbID: 10,
+ igdbURL: URL(string: "https://www.igdb.com/games/fixture"), reviewCount: 2)
+ XCTAssertFalse(saved.isValid)
+ let users = CriticRating(score: 71, source: .igdb, igdbID: 10,
+ igdbURL: URL(string: "https://www.igdb.com/games/fixture"), reviewCount: 1, audience: .users)
+ XCTAssertTrue(users.isValid)
+ }
+
+ func testCommunityFallbackIsDistinctAndRequiresACountAndProvenance() throws {
+ let entry = Data("""
+ [{"id":405460,"name":"The Legend of Zelda: Ocarina of Time","platforms":[508],
+ "rating":99.65387466304598,"rating_count":35,
+ "url":"https://www.igdb.com/games/the-legend-of-zelda-ocarina-of-time--1"}]
+ """.utf8)
+ let query = CriticRatingQuery(name: "The Legend of Zelda™: Ocarina of Time", platform: .switch2)
+ let rating = try XCTUnwrap(IGDBRatings.rating(in: entry, query: query))
+ XCTAssertTrue(rating.isCommunity)
+ XCTAssertEqual(rating.reviewCount, 35)
+ XCTAssertEqual(rating.score, 99.65387466304598)
+ XCTAssertEqual(rating.labelKey, "User score")
+ XCTAssertEqual(rating.attribution(context: .init(language: .italian, region: "IT")), "Utenti · IGDB")
+ XCTAssertEqual(try JSONDecoder().decode(CriticRating.self, from: JSONEncoder().encode(rating)), rating)
+ let noVotes = Data(String(decoding: entry, as: UTF8.self).replacingOccurrences(of: "\"rating_count\":35", with: "\"rating_count\":0").utf8)
+ XCTAssertNil(try IGDBRatings.rating(in: noVotes, query: query))
+ let invalid = Data(String(decoding: entry, as: UTF8.self).replacingOccurrences(of: "99.65387466304598", with: "101").utf8)
+ XCTAssertNil(try IGDBRatings.rating(in: invalid, query: query))
+ }
+
+ func testLegacyCriticCacheDecodesAndFreshLegacyMissRetriesForCommunity() async throws {
+ let rating = try XCTUnwrap(IGDBRatings.rating(in: game, query: query))
+ var legacy = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(rating)) as? [String: Any])
+ legacy.removeValue(forKey: "audience")
+ let decoded = try JSONDecoder().decode(CriticRating.self, from: JSONSerialization.data(withJSONObject: legacy))
+ XCTAssertFalse(decoded.isCommunity)
+ XCTAssertTrue(decoded.isValid)
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys]
+ let key = IGDBCredentials.digest(credentials.clientID + String(decoding: try encoder.encode(query), as: UTF8.self))
+ let old: [String: Any] = ["query": ["name": query.name, "platform": "switch"], "fetchedAt": Date().timeIntervalSinceReferenceDate]
+ try JSONSerialization.data(withJSONObject: old).write(to: root.appendingPathComponent(key + ".json"))
+ let token = token
+ let community = Data("""
+ [{"id":10,"name":"Fixture","platforms":[130],"rating":70,"rating_count":8,"url":"https://www.igdb.com/games/fixture"}]
+ """.utf8)
+ let service = IGDBRatingService(directory: root, transport: { request in
+ if request.url!.host == "api.igdb.com" {
+ let body = String(decoding: request.httpBody ?? Data(), as: UTF8.self)
+ XCTAssertTrue(body.contains(",rating,rating_count,"))
+ }
+ return (request.url!.host == "id.twitch.tv" ? token : community,
+ HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
+ })
+ let found = await service.load(query, credentials: credentials)
+ XCTAssertEqual(found.rating?.isCommunity, true)
+ let offline = IGDBRatingService(directory: root, transport: { _ in throw URLError(.notConnectedToInternet) })
+ let saved = await offline.load(query, credentials: credentials, now: Date().addingTimeInterval(8 * 86400))
+ XCTAssertEqual(saved.rating, found.rating)
+ XCTAssertTrue(saved.isStale)
+ var oldCriticCache = old
+ oldCriticCache["rating"] = legacy
+ try JSONSerialization.data(withJSONObject: oldCriticCache).write(to: root.appendingPathComponent(key + ".json"))
+ let retainedCritic = await offline.load(query, credentials: credentials)
+ XCTAssertEqual(retainedCritic.rating?.score, decoded.score)
+ XCTAssertEqual(retainedCritic.rating?.isCommunity, false)
+ XCTAssertFalse(retainedCritic.isStale)
+ }
+ func testExactTitleAliasAndPlatformWithoutSequelOrAmbiguity() throws {
+ let otherPlatform = Data(String(decoding: game, as: UTF8.self).replacingOccurrences(of: "[130]", with: "[6]").utf8)
+ XCTAssertNil(try IGDBRatings.rating(in: otherPlatform, query: query))
+ XCTAssertNil(try IGDBRatings.rating(in: game, query: .init(name: "Fixture II", platform: .switch)))
+ let duplicate = Data(("[" + String(decoding: game, as: UTF8.self).dropFirst().dropLast() + "," + String(decoding: game, as: UTF8.self).dropFirst().dropLast() + "]").utf8)
+ XCTAssertNil(try IGDBRatings.rating(in: duplicate, query: query))
+ }
+
+ func testRatingQueryUsesTheGamesConsoleAndPreservesLegacySwitchIdentity() throws {
+ var game = PortedGame(name: "Fixture", url: URL(fileURLWithPath: "/tmp/Fixture.app"),
+ platform: .macApp, sizeBytes: 1, modificationDate: Date(), titleId: "0100000000000000")
+ XCTAssertEqual(CriticRatingQuery(game: game).platform, .switch)
+ game.titleId = "0400000000000000"
+ let query = CriticRatingQuery(game: game, name: "Official Fixture")
+ XCTAssertEqual(query.platform, .switch2)
+ XCTAssertEqual(query.name, "Official Fixture")
+ XCTAssertNil(query.steamAppID)
+ XCTAssertEqual(try JSONDecoder().decode(CriticRatingQuery.self,
+ from: Data(#"{"name":"Fixture","platform":"switch"}"#.utf8)).platform, .switch)
+ XCTAssertEqual(try JSONDecoder().decode(CriticRatingQuery.self, from: JSONEncoder().encode(query)), query)
+ }
+
+ func testSameTitleOnDifferentConsolesSelectsOnlyTheRequestedEdition() throws {
+ // Synthetic scores: the important regression is identity, not a live game's current rating.
+ let games = Data("""
+ [{"id":1,"name":"Fixture","platforms":[4],"aggregated_rating":99,"aggregated_rating_count":3,"url":"https://www.igdb.com/games/original"},
+ {"id":2,"name":"Fixture","platforms":[508],"aggregated_rating":85,"aggregated_rating_count":3,"url":"https://www.igdb.com/games/remake"},
+ {"id":3,"name":"Fixture","platforms":[130],"aggregated_rating":80,"aggregated_rating_count":3,"url":"https://www.igdb.com/games/switch-edition"}]
+ """.utf8)
+ XCTAssertEqual(try IGDBRatings.rating(in: games, query: .init(name: "Fixture™", platform: .switch2))?.igdbID, 2)
+ XCTAssertEqual(try IGDBRatings.rating(in: games, query: query)?.igdbID, 3)
+ XCTAssertNil(try IGDBRatings.rating(in: games, query: .init(name: "Fixture", platform: .mac)))
+ let originalOnly = Data("""
+ [{"id":1,"name":"Fixture","platforms":[4],"aggregated_rating":99,"aggregated_rating_count":3,"url":"https://www.igdb.com/games/original"}]
+ """.utf8)
+ XCTAssertNil(try IGDBRatings.rating(in: originalOnly, query: .init(name: "Fixture", platform: .switch2)))
+ }
+
+ func testSwitch2RetriesDespiteLegacySwitchMissAndCachesItsOwnResult() async throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let token = token, query = query
+ let old = IGDBRatingService(directory: root, transport: { request in
+ let data = request.url!.host == "id.twitch.tv" ? token : Data("[]".utf8)
+ return (data, HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
+ })
+ let missed = await old.load(query, credentials: credentials)
+ XCTAssertNil(missed.rating)
+ XCTAssertNotNil(missed.fetchedAt)
+ let switch2 = CriticRatingQuery(name: query.name, platform: .switch2)
+ let game = Data(String(decoding: game, as: UTF8.self).replacingOccurrences(of: "[130]", with: "[508]").utf8)
+ let fixed = IGDBRatingService(directory: root, transport: { request in
+ let data = request.url!.host == "id.twitch.tv" ? token : game
+ return (data, HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
+ })
+ let found = await fixed.load(switch2, credentials: credentials)
+ XCTAssertEqual(found.rating?.score, 83.5)
+ let cached = IGDBRatingService(directory: root, transport: { _ in
+ XCTFail("Fresh results for either console must remain cached separately")
+ throw URLError(.notConnectedToInternet)
+ })
+ let retained = await cached.load(switch2, credentials: credentials)
+ XCTAssertEqual(retained.rating, found.rating)
+ let priorMiss = await cached.load(query, credentials: credentials)
+ XCTAssertNil(priorMiss.rating)
+ XCTAssertEqual(priorMiss.fetchedAt, missed.fetchedAt)
+ }
+ func testTokenAndAPIHostsAreIsolatedAndOfflineCacheSurvives() async throws {
+ actor Requests {
+ var items: [URLRequest] = []
+ func add(_ request: URLRequest) { items.append(request) }
+ }
+ let requests = Requests(), token = token, game = game
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = IGDBRatingService(directory: root, transport: { request in
+ await requests.add(request)
+ let data = request.url!.host == "id.twitch.tv" ? token : game
+ return (data, HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
+ })
+ let first = await service.load(query, credentials: credentials)
+ XCTAssertEqual(first.rating?.score, 83.5)
+ let all = await requests.items
+ XCTAssertEqual(all.map { $0.url!.host! }, ["id.twitch.tv", "api.igdb.com"])
+ XCTAssertNil(all[0].url!.query)
+ XCTAssertTrue(String(decoding: all[0].httpBody!, as: UTF8.self).contains("client_secret="))
+ XCTAssertNil(all[0].value(forHTTPHeaderField: "Authorization"))
+ XCTAssertEqual(all[1].value(forHTTPHeaderField: "Authorization"), "Bearer fixtureToken")
+ XCTAssertFalse(String(decoding: all[1].httpBody!, as: UTF8.self).contains("fixtureSecret"))
+ let offline = IGDBRatingService(directory: root, transport: { _ in throw URLError(.notConnectedToInternet) })
+ let retained = await offline.load(query, credentials: credentials, now: Date().addingTimeInterval(8*86400))
+ XCTAssertEqual(retained.rating, first.rating)
+ XCTAssertTrue(retained.isStale)
+ }
+ func testRejectedCredentialsAreNotSuccessfulChecks() async throws {
+ let service = IGDBRatingService(transport: { request in
+ (Data("{\"message\":\"secret response must never be shown\"}".utf8),
+ HTTPURLResponse(url: request.url!, statusCode: 401, httpVersion: nil, headerFields: nil)!)
+ })
+ do { try await service.check(credentials); XCTFail("Rejected credentials must fail") }
+ catch { XCTAssertEqual(error as? IGDBError, .rejected) }
+ }
+ func testSettingsSearchFindsIGDBInGeneralAPIServices() {
+ XCTAssertEqual(SettingsCatalog.search("IGDB").first { $0.id == "igdb" }?.group, .apiServices)
+ }
+
+ func testExpiredOrRevokedTokenRenewsOnceAndConcurrentReadersShareWork() async throws {
+ actor Calls {
+ var tokens = 0, games = 0
+ func next(isToken: Bool) -> Int {
+ if isToken { tokens += 1; return tokens }
+ games += 1; return games
+ }
+ }
+ let calls = Calls(), token = token, game = game
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = IGDBRatingService(directory: root, transport: { request in
+ let isToken = request.url!.host == "id.twitch.tv"
+ let count = await calls.next(isToken: isToken)
+ let status = !isToken && count == 1 ? 401 : 200
+ return (isToken ? token : game, HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!)
+ })
+ async let a = service.load(query, credentials: credentials)
+ async let b = service.load(query, credentials: credentials)
+ let values = await (a,b)
+ XCTAssertEqual(values.0.rating?.score, 83.5)
+ XCTAssertEqual(values.0.rating, values.1.rating)
+ let tokens = await calls.tokens, games = await calls.games
+ XCTAssertEqual(tokens, 2); XCTAssertEqual(games, 2)
+ }
+
+ func testCancellationStopsCredentialTransmissionAndDoesNotCacheAbsence() async throws {
+ let started = expectation(description: "token started"), stopped = expectation(description: "token cancelled")
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = IGDBRatingService(directory: root, transport: { _ in
+ started.fulfill()
+ do { try await Task.sleep(nanoseconds: 10_000_000_000); throw IGDBError.unreachable }
+ catch { stopped.fulfill(); throw error }
+ })
+ let task = Task { await service.load(query, credentials: credentials) }
+ await fulfillment(of: [started], timeout: 2)
+ task.cancel()
+ await fulfillment(of: [stopped], timeout: 2)
+ let result = await task.value
+ XCTAssertNil(result.rating)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: root.path))
+ }
+
+ func testWikidataRemainsTheFallbackWithFailedOrRemovedCredentials() async throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let wiki = CriticRatingService(directory: root.appendingPathComponent("wiki"), transport: { url in
+ if url.query?.contains("wbsearchentities") == true {
+ return Data("{\"search\":[{\"id\":\"Q10\",\"label\":\"Fixture\"}]}".utf8)
+ }
+ return Data("""
+ {"entities":{"Q10":{"claims":{"P31":[{"mainsnak":{"datavalue":{"value":{"id":"Q7889"}}}}],
+ "P444":[{"id":"Q10$s","mainsnak":{"datavalue":{"value":"78/100"}},
+ "qualifiers":{"P447":[{"datavalue":{"value":{"id":"Q21039459"}}}],"P459":[{"datavalue":{"value":{"id":"Q114712322"}}}]},
+ "references":[{"snaks":{"P248":[{"datavalue":{"value":{"id":"Q21039459"}}}]}}]}]}}}}
+ """.utf8)
+ })
+ let primary = IGDBRatingService(directory: root.appendingPathComponent("igdb"), transport: { _ in throw URLError(.notConnectedToInternet) })
+ let fallback = await wiki.preferred(query, credentials: credentials, igdb: primary)
+ XCTAssertEqual(fallback.rating?.source, .openCritic)
+ let removed = await wiki.preferred(query, credentials: nil, igdb: primary)
+ XCTAssertEqual(removed.rating, fallback.rating)
+
+ let token = token
+ let users = Data("""
+ [{"id":10,"name":"Fixture","platforms":[130],"rating":99,"rating_count":35,"url":"https://www.igdb.com/games/fixture"}]
+ """.utf8)
+ let community = IGDBRatingService(directory: root.appendingPathComponent("community"), transport: { request in
+ (request.url!.host == "id.twitch.tv" ? token : users,
+ HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
+ })
+ let criticsFirst = await wiki.preferred(query, credentials: credentials, igdb: community)
+ XCTAssertEqual(criticsFirst.rating?.source, .openCritic)
+ let criticGame = game
+ let critic = IGDBRatingService(directory: root.appendingPathComponent("critic"), transport: { request in
+ (request.url!.host == "id.twitch.tv" ? token : criticGame,
+ HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
+ })
+ let igdbFirst = await wiki.preferred(query, credentials: credentials, igdb: critic)
+ XCTAssertEqual(igdbFirst.rating?.source, .igdb)
+ XCTAssertEqual(igdbFirst.rating?.score, 83.5)
+ let missing = CriticRatingService(directory: root.appendingPathComponent("missing"), transport: { _ in Data("{\"search\":[]}".utf8) })
+ let usersLast = await missing.preferred(query, credentials: credentials, igdb: community)
+ XCTAssertEqual(usersLast.rating?.isCommunity, true)
+ let removedUsers = await missing.preferred(query, credentials: nil, igdb: community)
+ XCTAssertNil(removedUsers.rating)
+ }
+
+ func testSteamExternalMappingUsesItsSourceAndIDNotASimilarTitle() throws {
+ let entry = """
+ [{"uid":"42","external_game_source":{"name":"Steam"},"game":
+ {"id":10,"name":"Official title","aggregated_rating":80,"aggregated_rating_count":3,"url":"https://www.igdb.com/games/official"}}]
+ """
+ XCTAssertEqual(try IGDBRatings.steamRating(in: Data(entry.utf8), appID: 42)?.score, 80)
+ XCTAssertNil(try IGDBRatings.steamRating(in: Data(entry.utf8), appID: 99))
+ XCTAssertNil(try IGDBRatings.steamRating(in: Data(entry.replacingOccurrences(of: "Steam", with: "GOG").utf8), appID: 42))
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/ImportServiceTests.swift b/Tests/NXLibraryCoreTests/ImportServiceTests.swift
index 27d90ff0..5429f7f4 100644
--- a/Tests/NXLibraryCoreTests/ImportServiceTests.swift
+++ b/Tests/NXLibraryCoreTests/ImportServiceTests.swift
@@ -17,22 +17,23 @@ final class ImportServiceTests: XCTestCase {
bundleId: "org.nxnative.new", appURL: newURL, sizeBytes: 200,
modificationDate: Date(timeIntervalSince1970: 2))
let service = ImportService()
- let store = LibraryStore(directory: root.appendingPathComponent("Catalog"))
- _ = try store.merge(scanned: [service.makeGame(from: old)])
- let selected = service.appsForLibrary(scanned: [newer, old], existing: try store.load().games)
+ let store = CatalogRepository(store: CatalogStore(directory: root.appendingPathComponent("Catalog")))
+ try store.configureSource(.nxnative, enabled: true, root: nil)
+ _ = try store.mergeNXNative(scanned: [service.makeGame(from: old)])
+ let selected = service.appsForLibrary(scanned: [newer, old], existing: try store.load().nxnativeGames)
XCTAssertEqual(selected.count, 1)
- let library = try store.merge(scanned: selected.map { service.makeGame(from: $0) })
- let game = try XCTUnwrap(library.games.first)
+ let library = try store.mergeNXNative(scanned: selected.map { service.makeGame(from: $0) })
+ let game = try XCTUnwrap(library.nxnativeGames.first)
XCTAssertEqual(game.url, oldURL)
XCTAssertEqual(game.name, "Installed")
XCTAssertEqual(game.versionString, "1.0")
XCTAssertEqual(game.modificationDate, Date(timeIntervalSince1970: 1))
XCTAssertEqual(selected.first?.sizeBytes, 100)
// A different chosen folder does not silently switch an existing installed app.
- XCTAssertTrue(service.appsForLibrary(scanned: [newer], existing: library.games).isEmpty)
+ XCTAssertTrue(service.appsForLibrary(scanned: [newer], existing: library.nxnativeGames).isEmpty)
// If the old app is actually removed, the discovered build can replace its reference.
try FileManager.default.removeItem(at: oldURL)
- XCTAssertEqual(service.appsForLibrary(scanned: [newer], existing: library.games).first?.appURL, newURL)
+ XCTAssertEqual(service.appsForLibrary(scanned: [newer], existing: library.nxnativeGames).first?.appURL, newURL)
// A new title with multiple builds starts with the newest scan result, once.
XCTAssertEqual(service.appsForLibrary(scanned: [newer, old], existing: []).count, 1)
}
diff --git a/Tests/NXLibraryCoreTests/LaunchBoxArtTests.swift b/Tests/NXLibraryCoreTests/LaunchBoxArtTests.swift
index 9f8ebd48..c15616f2 100644
--- a/Tests/NXLibraryCoreTests/LaunchBoxArtTests.swift
+++ b/Tests/NXLibraryCoreTests/LaunchBoxArtTests.swift
@@ -62,13 +62,13 @@ final class LaunchBoxArtTests: XCTestCase {
return page(fixed + shots + [("Fanart - Background", "World", "fanart.jpg", "fanart-full.jpg", 1920, 1080), ("Square", "World", "r2_square.jpg", "r2_square-full.jpg", 950, 950)])
}
- static let search = "https://gamesdb.launchbox-app.com/games/results/Donkey%20Kong%20Bananza"
+ static let search = "https://gamesdb.launchbox-app.com/games/results/donkey%20kong%20bananza"
static let details = "https://gamesdb.launchbox-app.com/games/details/424483-donkey-kong-bananza"
func testSearchURLKeepsTheNameInThePath() {
XCTAssertEqual(LaunchBoxArt.searchURL(for: "Donkey Kong Bananza")?.absoluteString, Self.search)
XCTAssertEqual(LaunchBoxArt.searchURL(for: "Fate/Samurai")?.absoluteString,
- "https://gamesdb.launchbox-app.com/games/results/Fate%2FSamurai")
+ "https://gamesdb.launchbox-app.com/games/results/fate%2Fsamurai")
XCTAssertNil(LaunchBoxArt.searchURL(for: " "))
}
@@ -86,6 +86,19 @@ final class LaunchBoxArtTests: XCTestCase {
XCTAssertNil(LaunchBoxArt.pick(snes, names: ["Donkey Kong Bananza"], switch2: false, loose: true), "even typed")
}
+ func testAMacGameTakesItsComputerEntryNeverAConsoleOne() {
+ let results = LaunchBoxArt.results(in: Self.card("3-ps", "The Witcher 3: Wild Hunt", "Sony Playstation 4")
+ + Self.card("2-sw", "The Witcher 3: Wild Hunt", "Nintendo Switch")
+ + Self.card("1-win", "The Witcher 3: Wild Hunt", "Windows"))
+ XCTAssertEqual(LaunchBoxArt.pick(results, names: ["The Witcher 3: Wild Hunt"], computer: true)?.path, "/games/details/1-win")
+ let both = LaunchBoxArt.results(in: Self.card("1-win", "Fixture", "Windows") + Self.card("4-mac", "Fixture", "Apple Mac OS"))
+ XCTAssertEqual(LaunchBoxArt.pick(both, names: ["Fixture"], computer: true)?.path, "/games/details/4-mac", "the Mac entry first")
+ let consoles = LaunchBoxArt.results(in: Self.card("2-sw", "Fixture", "Nintendo Switch"))
+ XCTAssertNil(LaunchBoxArt.pick(consoles, names: ["Fixture"], computer: true, loose: true))
+ XCTAssertEqual(LaunchBoxArt.pick(results, names: ["The Witcher 3: Wild Hunt"], switch2: false)?.path, "/games/details/2-sw",
+ "a Switch game still takes the Switch entry")
+ }
+
func testATypedNameTakesTheFirstSwitchResult() {
let results = LaunchBoxArt.results(in: Self.card("2-y", "Mario Kart 64", "Nintendo 64")
+ Self.card("1-x", "Super Mario Odyssey", "Nintendo Switch"))
diff --git a/Tests/NXLibraryCoreTests/MoonlightAppearanceTests.swift b/Tests/NXLibraryCoreTests/MoonlightAppearanceTests.swift
new file mode 100644
index 00000000..422e19f3
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/MoonlightAppearanceTests.swift
@@ -0,0 +1,65 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class MoonlightAppearanceTests: XCTestCase {
+ func testRemovedParticlePreferenceIsIgnoredWithoutLosingOtherSettings() throws {
+ for value in [nil, "soft", "crystal", "future-effect"] as [String?] {
+ var object = try JSONSerialization.jsonObject(with: JSONEncoder().encode(AppSettings())) as! [String: Any]
+ object["soundVolume"] = 0.25
+ object["particleStyle"] = value
+ let decoded = try JSONDecoder().decode(AppSettings.self, from: JSONSerialization.data(withJSONObject: object))
+ XCTAssertEqual(decoded.soundVolume, 0.25)
+ let saved = try JSONSerialization.jsonObject(with: JSONEncoder().encode(decoded)) as! [String: Any]
+ XCTAssertNil(saved["particleStyle"])
+ }
+ }
+
+ func testLookHasNoParticleChoice() {
+ XCTAssertFalse(SettingsCatalog.all.contains { $0.id == "particleStyle" })
+ }
+
+ func testColorCycleIsContinuousBoundedAndSpatial() {
+ let period = MoonlightChromatics.period
+ for t: Float in [0, 1, 8, 16, 24.999] {
+ let color = MoonlightChromatics.sample(x: 0.4, y: 0.6, time: t)
+ let looped = MoonlightChromatics.sample(x: 0.4, y: 0.6, time: t + period)
+ for i in 0..<3 {
+ XCTAssertTrue((0...1).contains(color[i]))
+ XCTAssertEqual(color[i], looped[i], accuracy: 0.00001)
+ }
+ }
+ let near = MoonlightChromatics.sample(x: 0.4, y: 0.6, time: period - 0.0001)
+ let after = MoonlightChromatics.sample(x: 0.4, y: 0.6, time: period + 0.0001)
+ for i in 0..<3 { XCTAssertEqual(near[i], after[i], accuracy: 0.0001) }
+ XCTAssertNotEqual(MoonlightChromatics.sample(x: 0, y: 0, time: 0),
+ MoonlightChromatics.sample(x: 1, y: 1, time: 0))
+ }
+
+ func testLocalColorsStayNearTheirOwnHueOverTheWholeCycle() {
+ let positions: [(Float, Float)] = [(0.18,0.77),(0.84,0.43),(0.5,0.3)]
+ for (x,y) in positions {
+ let initial = MoonlightChromatics.sample(x: x, y: y, time: 0)
+ for t in stride(from: Float(0), to: 180, by: 5) {
+ let value = MoonlightChromatics.sample(x: x, y: y, time: t)
+ for k in 0..<3 { XCTAssertLessThan(abs(value[k]-initial[k]), 0.025) }
+ }
+ }
+ let pink = MoonlightChromatics.sample(x: 0.18, y: 0.77, time: 0)
+ let cyan = MoonlightChromatics.sample(x: 0.84, y: 0.43, time: 0)
+ XCTAssertGreaterThan(pink.x, cyan.x)
+ XCTAssertGreaterThan(cyan.y, pink.y)
+ }
+
+ func testThemeGridStopsAtItsEdgesBeforeTheBackgroundStep() {
+ var state = ThemePickerState(themeIndex: 11, backgroundIndex: 0)
+ XCTAssertFalse(state.move(.down, count: 12))
+ XCTAssertEqual(state.step, .theme)
+ XCTAssertFalse(state.move(.right, count: 12))
+ XCTAssertEqual(state.themeIndex, 11)
+ XCTAssertTrue(state.move(.up, count: 12))
+ XCTAssertEqual(state.themeIndex, 6)
+ state.step = .background
+ XCTAssertTrue(state.move(.right, count: 4))
+ XCTAssertEqual(state.backgroundIndex, 1)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/MoreArtworkSourcesTests.swift b/Tests/NXLibraryCoreTests/MoreArtworkSourcesTests.swift
index 27ac5cb5..5a922677 100644
--- a/Tests/NXLibraryCoreTests/MoreArtworkSourcesTests.swift
+++ b/Tests/NXLibraryCoreTests/MoreArtworkSourcesTests.swift
@@ -164,13 +164,6 @@ final class MoreArtworkSourcesTests: XCTestCase {
// MARK: - TheGamesDB
- private let gamesDBSearch = """
-
-
- """
-
private let gamesDBGame = """
logo
@@ -184,15 +177,6 @@ final class MoreArtworkSourcesTests: XCTestCase {
another game
"""
- func testTheGamesDBSearchesSwitchGamesAndTakesTheSameName() {
- let url = TheGamesDBArt.searchURL(for: "Hollow Knight™")
- XCTAssertEqual(query(url)["name"], "Hollow Knight")
- XCTAssertEqual(query(url)["platform_id[]"], "4971", "Nintendo Switch")
- XCTAssertEqual(TheGamesDBArt.gameID(in: gamesDBSearch, matching: ["Hollow Knight"]), 56105)
- XCTAssertNil(TheGamesDBArt.gameID(in: gamesDBSearch, matching: ["Celeste"]))
- XCTAssertEqual(TheGamesDBArt.gameURL(id: 56105).absoluteString, "https://thegamesdb.net/game.php?id=56105")
- }
-
func testTheGamesDBGivesItsClearLogoCoverFanartAndScreenshots() {
let list = TheGamesDBArt.candidates(in: gamesDBGame, id: 56105)
let base = "https://cdn.thegamesdb.net/images/original/"
@@ -204,6 +188,23 @@ final class MoreArtworkSourcesTests: XCTestCase {
XCTAssertTrue(list.allSatisfy { $0.source.hasPrefix("TheGamesDB") })
}
+ func testTheGamesDBArtworkForMacUsesVerifiedPCFallbackInsteadOfConsole() async throws {
+ let client = RoutedClient(), query = CriticRatingQuery(name: "Fixture", platform: .mac)
+ let mac = try XCTUnwrap(DatabaseMetadataParser.gamesDBSearch(query: query, platform: "Mac OS"))
+ let pc = try XCTUnwrap(DatabaseMetadataParser.gamesDBSearch(query: query, platform: "PC"))
+ client.routes[mac.absoluteString] = Data("TheGamesDB: no results
".utf8)
+ client.routes[pc.absoluteString] = Data("""
+
+ """.utf8)
+ client.routes[TheGamesDBArt.gameURL(id: 10).absoluteString] = Data("""
+ Fixture
Platform: PC
+
+ """.utf8)
+ let found = await TheGamesDBArt.find(names: ["Fixture"], platform: .mac, client: client)
+ XCTAssertEqual(found.map(\.slot), [.cover])
+ XCTAssertEqual(found.first?.url.absoluteString, "https://cdn.thegamesdb.net/images/original/boxart/front/10-1.jpg")
+ }
+
// MARK: - Fan wikis
func testFanWikisAreSearchedLikeCommons() {
diff --git a/Tests/NXLibraryCoreTests/MoreLikeThisTests.swift b/Tests/NXLibraryCoreTests/MoreLikeThisTests.swift
index b8c10d86..4122831d 100644
--- a/Tests/NXLibraryCoreTests/MoreLikeThisTests.swift
+++ b/Tests/NXLibraryCoreTests/MoreLikeThisTests.swift
@@ -50,4 +50,42 @@ final class MoreLikeThisTests: XCTestCase {
let data = [me.id: meta(genres: ["Other"]), other.id: meta(genres: ["other"])]
XCTAssertEqual(MoreLikeThis.pick(for: me, in: [me, other], metadata: { data[$0] }), [])
}
+
+ func testSteamUsesTheSameRankingAndOnlyVisibleSteamGames() {
+ let current = CatalogGame(steam: .init(appID: 10, name: "Current"))
+ let maker = CatalogGame(steam: .init(appID: 11, name: "Bravo"))
+ let genres = CatalogGame(steam: .init(appID: 12, name: "Alpha"))
+ var hidden = CatalogGame(steam: .init(appID: 13, name: "Hidden"))
+ hidden.setHidden(true)
+ let nx = CatalogGame(nxnative: game("Native"))
+ let all = [current, maker, genres, hidden, nx]
+ let own = MoreLikeThis.Traits(developers: ["Studio"], genres: ["Action", "Puzzle"])
+ let facts: [UUID: MoreLikeThis.Traits] = [
+ current.id: own, maker.id: .init(publishers: [" studio "]),
+ genres.id: .init(genres: ["action", "puzzle"]), hidden.id: own, nx.id: own
+ ]
+ XCTAssertEqual(MoreLikeThis.pick(for: current, in: all, traits: { facts[$0.id] }), [genres.id, maker.id])
+ XCTAssertEqual(MoreLikeThis.pick(for: current, in: all, traits: { facts[$0.id] }, limit: 1), [genres.id])
+ XCTAssertEqual(MoreLikeThis.pick(for: current, in: all, traits: { _ in nil }), [])
+ }
+
+ func testSteamFallsBackToGenuinelyRelatedGamesFromOtherSources() {
+ let steam = CatalogGame(steam: .init(appID: 10, name: "Current"))
+ let otherSteam = CatalogGame(steam: .init(appID: 11, name: "Steam candidate"))
+ let related = CatalogGame(nxnative: game("Related"))
+ let hidden = CatalogGame(nxnative: game("Hidden", hidden: true))
+ let different = CatalogGame(nxnative: game("Unrelated"))
+ let candidates = [steam, otherSteam, related, hidden, different]
+ let action = MoreLikeThis.Traits(genres: ["Action"])
+ let racing = MoreLikeThis.Traits(genres: ["Racing"])
+ var facts = [steam.id: action, otherSteam.id: racing, related.id: action, hidden.id: action, different.id: racing]
+ func picks() -> [UUID] {
+ MoreLikeThis.pick(for: steam, in: candidates, fallbackToOtherSources: true, traits: { facts[$0.id] })
+ }
+ XCTAssertEqual(picks(), [related.id])
+ facts[otherSteam.id] = action
+ XCTAssertEqual(picks(), [otherSteam.id], "A matching Steam game keeps precedence")
+ facts[steam.id] = nil
+ XCTAssertTrue(picks().isEmpty)
+ }
}
diff --git a/Tests/NXLibraryCoreTests/MultiuserSaveTests.swift b/Tests/NXLibraryCoreTests/MultiuserSaveTests.swift
new file mode 100644
index 00000000..c5c471a3
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/MultiuserSaveTests.swift
@@ -0,0 +1,230 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class MultiuserSaveTests: XCTestCase {
+ private func seed(_ prefix: String, _ h: SaveTestHome, _ location: SaveLocation) throws {
+ for slot in [SaveSlot.account, .device, .user2, .user8] {
+ try h.write(prefix + "-" + slot.rawValue, location.directory(slot).appendingPathComponent("progress"))
+ }
+ try h.write("nxnative-users-1\n" + prefix, location.directory(.users))
+ }
+
+ func testBackupIncludesRegistryAndAllCommittedUsersAndVerifiesTampering() throws {
+ let h = try SaveTestHome(); defer { h.remove() }
+ let location = try h.location(), store = SaveSnapshotStore(root: h.backups)
+ try seed("saved", h, location)
+ try h.write("uncommitted", location.root.appendingPathComponent("save_user3.work/progress"))
+ let snapshot = try store.create(location: location, identity: h.identity, reason: .manual)
+ XCTAssertEqual(snapshot.schemaVersion, 2)
+ XCTAssertEqual(snapshot.presentSlots, [.account, .device, .user2, .user8, .users])
+ let registry = try XCTUnwrap(snapshot.entries.first { $0.slot == .users })
+ XCTAssertEqual(registry.path, "")
+ XCTAssertFalse(registry.isDirectory)
+ XCTAssertEqual(try store.verify(snapshotID: snapshot.id, titleID: h.tid), snapshot)
+ let backup = try store.directory(snapshotID: snapshot.id, titleID: h.tid)
+ try h.write("tampered", backup.appendingPathComponent("save.users"))
+ XCTAssertThrowsError(try store.verify(snapshotID: snapshot.id, titleID: h.tid))
+ }
+
+ func testRestoreAllUsersAndRegistryAndRemoveUsersAbsentFromNewBackup() throws {
+ let h = try SaveTestHome(); defer { h.remove() }
+ let location = try h.location(), store = SaveSnapshotStore(root: h.backups)
+ try seed("target", h, location)
+ let target = try store.create(location: location, identity: h.identity, reason: .manual)
+ try seed("current", h, location)
+ try h.write("new user", location.directory(.user3).appendingPathComponent("progress"))
+ let safety = try SaveTransaction(store: store, isRunning: { false }).restore(target, location: location, identity: h.identity)
+ XCTAssertEqual(safety.schemaVersion, 2)
+ XCTAssertTrue(safety.presentSlots.contains(.user3))
+ XCTAssertFalse(SaveFiles.exists(location.directory(.user3)))
+ XCTAssertEqual(try String(contentsOf: location.directory(.user2).appendingPathComponent("progress")), "target-user2")
+ XCTAssertEqual(try String(contentsOf: location.directory(.users)), "nxnative-users-1\ntarget")
+ }
+
+ func testLegacyRestorePreservesAdditionalUsersAndRegistry() throws {
+ let h = try SaveTestHome(); defer { h.remove() }
+ let location = try h.location(), store = SaveSnapshotStore(root: h.backups)
+ try h.write("legacy", location.directory(.account).appendingPathComponent("progress"))
+ let legacy = try store.create(location: location, identity: h.identity, reason: .manual)
+ XCTAssertEqual(legacy.schemaVersion, 1)
+ try seed("current", h, location)
+ try SaveTransaction(store: store, isRunning: { false }).restore(legacy, location: location, identity: h.identity)
+ XCTAssertEqual(try String(contentsOf: location.directory(.account).appendingPathComponent("progress")), "legacy")
+ XCTAssertFalse(SaveFiles.exists(location.directory(.device)))
+ XCTAssertEqual(try String(contentsOf: location.directory(.user8).appendingPathComponent("progress")), "current-user8")
+ XCTAssertEqual(try String(contentsOf: location.directory(.users)), "nxnative-users-1\ncurrent")
+ }
+
+ func testImportPreservesOtherUsersAndRegistryAndRefusesRegistryAsAnImportTarget() throws {
+ let h = try SaveTestHome(); defer { h.remove() }
+ let location = try h.location(), store = SaveSnapshotStore(root: h.backups)
+ try seed("current", h, location)
+ let source = h.base.appendingPathComponent("external")
+ try h.write("imported", source.appendingPathComponent("progress"))
+ XCTAssertThrowsError(try store.stageImport(source: source, slot: .users, location: location))
+ let preview = try store.stageImport(source: source, slot: .account, location: location)
+ try SaveTransaction(store: store, isRunning: { false }).importSave(preview, location: location, identity: h.identity)
+ XCTAssertEqual(try String(contentsOf: location.directory(.account).appendingPathComponent("progress")), "imported")
+ XCTAssertEqual(try String(contentsOf: location.directory(.user2).appendingPathComponent("progress")), "current-user2")
+ XCTAssertEqual(try String(contentsOf: location.directory(.users)), "nxnative-users-1\ncurrent")
+ }
+
+ func testRegistryMutationInvalidatesRestorePreview() throws {
+ let h = try SaveTestHome(); defer { h.remove() }
+ let location = try h.location(), store = SaveSnapshotStore(root: h.backups)
+ try seed("before", h, location)
+ let snapshot = try store.create(location: location, identity: h.identity, reason: .manual)
+ let preview = try store.stageRestore(snapshot, location: location)
+ try h.write("changed outside Arcane", location.directory(.users))
+ XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }).restore(preview, location: location, identity: h.identity))
+ XCTAssertEqual(try String(contentsOf: location.directory(.users)), "changed outside Arcane")
+ try store.discardRestore(preview, location: location)
+ }
+
+ func testEveryMultiuserCheckpointRecoversWithoutChangingUncommittedData() throws {
+ for checkpoint in ["journal"] + SaveSlot.allCases.map(\.rawValue) + ["committed"] {
+ let h = try SaveTestHome(); defer { h.remove() }
+ let location = try h.location(), store = SaveSnapshotStore(root: h.backups)
+ try seed("target", h, location)
+ let target = try store.create(location: location, identity: h.identity, reason: .manual)
+ try seed("current", h, location)
+ try h.write("working", location.root.appendingPathComponent("save_user2.work/file"))
+ var io = SaveFileIO()
+ io.afterMutation = { if $0 == checkpoint { throw SaveFailure.io("Interrupted") } }
+ XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }, io: io)
+ .restore(target, location: location, identity: h.identity), checkpoint)
+ let restarted = SaveTransaction(store: store, isRunning: { false })
+ try restarted.recover(location: location)
+ try restarted.recover(location: location)
+ let prefix = checkpoint == "committed" ? "target" : "current"
+ XCTAssertEqual(try String(contentsOf: location.directory(.user2).appendingPathComponent("progress")), prefix + "-user2", checkpoint)
+ XCTAssertEqual(try String(contentsOf: location.directory(.users)), "nxnative-users-1\n" + prefix, checkpoint)
+ XCTAssertEqual(try String(contentsOf: location.root.appendingPathComponent("save_user2.work/file")), "working")
+ }
+ }
+
+ func testLegacyRecoveryPreservesUsersCreatedAfterInterruption() throws {
+ let h = try SaveTestHome(); defer { h.remove() }
+ let location = try h.location(), store = SaveSnapshotStore(root: h.backups)
+ let account = location.directory(.account).appendingPathComponent("progress")
+ try h.write("target", account)
+ let snapshot = try store.create(location: location, identity: h.identity, reason: .manual)
+ try h.write("original", account)
+ var io = SaveFileIO()
+ io.afterMutation = { if $0 == "account" { throw SaveFailure.io("Interrupted") } }
+ XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }, io: io)
+ .restore(snapshot, location: location, identity: h.identity))
+ try h.write("external", location.directory(.user2).appendingPathComponent("progress"))
+ try h.write("registry", location.directory(.users))
+ try SaveTransaction(store: store, isRunning: { false }).recover(location: location)
+ XCTAssertEqual(try String(contentsOf: account), "original")
+ XCTAssertEqual(try String(contentsOf: location.directory(.user2).appendingPathComponent("progress")), "external")
+ XCTAssertEqual(try String(contentsOf: location.directory(.users)), "registry")
+ }
+
+ func testRegistryDirectoryAndLinkAndOversizedFileAreRefused() throws {
+ let h = try SaveTestHome(); defer { h.remove() }
+ let location = try h.location(), store = SaveSnapshotStore(root: h.backups)
+ let registry = location.directory(.users)
+ try FileManager.default.createDirectory(at: registry, withIntermediateDirectories: true)
+ XCTAssertThrowsError(try store.create(location: location, identity: h.identity, reason: .manual))
+ try FileManager.default.removeItem(at: registry)
+ try FileManager.default.createSymbolicLink(at: registry, withDestinationURL: h.home)
+ XCTAssertThrowsError(try store.create(location: location, identity: h.identity, reason: .manual))
+ try FileManager.default.removeItem(at: registry)
+ try Data(repeating: 0, count: 65537).write(to: registry)
+ XCTAssertThrowsError(try store.create(location: location, identity: h.identity, reason: .manual))
+ }
+
+ func testSchemaOneCannotClaimOrHideNewComponents() throws {
+ let h = try SaveTestHome(); defer { h.remove() }
+ let location = try h.location(), store = SaveSnapshotStore(root: h.backups)
+ try seed("original", h, location)
+ let snapshot = try store.create(location: location, identity: h.identity, reason: .manual)
+ let folder = try store.directory(snapshotID: snapshot.id, titleID: h.tid)
+ let manifest = folder.appendingPathComponent("manifest.json")
+ var json = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: manifest)) as? [String: Any])
+ json["schemaVersion"] = 1
+ try JSONSerialization.data(withJSONObject: json).write(to: manifest)
+ XCTAssertThrowsError(try store.verify(snapshotID: snapshot.id, titleID: h.tid))
+ }
+
+ func testLateRegistryEditIsNotOverwrittenAndJournalIsKept() throws {
+ let h = try SaveTestHome(); defer { h.remove() }
+ let location = try h.location(), store = SaveSnapshotStore(root: h.backups)
+ try seed("target", h, location)
+ let target = try store.create(location: location, identity: h.identity, reason: .manual)
+ try seed("original", h, location)
+ var io = SaveFileIO()
+ io.afterMutation = { if $0 == "before-users" { try h.write("external", location.directory(.users)) } }
+ XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }, io: io)
+ .restore(target, location: location, identity: h.identity))
+ XCTAssertTrue(SaveTransaction.needsRecovery(location: location))
+ XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }).recover(location: location))
+ XCTAssertEqual(try String(contentsOf: location.directory(.users)), "external")
+ }
+
+ func testChangedDisplacedRegistryIsNeverDeletedDuringCleanupOrRecovery() throws {
+ let h = try SaveTestHome(); defer { h.remove() }
+ let location = try h.location(), store = SaveSnapshotStore(root: h.backups)
+ try seed("target", h, location)
+ let target = try store.create(location: location, identity: h.identity, reason: .manual)
+ try seed("original", h, location)
+ var displaced: URL?
+ var io = SaveFileIO()
+ io.afterMutation = { checkpoint in
+ guard checkpoint == "users" else { return }
+ let journal = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf:
+ location.root.appendingPathComponent(".nxlibrary-save-transaction.json"))) as? [String: Any])
+ let id = try XCTUnwrap(journal["id"] as? String)
+ let file = location.root.appendingPathComponent(".nxlibrary-save-transaction-" + id).appendingPathComponent("users")
+ try h.write("changed open inode", file)
+ displaced = file
+ }
+ XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }, io: io)
+ .restore(target, location: location, identity: h.identity))
+ XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }).recover(location: location))
+ XCTAssertEqual(try String(contentsOf: XCTUnwrap(displaced)), "changed open inode")
+ XCTAssertTrue(SaveTransaction.needsRecovery(location: location))
+ }
+
+ func testInterruptedPartialCleanupRecoversAfterCommitOrRollback() throws {
+ for committed in [true, false] {
+ let h = try SaveTestHome(); defer { h.remove() }
+ let location = try h.location(), store = SaveSnapshotStore(root: h.backups)
+ try seed("target", h, location)
+ let target = try store.create(location: location, identity: h.identity, reason: .manual)
+ try seed("original", h, location)
+ func partlyRemoveStaging() throws {
+ let json = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf:
+ location.root.appendingPathComponent(".nxlibrary-save-transaction.json"))) as? [String: Any])
+ let id = try XCTUnwrap(json["id"] as? String)
+ let file = location.root.appendingPathComponent(".nxlibrary-save-transaction-" + id)
+ .appendingPathComponent("account/progress")
+ try FileManager.default.removeItem(at: file)
+ }
+ var io = SaveFileIO()
+ io.afterMutation = {
+ if $0 == (committed ? "committed" : "users") {
+ if committed { try partlyRemoveStaging() }
+ throw SaveFailure.io("Interrupted")
+ }
+ }
+ XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }, io: io)
+ .restore(target, location: location, identity: h.identity))
+ if !committed {
+ var recoveryIO = SaveFileIO()
+ recoveryIO.afterMutation = {
+ if $0 == "recovery-users" { try partlyRemoveStaging(); throw SaveFailure.io("Interrupted rollback cleanup") }
+ }
+ XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }, io: recoveryIO).recover(location: location))
+ }
+ let restarted = SaveTransaction(store: store, isRunning: { false })
+ try restarted.recover(location: location)
+ try restarted.recover(location: location)
+ XCTAssertFalse(SaveTransaction.needsRecovery(location: location))
+ XCTAssertEqual(try String(contentsOf: location.directory(.user2).appendingPathComponent("progress")),
+ (committed ? "target" : "original") + "-user2")
+ }
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift b/Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift
index 50da7eda..9a38aaf6 100644
--- a/Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift
+++ b/Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift
@@ -2,6 +2,88 @@ import XCTest
@testable import NXLibraryCore
final class NUPSourceCatalogTests: XCTestCase {
+ private let editionProbe = "title 0400F00000010001\napplication 0100F00000010000\naoc_base 0100F00000011000\nname 546573742047616d65\nbase 272\nupdate 5 280\ndlc 0100F00000011001 2\n"
+
+ func testEditionKeepsSelectedProgramApplicationAndDLCIdentitySeparate() throws {
+ let game = try NUPSourceCatalog.parse(editionProbe, nup: dir.appendingPathComponent("Edition.nup"),
+ fileSize: 400, profiles: dir.appendingPathComponent("profiles"), provisional: true)
+ let selection = try XCTUnwrap(game.base?.nupProgram)
+ XCTAssertEqual(game.baseTitleId, 0x0400F00000010001)
+ XCTAssertEqual(selection.programID, game.baseTitleId)
+ XCTAssertEqual(selection.applicationID, 0x0100F00000010000)
+ XCTAssertEqual(selection.addOnContentBaseID, 0x0100F00000011000)
+ XCTAssertEqual(selection.index, 1)
+ XCTAssertEqual(game.dlcs.first?.titleId, 0x0100F00000011001)
+ XCTAssertTrue(game.allSources.allSatisfy { $0.nupProgram == selection })
+ let updateOnly = try NUPSourceCatalog.parse(editionProbe.replacingOccurrences(of: "base 272\n", with: ""),
+ nup: dir.appendingPathComponent("Edition.nup"), fileSize: 400,
+ profiles: dir.appendingPathComponent("profiles"), provisional: true)
+ XCTAssertNil(updateOnly.base)
+ XCTAssertEqual(updateOnly.updates.first?.nupProgram, selection)
+ XCTAssertTrue(updateOnly.hasGame)
+ }
+
+ func testPartialDuplicateAndMalformedProgramMetadataAreRefused() {
+ for output in [editionProbe.replacingOccurrences(of: "aoc_base 0100F00000011000\n", with: ""),
+ editionProbe + "application 0100F00000010000\n",
+ editionProbe.replacingOccurrences(of: "aoc_base 0100F00000011000", with: "aoc_base 0"),
+ editionProbe.replacingOccurrences(of: "application 0100F00000010000", with: "application not-hex"),
+ editionProbe.replacingOccurrences(of: "dlc 0100F00000011001", with: "dlc 0400F00000011001")] {
+ XCTAssertThrowsError(try NUPSourceCatalog.parse(output, nup: dir.appendingPathComponent("Edition.nup"),
+ fileSize: 400, profiles: dir.appendingPathComponent("profiles"), provisional: true))
+ }
+ }
+
+ func testProgramMetadataPersistsAndOldSourcesRemainReadable() throws {
+ let selection = NUPProgramSelection(programID: 0x0400F00000010001,
+ applicationID: 0x0100F00000010000, addOnContentBaseID: 0x0100F00000011000)
+ let source = GameFileItem(url: dir.appendingPathComponent("Edition.nup"), kind: .base,
+ titleId: "0400F00000010001", sizeBytes: 400, sourceLayout: .container, nupProgram: selection)
+ let saved = try JSONEncoder().encode(source)
+ XCTAssertEqual(try JSONDecoder().decode(GameFileItem.self, from: saved).nupProgram, selection)
+ var legacy = try XCTUnwrap(JSONSerialization.jsonObject(with: saved) as? [String: Any])
+ legacy.removeValue(forKey: "nupProgram")
+ XCTAssertNil(try JSONDecoder().decode(GameFileItem.self,
+ from: JSONSerialization.data(withJSONObject: legacy)).nupProgram)
+ XCTAssertFalse(SourceSelection.supported([source], titleSelection: true, extractedFolders: true, nupContainers: true))
+ XCTAssertTrue(SourceSelection.supported([source], titleSelection: true, extractedFolders: true,
+ nupContainers: true, nupPrograms: true))
+ var conflict = source
+ conflict.nupProgram = NUPProgramSelection(programID: 0x0400F00000010002,
+ applicationID: selection.applicationID, addOnContentBaseID: selection.addOnContentBaseID)
+ XCTAssertFalse(SourceSelection.supported([source, conflict], titleSelection: true, extractedFolders: true,
+ nupContainers: true, nupPrograms: true))
+ XCTAssertFalse(SourceSelection.matchesNUPProgram([source], titleID: "0100F00000010000"))
+ XCTAssertTrue(SourceSelection.matchesNUPProgram([source], titleID: "0400F00000010001"))
+ }
+
+ func testCandidateBuildExplicitlySelectsProgramZeroForLegacyNUPRecords() throws {
+ let legacy = GameFileItem(url: dir.appendingPathComponent("Game.nup"), kind: .base,
+ titleId: "0100F00000010000", sizeBytes: 400, sourceLayout: .container)
+ XCTAssertEqual(SourceSelection.programIndex(for: [legacy], titleID: "0100F00000010000", nupPrograms: true), 0)
+ XCTAssertNil(SourceSelection.programIndex(for: [legacy], titleID: "0100F00000010000", nupPrograms: false))
+ let repo = dir.appendingPathComponent("engine")
+ let command = BuildCommandBuilder.make(repo: repo,
+ toolchain: EngineToolchain(python: dir.appendingPathComponent("python"), extraPath: [], isBundled: true),
+ workspace: dir, keys: nil, output: dir.appendingPathComponent("Game.app"), developerDir: dir,
+ titleId: "0400F00000010001", programIndex: 1)
+ let args = command.arguments
+ XCTAssertEqual(args[try XCTUnwrap(args.firstIndex(of: "--program")) + 1], "1")
+ XCTAssertEqual(args[try XCTUnwrap(args.firstIndex(of: "--title-id")) + 1], "0400F00000010001")
+ XCTAssertTrue(EngineSourceCapabilities(script: "'--title-id'\nimport pack_nup\npack_nup.scan(n, program)").nupPrograms)
+ XCTAssertFalse(EngineSourceCapabilities(script: "'--title-id'\nimport pack_nup\npack_nup.scan(n)").nupPrograms)
+ }
+
+ func testLegacyNUPSourcesMustStillBeOnePhysicalContainer() {
+ let first = GameFileItem(url: dir.appendingPathComponent("First.nup"), kind: .base,
+ titleId: "0100F00000010000", sizeBytes: 400, sourceLayout: .container)
+ let second = GameFileItem(url: dir.appendingPathComponent("Second.nup"), kind: .update,
+ titleId: "0100F00000010800", sizeBytes: 400, sourceLayout: .container)
+ XCTAssertFalse(SourceSelection.supported([first, second], titleSelection: true,
+ extractedFolders: true, nupContainers: true, nupPrograms: true))
+ XCTAssertNil(SourceSelection.programIndex(for: [first, second], titleID: "0100F00000010000", nupPrograms: true))
+ }
+
private var dir: URL!
override func setUpWithError() throws {
diff --git a/Tests/NXLibraryCoreTests/LibraryStoreTests.swift b/Tests/NXLibraryCoreTests/NXNativeCatalogPersistenceTests.swift
similarity index 64%
rename from Tests/NXLibraryCoreTests/LibraryStoreTests.swift
rename to Tests/NXLibraryCoreTests/NXNativeCatalogPersistenceTests.swift
index 30d64bce..5fea0f71 100644
--- a/Tests/NXLibraryCoreTests/LibraryStoreTests.swift
+++ b/Tests/NXLibraryCoreTests/NXNativeCatalogPersistenceTests.swift
@@ -1,7 +1,7 @@
import XCTest
@testable import NXLibraryCore
-final class LibraryStoreTests: XCTestCase {
+final class NXNativeCatalogPersistenceTests: XCTestCase {
private var dir: URL!
override func setUpWithError() throws {
@@ -15,7 +15,8 @@ final class LibraryStoreTests: XCTestCase {
}
func testExplicitSelectionReplacesExistingSourcesAndSurvivesLaterScans() throws {
- let store = LibraryStore(directory: dir.appendingPathComponent("catalog"))
+ let store = CatalogRepository(store: CatalogStore(directory: dir.appendingPathComponent("catalog")))
+ try store.configureSource(.nxnative, enabled: true, root: nil)
let app = dir.appendingPathComponent("Game.app")
try FileManager.default.createDirectory(at: app.appendingPathComponent("Contents"), withIntermediateDirectories: true)
try Data("plist".utf8).write(to: app.appendingPathComponent("Contents/Info.plist"))
@@ -30,13 +31,13 @@ final class LibraryStoreTests: XCTestCase {
old.sources = [GameFileItem(url: oldSource, kind: .base, sizeBytes: 3)]
old.workspacePath = dir.appendingPathComponent("old-workspace").path
old.buildCachePath = dir.appendingPathComponent("old-cache").path
- try store.save(LibraryFile(games: [old]))
+ try store.updateNXNativeGames { $0 = [old] }
var selected = old
selected.url = dir.appendingPathComponent("new-workspace")
selected.sources = [GameFileItem(url: newSource, kind: .base, sizeBytes: 3)]
selected.workspacePath = selected.url.path
selected.buildCachePath = dir.appendingPathComponent("new-cache").path
- let result = try XCTUnwrap(try store.merge(scanned: [selected], replacingSources: true).games.first)
+ let result = try XCTUnwrap(try store.mergeNXNative(scanned: [selected], replacingSources: true).nxnativeGames.first)
XCTAssertEqual(result.sources, selected.sources)
XCTAssertEqual(result.workspacePath, selected.workspacePath)
XCTAssertEqual(result.buildCachePath, selected.buildCachePath)
@@ -46,13 +47,14 @@ final class LibraryStoreTests: XCTestCase {
XCTAssertTrue(result.isFavorite)
var scanned = selected
scanned.sources = []
- let refreshed = try XCTUnwrap(try store.merge(scanned: [scanned]).games.first)
+ let refreshed = try XCTUnwrap(try store.mergeNXNative(scanned: [scanned]).nxnativeGames.first)
XCTAssertEqual(refreshed.sources, selected.sources)
XCTAssertTrue(FileManager.default.fileExists(atPath: oldSource.path), "Replacing a selection never deletes sources")
}
- func testSaveLoadAndMergePreservesSettings() throws {
- let store = LibraryStore(directory: dir)
+ func testCatalogSaveLoadAndMergePreservesSettings() throws {
+ let store = CatalogRepository(store: CatalogStore(directory: dir))
+ try store.configureSource(.nxnative, enabled: true, root: nil)
var game = PortedGame(
name: "The Legend of Zelda: Breath of the Wild",
url: URL(fileURLWithPath: "/tmp/game.app"),
@@ -65,35 +67,36 @@ final class LibraryStoreTests: XCTestCase {
)
game.status = .builtSourcesMissing
game.settings.metalHUD = true
- try store.save(LibraryFile(schemaVersion: 1, games: [game]))
+ try store.updateNXNativeGames { $0 = [game] }
let loaded = try store.load()
- XCTAssertEqual(loaded.games.first?.status, .builtSourcesMissing)
- XCTAssertEqual(loaded.games.first?.settings.metalHUD, true)
+ XCTAssertEqual(loaded.nxnativeGames.first?.status, .builtSourcesMissing)
+ XCTAssertEqual(loaded.nxnativeGames.first?.settings.metalHUD, true)
var scanned = game
scanned.status = .built
scanned.settings = GameRuntimeConfig()
- let merged = try store.merge(scanned: [scanned])
- XCTAssertEqual(merged.games.first?.status, .built)
- XCTAssertEqual(merged.games.first?.settings.metalHUD, true)
- XCTAssertEqual(merged.games.count, 1)
+ let merged = try store.mergeNXNative(scanned: [scanned])
+ XCTAssertEqual(merged.nxnativeGames.first?.status, .built)
+ XCTAssertEqual(merged.nxnativeGames.first?.settings.metalHUD, true)
+ XCTAssertEqual(merged.nxnativeGames.count, 1)
}
func testMergeKeepsFavoriteAndHidden() throws {
- let store = LibraryStore(directory: dir)
+ let store = CatalogRepository(store: CatalogStore(directory: dir))
+ try store.configureSource(.nxnative, enabled: true, root: nil)
var game = PortedGame(name: "G", url: URL(fileURLWithPath: "/tmp/g.app"),
platform: .macApp, sizeBytes: 1,
modificationDate: Date(timeIntervalSince1970: 1),
titleId: "0100000000000001")
game.isFavorite = true
game.isHidden = true
- try store.save(LibraryFile(schemaVersion: 1, games: [game]))
+ try store.updateNXNativeGames { $0 = [game] }
var scanned = game
scanned.isFavorite = false
scanned.isHidden = false
- let merged = try store.merge(scanned: [scanned])
- XCTAssertEqual(merged.games.first?.isFavorite, true)
- XCTAssertEqual(merged.games.first?.isHidden, true)
+ let merged = try store.mergeNXNative(scanned: [scanned])
+ XCTAssertEqual(merged.nxnativeGames.first?.isFavorite, true)
+ XCTAssertEqual(merged.nxnativeGames.first?.isHidden, true)
}
func testRepeatedScansKeepPendingInstallAndFailureDetails() throws {
@@ -106,7 +109,8 @@ final class LibraryStoreTests: XCTestCase {
try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0)
.write(to: app.appendingPathComponent("Contents/Info.plist"))
let importer = ImportService()
- let store = LibraryStore(directory: dir.appendingPathComponent("store"))
+ let store = CatalogRepository(store: CatalogStore(directory: dir.appendingPathComponent("store")))
+ try store.configureSource(.nxnative, enabled: true, root: nil)
var game = try XCTUnwrap(importer.scan(directories: [apps]).first.map { importer.makeGame(from: $0) })
game.isFavorite = true
game.settings.metalHUD = true
@@ -115,13 +119,13 @@ final class LibraryStoreTests: XCTestCase {
toolchain: ToolchainInfo(engineCommit: "2716f78"))
game.portingFailure = .failed
game.portingFailureReason = PortingFailureReason(kind: .diskFull, detail: "Synthetic failure")
- try store.save(LibraryFile(games: [game]))
+ try store.updateNXNativeGames { $0 = [game] }
for _ in 0..<3 {
let scanned = importer.scan(directories: [apps]).map { importer.makeGame(from: $0) }
- let merged = try store.merge(scanned: scanned)
- let saved = try XCTUnwrap(store.load().games.first)
- XCTAssertEqual(merged.games.count, 1)
+ let merged = try store.mergeNXNative(scanned: scanned)
+ let saved = try XCTUnwrap(store.load().nxnativeGames.first)
+ XCTAssertEqual(merged.nxnativeGames.count, 1)
XCTAssertEqual(saved.id, game.id)
XCTAssertEqual(saved.pendingInstall, game.pendingInstall)
XCTAssertEqual(saved.portingFailure, game.portingFailure)
@@ -131,49 +135,9 @@ final class LibraryStoreTests: XCTestCase {
}
}
- func testCorruptFileRestoresBackup() throws {
- let store = LibraryStore(directory: dir)
- var game = PortedGame(name: "G", url: URL(fileURLWithPath: "/tmp/g.app"),
- platform: .macApp, sizeBytes: 1, modificationDate: Date())
- game.titleId = "0100000000010000"
- try store.save(LibraryFile(schemaVersion: 1, games: [game]))
- try Data("not json".utf8).write(to: store.fileURL)
- let recovered = try store.load()
- XCTAssertEqual(recovered.games.count, 1)
-
- // Saving the recovered value must not replace the good backup with the
- // corrupt main file. Corrupt the main again and recover again.
- try store.save(recovered)
- try Data("still not json".utf8).write(to: store.fileURL)
- XCTAssertEqual(try store.load().games.count, 1)
- }
-
- /// A library that cannot be read and has no backup is moved aside, never written over by the next save: the
- /// games in it can still be recovered by hand (or by a newer NX Library that reads it).
- func testUnreadableLibraryWithoutBackupIsKeptAside() throws {
- let store = LibraryStore(directory: dir)
- let damaged = Data(#"{"schemaVersion": 1, "games": [{"name": "#.utf8)
- try damaged.write(to: store.fileURL)
- XCTAssertEqual(try store.load().games.count, 0)
- try store.save(LibraryFile())
- let kept = try FileManager.default.contentsOfDirectory(atPath: dir.path)
- .filter { $0.hasPrefix("library.json.damaged-") }
- XCTAssertEqual(kept.count, 1)
- XCTAssertEqual(try Data(contentsOf: dir.appendingPathComponent(kept[0])), damaged)
- }
-
- func testLoadUsesBackupWhenMainIsMissing() throws {
- let store = LibraryStore(directory: dir)
- var game = PortedGame(name: "G", url: URL(fileURLWithPath: "/tmp/g.app"),
- platform: .macApp, sizeBytes: 1, modificationDate: Date())
- game.titleId = "0100000000010000"
- try store.save(LibraryFile(schemaVersion: 1, games: [game]))
- try FileManager.default.removeItem(at: store.fileURL)
- XCTAssertEqual(try store.load().games.count, 1)
- }
-
func testMergePreservesBuildMetadataAndMarksMissingSources() throws {
- let store = LibraryStore(directory: dir)
+ let store = CatalogRepository(store: CatalogStore(directory: dir))
+ try store.configureSource(.nxnative, enabled: true, root: nil)
let sourceFile = dir.appendingPathComponent("Game [0100000000010000].nsp")
try Data("x".utf8).write(to: sourceFile)
var game = PortedGame(name: "G", url: URL(fileURLWithPath: "/tmp/G.app"),
@@ -187,7 +151,7 @@ final class LibraryStoreTests: XCTestCase {
xcodeVersion: "27.1", verified: true)
game.lastBuild = BuildRecord(endedAt: Date(), exitCode: 0,
outputPath: "/tmp/G.app", toolchainVerified: true)
- try store.save(LibraryFile(schemaVersion: 1, games: [game]))
+ try store.updateNXNativeGames { $0 = [game] }
var imported = game
imported.status = .builtSourcesMissing
@@ -195,19 +159,20 @@ final class LibraryStoreTests: XCTestCase {
imported.lastBuild = nil
imported.sources = []
- let merged = try store.merge(scanned: [imported])
- XCTAssertEqual(merged.games.first?.status, .built)
- XCTAssertEqual(merged.games.first?.toolchain.verified, true)
- XCTAssertEqual(merged.games.first?.lastBuild?.exitCode, 0)
+ let merged = try store.mergeNXNative(scanned: [imported])
+ XCTAssertEqual(merged.nxnativeGames.first?.status, .built)
+ XCTAssertEqual(merged.nxnativeGames.first?.toolchain.verified, true)
+ XCTAssertEqual(merged.nxnativeGames.first?.lastBuild?.exitCode, 0)
try FileManager.default.removeItem(at: sourceFile)
- let afterDeletion = try store.merge(scanned: [imported])
- XCTAssertEqual(afterDeletion.games.first?.status, .builtSourcesMissing)
- XCTAssertEqual(afterDeletion.games.first?.toolchain.verified, true)
+ let afterDeletion = try store.mergeNXNative(scanned: [imported])
+ XCTAssertEqual(afterDeletion.nxnativeGames.first?.status, .builtSourcesMissing)
+ XCTAssertEqual(afterDeletion.nxnativeGames.first?.toolchain.verified, true)
}
func testAttachingSourcesKeepsTheImportedAppURL() throws {
- let store = LibraryStore(directory: dir)
+ let store = CatalogRepository(store: CatalogStore(directory: dir))
+ try store.configureSource(.nxnative, enabled: true, root: nil)
let app = dir.appendingPathComponent("Old.app")
try FileManager.default.createDirectory(
at: app.appendingPathComponent("Contents"), withIntermediateDirectories: true)
@@ -221,7 +186,7 @@ final class LibraryStoreTests: XCTestCase {
titleId: "0100000000010000",
versionString: "1.9.0")
imported.status = .builtSourcesMissing
- try store.save(LibraryFile(schemaVersion: 1, games: [imported]))
+ try store.updateNXNativeGames { $0 = [imported] }
var added = PortedGame(name: "G", url: dir.appendingPathComponent("workspace"),
platform: .macApp, sizeBytes: 1, modificationDate: Date(),
@@ -232,15 +197,16 @@ final class LibraryStoreTests: XCTestCase {
added.bundleId = "org.nxnative.0100000000010000"
added.versionString = "65536"
- let merged = try store.merge(scanned: [added])
- XCTAssertEqual(merged.games.first?.url, app)
- XCTAssertEqual(merged.games.first?.status, .built)
- XCTAssertEqual(merged.games.first?.versionString, "1.9.0")
- XCTAssertEqual(merged.games.first?.bundleId, "org.nxnative.0100000000010000")
+ let merged = try store.mergeNXNative(scanned: [added])
+ XCTAssertEqual(merged.nxnativeGames.first?.url, app)
+ XCTAssertEqual(merged.nxnativeGames.first?.status, .built)
+ XCTAssertEqual(merged.nxnativeGames.first?.versionString, "1.9.0")
+ XCTAssertEqual(merged.nxnativeGames.first?.bundleId, "org.nxnative.0100000000010000")
}
func testLocateSourcesReplacesMissingRecordedSources() throws {
- let store = LibraryStore(directory: dir)
+ let store = CatalogRepository(store: CatalogStore(directory: dir))
+ try store.configureSource(.nxnative, enabled: true, root: nil)
let app = dir.appendingPathComponent("Game.app")
try FileManager.default.createDirectory(
at: app.appendingPathComponent("Contents"), withIntermediateDirectories: true)
@@ -255,7 +221,7 @@ final class LibraryStoreTests: XCTestCase {
old.status = .builtSourcesMissing
old.sources = [GameFileItem(url: oldSource, kind: .base,
titleId: "0100000000010000", sizeBytes: 1)]
- try store.save(LibraryFile(schemaVersion: 1, games: [old]))
+ try store.updateNXNativeGames { $0 = [old] }
var scanned = PortedGame(name: "G", url: dir.appendingPathComponent("workspace"),
platform: .macApp, sizeBytes: 1, modificationDate: Date(),
@@ -264,25 +230,26 @@ final class LibraryStoreTests: XCTestCase {
scanned.sources = [GameFileItem(url: newSource, kind: .base,
titleId: "0100000000010000", sizeBytes: 1)]
- let merged = try store.merge(scanned: [scanned])
- XCTAssertEqual(merged.games.first?.sources.first?.url, newSource)
- XCTAssertEqual(merged.games.first?.status, .built)
- XCTAssertEqual(merged.games.first?.url, app)
+ let merged = try store.mergeNXNative(scanned: [scanned])
+ XCTAssertEqual(merged.nxnativeGames.first?.sources.first?.url, newSource)
+ XCTAssertEqual(merged.nxnativeGames.first?.status, .built)
+ XCTAssertEqual(merged.nxnativeGames.first?.url, app)
}
func testMergeTitleIdsCaseInsensitively() throws {
- let store = LibraryStore(directory: dir)
+ let store = CatalogRepository(store: CatalogStore(directory: dir))
+ try store.configureSource(.nxnative, enabled: true, root: nil)
var old = PortedGame(name: "G", url: URL(fileURLWithPath: "/tmp/G.app"),
platform: .macApp, sizeBytes: 1, modificationDate: Date(),
titleId: "01007EF00011E000")
old.status = .builtSourcesMissing
- try store.save(LibraryFile(schemaVersion: 1, games: [old]))
+ try store.updateNXNativeGames { $0 = [old] }
var scanned = old
scanned.titleId = "01007ef00011e000"
scanned.status = .builtSourcesMissing
- let merged = try store.merge(scanned: [scanned])
- XCTAssertEqual(merged.games.count, 1)
- XCTAssertEqual(merged.games.first?.titleId, "01007ef00011e000")
+ let merged = try store.mergeNXNative(scanned: [scanned])
+ XCTAssertEqual(merged.nxnativeGames.count, 1)
+ XCTAssertEqual(merged.nxnativeGames.first?.titleId, "01007ef00011e000")
}
}
diff --git a/Tests/NXLibraryCoreTests/NativeMacApplicationTests.swift b/Tests/NXLibraryCoreTests/NativeMacApplicationTests.swift
new file mode 100644
index 00000000..60e418e7
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/NativeMacApplicationTests.swift
@@ -0,0 +1,106 @@
+import XCTest
+import Darwin
+@testable import NXLibraryCore
+
+final class NativeMacApplicationTests: XCTestCase {
+ func testIdentifiesArm64GameAndPreservesItsBundleIdentity() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ let app = try fixture.app()
+ let result = try NativeMacApplication.inspect(at: app, within: fixture.root)
+ XCTAssertEqual(result.url.path, app.path)
+ XCTAssertEqual(result.bundleIdentifier, "test.game")
+ XCTAssertEqual(result.name, "Fixture game")
+ XCTAssertEqual(result.architectures, [.arm64])
+ XCTAssertTrue(result.isDeclaredGame)
+ }
+
+ func testRecognizesIntelAndUniversalExecutables() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ let intel = try fixture.app(at: "Intel.app", cpuTypes: [0x01000007])
+ let universal = try fixture.app(at: "Universal.app", cpuTypes: [0x01000007, 0x0100000c])
+ XCTAssertEqual(try NativeMacApplication.inspect(at: intel, within: fixture.root).architectures, [.x86_64])
+ XCTAssertEqual(try NativeMacApplication.inspect(at: universal, within: fixture.root).architectures, [.x86_64, .arm64])
+ }
+
+ func testDoesNotClassifyToolsOrUnclassifiedAppsAsGames() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ for (i, category) in ["public.app-category.developer-tools", nil, "public.app-category.not-games"].enumerated() {
+ let app = try fixture.app(at: "Tool\(i).app", category: category)
+ XCTAssertFalse(try NativeMacApplication.inspect(at: app, within: fixture.root).isDeclaredGame)
+ }
+ let action = try fixture.app(at: "Action.app", category: "public.app-category.action-games")
+ XCTAssertTrue(try NativeMacApplication.inspect(at: action, within: fixture.root).isDeclaredGame)
+ }
+
+ func testRejectsNonAppsAndIosOnlyBundles() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ let invalid: [[String: Any]] = [["CFBundlePackageType": "BNDL"], ["LSRequiresIPhoneOS": true],
+ ["CFBundleSupportedPlatforms": ["iPhoneOS"]]]
+ for (i, metadata) in invalid.enumerated() {
+ let app = try fixture.app(at: "Invalid\(i).app", metadata: metadata)
+ XCTAssertThrowsError(try NativeMacApplication.inspect(at: app, within: fixture.root))
+ }
+ }
+
+ func testRejectsMissingNonExecutableAndUnsupportedCpuFiles() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ let missing = try fixture.app(at: "Missing.app")
+ try FileManager.default.removeItem(at: missing.appendingPathComponent("Contents/MacOS/fixture"))
+ XCTAssertThrowsError(try NativeMacApplication.inspect(at: missing, within: fixture.root))
+ let wrong = try fixture.app(at: "Wrong.app")
+ try Data("not Mach-O".utf8).write(to: wrong.appendingPathComponent("Contents/MacOS/fixture"))
+ XCTAssertThrowsError(try NativeMacApplication.inspect(at: wrong, within: fixture.root))
+ let unsupported = try fixture.app(at: "Unsupported.app", cpuTypes: [12])
+ XCTAssertThrowsError(try NativeMacApplication.inspect(at: unsupported, within: fixture.root))
+ let library = try fixture.app(at: "Library.app")
+ try SteamTestFixture.machHeader(cpu: 0x0100000c, fileType: 6)
+ .write(to: library.appendingPathComponent("Contents/MacOS/fixture"))
+ XCTAssertThrowsError(try NativeMacApplication.inspect(at: library, within: fixture.root))
+ }
+
+ func testRejectsExecutableTraversalAndSymlinkEscape() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ let app = try fixture.app(metadata: ["CFBundleExecutable": "../fixture"])
+ XCTAssertThrowsError(try NativeMacApplication.inspect(at: app, within: fixture.root))
+ let valid = try fixture.app(at: "Valid.app")
+ let narrowRoot = fixture.root.appendingPathComponent("narrow")
+ try FileManager.default.createDirectory(at: narrowRoot, withIntermediateDirectories: true)
+ let link = narrowRoot.appendingPathComponent("Escaping.app")
+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: valid)
+ XCTAssertThrowsError(try NativeMacApplication.inspect(at: link, within: narrowRoot))
+ }
+
+ func testRejectsOversizedMetadataAndTruncatedFatSlices() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ let app = try fixture.app()
+ try Data(repeating: 65, count: 1024 * 1024 + 1).write(to: app.appendingPathComponent("Contents/Info.plist"))
+ XCTAssertThrowsError(try NativeMacApplication.inspect(at: app, within: fixture.root))
+ let fat = try fixture.app(at: "Truncated.app", cpuTypes: [0x01000007, 0x0100000c])
+ let bytes = SteamTestFixture.fatHeader(cpus: [0x01000007, 0x0100000c]).dropLast(20)
+ try Data(bytes).write(to: fat.appendingPathComponent("Contents/MacOS/fixture"))
+ XCTAssertThrowsError(try NativeMacApplication.inspect(at: fat, within: fixture.root))
+ }
+
+ func testNonRegularMetadataDoesNotBlockWaitingForAWriter() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ let app = try fixture.app()
+ let plist = app.appendingPathComponent("Contents/Info.plist")
+ try FileManager.default.removeItem(at: plist)
+ XCTAssertEqual(mkfifo(plist.path, 0o600), 0)
+ let finished = expectation(description: "Inspection rejects a FIFO without blocking")
+ DispatchQueue.global().async {
+ do {
+ _ = try NativeMacApplication.inspect(at: app, within: fixture.root)
+ XCTFail("A FIFO is not app metadata")
+ } catch {}
+ finished.fulfill()
+ }
+ let result = XCTWaiter.wait(for: [finished], timeout: 1)
+ // Release an old blocking implementation so a failed test leaves no blocked worker behind.
+ if result != .completed {
+ let writer = Darwin.open(plist.path, O_WRONLY | O_NONBLOCK)
+ if writer >= 0 { Darwin.close(writer) }
+ }
+ XCTAssertEqual(result, .completed)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/NewestEngineTests.swift b/Tests/NXLibraryCoreTests/NewestEngineTests.swift
index c5387c94..24bc2b1b 100644
--- a/Tests/NXLibraryCoreTests/NewestEngineTests.swift
+++ b/Tests/NXLibraryCoreTests/NewestEngineTests.swift
@@ -42,7 +42,7 @@ final class NewestEngineTests: XCTestCase {
XCTAssertEqual(NewestEngine.readiness(newestLock: lock("32024.100"), testedMetal: "32023.922"),
.needsNewerApp(metal: "32024.100"))
XCTAssertEqual(NewestEngineCopy.needsNewerApp(metal: "32024.100"),
- "The newest nxnative needs Metal 32024.100, so it needs a newer NX Library.")
+ "The newest nxnative needs Metal 32024.100, so it needs a newer Arcane.")
}
func testAnUnreadableLockIsUnknown() {
@@ -270,7 +270,7 @@ final class NewestEngineTests: XCTestCase {
XCTAssertEqual(card.chip, "NEWEST ENGINE")
XCTAssertEqual(card.actionTitle, "Back to tested")
XCTAssertEqual(card.about, NewestEngineCopy.note)
- XCTAssertEqual(card.detail, "At 9c1d2e7, 12 commits ahead of the tested 4a0551e, chosen in Settings → Engine.")
+ XCTAssertEqual(card.detail, "At 9c1d2e7, 12 commits ahead of the tested 4a0551e, chosen in Settings → Setup and engine.")
XCTAssertEqual(SetupActions.engineAction(for: .checkout(head: main, dirty: false), pinned: pin, newest: main), .none)
}
@@ -291,10 +291,10 @@ final class NewestEngineTests: XCTestCase {
func testTheSentenceIsTheOneAgreed() {
XCTAssertEqual(NewestEngineCopy.note,
- "Newest nxnative, not yet tested by NX Library. It usually works, but something may not. "
- + "Its new features reach NX Library in a future version.")
+ "Newest nxnative, not yet tested by Arcane. It usually works, but something may not. "
+ + "Its new features reach Arcane in a future version.")
XCTAssertEqual(NewestEngineCopy.ahead(1), "1 commit ahead")
XCTAssertEqual(NewestEngineCopy.offer(commit: main, aheadBy: 138),
- "Build with nxnative main (9c1d2e7, 138 commits ahead) before NX Library has tested it.")
+ "Build with nxnative main (9c1d2e7, 138 commits ahead) before Arcane has tested it.")
}
}
diff --git a/Tests/NXLibraryCoreTests/PendingInstallTests.swift b/Tests/NXLibraryCoreTests/PendingInstallTests.swift
index 859ad88b..9423247d 100644
--- a/Tests/NXLibraryCoreTests/PendingInstallTests.swift
+++ b/Tests/NXLibraryCoreTests/PendingInstallTests.swift
@@ -132,15 +132,16 @@ final class PendingInstallTests: XCTestCase {
importer.scan(directories: [root]).map { importer.makeGame(from: $0) }
}
let storeDirectory = root.appendingPathComponent("catalog")
- let store = LibraryStore(directory: storeDirectory)
+ let store = CatalogRepository(store: CatalogStore(directory: storeDirectory))
+ try store.configureSource(.nxnative, enabled: true, root: nil)
var g = try XCTUnwrap(scanned().first)
g.status = .built
g.pendingInstall = p
g.portingFailure = .failed
g.portingFailureReason = PortingFailureReason(kind: .diskFull, detail: "Previous failure")
g.settings.metalHUD = true
- try store.save(LibraryFile(games: [g]))
- XCTAssertEqual(try store.merge(scanned: scanned()).games.first?.pendingInstall, p)
+ try store.updateNXNativeGames { $0 = [g] }
+ XCTAssertEqual(try store.mergeNXNative(scanned: scanned()).nxnativeGames.first?.pendingInstall, p)
var io = BuildInstallIO()
io.afterPublish = { throw CocoaError(.userCancelled) }
@@ -149,8 +150,8 @@ final class PendingInstallTests: XCTestCase {
// Simulate termination after the bundle was published and staging was
// cleaned, but before the new build record reached the catalog.
try FileManager.default.removeItem(at: p.folder)
- let reopened = LibraryStore(directory: storeDirectory)
- g = try XCTUnwrap(try reopened.merge(scanned: scanned()).games.first)
+ let reopened = CatalogRepository(store: CatalogStore(directory: storeDirectory))
+ g = try XCTUnwrap(try reopened.mergeNXNative(scanned: scanned()).nxnativeGames.first)
XCTAssertEqual(g.pendingInstall, p)
XCTAssertEqual(try PendingInstaller.install(&g), .installed)
XCTAssertNil(g.pendingInstall)
@@ -160,8 +161,8 @@ final class PendingInstallTests: XCTestCase {
XCTAssertEqual(g.lastBuild, p.record)
XCTAssertEqual(g.toolchain, p.toolchain)
XCTAssertTrue(g.settings.metalHUD)
- try reopened.save(LibraryFile(games: [g]))
- g = try XCTUnwrap(try reopened.merge(scanned: scanned()).games.first)
+ try reopened.updateNXNativeGames { $0 = [g] }
+ g = try XCTUnwrap(try reopened.mergeNXNative(scanned: scanned()).nxnativeGames.first)
XCTAssertNil(try PendingInstaller.install(&g))
XCTAssertEqual(g.lastBuild, p.record)
XCTAssertEqual(BuildOutputInstaller.version(of: p.finalApp), "1.2.0")
diff --git a/Tests/NXLibraryCoreTests/PlaySessionStoreTests.swift b/Tests/NXLibraryCoreTests/PlaySessionStoreTests.swift
index e09a6f88..3b08251c 100644
--- a/Tests/NXLibraryCoreTests/PlaySessionStoreTests.swift
+++ b/Tests/NXLibraryCoreTests/PlaySessionStoreTests.swift
@@ -1,4 +1,5 @@
import XCTest
+import Combine
@testable import NXLibraryCore
final class PlaySessionStoreTests: XCTestCase {
@@ -49,6 +50,28 @@ final class PlaySessionStoreTests: XCTestCase {
XCTAssertEqual(store.sessions.count, 1)
}
+ func testSteamSessionIsQualifiedAndOnlyItsOwnerEndsIt() {
+ let store = store()
+ let steamID = UUID()
+ let nx = game()
+ XCTAssertTrue(store.start(gameID: steamID, sourceID: "steam-570"))
+ XCTAssertFalse(store.start(gameID: steamID, sourceID: "steam-570"), "one running session per game")
+ XCTAssertTrue(store.start(for: nx))
+ now = now.addingTimeInterval(120)
+ // An nxnative app quitting ends its own session only.
+ XCTAssertEqual(store.end(bundleID: nx.bundleId).map(\.gameID), [nx.id])
+ XCTAssertTrue(store.isRunning(gameID: steamID))
+ store.heartbeat(for: steamID)
+ now = now.addingTimeInterval(60)
+ store.end(gameID: steamID)
+ XCTAssertEqual(store.totalDuration(for: steamID), 180, accuracy: 0.001)
+ XCTAssertEqual(store.sessions.first { $0.gameID == steamID }?.titleID, "steam-570")
+ XCTAssertNil(store.sessions.first { $0.gameID == steamID }?.bundleID)
+ // Reloaded from disk with the old decoder shape.
+ let reloaded = PlaySessionStore(fileURL: url, now: { [unowned self] in self.now })
+ XCTAssertEqual(reloaded.totalDuration(for: steamID), 180, accuracy: 0.001)
+ }
+
func testDanglingSessionClosesAtHeartbeat() {
let store = store()
let game = game()
@@ -113,6 +136,16 @@ final class PlaySessionStoreTests: XCTestCase {
XCTAssertTrue(store.end(bundleID: "org.nxnative.0100000000010000").isEmpty)
}
+ func testEndByGameIDReturnsTheSessionsItEnded() {
+ let store = store(), id = UUID()
+ XCTAssertTrue(store.start(gameID: id, sourceID: "steam-440"))
+ now = now.addingTimeInterval(120)
+ let ended = store.end(gameID: id)
+ XCTAssertEqual(ended.map(\.gameID), [id])
+ XCTAssertEqual(ended.first?.duration ?? 0, 120, accuracy: 0.001)
+ XCTAssertTrue(store.end(gameID: id).isEmpty)
+ }
+
private func play(_ game: PortedGame, for seconds: TimeInterval, in store: PlaySessionStore) {
XCTAssertTrue(store.start(for: game))
now = now.addingTimeInterval(seconds)
@@ -175,4 +208,168 @@ final class PlaySessionStoreTests: XCTestCase {
let decoded = try JSONDecoder().decode([PlaySession].self, from: data)
XCTAssertEqual(decoded, store.sessions)
}
+
+ // MARK: - Steam's own playtime as a baseline
+
+ private func session(_ store: PlaySessionStore, _ id: UUID, from start: TimeInterval, to end: TimeInterval?) {
+ now = Date(timeIntervalSince1970: start)
+ store.start(gameID: id, sourceID: "steam-440")
+ guard let end else { return }
+ now = Date(timeIntervalSince1970: end)
+ store.end(gameID: id)
+ }
+
+ private func external(_ duration: TimeInterval = 3_600, lastPlayed: TimeInterval? = nil,
+ since: TimeInterval = 1_000) -> ExternalPlaytime {
+ ExternalPlaytime(duration: duration, lastPlayed: lastPlayed.map { Date(timeIntervalSince1970: $0) },
+ since: Date(timeIntervalSince1970: since))
+ }
+
+ func testNoExternalKeepsTodaysTotals() {
+ let store = store(), id = UUID()
+ session(store, id, from: 1_100, to: 1_400)
+ store.setExternal([:])
+ XCTAssertEqual(store.totalDuration(for: id), 300, accuracy: 0.001)
+ XCTAssertEqual(store.lastPlayed(for: id), Date(timeIntervalSince1970: 1_100))
+ }
+
+ func testExternalAloneIsItsTotal() {
+ let store = store(), id = UUID()
+ store.setExternal([id: external()])
+ XCTAssertEqual(store.totalDuration(for: id), 3_600, accuracy: 0.001)
+ XCTAssertNil(store.lastPlayed(for: id))
+ }
+
+ func testSessionsAfterSinceAreAdded() {
+ let store = store(), id = UUID()
+ session(store, id, from: 1_100, to: 1_400)
+ store.setExternal([id: external()])
+ XCTAssertEqual(store.totalDuration(for: id), 3_900, accuracy: 0.001)
+ }
+
+ func testSessionsBeforeSinceAreNotAdded() {
+ let store = store(), id = UUID()
+ session(store, id, from: 500, to: 900)
+ store.setExternal([id: external()])
+ XCTAssertEqual(store.totalDuration(for: id), 3_600, accuracy: 0.001)
+ }
+
+ func testStraddlingSessionCountsOnlyAfterSince() {
+ let store = store(), id = UUID()
+ session(store, id, from: 800, to: 1_300)
+ store.setExternal([id: external()])
+ XCTAssertEqual(store.totalDuration(for: id), 3_900, accuracy: 0.001)
+
+ let running = UUID()
+ session(store, running, from: 800, to: nil)
+ now = Date(timeIntervalSince1970: 1_300)
+ store.setExternal([running: external()])
+ XCTAssertEqual(store.totalDuration(for: running), 3_900, accuracy: 0.001)
+ }
+
+ func testCarriedTimeIsIgnoredWithExternal() {
+ let store = store(), id = UUID()
+ for index in 0...PlaySessionStore.maxSessions {
+ let start = TimeInterval(index * 10)
+ session(store, id, from: start, to: start + 5)
+ }
+ XCTAssertFalse(store.carried.isEmpty)
+ now = Date(timeIntervalSince1970: 3_000)
+ store.setExternal([id: external(since: 2_002)])
+ XCTAssertEqual(store.totalDuration(for: id), 3_603, accuracy: 0.001)
+ }
+
+ func testLastPlayedIsTheLaterOfBoth() {
+ let store = store(), id = UUID()
+ session(store, id, from: 1_100, to: 1_400)
+ store.setExternal([id: external(lastPlayed: 2_000)])
+ XCTAssertEqual(store.lastPlayed(for: id), Date(timeIntervalSince1970: 2_000))
+ store.setExternal([id: external(lastPlayed: 900)])
+ XCTAssertEqual(store.lastPlayed(for: id), Date(timeIntervalSince1970: 1_100))
+ }
+
+ // Sessions trimmed out of the recent list after Steam's value was seen still count until Steam moves on.
+ func testTrimmedSessionsAfterSinceStillCount() {
+ let store = store(), id = UUID()
+ store.setExternal([id: external(since: 0)])
+ for index in 0...PlaySessionStore.maxSessions {
+ let start = TimeInterval(10 + index * 10)
+ session(store, id, from: start, to: start + 5)
+ }
+ XCTAssertFalse(store.carried.isEmpty)
+ let sessionsTotal = TimeInterval(PlaySessionStore.maxSessions + 1) * 5
+ XCTAssertEqual(store.totalDuration(for: id), 3_600 + sessionsTotal, accuracy: 0.001)
+
+ let reloaded = PlaySessionStore(fileURL: url, now: { [unowned self] in self.now })
+ reloaded.setExternal([id: external(since: 0)])
+ XCTAssertEqual(reloaded.totalDuration(for: id), 3_600 + sessionsTotal, accuracy: 0.001)
+
+ store.setExternal([id: external(7_200, since: 5_000)])
+ XCTAssertEqual(store.totalDuration(for: id), 7_200, accuracy: 0.001, "Steam's new value covers them")
+ }
+
+ func testTrimmedStraddlingSessionCarriesOnlyItsPartAfterSince() {
+ let store = store(), id = UUID()
+ store.setExternal([id: external(since: 3)])
+ session(store, id, from: 0, to: 10)
+ for index in 0.. PortedGame in
- var game = game
- game.id = index == 0 ? a : b
- return game
- }
- let row = SpotlightRow.build(games: games, enabledCards: [.collection, .addGame], order: [], front: b)
+ let row = SpotlightRow.build(gameIDs: [a, b], enabledCards: [.collection, .addGame], order: [], front: [b])
XCTAssertEqual(row, [.card(.collection), .card(.addGame), .game(b), .game(a)])
// The player moved Add game to the end: the porting game still follows it.
- let moved = SpotlightRow.build(games: games, enabledCards: [.collection, .addGame],
+ let moved = SpotlightRow.build(gameIDs: [a, b], enabledCards: [.collection, .addGame],
order: ["card:collection", "game:\(a.uuidString)", "game:\(b.uuidString)", "card:addGame"],
- front: b)
+ front: [b])
XCTAssertEqual(moved, [.card(.collection), .game(a), .card(.addGame), .game(b)])
// Without the card: first among the games.
- let noCard = SpotlightRow.build(games: games, enabledCards: [.collection], order: [], front: b)
+ let noCard = SpotlightRow.build(gameIDs: [a, b], enabledCards: [.collection], order: [], front: [b])
XCTAssertEqual(noCard, [.card(.collection), .game(b), .game(a)])
- XCTAssertEqual(SpotlightRow.build(games: games, enabledCards: [.collection], order: [], front: UUID()),
- SpotlightRow.build(games: games, enabledCards: [.collection], order: []))
+ XCTAssertEqual(SpotlightRow.build(gameIDs: [a, b], enabledCards: [.collection], order: [], front: [UUID()]),
+ SpotlightRow.build(gameIDs: [a, b], enabledCards: [.collection], order: []))
+ }
+
+ /// The porting game leads, then the games Steam downloads this session, in the row's order.
+ func testPortingThenDownloadsLeadTheRow() {
+ let a = UUID(), b = UUID(), c = UUID(), d = UUID()
+ let row = SpotlightRow.build(gameIDs: [a, b, c, d], enabledCards: [.collection, .addGame], order: [],
+ front: [d, b])
+ XCTAssertEqual(row, [.card(.collection), .card(.addGame), .game(d), .game(b), .game(a), .game(c)])
+ XCTAssertEqual(SpotlightRow.leaders(porting: d, downloads: [c, a, d], row: [a, b, c, d]), [d, a, c])
+ XCTAssertEqual(SpotlightRow.leaders(porting: nil, downloads: [c], row: [a, b, c, d]), [c])
+ XCTAssertEqual(SpotlightRow.leaders(porting: nil, downloads: [], row: [a, b]), [])
+ // A game no longer in the row (filtered out, or the download removed) leads nothing.
+ XCTAssertEqual(SpotlightRow.leaders(porting: UUID(), downloads: [UUID()], row: [a, b]), [])
+ }
+
+ /// A game seen downloading stays remembered for the session, also once Steam has finished it.
+ func testSessionDownloadsRememberEveryGameSeenDownloading() {
+ func steam(_ appID: UInt32, downloading: Bool, id: UUID = UUID()) -> CatalogGame {
+ var game = SteamCatalogGame(id: id, appID: appID, name: "G\(appID)")
+ game.installations = [.init(libraryURL: URL(fileURLWithPath: "/tmp/steam"),
+ contentURL: URL(fileURLWithPath: "/tmp/steam/steamapps/common/G\(appID)"),
+ availability: downloading ? .unavailable : .available,
+ isDownloading: downloading)]
+ return CatalogGame(steam: game)
+ }
+ let downloading = steam(1, downloading: true), installed = steam(2, downloading: false)
+ var session = SessionDownloads()
+ XCTAssertTrue(session.note([downloading, installed]))
+ XCTAssertEqual(session.ids, [downloading.id])
+ XCTAssertFalse(session.note([downloading, installed]))
+ let finished = steam(1, downloading: false, id: downloading.id)
+ XCTAssertFalse(session.note([finished, installed]))
+ XCTAssertEqual(session.ids, [downloading.id])
}
func testPillMovesStopAtTheLimit() {
@@ -211,4 +265,14 @@ final class PortingPresentationTests: XCTestCase {
func testLockIcon() {
XCTAssertEqual(MaterialIcon.lock.rawValue, "\u{E897}")
}
+
+ func testCatalogTileLookIsDownloadingOnlyWhileSteamDownloads() {
+ let library = URL(fileURLWithPath: "/tmp/steam"), content = URL(fileURLWithPath: "/tmp/steam/steamapps/common/G")
+ var steam = SteamCatalogGame(appID: 10, name: "Steam game")
+ steam.installations = [.init(libraryURL: library, contentURL: content, availability: .unavailable, isDownloading: true)]
+ XCTAssertEqual(PortingTileLook.make(catalog: CatalogGame(steam: steam)), .downloading)
+ steam.installations = [.init(libraryURL: library, contentURL: content, availability: .available)]
+ XCTAssertEqual(PortingTileLook.make(catalog: CatalogGame(steam: steam)), .normal)
+ XCTAssertEqual(PortingTileLook.make(catalog: CatalogGame(nxnative: CatalogTestSupport.completeLegacyGame())), .normal)
+ }
}
diff --git a/Tests/NXLibraryCoreTests/PortingProgressTests.swift b/Tests/NXLibraryCoreTests/PortingProgressTests.swift
index f5c12074..f0833267 100644
--- a/Tests/NXLibraryCoreTests/PortingProgressTests.swift
+++ b/Tests/NXLibraryCoreTests/PortingProgressTests.swift
@@ -211,6 +211,17 @@ final class BuildWarningTests: XCTestCase {
XCTAssertEqual(BuildWarningCopy.text(stage: "pack", summary: nil), "Pack finished with a warning. The log has the details.")
}
+ func testPrewarmWarningExplainsTheFirstLaunchWithoutRawToolOutput() {
+ let text = BuildWarningCopy.text(stage: "Prewarm pipelines", summary: "RAW_TOOL_FAILURE")
+ XCTAssertTrue(text.contains("The game will prepare them on its first start"))
+ XCTAssertTrue(text.contains("rebuilding tries again"))
+ XCTAssertFalse(text.contains("RAW_TOOL_FAILURE"))
+ let event = BuildEventParser.parse(
+ #"{"ev":"stage_end","name":"Prewarm pipelines","ok":true,"warn":true,"summary":"failed, the app is packed without them"}"#)
+ XCTAssertEqual(event, .stageEnd(name: "Prewarm pipelines", ok: true, elapsed: nil,
+ summary: "failed, the app is packed without them", warn: true))
+ }
+
func testAWarnedStageStillCountsAsFinished() {
var progress = PortingProgress()
progress.apply(.stage(k: 1, n: 2, name: "Mac shaders", step: nil))
diff --git a/Tests/NXLibraryCoreTests/SavePresentationTests.swift b/Tests/NXLibraryCoreTests/SavePresentationTests.swift
index 233264db..0e89859f 100644
--- a/Tests/NXLibraryCoreTests/SavePresentationTests.swift
+++ b/Tests/NXLibraryCoreTests/SavePresentationTests.swift
@@ -32,4 +32,15 @@ final class SavePresentationTests: XCTestCase {
XCTAssertTrue(SavePresentation.closedNotice.contains("Finder"))
XCTAssertTrue(SavePresentation.importWarning.contains("newer"))
}
+
+ func testLegacyAndMultiuserRestoreExplainTheirScope() {
+ let identity = SaveIdentity(titleID: "0100000000000001", gameName: "Game", version: nil, buildID: nil)
+ var snapshot = SaveSnapshot(id: UUID(), identity: identity, created: Date(), reason: .manual, presentSlots: [], entries: [])
+ XCTAssertTrue(SavePresentation.restoreMessage(snapshot, installedVersion: nil).contains("kept"))
+ snapshot.schemaVersion = 2
+ XCTAssertTrue(SavePresentation.restoreMessage(snapshot, installedVersion: nil).contains("all local users"))
+ XCTAssertTrue(SavePresentation.cloudNotice.contains("primary"))
+ XCTAssertEqual(SavePresentation.slotName(.user2), "User 2")
+ XCTAssertEqual(SavePresentation.slotName(.users), "Local users")
+ }
}
diff --git a/Tests/NXLibraryCoreTests/SelenePaletteTests.swift b/Tests/NXLibraryCoreTests/SelenePaletteTests.swift
index eb40f70b..3a0ec747 100644
--- a/Tests/NXLibraryCoreTests/SelenePaletteTests.swift
+++ b/Tests/NXLibraryCoreTests/SelenePaletteTests.swift
@@ -8,9 +8,9 @@ final class SelenePaletteTests: XCTestCase {
.appendingPathComponent("Resources/Selene/palettes.json")
}
- func testLoadsAll23Palettes() throws {
+ func testLoadsAll25Palettes() throws {
let all = try SelenePaletteCatalog.load(from: paletteURL)
- XCTAssertEqual(all.count, 23)
+ XCTAssertEqual(all.count, 25)
let ids = Set(all.map(\.id))
XCTAssertTrue(ids.isSuperset(of: ["selene", "white", "catppuccin-latte"]))
}
@@ -22,13 +22,14 @@ final class SelenePaletteTests: XCTestCase {
XCTAssertEqual(SelenePaletteCatalog.defaultID, "selene")
let rest = ordered.dropFirst().map(\.name)
XCTAssertEqual(rest, rest.sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending })
- XCTAssertEqual(Array(rest.prefix(3)), ["Catppuccin", "Catppuccin Latte", "Ethereal"])
- XCTAssertEqual(ordered.count, 23)
+ XCTAssertEqual(Array(rest.prefix(3)), ["Arcane Crystal", "Arcane Flow", "Catppuccin"])
+ XCTAssertEqual(ordered.count, 25)
}
func testSelenePaletteValues() throws {
let all = try SelenePaletteCatalog.load(from: paletteURL)
let p = SelenePaletteCatalog.resolve("selene", in: all)
+ XCTAssertEqual(p.name, AppIdentity.name)
XCTAssertEqual(p.focus, 0xFFFFFF)
XCTAssertEqual(p.onFocus, 0x111111)
XCTAssertEqual(p.glass, 0x14181F)
@@ -38,6 +39,17 @@ final class SelenePaletteTests: XCTestCase {
XCTAssertEqual(p.base.stops, [.init(color: 0x102A5C, location: 0), .init(color: 0x03081A, location: 1)])
}
+ func testBothArcaneSurfacesAreSelectableAndOldPalettesStayClassic() throws {
+ let all = try SelenePaletteCatalog.load(from: paletteURL)
+ XCTAssertEqual(SelenePaletteCatalog.resolve("selene", in: all).surface, .classic)
+ XCTAssertEqual(SelenePaletteCatalog.resolve("arcane-crystal", in: all).surface, .arcane)
+ XCTAssertEqual(SelenePaletteCatalog.resolve("arcane-flow", in: all).surface, .flow)
+ XCTAssertEqual(SelenePaletteCatalog.resolve("white", in: all).surface, .classic)
+ var settings = AppSettings()
+ settings.colorThemeID = "arcane-flow"
+ XCTAssertEqual(try JSONDecoder().decode(AppSettings.self, from: JSONEncoder().encode(settings)).colorThemeID, "arcane-flow")
+ }
+
func testUnknownIdFallsBackToSelene() throws {
let all = try SelenePaletteCatalog.load(from: paletteURL)
XCTAssertEqual(SelenePaletteCatalog.resolve("nope", in: all).id, "selene")
@@ -46,10 +58,17 @@ final class SelenePaletteTests: XCTestCase {
func testMissingFileUsesFallback() {
XCTAssertThrowsError(try SelenePaletteCatalog.load(from: URL(fileURLWithPath: "/nonexistent/palettes.json")))
XCTAssertEqual(SelenePaletteCatalog.resolve("selene", in: []), .fallback)
+ XCTAssertEqual(SelenePalette.fallback.surface, .classic)
+ XCTAssertEqual(SelenePalette.fallback.base.kind, .linear)
+ XCTAssertEqual(SelenePalette.fallback.base.stops, [
+ .init(color: 0x17244A, location: 0), .init(color: 0x0C142C, location: 0.45),
+ .init(color: 0x05080F, location: 1)
+ ])
}
func testSettingsDecodeWithoutColorTheme() throws {
let settings = try JSONDecoder().decode(AppSettings.self, from: Data("{}".utf8))
XCTAssertEqual(settings.colorThemeID, "selene")
+ XCTAssertEqual(SelenePaletteCatalog.resolve(settings.colorThemeID, in: []).surface, .classic)
}
}
diff --git a/Tests/NXLibraryCoreTests/SessionSummaryTests.swift b/Tests/NXLibraryCoreTests/SessionSummaryTests.swift
index dc9a164d..85577386 100644
--- a/Tests/NXLibraryCoreTests/SessionSummaryTests.swift
+++ b/Tests/NXLibraryCoreTests/SessionSummaryTests.swift
@@ -54,4 +54,18 @@ final class SessionSummaryTests: XCTestCase {
lastHeartbeatAt: Date(timeIntervalSince1970: 0))
XCTAssertNil(SessionSummary(session: other, game: game, total: 600))
}
+
+ func testASteamGameSummarisesLikeAnyOther() throws {
+ let steam = CatalogGame(steam: SteamCatalogGame(appID: 440, name: "Steam game"))
+ let start = Date(timeIntervalSince1970: 1_000)
+ let played = PlaySession(gameID: steam.id, titleID: "steam-440", bundleID: nil, startedAt: start,
+ endedAt: start.addingTimeInterval(1_500), lastHeartbeatAt: start)
+ let summary = try XCTUnwrap(SessionSummary(session: played, game: steam, total: 36_000))
+ XCTAssertEqual(summary.gameID, steam.id)
+ XCTAssertEqual(summary.gameName, "Steam game")
+ XCTAssertEqual(summary.thisSession, "25m")
+ XCTAssertEqual(summary.total, "10h 0m")
+ XCTAssertNil(SessionSummary(session: played, game: CatalogGame(steam: SteamCatalogGame(appID: 1, name: "Other")),
+ total: 0), "another game's session")
+ }
}
diff --git a/Tests/NXLibraryCoreTests/SettingsCatalogTests.swift b/Tests/NXLibraryCoreTests/SettingsCatalogTests.swift
index ee212c1a..472f9984 100644
--- a/Tests/NXLibraryCoreTests/SettingsCatalogTests.swift
+++ b/Tests/NXLibraryCoreTests/SettingsCatalogTests.swift
@@ -2,6 +2,8 @@ import XCTest
@testable import NXLibraryCore
final class SettingsCatalogTests: XCTestCase {
+ private static let english = AppLocale(language: .english, region: nil, preferredLanguages: ["en"])
+
func testDefaultSettingsHaveNoChanges() {
XCTAssertEqual(SettingsCatalog.changed(in: AppSettings()).map(\.id), [])
}
@@ -12,15 +14,128 @@ final class SettingsCatalogTests: XCTestCase {
XCTAssertTrue(SettingsCatalog.changed(in: settings).map(\.id).contains("interfaceSounds"))
}
- func testRumbleChangesBelongToControllersRatherThanGameDefaults() {
+ func testRumbleChangesBelongToNewGameDefaults() {
var settings = AppSettings()
settings.gameDefaults.rumble.toggle()
settings.gameDefaults.rumbleGain += 1
let changed = SettingsCatalog.changed(in: settings)
XCTAssertEqual(Set(changed.map(\.id)), ["gameDefaults.rumble", "gameDefaults.rumbleGain"])
- XCTAssertTrue(changed.allSatisfy { $0.group == .controllers })
+ XCTAssertTrue(changed.allSatisfy { $0.group == .games })
+ XCTAssertTrue(changed.allSatisfy { $0.about.contains("new ported games") })
+ }
+
+ /// Every row identity as it was before the regrouping: moving rows never renames them.
+ private static let rowIDs: Set = [
+ "appLanguage", "appRegion", "startOn", "restoreLastGame", "startInFullscreen", "checkEngineAtLaunch",
+ "refreshLibraryAtLaunch", "checkAppUpdatesAtLaunch", "introAnimation", "showButtonHints", "buttonNames",
+ "viewButtonSwitches", "spotlightCards", "startingTab", "spotlightOrder", "interfaceSounds", "soundVolume",
+ "quietLaunch", "importSeleneSounds", "colorThemeID", "wallpaperID", "settingsWallpaperID", "backgroundSizing",
+ "wallpaperBrightness", "animatedBackground", "keepWallpaperOnGames", "backgroundShade", "readableText",
+ "showClock", "reduceMotion", "iconAppearance", "boxCovers", "igdb", "steamGridDB", "launchStyle",
+ "launchMotion", "launchShade", "surprisePool", "cloudSaves", "cloudSavesPickedFolder", "showsSessionCard",
+ "hiddenGames", "gameDefaults.fullscreen", "gameDefaults.enable60FPS", "gameDefaults.isDockedMode",
+ "gameDefaults.enableMetalFXUpscale", "gameDefaults.enableMetalHUD", "gameDefaults.language",
+ "gameDefaults.renderScale", "controllerStatus", "buttonLayout", "controllerDeadzone", "gameDefaults.rumble",
+ "gameDefaults.rumbleGain", "gameFolder", "libraryFolder", "libraryRefresh", "notifyPortingEnds",
+ "steamSource", "steamRefresh", "steamFolder", "steamInBackground", "storageUsage", "buildCaches", "logs",
+ "metadataCache", "artworkCache", "saveBackups", "console", "engineFolder", "engineStatus",
+ "toolchainOverride", "upstream", "newestEngine", "compare", "keys", "setup", "diagnostics", "appUpdates",
+ "projectDocs"
+ ]
+
+ func testRowIDsAreUnchanged() {
+ XCTAssertEqual(SettingsCatalog.all.count, Self.rowIDs.count)
+ XCTAssertEqual(Set(SettingsCatalog.all.map(\.id)), Self.rowIDs)
+ }
+
+ func testEveryRowSitsInItsNewSection() {
+ let groups = Dictionary(uniqueKeysWithValues: SettingsCatalog.all.map { ($0.id, $0.group) })
+ for id in ["launchStyle", "launchMotion", "launchShade", "surprisePool", "showsSessionCard", "hiddenGames"] {
+ XCTAssertEqual(groups[id], .libraryGames, id)
+ }
+ XCTAssertEqual(groups["cloudSaves"], .cloudSaves)
+ XCTAssertEqual(groups["cloudSavesPickedFolder"], .cloudSaves)
+ XCTAssertEqual(groups["gameDefaults.rumble"], .games)
+ XCTAssertEqual(groups["gameDefaults.rumbleGain"], .games)
+ XCTAssertEqual(groups["keys"], .keys)
+ XCTAssertEqual(groups["buildCaches"], .portingStorage)
+ XCTAssertEqual(groups["console"], .console)
+ XCTAssertEqual(groups["logs"], .storage)
+ XCTAssertEqual(groups["controllerDeadzone"], .controllers)
+ }
+
+ func testSidebarGroupsInOrder() {
+ let groups = SettingsSidebarGroup.all
+ XCTAssertEqual(groups.map(\.heading), [nil, "Settings group: General", "Settings group: Library",
+ "Settings group: Porting", "Settings group: System"])
+ XCTAssertEqual(groups.map(\.sections), [
+ [.search, .changed],
+ [.startUp, .navigation, .spotlight, .soundMusic, .look, .controllers, .apiServices],
+ [.sources, .libraryGames, .storage],
+ [.engine, .keys, .library, .games, .cloudSaves, .portingStorage],
+ [.about, .console],
+ ])
+ XCTAssertEqual(groups.map(\.isPlatform), [false, false, false, true, false])
+ XCTAssertEqual(SettingsSection.allCases, groups.flatMap(\.sections), "allCases follows the sidebar")
+ }
+
+ func testPortingIsThePlatformGroup() {
+ XCTAssertEqual(SettingsSection.games.place(in: Self.english), "Porting · New games")
+ XCTAssertEqual(SettingsSection.engine.place(in: Self.english), "Porting · Setup and engine")
+ XCTAssertEqual(SettingsSection.sources.place(in: Self.english), "Sources")
+ XCTAssertEqual(SettingsSection.apiServices.title(in: Self.english), "Online services")
+ }
+
+ func testGroupResetCoversMovedRows() {
+ var settings = AppSettings()
+ settings.launchMotion.toggle()
+ settings.showsSessionCard.toggle()
+ settings.gameDefaults.rumble.toggle()
+ settings.gameDefaults.fullscreen.toggle()
+ settings.cloudSavesPickedFolder = "/Volumes/Saves"
+
+ let library = SettingsReset.reset(.libraryGames, in: settings)
+ XCTAssertEqual(library.launchMotion, AppSettings().launchMotion)
+ XCTAssertEqual(library.showsSessionCard, AppSettings().showsSessionCard)
+ XCTAssertEqual(library.gameDefaults.rumble, settings.gameDefaults.rumble, "Rumble is a new-game default")
+ XCTAssertEqual(library.cloudSavesPickedFolder, "/Volumes/Saves")
+
+ let games = SettingsReset.reset(.games, in: settings)
+ XCTAssertEqual(games.gameDefaults, AppSettings().gameDefaults)
+ XCTAssertEqual(games.launchMotion, settings.launchMotion)
+
+ XCTAssertFalse(SettingsReset.canReset(.cloudSaves))
+ XCTAssertEqual(SettingsReset.reset(.cloudSaves, in: settings).cloudSavesPickedFolder, "/Volumes/Saves")
+ }
+
+ func testOldSectionRawValuesStillDecode() {
+ for raw in ["search", "changed", "startUp", "navigation", "spotlight", "soundMusic", "look", "apiServices",
+ "controllers", "library", "games", "engine", "sources", "storage", "about"] {
+ XCTAssertNotNil(SettingsSection(rawValue: raw), raw)
+ }
}
+ func testSwitchOnlyRowsLiveInTheSwitchSections() {
+ let groups = Dictionary(uniqueKeysWithValues: SettingsCatalog.all.map { ($0.id, $0.group) })
+ XCTAssertEqual(groups["checkEngineAtLaunch"], .engine)
+ XCTAssertTrue(SettingsCatalog.all.filter { [.engine, .keys, .library, .games, .cloudSaves, .portingStorage].contains($0.group) }
+ .allSatisfy { $0.group.group.isPlatform })
+ XCTAssertEqual(groups["setup"], .engine)
+ XCTAssertEqual(groups["refreshLibraryAtLaunch"], .library)
+ XCTAssertEqual(groups["boxCovers"], .library)
+ XCTAssertNil(groups["environment"], "Compatibility in Engine re-checks the environment")
+ XCTAssertFalse(SettingsCatalog.all.contains { $0.group == .startUp && !Self.generalStartUp.contains($0.id) })
+ }
+
+ func testEnvironmentIsFoundOnTheEnginePage() {
+ XCTAssertEqual(SettingsCatalog.search("environment").first { $0.id == "engineStatus" }?.group, .engine)
+ }
+
+ private static let generalStartUp: Set = [
+ "appLanguage", "appRegion", "startOn", "restoreLastGame", "startInFullscreen",
+ "checkAppUpdatesAtLaunch", "introAnimation"
+ ]
+
func testSearchMatchesAboutText() {
let titles = SettingsCatalog.search("crops").map(\.title)
XCTAssertTrue(titles.contains("Wallpaper sizing"))
@@ -34,7 +149,7 @@ final class SettingsCatalogTests: XCTestCase {
}
func testSessionCardIsAGamesRowThatCountsAsChanged() {
- XCTAssertEqual(SettingsCatalog.search("Session card").first { $0.id == "showsSessionCard" }?.group, .games)
+ XCTAssertEqual(SettingsCatalog.search("Session card").first { $0.id == "showsSessionCard" }?.group, .libraryGames)
var settings = AppSettings()
settings.showsSessionCard = false
XCTAssertEqual(SettingsCatalog.changed(in: settings).map(\.id), ["showsSessionCard"])
@@ -42,7 +157,16 @@ final class SettingsCatalogTests: XCTestCase {
func testSearchFindsHiddenGames() {
let hits = SettingsCatalog.search("hidden")
- XCTAssertEqual(hits.first { $0.id == "hiddenGames" }?.group, .games)
+ XCTAssertEqual(hits.first { $0.id == "hiddenGames" }?.group, .libraryGames)
+ }
+
+ func testPersonalAPIConnectionsShareAGeneralSectionWithoutChangingSourceIdentity() {
+ let connections = SettingsCatalog.all.filter { ["igdb", "steamGridDB"].contains($0.id) }
+ XCTAssertEqual(connections.map(\.group), [.apiServices, .apiServices])
+ XCTAssertEqual(connections.map(\.id), ["igdb", "steamGridDB"])
+ XCTAssertFalse(SettingsSection.apiServices.group.isPlatform)
+ XCTAssertEqual(SettingsSection.sources.place(in: Self.english), "Sources")
+ XCTAssertTrue(SettingsCatalog.search("API").contains { $0.group == .apiServices })
}
func testEmptySearchReturnsNothing() {
@@ -54,7 +178,7 @@ final class SettingsCatalogTests: XCTestCase {
let controls: [(String, SettingsSection)] = [
("60 FPS", .games), ("Fullscreen", .games), ("Metal HUD", .games),
("Render scale", .games), ("App icon", .look),
- ("Stick navigation deadzone", .controllers), ("Cloud saves folder", .games),
+ ("Stick navigation deadzone", .controllers), ("Cloud saves folder", .cloudSaves),
("Engine repository", .engine), ("Game apps", .library), ("Game files", .library)
]
for (name, group) in controls {
diff --git a/Tests/NXLibraryCoreTests/SetupCheckTests.swift b/Tests/NXLibraryCoreTests/SetupCheckTests.swift
index ba123b4d..c74b63c1 100644
--- a/Tests/NXLibraryCoreTests/SetupCheckTests.swift
+++ b/Tests/NXLibraryCoreTests/SetupCheckTests.swift
@@ -89,20 +89,20 @@ final class SetupCheckTests: XCTestCase {
XCTAssertEqual(item(.engine).state, .ready)
- // After an NX Library update the engine here is older than the pin: an update, not an error.
+ // After an Arcane update the engine here is older than the pin: an update, not an error.
for behind in [true, nil] as [Bool?] {
let update = item(.engine) { $0.engine = .checkout(head: "ee369f0", dirty: false); $0.engineBehind = behind }
XCTAssertEqual(update.state, .warning, "still reopens Setup and runs with Install all")
XCTAssertEqual(update.chip, "UPDATE READY")
XCTAssertEqual(update.actionTitle, "Update")
- XCTAssertEqual(update.detail, "This NX Library uses nxnative af616f5; the engine here is at ee369f0. Update downloads it and switches to it. Games you built keep playing.")
+ XCTAssertEqual(update.detail, "This version of Arcane uses nxnative af616f5; the engine here is at ee369f0. Update downloads it and switches to it. Games you built keep playing.")
}
// A checkout ahead of the pin (or on another branch) is moved back, said as such.
let ahead = item(.engine) { $0.engine = .checkout(head: "ee369f0", dirty: false); $0.engineBehind = false }
XCTAssertEqual(ahead.state, .warning)
XCTAssertEqual(ahead.chip, "OTHER VERSION")
XCTAssertEqual(ahead.actionTitle, "Switch")
- XCTAssertEqual(ahead.detail, "The engine here is at ee369f0, not the af616f5 this NX Library is tested with. Switch moves it to af616f5. Games you built keep playing.")
+ XCTAssertEqual(ahead.detail, "The engine here is at ee369f0, not the af616f5 this version of Arcane is tested with. Switch moves it to af616f5. Games you built keep playing.")
let dirty = item(.engine) { $0.engine = .checkout(head: "ee369f0", dirty: true) }
XCTAssertEqual(dirty.state, .warning)
diff --git a/Tests/NXLibraryCoreTests/SharedGamePresentationTests.swift b/Tests/NXLibraryCoreTests/SharedGamePresentationTests.swift
new file mode 100644
index 00000000..367db6b2
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SharedGamePresentationTests.swift
@@ -0,0 +1,131 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class SharedGamePresentationTests: XCTestCase {
+ private func installation(_ name: String, availability: CatalogInstallationAvailability,
+ size: Int64) -> SteamCatalogInstallation {
+ let root = URL(fileURLWithPath: "/Volumes/\(name)/Steam")
+ let content = root.appendingPathComponent("steamapps/common/Fixture")
+ let app = content.appendingPathComponent("Game.app")
+ let native = CatalogNativeApplication(NativeMacApplication(
+ url: app, executableURL: app.appendingPathComponent("Contents/MacOS/game"),
+ bundleIdentifier: "test.\(name)", name: "Fixture", architectures: [.arm64],
+ isDeclaredGame: true, fileObservations: []))
+ return SteamCatalogInstallation(libraryURL: root, contentURL: content, applications: [native],
+ availability: availability, reportedSizeBytes: size,
+ lastObservedAt: Date(timeIntervalSince1970: 0))
+ }
+
+ func testSteamArtworkAndDetailsKeepFirstAvailableInCatalogOrderWhileAmbiguousPlayIsBlocked() {
+ var steam = SteamCatalogGame(appID: 42, name: "Fixture")
+ steam.hasBeenRecognized = true
+ steam.installations = [installation("Old", availability: .notDetected, size: 1_000_000_000),
+ installation("First", availability: .available, size: 140_000_000_000),
+ installation("Second", availability: .available, size: 2_000_000_000)]
+ let game = CatalogGame(steam: steam)
+ let expected = "/Volumes/First/Steam/steamapps/common/Fixture/Game.app"
+ XCTAssertEqual(SteamArtworkRequest(game: game, role: .square).application?.url.path, expected)
+ let page = GameDetailPresentation(steamRecord: game, metadata: nil, totalPlaytime: 0, lastPlayed: nil)
+ XCTAssertEqual(page.appPath, expected)
+ let facts = DetailsFacts.steamGame(game, metadata: nil, volumeName: "First", locale: Locale(identifier: "en_US"))
+ XCTAssertEqual(facts.first { $0.kind == .size }?.value, "140 GB")
+ let launch = CatalogGamePresentation(game: game, sourceEnabled: true)
+ XCTAssertTrue(launch.requiresReview)
+ XCTAssertNil(launch.launchTarget)
+ }
+
+ func testSteamArtworkAndDetailsIgnoreHistoricalAndUnavailableInstallations() {
+ for availability in [CatalogInstallationAvailability.unavailable, .notDetected, .sourceUnavailable, .requiresReview] {
+ var steam = SteamCatalogGame(appID: 42, name: "Fixture")
+ steam.hasBeenRecognized = true
+ steam.installations = [installation("Old", availability: availability, size: 140_000_000_000)]
+ let game = CatalogGame(steam: steam)
+ XCTAssertNil(SteamArtworkRequest(game: game, role: .square).application)
+ let page = GameDetailPresentation(steamRecord: game, metadata: nil, totalPlaytime: 0, lastPlayed: nil)
+ XCTAssertEqual(page.appPath, "")
+ XCTAssertEqual(DetailsFacts.steamGame(game, metadata: nil, volumeName: "Old"), [])
+ XCTAssertNil(CatalogGamePresentation(game: game, sourceEnabled: true).launchTarget)
+ }
+ }
+
+ func testSteamPresentationKeepsIdentityPersonalOverridesAndHistory() throws {
+ let body = Data("""
+ {"10":{"success":true,"data":{"steam_appid":10,"short_description":"Store text","genres":[{"description":"Strategy"}],"publishers":["Studio"],"release_date":{"date":"23 mag 2023"}}}}
+ """.utf8)
+ let facts = try SteamMetadata.decode(body, appID: 10, language: "italian")
+ let record = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "Fixture"))
+ let result = LibraryPresentation(game: record, steamMetadata: facts,
+ overrides: [.description: "Personal", .genres: "Puzzle, Adventure"],
+ totalPlaytime: 7200, lastPlayed: nil)
+ XCTAssertEqual(result.title, "Fixture")
+ XCTAssertEqual(result.platform, "Steam")
+ XCTAssertEqual(result.console, "Steam")
+ XCTAssertEqual(result.summary, "Personal")
+ XCTAssertEqual(result.publisher, "Studio")
+ XCTAssertEqual(result.releaseYear, "2023")
+ XCTAssertEqual(result.genres.count, 2)
+ XCTAssertEqual(result.playtime, "2h 0m")
+ XCTAssertFalse(result.sourcesDetached)
+ }
+ func testNXDisplayRemainsEqualThroughCommonBoundary() {
+ let game = CatalogTestSupport.completeLegacyGame()
+ let direct = LibraryPresentation(game: game, metadata: nil, totalPlaytime: 100, lastPlayed: nil)
+ let common = LibraryPresentation(game: CatalogGame(nxnative: game), steamMetadata: nil,
+ totalPlaytime: 100, lastPlayed: nil)
+ XCTAssertEqual(common, direct)
+ }
+ func testPersonalFieldsRemainVisibleWithoutRemoteMetadata() {
+ let game = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "Local title"))
+ let result = LibraryPresentation(game: game, steamMetadata: nil, overrides: [.description: "Offline choice", .publisher: "Mine"],
+ totalPlaytime: 0, lastPlayed: nil)
+ XCTAssertEqual(result.summary, "Offline choice")
+ XCTAssertEqual(result.publisher, "Mine")
+ XCTAssertEqual(result.title, "Local title")
+ }
+ func testSquareRoleDoesNotUsePortraitArtwork() {
+ XCTAssertEqual(LibraryArtworkRole.square.slot, .icon)
+ XCTAssertEqual(LibraryArtworkRole.cover.slot, .cover)
+ XCTAssertEqual(LibraryArtworkRole.hero.slot, .background)
+ XCTAssertEqual(LibraryArtworkRole.logo.slot, .logo)
+ }
+ func testCommonOptionsHaveSameOrderAndSourceActionsStaySeparate() {
+ XCTAssertEqual(CatalogGameOptions.commonRows(origin: .spotlight),
+ [.play, .editDetails, .move, .favorite, .hidden, .showInFinder])
+ XCTAssertEqual(CatalogGameOptions.commonRows(origin: .collection),
+ [.play, .editDetails, .favorite, .hidden, .showInFinder])
+ let options = SteamOptionsPresentation(canPlay: true, hasApp: true)
+ let steam = Set([GameOptionsLevel.main, .editDetails].flatMap { level in
+ options.entries(level: level, origin: .spotlight).compactMap { entry -> GameOptionsRow? in
+ if case .row(let row) = entry { return row } else { return nil }
+ }
+ })
+ XCTAssertTrue(steam.isDisjoint(with: [.fullscreen, .frameRate, .consoleMode, .rebuild, .openSaves, .removeSources,
+ .cheats, .mods, .attachSources, .openLog]))
+ }
+
+ func testSteamPagePresentationClaimsNothingFromNxnative() throws {
+ let body = Data("""
+ {"10":{"success":true,"data":{"steam_appid":10,"short_description":"Store text","genres":[{"description":"Strategy"}],"developers":["Dev Studio"],"publishers":["Studio"],"release_date":{"date":"23 mag 2023"}}}}
+ """.utf8)
+ let facts = try SteamMetadata.decode(body, appID: 10, language: "italian")
+ let record = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "Fixture"))
+ let other = CatalogGame(steam: SteamCatalogGame(appID: 20, name: "Other"))
+ let page = GameDetailPresentation(steamRecord: record, metadata: facts, overrides: [.publisher: "Mine"],
+ totalPlaytime: 60, lastPlayed: nil,
+ libraryGames: [record, other], playtimeByGame: [other.id: 120])
+ XCTAssertEqual(page.console, "Steam")
+ XCTAssertEqual(page.description, "Store text")
+ XCTAssertEqual(page.released, "23 mag 2023")
+ XCTAssertEqual(page.releaseYear, "2023")
+ XCTAssertEqual(page.developerLine, "Dev Studio")
+ XCTAssertEqual(page.publisher, "Mine")
+ XCTAssertEqual(page.rank, "#2 of 2")
+ XCTAssertEqual(page.storeURL?.absoluteString, "https://store.steampowered.com/app/10/")
+ XCTAssertFalse(page.canPlay); XCTAssertFalse(page.canRebuild); XCTAssertFalse(page.sourcesDetached)
+ XCTAssertEqual(page.savePath, ""); XCTAssertEqual(page.engineCommitShort, "—")
+ // Facts delivered for another game never reach this page.
+ let stray = GameDetailPresentation(steamRecord: other, metadata: facts, totalPlaytime: 0, lastPlayed: nil)
+ XCTAssertEqual(stray.description, "")
+ XCTAssertNil(stray.rank)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/ShellOverlayInputTests.swift b/Tests/NXLibraryCoreTests/ShellOverlayInputTests.swift
new file mode 100644
index 00000000..f13036d0
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/ShellOverlayInputTests.swift
@@ -0,0 +1,25 @@
+import XCTest
+
+/// Screens read the keyboard through their own `NSEvent` monitors. A shell overlay drawn on top of them
+/// (the update offer, the welcome) must make every such monitor let the key go, or Return reaches the screen
+/// underneath: a game starts instead of the overlay's button.
+final class ShellOverlayInputTests: XCTestCase {
+ private var views: URL {
+ URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ .appendingPathComponent("Sources/NXLibrary/Views")
+ }
+
+ func testEveryMonitorThatYieldsToTheUpdateOfferYieldsToTheWelcome() throws {
+ let files = FileManager.default.enumerator(at: views, includingPropertiesForKeys: nil)?
+ .compactMap { $0 as? URL }.filter { $0.pathExtension == "swift" } ?? []
+ var missing: [String] = []
+ for file in files {
+ let text = try String(contentsOf: file, encoding: .utf8)
+ let offer = text.components(separatedBy: "!viewModel.isUpdateOfferOpen").count - 1
+ let welcome = text.components(separatedBy: "!viewModel.isWelcomeOpen").count - 1
+ if offer != welcome { missing.append("\(file.lastPathComponent): \(offer) vs \(welcome)") }
+ }
+ XCTAssertFalse(files.isEmpty)
+ XCTAssertEqual(missing.sorted(), [])
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SpotlightEntranceTests.swift b/Tests/NXLibraryCoreTests/SpotlightEntranceTests.swift
new file mode 100644
index 00000000..3f0365cc
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SpotlightEntranceTests.swift
@@ -0,0 +1,167 @@
+import CoreGraphics
+import XCTest
+@testable import NXLibraryCore
+
+final class SpotlightEntranceTests: XCTestCase {
+ private let row: CGFloat = 1760
+
+ /// Tiles of side 174 with a gap of 26, the first one starting at `start`.
+ private func tiles(_ count: Int, from start: CGFloat = 80) -> [ClosedRange] {
+ (0.. String = { SpotlightItem.game($0).key }
+ let saved = [key(a), key(steam), key(hidden), key(b), SpotlightItem.card(.mods).key]
+ // Only A and B are visible; Steam is disabled, another game hidden,
+ // and Mods disabled. All still belong to the saved layout.
+ let changed = SpotlightRow.saving(visibleOrder: [key(b), key(a)],
+ gameIDs: [a, steam, hidden, b], previousOrder: saved)
+ let restored = SpotlightRow.build(gameIDs: [a, steam, hidden, b], enabledCards: [], order: changed)
+ XCTAssertEqual(restored, [.game(b), .game(steam), .game(hidden), .game(a)])
+ XCTAssertTrue(changed.contains(SpotlightItem.card(.mods).key))
+ let back = SpotlightRow.saving(visibleOrder: [key(a), key(b)], gameIDs: [a, steam, hidden, b], previousOrder: changed)
+ XCTAssertEqual(SpotlightRow.build(gameIDs: [a, steam, hidden, b], enabledCards: [], order: back),
+ [.game(a), .game(steam), .game(hidden), .game(b)])
+ }
func testFilteredMoveKeepsHiddenSlots() {
// Saved A…E as D,A,B,C,E; Installed shows A,C,E; C moved first.
let merged = SpotlightRow.merging(visibleOrder: ["C", "A", "E"],
@@ -139,3 +154,34 @@ final class SpotlightRowMergeTests: XCTestCase {
}
}
+
+/// A game that starts becomes the first game of the row, the rest of a saved order staying as it was.
+final class SpotlightRowPlayedTests: XCTestCase {
+ private let a = UUID(), b = UUID(), c = UUID(), d = UUID()
+ private func key(_ id: UUID) -> String { SpotlightItem.game(id).key }
+ private var cards: [String] { SpotlightCard.allCases.map { SpotlightItem.card($0).key } }
+
+ func testPlayedGameBecomesTheFirstGame() {
+ let order = SpotlightRow.playing(c, previousOrder: cards + [key(a), key(b), key(c)])
+ XCTAssertEqual(SpotlightRow.build(gameIDs: [a, b, c], enabledCards: [], order: order), [.game(c), .game(a), .game(b)])
+ XCTAssertEqual(order, cards + [key(c), key(a), key(b)])
+ }
+
+ func testCardsPlacedAmongGamesStayWhereTheyAre() {
+ let mods = SpotlightItem.card(.mods).key
+ XCTAssertEqual(SpotlightRow.playing(b, previousOrder: [key(a), mods, key(b)]), [key(b), key(a), mods])
+ }
+
+ func testAGameNotInTheSavedOrderIsPlacedFirst() {
+ XCTAssertEqual(SpotlightRow.playing(d, previousOrder: cards + [key(a), key(b)]), cards + [key(d), key(a), key(b)])
+ }
+
+ func testNoSavedOrderStaysEmptyBecauseRecencyAlreadyLeads() {
+ XCTAssertEqual(SpotlightRow.playing(a, previousOrder: []), [])
+ }
+
+ func testTheFirstGameStaysPut() {
+ let order = cards + [key(a), key(b)]
+ XCTAssertEqual(SpotlightRow.playing(a, previousOrder: order), order)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SpotlightStateTests.swift b/Tests/NXLibraryCoreTests/SpotlightStateTests.swift
index 4e867982..4761ebf6 100644
--- a/Tests/NXLibraryCoreTests/SpotlightStateTests.swift
+++ b/Tests/NXLibraryCoreTests/SpotlightStateTests.swift
@@ -152,6 +152,74 @@ final class SpotlightStateTests: XCTestCase {
XCTAssertNil(SpotlightState(selectedKey: SpotlightItem.card(.collection).key).selectedGameID)
XCTAssertNil(SpotlightState().selectedGameID)
}
+ // MARK: - Achievements card
+
+ private func gameState(_ focus: SpotlightFocusArea) -> SpotlightState {
+ var state = SpotlightState(selectedKey: SpotlightItem.game(UUID()).key)
+ state.focus = focus
+ return state
+ }
+
+ func testDownFromStripEntersAchievements() {
+ var state = gameState(.strip)
+ XCTAssertTrue(state.moveDown(selectedIsGame: true, screenshotCount: 3, actionCount: 4, hasAchievements: true))
+ XCTAssertEqual(state.focus, .achievements)
+ }
+
+ func testDownFromAchievementsEntersActions() {
+ var state = gameState(.achievements)
+ XCTAssertTrue(state.moveDown(selectedIsGame: true, screenshotCount: 3, actionCount: 4, hasAchievements: true))
+ XCTAssertEqual(state.focus, .actions)
+ XCTAssertEqual(state.actionIndex, 0)
+ }
+
+ func testUpFromActionsFirstRowReturnsToAchievements() {
+ var state = gameState(.actions)
+ state.actionIndex = 1
+ XCTAssertTrue(state.moveUp(screenshotCount: 3, actionCount: 4, hasAchievements: true))
+ XCTAssertEqual(state.focus, .achievements)
+ }
+
+ func testUpFromAboutSkipsTheCardBesideIt() {
+ var about = gameState(.about)
+ XCTAssertTrue(about.moveUp(screenshotCount: 3, actionCount: 4, hasAchievements: true))
+ XCTAssertEqual(about.focus, .strip)
+ }
+
+ func testReadMoreAndTheCardSitSideBySide() {
+ var state = gameState(.about)
+ XCTAssertTrue(state.moveSideways(by: 1, screenshotCount: 3, actionCount: 4, readMore: true, hasAchievements: true))
+ XCTAssertEqual(state.focus, .achievements)
+ XCTAssertTrue(state.moveSideways(by: -1, screenshotCount: 3, actionCount: 4, readMore: true, hasAchievements: true))
+ XCTAssertEqual(state.focus, .about)
+ // Without the card Right goes to the actions, as before.
+ XCTAssertTrue(state.moveSideways(by: 1, screenshotCount: 3, actionCount: 4, readMore: true))
+ XCTAssertEqual(state.focus, .actions)
+ }
+
+ func testWithoutAchievementsThePathIsUnchanged() {
+ var state = gameState(.strip)
+ state.moveDown(selectedIsGame: true, screenshotCount: 3, actionCount: 4)
+ XCTAssertEqual(state.focus, .actions)
+ state.moveUp(screenshotCount: 3, actionCount: 4)
+ XCTAssertEqual(state.focus, .strip)
+ }
+
+ func testUpFromAchievementsWithoutScreenshotsGoesToPills() {
+ var state = gameState(.achievements)
+ XCTAssertTrue(state.moveUp(screenshotCount: 0, actionCount: 4, hasAchievements: true))
+ XCTAssertEqual(state.focus, .pills)
+ var pills = gameState(.pills)
+ pills.moveDown(selectedIsGame: true, screenshotCount: 0, actionCount: 4, hasAchievements: true)
+ XCTAssertEqual(pills.focus, .achievements)
+ }
+
+ func testSidewaysOnAchievementsWithoutReadMoreDoesNothing() {
+ var state = gameState(.achievements)
+ XCTAssertFalse(state.moveSideways(by: 1, screenshotCount: 3, actionCount: 4, hasAchievements: true))
+ XCTAssertFalse(state.moveSideways(by: -1, screenshotCount: 3, actionCount: 4, hasAchievements: true))
+ XCTAssertEqual(state.focus, .achievements)
+ }
}
final class SpotlightLiftTests: XCTestCase {
@@ -388,4 +456,5 @@ final class SpotlightLiftTests: XCTestCase {
XCTAssertEqual(s.focus, .strip)
XCTAssertEqual(s.stripIndex, 4)
}
+
}
diff --git a/Tests/NXLibraryCoreTests/SteamAchievementRarityTests.swift b/Tests/NXLibraryCoreTests/SteamAchievementRarityTests.swift
new file mode 100644
index 00000000..20dc76a4
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamAchievementRarityTests.swift
@@ -0,0 +1,171 @@
+import XCTest
+import ImageIO
+import UniformTypeIdentifiers
+@testable import NXLibraryCore
+
+final class SteamAchievementRarityTests: XCTestCase {
+ private var root: URL!
+ private actor Calls { var count = 0; func bump() { count += 1 } }
+
+ override func setUpWithError() throws {
+ root = FileManager.default.temporaryDirectory.appendingPathComponent("SteamRarity-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ }
+
+ override func tearDown() {
+ try? FileManager.default.removeItem(at: root)
+ super.tearDown()
+ }
+
+ private let body = Data(#"{"achievementpercentages":{"achievements":[{"name":"A","percent":"80.0"},{"name":"B","percent":4.5}]}}"#.utf8)
+
+ func testDecodesNumbersAndStrings() throws {
+ XCTAssertEqual(try SteamAchievementRarity.decode(body), ["A": 80.0, "B": 4.5])
+ }
+
+ /// A percent that is not a number (`"nan"`, `"inf"`) is no rarity: clamping left NaN as it was.
+ func testANonFinitePercentIsLeftOut() throws {
+ let body = Data(#"{"achievementpercentages":{"achievements":[{"name":"A","percent":"nan"},{"name":"B","percent":"inf"},{"name":"C","percent":"12.5"}]}}"#.utf8)
+ XCTAssertEqual(try SteamAchievementRarity.decode(body), ["C": 12.5])
+ }
+
+ /// A file that failed a moment ago fails at once, without waiting for a free download behind six others.
+ func testARecentFailureDoesNotWaitForASlot() async throws {
+ let png = try Self.png()
+ let failing = Calls()
+ let service = SteamMetadataService(directory: root, transport: { url in
+ if url.lastPathComponent == "bad.jpg" { await failing.bump(); throw URLError(.badServerResponse) }
+ try await Task.sleep(nanoseconds: 400_000_000)
+ return png
+ })
+ let first = await service.achievementIcon(appID: 7, file: "bad.jpg")
+ XCTAssertNil(first)
+ let busy = (0..<6).map { index in Task { await service.achievementIcon(appID: 7, file: "busy\(index).jpg") } }
+ try await Task.sleep(nanoseconds: 50_000_000)
+ let started = Date()
+ let again = await service.achievementIcon(appID: 7, file: "bad.jpg")
+ XCTAssertNil(again)
+ XCTAssertLessThan(Date().timeIntervalSince(started), 0.2)
+ let count = await failing.count
+ XCTAssertEqual(count, 1)
+ for task in busy { _ = await task.value }
+ }
+
+ func testMalformedThrows() {
+ XCTAssertThrowsError(try SteamAchievementRarity.decode(Data("{}".utf8)))
+ XCTAssertThrowsError(try SteamAchievementRarity.decode(Data("".utf8)))
+ }
+
+ func testIconURLRefusesPaths() {
+ XCTAssertEqual(SteamAchievementRarity.iconURL(appID: 7, file: "ab12.jpg")?.absoluteString,
+ "https://shared.akamai.steamstatic.com/community_assets/images/apps/7/ab12.jpg")
+ XCTAssertNil(SteamAchievementRarity.iconURL(appID: 7, file: "../x.jpg"))
+ XCTAssertNil(SteamAchievementRarity.iconURL(appID: 7, file: "a/b.jpg"))
+ XCTAssertNil(SteamAchievementRarity.iconURL(appID: 7, file: "x.exe"))
+ XCTAssertNil(SteamAchievementRarity.iconURL(appID: 7, file: ".jpg"))
+ }
+
+ func testOnlyThePercentagesPathIsAllowed() {
+ XCTAssertTrue(SteamMetadataService.allowed(SteamAchievementRarity.url(appID: 7)))
+ XCTAssertFalse(SteamMetadataService.allowed(URL(string: "https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/")!))
+ XCTAssertFalse(SteamMetadataService.allowed(URL(string: "http://api.steampowered.com/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/?gameid=7")!))
+ }
+
+ func testPercentsAreCachedForADay() async {
+ let calls = Calls(), body = body
+ let service = SteamMetadataService(directory: root, transport: { _ in await calls.bump(); return body })
+ let first = await service.achievementPercents(appID: 7)
+ let second = await service.achievementPercents(appID: 7)
+ XCTAssertEqual(first, ["A": 80, "B": 4.5])
+ XCTAssertEqual(second, first)
+ let count = await calls.count
+ XCTAssertEqual(count, 1)
+ }
+
+ func testOfflineKeepsTheStaleCache() async throws {
+ let file = root.appendingPathComponent("7/achievement-percents.json")
+ try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(#"{"fetchedAt":0,"percents":{"A":12}}"#.utf8).write(to: file)
+ let service = SteamMetadataService(directory: root, transport: { _ in throw URLError(.notConnectedToInternet) })
+ let percents = await service.achievementPercents(appID: 7)
+ XCTAssertEqual(percents, ["A": 12])
+ }
+
+ func testNothingCachedAndOfflineIsNil() async {
+ let service = SteamMetadataService(directory: root, transport: { _ in throw URLError(.notConnectedToInternet) })
+ let percents = await service.achievementPercents(appID: 7)
+ XCTAssertNil(percents)
+ }
+
+ func testIconIsCachedAndReused() async throws {
+ let calls = Calls(), png = try Self.png()
+ let service = SteamMetadataService(directory: root, transport: { _ in await calls.bump(); return png })
+ let first = await service.achievementIcon(appID: 7, file: "ab.jpg")
+ let second = await service.achievementIcon(appID: 7, file: "ab.jpg")
+ XCTAssertEqual(first?.lastPathComponent, "ab.jpg")
+ XCTAssertEqual(second, first)
+ let count = await calls.count
+ XCTAssertEqual(count, 1)
+ }
+
+ /// A screen of icons asks for more than the six downloads at once: the rest wait their turn instead of
+ /// failing, and no more than six run together.
+ func testIconsBeyondTheConcurrencyLimitWaitTheirTurn() async throws {
+ let gauge = Gauge(), png = try Self.png()
+ let service = SteamMetadataService(directory: root, transport: { _ in
+ await gauge.enter()
+ try await Task.sleep(nanoseconds: 30_000_000)
+ await gauge.leave()
+ return png
+ })
+ let icons = await withTaskGroup(of: URL?.self) { group in
+ for index in 0..<15 { group.addTask { await service.achievementIcon(appID: 7, file: "icon\(index).jpg") } }
+ return await group.reduce(into: [URL?]()) { $0.append($1) }
+ }
+ XCTAssertEqual(icons.compactMap { $0 }.count, 15)
+ let peak = await gauge.peak
+ XCTAssertLessThanOrEqual(peak, 6)
+ }
+
+ /// A request still waiting for its turn ends when its row goes away.
+ func testAWaitingIconRequestCanBeCancelled() async throws {
+ let png = try Self.png()
+ let service = SteamMetadataService(directory: root, transport: { _ in
+ try await Task.sleep(nanoseconds: 300_000_000)
+ return png
+ })
+ let busy = (0..<6).map { index in Task { await service.achievementIcon(appID: 7, file: "busy\(index).jpg") } }
+ try await Task.sleep(nanoseconds: 50_000_000)
+ let waiting = Task { await service.achievementIcon(appID: 7, file: "late.jpg") }
+ try await Task.sleep(nanoseconds: 50_000_000)
+ let started = Date()
+ waiting.cancel()
+ let late = await waiting.value
+ XCTAssertNil(late)
+ XCTAssertLessThan(Date().timeIntervalSince(started), 0.2)
+ for task in busy { _ = await task.value }
+ }
+
+ private actor Gauge {
+ var current = 0, peak = 0
+ func enter() { current += 1; peak = max(peak, current) }
+ func leave() { current -= 1 }
+ }
+
+ func testAnIconThatIsNotAnImageIsNotKept() async {
+ let service = SteamMetadataService(directory: root, transport: { _ in Data("nope".utf8) })
+ let icon = await service.achievementIcon(appID: 7, file: "ab.jpg")
+ XCTAssertNil(icon)
+ }
+
+ private static func png() throws -> Data {
+ let context = CGContext(data: nil, width: 4, height: 4, bitsPerComponent: 8, bytesPerRow: 0,
+ space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
+ context.setFillColor(CGColor(red: 1, green: 0, blue: 0, alpha: 1)); context.fill(CGRect(x: 0, y: 0, width: 4, height: 4))
+ let data = NSMutableData()
+ let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil)!
+ CGImageDestinationAddImage(destination, context.makeImage()!, nil)
+ CGImageDestinationFinalize(destination)
+ return data as Data
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamAchievementReaderTests.swift b/Tests/NXLibraryCoreTests/SteamAchievementReaderTests.swift
new file mode 100644
index 00000000..0acd62e6
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamAchievementReaderTests.swift
@@ -0,0 +1,197 @@
+import XCTest
+@testable import NXLibraryCore
+
+/// Made-up schemas and stats in Steam's layout; no Valve content.
+final class SteamAchievementReaderTests: XCTestCase {
+ private typealias E = [(String, Any)]
+ private let app: UInt32 = 4242
+ private let account: UInt32 = 1234
+
+ private func bit(_ api: String, names: [String: String], descs: [String: String] = [:], hidden: Bool = false,
+ icon: String? = "c.jpg", gray: String? = "g.jpg") -> E {
+ var display: E = [("name", names.map { ($0.key, $0.value as Any) }),
+ ("desc", descs.map { ($0.key, $0.value as Any) }),
+ ("hidden", hidden ? "1" : "0")]
+ if let icon { display.append(("icon", icon)) }
+ if let gray { display.append(("icon_gray", gray)) }
+ return [("name", api), ("display", display)]
+ }
+
+ private func schema(_ stats: [(String, E)]) -> [KeyValuesEntry] {
+ let tree: E = [("\(app)", [("stats", stats.map { ($0.0, $0.1 as Any) } as E), ("gamename", "Game"), ("version", Int32(3))] as E)]
+ return try! SteamBinaryKeyValues.parse(BinaryKV.data(tree))
+ }
+
+ private func stats(_ times: [(stat: String, bit: String, time: Int32)], extra: Bool = false) -> [KeyValuesEntry] {
+ var byStat: [String: E] = [:]
+ for t in times { byStat[t.stat, default: []].append((t.bit, t.time)) }
+ var cache: E = [("crc", Int32(99))]
+ if extra { cache.append(("PendingChanges", Int32(0))) }
+ for (stat, list) in byStat.sorted(by: { $0.key < $1.key }) {
+ cache.append((stat, [("data", Int32(7)), ("AchievementTimes", list)] as E))
+ }
+ return try! SteamBinaryKeyValues.parse(BinaryKV.data([("cache", cache)]))
+ }
+
+ private func read(_ schema: [KeyValuesEntry], _ stats: [KeyValuesEntry], language: String = "italian") throws -> [SteamAchievement] {
+ try SteamAchievementReader.achievements(schema: schema, stats: stats, appID: app, language: language)
+ }
+
+ func testReadsNamesInTheLanguageWithEnglishFallback() throws {
+ let rows = try read(schema([("1", [("type", "4"), ("bits", [
+ ("0", bit("A", names: ["english": "First", "italian": "Primo"], descs: ["english": "Do it", "italian": "Fallo"])),
+ ("1", bit("B", names: ["english": "Second"], descs: ["english": "Again"])),
+ ("2", bit("C", names: [:])),
+ ] as E)])]), stats([]))
+ XCTAssertEqual(rows.map(\.name), ["Primo", "Second", "C"])
+ XCTAssertEqual(rows.map(\.description), ["Fallo", "Again", ""])
+ }
+
+ func testUnlockTimesComeFromTheStatsFile() throws {
+ let rows = try read(schema([("1", [("bits", [("0", bit("A", names: [:])), ("1", bit("B", names: [:]))] as E)])]),
+ stats([("1", "0", 1_700_000_000)]))
+ XCTAssertEqual(rows[0].unlockedAt, Date(timeIntervalSince1970: 1_700_000_000))
+ XCTAssertNil(rows[1].unlockedAt)
+ }
+
+ func testStatsWithoutBitsAreSkipped() throws {
+ let rows = try read(schema([("1", [("type", "1"), ("name", "kills")]), ("2", [("bits", [("0", bit("A", names: [:]))] as E)])]),
+ stats([]))
+ XCTAssertEqual(rows.map(\.apiName), ["A"])
+ }
+
+ func testHiddenAndIcons() throws {
+ let rows = try read(schema([("1", [("bits", [("0", bit("A", names: [:], hidden: true, icon: "x.jpg", gray: "y.jpg")),
+ ("1", bit("B", names: [:], icon: nil, gray: nil))] as E)])]), stats([]))
+ XCTAssertEqual(rows[0].hidden, true)
+ XCTAssertEqual(rows[0].icon, "x.jpg")
+ XCTAssertEqual(rows[0].grayIcon, "y.jpg")
+ XCTAssertEqual(rows[1].hidden, false)
+ XCTAssertNil(rows[1].icon)
+ }
+
+ func testOrderIsStatThenBitNumerically() throws {
+ let rows = try read(schema([
+ ("10", [("bits", [("0", bit("S10B0", names: [:]))] as E)]),
+ ("2", [("bits", [("10", bit("S2B10", names: [:])), ("9", bit("S2B9", names: [:]))] as E)]),
+ ]), stats([]))
+ XCTAssertEqual(rows.map(\.apiName), ["S2B9", "S2B10", "S10B0"])
+ }
+
+ func testOtherStatsKeysAreIgnored() throws {
+ let rows = try read(schema([("1", [("bits", [("0", bit("A", names: [:]))] as E)])]), stats([("1", "0", 5)], extra: true))
+ XCTAssertEqual(rows.count, 1)
+ XCTAssertNotNil(rows[0].unlockedAt)
+ }
+
+ func testAZeroTimeIsLocked() throws {
+ let rows = try read(schema([("1", [("bits", [("0", bit("A", names: [:]))] as E)])]), stats([("1", "0", 0)]))
+ XCTAssertNil(rows[0].unlockedAt)
+ }
+
+ func testLookupSkipsWrongTypesAndKeepsTheFirstMatchingTypedValue() throws {
+ let fields: E = [("name", [] as E), ("NAME", "FIRST"), ("name", "SECOND"),
+ ("display", "wrong type"), ("DISPLAY", [
+ ("name", [("italian", [] as E), ("ITALIAN", "Primo"), ("italian", "Secondo")] as E)
+ ] as E)]
+ let game: E = [("stats", "wrong type"), ("STATS", [("1", [
+ ("bits", "wrong type"), ("BITS", [("0", fields)] as E)
+ ] as E)] as E)]
+ let schema = try SteamBinaryKeyValues.parse(BinaryKV.data([("\(app)", "wrong type"), ("\(app)", game)]))
+ let rows = try read(schema, stats([("1", "0", 5)]))
+ XCTAssertEqual(rows.map(\.apiName), ["FIRST"])
+ XCTAssertEqual(rows.map(\.name), ["Primo"])
+ XCTAssertEqual(rows.first?.unlockedAt, Date(timeIntervalSince1970: 5))
+ }
+
+ func testEmptyFirstLocalizedStringFallsBackToEnglishRatherThanADuplicate() throws {
+ let fields: E = [("name", "A"), ("display", [("name", [
+ ("italian", ""), ("ITALIAN", "Ignored duplicate"), ("english", "English fallback")
+ ] as E)] as E)]
+ let rows = try read(schema([("1", [("bits", [("0", fields)] as E)])]), stats([]))
+ XCTAssertEqual(rows.map(\.name), ["English fallback"])
+ }
+
+ // MARK: - Files
+
+ private var root: URL!
+
+ override func setUpWithError() throws {
+ root = FileManager.default.temporaryDirectory.appendingPathComponent("SteamAchievements-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: root.appendingPathComponent("appcache/stats"), withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: root.appendingPathComponent("config"), withIntermediateDirectories: true)
+ let id = 76_561_197_960_265_728 + UInt64(account)
+ try "\"users\" { \"\(id)\" { \"AccountName\" \"someone\" \"MostRecent\" \"1\" \"timestamp\" \"1\" } }"
+ .write(to: root.appendingPathComponent("config/loginusers.vdf"), atomically: true, encoding: .utf8)
+ }
+
+ override func tearDown() {
+ try? FileManager.default.removeItem(at: root)
+ super.tearDown()
+ }
+
+ private func writeSchema(_ data: Data) throws {
+ try data.write(to: SteamAchievementReader.schemaURL(root: root, appID: app))
+ }
+
+ private func writeStats(_ data: Data) throws {
+ try data.write(to: SteamAchievementReader.statsURL(root: root, account: account, appID: app))
+ }
+
+ private var schemaData: Data {
+ BinaryKV.data([("\(app)", [("stats", [("1", [("bits", [("0", bit("A", names: ["english": "First"]))] as E)] as E)] as E)] as E)])
+ }
+
+ func testFileNamesFollowSteam() {
+ XCTAssertEqual(SteamAchievementReader.schemaURL(root: root, appID: app).lastPathComponent, "UserGameStatsSchema_4242.bin")
+ XCTAssertEqual(SteamAchievementReader.statsURL(root: root, account: account, appID: app).lastPathComponent, "UserGameStats_1234_4242.bin")
+ }
+
+ func testNoStatsFileForTheAccountIsNil() throws {
+ try writeSchema(schemaData)
+ XCTAssertNil(try SteamAchievementReader.read(root: root, appID: app, language: "english"))
+ }
+
+ func testNoUnlockIsZeroNotNil() throws {
+ try writeSchema(schemaData)
+ try writeStats(BinaryKV.data([("cache", [("crc", Int32(1))] as E)]))
+ let rows = try XCTUnwrap(SteamAchievementReader.read(root: root, appID: app, language: "english"))
+ XCTAssertEqual(rows.count, 1)
+ XCTAssertNil(rows[0].unlockedAt)
+ }
+
+ func testNoSchemaIsNil() throws {
+ try writeStats(BinaryKV.data([("cache", [("crc", Int32(1))] as E)]))
+ XCTAssertNil(try SteamAchievementReader.read(root: root, appID: app, language: "english"))
+ }
+
+ func testCorruptSchemaThrows() throws {
+ try writeSchema(schemaData.dropLast(4))
+ try writeStats(BinaryKV.data([("cache", [("crc", Int32(1))] as E)]))
+ XCTAssertThrowsError(try SteamAchievementReader.read(root: root, appID: app, language: "english"))
+ }
+
+ func testSchemaSymlinkIsRejected() throws {
+ let target = root.appendingPathComponent("schema.bin")
+ try schemaData.write(to: target)
+ try FileManager.default.createSymbolicLink(at: SteamAchievementReader.schemaURL(root: root, appID: app),
+ withDestinationURL: target)
+ try writeStats(BinaryKV.data([("cache", [] as E)]))
+ XCTAssertThrowsError(try SteamAchievementReader.read(root: root, appID: app, language: "english"))
+ }
+
+ func testStatsSymlinkIsRejected() throws {
+ try writeSchema(schemaData)
+ let target = root.appendingPathComponent("stats.bin")
+ try BinaryKV.data([("cache", [] as E)]).write(to: target)
+ try FileManager.default.createSymbolicLink(at: SteamAchievementReader.statsURL(root: root, account: account, appID: app),
+ withDestinationURL: target)
+ XCTAssertThrowsError(try SteamAchievementReader.read(root: root, appID: app, language: "english"))
+ }
+
+ func testASchemaForAnotherGameReadsNothing() throws {
+ try writeSchema(BinaryKV.data([("999", [("stats", [] as E)] as E)]))
+ try writeStats(BinaryKV.data([("cache", [("crc", Int32(1))] as E)]))
+ XCTAssertEqual(try SteamAchievementReader.read(root: root, appID: app, language: "english"), [])
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamArtworkRequestTests.swift b/Tests/NXLibraryCoreTests/SteamArtworkRequestTests.swift
new file mode 100644
index 00000000..21b32036
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamArtworkRequestTests.swift
@@ -0,0 +1,86 @@
+import XCTest
+import AppKit
+@testable import NXLibraryCore
+
+final class SteamArtworkRequestTests: XCTestCase {
+ func testSquareUsesOriginalBundleAssetButPortraitNeverUsesIt() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let app = root.appendingPathComponent("Fixture.app")
+ let resources = app.appendingPathComponent("Contents/Resources")
+ try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true)
+ try PropertyListSerialization.data(fromPropertyList: ["CFBundleIconFile":"Original"], format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist"))
+ let icon = resources.appendingPathComponent("Original.icns")
+ try Data("fixture".utf8).write(to: icon)
+ let observed = NativeMacApplication(url: app, executableURL: app.appendingPathComponent("Contents/MacOS/main"), bundleIdentifier: "fixture", name: "Fixture", architectures: [.arm64], isDeclaredGame: true, fileObservations: [])
+ let native = CatalogNativeApplication(observed)
+ let install = SteamCatalogInstallation(libraryURL: root, contentURL: root, applications: [native], availability: .available)
+ var steam = SteamCatalogGame(appID: 10, name: "Fixture"); steam.installations = [install]; steam.hasBeenRecognized = true
+ let game = CatalogGame(steam: steam), picks = SteamPersonalizationStore(directory: root.appendingPathComponent("picks"))
+ XCTAssertEqual(SteamArtworkRequest(game: game, role: .square).localURL(picks: picks), icon)
+ XCTAssertNil(SteamArtworkRequest(game: game, role: .cover).localURL(picks: picks))
+ // A malicious icon path is not a request to read outside the bundle.
+ try PropertyListSerialization.data(fromPropertyList: ["CFBundleIconFile":"../../outside"], format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist"))
+ XCTAssertNil(SteamArtworkRequest(game: game, role: .square).localURL(picks: picks))
+ }
+
+ func testPersonalPickComesBeforeTheAppIcon() throws {
+ let (root, game, icon) = try fixture(iconName: "Original")
+ defer { try? FileManager.default.removeItem(at: root) }
+ let picks = SteamPersonalizationStore(directory: root.appendingPathComponent("picks"))
+ XCTAssertEqual(SteamArtworkRequest(game: game, role: .square).localURL(picks: picks), icon)
+ let png = try XCTUnwrap(Self.png())
+ try picks.save(fields: [:], images: [.icon: png, .cover: png], automatic: [], titleID: game.personalizationReference.key)
+ let square = try XCTUnwrap(SteamArtworkRequest(game: game, role: .square).localURL(picks: picks))
+ XCTAssertNotEqual(square, icon)
+ XCTAssertTrue(square.path.hasPrefix(root.appendingPathComponent("picks").path))
+ XCTAssertNotNil(SteamArtworkRequest(game: game, role: .cover).localURL(picks: picks))
+ XCTAssertNil(SteamArtworkRequest(game: game, role: .hero).localURL(picks: picks))
+ }
+
+ func testIconLinkLeavingTheBundleIsNotFollowed() throws {
+ let (root, game, icon) = try fixture(iconName: "Original.icns")
+ defer { try? FileManager.default.removeItem(at: root) }
+ let outside = root.appendingPathComponent("outside.icns")
+ try Data("outside".utf8).write(to: outside)
+ try FileManager.default.removeItem(at: icon)
+ try FileManager.default.createSymbolicLink(at: icon, withDestinationURL: outside)
+ let picks = SteamPersonalizationStore(directory: root.appendingPathComponent("picks"))
+ XCTAssertNil(SteamArtworkRequest(game: game, role: .square).localURL(picks: picks))
+ }
+
+ private func fixture(iconName: String) throws -> (URL, CatalogGame, URL) {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ let app = root.appendingPathComponent("Fixture.app")
+ let resources = app.appendingPathComponent("Contents/Resources")
+ try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true)
+ try PropertyListSerialization.data(fromPropertyList: ["CFBundleIconFile": iconName], format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist"))
+ let icon = resources.appendingPathComponent("Original.icns")
+ try Data("fixture".utf8).write(to: icon)
+ let observed = NativeMacApplication(url: app, executableURL: app.appendingPathComponent("Contents/MacOS/main"), bundleIdentifier: "fixture", name: "Fixture", architectures: [.arm64], isDeclaredGame: true, fileObservations: [])
+ let install = SteamCatalogInstallation(libraryURL: root, contentURL: root, applications: [CatalogNativeApplication(observed)], availability: .available)
+ var steam = SteamCatalogGame(appID: 10, name: "Fixture"); steam.installations = [install]; steam.hasBeenRecognized = true
+ return (root, CatalogGame(steam: steam), icon)
+ }
+
+ private static func png() -> Data? {
+ let image = NSImage(size: NSSize(width: 8, height: 8))
+ image.lockFocus(); NSColor.red.setFill(); NSRect(x: 0, y: 0, width: 8, height: 8).fill(); image.unlockFocus()
+ return image.tiffRepresentation.flatMap { NSBitmapImageRep(data: $0)?.representation(using: .png, properties: [:]) }
+ }
+
+ func testOnlyASquareWithoutAnAppWantsAnAutomaticIcon() {
+ var steam = SteamCatalogGame(appID: 3321460, name: "Downloading")
+ steam.installations = [.init(libraryURL: URL(fileURLWithPath: "/tmp/steam"),
+ contentURL: URL(fileURLWithPath: "/tmp/steam/steamapps/common/G"),
+ availability: .unavailable, isDownloading: true)]
+ let downloading = CatalogGame(steam: steam)
+ XCTAssertTrue(SteamArtworkRequest(game: downloading, role: .square).wantsAutomaticIcon)
+ XCTAssertFalse(SteamArtworkRequest(game: downloading, role: .cover).wantsAutomaticIcon)
+ let root = URL(fileURLWithPath: "/tmp/steam-fixture"), app = root.appendingPathComponent("Fixture.app")
+ let observed = NativeMacApplication(url: app, executableURL: app.appendingPathComponent("Contents/MacOS/main"), bundleIdentifier: "fixture",
+ name: "Fixture", architectures: [.arm64], isDeclaredGame: true, fileObservations: [])
+ steam.installations = [.init(libraryURL: root, contentURL: root, applications: [CatalogNativeApplication(observed)], availability: .available)]
+ XCTAssertFalse(SteamArtworkRequest(game: CatalogGame(steam: steam), role: .square).wantsAutomaticIcon)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamAutomaticIconTests.swift b/Tests/NXLibraryCoreTests/SteamAutomaticIconTests.swift
new file mode 100644
index 00000000..d33491e9
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamAutomaticIconTests.swift
@@ -0,0 +1,76 @@
+import XCTest
+import AppKit
+@testable import NXLibraryCore
+
+/// A Steam game with no app has no icon of its own: LaunchBox's Square for its PC entry, else nothing.
+final class SteamAutomaticIconTests: XCTestCase {
+ private final class Client: ArtworkHTTPClient, @unchecked Sendable {
+ var routes: [String: Data] = [:]
+ var asked: [String] = []
+ private let lock = NSLock()
+ func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) {
+ let url = request.url!.absoluteString
+ let body: Data? = lock.withLock { asked.append(url); return routes[url] }
+ return (body ?? Data(), HTTPURLResponse(url: request.url!, statusCode: body == nil ? 404 : 200, httpVersion: nil, headerFields: nil)!)
+ }
+ }
+
+ private static let search = "https://gamesdb.launchbox-app.com/games/results/crimson%20desert%20enhanced"
+ private static let details = "https://gamesdb.launchbox-app.com/games/details/436343-crimson-desert-enhanced"
+ private static let square = "https://images.launchbox-app.com/square-full.png"
+
+ private static var png: Data {
+ let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 8, pixelsHigh: 8, bitsPerSample: 8, samplesPerPixel: 4,
+ hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
+ return rep.representation(using: .png, properties: [:])!
+ }
+
+ private func store(_ client: Client) -> ArtworkStore {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("SteamIcon-" + UUID().uuidString)
+ addTeardownBlock { try? FileManager.default.removeItem(at: directory) }
+ return ArtworkStore(cacheDirectory: directory, client: client)
+ }
+
+ private func client(square: Bool) -> Client {
+ let client = Client()
+ // A console entry first, as LaunchBox lists it: never taken for a Steam game.
+ client.routes[Self.search] = Data((LaunchBoxArtTests.card("438331-crimson-desert", "Crimson Desert Enhanced", "Sony Playstation 5")
+ + LaunchBoxArtTests.card("436343-crimson-desert-enhanced", "Crimson Desert Enhanced", "Windows")).utf8)
+ var images: [LaunchBoxArtTests.Image] = [("Box - Front", "World", "front.jpg", "front-full.jpg", 600, 900),
+ ("Fanart - Background", "World", "fan.jpg", "fan-full.jpg", 1920, 1080)]
+ if square { images.append(("Square", "World", "square.png", "square-full.png", 512, 512)) }
+ client.routes[Self.details] = Data(LaunchBoxArtTests.page(images).utf8)
+ client.routes[Self.square] = Self.png
+ return client
+ }
+
+ func testTheSquareIsTheFullSquareImageOnly() {
+ let candidates = LaunchBoxArt.candidates(in: LaunchBoxArtTests.gamePage)
+ XCTAssertEqual(LaunchBoxArt.square(in: candidates)?.lastPathComponent, "r2_square-full.jpg")
+ XCTAssertNil(LaunchBoxArt.square(in: candidates.filter { $0.slot != .icon }))
+ }
+
+ func testTheComputerEntrySquareIsFetchedOnceAndKept() async throws {
+ let client = client(square: true)
+ let artwork = store(client)
+ let first = await artwork.automaticSteamIcon(titleID: "steam-3321460", names: ["Crimson Desert Enhanced"])
+ XCTAssertEqual(first, artwork.cachedURL(titleID: "steam-3321460", kind: .square))
+ XCTAssertTrue(client.asked.contains(Self.square))
+ let asked = client.asked.count
+ let again = await artwork.automaticSteamIcon(titleID: "steam-3321460", names: ["Crimson Desert Enhanced"])
+ XCTAssertEqual(again, first)
+ XCTAssertEqual(client.asked.count, asked, "kept on disk: no new lookup")
+ }
+
+ func testNoSquareGivesNothingAndIsNotAskedAgainThisSession() async {
+ let client = client(square: false)
+ let artwork = store(client)
+ let none = await artwork.automaticSteamIcon(titleID: "steam-3321460", names: ["Crimson Desert Enhanced"])
+ XCTAssertNil(none)
+ XCTAssertFalse(client.asked.contains(Self.square))
+ let asked = client.asked.count
+ let again = await artwork.automaticSteamIcon(titleID: "steam-3321460", names: ["Crimson Desert Enhanced"])
+ XCTAssertNil(again)
+ XCTAssertEqual(client.asked.count, asked)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamBackdropChoiceTests.swift b/Tests/NXLibraryCoreTests/SteamBackdropChoiceTests.swift
new file mode 100644
index 00000000..9ad5d133
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamBackdropChoiceTests.swift
@@ -0,0 +1,80 @@
+import XCTest
+import AppKit
+@testable import NXLibraryCore
+
+final class SteamBackdropChoiceTests: XCTestCase {
+ private let shot = URL(string: "https://shared.akamai.steamstatic.com/shot.jpg")!
+ private let hero = URL(string: "https://shared.akamai.steamstatic.com/library_hero.jpg")!
+
+ func testScreenShapedArtOnly() {
+ XCTAssertTrue(SteamBackdropChoice.suits(width: 1920, height: 1080))
+ XCTAssertTrue(SteamBackdropChoice.suits(width: 1920, height: 1200))
+ XCTAssertFalse(SteamBackdropChoice.suits(width: 3840, height: 1240), "Steam's library hero is a banner")
+ XCTAssertFalse(SteamBackdropChoice.suits(width: 1024, height: 576), "too small for a full screen")
+ XCTAssertFalse(SteamBackdropChoice.suits(width: 600, height: 900))
+ }
+
+ func testCleanStoreHeroesComeFirstThenTheExactScreenshotThenTheBanner() {
+ let art = [
+ ArtworkCandidate(slot: .background, source: "Xbox Store · titled", url: URL(string: "https://x/titled")!),
+ ArtworkCandidate(slot: .background, source: "TheGamesDB fan art", url: URL(string: "https://t/fan")!),
+ ArtworkCandidate(slot: .cover, source: "GOG", url: URL(string: "https://g/cover")!),
+ ArtworkCandidate(slot: .background, source: "GOG", url: URL(string: "https://g/galaxy")!),
+ ArtworkCandidate(slot: .background, source: "GOG", url: URL(string: "https://g/wide-cover")!),
+ ArtworkCandidate(slot: .background, source: "Xbox Store", url: URL(string: "https://x/hero")!)
+ ]
+ let order = SteamBackdropChoice.ordered(storeArt: art, screenshots: [shot, URL(string: "https://s/2")!], libraryHero: hero)
+ XCTAssertEqual(order.map(\.absoluteString), ["https://x/hero", "https://g/galaxy", "https://t/fan", shot.absoluteString, hero.absoluteString])
+ XCTAssertEqual(SteamBackdropChoice.ordered(storeArt: [], screenshots: [], libraryHero: hero), [hero])
+ }
+
+ func testLaunchBoxComputerFanartComesAfterTheStoresAndBeforeScreenshots() {
+ let fanart = { (name: String, w: Int?, h: Int?) in
+ ArtworkCandidate(slot: .background, source: "LaunchBox · Fanart - Background", url: URL(string: "https://l/\(name)-preview")!,
+ full: URL(string: "https://l/\(name)"), width: w, height: h)
+ }
+ let art = [
+ ArtworkCandidate(slot: .background, source: "LaunchBox · Screenshot - Gameplay", url: URL(string: "https://l/play")!,
+ full: URL(string: "https://l/play-full"), width: 1920, height: 1080),
+ fanart("banner", 3840, 1240),
+ fanart("small", 1024, 576),
+ fanart("wide", 2560, 1440),
+ ArtworkCandidate(slot: .background, source: "GOG", url: URL(string: "https://g/galaxy")!)
+ ]
+ let order = SteamBackdropChoice.ordered(storeArt: art, screenshots: [shot], libraryHero: hero)
+ // The full file, not its preview; only a screen-shaped one; gameplay shots are not fan art.
+ XCTAssertEqual(order.map(\.absoluteString), ["https://g/galaxy", "https://l/wide", shot.absoluteString, hero.absoluteString])
+ let unsized = SteamBackdropChoice.ordered(storeArt: [fanart("unknown", nil, nil)], screenshots: [], libraryHero: nil)
+ XCTAssertEqual(unsized.map(\.absoluteString), ["https://l/unknown"], "a size the page does not state is checked when chosen")
+ }
+
+ func testChoosesTheFirstScreenShapedImageAndFallsBackToTheBanner() async throws {
+ let banner = try XCTUnwrap(Self.png(width: 1500, height: 484))
+ let wide = try XCTUnwrap(Self.png(width: 1600, height: 900))
+ var asked: [URL] = []
+ let chosen = await SteamBackdropChoice.choose([URL(string: "https://x/missing")!, hero, shot], fallback: hero) { url in
+ asked.append(url)
+ return url == hero ? banner : url == self.shot ? wide : nil
+ }
+ XCTAssertEqual(chosen, shot)
+ XCTAssertEqual(asked.count, 3)
+ let fallback = await SteamBackdropChoice.choose([shot, hero], fallback: hero) { _ in banner }
+ XCTAssertEqual(fallback, hero)
+ }
+
+ func testWithoutAScreenShapedImageOrBannerTheFirstImageThatLoadsIsShown() async throws {
+ let small = try XCTUnwrap(Self.png(width: 1024, height: 576))
+ let missing = URL(string: "https://x/missing")!
+ let chosen = await SteamBackdropChoice.choose([missing, shot], fallback: nil) { $0 == self.shot ? small : nil }
+ XCTAssertEqual(chosen, shot, "never the last URL just for being last: one that loads")
+ let none = await SteamBackdropChoice.choose([missing], fallback: nil) { _ in nil }
+ XCTAssertNil(none)
+ }
+
+ private static func png(width: Int, height: Int) -> Data? {
+ guard let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height, bitsPerSample: 8,
+ samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB,
+ bytesPerRow: 0, bitsPerPixel: 0) else { return nil }
+ return rep.representation(using: .png, properties: [:])
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamBinaryKeyValuesTests.swift b/Tests/NXLibraryCoreTests/SteamBinaryKeyValuesTests.swift
new file mode 100644
index 00000000..c9e23c24
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamBinaryKeyValuesTests.swift
@@ -0,0 +1,94 @@
+import XCTest
+@testable import NXLibraryCore
+
+/// Writes Steam's binary KeyValues for tests: a `[(key, value)]` array is a subtree, a String is type 1, an Int32
+/// type 2, a Float type 3, a UInt64 type 7.
+enum BinaryKV {
+ static func data(_ entries: [(String, Any)], end: Bool = true) -> Data {
+ var out = Data()
+ write(entries, into: &out)
+ if end { out.append(8) }
+ return out
+ }
+
+ private static func write(_ entries: [(String, Any)], into out: inout Data) {
+ for (key, value) in entries {
+ switch value {
+ case let sub as [(String, Any)]:
+ out.append(0); cString(key, &out); write(sub, into: &out); out.append(8)
+ case let text as String:
+ out.append(1); cString(key, &out); cString(text, &out)
+ case let number as Int32:
+ out.append(2); cString(key, &out); withUnsafeBytes(of: number.littleEndian) { out.append(contentsOf: $0) }
+ case let number as Float:
+ out.append(3); cString(key, &out); withUnsafeBytes(of: number.bitPattern.littleEndian) { out.append(contentsOf: $0) }
+ case let number as UInt64:
+ out.append(7); cString(key, &out); withUnsafeBytes(of: number.littleEndian) { out.append(contentsOf: $0) }
+ default:
+ preconditionFailure("unsupported test value \(value)")
+ }
+ }
+ }
+
+ private static func cString(_ text: String, _ out: inout Data) {
+ out.append(contentsOf: Array(text.utf8)); out.append(0)
+ }
+}
+
+final class SteamBinaryKeyValuesTests: XCTestCase {
+ func testReadsEveryType() throws {
+ let data = BinaryKV.data([("root", [
+ ("text", "a"), ("int", Int32(-7)), ("float", Float(1.5)), ("big", UInt64(1) << 40),
+ ] as [(String, Any)])])
+ let entries = try SteamBinaryKeyValues.parse(data)
+ XCTAssertEqual(entries, [KeyValuesEntry(key: "root", value: .object([
+ KeyValuesEntry(key: "text", value: .string("a")),
+ KeyValuesEntry(key: "int", value: .string("-7")),
+ KeyValuesEntry(key: "float", value: .string("1.5")),
+ KeyValuesEntry(key: "big", value: .string("1099511627776")),
+ ]))])
+ }
+
+ func testKeepsOrderAndDuplicates() throws {
+ let entries = try SteamBinaryKeyValues.parse(BinaryKV.data([("b", "1"), ("a", "2"), ("b", "3")]))
+ XCTAssertEqual(entries.map(\.key), ["b", "a", "b"])
+ }
+
+ func testTruncatedThrowsMalformed() {
+ let data = BinaryKV.data([("root", [("int", Int32(5))] as [(String, Any)])], end: false)
+ XCTAssertThrowsError(try SteamBinaryKeyValues.parse(data.dropLast(2))) {
+ XCTAssertEqual($0 as? KeyValuesError, .malformed)
+ }
+ }
+
+ func testUnknownTypeThrowsMalformed() {
+ var data = Data([5]); data.append(contentsOf: Array("x".utf8)); data.append(0)
+ XCTAssertThrowsError(try SteamBinaryKeyValues.parse(data)) { XCTAssertEqual($0 as? KeyValuesError, .malformed) }
+ }
+
+ func testDepthLimit() {
+ var nested: [(String, Any)] = [("leaf", "x")]
+ for _ in 0..<33 { nested = [("n", nested)] }
+ XCTAssertThrowsError(try SteamBinaryKeyValues.parse(BinaryKV.data(nested), maximumDepth: 32)) {
+ XCTAssertEqual($0 as? KeyValuesError, .limitExceeded)
+ }
+ }
+
+ func testTopLevelNeedsItsTerminator() throws {
+ XCTAssertEqual(try SteamBinaryKeyValues.parse(BinaryKV.data([("a", "1")], end: true)).count, 1)
+ // Cut just before the last byte (Steam writing the file): not a shorter file, a broken one.
+ XCTAssertThrowsError(try SteamBinaryKeyValues.parse(BinaryKV.data([("a", "1")], end: false))) {
+ XCTAssertEqual($0 as? KeyValuesError, .malformed)
+ }
+ }
+
+ func testEmptyDataThrows() {
+ XCTAssertThrowsError(try SteamBinaryKeyValues.parse(Data())) { XCTAssertEqual($0 as? KeyValuesError, .malformed) }
+ }
+
+ func testAnUnclosedSubtreeThrows() {
+ var data = Data([0]); data.append(contentsOf: Array("s".utf8)); data.append(0)
+ data.append(1); data.append(contentsOf: Array("k".utf8)); data.append(0); data.append(contentsOf: Array("v".utf8)); data.append(0)
+ XCTAssertThrowsError(try SteamBinaryKeyValues.parse(data)) { XCTAssertEqual($0 as? KeyValuesError, .malformed) }
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamCatalogReconcilerTests.swift b/Tests/NXLibraryCoreTests/SteamCatalogReconcilerTests.swift
new file mode 100644
index 00000000..bb41a75b
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamCatalogReconcilerTests.swift
@@ -0,0 +1,240 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class SteamCatalogReconcilerTests: XCTestCase {
+ private let root = URL(fileURLWithPath: "/tmp/catalog-steam")
+ private let external = URL(fileURLWithPath: "/tmp/catalog-external")
+ private let observedAt = Date(timeIntervalSince1970: 1000.125)
+
+ private func catalog() -> CatalogDocument {
+ CatalogDocument(sources: [.init(integration: .nxnative, isEnabled: true),
+ .init(integration: .steam, isEnabled: true, rootURL: root)],
+ games: [.init(nxnative: CatalogTestSupport.completeLegacyGame())])
+ }
+ private func observation(_ id: UInt32 = 10, name: String = "Same name", library: URL? = nil,
+ directory: String = "Game", state: SteamGameObservation.State = .nativeReady,
+ size: Int64? = 100) throws -> SteamGameObservation {
+ let library = library ?? root
+ let content = library.appendingPathComponent("steamapps/common/" + directory)
+ let app = content.appendingPathComponent("Game.app")
+ let native = NativeMacApplication(url: app, executableURL: app.appendingPathComponent("Contents/MacOS/game"),
+ bundleIdentifier: "test.game", name: name, architectures: [.arm64],
+ isDeclaredGame: true, fileObservations: [])
+ return .init(appID: id, name: name, installationURL: content,
+ libraryURL: library, reportedSizeBytes: size, buildID: "42", nativeApps: [native], state: state)
+ }
+ private func snapshot(_ games: [SteamGameObservation], complete: Bool = true,
+ libraries: [SteamLibraryObservation]? = nil) -> SteamLibrarySnapshot {
+ .init(libraries: libraries ?? [.init(root: root, isReadable: true, isComplete: complete)], games: games,
+ issues: complete ? [] : [.init(url: root, appID: nil, reason: .invalidManifest)])
+ }
+ private func apply(_ scan: SteamLibrarySnapshot, to document: CatalogDocument) throws -> CatalogDocument {
+ try SteamCatalogReconciler.applying(scan, ticket: document.steamScanTicket(), to: document, observedAt: observedAt)
+ }
+
+ func testScansRequireEnabledSourceAndMatchingRevisionAndRoot() throws {
+ var document = catalog()
+ let ticket = try document.steamScanTicket()
+ document.sources[1].isEnabled = false
+ XCTAssertThrowsError(try document.steamScanTicket())
+ XCTAssertThrowsError(try SteamCatalogReconciler.applying(snapshot([]), ticket: ticket, to: document))
+ document = catalog(); document.revision = UUID()
+ XCTAssertThrowsError(try SteamCatalogReconciler.applying(snapshot([]), ticket: ticket, to: document))
+ document = catalog(); document.sources[1].rootURL = external
+ XCTAssertThrowsError(try SteamCatalogReconciler.applying(snapshot([]), ticket: ticket, to: document))
+ document = catalog()
+ XCTAssertThrowsError(try apply(snapshot([], libraries: [.init(root: external, isReadable: true, isComplete: true)]), to: document))
+ }
+
+ func testIdenticalNamesAcrossSourcesAndAppIDsStaySeparate() throws {
+ var first = try observation()
+ first = .init(appID: first.appID, name: "Fixture Switch game", installationURL: first.installationURL,
+ libraryURL: first.libraryURL, reportedSizeBytes: 100, buildID: "42", nativeApps: first.nativeApps, state: .nativeReady)
+ let original = catalog()
+ let result = try apply(snapshot([first, observation(20, name: "Fixture Switch game")]), to: original)
+ XCTAssertEqual(result.games.count, 3)
+ XCTAssertEqual(Set(result.games.map(\.id)).count, 3)
+ XCTAssertEqual(Set(result.games.compactMap { $0.steamGame?.appID }), [10, 20])
+ XCTAssertEqual(result.games.filter { $0.integration == .steam }.map(\.personalizationKey), ["steam-10", "steam-20"])
+ XCTAssertEqual(result.games[0].nxnativeGame, original.games[0].nxnativeGame)
+ }
+
+ func testRefreshKeepsUUIDInstallationIDAndPersonalChoicesWhileUpdatingObservations() throws {
+ let game = try observation()
+ var document = try apply(snapshot([game]), to: catalog())
+ document.games[1].setFavorite(true); document.games[1].setHidden(true)
+ let before = document.games[1]
+ let renamed = SteamGameObservation(appID: 10, name: "New name", installationURL: game.installationURL,
+ libraryURL: game.libraryURL, reportedSizeBytes: 200, buildID: "43", nativeApps: game.nativeApps, state: .nativeReady)
+ let result = try apply(snapshot([renamed]), to: document)
+ let after = result.games[1]
+ XCTAssertEqual(after.id, before.id)
+ XCTAssertEqual(after.steamGame?.installations.first?.id, before.steamGame?.installations.first?.id)
+ XCTAssertEqual(after.personalizationReference, before.personalizationReference)
+ XCTAssertTrue(after.isFavorite); XCTAssertTrue(after.isHidden)
+ XCTAssertEqual(after.name, "New name")
+ XCTAssertEqual(after.steamGame?.installations.first?.reportedSizeBytes, 200)
+ XCTAssertEqual(after.steamGame?.installations.first?.buildID, "43")
+ XCTAssertEqual(after.steamGame?.installations.first?.lastObservedAt, observedAt)
+ XCTAssertEqual(result.games[0], document.games[0])
+ XCTAssertEqual(result.revision, document.revision, "Store alone assigns the committed revision")
+ }
+
+ func testDuplicateAppIDRetainsBothInstallationsAndRequiresReview() throws {
+ let a = try observation(), b = try observation(library: external)
+ let scan = snapshot([a, b], libraries: [.init(root: root, isReadable: true, isComplete: true), .init(root: external, isReadable: true, isComplete: true)])
+ let result = try apply(scan, to: catalog())
+ XCTAssertEqual(result.games.count, 2)
+ XCTAssertEqual(result.games[1].steamGame?.installations.count, 2)
+ XCTAssertNil(CatalogGamePresentation(game: result.games[1], sourceEnabled: true).launchTarget)
+ XCTAssertTrue(CatalogGamePresentation(game: result.games[1], sourceEnabled: true).requiresReview)
+ let repeated = try apply(scan, to: result)
+ XCTAssertEqual(repeated.games[1].steamGame?.installations.map(\.id), result.games[1].steamGame?.installations.map(\.id))
+ }
+
+ func testCompleteAbsenceMarksNotDetectedWithoutDeletingGameOrHistoryIdentity() throws {
+ let document = try apply(snapshot([observation()]), to: catalog())
+ let result = try apply(snapshot([]), to: document)
+ XCTAssertEqual(result.games.count, 2)
+ XCTAssertEqual(result.games[1].id, document.games[1].id)
+ XCTAssertEqual(result.games[1].steamGame?.installations.first?.availability, .notDetected)
+ XCTAssertTrue(CatalogGamePresentation(game: result.games[1], sourceEnabled: true).isListedNormally)
+ XCTAssertNil(CatalogGamePresentation(game: result.games[1], sourceEnabled: true).launchTarget)
+ }
+
+ func testPartialScanPreservesUnseenStateAndUnreadableLibraryIsExplicit() throws {
+ let document = try apply(snapshot([observation()]), to: catalog())
+ let partial = try apply(snapshot([], complete: false), to: document)
+ XCTAssertEqual(partial.games, document.games)
+ let unavailable = snapshot([], complete: false, libraries: [.init(root: root, isReadable: false, isComplete: false)])
+ let missing = try apply(unavailable, to: document)
+ XCTAssertEqual(missing.games[1].steamGame?.installations.first?.availability, .sourceUnavailable)
+ XCTAssertEqual(missing.games[1].id, document.games[1].id)
+ XCTAssertNil(CatalogGamePresentation(game: missing.games[1], sourceEnabled: true).launchTarget)
+ }
+
+ func testMovedInstallationKeepsGameIdentityAndOldObservation() throws {
+ let document = try apply(snapshot([observation()]), to: catalog())
+ let result = try apply(snapshot([observation(directory: "Moved")]), to: document)
+ XCTAssertEqual(result.games[1].id, document.games[1].id)
+ let installs = try XCTUnwrap(result.games[1].steamGame?.installations)
+ XCTAssertEqual(installs.count, 2)
+ XCTAssertEqual(installs[0].availability, .notDetected)
+ XCTAssertEqual(installs[1].availability, .available)
+ XCTAssertEqual(installs[0].id, document.games[1].steamGame?.installations[0].id)
+ XCTAssertEqual(CatalogGamePresentation(game: result.games[1], sourceEnabled: true).launchTarget, .steam(appID: 10))
+ }
+
+ func testUnrecognizedCandidatesDoNotBecomeNormalGamesOrLaunchTargets() throws {
+ for state: SteamGameObservation.State in [.unavailable, .requiresReview] {
+ let result = try apply(snapshot([observation(state: state)]), to: catalog())
+ let presentation = CatalogGamePresentation(game: result.games[1], sourceEnabled: true)
+ XCTAssertFalse(presentation.isListedNormally)
+ XCTAssertTrue(presentation.requiresReview)
+ XCTAssertNil(presentation.launchTarget)
+ }
+ }
+
+ func testSourceDisableHidesAndBlocksLaunchWithoutLosingRecords() throws {
+ let document = try apply(snapshot([observation()]), to: catalog())
+ let steam = CatalogGamePresentation(game: document.games[1], sourceEnabled: false)
+ XCTAssertFalse(steam.isListedNormally)
+ XCTAssertNil(steam.launchTarget)
+ }
+
+ func testInvalidAppIDAndUnlistedLibraryCannotBeAccepted() throws {
+ XCTAssertThrowsError(try apply(snapshot([observation(0)]), to: catalog()))
+ XCTAssertThrowsError(try apply(snapshot([observation(library: external)]), to: catalog()))
+ }
+ func testNativeApplicationOutsideObservedInstallationIsRejected() throws {
+ let original = try observation()
+ let unsafe = SteamGameObservation(appID: 10, name: original.name,
+ installationURL: external.appendingPathComponent("Outside"), libraryURL: root,
+ reportedSizeBytes: nil, buildID: nil, nativeApps: original.nativeApps, state: .nativeReady)
+ XCTAssertThrowsError(try apply(snapshot([unsafe]), to: catalog()))
+ }
+
+ func testDifferentAppIDReusingAPathDoesNotKeepMissingOldGameAvailable() throws {
+ let document = try apply(snapshot([observation(10)]), to: catalog())
+ let result = try apply(snapshot([observation(20)]), to: document)
+ XCTAssertEqual(result.games[1].steamGame?.appID, 10)
+ XCTAssertEqual(result.games[1].steamGame?.installations.first?.availability, .notDetected)
+ XCTAssertNil(CatalogGamePresentation(game: result.games[1], sourceEnabled: true).launchTarget)
+ }
+
+ func testDuplicateInstallationPathsAreRejectedBeforeReconciliation() throws {
+ var document = try apply(snapshot([observation()]), to: catalog())
+ var game = try XCTUnwrap(document.games[1].steamGame)
+ let original = game.installations[0]
+ game.installations.append(.init(libraryURL: original.libraryURL, contentURL: original.contentURL,
+ applications: original.applications, availability: .available))
+ try document.games[1].updateSteam(game)
+ XCTAssertThrowsError(try document.validate())
+ }
+
+ func testMissingDiskCannotResolveDuplicateAmbiguityAndReconnectRemainsBlocked() throws {
+ let a = try observation(), b = try observation(library: external)
+ let both = snapshot([a, b], libraries: [.init(root: root, isReadable: true, isComplete: true),
+ .init(root: external, isReadable: true, isComplete: true)])
+ let duplicate = try apply(both, to: catalog())
+ let absentDisk = snapshot([a], complete: false, libraries: [.init(root: root, isReadable: true, isComplete: true),
+ .init(root: external, isReadable: false, isComplete: false)])
+ let partial = try apply(absentDisk, to: duplicate)
+ let shown = CatalogGamePresentation(game: partial.games[1], sourceEnabled: true)
+ XCTAssertTrue(shown.requiresReview)
+ XCTAssertNil(shown.launchTarget)
+ XCTAssertEqual(partial.games[1].steamGame?.installations.first { $0.libraryURL == external }?.availability, .sourceUnavailable)
+ let reloaded = try JSONDecoder().decode(CatalogDocument.self, from: JSONEncoder().encode(partial))
+ XCTAssertTrue(CatalogGamePresentation(game: reloaded.games[1], sourceEnabled: true).requiresReview)
+ let reconnected = try apply(both, to: reloaded)
+ XCTAssertTrue(CatalogGamePresentation(game: reconnected.games[1], sourceEnabled: true).requiresReview)
+ XCTAssertNil(CatalogGamePresentation(game: reconnected.games[1], sourceEnabled: true).launchTarget)
+ // Only complete evidence of one remaining installation resolves it.
+ let resolved = try apply(snapshot([a], libraries: [.init(root: root, isReadable: true, isComplete: true),
+ .init(root: external, isReadable: true, isComplete: true)]), to: reconnected)
+ XCTAssertFalse(CatalogGamePresentation(game: resolved.games[1], sourceEnabled: true).requiresReview)
+ XCTAssertEqual(CatalogGamePresentation(game: resolved.games[1], sourceEnabled: true).launchTarget, .steam(appID: 10))
+ XCTAssertEqual(resolved.games[1].id, duplicate.games[1].id)
+ }
+
+ private func downloading(directory: String = "Game") -> SteamGameObservation {
+ .init(appID: 10, name: "Same name", installationURL: root.appendingPathComponent("steamapps/common/" + directory),
+ libraryURL: root, reportedSizeBytes: 0, buildID: "42", nativeApps: [], state: .downloading)
+ }
+
+ func testDownloadingObservationIsListedButNeitherRecognizedNorReviewed() throws {
+ let result = try apply(snapshot([downloading()]), to: catalog())
+ let steam = try XCTUnwrap(result.games[1].steamGame)
+ XCTAssertEqual(steam.installations.first?.availability, .unavailable)
+ XCTAssertEqual(steam.installations.first?.isDownloading, true)
+ XCTAssertTrue(steam.isDownloading)
+ XCTAssertFalse(steam.hasBeenRecognized)
+ XCTAssertFalse(steam.needsInstallationReview)
+ XCTAssertFalse(steam.needsReview)
+ }
+
+ func testFinishedDownloadBecomesRecognizedAndClearsFlag() throws {
+ let first = try apply(snapshot([downloading()]), to: catalog())
+ let result = try apply(snapshot([observation(directory: "Game")]), to: first)
+ let steam = try XCTUnwrap(result.games[1].steamGame)
+ XCTAssertEqual(steam.installations.count, 1)
+ XCTAssertEqual(steam.installations[0].id, first.games[1].steamGame?.installations[0].id)
+ XCTAssertFalse(steam.installations[0].isDownloading)
+ XCTAssertFalse(steam.isDownloading)
+ XCTAssertTrue(steam.hasBeenRecognized)
+ XCTAssertEqual(CatalogGamePresentation(game: result.games[1], sourceEnabled: true).launchTarget, .steam(appID: 10))
+ }
+
+ func testRecognizedGameReinstalledShowsDownloading() throws {
+ let installed = try apply(snapshot([observation(directory: "Game")]), to: catalog())
+ let result = try apply(snapshot([downloading(directory: "Again")]), to: installed)
+ let steam = try XCTUnwrap(result.games[1].steamGame)
+ XCTAssertEqual(steam.installations.map(\.availability), [.notDetected, .unavailable])
+ XCTAssertTrue(steam.isDownloading)
+ let shown = CatalogGamePresentation(game: result.games[1], sourceEnabled: true)
+ XCTAssertTrue(shown.isDownloading)
+ XCTAssertTrue(shown.isListedNormally)
+ XCTAssertFalse(shown.requiresReview)
+ XCTAssertNil(shown.launchTarget)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamDiscoveryConsistencyTests.swift b/Tests/NXLibraryCoreTests/SteamDiscoveryConsistencyTests.swift
new file mode 100644
index 00000000..2fb07582
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamDiscoveryConsistencyTests.swift
@@ -0,0 +1,111 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class SteamDiscoveryConsistencyTests: XCTestCase {
+ func testManifestAddedAfterInventoryInvalidatesTheSource() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ let source = SteamLibrarySource(root: root, directoryReader: { url, limit, cancelled in
+ let read = try InstallationDirectorySnapshot.read(at: url, maximumEntries: limit, cancelled: cancelled)
+ if url.path == root.appendingPathComponent("steamapps").path {
+ try f.manifest(in: root, id: "20", directory: "Second")
+ try f.app(at: "Steam/steamapps/common/Second/Game.app")
+ }
+ return read
+ })
+ XCTAssertThrowsError(try source.scan()) { XCTAssertEqual($0 as? SteamSourceError, .sourceChanged) }
+ }
+
+ func testPreviouslyAbsentIndexAppearingBeforeInventoryIsDetected() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library(), external = try f.library("External")
+ let source = SteamLibrarySource(root: root, directoryReader: { url, limit, cancelled in
+ if url.path == root.appendingPathComponent("steamapps").path {
+ try Data("libraryfolders { 1 \(SteamTestFixture.quote(external.path)) }".utf8)
+ .write(to: root.appendingPathComponent("steamapps/libraryfolders.vdf"))
+ }
+ return try InstallationDirectorySnapshot.read(at: url, maximumEntries: limit, cancelled: cancelled)
+ })
+ XCTAssertThrowsError(try source.scan()) { XCTAssertEqual($0 as? SteamSourceError, .sourceChanged) }
+ }
+
+ func testNativeMetadataAndExecutableAreRecheckedAfterOtherGamesAreRead() throws {
+ for removeExecutable in [false, true] {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ try f.manifest(in: root, id: "20", directory: "Second")
+ let first = try f.app(at: "Steam/steamapps/common/First/Game.app")
+ try f.app(at: "Steam/steamapps/common/Second/Game.app")
+ let second = root.appendingPathComponent("steamapps/common/Second")
+ let source = SteamLibrarySource(root: root, directoryReader: { url, limit, cancelled in
+ let read = try InstallationDirectorySnapshot.read(at: url, maximumEntries: limit, cancelled: cancelled)
+ if url.path == second.path {
+ if removeExecutable {
+ try FileManager.default.removeItem(at: first.appendingPathComponent("Contents/MacOS/fixture"))
+ } else {
+ let file = first.appendingPathComponent("Contents/Info.plist")
+ var info = try XCTUnwrap(PropertyListSerialization.propertyList(from: Data(contentsOf: file), format: nil) as? [String: Any])
+ info["LSApplicationCategoryType"] = "public.app-category.developer-tools"
+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: file)
+ }
+ }
+ return read
+ })
+ XCTAssertThrowsError(try source.scan()) { XCTAssertEqual($0 as? SteamSourceError, .sourceChanged) }
+ }
+ }
+
+ func testDirectoryReadEnforcesTheEntryBudget() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ for i in 0..<12 { try Data().write(to: f.root.appendingPathComponent("item\(i)")) }
+ let result = try InstallationDirectorySnapshot.read(at: f.root, maximumEntries: 3, cancelled: { false })
+ XCTAssertEqual(result.entries.count, 3)
+ XCTAssertFalse(result.isComplete)
+ }
+
+ func testDirectoryReadHonorsCancellationWhileCollectingEntries() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ for i in 0..<12 { try Data().write(to: f.root.appendingPathComponent("item\(i)")) }
+ var checkpoints = 0
+ XCTAssertThrowsError(try InstallationDirectorySnapshot.read(at: f.root, maximumEntries: 100, cancelled: {
+ checkpoints += 1
+ return checkpoints >= 2
+ })) { XCTAssertTrue($0 is CancellationError) }
+ }
+
+ func testHiddenEntriesAlsoConsumeTheDirectoryReadBudget() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ for i in 0..<12 { try Data().write(to: f.root.appendingPathComponent(".hidden\(i)")) }
+ let result = try InstallationDirectorySnapshot.read(at: f.root, maximumEntries: 3, cancelled: { false })
+ XCTAssertTrue(result.entries.isEmpty)
+ XCTAssertFalse(result.isComplete)
+ }
+
+ func testWideInstallationRemainsPartialWhenItsEntryBudgetIsReached() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ for i in 0..<12 {
+ try Data().write(to: root.appendingPathComponent("steamapps/common/First/item\(i)"))
+ }
+ var limits = SteamScanLimits.standard
+ limits.maximumDirectoryEntries = 4
+ let result = try SteamLibrarySource(root: root, limits: limits).scan()
+ XCTAssertFalse(result.isComplete)
+ XCTAssertEqual(result.games.first?.state, .requiresReview)
+ XCTAssertTrue(result.issues.contains { $0.reason == .directoryLimit })
+ }
+
+ func testCancellationFromInventoryReaderIsNotSwallowedAsUnavailable() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ let source = SteamLibrarySource(root: root, directoryReader: { url, limit, _ in
+ try InstallationDirectorySnapshot.read(at: url, maximumEntries: limit, cancelled: { true })
+ })
+ XCTAssertThrowsError(try source.scan()) { XCTAssertTrue($0 is CancellationError) }
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamKeyValuesTests.swift b/Tests/NXLibraryCoreTests/SteamKeyValuesTests.swift
new file mode 100644
index 00000000..2671fa26
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamKeyValuesTests.swift
@@ -0,0 +1,65 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class SteamKeyValuesTests: XCTestCase {
+ func testReadsNestedLibraryWithSpacesAndUnicode() throws {
+ let document = try KeyValuesDocument(text: "\"libraryfolders\" { \"0\" { \"path\" \"/Volumes/Giochi è/SteamLibrary\" } }")
+ guard case .object(let libraries)? = try document.uniqueValue(for: "libraryfolders"),
+ case .object(let first)? = try libraries.uniqueValue(for: "0") else {
+ return XCTFail("Missing library")
+ }
+ XCTAssertEqual(try first.uniqueValue(for: "PATH"), .string("/Volumes/Giochi è/SteamLibrary"))
+ }
+
+ func testCommentsDoNotConsumeSlashesInsideStrings() throws {
+ let document = try KeyValuesDocument(text: "// heading\nname \"https://example.invalid/game\" // comment\nempty {}")
+ XCTAssertEqual(try document.uniqueValue(for: "name"), .string("https://example.invalid/game"))
+ XCTAssertEqual(try document.uniqueValue(for: "empty"), .object([]))
+ }
+
+ func testQuotedEscapeSequencesAndUnquotedScalars() throws {
+ let document = try KeyValuesDocument(text: #"name "A \"quote\" \\ slash\nline\ttab\rend" appid 10"#)
+ XCTAssertEqual(try document.uniqueValue(for: "name"), .string("A \"quote\" \\ slash\nline\ttab\rend"))
+ XCTAssertEqual(try document.uniqueValue(for: "appid"), .string("10"))
+ }
+
+ func testConflictingCaseVariantsAreNotSilentlyOverwritten() throws {
+ let document = try KeyValuesDocument(text: "appid 10 APPID 20")
+ XCTAssertEqual(document.entries.count, 2)
+ XCTAssertThrowsError(try document.uniqueValue(for: "appid"))
+ }
+
+ func testUnknownDuplicateFieldsRemainInTheDocument() throws {
+ let document = try KeyValuesDocument(text: "unknown first unknown second appid 10")
+ XCTAssertEqual(document.entries.map(\.key), ["unknown", "unknown", "appid"])
+ XCTAssertEqual(try document.uniqueValue(for: "appid"), .string("10"))
+ XCTAssertNil(try document.uniqueValue(for: "absent"))
+ }
+
+ func testRejectsMalformedAndTruncatedDocuments() {
+ for text in ["key", "{", "key {", "key }", "key { child value", "key value }", "key \"unterminated", #"key "bad\q""#] {
+ XCTAssertThrowsError(try KeyValuesDocument(text: text), text)
+ }
+ }
+
+ func testDoesNotExecuteIncludeOrBaseDirectives() {
+ for directive in ["#include", "#base", "#INCLUDE"] {
+ XCTAssertThrowsError(try KeyValuesDocument(text: "\(directive) \"/private/should-not-be-read\""))
+ }
+ }
+
+ func testDepthLimitAllowsBoundaryAndRejectsOneMoreObject() throws {
+ XCTAssertNoThrow(try KeyValuesDocument(text: "a { b c }", maximumDepth: 1))
+ XCTAssertThrowsError(try KeyValuesDocument(text: "a { b { c d } }", maximumDepth: 1))
+ }
+
+ func testEntryLimitCountsNestedEntries() throws {
+ XCTAssertNoThrow(try KeyValuesDocument(text: "a { b c }", maximumEntries: 2))
+ XCTAssertThrowsError(try KeyValuesDocument(text: "a { b c d e }", maximumEntries: 2))
+ }
+
+ func testEmptyDocumentAndUtf8Bom() throws {
+ XCTAssertEqual(try KeyValuesDocument(text: " \n// empty").entries, [])
+ XCTAssertEqual(try KeyValuesDocument(text: "\u{FEFF}appid 10").uniqueValue(for: "appid"), .string("10"))
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamLaunchQuestionsTests.swift b/Tests/NXLibraryCoreTests/SteamLaunchQuestionsTests.swift
new file mode 100644
index 00000000..174ec373
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamLaunchQuestionsTests.swift
@@ -0,0 +1,229 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class SteamLaunchQuestionsTests: XCTestCase {
+ private func date(_ seconds: TimeInterval) -> Date { Date(timeIntervalSince1970: seconds) }
+ private func line(_ app: UInt32 = 2141910, _ text: String) -> String {
+ "[2026-11-14 18:03:08] GameAction [AppID \(app), ActionID 1] : LaunchApp \(text)\n"
+ }
+ private func waiting(_ app: UInt32 = 2141910, _ task: String = "KickingOtherSession") -> String {
+ line(app, "waiting for user response to \(task) \"Game\"")
+ }
+
+ func testAQuestionAnsweredAtOnceIsNotAsking() {
+ var questions = SteamLaunchQuestions()
+ questions.read(waiting(2141910, "ShowInterstitials") + line(2141910, "continues with user response \"ShowInterstitials\""),
+ now: date(0))
+ XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(5)))
+ }
+
+ func testColdStartInterstitialDoesNotDismissTheCoverBeforeARealQuestion() {
+ var questions = SteamLaunchQuestions()
+ questions.read(line(2141910, "changed task to ShowInterstitials with \"\"")
+ + line(2141910, "waiting for user response to ShowInterstitials \"\""), now: date(7))
+ XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(9)))
+
+ questions.read(waiting(), now: date(10))
+ XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(10.5)))
+ XCTAssertTrue(questions.isAsking(appID: 2141910, now: date(11)))
+ }
+
+ func testAnOpenQuestionAsksOnceItOutlastsTheGrace() {
+ var questions = SteamLaunchQuestions()
+ questions.read(waiting(), now: date(10))
+ XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(10.5)))
+ XCTAssertTrue(questions.isAsking(appID: 2141910, now: date(10 + SteamLaunchQuestions.grace)))
+ }
+
+ func testAnotherGamesQuestionIsNotOurs() {
+ var questions = SteamLaunchQuestions()
+ questions.read(waiting(440), now: date(0))
+ XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(5)))
+ XCTAssertTrue(questions.isAsking(appID: 440, now: date(5)))
+ }
+
+ func testTheLaunchMovingOnClearsTheQuestion() {
+ var questions = SteamLaunchQuestions()
+ questions.read(waiting(), now: date(0))
+ questions.read(line(2141910, "changed task to SynchronizingCloud with \"\""), now: date(3))
+ XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(5)))
+ }
+
+ func testAQuestionRepeatedKeepsWhenItWasFirstSeen() {
+ var questions = SteamLaunchQuestions()
+ questions.read(waiting(), now: date(0))
+ questions.read(waiting(), now: date(0.9))
+ XCTAssertTrue(questions.isAsking(appID: 2141910, now: date(1)))
+ }
+
+ func testOtherLinesAreIgnored() {
+ var questions = SteamLaunchQuestions()
+ questions.read("[2026-11-14 18:13:38] ExecuteSteamURL: \"steam://run/2141910\"\n"
+ + "waiting for user response to KickingOtherSession\n", now: date(0))
+ XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(5)))
+ }
+
+ func testResetForgetsEverything() {
+ var questions = SteamLaunchQuestions()
+ questions.read(waiting(), now: date(0))
+ questions.read("[2026-11-14 18:03:09] GameAction [AppID 2141910, Act", now: date(0))
+ questions.reset()
+ XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(5)))
+ questions.read("ionID 1] : LaunchApp waiting for user response to X \"\"\n", now: date(5))
+ XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(9)), "the half line before the reset is gone")
+ }
+
+ /// Steam's own sequence for a game already playing elsewhere (console_log.txt, 14 Nov 2026).
+ func testSteamsSequenceForASessionElsewhereAsks() {
+ let log = """
+ [2026-11-14 18:03:07] ExecuteSteamURL: "steam://run/2141910"
+ [2026-11-14 18:03:07] GameAction [AppID 2141910, ActionID 1] : LaunchApp changed task to RunningInstallScript with ""
+ [2026-11-14 18:03:07] GameAction [AppID 2141910, ActionID 1] : LaunchApp changed task to SynchronizingStats with ""
+ [2026-11-14 18:03:07] CAPIJobRequestUserStats - Server response failed 2
+ [2026-11-14 18:03:07] GameAction [AppID 2141910, ActionID 1] : LaunchApp changed task to ShowInterstitials with ""
+ [2026-11-14 18:03:07] GameAction [AppID 2141910, ActionID 1] : LaunchApp waiting for user response to ShowInterstitials ""
+ [2026-11-14 18:03:07] GameAction [AppID 2141910, ActionID 1] : LaunchApp continues with user response "ShowInterstitials"
+ [2026-11-14 18:03:07] GameAction [AppID 2141910, ActionID 1] : LaunchApp changed task to SynchronizingControllerConfig with ""
+ [2026-11-14 18:03:08] GameAction [AppID 2141910, ActionID 1] : LaunchApp changed task to KickingOtherSession with ""
+ [2026-11-14 18:03:08] GameAction [AppID 2141910, ActionID 1] : LaunchApp waiting for user response to KickingOtherSession "DRAGON BALL: Sparking! ZERO"
+
+ """
+ var questions = SteamLaunchQuestions()
+ questions.read(log, now: date(0))
+ XCTAssertTrue(questions.isAsking(appID: 2141910, now: date(1)))
+ }
+}
+
+final class SteamConsoleLogTests: XCTestCase {
+ private var folder: URL!
+ private var file: URL { folder.appendingPathComponent("logs/console_log.txt") }
+
+ override func setUpWithError() throws {
+ folder = FileManager.default.temporaryDirectory.appendingPathComponent("SteamConsoleLog-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: folder.appendingPathComponent("logs"), withIntermediateDirectories: true)
+ }
+
+ override func tearDown() {
+ try? FileManager.default.removeItem(at: folder)
+ super.tearDown()
+ }
+
+ private func append(_ text: String) throws {
+ if !FileManager.default.fileExists(atPath: file.path) { FileManager.default.createFile(atPath: file.path, contents: nil) }
+ let handle = try FileHandle(forWritingTo: file)
+ defer { try? handle.close() }
+ try handle.seekToEnd()
+ try handle.write(contentsOf: Data(text.utf8))
+ }
+
+ func testTheLogLivesInSteamsLogsFolder() {
+ XCTAssertEqual(SteamConsoleLog(steamRoot: folder).fileURL, file)
+ }
+
+ func testAMissingLogReadsNothing() {
+ var log = SteamConsoleLog(steamRoot: folder)
+ XCTAssertNil(log.readNew())
+ }
+
+ func testTheFirstReadTakesTheFileThenOnlyWhatWasAdded() throws {
+ try append("one\n")
+ var log = SteamConsoleLog(steamRoot: folder)
+ XCTAssertEqual(log.readNew()?.text, "one\n")
+ XCTAssertEqual(log.readNew()?.isNewFile, false)
+ XCTAssertEqual(log.readNew()?.text, "")
+ try append("two\n")
+ let next = log.readNew()
+ XCTAssertEqual(next?.text, "two\n")
+ XCTAssertEqual(next?.isNewFile, false)
+ }
+
+ func testTheFirstReadIsANewFile() throws {
+ try append("one\n")
+ var log = SteamConsoleLog(steamRoot: folder)
+ XCTAssertEqual(log.readNew()?.isNewFile, true)
+ }
+
+ func testANewFileFromAStartingSteamIsReadFromTheTop() throws {
+ try append("an old session that ran long\n")
+ var log = SteamConsoleLog(steamRoot: folder)
+ _ = log.readNew()
+ try FileManager.default.removeItem(at: file)
+ try append("new\n")
+ let next = log.readNew()
+ XCTAssertEqual(next?.text, "new\n")
+ XCTAssertEqual(next?.isNewFile, true)
+ }
+
+ func testAShorterFileIsANewFile() throws {
+ try append("an old session that ran long\n")
+ var log = SteamConsoleLog(steamRoot: folder)
+ _ = log.readNew()
+ try Data("new\n".utf8).write(to: file)
+ XCTAssertEqual(log.readNew()?.isNewFile, true)
+ }
+
+ /// A line Steam is still writing is read once it ends, so a character cut between two reads stays whole.
+ func testACharacterCutBetweenReadsStaysWhole() throws {
+ let line = Data("GameAction \"Pokémon\"\n".utf8)
+ let cut = line.firstIndex(of: 0xC3)! + 1
+ try line[.. Date { Date(timeIntervalSince1970: seconds) }
+ private let question = "[2026-11-14 18:03:08] GameAction [AppID 2141910, ActionID 1] : LaunchApp waiting for user response to KickingOtherSession \"Game\"\n"
+
+ override func setUpWithError() throws {
+ folder = FileManager.default.temporaryDirectory.appendingPathComponent("SteamQuestionWatch-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: folder.appendingPathComponent("logs"), withIntermediateDirectories: true)
+ }
+
+ override func tearDown() {
+ try? FileManager.default.removeItem(at: folder)
+ super.tearDown()
+ }
+
+ /// Steam asked before this Play and still waits: a new steam://run adds no GameAction line.
+ func testAQuestionStillOpenFromAnEarlierPlayAsks() throws {
+ try Data((question + "[2026-11-14 18:13:38] ExecuteSteamURL: \"steam://run/2141910\"\n").utf8).write(to: file)
+ var watch = SteamLaunchQuestionWatch(appID: 2141910, steamRoot: folder)
+ XCTAssertFalse(watch.look(now: date(0)))
+ XCTAssertTrue(watch.look(now: date(1)))
+ }
+
+ func testAStartingSteamsNewLogForgetsTheOldQuestion() throws {
+ try Data(question.utf8).write(to: file)
+ var watch = SteamLaunchQuestionWatch(appID: 2141910, steamRoot: folder)
+ _ = watch.look(now: date(0))
+ try FileManager.default.removeItem(at: file)
+ try Data("[2026-11-14 18:20:00] Console Log Start\n".utf8).write(to: file)
+ XCTAssertFalse(watch.look(now: date(5)))
+ }
+
+ func testWithoutALogNothingAsks() {
+ var watch = SteamLaunchQuestionWatch(appID: 2141910, steamRoot: folder)
+ XCTAssertFalse(watch.look(now: date(5)))
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamLibrarySourceTests.swift b/Tests/NXLibraryCoreTests/SteamLibrarySourceTests.swift
new file mode 100644
index 00000000..64b6caa0
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamLibrarySourceTests.swift
@@ -0,0 +1,314 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class SteamLibrarySourceTests: XCTestCase {
+ func testFindsTwoDistinctGamesAndDoesNotWriteSourceFiles() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ try f.manifest(in: root, id: "20", name: "Second game", directory: "Second")
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ try f.app(at: "Steam/steamapps/common/Second/Game.app")
+ let before = try f.inventory()
+ let result = try SteamLibrarySource(root: root).scan()
+ XCTAssertEqual(result.games.map(\.appID), [10, 20])
+ XCTAssertEqual(result.games.map(\.name), ["First game", "Second game"])
+ XCTAssertEqual(result.games.map(\.state), [.nativeReady, .nativeReady])
+ XCTAssertEqual(result.games.first?.reportedSizeBytes, 100)
+ XCTAssertEqual(result.games.first?.buildID, "42")
+ XCTAssertTrue(result.libraries.first?.isComplete == true)
+ XCTAssertEqual(try f.inventory(), before)
+ }
+
+ func testModernAndLegacyIndexesIncludeExternalLibrariesAndDeduplicatePaths() throws {
+ for modern in [false, true] {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library(), external = try f.library("External library")
+ try f.manifest(in: external)
+ try f.app(at: "External library/steamapps/common/First/Game.app")
+ let value = modern ? "{ path \(SteamTestFixture.quote(external.path)) label \"\" }" : SteamTestFixture.quote(external.path)
+ let index = "libraryfolders { 0 { path \(SteamTestFixture.quote(root.path)) } 1 \(value) 2 \(value) }"
+ try Data(index.utf8).write(to: root.appendingPathComponent("steamapps/libraryfolders.vdf"))
+ let result = try SteamLibrarySource(root: root).scan()
+ XCTAssertEqual(result.libraries.count, 2)
+ XCTAssertEqual(result.games.map(\.appID), [10])
+ }
+ }
+
+ func testMissingOrMalformedIndexDoesNotHideDefaultLibraryOrItsError() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ XCTAssertEqual(try SteamLibrarySource(root: root).scan().games.count, 1)
+ try Data("libraryfolders {".utf8).write(to: root.appendingPathComponent("steamapps/libraryfolders.vdf"))
+ let partial = try SteamLibrarySource(root: root).scan()
+ XCTAssertEqual(partial.games.count, 1)
+ XCTAssertTrue(partial.issues.contains { $0.reason == .invalidIndex })
+ XCTAssertFalse(partial.libraries[0].isComplete)
+ }
+
+ func testUnavailableExternalLibraryIsNotASuccessfulEmptyScan() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library(), absent = f.root.appendingPathComponent("disconnected")
+ let index = "libraryfolders { 1 { path \(SteamTestFixture.quote(absent.path)) } }"
+ try Data(index.utf8).write(to: root.appendingPathComponent("steamapps/libraryfolders.vdf"))
+ let result = try SteamLibrarySource(root: root).scan()
+ let observation = try XCTUnwrap(result.libraries.first { $0.root.path == absent.path })
+ XCTAssertFalse(observation.isReadable)
+ XCTAssertFalse(observation.isComplete)
+ XCTAssertTrue(result.issues.contains { $0.reason == .unavailableLibrary })
+ }
+
+ func testInvalidManifestRetainsFilenameIdentityInIssueContext() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ let manifest = try f.manifest(in: root)
+ try Data("AppState {".utf8).write(to: manifest)
+ let result = try SteamLibrarySource(root: root).scan()
+ XCTAssertTrue(result.games.isEmpty)
+ XCTAssertTrue(result.issues.contains { $0.reason == .invalidManifest && $0.appID == 10 })
+ XCTAssertFalse(result.libraries[0].isComplete)
+ }
+
+ func testDuplicateOrWrongTypedKnownScalarsRejectTheManifest() throws {
+ for field in ["APPID 10", "NAME Other", "INSTALLDIR First", "SizeOnDisk {}", "buildid {}", "StateFlags {}"] {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ let manifest = root.appendingPathComponent("steamapps/appmanifest_10.acf")
+ try Data("AppState { appid 10 name Fixture installdir First \(field) }".utf8).write(to: manifest)
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ let result = try SteamLibrarySource(root: root).scan()
+ XCTAssertTrue(result.games.isEmpty, field)
+ XCTAssertTrue(result.issues.contains { $0.reason == .invalidManifest && $0.appID == 10 }, field)
+ XCTAssertFalse(result.libraries[0].isComplete, field)
+ }
+ }
+
+ func testDuplicateOrWrongTypedLibraryPathPreservesDefaultLibraryAndReportsInvalidIndex() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ for path in ["path {}", "path \"/Volumes/First\" PATH \"/Volumes/Second\""] {
+ let index = root.appendingPathComponent("steamapps/libraryfolders.vdf")
+ try Data("libraryfolders { 1 { \(path) } }".utf8).write(to: index)
+ let result = try SteamLibrarySource(root: root).scan()
+ XCTAssertEqual(result.games.map(\.appID), [10])
+ XCTAssertTrue(result.issues.contains { $0.reason == .invalidIndex })
+ XCTAssertFalse(result.libraries[0].isComplete)
+ }
+ }
+
+ func testRejectsMismatchedOrInvalidAppIdentifiers() throws {
+ for id in ["20", "+10", "0", "4294967296", "a10"] {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root, id: id, filenameID: "10")
+ let result = try SteamLibrarySource(root: root).scan()
+ XCTAssertTrue(result.games.isEmpty, id)
+ XCTAssertFalse(result.issues.isEmpty, id)
+ }
+ }
+
+ func testEscapedUnicodeNamesAndInvalidOptionalSizes() throws {
+ for size in ["-1", "9223372036854775808"] {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root, name: "L'avventura \"è\" bella", directory: "Gioco è", size: size)
+ try f.app(at: "Steam/steamapps/common/Gioco è/Game.app")
+ let result = try SteamLibrarySource(root: root).scan()
+ XCTAssertEqual(result.games.first?.name, "L'avventura \"è\" bella")
+ XCTAssertNil(result.games.first?.reportedSizeBytes)
+ XCTAssertEqual(result.games.first?.state, .nativeReady)
+ }
+ }
+
+ func testUnsafeInstallDirectoryDoesNotEscapeTheLibrary() throws {
+ for directory in ["../escape", "/tmp/escape", "First/../../escape"] {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root, directory: directory)
+ let result = try SteamLibrarySource(root: root).scan()
+ XCTAssertTrue(result.games.isEmpty)
+ XCTAssertTrue(result.issues.contains { $0.reason == .unsafePath })
+ }
+ }
+
+ func testSymlinkInstallEscapeIsRejected() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ let externalApp = try f.app(at: "Elsewhere/Game.app")
+ try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("steamapps/common/First"),
+ withDestinationURL: externalApp.deletingLastPathComponent())
+ let result = try SteamLibrarySource(root: root).scan()
+ XCTAssertTrue(result.games.isEmpty)
+ XCTAssertTrue(result.issues.contains { $0.reason == .unsafePath })
+ }
+
+ func testSymlinkedSteamappsCannotSupplyAnIndexOutsideTheChosenRoot() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library(), foreign = try f.library("Foreign"), third = try f.library("Third")
+ try f.manifest(in: third)
+ try f.app(at: "Third/steamapps/common/First/Game.app")
+ try Data("libraryfolders { 1 \(SteamTestFixture.quote(third.path)) }".utf8)
+ .write(to: foreign.appendingPathComponent("steamapps/libraryfolders.vdf"))
+ try FileManager.default.removeItem(at: root.appendingPathComponent("steamapps"))
+ try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("steamapps"),
+ withDestinationURL: foreign.appendingPathComponent("steamapps"))
+ let result = try SteamLibrarySource(root: root).scan()
+ XCTAssertTrue(result.games.isEmpty)
+ XCTAssertEqual(result.libraries.count, 1)
+ XCTAssertTrue(result.issues.contains { $0.reason == .unsafePath })
+ }
+
+ func testLibraryAndManifestLimitsAreReported() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library(), external = try f.library("External")
+ try f.manifest(in: root)
+ try f.manifest(in: root, id: "20", directory: "Second")
+ try Data("libraryfolders { 1 \(SteamTestFixture.quote(external.path)) }".utf8)
+ .write(to: root.appendingPathComponent("steamapps/libraryfolders.vdf"))
+ var limits = SteamScanLimits.standard
+ limits.maximumLibraries = 1
+ limits.maximumManifests = 1
+ let result = try SteamLibrarySource(root: root, limits: limits).scan()
+ XCTAssertEqual(result.libraries.count, 1)
+ XCTAssertEqual(result.games.count, 1)
+ XCTAssertFalse(result.isComplete)
+ XCTAssertTrue(result.issues.contains { $0.reason == .libraryLimit })
+ XCTAssertTrue(result.issues.contains { $0.reason == .manifestLimit })
+ }
+
+ func testDuplicateAppIdsAcrossLibrariesRemainAmbiguousObservations() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library(), second = try f.library("Other")
+ for library in [root, second] { try f.manifest(in: library) }
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ try f.app(at: "Other/steamapps/common/First/Game.app")
+ try Data("libraryfolders { 1 \(SteamTestFixture.quote(second.path)) }".utf8)
+ .write(to: root.appendingPathComponent("steamapps/libraryfolders.vdf"))
+ let result = try SteamLibrarySource(root: root).scan()
+ XCTAssertEqual(result.games.count, 2)
+ XCTAssertTrue(result.games.allSatisfy { $0.state == .requiresReview })
+ XCTAssertTrue(result.issues.contains { $0.reason == .conflictingIdentity })
+ }
+
+ func testMainGameAndHelperAreNotTwoGames() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ try f.app(at: "Steam/steamapps/common/First/Helper.app", category: nil)
+ let result = try SteamLibrarySource(root: root).scan()
+ XCTAssertEqual(result.games.first?.state, .nativeReady)
+ XCTAssertEqual(result.games.first?.nativeApps.filter(\.isDeclaredGame).count, 1)
+ }
+
+ func testRecognizedTopLevelGameDoesNotRequireWalkingItsLooseDataTree() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ try FileManager.default.createDirectory(at: root.appendingPathComponent("steamapps/common/First/LooseData/deep/assets"),
+ withIntermediateDirectories: true)
+ var limits = SteamScanLimits.standard
+ limits.maximumDirectoriesPerInstall = 1
+ let result = try SteamLibrarySource(root: root, limits: limits).scan()
+ XCTAssertEqual(result.games.first?.state, .nativeReady)
+ XCTAssertTrue(result.isComplete)
+ }
+
+ func testToolsUnclassifiedAndMultipleMainAppsAreNotConfirmedGames() throws {
+ for categories: [String?] in [["public.app-category.developer-tools"], [nil],
+ ["public.app-category.games", "public.app-category.games"]] {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ for (i, category) in categories.enumerated() {
+ try f.app(at: "Steam/steamapps/common/First/App\(i).app", category: category)
+ }
+ XCTAssertEqual(try SteamLibrarySource(root: root).scan().games.first?.state, .requiresReview)
+ }
+ }
+
+ func testMissingContentAndWindowsOnlyDirectoryAreNotNativeReady() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ XCTAssertEqual(try SteamLibrarySource(root: root).scan().games.first?.state, .unavailable)
+ let install = root.appendingPathComponent("steamapps/common/First")
+ try FileManager.default.createDirectory(at: install, withIntermediateDirectories: true)
+ try Data("synthetic".utf8).write(to: install.appendingPathComponent("game.exe"))
+ XCTAssertEqual(try SteamLibrarySource(root: root).scan().games.first?.state, .unavailable)
+ }
+
+ func testLimitsDoNotReturnADeceptivelyCompleteLibrary() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root)
+ try f.app(at: "Steam/steamapps/common/First/deep/Game.app")
+ var limits = SteamScanLimits.standard
+ limits.maximumDirectoriesPerInstall = 1
+ let limited = try SteamLibrarySource(root: root, limits: limits).scan()
+ XCTAssertFalse(limited.libraries[0].isComplete)
+ XCTAssertTrue(limited.issues.contains { $0.reason == .directoryLimit })
+ limits = .standard
+ limits.maximumTextBytes = 10
+ let oversized = try SteamLibrarySource(root: root, limits: limits).scan()
+ XCTAssertTrue(oversized.games.isEmpty)
+ XCTAssertTrue(oversized.issues.contains { $0.reason == .oversizedManifest })
+ }
+
+ func testCancellationThrowsRatherThanPublishingPartialResults() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ XCTAssertThrowsError(try SteamLibrarySource(root: root).scan(cancelled: { true })) {
+ XCTAssertTrue($0 is CancellationError)
+ }
+ }
+
+ func testSourceSnapshotDetectsAFileChangingBeforePublication() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ let file = try f.manifest(in: root)
+ let snapshot = try InstallationFileSnapshot.read(at: file, maximumBytes: 1024)
+ try Data("changed".utf8).write(to: file, options: .atomic)
+ XCTAssertThrowsError(try snapshot.verifyUnchanged())
+ XCTAssertEqual(try String(contentsOf: file), "changed")
+ }
+
+ func testManifestWithoutFullyInstalledIsDownloadingAndNotWalked() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root, stateFlags: "1026")
+ // A partial bundle Steam is still writing: it must not be read or raise an issue.
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ let result = try SteamLibrarySource(root: root).scan()
+ XCTAssertEqual(result.games.map(\.state), [.downloading])
+ XCTAssertEqual(result.games.first?.nativeApps, [])
+ XCTAssertTrue(result.issues.isEmpty)
+ }
+
+ func testFullyInstalledBitWinsOverUpdateBits() throws {
+ for flags in ["6", "1030"] {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root, stateFlags: flags)
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ XCTAssertEqual(try SteamLibrarySource(root: root).scan().games.map(\.state), [.nativeReady], flags)
+ }
+ }
+
+ func testMissingOrGarbageStateFlagsKeepTodayBehaviour() throws {
+ for flags in [nil, "abc"] as [String?] {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ try f.manifest(in: root, stateFlags: flags)
+ try f.manifest(in: root, id: "20", name: "Empty", directory: "Empty", stateFlags: flags)
+ try f.app(at: "Steam/steamapps/common/First/Game.app")
+ XCTAssertEqual(try SteamLibrarySource(root: root).scan().games.map(\.state), [.nativeReady, .unavailable])
+ }
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamManifestWatcherTests.swift b/Tests/NXLibraryCoreTests/SteamManifestWatcherTests.swift
new file mode 100644
index 00000000..e476f5ca
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamManifestWatcherTests.swift
@@ -0,0 +1,81 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class SteamManifestWatcherTests: XCTestCase {
+ func testOnlyManifestsAndTheLibraryIndexAreRelevant() {
+ let root = "/Users/p/Library/Application Support/Steam", second = "/Volumes/Games/SteamLibrary"
+ let libraries = [root, second] // as `watch` keeps them: resolved paths
+ func relevant(_ path: String) -> Bool { SteamManifestWatcher.isRelevant(path, libraries: libraries, root: root) }
+ XCTAssertTrue(relevant(root + "/steamapps/appmanifest_3321460.acf"))
+ XCTAssertTrue(relevant(second + "/steamapps/appmanifest_10.acf"))
+ XCTAssertTrue(relevant(root + "/steamapps/libraryfolders.vdf"))
+ XCTAssertFalse(relevant(second + "/steamapps/libraryfolders.vdf"))
+ XCTAssertFalse(relevant(root + "/steamapps/downloading/3321460/data.bin"))
+ XCTAssertFalse(relevant(root + "/steamapps/common/Game/appmanifest_1.acf"))
+ XCTAssertFalse(relevant(root + "/steamapps/appmanifest_1.acf.tmp"))
+ XCTAssertFalse(relevant(root + "/steamapps/appmanifest_x.acf"))
+ XCTAssertFalse(relevant(root + "/steamapps/appmanifest_.acf"))
+ XCTAssertFalse(relevant("/Volumes/Other/steamapps/appmanifest_1.acf"))
+ XCTAssertFalse(relevant(root + "/steamapps"))
+ }
+
+ func testDroppedEventsCountOnlyForASteamappsFolderOrAbove() {
+ let root = "/Users/p/Library/Application Support/Steam"
+ func dropped(_ path: String) -> Bool { SteamManifestWatcher.isRelevant(path, dropped: true, libraries: [root], root: root) }
+ // A drop inside a download's folder says nothing about the manifests: no rescan every batch.
+ XCTAssertFalse(dropped(root + "/steamapps/downloading/3321460"))
+ XCTAssertFalse(dropped(root + "/steamapps/common/Game"))
+ XCTAssertTrue(dropped(root + "/steamapps"))
+ XCTAssertTrue(dropped(root + "/steamapps/"))
+ XCTAssertTrue(dropped("/Users/p/Library"))
+ XCTAssertFalse(dropped("/Volumes/Other"))
+ XCTAssertTrue(SteamManifestWatcher.isRelevant(root + "/steamapps/appmanifest_1.acf", dropped: false, libraries: [root], root: root))
+ }
+
+ @MainActor
+ func testRetriesTheSameLibraryWhenItsFolderBecomesAvailable() async throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let library = f.root.appendingPathComponent("Later")
+ let changed = expectation(description: "Newly available library is watched")
+ let watcher = SteamManifestWatcher { changed.fulfill() }
+ defer { watcher.stop() }
+ watcher.watch([library], root: library)
+ _ = try f.library("Later")
+ watcher.watch([library], root: library)
+ try f.manifest(in: library)
+ await fulfillment(of: [changed], timeout: 6)
+ }
+
+ @MainActor
+ func testAddsANewlyAvailableLibraryAlongsideAnExistingStream() async throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let root = try f.library()
+ let library = f.root.appendingPathComponent("Later")
+ let changed = expectation(description: "Additional library is watched")
+ let watcher = SteamManifestWatcher { changed.fulfill() }
+ defer { watcher.stop() }
+ watcher.watch([root, library], root: root)
+ _ = try f.library("Later")
+ watcher.watch([root, library], root: root)
+ try f.manifest(in: library)
+ await fulfillment(of: [changed], timeout: 6)
+ }
+
+ @MainActor
+ func testTheStreamKeepsItsWatcherAliveUntilStopped() throws {
+ let f = try SteamTestFixture.temporary(in: self)
+ let library = try f.library()
+ weak var weakWatcher: SteamManifestWatcher?
+ do {
+ let watcher = SteamManifestWatcher()
+ watcher.watch([library], root: library)
+ weakWatcher = watcher
+ }
+ // A callback already queued must still find its watcher.
+ XCTAssertNotNil(weakWatcher)
+ weakWatcher?.stop()
+ // The stream lets go of its context on its queue (the main one).
+ RunLoop.main.run(until: Date().addingTimeInterval(0.2))
+ XCTAssertNil(weakWatcher)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamMetadataTests.swift b/Tests/NXLibraryCoreTests/SteamMetadataTests.swift
new file mode 100644
index 00000000..ac503373
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamMetadataTests.swift
@@ -0,0 +1,209 @@
+import XCTest
+import AppKit
+@testable import NXLibraryCore
+
+final class SteamMetadataTests: XCTestCase {
+ private func payload(id: Int = 10) -> Data {
+ Data("""
+ {"10":{"success":true,"data":{"steam_appid":\(id),"name":"Fixture","short_description":"A & B","genres":[{"id":"2","description":"Strategia"}],"developers":["Studio"],"publishers":["Publisher"],"release_date":{"date":"23 mag 2023"},"screenshots":[{"path_full":"https://shared.akamai.steamstatic.com/test.jpg"},{"path_full":"http://localhost/private"}]}}}
+ """.utf8)
+ }
+ func testIdentityLocalizedFieldsAndSafeScreenshots() throws {
+ let value = try SteamMetadata.decode(payload(), appID: 10, language: "italian")
+ XCTAssertEqual(value.description, "A & B")
+ XCTAssertEqual(value.genres, ["Strategia"])
+ XCTAssertEqual(value.screenshots.count, 1)
+ XCTAssertEqual(value.releaseDate, "23 mag 2023")
+ XCTAssertThrowsError(try SteamMetadata.decode(payload(id: 20), appID: 10, language: "italian"))
+ XCTAssertThrowsError(try SteamMetadata.decode(Data("{}".utf8), appID: 10, language: "italian"))
+ XCTAssertNil(SteamMetadata.safeImage(URL(string: "https://steamstatic.com.attacker.test/x")))
+ }
+ func testLanguageMappingIsIndependentOfRegionalFormats() {
+ XCTAssertEqual(SteamMetadata.language(.portugueseBrazil), "brazilian")
+ XCTAssertEqual(SteamMetadata.language(.italian), "italian")
+ }
+ func testRelatedTraitsReadTheRequestedLanguageFromCacheWithoutNetwork() async throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let body = payload()
+ let online = SteamMetadataService(directory: root, transport: { _ in body })
+ _ = await online.metadata(appID: 10, language: "italian")
+ let cached = SteamMetadataService(directory: root, transport: { _ in
+ XCTFail("Recommendations must read the cache without fetching other games")
+ throw URLError(.notConnectedToInternet)
+ })
+ let italian = await cached.cachedRelatedTraits(appIDs: [10, 20], language: "italian")
+ let english = await cached.cachedRelatedTraits(appIDs: [10], language: "english")
+ XCTAssertEqual(italian[10]?.genres, ["Strategia"])
+ XCTAssertEqual(italian[10]?.developers, ["Studio"])
+ XCTAssertNil(italian[20])
+ XCTAssertTrue(english.isEmpty)
+ }
+ func testOfflineCacheAndPersonalDataAreIndependentOfRefresh() async throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let body = payload()
+ let online = SteamMetadataService(directory: root, transport: { _ in body })
+ let first = await online.metadata(appID: 10, language: "italian")
+ XCTAssertEqual(first?.genres, ["Strategia"])
+ let offline = SteamMetadataService(directory: root, transport: { _ in throw URLError(.notConnectedToInternet) })
+ let retained = await offline.metadata(appID: 10, language: "italian", refresh: true)
+ XCTAssertEqual(retained, first)
+ let other = await offline.metadata(appID: 10, language: "english")
+ XCTAssertNil(other)
+ let picks = MetadataPicks(directory: root.appendingPathComponent("personal"))
+ picks.set("My description", titleID: "10", field: .description)
+ _ = await online.metadata(appID: 10, language: "italian", refresh: true)
+ XCTAssertEqual(picks.value(titleID: "10", field: .description), "My description")
+ }
+ func testConcurrentMetadataRequestsShareOneTransport() async throws {
+ actor Counter {
+ var count = 0
+ func bump() { count += 1 }
+ }
+ let counter = Counter(), body = payload()
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = SteamMetadataService(directory: root, transport: { _ in
+ await counter.bump(); try await Task.sleep(nanoseconds: 30_000_000); return body
+ })
+ async let a = service.metadata(appID: 10, language: "english")
+ async let b = service.metadata(appID: 10, language: "english")
+ let values = await (a, b)
+ XCTAssertNotNil(values.0); XCTAssertEqual(values.0?.description, values.1?.description)
+ let count = await counter.count
+ XCTAssertEqual(count, 1)
+ }
+ func testFailedPersonalSaveDoesNotPublishUnsavedValues() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ try Data("not a folder".utf8).write(to: root)
+ let picks = SteamPersonalizationStore(directory: root)
+ XCTAssertThrowsError(try picks.save(fields: [.description: "Lost"], images: [:], automatic: [], titleID: "10"))
+ XCTAssertNil(picks.value(titleID: "10", field: .description))
+ XCTAssertEqual(picks.revision, 0)
+ }
+ func testStoreFailuresAndNonHTTPSImagesAreRejected() throws {
+ XCTAssertThrowsError(try SteamMetadata.decode(Data("{\"10\":{\"success\":false}}".utf8), appID: 10, language: "english"))
+ for text in ["http://cdn.steamstatic.com/a", "https://user@cdn.steamstatic.com/a", "https://cdn.steamstatic.com:444/a", "file:///tmp/a"] {
+ XCTAssertNil(SteamMetadata.safeImage(URL(string: text)))
+ }
+ }
+
+ func testSemanticFailuresBackOffWithoutLosingTheLibrary() async {
+ actor Calls { var count = 0; func bump() { count += 1 } }
+ let calls = Calls()
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = SteamMetadataService(directory: root, transport: { _ in await calls.bump(); return Data("{}".utf8) })
+ let first = await service.metadata(appID: 10, language: "english")
+ let second = await service.metadata(appID: 10, language: "english")
+ XCTAssertNil(first); XCTAssertNil(second)
+ let count = await calls.count; XCTAssertEqual(count, 1)
+ }
+ func testCancellingSoleImageWaiterStopsTransportAndFallbacks() async {
+ actor Calls { var count = 0; func bump() { count += 1 } }
+ let calls = Calls(), started = expectation(description: "started"), stopped = expectation(description: "cancelled")
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = SteamMetadataService(directory: root, transport: { _ in
+ await calls.bump(); started.fulfill()
+ do { try await Task.sleep(nanoseconds: 10_000_000_000); return Data() }
+ catch { stopped.fulfill(); throw error }
+ })
+ let request = Task { await service.image(appID: 10, slot: .cover) }
+ await fulfillment(of: [started], timeout: 1)
+ request.cancel()
+ await fulfillment(of: [stopped], timeout: 1)
+ let image = await request.value; XCTAssertNil(image)
+ let count = await calls.count; XCTAssertEqual(count, 1)
+ }
+ func testCancelledSharedWaiterPreservesInterestedReader() async {
+ let started = expectation(description: "started"), body = payload()
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = SteamMetadataService(directory: root, transport: { _ in
+ started.fulfill(); try await Task.sleep(nanoseconds: 150_000_000); return body
+ })
+ let a = Task { await service.metadata(appID: 10, language: "english") }
+ await fulfillment(of: [started], timeout: 1)
+ let b = Task { await service.metadata(appID: 10, language: "english") }
+ try? await Task.sleep(nanoseconds: 30_000_000)
+ a.cancel()
+ let result = await b.value; XCTAssertNotNil(result)
+ let cancelled = await a.value; XCTAssertNil(cancelled)
+ }
+ func testFailedCombinedDraftKeepsAllPreviousPicksAndAutomaticReferences() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let image = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 2, pixelsHigh: 2, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
+ let png = image.representation(using: .png, properties: [:])!
+ let initial = SteamPersonalizationStore(directory: root)
+ try initial.save(fields: [.description: "Previous"], images: [.cover: png], automatic: [], titleID: "10")
+ let original = initial.url(titleID: "10", slot: .cover)!
+ let before = try Data(contentsOf: original)
+ let failing = SteamPersonalizationStore(directory: root, publish: { _,_ in throw CocoaError(.fileWriteOutOfSpace) })
+ XCTAssertThrowsError(try failing.save(fields: [.description: "New"], images: [.logo: png], automatic: [.cover], titleID: "10"))
+ let restored = SteamPersonalizationStore(directory: root)
+ XCTAssertEqual(restored.value(titleID: "10", field: .description), "Previous")
+ XCTAssertEqual(restored.url(titleID: "10", slot: .cover), original)
+ XCTAssertEqual(try Data(contentsOf: original), before)
+ XCTAssertNil(restored.url(titleID: "10", slot: .logo))
+ XCTAssertEqual(failing.revision, 0)
+ try initial.save(fields: [:], images: [:], automatic: [.cover], titleID: "10")
+ XCTAssertNil(SteamPersonalizationStore(directory: root).url(titleID: "10", slot: .cover))
+ }
+
+ func testRedirectIsRefusedBeforeSendingAnotherRequest() {
+ let session = URLSession(configuration: .ephemeral)
+ defer { session.invalidateAndCancel() }
+ let initial = URL(string: "https://store.steampowered.com/api/appdetails")!
+ let task = session.dataTask(with: initial)
+ let response = HTTPURLResponse(url: initial, statusCode: 302, httpVersion: nil, headerFields: nil)!
+ let delegate = SteamMetadataService.NoRedirects()
+ var invoked = false
+ delegate.urlSession(session, task: task, willPerformHTTPRedirection: response,
+ newRequest: URLRequest(url: URL(string: "https://example.invalid/private")!)) { request in
+ invoked = true; XCTAssertNil(request)
+ }
+ XCTAssertTrue(invoked)
+ XCTAssertEqual(task.state, .suspended)
+ XCTAssertFalse(SteamMetadataService.allowed(URL(string: "http://store.steampowered.com/a")!))
+ }
+ func testInvalidImageBytesAreBackedOffForBothCandidateURLs() async {
+ actor Calls { var count = 0; func bump() { count += 1 } }
+ let calls = Calls(), root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = SteamMetadataService(directory: root, transport: { _ in await calls.bump(); return Data("invalid image".utf8) })
+ _ = await service.image(appID: 10, slot: .cover)
+ _ = await service.image(appID: 10, slot: .cover)
+ let count = await calls.count; XCTAssertEqual(count, 2)
+ }
+ func testSelectionBurstBoundsOutstandingTransfers() async {
+ actor Calls {
+ var active = 0, peak = 0
+ func enter() { active += 1; peak = max(peak, active) }
+ func leave() { active -= 1 }
+ }
+ let calls = Calls(), root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let service = SteamMetadataService(directory: root, transport: { _ in
+ await calls.enter(); try await Task.sleep(nanoseconds: 100_000_000); await calls.leave(); return Data("{}".utf8)
+ })
+ await withTaskGroup(of: Void.self) { group in
+ for id in 1...20 { group.addTask { _ = await service.metadata(appID: UInt32(id), language: "english") } }
+ }
+ let peak = await calls.peak; XCTAssertGreaterThan(peak, 0); XCTAssertLessThanOrEqual(peak, 6)
+ }
+ func testUnreadablePersonalManifestIsPreserved() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ let file = root.appendingPathComponent("personal.json"), original = Data("damaged".utf8)
+ try original.write(to: file)
+ let store = SteamPersonalizationStore(directory: root)
+ XCTAssertThrowsError(try store.save(fields: [.description: "New"], images: [:], automatic: [], titleID: "10"))
+ XCTAssertEqual(try Data(contentsOf: file), original)
+ }
+
+}
diff --git a/Tests/NXLibraryCoreTests/SteamOptionsTests.swift b/Tests/NXLibraryCoreTests/SteamOptionsTests.swift
new file mode 100644
index 00000000..3c74e331
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamOptionsTests.swift
@@ -0,0 +1,64 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class SteamOptionsTests: XCTestCase {
+ func testSteamMainRowsAreNxnativeCommonRowsInTheSameOrder() {
+ let nx = GameOptionsPresentation(supportsRenderScale: false, isPlayable: true, sourcesDetached: false)
+ for origin in [GameOptionsOrigin.spotlight, .collection] {
+ let steam = SteamOptionsPresentation(canPlay: true, hasApp: true).focusableRows(level: .main, origin: origin)
+ let shared = nx.focusableRows(level: .main, origin: origin).filter(steam.contains)
+ XCTAssertEqual(steam, shared)
+ }
+ XCTAssertTrue(SteamOptionsPresentation(canPlay: true, hasApp: true).focusableRows(level: .main, origin: .spotlight).contains(.move))
+ XCTAssertFalse(SteamOptionsPresentation(canPlay: true, hasApp: true).focusableRows(level: .main, origin: .collection).contains(.move))
+ }
+
+ func testSteamOptionsOfferNothingFromNxnative() {
+ let p = SteamOptionsPresentation(canPlay: true, hasApp: true)
+ let all = Set(p.focusableRows(level: .main, origin: .spotlight) + p.focusableRows(level: .editDetails, origin: .spotlight))
+ XCTAssertTrue(all.isDisjoint(with: [.fullscreen, .frameRate, .consoleMode, .cheats, .mods, .openSaves, .rebuild,
+ .attachSources, .openLog, .removeSources, .removeGame, .restoreDefaults]))
+ XCTAssertEqual(p.focusableRows(level: .editDetails, origin: .collection), [.changeArtwork, .changeMetadata, .storePage])
+ XCTAssertTrue(all.allSatisfy { p.about($0) != nil })
+ }
+
+ func testPlayAndFinderDimWithoutAnInstallation() {
+ let missing = SteamOptionsPresentation(canPlay: false, hasApp: false)
+ XCTAssertTrue(missing.isDimmed(.play))
+ XCTAssertTrue(missing.isDimmed(.showInFinder))
+ XCTAssertFalse(missing.isDimmed(.favorite))
+ XCTAssertFalse(SteamOptionsPresentation(canPlay: true, hasApp: true).isDimmed(.play))
+ }
+
+ func testSteamArtworkPutsTheExactAppFirstWithoutRepeats() throws {
+ let shot = try XCTUnwrap(URL(string: "https://shared.akamai.steamstatic.com/shot1.jpg"))
+ let steamCover = SteamStoreArt.candidates(appID: 10, slot: .cover)
+ let other = ArtworkCandidate(slot: .cover, source: "SteamGridDB", url: try XCTUnwrap(URL(string: "https://example.com/c.png")))
+ let covers = ArtworkCandidates.steamList(for: .cover, appID: 10, screenshots: [shot],
+ online: [steamCover[0], other, ArtworkCandidate(slot: .logo, source: "x", url: shot)])
+ XCTAssertEqual(covers.map(\.url), [steamCover[0].url, other.url])
+ let backgrounds = ArtworkCandidates.steamList(for: .background, appID: 10, screenshots: [shot])
+ XCTAssertEqual(backgrounds.map(\.source), ["Steam library", "Steam screenshot 1"])
+ XCTAssertTrue(ArtworkCandidates.steamList(for: .icon, appID: 10, screenshots: [shot]).isEmpty)
+ XCTAssertTrue(ArtworkCandidates.steamList(for: .cover, appID: 0, screenshots: []).isEmpty)
+ }
+}
+
+final class SteamLaunchSettingTests: XCTestCase {
+ func testSteamStaysInTheBackgroundByDefaultAndOldFilesKeepIt() throws {
+ XCTAssertTrue(AppSettings().steamInBackground)
+ let old = try JSONDecoder().decode(AppSettings.self, from: Data("{}".utf8))
+ XCTAssertTrue(old.steamInBackground)
+ var off = AppSettings(); off.steamInBackground = false
+ let back = try JSONDecoder().decode(AppSettings.self, from: JSONEncoder().encode(off))
+ XCTAssertFalse(back.steamInBackground)
+ }
+
+ func testTheSettingIsListedWithSteamAndMarkedChangedWhenOff() throws {
+ let row = try XCTUnwrap(SettingsCatalog.all.first { $0.id == "steamInBackground" })
+ XCTAssertEqual(row.group, .sources)
+ var off = AppSettings(); off.steamInBackground = false
+ XCTAssertTrue(row.isChanged(off))
+ XCTAssertFalse(row.isChanged(AppSettings()))
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamPlayStateTests.swift b/Tests/NXLibraryCoreTests/SteamPlayStateTests.swift
new file mode 100644
index 00000000..16289825
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamPlayStateTests.swift
@@ -0,0 +1,157 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class SteamPlayStateTests: XCTestCase {
+ private let app = CatalogNativeApplication(NativeMacApplication(
+ url: URL(fileURLWithPath: "/Steam/steamapps/common/Game/Game.app"),
+ executableURL: URL(fileURLWithPath: "/Steam/steamapps/common/Game/Game.app/Contents/MacOS/Game"),
+ bundleIdentifier: "com.example.game", name: "Game", architectures: [.arm64], isDeclaredGame: true, fileObservations: []))
+ private let t0 = Date(timeIntervalSince1970: 1_000_000)
+ private var game: NativeProcessObservation {
+ .init(pid: 42, bundleURL: app.url, executableURL: app.executableURL)
+ }
+ private let steamClient = NativeProcessObservation(pid: 7, bundleURL: URL(fileURLWithPath: "/Applications/Steam.app"),
+ executableURL: URL(fileURLWithPath: "/Applications/Steam.app/Contents/MacOS/steam_osx"))
+
+ func testAnInstallationReachedThroughASymlinkMatchesTheRunningApp() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let real = root.appendingPathComponent("Drive/common/Game")
+ try FileManager.default.createDirectory(at: real.appendingPathComponent("Game.app/Contents/MacOS"), withIntermediateDirectories: true)
+ try Data().write(to: real.appendingPathComponent("Game.app/Contents/MacOS/Game"))
+ try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("steamapps"), withDestinationURL: root.appendingPathComponent("Drive"))
+ let linked = root.appendingPathComponent("steamapps/common/Game/Game.app")
+ let installed = CatalogNativeApplication(NativeMacApplication(
+ url: linked, executableURL: linked.appendingPathComponent("Contents/MacOS/Game"),
+ bundleIdentifier: "com.example.game", name: "Game", architectures: [.arm64], isDeclaredGame: true, fileObservations: []))
+ // The system names the real path; the caller hands it over in canonical form.
+ let running = NativeProcessObservation(pid: 42, bundleURL: real.appendingPathComponent("Game.app"),
+ executableURL: real.appendingPathComponent("Game.app/Contents/MacOS/Game")).canonical()
+ var state = SteamPlayState()
+ XCTAssertEqual(state.observe([running], application: installed, now: t0), .started(pid: 42))
+ XCTAssertNil(state.observe([running], application: installed, now: t0.addingTimeInterval(30)), "still the same game")
+ }
+
+ func testHandOffStartsNoSessionUntilTheGameItselfRuns() {
+ var state = SteamPlayState()
+ XCTAssertEqual(state.requestPlay(target: .steam(appID: 570), clientAvailable: true, now: t0),
+ .handOff(URL(string: "steam://run/570")!, generation: 1))
+ state.handoffFinished(accepted: true, generation: 1)
+ XCTAssertNil(state.observe([steamClient], application: app, now: t0.addingTimeInterval(5)), "Steam alone is not the game")
+ XCTAssertEqual(state.phase, .starting(since: t0))
+ XCTAssertEqual(state.observe([steamClient, game], application: app, now: t0.addingTimeInterval(20)), .started(pid: 42))
+ XCTAssertEqual(state.requestPlay(target: .steam(appID: 570), clientAvailable: true, now: t0), .resume(pid: 42))
+ // The game quits while Steam stays open: the session ends.
+ XCTAssertEqual(state.observe([steamClient], application: app, now: t0.addingTimeInterval(600)), .ended(pid: 42))
+ XCTAssertEqual(state.phase, .idle)
+ }
+
+ func testDuplicatePlayAndLateAnswersChangeNothing() {
+ var state = SteamPlayState()
+ _ = state.requestPlay(target: .steam(appID: 570), clientAvailable: true, now: t0)
+ XCTAssertEqual(state.requestPlay(target: .steam(appID: 570), clientAvailable: true, now: t0), .wait)
+ state.cancel()
+ _ = state.requestPlay(target: .steam(appID: 570), clientAvailable: true, now: t0)
+ state.handoffFinished(accepted: false, generation: 1) // the cancelled request's answer
+ XCTAssertEqual(state.phase, .starting(since: t0))
+ state.handoffFinished(accepted: false, generation: state.generation)
+ XCTAssertEqual(state.phase, .failed(.handoffRejected))
+ }
+
+ func testRefusalsAndTimeoutNeverStartASession() {
+ var state = SteamPlayState()
+ XCTAssertEqual(state.requestPlay(target: nil, clientAvailable: true, now: t0), .refuse(.unavailable))
+ XCTAssertEqual(state.requestPlay(target: .nxnative(appURL: app.url), clientAvailable: true, now: t0), .refuse(.unavailable))
+ XCTAssertEqual(state.requestPlay(target: .steam(appID: 0), clientAvailable: true, now: t0), .refuse(.unavailable))
+ XCTAssertEqual(state.requestPlay(target: .steam(appID: 570), clientAvailable: false, now: t0), .refuse(.clientMissing))
+ _ = state.requestPlay(target: .steam(appID: 570), clientAvailable: true, now: t0)
+ XCTAssertNil(state.observe([], application: app, now: t0.addingTimeInterval(SteamPlayState.startDeadline + 1)))
+ XCTAssertEqual(state.phase, .failed(.notStarted))
+ // A game that appears later (an update finished) is still followed.
+ XCTAssertEqual(state.observe([game], application: app, now: t0.addingTimeInterval(900)), .started(pid: 42))
+ }
+
+ func testOnlyThisInstallationsAppMatches() {
+ let otherCopy = NativeProcessObservation(pid: 3, bundleURL: URL(fileURLWithPath: "/Volumes/Ext/Game.app"),
+ executableURL: URL(fileURLWithPath: "/Volumes/Ext/Game.app/Contents/MacOS/Game"))
+ let helper = NativeProcessObservation(pid: 4, bundleURL: app.url,
+ executableURL: app.url.appendingPathComponent("Contents/MacOS/CrashReporter"))
+ let withoutExecutable = NativeProcessObservation(pid: 1, bundleURL: app.url, executableURL: nil)
+ for (process, expected) in [(game, SteamPlayState.Change.started(pid: 42)),
+ (withoutExecutable, .started(pid: 1)), (steamClient, nil),
+ (otherCopy, nil), (helper, nil)] {
+ var state = SteamPlayState()
+ XCTAssertEqual(state.observe([process], application: app, now: t0), expected)
+ }
+ XCTAssertNil(SteamPlayState.launchURL(appID: 0))
+ }
+
+ func testAGameAlreadyRunningIsFollowedWithoutAPlay() {
+ var state = SteamPlayState()
+ XCTAssertEqual(state.observe([game], application: app, now: t0), .started(pid: 42))
+ // The same pid reused by another program is not mistaken for the game.
+ XCTAssertEqual(state.observe([.init(pid: 42, bundleURL: steamClient.bundleURL, executableURL: steamClient.executableURL)],
+ application: app, now: t0), .ended(pid: 42))
+ XCTAssertNil(state.observe([.init(pid: 42, bundleURL: steamClient.bundleURL, executableURL: steamClient.executableURL)],
+ application: app, now: t0))
+ }
+
+ func testARunningSessionFollowsTheProcessItSawStartNotTheInstallationNow() {
+ var state = SteamPlayState()
+ XCTAssertEqual(state.observe([game], application: app, now: t0), .started(pid: 42))
+ // The installation disappears from the catalog (a refresh): the game keeps playing.
+ XCTAssertNil(state.observe([game], application: nil, now: t0.addingTimeInterval(60)))
+ // The catalog now names the app at a new path: one session, not ended and started again.
+ let moved = CatalogNativeApplication(NativeMacApplication(
+ url: URL(fileURLWithPath: "/Volumes/Games/Game.app"),
+ executableURL: URL(fileURLWithPath: "/Volumes/Games/Game.app/Contents/MacOS/Game"),
+ bundleIdentifier: "com.example.game", name: "Game", architectures: [.arm64], isDeclaredGame: true, fileObservations: []))
+ XCTAssertNil(state.observe([game], application: moved, now: t0.addingTimeInterval(120)))
+ XCTAssertEqual(state.phase, .running(pid: 42))
+ // With no installation to compare, the pid reused by another program still ends it.
+ XCTAssertEqual(state.observe([steamClient, .init(pid: 42, bundleURL: steamClient.bundleURL, executableURL: nil)],
+ application: nil, now: t0.addingTimeInterval(180)), .ended(pid: 42))
+ }
+}
+
+final class SteamBackgroundLaunchTests: XCTestCase {
+ func testSilentArgumentsOnlyWhenPlayStartsSteamAndTheSettingIsOn() {
+ XCTAssertEqual(SteamBackgroundLaunch.arguments(enabled: true, steamRunning: false), ["-silent", "-nofriendsui"])
+ XCTAssertEqual(SteamBackgroundLaunch.arguments(enabled: true, steamRunning: true), [])
+ XCTAssertEqual(SteamBackgroundLaunch.arguments(enabled: false, steamRunning: false), [])
+ }
+
+ func testSteamMayNeedThePlayerOnlyAfterAStartingGameIsLate() {
+ let start = Date(timeIntervalSince1970: 1_000)
+ let waiting = SteamPlayState.Phase.starting(since: start)
+ let late = start.addingTimeInterval(SteamBackgroundLaunch.attentionDelay + 1)
+ XCTAssertTrue(SteamBackgroundLaunch.mayNeedPlayer(phase: waiting, now: late))
+ XCTAssertFalse(SteamBackgroundLaunch.mayNeedPlayer(phase: waiting, now: start.addingTimeInterval(5)))
+ XCTAssertFalse(SteamBackgroundLaunch.mayNeedPlayer(phase: .running(pid: 7), now: late))
+ XCTAssertFalse(SteamBackgroundLaunch.mayNeedPlayer(phase: .idle, now: late))
+ }
+
+ func testAColdSteamGetsMorePatience() {
+ XCTAssertEqual(SteamBackgroundLaunch.patience(steamWasRunning: true), 15)
+ XCTAssertEqual(SteamBackgroundLaunch.patience(steamWasRunning: false), 45)
+ let start = Date(timeIntervalSince1970: 1_000)
+ let waiting = SteamPlayState.Phase.starting(since: start)
+ let thirty = start.addingTimeInterval(30)
+ XCTAssertFalse(SteamBackgroundLaunch.mayNeedPlayer(phase: waiting, now: thirty, patience: 45))
+ XCTAssertTrue(SteamBackgroundLaunch.mayNeedPlayer(phase: waiting, now: thirty, patience: 15))
+ }
+
+ func testTheLaunchScreenWaitsOnlyForAGameOnItsWay() {
+ let start = Date(timeIntervalSince1970: 1_000)
+ let waiting = SteamPlayState.Phase.starting(since: start)
+ XCTAssertEqual(SteamBackgroundLaunch.launchScreen(phase: waiting, now: start.addingTimeInterval(10), patience: 15), .waiting)
+ XCTAssertEqual(SteamBackgroundLaunch.launchScreen(phase: waiting, now: start.addingTimeInterval(16), patience: 15), .late)
+ XCTAssertEqual(SteamBackgroundLaunch.launchScreen(phase: .running(pid: 7), now: start, patience: 15), .gameStarted)
+ XCTAssertEqual(SteamBackgroundLaunch.launchScreen(phase: .idle, now: start, patience: 15), .over)
+ XCTAssertEqual(SteamBackgroundLaunch.launchScreen(phase: .failed(.notStarted), now: start, patience: 15), .over)
+ }
+
+ func testDownloadsURLOpensSteamDownloads() {
+ XCTAssertEqual(SteamPlayState.downloadsURL.absoluteString, "steam://open/downloads")
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamPlaytimeBaselinesTests.swift b/Tests/NXLibraryCoreTests/SteamPlaytimeBaselinesTests.swift
new file mode 100644
index 00000000..b18d183c
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamPlaytimeBaselinesTests.swift
@@ -0,0 +1,126 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class SteamPlaytimeBaselinesTests: XCTestCase {
+ private var url: URL!
+
+ override func setUp() {
+ super.setUp()
+ url = FileManager.default.temporaryDirectory.appendingPathComponent("SteamPlaytime-\(UUID().uuidString).json")
+ }
+
+ override func tearDown() {
+ try? FileManager.default.removeItem(at: url)
+ super.tearDown()
+ }
+
+ private func date(_ seconds: TimeInterval) -> Date { Date(timeIntervalSince1970: seconds) }
+
+ private func snapshot(account: UInt32 = 1, _ entries: [UInt32: (Int, TimeInterval?)]) -> SteamPlaytimeSnapshot {
+ SteamPlaytimeSnapshot(accountID: account, entries: entries.mapValues {
+ SteamPlaytimeEntry(minutes: $0.0, lastPlayed: $0.1.map(date))
+ })
+ }
+
+ func testFirstSnapshotSetsSeenAtNow() {
+ var baselines = SteamPlaytimeBaselines(fileURL: url)
+ XCTAssertTrue(baselines.apply(snapshot([440: (75, 500)]), now: date(1_000)))
+ XCTAssertEqual(baselines.accountID, 1)
+ XCTAssertEqual(baselines.byAppID[440], SteamPlaytimeBaseline(appID: 440, minutes: 75, lastPlayed: date(500), seenAt: date(1_000)))
+ }
+
+ func testSameMinutesKeepsSeenAt() {
+ var baselines = SteamPlaytimeBaselines(fileURL: url)
+ baselines.apply(snapshot([440: (75, 500)]), now: date(1_000))
+ XCTAssertFalse(baselines.apply(snapshot([440: (75, 500)]), now: date(2_000)))
+ XCTAssertTrue(baselines.apply(snapshot([440: (75, 1_500)]), now: date(3_000)))
+ XCTAssertEqual(baselines.byAppID[440]?.seenAt, date(1_000))
+ XCTAssertEqual(baselines.byAppID[440]?.lastPlayed, date(1_500))
+ }
+
+ func testNewMinutesResetSeenAt() {
+ var baselines = SteamPlaytimeBaselines(fileURL: url)
+ baselines.apply(snapshot([440: (75, 500)]), now: date(1_000))
+ XCTAssertTrue(baselines.apply(snapshot([440: (80, 500)]), now: date(2_000)))
+ XCTAssertEqual(baselines.byAppID[440]?.minutes, 80)
+ XCTAssertEqual(baselines.byAppID[440]?.seenAt, date(2_000))
+ XCTAssertTrue(baselines.apply(snapshot([440: (10, 500)]), now: date(3_000)), "Steam is the source of truth, even going down")
+ XCTAssertEqual(baselines.byAppID[440]?.minutes, 10)
+ XCTAssertEqual(baselines.byAppID[440]?.seenAt, date(3_000))
+ }
+
+ func testAnotherAccountStartsOver() {
+ var baselines = SteamPlaytimeBaselines(fileURL: url)
+ baselines.apply(snapshot(account: 1, [440: (75, nil), 10: (5, nil)]), now: date(1_000))
+ XCTAssertTrue(baselines.apply(snapshot(account: 2, [440: (75, nil)]), now: date(2_000)))
+ XCTAssertEqual(baselines.accountID, 2)
+ XCTAssertEqual(Set(baselines.byAppID.keys), [440])
+ XCTAssertEqual(baselines.byAppID[440]?.seenAt, date(2_000))
+ }
+
+ func testAppsMissingFromSnapshotAreDropped() {
+ var baselines = SteamPlaytimeBaselines(fileURL: url)
+ baselines.apply(snapshot([440: (75, nil), 10: (5, nil)]), now: date(1_000))
+ XCTAssertTrue(baselines.apply(snapshot([440: (75, nil)]), now: date(2_000)))
+ XCTAssertNil(baselines.byAppID[10])
+ }
+
+ func testSaveAndReloadRoundTrip() throws {
+ var baselines = SteamPlaytimeBaselines(fileURL: url)
+ baselines.apply(snapshot([440: (75, 500)]), now: date(1_000))
+ try baselines.save()
+ XCTAssertEqual(SteamPlaytimeBaselines(fileURL: url), baselines)
+ }
+
+ func testBrokenFileLoadsEmpty() throws {
+ try Data("not json".utf8).write(to: url)
+ let baselines = SteamPlaytimeBaselines(fileURL: url)
+ XCTAssertNil(baselines.accountID)
+ XCTAssertTrue(baselines.byAppID.isEmpty)
+ }
+
+ func testExternalMapsOnlyCatalogSteamGames() {
+ var baselines = SteamPlaytimeBaselines(fileURL: url)
+ baselines.apply(snapshot([440: (75, 500), 10: (5, nil)]), now: date(1_000))
+ let steam = CatalogGame(steam: SteamCatalogGame(appID: 440, name: "Steam game"))
+ let switchGame = CatalogGame(nxnative: PortedGame(name: "Switch", url: URL(fileURLWithPath: "/tmp/Switch.app"),
+ platform: .macApp, sizeBytes: 1,
+ modificationDate: date(0), bundleId: "org.nxnative.x", titleId: "0100000000010000"))
+ XCTAssertEqual(baselines.external(for: [steam, switchGame]),
+ [steam.id: ExternalPlaytime(duration: 75 * 60, lastPlayed: date(500), since: date(1_000))])
+ }
+
+ // Steam keeps whole minutes: when its value rises, up to a minute NX Library already showed is kept.
+ func testRisingMinutesKeepUpToAMinuteAlreadyShown() {
+ var baselines = SteamPlaytimeBaselines(fileURL: url)
+ baselines.apply(snapshot([440: (75, nil)]), now: date(1_000))
+ baselines.apply(snapshot([440: (76, nil)]), now: date(2_000), previousTotals: [440: 75 * 60 + 90])
+ XCTAssertEqual(baselines.byAppID[440]?.carry, 30)
+ let steam = CatalogGame(steam: SteamCatalogGame(appID: 440, name: "Steam game"))
+ XCTAssertEqual(baselines.external(for: [steam])[steam.id]?.duration, 76 * 60 + 30)
+
+ baselines.apply(snapshot([440: (77, nil)]), now: date(3_000), previousTotals: [440: 76 * 60 + 500])
+ XCTAssertEqual(baselines.byAppID[440]?.carry, 60, "a bigger gap is Steam's call")
+ }
+
+ func testCarryStaysWithTheSameMinutesAndResetsOtherwise() {
+ var baselines = SteamPlaytimeBaselines(fileURL: url)
+ baselines.apply(snapshot([440: (75, nil)]), now: date(1_000))
+ baselines.apply(snapshot([440: (76, nil)]), now: date(2_000), previousTotals: [440: 75 * 60 + 90])
+ baselines.apply(snapshot([440: (76, 1_500)]), now: date(2_500), previousTotals: [440: 99_999])
+ XCTAssertEqual(baselines.byAppID[440]?.carry, 30)
+ baselines.apply(snapshot([440: (10, nil)]), now: date(3_000), previousTotals: [440: 76 * 60 + 30])
+ XCTAssertEqual(baselines.byAppID[440]?.carry, 0, "a lower value is Steam's reset")
+ baselines.apply(snapshot([440: (11, nil)]), now: date(4_000), previousTotals: [440: 11 * 60 + 30])
+ baselines.apply(snapshot(account: 2, [440: (12, nil)]), now: date(5_000), previousTotals: [440: 12 * 60 + 30])
+ XCTAssertEqual(baselines.byAppID[440]?.carry, 0, "another account starts over")
+ }
+
+ func testFilesWithoutCarryStillLoad() throws {
+ let json = #"{"accountID":1,"baselines":[{"appID":440,"minutes":75,"seenAt":1000}]}"#
+ try Data(json.utf8).write(to: url)
+ let baselines = SteamPlaytimeBaselines(fileURL: url)
+ XCTAssertEqual(baselines.byAppID[440]?.carry, 0)
+ XCTAssertEqual(baselines.byAppID[440]?.minutes, 75)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamPlaytimeReaderTests.swift b/Tests/NXLibraryCoreTests/SteamPlaytimeReaderTests.swift
new file mode 100644
index 00000000..82b5b971
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamPlaytimeReaderTests.swift
@@ -0,0 +1,201 @@
+import XCTest
+import Darwin
+@testable import NXLibraryCore
+
+final class SteamPlaytimeReaderTests: XCTestCase {
+ private static let base: UInt64 = 76_561_197_960_265_728
+
+ private static func localConfig(apps: String, before: String = "") -> String {
+ """
+ "UserLocalConfigStore"
+ {
+ \(before)
+ "apptickets" { "440" "c2VjcmV0" }
+ "Software" { "Valve" { "Steam" { "apps" {
+ \(apps)
+ } } } }
+ }
+ """
+ }
+
+ private static func loginUsers(_ users: [(id: UInt64, mostRecent: Bool?, timestamp: Int)]) -> String {
+ let body = users.map { user in
+ let recent = user.mostRecent.map { "\"MostRecent\" \"\($0 ? 1 : 0)\"" } ?? ""
+ return "\"\(user.id)\" { \"AccountName\" \"someone\" \(recent) \"timestamp\" \"\(user.timestamp)\" }"
+ }.joined(separator: "\n")
+ return "\"users\" {\n\(body)\n}"
+ }
+
+ func testEntriesReadOnlyPlaytimeAndLastPlayed() throws {
+ let text = Self.localConfig(apps: """
+ "7" { "cloud" { "last_sync_state" "synchronized" } }
+ "440" { "LastPlayed" "1729257000" "Playtime" "75" "Playtime2wks" "3" }
+ """)
+ XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: text),
+ [440: SteamPlaytimeEntry(minutes: 75, lastPlayed: Date(timeIntervalSince1970: 1_729_257_000))])
+ }
+
+ func testZeroOrMissingLastPlayedIsNone() throws {
+ let text = Self.localConfig(apps: """
+ "10" { "LastPlayed" "0" "Playtime" "5" }
+ "20" { "Playtime" "6" }
+ "30" { "LastPlayed" "1729257000" }
+ """)
+ XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: text),
+ [10: SteamPlaytimeEntry(minutes: 5, lastPlayed: nil),
+ 20: SteamPlaytimeEntry(minutes: 6, lastPlayed: nil)])
+ }
+
+ func testMostRecentUserWins() throws {
+ let text = Self.loginUsers([(Self.base + 100, false, 900), (Self.base + 200, true, 100)])
+ XCTAssertEqual(try SteamPlaytimeReader.accountID(loginUsers: text), 200)
+ }
+
+ func testLatestTimestampWinsWithoutMostRecent() throws {
+ let text = Self.loginUsers([(Self.base + 100, nil, 900), (Self.base + 200, nil, 100)])
+ XCTAssertEqual(try SteamPlaytimeReader.accountID(loginUsers: text), 100)
+ }
+
+ func testReadFindsTheAccountsLocalConfig() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ try write(Self.loginUsers([(Self.base + 42, true, 1)]), to: "config/loginusers.vdf", in: fixture.root)
+ try write(Self.localConfig(apps: "\"440\" { \"Playtime\" \"9\" }"), to: "userdata/42/config/localconfig.vdf", in: fixture.root)
+ XCTAssertEqual(try SteamPlaytimeReader.accountID(root: fixture.root), 42)
+ let config = SteamPlaytimeReader.localConfigURL(root: fixture.root, account: 42)
+ XCTAssertEqual(config.path, fixture.root.appendingPathComponent("userdata/42/config/localconfig.vdf").path)
+ XCTAssertEqual(try SteamPlaytimeReader.read(config: config, account: 42),
+ SteamPlaytimeSnapshot(accountID: 42, entries: [440: SteamPlaytimeEntry(minutes: 9, lastPlayed: nil)]))
+ }
+
+ func testNoLoginUsersMeansNoAccount() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ XCTAssertNil(try SteamPlaytimeReader.accountID(root: fixture.root))
+ }
+
+ func testLargeConfigWithManyEntriesIsRead() throws {
+ let filler = "\"WebStorage\" {\n" + (0..<30_000).map { "\"k\($0)\" \"v\"" }.joined(separator: "\n") + "\n}"
+ let text = Self.localConfig(apps: "\"440\" { \"Playtime\" \"1\" }", before: filler)
+ XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: text)[440]?.minutes, 1)
+ }
+
+ func testMalformedConfigThrows() {
+ XCTAssertThrowsError(try SteamPlaytimeReader.entries(localConfig: "\"UserLocalConfigStore\" { \"Software\" {"))
+ }
+
+ // A file Steam is rewriting must fail the read, never look like an account with no playtime.
+ func testEmptyOrRootlessConfigThrows() {
+ for text in ["", " \n", "\"Other\" { }"] {
+ XCTAssertThrowsError(try SteamPlaytimeReader.entries(localConfig: text), text)
+ }
+ }
+
+ func testAnAccountWithNoAppsHasNoEntries() throws {
+ XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: "\"UserLocalConfigStore\" { }"), [:])
+ }
+
+ func testUnreadableLoginUsersFailsInsteadOfMeaningNoAccount() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ try write("\"users\" {", to: "config/loginusers.vdf", in: fixture.root)
+ XCTAssertThrowsError(try SteamPlaytimeReader.accountID(root: fixture.root))
+ try write("\"users\" { }", to: "config/loginusers.vdf", in: fixture.root)
+ XCTAssertNil(try SteamPlaytimeReader.accountID(root: fixture.root))
+ }
+
+ func testDuplicatePathKeysUseTheFirst() throws {
+ let text = """
+ "UserLocalConfigStore" {
+ "Software" { "Valve" { "Steam" { "apps" { "440" { "Playtime" "3" } } } } }
+ "software" { "Other" "x" }
+ }
+ """
+ XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: text)[440]?.minutes, 3)
+ }
+
+ func testWrongTypedFirstPathDoesNotFallThroughToALaterObject() throws {
+ let apps = "\"440\" { \"Playtime\" \"9\" }"
+ let duplicateRoot = "\"UserLocalConfigStore\" \"wrong type\" " + Self.localConfig(apps: apps)
+ let duplicateSoftware = Self.localConfig(apps: apps, before: "\"software\" \"wrong type\"")
+ for text in [duplicateRoot, duplicateSoftware] {
+ XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: text), [:])
+ }
+ }
+
+ func testDuplicateOrWrongTypedScalarsDoNotReplacePlaytimeOrInventDates() throws {
+ let text = Self.localConfig(apps: """
+ "440" { "Playtime" "3" "PLAYTIME" "9" }
+ "441" { "Playtime" "7" "LastPlayed" "10" "LASTPLAYED" "20" }
+ "442" { "Playtime" {} "PLAYTIME" "9" }
+ "443" { "Playtime" "4" "LastPlayed" {} }
+ "444" { "Playtime" {} }
+ """)
+ XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: text),
+ [441: SteamPlaytimeEntry(minutes: 7, lastPlayed: nil),
+ 443: SteamPlaytimeEntry(minutes: 4, lastPlayed: nil)])
+ }
+
+ func testDuplicateMostRecentMarkerDoesNotTakeAnotherAccountsPriority() throws {
+ let text = """
+ "users" {
+ "\(Self.base + 42)" { "MostRecent" "1" "MOSTRECENT" "1" "timestamp" "900" }
+ "\(Self.base + 43)" { "MostRecent" "1" "timestamp" "100" }
+ }
+ """
+ XCTAssertEqual(try SteamPlaytimeReader.accountID(loginUsers: text), 43)
+ }
+
+ func testHashKeysElsewhereDoNotFailTheRead() throws {
+ let text = Self.localConfig(apps: "\"440\" { \"Playtime\" \"2\" }", before: "\"WebStorage\" { \"#tag\" \"x\" }")
+ XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: text)[440]?.minutes, 2)
+ }
+
+ func testOversizedConfigThrows() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ try write(Self.loginUsers([(Self.base + 42, true, 1)]), to: "config/loginusers.vdf", in: fixture.root)
+ let filler = String(repeating: " ", count: SteamPlaytimeReader.maximumBytes + 1)
+ try write(Self.localConfig(apps: "") + filler, to: "userdata/42/config/localconfig.vdf", in: fixture.root)
+ XCTAssertThrowsError(try SteamPlaytimeReader.read(config: SteamPlaytimeReader.localConfigURL(root: fixture.root, account: 42), account: 42))
+ }
+
+ func testConfigSymlinkIsRejected() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ try write(Self.localConfig(apps: "\"440\" { \"Playtime\" \"9\" }"), to: "target.vdf", in: fixture.root)
+ let link = fixture.root.appendingPathComponent("config.vdf")
+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: fixture.root.appendingPathComponent("target.vdf"))
+ XCTAssertThrowsError(try SteamPlaytimeReader.read(config: link, account: 42))
+ }
+
+ func testLoginUsersSymlinkIsRejected() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ try write(Self.loginUsers([(Self.base + 42, true, 1)]), to: "target.vdf", in: fixture.root)
+ try FileManager.default.createDirectory(at: fixture.root.appendingPathComponent("config"), withIntermediateDirectories: true)
+ try FileManager.default.createSymbolicLink(at: fixture.root.appendingPathComponent("config/loginusers.vdf"),
+ withDestinationURL: fixture.root.appendingPathComponent("target.vdf"))
+ XCTAssertThrowsError(try SteamPlaytimeReader.accountID(root: fixture.root))
+ }
+
+ func testConfigFIFOIsRejectedWithoutWaitingForAWriter() throws {
+ let fixture = try SteamTestFixture.temporary(in: self)
+ let fifo = fixture.root.appendingPathComponent("config.vdf")
+ XCTAssertEqual(mkfifo(fifo.path, 0o600), 0)
+ let finished = expectation(description: "Playtime rejects a FIFO without blocking")
+ DispatchQueue.global().async {
+ do {
+ _ = try SteamPlaytimeReader.read(config: fifo, account: 42)
+ XCTFail("A FIFO is not playtime data")
+ } catch {}
+ finished.fulfill()
+ }
+ let result = XCTWaiter.wait(for: [finished], timeout: 1)
+ if result != .completed {
+ let writer = Darwin.open(fifo.path, O_WRONLY | O_NONBLOCK)
+ if writer >= 0 { Darwin.close(writer) }
+ }
+ XCTAssertEqual(result, .completed)
+ }
+
+ private func write(_ text: String, to relative: String, in root: URL) throws {
+ let url = root.appendingPathComponent(relative)
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(text.utf8).write(to: url)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamPlaytimeSyncTests.swift b/Tests/NXLibraryCoreTests/SteamPlaytimeSyncTests.swift
new file mode 100644
index 00000000..e639131e
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamPlaytimeSyncTests.swift
@@ -0,0 +1,192 @@
+import XCTest
+@testable import NXLibraryCore
+
+final class SteamPlaytimeSyncTests: XCTestCase {
+ private static let base: UInt64 = 76_561_197_960_265_728
+ private var url: URL!
+ private let steam = CatalogGame(steam: SteamCatalogGame(appID: 440, name: "Steam game"))
+
+ override func setUp() {
+ super.setUp()
+ url = FileManager.default.temporaryDirectory.appendingPathComponent("SteamPlaytimeSync-\(UUID().uuidString).json")
+ }
+
+ override func tearDown() {
+ try? FileManager.default.removeItem(at: url)
+ super.tearDown()
+ }
+
+ private func date(_ seconds: TimeInterval) -> Date { Date(timeIntervalSince1970: seconds) }
+ private func stamp(_ seconds: TimeInterval = 1) -> SteamFileStamp {
+ SteamFileStamp(file: URL(fileURLWithPath: "/tmp/localconfig.vdf"), modified: date(seconds))
+ }
+ private func snapshot(account: UInt32 = 1, minutes: Int = 75) -> SteamPlaytimeSnapshot {
+ SteamPlaytimeSnapshot(accountID: account, entries: [440: SteamPlaytimeEntry(minutes: minutes, lastPlayed: nil)])
+ }
+ private func handle(_ sync: inout SteamPlaytimeSync, _ reading: SteamPlaytimeReading, games: [CatalogGame]? = nil,
+ shown: TimeInterval = 0, now: TimeInterval = 1_000) -> SteamPlaytimeSync.Result {
+ sync.handle(reading, games: games ?? [steam], shownTotal: { _, _ in shown }, now: date(now))
+ }
+
+ // MARK: - Reading Steam's files
+
+ private func write(_ text: String, to relative: String, in root: URL) throws {
+ let file = root.appendingPathComponent(relative)
+ try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(text.utf8).write(to: file)
+ }
+
+ private func account(_ root: URL, id: UInt64 = 42) throws {
+ try write("\"users\" { \"\(Self.base + id)\" { \"MostRecent\" \"1\" } }", to: "config/loginusers.vdf", in: root)
+ }
+
+ func testTakeWithoutAccountOrFileIsNoAccount() throws {
+ let root = try SteamTestFixture.temporary(in: self).root
+ XCTAssertEqual(SteamPlaytimeReading.take(root: root, known: nil), .noAccount)
+ try account(root)
+ XCTAssertEqual(SteamPlaytimeReading.take(root: root, known: nil), .noAccount)
+ }
+
+ func testTakeUnreadableLoginUsersFailsWithoutAnAccount() throws {
+ let root = try SteamTestFixture.temporary(in: self).root
+ try write("\"users\" {", to: "config/loginusers.vdf", in: root)
+ XCTAssertEqual(SteamPlaytimeReading.take(root: root, known: nil), .failed(accountID: nil))
+ }
+
+ func testTakeMalformedConfigFailsWithItsAccount() throws {
+ let root = try SteamTestFixture.temporary(in: self).root
+ try account(root)
+ try write("", to: "userdata/42/config/localconfig.vdf", in: root)
+ XCTAssertEqual(SteamPlaytimeReading.take(root: root, known: nil), .failed(accountID: 42))
+ }
+
+ func testTakeReadsOnceAndThenIsUnchanged() throws {
+ let root = try SteamTestFixture.temporary(in: self).root
+ try account(root)
+ try write("\"UserLocalConfigStore\" { \"Software\" { \"Valve\" { \"Steam\" { \"apps\" { \"440\" { \"Playtime\" \"9\" } } } } } }",
+ to: "userdata/42/config/localconfig.vdf", in: root)
+ guard case .read(let snapshot, let stamp) = SteamPlaytimeReading.take(root: root, known: nil) else {
+ return XCTFail("expected a reading")
+ }
+ XCTAssertEqual(snapshot, SteamPlaytimeSnapshot(accountID: 42, entries: [440: SteamPlaytimeEntry(minutes: 9, lastPlayed: nil)]))
+ XCTAssertEqual(stamp.file.lastPathComponent, "localconfig.vdf")
+ XCTAssertEqual(SteamPlaytimeReading.take(root: root, known: stamp), .unchanged(accountID: 42))
+ }
+
+ // MARK: - What a reading does
+
+ func testReadPublishesAndSaves() {
+ var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url))
+ XCTAssertEqual(handle(&sync, .read(snapshot(), stamp())),
+ .publish([steam.id: ExternalPlaytime(duration: 75 * 60, lastPlayed: nil, since: date(1_000))], save: true))
+ XCTAssertEqual(sync.stamp, stamp())
+ XCTAssertEqual(handle(&sync, .read(snapshot(), stamp(2)), now: 2_000),
+ .publish([steam.id: ExternalPlaytime(duration: 75 * 60, lastPlayed: nil, since: date(1_000))], save: false))
+ }
+
+ func testReadCarriesWhatWasShown() {
+ var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url))
+ _ = handle(&sync, .read(snapshot(minutes: 75), stamp()))
+ XCTAssertEqual(handle(&sync, .read(snapshot(minutes: 76), stamp(2)), shown: 75 * 60 + 90, now: 2_000),
+ .publish([steam.id: ExternalPlaytime(duration: 76 * 60 + 30, lastPlayed: nil, since: date(2_000))], save: true))
+ }
+
+ func testUnchangedRepublishesForTheCurrentGames() {
+ var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url))
+ _ = handle(&sync, .read(snapshot(), stamp()))
+ XCTAssertEqual(handle(&sync, .unchanged(accountID: 1), games: []), .publish([:], save: false))
+ }
+
+ func testFailedKeepsTheLastGoodTotals() {
+ var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url))
+ _ = handle(&sync, .read(snapshot(), stamp()))
+ let kept = SteamPlaytimeSync.Result.publish([steam.id: ExternalPlaytime(duration: 75 * 60, lastPlayed: nil, since: date(1_000))], save: false)
+ XCTAssertEqual(handle(&sync, .failed(accountID: 1)), kept)
+ XCTAssertEqual(handle(&sync, .failed(accountID: nil)), kept)
+ XCTAssertEqual(sync.stamp, stamp(), "a failure does not move the stamp")
+ }
+
+ func testFailedForAnotherAccountShowsNothing() {
+ var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url))
+ _ = handle(&sync, .read(snapshot(account: 1), stamp()))
+ XCTAssertEqual(handle(&sync, .failed(accountID: 2)), .clear)
+ }
+
+ func testNoAccountClearsAndForgetsTheStamp() {
+ var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url))
+ _ = handle(&sync, .read(snapshot(), stamp()))
+ XCTAssertEqual(handle(&sync, .noAccount), .clear)
+ XCTAssertNil(sync.stamp)
+ }
+
+ func testResetStampMakesTheNextReadingFull() {
+ var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url))
+ _ = handle(&sync, .read(snapshot(), stamp()))
+ sync.resetStamp()
+ XCTAssertNil(sync.stamp)
+ }
+
+ func testFailedWithoutAnAccountStaysClearedAfterAnotherAccountWasSeen() {
+ var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url))
+ _ = handle(&sync, .read(snapshot(account: 1), stamp()))
+ XCTAssertEqual(handle(&sync, .failed(accountID: 2)), .clear)
+ XCTAssertEqual(handle(&sync, .failed(accountID: nil)), .clear)
+ }
+
+ func testCarryIsMeasuredFromTheOldBaseline() {
+ var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url))
+ _ = handle(&sync, .read(snapshot(minutes: 75), stamp()))
+ var asked: ExternalPlaytime?
+ let result = sync.handle(.read(snapshot(minutes: 76), stamp(2)), games: [steam],
+ shownTotal: { _, old in asked = old; return old.duration + 90 }, now: date(2_000))
+ XCTAssertEqual(asked, ExternalPlaytime(duration: 75 * 60, lastPlayed: nil, since: date(1_000)))
+ XCTAssertEqual(result, .publish([steam.id: ExternalPlaytime(duration: 76 * 60 + 30, lastPlayed: nil, since: date(2_000))], save: true))
+ }
+}
+
+final class SteamPlaytimeReadQueueTests: XCTestCase {
+ func testOneReadAtATime() {
+ var queue = SteamPlaytimeReadQueue()
+ let ticket = queue.request()
+ XCTAssertNotNil(ticket)
+ XCTAssertNil(queue.request())
+ XCTAssertNil(queue.request())
+ XCTAssertTrue(queue.isReading)
+ }
+
+ func testRequestsDuringAReadReadOnceMore() throws {
+ var queue = SteamPlaytimeReadQueue()
+ let ticket = try XCTUnwrap(queue.request())
+ _ = queue.request(); _ = queue.request()
+ XCTAssertEqual(queue.finish(ticket).apply, true)
+ let again = try XCTUnwrap(queue.request(), "the read after finishing starts")
+ XCTAssertEqual(queue.finish(again).readAgain, false, "one more read served every request")
+ }
+
+ func testFinishWithoutRequestsStops() throws {
+ var queue = SteamPlaytimeReadQueue()
+ let ticket = try XCTUnwrap(queue.request())
+ let result = queue.finish(ticket)
+ XCTAssertTrue(result.apply)
+ XCTAssertFalse(result.readAgain)
+ XCTAssertFalse(queue.isReading)
+ }
+
+ func testAnInvalidatedReadIsNotAppliedAndReadsAgain() throws {
+ var queue = SteamPlaytimeReadQueue()
+ let ticket = try XCTUnwrap(queue.request())
+ queue.invalidate()
+ let result = queue.finish(ticket)
+ XCTAssertFalse(result.apply)
+ XCTAssertTrue(result.readAgain)
+ }
+
+ func testStoppingDropsPendingRequests() throws {
+ var queue = SteamPlaytimeReadQueue()
+ let ticket = try XCTUnwrap(queue.request())
+ _ = queue.request()
+ queue.stop()
+ XCTAssertEqual(queue.finish(ticket).apply, false)
+ XCTAssertFalse(queue.isReading)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamReturnFocusTests.swift b/Tests/NXLibraryCoreTests/SteamReturnFocusTests.swift
new file mode 100644
index 00000000..fa049052
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamReturnFocusTests.swift
@@ -0,0 +1,70 @@
+import XCTest
+@testable import NXLibraryCore
+
+/// Arcane comes back after a Steam game only when Play came from Arcane, the game was the app in front
+/// and no other library game is still open.
+final class SteamReturnFocusTests: XCTestCase {
+ private let id = UUID()
+
+ func testPlayedHereInFrontAndAloneComesBack() {
+ var focus = SteamReturnFocus()
+ focus.playPressed(id)
+ focus.gameCameForward(id)
+ XCTAssertTrue(focus.gameEnded(id, othersRunning: false).returnsToLibrary)
+ }
+
+ func testStartedFromSteamDoesNotComeBack() {
+ var focus = SteamReturnFocus()
+ focus.gameCameForward(id)
+ XCTAssertFalse(focus.gameEnded(id, othersRunning: false).returnsToLibrary)
+ }
+
+ func testLeavingTheGameForAnotherAppDoesNotComeBack() {
+ var focus = SteamReturnFocus()
+ focus.playPressed(id)
+ focus.gameCameForward(id)
+ focus.otherAppStayedForward(whileRunning: id)
+ XCTAssertFalse(focus.gameEnded(id, othersRunning: false).returnsToLibrary)
+ }
+
+ func testAnotherOpenGameKeepsNXLibraryBack() {
+ var focus = SteamReturnFocus()
+ focus.playPressed(id)
+ focus.gameCameForward(id)
+ XCTAssertFalse(focus.gameEnded(id, othersRunning: true).returnsToLibrary)
+ }
+
+ func testAnAbandonedPlayDoesNotCountLater() {
+ var focus = SteamReturnFocus()
+ focus.playPressed(id)
+ focus.playAbandoned(id)
+ focus.gameCameForward(id)
+ XCTAssertFalse(focus.gameEnded(id, othersRunning: false).returnsToLibrary)
+ }
+
+ func testEachPlayCountsOnce() {
+ var focus = SteamReturnFocus()
+ focus.playPressed(id)
+ focus.gameCameForward(id)
+ XCTAssertTrue(focus.gameEnded(id, othersRunning: false).returnsToLibrary)
+ focus.gameCameForward(id)
+ XCTAssertFalse(focus.gameEnded(id, othersRunning: false).returnsToLibrary, "a later start from Steam is not Arcane's")
+ }
+
+ // MARK: - Whether the player was still in the game
+
+ func testAGameInFrontAtQuitWasBeingPlayed() {
+ var focus = SteamReturnFocus()
+ focus.playPressed(id)
+ focus.gameCameForward(id)
+ XCTAssertTrue(focus.gameEnded(id, othersRunning: true).wasInFront, "true even when Arcane stays back")
+ }
+
+ func testAGameLeftForAnotherAppWasNotInFront() {
+ var focus = SteamReturnFocus()
+ focus.playPressed(id)
+ focus.gameCameForward(id)
+ focus.otherAppStayedForward(whileRunning: id)
+ XCTAssertFalse(focus.gameEnded(id, othersRunning: false).wasInFront)
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/SteamTestSupport.swift b/Tests/NXLibraryCoreTests/SteamTestSupport.swift
new file mode 100644
index 00000000..af7cc1f4
--- /dev/null
+++ b/Tests/NXLibraryCoreTests/SteamTestSupport.swift
@@ -0,0 +1,84 @@
+import Foundation
+import XCTest
+
+/// Generated metadata/header bytes only; these fixtures are not game executables.
+struct SteamTestFixture: Sendable {
+ let root: URL
+
+ static func temporary(in test: XCTestCase) throws -> Self {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("SteamSourceTests-" + UUID().uuidString)
+ .resolvingSymlinksInPath().standardizedFileURL
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ test.addTeardownBlock { try FileManager.default.removeItem(at: root) }
+ return Self(root: root)
+ }
+
+ @discardableResult
+ func app(at relative: String = "Game.app", category: String? = "public.app-category.games",
+ cpuTypes: [UInt32] = [0x0100000c], metadata: [String: Any] = [:]) throws -> URL {
+ let app = root.appendingPathComponent(relative)
+ try FileManager.default.createDirectory(at: app.appendingPathComponent("Contents/MacOS"), withIntermediateDirectories: true)
+ var info: [String: Any] = ["CFBundlePackageType": "APPL", "CFBundleIdentifier": "test.game",
+ "CFBundleDisplayName": "Fixture game", "CFBundleExecutable": "fixture"]
+ info["LSApplicationCategoryType"] = category
+ info.merge(metadata) { _, new in new }
+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0)
+ .write(to: app.appendingPathComponent("Contents/Info.plist"))
+ let executable = app.appendingPathComponent("Contents/MacOS/fixture")
+ let data = cpuTypes.count == 1 ? Self.machHeader(cpu: cpuTypes[0]) : Self.fatHeader(cpus: cpuTypes)
+ try data.write(to: executable)
+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path)
+ return app
+ }
+
+ static func words(_ values: [UInt32], bigEndian: Bool = false) -> Data {
+ Data(values.flatMap { word in
+ let shifts = bigEndian ? [24, 16, 8, 0] : [0, 8, 16, 24]
+ return shifts.map { UInt8(truncatingIfNeeded: word >> $0) }
+ })
+ }
+
+ static func machHeader(cpu: UInt32, fileType: UInt32 = 2) -> Data {
+ words([0xfeedfacf, cpu, 0, fileType, 0, 0, 0, 0])
+ }
+
+ func library(_ relative: String = "Steam") throws -> URL {
+ let library = root.appendingPathComponent(relative)
+ try FileManager.default.createDirectory(at: library.appendingPathComponent("steamapps/common"), withIntermediateDirectories: true)
+ return library
+ }
+
+ @discardableResult
+ func manifest(in library: URL, id: String = "10", name: String = "First game", directory: String = "First",
+ filenameID: String? = nil, size: String = "100", stateFlags: String? = "4", extra: String = "") throws -> URL {
+ let file = library.appendingPathComponent("steamapps/appmanifest_\(filenameID ?? id).acf")
+ let flags = stateFlags.map { "\"StateFlags\" \(Self.quote($0))" } ?? ""
+ let text = "\"AppState\" { \"appid\" \(Self.quote(id)) \"name\" \(Self.quote(name)) \"installdir\" \(Self.quote(directory)) \"SizeOnDisk\" \(Self.quote(size)) \"buildid\" \"42\" \(flags) \(extra) }"
+ try Data(text.utf8).write(to: file)
+ return file
+ }
+
+ static func quote(_ text: String) -> String {
+ "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
+ }
+
+ func inventory() throws -> [String: Data] {
+ let files = try XCTUnwrap(FileManager.default.enumerator(at: root, includingPropertiesForKeys: [.isRegularFileKey]))
+ var result: [String: Data] = [:]
+ for case let file as URL in files {
+ if (try file.resourceValues(forKeys: [.isRegularFileKey])).isRegularFile == true {
+ result[String(file.path.dropFirst(root.path.count))] = try Data(contentsOf: file)
+ }
+ }
+ return result
+ }
+
+ static func fatHeader(cpus: [UInt32]) -> Data {
+ var data = words([0xcafebabe, UInt32(cpus.count)], bigEndian: true)
+ for (i, cpu) in cpus.enumerated() {
+ data.append(words([cpu, 0, UInt32(8 + cpus.count * 20 + i * 32), 32, 0], bigEndian: true))
+ }
+ for cpu in cpus { data.append(machHeader(cpu: cpu)) }
+ return data
+ }
+}
diff --git a/Tests/NXLibraryCoreTests/TileMotionTests.swift b/Tests/NXLibraryCoreTests/TileMotionTests.swift
index 14edff72..f7b7affa 100644
--- a/Tests/NXLibraryCoreTests/TileMotionTests.swift
+++ b/Tests/NXLibraryCoreTests/TileMotionTests.swift
@@ -74,4 +74,16 @@ final class TileMotionTests: XCTestCase {
XCTAssertEqual(TileMotion.phase(period: 5, at: 812.5), 2.5, accuracy: 1e-9)
XCTAssertEqual(TileMotion.phase(period: 3.6, at: 7.2), 0, accuracy: 1e-9)
}
+
+ func testDownloadMarkPulsesSlowlyBetweenDimAndFull() {
+ XCTAssertEqual(TileMotion.downloadPeriod, 2.8)
+ XCTAssertEqual(TileMotion.downloadMarkOpacity(at: 0), 0.4, accuracy: 1e-9)
+ XCTAssertEqual(TileMotion.downloadMarkOpacity(at: 1.4), 1, accuracy: 1e-9)
+ XCTAssertEqual(TileMotion.downloadMarkOpacity(at: 2.8), 0.4, accuracy: 1e-9)
+ XCTAssertEqual(TileMotion.downloadMarkOpacity(at: 0.7), 0.7, accuracy: 1e-9)
+ let loop = TileMotion.loop(period: TileMotion.downloadPeriod, steps: 84) { TileMotion.downloadMarkOpacity(at: $0) }
+ let largest = zip(loop.values, loop.values.dropFirst()).map { abs($1 - $0) }.max()!
+ XCTAssertLessThan(largest, 0.05)
+ XCTAssertEqual(loop.values.first!, loop.values.last!, accuracy: 1e-3)
+ }
}
diff --git a/Tests/NXLibraryCoreTests/ToolchainGateCopyTests.swift b/Tests/NXLibraryCoreTests/ToolchainGateCopyTests.swift
index c1038d88..4afca443 100644
--- a/Tests/NXLibraryCoreTests/ToolchainGateCopyTests.swift
+++ b/Tests/NXLibraryCoreTests/ToolchainGateCopyTests.swift
@@ -30,7 +30,7 @@ final class ToolchainGateCopyTests: XCTestCase {
XCTAssertEqual(off.label, "Newer Metal")
XCTAssertEqual(off.tone, .info)
XCTAssertEqual(off.message, "Your Metal compiler (32023.922) is newer than the one nxnative is tested with (32023.921). There should be no problems: turn on Untested toolchain override to build.")
- XCTAssertEqual(off.buildHint, "Newer Metal: turn on the override in Settings → Engine")
+ XCTAssertEqual(off.buildHint, "Newer Metal: turn on the override in Settings → Setup and engine")
let on = ToolchainGateCopy.summary(report: report(metal: newer), overrideOn: true)
XCTAssertEqual(on.label, "Newer Metal · override on")
XCTAssertEqual(on.tone, .info)
@@ -42,7 +42,7 @@ final class ToolchainGateCopyTests: XCTestCase {
XCTAssertEqual(off.label, "Update recommended")
XCTAssertEqual(off.tone, .warning)
XCTAssertEqual(off.message, "Your Metal compiler (32023.917) is older than the one nxnative needs (32023.921). Updating to Metal 32023.921 is strongly recommended. Untested toolchain override builds anyway, at your own risk.")
- XCTAssertEqual(off.buildHint, "Older Metal: update it, or use the override in Settings → Engine")
+ XCTAssertEqual(off.buildHint, "Older Metal: update it, or use the override in Settings → Setup and engine")
let on = ToolchainGateCopy.summary(report: report(metal: older), overrideOn: true)
XCTAssertEqual(on.label, "Older Metal · override on")
XCTAssertEqual(on.tone, .warning)
@@ -52,7 +52,7 @@ final class ToolchainGateCopyTests: XCTestCase {
let s = ToolchainGateCopy.summary(report: report(metal: newer, otherBlock: true), overrideOn: false)
XCTAssertEqual(s.label, "Blocked")
XCTAssertEqual(s.tone, .blocked)
- XCTAssertEqual(s.buildHint, "Build blocked — Settings → Engine")
+ XCTAssertEqual(s.buildHint, "Build blocked — Settings → Setup and engine")
let on = ToolchainGateCopy.summary(report: report(metal: .same, otherBlock: true), overrideOn: true)
XCTAssertEqual(on.label, "Override enabled")
XCTAssertEqual(on.tone, .override)
diff --git a/Tests/NXLibraryCoreTests/UpstreamCopyTests.swift b/Tests/NXLibraryCoreTests/UpstreamCopyTests.swift
index ee7c3cf3..cefadedc 100644
--- a/Tests/NXLibraryCoreTests/UpstreamCopyTests.swift
+++ b/Tests/NXLibraryCoreTests/UpstreamCopyTests.swift
@@ -3,10 +3,10 @@ import XCTest
final class UpstreamCopyTests: XCTestCase {
func testNewCommitsArriveWithUpdates() {
- XCTAssertEqual(UpstreamCopy.subtitle(upToDate: true, newCommits: 0), "This NX Library uses the newest nxnative.")
+ XCTAssertEqual(UpstreamCopy.subtitle(upToDate: true, newCommits: 0), "This version of Arcane uses the newest nxnative.")
XCTAssertEqual(UpstreamCopy.subtitle(upToDate: false, newCommits: 1),
- "nxnative has 1 newer commit. Engine updates reach you with NX Library updates, once tested.")
+ "nxnative has 1 newer commit. Engine updates reach you with Arcane updates, once tested.")
XCTAssertEqual(UpstreamCopy.subtitle(upToDate: false, newCommits: 12),
- "nxnative has 12 newer commits. Engine updates reach you with NX Library updates, once tested.")
+ "nxnative has 12 newer commits. Engine updates reach you with Arcane updates, once tested.")
}
}
diff --git a/Tests/PublicationChecks/test_profile_boundaries.py b/Tests/PublicationChecks/test_profile_boundaries.py
new file mode 100644
index 00000000..4cb6c1d6
--- /dev/null
+++ b/Tests/PublicationChecks/test_profile_boundaries.py
@@ -0,0 +1,19 @@
+from pathlib import Path
+import re
+import unittest
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+class ProfileBoundaries(unittest.TestCase):
+ def test_launcher_storage_and_default_preferences_are_centralized(self):
+ unexpected = []
+ for file in (ROOT / 'Sources').rglob('*.swift'):
+ if file.name == 'AppDataProfile.swift':
+ continue
+ source = file.read_text()
+ if 'UserDefaults.standard' in source or re.search(r'UserDefaults\s*=\s*\.standard', source):
+ unexpected.append(str(file.relative_to(ROOT)) + ': unscoped preferences')
+ if re.search(r'\.appendingPathComponent\("Library/Application Support/NXLibrary(?:/|"|\-)', source):
+ unexpected.append(str(file.relative_to(ROOT)) + ': unscoped launcher directory')
+ self.assertEqual(unexpected, [], '\n'.join(unexpected))
diff --git a/VERSION b/VERSION
index b6586755..0ea3a944 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.1.4.3
+0.2.0
diff --git a/docs/architecture.md b/docs/architecture.md
index 3b873fce..8c828f3d 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -1,26 +1,41 @@
-# NX Library — guida tecnica
+# Arcane — guida tecnica
-Aggiornamento 12 novembre 2026 per NX Library 0.1.4.3. Il pin è `8a5c5e7e`, con Metal 32023.922 / Xcode 27.2: adozione esplicitamente richiesta dal maintainer dopo la revisione di 152 commit. I tool dell'engine sono nativi (niente .NET); NX Library ferma i build dando all'engine il tempo di chiudere i tool nelle loro sessioni e rifiuta import/ripristino dei salvataggi mentre un download cloud dell'engine è incompleto. Build e avvio reali sull'esatto hash restano da confermare dal maintainer. Vedi la [revisione engine](upstream-upgrades/2026-11-12-79741184-8a5c5e7e-review.md).
+Questa guida descrive **come funziona l'app oggi**, area per area. Non contiene storia né stati di validazione: lo storico è nel [CHANGELOG](../CHANGELOG.md) e nelle note datate, cosa ha provato il maintainer è in [validation.md](validation.md).
-Questa guida descrive il funzionamento attuale. Il [catalogo dei file](file-map.md) assegna una responsabilità a ogni file versionato, suddiviso per area.
+Ordine di lettura per chi lavora sul codice:
+1. [AGENTS.md](../AGENTS.md): le regole.
+2. Questa guida: la mappa.
+3. [conventions.md](conventions.md): come si costruisce una cosa nuova.
+4. [flows.md](flows.md): i percorsi completi.
+5. Il documento dell'area, se c'è (per esempio [steam.md](steam.md)).
+6. [file-map.md](file-map.md): un file per riga.
-Il [README](../README.md) è la guida d'uso; la [guida di sviluppo](development.md) raccoglie build, runtime, CI e release. Il [changelog](../CHANGELOG.md) distingue il lavoro non pubblicato dalle versioni distribuite. Il runtime e i contenuti versionati vengono verificati da `scripts/check_publication.py`; `build_app.sh` installa il bundle completo attraverso `BuildOutputInstaller`, dopo firma e verifica.
+Il [README](../README.md) è la guida d'uso; la [guida di sviluppo](development.md) raccoglie build, runtime, CI e release.
+
+**Engine attuale:** pin `461a5f9f95fc9fc40a690bb2a82eb23f1f03bdca`, definito in `AppViewModel.pinnedEngineCommit`. Il suo lock certifica Metal `32023.922`, asset Apple `27B47`, con Xcode minimo `27.2`. Le revisioni di ogni pin sono in [upstream-upgrades](upstream-upgrades/README.md).
## Indice
- [Struttura e dipendenze](#struttura-e-dipendenze)
-- [Avvio e stato dell’app](#avvio-e-stato-dellapp)
-- [Libreria e navigazione](#libreria-e-navigazione)
-- [Setup e compatibilità](#setup-e-compatibilità)
+- [Avvio e stato dell'app](#avvio-e-stato-dellapp)
+- [Catalogo, fonti e libreria](#catalogo-fonti-e-libreria)
+- [Navigazione e focus](#navigazione-e-focus)
+- [Impostazioni](#impostazioni)
+- [Lingua e regione](#lingua-e-regione)
+- [Setup, engine e compatibilità](#setup-engine-e-compatibilità)
- [Sorgenti e porting](#sorgenti-e-porting)
- [Avvio dei giochi e sessioni](#avvio-dei-giochi-e-sessioni)
-- [Cheats](#cheats)
+- [Pagina del gioco](#pagina-del-gioco)
+- [Cheat](#cheat)
+- [Mod](#mod)
- [Salvataggi, backup e recupero](#salvataggi-backup-e-recupero)
-- [Artwork, metadati e sfondi](#artwork-metadati-e-sfondi)
+- [Spazio su disco](#spazio-su-disco)
+- [Artwork, metadati e voti](#artwork-metadati-e-voti)
- [Interfaccia Selene e input](#interfaccia-selene-e-input)
- [Dati su disco](#dati-su-disco)
- [Aggiornamenti e distribuzione](#aggiornamenti-e-distribuzione)
- [Verifica e manutenzione](#verifica-e-manutenzione)
+- [Steam](steam.md): documento a parte
## Struttura e dipendenze
@@ -32,7 +47,7 @@ Il [README](../README.md) è la guida d'uso; la [guida di sviluppo](development.
| `NXLibraryCore` | Modelli, persistenza, parsing, gestione file, contratti del motore, processi e logica delle funzionalità. |
| `NXLibraryCoreTests` | Test XCTest del Core, con dati sintetici e dipendenze sostituibili. |
-`NXLibrary` dipende da `NXLibraryCore`. Il Core usa anche framework macOS, fra cui Combine, AppKit, ImageIO, CommonCrypto e IOKit. Il package attuale usa i framework del sistema e non dichiara dipendenze SwiftPM esterne.
+`NXLibrary` dipende da `NXLibraryCore`. Il Core usa anche framework macOS, fra cui Combine, AppKit, ImageIO, CommonCrypto e IOKit. Il package non dichiara dipendenze SwiftPM esterne.
```mermaid
flowchart TD
@@ -47,274 +62,707 @@ flowchart TD
Core --> Network["Cataloghi artwork, metadati e release"]
```
-Il checkout nxnative fornisce estrattore, rewriter, shader, profili dei giochi e runtime dei giochi compilati. NX Library prepara gli argomenti, controlla i requisiti e presenta lo stato delle operazioni. Il pin attuale è `4a0551e4b9abc75ea736006e4dbd30fcac0d03a4`, definito in `AppViewModel.pinnedEngineCommit`. La cache dello stato upstream viene riutilizzata soltanto quando il suo commit di base coincide con il pin.
-
-## Avvio e stato dell’app
-
-`NXLibraryApp.swift` registra una sola `Window` e i comandi della barra menu. File → Add Game sostituisce New Window: controller, updater e catalogo condiviso non offrono un flusso multi-finestra. `AppDelegate.swift` registra il font Material Icons e gestisce chiusura e riapertura della finestra. `MainView.swift` presenta `AppShellView`.
-
-`AppShellView.swift` possiede gli oggetti condivisi tramite `@StateObject`. Comprendono `AppViewModel`, router, impostazioni, sessioni di gioco, artwork, monitor dei giochi e updater. Imposta palette, canvas Selene, preferenze di accessibilità e livelli sovrapposti. Intro, Setup, menu, ricerca, opzioni di un gioco e conferme ricevono una priorità esplicita nell’input.
-
-`NativeMenuCommands` osserva il tracking dei menu AppKit e rinvia le azioni al turno successivo della coda principale, conservando la sospensione dell’input durante il passaggio. La shell pubblica le disponibilità nella scena attiva tramite `FocusedValues`: intro, Setup, pannelli e assenza di selezione disabilitano i comandi non applicabili. Mouse, monitor tastiera e dispatch controller non cambiano selezione sotto un menu nativo. In Spotlight, Game Details usa `SpotlightState.showGameDetails` come il comando interno e conserva il titolo selezionato; in Collection apre la pagina Details. Game Options blocca l’hit testing del contenuto sottostante.
-
-`startInFullscreen` viene salvato in AppSettings, ha default false per i vecchi file, compare in Search/Changed e viene ripristinato dal reset Start-up. `StartupWindowView` legge il valore alla creazione e applica una sola volta la modalità alla finestra visibile e attiva. Cambiare la preferenza non altera la finestra corrente.
-
-
-`AppViewModel.swift` coordina libreria, rilevamento dell’ambiente, selezione delle sorgenti, porting e lancio. Le estensioni `AppViewModel+…` contengono le integrazioni di cheats, salvataggi, diagnostica, controlli delle chiavi, toolchain e installazioni in attesa. Sono parti dello stesso oggetto osservabile.
-
-La shell condivide un solo `AppSettingsStore` con router e coordinatore. L’avvio rispetta i flag di verifica del motore e scansione della libreria; senza scansione carica il catalogo salvato. Il primo Setup accompagna l'utente in Get ready e Your games, dove Skip for now completa l'introduzione anche con libreria vuota. La verifica prima di ogni porting resta obbligatoria. I pannelli di build possono avviarla su richiesta. I risultati asincroni relativi a un checkout precedente vengono scartati e il porting registra la propria fotografia della toolchain.
-
-`FirstRunSetup` tiene insieme pagina corrente e completamento: `NXLibrary_SetupPage` permette di riprendere una prima configurazione interrotta, mentre `NXLibrary_SetupCompleted` mantiene compatibili gli utenti già configurati e impedisce ripetizioni automatiche dopo Skip. Open Setup riapre manualmente entrambi i passaggi senza rendere incompleta una configurazione precedente. `YourGamesSetupView` aspetta la scansione prima di distinguere libreria vuota o pronta; Open library e Skip tornano alla libreria. I due passaggi condividono backdrop, indicatore, transizioni e canale di input; Add Game sospende il proprio input quando Setup è davanti.
-
-`SetupCheckModel` e `SavePanelModel` possiedono lo stato dei rispettivi pannelli. `SavePanelModel`, per esempio, mantiene anteprima, operazione in corso, errore, ultimo backup ed evento di importazione riuscita. Gli aggiornamenti destinati alla UI vengono pubblicati sulla coda principale.
-
-## Libreria e navigazione
-
-`PortedGame` rappresenta un titolo della libreria. Include identità, app installata, sorgenti, impostazioni runtime, ultimo porting, toolchain e installazione eventualmente differita. `LibraryFile` è il contenitore persistito in `library.json`.
-
-`GameResourceState` riconcilia app, sorgenti e stato: conserva build in corso e workspace non ancora compilati, distingue app mancante e file di origine mancanti e mantiene Play per una build esistente. Le viste usano `PortingPills.unavailable` per il motivo breve e l'azione primaria disabilitata; `PortingTileLook.locked` riusa sfocatura e lucchetto. La voce rimane in libreria. Non viene aggiunta alcuna ricerca dell'app spostata; Refresh controlla le cartelle già configurate. Un cambio cartella durante la scansione scarta il contesto precedente e avvia quella nuova.
-
-`ImportService` scansiona i bundle `.app`, legge `Info.plist`, riconosce gli identificativi nxnative e produce le voci importabili. La candidata UX aggiunge una visita breadth-first nelle sole cartelle scelte, fino a sei livelli e 4000 directory, con deduplicazione dei percorsi canonici. Non entra in bundle/package e non segue i symlink delle sottocartelle. Limiti e letture fallite producono avvisi con motivo e azione utile: sono visibili accanto a Scan game apps nelle impostazioni e, nel primo Setup, sotto Game apps. Non aprono dialoghi automatici né un ciclo Retry all’avvio e non cancellano il catalogo. Una scansione successiva aggiorna o rimuove gli avvisi. `appsForLibrary` seleziona una sola osservazione per titolo: il percorso già registrato se esiste, altrimenti la prima osservazione del risultato ordinato dalla più recente. Se un'app esiste fuori dall'area scandita, la sua voce resta invariata. Merge e metadati usano la stessa selezione.
-
-`AppSizeCache` ricorda le dimensioni in funzione di percorso e data di modifica. `LibraryStore` carica e salva il catalogo, conserva `library.json.bak` e offre il merge delle voci. Il coordinamento applicativo riconcilia app trovate, dati già salvati e sorgenti disponibili.
-
-La candidata UX integra `FullscreenCursorView` nella shell. Un NSView osserva la propria finestra, il mouse e le transizioni native; `CursorIdleState` decide la visibilità usando il tempo monotono. In fullscreen attivo, con mouse nel contenuto, il puntatore si nasconde dopo tre secondi senza movimento. Cambi di schermata, menu interni, ricerca, opzioni, tastiera/controller, click e scroll non lo rendono visibile. La posizione reale viene campionata anche dal timer: i loop nativi di menu e controlli possono consumare gli eventi prima del monitor locale. Durante un menu nativo si sospende il nuovo nascondimento, senza svelare un puntatore già nascosto; alla chiusura viene riallineato lo stato AppKit. Un movimento riavvia il ritardo. Pannelli di sistema, perdita di focus e uscita fullscreen ripristinano la visibilità. Il distacco rimuove monitor, timer e osservatori e ripristina il precedente `acceptsMouseMovedEvents`. **Il maintainer ha confermato la revisione 2 di scansione e cursore e, nella candidata finale 0.1.2, menu nativi, dialogo aggiornamenti, avvio fullscreen, riga di scansione e gate certificato.**
-
-Il merge parte dalla voce persistita e aggiorna esplicitamente i dati osservati dalla scansione. Conserva impostazioni, identità, preferiti, installazione in attesa ed errore dell’ultimo porting. Restano le regole precedenti per associare le sorgenti e conservare la provenienza di una build installata.
-
-Settings → Library usa un'unica riga **Scan game apps**, con la stessa azione per scoperta e refresh. La riga e l'azione controller sono disabilitate durante la scansione. Il catalogo Search usa lo stesso nome; Collection conserva il proprio ingresso per importare build esistenti.
-
-L’aggiunta o il collegamento esplicito delle sorgenti usa `merge(replacingSources: true)`: la selezione confermata sostituisce sorgenti, workspace e percorso della cache, anche se i file precedenti esistono ancora. I file originali restano sul disco. Le scansioni automatiche continuano a conservare la selezione già registrata e il bundle installato.
-
-### Ambito delle impostazioni
-
-| Punto dell’interfaccia | Autorità |
+Il checkout nxnative fornisce estrattore, rewriter, shader, profili dei giochi e runtime dei giochi compilati. Arcane prepara gli argomenti, controlla i requisiti e presenta lo stato delle operazioni. La cache dello stato upstream si riusa soltanto quando il suo commit di base coincide con il pin.
+
+## Avvio e stato dell'app
+
+**Finestra e menu.**
+- `NXLibraryApp.swift` registra una sola `Window` e i comandi della barra menu. File → Add Game sostituisce New Window: controller, updater e catalogo condiviso non offrono un flusso a più finestre.
+- `AppDelegate.swift` registra il font Material Icons e gestisce chiusura e riapertura della finestra. `MainView.swift` presenta `AppShellView`.
+- `NativeMenuCommands` osserva il tracking dei menu AppKit e rinvia le azioni al turno successivo della coda principale, mantenendo l'input sospeso durante il passaggio.
+- La shell pubblica le disponibilità nella scena attiva tramite `FocusedValues`: benvenuto, Setup, pannelli e assenza di selezione disabilitano i comandi che non si applicano. Mouse, tastiera e controller non cambiano selezione sotto un menu nativo.
+- In Spotlight, Game Details usa `SpotlightState.showGameDetails` come il comando interno e conserva il titolo selezionato; in Collection apre la pagina Details. Game Options blocca l'hit testing del contenuto sottostante.
+
+**Profilo dei dati.**
+- `AppDataProfile` e `AppData` centralizzano percorsi e preferenze. Il marker di build `NXLibraryDevelopmentProfile` e il bundle ID `local.nxlibrary.development` distinguono la Dev dalla release; la release usa i percorsi di sempre.
+- `DevelopmentStartupView` prepara il profilo in background prima di costruire gli store e la shell, senza schermata di preparazione. `LaunchReveal` tiene trasparente la finestra fino al primo frame del moonlight (il drawable presentato, su entrambi i percorsi di rendering), con ripiego dopo 1 s, poi la mostra con una dissolvenza di 0,25 s. Un errore mostra il recupero senza aspettare il moonlight. *Perché:* la transizione fullscreen parte da una finestra già disegnata. `DevelopmentProfileImporter` legge la sorgente senza attivare gli store che la potrebbero riparare, copia in staging una lista dichiarata di dati, verifica gli hash e attiva la destinazione separata.
+- Le preferenze storiche appartengono a una lista esplicita; file di credenziali e nuovi token non si copiano per semplice prefisso. Le sessioni rimaste aperte nella copia terminano all'ultimo heartbeat registrato. Ripetere l'avvio non reimporta e non sovrascrive la Dev. La copia fallisce con Retry/Close, senza ripiegare sul profilo stabile.
+- Nella Dev il recupero dei salvataggi e la riconciliazione automatica delle icone non partono all'avvio. `DevelopmentOperationStore`, escluso dall'import, registra le richieste esplicite di build e icone e ne permette la ripresa dopo un riavvio. La pulizia automatica visita solo la Temp del profilo Dev, non lo staging sui volumi condivisi. Il factory dei `ModStore` disabilita la manutenzione automatica: consultare e aggiornare le schede non scrive l'overlay né elimina installazioni residue, e la lettura usa lo stato reale dell'overlay. Le azioni manuali agiscono sui giochi reali.
+- `release.sh` rifiuta un marker Dev nel pacchetto, e `AppUpdate` rifiuta un pacchetto del genere come aggiornamento.
+
+**Shell.**
+- `AppShellState` prepara coordinatore, router, lingua e tema sul main actor prima di pubblicare la shell pronta. L'inserimento nella finestra già visibile conserva gli oggetti preparati. Il bootstrap prepara catalogo e profilo prima della shell, quindi il modello usa quel documento senza una seconda lettura fallibile durante l'inizializzazione.
+- `AppShellView.swift` possiede gli oggetti condivisi tramite `@StateObject`: `AppViewModel`, router, impostazioni, sessioni, artwork, monitor dei giochi e updater. Imposta palette, canvas Selene, preferenze di accessibilità e livelli sovrapposti. Benvenuto, Setup, menu, ricerca, opzioni di un gioco e conferme ricevono una priorità esplicita nell’input.
+- La shell condivide un solo `AppSettingsStore` con router e coordinatore. L'avvio rispetta i flag di verifica del motore e di scansione della libreria; senza scansione carica il catalogo salvato.
+- `startInFullscreen` sta in `AppSettings` (default false), compare in Search e Changed e torna al default con il reset di Start-up. `StartupWindowView` lo legge alla creazione e lo applica una sola volta alla finestra visibile e attiva, dopo `LaunchReveal.whenShown`. `isWindowSettling` tiene ferma l’entrata fino alla notifica di fine transizione, con ripiego a 4 s dall’aggancio alla finestra. Cambiare la preferenza non altera la finestra corrente.
+
+**Coordinatore.**
+- `AppViewModel.swift` coordina libreria, rilevamento dell'ambiente, selezione delle sorgenti, porting e lancio. Le estensioni `AppViewModel+…` collegano cheat, salvataggi, diagnostica, chiavi, toolchain, installazioni in attesa e fonti; sono parti dello stesso oggetto osservabile.
+- Gli stati di un solo pannello hanno il loro modello: `SetupCheckModel`, `SavePanelModel` (anteprima, operazione in corso, errore, ultimo backup, importazione riuscita) e gli altri elencati in [conventions.md](conventions.md#1-dove-va-il-codice). Gli aggiornamenti destinati alla UI si pubblicano sulla coda principale.
+
+**Primo avvio.**
+- Il primo avvio apre su `found`: cosa c'è già sul Mac, letto senza cambiare nulla.
+ `FirstRunFindings` conta i giochi Steam per Mac installati (`.nativeReady`) e le app portate nella
+ cartella Game apps; `FirstRunFindingsReader` legge in un worker annullabile. Open library è utilizzabile anche durante la lettura: annulla la richiesta prima di completare il Setup, senza inventare risultati o attivare fonti non scelte. Le fonti restano aggiungibili dalle Impostazioni; un risultato tardivo è scartato dal requestID.
+- La scoperta usa `CatalogSourcesModel.discoveryRoot`: cartella scelta nella fonte, anche spenta,
+ altrimenti quella standard. Una lettura incompleta o fallita mostra Retry senza interruttore;
+ non equivale a nessun gioco trovato. Retry ripete la lettura senza attivare la fonte.
+- La riga Steam pronta ha un interruttore acceso; le app portate sono una riga informativa;
+ Porting apre i requisiti. `FirstRunSetup.steamChoice` si salva in `NXLibrary_SetupSteamChoice`
+ finché il Setup è incompleto, così resta anche dopo una chiusura durante Porting.
+ Quando il primo avvio finisce da Open library, Your games o Skip, la shell applica la scelta
+ con `CatalogSourcesModel.configure`. Open library completa il Setup; la fonte Switch si
+ accende solo se c'erano app portate, che entrano subito nella libreria.
+- Dalla card Porting il Setup prosegue in Get ready e Your games; B su Get ready torna a `found` durante il primo avvio. Skip for now completa l'introduzione anche con libreria vuota. La verifica prima di ogni porting resta obbligatoria, e i pannelli di build possono avviarla su richiesta. I risultati asincroni di un checkout precedente si scartano, e il porting registra la propria fotografia della toolchain.
+- `FirstRunSetup` tiene insieme pagina corrente e completamento. `NXLibrary_SetupPage` permette di riprendere una configurazione interrotta; `NXLibrary_SetupSteamChoice` conserva la scelta facoltativa (acceso, spento o mai scelta) e si elimina al completamento, dopo averla mantenuta nel modello per la shell; `NXLibrary_SetupCompleted` mantiene compatibili gli utenti già configurati e impedisce ripetizioni automatiche dopo Skip. Una configurazione completata non torna mai a `found`; Open Setup riapre manualmente Get ready e Your games senza rendere incompleta una configurazione precedente.
+- `YourGamesSetupView` aspetta la scansione prima di distinguere libreria vuota o pronta; Open library e Skip tornano alla libreria. `FoundGamesSetupView` e Your games disegnano le righe con `SetupCardRow`. Le pagine condividono backdrop, indicatore, transizioni e canale di input; Add Game sospende il proprio input quando Setup è davanti.
+- **Benvenuto in Arcane.** Chi aggiorna da NX Library vede una volta `ArcaneWelcomeView`: il nome nuovo, quattro novità, l'offerta di Steam se è trovato con giochi e la sua fonte è spenta (la ricerca e l’attivazione usano la stessa `discoveryRoot`; Add accende la fonte con `CatalogSourcesModel.configure`, Not now non accende nulla) e Open library. `ArcaneWelcome` decide: Setup completato, `AppSettings.welcomeArcaneShown` falso e nessun recupero in corso.
+- `AppShellState` decide il benvenuto prima di pubblicare la shell, così la libreria non compare in mezzo. Benvenuto e pagine Setup chiedono lo sfondo alla shell come ogni pagina (`SeleneBackdropRequest`): il moonlight è uno solo, quindi chiuderli lascia lo stesso sfondo in movimento. I recuperi si aprono sopra; se il benvenuto non era dovuto all’avvio, la shell lo presenta più tardi solo quando Setup, dialoghi, lancio e visore sono chiusi e nessuna operazione sui salvataggi è in corso (`hasActiveSaveOperations`). Il Setup ha precedenza nel disegno e nell’input.
+- Fino alla fine della dissolvenza del benvenuto, `AppViewModel.isWelcomeOpen` fa cedere la tastiera ai monitor delle schermate sotto e trattiene l’entrata di Spotlight, come `isUpdateOfferOpen` per l’offerta di aggiornamento; `ShellOverlayInputTests` controlla che ogni monitor ceda a entrambi. Ogni uscita (Open library, B, Esc) prima sfuma, poi salva e passa alla libreria (`SeleneTheme.screenDuration` dopo). Le uscite e la fine di un primo Setup impostano `welcomeArcaneShown`, così un’installazione nuova non lo vede mai. Non tocca `RunningGameMonitor` né `SteamPlayCoordinator`: un gioco aperto resta giocabile.
+
+## Catalogo, fonti e libreria
+
+**Il catalogo comune.**
+- `CatalogGame` conserva un payload tipizzato: il `PortedGame` completo per nxnative oppure `SteamCatalogGame`. Nome, UUID e scelte personali hanno un solo proprietario; il riferimento alle personalizzazioni conserva chiave e namespace dell'integrazione. Non si costruisce mai un falso gioco nxnative per Steam.
+- `CatalogGamePresentation` espone installazioni, operazioni supportate e un target di avvio tipizzato, senza avviare servizi o consultare il disco. La disponibilità dell'avvio resta distinta dal supporto dell'operazione, e una fonte disattivata non produce un target utilizzabile.
+- `CatalogDocument` (versione 1) contiene revisioni, fonti abilitate e fingerprint della base legacy riconosciuta alla conversione o dopo una scelta esplicita di conservare il catalogo.
+- `CatalogStore` legge input regolari fino a 16 MiB. Converte direttamente i byte di `library.json` (formato precedente, descritto da `LibraryFile`), mantiene UUID, payload e chiavi e lascia `library.json` intatto.
+ - Le scritture concorrenti usano un lock non bloccante e la revisione attesa. Il candidato si serializza, si rilegge e si valida prima della pubblicazione atomica; una copia valida precede la sostituzione del principale.
+ - Archivio danneggiato, versione sconosciuta, input legacy cambiato e principale assente con backup richiedono un recupero esplicito, mai una libreria vuota automatica. L'offerta di ripristino conserva gli hash di principale e backup: se i file cambiano, l'offerta non vale più; il principale danneggiato si conserva e il backup resta intatto.
+ - Se il catalogo è valido ma la vecchia app modifica gli input legacy, `DevelopmentStartupView` offre **Keep Arcane's library**. `CatalogLegacyConflictCandidate` cattura le impronte di catalogo, backup e input; `keepCurrentLibrary` le rivalida sotto lock e archivia i byte presenti in una cartella esclusiva `catalog-conflict-*` prima di riconoscere la nuova base legacy. Mantiene giochi e fonti Arcane, senza fusione e senza scrivere sui file legacy. Il catalogo e il suo restore point usano la stessa base riconosciuta; una successiva modifica legacy torna a bloccare letture e scritture. *Perché:* una vecchia copia riaperta dopo un aggiornamento manuale non deve imporre di scartare il catalogo nuovo.
+ - `commitUncertain` segnala un errore della sincronizzazione finale dopo una possibile pubblicazione: il chiamante rilegge la revisione prima di ritentare.
+ - Il formato usa i valori Date Codable per conservare le frazioni; solo l'ingresso legacy usa ISO8601.
+- `CatalogRepository` è l'unico writer del catalogo. Carica la versione corrente e applica ogni modifica tipizzata una volta; non ritenta da solo operazioni con effetti sui file. Le scansioni confrontano la generazione osservata con build, installazione e sorgenti correnti prima di aggiornare i campi; una richiesta di refresh durante una scansione resta in coda.
+- `AppViewModel` pubblica il catalogo e una proiezione nxnative di sola lettura. Scansioni, icone, sorgenti e risultati delle build passano dallo stesso repository; le righe mostrate non si salvano mai come libreria di ripiego.
+- Il risultato di una build aggiorna soltanto i campi di sua competenza. Un risultato non salvato resta in `CatalogBuildRecoveries` per il retry della generazione giusta; le installazioni automatiche aspettano che sia risolto. Il risultato e il menu File tengono disponibile l'azione di salvataggio anche dopo la chiusura dell'avviso.
+- `CatalogPersonalizations` porta i riferimenti alle viste e ai loader; i percorsi nxnative restano quelli di sempre, i dati personali Steam hanno una radice separata. L'importatore Dev comprende i file del catalogo.
+
+**I giochi Switch (nxnative).**
+- `PortedGame` rappresenta un titolo nxnative: identità, app installata, sorgenti, impostazioni runtime, ultimo porting, toolchain e installazione eventualmente differita.
+- `ImportService` scansiona i bundle `.app` nelle sole cartelle scelte e riconosce un gioco da `DMTitleID` o dal bundle ID `org.nxnative.`. La visita è in ampiezza, fino a sei livelli e 4000 cartelle, con deduplicazione dei percorsi canonici. Non entra in bundle e package e non segue i link delle sottocartelle.
+- Limiti e letture fallite producono avvisi con motivo e azione utile, visibili accanto a Scan game apps e, nel primo Setup, sotto Game apps. Non aprono dialoghi automatici né cicli di Retry all'avvio e non cancellano il catalogo; una scansione successiva li aggiorna o li toglie.
+- `appsForLibrary` sceglie una sola osservazione per titolo: il percorso già registrato se esiste, altrimenti la più recente. Un'app fuori dall'area scandita lascia invariata la sua voce. Merge e metadati usano la stessa scelta.
+- `NXNativeLibraryMerge` parte dalla voce salvata e aggiorna esplicitamente i dati osservati. Conserva impostazioni, identità, preferiti, installazione in attesa ed errore dell'ultimo porting, e la provenienza di una build installata.
+- L'aggiunta o il collegamento esplicito delle sorgenti usa `merge(replacingSources: true)`: la selezione confermata sostituisce sorgenti, workspace e percorso della cache, anche se i file precedenti esistono ancora. I file originali restano sul disco. Le scansioni automatiche conservano la selezione registrata e il bundle installato.
+- `GameResourceState` riconcilia app, sorgenti e stato. Conserva build in corso e workspace non ancora compilati, distingue app mancante da file d'origine mancanti e mantiene Play per una build esistente. Le viste usano `PortingPills.unavailable` per il motivo breve e l'azione primaria disabilitata; `PortingTileLook.locked` riusa sfocatura e lucchetto. La voce resta in libreria: non si cerca l'app spostata, e Refresh controlla le cartelle già configurate. Un cambio di cartella durante la scansione scarta il contesto precedente e avvia quella nuova.
+- `AppSizeCache` ricorda le dimensioni per percorso e data di modifica.
+- Settings → Library usa un'unica riga **Scan game apps** per scoperta e refresh, disabilitata durante la scansione (anche come azione del controller). Collection conserva il proprio ingresso per importare build esistenti.
+
+**Le fonti.**
+- `CatalogSourcesModel` tiene configurazione e stato della fonte Steam e la richiesta di scansione corrente. La lettura avviene su un worker annullabile. Disattivazione, cambio di cartella o nuova richiesta invalidano il risultato precedente. La generazione salvata distingue anche disattivazione e riattivazione sulla stessa radice; nei cataloghi schema 1 più vecchi il valore mancante si legge come una sentinella fissa. Un risultato valido si applica all'ultima revisione conservando le modifiche indipendenti ai preferiti.
+- `SteamCatalogReconciler` applica snapshot già letti, con un ticket legato alla revisione e alla radice. La fusione mantiene UUID, preferiti, nascosti e installazioni storiche. Un titolo ambiguo resta da verificare, una scansione parziale conserva le osservazioni non viste, una fonte assente segnala indisponibilità; l'assenza diventa "non rilevato" solo con uno snapshot completo. `needsInstallationReview` tiene l'ambiguità separata dalla disponibilità del disco. Nessun record o file di gioco viene eliminato.
+- Menu → Manage sources e Settings → Sources attivano Steam, aggiornano o annullano la ricerca, scelgono la sua cartella e recuperano titoli nascosti o installazioni da controllare. L'avvio scansiona solo Steam già abilitato. Adottare esplicitamente sorgenti o build Switch abilita nxnative nello stesso catalogo; una scansione passiva non attiva un'esperienza non scelta.
+- Tutto il resto di Steam è in [steam.md](steam.md).
+
+**La libreria mostrata.**
+- `CatalogLibraryProjection` seleziona le voci delle fonti attive. Spotlight, Collection e ricerca usano gli stessi record, UUID, filtri e ordine salvato; le viste specifiche ricevono il payload reale.
+- I giochi Steam mostrano l'icona della propria app Mac e la fonte, senza interrogare servizi Nintendo né riscrivere bundle. Hanno la stessa testata, pagina e Opzioni dei giochi nxnative. I titoli nascosti restano recuperabili dalle fonti.
+- Menu e comandi specifici nxnative ricevono soltanto `PortedGame`: selezionare un gioco Steam non può avviare una build né aprire salvataggi o mod Switch.
+
+## Navigazione e focus
+
+- `AppRouter` gestisce schermata corrente, cronologia di ritorno e richieste di selezione. `SpotlightState`, `LibrarySelectionState`, `DetailsFocus`, `MenuSelectionModel` e `FocusIndex` descrivono il focus indipendentemente dal disegno SwiftUI. `LibraryQuery` applica ricerca, filtri e ordinamento.
+- Le viste principali sono Spotlight, Collection e Details. Ricerca, Add Game, Console, Game Options e Settings si raggiungono dalla shell e dalle azioni del router. Le estensioni `…+Input.swift` traducono tastiera, mouse e controller in modifiche ai modelli di focus.
+- **Righe di tessere.**
+ - `SpotlightTileArtwork` e `SteamArtwork` leggono l'immagine già decodificata dalla cache anche nel primo body, prima della `.task`. `TileArtMemo` distingue fonte, richiesta e revisione della scelta personale, con limiti di 200 immagini e 160 MB. `GameIconProvider` ricorda anche i giochi senza icona quadrata, per percorso dell'app e del workspace: la build sposta il gioco sulla sua app, e `forget` legge di nuovo dopo un cambio d'icona. Steam include il build ID dell'installazione e rivalida i file nel task senza svuotare l'immagine durante la lettura. *Perché:* tornando da Settings le viste sono nuove, ma l'arte già caricata non deve passare dal ripiego mentre il task riparte.
+ - Le righe di Spotlight e Collection mettono ogni tessera al suo posto e scorrono con un'unica camera (`SpotlightRowGeometry`): la riga si muove come un pezzo solo, e una tessera creata al bordo mentre la riga scorre non arriva prima delle vicine.
+ - Lo scorrimento è una molla smorzata: a pressioni rapide riprende la velocità che ha invece di ripartire ogni volta. Le tessere si creano quattro oltre ogni bordo dello schermo.
+ - In Spotlight posto e dimensione di ogni tessera e la camera si ricavano da un solo valore animato, la posizione della selezione (un indice, con frazioni a metà strada). *Perché:* animati separatamente, la crescita di una tessera partiva un paio di fotogrammi dopo il suo spostamento e la tessera si staccava dalla vicina.
+ - Una selezione che salta più tessere scorre attraverso quelle in mezzo; mentre una tessera è sollevata per spostarla cresce solo lei.
+ - In Spotlight sinistra e destra sulla riga lavorano sulla lista filtrata. La parte sotto gli screenshot si monta quando la pagina sale, così navigare tra tessere evita il calcolo di descrizioni, classifica e link fuori schermo.
+- **Entrata di Spotlight** (`SpotlightView+Entrance`, tempi e fasi in `SpotlightEntrance`).
+ - C’è solo la prima volta che una home si vede dopo l’avvio, se è Spotlight (`AppViewModel.homeSeen`, che segna anche Collection), con **Entrance animation** accesa e mai con Riduci movimento. La chiave `introAnimation` resta compatibile; la shell usa lo stesso interruttore per il suono di avvio.
+ - Benvenuto e Setup, fino alla fine della chiusura, e la finestra che prende il fullscreen tengono l’entrata coperta. L’arte è nascosta (`ArtReveal.hidden`); riga e informazioni si preparano a opacità 0,001, mentre barra e pillola sono nascoste e non ricevono input. *Perché:* il primo disegno delle tessere avviene prima del volo. Benvenuto e Setup chiedono alla shell lo stesso sfondo condiviso, così chiuderli lascia lo stesso moonlight in movimento.
+ - Scoperta la home, il moonlight ha 0,5 s da solo. Poi l’entrata aspetta, per al massimo un altro secondo, che finisca la prima ricerca dell’arte (`TileArtPendingKey`, da `SpotlightTileArtwork` e `SteamArtwork`).
+ - L’arte entra in 1,4 s con la curva di `OpacityFade`, come lo scorrimento fra giochi. Il moonlight continua a muoversi finché l’arte è entrata; anche la prima immagine arrivata tardi sfuma (`SeleneArtLayerView.heldOnce`).
+ - Ogni tessera visibile parte più vicina al centro della riga (75% della distanza), con scala 0,35 e spostamento verticale −18 unità; vola in 0,9 s, con dissolvenza di 0,5 s, da 0,6 s più 0,06 s per tessera. Le tessere oltre il bordo destro fanno solo una dissolvenza, al massimo dodici. `EntranceFlight` e `EntranceFade` calcolano movimento e opacità su orologi lineari avviati insieme, con il ritardo dentro ogni effetto.
+ - Le informazioni salgono di 40 unità da 1,3 s, in 0,8 s, con dissolvenza di 0,7 s; il titolo sotto la selezione arriva da 2 s. `SpotlightEntrance.end(of:)` determina l’atterraggio finale. Le [misure dell’entrata](reviews/2026-11-17-entrance-frames.md) descrivono metodo, campioni e limiti della sonda temporanea.
+ - Barra in alto (tab e orologio) e hint dei pulsanti (`SeleneHomeChrome.hintsHeld`) arrivano per ultimi, insieme: a volo finito sfumano in 0,4 s (`SpotlightEntrance.controlsFade`). La pillola del filtro sale con lo sfondo.
+ - Nessun input salta l’entrata. Fino all’atterraggio (`Phase.takesInput`) Spotlight ignora controller, tasti e rotella e non riceve clic; passano solo le scorciatoie con ⌘, ⌃ o ⌥. *Perché:* l’entrata è l’apertura dell’app e va vista intera. Un volo iniziato atterra comunque entro 5 s (`SpotlightEntrance.longestWait`), così l’input non resta mai bloccato.
+ - Uscendo da Spotlight, ridimensionando durante il volo o accendendo Riduci movimento, tutto atterra subito, barra e hint compresi.
+- **Cursore a schermo intero.** `FullscreenCursorView` (un NSView nella shell) osserva finestra, mouse e transizioni native; `CursorIdleState` decide la visibilità con il tempo monotono.
+ - In fullscreen, con il mouse nel contenuto, il puntatore si nasconde dopo tre secondi senza movimento. Cambi di schermata, menu interni, ricerca, opzioni, tastiera, controller, clic e scroll non lo rendono visibile; un movimento riavvia il ritardo.
+ - La posizione reale si campiona anche dal timer, perché i loop nativi di menu e controlli possono consumare gli eventi prima del monitor locale. Durante un menu nativo non parte un nuovo nascondimento, ma un puntatore già nascosto resta nascosto; alla chiusura si riallinea lo stato AppKit.
+ - Pannelli di sistema, perdita di focus e uscita dal fullscreen ripristinano la visibilità. Il distacco rimuove monitor, timer e osservatori e ripristina il precedente `acceptsMouseMovedEvents`.
+
+## Impostazioni
+
+**La barra laterale.** `SettingsSidebarGroup` raggruppa le sezioni: Search e Changed, poi quattro gruppi.
+- **General:** Start-up, Navigation, Spotlight, Sound & music, Look, Controllers, Online services.
+- **Library:** Sources, Games, Storage. Valgono per i giochi di ogni fonte.
+- **Porting:** Setup and engine, Keys, Library, New games, Cloud saves, Storage. Valgono solo per i giochi convertiti.
+- **System:** About, Console. In `SettingsAboutSection`, il pulsante di sostegno volontario a tutta larghezza, prima dei crediti, mostra l’icona di Buy Me a Coffee e apre la pagina nel browser predefinito. Clic, tastiera e controller usano la stessa azione.
+
+Regole della barra:
+- Porting è l'unico gruppo di piattaforma (`isPlatform`): Search, Changed e il titolo di pagina chiamano le sue sezioni col nome del gruppo ("Porting · New games").
+- `SettingsSection` dichiara i casi nell'ordine della barra, quindi `allCases` la percorre come è disegnata. I `rawValue` sono identità e non cambiano: `sources` è la pagina Sources, `library` e `games` sono Library e New games di Porting; i casi nuovi (`libraryGames`, `keys`, `cloudSaves`, `portingStorage`, `console`) hanno identità proprie.
+- Ogni riga di `SettingsCatalog` tiene il suo `rowID` quando cambia sezione.
+- Dove stanno le righe che si potrebbero cercare altrove:
+ - schermata di lancio, Surprise me, card della sessione e giochi nascosti in Library → Games, perché valgono per ogni fonte;
+ - Rumble e Rumble strength in Porting → New games, perché sono default copiati nei nuovi giochi convertiti;
+ - prod.keys in Porting → Keys; Check engine at launch e Setup in Setup and engine, dove Compatibility ripete già il controllo dell'ambiente;
+ - Refresh library at launch e Box covers in Porting → Library;
+ - le cache di compilazione, per gioco e per tutti, in Porting → Storage; spazio usato, log, cache di metadati e artwork e backup in Library → Storage;
+ - App icon in Look: è l'icona del Dock.
+- Online services (`apiServices`) raccoglie IGDB (voti) e SteamGridDB (artwork). La nota iniziale dice che le connessioni sono facoltative e che le fonti pubbliche funzionano senza chiavi. Non esiste un reset di gruppo che elimini le credenziali.
+
+**Chi decide cosa.**
+
+| Punto dell'interfaccia | Autorità |
|---|---|
-| Settings → Games → New games | Valori iniziali copiati nei nuovi titoli. |
+| Settings → Porting → New games | Valori iniziali copiati nei nuovi titoli, vibrazione compresa. |
| Game Options → Next launch | Configurazione di quel titolo, applicata al prossimo avvio. |
| Use new game defaults | Copia una volta i default correnti nel gioco selezionato. |
| Add Game → Review | Nuovo titolo: parte dai default. Titolo esistente: `GameRuntimeConfig.forReview` legge le sue opzioni effettive. La conferma salva i valori mostrati. |
| Cloud saves | Preferenza riapplicata prima di ogni avvio, compreso Off. |
-| Controllers | Navigazione della libreria; il sottogruppo New games contiene i default della vibrazione. |
-
-Options e Play leggono `GameRuntimeConfig.load`: preferenze per titolo in UserDefaults, poi `env.txt` del titolo, quello nel bundle e infine i valori del modello. Il rebuild ricava `languageForBuild` dalla configurazione del titolo e non conserva una lingua separata dal wizard. Le modifiche dei default globali non aggiornano automaticamente i giochi già aggiunti. Search e Changed attribuiscono la vibrazione a Controllers.
-
-Il catalogo Settings descrive i singoli controlli; Changed riceve anche le differenze delle preferenze esterne ad AppSettings. Le azioni da controller si aggiornano con lo stato dei pannelli e mantengono il focus per identità. About pubblica azioni selezionabili. Il reset aggiorna AppSettings con una sola assegnazione e segnala le scelte cloud/percorso preservate.
-
-`AppSettingsStore` pubblica gli errori e conserva una copia dei file illeggibili prima di consentirne la sostituzione. La UI usa un dialogo Selene, con Retry per una scrittura fallita. `GameRuntimeConfig.save` propaga gli errori di env.txt e persiste le preferenze per titolo dopo la scrittura riuscita. Un env.txt illeggibile viene conservato e segnalato.
-
-`AppRouter` gestisce schermata corrente, cronologia di ritorno e richieste di selezione. I modelli `SpotlightState`, `LibrarySelectionState`, `DetailsFocus`, `MenuSelectionModel` e `FocusIndex` descrivono il focus indipendentemente dal disegno SwiftUI. `LibraryQuery` applica ricerca, filtri e ordinamento.
-
-Le viste principali sono Spotlight, Collection e Details. Ricerca, Add Game, Console, Game Options e Settings sono raggiunti dalla shell e dalle azioni del router. Le estensioni `…+Input.swift` traducono tastiera, mouse e controller in modifiche ai modelli di focus. Le righe di Spotlight e Collection mettono ogni tessera al suo posto nella riga e scorrono con un'unica camera (`SpotlightRowGeometry`): la riga si muove come un pezzo solo, e una tessera creata al bordo mentre la riga ancora scorre non arriva prima delle vicine. Lo scorrimento è una molla smorzata, che a pressioni rapide riprende la velocità che ha invece di ripartire a ogni pressione; le tessere si creano quattro oltre ogni bordo dello schermo. In Spotlight posto e dimensione di ogni tessera e la camera si ricavano da un solo valore animato, la posizione della selezione (un indice, con frazioni a metà strada): animati separatamente (offset, scala, camera), la crescita di una tessera iniziata mentre la riga ancora scorreva partiva un paio di fotogrammi dopo il suo spostamento, e la tessera si staccava da quella alla sua destra. Una selezione che salta più tessere scorre attraverso quelle in mezzo; mentre una tessera è sollevata per spostarla cresce solo lei.
-
-### Lingua e regione (non pubblicato, validato dal maintainer)
-
-`AppLanguage` definisce auto/en/it/fr/de/es/pt-BR; `AppLocale` risolve le preferenze ordinate del Mac e una regione indipendente, valida i codici e mappa pt-BR a pt soltanto per Nlib. `AppSettings` conserva i due override in modo additivo: vecchi file e scelte non riconosciute tornano ad Automatic. `NXLibraryApp.init` carica un solo `AppSettingsStore` e configura il locale prima della creazione delle scene; lo stesso store passa a `MainView` e `AppShellView`. Gli initializer delle viste non pubblicano cambi di locale: il controllo sincrono della toolchain può far rientrare il run loop mentre SwiftUI costruisce i propri StateObject. `AppLocalization` pubblica il contesto; la shell lo propaga alle viste tramite `nxAppLocale`, una dipendenza SwiftUI esplicita che non ricrea identità o stato. Settings passa questo valore alla sidebar e `SettingsSection.title(in:)` risolve le categorie nel contesto ricevuto, anche con focus sulle righe. Righe, informazioni, pannelli e suggerimenti condivisi consumano lo stesso valore. `L10n` mantiene al massimo un bundle per ciascuna delle sei lingue; le risorse iniettate restano isolate, senza memorizzare testi interpolati o dati personali. Cattura il contesto per il lavoro asincrono e legge esplicitamente il catalogo compilato, cercando prima nel bundle installato. Nessun servizio di posizione o traduzione esterno viene usato.
-
-I testi controllati dall'app sono nel catalogo condiviso `NXLibraryCore/Resources/Localizable.xcstrings`, con interpolazioni e plurali. Dati personali, rawValue persistiti, regex, eventi dell'engine, variabili DM_* e identità dei controlli restano indipendenti dalla lingua. I componenti Settings risolvono le etichette alla presentazione e mantengono i rowID originali; le righe coi nomi dei giochi usano titoli verbatim. Search confronta anche i testi tradotti. I testi upstream noti di launcher.json si localizzano solo nella presentazione; valori e note sconosciute conservano il fallback upstream.
-
-Start-up ospita lingua e regione. `LocalePicker` offre una scelta diretta delle lingue e ricerca i nomi localizzati delle regioni per codice stabile, con input tastiera/controller distinto da Settings. Le righe distinguono la lingua di menu, generi e descrizioni dai soli formati regionali. Il cambio non ricrea il router o le sessioni e non cambia la lingua di alcun gioco. Date e dimensioni rispettano il locale scelto; nomi dei giorni e durate hanno una presentazione localizzata.
-
-`GameGenre` traduce alla presentazione i generi noti senza modificare i metadati e le scelte salvate; generi sconosciuti restano verbatim. `NintendoStoreMetadataService` conserva le vecchie cache come inglesi e i percorsi per lingua/regione, riusando i dati tra regioni della stessa lingua. Un cambio di sola regione non aggiorna i metadati; un cambio lingua conserva la scheda visibile, legge la cache fuori dal thread principale e, con dati freschi già presenti, richiede soltanto la descrizione tradotta. Gli ID 0400 dei giochi Switch 2 sono ammessi al lookup Nlib come gli 0100. `descriptionCheckedAt` distingue un ripiego già controllato da una vecchia cache mai cercata nella lingua richiesta: una traduzione vuota viene ricontrollata dopo 24 ore, un errore temporaneo consente un nuovo tentativo dopo un minuto. Richiede una descrizione Nlib localizzata anche quando il catalogo US ne ha già una inglese; non invia parametri regione non documentati. Fallimenti parziali conservano prima una descrizione tradotta già presente in cache, senza rinnovarne artificialmente la freschezza; in sua assenza, fallimenti o descrizioni vuote conservano il ripiego inglese; il modello conserva la lingua della descrizione e Details e Spotlight indicano la lingua effettiva quando differisce dalla lingua dell’app. Scelte personali restano prioritarie. `metadataLocaleGeneration` impedisce a una risposta precedente di ripopolare la UI dopo un cambio lingua; screenshot e artwork rimangono condivisi.
-
-SwiftPM compila le risorse; build_app.sh le include prima della firma, mentre `check_localizations.py` verifica copertura delle sei lingue, placeholder, plurali e risorse compilate. release.sh ripete il controllo sullo ZIP estratto. Le traduzioni iniziali sono bozze dell'agente, non revisioni madrelingua certificate. Il maintainer ha confermato nella Dev i flussi e il cambio immediato di lingua, inclusa la sidebar senza spostare il focus; nessun servizio Crowdin/Transifex è stato aperto e la issue #10 non viene chiusa automaticamente.
-
-## Setup e compatibilità
-
-`SystemDetector` e `EngineLocation` individuano checkout e cartelle dell’utente. `NXNativeEnvironment` raccoglie lo stato di Python, strumenti, Xcode e Metal; da nxnative 641636e2 i tool dell'engine sono eseguibili nativi e .NET non serve più. `EngineToolchain` risolve Python e `PATH`, preferendo il runtime incluso nel bundle quando disponibile.
-
-`SetupProbe` costruisce i dati del Setup. `SetupCheck` li traduce in schede, stati e azioni. `SetupCheckModel` esegue i controlli in background e coordina installazioni e avanzamento. `SetupActions` prepara gli argomenti Git per portare un checkout gestibile al pin.
-
-Get ready mostra soltanto i cinque requisiti tecnici, in una griglia 3 + 2; i problemi alle cartelle non riaprono questa schermata. Your games presenta Game apps, la cartella unica in cui cercare giochi nxnative esistenti e installare le prime build. Il default `~/Applications` può essere preparato al primo uso solo se non è già stato scelto o ricordato un percorso. Le destinazioni personalizzate o confermate rimangono ricordate anche quando non disponibili. La lettura basta per scoperta e Play; le nuove installazioni richiedono scrittura. Game files rimane una preferenza facoltativa in Settings → Library, separata dalla selezione temporanea del wizard. Cambiare Game apps non sposta app già registrate; cambiare Game files non sostituisce i sorgenti di un titolo senza conferma esplicita. `GameFoldersCopy` mantiene i nomi coerenti.
-
-`CompatibilityChecker` verifica commit, modifiche del checkout, contratto CLI e compilatore Metal richiesto dal lock del motore. `ToolchainRequirements.current` contiene Xcode minimo e asset Metal. `ToolchainGateCopy` produce la spiegazione del risultato per la UI.
-
-Il lock del pin attuale certifica Metal `32023.922`, asset Apple `27B47`, con Xcode minimo `27.2`. La [revisione 79741184 → 8a5c5e7e](upstream-upgrades/2026-11-12-79741184-8a5c5e7e-review.md) registra il pin della 0.1.4.3, adottato su richiesta esplicita del maintainer; la [nota dell’upgrade del 6 novembre](upstream-upgrades/2026-11-06-4a0551e4-04df08d4-review.md) registra 04df08d4, confermato dal maintainer con un build di Ocarina of Time; quella [bd979ced → 79741184](upstream-upgrades/2026-11-09-bd979ced-79741184-review.md) registra il pin della 0.1.4.2, adottato su richiesta esplicita del maintainer con gate e test automatici superati ma build/avvio sull'esatto hash ancora non confermati; quella [e5f03403 → bd979ced](upstream-upgrades/2026-11-08-e5f03403-bd979ced-review.md) registra il pin della 0.1.4.1; quella [7fe9fc4d → e5f03403](upstream-upgrades/2026-11-07-7fe9fc4d-e5f03403-review.md) registra il pin precedente, confermato dal maintainer con un rebuild di Ocarina of Time; quella [b2d46b86 → 7fe9fc4d](upstream-upgrades/2026-11-07-b2d46b86-7fe9fc4d-review.md) registra il pin precedente, confermato dal maintainer con un rebuild di Ocarina of Time; quella [04df08d4 → b2d46b86](upstream-upgrades/2026-11-06-04df08d4-b2d46b86-review.md) registra b2d46b86, che aggiunge il controllo dei file `.zs` danneggiati in NUP e cartelle (riga `files.format` del classificatore); quella [del 5 novembre](upstream-upgrades/2026-11-05-b64a5ff0-4a0551e4-review.md) registra gate certificato senza override, build reale di Wonder con archivio pipeline e avvio confermato dall’utente per 4a0551e4. Un build con override riceve `toolchainVerified=false` e `--allow-other-metal`. Play valuta la disponibilità dell’app già installata separatamente dal gate per un nuovo porting.
-
-L'engine più nuovo è una scelta esplicita del giocatore (Settings → Engine → **Newest engine**). Dopo il controllo Upstream, che misura sempre i commit rispetto al pin, `NewestEngine.fetchLock` legge il lock di main da GitHub: se certifica un Metal diverso da quello del lock del pin, la riga dice che serve un NX Library più nuovo e non offre il cambio. `NewestEngineSwitcher` rifiuta un checkout con file modificati, scarica, rilegge il lock con git e solo allora fa `checkout --detach`. La scelta (`NewestEngineChoice`) è salvata, diventa il commit atteso dal gate e quello registrato nelle build, accende l'override (che resta bloccato finché la scelta è attiva) e marca le build come non testate; il gate mostra **Newest engine** in arancione, mai Certified. Il Setup continua a installare il pin, ma per il commit scelto mostra la scheda pronta in arancione con **Back to tested** e non la riporta indietro da solo. La scelta decade quando il checkout non è più su quel commit o quando un aggiornamento di NX Library porta un pin che lo contiene; se l'override l'aveva acceso la scelta, torna spento. Settings e Setup usano la stessa frase (`NewestEngineCopy.note`).
-
-Il pin `04df08d4` (poi superato da `b2d46b86`) non cambia CLI, eventi di progresso, compilatore Metal né lettori NUP e cartelle (`pack_nup`, `pack_dump`). Cache di compilazione e librerie shader diventano un file ciascuna (`shader/cache/cas.db`, `msl/b-.img`): NX Library non legge dentro nessuno dei due. Il primo build di un gioco dopo l'aggiornamento sposta prima la vecchia cache nel nuovo file e lo annuncia con `moving the compile cache …`; `PortingProgress.isUpdatingShaderCache` lo mostra come **Updating shader cache**. Il nuovo `.github/requirements/tools.txt` dell'engine elenca numpy, pillow e texture2ddecoder, usati solo da strumenti di sviluppo: `EngineRuntimeRequirementsTests.notBundled` ne registra il motivo.
-
-Il pin `4a0551e4` aggiorna shader, runtime e profili (compresi nuovi giochi Switch 2) e porta le righe `Front-ends:` nei commit dell'engine, lette a ogni re-pin. Tre capacità hanno un riflesso nell'interfaccia: `stage_end` con `warn: true` (archivio pipeline mancante) mostra ⚠ sulla fase e una spiegazione in **Ready to play** (`BuildWarningCopy`); quando lo script espone `survey_nup` / `survey_dump`, `EngineSourceCapabilities` accetta NUP e cartelle estratte senza profilo, che l'engine porta con un profilo provvisorio, e Review mostra **Not tested with this engine yet** per qualunque sorgente senza profilo; la guida dei controlli elenca l'uscita con Home (2 s, poi A). Dopo 0.1.3 anche un NUP senza base (777a5f6c) è accettato: Review offre solo le versioni di update (la più recente selezionata, una sempre scelta) e la build passa quella versione con `--package`, mai `v0`. Le nuove righe di `settings.tsv` (120 fps, upscaler del gioco, forma dell'immagine) arrivano da sole tramite Game options. `--seen-shaders`, `--program` e le opzioni per i profili provvisori non vengono adottate. Un salvataggio con nomi creati prima di 7c23cc0 viene rinominato al primo mount: una build più vecchia dello stesso gioco potrebbe non leggerlo più.
-
-Il pin precedente `b64a5ff0` aggiorna audio, allineamento memoria, rendering, shader e profili; aggiunge il controllo chiavi anticipato e la pulizia cache. NUP resta un formato sorgente non esposto dal frontend, i diagnostici non diventano nuovi toggle e i controlli FPS rimangono quelli già supportati. Le precedenti correzioni AV1 restano incluse. Il motore compila dav1d dalle proprie sorgenti incluse; il runtime del frontend non cambia. Gli hook per incorporare la vista del gioco in un frontend non vengono adottati: NX Library avvia app di gioco separate.
+| Controllers | Navigazione della libreria. |
+
+- Options e Play leggono `GameRuntimeConfig.load`: prima le preferenze per titolo in UserDefaults, poi `env.txt` del titolo, poi quello nel bundle, infine i valori del modello.
+- Il rebuild ricava `languageForBuild` dalla configurazione del titolo e non tiene una lingua separata dal wizard. I default globali cambiati non aggiornano da soli i giochi già aggiunti. Search e Changed attribuiscono la vibrazione a Porting · New games.
+
+**Catalogo e salvataggio.**
+- `SettingsCatalog` descrive i singoli controlli. Changed riceve anche le differenze delle preferenze esterne ad `AppSettings`. Le azioni del controller si aggiornano con lo stato dei pannelli e mantengono il focus per identità. About pubblica azioni selezionabili.
+- Reset group è possibile dove `SettingsReset.canReset` lo dice. `SettingsReset.reset` rimette ai default i valori `AppSettings` della sezione in una sola assegnazione; la schermata azzera accanto le preferenze esterne (tema applicato, icona dell'app, zona morta della levetta, cartella Game apps) e segnala la cartella delle sorgenti conservata. Cloud saves e le credenziali non hanno reset.
+- `AppSettingsStore` salva `settings.json` tramite un file temporaneo, pubblica gli errori e conserva una copia di un file illeggibile prima di permetterne la sostituzione. La UI usa un dialogo Selene con Retry per una scrittura fallita.
+ In Spotlight e Collection l'ultimo gioco selezionato è stato di navigazione nello stesso store, senza notificare gli osservatori delle impostazioni a ogni movimento. Lo store include lo stesso campo nel JSON, accoda la scrittura in background e sostituisce le scritture ancora in attesa con la selezione più recente. Un salvataggio esplicito e la chiusura conservano la selezione corrente.
+- `GameRuntimeConfig.save` propaga gli errori di `env.txt` e salva le preferenze per titolo solo dopo una scrittura riuscita. Un `env.txt` illeggibile si conserva e si segnala.
+
+## Lingua e regione
+
+**Scelta della lingua.**
+- `AppLanguage` definisce auto/en/it/fr/de/es/pt-BR. `AppLocale` risolve le preferenze ordinate del Mac e una regione indipendente, valida i codici e mappa pt-BR a pt soltanto per Nlib.
+- `AppSettings` conserva i due override in modo additivo: vecchi file e scelte non riconosciute tornano ad Automatic.
+- `DevelopmentStartupView` carica un solo `AppSettingsStore`, configura il locale e passa lo store a `MainView` e `AppShellView`. Gli initializer delle viste non pubblicano cambi di locale, perché il controllo sincrono della toolchain può far rientrare il run loop mentre SwiftUI costruisce i propri StateObject.
+
+**Propagazione alle viste.**
+- `AppLocalization` pubblica il contesto. La shell lo propaga alle viste tramite `nxAppLocale`, una dipendenza SwiftUI esplicita che non ricrea identità o stato.
+- Settings passa questo valore alla barra laterale, e `SettingsSection.title(in:)` risolve le categorie nel contesto ricevuto, anche con il focus sulle righe. Righe, informazioni, pannelli e suggerimenti condivisi usano lo stesso valore.
+- `L10n` tiene al massimo un bundle per ciascuna delle sei lingue. Le risorse iniettate restano isolate, senza memorizzare testi interpolati o dati personali. Cattura il contesto per il lavoro asincrono e legge il catalogo compilato, cercando prima nel bundle installato. Non si usa nessun servizio esterno di posizione o traduzione.
+
+**Testi.**
+- I testi controllati dall'app sono nel catalogo condiviso `NXLibraryCore/Resources/Localizable.xcstrings`, con interpolazioni e plurali.
+- Restano indipendenti dalla lingua: dati personali, rawValue salvati, regex, eventi dell'engine, variabili `DM_*` e identità dei controlli.
+- I componenti Settings risolvono le etichette alla presentazione e mantengono i rowID originali; le righe con i nomi dei giochi usano i titoli così come sono. Search confronta anche i testi tradotti.
+- I testi upstream noti di `launcher.json` si localizzano solo nella presentazione; valori e note sconosciute tengono il testo upstream.
+- Il nome dell'app, "Arcane", sta in `AppIdentity.name` e non si traduce: le viste che mostrano solo il nome lo leggono da lì, e il catalogo non contiene più il vecchio nome. Bundle ID, cartelle dei dati, chiavi delle preferenze e segni `.nxlibrary-*` tengono il nome storico, perché cambiarli separerebbe i dati di chi aggiorna.
+- Ogni richiesta di rete si presenta con `AppIdentity.userAgent()`, cioè `Arcane/ (macOS; +https://github.com/Bium23/NxLibrary)`.
+
+**Start-up.**
+- Start-up ospita lingua e regione. `LocalePicker` offre la scelta diretta delle lingue e cerca i nomi localizzati delle regioni per codice stabile, con input da tastiera e controller distinto da Settings.
+- Le righe distinguono la lingua di menu, generi e descrizioni dai soli formati regionali. Il cambio non ricrea router o sessioni e non cambia la lingua di nessun gioco. Date e dimensioni seguono il locale scelto; nomi dei giorni e durate sono localizzati.
+
+**Generi e descrizioni.**
+- `GameGenre` traduce alla presentazione i generi noti senza modificare metadati e scelte salvate; i generi sconosciuti restano come sono.
+- `NintendoStoreMetadataService` legge le vecchie cache come inglesi e salva i percorsi per lingua e regione, riusando i dati tra regioni della stessa lingua.
+ - Un cambio di sola regione non aggiorna i metadati. Un cambio di lingua conserva la scheda visibile, legge la cache fuori dal thread principale e, con dati freschi già presenti, chiede solo la descrizione tradotta.
+ - Gli ID 0400 dei giochi Switch 2 sono ammessi al lookup Nlib come gli 0100.
+ - `descriptionCheckedAt` distingue un ripiego già controllato da una vecchia cache mai cercata nella lingua richiesta. Una traduzione vuota si ricontrolla dopo 24 ore; dopo un errore temporaneo si riprova dopo un minuto.
+ - Chiede una descrizione Nlib localizzata anche quando il catalogo US ne ha già una inglese, e non invia parametri di regione non documentati.
+ - Se qualcosa fallisce, si tiene prima una descrizione tradotta già in cache, senza rinnovarne la freschezza; altrimenti si tiene il ripiego inglese.
+ - Il modello conserva la lingua della descrizione, e Details e Spotlight la indicano quando è diversa da quella dell'app. Le scelte personali hanno la precedenza.
+ - `metadataLocaleGeneration` impedisce a una risposta vecchia di ripopolare la UI dopo un cambio di lingua. Screenshot e artwork restano condivisi.
+
+**Controlli.** SwiftPM compila le risorse e `build_app.sh` le include prima della firma. `check_localizations.py` verifica copertura delle sei lingue, segnaposto, plurali e risorse compilate; `release.sh` ripete il controllo sullo ZIP estratto. Le traduzioni sono bozze dell'agente, non revisioni di madrelingua.
+
+## Setup, engine e compatibilità
+
+**Ambiente.**
+- `SystemDetector` e `EngineLocation` trovano checkout e cartelle dell'utente.
+- `NXNativeEnvironment` raccoglie lo stato di Python, strumenti, Xcode e Metal. I tool dell'engine sono eseguibili nativi: .NET non serve.
+- `EngineToolchain` risolve Python e `PATH`, preferendo il runtime incluso nel bundle quando c'è.
+
+**Setup.**
+- `SetupProbe` raccoglie i dati del Setup. `SetupCheck` li traduce in schede, stati e azioni. `SetupCheckModel` esegue i controlli in background, compresa la lettura di `xcode-select` a ogni ricontrollo (4 s), e coordina installazioni e avanzamento. `SetupActions` prepara gli argomenti Git per portare un checkout gestibile al pin.
+- Get ready mostra soltanto i cinque requisiti tecnici, in una griglia 3 + 2. I problemi alle cartelle non riaprono questa schermata.
+- Your games presenta Game apps, la cartella unica in cui cercare giochi nxnative esistenti e installare le prime build.
+ - Il default `~/Applications` si prepara al primo uso solo se non è già stato scelto o ricordato un percorso. Le destinazioni personalizzate o confermate restano ricordate anche quando non sono disponibili.
+ - La lettura basta per scoperta e Play; le nuove installazioni richiedono la scrittura.
+ - Game files è una preferenza facoltativa in Settings → Library, separata dalla selezione temporanea del wizard.
+ - Cambiare Game apps non sposta le app registrate; cambiare Game files non sostituisce i sorgenti di un titolo senza conferma esplicita. `GameFoldersCopy` mantiene coerenti i nomi.
+- Con un engine che riconosce le cartelle estratte, Setup permette di proseguire senza chiavi. Le sorgenti cifrate continuano a richiederle e a passare dal controllo preliminare.
+
+**Gate di compatibilità.**
+- `CompatibilityChecker` verifica commit, modifiche del checkout, contratto CLI e compilatore Metal richiesto dal lock del motore. `ToolchainRequirements.current` contiene Xcode minimo e asset Metal. `ToolchainGateCopy` spiega il risultato nella UI.
+- Una build con l'override del gate riceve `toolchainVerified=false` e `--allow-other-metal`.
+- Play valuta la disponibilità dell'app già installata separatamente dal gate per un nuovo porting.
+
+**Newest engine.** L'engine più nuovo è una scelta esplicita del giocatore (Settings → Setup and engine → **Newest engine**).
+- Dopo il controllo Upstream, che misura sempre i commit rispetto al pin, `NewestEngine.fetchLock` legge il lock di main da GitHub. Se certifica un Metal diverso da quello del lock del pin, la riga dice che serve una versione più nuova di Arcane e non offre il cambio.
+- `NewestEngineSwitcher` rifiuta un checkout con file modificati, scarica, rilegge il lock con git e solo allora fa `checkout --detach`.
+- La scelta (`NewestEngineChoice`) è salvata e diventa il commit atteso dal gate e quello registrato nelle build. Accende l'override, che resta bloccato finché la scelta è attiva, e marca le build come non testate. Il gate mostra **Newest engine** in arancione, mai Certified.
+- Il Setup continua a installare il pin, ma per il commit scelto mostra la scheda pronta in arancione con **Back to tested** e non la riporta indietro da solo.
+- La scelta decade quando il checkout non è più su quel commit, o quando un aggiornamento di Arcane porta un pin che lo contiene. Se l'override l'aveva acceso la scelta, torna spento. Settings e Setup usano la stessa frase (`NewestEngineCopy.note`).
+
+**Capacità dell'engine adottate** (la decisione per ogni pin è nella sua nota in `upstream-upgrades/`):
+- **Cartelle estratte e pacchetti con più contenuti:** `EnginePackageReader` riusa il lettore content-meta upstream; `ExtractedSourceCatalog` legge NPDM e profili registrati senza chiavi.
+- **NUP e cartelle senza profilo:** quando lo script espone `survey_nup` / `survey_dump`, `EngineSourceCapabilities` li accetta e l'engine li porta con un profilo provvisorio. Review mostra **Not tested with this engine yet** per qualunque sorgente senza profilo.
+- **File `.zs` danneggiati:** il classificatore dell'engine controlla i file `.zs` danneggiati in NUP e cartelle (riga `files.format`).
+- **Programmi NUP:** `NUPSourceCatalog` conserva programma, applicazione e base DLC distinti in
+ `NUPProgramSelection`, facoltativo sui record storici. Le conversioni UI e i sorgenti salvati mantengono
+ la selezione. Un engine con il contratto multiprogramma riceve `--program` esplicito, anche zero per
+ i vecchi record, così un rebuild non segue un nuovo default. Metadati discordanti o un checkout
+ incapace di selezionare il programma fermano il build; non viene mascherato l'ID.
+- **NUP senza base:** Review offre solo le versioni di update (la più recente selezionata, una sempre scelta), e la build passa quella versione con `--package`, mai `v0`.
+- **Archivio pipeline mancante:** `stage_end` con `warn: true` mostra ⚠ sulla fase e una spiegazione in **Ready to play** (`BuildWarningCopy`).
+- **Preparazione del primo avvio:** quando l'engine riporta `Prewarm pipelines`, `PortingETA` mostra un'attività localizzata invece di riusare la durata finale di un vecchio build. Il tempo trascorso resta nella lista delle fasi; senza un conteggio non si inventa una percentuale. Un warning di questa fase spiega che il gioco prepara le pipeline mancanti al primo avvio.
+- **Cache shader in un file:** cache di compilazione e librerie shader sono un file ciascuna (`shader/cache/cas.db`, `msl/b-.img`); Arcane non legge dentro nessuno dei due. Quando l'engine sposta una vecchia cache, con l'evento `say` `moving the compile cache …` (`PortingProgress.shaderCacheWorkMessage`), `PortingProgress.isUpdatingShaderCache` si accende e `PortingETA` mostra **Updating shader cache** senza avanzare la percentuale né stimare una durata. Lo stato si azzera alla fase o al passo successivo e a fine build; `PortingFailureEngineTests` verifica che l'engine del pin stampi ancora quel testo.
+- **Errori delle chiavi:** si riconoscono le chiavi troppo vecchie (con la versione firmware quando è nota) e il ticket comune mancante nel pacchetto. Quest'ultimo usa il kind salvato `keys` con un dettaglio identificativo, così anche un launcher precedente legge la voce durante un rollback. La UI spiega il ticket senza proporre di sostituire le chiavi o forzare il porting.
+- **Interfaccia dei giochi:** la guida dei controlli elenca l'uscita con Home (2 s, poi A) e Shift + frecce per la levetta destra. Le righe nuove di `settings.tsv` (120 fps, upscaler del gioco, forma dell'immagine) arrivano da sole tramite Game options.
+- **Salvataggi:** un salvataggio con nomi creati prima di 7c23cc0 si rinomina al primo mount, quindi una build più vecchia dello stesso gioco potrebbe non leggerlo più.
+- **Strumenti di sviluppo:** `.github/requirements/tools.txt` dell'engine elenca numpy, pillow e texture2ddecoder, usati solo da strumenti di sviluppo; `EngineRuntimeRequirementsTests.notBundled` ne registra il motivo. dav1d si compila dalle sorgenti incluse dell'engine, e il runtime del frontend non cambia.
+- **Non adottati:** `--seen-shaders`, un selettore manuale dei programmi, le opzioni per i profili provvisori, i diagnostici come nuovi interruttori e gli hook per incorporare la vista del gioco in un frontend (Arcane avvia app di gioco separate).
## Sorgenti e porting
-L'integrazione di [nxnative 163a9905](upstream-upgrades/2026-11-02-2716f78-163a9905-review.md) aggiunge un ingresso per cartelle estratte e metadati per pacchetti con più contenuti. `EnginePackageReader` riusa il lettore content-meta upstream; `ExtractedSourceCatalog` legge NPDM e profili registrati senza chiavi. `SourceSelection` tiene separati contenuti selezionati e file fisici: un pacchetto si conta e si collega una sola volta, il DLC incorporato rimane incluso e la versione scelta viene passata con `-p`.
-
-`GameFileItem` conserva facoltativamente layout e requisito di selezione del titolo; i vecchi JSON continuano a indicare pacchetti. Questi requisiti sono verificati prima del build anche cambiando checkout. Le cartelle estratte sono collegate nel layout `base/`, `updates//`, `dlc//0/romfs/`; il restaging rimuove link esclusi e contenitori vuoti, preservando cache e originali. Un pacchetto illeggibile non nasconde gli altri giochi validi: la scansione mantiene i risultati e segnala i file saltati.
-
-Con un engine che riconosce cartelle estratte, Setup permette di proseguire senza chiavi. La selezione di pacchetti cifrati continua a richiederle e a eseguire il preflight. La guida In game include Shift + frecce per la levetta destra delle nuove build. L'integrazione è inclusa nella versione principale al pin riportato sopra.
-
-1. `AddGameView` raccoglie cartelle o file. `SourceCatalog` riconosce NSP, XCI, NSZ e XCZ e raggruppa base, aggiornamenti e DLC. Le selezioni di file vengono scandite e collegate singolarmente, senza includere altri pacchetti della cartella né modificare la preferenza globale Game files. Il reset della bozza avviene solo dopo la conferma del selettore. Più titoli richiedono una scelta esplicita; le riletture dello stesso titolo mantengono nome, impostazioni e selezioni logiche di update/DLC anche se cambiano gli UUID delle righe.
-2. `AppViewModel+KeyCheck` invoca `KeyCheck` sulle sorgenti selezionate. Il risultato dipende dalla selezione corrente, così un controllo precedente non abilita un porting diverso.
-3. `WorkspaceManager` usa la cartella sorgente in loco oppure prepara un workspace di collegamenti simbolici. Gestisce anche il riuso di una cache esistente. `BuildScratch` sceglie dove: workspace e app temporanea stanno sul volume dell'app. Se la cartella delle app è su un altro volume locale APFS o Mac OS esteso vanno in `.nxlibrary-build/` accanto alle app (exFAT e FAT accettano i link ma tengono gli attributi in file `._` che rompono la firma dell'app; `statfs` dà il tipo), così il disco del Mac non serve e l'installazione è una rinomina; altrimenti (stesso volume, exFAT, rete) restano in Application Support. Una cartella `workspaces` che il giocatore ha spostato su quel volume resta dov'è, e un workspace gestito già su quel volume conserva la sua cache. Un workspace gestito rimasto su un altro volume viene cancellato quando ne nasce uno nuovo, tranne se il gioco non è ancora costruito e punta ancora lì. Il controllo dello spazio misura ogni volume usato una volta sola; la pulizia all'avvio guarda anche le `.nxlibrary-build/Temp`, e cancellare un gioco o le sue sorgenti tocca solo workspace riconosciuti da `BuildScratch.isManaged`.
-4. Il coordinatore ricontrolla requisiti, spazio, chiavi e destinazione. `BuildCommandBuilder` produce eseguibile, argomenti, directory di lavoro e ambiente.
-5. `BuildService` avvia il processo del motore, gestisce il gruppo di processi, raccoglie stdout e stderr, scrive il log e mantiene l’asserzione contro lo stop per inattività.
-6. `BuildEventParser` decodifica il progresso JSON. `PortingProgress` lo aggrega per la UI, con gli shader fino al 90% e le fasi finali nel restante 10%. Il modello alimenta wizard, tile, percentuale e stima del tempo.
-7. `BuildOutputInstaller` valida il bundle temporaneo e pubblica il gioco con `renamex_np`: `RENAME_SWAP` scambia atomicamente due app esistenti; `RENAME_EXCL` installa la prima copia senza sovrascrivere una destinazione comparsa nel frattempo. Sullo stesso volume usa direttamente il bundle pronto. Fra volumi diversi prepara prima una copia nascosta accanto alla destinazione, lasciando disponibile l’app corrente fino allo scambio.
-8. Se il gioco è aperto o l’installazione è trattenuta da un’operazione sui salvataggi, `PendingInstall` conserva il risultato temporaneo. `AppViewModel+PendingInstall` lo riprende quando può acquisire l’accesso necessario.
-
-`GameAppDestination` centralizza il percorso mostrato nella review, il volume controllato per lo spazio e la destinazione effettiva. Le prime build usano Game apps; un rebuild conserva l'app esistente quando il suo percorso è sicuro, anche dopo un cambio di cartella. I conflitti di nome con app di altri titoli ricevono un percorso distinto. La destinazione viene fissata prima del porting e rimane tale anche nelle installazioni differite. Le installazioni dei giochi richiedono che la cartella esista ancora: se si disconnette o diventa non scrivibile, il risultato pronto viene conservato per Retry. Il packaging del frontend continua a poter creare la propria cartella di installazione.
-
-Se il motore termina correttamente con un bundle valido e fallisce solo l’installazione, `BuildResult.heldApp` conserva la build pronta e `installationFailed` distingue questo caso dal porting fallito. Il coordinatore registra la stessa `PendingInstall` già usata per i giochi aperti. Un dialogo Selene offre Retry e Close: Retry installa quel bundle senza riavviare il motore; Close conserva la build. Gli errori delle installazioni differite passano dallo stesso dialogo. La schermata del porting offre anche Retry installation finché la build resta in attesa. Un errore di scrittura del catalogo conserva lo stato in memoria e impedisce che una scansione immediata lo sostituisca con quello precedente.
-
-Prima della pubblicazione, l’installer registra una piccola ricevuta accanto all’app con percorso di staging e identità filesystem dei bundle. Una ricevuta per destinazione resta dopo il successo e viene aggiornata al prossimo porting: se il processo termina prima del salvataggio del catalogo, il tentativo successivo riconosce l’app già pubblicata e completa il record, anche dopo la pulizia dello staging. Evita così un secondo scambio che rimetterebbe la vecchia app al suo posto. Una destinazione modificata esternamente durante lo stesso tentativo causa un errore conservativo. La vecchia app e l’eventuale sorgente copiata vengono eliminate solo dopo la pubblicazione.
-
-La 0.1.4.2 (in attesa di validazione manuale) mostra il tempo trascorso della fase attiva e formatta durate ed ETA in ore oltre i 60 minuti. Un timer a 1 Hz sul main run loop aggiorna la fase; il controllo di `logs/pso_offline_mac.log` gira fuori dal main thread. `PipelineArchiveProgress` legge soltanto log modificati dopo l'inizio della fase e conta i gruppi dichiarati `ready`, distinguendo `compiled` e `reused`: i file temporanei del compilatore e le chiavi delle vecchie cache non sono una prova di lavoro completato. Le dimensioni dei gruppi vengono dal log, senza assumere quelle predefinite. La stima riguarda le pipeline, non il confezionamento successivo dell'app. Formati ignoti non inventano un avanzamento; cambi di fase, annullamento e fine build invalidano i controlli ancora in corso. `PortingFailureClassifier` riconosce anche lo spazio richiesto da `pack_app.py`; il fallback sulle chiavi si applica solo alle sorgenti che le richiedono.
-
-`BuildRecord` conserva l’esito e la provenienza del build. `PortingFailureClassifier` riconosce i messaggi del motore e propone un’azione, presentata da `AppViewModel+Porting`. `PortingNotice` decide se notificare l’esito mentre l’app è in background. `NotificationService` gestisce la notifica di sistema e la destinazione del clic.
-
-Gli adattamenti di b64a5ff0 riconoscono i nuovi errori di chiavi troppo vecchie, conservando la versione firmware quando conosciuta, e il ticket comune mancante nel pacchetto. Quest'ultimo usa il kind persistito `keys` con un dettaglio identificativo: anche un launcher precedente riesce a leggere la voce durante un rollback. La UI corrente offre la spiegazione sul ticket senza proporre di sostituire le chiavi o forzare il porting. L'evento `say` con cui l'engine sposta una vecchia cache shader nel nuovo file (`PortingProgress.shaderCacheWorkMessage`) accende `PortingProgress.isUpdatingShaderCache`; `PortingETA` mostra **Updating shader cache** senza avanzare la percentuale né stimare una durata. Lo stato si azzera a stage o step successivo e al termine del build. `PortingFailureEngineTests` verifica che l'engine del pin stampi ancora quel testo.
+Il percorso completo è in [flows.md](flows.md#5-costruire-un-gioco-switch-add-game).
+
+**Le sorgenti.**
+- La preferenza **Game files** conserva solo il percorso iniziale del selettore. `AppViewModel` non la assegna a `selectedGameFolder` all'avvio: quell'assegnazione avvia una scansione. Il refresh della libreria riguarda le app installate; scegliere cartella o file in Add game avvia la lettura dei sorgenti. *Perché:* aprire la libreria non richiede di enumerare una cartella protetta come Download. I rebuild usano le sorgenti registrate sul gioco.
+- `SourceSelection` tiene separati contenuti selezionati e file fisici: un pacchetto si conta e si collega una sola volta, il DLC incorporato resta incluso e la versione scelta passa con `-p`.
+- `GameFileItem` conserva, se serve, layout e requisito di selezione del titolo; i vecchi JSON continuano a indicare pacchetti. Questi requisiti e la selezione NUP si verificano prima del build, anche dopo un cambio di checkout. Il programma salvato deve corrispondere al title ID del gioco; il DLC usa la base add-on dichiarata dall’applicazione.
+- Le cartelle estratte si collegano nel layout `base/`, `updates//`, `dlc//0/romfs/`. Il restaging rimuove i link esclusi e i contenitori vuoti, preservando cache e originali.
+- Un pacchetto illeggibile non nasconde gli altri giochi validi: la scansione tiene i risultati e segnala i file saltati.
+
+**Il percorso, passo per passo.**
+1. **Scelta dei file.** `AddGameView` raccoglie cartelle o file. `SourceCatalog` riconosce NSP, XCI, NSZ e XCZ e raggruppa base, aggiornamenti e DLC.
+ - I file scelti si scandiscono e collegano uno per uno, senza includere altri pacchetti della cartella né cambiare la preferenza globale Game files.
+ - La bozza si azzera solo dopo la conferma del selettore. Più titoli richiedono una scelta esplicita.
+ - Le riletture dello stesso titolo mantengono nome, impostazioni e selezioni di update/DLC anche se cambiano gli UUID delle righe.
+2. **Chiavi.** `AppViewModel+KeyCheck` chiama `KeyCheck` sulle sorgenti selezionate. Il risultato vale per la selezione corrente, quindi un controllo precedente non abilita un porting diverso.
+3. **Workspace.** `WorkspaceManager` usa la cartella sorgente così com'è oppure prepara un workspace di collegamenti simbolici, riusando una cache esistente. `BuildScratch` sceglie dove mettere workspace e app temporanea: sul volume dell'app.
+ - Se la cartella delle app è su un altro volume locale APFS o Mac OS esteso, vanno in `.nxlibrary-build/` accanto alle app, così il disco del Mac non serve e l'installazione è una rinomina. exFAT e FAT accettano i link ma tengono gli attributi in file `._` che rompono la firma; il tipo lo dà `statfs`.
+ - Negli altri casi (stesso volume, exFAT, rete) restano in Application Support.
+ - Una cartella `workspaces` spostata dal giocatore su quel volume resta dov'è, e un workspace gestito già su quel volume conserva la sua cache.
+ - Un workspace gestito rimasto su un altro volume si cancella quando ne nasce uno nuovo, tranne se il gioco non è ancora costruito e punta ancora lì.
+ - Il controllo dello spazio misura ogni volume usato una sola volta. La pulizia all'avvio guarda anche le `.nxlibrary-build/Temp`, e cancellare un gioco o le sue sorgenti tocca solo i workspace riconosciuti da `BuildScratch.isManaged`.
+4. **Ultimo controllo.** Il coordinatore ricontrolla requisiti, spazio, chiavi e destinazione. `BuildCommandBuilder` produce eseguibile, argomenti, cartella di lavoro e ambiente.
+5. **Processo.** `BuildService` avvia il processo del motore e gestisce il suo gruppo di processi. Raccoglie stdout e stderr, scrive il log e tiene attiva l'asserzione contro lo stop per inattività. Se il processo non parte, chiude subito log e pipe.
+6. **Avanzamento.** `BuildEventParser` decodifica il progresso JSON e `PortingProgress` lo aggrega per la UI: gli shader arrivano fino al 90%, le fasi finali occupano il restante 10%. Il modello alimenta wizard, tile, percentuale e stima del tempo.
+7. **Installazione.** `BuildOutputInstaller` valida il bundle temporaneo e pubblica il gioco con `renamex_np`: `RENAME_SWAP` scambia atomicamente due app esistenti, `RENAME_EXCL` installa la prima copia senza sovrascrivere una destinazione comparsa nel frattempo. Sullo stesso volume usa direttamente il bundle pronto; fra volumi diversi prepara prima una copia nascosta accanto alla destinazione, e l'app corrente resta disponibile fino allo scambio.
+8. **Installazione in attesa.** Se il gioco è aperto, o un'operazione sui salvataggi trattiene l'installazione, `PendingInstall` conserva il risultato temporaneo. `AppViewModel+PendingInstall` lo riprende quando può ottenere l'accesso.
+
+**Destinazione.**
+- `GameAppDestination` centralizza il percorso mostrato nella review, il volume controllato per lo spazio e la destinazione effettiva.
+- Le prime build usano Game apps; un rebuild conserva l'app esistente se il suo percorso è sicuro, anche dopo un cambio di cartella. Un nome già usato da un altro titolo riceve un percorso distinto.
+- La destinazione si fissa prima del porting e resta tale anche nelle installazioni differite. Le installazioni richiedono che la cartella esista ancora: se si scollega o non è più scrivibile, il risultato pronto si conserva per Retry. Il packaging del frontend può creare la propria cartella di installazione.
+
+**Installazione fallita.**
+- Se il motore termina bene con un bundle valido e fallisce solo l'installazione, `BuildResult.heldApp` conserva la build pronta, e `installationFailed` distingue questo caso dal porting fallito. Il coordinatore registra la stessa `PendingInstall` usata per i giochi aperti.
+- Un dialogo Selene offre Retry e Close: Retry installa quel bundle senza riavviare il motore, Close conserva la build. Anche gli errori delle installazioni differite passano da questo dialogo, e la schermata del porting offre Retry installation finché la build resta in attesa.
+- Un errore di scrittura del catalogo conserva lo stato in memoria e impedisce che una scansione immediata lo sostituisca con quello precedente.
+
+**Ricevuta di installazione.**
+- Prima della pubblicazione l'installer scrive accanto all'app una piccola ricevuta, con il percorso di staging e l'identità filesystem dei bundle. Ne resta una per destinazione, aggiornata al porting successivo.
+- Se il processo termina prima del salvataggio del catalogo, il tentativo successivo riconosce l'app già pubblicata e completa il record, anche dopo la pulizia dello staging. *Perché:* evita un secondo scambio che rimetterebbe la vecchia app al suo posto.
+- Una destinazione modificata da fuori durante lo stesso tentativo causa un errore prudente. La vecchia app e l'eventuale sorgente copiata si eliminano solo dopo la pubblicazione.
+
+**Tempo e stime.**
+- La fase attiva mostra il tempo trascorso; durate ed ETA passano alle ore oltre i 60 minuti. Un timer a 1 Hz sul main run loop aggiorna la fase, mentre il controllo di `logs/pso_offline_mac.log` gira fuori dal main thread.
+- `PipelineArchiveProgress` legge soltanto log modificati dopo l'inizio della fase e conta i gruppi dichiarati `ready`, distinguendo `compiled` e `reused`. I file temporanei del compilatore e le chiavi delle vecchie cache non contano come lavoro finito. Le dimensioni dei gruppi vengono dal log, senza assumere quelle predefinite.
+- La stima riguarda le pipeline, non il confezionamento dell'app che segue. Un formato sconosciuto non inventa un avanzamento. Cambi di fase, annullamento e fine build invalidano i controlli ancora in corso.
+- Durante `Prewarm pipelines` la riga mostra **Preparing the first launch**: la durata precedente può non includere questo lavoro, quindi non viene usata come ETA. Fine build e annullamento rimuovono l'attività insieme allo stato di porting.
+
+**Esito.**
+- `BuildRecord` conserva esito e provenienza del build.
+- `PortingFailureClassifier` riconosce i messaggi del motore, compreso lo spazio richiesto da `pack_app.py`, e propone un'azione, presentata da `AppViewModel+Porting`. Il ripiego sulle chiavi vale solo per le sorgenti che le richiedono.
+- `PortingNotice` decide se notificare l'esito mentre l'app è in background. `NotificationService` gestisce la notifica di sistema e la destinazione del clic. Il permesso si richiede quando un porting supera i controlli preliminari e parte, mai durante l’avvio o per la sola libreria Steam. Il delegate resta registrato all’avvio per aprire il gioco o l’errore da una notifica precedente.
## Avvio dei giochi e sessioni
-Il flusso Play controlla operazioni di salvataggio, recuperi e installazioni in attesa. `GameRuntimeConfig` traduce le impostazioni in variabili `DM_*`. `LauncherSettingsReader` legge il contratto `launcher.json` del gioco e determina i controlli supportati, con fallback per le app più vecchie.
-
-`LaunchService` scrive `env.txt`, conserva le variabili non gestite tramite il merge del modello runtime e avvia il bundle con `NSWorkspace.OpenConfiguration`. Passa anche `DM_LAUNCHER=0`. `CloudSavesPreferences` applica la preferenza cloud al dominio del gioco prima del lancio.
-
-Off rimuove la preferenza cloud salvata dal launcher del gioco anche all’avvio. Gli override avanzati `DM_SAVE_SYNC` nei file o nell’ambiente mantengono la precedenza del motore: `SaveLocation.inspect` ne segnala l’origine e mantiene il blocco delle operazioni incompatibili con la sincronizzazione attiva.
-
-Nella 0.1.4.2 (in attesa di validazione manuale), Play durante la firma dell'icona apre il dialogo Selene **Preparing** con **Cancel**. `IconLaunchWait` lega la richiesta all'identità del gioco e del dialogo; la chiusura o sostituzione del dialogo revoca la richiesta. Solo l'ultimo aggiornamento icona riuscito può riprendere Play, che rilegge il gioco corrente e ripete tutti i controlli dei salvataggi e dell'app. Un errore non avvia il gioco. Cancel lascia terminare la firma, necessaria a mantenere il bundle valido. L'attesa usa `launchingGameId` e blocca anche l'aggiornamento del frontend.
-
-`RunningGameMonitor` confronta i bundle ID della libreria con le applicazioni in esecuzione e offre Resume e Close Game. `LaunchReadinessProbe` attende una finestra visibile del processo per chiudere la schermata di lancio. `PlaySessionStore` registra avvio, heartbeat, fine e riconciliazione delle sessioni. `ActivitySummary` aggrega la settimana, mentre `LibraryPresentation` e `GameDetailPresentation` preparano i valori delle schermate.
-
-## Cheats
-
-`CheatLocator` legge title ID, build ID e percorso secondo il contratto del launcher. `EngineAncestry` e `CheatStatus` determinano se l’app del gioco contiene il supporto ai cheats, dal commit del registro di build o, per un'app importata, da `DMCommit` nel suo `Info.plist`. `CheatFile` riproduce il parsing dei codici e dei metadati del motore. `CheatInstall` decide se un file appartiene alla build, richiede conferma o va rifiutato.
-
-`CheatStore` legge e modifica file, metadati, master switch e selezione `.enabled`. `AppViewModel+Cheats` espone contesto, stato della riga e informazioni per la diagnostica. `CheatsPanel` presenta lista, importazione, conferme e switch. Il gioco chiuso è una condizione delle modifiche. I file installati vengono poi letti dal motore al lancio.
-
-Le mod di file (RomFS) di un gioco stanno in `~/Library/Application Support/nxnative//mods//romfs`. `ModFolderScanner` trova le cartelle e il loro `romfs` (anche nel formato Atmosphère); un file lasciato lì (un archivio non estratto) compare come "non è una mod", e i file nascosti come `.DS_Store` non contano per i conflitti. `ModStore` tiene ordine e stato acceso/spento in `~/Library/Application Support/NXLibrary/mods/.json` e scrive nell'`env.txt` del gioco solo la riga `DM_ROMFS_OVERLAY` (con `EnvFileEditor`), che il motore legge al lancio: le mod accese, la prima vince, senza rebuild. Il valore non supera 4077 byte (il buffer di riga del launcher). Remove sposta la cartella nel Cestino; nessuna modifica mentre il gioco è aperto. All'apertura della pagina del gioco e del pannello, `sync()` toglie dalla riga le mod sparite; finché NX Library non ha mai gestito le mod di quel gioco non tocca una riga `DM_ROMFS_OVERLAY` scritta a mano. `AppViewModel+Mods` crea lo store e traduce gli errori; `ModsPanel` (Game options → Mods) e la fascia Mods della pagina del gioco (`DetailsModsBand`) presentano lo stato. Le mod che modificano il codice (exefs) non funzionano con il motore.
-
-Le mod di GameBanana compaiono nella stessa fascia (`Services/GameBanana/`). `GameBananaClient` parla con l'API pubblica (apiv11 e, per il contenuto degli archivi, la vecchia Core API), con un solo User-Agent, al massimo 4 richieste insieme e una cache su disco in `~/Library/Caches/NXLibrary/gamebanana` (ricerche 1 giorno, pagine delle mod 6 ore, contenuto degli archivi per sempre, tranne un elenco vuoto, perché GameBanana può ancora leggere un file nuovo; senza rete usa anche le voci scadute). `GameBananaMatch` abbina il gioco per nome (preferisce la voce "(Switch)", chiede quando non è sicuro) e `GameBananaMatchStore` ricorda la scelta per title ID in `Application Support/NXLibrary/gamebanana/matches.json`. `AvailableModsFinder` scorre le mod più scaricate e tiene solo quelle che `ModSupport` riconosce: un'unica cartella `romfs` per questo title ID, niente exefs, IPS o pchtxt, niente mod obsolete, private o con content rating. `ModInstaller` scarica (`ModDownload`, solo host `*.gamebanana.com`), controlla dimensione e MD5, legge e controlla l'archivio con `/usr/bin/bsdtar`, lo estrae in una cartella nascosta dentro `mods`, rifiuta percorsi `..`, symlink e hard link prima di estrarre, e passa l'albero a `ModStore.adopt`; un aggiornamento manda la versione vecchia nel Cestino e tiene posto e stato. La fascia Mods compare sia nella pagina del gioco della Spotlight sia in Details, tra Build & Sources e More like this (focus `.mods` in `SpotlightState`, `DetailsFocus.modsZone`); è una griglia di sei tessere per riga che non scorre di lato (`ModsBandLayout`: Sinistra/Destra restano nella riga, Giù scende di riga e dall'ultima passa a More like this): `ModsBandHost` tiene per entrambe mod installate, GameBanana e pannelli, e chiede a GameBanana solo quando la pagina è aperta, non mentre si scorre la riga. `GameBananaBandModel` coordina abbinamento, ricerca e installazioni per la pagina del gioco: cambiando gioco dimentica le mod del precedente, e alla prima apertura di un gioco in ogni avvio toglie gli avanzi di un'installazione interrotta (`ModStore.removeLeftoverInstalls`); `GameBananaFindModel` tiene lo stato della ricerca per nome. Le mod trovate entrano nella fascia in due gruppi al massimo: le prime cinque, accanto ad Add mods, appena ci sono, poi tutte le altre a ricerca finita; ogni gruppo aspetta (al massimo 1,2 s, `imageWait`) che la sua arte sia decodificata (`prepareImages`, cioè `GameBananaImageView.prepare`, in parallelo) ed entra con un'unica dissolvenza, e una tessera di stato spinta più in là sfuma nel nuovo posto invece di attraversare la griglia. I link presi dall'API valgono solo se sono `https` su un host GameBanana; `ModDetailPanel` e `GameBananaFindPanel` sono i pannelli sopra la pagina. Nel pannello della mod la descrizione mostra otto righe con Read more subito sotto; Read more la apre tutta (`TextScroll.windowHeight`) e i file, sotto il titolo Files, scendono. La colonna (intestazione, descrizione, file) scorre dentro il pannello quando è più alta (al massimo 980u): con rotella o trackpad, e con Su/Giù, che prima leggono a passi quello che c'è prima della riga seguente e poi spostano il fuoco e mostrano la riga intera (`TextScroll.step`); i bordi sfumano dove c'è altro e una barra sottile dice dove si è. Lo scorrimento sta in `ModsBandHost.detailScroll`, un oggetto a parte, così muoverlo ridisegna solo il pannello e non la pagina sotto. Un'installazione è per un file (`GameBananaBandModel.installFiles`): solo la sua riga ne mostra avanzamento ed esito, le altre aspettano che finisca. Ogni mod mostra autore e link alla sua pagina, e la fascia dice "Mod data provided by GameBanana".
-
-Lo store è la card **Mods** della Spotlight (`SpotlightCard.mods`; la sua visibilità sta in `showsModsCard`, mai in `spotlightCards`, così la versione rilasciata legge ancora le impostazioni). Giù dalla card porta il focus a `.store` e `ModStoreHost` muove `ModStoreFocus` dentro la pagina (`ModStorePage`): barra di ordinamento, Featured (dissolvenza tra le prime cinque), mod popolari dei tuoi giochi, una riga per categoria (`ModCategory`, raggruppate dai nomi delle categorie GameBanana) e una per gioco, dal più giocato di recente. `ModStoreLayout` costruisce le sezioni e dà a ognuna un'altezza fissa, così lo scorrimento non misura nulla e si disegnano solo le sezioni vicine al focus. `ModStoreModel` apre dalle copie su disco (`ModCatalogSnapshots`, `~/Library/Caches/NXLibrary/gamebanana/store`) e aggiorna in background quelle più vecchie di 6 ore, due giochi alla volta, pubblicando un gioco intero per volta; un gioco senza abbinamento si abbina solo se il nome è certo. L'ordinamento è locale sulle mod già trovate. Le immagini decodificate restano in memoria (`GameBananaImageView`, che le prepara in anticipo con `prewarm` per le prime tessere di ogni riga). La copertina della card Mods (`ModStoreLayout.coverArt`) sono le prime quattro mod del Featured per popolarità, qualunque sia l'ordinamento, coi giochi in ordine di title ID: all'avvio la si legge dalle copie su disco dei tuoi giochi ed è la stessa che trova lo store aperto. Cambia solo se lo store trova mod nuove, e solo dopo che tutte e quattro le immagini sono decodificate (`GameBananaImageView.prepare`), in un'unica dissolvenza. Lo sfondo del Featured è sfocato una volta sola, fuori dal main thread, su una copia di 240 px (`GameBananaBlur`): nessuna sfocatura gira a ogni frame. Mentre la pagina scorre, `ModStoreHost.hold(until:)` trattiene le mod trovate in background e ricostruisce le sezioni solo a pagina ferma (il log `store rebuild … ms` misura ogni ricostruzione). Sulla riga, la faccia della card è un mosaico sfocato dell'arte delle mod migliori col puzzle al centro (`ModsCardCover`, dalle copie su disco prima che lo store abbia cercato; senza arte, il gradiente Selene). Con la card selezionata lo sfondo non mostra arte: il moonlight sfuma in 1,2 s verso l'oro (`SeleneBackdrop.modsTint`), anche sopra una wallpaper, che resta ferma sotto. Colore e fondo oro sono uniform dello shader (il fondo lo disegna il passaggio di luce che gira comunque), che `MoonlightLayerView` interpola sul suo thread: la sfumatura non dipende dal main thread e il frame costa uguale; da fermo il display link gira solo per la durata della sfumatura. Lasciando la card verso un gioco, l'oro resta finché l'arte del gioco non è arrivata (`SpotlightView.modsBackdrop`), così il passaggio è uno solo. L'arte dei giochi (`SeleneArtLayer`) è una pila di `CALayer` animati nel render server: ogni nuova immagine entra sopra ciò che si vede, che resta fermo sotto finché non è entrata, così una dissolvenza interrotta riparte da ciò che è a schermo (niente salti, niente moonlight che traspare) e non scatta se il main thread è occupato. Ciò che un layer mostra durante una dissolvenza si calcola sull’orologio (`OpacityFade`, la stessa curva dell’animazione), non dal presentation layer, che per un layer aggiunto nello stesso passaggio non esiste ancora: due immagini in fila non fanno saltare la prima a piena opacità. Scorrendo veloce, i livelli che lasciano passare meno di mezzo gradino a 8 bit (`ArtStack`) escono subito, così la pila resta di pochi livelli invece di un’immagine a tutto schermo per ogni gioco passato. Se tenere l’arte del gioco precedente lo decide `BackdropArtRule` sulla selezione che il body vede, così il primo render di una nuova selezione, prima di `onChange`, non toglie l’arte per poi rimetterla. Sopra una wallpaper il moonlight oro resta montato, nascosto e fermo finché non serve, ed entra ed esce con l'uniform `presence` sul suo thread. Su una card Spotlight tiene l'arte dell'ultimo gioco (`loadHero(keepsWithoutGame:)`) senza mostrarla, così tornare allo stesso gioco non ricarica nulla. Il pannello della mod è lo stesso della fascia; `GameBananaBandModel.attach(store:)` installa nella cartella del gioco della mod.
+I percorsi completi sono in [flows.md](flows.md#3-play-di-un-gioco-switch-nxnative) (Switch) e in [steam.md](steam.md) (Steam).
+
+**Preparazione.**
+- Il flusso Play controlla operazioni sui salvataggi, recuperi e installazioni in attesa.
+- `GameRuntimeConfig` traduce le impostazioni in variabili `DM_*`. `LauncherSettingsReader` legge il contratto `launcher.json` del gioco e decide i controlli supportati, con un ripiego per le app più vecchie.
+- `LaunchService` scrive `env.txt`, conserva le variabili non gestite tramite il merge del modello runtime e avvia il bundle con `NSWorkspace.OpenConfiguration`, passando anche `DM_LAUNCHER=0`.
+- `CloudSavesPreferences` applica la preferenza cloud al dominio del gioco prima del lancio. Off rimuove anche all'avvio la preferenza cloud salvata dal launcher del gioco. Gli override avanzati `DM_SAVE_SYNC`, nei file o nell'ambiente, mantengono la precedenza del motore: `SaveLocation.inspect` ne segnala l'origine e blocca le operazioni incompatibili con la sincronizzazione attiva.
+
+**Firma dell'icona in corso.**
+- Play durante la firma dell'icona apre il dialogo Selene **Preparing** con **Cancel**. `IconLaunchWait` lega la richiesta all'identità del gioco e del dialogo; chiudere o sostituire il dialogo revoca la richiesta.
+- Solo l'ultimo aggiornamento dell'icona riuscito può riprendere Play, che rilegge il gioco corrente e ripete tutti i controlli su salvataggi e app. Un errore non avvia il gioco.
+- Cancel lascia finire la firma, che serve a mantenere valido il bundle. L'attesa usa `launchingGameId` e blocca anche l'aggiornamento del frontend.
+
+**Schermata di lancio.**
+- `RunningGameMonitor` confronta i bundle ID della libreria con le applicazioni in esecuzione e offre Resume e Close Game. `LaunchReadinessProbe` aspetta una finestra visibile del processo per chiudere la schermata di lancio.
+- La schermata ha una finestra propria, come la "launch cover" di Selene (`LaunchCoverWindow`). È senza bordi e trasparente (appare sfumando sopra la libreria), sta sopra ogni app, il Dock e la barra dei menu, su ogni Space compresi quelli a schermo intero, e non viene mai attivata.
+- Quando un gioco si apre a schermo intero, la schermata scorre via con la libreria e rientra con lo Space del gioco, coprendolo finché il gioco non disegna. *Perché:* tenuta nel solo Space di Arcane, lì si vedeva lo sfondo della scrivania; il maintainer preferisce la schermata (prova con MTGA, 15 nov 2026).
+- Il gioco parte dietro di lei; Steam che prende il primo piano o macOS che cambia Space restano dietro, quindi Arcane non deve mai riprendersi il primo piano.
+- Play Steam accoda la richiesta fino a quando AppKit ordina e invia il pannello al server delle finestre. Arcane lascia al pannello il passaggio SwiftUI di preparazione prima che Steam possa cambiare Space. Se il pannello manca, Play procede comunque entro un secondo. Solo la richiesta ancora corrente può partire.
+- La schermata d'attesa mostra artwork, logo o titolo del gioco secondo lo stile scelto, con l'angolo inferiore destro libero.
+- Il movimento è quello di Selene (`LaunchMotion`), in Core Animation così resta fluido mentre il gioco o Steam si avviano:
+ - l'arte si avvicina piano (scala da 1,04 a 1,12 in 20 s);
+ - il logo entra una sola volta, poco dopo la dissolvenza della schermata (0,36 s): appare in 0,75 s mentre sale di 30 unità in 1 s, poi resta fermo. Al massimo metà larghezza e 38% dell'altezza, come Selene;
+ - con Riduci movimento l'arte resta ferma e il logo appare soltanto.
+
+**Sessioni.** `PlaySessionStore` registra avvio, heartbeat, fine e riconciliazione delle sessioni. `ActivitySummary` aggrega la settimana; `LibraryPresentation` e `GameDetailPresentation` preparano i valori delle schermate.
+
+## Pagina del gioco
+
+**Pannello Details.**
+- La colonna destra della pagina del gioco, nella Spotlight e in Details, si chiude con lo stesso pannello per ogni fonte (`DetailsPanel`). Sono righe etichetta → valore con una piccola icona grigia (Developer, Publisher, Version, Size on disk, Installed in), direttamente sulla pagina, con separatori sottili e senza riquadro.
+- La card Achievements, che si preme, ha un fondo trasparente al 5% (10% su hover e focus) e il bordo, senza materiale sfocato aggiuntivo.
+- Sotto ci sono i link Reveal in Finder, Store page e HowLongToBeat (`DetailsLink`, `SeleneActionGrid`, focus `DetailsFocus.actionsZone` / `.actions`).
+- `DetailsFacts` nel Core sceglie le righe: una riga senza valore non compare. Steam non mostra mai la versione (il build ID è tecnico) e, senza un'installazione disponibile (download in corso), mostra solo Developer e Publisher. Cartella e volume arrivano per nome visualizzato, mai come percorso.
+- Lo stato tecnico (sorgenti, engine, toolchain, build bloccata) non sta sulla pagina. Rebuild, Attach sources, Open log, Saves e, senza descrizione, Search Nintendo Store stanno in Options; un problema che ferma il giocatore resta nella nota di Play. Nella pagina Details le righe vanno su due colonne.
+
+**Voto della critica.**
+- L'ultima riga del pannello, dopo Installed in, mostra cinque stelle proporzionali, il voto originale /100 e la fonte. È una riga informativa, senza card o finestre aggiuntive, e non aggiunge azioni al focus.
+- Caricamento e voto assente hanno un testo esplicito, senza fingere un voto zero. Provenienza, data del voto, ambito ed eventuale ripiego sulla copia salvata stanno nel testo accessibile e nell'aiuto.
+- La media utenti IGDB usa "Voto utenti" e "Utenti · IGDB", conservando stelle, numero e posizione della riga. Le fonti sono descritte in [Artwork, metadati e voti](#artwork-metadati-e-voti).
+
+**Fascia Mods.** Sta tra Details e More like this: vedi [Mod](#mod).
+
+**More like this.** La fascia condivisa `DetailsMoreBand` mostra fino a sei giochi, dopo Mods per Switch e sotto About e Details per Steam. `MoreLikeThis` ordina per generi, sviluppatore ed editore in comune. Esclude il gioco corrente e quelli nascosti. Steam dà precedenza ai titoli Steam e cerca titoli Switch correlati quando non trova corrispondenze Steam. Usa scelte personali e metadati già disponibili, con i generi nella lingua dell'interfaccia. La cache Steam si legge all'apertura della pagina e la fascia compare solo con corrispondenze effettive.
+
+## Cheat
+
+- `CheatLocator` legge title ID, build ID e percorso secondo il contratto del launcher.
+- `EngineAncestry` e `CheatStatus` decidono se l'app del gioco contiene il supporto ai cheat, dal commit del registro di build o, per un'app importata, da `DMCommit` nel suo `Info.plist`.
+- `CheatFile` riproduce il parsing di codici e metadati del motore. `CheatInstall` decide se un file appartiene alla build, richiede conferma o va rifiutato.
+- `CheatStore` legge e modifica file, metadati, master switch e selezione `.enabled`. `AppViewModel+Cheats` espone contesto, stato della riga e informazioni per la diagnostica. `CheatsPanel` presenta lista, importazione, conferme e switch. La pagina del gioco legge "Cheats on" all'apertura, al cambio del gioco, alla chiusura di Game options e al ritorno da Finder (`reloadCheats`), non a ogni ridisegno.
+- Le modifiche richiedono il gioco chiuso. Il motore legge i file installati al lancio.
+
+## Mod
+
+**Mod locali.**
+- Le mod di file (RomFS) di un gioco stanno in `~/Library/Application Support/nxnative//mods//romfs`.
+- `ModFolderScanner` trova le cartelle e il loro `romfs`, anche nel formato Atmosphère. Un file lasciato lì (per esempio un archivio non estratto) compare come "non è una mod"; i file nascosti come `.DS_Store` non contano per i conflitti.
+- `ModStore` tiene ordine e stato acceso/spento in `~/Library/Application Support/NXLibrary/mods/.json`. Nell'`env.txt` del gioco scrive solo la riga `DM_ROMFS_OVERLAY` (con `EnvFileEditor`), che il motore legge al lancio: le mod accese, la prima vince, senza rebuild. Il valore non supera 4077 byte, il buffer di riga del launcher.
+- Remove sposta la cartella nel Cestino. Niente modifiche mentre il gioco è aperto.
+- All'apertura della pagina e del pannello, `sync()` toglie dalla riga le mod sparite. Finché Arcane non ha mai gestito le mod di un gioco, non tocca una riga `DM_ROMFS_OVERLAY` scritta a mano.
+- `AppViewModel+Mods` crea lo store e traduce gli errori; `ModsPanel` (Game options → Mods; `GameOptionsFiles` legge configurazione, impostazioni, cheat e mod una volta per apertura) e la fascia Mods della pagina (`DetailsModsBand`) presentano lo stato. Le mod che modificano il codice (exefs) non funzionano con il motore.
+
+**GameBanana** (`Services/GameBanana/`).
+- `GameBananaClient` parla con l'API pubblica (apiv11 e, per il contenuto degli archivi, la vecchia Core API). Usa un solo User-Agent, al massimo 4 richieste insieme, e una cache su disco in `~/Library/Caches/NXLibrary/gamebanana`:
+ - ricerche 1 giorno, pagine delle mod 6 ore;
+ - contenuto degli archivi per sempre, tranne un elenco vuoto, perché GameBanana può ancora leggere un file nuovo;
+ - senza rete usa anche le voci scadute.
+- `GameBananaMatch` abbina il gioco per nome (preferisce la voce "(Switch)" e chiede quando non è sicuro); `GameBananaMatchStore` ricorda la scelta per title ID in `Application Support/NXLibrary/gamebanana/matches.json`.
+- `AvailableModsFinder` scorre le mod più scaricate e tiene solo quelle che `ModSupport` riconosce: un'unica cartella `romfs` per questo title ID, niente exefs, IPS o pchtxt, niente mod obsolete, private o con content rating.
+- `ModInstaller` scarica con `ModDownload` (solo host `*.gamebanana.com`) e controlla dimensione e MD5. Legge e controlla l'archivio con `/usr/bin/bsdtar`, rifiuta percorsi `..`, symlink e hard link prima di estrarre, lo estrae in una cartella nascosta dentro `mods` e passa l'albero a `ModStore.adopt`. Un aggiornamento manda la versione vecchia nel Cestino e tiene posto e stato.
+- I link presi dall'API valgono solo se sono `https` su un host GameBanana. Ogni mod mostra autore e link alla sua pagina, e la fascia dice "Mod data provided by GameBanana".
+
+**Fascia Mods della pagina.**
+- Compare sia nella pagina del gioco della Spotlight sia in Details, tra Details e More like this (focus `.mods` in `SpotlightState`, `DetailsFocus.modsZone`).
+- È una griglia di sei tessere per riga che non scorre di lato (`ModsBandLayout`): Sinistra e Destra restano nella riga, Giù scende di riga e dall'ultima passa a More like this.
+- `ModsBandHost` tiene per entrambe le pagine mod installate, GameBanana e pannelli. In Spotlight legge le mod all'apertura della pagina del gioco. Cambiare selezione sulla riga svuota la fascia precedente senza leggere quella successiva, così la lettura delle mod resta fuori dallo scorrimento.
+ Le [misure dei primi cambi gioco](reviews/2026-11-18-spotlight-glide.md) mostrano il costo della lettura prima e dopo.
+- Play riconcilia le cartelle delle mod prima di avviare il gioco, anche dalla riga. Se la cartella o i record non si leggono, `ModStore.sync` conserva entrambi i file di stato. La Dev mantiene il divieto di manutenzione automatica dell'overlay.
+- `GameBananaBandModel` coordina abbinamento, ricerca e installazioni. Cambiando gioco dimentica le mod del precedente; alla prima apertura di un gioco in ogni avvio toglie gli avanzi di un'installazione interrotta (`ModStore.removeLeftoverInstalls`). `GameBananaFindModel` tiene lo stato della ricerca per nome.
+- Le mod trovate entrano al massimo in due gruppi: le prime cinque, accanto ad Add mods, appena ci sono, poi tutte le altre a ricerca finita. Ogni gruppo aspetta (al massimo 1,2 s, `imageWait`) che la sua arte sia decodificata (`prepareImages`, cioè `GameBananaImageView.prepare`, in parallelo) ed entra con un'unica dissolvenza. Una tessera di stato spinta più in là sfuma nel nuovo posto invece di attraversare la griglia.
+- Un'installazione è per un file (`GameBananaBandModel.installFiles`): solo la sua riga mostra avanzamento ed esito, le altre aspettano che finisca.
+
+**Pannello della mod.**
+- `ModDetailPanel` e `GameBananaFindPanel` sono i pannelli sopra la pagina.
+- La descrizione mostra otto righe con Read more subito sotto; Read more la apre tutta (`TextScroll.windowHeight`) e i file, sotto il titolo Files, scendono.
+- La colonna (intestazione, descrizione, file) scorre dentro il pannello quando è più alta, al massimo 980 unità. Si scorre con rotella o trackpad, e con Su/Giù, che prima leggono a passi quello che c'è prima della riga seguente e poi spostano il fuoco e mostrano la riga intera (`TextScroll.step`). I bordi sfumano dove c'è altro, e una barra sottile dice dove si è.
+- Lo scorrimento sta in `ModsBandHost.detailScroll`, un oggetto a parte, così muoverlo ridisegna solo il pannello e non la pagina sotto.
+
+**Store delle mod.**
+- Lo store è la card **Mods** della Spotlight (`SpotlightCard.mods`). La sua visibilità sta in `showsModsCard`, mai in `spotlightCards`, così la versione rilasciata legge ancora le impostazioni.
+- Giù dalla card porta il focus a `.store`, e `ModStoreHost` muove `ModStoreFocus` dentro la pagina (`ModStorePage`). La pagina contiene:
+ - una barra di ordinamento;
+ - Featured, con dissolvenza tra le prime cinque;
+ - le mod popolari dei tuoi giochi;
+ - una riga per categoria (`ModCategory`, raggruppate dai nomi delle categorie GameBanana);
+ - una riga per gioco, dal più giocato di recente.
+- `ModStoreLayout` costruisce le sezioni e dà a ognuna un'altezza fissa, così lo scorrimento non misura nulla e si disegnano solo le sezioni vicine al focus.
+- `ModStoreModel` apre dalle copie su disco (`ModCatalogSnapshots`, `~/Library/Caches/NXLibrary/gamebanana/store`) e aggiorna in background quelle più vecchie di 6 ore, due giochi alla volta, pubblicando un gioco intero per volta. Un gioco senza abbinamento si abbina solo se il nome è certo. L'ordinamento è locale sulle mod già trovate.
+- Le immagini decodificate restano in memoria (`GameBananaImageView`, che le prepara in anticipo con `prewarm` per le prime tessere di ogni riga).
+- La copertina della card (`ModStoreLayout.coverArt`) sono le prime quattro mod del Featured per popolarità, qualunque sia l'ordinamento, con i giochi in ordine di title ID. All'avvio si legge dalle copie su disco dei tuoi giochi ed è la stessa che trova lo store aperto. Cambia solo se lo store trova mod nuove, e solo dopo che tutte e quattro le immagini sono decodificate, in un'unica dissolvenza.
+- Sulla riga, la faccia della card è un mosaico sfocato dell'arte delle mod migliori con il puzzle al centro (`ModsCardCover`, dalle copie su disco prima che lo store abbia cercato; senza arte, il gradiente Selene).
+ `AppShellState` possiede `ModStoreHost`, che Spotlight osserva: il mosaico pronto sopravvive alla navigazione. Uscire dalla home continua a chiudere il pannello e fermare lo store.
+
+ A ogni ritorno gli snapshot vengono rivalidati rispetto agli abbinamenti GameBanana, mantenendo la cover finché la lettura finisce; un risultato vuoto la rimuove. Cambiare i title ID la invalida subito e le identità delle richieste scartano letture precedenti; una cover pubblicata dal catalogo invalida lo snapshot ancora in lettura. Gli stati transitori idle/loading del catalogo non svuotano il mosaico.
+
+ I record Installed/Update vengono riletti a ogni apertura, con generazione separata per scartare letture precedenti a una chiusura o installazione.
+- Lo sfondo del Featured si sfoca una volta sola, fuori dal main thread, su una copia di 240 px (`GameBananaBlur`): nessuna sfocatura gira a ogni frame.
+- Mentre la pagina scorre, `ModStoreHost.hold(until:)` trattiene le mod trovate in background e ricostruisce le sezioni solo a pagina ferma (il log `store rebuild … ms` misura ogni ricostruzione).
+- Con la card selezionata lo sfondo diventa oro: vedi [Interfaccia Selene e input](#interfaccia-selene-e-input). Il pannello della mod è lo stesso della fascia; `GameBananaBandModel.attach(store:)` installa nella cartella del gioco della mod.
## Salvataggi, backup e recupero
-### Riconoscimento e anteprima
-
-Il flusso usa il title ID e conserva i percorsi interni del salvataggio per ogni gioco. `SaveLocation` ammette l’ID esadecimale di 16 caratteri, risolve il percorso predefinito e legge la configurazione cloud effettiva. `AppViewModel+Saves` verifica anche l’identità nel bundle installato e le preferenze del gioco.
-
-`RyujinxSaveFolder` riconosce `bis/user/save/`, risale dalle sottocartelle, confronta il title ID in `ExtraData0` e seleziona l’intero albero committed `0`. Le cartelle di esportazione ordinarie mantengono la propria struttura. Il tipo User/Device è una scelta separata dal nome della cartella sorgente.
-
-`SaveSnapshotStore.stageImport` prepara una copia temporanea vicino alla destinazione. L’anteprima contiene inventario, hash SHA-256, attributi estesi e impronta del salvataggio attuale. `SaveRestorePreview.swift` prepara allo stesso modo un ripristino da backup. Alla conferma vengono ricontrollati sorgente, staging e salvataggio attuale.
-
-### Copia protettiva e sostituzione
-
-`SaveTransaction` crea prima un backup verificato dei due slot committed, inclusa l’eventuale assenza di uno slot. Persiste poi il journal `.nxlibrary-save-transaction.json` e sostituisce ciascuna directory con staging sullo stesso volume. Usa `renamex_np(RENAME_SWAP)` per scambiare due directory esistenti e spostamenti per i casi di presenza o assenza.
-
-L’importazione sostituisce lo slot scelto. Il ripristino applica l’intero snapshot, compresa la presenza o assenza dei due slot. `SaveOperationGate` assegna lease per title ID, coordinando salvataggi, Play e installazioni anche quando più voci della libreria condividono lo stesso gioco.
-
-### Integrità e recupero
-
-`SaveFileIO` centralizza copie, hash, metadati, controlli dei percorsi, scritture durevoli e punti di errore sostituibili nei test. La verifica normalizza provenienza e label di accesso gestite da macOS, più il campo agente della quarantena. Confronta i metadati guest e il contenuto dei file. I manifest e i journal precedenti passano dalla stessa normalizzazione.
-
-All’avvio o al refresh, un journal incompleto porta al rollback del salvataggio precedente verificato. Un journal committed richiede la verifica del risultato prima della pulizia. Dati modificati esternamente o copie non verificabili mantengono il recupero bloccato e conservano gli artefatti per l’intervento. Play attende la risoluzione.
-
-`SavesPanel` espone apertura cartella, backup manuale, destinazione, importazione, refresh e cartella backup con data dell’ultima copia. L’anteprima From → To è in `SaveImportDetails`. Dopo ogni importazione riuscita, `SavePanelModel` pubblica un nuovo evento e la vista mostra `SeleneSuccessNotice`, che si chiude dopo tre secondi. Il timer della vista si annulla quando il pannello scompare.
-
-Storage → Save backups apre la cartella comune degli snapshot. Il vecchio export ZIP di Storage è stato rimosso; la creazione delle copie passa dal pannello Saves.
-
-### Spazio per gioco (non pubblicato, validato dal maintainer)
-
-Settings → Storage riusa `StorageManager.snapshot`: `GameStorageUsage` distingue app, cache e log per voce, compresi i giochi nascosti, ordinando le cache dalla più grande. `StorageSize` distingue file assenti da percorsi non leggibili o volumi scollegati. Le misure sono dimensioni logiche dei file, inclusi quelli nascosti; la visita fisica fts non segue i collegamenti interni e scarta misure incomplete in caso di errore. I percorsi canonici condivisi vengono misurati e contati una sola volta nei totali. Lo spazio libero è quello della cartella Game apps corrente e non ripiega sul disco interno se questa manca.
-
-La conferma per gioco conserva identità e percorso selezionati. Prima della cancellazione, il coordinatore ricontrolla la voce corrente; `StorageManager` richiede la cartella `_build` immediatamente sotto il workspace registrato, rifiuta file ordinari e cache che siano symlink e protegge app, sorgenti e installazioni differite di tutte le voci. Un collegamento dentro la cache viene rimosso senza visitarne la destinazione. Le cache condivise sono indicate sia nella riga sia nella conferma. Non viene rimossa l'intera cartella workspace né modificato il catalogo: una ricompilazione ricrea la cache.
-
-Misura e pulizia girano sulla coda utility. `isCleaningStorage` blocca nuove pulizie, build e installazioni dell'updater; i giochi già installati restano avviabili. Una misura superata da cambi di libreria o destinazione viene ripetuta. Il termine della pulizia pubblica l'esito, espone eventuali errori e ricalcola le dimensioni. Le righe dei giochi hanno identità UUID stabili per mouse, tastiera e controller. Il maintainer ha confermato il funzionamento nella Dev il 9 novembre 2026; test automatici e build sostengono la verifica.
-
-I backup sono copie locali conservate fino alla gestione dell’utente. Sono automatici prima di importazione e ripristino, oppure manuali con Back up now. Importazione e ripristino richiedono sincronizzazione cloud effettivamente disattivata. I casi rifiutati e le verifiche eseguite sono descritti nelle sezioni Saves del README e dei test.
-
-## Artwork, metadati e sfondi
-
-Look distingue Wallpaper e Library screens. Game backgrounds è un controllo positivo: On mostra l’artwork del titolo in Spotlight e Collection, Off mantiene il wallpaper. Riusa la preferenza `keepWallpaperOnGames` invertendo soltanto il binding, senza migrazione dei dati. Details continua a usare l’artwork del gioco; il layout di avvio segue le proprie impostazioni globali. Wallpaper sizing riguarda il wallpaper e Library shade le maschere delle schermate della libreria.
-
-Change artwork conserva la precedenza delle scelte manuali per titolo. La riga di stato ha altezza stabile, testo breve per la ricerca e indicazione della destinazione dell’immagine; segnala Home: wallpaper quando lo sfondo della home è governato dal wallpaper globale.
-
-LaunchBox e SteamGridDB non entrano nella griglia automatica: ciascuno ha un riquadro **Browse online** che apre una griglia propria (`ArtworkBrowseSource`), con ricerca precompilata e modificabile, risultati per lo slot aperto, credito per immagine e X per la pagina del gioco sulla sorgente. La griglia carica solo le anteprime; il file pieno (`ArtworkCandidate.full`) si scarica alla scelta e viene ridimensionato come ogni scelta manuale. LaunchBox non ha API: ricerca e pagina gioco si leggono come TheGamesDB, e immagini e dimensioni vengono dal payload `__NUXT_DATA__`. SteamGridDB usa l’API v2 con la chiave personale dell’utente (file `0600`, mai registrata nei log). Per i giochi senza screenshot Title DB, il caricamento dei metadati (selezione o apertura del gioco) chiede una volta a LaunchBox gli screenshot Gameplay e li conserva 30 giorni (`ScreenshotFallbackStore`); le scansioni della libreria non avviano richieste.
-
-`NintendoStoreMetadataService`, `GameTDBStore`, Title DB e le sorgenti di artwork raccolgono descrizioni, date, generi, copertine, loghi, sfondi e screenshot. `ArtworkNames` confronta i nomi per limitare i candidati al gioco o alle sue edizioni. `ArtworkPicker` e `MetadataOptions` aggregano i risultati per i selettori. `ArtworkPicks` e `MetadataPicks` conservano le scelte manuali.
-
-La 0.1.4.2 prepara inoltre un resolver delle icone automatiche (`AutomaticIconResolver`, in attesa di validazione manuale e di chiarimento dell'accesso al provider secondario). Il gioco e le scelte manuali mantengono precedenza; `ArtworkStore.automaticIcon` prova Title DB e poi una corrispondenza esatta normalizzata in Switch Icon Showdown, senza confondere sequel, omonimi o edizioni. Un title ID Switch 2 da solo non identifica una Switch 2 Edition. La cache PNG resta separata da `ArtworkPicks`, con attribuzione e una sola piccola voce negativa per gioco (15 minuti). Il resolver condivide le richieste concorrenti della stessa istanza, limita dimensioni e tempi delle risposte, verifica host e immagini quadrate e consulta `robots.txt` prima del download secondario. **Al 9 novembre 2026, il sito esclude `/images/` dai crawler: il resolver non scarica le immagini di Switch Icon Showdown. Non considerare la issue #12 risolta o questa fonte operativa finché non viene chiarito un accesso consentito.** Le immagini automatiche disponibili possono riempire l'icona di un'app che non ne ha una, solo senza pick manuale e senza un esplicito Only here. Le app con icona propria rimangono intatte. Fallimenti di rete o ricerche ambigue non fanno fallire il porting. Nessun file del motore viene modificato.
-
-L'icona scelta in Change artwork (slot Icon, conservata a 1024 px) diventa anche l'icona dell'app del gioco in Finder e nel Dock (`AppIconWriter`, `AppViewModel+AppIcon`). Nella 0.1.4.2 (in attesa di validazione manuale) il pop-up offre **Only here** / **Use on the Mac** per ogni gioco, anche senza icona propria o non ancora costruito. `PortedGame.appIconOnMac` memorizza la scelta esplicita: false vieta la scrittura anche per NUP e dump; true la richiede quando esiste un'Icon pick; nil conserva la regola precedente (`usesPickedAppIcon` oppure assenza di icona originale) per le vecchie librerie fino alla prossima scelta. Riconciliazione e scrittura condividono `wantsPickedAppIcon`. Only here ripristina l'icona originale o la sua assenza se una personalizzata era già applicata. Automatic rimuove solo la scelta dell'immagine, conserva la destinazione esplicita (e l'opt-in legacy) e usa prima l'originale, anche dal backup durante una personalizzazione, poi l'icona estratta o quella online disponibile. La tile Icon location permette di modificare la destinazione anche senza pick. Se la ricerca non trova un sostituto, il writer ripristina l'originale o la sua assenza, senza lasciare la vecchia immagine personalizzata. La tile Automatic mostra l'anteprima risolta; lo stato distingue ricerca, firma e icona non disponibile. AppIconProgress conserva i testi condivisi fra UI e log. Dopo una build installata, inclusa un'installazione differita, l'esito della preparazione viene aggiunto al relativo log già chiuso dall'engine e al log della UI; assenza di artwork non cambia il successo della build. La riga informativa viene scritta solo dopo l'ultimo aggiornamento in coda, non per le successive modifiche manuali. Scansioni e rebuild conservano la preferenza. La scrittura crea `Resources/AppIcon.icns`, marca `Info.plist` con `NXLibraryAppIcon`, rifirma il bundle ad hoc come l'engine e verifica con `codesign --verify --deep --strict`; l'icona originale resta in `Application Support/NXLibrary/app-icons//`, e ogni errore rimette i file toccati. Avviene dopo ogni build installata (la rebuild sostituisce l'app, e l'engine ricrea il pacchetto se trova file cambiati), all'avvio e quando un gioco si chiude, mai mentre il gioco gira o si costruisce; durante la firma (circa 50 secondi per un gioco di 9–12 GB) avvio e build del gioco attendono, e la riga di stato di Change artwork mostra l'avanzamento. Una scelta fatta mentre la stessa app si firma viene rieseguita alla fine, così vale l'ultima. Dopo ogni scansione della libreria `reconcileAppIcons` confronta lo stato voluto con l'app (marca `NXLibraryAppIcon`) e rimette in coda le differenze, per esempio una scelta fatta mentre l'app era stata spostata.
-
-`ArtworkStore` mantiene la cache immagini. `BoxArtService` risolve le copertine Switch di GameTDB. `GameArtLoader` e `SeleneHeroArt` alimentano sfondo e logo delle schermate con caricamento e cache dedicati.
-
-Per gli sfondi online, i parser dei provider sono in `OnlineBackgrounds.swift`. `OnlineBackgroundService` gestisce rete, progressi, miniature e crediti. `OnlineBrowser` e `OnlineTransfer`, definiti in `OnlineBrowsePanel.swift`, alimentano la griglia e l’importazione nel selettore temi. `ThemeStore` unisce palette, wallpaper inclusi e file importati.
+Il percorso completo è in [flows.md](flows.md#6-importare-o-ripristinare-un-salvataggio).
+
+**Riconoscimento e anteprima.**
+- Il flusso usa il title ID e conserva i percorsi interni del salvataggio per ogni gioco. `SaveLocation` ammette l'ID esadecimale di 16 caratteri, risolve il percorso predefinito e legge la configurazione cloud effettiva. `AppViewModel+Saves` verifica anche l'identità nel bundle installato e le preferenze del gioco.
+- `RyujinxSaveFolder` riconosce `bis/user/save/`, risale dalle sottocartelle, confronta il title ID in `ExtraData0` e seleziona l'intero albero committed `0`. Le cartelle di esportazione ordinarie mantengono la propria struttura. Il tipo User/Device è una scelta separata dal nome della cartella sorgente.
+- `SaveSnapshotStore.stageImport` prepara una copia temporanea vicino alla destinazione. L'anteprima contiene inventario, hash SHA-256, attributi estesi e impronta del salvataggio attuale. `SaveRestorePreview.swift` prepara allo stesso modo un ripristino da backup. Alla conferma si ricontrollano sorgente, staging e salvataggio attuale.
+
+**Copia protettiva e sostituzione.**
+- `SaveSlot` descrive account e device, `user2`…`user8` e il file registro `users` (`save.users`).
+ Gli altri pezzi sono directory. Le cartelle transazionali dell’engine (`.work` / `.new`) non entrano
+ nell’inventario; il registro si copia come file regolare, con limite 64 KiB e senza seguirne link.
+- `SaveSnapshotStore` crea un backup verificato di tutti i pezzi locali committed presenti, compresa
+ la loro assenza. Il manifest resta schema 1 per soli account/device e usa schema 2 per gli utenti
+ aggiuntivi o il registro. I vecchi backup non si riscrivono; versioni o dichiarazioni incoerenti si rifiutano.
+- `SaveTransaction` prepara lo staging, salva il journal `.nxlibrary-save-transaction.json` e cambia
+ soltanto i pezzi dichiarati in `mutatedSlots`. Usa `renamex_np(RENAME_SWAP)` per scambiare file o
+ directory e spostamenti per presenza/assenza. Il registro si scambia per ultimo.
+- L’importazione da cartella modifica solo User oppure Device; registro e utenti aggiuntivi restano
+ intatti, senza ricopiarli o scambiarli. Il restore schema 1 modifica solo i due slot storici e conserva
+ gli altri utenti correnti. Il restore schema 2 applica tutto il gruppo, comprese le assenze, sempre
+ dopo un backup di sicurezza. La conferma spiega l’ambito prima di agire.
+- Il cloud dell’engine copre soltanto utente principale e device. Il pannello e le impostazioni lo
+ dichiarano; un backup locale completo non equivale alla sincronizzazione di tutti gli utenti.
+- `SaveOperationGate` assegna lease per title ID, coordinando salvataggi, Play e installazioni anche quando più voci della libreria condividono lo stesso gioco.
+
+**Integrità e recupero.**
+- `SaveFileIO` centralizza copie, hash, metadati, controlli dei percorsi, scritture durevoli e punti di errore sostituibili nei test.
+- La verifica normalizza provenienza e label di accesso gestite da macOS, più il campo agente della quarantena. Confronta i metadati guest e il contenuto dei file. Manifest e journal precedenti passano dalla stessa normalizzazione.
+- Prima e dopo ogni scambio si verificano contenuto live e originale spostato in staging; una modifica
+ inattesa conserva journal e artefatti. La pulizia registra l’intenzione e l’inventario verificato nel journal prima di eliminare i residui, un elemento alla volta; si riprende anche dopo una cancellazione parziale e rifiuta dati nuovi o cambiati.
+- All’avvio o al refresh, un journal incompleto porta al rollback al salvataggio precedente verificato.
+ Il journal 1 osserva solo account/device, conservando eventuali utenti comparsi dopo l’interruzione;
+ il journal 2 osserva il gruppo completo. `mutatedSlots` manca nei journal storici, che conservano
+ l’ambito dei due slot originali. Un journal committed verifica il risultato prima della pulizia.
+ La recovery può a sua volta interrompersi e riprendere. Il gioco deve restare chiuso anche per lanci esterni.
+- Dati modificati da fuori o copie non verificabili tengono il recupero bloccato e conservano gli artefatti per l'intervento. Play aspetta la risoluzione.
+
+**Pannello e backup.**
+- `SavesPanel` offre: apertura della cartella, backup manuale, destinazione, importazione, refresh e cartella dei backup con la data dell'ultima copia. L'anteprima From → To è in `SaveImportDetails`.
+- Dopo ogni importazione riuscita, `SavePanelModel` pubblica un evento e la vista mostra `SeleneSuccessNotice`, che si chiude dopo tre secondi; il timer si annulla quando il pannello scompare.
+- I backup sono copie locali conservate finché l'utente non li gestisce. Sono automatici prima di importazione e ripristino, oppure manuali con Back up now.
+- Importazione e ripristino richiedono la sincronizzazione cloud davvero disattivata. I casi rifiutati e le verifiche sono descritti nelle sezioni Saves del README e dei test.
+- Storage → Save backups apre la cartella comune degli snapshot; le copie si creano dal pannello Saves.
+
+## Spazio su disco
+
+**Misura.**
+- Settings → Storage e Porting → Storage usano `StorageManager.snapshot`. `GameStorageUsage` distingue app, cache e log per voce, compresi i giochi nascosti, e ordina le cache dalla più grande.
+- `StorageSize` distingue file assenti da percorsi non leggibili o volumi scollegati.
+- Le misure sono dimensioni logiche dei file, compresi quelli nascosti. La visita fisica fts non segue i collegamenti interni e scarta le misure incomplete in caso di errore. I percorsi canonici condivisi si misurano e si contano una sola volta nei totali.
+- Lo spazio libero è quello della cartella Game apps corrente, senza ripiegare sul disco interno se questa manca.
+
+**Pulizia.**
+- La conferma per gioco conserva identità e percorso scelti. Prima di cancellare, il coordinatore ricontrolla la voce corrente.
+- `StorageManager` richiede la cartella `_build` immediatamente sotto il workspace registrato. Rifiuta file ordinari e cache che siano symlink, e protegge app, sorgenti e installazioni differite di tutte le voci.
+- Un collegamento dentro la cache si rimuove senza visitarne la destinazione. Le cache condivise sono indicate sia nella riga sia nella conferma.
+- Non si rimuove l'intera cartella workspace né si modifica il catalogo: una ricompilazione ricrea la cache.
+
+**Esecuzione.**
+- Misura e pulizia girano sulla coda utility. `isCleaningStorage` blocca nuove pulizie, build e installazioni dell'updater; i giochi già installati restano avviabili.
+- Una misura superata da cambi di libreria o destinazione si ripete. A fine pulizia si pubblica l'esito, si mostrano gli eventuali errori e si ricalcolano le dimensioni.
+- Le righe dei giochi hanno identità UUID stabili per mouse, tastiera e controller.
+
+## Artwork, metadati e voti
+
+**Sfondi delle schermate.**
+- Look distingue Wallpaper e Library screens. Game backgrounds è un controllo positivo: On mostra l'artwork del titolo in Spotlight e Collection, Off tiene il wallpaper. Riusa la preferenza `keepWallpaperOnGames` invertendo solo il binding.
+- Details usa sempre l'artwork del gioco, e la schermata di avvio segue le proprie impostazioni globali. Wallpaper sizing riguarda il wallpaper, Library shade le maschere delle schermate della libreria.
+
+**Fonti dell'artwork.**
+- `NintendoStoreMetadataService`, `GameTDBStore`, Title DB e le sorgenti di artwork raccolgono descrizioni, date, generi, copertine, loghi, sfondi e screenshot.
+- `ArtworkNames` confronta i nomi per limitare i candidati al gioco o alle sue edizioni. `ArtworkPicker` e `MetadataOptions` aggregano i risultati per i selettori; `ArtworkPicks` e `MetadataPicks` conservano le scelte manuali.
+- `ArtworkStore` tiene la cache delle immagini. `BoxArtService` risolve le copertine Switch di GameTDB. `GameArtLoader` e `SeleneHeroArt` alimentano sfondo e logo delle schermate.
+
+**Change artwork.**
+- Le scelte manuali per titolo hanno la precedenza. La riga di stato ha altezza stabile, testo breve per la ricerca e l'indicazione di dove va l'immagine; segnala Home: wallpaper quando lo sfondo della home dipende dal wallpaper globale.
+- LaunchBox e SteamGridDB non entrano nella griglia automatica: ciascuno ha un riquadro **Browse online** con una griglia propria (`ArtworkBrowseSource`). La ricerca è precompilata e modificabile, i risultati sono per lo slot aperto, ogni immagine ha il suo credito e X apre la pagina del gioco sulla sorgente.
+- La griglia carica solo le anteprime. Il file pieno (`ArtworkCandidate.full`) si scarica alla scelta e si ridimensiona come ogni scelta manuale.
+- LaunchBox non ha API: ricerca e pagina del gioco si leggono come TheGamesDB, e immagini e dimensioni vengono dal payload `__NUXT_DATA__`. SteamGridDB usa l'API v2 con la chiave personale dell'utente (file `0600`, mai nei log).
+- Per i giochi senza screenshot Title DB, caricare i metadati (selezione o apertura del gioco) chiede una volta a LaunchBox gli screenshot Gameplay e li conserva 30 giorni (`ScreenshotFallbackStore`). Le scansioni della libreria non avviano richieste.
+
+**Icone automatiche.**
+- `AutomaticIconResolver` riempie l'icona di un'app che non ne ha una, solo senza scelta manuale e senza un esplicito Only here. Le app con un'icona propria restano intatte.
+- `ArtworkStore.automaticIcon` prova Title DB e poi una corrispondenza esatta normalizzata in Switch Icon Showdown, senza confondere sequel, omonimi o edizioni. Un title ID Switch 2 da solo non identifica una Switch 2 Edition.
+- La cache PNG è separata da `ArtworkPicks`, con attribuzione e una sola piccola voce negativa per gioco (15 minuti). Il resolver condivide le richieste concorrenti, limita dimensioni e tempi delle risposte, verifica host e immagini quadrate e consulta `robots.txt` prima del download secondario.
+- Switch Icon Showdown esclude `/images/` dai crawler, quindi il resolver non scarica le sue immagini (stato in [validation.md](validation.md)).
+- Fallimenti di rete o ricerche ambigue non fanno fallire il porting. Nessun file del motore viene modificato.
+
+**Icona dell'app del gioco.** L'icona scelta in Change artwork (slot Icon, conservata a 1024 px) diventa anche l'icona dell'app del gioco in Finder e nel Dock (`AppIconWriter`, `AppViewModel+AppIcon`).
+- **La scelta.**
+ - Il pop-up offre **Only here** / **Use on the Mac** per ogni gioco, anche senza icona propria o non ancora costruito.
+ - `PortedGame.appIconOnMac` memorizza la scelta esplicita: false vieta la scrittura (anche per NUP e dump), true la richiede quando c'è una scelta Icon, nil applica la regola delle vecchie librerie (`usesPickedAppIcon` oppure assenza dell'icona originale) fino alla prossima scelta. Riconciliazione e scrittura condividono `wantsPickedAppIcon`.
+ - Only here ripristina l'icona originale, o la sua assenza, se era già applicata una personalizzata.
+ - Automatic rimuove solo la scelta dell'immagine e conserva la destinazione. Usa prima l'originale (anche dal backup durante una personalizzazione), poi l'icona estratta o quella online. Se non trova un sostituto, il writer ripristina l'originale o la sua assenza, senza lasciare la vecchia immagine personalizzata.
+ - La tile Icon location cambia la destinazione anche senza una scelta. La tile Automatic mostra l'anteprima risolta; lo stato distingue ricerca, firma e icona non disponibile.
+- **La scrittura.**
+ - Crea `Resources/AppIcon.icns`, marca `Info.plist` con `NXLibraryAppIcon`, rifirma il bundle ad hoc come l'engine e verifica con `codesign --verify --deep --strict`.
+ - L'icona originale resta in `Application Support/NXLibrary/app-icons//`; ogni errore rimette a posto i file toccati.
+ - Avviene dopo ogni build installata (la rebuild sostituisce l'app), all'avvio e quando un gioco si chiude, mai mentre il gioco gira o si costruisce.
+ - Durante la firma (circa 50 secondi per un gioco di 9–12 GB) avvio e build del gioco aspettano, e la riga di stato di Change artwork mostra l'avanzamento. Una scelta fatta mentre la stessa app si firma si riesegue alla fine, così vale l'ultima.
+- **Log e riconciliazione.**
+ - `AppIconProgress` tiene i testi condivisi fra UI e log. Dopo una build installata, anche differita, l'esito si aggiunge al log della build già chiuso dall'engine e al log della UI; l'assenza di artwork non cambia il successo della build. La riga si scrive solo dopo l'ultimo aggiornamento in coda.
+ - Scansioni e rebuild conservano la preferenza. Dopo ogni scansione `reconcileAppIcons` confronta lo stato voluto con l'app (marca `NXLibraryAppIcon`) e rimette in coda le differenze.
+
+**Change metadata** (`ChangeMetadataView`). Il selettore propone, per descrizione, generi, sviluppatore, editore e data, i valori delle fonti disponibili per nxnative e Steam.
+- **Comportamento del selettore.**
+ - Caricare le proposte non modifica `MetadataPicks`, `SteamPersonalizations` o i dati dello store. A decide solo il campo in anteprima, Automatic rimuove l'override, Write your own resta disponibile.
+ - Le descrizioni mantengono la lingua originale e lo dicono nel sottotitolo. Non si aggiungono artwork né sostituzioni automatiche.
+ - Il valore adottato è una copia personale, non un abbonamento alla fonte: compare una sola volta in "La tua scelta", con la spunta. Le righe delle fonti restano alternative, senza spunte multiple quando condividono lo stesso testo. Salvataggio e rimozione conservano il focus per identità della riga.
+ - Le righe hanno identità per fonte e alternativa, non per testo scaricato, quindi caricamento, disponibilità e cambio di campo non ricreano la lista. Sono dichiarati campo assente, risultato ambiguo, valore uguale ad Automatic, copia salvata e fonte non disponibile.
+ - Le righe senza azione non mostrano A Choose. Un errore permette Retry anche dal controller, senza doppie richieste. Ogni fonte aggiorna solo le sue righe, e una risposta si ignora se la query è cambiata. Il focus resta sulla scelta corrente quando arrivano nuove righe e torna ad Automatic se la scelta sparisce, senza aprire il campo di testo.
+ - `SeleneExpandableText` conserva estratto (240 caratteri) e testo completo alla stessa larghezza: `Layout` risolve subito la geometria finale e SwiftUI anima frame e dissolvenza. *Perché:* interpolare le misure dentro `Layout` sposterebbe il bersaglio di `scrollTo` mentre si chiude la riga precedente. Espansione e scroll usano la stessa curva, con allineamento iniziale per leggere il titolo delle descrizioni lunghe; Riduci movimento li disattiva. Vale solo per i metadati: gli altri `SeleneOptionRow` non cambiano. `scripts/check_metadata_text_layout.swift` verifica fuori schermo altezze, cambio di contenuto e destinazioni dello scroll.
+- **LaunchBox e TheGamesDB** sono alternative nello stesso selettore per i giochi già gestiti.
+ - La ricerca usa titolo, edizione e piattaforma, non il negozio; lo Steam ID aiuta dove è supportato ma non è necessario. GameTDB e Title DB restano fonti Nintendo.
+ - Si leggono su richiesta una ricerca e una scheda pubblica per database, con parser separati e cache di sole proposte, senza scaricare l'intero Metadata.zip né duplicare un catalogo di immagini. I parser verificano anche la scheda finale, rifiutano le ambiguità e non eliminano parole di edizione.
+ - Mac ha la precedenza su PC/Windows: una proposta PC è dichiarata come tale e non fornisce una falsa data Mac.
+ - `DatabaseMetadataService` ha due istanze esplicite, ognuna con cache separata per la query pubblica e al massimo quattro ricerche attive. Lettori della stessa query condividono il lavoro; uscire dall'ultimo lettore annulla la richiesta senza salvare un'assenza.
+ - Pagine fino a 2 MiB, cache fino a 256 KiB per proposta. Host e percorsi sono vincolati, cookie e redirect disabilitati; errori HTTP e corpi inattesi non diventano metadati.
+ - Dati validi durano sette giorni, assenze e ambiguità un giorno. Un errore conserva la proposta precedente come copia salvata e non crea una cache negativa; Retry forza un nuovo tentativo senza cambiare i valori personali. La cache sta dentro `metadata` ed è compresa nei conteggi e nella pulizia delle informazioni del negozio.
+ - `LaunchBoxArt.searchURL` genera direttamente la forma canonica in minuscolo, così si evita il redirect 301.
+ - Se IGDB è configurato, un suo nome canonico verificato può affinare la ricerca pubblica, senza inviare account, percorsi o attività.
+- `OnlineArtwork.find` riceve la piattaforma della richiesta. TheGamesDB cerca Mac OS (37), poi PC (1), oppure Switch (4971) / Switch 2 (5021). La scheda finale deve confermare titolo e piattaforma prima di proporre immagini, senza prendere il primo omonimo. LaunchBox e TheGamesDB sono attribuiti in About.
+- Le vecchie assenze di copertina Switch 2 si riprovano con un'identità del resolver distinta, conservando le immagini salvate e le assenze Switch valide.
+
+**Voti della critica.** `CriticRatingService.preferred` ordina i risultati: prima la critica IGDB (con credenziali), poi la critica Wikidata, infine la media utenti IGDB. Un voto pubblico della critica prevale quindi su una media utenti, anche se arriva per prima.
+- **Wikidata.**
+ - `WikidataRatings` verifica nome o alias esatti (anche il campo `match` degli alias), il tipo videogioco e l'eventuale ID Steam. Per Steam prova prima P1733, l'ID pubblico esatto, verificato di nuovo nelle dichiarazioni dell'entità. Le query tolgono soltanto i simboli ™/®/©, conservando sequel ed edizioni.
+ - Abbinamenti ambigui o ID contrastanti non pubblicano un voto.
+ - Seleziona solo medie /100 documentate di OpenCritic, Metacritic o CriticDB. Preferisce la piattaforma corrispondente, altrimenti un voto senza piattaforma dichiarata. Non prende il voto Windows per macOS, non converte percentuali di raccomandazione e non fa medie fra fonti.
+- **Servizio Wikidata.** `CriticRatingService` interroga solo l'API pubblica Wikidata, senza chiavi, cookie o scraping.
+ - Serializza e unisce le richieste, limita dimensione e durata e sospende le richieste dopo un errore.
+ - La cache `ratings/wikidata` del profilo corrente dura sette giorni per un voto e un giorno per un'assenza verificata; offline conserva il dato con la sua data. La data di scaricamento resta distinta da quella del voto.
+ - Cambiare gioco annulla il lettore e impedisce di pubblicare un risultato precedente. Niente viene scritto nel catalogo, nei dati Steam o nei giochi.
+- **IGDB (facoltativo)**, in Settings → Online services.
+ - **Credenziali.**
+ - Il dialogo chiede Client ID e Client Secret dell'applicazione Twitch personale, in cinque passi brevi con i campi del portale, il requisito email/2FA e un link diretto alla registrazione. Controlla la connessione prima di salvare e si può annullare anche durante la verifica. Tastiera e controller della pagina sotto sono sospesi.
+ - Search trova IGDB, About contiene l'attribuzione, e nel bundle non c'è nessuna credenziale condivisa.
+ - `IGDBCredentialsStore` conserva le credenziali solo nel profilo corrente, in `credentials/igdb.json` con modo 0600, dentro una cartella `credentials` riportata a 0700, esclusa dall'importazione Dev. Non passano da `AppSettings`, UserDefaults, log o URL.
+ - Il Client Secret va nel corpo del POST a Twitch; solo il token derivato e il Client ID raggiungono IGDB. I token stanno in memoria, si rinnovano a scadenza o una sola volta dopo 401 e non si scrivono su disco.
+ - **Client.** `IGDBClient` è l'unico accesso Twitch/IGDB per voti e metadati: host e endpoint vincolati, redirect e cookie rifiutati, una coda seriale fino a otto lavori con distanza fra le richieste, limiti di dimensione e durata, annullamento e messaggi senza il corpo del server. *Perché:* separare autenticazione e rete dai servizi evita di duplicare token e limiti.
+ - **Voti.**
+ - `IGDBRatingService` preferisce `aggregated_rating` e `aggregated_rating_count`, valida solo con almeno 3 recensioni (`IGDBRatings.minimumCriticReviews`). Altrimenti usa `rating` e `rating_count` come media utenti esplicita, mai `total_rating`, che è un dato misto.
+ - Nome o alias e piattaforma devono corrispondere, oppure l'ID Steam deve essere verificato su `external_games` con `external_game_source.name`. La console deriva da `PortedGame.isSwitch2`, come Details, e distingue `switch` (IGDB 130) da `switch2` (IGDB 508; Wikidata Q122761124), senza mai allargare il filtro alle due console insieme. La console fa parte della chiave di entrambe le cache.
+ - La media IGDB è del gioco, non di un port specifico, e conserva questo ambito.
+ - `CriticRating` distingue provenienza IGDB e Wikidata, e con `audience` critica da utenti (nil nelle vecchie cache vuol dire critica). `CriticRating.isValid` applica lo stesso minimo di 3 recensioni, quindi le cache con 1–2 recensioni si richiedono di nuovo. Le vecchie assenze IGDB senza versione si riprovano una volta. Togliere IGDB esclude anche i suoi voti utenti.
+ - La cache IGDB è per client pubblico e identità del gioco, senza segreti o token, e conserva offline il voto datato. Configurare o rimuovere il provider invalida richieste e token e ridisegna la riga tramite una revisione posseduta da `IGDBSettings`.
+ - **Metadati.**
+ - `IGDBMetadataParser` usa le stesse regole di nome, alias e piattaforma dei voti. Per Steam verifica `external_games.uid` e la fonte Steam; zero risultati permettono il ripiego per nome, un'identità ambigua non si indovina.
+ - Le aziende sono qualificate dai flag developer/publisher, non dalla semplice presenza nell'elenco. Una data richiede la piattaforma corrispondente e il formato `YYYYMMDD`: una data Windows non diventa Mac, e un anno o un mese non diventano un giorno inventato.
+ - `IGDBMetadataService` conserva solo la proposta e l'identità verificate, per client pubblico e query, in `metadata/igdb`: sette giorni per i dati, uno per assenze o ambiguità. Gli errori non diventano assenze in cache, e i dati salvati restano disponibili offline con un avviso. Risposte tardive o di credenziali rimosse non si pubblicano.
+- **Download a blocchi.** I download di Wikidata, IGDB, LaunchBox/TheGamesDB e Steam passano da `BoundedDownload`, che conserva i blocchi ricevuti da URLSession invece di leggere un byte alla volta. Limiti di dimensione, rifiuto dei redirect e annullamento restano gli stessi.
+
+Prove e misure di queste scelte: [docs/reviews/2026-11-16-ratings-metadata-evidence.md](reviews/2026-11-16-ratings-metadata-evidence.md).
+
+**Sfondi online.**
+- I parser dei provider sono in `OnlineBackgrounds.swift`. `OnlineBackgroundService` gestisce rete, progressi, miniature e crediti.
+- `OnlineBrowser` e `OnlineTransfer`, in `OnlineBrowsePanel.swift`, alimentano la griglia e l'importazione nel selettore dei temi. `ThemeStore` unisce palette, wallpaper inclusi e file importati.
+- Impostazioni rapide → Theme mantiene due passaggi: colori con anteprima viva, poi sfondo. Il focus si muove nella griglia delle palette e si ferma ai suoi bordi; A applica la palette e continua allo sfondo. L’anteprima usa il renderer animato quando il movimento è consentito.
## Interfaccia Selene e input
-`SeleneCanvas` scala il canvas 1920×1080 nello spazio disponibile. `SeleneCanvasEnvironment` espone unità e font alle viste. `SeleneTheme` ricava colori e curve di animazione dalla palette. `MaterialIcon` elenca i glifi, mentre `SeleneFonts` registra il font e li rende in SwiftUI.
-
-I componenti condivisi in `Views/Components` disegnano righe, switch, pill, focus, suggerimenti dei tasti, dialoghi e conferme. L'anello e il riflesso della tile selezionata (`SeleneTileRing`, `SeleneShine`) girano in Core Animation (`TileMotionLayers`): curve e campioni stanno in `TileMotion`, il bagliore è disegnato una volta da SwiftUI (`ImageRenderer`) e poi solo dissolto, così a schermo fermo l'app non ridisegna nulla tra un frame e l'altro. Con Reduce motion l'anello resta il disegno SwiftUI fermo. `SeleneBackdrop` combina gradiente, wallpaper e sfondo animato. `MoonlightRenderer` e `MoonlightShaders` rendono la componente Metal dell’interfaccia. `LiveBackdrop` usa AVFoundation per i video in loop.
-
-`GameControllerService` produce `GamepadAction` e riconosce i simboli dei tasti. La shell assegna l’input al livello attivo. `ButtonPrompts` esclude i segnaposto costituiti soltanto da forme, comprese varianti come `capsule.portrait.fill`, e usa in quel caso i simboli della marca riconosciuta; conserva glifi significativi come `circle.circle` e `square.circle`. `HoldDetector` e i modelli di focus rendono verificabili mapping e navigazione. `SoundEffectService` risolve i cue tramite `SeleneImporter` e applica le impostazioni di volume e attivazione.
-
-La preferenza Riduci movimento unisce l’impostazione dell’app a quella di sistema. Le viste consumano `seleneReduceMotion`, insieme agli altri valori dell’ambiente Selene.
+**Canvas, temi e componenti.**
+- `SeleneCanvas` scala il canvas 1920×1080 nello spazio disponibile, e `SeleneCanvasEnvironment` espone unità e font alle viste. `SeleneTheme` ricava colori e curve di animazione dalla palette. `MaterialIcon` elenca i glifi; `SeleneFonts` registra il font e li rende in SwiftUI.
+- I componenti condivisi in `Views/Components` disegnano righe, switch, pill, focus, suggerimenti dei tasti, dialoghi e conferme. Quando usarli è in [conventions.md](conventions.md#3-una-schermata-o-un-pannello-selene).
+
+**Suggerimenti dei tasti.**
+- Le barre `SeleneHintsBar` stanno a 32 unità Selene dal fondo (`SeleneBottomScrim.hintsBottom`). I simboli sono da 30 unità; solo Q/E e i corrispondenti LB/RB accanto ai filtri Achievements sono da 22, con area cliccabile di 30×36. Il margine sinistro aggiuntivo è 18.
+- Le schermate con la barra in un VStack riservano lo spazio nel layout. Spotlight e Achievements riservano invece una fascia trasparente di 84 unità e tengono il focus sopra la sfumatura inferiore.
+- In Details la barra è ancorata alla finestra: il contenuto sparisce prima dei comandi, e le fasce in focus salgono insieme alla barra. La stessa posizione vale per le opzioni, il visualizzatore di screenshot e le schermate Home.
+
+**Movimento.**
+- L'anello e il riflesso della tessera selezionata (`SeleneTileRing`, `SeleneShine`) girano in Core Animation (`TileMotionLayers`). Curve e campioni stanno in `TileMotion`; il bagliore si disegna una volta con SwiftUI (`ImageRenderer`) e poi si dissolve soltanto, così a schermo fermo l'app non ridisegna nulla tra un frame e l'altro. Con Riduci movimento l'anello resta il disegno SwiftUI fermo.
+- Un blocco che scorre per un offset animato passa da `GlideGroup` (`geometryGroup`, macOS 14): pagina Spotlight, pagina del gioco, lista Achievements, pannello Mod, riga Collection. *Perché:* SwiftUI trasmette l'offset a ogni elemento, e un'altra animazione nello stesso momento (una dissolvenza, un ventaglio, un'immagine che arriva) ne cambiava i tempi, così testi, icone e stelle scivolavano a velocità diverse. Il gruppo risolve lo scorrimento una volta per tutto il blocco, e un nuovo blocco che scorre deve usarlo. Su macOS 13 il blocco scorre senza gruppo.
+- La preferenza Riduci movimento unisce l'impostazione dell'app a quella di sistema. Le viste la leggono da `seleneReduceMotion`, insieme agli altri valori dell'ambiente Selene.
+
+**Sfondo.**
+- `SeleneBackdrop` combina gradiente, wallpaper e sfondo animato. Dentro la shell dichiara una `SeleneBackdropRequest` (stile, pausa, Mods e opacità); una sola istanza nella shell conserva il renderer attraverso i cambi di pagina. Le pagine continuano a possedere artwork e maschere. `ShellBackdropCover` assegna la precedenza a Setup, benvenuto e scelta tema: gli strati inferiori restano montati e caldi con opacità minima ma senza input, quelli superiori rimangono visibili. Il blur di opzioni/Add game/Console si applica anche al backdrop condiviso. Senza richiesta si conserva il frame e si ferma il movimento; fuori dalla shell il componente disegna autonomamente. La shell pubblica anche la palette completa in `SeleneBackdropStyle`: un cambio di soli colori invalida il valore condiviso anche con lo stesso wallpaper e la stessa card. Sfondo, superficie Metal e maschere leggono questo snapshot, evitando di aspettare un altro evento della pagina. `MoonlightRenderer` e `MoonlightShaders` rendono la parte Metal; `LiveBackdrop` usa AVFoundation per i video in loop.
+ - **Arcane** (ID storico `selene`) mantiene il blu classico come predefinito, con il gradiente radiale originale `0x102A5C` → `0x03081A`. Il fallback mantiene il gradiente lineare storico `0x17244A` → `0x0C142C` → `0x05080F`. **Arcane Crystal** (`arcane-crystal`) dispone fili diagonali; **Arcane Flow** (`arcane-flow`) usa curve più ampie. Entrambi mantengono soltanto filamenti e una luce diffusa tenue, senza piani o fasci luminosi. Il metadato opzionale `moonlight` della palette seleziona `MoonlightSurface`; palette senza metadato o con valore sconosciuto restano classiche. Nessuna nuova preferenza: il selettore e Look salvano lo stesso `colorThemeID`.
+ - I filamenti sono funzioni analitiche nello stesso passaggio Metal della luce: nucleo luminoso antialias di circa un pixel fisico, fili secondari più deboli ed estremi sfumati. Due onde viaggianti piegano le curve lungo la loro lunghezza, invece di spostare un bordo rigido; la forma di base varia su120/140s e i bagliori intorno a100–120s. Nei soli temi alternativi i dischi sfocati grandi sono attenuati per lasciare leggibili i fili. Rosa a sinistra e ciano a destra cambiano di pochi livelli RGB su180s (`MoonlightChromatics` condiviso col fallback), senza attraversare lo spettro. Nessuna immagine o video: il movimento appartiene alle superfici.
+ - Le particelle sono sempre morbide, senza un selettore: due stili quasi indistinguibili non giustificano una scelta in più. Il decoder ignora l’eventuale campo storico `particleStyle`, senza modificare le altre preferenze, e non lo riscrive.
+ - Colore e particelle avanzano con l’orologio del display link esistente, senza timer SwiftUI. Background motion spento e Riduci movimento tengono fermo l’orologio; il fallback senza Metal resta statico. Gli altri temi mantengono la loro palette. Le uniform interpolano superficie, variante Flow, tint e presenza; la cache dei campioni fermi comprende gli stessi valori. Le regole di pausa, Riduci movimento e passaggio all’artwork restano condivise nel percorso esistente. Senza Metal il ripiego mantiene soltanto bagliori statici nei colori locali.
+ - Nella Dev, la categoria locale `backdrop-transition` registra creazione e prima presentazione di ogni renderer, oltre all’apertura di Settings e allo stato del fullscreen iniziale. Non registra input o dati del giocatore.
+ - Le misure GPU fuori schermo e i loro limiti sono nella [nota del 17 novembre](reviews/2026-11-17-arcane-moonlight.md).
+- **Arte dei giochi.** `SeleneArtLayer` è una pila di `CALayer` animati nel render server.
+ - Ogni nuova immagine entra sopra ciò che si vede, che resta fermo sotto finché la nuova non è entrata. Così una dissolvenza interrotta riparte da ciò che è a schermo (niente salti, niente moonlight che traspare) e non scatta se il main thread è occupato.
+ - Ciò che un layer mostra durante una dissolvenza si calcola sull'orologio (`OpacityFade`, la stessa curva dell'animazione), non dal presentation layer, che per un layer aggiunto nello stesso passaggio non esiste ancora. *Perché:* altrimenti due immagini in fila fanno saltare la prima a piena opacità.
+ - Scorrendo veloce, i livelli che lasciano passare meno di mezzo gradino a 8 bit (`ArtStack`) escono subito, così la pila resta di pochi livelli.
+ - Se tenere l'arte del gioco precedente lo decide `BackdropArtRule` sulla selezione che il body vede, così il primo render di una nuova selezione, prima di `onChange`, non toglie l'arte per poi rimetterla.
+ - Su una card Spotlight tiene l'arte dell'ultimo gioco senza mostrarla (`loadHero(keepsWithoutGame:)`), così tornare allo stesso gioco non ricarica nulla.
+- **Card Mods.**
+ - Con la card selezionata lo sfondo non mostra arte: il moonlight sfuma in 1,2 s verso l'oro (`SeleneBackdrop.modsTint`), anche sopra una wallpaper, che resta ferma sotto.
+ - Colore e fondo oro sono uniform dello shader, che `MoonlightLayerView` interpola sul suo thread: la sfumatura non dipende dal main thread e il frame costa uguale. Da fermo il display link gira solo per la durata della sfumatura.
+ - Lasciando la card verso un gioco, l'oro resta finché l'arte del gioco non è arrivata (`SpotlightView.modsBackdrop`), così il passaggio è uno solo.
+ - Sopra una wallpaper il moonlight oro resta montato, nascosto e fermo finché non serve, ed entra ed esce con l'uniform `presence` sul suo thread.
+
+**Input e suoni.**
+- `GameControllerService` produce `GamepadAction` e riconosce i simboli dei tasti. La shell dà l'input al livello attivo.
+- `AppShellView.nativeDialogOwnsInput` dà precedenza a un alert in attesa (`alertMessage`), a `NSApp.modalWindow`, alla sheet nella finestra key o allegata alla finestra key/main. Controller, tastiera e disponibilità dei menu condividono questo controllo; la tastiera controlla anche la finestra dell'evento. Il controller scarta l'azione prima di inoltrarla a qualunque schermata o dialogo interno. *Perché:* il controller non attraversa i monitor `NSEvent` che già cedono la tastiera ai dialoghi nativi. `run_review.py` esegue il routing reale con stati sintetici, compreso il ritorno ai comandi dopo la chiusura.
+- `ButtonPrompts` esclude i segnaposto fatti solo di forme, comprese varianti come `capsule.portrait.fill`, e usa in quel caso i simboli della marca riconosciuta; conserva i glifi significativi come `circle.circle` e `square.circle`.
+- `HoldDetector` e i modelli di focus rendono verificabili mapping e navigazione.
+- `SoundEffectService` risolve i cue tramite `SeleneImporter` e applica volume e attivazione.
## Dati su disco
-I percorsi sono relativi alla home dell’utente. `Application Support/NXLibrary` corrisponde a `~/Library/Application Support/NXLibrary`.
+I percorsi sono relativi alla home. `Application Support/NXLibrary` è `~/Library/Application Support/NXLibrary`; la Dev usa la radice del suo profilo (`AppData`).
| Percorso | Contenuto e proprietario |
|---|---|
-| `Application Support/NXLibrary/library.json` e `.bak` | Catalogo e ultima copia valida, gestiti da `LibraryStore`. |
+| `Application Support/NXLibrary/library.json` e `.bak` | Input del formato precedente, conservati intatti dopo la conversione da `CatalogStore`. |
+| `Application Support/NXLibrary/catalog.json` e `.bak` | Catalogo comune e copia valida, gestiti da `CatalogStore` attraverso `CatalogRepository`. |
| `Application Support/NXLibrary/settings.json` | Impostazioni globali, gestite da `AppSettingsStore`. |
| `Application Support/NXLibrary/play-sessions.json` | Sessioni e tempi di gioco, gestiti da `PlaySessionStore`. Array semplice delle ultime 200 sessioni, leggibile anche dalle versioni precedenti. |
| `Application Support/NXLibrary/play-sessions-totals.json` | Tempo e ultima partita delle sessioni oltre le 200, per gioco: `totalDuration(for:)` e `lastPlayed(for:)` li sommano alle sessioni recenti. |
| `Application Support/NXLibrary/keys/prod.keys` | Chiavi importate da `KeyStore`, con permessi `0600`. |
-| `Application Support/NXLibrary/app-sizes.json` | Cache dimensioni dei bundle. |
+| `Application Support/NXLibrary/credentials/igdb.json` | Credenziali IGDB personali (`0600`, cartella `0700`), escluse dall'importazione Dev. |
+| `Application Support/NXLibrary/app-sizes.json` | Cache delle dimensioni dei bundle. |
| `Application Support/NXLibrary/workspaces/` e `Temp/` | Collegamenti alle sorgenti, workspace e app temporanee dei porting, quando l'app va sul volume del Mac (o su un volume che non accetta link simbolici). |
-| `Application Support/NXLibrary/artwork/` | Cache immagini, copertine, screenshot e miniature online. |
-| `Application Support/NXLibrary/metadata/` | Cache dei metadati dello store. |
+| `Application Support/NXLibrary/artwork/` | Cache di immagini, copertine, screenshot e miniature online. |
+| `Application Support/NXLibrary/metadata/` | Cache dei metadati dello store e delle proposte di IGDB, LaunchBox e TheGamesDB. |
+| `Application Support/NXLibrary/ratings/` | Cache dei voti (Wikidata, IGDB). |
| `Application Support/NXLibrary/artwork-picks/` e `metadata-picks.json` | Scelte manuali di immagini e campi. |
+| `Application Support/NXLibrary/app-icons//` | Icona originale dell'app del gioco, conservata da `AppIconWriter`. |
| `Application Support/NXLibrary/SeleneImports/` | Suoni, wallpaper, video e relativi crediti importati. |
| `Application Support/NXLibrary/SaveBackups//` | Snapshot datati, manifest e copie protettive. |
-| `Application Support/NXLibrary/Logs/.log` | Log di porting costruito dall’app. |
-| `~/Library/Application Support/nxnative//` | `env.txt`, `save`, eventuale `save_device`, cheats e dati runtime del motore. |
+| `Application Support/NXLibrary/Logs/.log` | Log del porting costruito dall'app. |
| `Application Support/NXLibrary/mods/.json` | Ordine, stato e origine GameBanana delle mod di un gioco, gestiti da `ModStore`. |
| `Application Support/NXLibrary/gamebanana/matches.json` | Pagina GameBanana scelta per ogni gioco, gestita da `GameBananaMatchStore`. |
-| `~/Library/Caches/NXLibrary/gamebanana/` | Cache delle risposte e delle immagini di GameBanana. |
+| `~/Library/Caches/NXLibrary/gamebanana/` | Cache delle risposte e delle immagini di GameBanana, comprese le copie dello store. |
+| `~/Library/Application Support/nxnative//` | `env.txt`, `save`, eventuale `save_device`, `save_user2`…`save_user8`, registro `save.users`, cheat, mod e dati runtime del motore. |
| `~/Library/Logs/nxnative/.log` | Log del gioco avviato. |
-| `/.app` | Prima installazione del gioco; default `~/Applications`. I rebuild aggiornano l'app nella sua posizione esistente. |
+| `/.app` | Prima installazione del gioco; default `~/Applications`. I rebuild aggiornano l'app nella sua posizione. |
| Accanto al gioco: `.nxlibrary-install-.json` | Ultima ricevuta di installazione per quel percorso, gestita da `BuildOutputInstaller`. |
| Accanto al gioco: `.nxlibrary-incoming-.app` | Preparazione temporanea quando il bundle pronto si trova su un altro volume. |
| `/.nxlibrary-build/workspaces//` e `Temp/` | Workspace e app temporanee dei porting quando la cartella delle app è su un altro volume (`BuildScratch`). |
-| `UserDefaults` del bundle NX Library | Percorsi ricordati, stato Setup, override toolchain e cache di alcuni controlli. |
-
-Nel repository, `.build/` contiene gli output SwiftPM. `work/Runtime` è il runtime preparato per il packaging, `work/release` contiene i prodotti di release e `dist/` il DMG di sviluppo. Queste cartelle sono escluse da Git. Il catalogo descrive i file versionati separatamente dai dati personali creati durante l’uso.
-
-## Aggiornamenti e distribuzione
-
-Il controllo manuale da menu macOS e About presenta `AppUpdateDialog` sia durante la richiesta sia al suo esito: versione corrente, nuova release con note scorrevoli, errore con Retry o progresso. Il dialogo ha priorità sull’input sottostante; frecce/controller scorrono le note e selezionano le azioni, Escape chiude. La chiusura durante il download lascia il trasferimento in corso. Una richiesta manuale durante un controllo automatico impedisce una successiva seconda offerta automatica per la stessa risposta. Le note mostrano la propria versione anche quando la candidata è più recente dell’ultima release pubblica.
-
-`AppUpdateState` descrive gli stati nel Core. `AppUpdate.mayInstall` impone versione più recente e copia installabile: i controlli manuali di copie di sviluppo o in sola lettura leggono le release, senza autorizzarne la sostituzione. Il gate viene verificato prima del download e prima dell’installazione, insieme ai controlli e ai lease già esistenti. Il motivo di attesa viene passato al dialogo come valore, così la chiusura di un gioco aggiorna il pulsante Update.
+| `UserDefaults` del bundle Arcane | Percorsi ricordati, stato del Setup, override della toolchain e cache di alcuni controlli. |
+I dati Steam di Arcane sono descritti in [steam.md](steam.md#dati-su-disco-di-arcane).
-`UpstreamChecker` consulta il changelog del motore e `UpstreamCopy` lo presenta. L’adozione di un nuovo commit passa dalla procedura manuale in [AGENTS.md](../AGENTS.md) e dalle [note di upgrade](upstream-upgrades/README.md).
+Nel repository, `.build/` contiene gli output SwiftPM, `work/Runtime` il runtime preparato per il packaging, `work/release` i prodotti di release e `dist/` il DMG di sviluppo. Queste cartelle sono escluse da Git.
-`AppUpdater` coordina gli aggiornamenti di NX Library da `Bium23/NxLibrary`, senza autenticazione. Le regole di versione, requisiti, digest, identità del bundle e installazione sono in `AppUpdate`. Le copie di sviluppo non si sostituiscono. `AppUpdateDownload` limita il trasferimento alla dimensione dichiarata e agli host HTTPS di GitHub. `validate_update.py` verifica struttura e percorsi, poi estrae contando i dati effettivamente decompressi tramite il Python incluso; prima della sostituzione vengono controllati versione, marker, identificativo e firma del bundle. La firma ad hoc protegge il contenuto sigillato ma non identifica autonomamente il manutentore. La prova interattiva A → B resta necessaria.
-
-Prima dell’installazione, l’updater acquisisce un’esclusione globale dal `SaveOperationGate`: aspetta operazioni save/Play/installazioni attive e impedisce nuovi ingressi durante sostituzione e riavvio. Un recupero bloccato senza I/O attivo non impedisce l’aggiornamento. Il coordinatore esclude nuovi porting mentre l’app viene aggiornata.
-
-`bundle_runtime.sh` prepara Python e strumenti da `runtime.lock`, controlla gli hash e sistema i riferimenti Mach-O con `relink_macho.py`. `build_app.sh` compila e confeziona il bundle, risorse, plist e firma ad hoc. Il suo parametro di destinazione permette di preparare una copia temporanea prima della sostituzione della copia installata.
+## Aggiornamenti e distribuzione
-`release.sh` richiede albero pulito e runtime pronto, imposta versione e marker di release e crea ZIP e DMG. `--publish` abilita tag e pubblicazione GitHub con autorizzazione esplicita dell’utente. Il repository contiene anche `build_dmg.sh` per confezionare un bundle già costruito.
+**Dialogo degli aggiornamenti.**
+- Il controllo manuale (menu macOS e About) presenta `AppUpdateDialog` durante la richiesta e al suo esito: versione corrente, nuova release con note scorrevoli, errore con Retry, oppure avanzamento.
+- Il dialogo ha priorità sull'input sottostante: frecce e controller scorrono le note e scelgono le azioni, Escape chiude. Chiuderlo durante il download lascia il trasferimento in corso.
+- Una richiesta manuale durante un controllo automatico impedisce una seconda offerta automatica per la stessa risposta. Le note mostrano la propria versione anche quando la candidata è più recente dell'ultima release pubblica.
+
+**Regole di installazione.**
+- `AppUpdateState` descrive gli stati nel Core. `AppUpdate.mayInstall` richiede una versione più recente e una copia installabile: i controlli manuali di copie di sviluppo o in sola lettura leggono le release senza autorizzarne la sostituzione.
+- Il gate si verifica prima del download e prima dell'installazione, insieme ai controlli e ai lease esistenti. Il motivo dell'attesa arriva al dialogo come valore, così la chiusura di un gioco aggiorna il pulsante Update.
+
+**Download e verifica.**
+- `AppUpdater` coordina gli aggiornamenti da `Bium23/NxLibrary`, senza autenticazione. Le regole di versione, requisiti, digest, identità del bundle e installazione sono in `AppUpdate`.
+- La release si accetta solo se lo zip `NXLibrary-.zip` sta nel percorso di download di quel repository. `AppUpdate.successorRepository` (oggi `nil`) nomina un repository che può sostituirlo con un altro nome: GitHub reindirizza lì la vecchia API delle release, quindi anche i suoi asset sono accettati.
+- `AppUpdateDownload` limita il trasferimento alla dimensione dichiarata e agli host HTTPS di GitHub.
+- `validate_update.py` verifica struttura e percorsi, poi estrae contando i dati davvero decompressi tramite il Python incluso. Prima della sostituzione si controllano versione, marker, identificativo e firma del bundle.
+- La firma ad hoc protegge il contenuto sigillato ma non identifica da sola il maintainer.
+- `AppUpdate.install` copia il candidato in una cartella esclusiva `.arcane-update.*` sul volume di destinazione e scambia i bundle con `RENAME_SWAP`, mantenendo il nome corrente. Le copie già presenti accanto all’app non vengono usate né rimosse. L’app precedente va nel Cestino; se il Cestino fallisce, resta nella cartella esclusiva. Un errore prima dello scambio pulisce soltanto il candidato posseduto; la cartella finale si rimuove solo se vuota. *Perché:* nomi prevedibili come `(new)` e `(old)` possono appartenere al giocatore.
+- Prima dell'installazione l'updater ottiene un'esclusione globale dal `SaveOperationGate`: aspetta che finiscano le operazioni in corso su salvataggi, Play e installazioni e impedisce nuovi ingressi durante sostituzione e riavvio. Un recupero bloccato senza I/O attivo non impedisce l'aggiornamento. Il coordinatore esclude nuovi porting mentre l'app si aggiorna.
+
+**Nome del file alla chiusura.**
+- Lo zip dell'aggiornamento contiene sempre `NXLibrary.app`, perché le copie precedenti leggono quel nome, e l'installazione tiene il nome del file corrente. Il nome Arcane arriva al file alla chiusura.
+- `AppDelegate.applicationWillTerminate` chiede ad `AppBundleRename.target` se rinominare. Lo fa solo una copia release, non traslocata, che si chiama `NX Library.app`, in una cartella scrivibile senza un `Arcane.app` accanto.
+- Non rinomina mentre una build, un aggiornamento o un'operazione sui salvataggi usa ancora il bundle (`AppDelegate.isBusy`, impostato da `AppShellState`), né quando un riavvio è in programma (`AppDelegate.relaunchScheduled`, da Restart app e dall'updater): l'aiuto che riapre l'app usa il percorso attuale.
+- *Perché alla chiusura:* rinominare un bundle in esecuzione lascia `Bundle.main` sul percorso vecchio fino al riavvio. Il Dock segue la rinomina nella stessa cartella ([sonda](reviews/2026-11-17-dock-rename-probe.md)).
+- Un errore va nel log e non ferma la chiusura. La copia Dev non si rinomina mai: la ricostruisce `build_app.sh`.
+
+**Changelog dell'engine.** `UpstreamChecker` consulta il changelog del motore e `UpstreamCopy` lo presenta. L'adozione di un nuovo commit segue la procedura manuale di [AGENTS.md](../AGENTS.md) e delle [note di upgrade](upstream-upgrades/README.md).
+
+**Script di build e release.**
+- `bundle_runtime.sh` prepara Python e strumenti da `runtime.lock`, controlla gli hash e sistema i riferimenti Mach-O con `relink_macho.py`.
+- `build_app.sh` compila e confeziona bundle, risorse, plist e firma ad hoc, poi installa il bundle completo attraverso `BuildOutputInstaller` dopo firma e verifica. Il suo parametro di destinazione permette di preparare una copia temporanea prima di sostituire quella installata.
+- `release.sh` richiede un albero pulito e il runtime pronto, esegue suite Swift e tutti i controlli `Tests/CatalogAppChecks/run_*.py` senza UI, imposta versione e marker di release e crea ZIP e DMG. `--publish` abilita tag e pubblicazione su GitHub, solo con autorizzazione esplicita dell'utente. `build_dmg.sh` confeziona un bundle già costruito.
+- Il runtime e i contenuti versionati si verificano con `scripts/check_publication.py`.
## Verifica e manutenzione
-`NX_TEST_ENGINE_REPO` permette al controllo dei messaggi del motore di usare un checkout separato; il valore esplicito non valido produce un errore. Durante una revisione, `NX_TEST_ENGINE_COMMIT` seleziona l'hash completo del candidato prima di cambiare il pin dell'app; senza override il test controlla sempre il pin. La suite Core usa fixture sintetiche, directory temporanee, runner e confini I/O sostituibili. Copre modelli, persistenza, sorgenti, chiavi, contratti CLI, processi, installazione, lancio, UI state, artwork, cheats e transazioni dei salvataggi. Il [catalogo dei test](file-map.md#test-e-fixture) indica la responsabilità di ogni file.
+**Test.**
+- La suite Core usa fixture sintetiche, cartelle temporanee, runner e confini I/O sostituibili. Copre modelli, persistenza, sorgenti, chiavi, contratti CLI, processi, installazione, lancio, stato della UI, artwork, cheat e transazioni dei salvataggi. Il [catalogo dei test](file-map.md#test-e-fixture) indica la responsabilità di ogni file.
+- `run_nup_programs.py` verifica i convertitori reali UI/persistenza e gli argomenti NUP; con uno snapshot
+ immutabile dell’engine verifica anche il probe Python su un contenitore sintetico. `run_save_restart.py`
+ arresta e riavvia processi distinti nei checkpoint di sostituzione e recovery, conservando backup e
+ dati non committed; non apre finestre né accede ai salvataggi del giocatore.
+- `NX_TEST_ENGINE_REPO` permette al controllo dei messaggi del motore di usare un checkout separato; un valore esplicito non valido è un errore. Durante una revisione, `NX_TEST_ENGINE_COMMIT` seleziona l'hash completo del candidato prima di cambiare il pin; senza override il test controlla sempre il pin.
```bash
DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer swift test
bash scripts/build_app.sh
-codesign --verify --deep --strict "$HOME/Applications/NXLibrary.app"
+codesign --verify --deep --strict "$HOME/Applications/Arcane Dev.app"
```
-Le prove interattive dell’app e dei giochi sono eseguite dall’utente. Gli agenti svolgono controlli sul codice, test automatici e build/installazione, secondo `AGENTS.md`.
+**Prove interattive.** Le esegue l'utente; gli agenti svolgono controlli sul codice, test automatici e build/installazione, secondo `AGENTS.md`.
-Per una modifica, partire dall’area nel catalogo, seguire il collegamento al file e leggere i chiamanti reali. Aggiornare la descrizione quando cambia la responsabilità di un file. I piani datati registrano il lavoro svolto, mentre questa guida e il catalogo descrivono l’organizzazione corrente.
+**Per una modifica.** Parti dall'area in questa guida e nel catalogo dei file, segui il collegamento al file e leggi i chiamanti reali. Segui la ricetta di [conventions.md](conventions.md) e aggiorna i documenti come dice la sua sezione 10.
diff --git a/docs/conventions.md b/docs/conventions.md
new file mode 100644
index 00000000..b8fee229
--- /dev/null
+++ b/docs/conventions.md
@@ -0,0 +1,127 @@
+# Arcane — come si costruisce
+
+Questa guida dice **dove va una cosa nuova e come si scrive**, partendo da quello che il codice fa già. Prima di scrivere codice nuovo, trova qui la ricetta che corrisponde e segui il file d'esempio indicato. Se nessuna ricetta va bene, non inventarne una in silenzio: proponila al maintainer e, una volta approvata, aggiungila qui.
+
+Gli altri documenti:
+- [architecture.md](architecture.md): come funziona ogni area;
+- [flows.md](flows.md): i percorsi completi, dall'input all'effetto;
+- [file-map.md](file-map.md): un file per riga;
+- [validation.md](validation.md): cosa ha validato il maintainer.
+
+## 1. Dove va il codice
+
+| Cosa | Dove | Perché |
+|---|---|---|
+| Modelli, regole, parsing, persistenza, rete, processi, decisioni di focus e di layout calcolabili | `Sources/NXLibraryCore` | Si prova con XCTest senza finestre. |
+| Viste SwiftUI, integrazione AppKit, controller, coordinamento degli store | `Sources/NXLibrary` | Dipende dal Core, mai il contrario. |
+| Testi mostrati all'utente | `NXLibraryCore/Resources/Localizable.xcstrings` | Un solo catalogo per le sei lingue. |
+| Test | `Tests/NXLibraryCoreTests`; prove senza finestre dei corpi reali delle viste in `Tests/CatalogAppChecks`; controlli del pacchetto in `Tests/PublicationChecks` | — |
+
+Regole:
+- **Una decisione sta nel Core se si può scrivere senza SwiftUI.** Esempi:
+ - quali righe mostra il pannello Details: `DetailsFacts`;
+ - dove si sposta il focus: `SpotlightState`, `DetailsFocus`, `ModStoreFocus`;
+ - la geometria di una riga: `SpotlightRowGeometry`, `GridListLayout`.
+
+ La vista disegna e traduce l'input.
+- **Non far crescere `AppViewModel`.** Uno stato che appartiene a una sola schermata o a un solo pannello ha il suo modello. Esempi: `SavePanelModel`, `SetupCheckModel`, `ModStoreHost`, `AchievementsScreenModel`, `CatalogSourcesModel`. Le estensioni `AppViewModel+…` servono solo a collegare il coordinatore a un servizio del Core.
+- **Un solo writer per ogni file su disco.** Il catalogo lo scrive solo `CatalogRepository`, le impostazioni solo `AppSettingsStore`, le sessioni solo `PlaySessionStore`, le mod di un gioco solo `ModStore`.
+
+## 2. Una fonte di giochi (Steam oggi, CrossOver e altre domani)
+
+Esempio completo: Steam, documentato in [steam.md](steam.md).
+
+- Il gioco entra nel catalogo comune come `CatalogGame` con il **suo payload reale** (`SteamCatalogGame`, `PortedGame`). Non si costruisce mai un gioco di un'altra fonte finto.
+- Cosa offre la pagina lo dice `CatalogGamePresentation`: installazioni, operazioni supportate, `CatalogLaunchTarget`. L'ordine delle Opzioni comuni sta in `CatalogGameOptions`. Una fonte dichiara cosa sa fare; non aggiunge schermate parallele.
+- I comandi di una fonte ricevono solo il suo payload: i comandi Switch prendono `PortedGame`, quindi non possono partire da un gioco Steam.
+- La lettura avviene su un worker annullabile, con limiti di dimensione e di cartelle. Il risultato porta una generazione o un ticket, e un risultato superato non si pubblica (`SteamCatalogReconciler`, `CatalogSourcesModel`).
+- Un'assenza non è una cancellazione. Un disco scollegato, una scansione parziale o un titolo ambiguo conservano la voce, gli UUID e le scelte personali.
+- I file di altre applicazioni si leggono e non si scrivono mai. Le letture protette passano da `InstallationFileSnapshot` e `InstallationDirectorySnapshot`.
+- La fonte è facoltativa: se è spenta non si legge nulla e il resto si comporta come prima.
+- **La funzione sta nell'app, il formato sta nella fonte.** Salvataggi, mod e cheat sono una sola schermata ciascuno; la fonte dice dove sono i file e come si leggono.
+
+## 3. Una schermata o un pannello Selene
+
+Esempi: `AchievementsScreen` con `AchievementsScreenModel` (schermata intera), `SavesPanel` con `SavePanelModel` (pannello), `ModStorePage` con `ModStoreHost` (pagina che scorre).
+
+- **Misure in unità del canvas** 1920×1080: `canvas.u(…)` da `SeleneCanvasEnvironment`, mai punti fissi. Colori, curve e font vengono da `SeleneTheme` e `SeleneFonts`, le icone da `MaterialIcon`.
+- **Componenti condivisi prima di tutto** (`Views/Components`):
+ - `SeleneOptionRow`, `SeleneSettingsRow`;
+ - `SelenePillButton`, `SeleneSwitch`, `SeleneValueChip`;
+ - `SeleneConfirmDialog`, `SeleneSuccessNotice`;
+ - `SeleneHintsBar`, `GamePrimaryActions`, `DetailsPanel`.
+
+ Un componente nuovo nasce solo se nessuno di questi va bene.
+- **Focus nel Core, input in un file `+Input`.** Lo stato del focus è un tipo del Core con i suoi test. La vista ha un'estensione `…+Input.swift` che traduce tastiera, mouse e controller in azioni sul modello.
+- **Priorità dell'input:** menu e dialoghi nativi vengono prima delle schermate dell'app. La shell (`AppShellView`, `nativeDialogOwnsInput`) sospende il controller prima del routing e condivide il controllo con tastiera e menu. Nell'app dà l'input al livello più alto: un pannello sopra la pagina sospende l'input della pagina sotto.
+- **Suggerimenti dei tasti:** `SeleneHintsBar` alla posizione condivisa `SeleneBottomScrim.hintsBottom` (32 unità dal fondo). I simboli vengono da `ButtonPrompts`.
+- **Movimento:**
+ - un blocco che scorre di un offset animato passa per `GlideGroup`;
+ - i loop continui (anelli, bagliori, sfondi) girano in Core Animation o Metal, mai con timer SwiftUI a 30 fps;
+ - Riduci movimento si legge da `seleneReduceMotion` e ferma tutto ciò che si muove da solo.
+- **Suoni:** `SoundEffectService` con i cue Selene esistenti.
+- **Testi:** frasi brevi e semplici, nelle sei lingue (sezione 7).
+
+## 4. Un'impostazione
+
+Esempio: qualunque riga di `SettingsCatalog`.
+
+1. Il valore sta in `AppSettings`, con un default. La decodifica è **compatibile**: un file vecchio senza il campo prende il default, e un valore sconosciuto torna ad Automatic.
+2. La riga si dichiara in `SettingsCatalog` (`row`/`action`) con identità stabile, sezione, titolo e descrizione. Così compare in **Search** e in **Changed** e torna al valore iniziale con il reset del gruppo.
+3. Va nella sezione giusta di `SettingsSection` / `SettingsSidebarGroup`. Una sezione di piattaforma contiene solo impostazioni che agiscono sui giochi di quella piattaforma. Ogni impostazione sta in un solo posto.
+4. Le preferenze fuori da `AppSettings`, come cloud o percorsi, compaiono in Changed attraverso il catalogo. Le credenziali non passano mai da `AppSettings` (sezione 6).
+
+## 5. Un file su disco
+
+Esempi: `AppSettingsStore`, `CatalogStore`, `PlaySessionStore`, `ModStore`.
+
+- **Percorsi solo da `AppData`** (`AppData.supportRoot`, `AppData.cacheRoot`, `AppData.preferences`), così la copia Dev resta separata dalla release. Un file nuovo che la Dev deve ricevere va aggiunto alla lista dichiarata di `DevelopmentProfileImporter`; credenziali e token non si copiano.
+- **Formato con versione** e lettura compatibile con i file vecchi; un campo nuovo è sempre facoltativo.
+- **Scrittura sicura:** si scrive su un file temporaneo nella stessa cartella e lo si sostituisce in un passo solo. Per un file importante si tiene una copia valida (`.bak`) e si rilegge il candidato prima di pubblicarlo (`CatalogStore`).
+
+ Oggi ogni store scrive per conto suo: non esiste un aiuto condiviso. Un nuovo store segue `CatalogStore` per i dati importanti e `AppSettingsStore` per le preferenze.
+- **Un file illeggibile non si sovrascrive in silenzio:** si conserva e si segnala con un dialogo e Retry. Mai una libreria vuota automatica.
+- **Eliminare:** si sposta nel Cestino, salvo nei casi documentati. Esempi: la cache di build di un gioco, le cartelle temporanee riconosciute da `BuildScratch.isManaged`.
+
+## 6. Rete, chiavi e dati privati
+
+Esempi: `BoundedDownload`, `GameBananaClient`, `IGDBClient`, `SteamMetadataService`.
+
+- Ogni download passa da `BoundedDownload`, con limite di dimensione, redirect rifiutati e annullamento. Gli host sono fissati in un elenco.
+- Richieste coalescenti, un numero massimo in contemporanea, cache su disco con una durata, e uso della copia salvata senza rete. Un errore non diventa un "non trovato" salvato in cache.
+- Un risultato che arriva tardi (dopo un cambio di gioco o di lingua, o dopo la rimozione delle credenziali) non si pubblica.
+- **Chiavi e credenziali** in un file con modo `0600`, dentro una cartella `0700`. Non vanno mai in log, URL, `AppSettings` o `UserDefaults`. `DiagnosticsReport` toglie la home e i valori che sembrano chiavi.
+- Nessun dato personale o privato va in rete, e nessun dato dei giochi altrui viene scritto.
+
+## 7. Testi e lingue
+
+- Ogni testo dell'interfaccia passa da `L10n.text` / `L10n.format` e sta in `Localizable.xcstrings` con en, it, fr, de, es e pt-BR.
+- Le identità restano in inglese e non si traducono: rawValue salvati, rowID, variabili `DM_*`, eventi dell'engine.
+- Le viste leggono la lingua da `nxAppLocale`, così un cambio di lingua non ricrea stato o focus.
+- Controllo: `scripts/check_localizations.py`, che verifica copertura, segnaposto e plurali.
+
+## 8. Lavoro in background e stato
+
+- Il lavoro su file e rete gira fuori dal thread principale; ciò che cambia l'interfaccia si pubblica sul main actor.
+- Un `body` e l'initializer di una vista non leggono file: si ridisegnano a ogni cambio della shell. Ciò che viene dal disco si legge quando la pagina si apre o quando può cambiare (`GameOptionsFiles`, `GameDetailView.reloadCheats`), e un'assenza si ricorda (`GameIconProvider`).
+- Ogni lavoro annullabile porta un'identità (generazione, ticket, UUID del gioco). Il risultato si applica solo se l'identità è ancora quella attuale.
+- Le operazioni su un gioco che si escludono a vicenda (salvataggi, Play, installazioni, aggiornamento dell'app) passano da `SaveOperationGate`.
+- Niente ritardi a tempo, ridisegni forzati o errori nascosti per far "sembrare" che funzioni (AGENTS.md).
+
+## 9. Test
+
+- Prima il test che fallisce, poi il codice (TDD). Per un bug: prima la causa, poi un test che la riproduce.
+- I dati sono sintetici, in cartelle temporanee, con dipendenze sostituibili: `CommandRunner`, trasporti di rete iniettati, `SaveTestHome`, `SteamTestSupport`, `CatalogTestSupport`. Niente file reali dell'utente, niente chiavi o ROM.
+- Si prova il comportamento, non il mock.
+- Comandi in [development.md](development.md#verification). I test non sostituiscono la validazione del maintainer.
+
+## 10. Documentazione
+
+Ogni modifica aggiorna, nello stesso commit:
+- la riga del file in [file-map.md](file-map.md) e il totale;
+- la sezione della sua area in [architecture.md](architecture.md), o il documento dell'area (come [steam.md](steam.md));
+- il percorso in [flows.md](flows.md), se cambia un flusso;
+- [validation.md](validation.md), se il maintainer ha validato qualcosa o se c'è una cosa nuova da validare;
+- questa guida, se nasce una ricetta nuova approvata.
+
+I documenti descrivono il **presente**. Lo storico ("prima faceva…") va nel [CHANGELOG](../CHANGELOG.md), nelle note datate (`docs/upstream-upgrades/`, `docs/reviews/`) o nella cronologia git. Il **perché** di una scelta resta invece accanto alla scelta, in una frase.
diff --git a/docs/development.md b/docs/development.md
index d911e2f9..c27af3be 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -1,6 +1,6 @@
# Development and releases
-This guide covers building NX Library itself. For app setup, game preparation and daily use, start with the [user guide](../README.md). Read [AGENTS.md](../AGENTS.md) before changing engine integration or installation behaviour.
+This guide covers building Arcane itself. For app setup, game preparation and daily use, start with the [user guide](../README.md). Read [AGENTS.md](../AGENTS.md) before changing engine integration or installation behaviour.
## Development prerequisites
@@ -19,12 +19,12 @@ From the repository root:
~~~sh
bash scripts/bundle_runtime.sh
bash scripts/build_app.sh
-codesign --verify --deep --strict "$HOME/Applications/NXLibrary Dev.app"
+codesign --verify --deep --strict "$HOME/Applications/Arcane Dev.app"
~~~
-The default destination is `~/Applications/NXLibrary Dev.app`, named **NX Library Dev**: the copy every change is tested in, kept apart from the released **NX Library** (`~/Applications/NX Library.app`, installed from GitHub and updated by itself), which a development build never replaces. Both use the bundle ID `local.nxlibrary`, so they share the library, keys and settings, and macOS runs only one at a time: quit one before opening the other. `build_app.sh` compiles the Release configuration, creates the bundle in staging, includes resources and notices, ad-hoc signs and verifies it, then installs it through the same atomic installer used by the application. It does not launch the app.
+The default destination is `~/Applications/Arcane Dev.app`, named **Arcane Dev**: the copy every change is tested in, kept apart from the released copy (`~/Applications/NX Library.app`, installed from GitHub and updated by itself), which a development build never replaces. On the launcher-development branch, Dev uses bundle ID `local.nxlibrary.development`, app data under `~/Library/Application Support/NXLibrary-Development`, a separate cache root and preference domain. At its first launch it prepares an independent, one-time copy of selected launcher data; games and build caches are not copied, and credential files are excluded. Close the previous launcher copy before that initial import. The held 0.1.4.3 branch retains its previously validated behavior. `build_app.sh` compiles the Release configuration, creates the bundle in staging, includes resources and notices, ad-hoc signs and verifies it, then installs it through the same atomic installer used by the application. It does not launch the app.
-A development copy carries the version in progress from the `VERSION` file at the repository root and shows it as "(development build)" in Settings; it has no release marker, so it never offers or installs app updates. `scripts/release.sh ` sets the released version itself and refuses to run unless `VERSION` already says that version. After a release, raise `VERSION` to the next version being worked on.
+A development copy carries the version in progress from the `VERSION` file at the repository root and shows it as "(Dev · Launcher)" on this development line in Settings; it has no release marker, so it never offers or installs app updates. `scripts/release.sh ` sets the released version itself and refuses to run unless `VERSION` already says that version. After a release, raise `VERSION` to the next version being worked on.
An alternate destination can be supplied without replacing the installed development copy:
@@ -32,7 +32,7 @@ An alternate destination can be supplied without replacing the installed develop
bash scripts/build_app.sh /tmp/NXLibrary-Review.app
~~~
-A plain development app uses bundle ID `local.nxlibrary`, defaults to version `0.1.0` and has no release marker. It never installs its own updates.
+A plain development app uses bundle ID `local.nxlibrary.development`, takes its version from `VERSION` and has no release marker. It never installs its own updates.
### Bundled runtime
@@ -59,8 +59,17 @@ python3 scripts/check_publication.py
python3 scripts/check_localizations.py
python3 -m unittest discover -s Tests/PublicationChecks
DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer swift test
+DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_notices.py
+DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_review.py
+DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_startup_recovery.py
+DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_theme.py
+DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_nested_bundles.py
+DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_artwork_return.py
+DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_source_access.py
+DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_entrance.py
+DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_achievement_scroll.py
bash scripts/build_app.sh
-codesign --verify --deep --strict "$HOME/Applications/NXLibrary Dev.app"
+codesign --verify --deep --strict "$HOME/Applications/Arcane Dev.app"
~~~
When reviewing an engine upgrade in a separate checkout, set `NX_TEST_ENGINE_REPO` to that checkout's absolute path for `swift test`. The engine-fragment regression reads the application's pin and checks it in that repository; an invalid explicit path fails. Without the variable it uses `~/nxnative`, skipping only when that default checkout is absent. This allows verification without fetching into or changing the engine used by the installed app.
@@ -73,13 +82,19 @@ python3 scripts/check_publication.py --runtime work/Runtime
The Swift suite covers persistence, sources, keys and permissions, CLI contracts, process output and cancellation, compatibility gates, installation and retries, launch configuration, presentation state, artwork, cheats and save recovery. Publication regressions use temporary repositories and synthetic content. Tests must never require copyrighted game content or real keys.
+The nested-bundle check creates tiny Mach-O fixtures with signed data bundles and relative Resources links. It exercises the real installer, icon writer and codesign, including signature rollback, interrupted publication and rejection of modified nested data. Its forced copy branch does not establish compatibility with a real external filesystem or game build.
+
+The artwork-return check compiles the real tile views, loading tasks and retained Mods host with generated images and isolated preferences. It records which image the first body selects after view recreation, without rendering or opening a window, and checks pick removal, Steam app updates, Mods badges after external removal and changed GameBanana matches. Network is forbidden in the Mods fixture.
+
The latest complete Swift verification on 2 November 2026 passed **774 tests**, including first-run skip/resume, setup navigation, explicit title choice, source-selection restoration, chosen-folder installation/discovery and preserving ready builds after destination disconnection. The earlier publication verification passed **15 Python checks**; the development-app bundle passed signature verification, and a headless check exercised a real public GitHub download, its redirect and rejection of a mismatched size. These checks do not establish that the interactive update or a game worked. This is dated evidence, not a promise about future changes. See the [test catalog](file-map.md#test-e-fixture).
For manual setup checks on an existing account, use **Settings → Start-up → Open Setup**: Continue opens Your games without resetting the library. Check file-picker cancellation, Back, Open library and source review. A fresh account additionally verifies Skip persistence and resuming an interrupted first setup. Interactive checks remain the user's responsibility; agents do not launch the UI.
+`release.sh` runs the same `CatalogAppChecks/run_*.py` set after the Swift suite and stops if any check fails. These checks use synthetic inputs without opening windows; the NUP engine-snapshot probe remains optional.
+
### Continuous integration
-The [Checks workflow](../.github/workflows/ci.yml) runs publication checks and their regressions, Swift tests, Release compilation, development-app packaging and signature verification on the `xcode-27` runner. Pull requests from forks stay off that runner and receive the hosted publication checks instead. The checkout action is pinned, repository permissions are read-only and credentials are not retained by checkout. It does not publish releases or run the UI, games or engine builds.
+The [Checks workflow](../.github/workflows/ci.yml) runs publication checks and their regressions, Swift tests, all `Tests/CatalogAppChecks/run_*.py` headless regressions, Release compilation, development-app packaging and signature verification on the `xcode-27` runner. Pull requests from forks stay off that runner and receive the hosted publication checks instead. The checkout action is pinned, repository permissions are read-only and credentials are not retained by checkout. It does not publish releases or run the UI, games or engine builds.
The engine-log-fragment test skips when `~/nxnative` is absent. A private CI run completed with **703 Swift tests reported: 702 passed and one skipped**, plus five Python checks. It verifies frontend packaging without the bundled game runtime; it does not replace the runtime check or the engine compatibility gate.
@@ -87,7 +102,7 @@ The engine-log-fragment test skips when `~/nxnative` is absent. A private CI run
Interactive app and game checks are performed by the user. Agents must not use computer-use or other UI automation. Compilation, unit tests and signature verification cannot establish that the interface or a game works.
-Before a game/toolchain combination is described as working, the user checks **Settings → Engine**, builds a real game and launches it to a visible screen. Record the engine and Metal versions and whether the untested override was used.
+Before a game/toolchain combination is described as working, the user checks **Settings → Setup and engine**, builds a real game and launches it to a visible screen. Record the engine and Metal versions and whether the untested override was used.
## Engine upgrades
@@ -107,6 +122,8 @@ bash scripts/release.sh 0.1.2
The script builds a release-marked app, verifies its version and signature, and produces a ZIP and DMG in `work/release/`. Without `--publish`, it does not push a tag or create a GitHub release. Version `0.1.0` is the first public alpha; use an unused version for later releases.
+Valve's attribution for the Steam logo carries the year Valve's page gives ("©2026 Valve Corporation…", https://partner.steamgames.com/doc/marketing/branding/attribution). In a new year, copy Valve's current wording for each language into `NOTICE` and the `Localizable.xcstrings` entry used by Settings › About before releasing.
+
Publishing requires an explicit maintainer decision and the script's `--publish --notes ` options. Prepare reviewed notes from [CHANGELOG.md](../CHANGELOG.md), then date the version when it is actually published. The script adds engine/Xcode requirement metadata to release notes for the updater. Never publish automatically as part of an agent's verification.
### Distribution work still open
@@ -141,8 +158,22 @@ These are distribution decisions. Do not bypass the dirty-tree check, change the
| `scripts/` | Runtime preparation, app packaging, installation helpers, release packaging and publication checks. |
| `docs/` | Current guides, audits, dated designs and engine-adoption evidence. |
-For component interactions, read the [architecture guide](architecture.md). For the role of every individual file, use the [file catalog](file-map.md). Screenshots and demo placement are described in the [media guide](media/README.md).
+For component interactions, read the [architecture guide](architecture.md); for where new code goes, the [conventions](conventions.md); for end-to-end paths, the [flows](flows.md). For the role of every individual file, use the [file catalog](file-map.md). Screenshots and demo placement are described in the [media guide](media/README.md).
### Localization resources
SwiftPM processes the shared string catalog into `NXLibrary_NXLibraryCore.bundle`. `build_app.sh` requires and copies that bundle into `Contents/Resources`, declares the six supported app languages and validates the compiled strings/plurals before signing. `scripts/check_localizations.py --app ` verifies the same resources independently. Missing resources or placeholder mismatches fail packaging. Locale selection is independent from each game's DM_LANG setting.
+
+### Isolated launcher-development data
+
+`AppDataProfile` selects immutable roots from the explicit build marker, and `AppData` routes app-owned stores/default preferences through that policy. `DevelopmentStartupView` completes the background import before constructing app stores or the shell. A failure shows Retry/Close; it never opens a writable fallback on the release profile. A changed legacy library with a valid catalog also offers **Keep Arcane’s library**: it archives the catalog, backup and legacy inputs before acknowledging the changed fingerprint, keeping the catalog’s games and sources without merging older changes. `run_startup_recovery.py` exercises this coordinator using a synthetic profile without windows. The source is read directly, not through store load/recovery methods. A staged, hashed allowlist copy and preference import can resume after failure; a completed profile is never automatically reimported. Copied unfinished sessions end at their last recorded heartbeat.
+
+After the import, `AppShellState` creates the view model and initial router and applies the initial locale/theme on the main actor before publishing the ready shell. Views retain these prepared objects; they do not run model startup or mutate shared theme state as SwiftUI inserts the shell into an already-visible window. Startup logs record only phase boundaries, without library contents or preference values.
+
+The separate bundle IDs select separate standard preference domains. Do not open the app's own bundle ID with `UserDefaults(suiteName:)`: Foundation rejects that suite. Packaging runs `scripts/check_app_profile.swift` in a temporary headless app with the built Info.plist, exercising the real preferences accessor and profile roots without starting UI, running the importer or writing data. Ordinary unit-test hosts do not reproduce the packaged app's identity.
+
+The Dev does not automatically import credentials or restore saves, reconcile app icons, install copied pending builds, sync real mod overlays, or sweep shared external staging. Explicit Dev icon/build requests are recorded in `DevelopmentOperationStore` and can resume on restart. When automatic mod maintenance is disabled, browsing reads the actual overlay without rewriting it or cleaning another profile's staging.
+
+The isolation covers launcher data, not the physical game installations and their saves. Explicit Play, game settings, builds, save/mod actions and cleanup still refer to real resources. Do not describe this as a sandbox of all game effects. Release packaging excludes the development marker, and the updater rejects a release that also selects the development profile. Initial Dev import and native interaction remain awaiting maintainer validation.
+
+Launch the packaged Dev for app checks: an unmarked executable cannot silently choose the stable data profile. Build markers and bundle identity must agree before the startup transaction opens any app store.
diff --git a/docs/file-map.md b/docs/file-map.md
index 05088619..112a59db 100644
--- a/docs/file-map.md
+++ b/docs/file-map.md
@@ -1,10 +1,10 @@
-# NX Library — catalogo dei file
+# Arcane — catalogo dei file
-Aggiornato il 3 novembre 2026. Copertura di **398 file** del progetto, compresi i controlli di pubblicazione, la CI, il master dell’icona, le guide per sviluppo e media, gli screenshot del README, l'integrazione di nxnative, il canale di aggiornamento e il setup in due passaggi con cartella unica per scoperta e installazione dei giochi. Le cartelle personali, gli output generati e gli appunti non versionati sono esclusi.
+Aggiornato il 18 novembre 2026. Copertura di **714 file** del progetto, compresi i controlli di pubblicazione, la CI con regressioni app senza UI, il master dell’icona, le guide per sviluppo e media, gli screenshot del README, l'integrazione di nxnative, il canale di aggiornamento e il primo avvio che parte da ciò che è già sul Mac, il setup del porting con cartella unica per scoperta e installazione dei giochi. Le cartelle personali, gli output generati e gli appunti non versionati sono esclusi.
La [guida tecnica](architecture.md) spiega come collaborano i componenti. Qui ogni riga identifica un file e la sua responsabilità. Le sezioni Core seguono le funzionalità, quelle UI seguono schermate e componenti. Le viste usano i modelli e i servizi del Core attraverso il coordinamento applicativo.
-Le cartelle generate `.build/`, `work/` e `dist/` e i dati personali in Application Support sono descritti nella guida. Per i piani datati, leggere anche le note finali di esecuzione e la specifica della funzionalità interessata.
+Le cartelle generate `.build/`, `work/` e `dist/` e i dati personali in Application Support sono descritti nella guida.
## Indice
@@ -16,10 +16,15 @@ Le cartelle generate `.build/`, `work/` e `dist/` e i dati personali in Applicat
- [Core · libreria, stato e sessioni](#core--libreria-stato-e-sessioni)
- [Core · Setup, motore e chiavi](#core--setup-motore-e-chiavi)
- [Core · sorgenti, porting, installazione e lancio](#core--sorgenti-porting-installazione-e-lancio)
-- [Core · cheats](#core--cheats)
+- [Core · cheat e mod](#core--cheat-e-mod)
- [Core · salvataggi e cloud](#core--salvataggi-e-cloud)
- [Core · artwork, metadati e sfondi online](#core--artwork-metadati-e-sfondi-online)
- [Core · presentazione Selene, focus e impostazioni](#core--presentazione-selene-focus-e-impostazioni)
+- [Core · catalogo comune e fonti](#core--catalogo-comune-e-fonti)
+- [Core · Steam](#core--steam)
+- [Core · achievement](#core--achievement)
+- [Core · lingua e testi](#core--lingua-e-testi)
+- [Core · profilo dei dati](#core--profilo-dei-dati)
- [UI · Add Game e porting](#ui--add-game-e-porting)
- [UI · Spotlight](#ui--spotlight)
- [UI · Collection e Details](#ui--collection-e-details)
@@ -28,6 +33,8 @@ Le cartelle generate `.build/`, `work/` e `dist/` e i dati personali in Applicat
- [UI · Setup, avvio, ricerca e console](#ui--setup-avvio-ricerca-e-console)
- [UI · componenti condivisi](#ui--componenti-condivisi)
- [UI · temi, rendering e sfondi](#ui--temi-rendering-e-sfondi)
+- [UI · fonti, Steam e libreria mista](#ui--fonti-steam-e-libreria-mista)
+- [UI · achievement](#ui--achievement)
- [Test e fixture](#test-e-fixture)
- [Script di sviluppo e packaging](#script-di-sviluppo-e-packaging)
- [Risorse incluse](#risorse-incluse)
@@ -40,33 +47,38 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| File | Responsabilità |
|---|---|
+| [.github/FUNDING.yml](../.github/FUNDING.yml) | Collega il pulsante Sponsor del repository alla pagina Buy Me a Coffee di Arcane. |
| [.gitignore](../.gitignore) | Esclude output di build, bundle, cache, work e file personali dell’IDE dal versionamento. |
| [AGENTS.md](../AGENTS.md) | Definisce vincoli per gli agenti, procedura di upgrade del motore e verifiche assegnate all’utente. |
-| [CHANGELOG.md](../CHANGELOG.md) | Registra le modifiche visibili all'utente per release; Unreleased raccoglie il lavoro non ancora pubblicato. |
-| [LICENSE](../LICENSE) | Contiene la licenza MIT di NX Library. |
-| [NOTICE](../NOTICE) | Conserva attribuzioni e provenienza dei componenti e dei riferimenti riutilizzati. |
+| [CHANGELOG.md](../CHANGELOG.md) | Registra le modifiche visibili all'utente per versione. |
+| [LICENSE](../LICENSE) | Contiene la licenza MIT di Arcane. |
+| [NOTICE](../NOTICE) | Conserva attribuzioni del motore al pin corrente, dei componenti, dei loghi e delle altre risorse riutilizzate. |
| [Package.swift](../Package.swift) | Dichiara i target SwiftPM, le loro dipendenze e il deployment macOS minimo. |
-| [README.md](../README.md) | Presenta l'app con logo e badge, guida d'uso, requisiti, risoluzione dei problemi, crediti e note legali. |
+| [README.md](../README.md) | Presenta Arcane come libreria e launcher Mac, con guide, requisiti, sostegno volontario, crediti e note legali. |
| [runtime.lock](../runtime.lock) | Fissa versioni, download e hash del runtime Python e degli strumenti inclusi nel bundle. |
+| [VERSION](../VERSION) | Versione in sviluppo usata dal packaging e verificata dalla procedura di release. |
## Ingresso e shell dell’app
| File | Responsabilità |
|---|---|
| [Sources/NXLibrary/NXLibraryApp.swift](../Sources/NXLibrary/NXLibraryApp.swift) | Punto @main, finestra SwiftUI, notifiche interne e comandi della barra menu. |
-| [Sources/NXLibrary/AppDelegate.swift](../Sources/NXLibrary/AppDelegate.swift) | Registra Material Icons e gestisce il ciclo di chiusura e riapertura della finestra. |
+| [Sources/NXLibrary/AppDelegate.swift](../Sources/NXLibrary/AppDelegate.swift) | Registra Material Icons, gestisce il ciclo della finestra, completa la scrittura della selezione alla chiusura e dà a una copia release il nome `Arcane.app`. |
| [Sources/NXLibrary/Views/MainView.swift](../Sources/NXLibrary/Views/MainView.swift) | Presenta AppShellView come contenuto della finestra principale. |
-| [Sources/NXLibrary/Views/Shell/AppShellView.swift](../Sources/NXLibrary/Views/Shell/AppShellView.swift) | Possiede lo stato condiviso, compone schermate e overlay e assegna priorità all’input. |
+| [Sources/NXLibrary/Views/Shell/AppShellView.swift](../Sources/NXLibrary/Views/Shell/AppShellView.swift) | Possiede il backdrop persistente e aggiorna le richieste delle pagine e la palette nello snapshot reattivo, possiede lo stato condiviso, passa a Spotlight il modello Mods della shell, compone schermate e overlay (compreso il benvenuto in Arcane) e assegna priorità all’input; `nativeDialogOwnsInput` sospende controller, tastiera e comandi dei menu sotto alert e selettori nativi. |
| [Sources/NXLibrary/Views/Shell/FullscreenCursorView.swift](../Sources/NXLibrary/Views/Shell/FullscreenCursorView.swift) | Gestisce il cursore inattivo nella sola finestra fullscreen del launcher, sospendendolo per pannelli e menu e ripristinando gli eventi al distacco. |
-| [Sources/NXLibrary/Views/Shell/StartupWindowView.swift](../Sources/NXLibrary/Views/Shell/StartupWindowView.swift) | Applica una sola volta alla finestra pronta la preferenza fullscreen letta al lancio. |
+| [Sources/NXLibrary/Views/Shell/StartupWindowView.swift](../Sources/NXLibrary/Views/Shell/StartupWindowView.swift) | Applica il fullscreen dopo la comparsa della finestra e segnala fine transizione o scadenza alla fase dell’entrata. |
| [Sources/NXLibrary/Views/Shell/MenuOverlayView.swift](../Sources/NXLibrary/Views/Shell/MenuOverlayView.swift) | Disegna il control center con azioni, focus e sottomenu Power. |
| [Sources/NXLibraryCore/NXLibraryCore.swift](../Sources/NXLibraryCore/NXLibraryCore.swift) | Espone la versione nominale del modulo Core. |
+| [LaunchReveal.swift](../Sources/NXLibrary/Views/Launch/LaunchReveal.swift) | Rende visibile la finestra al primo frame del moonlight, con dissolvenza e scadenza, poi consente il fullscreen; integra il bootstrap con un NSView non interattivo. |
+| [DevelopmentStartupView.swift](../Sources/NXLibrary/Views/Launch/DevelopmentStartupView.swift) | Avvio asincrono senza schermata di preparazione, recupero degli errori e scelta esplicita sul conflitto legacy prima di costruire la shell. |
+| [AppShellState.swift](../Sources/NXLibrary/Views/Shell/AppShellState.swift) | Prepara coordinatore, router, fonti, lingua e tema. Condivide lo store con il delegato alla chiusura e conserva la cover Mods durante la navigazione. |
## Coordinamento applicativo
| File | Responsabilità |
|---|---|
-| [Sources/NXLibrary/ViewModels/AppViewModel.swift](../Sources/NXLibrary/ViewModels/AppViewModel.swift) | Coordina libreria, sorgenti, ambiente, porting, log, impostazioni dei giochi e lancio. |
+| [Sources/NXLibrary/ViewModels/AppViewModel.swift](../Sources/NXLibrary/ViewModels/AppViewModel.swift) | Coordina libreria, sorgenti, ambiente, porting e lancio, inclusa la sincronizzazione delle mod prima di Play. Conserva scelta Steam del Setup e programma NUP, chiede notifiche al porting e non scansiona Game files all’avvio. |
| [Sources/NXLibrary/ViewModels/AppViewModel+Cheats.swift](../Sources/NXLibrary/ViewModels/AppViewModel+Cheats.swift) | Adatta Core e bundle installato al pannello Cheats, alla riga di stato e alla diagnostica. |
| [Sources/NXLibrary/ViewModels/AppViewModel+Mods.swift](../Sources/NXLibrary/ViewModels/AppViewModel+Mods.swift) | Crea lo `ModStore` di un gioco, il valore della riga Mods e le frasi per ogni errore. |
| [Sources/NXLibrary/ViewModels/AppViewModel+Controller.swift](../Sources/NXLibrary/ViewModels/AppViewModel+Controller.swift) | Conserva il contesto di gioco per i comandi e offre il collegamento alla cartella dei save. |
@@ -92,6 +104,7 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Sources/NXLibrary/Models/GameDetailsInfo.swift](../Sources/NXLibrary/Models/GameDetailsInfo.swift) | Ispeziona DLC e salvataggi del bundle e prepara dimensioni e dettagli del gioco. |
| [Sources/NXLibrary/Models/GamepadType.swift](../Sources/NXLibrary/Models/GamepadType.swift) | Definisce brand dei controller e azioni astratte GamepadAction. |
| [Sources/NXLibrary/Models/LogEntry.swift](../Sources/NXLibrary/Models/LogEntry.swift) | Rappresenta messaggi, livelli e identità delle righe di log mostrate dall’app. |
+| [Sources/NXLibrary/Models/PlayedGame.swift](../Sources/NXLibrary/Models/PlayedGame.swift) | Gioco nxnative o Steam per schermata di lancio e card di fine sessione. |
| [Sources/NXLibrary/Models/NXLibraryError.swift](../Sources/NXLibrary/Models/NXLibraryError.swift) | Raggruppa errori applicativi e relative spiegazioni, compresi i rifiuti prima del porting. |
| [Sources/NXLibrary/Models/SelectableGame.swift](../Sources/NXLibrary/Models/SelectableGame.swift) | Rappresenta le sorgenti selezionabili e l’ordinamento delle versioni nel wizard. |
| [Sources/NXLibrary/Models/UpstreamCheckState.swift](../Sources/NXLibrary/Models/UpstreamCheckState.swift) | Rappresenta gli stati del controllo del changelog upstream. |
@@ -100,13 +113,14 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| File | Responsabilità |
|---|---|
-| [Sources/NXLibrary/Services/AppUpdater.swift](../Sources/NXLibrary/Services/AppUpdater.swift) | Coordina controllo release, download, verifica, installazione e riavvio di NX Library. |
+| [Sources/NXLibrary/Services/AppUpdater.swift](../Sources/NXLibrary/Services/AppUpdater.swift) | Coordina controllo release, download, verifica, installazione e riavvio di Arcane. |
| [Sources/NXLibrary/Services/NativeMenuCommands.swift](../Sources/NXLibrary/Services/NativeMenuCommands.swift) | Coordina tracking, disponibilità nella scena e passaggio differito dai menu macOS alle azioni del launcher. |
| [Sources/NXLibrary/Services/GameControllerService.swift](../Sources/NXLibrary/Services/GameControllerService.swift) | Rileva controller e rimappature, gestisce tap e hold e produce azioni e simboli dei pulsanti. |
-| [Sources/NXLibrary/Services/LaunchReadinessProbe.swift](../Sources/NXLibrary/Services/LaunchReadinessProbe.swift) | Attende una finestra visibile del gioco per terminare la schermata di lancio. |
+| [Sources/NXLibrary/Services/LaunchReadinessProbe.swift](../Sources/NXLibrary/Services/LaunchReadinessProbe.swift) | Attende una finestra visibile del gioco (per bundle o, per Steam, per pid) per terminare la schermata di lancio. |
| [Sources/NXLibrary/Services/NotificationService.swift](../Sources/NXLibrary/Services/NotificationService.swift) | Invia notifiche dei porting e instrada i clic verso il titolo o l’errore interessato. |
| [Sources/NXLibrary/Services/OnlineBackgroundService.swift](../Sources/NXLibrary/Services/OnlineBackgroundService.swift) | Carica pagine e miniature e scarica wallpaper o video conservando progressi e crediti. |
| [Sources/NXLibrary/Services/RunningGameMonitor.swift](../Sources/NXLibrary/Services/RunningGameMonitor.swift) | Riconcilia applicazioni in esecuzione e libreria e offre Resume e chiusura del gioco. |
+| [Sources/NXLibrary/Services/LibraryWindow.swift](../Sources/NXLibrary/Services/LibraryWindow.swift) | Riporta davanti la finestra di Arcane dopo un gioco nxnative o Steam, mai sopra un gioco della libreria. |
| [Sources/NXLibrary/Services/SoundEffectService.swift](../Sources/NXLibrary/Services/SoundEffectService.swift) | Riproduce i cue Selene e applica attivazione, volume e file importati. |
| [Sources/NXLibrary/Services/SystemDetector.swift](../Sources/NXLibrary/Services/SystemDetector.swift) | Individua checkout nxnative, root personale e possibili percorsi delle chiavi. |
@@ -122,21 +136,22 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Sources/NXLibraryCore/Models/BackdropArt.swift](../Sources/NXLibraryCore/Models/BackdropArt.swift) | Regola che tiene l’arte del gioco precedente sullo sfondo Spotlight (`BackdropArtRule`) dissolvenza di un layer calcolata sull’orologio (`OpacityFade`) e livelli ormai coperti da togliere (`ArtStack`). |
| [Sources/NXLibraryCore/Models/TileMotion.swift](../Sources/NXLibraryCore/Models/TileMotion.swift) | Curve e campioni dei loop di ring, bagliore e riflesso della tile selezionata, sull'orologio condiviso. |
| [Sources/NXLibraryCore/Models/TextScroll.swift](../Sources/NXLibraryCore/Models/TextScroll.swift) | Scorrimento della colonna del pannello della mod: altezza della descrizione dopo Read more, limiti, riga a fuoco mostrata intera e passo Su/Giù che legge prima della riga seguente. |
-| [Sources/NXLibraryCore/Models/AppSettings.swift](../Sources/NXLibraryCore/Models/AppSettings.swift) | Definisce impostazioni globali, default e decodifica compatibile dei campi aggiunti nel tempo. |
-| [Sources/NXLibraryCore/Models/LibraryFilter.swift](../Sources/NXLibraryCore/Models/LibraryFilter.swift) | Definisce filtri, PlayHistory e LibraryQuery per ricerca e ordinamento dei giochi. |
+| [Sources/NXLibraryCore/Models/AppSettings.swift](../Sources/NXLibraryCore/Models/AppSettings.swift) | Definisce impostazioni globali, default e decodifica compatibile; ignora la scelta storica delle particelle. |
+| [Sources/NXLibraryCore/Models/LibraryFilter.swift](../Sources/NXLibraryCore/Models/LibraryFilter.swift) | Definisce filtri, PlayHistory e query condivisa per ricerca/ordine del catalogo misto, conservando l’API nxnative. |
| [Sources/NXLibraryCore/Models/LibrarySelectionState.swift](../Sources/NXLibraryCore/Models/LibrarySelectionState.swift) | Mantiene selezione e spostamento nel risultato filtrato della Collection. |
| [Sources/NXLibraryCore/Models/LibraryPresentation.swift](../Sources/NXLibraryCore/Models/LibraryPresentation.swift) | Formatta metadati e statistiche temporali per le schermate della libreria. |
| [Sources/NXLibraryCore/Models/GameDetailPresentation.swift](../Sources/NXLibraryCore/Models/GameDetailPresentation.swift) | Prepara badge, disponibilità delle azioni, date e dati della pagina Details. |
| [Sources/NXLibraryCore/Models/PlaySession.swift](../Sources/NXLibraryCore/Models/PlaySession.swift) | Descrive una sessione persistibile con gioco e riferimenti temporali. |
| [Sources/NXLibraryCore/Models/ActivitySummary.swift](../Sources/NXLibraryCore/Models/ActivitySummary.swift) | Aggrega sessioni, giorni e tempi della settimana per la scheda Activity. |
-| [Sources/NXLibraryCore/Models/MoreLikeThis.swift](../Sources/NXLibraryCore/Models/MoreLikeThis.swift) | Ordina i giochi correlati usando generi, sviluppatore e publisher. |
-| [Sources/NXLibraryCore/Services/LibraryStore.swift](../Sources/NXLibraryCore/Services/LibraryStore.swift) | Salva il catalogo con recupero; conserva lo stato nelle scansioni e sostituisce le sorgenti solo per una selezione esplicita. |
+| [Sources/NXLibraryCore/Models/MoreLikeThis.swift](../Sources/NXLibraryCore/Models/MoreLikeThis.swift) | Ordina i giochi correlati per generi, sviluppatore ed editore, con precedenza alla stessa fonte e ripiego facoltativo. |
| [Sources/NXLibraryCore/Services/ImportService.swift](../Sources/NXLibraryCore/Services/ImportService.swift) | Scansiona bundle nxnative e ne ricava identità, versione, percorso e dimensioni. |
| [Sources/NXLibraryCore/Models/CursorIdleState.swift](../Sources/NXLibraryCore/Models/CursorIdleState.swift) | Politica del ritardo di visibilità del puntatore e reset su mouse o perdita di eleggibilità. |
| [Sources/NXLibraryCore/Services/AppSizeCache.swift](../Sources/NXLibraryCore/Services/AppSizeCache.swift) | Conserva dimensioni per percorso e data del bundle e decide lo stato vuoto della libreria. |
-| [Sources/NXLibraryCore/Services/AppSettingsStore.swift](../Sources/NXLibraryCore/Services/AppSettingsStore.swift) | Pubblica impostazioni ed errori, preserva i file illeggibili e salva settings.json tramite file temporaneo. |
-| [Sources/NXLibraryCore/Services/PlaySessionStore.swift](../Sources/NXLibraryCore/Services/PlaySessionStore.swift) | Registra avvio, heartbeat, fine e riconciliazione delle sessioni di gioco. |
-| [Sources/NXLibraryCore/Navigation/AppRouter.swift](../Sources/NXLibraryCore/Navigation/AppRouter.swift) | Gestisce route, ritorno, menu, ricerca e richieste di selezione o spostamento su Spotlight. |
+| [Sources/NXLibraryCore/Services/AppSettingsStore.swift](../Sources/NXLibraryCore/Services/AppSettingsStore.swift) | Pubblica impostazioni ed errori, preserva i file illeggibili e salva settings.json in modo atomico. Tiene l'ultima selezione fuori dalle notifiche e la scrive in background. |
+| [Sources/NXLibraryCore/Services/PlaySessionStore.swift](../Sources/NXLibraryCore/Services/PlaySessionStore.swift) | Registra avvio, heartbeat, fine e riconciliazione delle sessioni di gioco; unisce i totali esterni (Steam) con le sessioni successive. |
+| [Sources/NXLibraryCore/Navigation/AppRouter.swift](../Sources/NXLibraryCore/Navigation/AppRouter.swift) | Gestisce route, ritorno, menu, ricerca e richieste Spotlight; ShellBackdropCover definisce quali strati sono coperti da Setup, benvenuto e scelta tema. |
+| [Sources/NXLibraryCore/Models/GameFocus.swift](../Sources/NXLibraryCore/Models/GameFocus.swift) | Quando un gioco che esce riporta Arcane davanti: solo se era l’app in primo piano e nessun altro gioco della libreria è aperto. |
+| [Sources/NXLibraryCore/Models/SessionSummary.swift](../Sources/NXLibraryCore/Models/SessionSummary.swift) | Cosa dice la card di fine sessione: gioco, durata di questa sessione e totale scritto come nelle info del gioco; niente card sotto i dieci secondi. |
## Core · Setup, motore e chiavi
@@ -146,18 +161,20 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Sources/NXLibraryCore/Models/ToolchainInfo.swift](../Sources/NXLibraryCore/Models/ToolchainInfo.swift) | Registra provenienza e verifica della toolchain associata a un build. |
| [Sources/NXLibraryCore/Models/ToolchainGateCopy.swift](../Sources/NXLibraryCore/Models/ToolchainGateCopy.swift) | Traduce il gate in testi distinguendo Metal certificato, precedente e successivo. |
| [Sources/NXLibraryCore/Models/SetupCheck.swift](../Sources/NXLibraryCore/Models/SetupCheck.swift) | Converte fatti e override del Setup in schede, stati, azioni e condizioni di riapertura. |
-| [Sources/NXLibraryCore/Models/FirstRunSetup.swift](../Sources/NXLibraryCore/Models/FirstRunSetup.swift) | Coordina pagine, completamento, ripresa del primo avvio, stato della scansione, focus e consumo unico delle selezioni avviate da Your games. |
+| [Sources/NXLibraryCore/Models/FirstRunSetup.swift](../Sources/NXLibraryCore/Models/FirstRunSetup.swift) | Coordina pagina e completamento del Setup, scelta Steam persistente fino alla fine, ripresa, focus e consumo unico delle selezioni da Your games. |
+| [Sources/NXLibraryCore/Models/FirstRunFindings.swift](../Sources/NXLibraryCore/Models/FirstRunFindings.swift) | Conta giochi Steam e app portate senza modifiche; distingue lettura incompleta da assenza e permette nuove letture annullabili. |
+| [Sources/NXLibraryCore/Models/ArcaneWelcome.swift](../Sources/NXLibraryCore/Models/ArcaneWelcome.swift) | Decide quando compare il benvenuto in Arcane, l'offerta di Steam, il focus e come ogni uscita lo segna visto. |
| [Sources/NXLibraryCore/Models/GameFoldersCopy.swift](../Sources/NXLibraryCore/Models/GameFoldersCopy.swift) | Condivide nomi delle cartelle, formati e descrizioni tra Setup, Settings e selettori dei percorsi. |
| [Sources/NXLibraryCore/Models/SetupGrid.swift](../Sources/NXLibraryCore/Models/SetupGrid.swift) | Calcola disposizione, centratura e navigazione del focus nella griglia del Setup. |
-| [Sources/NXLibraryCore/Models/UpstreamCopy.swift](../Sources/NXLibraryCore/Models/UpstreamCopy.swift) | Prepara i testi del changelog upstream e dell’adozione degli aggiornamenti tramite NX Library. |
+| [Sources/NXLibraryCore/Models/UpstreamCopy.swift](../Sources/NXLibraryCore/Models/UpstreamCopy.swift) | Prepara i testi del changelog upstream e dell’adozione degli aggiornamenti tramite Arcane. |
| [Sources/NXLibraryCore/Services/NXNativeEnvironment.swift](../Sources/NXLibraryCore/Services/NXNativeEnvironment.swift) | Ispeziona strumenti, Python, Xcode e Metal e restituisce uno stato dell’ambiente. |
| [Sources/NXLibraryCore/Services/EngineLocation.swift](../Sources/NXLibraryCore/Services/EngineLocation.swift) | Risolve checkout predefinito o scelto e produce i candidati per prod.keys. |
| [Sources/NXLibraryCore/Services/EngineToolchain.swift](../Sources/NXLibraryCore/Services/EngineToolchain.swift) | Individua runtime incluso o venv del checkout e prepara ambiente e PATH dei processi. |
-| [Sources/NXLibraryCore/Services/EnginePackageReader.swift](../Sources/NXLibraryCore/Services/EnginePackageReader.swift) | Legge capacità delle sorgenti e content meta di tutti i pacchetti in un solo passaggio del lettore upstream (`package_reader`, o `package_title_reader` sugli engine precedenti a 5c4dc18f), validando identità e tipi senza esporre chiavi. |
-| [Sources/NXLibraryCore/Models/BuildWarningCopy.swift](../Sources/NXLibraryCore/Models/BuildWarningCopy.swift) | Testo mostrato a fine build per una fase terminata con `warn` dell’engine (archivio delle pipeline mancante). |
+| [Sources/NXLibraryCore/Services/EnginePackageReader.swift](../Sources/NXLibraryCore/Services/EnginePackageReader.swift) | Legge content meta e capacità del checkout, compresa selezione NUP multiprogramma, senza esporre chiavi. |
+| [Sources/NXLibraryCore/Models/BuildWarningCopy.swift](../Sources/NXLibraryCore/Models/BuildWarningCopy.swift) | Testo mostrato a fine build per `warn` dell’engine: archivio mancante o pipeline da preparare al primo avvio. |
| [Sources/NXLibraryCore/Models/ReleaseNotesLayout.swift](../Sources/NXLibraryCore/Models/ReleaseNotesLayout.swift) | Divide le note di release in titoli, voci e testo, una riga per volta, per il dialogo degli aggiornamenti. |
| [Sources/NXLibraryCore/Services/NewestEngine.swift](../Sources/NXLibraryCore/Services/NewestEngine.swift) | Scelta dell’engine più nuovo: testi condivisi, lettura del Metal dal lock di main, cambio di commit con git senza toccare file modificati. |
-| [Sources/NXLibraryCore/Services/NUPSourceCatalog.swift](../Sources/NXLibraryCore/Services/NUPSourceCatalog.swift) | Riconosce i file NUP Switch 2 e ne elenca base, update e DLC tramite il lettore pack_nup dell’engine; accetta anche un NUP senza base (solo update). |
+| [Sources/NXLibraryCore/Services/NUPSourceCatalog.swift](../Sources/NXLibraryCore/Services/NUPSourceCatalog.swift) | Legge NUP con base o soli update; tiene distinti programma, applicazione e base DLC tramite il lettore upstream e conserva il default selezionato. |
| [Sources/NXLibraryCore/Services/DirectorySize.swift](../Sources/NXLibraryCore/Services/DirectorySize.swift) | Misura le cartelle con fts come du, così il refresh non resta bloccato su app grandi in dischi esterni (issue #2). |
| [Sources/NXLibraryCore/Services/NXNativeGameSettings.swift](../Sources/NXLibraryCore/Services/NXNativeGameSettings.swift) | Legge l’elenco impostazioni del build, i valori attuali e le chiavi fissate da env.txt. |
| [Sources/NXLibraryCore/Services/SavedChoicesStore.swift](../Sources/NXLibraryCore/Services/SavedChoicesStore.swift) | Legge e scrive le scelte salvate launcher. nel dominio preferenze dell’app gioco. |
@@ -174,8 +191,9 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| File | Responsabilità |
|---|---|
-| [Sources/NXLibraryCore/Models/GameFileItem.swift](../Sources/NXLibraryCore/Models/GameFileItem.swift) | Descrive sorgenti, tipo base/update/DLC, percorso, dimensione e metadati rilevati. |
-| [Sources/NXLibraryCore/Models/SourceSelection.swift](../Sources/NXLibraryCore/Models/SourceSelection.swift) | Gestisce scelta esplicita dei titoli, selezione e ripristino logico dei contenuti, DLC incorporati, dimensioni uniche, versione di build e requisiti del motore. |
+| [Sources/NXLibraryCore/Models/GameFileItem.swift](../Sources/NXLibraryCore/Models/GameFileItem.swift) | Sorgenti salvate con layout, requisiti e selezione NUP facoltativa, compatibile con i vecchi record. |
+| [NUPProgramSelection.swift](../Sources/NXLibraryCore/Models/NUPProgramSelection.swift) | Identità tipizzata del programma NUP, applicazione e base add-on; indice ricavato dal programma, persistito con i sorgenti. |
+| [Sources/NXLibraryCore/Models/SourceSelection.swift](../Sources/NXLibraryCore/Models/SourceSelection.swift) | Scelte dei contenuti, dimensioni e versione di build; verifica coerenza e supporto del programma NUP e ne vincola l’indice nel rebuild. |
| [Sources/NXLibraryCore/Models/BuildRecord.swift](../Sources/NXLibraryCore/Models/BuildRecord.swift) | Conserva esito, tempi, log e provenienza di un porting. |
| [Sources/NXLibraryCore/Models/TargetPlatform.swift](../Sources/NXLibraryCore/Models/TargetPlatform.swift) | Definisce il target mac-app e le sue etichette per l’interfaccia. |
| [Sources/NXLibraryCore/Models/GameRuntimeConfig.swift](../Sources/NXLibraryCore/Models/GameRuntimeConfig.swift) | Persiste opzioni per titolo, prepara Review e lingua del rebuild, mappa DM_* e unisce env.txt. |
@@ -183,18 +201,18 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Sources/NXLibraryCore/Models/AppIconProgress.swift](../Sources/NXLibraryCore/Models/AppIconProgress.swift) | Stati e testi della preparazione icona, con esito informativo aggiunto al log della build conclusa. |
| [Sources/NXLibraryCore/Models/IconLaunchWait.swift](../Sources/NXLibraryCore/Models/IconLaunchWait.swift) | Conserva una richiesta Play durante la firma dell'icona e la revoca su annullamento, errore o chiusura del dialogo. |
| [Sources/NXLibraryCore/Services/PipelineArchiveProgress.swift](../Sources/NXLibraryCore/Services/PipelineArchiveProgress.swift) | Legge il log pipeline della build corrente e conta solo i gruppi confermati pronti dal motore. |
-| [Sources/NXLibraryCore/Models/PortingProgress.swift](../Sources/NXLibraryCore/Models/PortingProgress.swift) | Aggrega eventi del motore in fasi e percentuale complessiva per la UI. |
-| [Sources/NXLibraryCore/Models/PortingPresentation.swift](../Sources/NXLibraryCore/Models/PortingPresentation.swift) | Definisce fallimento persistito, ETA, aspetto della tile e pill del porting. |
+| [Sources/NXLibraryCore/Models/PortingProgress.swift](../Sources/NXLibraryCore/Models/PortingProgress.swift) | Aggrega eventi del motore in fasi e percentuale complessiva; identifica archivio e prewarm senza dedurre conteggi dal tempo trascorso. |
+| [Sources/NXLibraryCore/Models/PortingPresentation.swift](../Sources/NXLibraryCore/Models/PortingPresentation.swift) | Definisce fallimento persistito, ETA, attività senza stima del prewarm, aspetto della tile e pill del porting. |
| [Sources/NXLibraryCore/Models/PortingFailureReason.swift](../Sources/NXLibraryCore/Models/PortingFailureReason.swift) | Classifica messaggi del motore e rifiuti preliminari in motivazioni e azioni spiegabili. |
| [Sources/NXLibraryCore/Models/PortingNotice.swift](../Sources/NXLibraryCore/Models/PortingNotice.swift) | Decide quando notificare l’esito di un porting e prepara il relativo messaggio. |
| [Sources/NXLibraryCore/Models/PendingInstall.swift](../Sources/NXLibraryCore/Models/PendingInstall.swift) | Conserva un bundle pronto in attesa e ne gestisce installazione, scarto e aggiornamento del record, anche dopo una pubblicazione interrotta. |
| [Sources/NXLibraryCore/Models/RunningGames.swift](../Sources/NXLibraryCore/Models/RunningGames.swift) | Confronta bundle ID e mantiene uno snapshot delle applicazioni in esecuzione. |
-| [Sources/NXLibraryCore/Services/SourceCatalog.swift](../Sources/NXLibraryCore/Services/SourceCatalog.swift) | Riconosce sorgenti NSP/XCI/NSZ/XCZ e raggruppa titoli, aggiornamenti e DLC. |
+| [Sources/NXLibraryCore/Services/SourceCatalog.swift](../Sources/NXLibraryCore/Services/SourceCatalog.swift) | Riconosce sorgenti NSP/XCI/NSZ/XCZ e raggruppa titoli, update e DLC; DetectedSource conserva la selezione NUP tipizzata. |
| [Sources/NXLibraryCore/Services/ExtractedSourceCatalog.swift](../Sources/NXLibraryCore/Services/ExtractedSourceCatalog.swift) | Verifica il layout di un gioco estratto, legge NPDM e profilo registrato e rileva update e DLC. |
| [Sources/NXLibraryCore/Services/WorkspaceManager.swift](../Sources/NXLibraryCore/Services/WorkspaceManager.swift) | Prepara collegamenti simbolici, verifica link interrotti e adotta workspace e cache esistenti. |
| [Sources/NXLibraryCore/Services/BuildScratch.swift](../Sources/NXLibraryCore/Services/BuildScratch.swift) | Sceglie dove stanno workspace e app temporanea (sul volume dell'app quando può ospitarli), riconosce i workspace gestiti e le cartelle temporanee da pulire. |
| [Sources/NXLibraryCore/Services/BuildCommand.swift](../Sources/NXLibraryCore/Services/BuildCommand.swift) | Valore con eseguibile, argomenti, ambiente e directory di lavoro del processo di porting. |
-| [Sources/NXLibraryCore/Services/BuildCommandBuilder.swift](../Sources/NXLibraryCore/Services/BuildCommandBuilder.swift) | Costruisce il contratto CLI nxnative, comprese destinazione Mac, JSON e override toolchain. |
+| [Sources/NXLibraryCore/Services/BuildCommandBuilder.swift](../Sources/NXLibraryCore/Services/BuildCommandBuilder.swift) | Contratto CLI nxnative: Mac, JSON, versione pacchetto, selezione --program esplicita e override toolchain. |
| [Sources/NXLibraryCore/Services/BuildEvent.swift](../Sources/NXLibraryCore/Services/BuildEvent.swift) | Definisce gli eventi di fase, step, avanzamento e log ricevuti dal motore. |
| [Sources/NXLibraryCore/Services/BuildEventParser.swift](../Sources/NXLibraryCore/Services/BuildEventParser.swift) | Decodifica eventi JSON e tratta le altre righe come log. |
| [Sources/NXLibraryCore/Services/BuildService.swift](../Sources/NXLibraryCore/Services/BuildService.swift) | Avvia il porting, gestisce processi, cancellazione, log ed eventi; conserva il bundle valido quando fallisce solo l’installazione. |
@@ -203,11 +221,12 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Sources/NXLibraryCore/Services/LaunchService.swift](../Sources/NXLibraryCore/Services/LaunchService.swift) | Scrive l’ambiente runtime e avvia il bundle del gioco tramite NSWorkspace. |
| [Sources/NXLibraryCore/Services/StorageManager.swift](../Sources/NXLibraryCore/Services/StorageManager.swift) | Misura app, cache e log per gioco e totali senza duplicare percorsi condivisi; verifica cartelle e sorgenti prima della pulizia selettiva. I backup appartengono al flusso Saves. |
| [Sources/NXLibraryCore/Services/DiagnosticsReport.swift](../Sources/NXLibraryCore/Services/DiagnosticsReport.swift) | Genera il rapporto diagnostico e rimuove percorso home e valori riconosciuti come chiavi. |
-| [Sources/NXLibraryCore/Services/AppUpdate.swift](../Sources/NXLibraryCore/Services/AppUpdate.swift) | Definisce repository, versioni, requisiti, limiti di download, digest, firma e regole di verifica e sostituzione dell’app NX Library. |
+| [Sources/NXLibraryCore/Services/AppUpdate.swift](../Sources/NXLibraryCore/Services/AppUpdate.swift) | Definisce repository, versioni, verifica del download e sostituzione atomica dell’app in staging esclusivo, con conservazione della vecchia copia se il Cestino fallisce. |
+| [Sources/NXLibraryCore/Services/AppBundleRename.swift](../Sources/NXLibraryCore/Services/AppBundleRename.swift) | Decide se una copia release che si chiama ancora `NX Library.app` diventa `Arcane.app` alla chiusura, e fa lo spostamento nella stessa cartella. |
| [Sources/NXLibraryCore/Models/AppUpdatePresentation.swift](../Sources/NXLibraryCore/Models/AppUpdatePresentation.swift) | Definisce gli stati dell’updater e il gate di installazione per versione e tipo di copia. |
| [Sources/NXLibraryCore/Services/AppUpdateDownload.swift](../Sources/NXLibraryCore/Services/AppUpdateDownload.swift) | Scarica gli aggiornamenti con limiti di dimensione, redirect HTTPS vincolati a GitHub e gestione del file temporaneo. |
-## Core · cheats
+## Core · cheat e mod
| File | Responsabilità |
|---|---|
@@ -217,8 +236,8 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Sources/NXLibraryCore/Models/CheatStatus.swift](../Sources/NXLibraryCore/Models/CheatStatus.swift) | Valuta il supporto del motore tramite ancestry e prepara stato della riga e indicatore attivo. |
| [Sources/NXLibraryCore/Models/CheatCopy.swift](../Sources/NXLibraryCore/Models/CheatCopy.swift) | Centralizza testi di stato, rifiuto, importazione, sostituzione e rimozione dei cheats. |
| [Sources/NXLibraryCore/Services/CheatStore.swift](../Sources/NXLibraryCore/Services/CheatStore.swift) | Legge e modifica cheats, file enabled, master switch e metadati della build corrente. |
-| [Sources/NXLibraryCore/Services/ModStore.swift](../Sources/NXLibraryCore/Services/ModStore.swift) | Ordine, stato acceso/spento, conflitti, Cestino e riga `DM_ROMFS_OVERLAY` delle mod RomFS di un gioco. |
-| [Sources/NXLibraryCore/Services/ModFolderScanner.swift](../Sources/NXLibraryCore/Services/ModFolderScanner.swift) | Trova le voci della cartella mods (cartelle e file sparsi), il loro `romfs` e i file che contengono (senza quelli nascosti). |
+| [Sources/NXLibraryCore/Services/ModStore.swift](../Sources/NXLibraryCore/Services/ModStore.swift) | Ordine, interruttori, conflitti, Cestino e overlay delle mod RomFS. Ferma la riconciliazione se cartella o record non si leggono. |
+| [Sources/NXLibraryCore/Services/ModFolderScanner.swift](../Sources/NXLibraryCore/Services/ModFolderScanner.swift) | Elenca cartelle, archivi e file RomFS. La lettura stretta distingue una cartella vuota da una scansione fallita durante la riconciliazione. |
| [Sources/NXLibraryCore/Services/GameBanana/GameBananaAPI.swift](../Sources/NXLibraryCore/Services/GameBanana/GameBananaAPI.swift) | URL, host fidati, modelli delle risposte di GameBanana e testo semplice dalle descrizioni HTML. |
| [Sources/NXLibraryCore/Services/GameBanana/GameBananaClient.swift](../Sources/NXLibraryCore/Services/GameBanana/GameBananaClient.swift) | Richieste a GameBanana con User-Agent, limite di 4 alla volta e cache su disco. |
| [Sources/NXLibraryCore/Services/GameBanana/GameBananaImageCache.swift](../Sources/NXLibraryCore/Services/GameBanana/GameBananaImageCache.swift) | Cache su disco delle immagini delle mod dal CDN di GameBanana. |
@@ -241,16 +260,16 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| File | Responsabilità |
|---|---|
-| [Sources/NXLibraryCore/Models/SaveLocation.swift](../Sources/NXLibraryCore/Models/SaveLocation.swift) | Valida percorsi e identità, risolve cloud effettivo e definisce slot ed errori dei salvataggi. |
-| [Sources/NXLibraryCore/Models/SaveSnapshot.swift](../Sources/NXLibraryCore/Models/SaveSnapshot.swift) | Definisce identità, inventario, manifest e anteprime di importazione o ripristino. |
-| [Sources/NXLibraryCore/Models/SavePresentation.swift](../Sources/NXLibraryCore/Models/SavePresentation.swift) | Prepara riepiloghi, date, dimensioni, nomi degli slot e disponibilità dell’importazione. |
+| [Sources/NXLibraryCore/Models/SaveLocation.swift](../Sources/NXLibraryCore/Models/SaveLocation.swift) | Percorsi e identità dei salvataggi; account/device, utenti locali aggiuntivi e file registro; cloud effettivo e percorsi sicuri. |
+| [Sources/NXLibraryCore/Models/SaveSnapshot.swift](../Sources/NXLibraryCore/Models/SaveSnapshot.swift) | Identità, inventario, manifest schema 1/2 e anteprime; rifiuta dichiarazioni storiche con componenti nuovi. |
+| [Sources/NXLibraryCore/Models/SavePresentation.swift](../Sources/NXLibraryCore/Models/SavePresentation.swift) | Riepiloghi e ambito dei restore storici/multiutente, nomi dei componenti e limite cloud a primario/device. |
| [Sources/NXLibraryCore/Models/CloudSaves.swift](../Sources/NXLibraryCore/Models/CloudSaves.swift) | Descrive scelta cloud, cartelle iCloud o personalizzate e passaggi fra le opzioni. |
| [Sources/NXLibraryCore/Services/CloudSavesPreferences.swift](../Sources/NXLibraryCore/Services/CloudSavesPreferences.swift) | Prepara la cartella e riapplica la scelta cloud ai domini dei giochi prima di ogni avvio, anche Off. |
| [Sources/NXLibraryCore/Services/RyujinxSaveFolder.swift](../Sources/NXLibraryCore/Services/RyujinxSaveFolder.swift) | Riconosce contenitori Ryujinx, controlla il title ID e seleziona l’intero albero committed 0. |
-| [Sources/NXLibraryCore/Services/SaveFileIO.swift](../Sources/NXLibraryCore/Services/SaveFileIO.swift) | Centralizza copie, hash, xattr portabili, controlli dei percorsi, spazio e scritture durevoli. |
-| [Sources/NXLibraryCore/Services/SaveSnapshotStore.swift](../Sources/NXLibraryCore/Services/SaveSnapshotStore.swift) | Crea e verifica backup e prepara importazioni da esportazioni o backup datati. |
-| [Sources/NXLibraryCore/Services/SaveRestorePreview.swift](../Sources/NXLibraryCore/Services/SaveRestorePreview.swift) | Estende lo store con staging, validazione e rilascio delle anteprime di ripristino. |
-| [Sources/NXLibraryCore/Services/SaveTransaction.swift](../Sources/NXLibraryCore/Services/SaveTransaction.swift) | Esegue sostituzioni con copia protettiva e journal e recupera o ripulisce transazioni interrotte. |
+| [Sources/NXLibraryCore/Services/SaveFileIO.swift](../Sources/NXLibraryCore/Services/SaveFileIO.swift) | Copie, hash e xattr portabili; inventario di directory e registro regolare limitato, controlli dei percorsi e scritture durevoli. |
+| [Sources/NXLibraryCore/Services/SaveSnapshotStore.swift](../Sources/NXLibraryCore/Services/SaveSnapshotStore.swift) | Backup completi degli utenti locali e registro, formati storici compatibili, staging e import User/Device. |
+| [Sources/NXLibraryCore/Services/SaveRestorePreview.swift](../Sources/NXLibraryCore/Services/SaveRestorePreview.swift) | Staging e validazione dei pezzi registrati nel backup, compreso il file utenti, con rilevamento dei cambiamenti concorrenti. |
+| [Sources/NXLibraryCore/Services/SaveTransaction.swift](../Sources/NXLibraryCore/Services/SaveTransaction.swift) | Sostituzioni con ambito esplicito, backup completo e journal 1/2; verifica originali, recovery e pulizia parziale riprendibili con intento durevole. |
| [Sources/NXLibraryCore/Services/SaveOperationGate.swift](../Sources/NXLibraryCore/Services/SaveOperationGate.swift) | Assegna lease per titolo e un’esclusione globale per l’updater; coordina salvataggi, Play, installazioni e recuperi. |
## Core · artwork, metadati e sfondi online
@@ -273,6 +292,7 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Sources/NXLibraryCore/Services/LaunchBoxArt.swift](../Sources/NXLibraryCore/Services/LaunchBoxArt.swift) | Legge ricerca e pagina gioco di LaunchBox; dal payload Nuxt ricava anteprime, file pieni, tipo, regione e dimensioni; screenshot Gameplay. |
| [Sources/NXLibraryCore/Services/SteamGridDBArt.swift](../Sources/NXLibraryCore/Services/SteamGridDBArt.swift) | Conserva la chiave SteamGridDB in un file 0600 e interroga l’API v2 per griglie, hero, loghi e icone statiche accreditate. |
| [Sources/NXLibraryCore/Services/ScreenshotFallback.swift](../Sources/NXLibraryCore/Services/ScreenshotFallback.swift) | Conserva per 30 giorni gli screenshot LaunchBox dei giochi senza screenshot Title DB e li sovrappone ai metadati. |
+| [Sources/NXLibraryCore/Models/LibraryArtworkRole.swift](../Sources/NXLibraryCore/Models/LibraryArtworkRole.swift) | Ruoli di layout delle immagini (copertina, quadrato, sfondo…) separati dal fornitore: un quadrato non chiede né ritaglia mai la copertina verticale. |
## Core · presentazione Selene, focus e impostazioni
@@ -280,7 +300,20 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
|---|---|
| [Sources/NXLibraryCore/Models/ButtonPrompts.swift](../Sources/NXLibraryCore/Models/ButtonPrompts.swift) | Traduce azioni in simboli o etichette per tastiera e controller Switch, Xbox e PlayStation. |
| [Sources/NXLibraryCore/Models/CollectionRow.swift](../Sources/NXLibraryCore/Models/CollectionRow.swift) | Definisce proporzioni delle copertine e geometria della riga Collection. |
-| [Sources/NXLibraryCore/Models/DetailsFocus.swift](../Sources/NXLibraryCore/Models/DetailsFocus.swift) | Gestisce zone e spostamenti del focus nelle azioni e nelle bande di Details. |
+| [Sources/NXLibraryCore/Models/DetailsFacts.swift](../Sources/NXLibraryCore/Models/DetailsFacts.swift) | Sceglie le righe del pannello Details per Switch e Steam: solo i valori presenti, niente di tecnico. |
+| [Sources/NXLibraryCore/Models/CriticRating.swift](../Sources/NXLibraryCore/Models/CriticRating.swift) | Identità pubblica del gioco e console (Mac, Switch, Switch 2), voto originale /100, provenienza e riempimento proporzionale delle cinque stelle. |
+| [Sources/NXLibraryCore/Services/WikidataRatings.swift](../Sources/NXLibraryCore/Services/WikidataRatings.swift) | Abbina titoli esatti e ID Steam; seleziona medie della critica documentate, senza confondere piattaforme o raccomandazioni. |
+| [Sources/NXLibraryCore/Services/BoundedDownload.swift](../Sources/NXLibraryCore/Services/BoundedDownload.swift) | Lettura HTTP limitata a blocchi, senza redirect né byte per byte: usata da Wikidata, IGDB, LaunchBox/TheGamesDB e Steam. |
+| [Sources/NXLibraryCore/Services/CriticRatingService.swift](../Sources/NXLibraryCore/Services/CriticRatingService.swift) | Preferenza IGDB personale → Wikidata pubblico, cache Wikidata, ripiego offline e pausa dopo errori. |
+| [Sources/NXLibraryCore/Services/IGDBCredentials.swift](../Sources/NXLibraryCore/Services/IGDBCredentials.swift) | Credenziali Twitch personali in file 0600, validazione e messaggi sicuri senza segreti nei log. |
+| [Sources/NXLibraryCore/Services/IGDBRatings.swift](../Sources/NXLibraryCore/Services/IGDBRatings.swift) | Abbinamento IGDB esatto o tramite ID Steam, critica preferita e ripiego utenti esplicito, con provenienza distinta da Wikidata. |
+| [Sources/NXLibraryCore/Services/IGDBRatingService.swift](../Sources/NXLibraryCore/Services/IGDBRatingService.swift) | Cache dei voti, richieste coalescenti e verifica credenziali tramite il client IGDB condiviso. |
+| [Sources/NXLibraryCore/Services/IGDBClient.swift](../Sources/NXLibraryCore/Services/IGDBClient.swift) | Unico accesso Twitch/IGDB per voti e metadati: token in memoria, coda limitata seriale, host vincolati, rinnovo 401 e annullamento. |
+| [Sources/NXLibraryCore/Services/IGDBMetadata.swift](../Sources/NXLibraryCore/Services/IGDBMetadata.swift) | Proposte IGDB per campo: identità esatta, ruoli delle aziende e date complete della piattaforma corretta. |
+| [Sources/NXLibraryCore/Services/IGDBMetadataService.swift](../Sources/NXLibraryCore/Services/IGDBMetadataService.swift) | Ricerca metadati su richiesta, ID Steam verificato, cache separata e ripiego offline; nessuna scrittura delle scelte personali. |
+| [Sources/NXLibraryCore/Services/DatabaseMetadata.swift](../Sources/NXLibraryCore/Services/DatabaseMetadata.swift) | Proposte LaunchBox/TheGamesDB: identità e piattaforma verificate, campi separati, fonte esplicita e date della versione corretta. |
+| [Sources/NXLibraryCore/Services/DatabaseMetadataService.swift](../Sources/NXLibraryCore/Services/DatabaseMetadataService.swift) | Letture pubbliche limitate e annullabili, richieste condivise, cache testuale per gioco/piattaforma e recupero offline. |
+| [Sources/NXLibraryCore/Models/DetailsFocus.swift](../Sources/NXLibraryCore/Models/DetailsFocus.swift) | Gestisce zone e spostamenti del focus nei link e nelle bande di Details. |
| [Sources/NXLibraryCore/Models/FocusIndex.swift](../Sources/NXLibraryCore/Models/FocusIndex.swift) | Mantiene un indice di focus entro i limiti di una lista. |
| [Sources/NXLibraryCore/Models/SettingsRowAction.swift](../Sources/NXLibraryCore/Models/SettingsRowAction.swift) | Identifica azioni e righe Settings, mantenendo una sola azione primaria per riga senza accorpare giochi omonimi. |
| [Sources/NXLibraryCore/Models/GameOptionsPresentation.swift](../Sources/NXLibraryCore/Models/GameOptionsPresentation.swift) | Definisce righe, livelli, etichette, scelte runtime e focus di Game Options. |
@@ -288,18 +321,98 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Sources/NXLibraryCore/Models/MaterialIcon.swift](../Sources/NXLibraryCore/Models/MaterialIcon.swift) | Elenca i glifi del font Material Icons incluso nel bundle. |
| [Sources/NXLibraryCore/Models/MenuSelectionModel.swift](../Sources/NXLibraryCore/Models/MenuSelectionModel.swift) | Gestisce azioni selezionate nel control center e nelle scelte Power. |
| [Sources/NXLibraryCore/Models/MoonlightField.swift](../Sources/NXLibraryCore/Models/MoonlightField.swift) | Genera in modo deterministico i dati delle particelle per lo sfondo Metal. |
+| [MoonlightAppearance.swift](../Sources/NXLibraryCore/Models/MoonlightAppearance.swift) | Identità delle superfici classica/Arcane/Flow e campionamento dei colori locali condiviso fra shader e fallback. |
| [Sources/NXLibraryCore/Models/ScreenshotViewerState.swift](../Sources/NXLibraryCore/Models/ScreenshotViewerState.swift) | Mantiene indice e limiti della navigazione nel visualizzatore screenshot. |
| [Sources/NXLibraryCore/Models/SeleneCanvas.swift](../Sources/NXLibraryCore/Models/SeleneCanvas.swift) | Calcola scala uniforme, stage centrato e conversione delle unità del canvas 1920×1080. |
-| [Sources/NXLibraryCore/Models/SelenePalette.swift](../Sources/NXLibraryCore/Models/SelenePalette.swift) | Decodifica palette, ordine del selettore e fallback della palette predefinita. |
-| [Sources/NXLibraryCore/Models/SettingsCatalog.swift](../Sources/NXLibraryCore/Models/SettingsCatalog.swift) | Descrive righe, ricerca e valori modificati, distinguendo i default dei nuovi giochi dalla vibrazione in Controllers. |
-| [Sources/NXLibraryCore/Models/SettingsSection.swift](../Sources/NXLibraryCore/Models/SettingsSection.swift) | Enumera gruppi, titoli e icone della schermata Settings. |
+| [Sources/NXLibraryCore/Models/SelenePalette.swift](../Sources/NXLibraryCore/Models/SelenePalette.swift) | Decodifica palette e metadato opzionale moonlight, ordine del selettore e fallback Arcane con ID selene. |
+| [Sources/NXLibraryCore/Models/SettingsCatalog.swift](../Sources/NXLibraryCore/Models/SettingsCatalog.swift) | Descrive righe, ricerca e valori modificati; ogni riga tiene il suo `rowID` e sta in una sola sezione, vibrazione compresa tra i default dei nuovi giochi. |
+| [Sources/NXLibraryCore/Models/SettingsSection.swift](../Sources/NXLibraryCore/Models/SettingsSection.swift) | Sezioni di Settings con titoli e icone, dichiarate in ordine di sidebar, e `SettingsSidebarGroup`: General, Library, Porting (il gruppo di piattaforma) e System. |
+| [Sources/NXLibraryCore/Models/SettingsReset.swift](../Sources/NXLibraryCore/Models/SettingsReset.swift) | Reset group per sezione: quali sezioni si azzerano e quali valori di `AppSettings` tornano ai default. |
| [Sources/NXLibraryCore/Models/SpotlightPage.swift](../Sources/NXLibraryCore/Models/SpotlightPage.swift) | Calcola estratti delle descrizioni e stati dello scorrimento della pagina Spotlight. |
-| [Sources/NXLibraryCore/Models/SpotlightRow.swift](../Sources/NXLibraryCore/Models/SpotlightRow.swift) | Costruisce la sequenza di card e giochi, riordino e selezione Surprise. |
+| [Sources/NXLibraryCore/Models/SpotlightRow.swift](../Sources/NXLibraryCore/Models/SpotlightRow.swift) | Costruisce la sequenza per UUID e salva riordini conservando giochi/fonti/card temporaneamente nascosti; Surprise mantiene il proprio contratto nxnative. |
| [Sources/NXLibraryCore/Models/SpotlightRowGeometry.swift](../Sources/NXLibraryCore/Models/SpotlightRowGeometry.swift) | Posti delle tessere nella riga, camera unica che la fa scorrere e finestra delle tessere create; posto, scala e camera lungo lo scorrimento dalla posizione continua della selezione. |
-| [Sources/NXLibraryCore/Models/SpotlightState.swift](../Sources/NXLibraryCore/Models/SpotlightState.swift) | Gestisce selezione, focus, azioni e spostamento delle tile su Spotlight. |
-| [Sources/NXLibraryCore/Models/ThemePicker.swift](../Sources/NXLibraryCore/Models/ThemePicker.swift) | Gestisce griglia, tab Wallpapers/Live e scelte di sfondo nel selettore temi. |
+| [Sources/NXLibraryCore/Models/SpotlightState.swift](../Sources/NXLibraryCore/Models/SpotlightState.swift) | Gestisce selezione, focus (anche la card Achievements), azioni e spostamento delle tile su Spotlight. |
+| [Sources/NXLibraryCore/Models/SpotlightEntrance.swift](../Sources/NXLibraryCore/Models/SpotlightEntrance.swift) | Tempi e partenze del volo delle tessere, dissolvenza oltre il bordo, sfondo, informazioni, hint e fasi della prima entrata di Spotlight, compreso quando accetta input. |
+| [Sources/NXLibraryCore/Models/ThemePicker.swift](../Sources/NXLibraryCore/Models/ThemePicker.swift) | Gestisce il focus nella griglia colori, tab Wallpapers/Live e scelta dello sfondo successivo. |
| [Sources/NXLibraryCore/Models/WallpaperCatalog.swift](../Sources/NXLibraryCore/Models/WallpaperCatalog.swift) | Elenca wallpaper e video, gruppi, nomi e file delle risorse incluse o importate. |
| [Sources/NXLibraryCore/Models/WallpaperPlacement.swift](../Sources/NXLibraryCore/Models/WallpaperPlacement.swift) | Decide dove applicare uno sfondo scelto fra schermi principali e Settings. |
+| [Sources/NXLibraryCore/Models/DisplayNameCache.swift](../Sources/NXLibraryCore/Models/DisplayNameCache.swift) | Nomi visualizzati di cartelle e volumi letti una volta per URL: la pagina si ricostruisce a ogni disegno e un disco esterno in stop bloccherebbe ogni volta. |
+
+## Core · catalogo comune e fonti
+
+| File | Responsabilità |
+|---|---|
+| [CatalogGame.swift](../Sources/NXLibraryCore/Models/CatalogGame.swift) | Record tipizzato nxnative/Steam, identità e personalizzazioni con namespace, osservazioni delle installazioni; lookup condiviso della prima installazione disponibile, separato dal gate di Play. |
+| [CatalogDocument.swift](../Sources/NXLibraryCore/Models/CatalogDocument.swift) | Schema, revisione, base legacy riconosciuta, configurazione delle fonti e validazione delle identità. |
+| [CatalogGamePresentation.swift](../Sources/NXLibraryCore/Models/CatalogGamePresentation.swift) | Contratto comune per presentazione, operazioni supportate e target di avvio; nessuna operazione I/O. |
+| [CatalogStore.swift](../Sources/NXLibraryCore/Services/Catalog/CatalogStore.swift) | Conversione conservativa, letture limitate, revisioni attese, lock e archiviazione esplicita del conflitto legacy senza fusione. |
+| [CatalogPublication.swift](../Sources/NXLibraryCore/Services/Catalog/CatalogPublication.swift) | Staging verificato, creazione esclusiva e sostituzione atomica, con confine di errore controllabile. |
+| [CatalogRepository.swift](../Sources/NXLibraryCore/Services/Catalog/CatalogRepository.swift) | Modifiche tipizzate sull'ultimo catalogo, senza replay di effetti esterni; risultati build limitati ai propri campi. |
+| [NXNativeLibraryMerge.swift](../Sources/NXLibraryCore/Services/NXNativeLibraryMerge.swift) | Algoritmo di merge nxnative usato dal repository del catalogo comune. |
+| [CatalogRecovery.swift](../Sources/NXLibraryCore/Models/CatalogRecovery.swift) | Offerte di recupero e conflitto legacy con impronte degli input, rivalidate all’accettazione. |
+| [CatalogPersonalizations.swift](../Sources/NXLibraryCore/Models/CatalogPersonalizations.swift) | Lookup personali immutabili per identità e radici distinte per integrazione. |
+| [CatalogErrorCopy.swift](../Sources/NXLibraryCore/Services/Catalog/CatalogErrorCopy.swift) | Errori recuperabili del catalogo nelle sei lingue. |
+| [CatalogBuildRecoveries.swift](../Sources/NXLibraryCore/Models/CatalogBuildRecoveries.swift) | Generazioni di build non ancora salvate, selezione del retry e conferma della sola generazione persistita. |
+| [CatalogGameOptions.swift](../Sources/NXLibraryCore/Models/CatalogGameOptions.swift) | Ordine unico delle operazioni comuni della libreria; ciò che una fonte può fare dipende dal suo record (nessuna modifica nxnative su un gioco Steam). |
+| [CatalogSourcesModel.swift](../Sources/NXLibraryCore/Services/Catalog/CatalogSourcesModel.swift) | Opt-in, worker annullabile e stato Steam; discoveryRoot conserva la cartella scelta anche con fonte spenta; pubblica solo documenti salvati dal repository. |
+| [CatalogLibraryProjection.swift](../Sources/NXLibraryCore/Models/CatalogLibraryProjection.swift) | Visibilità comune per fonti attive e giochi riconosciuti; nessuna scansione. |
+
+## Core · Steam
+
+| File | Responsabilità |
+|---|---|
+| [SteamBackgroundLaunch.swift](../Sources/NXLibraryCore/Services/Steam/SteamBackgroundLaunch.swift) | Attesa di un gioco Steam avviato da Play: pazienza (15 s, 45 s se Play avvia Steam), stato della schermata di lancio, regole di «Keep Steam in the background». |
+| [SteamKeyValues.swift](../Sources/NXLibraryCore/Services/Steam/SteamKeyValues.swift) | Parser testuale limitato e lookup condivisi dei lettori: prima chiave, primo valore tipizzato o campo unico, con regole esplicite sui duplicati; nessuna direttiva eseguita. |
+| [SteamPlaytimeReader.swift](../Sources/NXLibraryCore/Services/Steam/SteamPlaytimeReader.swift) | Ore e ultima partita dell’account Steam più recente da `localconfig.vdf`; nient’altro del file esce dal tipo. |
+| [SteamPlaytimeBaselines.swift](../Sources/NXLibraryCore/Services/Steam/SteamPlaytimeBaselines.swift) | Totali Steam con il momento in cui sono stati visti; nuovo valore o account ripartono; mappa ai giochi del catalogo. |
+| [SteamReturnFocus.swift](../Sources/NXLibraryCore/Models/SteamReturnFocus.swift) | Quando un gioco Steam che esce riporta Arcane davanti: Play premuto qui, gioco in primo piano, nessun altro gioco aperto. |
+| [SteamLaunchQuestions.swift](../Sources/NXLibraryCore/Services/Steam/SteamLaunchQuestions.swift) | Domande con cui Steam ferma un avvio, dalle righe `GameAction` di `logs/console_log.txt`. `ShowInterstitials` è avanzamento; le domande contano dopo 1 s. |
+| [SteamPlaytimeSync.swift](../Sources/NXLibraryCore/Services/Steam/SteamPlaytimeSync.swift) | Una lettura dei file Steam e cosa fa (pubblica, conserva gli ultimi totali buoni dello stesso account o azzera); coda di una lettura alla volta. |
+| [InstallationFileSnapshot.swift](../Sources/NXLibraryCore/Services/Steam/InstallationFileSnapshot.swift) | Letture limitate e non bloccanti di file regolari; verifica dell'identità prima della pubblicazione. |
+| [InstallationDirectorySnapshot.swift](../Sources/NXLibraryCore/Services/Steam/InstallationDirectorySnapshot.swift) | Lettura incrementale delle cartelle, budget anche sulle voci nascoste e annullamento durante l'enumerazione. |
+| [NativeMacApplication.swift](../Sources/NXLibraryCore/Services/Steam/NativeMacApplication.swift) | Evidenze del bundle Mac e degli header eseguibili, architetture e categoria dichiarata, senza avvio. |
+| [SteamLibrarySource.swift](../Sources/NXLibraryCore/Services/Steam/SteamLibrarySource.swift) | Snapshot delle librerie/manifest dichiarati, disponibilità, ambiguità, limiti e annullamento; non modifica il catalogo. |
+| [SteamPlayState.swift](../Sources/NXLibraryCore/Services/Steam/SteamPlayState.swift) | Stato di Play per un gioco Steam: processi osservati con i percorsi risolti, passaggio a Steam, sessione solo quando gira l’app di questa installazione, attese e rifiuti. |
+| [SteamBinaryKeyValues.swift](../Sources/NXLibraryCore/Services/Steam/SteamBinaryKeyValues.swift) | Lettura limitata del formato KeyValues binario di Steam (`appcache/stats`): tipi noti, profondità, voci e dimensione; qualunque altro byte è un errore. |
+| [SteamAchievementReader.swift](../Sources/NXLibraryCore/Services/Steam/SteamAchievementReader.swift) | Achievement di un gioco per l’account corrente: schema (nomi nella lingua dell’app, poi inglese; nascosti; icone) e soli `AchievementTimes` del file delle statistiche; nessun file, account o statistiche: nessun dato. |
+| [SteamAchievementRarity.swift](../Sources/NXLibraryCore/Services/Steam/SteamAchievementRarity.swift) | Rarità pubblica (`GetGlobalAchievementPercentagesForApp`, senza chiave) (una percentuale non numerica, «nan» o «inf», si scarta) e indirizzi delle icone sull’host community-assets del CDN di Steam, solo per nomi di file semplici. |
+| [SteamManifestWatcher.swift](../Sources/NXLibraryCore/Services/Steam/SteamManifestWatcher.swift) | Uno stream FSEvents sulle cartelle `steamapps` delle librerie dell’ultima scansione; segnala solo i manifest `appmanifest_.acf` e l’indice `libraryfolders.vdf` della radice, una volta per gruppo di eventi. |
+| [SteamCatalogReconciler.swift](../Sources/NXLibraryCore/Services/Catalog/SteamCatalogReconciler.swift) | Ticket e fusione pura degli snapshot Steam, identità conservate e assenza trattata secondo completezza. |
+| [SteamMetadata.swift](../Sources/NXLibraryCore/Services/Steam/SteamMetadata.swift) | Dati store Steam tipizzati, lingua e URL immagini verificati. |
+| [SteamMetadataService.swift](../Sources/NXLibraryCore/Services/Steam/SteamMetadataService.swift) | Fino a sei download coalescenti, cache per lingua, ripiego offline e immagini ridimensionate. Legge i tratti dei giochi correlati solo da cache. |
+| [SteamPersonalizationStore.swift](../Sources/NXLibraryCore/Services/Steam/SteamPersonalizationStore.swift) | Pubblicazione unica di metadati e riferimenti artwork; fallimenti e Automatic conservano le scelte coerenti. |
+| [GameDetailPresentation+Steam.swift](../Sources/NXLibraryCore/Models/GameDetailPresentation+Steam.swift) | Dati della pagina Steam e generi della testata Spotlight; ignora i dati di altri AppID e dà precedenza ai campi personali. |
+| [SteamArtworkRequest.swift](../Sources/NXLibraryCore/Services/Steam/SteamArtworkRequest.swift) | Cosa chiede la tile di un gioco Steam per ogni ruolo: prima la scelta personale, poi per il quadrato l’icona dell’app installata, mai la copertina; gli altri ruoli vanno all’arte dello store. |
+| [SteamBackdropChoice.swift](../Sources/NXLibraryCore/Services/Steam/SteamBackdropChoice.swift) | Sfondo automatico di un gioco Steam: arte 16:9 pulita (Xbox, GOG, TheGamesDB, fan art LaunchBox), poi il primo screenshot, per ultimo il banner della libreria ritagliato. |
+
+Giochi in download: `SteamLibrarySource` (StateFlags senza il bit 4 → `.downloading`, cartella non letta), `SteamCatalogInstallation.isDownloading` e `SteamCatalogGame.isDownloading`/`needsReview`, `CatalogGamePresentation.isDownloading`, `PortingTileLook.downloading` con `PortingArtLook` (la scritta) e `PortingDownloadMark` → `DownloadMarkLayers` in `TileMotionLayers.swift` (il simbolo che pulsa, fuori dal `drawingGroup`), `SteamPlayCoordinator.openDownloads`, `CatalogSteamInfo` e `GamePrimaryActions.primaryWaveDots` (pulsante «Downloading» con i puntini, come «Porting»), il ritmo delle riscansioni in `CatalogSourcesModel.steamFilesChanged`..
+
+## Core · achievement
+
+| File | Responsabilità |
+|---|---|
+| [AchievementSummary.swift](../Sources/NXLibraryCore/Models/AchievementSummary.swift) | Riepilogo puro per la tile e la schermata: conteggi, percentuale, gioco completato (`isComplete`), righe recenti con icona, conteggi per tier, sbloccati di recente, ultimo sblocco, filtri e ordini; maschera i nascosti ancora bloccati. |
+| [AchievementTier.swift](../Sources/NXLibraryCore/Models/AchievementTier.swift) | Tier a cristallo come i trofei PS5: Arcano (viola, al posto del Platino) per il gioco completato, Oro / Argento / Bronzo per rarità Steam (<10%, <30%, il resto); nomi tradotti e PNG nelle risorse del Core; `videoURL` dà il video in loop dell'Arcane (`crystal-arcane.mov`, HEVC con alpha a 384 px). |
+| [AchievementsScreenState.swift](../Sources/NXLibraryCore/Models/AchievementsScreenState.swift) | Filtro e selezione della schermata Achievements: due colonne, bordi fermi, LB/RB che girano i filtri. |
+| [GridListLayout.swift](../Sources/NXLibraryCore/Models/GridListLayout.swift) | Geometria di una lista a colonne di righe uguali: altezza, posizione di ogni riga, linee da disegnare, riga da mostrare e riga in vista più vicina. |
+
+## Core · lingua e testi
+
+| File | Responsabilità |
+|---|---|
+| [Sources/NXLibraryCore/Models/AppIdentity.swift](../Sources/NXLibraryCore/Models/AppIdentity.swift) | Nome visibile dell'app ("Arcane", non tradotto), il vecchio nome detto solo dal benvenuto, il nome del modulo Porting, pagina del progetto e User-Agent unico delle richieste di rete. |
+| [Sources/NXLibraryCore/Models/AppLocale.swift](../Sources/NXLibraryCore/Models/AppLocale.swift) | Sei lingue, risoluzione delle preferenze e regione indipendente; nomi e ricerca delle regioni. |
+| [Sources/NXLibraryCore/Models/GameGenre.swift](../Sources/NXLibraryCore/Models/GameGenre.swift) | Generi noti tradotti alla presentazione; dati originali e generi personali conservati. |
+| [Sources/NXLibraryCore/Services/AppLocalization.swift](../Sources/NXLibraryCore/Services/AppLocalization.swift) | Contesto osservabile, lookup portabile delle risorse e interpolazioni/plurali. |
+| [Sources/NXLibraryCore/Resources/Localizable.xcstrings](../Sources/NXLibraryCore/Resources/Localizable.xcstrings) | Testi condivisi e traduzioni en/it/fr/de/es/pt-BR. |
+
+## Core · profilo dei dati
+
+| File | Responsabilità |
+|---|---|
+| [AppDataProfile.swift](../Sources/NXLibraryCore/Services/AppDataProfile.swift) | Policy di percorsi, cache, preferenze e staging del profilo. |
+| [DevelopmentProfileImporter.swift](../Sources/NXLibraryCore/Services/DevelopmentProfileImporter.swift) | Copia iniziale selettiva (compresa la scelta Steam del Setup), hash, validazione e ripresa senza modificare la sorgente. |
+| [DevelopmentOperationStore.swift](../Sources/NXLibraryCore/Services/DevelopmentOperationStore.swift) | Autorizzazioni persistenti per le operazioni richieste nella Dev, distinte da quelle importate. |
## UI · Add Game e porting
@@ -315,47 +428,53 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| File | Responsabilità |
|---|---|
-| [Sources/NXLibrary/Views/Spotlight/SpotlightView.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightView.swift) | Compone home, selezione, filtri, pagina del gioco e stato delle tile. |
-| [Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift) | Traduce input, card, azioni, screenshot e riordino nel modello Spotlight. |
+| [Sources/NXLibrary/Views/Spotlight/SpotlightView.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightView.swift) | Compone home e tessere da una lista filtrata per render. Monta Dettagli, Mods e correlati quando sale la pagina. |
+| [Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift) | Traduce input, card, azioni, screenshot e riordino. Le frecce sulla riga usano solo le tessere, prima di costruire i dati della pagina. |
+| [Sources/NXLibrary/Views/Spotlight/SpotlightView+Entrance.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightView+Entrance.swift) | Coordina l’entrata su moonlight condiviso: coperture e fullscreen, pausa, attesa dell’arte, effetti di volo e dissolvenza, barra in alto e hint per ultimi, atterraggio di sicurezza; nessun input salta l’entrata. |
| [Sources/NXLibrary/Views/Spotlight/SpotlightRowView.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightRowView.swift) | Disegna la riga di tile con finestra visibile, focus e titoli; la faccia della card Mods (`ModsCardCover`). |
| [Sources/NXLibrary/Views/Spotlight/SpotlightTopBar.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightTopBar.swift) | Disegna filtri, prompt dei dorsali e orologio condivisi con Collection. |
| [Sources/NXLibrary/Views/Spotlight/SpotlightInfoView.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightInfoView.swift) | Mostra logo, Play/Options/Favorite, statistiche e stato di porting del gioco selezionato. |
| [Sources/NXLibrary/Views/Spotlight/SpotlightCardInfoView.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightCardInfoView.swift) | Mostra informazioni e azioni delle card Collection, Surprise, Activity e Add Game. |
-| [Sources/NXLibrary/Views/Spotlight/SpotlightPageSections.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightPageSections.swift) | Prepara generi, descrizione, Build & Sources e giochi correlati della pagina inferiore. |
+| [Sources/NXLibrary/Views/Spotlight/SpotlightPageSections.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightPageSections.swift) | Modello della pagina inferiore con dettagli, link e giochi correlati del catalogo; generi e descrizione. |
| [Sources/NXLibrary/Views/Spotlight/SpotlightScreenshotStrip.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightScreenshotStrip.swift) | Disegna la striscia di screenshot con focus e stile adattabile alle schermate. |
-| [Sources/NXLibrary/Views/Spotlight/SeleneArtBackground.swift](../Sources/NXLibrary/Views/Spotlight/SeleneArtBackground.swift) | Compone wallpaper, sfondo del gioco, transizioni e maschere Selene; l'arte è un `CALayer` che dissolve nel render server (`SeleneArtLayer`). |
+| [Sources/NXLibrary/Views/Spotlight/SeleneArtBackground.swift](../Sources/NXLibrary/Views/Spotlight/SeleneArtBackground.swift) | Compone wallpaper, sfondo del gioco, transizioni e maschere leggendo la palette dallo snapshot condiviso; l'arte è un `CALayer` che dissolve nel render server (`SeleneArtLayer`) e che l'entrata di Spotlight tiene nascosto (`ArtReveal`). |
| [Sources/NXLibrary/Views/Spotlight/SeleneHeroArt.swift](../Sources/NXLibrary/Views/Spotlight/SeleneHeroArt.swift) | Coordina il caricamento differito di hero e logo del gioco selezionato. |
| [Sources/NXLibrary/Views/Spotlight/GameArtLoader.swift](../Sources/NXLibrary/Views/Spotlight/GameArtLoader.swift) | Carica e memorizza hero e loghi attraverso ArtworkStore e decoder immagini dedicati. |
+| [Sources/NXLibrary/Views/Spotlight/GameArtLoader+Played.swift](../Sources/NXLibrary/Views/Spotlight/GameArtLoader+Played.swift) | Hero e logo di un `PlayedGame` per schermata di lancio e card di fine sessione; per Steam le stesse scelte delle sue pagine. |
## UI · Collection e Details
| File | Responsabilità |
|---|---|
-| [Sources/NXLibrary/Views/Collection/CollectionView.swift](../Sources/NXLibrary/Views/Collection/CollectionView.swift) | Compone la libreria a copertine, filtri e informazioni del gioco selezionato. |
+| [Sources/NXLibrary/Views/Collection/CollectionView.swift](../Sources/NXLibrary/Views/Collection/CollectionView.swift) | Compone libreria a copertine, filtri, informazioni e ripristino dell'ultima selezione tramite lo store. |
| [Sources/NXLibrary/Views/Collection/CollectionView+Input.swift](../Sources/NXLibrary/Views/Collection/CollectionView+Input.swift) | Gestisce navigazione, azioni e selezione nella Collection. |
| [Sources/NXLibrary/Views/Collection/CollectionCoverRow.swift](../Sources/NXLibrary/Views/Collection/CollectionCoverRow.swift) | Disegna copertine e scorrimento della riga Collection. |
| [Sources/NXLibrary/Views/Detail/GameDetailView.swift](../Sources/NXLibrary/Views/Detail/GameDetailView.swift) | Compone la pagina Details e coordina bande, modello corrente e focus. |
| [Sources/NXLibrary/Views/Detail/GameDetailView+Input.swift](../Sources/NXLibrary/Views/Detail/GameDetailView+Input.swift) | Gestisce azioni, screenshot, navigazione e passaggio ai giochi correlati da Details. |
| [Sources/NXLibrary/Views/Detail/DetailsBackground.swift](../Sources/NXLibrary/Views/Detail/DetailsBackground.swift) | Compone hero e maschere dello sfondo dedicato alla pagina Details. |
| [Sources/NXLibrary/Views/Detail/DetailsTopBlock.swift](../Sources/NXLibrary/Views/Detail/DetailsTopBlock.swift) | Mostra logo, crediti, azioni, statistiche, generi e descrizione del gioco. |
-| [Sources/NXLibrary/Views/Detail/DetailsBands.swift](../Sources/NXLibrary/Views/Detail/DetailsBands.swift) | Disegna bande screenshot, mod, attività e giochi correlati con i relativi titoli. |
-| [Sources/NXLibrary/Views/Detail/BuildSourcesPanel.swift](../Sources/NXLibrary/Views/Detail/BuildSourcesPanel.swift) | Prepara e disegna le azioni di app, sorgenti, rebuild, log e cartelle. |
+| [Sources/NXLibrary/Views/Detail/DetailsBands.swift](../Sources/NXLibrary/Views/Detail/DetailsBands.swift) | Disegna screenshot, mod e fascia correlati condivisa, con copertine Switch o Steam secondo la fonte. |
+| [Sources/NXLibrary/Views/Detail/DetailsPanel.swift](../Sources/NXLibrary/Views/Detail/DetailsPanel.swift) | Pannello Details uguale per ogni fonte: righe con icona, voto della critica in ultima riga e link in `SeleneActionGrid`; carica solo il voto del gioco mostrato. |
+| [Sources/NXLibrary/Views/Detail/CriticRatingValue.swift](../Sources/NXLibrary/Views/Detail/CriticRatingValue.swift) | Valore della riga Critic score: cinque stelle, numero /100 e fonte, senza finestre aggiuntive; caricamento e assenza espliciti. |
+| [Sources/NXLibrary/ViewModels/IGDBSettings.swift](../Sources/NXLibrary/ViewModels/IGDBSettings.swift) | Configurazione IGDB facoltativa: verifica prima del salvataggio, rimozione e invalidazione delle richieste/voti precedenti. |
+| [Sources/NXLibrary/Views/Components/IGDBCredentialsDialog.swift](../Sources/NXLibrary/Views/Components/IGDBCredentialsDialog.swift) | Guida sintetica in cinque passi, Client ID, Client Secret nascosto, verifica/salvataggio e annullamento; input Settings sospeso. |
+| [Sources/NXLibrary/Views/Settings/SettingsAPISection.swift](../Sources/NXLibrary/Views/Settings/SettingsAPISection.swift) | Pagina generale Servizi API: nota sulle fonti facoltative, IGDB e SteamGridDB con azioni e focus condivisi. |
## UI · Game Options, cheats e salvataggi
| File | Responsabilità |
|---|---|
-| [Sources/NXLibrary/Views/GameOptions/GameOptionsView.swift](../Sources/NXLibrary/Views/GameOptions/GameOptionsView.swift) | Presenta opzioni del gioco, Edit details, impostazioni runtime e conferme delle azioni. |
+| [Sources/NXLibrary/Views/GameOptions/GameOptionsView.swift](../Sources/NXLibrary/Views/GameOptions/GameOptionsView.swift) | Presenta opzioni del gioco, Edit details, impostazioni runtime e conferme delle azioni; `GameOptionsFiles` legge i file una volta per apertura. |
| [Sources/NXLibrary/Views/GameOptions/ChangeArtworkView.swift](../Sources/NXLibrary/Views/GameOptions/ChangeArtworkView.swift) | Seleziona artwork per titolo da rete o file e indica dove viene usato, con stato ad altezza stabile. |
-| [Sources/NXLibrary/Views/GameOptions/ChangeMetadataView.swift](../Sources/NXLibrary/Views/GameOptions/ChangeMetadataView.swift) | Offre alternative o testo personalizzato per descrizione, generi, crediti e data. |
+| [Sources/NXLibrary/Views/GameOptions/ChangeMetadataView.swift](../Sources/NXLibrary/Views/GameOptions/ChangeMetadataView.swift) | Offre alternative per campo da store, Title DB, GameTDB e IGDB, oppure testo personale; anteprima, scelta, annullamento e retry con lo stesso input. |
| [Sources/NXLibrary/Views/GameOptions/CheatsPanel.swift](../Sources/NXLibrary/Views/GameOptions/CheatsPanel.swift) | Presenta file, master switch, codici, importazione, rimozione e stato di scrittura dei cheats. |
| [Sources/NXLibrary/Views/GameOptions/ModsPanel.swift](../Sources/NXLibrary/Views/GameOptions/ModsPanel.swift) | Game options → Mods: accende, ordina e sposta nel Cestino le mod RomFS, apre la cartella mods. |
| [Sources/NXLibrary/Views/Detail/ModDetailPanel.swift](../Sources/NXLibrary/Views/Detail/ModDetailPanel.swift) | Dettaglio di una mod GameBanana: immagini, autore, versione, descrizione, Install/Update e link. |
| [Sources/NXLibrary/Views/Detail/GameBananaFindPanel.swift](../Sources/NXLibrary/Views/Detail/GameBananaFindPanel.swift) | Cerca su GameBanana la pagina del gioco quando l'abbinamento automatico non basta. |
-| [Sources/NXLibrary/ViewModels/ModStoreHost.swift](../Sources/NXLibrary/ViewModels/ModStoreHost.swift) | Store della card Mods: catalogo, ordinamento, focus, chip Installed/Update e pannello della mod. |
+| [Sources/NXLibrary/ViewModels/ModStoreHost.swift](../Sources/NXLibrary/ViewModels/ModStoreHost.swift) | Store della card Mods: mantiene la cover fra schermate, rivalida abbinamenti e snapshot; rilegge i badge a ogni apertura e scarta i risultati di generazioni precedenti. |
| [Sources/NXLibrary/Views/Store/ModStorePage.swift](../Sources/NXLibrary/Views/Store/ModStorePage.swift) | Pagina dello store: barra di ordinamento, banner Featured, righe di tessere; disegna solo le sezioni vicine al focus. |
| [Sources/NXLibrary/Views/Store/GameBananaBlur.swift](../Sources/NXLibrary/Views/Store/GameBananaBlur.swift) | Arte di una mod rimpicciolita e sfocata una volta, fuori dal main thread, e tenuta in memoria: sfondo del Featured. |
-| [Sources/NXLibrary/ViewModels/ModsBandHost.swift](../Sources/NXLibrary/ViewModels/ModsBandHost.swift) | Fascia Mods condivisa da Spotlight e Details: mod installate, GameBanana, pannelli di dettaglio e ricerca. |
+| [Sources/NXLibrary/ViewModels/ModsBandHost.swift](../Sources/NXLibrary/ViewModels/ModsBandHost.swift) | Fascia Mods condivisa da Spotlight e Details. Legge mod installate, coordina GameBanana e pannelli, svuota i dati del gioco precedente sulla riga Spotlight. |
| [Sources/NXLibrary/ViewModels/GameBananaServices.swift](../Sources/NXLibrary/ViewModels/GameBananaServices.swift) | Client, cache delle immagini e abbinamenti GameBanana condivisi da tutta l'app. |
| [Sources/NXLibrary/Views/GameOptions/SavesPanel.swift](../Sources/NXLibrary/Views/GameOptions/SavesPanel.swift) | Presenta azioni sui save, anteprime, errori e popup di successo a scomparsa automatica. |
| [Sources/NXLibrary/Views/GameOptions/MoreSettingsPanel.swift](../Sources/NXLibrary/Views/GameOptions/MoreSettingsPanel.swift) | Mostra le impostazioni del launcher.json senza riga dedicata: interruttori, scelte e intervalli; le righe fissate da env.txt restano attenuate. |
@@ -365,31 +484,42 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| File | Responsabilità |
|---|---|
-| [Sources/NXLibrary/Views/Settings/SettingsView.swift](../Sources/NXLibrary/Views/Settings/SettingsView.swift) | Compone sidebar e gruppo attivo e coordina focus, input e reset delle impostazioni. |
-| [Sources/NXLibrary/Views/Settings/SettingsSidebar.swift](../Sources/NXLibrary/Views/Settings/SettingsSidebar.swift) | Disegna intestazione e lista dei gruppi della schermata Settings. |
+| [Sources/NXLibrary/Views/Settings/SettingsView.swift](../Sources/NXLibrary/Views/Settings/SettingsView.swift) | Compone sidebar e gruppo attivo e coordina focus, input e reset; nella Dev registra apertura e stato del fullscreen per la diagnosi della transizione. |
+| [Sources/NXLibrary/Views/Settings/SettingsSidebar.swift](../Sources/NXLibrary/Views/Settings/SettingsSidebar.swift) | Disegna intestazione e sezioni sotto le intestazioni di gruppo (General, Switch, Steam, System). |
| [Sources/NXLibrary/Views/Settings/SettingsSectionContent.swift](../Sources/NXLibrary/Views/Settings/SettingsSectionContent.swift) | Instrada il gruppo selezionato e fornisce sottotitoli e formattazioni condivise. |
| [Sources/NXLibrary/Views/Settings/SettingsSearchSection.swift](../Sources/NXLibrary/Views/Settings/SettingsSearchSection.swift) | Presenta ricerca e Changed, con apertura del gruppo della riga selezionata. |
-| [Sources/NXLibrary/Views/Settings/SettingsStartUpSection.swift](../Sources/NXLibrary/Views/Settings/SettingsStartUpSection.swift) | Espone schermata iniziale, intro, Setup e controlli degli aggiornamenti all’avvio. |
+| [Sources/NXLibrary/Views/Settings/SettingsStartUpSection.swift](../Sources/NXLibrary/Views/Settings/SettingsStartUpSection.swift) | Espone schermata iniziale, animazione d’entrata, Setup e controlli degli aggiornamenti all’avvio. |
| [Sources/NXLibrary/Views/Settings/SettingsNavigationSection.swift](../Sources/NXLibrary/Views/Settings/SettingsNavigationSection.swift) | Espone le preferenze di navigazione e dei suggerimenti dei tasti. |
| [Sources/NXLibrary/Views/Settings/SettingsSpotlightSection.swift](../Sources/NXLibrary/Views/Settings/SettingsSpotlightSection.swift) | Espone card, ordine e preferenze della home Spotlight. |
| [Sources/NXLibrary/Views/Settings/SettingsSoundSection.swift](../Sources/NXLibrary/Views/Settings/SettingsSoundSection.swift) | Espone volume e suoni e importa risorse da una cartella Selene. |
| [Sources/NXLibrary/Views/Settings/SettingsLookSection.swift](../Sources/NXLibrary/Views/Settings/SettingsLookSection.swift) | Espone palette, wallpaper, luminosità, adattamento, animazione e aspetto dell’icona. |
-| [Sources/NXLibrary/Views/Settings/SettingsGamesSection.swift](../Sources/NXLibrary/Views/Settings/SettingsGamesSection.swift) | Espone default runtime, cloud saves e gestione dei giochi nascosti. |
-| [Sources/NXLibrary/Views/Settings/SettingsControllersSection.swift](../Sources/NXLibrary/Views/Settings/SettingsControllersSection.swift) | Espone preferenze dei controller e relative azioni di gruppo. |
+| [Sources/NXLibrary/Views/Settings/SettingsGamesSection.swift](../Sources/NXLibrary/Views/Settings/SettingsGamesSection.swift) | Porting → New games: default copiati nei nuovi giochi convertiti, vibrazione compresa. |
+| [Sources/NXLibrary/Views/Settings/SettingsLibraryGamesSection.swift](../Sources/NXLibrary/Views/Settings/SettingsLibraryGamesSection.swift) | Library → Games: schermata di lancio, Surprise me, card della sessione e giochi nascosti. |
+| [Sources/NXLibrary/Views/Settings/SettingsCloudSavesSection.swift](../Sources/NXLibrary/Views/Settings/SettingsCloudSavesSection.swift) | Porting → Cloud saves: scelta e cartella; chiarisce che sincronizzano solo primario e device. |
+| [Sources/NXLibrary/Views/Settings/SettingsControllersSection.swift](../Sources/NXLibrary/Views/Settings/SettingsControllersSection.swift) | Espone controller, schema dei tasti e zona morta per la libreria. |
| [Sources/NXLibrary/Views/Settings/SettingsLibrarySection.swift](../Sources/NXLibrary/Views/Settings/SettingsLibrarySection.swift) | Espone cartella della libreria, scansione e notifiche dei porting. |
-| [Sources/NXLibrary/Views/Settings/SettingsStorageSection.swift](../Sources/NXLibrary/Views/Settings/SettingsStorageSection.swift) | Mostra spazio occupato, azioni su cache/log e accesso alla cartella comune dei backup verificati. |
-| [Sources/NXLibrary/Views/Settings/SettingsEngineSection.swift](../Sources/NXLibrary/Views/Settings/SettingsEngineSection.swift) | Mostra checkout, pin, gate, toolchain, runtime, chiavi e changelog upstream. |
-| [Sources/NXLibrary/Views/Settings/SettingsAboutSection.swift](../Sources/NXLibrary/Views/Settings/SettingsAboutSection.swift) | Mostra versione, attribuzioni, diagnostica, documentazione e aggiornamenti dell’app. |
+| [Sources/NXLibrary/Views/Settings/SettingsStorageSection.swift](../Sources/NXLibrary/Views/Settings/SettingsStorageSection.swift) | Library → Storage: spazio occupato, log, cache di metadati e artwork, cartella comune dei backup verificati. |
+| [Sources/NXLibrary/Views/Settings/SettingsPortingStorageSection.swift](../Sources/NXLibrary/Views/Settings/SettingsPortingStorageSection.swift) | Porting → Storage: cache di compilazione per gioco, dalla più grande, e per tutti i giochi, con conferma. |
+| [Sources/NXLibrary/Views/Settings/SettingsConsoleSection.swift](../Sources/NXLibrary/Views/Settings/SettingsConsoleSection.swift) | System → Console: apre la console dei log di build e avvio. |
+| [Sources/NXLibrary/Views/Settings/SettingsEngineSection.swift](../Sources/NXLibrary/Views/Settings/SettingsEngineSection.swift) | Porting → Setup and engine: checkout, pin, gate, toolchain, runtime, changelog upstream e Setup. |
+| [Sources/NXLibrary/Views/Settings/SettingsKeysSection.swift](../Sources/NXLibrary/Views/Settings/SettingsKeysSection.swift) | Porting → Keys: stato, importazione, sostituzione e rilevamento di prod.keys. |
+| [Sources/NXLibrary/Views/Settings/SettingsAboutSection.swift](../Sources/NXLibrary/Views/Settings/SettingsAboutSection.swift) | Mostra versione, diagnostica, aggiornamenti, pulsante di sostegno volontario, crediti e documentazione. |
+| [Sources/NXLibrary/Views/Settings/LocalePicker.swift](../Sources/NXLibrary/Views/Settings/LocalePicker.swift) | Scelta diretta della lingua e ricerca dei formati regionali, con focus tastiera/controller e codici stabili. |
## UI · Setup, avvio, ricerca e console
| File | Responsabilità |
|---|---|
| [Sources/NXLibrary/Views/Setup/SetupCheckView.swift](../Sources/NXLibrary/Views/Setup/SetupCheckView.swift) | Disegna schede dei requisiti, dettagli, progressi e pulsanti Install all/Continue. |
-| [Sources/NXLibrary/Views/Setup/SetupCheckView+Input.swift](../Sources/NXLibrary/Views/Setup/SetupCheckView+Input.swift) | Gestisce focus iniziale, navigazione della griglia e attivazione delle schede Setup. |
-| [Sources/NXLibrary/Views/Setup/YourGamesSetupView.swift](../Sources/NXLibrary/Views/Setup/YourGamesSetupView.swift) | Disegna scelta cartella, primo gioco, apertura libreria e Skip; condivide l'indicatore dei due passaggi e gestisce mouse, tastiera e controller. |
-| [Sources/NXLibrary/Views/Launch/IntroView.swift](../Sources/NXLibrary/Views/Launch/IntroView.swift) | Mostra l’intro a freddo (solo lo sfondo animato, senza icona né scritta) e gestisce il salto tramite input. |
-| [Sources/NXLibrary/Views/Launch/LaunchScreenView.swift](../Sources/NXLibrary/Views/Launch/LaunchScreenView.swift) | Mostra artwork e logo durante l’avvio del gioco e chiude l’overlay a finestra visibile. |
+| [Sources/NXLibrary/Views/Setup/SetupCheckView+Input.swift](../Sources/NXLibrary/Views/Setup/SetupCheckView+Input.swift) | Gestisce focus iniziale, navigazione della griglia, attivazione delle schede Setup e B verso `found` durante il primo avvio. |
+| [Sources/NXLibrary/Views/Setup/ArcaneWelcomeView.swift](../Sources/NXLibrary/Views/Setup/ArcaneWelcomeView.swift) | Disegna il benvenuto in Arcane: nome nuovo, novità, offerta Steam dalla cartella scelta, Add / Not now e Open library. |
+| [Sources/NXLibrary/Views/Setup/ArcaneWelcomeView+Input.swift](../Sources/NXLibrary/Views/Setup/ArcaneWelcomeView+Input.swift) | Gestisce focus, mouse, tastiera e controller del benvenuto. |
+| [Sources/NXLibrary/Views/Setup/FoundGamesSetupView.swift](../Sources/NXLibrary/Views/Setup/FoundGamesSetupView.swift) | Prima pagina del Setup: Steam con interruttore o Retry, app portate e card Porting; Open library resta disponibile durante la lettura. |
+| [Sources/NXLibrary/Views/Setup/FoundGamesSetupView+Input.swift](../Sources/NXLibrary/Views/Setup/FoundGamesSetupView+Input.swift) | Focus, mouse, tastiera e controller di found; Retry della lettura Steam e uscita che annulla la richiesta prima di aprire la libreria. |
+| [Sources/NXLibrary/Views/Setup/YourGamesSetupView.swift](../Sources/NXLibrary/Views/Setup/YourGamesSetupView.swift) | Disegna scelta cartella, primo gioco, apertura libreria e Skip; gestisce mouse, tastiera e controller; contiene `SetupCardRow`, la riga condivisa con `found`. |
+| [Sources/NXLibrary/Views/Launch/LaunchScreenView.swift](../Sources/NXLibrary/Views/Launch/LaunchScreenView.swift) | Mostra artwork e logo per nxnative e Steam. Sfuma anche quando la finestra del gioco è già pronta alla comparsa. |
+| [Sources/NXLibrary/Views/Launch/LaunchMotion.swift](../Sources/NXLibrary/Views/Launch/LaunchMotion.swift) | Movimento della schermata di lancio in Core Animation: artwork che si avvicina e logo del gioco che sale una volta. Con Riduci movimento resta la dissolvenza del logo. |
+| [Sources/NXLibrary/Views/Launch/LaunchCoverWindow.swift](../Sources/NXLibrary/Views/Launch/LaunchCoverWindow.swift) | Ordina la finestra d’attesa sopra ogni app e Space e avvisa il coordinatore dopo aver inviato il pannello al server delle finestre. |
| [Sources/NXLibrary/Views/Search/FindGameView.swift](../Sources/NXLibrary/Views/Search/FindGameView.swift) | Presenta ricerca nella libreria e risultati navigabili e inoltra il gioco scelto alla home. |
| [Sources/NXLibrary/Views/Console/ConsoleView.swift](../Sources/NXLibrary/Views/Console/ConsoleView.swift) | Mostra log e stato corrente e offre copia di log e diagnostica. |
| [Sources/NXLibrary/Views/ControlsView.swift](../Sources/NXLibrary/Views/ControlsView.swift) | Guida Selene separata fra Library e In game; stato controller, rilevamento e scorrimento delle righe con tastiera/controller. |
@@ -401,17 +531,19 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Sources/NXLibrary/Views/Components/BuildLiveLogsDrawer.swift](../Sources/NXLibrary/Views/Components/BuildLiveLogsDrawer.swift) | Mostra il log del porting con livelli, scroll sul nuovo contenuto e apertura o chiusura. |
| [Sources/NXLibrary/Views/Components/BuildStageStepperView.swift](../Sources/NXLibrary/Views/Components/BuildStageStepperView.swift) | Disegna elenco delle fasi e relativo stato di completamento. |
| [Sources/NXLibrary/Views/Components/DropZoneView.swift](../Sources/NXLibrary/Views/Components/DropZoneView.swift) | Presenta la zona di trascinamento per scegliere le sorgenti del gioco. |
-| [Sources/NXLibrary/Views/Components/GameIconProvider.swift](../Sources/NXLibrary/Views/Components/GameIconProvider.swift) | Fornisce e conserva l’icona estratta dai bundle dei giochi. |
+| [Sources/NXLibrary/Views/Components/GameIconProvider.swift](../Sources/NXLibrary/Views/Components/GameIconProvider.swift) | Fornisce e conserva l’icona estratta dai bundle dei giochi; ricorda anche quando manca. |
| [Sources/NXLibrary/Views/Components/PortingArtLook.swift](../Sources/NXLibrary/Views/Components/PortingArtLook.swift) | Applica alla tile desaturazione, riempimento e barra di avanzamento del porting. |
| [Sources/NXLibrary/Views/Components/ScreenshotViewer.swift](../Sources/NXLibrary/Views/Components/ScreenshotViewer.swift) | Mostra screenshot a schermo pieno e navigazione fra le immagini. |
-| [Sources/NXLibrary/Views/Components/SeleneBottomScrim.swift](../Sources/NXLibrary/Views/Components/SeleneBottomScrim.swift) | Definisce maschera inferiore e spazi riservati ai suggerimenti dei tasti. |
+| [Sources/NXLibrary/Views/Components/SeleneBottomScrim.swift](../Sources/NXLibrary/Views/Components/SeleneBottomScrim.swift) | Definisce sfumatura inferiore, posizione condivisa dei comandi (32 unità dal fondo) e fascia libera dai contenuti. |
| [Sources/NXLibrary/Views/Components/SeleneConfirmDialog.swift](../Sources/NXLibrary/Views/Components/SeleneConfirmDialog.swift) | Definisce card e pulsanti delle conferme, scelte multiple e SeleneSuccessNotice. |
| [Sources/NXLibrary/Views/Components/AppUpdateDialog.swift](../Sources/NXLibrary/Views/Components/AppUpdateDialog.swift) | Presenta controllo aggiornamenti, note di release, errori e progresso nel dialogo dell’app. |
-| [Sources/NXLibrary/Views/Components/SeleneHintsBar.swift](../Sources/NXLibrary/Views/Components/SeleneHintsBar.swift) | Disegna i suggerimenti contestuali allineati ai bordi inferiori della schermata. |
-| [Sources/NXLibrary/Views/Components/SeleneHomeChrome.swift](../Sources/NXLibrary/Views/Components/SeleneHomeChrome.swift) | Rende elementi condivisi della cornice e dei controlli della home Selene. |
+| [Sources/NXLibrary/Views/Components/SeleneHintsBar.swift](../Sources/NXLibrary/Views/Components/SeleneHintsBar.swift) | Disegna i suggerimenti contestuali alla posizione condivisa, con grandezza dei simboli invariata. |
+| [Sources/NXLibrary/Views/Components/SeleneHomeChrome.swift](../Sources/NXLibrary/Views/Components/SeleneHomeChrome.swift) | Rende elementi condivisi della cornice e dei controlli della home Selene; trattiene gli hint durante l’entrata. |
| [Sources/NXLibrary/Views/Components/SeleneOptionRow.swift](../Sources/NXLibrary/Views/Components/SeleneOptionRow.swift) | Disegna righe di opzioni con icona, titolo, descrizione, focus e contenuto laterale. |
+| [Sources/NXLibrary/Views/Components/SeleneExpandableText.swift](../Sources/NXLibrary/Views/Components/SeleneExpandableText.swift) | Rivela la descrizione completa animando l'altezza fra due layout di testo stabili; usato solo dalle righe dei metadati. |
| [Sources/NXLibrary/Views/Components/SelenePillButton.swift](../Sources/NXLibrary/Views/Components/SelenePillButton.swift) | Disegna il pulsante pill condiviso da azioni e dialoghi. |
| [Sources/NXLibrary/Views/Components/SelenePromptBadge.swift](../Sources/NXLibrary/Views/Components/SelenePromptBadge.swift) | Rende simbolo o etichetta del pulsante del controller o della tastiera. |
+| [Sources/NXLibrary/Views/Components/GlideGroup.swift](../Sources/NXLibrary/Views/Components/GlideGroup.swift) | Fa muovere un blocco come un pezzo unico durante una scivolata (pagina Spotlight, lista Achievements, pannello Mod, pagina gioco, riga Collection): una dissolvenza, un'immagine che arriva o un'altra animazione non fanno più correre i singoli elementi a velocità diversa. Usa `geometryGroup`, quindi richiede macOS 14. |
| [Sources/NXLibrary/Views/Components/SeleneReveal.swift](../Sources/NXLibrary/Views/Components/SeleneReveal.swift) | Applica l’animazione di comparsa Selene rispettando la preferenza Riduci movimento. |
| [Sources/NXLibrary/Views/Components/SeleneSettingsRow.swift](../Sources/NXLibrary/Views/Components/SeleneSettingsRow.swift) | Disegna righe delle impostazioni con valore, focus e azione. |
| [Sources/NXLibrary/Views/Components/SeleneStatsRow.swift](../Sources/NXLibrary/Views/Components/SeleneStatsRow.swift) | Disegna le statistiche compatte del gioco nella libreria. |
@@ -419,10 +551,14 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Sources/NXLibrary/Views/Components/SeleneTileRing.swift](../Sources/NXLibrary/Views/Components/SeleneTileRing.swift) | Ring e riflesso della tile selezionata; con Reduce motion il ring fermo disegnato da SwiftUI. |
| [Sources/NXLibrary/Views/Components/TileMotionLayers.swift](../Sources/NXLibrary/Views/Components/TileMotionLayers.swift) | Ring e riflesso come layer Core Animation in loop: nessun ridisegno dell'app tra un frame e l'altro. |
| [Sources/NXLibrary/Views/Components/SeleneValueChip.swift](../Sources/NXLibrary/Views/Components/SeleneValueChip.swift) | Rende valori e badge compatti nel linguaggio visivo Selene. |
-| [Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift](../Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift) | Carica e disegna l’artwork quadrato usato dalle tile Spotlight. |
+| [Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift](../Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift) | Disegna subito l’icona nxnative già decodificata; cache condivisa `TileArtMemo` con fonte e revisione delle scelte, caricamento annullabile e segnale `TileArtPendingKey`. |
| [Sources/NXLibrary/Views/Components/SwitchBoxArtCover.swift](../Sources/NXLibrary/Views/Components/SwitchBoxArtCover.swift) | Carica e disegna la copertina Switch mantenendone le proporzioni. |
| [Sources/NXLibrary/Views/Components/SteamGridDBKeyDialog.swift](../Sources/NXLibrary/Views/Components/SteamGridDBKeyDialog.swift) | Popup per incollare e verificare la chiave SteamGridDB da Settings → Look e da Change artwork. |
| [Sources/NXLibrary/Views/Components/SwitchPlatformIcon.swift](../Sources/NXLibrary/Views/Components/SwitchPlatformIcon.swift) | Icona vettoriale della console Switch per la riga della piattaforma. |
+| [Sources/NXLibrary/Views/Components/SteamPlatformLogo.swift](../Sources/NXLibrary/Views/Components/SteamPlatformLogo.swift) | Logo ufficiale Steam per la piattaforma dei giochi Steam: da solo, almeno 50 pixel, spazio libero della manovella. |
+| [Sources/NXLibrary/Views/Components/GameLogoArea.swift](../Sources/NXLibrary/Views/Components/GameLogoArea.swift) | Area del logo del gioco con la geometria condivisa da Spotlight e Collection; caricamento e impostazioni restano fuori. |
+| [Sources/NXLibrary/Views/Components/GamePrimaryActions.swift](../Sources/NXLibrary/Views/Components/GamePrimaryActions.swift) | Play, Options e preferito con lo stesso aspetto e gli stessi bersagli di input per ogni fonte; i puntini di «Porting» e «Downloading». |
+| [Sources/NXLibrary/Views/Components/SessionCard.swift](../Sources/NXLibrary/Views/Components/SessionCard.swift) | Card di fine sessione: aspetta che Arcane sia davanti, compare 1,8 s dopo per 8 s; una sessione più recente sostituisce quella in attesa. |
## UI · temi, rendering e sfondi
@@ -432,13 +568,46 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Sources/NXLibrary/Views/Theme/SeleneTheme.swift](../Sources/NXLibrary/Views/Theme/SeleneTheme.swift) | Espone colori, stili, curve di animazione, focus e chiavi dell’ambiente Selene. |
| [Sources/NXLibrary/Views/Theme/SeleneFonts.swift](../Sources/NXLibrary/Views/Theme/SeleneFonts.swift) | Registra il font incluso e definisce MaterialIconView. |
| [Sources/NXLibrary/Views/Theme/SeleneCanvasEnvironment.swift](../Sources/NXLibrary/Views/Theme/SeleneCanvasEnvironment.swift) | Pubblica il canvas della finestra e applica unità e font scalati. |
-| [Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift](../Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift) | Compone gradiente, wallpaper e Moonlight e conserva le immagini già decodificate. |
-| [Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift](../Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift) | Gestisce device Metal, pipeline, display link, particelle e rendering live o statico del backdrop. |
-| [Sources/NXLibrary/Views/Theme/MoonlightShaders.swift](../Sources/NXLibrary/Views/Theme/MoonlightShaders.swift) | Contiene le sorgenti shader Metal dello sfondo compilate a runtime. |
+| [Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift](../Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift) | Nella shell dichiara la richiesta di sfondo condiviso, fuori dalla shell disegna; consuma lo snapshot completo della palette e compone gradiente, wallpaper e Moonlight a particelle morbide; conserva le immagini decodificate e il fallback statico. |
+| [Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift](../Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift) | Gestisce Metal, display link e rendering live/statico; su entrambi i percorsi il primo drawable presentato sblocca `LaunchReveal`. Da macOS 14 disegna solo il `CAMetalDisplayLink`, anche il frame fermo; nella Dev registra creazione e prima presentazione. |
+| [Sources/NXLibrary/Views/Theme/MoonlightShaders.swift](../Sources/NXLibrary/Views/Theme/MoonlightShaders.swift) | Contiene gli shader Metal del Moonlight, superfici analitiche Arcane/Flow, filamenti sottili antialias piegati da onde viaggianti e particelle morbide, compilati a runtime. |
| [Sources/NXLibrary/Views/Theme/LiveBackdrop.swift](../Sources/NXLibrary/Views/Theme/LiveBackdrop.swift) | Integra video AVFoundation in loop e adatta riproduzione e frame alla visibilità della finestra. |
| [Sources/NXLibrary/Views/Theme/OnlineBrowsePanel.swift](../Sources/NXLibrary/Views/Theme/OnlineBrowsePanel.swift) | Mantiene stato di ricerca e download e presenta griglia e miniature degli sfondi online. |
-| [Sources/NXLibrary/Views/Theme/ThemePickerView.swift](../Sources/NXLibrary/Views/Theme/ThemePickerView.swift) | Presenta palette, tab Wallpapers/Live, provider e scelta della destinazione dello sfondo. |
-| [Sources/NXLibrary/Views/Theme/ThemePreview.swift](../Sources/NXLibrary/Views/Theme/ThemePreview.swift) | Disegna un’anteprima della home con palette e sfondo in valutazione. |
+| [Sources/NXLibrary/Views/Theme/ThemePickerView.swift](../Sources/NXLibrary/Views/Theme/ThemePickerView.swift) | Presenta i colori con anteprima viva nel primo passo; sfondi, provider e destinazione nel passo successivo. |
+| [Sources/NXLibrary/Views/Theme/ThemePreview.swift](../Sources/NXLibrary/Views/Theme/ThemePreview.swift) | Disegna un’anteprima della home con palette, sfondo e particelle morbide; il movimento segue le preferenze. |
+| [Sources/NXLibrary/Views/Theme/AppLocaleEnvironment.swift](../Sources/NXLibrary/Views/Theme/AppLocaleEnvironment.swift) | Contesto della lingua reattivo per le viste; conserva identità, selezione e focus. |
+
+## UI · fonti, Steam e libreria mista
+
+| File | Responsabilità |
+|---|---|
+| [AppViewModel+Catalog.swift](../Sources/NXLibrary/ViewModels/AppViewModel+Catalog.swift) | Rilettura, errori e retry del risultato di build senza libreria di ripiego. |
+| [CatalogPersonalizationsEnvironment.swift](../Sources/NXLibrary/Views/Theme/CatalogPersonalizationsEnvironment.swift) | Dipendenza SwiftUI esplicita per le chiavi personali stabili. |
+| [AppViewModel+Sources.swift](../Sources/NXLibrary/ViewModels/AppViewModel+Sources.swift) | Proiezione visibile, selezione comune e modifiche personali tipizzate. |
+| [SettingsSourcesSection.swift](../Sources/NXLibrary/Views/Settings/SettingsSourcesSection.swift) | Attivazione, refresh/cancel, cartella Steam, avvio in background, revisione e recupero dei nascosti. |
+| [CatalogNativeArtwork.swift](../Sources/NXLibrary/Views/Catalog/CatalogNativeArtwork.swift) | Icona nativa in sola lettura e indicatore Steam; nessun artwork Nintendo. |
+| [CatalogSteamInfo.swift](../Sources/NXLibrary/Views/Catalog/CatalogSteamInfo.swift) | Intestazione condivisa nelle due librerie: Play/Riprendi/Annulla/Riprova, Opzioni e preferito, con la nota di stato. |
+| [SteamPlayCoordinator.swift](../Sources/NXLibrary/Services/SteamPlayCoordinator.swift) | Play tramite il client verificato dopo la preparazione della schermata. La schermata copre Steam durante l'attesa. Sessioni dal processo dell’app installata. |
+| [SteamPlaytimeCoordinator.swift](../Sources/NXLibrary/Services/SteamPlaytimeCoordinator.swift) | Una lettura alla volta delle ore di Steam fuori dal thread principale; applica `SteamPlaytimeSync` e passa i totali a `PlaySessionStore`. |
+| [SteamOptionsView.swift](../Sources/NXLibrary/Views/GameOptions/SteamOptionsView.swift) | Opzioni di un gioco Steam con l’aspetto e l’input di Game options: Play, Edit details, Move, preferito, nascosto, Finder. |
+| [PersonalizationSubject.swift](../Sources/NXLibrary/Views/GameOptions/PersonalizationSubject.swift) | Il gioco che Change artwork e Change metadata personalizzano: scelte nxnative o archivio personale Steam, senza icona Mac per Steam. |
+| [SteamGamePage.swift](../Sources/NXLibrary/Views/Catalog/SteamGamePage.swift) | Dati store Steam dei giochi a schermo, una copia condivisa da Spotlight e Collection, per AppID e lingua; una risposta per un gioco o una lingua non più chiesti si scarta. |
+| [SteamArtwork.swift](../Sources/NXLibrary/Views/Catalog/SteamArtwork.swift) | Immagini Steam con cache disponibile prima del task, identità di richiesta/build e ripiego già letto; rivalidazione dei file, scelte personali, annullamento e `TileArtPendingKey`. |
+| [SteamPersonalizations.swift](../Sources/NXLibrary/Views/Catalog/SteamPersonalizations.swift) | Archivio delle scelte personali Steam (metadati e artwork), modificate da Change artwork e Change metadata. |
+
+## UI · achievement
+
+| File | Responsabilità |
+|---|---|
+| [SteamAchievementsStore.swift](../Sources/NXLibrary/Services/SteamAchievementsStore.swift) | Legge gli achievement fuori dal thread principale (selezione, apertura della schermata e, per il gioco selezionato, fine di una sessione Steam: subito e dopo un minuto), uno per AppID alla volta; tiene gli ultimi 16 giochi e aggiunge la rarità quando arriva. |
+| [ArcaneOrbVideo.swift](../Sources/NXLibrary/Views/Spotlight/ArcaneOrbVideo.swift) | L'Arcane della card come video: grigio e fermo a riposo, a colori e in movimento con hover o focus, si ferma sul suo fotogramma e riparte da lì; colore, luce e scala animati da Core Animation. Usato anche, grande e sempre attivo, in testa alla schermata Achievements quando l'Arcane è conquistato. |
+| [DetailsAchievementsCard.swift](../Sources/NXLibrary/Views/Detail/DetailsAchievementsCard.swift) | Card Achievements in cima alla colonna destra della pagina, sopra il pannello Details; prende il focus e apre la schermata. |
+| [AchievementIcon.swift](../Sources/NXLibrary/Views/Detail/AchievementIcon.swift) | Icona di un achievement dalla cache di `SteamMetadataService`, decodificata fuori dal thread principale e tenuta in memoria (niente lampo quando una riga torna in vista), con un riquadro neutro finché manca; un segreto non sbloccato è sfocato sotto un lucchetto. |
+| [AchievementsScreen.swift](../Sources/NXLibrary/Views/Spotlight/AchievementsScreen.swift) | Schermata Achievements sopra l’arte del gioco, impaginata come Selene: logo e sbloccati di recente a sinistra; a destra i cristalli per tier con sotto percentuale, barra larga quanto i quattro cristalli e conteggio (`TrophyColumn`), oppure, a gioco completato, il medaglione dell’Arcane (video, nome, conteggio e piccoli cristalli Oro/Argento/Bronzo); filtri tra LB e RB (Q/E su tastiera), ordine (Y) in basso a destra accanto a Open, con Q/E e LB/RB compatti ai lati delle categorie e barra alla posizione condivisa; lista e sfumatura lasciano libera la fascia dei comandi e lista in una colonna mossa da un offset proprio (niente ScrollView), disegnando solo le righe in vista. |
+| [AchievementDetail.swift](../Sources/NXLibrary/Views/Spotlight/AchievementDetail.swift) | Dettaglio di un obiettivo come medaglione (A sulla riga o clic sulla riga in focus): icona grande con il cristallo della tier come piccolo distintivo sull’angolo, nome e descrizione interi centrati, percentuale dei giocatori, data di sblocco; le frecce scorrono la lista, A/B o un clic fuori chiudono. |
+| [TierCrystal.swift](../Sources/NXLibrary/Views/Spotlight/TierCrystal.swift) | Il cristallo di una tier dalle risorse del Core, decodificato una volta; non ancora ottenuto, tenue con una traccia del suo colore, così oro, argento e bronzo restano distinguibili. |
+| [AchievementsScreenModel.swift](../Sources/NXLibrary/ViewModels/AchievementsScreenModel.swift) | Schermata Achievements aperta: selezione, filtro, input e scorrimento della lista; un riferimento, così un passo non ridisegna la Spotlight sotto. Dopo la rotella la prima freccia porta il fuoco alla riga in vista più vicina. |
+| [ListScroll.swift](../Sources/NXLibrary/ViewModels/ListScroll.swift) | Offset di una lista (`TextScroll`) con la planata del pannello delle mod: rotella, trackpad e frecce muovono lo stesso valore. |
## Test e fixture
@@ -453,11 +622,15 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| File | Responsabilità |
|---|---|
| [Tests/NXLibraryCoreTests/ActivitySummaryTests.swift](../Tests/NXLibraryCoreTests/ActivitySummaryTests.swift) | Totali settimanali, distribuzione giornaliera, sessioni aperte e passaggi di mezzanotte. |
-| [Tests/NXLibraryCoreTests/AppRouterTests.swift](../Tests/NXLibraryCoreTests/AppRouterTests.swift) | Route iniziale, ritorno, overlay e richieste di selezione o spostamento. |
-| [Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift](../Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift) | Default, persistenza, errori osservabili, conservazione dei file illeggibili e compatibilità dei campi mancanti. |
+| [Tests/NXLibraryCoreTests/AppBundleRenameTests.swift](../Tests/NXLibraryCoreTests/AppBundleRenameTests.swift) | Rinomina alla chiusura: nome vecchio, `Arcane.app` già presente, cartella in sola lettura, copia Dev, traslocata o occupata, altri nomi, spostamento fallito. |
+| [Tests/NXLibraryCoreTests/AppRouterTests.swift](../Tests/NXLibraryCoreTests/AppRouterTests.swift) | Route iniziale, ritorno, overlay, richieste Spotlight e precedenza/occlusione delle coperture fullscreen. |
+| [Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift](../Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift) | Default, errori, recupero, compatibilità e ultima selezione persistita in background e alla chiusura, senza invalidare gli osservatori. |
| [Tests/NXLibraryCoreTests/AppSizeCacheTests.swift](../Tests/NXLibraryCoreTests/AppSizeCacheTests.swift) | Riuso delle dimensioni, invalidazione sui bundle modificati e scansione senza falso stato vuoto. |
-| [Tests/NXLibraryCoreTests/AppUpdateTests.swift](../Tests/NXLibraryCoreTests/AppUpdateTests.swift) | Versioni, asset release, requisiti, digest, identità del bundle e sostituzione dell’app. |
+| [Tests/NXLibraryCoreTests/AppUpdateTests.swift](../Tests/NXLibraryCoreTests/AppUpdateTests.swift) | Versioni, asset release, requisiti, digest, identità del bundle, collisioni con copie esistenti e guasti di copia, scambio e Cestino. |
| [Tests/NXLibraryCoreTests/AppUpdatePresentationTests.swift](../Tests/NXLibraryCoreTests/AppUpdatePresentationTests.swift) | Verifica che i controlli manuali non permettano sostituzioni di copie di sviluppo, in sola lettura o con una versione uguale/più recente. |
+| [Tests/NXLibraryCoreTests/ArcaneWelcomeTests.swift](../Tests/NXLibraryCoreTests/ArcaneWelcomeTests.swift) | Una volta dopo l'aggiornamento, mai dopo un primo Setup né con un recupero in corso, decodifica di un file vecchio, offerta di Steam, focus e uscite. |
+| [Tests/NXLibraryCoreTests/ShellOverlayInputTests.swift](../Tests/NXLibraryCoreTests/ShellOverlayInputTests.swift) | Ogni monitor della tastiera che cede all'offerta di aggiornamento cede anche al benvenuto, così Invio non arriva alla schermata sotto. |
+| [Tests/NXLibraryCoreTests/ArcaneNameTests.swift](../Tests/NXLibraryCoreTests/ArcaneNameTests.swift) | Nessun testo del catalogo, in nessuna lingua, mostra il vecchio nome; User-Agent con il nome Arcane e nessuna sorgente con il vecchio. |
| [Tests/NXLibraryCoreTests/ArtworkPickerFocusTests.swift](../Tests/NXLibraryCoreTests/ArtworkPickerFocusTests.swift) | Spostamenti nella griglia dei candidati e passaggi fra slot di artwork. |
| [Tests/NXLibraryCoreTests/ArtworkPickerTests.swift](../Tests/NXLibraryCoreTests/ArtworkPickerTests.swift) | Decodifica Title DB, candidati per slot e scelte manuali. |
| [Tests/NXLibraryCoreTests/AutomaticIconTests.swift](../Tests/NXLibraryCoreTests/AutomaticIconTests.swift) | Priorità delle fonti, ambiguità, edizioni, cache offline, immagini invalide e opt-out del sito. |
@@ -467,7 +640,7 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Tests/NXLibraryCoreTests/BuildEventParserTests.swift](../Tests/NXLibraryCoreTests/BuildEventParserTests.swift) | Eventi JSON, fasi, percentuali e righe ordinarie di log. |
| [Tests/NXLibraryCoreTests/BuildOutputInstallerTests.swift](../Tests/NXLibraryCoreTests/BuildOutputInstallerTests.swift) | Pubblicazione atomica, interruzioni, tentativi ripetuti, copie fra volumi e conservazione dei bundle in caso di errore. |
| [Tests/NXLibraryCoreTests/BuildScratchTests.swift](../Tests/NXLibraryCoreTests/BuildScratchTests.swift) | Posto dei file di build per Mac, disco esterno, exFAT e workspaces spostati; workspace gestiti e cartelle temporanee. |
-| [Tests/NXLibraryCoreTests/BuildServiceTests.swift](../Tests/NXLibraryCoreTests/BuildServiceTests.swift) | Processi, eventi, cancellazione, lease e conservazione della build dopo un errore d’installazione, con retry senza nuova esecuzione del motore. |
+| [Tests/NXLibraryCoreTests/BuildServiceTests.swift](../Tests/NXLibraryCoreTests/BuildServiceTests.swift) | Processi, eventi, cancellazione, lease e conservazione della build dopo un errore d’installazione, con retry senza nuova esecuzione del motore; un avvio fallito non lascia file aperti. |
| [Tests/NXLibraryCoreTests/GameAppDestinationTests.swift](../Tests/NXLibraryCoreTests/GameAppDestinationTests.swift) | Installazione e scoperta nella cartella scelta, rebuild dopo il cambio cartella, conflitti di nome, sorgenti protette e cartelle non disponibili o di sola lettura. |
| [Tests/NXLibraryCoreTests/ButtonPromptsTests.swift](../Tests/NXLibraryCoreTests/ButtonPromptsTests.swift) | Etichette e simboli per tastiera, controller e scelte esplicite dell’utente. |
| [Tests/NXLibraryCoreTests/CheatCopyTests.swift](../Tests/NXLibraryCoreTests/CheatCopyTests.swift) | Testi di intestazione, rifiuto, conferma e rimozione dei cheats. |
@@ -512,16 +685,17 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Tests/NXLibraryCoreTests/LaunchBoxArtTests.swift](../Tests/NXLibraryCoreTests/LaunchBoxArtTests.swift) | Risultati di ricerca, scelta della voce Switch/Switch 2, payload Nuxt con file pieni e screenshot. |
| [Tests/NXLibraryCoreTests/LibraryPresentationTests.swift](../Tests/NXLibraryCoreTests/LibraryPresentationTests.swift) | Formattazione dei metadati e delle statistiche della libreria. |
| [Tests/NXLibraryCoreTests/LibraryQueryTests.swift](../Tests/NXLibraryCoreTests/LibraryQueryTests.swift) | Filtri, ricerca, ordinamento e rapporto con la cronologia di gioco. |
-| [Tests/NXLibraryCoreTests/LibraryStoreTests.swift](../Tests/NXLibraryCoreTests/LibraryStoreTests.swift) | Persistenza, merge, recupero e conservazione di installazioni in attesa ed errori dopo scansioni ripetute. |
+| [Tests/NXLibraryCoreTests/NXNativeCatalogPersistenceTests.swift](../Tests/NXLibraryCoreTests/NXNativeCatalogPersistenceTests.swift) | Persistenza e merge nxnative attraverso il repository attuale: sorgenti, impostazioni, preferiti, installazioni in attesa e dettagli degli errori. Recupero e conversione legacy sono verificati da CatalogStoreTests. |
| [Tests/NXLibraryCoreTests/MaterialIconTests.swift](../Tests/NXLibraryCoreTests/MaterialIconTests.swift) | Integrità dei glifi e del font delle icone. |
| [Tests/NXLibraryCoreTests/MetadataPickerTests.swift](../Tests/NXLibraryCoreTests/MetadataPickerTests.swift) | Alternative per campo, override persistiti e applicazione ai metadati del gioco. |
| [Tests/NXLibraryCoreTests/MoonlightFieldTests.swift](../Tests/NXLibraryCoreTests/MoonlightFieldTests.swift) | Generazione deterministica e limiti dei dati delle particelle. |
+| [MoonlightAppearanceTests.swift](../Tests/NXLibraryCoreTests/MoonlightAppearanceTests.swift) | Ignora la preferenza storica delle particelle senza perdere altri valori; continuità del ciclo e bordi della griglia colori. |
| [Tests/NXLibraryCoreTests/MoreArtworkSourcesTests.swift](../Tests/NXLibraryCoreTests/MoreArtworkSourcesTests.swift) | Matching dei titoli e risposte delle sorgenti artwork aggiuntive. |
-| [Tests/NXLibraryCoreTests/MoreLikeThisTests.swift](../Tests/NXLibraryCoreTests/MoreLikeThisTests.swift) | Ranking dei giochi correlati e gestione di metadati incompleti. |
+| [Tests/NXLibraryCoreTests/MoreLikeThisTests.swift](../Tests/NXLibraryCoreTests/MoreLikeThisTests.swift) | Ranking condiviso, precedenza Steam e ripiego Switch, giochi nascosti e metadati incompleti. |
| [Tests/NXLibraryCoreTests/NintendoStoreMetadataTests.swift](../Tests/NXLibraryCoreTests/NintendoStoreMetadataTests.swift) | Decodifica store e Title DB, cache, screenshot e risposte incomplete. |
| [Tests/NXLibraryCoreTests/ReleaseNotesLayoutTests.swift](../Tests/NXLibraryCoreTests/ReleaseNotesLayoutTests.swift) | Titoli, voci e righe vuote delle note di release, una voce per riga. |
| [Tests/NXLibraryCoreTests/NewestEngineTests.swift](../Tests/NXLibraryCoreTests/NewestEngineTests.swift) | Lock e Metal di main, validità della scelta, comandi git del cambio, gate Newest engine, scheda Setup e frase. |
-| [Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift](../Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift) | Magic NUP, cartelle, lettura tramite engine, nomi NACP, profili mancanti, selezione e NUP senza base. |
+| [Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift](../Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift) | NUP storici, multiprogramma e soli update; identità DLC, JSON, capacità checkout, programma zero nei vecchi record e argv coerenti. |
| [Tests/NXLibraryCoreTests/NXNativeGameSettingsTests.swift](../Tests/NXLibraryCoreTests/NXNativeGameSettingsTests.swift) | Build senza adattatore, migrazione da env.txt, scrittura dei soli valori diversi dal default e chiavi fissate. |
| [Tests/NXLibraryCoreTests/OnlineArtworkSourcesTests.swift](../Tests/NXLibraryCoreTests/OnlineArtworkSourcesTests.swift) | Ricerca Steam e loghi MediaWiki/Commons con risposte sintetiche. |
| [Tests/NXLibraryCoreTests/OnlineBackgroundsTests.swift](../Tests/NXLibraryCoreTests/OnlineBackgroundsTests.swift) | Parser degli sfondi fissi, risoluzioni, crediti e nomi dei download. |
@@ -531,36 +705,43 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Tests/NXLibraryCoreTests/PortedGameTests.swift](../Tests/NXLibraryCoreTests/PortedGameTests.swift) | Modello del gioco, compatibilità dei record e condizioni di disponibilità dell’app. |
| [Tests/NXLibraryCoreTests/PortingFailureReasonTests.swift](../Tests/NXLibraryCoreTests/PortingFailureReasonTests.swift) | Classificazione dei fallimenti e corrispondenza con i messaggi del pin, anche da un checkout separato scelto con NX_TEST_ENGINE_REPO. |
| [Tests/NXLibraryCoreTests/PortingNoticeTests.swift](../Tests/NXLibraryCoreTests/PortingNoticeTests.swift) | Condizioni e testi delle notifiche di esito del porting. |
-| [Tests/NXLibraryCoreTests/PortingPresentationTests.swift](../Tests/NXLibraryCoreTests/PortingPresentationTests.swift) | ETA, tile, pill e rappresentazione dei fallimenti del porting. |
+| [Tests/NXLibraryCoreTests/PortingPresentationTests.swift](../Tests/NXLibraryCoreTests/PortingPresentationTests.swift) | ETA, attività del prewarm senza stime storiche, tile, pill e rappresentazione dei fallimenti del porting. |
| [Tests/NXLibraryCoreTests/AppIconPreferenceTests.swift](../Tests/NXLibraryCoreTests/AppIconPreferenceTests.swift) | Ambito dell’icona: scelta esplicita, vecchie librerie, scansioni, persistenza e rebuild. |
| [Tests/NXLibraryCoreTests/AppIconProgressTests.swift](../Tests/NXLibraryCoreTests/AppIconProgressTests.swift) | Verifica che l'esito di un'icona mancante non sovrascriva il log o segnali una build fallita. |
| [Tests/NXLibraryCoreTests/IconLaunchWaitTests.swift](../Tests/NXLibraryCoreTests/IconLaunchWaitTests.swift) | Attesa Play: successo, errore, annullamento, gioco diverso e nuova firma in coda. |
| [Tests/NXLibraryCoreTests/PipelineArchiveProgressTests.swift](../Tests/NXLibraryCoreTests/PipelineArchiveProgressTests.swift) | Log obsoleti, righe incomplete, cache riusata, gruppi paralleli e GPU diverse. |
-| [Tests/NXLibraryCoreTests/PortingProgressTests.swift](../Tests/NXLibraryCoreTests/PortingProgressTests.swift) | Aggregazione delle fasi, avanzamento monotono e peso degli shader. |
+| [Tests/NXLibraryCoreTests/PortingProgressTests.swift](../Tests/NXLibraryCoreTests/PortingProgressTests.swift) | Aggregazione delle fasi, avanzamento monotono, peso degli shader e avvisi di archivio/prewarm. |
| [Tests/NXLibraryCoreTests/ProdKeysLocationsTests.swift](../Tests/NXLibraryCoreTests/ProdKeysLocationsTests.swift) | Selezione e validazione dei possibili percorsi delle chiavi. |
| [Tests/NXLibraryCoreTests/RunningGamesTests.swift](../Tests/NXLibraryCoreTests/RunningGamesTests.swift) | Associazione bundle ID, applicazioni aperte e voci della libreria. |
| [Tests/NXLibraryCoreTests/RyujinxSaveImportTests.swift](../Tests/NXLibraryCoreTests/RyujinxSaveImportTests.swift) | Contenitori e slot Ryujinx, identità del titolo e importazioni con strutture e destinazioni differenti. |
| [Tests/NXLibraryCoreTests/SaveLocationTests.swift](../Tests/NXLibraryCoreTests/SaveLocationTests.swift) | Identificativi, percorsi sicuri, precedenze dell’ambiente e cloud effettivo. |
| [Tests/NXLibraryCoreTests/SaveOperationGateTests.swift](../Tests/NXLibraryCoreTests/SaveOperationGateTests.swift) | Lease per titolo, esclusione globale dell’updater, operazioni concorrenti e recupero bloccato senza I/O attivo. |
-| [Tests/NXLibraryCoreTests/SavePresentationTests.swift](../Tests/NXLibraryCoreTests/SavePresentationTests.swift) | Riepiloghi, date, nomi degli slot e accessibilità dell’azione di importazione. |
+| [Tests/NXLibraryCoreTests/SavePresentationTests.swift](../Tests/NXLibraryCoreTests/SavePresentationTests.swift) | Azioni e messaggi del pannello; distingue backup storico/completo e limite cloud. |
| [Tests/NXLibraryCoreTests/SaveSnapshotStoreTests.swift](../Tests/NXLibraryCoreTests/SaveSnapshotStoreTests.swift) | Inventari, xattr, integrità dei backup, staging e selezione dei backup datati. |
+| [MultiuserSaveTests.swift](../Tests/NXLibraryCoreTests/MultiuserSaveTests.swift) | Backup e restore utenti/registro, compatibilità storica, import circoscritti, fault injection e conservazione di dati cambiati da fuori. |
| [Tests/NXLibraryCoreTests/SaveTestHome.swift](../Tests/NXLibraryCoreTests/SaveTestHome.swift) | Fixture condivisa che crea una home e un bundle sintetici in una directory temporanea dedicata. |
| [Tests/NXLibraryCoreTests/SaveTransactionTests.swift](../Tests/NXLibraryCoreTests/SaveTransactionTests.swift) | Sostituzioni, interruzioni, rollback, modifiche esterne e compatibilità dei journal precedenti. |
| [Tests/NXLibraryCoreTests/ScreenshotViewerStateTests.swift](../Tests/NXLibraryCoreTests/ScreenshotViewerStateTests.swift) | Indice, avanzamento e limiti del visualizzatore screenshot. |
| [Tests/NXLibraryCoreTests/SeleneCanvasTests.swift](../Tests/NXLibraryCoreTests/SeleneCanvasTests.swift) | Scala, centratura e conversione delle unità del canvas. |
| [Tests/NXLibraryCoreTests/SeleneImporterTests.swift](../Tests/NXLibraryCoreTests/SeleneImporterTests.swift) | Copia delle risorse Selene e risoluzione dei cue sonori. |
-| [Tests/NXLibraryCoreTests/SelenePaletteTests.swift](../Tests/NXLibraryCoreTests/SelenePaletteTests.swift) | Lettura delle palette, ordine e fallback. |
-| [Tests/NXLibraryCoreTests/SettingsCatalogTests.swift](../Tests/NXLibraryCoreTests/SettingsCatalogTests.swift) | Catalogo delle righe, ricerca e identificazione dei valori modificati. |
+| [Tests/NXLibraryCoreTests/SelenePaletteTests.swift](../Tests/NXLibraryCoreTests/SelenePaletteTests.swift) | Lettura delle 25 palette, valori RGB e fallback storici del blu, alternative Crystal/Flow, persistenza ID, ordine e fallback. |
+| [Tests/NXLibraryCoreTests/SettingsCatalogTests.swift](../Tests/NXLibraryCoreTests/SettingsCatalogTests.swift) | Catalogo delle righe, ricerca, valori modificati, identità invariate, sezioni e gruppi in ordine, reset delle righe spostate. |
| [Tests/NXLibraryCoreTests/SetupActionsTests.swift](../Tests/NXLibraryCoreTests/SetupActionsTests.swift) | Comandi Git del Setup e rispetto delle modifiche locali nel checkout. |
| [Tests/NXLibraryCoreTests/SetupCheckTests.swift](../Tests/NXLibraryCoreTests/SetupCheckTests.swift) | Stati delle schede, requisiti, override e condizioni di riapertura del Setup. |
| [Tests/NXLibraryCoreTests/SetupGridTests.swift](../Tests/NXLibraryCoreTests/SetupGridTests.swift) | Bilanciamento delle righe e spostamento del focus fra le schede. |
-| [Tests/NXLibraryCoreTests/FirstRunSetupTests.swift](../Tests/NXLibraryCoreTests/FirstRunSetupTests.swift) | Skip persistente, ripresa, riapertura manuale senza reset, attesa della scansione, separazione dei requisiti e navigazione del primo gioco. |
+| [Tests/NXLibraryCoreTests/FirstRunSetupTests.swift](../Tests/NXLibraryCoreTests/FirstRunSetupTests.swift) | Pagina iniziale, Porting, scelta Steam acceso/spento dopo interruzione, completamento e pulizia della scelta salvata, focus, scansione e ripresa. |
+| [Tests/NXLibraryCoreTests/FirstRunFindingsTests.swift](../Tests/NXLibraryCoreTests/FirstRunFindingsTests.swift) | Steam assente, solo giochi Mac pronti, zero giochi, errore/parziale distinto da assenza, annullamento e app portate contate. |
| [Tests/NXLibraryCoreTests/SmokeTests.swift](../Tests/NXLibraryCoreTests/SmokeTests.swift) | Importabilità e versione nominale del modulo Core. |
+| [Tests/NXLibraryCoreTests/CriticRatingTests.swift](../Tests/NXLibraryCoreTests/CriticRatingTests.swift) | Abbinamenti esatti, metriche e piattaforme, stelle proporzionali, cache offline, richieste seriali/condivise, errori e annullamento delle valutazioni. |
+| [Tests/NXLibraryCoreTests/IGDBRatingTests.swift](../Tests/NXLibraryCoreTests/IGDBRatingTests.swift) | Credenziali 0600 sintetiche, isolamento degli host, voti critica/utenti, rinnovo accesso, annullamento, cache offline e ripiego Wikidata. |
+| [Tests/NXLibraryCoreTests/IGDBMetadataTests.swift](../Tests/NXLibraryCoreTests/IGDBMetadataTests.swift) | Identità, ruoli, date precise per piattaforma, Steam, cache offline, retry, annullamento e token/coda condivisi. |
+| [Tests/NXLibraryCoreTests/DatabaseMetadataTests.swift](../Tests/NXLibraryCoreTests/DatabaseMetadataTests.swift) | Parser pubblici, identità/ambiguità, date, conteggio richieste, letture concorrenti, cache, annullamento, risposte errate e retry. |
| [Tests/NXLibraryCoreTests/SourceCatalogTests.swift](../Tests/NXLibraryCoreTests/SourceCatalogTests.swift) | Fixture PFS0/CNMT e riconoscimento di base, aggiornamenti e DLC. |
| [Tests/NXLibraryCoreTests/EngineUpgradeSourcesTests.swift](../Tests/NXLibraryCoreTests/EngineUpgradeSourcesTests.swift) | Copre cartelle estratte, pacchetti multipli, selezione, persistenza, bridge Python, file illeggibili e restaging senza perdita di cache o originali. |
| [Tests/NXLibraryCoreTests/SpotlightPageTests.swift](../Tests/NXLibraryCoreTests/SpotlightPageTests.swift) | Estratti del testo e stati dello scorrimento della pagina del gioco. |
-| [Tests/NXLibraryCoreTests/SpotlightRowTests.swift](../Tests/NXLibraryCoreTests/SpotlightRowTests.swift) | Ordine, card, riordino delle tile e selezione Surprise. |
+| [Tests/NXLibraryCoreTests/SpotlightRowTests.swift](../Tests/NXLibraryCoreTests/SpotlightRowTests.swift) | Ordine, card, riordino delle tile, gioco avviato primo nell’ordine salvato e selezione Surprise. |
| [Tests/NXLibraryCoreTests/SpotlightStateTests.swift](../Tests/NXLibraryCoreTests/SpotlightStateTests.swift) | Focus, selezione, filtri, azioni e spostamento delle tile Spotlight. |
+| [Tests/NXLibraryCoreTests/SpotlightEntranceTests.swift](../Tests/NXLibraryCoreTests/SpotlightEntranceTests.swift) | Partenze, tempi di volo e dissolvenza, bordi, durata, messaggio vuoto, avanzamento degli effetti e fasi dell’entrata; interruttore e Riduci movimento. |
| [Tests/NXLibraryCoreTests/StorageManagerTests.swift](../Tests/NXLibraryCoreTests/StorageManagerTests.swift) | Misure per gioco, cache condivise e nascoste, pulizia selettiva, protezione di app/sorgenti/symlink, file incoerenti e volumi/cartelle non disponibili. |
| [Tests/NXLibraryCoreTests/ThemePickerTests.swift](../Tests/NXLibraryCoreTests/ThemePickerTests.swift) | Navigazione della griglia, tab e selezione degli sfondi. |
| [Tests/NXLibraryCoreTests/ToolchainGateCopyTests.swift](../Tests/NXLibraryCoreTests/ToolchainGateCopyTests.swift) | Testi del gate per Metal certificato, precedente, successivo e altre cause di blocco. |
@@ -571,39 +752,118 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| [Tests/NXLibraryCoreTests/WallpaperCatalogTests.swift](../Tests/NXLibraryCoreTests/WallpaperCatalogTests.swift) | Catalogo dei file inclusi/importati, gruppi e tipi immagine/video. |
| [Tests/NXLibraryCoreTests/WallpaperPlacementTests.swift](../Tests/NXLibraryCoreTests/WallpaperPlacementTests.swift) | Destinazione dello sfondo fra home e impostazioni. |
| [Tests/NXLibraryCoreTests/WorkspaceManagerTests.swift](../Tests/NXLibraryCoreTests/WorkspaceManagerTests.swift) | Collegamenti simbolici, cache adottate e rilevamento dei link interrotti. |
+| [Tests/NXLibraryCoreTests/AppIconWriterTests.swift](../Tests/NXLibraryCoreTests/AppIconWriterTests.swift) | Icona scelta scritta e ripristinata, originale ricordato anche se assente, ricostruzione dell’app, firma fallita senza modifiche, icona rifilata e opaca. |
+| [Tests/NXLibraryCoreTests/BackdropArtTests.swift](../Tests/NXLibraryCoreTests/BackdropArtTests.swift) | Arte tenuta fra un gioco e l’altro e mai fra card e gioco, dissolvenze sull’orologio come Core Animation, livelli coperti tolti e scorrimento rapido. |
+| [Tests/NXLibraryCoreTests/BoundedDownloadTests.swift](../Tests/NXLibraryCoreTests/BoundedDownloadTests.swift) | Blocchi raccolti fino al limite, corpo o lunghezza dichiarata oltre il limite rifiutati, nessun redirect, annullamento della lettura. |
+| [Tests/NXLibraryCoreTests/DetailsFactsTests.swift](../Tests/NXLibraryCoreTests/DetailsFactsTests.swift) | Righe Details per Switch e Steam: ordine, valori mancanti o vuoti nascosti, mai la versione Steam, solo crediti durante il download, simboli. |
+| [Tests/NXLibraryCoreTests/DetailsReviewFixTests.swift](../Tests/NXLibraryCoreTests/DetailsReviewFixTests.swift) | Play costruisce un gioco non ancora costruito con le sorgenti; nome di cartella o volume letto una volta per URL. |
+| [Tests/NXLibraryCoreTests/EngineRuntimeRequirementsTests.swift](../Tests/NXLibraryCoreTests/EngineRuntimeRequirementsTests.swift) | Il runtime incluso porta ogni pacchetto Python che il motore fissato chiede (riga `pip install` del README e `tools.txt`). |
+| [Tests/NXLibraryCoreTests/GameFocusTests.swift](../Tests/NXLibraryCoreTests/GameFocusTests.swift) | Ritorno della libreria davanti solo per il gioco in primo piano, mai con un altro gioco aperto, uscita contata una volta. |
+| [Tests/NXLibraryCoreTests/ModStoreModelTests.swift](../Tests/NXLibraryCoreTests/ModStoreModelTests.swift) | Store delle mod da copia fresca o vecchia, abbinamenti incerti o sicuri, ordine della libreria, copie di un altro gioco, chiusura senza perdite. |
+| [Tests/NXLibraryCoreTests/SessionSummaryTests.swift](../Tests/NXLibraryCoreTests/SessionSummaryTests.swift) | Card di fine sessione: gioco, sessione e totale, meno di un minuto, sessioni troppo brevi o in corso, altri giochi, giochi Steam. |
+| [Tests/NXLibraryCoreTests/SettingsRowButtonsTests.swift](../Tests/NXLibraryCoreTests/SettingsRowButtonsTests.swift) | Riga con due pulsanti: Sinistra/Destra fra i pulsanti, uscita dalla riga, riga con un solo pulsante, A preme quello in focus. |
+| [Tests/NXLibraryCoreTests/SpotlightRowGeometryTests.swift](../Tests/NXLibraryCoreTests/SpotlightRowGeometryTests.swift) | Posto a schermo = camera più posto nella riga, tessere che restano ferme durante lo scorrimento, distanze costanti e quattro tessere di riserva ai bordi. |
+| [Tests/NXLibraryCoreTests/TileMotionTests.swift](../Tests/NXLibraryCoreTests/TileMotionTests.swift) | Periodi e curve di bagliore, ring e riflesso, campioni che chiudono il loop senza salti, fase nel periodo e simbolo del download. |
+| [Tests/NXLibraryCoreTests/AppLocaleTests.swift](../Tests/NXLibraryCoreTests/AppLocaleTests.swift) | Preferenze, migrazione, formati, ricerca, identità e traduzioni native; avvisi pipeline localizzati senza output tecnico grezzo. |
+| [Tests/PublicationChecks/test_localizations.py](../Tests/PublicationChecks/test_localizations.py) | Rifiuto di cataloghi incompleti e bundle senza risorse. |
+| [DevelopmentProfileTests.swift](../Tests/NXLibraryCoreTests/DevelopmentProfileTests.swift) | Copia, conservazione della sorgente, errori, sessioni, symlink e ripetizione. |
+| [DevelopmentProfileEffectTests.swift](../Tests/NXLibraryCoreTests/DevelopmentProfileEffectTests.swift) | Isolamento Dev, staging e richieste esplicite. Verifica anche che la riconciliazione delle mod conservi record e overlay dopo un errore di lettura. |
+| [test_profile_boundaries.py](../Tests/PublicationChecks/test_profile_boundaries.py) | Guardia contro percorsi/defaults del launcher non centralizzati. |
+| [SteamKeyValuesTests.swift](../Tests/NXLibraryCoreTests/SteamKeyValuesTests.swift) | Formato, escape, Unicode, duplicati, input troncati e limiti del parser. |
+| [SteamPlaytimeReaderTests.swift](../Tests/NXLibraryCoreTests/SteamPlaytimeReaderTests.swift) | Campi letti, ultima partita, scelta dell’account, duplicati e tipi errati di blocchi/scalari, file grandi, malformati o non sicuri. |
+| [SteamPlaytimeBaselinesTests.swift](../Tests/NXLibraryCoreTests/SteamPlaytimeBaselinesTests.swift) | Base mantenuta o ripartita, minuto conservato, cambio account, salvataggio e mappatura sul catalogo. |
+| [SteamReturnFocusTests.swift](../Tests/NXLibraryCoreTests/SteamReturnFocusTests.swift) | Ritorno ad Arcane solo per Play premuto qui, gioco davanti e nessun altro gioco aperto. |
+| [SteamLaunchQuestionsTests.swift](../Tests/NXLibraryCoreTests/SteamLaunchQuestionsTests.swift) | Fase `ShowInterstitials` a freddo, domande aperte o risposte subito, log per righe intere e sostituzione del file. |
+| [SteamPlaytimeSyncTests.swift](../Tests/NXLibraryCoreTests/SteamPlaytimeSyncTests.swift) | Letture con o senza account, file illeggibili, file invariato, regole di pubblicazione e coda delle letture. |
+| [NativeMacApplicationTests.swift](../Tests/NXLibraryCoreTests/NativeMacApplicationTests.swift) | Fixture native, classificazione, traversal/link, metadata non regolari e header invalidi. |
+| [SteamLibrarySourceTests.swift](../Tests/NXLibraryCoreTests/SteamLibrarySourceTests.swift) | Più fonti, dischi assenti, identità, manifest/path con campi duplicati o di tipo errato, file cambiati, limiti e assenza di scritture. |
+| [SteamDiscoveryConsistencyTests.swift](../Tests/NXLibraryCoreTests/SteamDiscoveryConsistencyTests.swift) | Mutazioni reali di inventario e app durante scan, indice inizialmente assente, budget e propagazione dell'annullamento. |
+| [SteamTestSupport.swift](../Tests/NXLibraryCoreTests/SteamTestSupport.swift) | Genera solo metadati e header sintetici nelle directory temporanee dei test. |
+| [SteamPlayStateTests.swift](../Tests/NXLibraryCoreTests/SteamPlayStateTests.swift) | Symlink, passaggio senza sessione, Play doppi e risposte tardive, rifiuti e timeout, giochi già aperti, argomenti silenziosi, pazienza di Steam a freddo e schermata di lancio. |
+| [SteamBinaryKeyValuesTests.swift](../Tests/NXLibraryCoreTests/SteamBinaryKeyValuesTests.swift) | Tipi, annidamento, fine dei dati, input troncati, tipi ignoti e limiti del parser binario. |
+| [SteamAchievementReaderTests.swift](../Tests/NXLibraryCoreTests/SteamAchievementReaderTests.swift) | Percorsi, account e file mancanti/non sicuri, lingue con ripiego anche su stringhe vuote duplicate, primo valore tipizzato, nascosti, icone, ordine numerico e file corrotti. |
+| [SteamAchievementRarityTests.swift](../Tests/NXLibraryCoreTests/SteamAchievementRarityTests.swift) | Percentuali numeriche o testuali (non numeriche scartate), host e percorso ammessi, cache di un giorno, cache vecchia offline, icone in cache, coda oltre sei download con annullamento, errore recente senza attesa e file che non sono immagini. |
+| [AchievementSummaryTests.swift](../Tests/NXLibraryCoreTests/AchievementSummaryTests.swift) | Conteggi, gioco completato, ordini dei filtri, rarità sconosciute in fondo, soglia del raro, maschera dei nascosti e icone recenti (segreti compresi). |
+| [AchievementsScreenStateTests.swift](../Tests/NXLibraryCoreTests/AchievementsScreenStateTests.swift) | Movimento in due colonne, bordi, liste vuote, cambio filtro e liste che si accorciano. |
+| [GridListLayoutTests.swift](../Tests/NXLibraryCoreTests/GridListLayoutTests.swift) | Linee, altezza, posizione delle righe, spazio da mostrare, linee visibili e riga in vista più vicina dopo la rotella. |
+| [AchievementTierTests.swift](../Tests/NXLibraryCoreTests/AchievementTierTests.swift) | Soglie, tier dalla percentuale mostrata, ordine dal più raro, conteggi per tier, Arcane solo al 100% e mai senza achievement, miglior tier ottenuto, rarità sconosciuta. |
+| [SteamManifestWatcherTests.swift](../Tests/NXLibraryCoreTests/SteamManifestWatcherTests.swift) | Filtri e durata dello stream; eventi reali da librerie tornate disponibili, da sole o accanto a una già osservata, inclusa la normalizzazione `/private`. |
+| [CatalogModelTests.swift](../Tests/NXLibraryCoreTests/CatalogModelTests.swift) | Conservazione del record precedente, proprietà comuni e separazione delle azioni per integrazione. |
+| [CatalogStoreTests.swift](../Tests/NXLibraryCoreTests/CatalogStoreTests.swift) | Conversione, backup, corruzione, versioni, input cambiati, scrittori concorrenti e guasti di pubblicazione. |
+| [SteamCatalogReconcilerTests.swift](../Tests/NXLibraryCoreTests/SteamCatalogReconcilerTests.swift) | Identità, aggiornamenti, installazioni ambigue, fonti assenti e scansioni obsolete/parziali. |
+| [CatalogTestSupport.swift](../Tests/NXLibraryCoreTests/CatalogTestSupport.swift) | Record legacy sintetico completo e scrittura di fixture; nessun contenuto di gioco. |
+| [CatalogRepositoryTests.swift](../Tests/NXLibraryCoreTests/CatalogRepositoryTests.swift) | Modifiche concorrenti, confini per integrazione, campi build e conservazione di Steam/legacy. |
+| [CatalogRecoveryTests.swift](../Tests/NXLibraryCoreTests/CatalogRecoveryTests.swift) | Recupero esplicito, conflitto legacy senza fusione, archivi, offerte obsolete, guasti di pubblicazione, restore point e importazione Dev. |
+| [CatalogPersonalizationTests.swift](../Tests/NXLibraryCoreTests/CatalogPersonalizationTests.swift) | Rinomina senza perdita del lookup e isolamento di chiavi uguali tra fonti. |
+| [CatalogBuildRecoveryTests.swift](../Tests/NXLibraryCoreTests/CatalogBuildRecoveryTests.swift) | Vecchia build persistita e nuova conservata, sospensione automatica e conferme obsolete. |
+| [run_notices.py](../Tests/CatalogAppChecks/run_notices.py) | Esegue i metodi reali degli avvisi e del ponte legacy senza finestre, dopo swift test. |
+| [run_review.py](../Tests/CatalogAppChecks/run_review.py) | Verifica achievement, loghi, focus, navigazione, lettura Mods e priorità dei dialoghi. Prova Steam che riappare durante Play e aspetta il completamento del task che gestisce il ripiego del pannello. Dati sintetici, senza finestre. |
+| [run_startup_recovery.py](../Tests/CatalogAppChecks/run_startup_recovery.py) | Coordinatore di avvio reale su profili sintetici: conflitto, scelta esplicita, offerta obsoleta, Retry e fallimento della preparazione; nessuna finestra. |
+| [run_source_access.py](../Tests/CatalogAppChecks/run_source_access.py) | Esegue il ripristino di avvio, l'observer e i selettori reali: nessuna scansione automatica dei sorgenti, cartella ricordata, annullamento e lettura dei soli file scelti; nessuna finestra o dato personale. |
+| [run_onboarding.py](../Tests/CatalogAppChecks/run_onboarding.py) | Esegue observer e ripristino del Setup, uscita durante lettura pendente con annullamento, input sotto modali, scelte acceso/spento/nil, radice della fonte, focus dopo Retry e richiesta notifiche su dati sintetici; nessuna finestra. |
+| [run_artwork_return.py](../Tests/CatalogAppChecks/run_artwork_return.py) | Viste, task e host Mods reali su fixture: primo body con arte warm, scelte personali, aggiornamenti Steam nello stesso percorso, badge dopo rimozione, cambi abbinamento e snapshot completato fuori ordine; nessuna finestra o rendering. |
+| [run_nested_bundles.py](../Tests/CatalogAppChecks/run_nested_bundles.py) | App sintetiche con bundle dati annidati e firme reali: installazione, icona, rollback, copia forzata, ripresa e rifiuto di dati alterati; nessuna UI. |
+| [run_nup_programs.py](../Tests/CatalogAppChecks/run_nup_programs.py) | Esegue il probe NUP opzionale su snapshot sintetico, convertitori UI reali, persistenza e argv del rebuild. |
+| [run_save_restart.py](../Tests/CatalogAppChecks/run_save_restart.py) | Arresti reali e nuovi processi nei checkpoint di transazione, recovery e pulizia; verifica tutti gli utenti, registro e integrità dei backup su fixture temporanee. |
+| [run_entrance.py](../Tests/CatalogAppChecks/run_entrance.py) | Esegue i metodi reali di input e readiness: nessun comando agisce o salta l’entrata prima dell’atterraggio, precedenza delle coperture, drawable mancante e presentazione su entrambi i percorsi. Nessuna finestra o GPU reale. |
+| [run_icon_cache.py](../Tests/CatalogAppChecks/run_icon_cache.py) | Esegue il vero `GameIconProvider`: un gioco senza icona non si rilegge dal disco a ogni disegno; dopo `forget` o la build si legge di nuovo. |
+| [run_theme.py](../Tests/CatalogAppChecks/run_theme.py) | Regressioni delle richieste condivise (precedenza, frame mantenuto e pausa) e del cambio palette a wallpaper/card invariati con snapshot e apply reali, ordine Look e input del selettore; shader Metal fuori schermo, colori locali GPU/Core, profilo sottile, deformazione delle onde, superfici distinte, frame fermo e uniform Mods. |
+| [run_achievement_scroll.py](../Tests/CatalogAppChecks/run_achievement_scroll.py) | Verifica fuori schermo la vera lista e i modelli durante riaperture rapide, dettagli della prima riga, ridimensionamento e Riduci movimento; nessuna finestra o automazione UI. |
+| [run_game_header.py](../Tests/CatalogAppChecks/run_game_header.py) | Esegue i corpi reali di logo e azioni condivisi senza finestra né store applicativi, per entrambi i layout. |
+| [NoticeHost.swift](../Tests/CatalogAppChecks/NoticeHost.swift) | Host minimo per i controlli applicativi, con storage reale e dati sintetici temporanei. |
+| [SharedGamePresentationTests.swift](../Tests/NXLibraryCoreTests/SharedGamePresentationTests.swift) | Presentazione Steam con identità, personalizzazioni e cronologia; prima installazione disponibile coerente per artwork e dettagli, con Play bloccato se ambiguo; confine nxnative e opzioni comuni. |
+| [CatalogSourcesRepositoryTests.swift](../Tests/NXLibraryCoreTests/CatalogSourcesRepositoryTests.swift) | Compatibilità generazioni, cambi fonte, preferenze concorrenti e adozione NX esplicita. |
+| [CatalogSourcesModelTests.swift](../Tests/NXLibraryCoreTests/CatalogSourcesModelTests.swift) | Opt-in, annullamento, cambio radice, recupero errori e intervallo tra riscansioni, misurato dagli avvii pubblicati dal modello. |
+| [CatalogLibraryQueryTests.swift](../Tests/NXLibraryCoreTests/CatalogLibraryQueryTests.swift) | Visibilità, ricerca/filtri misti e selezione per UUID senza sessioni simulate. |
+| [SteamOptionsTests.swift](../Tests/NXLibraryCoreTests/SteamOptionsTests.swift) | Righe delle opzioni Steam come quelle comuni nxnative, niente di nxnative, Play e Finder spenti senza installazione, artwork e impostazione «Keep Steam in the background». |
+| [SteamMetadataTests.swift](../Tests/NXLibraryCoreTests/SteamMetadataTests.swift) | Identità, lingue, offline, URL, concorrenza, tratti correlati in cache ed esito del salvataggio. |
+| [SteamArtworkRequestTests.swift](../Tests/NXLibraryCoreTests/SteamArtworkRequestTests.swift) | Quadrato dall’icona originale e mai dalla copertina, scelta personale prima, link che escono dal bundle ignorati, icona automatica solo senza app. |
+| [SteamAutomaticIconTests.swift](../Tests/NXLibraryCoreTests/SteamAutomaticIconTests.swift) | Quadrato LaunchBox della voce PC preso intero, scaricato una volta e conservato; nessun quadrato non si richiede di nuovo nella sessione. |
+| [SteamBackdropChoiceTests.swift](../Tests/NXLibraryCoreTests/SteamBackdropChoiceTests.swift) | Solo arte in formato schermo, ordine store → screenshot → banner, fan art LaunchBox fra store e screenshot, ripiego sulla prima immagine che si carica. |
+| [test_app_bundle.py](../Tests/PublicationChecks/test_app_bundle.py) | Verifica che il bundle del launcher rinunci a Game Mode. |
## Script di sviluppo e packaging
| File | Responsabilità |
|---|---|
| [scripts/build_app.sh](../scripts/build_app.sh) | Compila in staging, prepara plist, runtime e risorse, verifica la firma e pubblica il bundle con sostituzione atomica. |
-| [scripts/install_built_app.swift](../scripts/install_built_app.swift) | Piccolo ingresso CLI che riusa BuildOutputInstaller per installare NX Library dopo il packaging. |
+| [scripts/install_built_app.swift](../scripts/install_built_app.swift) | Piccolo ingresso CLI che riusa BuildOutputInstaller per installare Arcane dopo il packaging. |
| [scripts/check_publication.py](../scripts/check_publication.py) | Rifiuta contenuti personali o di gioco versionati e formati di segreto riconoscibili; verifica il runtime rispetto al lock prima del packaging. |
| [scripts/build_dmg.sh](../scripts/build_dmg.sh) | Confeziona un bundle già costruito in un’immagine DMG di sviluppo. |
| [scripts/bundle_runtime.sh](../scripts/bundle_runtime.sh) | Prepara Python e strumenti dalle versioni bloccate, verifica gli hash e firma il runtime incluso. |
-| [scripts/release.sh](../scripts/release.sh) | Controlla i prerequisiti e produce ZIP e DMG di release, con pubblicazione esplicita opzionale. |
+| [scripts/release.sh](../scripts/release.sh) | Controlla prerequisiti, suite Swift e tutti gli script headless delle regressioni app; produce ZIP e DMG di release, con pubblicazione esplicita opzionale. |
| [scripts/validate_update.py](../scripts/validate_update.py) | Verifica struttura, percorsi e limiti degli archivi prima dell'estrazione, sia nel bundle sia durante il packaging delle release. |
| [scripts/relink_macho.py](../scripts/relink_macho.py) | Riscrive riferimenti Mach-O dei binari e delle librerie affinché il runtime incluso sia rilocabile. |
| [scripts/make_icons.swift](../scripts/make_icons.swift) | Genera le risorse dell’icona dell’app nelle varianti usate dal bundle. |
| [scripts/import_selene_palettes.py](../scripts/import_selene_palettes.py) | Converte le palette Selene nel catalogo JSON usato dall’app. |
+| [scripts/check_localizations.py](../scripts/check_localizations.py) | Verifica copertura, placeholder, plurali e risorse nel bundle installato. |
+| [scripts/check_metadata_text_layout.swift](../scripts/check_metadata_text_layout.swift) | Verifica fuori schermo il layout delle descrizioni e la destinazione dello scroll dopo cambi di focus, anche rapidi e con Riduci movimento. |
+| [check_app_profile.swift](../scripts/check_app_profile.swift) | Prova senza UI di identità, accesso reale alle preferenze e percorsi nel pacchetto prodotto dalla build; non importa né scrive dati. |
## Risorse incluse
| File | Responsabilità aggiuntiva |
|---|---|
-| [Resources/IconArtwork.png](../Resources/IconArtwork.png) | Master quadrato originale dell’icona, fornito dall’utente e creato con AI. |
+| [Resources/IconArtwork.png](../Resources/IconArtwork.png) | Master quadrato originale dell’icona (cristallo nella sfera di vetro), fornito dall’utente e creato con AI. |
| [Resources/IconArtwork.md](../Resources/IconArtwork.md) | Provenienza dichiarata, brief e riproduzione delle varianti tramite il generatore. |
+| [crystal-arcane.png](../Sources/NXLibraryCore/Resources/crystal-arcane.png) | Immagine ferma del trofeo Arcane, anche come ripiego del video. |
+| [crystal-arcane.mov](../Sources/NXLibraryCore/Resources/crystal-arcane.mov) | Animazione con alpha del trofeo Arcane. |
+| [crystal-gold.png](../Sources/NXLibraryCore/Resources/crystal-gold.png) | Immagine del trofeo Oro. |
+| [crystal-silver.png](../Sources/NXLibraryCore/Resources/crystal-silver.png) | Immagine del trofeo Argento. |
+| [crystal-bronze.png](../Sources/NXLibraryCore/Resources/crystal-bronze.png) | Immagine del trofeo Bronzo. |
| File | Responsabilità |
|---|---|
-| [Resources/AppIcon.icns](../Resources/AppIcon.icns) | Icona macOS del bundle NX Library. |
+| [Resources/AppIcon.icns](../Resources/AppIcon.icns) | Icona macOS del bundle Arcane. |
| [Resources/AppIcon-Dark.png](../Resources/AppIcon-Dark.png) | Variante scura dell’icona dell’app. |
| [Resources/AppIcon-Light.png](../Resources/AppIcon-Light.png) | Variante chiara dell’icona dell’app. |
| [Resources/AppIcon-Mono.png](../Resources/AppIcon-Mono.png) | Variante monocromatica dell’icona dell’app. |
-| [Resources/Selene/palettes.json](../Resources/Selene/palettes.json) | Catalogo serializzato delle palette disponibili. |
+| [Resources/Selene/palettes.json](../Resources/Selene/palettes.json) | Catalogo delle 25 palette: blu classico predefinito, Arcane Crystal e Arcane Flow come superfici opzionali. |
| [Resources/Selene/Fonts/MaterialIcons-Regular.ttf](../Resources/Selene/Fonts/MaterialIcons-Regular.ttf) | Font dei glifi Material Icons disegnati dalla UI. |
| [Resources/Selene/Fonts/MaterialIcons-LICENSE.txt](../Resources/Selene/Fonts/MaterialIcons-LICENSE.txt) | Licenza del font Material Icons incluso. |
| [Resources/Selene/NOTICE.txt](../Resources/Selene/NOTICE.txt) | Attribuzioni delle risorse Selene incluse. |
+| [Resources/Brands/SteamLogo.png](../Resources/Brands/SteamLogo.png) | Logo Steam inverso dalle linee guida Valve, inalterato; attribuzione in `NOTICE`. |
+| [Resources/Brands/BuyMeACoffee.png](../Resources/Brands/BuyMeACoffee.png) | Icona gialla dal kit ufficiale Buy Me a Coffee per il pulsante di sostegno; attribuzione in `NOTICE`. |
| [Resources/Selene/NOTICE-palettes.txt](../Resources/Selene/NOTICE-palettes.txt) | Attribuzioni delle palette incluse con esse. |
| [Resources/Selene/Sounds/Boot.wav](../Resources/Selene/Sounds/Boot.wav) | Cue sonoro incluso per l’avvio. |
| [Resources/Selene/Sounds/Key.wav](../Resources/Selene/Sounds/Key.wav) | Cue sonoro incluso per la pressione dei tasti. |
@@ -614,12 +874,13 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| File | Responsabilità |
|---|---|
-| [docs/media/README.md](../docs/media/README.md) | Registra provenienza e posizione degli screenshot, ottimizzazione delle copie e inserimento del video futuro. |
+| [docs/media/README.md](../docs/media/README.md) | Registra i media del README e la loro posizione. |
| [docs/media/spotlight.webp](../docs/media/spotlight.webp) | Presenta Spotlight e la libreria nell'apertura del README. |
| [docs/media/game-details.webp](../docs/media/game-details.webp) | Mostra dettagli, attività e informazioni di build di un gioco. |
+| [docs/media/mod-store.webp](../docs/media/mod-store.webp) | Presenta lo store delle mod nel README. |
| [docs/media/quick-menu.webp](../docs/media/quick-menu.webp) | Illustra il menu rapido sopra la libreria. |
| [docs/media/porting-progress.webp](../docs/media/porting-progress.webp) | Mostra l'avanzamento di un porting dalla schermata Spotlight. |
-| [docs/media/settings.webp](../docs/media/settings.webp) | Illustra le categorie di Settings e il pannello Start-up. |
+| [docs/media/settings.webp](../docs/media/settings.webp) | Cattura storica di Settings in NX Library. |
| [docs/media/color-themes.webp](../docs/media/color-themes.webp) | Mostra la scelta delle palette con anteprima della libreria. |
| [docs/media/static-wallpapers.webp](../docs/media/static-wallpapers.webp) | Illustra il browser degli sfondi statici e la relativa anteprima. |
| [docs/media/live-wallpapers.webp](../docs/media/live-wallpapers.webp) | Mostra il selettore degli sfondi animati e l'importazione di video personali. |
@@ -628,7 +889,25 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
| File | Responsabilità |
|---|---|
-| [docs/architecture.md](../docs/architecture.md) | Spiega architettura corrente, confini dei componenti, flussi, dati su disco e verifiche. |
+| [docs/architecture.md](../docs/architecture.md) | Come funziona oggi ogni area: confini dei componenti, regole, dati su disco e verifiche; niente storia né stati di validazione. |
+| [docs/conventions.md](../docs/conventions.md) | Come si costruisce una cosa nuova: dove va il codice, ricette per fonte, schermata Selene, impostazione, file su disco, rete, testi, lavoro in background, test e documentazione. |
+| [docs/flows.md](../docs/flows.md) | Schemi dei flussi completi: avvio, libreria, Play Switch e Steam, Add Game, salvataggi, mod, impostazioni, aggiornamento dell’app. |
+| [docs/validation.md](../docs/validation.md) | Elenco unico di ciò che il maintainer ha validato o deve ancora provare, compresi i pin dell’engine. |
+| [docs/steam.md](../docs/steam.md) | Riferimento unico dell’integrazione Steam: file letti, stati, osservazione, libreria, Play, ore, achievement, scelte e limiti. |
+| [2026-11-18-spotlight-glide.md](../docs/reviews/2026-11-18-spotlight-glide.md) | Campioni dei primi cambi gioco e costo di mod e salvataggio selezione. |
+| [2026-11-18-steam-launch-spaces.md](../docs/reviews/2026-11-18-steam-launch-spaces.md) | Riscontro video e log dei cambi rapidi di Space durante Play Steam, causa e regressione. |
+| [2026-11-17-entrance-frames.md](../docs/reviews/2026-11-17-entrance-frames.md) | Metodo, campioni e limiti delle misure temporanee dell’entrata e del passaggio al fullscreen. |
+| [2026-11-17-dock-rename-probe.md](../docs/reviews/2026-11-17-dock-rename-probe.md) | Sonda: il Dock apre ancora un'app rinominata nella stessa cartella. |
+| [docs/reviews/2026-11-17-arcane-moonlight.md](../docs/reviews/2026-11-17-arcane-moonlight.md) | Contratti provati fuori schermo e tempi GPU del Moonlight prima/dopo, con limiti delle misure. |
+| [2026-11-16-ratings-metadata-evidence.md](../docs/reviews/2026-11-16-ratings-metadata-evidence.md) | Prove e misure dietro le scelte di voti e metadati: abbinamenti Wikidata, console Switch 2 in IGDB, download a blocchi, movimento del selettore, sonde LaunchBox/TheGamesDB. |
+| [2026-11-09-hotfix-0.1.4.2.md](../docs/reviews/2026-11-09-hotfix-0.1.4.2.md) | Ambito della release 0.1.4.2, autorizzazione del maintainer e verifiche ancora non confermate. |
+| [04df08d4 → b2d46b86](../docs/upstream-upgrades/2026-11-06-04df08d4-b2d46b86-review.md) | Revisione del delta engine del 6 novembre e compatibilità della toolchain. |
+| [b2d46b86 → 7fe9fc4d](../docs/upstream-upgrades/2026-11-07-b2d46b86-7fe9fc4d-review.md) | Revisione engine del 7 novembre, shader e requisiti. |
+| [7fe9fc4d → e5f03403](../docs/upstream-upgrades/2026-11-07-7fe9fc4d-e5f03403-review.md) | Revisione engine del 7 novembre, eventi di progresso e prompt dei controller. |
+| [e5f03403 → bd979ced](../docs/upstream-upgrades/2026-11-08-e5f03403-bd979ced-review.md) | Revisione engine dell’8 novembre e nuova catena di traduzione shader. |
+| [bd979ced → 79741184](../docs/upstream-upgrades/2026-11-09-bd979ced-79741184-review.md) | Adozione engine per 0.1.4.2 e limiti della validazione registrata. |
+| [79741184 → 8a5c5e7e](../docs/upstream-upgrades/2026-11-12-79741184-8a5c5e7e-review.md) | Adozione engine per 0.1.4.3 e limiti della validazione registrata. |
+| [8a5c5e7e → 461a5f9f](../docs/upstream-upgrades/2026-11-18-8a5c5e7e-461a5f9f-review.md) | Revisione engine per 0.2.0, confronto con il commit già provato, scelte d'integrazione e prove del gate. |
| [docs/development.md](../docs/development.md) | Documenta prerequisiti, runtime, build, debug, verifiche, CI e preparazione delle release. |
| [docs/file-map.md](../docs/file-map.md) | Catalogo corrente delle responsabilità di tutti i file versionati, suddiviso per area. |
| [docs/upstream-upgrades/2026-10-27-06b7b3e-4f24ce6.md](../docs/upstream-upgrades/2026-10-27-06b7b3e-4f24ce6.md) | Registro della revisione del delta, scelte di adozione e verifiche per questo upgrade del motore. |
@@ -644,18 +923,4 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT
## Aggiornare questo catalogo
-Quando si aggiunge, rinomina o rimuove un file versionato, aggiornare la sua riga e il totale iniziale. Quando cambia un flusso o una responsabilità, aggiornare anche la sezione corrispondente della guida tecnica. Le descrizioni dei test indicano l’ambito dei controlli, mentre l’esito di esecuzione appartiene ai rapporti di verifica.
-
-## Localizzazione (hotfix non pubblicato)
-
-| File | Responsabilità |
-|---|---|
-| [Sources/NXLibraryCore/Models/AppLocale.swift](../Sources/NXLibraryCore/Models/AppLocale.swift) | Sei lingue, risoluzione delle preferenze e regione indipendente; nomi e ricerca delle regioni. |
-| [Sources/NXLibraryCore/Models/GameGenre.swift](../Sources/NXLibraryCore/Models/GameGenre.swift) | Generi noti tradotti alla presentazione; dati originali e generi personali conservati. |
-| [Sources/NXLibrary/Views/Theme/AppLocaleEnvironment.swift](../Sources/NXLibrary/Views/Theme/AppLocaleEnvironment.swift) | Contesto della lingua reattivo per le viste; conserva identità, selezione e focus. |
-| [Sources/NXLibraryCore/Services/AppLocalization.swift](../Sources/NXLibraryCore/Services/AppLocalization.swift) | Contesto osservabile, lookup portabile delle risorse e interpolazioni/plurali. |
-| [Sources/NXLibraryCore/Resources/Localizable.xcstrings](../Sources/NXLibraryCore/Resources/Localizable.xcstrings) | Testi condivisi e traduzioni en/it/fr/de/es/pt-BR. |
-| [Sources/NXLibrary/Views/Settings/LocalePicker.swift](../Sources/NXLibrary/Views/Settings/LocalePicker.swift) | Scelta diretta della lingua e ricerca dei formati regionali, con focus tastiera/controller e codici stabili. |
-| [Tests/NXLibraryCoreTests/AppLocaleTests.swift](../Tests/NXLibraryCoreTests/AppLocaleTests.swift) | Preferenze, migrazione, formati, ricerca, identità e traduzioni native. |
-| [scripts/check_localizations.py](../scripts/check_localizations.py) | Verifica copertura, placeholder, plurali e risorse nel bundle installato. |
-| [Tests/PublicationChecks/test_localizations.py](../Tests/PublicationChecks/test_localizations.py) | Rifiuto di cataloghi incompleti e bundle senza risorse. |
+Quando si aggiunge, rinomina o rimuove un file versionato, aggiornare la sua riga nella sezione della sua area e il totale iniziale; una funzione nuova non apre una sezione in fondo al catalogo. Le regole complete sono in [conventions.md](conventions.md#10-documentazione). Quando cambia un flusso o una responsabilità, aggiornare anche la sezione corrispondente della guida tecnica. Le descrizioni dei test indicano l’ambito dei controlli, mentre l’esito di esecuzione appartiene ai rapporti di verifica.
diff --git a/docs/flows.md b/docs/flows.md
new file mode 100644
index 00000000..5a696be1
--- /dev/null
+++ b/docs/flows.md
@@ -0,0 +1,191 @@
+# Arcane — i flussi principali
+
+Ogni flusso segue un'azione dall'input all'effetto, nominando i tipi che se ne occupano. I dettagli e le regole di ogni passo sono nella sezione dell'area in [architecture.md](architecture.md); come costruire un pezzo nuovo è in [conventions.md](conventions.md). Se un flusso cambia, il suo schema si aggiorna nello stesso commit.
+
+- [1. Avvio dell'app](#1-avvio-dellapp)
+- [2. Dal disco alla libreria](#2-dal-disco-alla-libreria)
+- [3. Play di un gioco Switch (nxnative)](#3-play-di-un-gioco-switch-nxnative)
+- [4. Play di un gioco Steam](#4-play-di-un-gioco-steam)
+- [5. Costruire un gioco Switch (Add Game)](#5-costruire-un-gioco-switch-add-game)
+- [6. Importare o ripristinare un salvataggio](#6-importare-o-ripristinare-un-salvataggio)
+- [7. Installare una mod](#7-installare-una-mod)
+- [8. Cambiare un'impostazione](#8-cambiare-unimpostazione)
+- [9. Aggiornare l'app](#9-aggiornare-lapp)
+
+## 1. Avvio dell'app
+
+```mermaid
+flowchart TD
+ A["NXLibraryApp (@main)"] --> B["DevelopmentStartupView
AppData.prepare: profilo release o Dev"]
+ B --> C["AppSettingsStore · lingua (AppLocalization)
LaunchReveal: finestra pronta, poi fullscreen"]
+ C --> D["CatalogStore legge catalog.json
(conversione da library.json se serve)"]
+ D -->|"archivio danneggiato"| R["Recupero esplicito: Retry / ripristino backup"]
+ D -->|"catalogo valido, legacy modificato"| L["Scelta Keep Arcane’s library"]
+ L --> LA["Rivalida impronte → archivia catalogo, backup e legacy
Mantieni i giochi Arcane e riconosci la base legacy"]
+ LA --> D
+ D --> E["AppShellState prepara coordinatore, router, tema"]
+ E --> F["AppShellView: AppViewModel, store, monitor, updater"]
+ F --> G{"Primo avvio completato?
(FirstRunSetup)"}
+ G -->|"no"| H["Setup: found (Steam, app portate) → Open library
oppure Porting → Get ready → Your games"]
+ G -->|"sì"| I["Benvenuto in Arcane una volta, per chi aggiorna
altrimenti home scelta"]
+ H --> K["Prima home Spotlight: moonlight condiviso → entrata
Entrance animation; niente volo con Riduci movimento"]
+ I --> K
+ F --> J["In background: recuperi dei salvataggi, installazioni in attesa,
scansione Steam se attivo, controllo engine se attivo, aggiornamenti"]
+```
+
+Punti fissi:
+- Gli store si costruiscono una volta sola, prima della shell.
+- Un archivio illeggibile non diventa mai una libreria vuota.
+- La Dev legge e scrive solo nel suo profilo.
+- La scelta Steam del primo Setup resta salvata anche alla chiusura; lettura e attivazione usano la cartella scelta nella fonte. Una lettura incompleta offre Retry, senza dichiarare la libreria vuota.
+- La cartella Game files ricordata resta una preferenza del selettore: l'avvio non ne enumera i sorgenti.
+- Menu e dialoghi nativi hanno precedenza sul routing della shell: `nativeDialogOwnsInput` ferma i comandi del controller anche se un benvenuto, Setup o dialogo dell'app è già aperto sotto.
+
+## 2. Dal disco alla libreria
+
+```mermaid
+flowchart TD
+ subgraph NX["Switch (nxnative)"]
+ N1["Cartella Game apps"] --> N2["ImportService
DMTitleID o org.nxnative.*"]
+ N2 --> N3["NXNativeLibraryMerge
conserva impostazioni, preferiti, build"]
+ end
+ subgraph ST["Steam"]
+ S1["libraryfolders.vdf + manifest"] --> S2["SteamLibrarySource
(worker annullabile, limiti)"]
+ S2 --> S3["SteamCatalogReconciler
ticket di revisione e radice"]
+ S4["SteamManifestWatcher (FSEvents)"] --> S2
+ end
+ N3 --> W["CatalogRepository
unico writer di catalog.json"]
+ S3 --> W
+ W --> P["CatalogLibraryProjection
solo fonti attive"]
+ P --> V["Spotlight · Collection · Ricerca
(stessi UUID, filtri, ordine)"]
+```
+
+Punti fissi:
+- Una scansione aggiorna solo ciò che ha osservato; un'assenza non cancella nulla.
+- Un risultato superato da un cambio di cartella o di fonte non si applica.
+
+## 3. Play di un gioco Switch (nxnative)
+
+```mermaid
+flowchart TD
+ A["Play (GamePrimaryActions)"] --> B["AppViewModel.launchGame"]
+ B --> C{"Possibile ora?"}
+ C -->|"operazione sui salvataggi o recupero"| X["Attesa / spiegazione"]
+ C -->|"icona in firma"| Y["Dialogo Preparing (IconLaunchWait)"]
+ C -->|"sì"| D["SaveOperationGate: lease del titolo"]
+ D --> E["LauncherSettings migra launcher.json
oppure LaunchService aggiorna env.txt"]
+ E --> F["CloudSavesPreferences applica la scelta cloud"]
+ F --> M["ModStore riconcilia le cartelle prima di Play"]
+ M --> G["LaunchService apre l'app (NSWorkspace)"]
+ G --> H["LaunchCoverWindow + LaunchMotion
finché LaunchReadinessProbe vede una finestra"]
+ H --> I["RunningGameMonitor · PlaySessionStore (heartbeat)"]
+ I --> J["Fine: sessione salvata → SessionCard
GameFocus/LibraryWindow riportano la libreria davanti"]
+ J --> K["Dopo la chiusura: icone, installazioni in attesa"]
+```
+
+## 4. Play di un gioco Steam
+
+```mermaid
+flowchart TD
+ A["Play (GamePrimaryActions)"] --> B["SteamPlayCoordinator"]
+ B --> K["LaunchCoverWindow
ripiego entro 1 s se il pannello manca"]
+ K --> C["steam://run/AppID al client di Valve"]
+ C --> D["SteamPlayState / SteamBackgroundLaunch
attesa del processo del gioco"]
+ D -->|"Domanda effettiva o scadenza"| Q["La schermata lascia spazio a Steam"]
+ D --> E["LaunchCoverWindow finché il gioco disegna"]
+ E --> F["PlaySessionStore registra la sessione reale"]
+ F --> G["Fine: SessionCard · SteamReturnFocus"]
+ G --> H["SteamPlaytimeSync rilegge le ore da localconfig.vdf"]
+```
+
+Arcane legge le domande dal log di Steam. Durante `ShowInterstitials` l'attesa prosegue e il client può aprire le sue finestre dietro la schermata. Arcane non scrive mai i file di Steam e non apre l'app del gioco direttamente. Dettagli in [steam.md](steam.md).
+
+Nella pagina Spotlight di un titolo Steam, Giù porta anche a **More like this** quando la fascia è presente. Invio, A o doppio clic selezionano la copertina sulla riga della libreria. Se il filtro la esclude, la libreria passa a **All games** come per Switch.
+
+## 5. Costruire un gioco Switch (Add Game)
+
+```mermaid
+flowchart TD
+ A["AddGameView: scelta esplicita di file o cartelle
il selettore ricorda Game files"] --> B["SourceCatalog · ExtractedSourceCatalog · NUPSourceCatalog
base, update, DLC"]
+ B --> C["SourceSelection: titolo e versioni scelte"]
+ C --> D["KeyCheck (se le sorgenti sono cifrate)
NUP: identità programma e capacità del checkout"]
+ D --> E["Review: GameAppDestination, GameRuntimeConfig.forReview"]
+ E --> F{"Gate: CompatibilityChecker
Metal certificato o override"}
+ F -->|"bloccato"| Z["Spiegazione (ToolchainGateCopy)
Play delle app esistenti resta attivo"]
+ F -->|"ok"| G["WorkspaceManager + BuildScratch"]
+ G --> N["Porting accettato: richiesta permesso notifiche"]
+ N --> H["BuildCommandBuilder → BuildService
processo dell'engine nxnative"]
+ H --> I["BuildEventParser → PortingProgress
tile, percentuale, ETA
prewarm senza conteggio: attività e tempo trascorso"]
+ I --> J["BuildOutputInstaller: scambio atomico"]
+ J -->|"gioco aperto o installazione fallita"| K["PendingInstall: Retry più tardi"]
+ J --> L["CatalogRepository: BuildRecord, toolchain"]
+ L --> M["AppIconWriter (se c'è un'icona scelta) · notifica"]
+```
+
+## 6. Importare o ripristinare un salvataggio
+
+```mermaid
+flowchart TD
+ A["SavesPanel"] --> B["SavePanelModel"]
+ B --> C["AppViewModel+Saves: SaveLocation, identità, cloud"]
+ C -->|"cloud attivo o gioco aperto"| X["Rifiuto con motivo (SaveFailure)"]
+ C --> D["SaveOperationGate: lease"]
+ D --> E["SaveSnapshotStore.stageImport / SaveRestorePreview
copia accanto, hash, anteprima From → To"]
+ E --> F["Conferma: sorgente, staging e salvataggio attuale
schema 1: due slot · schema 2: tutti gli utenti + registro"]
+ F --> G["SaveTransaction: backup completo → journal → soli pezzi da modificare
verifica originali; registro per ultimo"]
+ G --> H["SeleneSuccessNotice"]
+ G -.->|"interruzione"| I["Al prossimo avvio: rollback o verifica dal journal
Play attende"]
+```
+
+## 7. Installare una mod
+
+```mermaid
+flowchart TD
+ A["Fascia Mods o card Mods (store)"] --> B["GameBananaMatch: pagina del gioco"]
+ B --> C["AvailableModsFinder + ModSupport
solo mod RomFS che funzionano"]
+ C --> D["ModDetailPanel: Install"]
+ D --> E["ModDownload (host GameBanana) · dimensione e MD5"]
+ E --> F["ModInstaller: bsdtar, niente .. / link"]
+ F --> G["ModStore.adopt: ordine e stato in mods/TID.json"]
+ G --> H["EnvFileEditor scrive DM_ROMFS_OVERLAY in env.txt"]
+ H --> I["L'engine legge le mod al prossimo avvio del gioco"]
+```
+
+## 8. Cambiare un'impostazione
+
+```mermaid
+flowchart TD
+ A["Riga in Settings (SettingsCatalog)"] --> B["AppSettings modificato"]
+ B --> C["AppSettingsStore.save: file temporaneo e sostituzione"]
+ C -->|"errore"| X["Dialogo Selene con Retry"]
+ C --> D["Pubblicazione: le viste si aggiornano"]
+ A --> E["Search e Changed leggono lo stesso catalogo"]
+ F["Reset group (X)"] --> G["SettingsReset.reset: i valori della sezione tornano ai default"]
+ G --> B
+```
+
+Nel menu rapido, Theme apre prima i colori con anteprima viva; A applica la palette e passa alla selezione dello sfondo. Il tema Arcane conserva il blu classico e l’identità predefinita `selene`; le alternative Arcane Crystal e Arcane Flow salvano `arcane-crystal` e `arcane-flow` nello stesso `colorThemeID`. La shell conserva un backdrop persistente; le pagine ne dichiarano stile, pausa e Mods con `SeleneBackdropRequest`, mantenendo artwork e maschere locali. La shell passa la palette completa in `SeleneBackdropStyle`: cambia il valore dell’ambiente e aggiorna sfondo e maschere anche senza spostare la selezione. La superficie usa lo stesso renderer, con orologio e regole di pausa condivisi. Le particelle sono sempre morbide, senza una scelta aggiuntiva. La scelta dello sfondo mantiene il dialogo di destinazione esistente.
+
+La barra laterale segue `SettingsSidebarGroup`: General, Library, Porting e System. Ogni sezione mostra solo le righe di `SettingsCatalog` che le appartengono.
+
+In System → About, il pulsante Support Arcane compare tra il riepilogo dell’app e i crediti. `SettingsAboutSection` apre la pagina Buy Me a Coffee nel browser predefinito tramite clic, Invio o conferma del controller.
+
+Tornando alla home, le viste delle tessere ricreate leggono subito le immagini decodificate in `TileArtMemo`; i task caricano quelle mancanti e rivalidano i file Steam. La cover della card Mods resta nel `ModStoreHost` posseduto dalla shell ed è rivalidata in background rispetto agli abbinamenti correnti.
+
+## 9. Aggiornare l'app
+
+```mermaid
+flowchart TD
+ A["AppUpdater: release su GitHub"] --> B{"AppUpdate.mayInstall
versione più nuova e copia installabile"}
+ B -->|"no (copia Dev o sola lettura)"| X["Solo note di rilascio"]
+ B --> C["AppUpdateDownload: dimensione dichiarata, host GitHub"]
+ C --> D["validate_update.py: struttura e percorsi"]
+ D --> E["SaveOperationGate: esclusione globale"]
+ E --> F["Controllo di versione, identità e firma"]
+ F --> G["Copia in cartella esclusiva sul volume corrente"]
+ G --> H["Scambio atomico"]
+ H --> I["Vecchia app nel Cestino; se fallisce, conservarla nella cartella esclusiva"]
+ I --> J["Riavvio allo stesso percorso"]
+```
+
+Alla chiusura successiva, una copia release che si chiama ancora `NX Library.app` diventa `Arcane.app` (`AppBundleRename`, chiamato da `AppDelegate.applicationWillTerminate`). Non succede se un riavvio è in programma, perché l'aiuto che riapre l'app usa il percorso attuale.
diff --git a/docs/media/README.md b/docs/media/README.md
index 382d4a52..a9b347f4 100644
--- a/docs/media/README.md
+++ b/docs/media/README.md
@@ -1,41 +1,30 @@
# Immagini e video del README
-Il README apre con logo, nome, descrizione e pochi badge. Spotlight introduce l'app; gli altri screenshot accompagnano la funzione descritta nella guida. Il video avrà posto subito sotto la presentazione, prima di Spotlight. Il blocco legale rimane in fondo.
+Il README apre con l'icona di Arcane, il nome e la descrizione. Spotlight introduce la libreria. Le altre immagini accompagnano le funzioni della guida.
## Screenshot inclusi
-Le otto catture fornite dall'utente il 2 novembre 2026 sono state rinominate nelle copie del repository. Gli originali sul Desktop restano invariati. Gli agenti non hanno aperto né automatizzato l'app.
+| File nel repository | Posizione nel README |
+|---|---|
+| [spotlight.webp](spotlight.webp) | Apertura, prima di Overview. |
+| [game-details.webp](game-details.webp) | Your library, dettagli e attività del gioco. |
+| [quick-menu.webp](quick-menu.webp) | Your library, accesso al menu rapido. |
+| [porting-progress.webp](porting-progress.webp) | Add or rebuild a game, avanzamento in Spotlight. |
+| [color-themes.webp](color-themes.webp) | Artwork, themes and sound, scelta della palette. |
+| [static-wallpapers.webp](static-wallpapers.webp) | Artwork, themes and sound, sfondi statici. |
+| [live-wallpapers.webp](live-wallpapers.webp) | Artwork, themes and sound, sfondi animati. |
+| [mod-store.webp](mod-store.webp) | Mods, store con banner e righe. |
-| Nome originale | File nel repository | Posizione nel README |
-|---|---|---|
-| `Spotlight View.png` | [spotlight.webp](spotlight.webp) | Apertura, prima di Overview. |
-| `Details Games.png` | [game-details.webp](game-details.webp) | Your library: dettagli e attività del gioco. |
-| `Rapid Menu.png` | [quick-menu.webp](quick-menu.webp) | Your library: accesso al menu rapido. |
-| `Porting State home .png` | [porting-progress.webp](porting-progress.webp) | Add or rebuild a game: avanzamento in Spotlight. |
-| `Setting View.png` | [settings.webp](settings.webp) | Know which settings apply: categorie e Start-up. |
-| `Color theme.png` | [color-themes.webp](color-themes.webp) | Artwork, themes and sound: scelta della palette. |
-| `Background Static Wallpaper.png` | [static-wallpapers.webp](static-wallpapers.webp) | Artwork, themes and sound: sfondi statici. |
-| `Background Wallpaper Live .png` | [live-wallpapers.webp](live-wallpapers.webp) | Artwork, themes and sound: sfondi animati. |
-| `Mods.png` (7 novembre 2026) | [mod-store.webp](mod-store.webp) | Mods: lo store con il banner Featured e le righe. |
+Le copie WebP sono larghe 1920 pixel, mantengono le proporzioni delle catture e usano il profilo colore sRGB. Le didascalie e i testi alternativi sono in inglese. [settings.webp](settings.webp) documenta l'interfaccia di NX Library precedente alla riorganizzazione di Settings.
-Le copie WebP sono larghe 1920 pixel, mantengono proporzioni e contenuto delle catture e usano il profilo colore sRGB. Occupano complessivamente circa 2,3 MB, rispetto ai circa 73 MB degli originali. I metadati personali non vengono trasferiti. Le didascalie e i testi alternativi sono in inglese; ciascuna immagine ha una propria riga per preservare la leggibilità.
-
-La cattura di Settings mostra ancora il precedente pin `2716f78`; il pin corrente e i requisiti sono quelli del README. Aggiornare questa foto alla prossima sessione di cattura. Anche lo stato delle sorgenti e della toolchain nei dettagli di un gioco descrive soltanto il gioco fotografato.
-
-Le immagini illustrano la libreria dell'utente. Copertine, loghi e wallpaper visibili restano soggetti ai diritti e ai termini dei rispettivi proprietari; la licenza MIT del codice non ne modifica i termini.
+Le copertine, i loghi e i wallpaper visibili nelle catture restano soggetti ai diritti e ai termini dei rispettivi proprietari.
## Aggiornare le immagini
-Conservare le catture complete, senza modificare lo stato mostrato o ricreare l'interfaccia. Preparare copie ottimizzate in questa cartella e collegarle alla sezione pertinente del README con testo alternativo e una didascalia breve. Controllare che non siano visibili chiavi, percorsi privati o notifiche personali. Non aggiungere file di gioco o asset separati.
-
-Gli screenshot del setup in due passaggi e dell'anteprima dei salvataggi potranno essere aggiunti quando disponibili; non ci sono segnaposto visibili. Il commento `NX-SCREENSHOTS` delimita l'immagine d'apertura e `NX-DEMO` riserva il posto al video. Aggiornare anche il [catalogo dei file](../file-map.md) quando si aggiungono o rinominano immagini.
+Conservare le catture complete con lo stato originale dell'interfaccia. Aggiungere una copia WebP con didascalia e testo alternativo. Controllare che percorsi privati, chiavi e notifiche personali restino fuori dalle catture. Il commento `NX-SCREENSHOTS` delimita l'immagine d'apertura. Aggiornare il [catalogo dei file](../file-map.md) se cambia l'inventario.
## Video subito dopo la presentazione
-Una registrazione breve, circa 45–90 secondi, può mostrare Spotlight, Collection, le opzioni di un gioco, un'anteprima dei salvataggi e Settings. I tempi di una build vanno abbreviati dichiarandolo; non presentare una sequenza tagliata come una compilazione istantanea.
-
-Preferire un MP4 con H.264 per un'ampia compatibilità. Quando l'utente fornirà il video, caricarlo come allegato GitHub e mettere il suo URL su una riga autonoma al posto del commento `NX-DEMO`, subito dopo la presentazione. Non aggiungere un file video pesante alla cronologia Git. Verificare la riproduzione e l'accessibilità dell'allegato anche nel contesto di pubblicazione previsto.
-
-La resa degli allegati dipende dal contesto e dal browser. Se il lettore non viene mostrato nel README, usare un fermo immagine cliccabile che apra il video, conservandolo nella stessa posizione. Non inserire pulsanti Play che portano a un video ancora inesistente. Riferimenti: [allegati GitHub](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/attaching-files) e [allegati tramite GitHub CLI](https://docs.github.com/en/github-cli/github-cli/attaching-files-with-github-cli).
+Il blocco `NX-DEMO` accoglie un allegato GitHub subito dopo la presentazione. Preferire un MP4 con H.264 e verificare la riproduzione nel README pubblico. Segnalare nel video eventuali tempi di compilazione abbreviati.
-Quando uscirà una release, aggiornare immagini o filmato se l'interfaccia è cambiata. Il video e gli screenshot illustrano la versione mostrata e non certificano il supporto di ogni gioco.
+Se il lettore non appare nel README, usare un fermo immagine che apre il video. [Allegati GitHub](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/attaching-files)
diff --git a/docs/reviews/2026-11-16-ratings-metadata-evidence.md b/docs/reviews/2026-11-16-ratings-metadata-evidence.md
new file mode 100644
index 00000000..6fd0f4ec
--- /dev/null
+++ b/docs/reviews/2026-11-16-ratings-metadata-evidence.md
@@ -0,0 +1,104 @@
+# Voti e metadati: prove e verifiche (16 nov 2026)
+
+Nota datata. Raccoglie le verifiche reali e le misure che hanno motivato scelte descritte in [architecture.md](../architecture.md#artwork-metadati-e-voti). Il testo è quello che stava nella guida tecnica prima del riordino del 17 novembre 2026; qui resta come prova, la guida descrive solo il comportamento attuale.
+
+## Wikidata: difetti trovati nella libreria reale
+
+La verifica nella libreria reale ha individuato due difetti di ricerca: i simboli ™/®/©
+nei nomi dello store davano risultati vuoti, e un nome Steam personalizzato non identificava
+il titolo. Le query ora tolgono soltanto quei simboli, conservando sequel/edizioni; Steam
+prova prima P1733 (ID pubblico esatto), verificato di nuovo nelle dichiarazioni dell'entità.
+Il ripiego per nome usa anche il campo `match` degli alias. Le assenze salvate dal vecchio
+resolver vengono ricontrollate, senza eliminare voti validi o modificare la libreria.
+
+## IGDB: console Switch 2 (Ocarina of Time)
+
+La verifica di Ocarina of Time (2026-11-16) ha individuato un filtro errato: entrambe
+le pagine passavano sempre Switch (IGDB 130), scartando la scheda Switch 2. La query ora
+deriva la console da `PortedGame.isSwitch2`, come Details, e distingue `switch` da
+`switch2` (IGDB 508; Wikidata Q122761124). Nome/alias esatti e unicità rimangono obbligatori:
+non si allarga il filtro alle due console insieme, evitando di mescolare edizioni omonime.
+La console fa parte della chiave di entrambe le cache: Switch 2 riprova subito senza
+riutilizzare l'assenza salvata come Switch, mentre voti validi e cache esistenti restano
+intatti. Nessuna cancellazione di dati o modifica alle credenziali. Test con dati sintetici
+coprono edizioni omonime, query dai giochi, compatibilità della vecchia identità Switch,
+ripiego Wikidata e un'assenza preesistente. Restano da validare in Dev Ocarina/Switch 2,
+un titolo Switch e uno Steam; la disponibilità effettiva del dato è stata poi verificata
+con la richiesta autorizzata descritta sotto. La nuova presentazione del ripiego utenti
+rimane in attesa di validazione umana.
+
+## IGDB: verifica diretta autorizzata
+
+Verifica diretta autorizzata dal maintainer il 16 novembre 2026: la stessa ricerca
+dell'app restituisce la scheda Ocarina Switch 2 (405460, piattaforma 508), confermata
+anche per ID. La risposta non contiene `aggregated_rating` né `aggregated_rating_count`:
+ha solo `rating` (circa 99,7) e `rating_count` (35), cioè voti utenti al momento della
+verifica. L'assenza nella riga della critica è quindi attesa anche dopo la correzione
+della console. Non sostituire silenziosamente il voto utenti o quello di un'altra
+edizione. Il maintainer ha poi approvato il ripiego utenti esplicitamente distinto.
+Nessuna credenziale o token è stata registrata.
+
+## Download a blocchi: misura
+
+Correzioni del 16 novembre 2026 (in attesa di validazione umana). Una media della critica IGDB
+vale solo con almeno 3 recensioni (`IGDBRatings.minimumCriticReviews`): con meno, la riga usa
+Wikidata o, in sua assenza, la media utenti IGDB esplicita. `CriticRating.isValid` applica lo
+stesso minimo, così le vecchie cache con 1–2 recensioni vengono richieste di nuovo. Salvare le
+credenziali riporta anche una cartella `credentials` già esistente al modo 0700. I download di
+Wikidata, IGDB, LaunchBox/TheGamesDB e Steam passano per `BoundedDownload`, che conserva i
+blocchi ricevuti da URLSession: leggere `AsyncBytes` un byte alla volta costava circa 6 µs per
+byte (pagina LaunchBox da 640 KB: 5,4 s e 3,9 s di CPU, ora 2,0 s e circa 10–30 ms di CPU).
+Limiti di dimensione, rifiuto dei redirect e annullamento restano invariati.
+
+## Selettore dei metadati: correzione del movimento
+
+Correzione del movimento nel selettore: il cambio di focus sostituiva istantaneamente
+l'estratto (240 caratteri) con il testo completo e avviava separatamente uno scroll
+centrato, anche per righe più alte della finestra. `SeleneExpandableText` conserva i
+due layout alla stessa larghezza: `Layout` risolve subito la geometria finale,
+mentre SwiftUI anima i frame e la dissolvenza tra estratto e testo completo
+([contratto SwiftUI](https://developer.apple.com/documentation/swiftui/layout)).
+Interpolare le misure dentro `Layout` sposterebbe il bersaglio di `scrollTo`
+durante la chiusura della riga precedente; la sonda fuori schermo ha riprodotto
+questo errore e verificato l'allineamento con misure finali stabili.
+Il selettore usa la stessa curva per espansione e scroll, con allineamento iniziale
+per leggere il titolo delle descrizioni lunghe. Riduci movimento disattiva entrambi.
+L'opzione è locale ai metadati: gli altri `SeleneOptionRow` restano invariati. Nessuna
+modifica a richieste, cache, testi salvati o selezione delle fonti.
+
+`scripts/check_metadata_text_layout.swift` verifica fuori schermo le altezze a tre
+larghezze, il cambio di contenuto e le destinazioni dello scroll durante cambi
+di focus ripetuti, anche con Riduci movimento; non misura frame rate o fluidità reale.
+Da verificare nella Dev: su/giù ripetuti fra descrizioni corte e molto lunghe, scroll
+manuale fino alla fine, Q/E, scelta/salvataggio e Riduci movimento. Correzione del
+movimento **in attesa di validazione umana**.
+
+## LaunchBox e TheGamesDB: sonde reali
+
+Scelta: leggere su richiesta una ricerca e una scheda pubblica per database, con
+parser separati e cache di sole proposte; non scaricare l'intero Metadata.zip né
+duplicare un catalogo immagini. Le sonde delle pagine pubbliche hanno misurato circa
+74 KB per una scheda LaunchBox e 15 KB per una TheGamesDB, senza scaricare immagini.
+Il formato corrente LaunchBox espone gameKey/name/platform e campi indicizzati nel
+payload Nuxt; TheGamesDB espone titolo, piattaforma e campi etichettati. I parser
+devono verificare anche la scheda finale, rifiutare ambiguità e non eliminare parole
+di edizione. Mac è preferito a PC/Windows; una proposta alternativa PC è dichiarata
+e non fornisce una falsa data Mac. Le righe delle fonti restano visibili e stabili,
+con stati assente/uguale ad Automatico/errore e retry accessibile, senza scrivere
+scelte personali durante il caricamento. Cache, dimensioni, durata, annullamento e
+numero di richieste sono verificati con test e sonde: nessuna promessa di massima
+prestazione deriva dalla sola compilazione. Implementato; controlli automatici e confezionamento Dev descritti sotto.
+Validazione umana ancora necessaria.
+
+La sonda reale ha individuato un redirect LaunchBox da ricerca con maiuscole al
+percorso minuscolo: `LaunchBoxArt.searchURL` ora genera direttamente la forma canonica,
+evita il 301 e permette il client vincolato anche per i metadati. La prova, con cache
+isolata e titoli pubblici di fixture, ha restituito cinque campi per Donkey Kong
+Bananza (Switch 2) e quattro per Hollow Knight (PC come alternativa Mac, senza data
+PC). In quella singola esecuzione la prima lettura ha impiegato circa 1,595 s e
+0,510 s; le riletture locali circa 0,420 ms e 0,275 ms. Non sono misure di frame rate
+né garanzie sulla latenza dei servizi. Il probe temporaneo non è incluso nei test
+normali; i test riproducibili verificano invece due richieste per una ricerca
+LaunchBox, zero richieste cambiando campo/rileggendo una cache fresca, coalescenza,
+annullamento, retry e risposte sovradimensionate o di destinazione inattesa.
+
diff --git a/docs/reviews/2026-11-17-arcane-moonlight.md b/docs/reviews/2026-11-17-arcane-moonlight.md
new file mode 100644
index 00000000..2c3f802f
--- /dev/null
+++ b/docs/reviews/2026-11-17-arcane-moonlight.md
@@ -0,0 +1,173 @@
+# Moonlight Arcane — prove e misure del 17 novembre 2026
+
+Il tema Arcane mantiene l’identità `selene` e usa un campo cromatico continuo
+nei passaggi Metal già esistenti. Le misure sotto documentano anche la prima
+prova di Crystal dust, successivamente rimossa; immagini e video mantengono
+il proprio aspetto.
+
+## Contratti verificati
+
+`MoonlightAppearanceTests` prova compatibilità dei file vecchi e dei valori
+sconosciuti, salvataggio, Changed/Reset, continuità e periodicità dei colori,
+e accesso alla riga delle particelle prima della scelta dello sfondo.
+
+`run_theme.py` esegue i veri metodi di input con `AppSettingsStore` su una
+cartella sintetica: movimento dal bordo della griglia alla riga, scelta
+sinistra/destra, ritorno alle palette, mouse e A verso il passo sfondo.
+Confronta anche l’ordine delle righe visibili di Look con quello delle azioni
+di tastiera e controller. Questa regressione falliva prima della correzione
+dell’ordine fra Background motion e Particles.
+
+Con Metal disponibile, lo stesso script compila gli shader reali e confronta
+il campionamento GPU dello spettro con quello del Core. Verifica le uniform
+dei due effetti e di Mods, la differenza dei frame delle particelle e
+l’identità di due immagini renderizzate allo stesso istante. Non apre
+finestre, non cattura lo schermo e non legge profili del giocatore. Senza
+device Metal salta soltanto la parte GPU; con un device e shader non
+compilabili fallisce.
+
+## Semplificazione delle particelle, 17 novembre
+
+Il maintainer chiede di mantenere soltanto le particelle morbide: le faccette
+sono poco distinguibili e non giustificano un’opzione. Il selettore esce da
+Theme e Look, dal catalogo Search/Changed/Reset e dal renderer. Il campo
+storico `particleStyle` è ignorato alla lettura e non viene più salvato.
+
+I test di compatibilità e focus falliscono prima della rimozione e passano
+dopo; la suite Swift esegue 1790 test senza errori. `run_theme.py` verifica
+i metodi reali della griglia, il passaggio allo sfondo, l’ordine delle righe
+Look e gli shader Metal reali: particelle morbide, campionamento GPU/Core,
+frame fermo e uniform distinti per Mods. Questi controlli non sostituiscono
+la prova visiva del maintainer. La tabella seguente resta la misura storica
+della prima versione e non misura la rimozione delle faccette.
+
+## Tempo dei passaggi GPU, fuori schermo
+
+Misura locale con il renderer precedente e quello nuovo, stesso campo
+deterministico e texture BGRA8 privata. Ogni riga ha 32 campioni dopo
+10 frame di riscaldamento. Il tempo viene da `MTLCommandBuffer.gpuStartTime`
+e `gpuEndTime`; include luce e particelle, non composizione della finestra,
+SwiftUI, acquisizione del drawable o presentazione sul display.
+
+| Profilo | Dimensione | Mediana GPU | P95 GPU |
+|---|---|---|---|
+| Precedente | 1920 × 1080 | 0,373 ms | 1,406 ms |
+| Classico nel renderer nuovo | 1920 × 1080 | 0,395 ms | 2,280 ms |
+| Arcane + Crystal dust | 1920 × 1080 | 0,238 ms | 1,541 ms |
+| Precedente | 3840 × 2160 | 0,751 ms | 2,414 ms |
+| Classico nel renderer nuovo | 3840 × 2160 | 0,711 ms | 2,298 ms |
+| Arcane + Crystal dust | 3840 × 2160 | 0,894 ms | 2,554 ms |
+
+L’ordine delle misure, il carico del desktop e la frequenza dinamica della GPU
+non sono controllati. Le differenze non dimostrano un miglioramento di
+prestazioni né garantiscono un frame rate nell’app. Servono a rilevare costi
+evidenti nei soli passaggi aggiunti; fluidità, contrasto e integrazione si
+verificano nella Dev. Lo stato delle prove umane è in
+[validation.md](../validation.md).
+
+## Superfici Arcane e Arcane Flow
+
+Le due superfici usano filamenti analitici e piani generati nello shader.
+Il colore resta locale (rosa a sinistra, ciano a destra), con variazioni
+minime su180s. Nessun asset grafico esterno alimenta il movimento.
+La variante è un metadato facoltativo della palette; la preferenza resta
+`colorThemeID`. Le regole di pausa, Riduci movimento, copertura da artwork
+ed entrata restano quelle del renderer e delle viste condivise.
+
+La suite esegue1792test senza errori. Il controllo Metal confronta colori
+GPU/Core, superfici distinte, fotogrammi identici a tempo fermo, movimento
+a tempi diversi, uniform della variante Flow e oro Mods indipendente.
+I fotogrammi sintetici delle due superfici sono stati ispezionati fuori
+schermo; non sono screenshot dell’app e non provano la fluidità interattiva.
+
+Una sonda a1920×1080 registra il tempo completo di `snapshot`, inclusi
+allocazione, rendering, attesa e lettura CPU:12campioni dopo3di riscaldamento.
+Mediane classico10,68ms, Arcane12,55ms, Flow12,41ms; massimi rispettivamente
+11,86/13,08/13,08ms. Questi valori non sono tempi GPU né frame rate della
+finestra e non sono confrontabili con la tabella GPU precedente. La prova
+umana nella Dev resta necessaria per fluidità, leggibilità e ritmo.
+
+La revisione individua valutazioni inutili: variante nascosta e fascio classico
+anche con superficie Arcane pienamente visibile. I rami uniformi ora evitano
+quei percorsi a regime; durante le dissolvenze restano entrambi. Le misure
+sopra precedono questa correzione e non ne quantificano il beneficio. Il
+controllo finale include anche blend intermedi e trasparenza a presenza zero.
+
+Il blu classico resta il default `selene` e il fallback. Le superfici nuove
+sono alternative esplicite: `arcane-crystal` (Arcane Crystal) e `arcane-flow`
+(Arcane Flow). I controlli verificano anche questa separazione, l’ordine
+predefinito e la persistenza degli ID; nessuna preferenza è riscritta.
+Il ripristino del blu confronta esattamente i valori della palette storica;
+il metadato delle nuove superfici è assente sia dal default sia dal fallback.
+La suite completa passa ancora1792test, con una regressione inizialmente
+rossa per default, fallback, ordine e numero delle alternative.
+
+## Ripristino effettivo della luminosità originale
+
+Il primo ripristino usava ancora i colori scuriti nell’esperimento5eb9862.
+Il riferimento corretto è f427937: default radiale0x102A5C/0x03081A e fallback
+lineare0x17244A/0x0C142C/0x05080F. Test inizialmente rossi ora proteggono
+questi valori. Gli shader classici attuali sono confrontati fuori schermo con
+quelli di f427937, stesso campo e uniform: differenza massima per canale
+0/255 a320px,1/255 a640px,0/255 a960px. Il controllo del pacchetto Dev
+conferma l’esatta palette storica, escluso il nome visibile. Non è una prova
+della finestra o della composizione dello schermo.
+
+## Fili sottili e onde viaggianti
+
+La correzione mantiene intatto il percorso classico. Nei due temi opzionali
+il profilo usa un nucleo gaussiano da0,5pixel sigma e dispersione molto
+debole; il footprint è calcolato dalle derivate spaziali per mantenere il
+tratto sottile anche sulle diagonali. Due onde sovrapposte deformano le curve
+lungo la loro lunghezza, con fili secondari più deboli ed estremi sfumati.
+I bokeh grandi sono attenuati soltanto nelle alternative.
+
+La regressione GPU inizialmente rossa prova le funzioni Metal effettive:
+luce a un pixel dal nucleo inferiore al20% del picco, escursione limitata,
+spostamenti continui e deformazioni diverse in due punti del filo. Restano
+le prove di colori locali, trasparenza a presenza zero, blend e Mods.
+Fotogrammi sintetici e una sequenza reale di18secondi a30fps sono generati
+fuori schermo, senza finestre o catture; questi dati non verificano la
+fluidità dell’app e la qualità visiva resta da confermare dal maintainer.
+
+## Cambio palette con selezione invariata
+
+La prova dei metodi reali della shell e di ThemeStore riproduce la regressione:
+il valore di SeleneBackdropStyle restava identico quando cambiava soltanto la
+palette. SwiftUI non riceveva un cambiamento dell’ambiente; il successivo
+spostamento della card ridisegnava il contenuto e rileggeva i colori globali.
+Ora lo snapshot comprende la palette e i consumer di sfondo/maschere usano
+quel valore. La prova inizialmente rossa passa per blu → Crystal → Flow → blu
+senza cambiare il wallpaper né la card. Non si ricrea la pagina con un ID.
+
+Su richiesta del maintainer, le alternative conservano solo filamenti e
+luce ambientale molto tenue: rimossi i piani e ridotti i campi diffusi.
+Il percorso classico del default resta invariato. Lo scatto/intervallo nero
+nell’apertura immediata delle impostazioni resta distinto: log locali nella
+sola Dev misurano renderer creato/presentato e apertura pagina, senza dati
+del giocatore. I test d’ingresso verificano i contratti di readiness, non
+la fluidità della finestra.
+
+## Continuità home → Settings
+
+La prova umana conferma lo scatto/nero. I log mostrano windowSettling=false
+e un renderer nuovo ad ogni ingresso/ritorno, con21–57ms al primo drawable
+presentato; la discontinuità non dipende soltanto dal fullscreen iniziale.
+La shell conserva ora la superficie persistente. Le pagine dichiarano i
+parametri tramite SeleneBackdropRequest e mantengono artwork/maschere,
+senza creare un secondo sfondo. Il frame e il clock restano nella stessa
+istanza; una richiesta assente conserva i parametri e mette in pausa.
+
+I controlli headless coprono ordine delle richieste sovrapposte, mantenimento
+del frame, pausa, ritorno agli stessi parametri, cambio palette e Mods.
+Passano anche ingresso, onboarding e routing reali senza finestre. La prova
+finale nella Dev deve confermare continuità visiva e stesso ID del renderer
+attraverso home/Settings; i test di codice non sostituiscono questa verifica.
+
+La revisione rileva che condividere la superficie richiede anche di coprire
+i contenuti dei livelli inferiori. ShellBackdropCover definisce nel Core
+la precedenza Setup2,5 → benvenuto2,4 → scelta tema1: ogni strato inferiore
+resta montato/caldo ma quasi trasparente e senza input; dialoghi superiori
+restano visibili. Controls applica la stessa separazione al contenuto locale
+di Settings. Il blur esistente copre anche lo sfondo persistente. I test
+verificano la precedenza dei tre schermi e i livelli0/0,5/0,8/1/2/2,4/2,5/3/4.
diff --git a/docs/reviews/2026-11-17-dock-rename-probe.md b/docs/reviews/2026-11-17-dock-rename-probe.md
new file mode 100644
index 00000000..54fa671e
--- /dev/null
+++ b/docs/reviews/2026-11-17-dock-rename-probe.md
@@ -0,0 +1,11 @@
+# Dock e app rinominata — sonda del 17 novembre 2026
+
+**Domanda:** se un'app nel Dock viene rinominata mentre è chiusa, il Dock la apre ancora?
+
+**Sonda** (macOS 27.2, Mac del maintainer):
+1. Un'app minima `NX Probe.app` in `~/Applications`, firmata ad-hoc, bundle ID `local.nxlibrary.dockprobe`, tenuta nel Dock dal maintainer e chiusa.
+2. Rinominata in `Arcane Probe.app` con `mv`, nella stessa cartella.
+3. Dopo la rinomina, `defaults read com.apple.dock persistent-apps` mostra ancora `_CFURLString` = `file:///Users//Applications/NX%20Probe.app/` e `file-label` = "NX Probe".
+4. Il maintainer ha cliccato l'icona nel Dock: l'app si è aperta e la sua finestra mostrava il percorso nuovo.
+
+**Esito:** il Dock segue una rinomina nella stessa cartella. Il percorso salvato non serve a ritrovare l'app: per inferenza, il Dock la risolve dal segnalibro o dal bundle ID. L'app di prova è stata messa nel Cestino.
diff --git a/docs/reviews/2026-11-17-entrance-frames.md b/docs/reviews/2026-11-17-entrance-frames.md
new file mode 100644
index 00000000..af75dac6
--- /dev/null
+++ b/docs/reviews/2026-11-17-entrance-frames.md
@@ -0,0 +1,50 @@
+# Entrata della libreria — misure del 17 novembre 2026
+
+## Metodo
+
+Una sonda temporanea nella Dev registrava `CACurrentMediaTime()` durante le
+valutazioni di `EntranceFlight.effectValue`, unendo campioni distanti meno di
+2 ms. Il log `entrance` riportava attesa dopo la copertura, durata, intervallo
+massimo e numero di intervalli oltre 1,5 volte il periodo ricavato da
+`NSScreen.maximumFramesPerSecond`. Il conteggio escludeva i primi 100 ms.
+
+Le aperture erano eseguite dal maintainer, con e senza benvenuto e con avvio
+fullscreen. Non sono state usate automazione UI o catture dello schermo.
+
+## Campioni
+
+I campioni seguenti provengono dal log della Dev durante le iterazioni della
+stessa giornata. Le versioni avevano tempi diversi: la durata non è un confronto
+diretto di velocità fra prima e dopo.
+
+| Campione | Frequenza dichiarata | Attesa | Durata campionata | Intervallo massimo | Intervalli oltre soglia |
+|---|---:|---:|---:|---:|---:|
+| 10:16:33, benvenuto, prima del disegno anticipato delle tessere | 120 Hz | 0 ms | 1.471 ms | 28 ms | 3 / 160 |
+| 11:08:57, benvenuto, disegno anticipato e pausa di 0,5 s | 120 Hz | 512 ms | 2.124 ms | 9 ms | 0 / 243 |
+| 11:39:06, fullscreen, arte ancora in lettura alla scadenza | 120 Hz | 1.562 ms | 2.184 ms | 10 ms | 0 / 251 |
+| 11:57:18, fullscreen, senza benvenuto | 120 Hz | 523 ms | 2.188 ms | 9 ms | 0 / 251 |
+
+Nel primo campione i tre intervalli lunghi cadevano a 523, 610 e 798 ms,
+vicino alle prime apparizioni di tessere. Il disegno anticipato usa opacità
+0,001 per la riga e il contenuto dell'effetto prima della comparsa: negli
+ultimi campioni non si osservano intervalli oltre soglia dopo i primi 100 ms.
+Resta la riga reale animata in SwiftUI; il livello dell'arte sfuma in Core Animation.
+
+Per l'avvio fullscreen delle 11:57, il log registra il primo frame del moonlight
+a 388 ms, l'inizio della transizione a 702 ms e la fine a 1.547 ms dalla prima
+apparizione della finestra. `LaunchReveal` attende il primo frame con un limite
+di 1 s prima di mostrare la finestra e consentire il fullscreen.
+
+## Limiti e conservazione
+
+- I campioni misurano valutazioni dell'animazione SwiftUI sul thread principale,
+ non i frame presentati dalla GPU o dal compositor.
+- La frequenza usata è il massimo dichiarato dallo schermo, non una misura del
+ refresh effettivo. La soglia è quindi un indicatore diagnostico.
+- I primi 100 ms non partecipano al conteggio degli intervalli lunghi.
+- Hardware, cache, libreria e tempi sono quelli delle singole aperture; questi
+ numeri non garantiscono lo stesso risultato su altri Mac o dati.
+
+La sonda e le sue chiamate sono rimosse dal codice applicativo; questa nota
+conserva metodo e risultati. Lo stato delle prove manuali resta soltanto in
+[validation.md](../validation.md).
diff --git a/docs/reviews/2026-11-18-spotlight-glide.md b/docs/reviews/2026-11-18-spotlight-glide.md
new file mode 100644
index 00000000..0f473aa6
--- /dev/null
+++ b/docs/reviews/2026-11-18-spotlight-glide.md
@@ -0,0 +1,77 @@
+# Primi cambi gioco in Spotlight — misure del 18 novembre 2026
+
+Lo scatto compariva con destra e sinistra nei primi movimenti dopo l'entrata.
+La prova manuale confronta più avvii della Dev. Una sonda temporanea campiona il
+valore animato della camera della riga sul thread principale, unisce le letture
+a meno di 2 ms e riporta l'intervallo più lungo e il lavoro sincrono misurato.
+
+| Campione | Primo aggiornamento | Intervallo massimo | Mod sul thread principale | Salvataggio selezione |
+|---|---:|---:|---:|---:|
+| Prima, primo cambio | 24 ms | 35 ms | 9 ms | 2 ms |
+| Prima, secondo cambio | 9 ms | 15 ms | 5 ms | 1 ms |
+| Dopo, primo cambio | 19 ms | 28 ms | < 0,5 ms | 9 ms |
+| Dopo, secondo cambio | 15 ms | 16 ms | < 0,5 ms | 7 ms |
+| Scrittura in background, primo cambio (avvio 1) | 28 ms | 52 ms | — | in background |
+| Scrittura in background, secondo cambio (avvio 1) | 17 ms | 18 ms | — | in background |
+| Scrittura in background, primo cambio (avvio 2) | 29 ms | 53 ms | — | in background |
+| Scrittura in background, secondo cambio (avvio 2) | 14 ms | 15 ms | — | in background |
+
+Spotlight legge le mod all'apertura della pagina e Play riconcilia le cartelle
+prima dell'avvio del gioco. Il controllo senza finestre usa la funzione di
+Spotlight con un sostituto di `ModsBandHost` e verifica che la riga non legga
+la fascia del gioco successivo, mentre la pagina la carica.
+
+Il salvataggio sincrono della selezione arriva a 7–9 ms dopo il primo intervento.
+`AppSettingsStore` passa quella scrittura alla coda seriale in background e
+completa la scelta alla chiusura. I test esercitano la scrittura fuori dal
+thread principale e la precedenza del valore più recente al salvataggio.
+
+Entrambi i primi cambi nel passaggio con scrittura in background hanno 27
+aggiornamenti in circa mezzo secondo. I secondi ne hanno 58 e 59. Nei due
+campioni freddi l'artwork successivo entra 45 ms dopo la fine del
+campionamento della riga. La differenza di cadenza richiede una misura
+dedicata e non stabilisce da sola la causa.
+
+Un campionamento CPU di 12 s rallenta anche i movimenti successivi, con
+intervalli di 112–172 ms. Questi tempi sono esclusi dal confronto. Nelle pile
+del thread principale si osserva `rememberLastSelectedGame` → setter
+`@Published` → invalidazione e aggiornamento sincrono della pagina Spotlight.
+La scelta diventa stato di navigazione osservato solo dalla logica di
+ripristino. Lo stesso store conserva il campo nel JSON. Un test conta le
+notifiche dello store e richiede zero per un cambio di selezione riuscito.
+
+Senza la notifica delle impostazioni, i primi cambi dei tre avvii danno
+55, 51 e 27 aggiornamenti, con intervalli massimi di 25, 33 e 51 ms.
+Il secondo cambio singolo dell'ultimo avvio dà 59 aggiornamenti e 22 ms.
+In quest'ultimo avvio la nuova immagine sfuma dopo il campionamento.
+Una prova con `CADisplayLink` chiede 120 Hz durante lo scorrimento. Core
+Animation indica un obiettivo di circa 8 ms, ma la riga registra 26
+aggiornamenti e un intervallo massimo di 53 ms. La prova non risolve lo
+scatto e la richiesta viene rimossa.
+
+Il percorso delle frecce costruiva il modello Dettagli prima di spostare
+la riga, anche se non lo usava. SwiftUI impaginava la parte inferiore della
+pagina anche durante la navigazione tra tessere. La riga usa ora solo la
+lista filtrata. Dettagli, descrizione e giochi correlati si costruiscono
+quando la pagina sale. Il controllo senza finestre verifica il cambio di
+tessera, il bordo della riga e la precedenza della navigazione nella pagina.
+
+### Esito della riga separata
+
+| Avvio | Primo aggiornamento | Intervallo massimo | Aggiornamenti nel primo cambio |
+|---|---:|---:|---:|
+| 1 | 19 ms | 11 ms | 59 |
+| 2 | 9 ms | 14 ms | 60 |
+| 3 | 12 ms | 15 ms | 59 |
+
+Il primo cambio nella prova precedente registrava 26 aggiornamenti e un
+intervallo massimo di 53 ms. La curva, la geometria della riga e l'entrata
+rimangono identiche nel codice. La parte inferiore della pagina si monta
+alla sua apertura, quindi i suoi caricamenti possono iniziare più tardi.
+Il controllo dei file prima di Play conserva record e overlay se la lettura
+fallisce. Le fixture coprono cartella illeggibile, JSON corrotto e singola
+mod assente in una cartella leggibile.
+
+I valori provengono da singoli avvii. Indicano i tempi degli aggiornamenti di
+SwiftUI, non i frame presentati dal compositor. La sonda è rimossa dalla Dev.
+Lo stato delle prove manuali è in [validation.md](../validation.md).
diff --git a/docs/reviews/2026-11-18-steam-launch-spaces.md b/docs/reviews/2026-11-18-steam-launch-spaces.md
new file mode 100644
index 00000000..09f2ee45
--- /dev/null
+++ b/docs/reviews/2026-11-18-steam-launch-spaces.md
@@ -0,0 +1,7 @@
+# 2026-11-18 — Cambi ripetuti di Space durante Play Steam
+
+Il video mostra la schermata di attesa e la pagina di Arcane che scorrono lateralmente, alternate a Steam, scrivania e fotogrammi neri. Arcane segnala il pannello consegnato al server delle finestre e invia Play alle 09:36:06.407. Steam è già in esecuzione e si ferma a `ShowInterstitials`. Il log di sistema conta 55 eventi `DoHide(self)` di Steam fra 09:36:07.454 e 09:36:12.035, durante le oscillazioni. Alle 09:36:21.910 la schermata lascia spazio a Steam per scadenza dell'attesa. Gli eventi relativi al controller si sovrappongono al problema, con il primo evento osservato dopo l'inizio dei nascondimenti. Non stabiliscono cosa abbia fatto riapparire Steam.
+
+Con **Keep Steam in the background** attivo, ogni notifica di attivazione o riapertura richiamava il controllo che nascondeva il client mentre il gioco era in avvio. Il rilancio della finestra di Steam riattivava quel controllo. Limitarsi a ritardare i nascondimenti conserva la causa. Per l'attesa è già disponibile il pannello che attraversa gli Space, quindi il client può finire di aprire le finestre senza essere nascosto durante Play.
+
+La regressione headless esegue il metodo reale su dieci riaperture simulate. Prima della correzione rileva chiamate a `hide()`. Con la correzione il contatore resta a zero e, alla scadenza, Steam viene comunque mostrato. [Prove interattive](../validation.md)
diff --git a/docs/steam.md b/docs/steam.md
new file mode 100644
index 00000000..17249f14
--- /dev/null
+++ b/docs/steam.md
@@ -0,0 +1,343 @@
+# Steam in Arcane
+
+Riferimento unico dell’integrazione Steam: cosa legge, come decide, cosa mostra, e cosa resta da validare. È il
+documento da leggere prima di toccare qualunque parte Steam. `architecture.md` ne tiene solo un riassunto;
+`file-map.md` elenca i file uno per uno.
+
+Ramo: `bium/library-manager` (rilascio grande, non pubblicato). Aggiornato al 17 novembre 2026.
+
+## Indice
+
+- [Principi](#principi)
+- [Stato di validazione](#stato-di-validazione)
+- [File di Steam letti](#file-di-steam-letti)
+- [Rilevamento e catalogo](#rilevamento-e-catalogo)
+- [Stati di un gioco Steam](#stati-di-un-gioco-steam)
+- [Osservazione dei file di Steam](#osservazione-dei-file-di-steam)
+- [Libreria: tile, ordine, pagina](#libreria-tile-ordine-pagina)
+- [Play, sessioni e primo piano](#play-sessioni-e-primo-piano)
+- [Ore di gioco](#ore-di-gioco)
+- [Achievement](#achievement)
+- [Metadati, arte e personalizzazioni](#metadati-arte-e-personalizzazioni)
+- [Dati su disco di Arcane](#dati-su-disco-di-arcane)
+- [Scelte del maintainer](#scelte-del-maintainer)
+- [Limiti noti e punti rimandati](#limiti-noti-e-punti-rimandati)
+- [Cambiare l’integrazione](#cambiare-lintegrazione)
+
+## Principi
+
+- **Steam non viene mai scritto.** Arcane legge file di Steam e invia solo URL `steam://` al client di Valve
+ (bundle `com.valvesoftware.steam`); non apre mai l’app di un gioco direttamente.
+- **Dati privati fuori dal tipo.** `localconfig.vdf`, `loginusers.vdf` e i file delle statistiche contengono ticket,
+ amici e altro: ogni lettore estrae solo i campi che servono, non li registra nei log e non li conserva oltre il
+ necessario. Nessun dato privato va in rete.
+- **Meglio niente che un numero sbagliato.** Un file illeggibile, un formato cambiato o un account diverso nascondono
+ il dato (ore, achievement) invece di indovinarlo.
+- **Formati di Valve non documentati.** Manifest, VDF, KeyValues binario e `console_log.txt` non hanno contratto. Ogni
+ lettore ha limiti di dimensione, rifiuta l’input malformato e degrada a un comportamento sicuro.
+- **Solo giochi Mac nativi.** Un gioco conta se nella sua cartella c’è esattamente un’app Mac che si dichiara gioco.
+ Niente Windows, CrossOver o Proton.
+- **Nessun gioco nxnative finto.** `CatalogGame` porta il payload reale (`SteamCatalogGame`); i comandi Switch
+ (build, salvataggi, mod) ricevono solo `PortedGame` e non possono partire da un gioco Steam.
+- **Fonte opzionale.** Con la fonte Steam spenta non partono scansioni o watcher del catalogo. La scoperta del primo avvio e l’offerta del benvenuto leggono soltanto per proporre la scelta, senza attivare la fonte; usano la cartella Steam salvata oppure quella standard. Una lettura incompleta nel primo avvio offre Retry, senza indicare che i giochi sono assenti.
+
+## Stato di validazione
+
+Lo stato di ogni parte Steam sta nell'elenco unico [validation.md](validation.md). Una parte conta come validata solo dopo la prova del maintainer in Arcane Dev.
+
+## File di Steam letti
+
+`` è la cartella scelta in Settings → Sources (di solito `~/Library/Application Support/Steam`).
+`` è ogni libreria: `` e quelle elencate in `libraryfolders.vdf`.
+
+| File | Lettore | Cosa ne esce |
+|---|---|---|
+| `/steamapps/libraryfolders.vdf` | `SteamLibrarySource` | percorsi delle librerie |
+| `/steamapps/appmanifest_.acf` | `SteamLibrarySource` | AppID, nome, `installdir`, `SizeOnDisk`, `buildid`, `StateFlags` |
+| `/steamapps/common//…` | `NativeMacApplication` | bundle Mac, header Mach-O (architetture), categoria dichiarata; mai eseguito |
+| `/config/loginusers.vdf` | `SteamPlaytimeReader` | l’account `MostRecent` |
+| `/userdata//config/localconfig.vdf` | `SteamPlaytimeReader` | per gioco solo `Playtime` (minuti) e `LastPlayed` |
+| `/appcache/stats/UserGameStatsSchema_.bin` | `SteamAchievementReader` | nomi, descrizioni, nascosti, icone degli achievement |
+| `/appcache/stats/UserGameStats__.bin` | `SteamAchievementReader` | solo `AchievementTimes` |
+| `/logs/console_log.txt` | `SteamLaunchQuestionWatch` | solo righe `GameAction [AppID …]`, durante un Play |
+
+Formati: `SteamKeyValues` (testo, campi duplicati conservati, nessuna direttiva eseguita), `SteamBinaryKeyValues`
+(binario). Le letture di file e cartelle hanno limiti di dimensione e di voci (`InstallationFileSnapshot`,
+`InstallationDirectorySnapshot`) e si possono annullare.
+
+I lookup senza distinzione maiuscole/minuscole sono condivisi nell’estensione di `[KeyValuesEntry]` in
+`SteamKeyValues.swift`. Le regole restano esplicite e distinte:
+
+| Lookup | Regola | Uso |
+|---|---|---|
+| `firstValue` | prima chiave, anche se il suo valore ha un tipo inatteso | blocchi del percorso in `localconfig.vdf` |
+| `firstString` / `firstObject` | primo valore del tipo richiesto; copie di altro tipo vengono saltate | schema e statistiche achievement |
+| `uniqueValue` / `uniqueString` | duplicati di qualsiasi tipo rifiutati; `uniqueString` rifiuta anche un valore non stringa | manifest, indice librerie e campi delle ore/account |
+
+I lettori decidono l’esito al proprio confine: i campi scalari non utilizzabili delle ore mantengono i ripieghi
+esistenti, mentre manifest e indici non validi producono una scansione parziale con un problema segnalato.
+Una prima stringa localizzata vuota negli achievement mantiene il ripiego inglese, senza scegliere un duplicato
+successivo. La pulizia del 16 novembre conserva questi risultati: sette prove aggiunte sui lettori reali passano
+prima e dopo l’estrazione. La verifica nella Dev resta da confermare; non è stata cambiata la semantica dei file.
+
+## Rilevamento e catalogo
+
+1. `CatalogSourcesModel` avvia una scansione: all’avvio se Steam è abilitato, su Refresh, quando si attiva la fonte o
+ si cambia cartella, e quando cambiano i file di Steam (vedi sotto). Una scansione alla volta, su un worker
+ annullabile; disattivare, cambiare cartella o chiederne un’altra invalida il risultato precedente.
+2. `SteamLibrarySource` produce uno `SteamLibrarySnapshot`: librerie lette, un’osservazione per manifest, problemi
+ trovati. Lo snapshot è completo solo senza problemi; uno parziale non autorizza mai a dimenticare giochi o librerie
+ non visti.
+3. `SteamCatalogReconciler` fonde lo snapshot nel catalogo: conserva UUID, preferiti, nascosti, scelte personali e le
+ installazioni già note. Un gioco non visto diventa «non rilevato» solo con uno snapshot completo.
+4. `CatalogRepository` è l’unico che scrive il catalogo (`CatalogDocument`, revisioni, lock); `CatalogLibraryProjection`
+ sceglie cosa mostrare in Spotlight, Collection e ricerca, con gli stessi UUID, filtri e ordine salvato dei giochi
+ Switch.
+
+## Stati di un gioco Steam
+
+Lo stato nasce dall’osservazione (`SteamGameObservation.State`) e arriva alla vista come `CatalogGamePresentation`.
+
+| Osservazione | Quando | Nel catalogo | Nella libreria |
+|---|---|---|---|
+| `nativeReady` | un’unica app Mac che si dichiara gioco, nessun problema | `.available`, riconosciuto | tile a colori, Play |
+| `downloading` | `StateFlags` senza il bit 4 (FullyInstalled); la cartella non viene letta | `.unavailable` + `isDownloading` | tile in download, pulsante «Downloading» |
+| `unavailable` | nessuna app nella cartella (es. disco scollegato) | `.unavailable` | resta nella riga senza Play se era già stato riconosciuto, altrimenti non entra |
+| `requiresReview` | più app, problemi di lettura, stesso AppID in due librerie | da controllare | Settings → Sources, «to review» |
+
+- Un gioco mai riconosciuto non entra nella riga, salvo mentre scarica. Play esiste solo con un’unica installazione
+ disponibile e niente da controllare.
+- `needsReview` è falso per un gioco in download: non compare fra quelli da controllare.
+- Un aggiornamento in coda su un gioco installato (`StateFlags` 6 o 1030: bit 4 presente) resta giocabile; Steam
+ aggiorna al lancio.
+- `StateFlags` mancante o illeggibile: si guarda solo la cartella, come prima del supporto ai download.
+- Il catalogo resta leggibile da una versione più vecchia di Arcane: `isDownloading` si decodifica con `decodeIfPresent` e la
+ disponibilità usa casi già esistenti.
+
+## Osservazione dei file di Steam
+
+`SteamManifestWatcher` apre un solo `FSEventStream` (eventi per file, latenza 2 s) sulle cartelle `steamapps` di
+tutte le librerie disponibili dell’ultima scansione. Ogni scansione ricontrolla anche i percorsi invariati: una
+cartella tornata disponibile entra nello stream, anche se le altre erano già osservate. Un avvio dello stream
+fallito si può ritentare. I percorsi degli eventi e delle cartelle usano la stessa normalizzazione (anche sotto
+`/var` e `/tmp`). Contano solo
+`appmanifest_.acf` e il `libraryfolders.vdf` della radice; un evento «rileggi le sottocartelle» del sistema
+conta solo se riguarda `steamapps` o una cartella sopra. Tutto il resto (`downloading/`, `common/`) viene scartato nel
+callback.
+
+`CatalogSourcesModel.steamFilesChanged` decide quando riscansionare: 3 s dopo l’ultimo evento utile, al massimo ogni
+15 s, mai sopra una scansione in corso (quella successiva la segue). Il watcher parte con la fonte e si ferma quando la
+fonte si spegne o l’app esce. Nessun polling.
+
+Il test dell’intervallo minimo confronta gli avvii delle scansioni pubblicati dal modello.
+
+Effetto: a fine download la tile passa da sola a colori con Play; un gioco installato o rimosso in Steam appare o
+sparisce senza Refresh.
+
+## Libreria: tile, ordine, pagina
+
+**Tile.** Il riquadro quadrato mostra sempre un’icona vera, mai una copertina ritagliata. Ordine: scelta del
+giocatore → icona dell’app installata → «Square» di LaunchBox della voce Mac o Windows, cercata per nome
+(`ArtworkStore.automaticSteamIcon`; un’assenza non si ricerca fino al prossimo avvio) → riquadro neutro. Nessuna
+etichetta «Steam» sulla tile: la piattaforma è nella pagina.
+
+**Tile in download** (`PortingTileLook.downloading`). Bianco e nero, la stessa leggera sfocatura del lucchetto Switch,
+«Downloading» sotto una freccia sottile in un cerchio (SF Symbol `arrow.down.circle`, peso light). Il simbolo pulsa
+piano in luminosità (`TileMotion.downloadMarkOpacity`, 0,4 ↔ 1 in 2,8 s; fermo con Riduci movimento). È un livello
+Core Animation (`DownloadMarkLayers`) posato fuori dal `drawingGroup` della tile: dentro, SwiftUI mostrerebbe un
+segnaposto giallo. Niente percentuale: Steam scrive il manifest troppo di rado (misurato: fermo 8 minuti durante un
+download).
+
+**Ordine della riga.** Ogni gioco che parte, anche da Steam, diventa il primo gioco della riga. Un gioco visto
+scaricare in questa sessione la guida come un gioco in porting: subito dopo la scheda Aggiungi gioco, dopo il porting,
+sopra l’ordine salvato con Move, e ci resta fino all’uscita anche a download finito (`SessionDownloads`,
+`SpotlightRow.leaders`). Al riavvio torna all’ordine normale.
+
+**Pagina.** Gli stessi pezzi Selene dei giochi nxnative (`GameLogoArea`, `GamePrimaryActions`, `SeleneStatsRow`,
+`SeleneHeroArt`), poi screenshot, About, la card Achievements e il pannello Details condiviso (`DetailsPanel`: Developer, Publisher,
+Size on disk, Installed in «Steam · »; in download solo Developer e Publisher; mai il build ID). La piattaforma è il logo
+ufficiale Valve (`SteamPlatformLogo`), con l’attribuzione in Settings › About e in `NOTICE`.
+
+**More like this** sta sotto About e Details. Usa la fascia e il focus condivisi con Switch, con fino a sei titoli correlati della libreria. I titoli Steam hanno precedenza; quando nessuno corrisponde, la fascia usa le corrispondenze Switch. Lo store legge i tratti per il punteggio dalla cache Steam all'apertura, e le scelte personali prevalgono. Doppio clic, Invio o A selezionano il gioco sulla riga di Spotlight.
+
+| Situazione | Primo pulsante | Nota sopra i pulsanti |
+|---|---|---|
+| installato | Play | — |
+| in download | «Downloading» con i puntini, come «Porting»; apre `steam://open/downloads` | — |
+| in download, senza client Steam | «Downloading», spento | «Steam is not installed on this Mac.» |
+| in avvio, in gioco, errore | Cancel, Resume, Try again | il motivo |
+
+Opzioni (`SteamOptionsView`): Play, Edit details (Change artwork, Change metadata, Store page), Move (solo Spotlight),
+Favorite, Hidden, Show in Finder.
+
+## Play, sessioni e primo piano
+
+- Play invia `steam://run/` (`SteamPlayCoordinator`) solo al client di Valve registrato. La richiesta aspetta che Arcane ordini e invii la finestra d'attesa al server delle finestre, così la copertura precede il passaggio di Space. Se il pannello non si prepara, la richiesta parte entro un secondo.
+ Il controllo senza finestre attende il completamento del task di ripiego, così il carico del runner non anticipa l'asserzione rispetto all'invio.
+- La sessione inizia quando compare il processo dell’app installata (stesso bundle ed eseguibile) e finisce quando
+ esce. Steam aperto non conta; un gioco avviato da Steam viene seguito allo stesso modo. Attesa massima 300 s; un pid
+ riusato non è il gioco. Una sessione in corso segue il processo che ha visto partire (pid e bundle) anche se il
+ catalogo nel frattempo cambia; le risposte tardive si scartano per generazione. Il coordinatore non osserva nulla
+ prima di Play: `RunningGameMonitor` chiude le sessioni rimaste aperte all’ultimo heartbeat e un gioco ancora in
+ esecuzione ne apre una nuova. I percorsi di ogni pid si risolvono una volta finché vive.
+- La schermata di lancio dei giochi Switch copre l’attesa in una finestra propria. Se ne va quando la finestra del
+ gioco è visibile, quando Play finisce o fallisce, quando il log dice che Steam aspetta una risposta del giocatore
+ (`SteamLaunchQuestions`: una riga `LaunchApp waiting for user response…` non seguita entro 1 s), o passata la
+ pazienza (15 s con Steam aperto, 45 s se Play deve avviarlo). Negli ultimi due casi Steam viene mostrato e la
+ testata invita a controllarlo. Perché una finestra propria: riprendersi il primo piano mentre Steam si portava davanti
+ faceva alternare a macOS schermo intero e scrivania per tutta l’attesa. Mentre la schermata è aperta Play non fa
+ nulla, per nessun gioco. Un clic la chiude (Arcane torna davanti se il gioco non è arrivato, salvo un gioco in
+ primo piano); se ne va comunque dopo 120 s. Un gioco avviato da Steam non la mostra.
+- `ShowInterstitials` è un passaggio di avvio che può restare in attesa oltre un secondo.
+ La schermata rimane visibile durante quel passaggio, con il normale limite di 15 s o 45 s.
+- Il log si legge fuori dal thread principale ogni 0,5 s durante l’attesa, per righe intere; la prima lettura prende
+ l’ultimo megabyte (conta anche una domanda rimasta aperta da un Play precedente), un file nuovo (Steam riavviato)
+ azzera tutto. Esempio di domanda: `KickingOtherSession`, il gioco è aperto su un altro dispositivo. Se Valve cambia
+ il formato, resta l’attesa a tempo.
+- **Keep Steam in the background** (`SteamBackgroundLaunch`): Steam avviato da Play parte con `-silent -nofriendsui`.
+ Durante l'attesa la schermata copre il client, che può finire di aprire le sue finestre. Nasconderlo in risposta
+ a ogni riapertura fa oscillare macOS fra lo Space fullscreen e la scrivania.
+ All'uscita di un gioco rimasto in primo piano, Steam torna fuori vista se lo era prima del Play.
+ [Analisi dello sfarfallio](reviews/2026-11-18-steam-launch-spaces.md)
+- All’uscita del gioco Arcane torna davanti se Play era partito da qui, il gioco era in primo piano e nessun
+ altro gioco della libreria è aperto (`SteamReturnFocus`). Una sessione finita mostra la card di fine sessione dei
+ giochi Switch, con il totale che include le ore di Steam.
+
+## Ore di gioco
+
+Le ore sono quelle di Steam (`Playtime`, tutti i computer) più le sessioni di Arcane successive all’ultimo valore
+visto, così nulla si conta due volte anche se Steam aggiorna il file in ritardo (`SteamPlaytimeBaselines`,
+`PlaySessionStore`). Un valore più basso o un altro account ripartono da capo; il totale non torna mai indietro per
+un minuto. Le letture (`SteamPlaytimeCoordinator`, una alla volta, fuori dal thread principale) avvengono quando
+cambiano catalogo o fonti, quando Arcane torna attiva e a fine sessione Steam (subito e dopo un minuto), solo se
+la data del file è cambiata; la regola di ogni lettura è il tipo puro `SteamPlaytimeSync`. Un file illeggibile
+conserva gli ultimi totali buoni dello stesso account; solo l’assenza di un account li azzera. Le sessioni uscite
+dall’elenco recente restano contate (`CarriedPlaytime.afterExternal`) finché Steam non aggiorna il valore; mentre i
+totali Steam sono nascosti, `PlaySessionStore.trimReferences` conserva il momento dell’ultimo valore di ogni gioco.
+
+## Achievement
+
+Dai file locali di `appcache/stats`, per l’account delle ore. Senza schema, account o file delle statistiche non c’è
+la card; un file malformato la nasconde (un file vuoto o troncato non è «nessuno sbloccato»). In rete vanno solo la
+rarità pubblica (`GetGlobalAchievementPercentagesForApp`, senza chiave, in cache un giorno, usata anche scaduta
+offline; una percentuale non numerica si scarta) e le icone dall’host community-assets del CDN di Steam (il vecchio
+percorso `steamcommunity/public/images` risponde 404 per le icone recenti). `SteamAchievementsStore` legge alla
+selezione del gioco, all’apertura della schermata e a fine sessione; tiene in memoria gli ultimi 16 giochi.
+
+Tier come i trofei PS5 (`AchievementTier`): Oro, Argento e Bronzo per rarità (sotto il 10%, sotto il 30%, il resto);
+Arcane, al posto del Platino, quando tutto è sbloccato. I cristalli sono arte del maintainer; l’Arcane è un video in
+loop (`ArcaneOrbVideo`, 1,5×) che a riposo resta fermo e grigio. Una tier non ottenuta tiene una traccia del suo
+colore. Un achievement segreto non ancora sbloccato mostra il nome mascherato e l’icona sfocata sotto un lucchetto.
+
+In cima alla colonna a destra di About, in un pannello chiaro quasi trasparente (sfocatura leggera dell’immagine)
+con il contorno sottile dei pulsanti
+(`DetailsAchievementsCard`: il miglior cristallo ottenuto a sinistra, «17/50» o, a gioco completato, il nome
+dell’Arcane, le ultime tre icone a ventaglio con hover o focus; selezionato, l’anello Selene sta sul bordo del
+pannello); A apre `AchievementsScreen` (filtri con LB/RB, ordine con Y, raro sotto il 10%: regole in
+`AchievementSummary`), B torna alla card. In testa alla schermata, a destra, i quattro cristalli con sotto la
+percentuale, la barra e il conteggio; a gioco completato il medaglione dell’Arcane. A su una riga apre il dettaglio
+come medaglione (`AchievementDetail`): icona grande con il cristallo sull’angolo, nome, descrizione, rarità e data. La card prende il focus fra gli screenshot e il pannello della fonte, accanto a Read more
+(Sinistra/Destra). «Your activity» non c’è: ore e ultima partita sono già nella testata. Schema: nomi e descrizioni
+nella lingua dell’app, poi inglese. Nessuna chiave Web API di Steam: non serve per questi dati.
+
+Correzione del 16 novembre, **validata dal maintainer nella Dev**: riaprire rapidamente la schermata durante la sua
+transizione poteva riusare la vista della lista con un nuovo `AchievementsScreenModel`, senza richiamare
+`onAppear` né cambiare altezza. La selezione avanzava, ma il nuovo modello non aveva geometria e lo scroll
+restava a zero. La lista riporta ora le misure con un `task(id:)` legato all’istanza corrente del modello
+([contratto SwiftUI](https://developer.apple.com/documentation/swiftui/view/task%28id%3Aname%3Apriority%3Afile%3Aline%3A_%3A%29)),
+conservando i controlli per altezza, scala e Riduci movimento. Nessun reset dell’identità della vista o dello stato.
+La sonda fuori schermo `run_achievement_scroll.py` riproduce il difetto con 41 righe sintetiche e verifica
+riaperture rapide e dopo la transizione, dettagli della prima riga, ridimensionamento e Riduci movimento.
+
+Armonizzazione successiva del 16 novembre: `SteamCatalogGame.firstAvailableInstallation` è il lookup condiviso
+per artwork, pagina, Opzioni, volume e osservazione dei processi. Restituisce la prima installazione con stato
+`available` nell’ordine del catalogo; non effettua I/O, non modifica i record e non decide se Play sia consentito.
+`CatalogGamePresentation` conserva i controlli di fonte, riconoscimento, review e unicità prima del lancio.
+I test di caratterizzazione di artwork e dettagli passano prima e dopo l’estrazione, compreso Play bloccato con
+più installazioni e assenza di app/dati installazione negli stati non disponibili. Questa pulizia non aggiunge
+funzionalità; la verifica nell’app dopo il refactor resta da confermare.
+
+## Metadati, arte e personalizzazioni
+
+- `SteamMetadataService`: dati pubblici dello store per AppID e lingua, separati da installazioni e scelte personali.
+ Solo HTTPS, niente redirect, al massimo sei trasferimenti insieme (gli altri aspettano in coda e si annullano se
+ la loro vista sparisce), 20 s per richiesta, ripiego sui dati validi già in cache.
+- Sfondo automatico (`SteamBackdropChoice`): immagini in formato schermo (Xbox, GOG, TheGamesDB, poi la fan art
+ LaunchBox), poi il primo screenshot, per ultimo il banner della libreria Steam ritagliato. La scelta del giocatore
+ vince sempre; svuotare la cache artwork ricalcola la scelta automatica.
+- Le immagini si decodificano fuori dal thread principale (`GameArtLoader.decode`) alle misure dei giochi Switch
+ (sfondo 2560 px, logo 1600, copertina 900, icona 512): un `NSImage(contentsOf:)` si decodificava al primo disegno e
+ costava a quel frame 40–60 ms.
+- `SteamGameFacts` condivide i dati store per AppID e lingua fra testata, pagina e input; un’assenza si richiede di
+ nuovo dopo un minuto.
+- `SteamPersonalizationStore`: testo e immagini scelte in un solo manifest atomico; un errore conserva le scelte
+ precedenti. SteamGridDB usa la chiave del giocatore, in `steamgriddb-api-key` con permessi `0600`, mai nei log.
+
+## Dati su disco di Arcane
+
+Sotto `Application Support/NXLibrary` (Dev: `NXLibrary-Development`):
+
+| Percorso | Contenuto |
+|---|---|
+| catalogo (`CatalogDocument`) | giochi Steam con installazioni, preferiti, nascosti, `isDownloading` |
+| `integrations/steam/enrichment//` | metadati store, icone degli achievement, rarità |
+| `integrations/steam/artwork-picks/` | immagini scelte dal giocatore |
+| `integrations/steam/metadata-picks.json` | testi scelti dal giocatore |
+| `integrations/steam/playtime-baselines.json` | ultimo totale di Steam visto per gioco, con l’ora |
+
+## Scelte del maintainer
+
+- Lucchetto solo per i fallimenti Switch; un download ha il suo aspetto (15 nov 2026).
+- Riquadri: solo icone vere, mai arte ritagliata; ordine scelta → icona dell’app → Square LaunchBox → neutro.
+- Download: bianco e nero pieno (non colori sbiaditi), simbolo che pulsa senza alone, cerchio sottile, pulsante
+ «Downloading» come «Porting», nessuna nota sopra i pulsanti, gioco in testa alla riga fino all’uscita.
+- Nessuna etichetta «Steam» sulle tile.
+- Pagina: «Your activity» tolta, Achievements in cima alla colonna destra, in un pannello chiaro quasi trasparente
+ con contorno sottile (dopo aver provato senza riquadro e con un’ombra, 15 nov 2026).
+- Logo Steam inalterato al posto del valore sotto PLATFORM, con lo spazio libero ridotto sopra.
+- Ore: base di Steam più le sessioni successive.
+- Achievement (16 nov 2026): Arcane al posto del Platino, cristalli e video dell’Arcane fatti dal maintainer, video a
+ 1,5×, medaglione al 100% e nel dettaglio, percentuale e barra larga sotto i cristalli, lucchetto sfocato sui segreti.
+
+## Limiti noti e punti rimandati
+
+Decisi consapevolmente:
+- Un download in pausa, in coda o abbandonato ha lo stesso aspetto di uno attivo (i flag non li distinguono); i
+ puntini si muovono comunque. Steam → Download dice quale.
+- `StateFlags` senza il bit 4 per altri motivi (file mancanti, disinstallato a metà) mostra «Downloading»: anche lì
+ Steam deve scaricare.
+- Un manifest rimasto a 1026 dopo un download annullato continua a mostrare «Downloading».
+- Un’assenza su LaunchBox (anche per rete assente) non si ricerca fino al prossimo avvio.
+
+Punti minori rimandati dalle revisioni, da decidere prima del rilascio:
+- Watcher: se la scrittura della configurazione fallisce, resta fermo fino alla scansione successiva;
+ il callback usa `unsafeBitCast` a `NSArray`. Il solo collegamento di un volume non avvia una scansione:
+ serve Refresh o una modifica rilevante ai file Steam già osservati.
+- Un Refresh manuale non annulla una riscansione in attesa (una scansione in più).
+- `openDownloads` ignora gli errori di apertura.
+- Achievement: la freccia Su sparisce col focus sulla card; riepilogo ricalcolato a ogni disegno. (Risolti il 16 nov
+ 2026: ordine «più rari» stabile a parità di percentuale, rarità `nan` scartata, lampo dell’icona allo scorrimento.)
+- Il focus dei link Details non viene limitato quando una disinstallazione Steam ne riduce il numero.
+- Un errore Wikidata sospende per 60 s anche le richieste degli altri giochi.
+- In Change metadata, il nome canonico arrivato da IGDB riavvia le ricerche LaunchBox/TheGamesDB.
+- Ore Steam: dopo «nessun account», un errore senza account può ripubblicare le ore precedenti.
+- Un catalogo occupato da un’altra istanza viene presentato come installazione fallita.
+- La prima conversione scrive il backup prima del principale: un errore del secondo può offrire «Restore backup»
+ per il catalogo appena convertito, con dati corretti ma un messaggio poco chiaro.
+
+Revisione del 16 novembre 2026: corretti il focus della card durante lo scroll, il caricamento degli achievement
+richiesto prima della configurazione Steam e la disponibilità di Details sotto i pannelli. I lettori di statistiche,
+schema, account e ore usano ora `InstallationFileSnapshot`, con limite durante la lettura, rifiuto dei symlink finali
+e verifica della stabilità del file. Test Core e controlli delle vere funzioni dell’app con dati sintetici verificano
+le regressioni; nessuna finestra viene aperta. **In attesa di validazione umana nella Dev.**
+
+## Cambiare l’integrazione
+
+- Un nuovo file di Steam da leggere: un lettore in `Sources/NXLibraryCore/Services/Steam/` che estrae solo i campi
+ necessari, con limiti di dimensione, test con fixture sintetiche (`SteamTestSupport`) e una riga nella tabella
+ [File di Steam letti](#file-di-steam-letti).
+- Un nuovo stato o campo nel catalogo: decodifica tollerante (`decodeIfPresent`) e nessun nuovo caso persistito che una
+ versione più vecchia di Arcane non sappia leggere.
+- Una nuova animazione su una tile: Core Animation fuori dal `drawingGroup`, ferma con Riduci movimento.
+- Testi: sei lingue in `Localizable.xcstrings`.
+- Aggiornare questo documento, il riassunto in `architecture.md` e `file-map.md` nello stesso commit.
diff --git a/docs/upstream-upgrades/2026-11-18-8a5c5e7e-461a5f9f-review.md b/docs/upstream-upgrades/2026-11-18-8a5c5e7e-461a5f9f-review.md
new file mode 100644
index 00000000..6ca3e00b
--- /dev/null
+++ b/docs/upstream-upgrades/2026-11-18-8a5c5e7e-461a5f9f-review.md
@@ -0,0 +1,16 @@
+# 2026-11-18 — nxnative 8a5c5e7e → 461a5f9f
+
+Arcane 0.2.0 pins `461a5f9f95fc9fc40a690bb2a82eb23f1f03bdca` at the maintainer's direction. The previous pin was `8a5c5e7e1ee606c650fe1aef6959a83009b6a2fc`. The upstream range contains 383 commits across 989 files. The narrower range from `a2c731e32ea5124055553aac62ccb10fab34805d`, the commit already tried through **Newest engine**, contains 30 commits. [Upstream comparison](https://github.com/seedds/nxnative/compare/a2c731e3...461a5f9f)
+
+| Area | Change and Arcane integration |
+|---|---|
+| Shaders and pipelines | Updated translation tools, resource ordering and prewarm. nxnative manages shader compatibility through its chain ID and builds pipelines through the existing Mac packer. |
+| Host, input and audio | NVN texture layout, audio device routes, video decoder recovery, controller trigger thresholds and Joy-Con haptics are handled by the generated Mac host. The account picker is implemented in that host, and Arcane's local backups preserve the user registry. |
+| Profiles | Upstream updates game profiles and reports Mac testing for Fast Fusion, Orbitals and Nintendo Switch 2 Welcome Tour. Arcane uses those profiles through the existing porting workflow. |
+| Packing and extraction | nxnative handles truncated PFS0 payloads and unreadable optional base lookups. For multiprogram NUPs, the Mac packer bundles the additional RomFS images and Arcane's existing selection passes the requested program explicitly. |
+| CLI and runtime | The flags Arcane sends are available. Bundled Python covers the declared dependencies. Xcode 27.2 / Metal 32023.922 remains the certified toolchain. |
+| Scope | Diagnostic environment switches, custom iOS lifecycle interfaces and frontend-owned RomFS placement are outside the Arcane Mac workflow. |
+
+The last commit reduces unnecessary scans in shader rewriting. Upstream reports identical MSL, reflection data and variants for the 2,976 Fast Fusion shaders built on both revisions. [Upstream PR #2897](https://github.com/seedds/nxnative/pull/2897)
+
+Arcane's actual compatibility checker passes on a clean temporary checkout of the exact commit, with the bundled Python and installed Metal 32023.922. All 1,806 Swift tests pass, including the runtime dependency and porting-error checks against this exact hash. Arcane Dev carries the new pin and passes strict signature verification. The maintainer chose to adopt the pin without repeating a game rebuild. The individual manual checks are recorded in [validation.md](../validation.md).
diff --git a/docs/upstream-upgrades/README.md b/docs/upstream-upgrades/README.md
index 1d65abde..02d6eaf2 100644
--- a/docs/upstream-upgrades/README.md
+++ b/docs/upstream-upgrades/README.md
@@ -81,3 +81,4 @@ This directory records the review that must happen before the pin changes, plus
- [2026-11-09 — bd979ced → 79741184](2026-11-09-bd979ced-79741184-review.md) (0.1.4.2: 71 commits; adopted at the maintainer's explicit request after automated review/gate checks; exact-hash real game build/launch remains unconfirmed).
- [2026-11-12 — 79741184 → 8a5c5e7e](2026-11-12-79741184-8a5c5e7e-review.md) (0.1.4.3: 152 commits; adopted at the maintainer's explicit request; builds need no .NET; build stop and package probe adapted; real build/launch awaiting the maintainer)
+- [2026-11-18 — 8a5c5e7e → 461a5f9f](2026-11-18-8a5c5e7e-461a5f9f-review.md) (0.2.0: 383 commits; adopted at the maintainer's explicit request after the certified gate and automated checks)
diff --git a/docs/validation.md b/docs/validation.md
new file mode 100644
index 00000000..fbdd2dfd
--- /dev/null
+++ b/docs/validation.md
@@ -0,0 +1,88 @@
+# Arcane — stato della validazione
+
+Questo è l'unico elenco di ciò che il maintainer ha provato nell'app. Una cosa è **validata** solo quando il maintainer conferma di averla provata nell'app (Arcane Dev per il lavoro non pubblicato). Test automatici, compilazione e revisioni degli agenti la sostengono, ma non la sostituiscono (AGENTS.md).
+
+Come si aggiorna:
+- Quando il maintainer conferma, la riga passa a **validato**, con la data e le sue parole se utili.
+- Ogni lavoro nuovo aggiunge la sua riga **in attesa**, con le prove manuali da fare.
+- Le guide ([architecture.md](architecture.md), [steam.md](steam.md)) descrivono come funziona; lo stato sta solo qui.
+
+## Lavoro non pubblicato (ramo `bium/library-manager`)
+
+| Parte | Stato | Prove ancora da fare |
+|---|---|---|
+| Pulsante di sostegno volontario | in attesa | In Arcane Dev, Settings → About mostra Support Arcane prima dei crediti, con la tazza Buy Me a Coffee e il testo sul contributo facoltativo. Verificare il focus e l’apertura della pagina pubblica con mouse, tastiera e controller. Dopo la pubblicazione, verificare lo stesso indirizzo dal README e dal pulsante Sponsor di GitHub. |
+| Candidata 0.2.0 con pin `461a5f9f` | in attesa | Su copie temporanee, l'updater della 0.1.4.3 legge il requisito del nuovo engine, verifica lo ZIP con questo pin e sostituisce il bundle. La rinomina conserva la firma. Prima del passaggio da 0.1.4.3 spostare eventuali copie sorelle `(new)` e `(old)`, che il vecchio updater può cancellare. Resta la prova interattiva dell'aggiornamento con benvenuto, dati conservati e rinomina su Quit. |
+| Nome Arcane in ciò che si vede (finestra, menu, Settings, About, testi nelle sei lingue; copia Dev `Arcane Dev.app`) | in attesa | Aprire `~/Applications/Arcane Dev.app` e ritrovare libreria e impostazioni della vecchia Dev; nessun "NX Library" visibile nelle sei lingue |
+| Rinomina del file alla chiusura (`NX Library.app` → `Arcane.app`) | in attesa | Con la prova del ponte A → B: dopo l'aggiornamento, chiudere; il file diventa `Arcane.app` e il Dock lo apre. Restart app non rinomina |
+| Impostazioni in General, Library, Porting e System (sezioni nuove Games, Keys, Cloud saves, Storage di Porting, Console; Rumble in New games) | gruppi, navigazione con controller, Search e conservazione dei valori confermati il 17 nov 2026 («ho fatto tutte le verifiche e mi sembra che non ci sia niente di sbagliato»); altre varianti in attesa | Changed mostra "Porting · …"; Reset group in Library → Games non tocca Rumble; i link "Settings → …" degli errori aprono la sezione giusta |
+| Primo avvio da ciò che è già sul Mac (pagina `found`) | percorso base con profilo vuoto e riavvio validato il 17 nov 2026 («fatto»); interruttore spento e Setup interrotto confermati il 17 nov; altre varianti in attesa | Conteggi e scelte Steam nei diversi casi; interruttore spento → nessuna fonte Steam; card Porting → Get ready, B torna indietro; con l'interruttore acceso e il percorso Porting fino a Your games o Skip, Steam è acceso; caso vuoto con "No games found"; Open library durante la lettura prosegue e le fonti restano aggiungibili dopo; verifiche complete con frecce, mouse e controller |
+| Benvenuto in Arcane, una volta, per chi aggiorna | percorso Add Steam → Open library → riavvio validato nella Dev il 17 nov 2026 («fatto»), con flag del benvenuto e fonte Steam salvati; caso Steam già attivo confermato il 17 nov; altre varianti in attesa | Not now; chiusura con B/Esc e diverse modalità di input; gioco già aperto con Play/Resume; Riduci movimento e precedenza del Setup. Il percorso di installazione tramite updater resta nella prova A → B |
+| Rifinitura del primo avvio: scelta Steam persistente, cartella personalizzata, Retry e notifiche contestuali | in attesa | Chiudere e riaprire durante Porting con scelta Steam accesa/spenta; nessuna scelta residua dopo il completamento; radice Steam personalizzata sia in scoperta sia dopo Add; lettura incompleta → Retry o continua; nessuna richiesta notifiche all’avvio, richiesta soltanto al primo porting accettato |
+| Blu predefinito e superfici Arcane Crystal / Arcane Flow e particelle morbide | in attesa | Menu rapido → Theme: Arcane è il primo tema e conserva il blu originale anche al primo avvio e nel fallback; Arcane Crystal e Arcane Flow sono scelte aggiuntive; provare entrambi per fili sottilissimi piegati da onde lente lungo le curve (senza bordi rigidi), soli filamenti con luce diffusa appena visibile, senza fasci o piani, colore locale stabile; cambio tema immediato senza spostare la card, riavvio e passaggi fra temi, artwork, wallpaper e Mods; senza riga Particles; frecce/controller restano nella griglia e A continua allo sfondo. Nessuna scelta delle particelle in Look/Search/Changed. Preferenze esistenti, riavvio e Reset conservano gli altri valori; wallpaper/video conservati; Riduci movimento e Background motion fermano colori e moti; card Mods mantiene l’oro; ritorno alla home e primo avvio senza lampi |
+| Particellare e ritmo dell'entrata della libreria | aspetto validato il 17 nov 2026 («abbiamo risolto la questione particellare») | Riduci movimento prima e durante il volo; avvio con wallpaper e recupero di un errore di preparazione; con entrata spenta il primo input agisce subito, filtri vuoti e righe corte; avvio su macOS 13. Le prove dei dialoghi nativi hanno una riga separata |
+| Entrata senza salto; barra in alto e hint dei pulsanti per ultimi | in attesa | All'avvio la barra in alto (tab e orologio) e gli hint in basso compaiono insieme solo dopo tessere e informazioni, con una breve dissolvenza. Durante fullscreen, attesa e volo: frecce, Invio, clic su una tessera o sugli hint, rotella e controller non fanno nulla e non saltano l'entrata; dopo, tutto risponde. ⌘Q e ⌘, funzionano anche durante l'entrata. Ritorno alla home e Riduci movimento: barra e hint subito visibili. |
+| Primi cambi gioco in Spotlight | scorrimento e prova di Play confermati dal maintainer il 18 nov 2026 | Apertura con Giù, dissolvenza sotto gli screenshot, ripristino selezione e fascia Mods su due giochi. Nella prova di rilascio isolata resta la riconciliazione di una mod rimossa. |
+| Apertura immediata di Settings con ⌘, | correzione del backdrop persistente in attesa di prova umana | Dopo avvio a freddo premere subito ⌘,; verificare scatto o intervallo nero. Ripetere dopo il fullscreen; i log locali Dev `backdrop-transition` devono mostrare lo stesso renderer fra home e Settings con lo stesso wallpaper; controllare anche wallpaper Settings dedicato, Theme e Mods. Nessuna conferma visiva automatica |
+| Immagini Spotlight al ritorno da Settings | in attesa | Ripetere Settings → home con icone nxnative automatiche e personali, Steam e card Mods già caricata; nessun passaggio al ripiego. Cambiare/rimuovere un'immagine personale e tornare ad Automatic; aggiornamento Steam nello stesso percorso; badge e cover Mods dopo rimozioni o cambio abbinamento da Collection. Il controllo automatico costruisce i valori delle viste senza finestre, non sostituisce la prova visiva |
+| Cartella Game files ricordata senza scansione dei sorgenti all'avvio | avvio e scelta cartella validati il 17 nov 2026 («funziona») | Annullare il selettore senza perdere la bozza; scegliere singoli file da un'altra cartella senza cambiare Game files; rebuild di un gioco dalle sue sorgenti registrate |
+| Priorità dei dialoghi nativi su controller, tastiera e menu | selettore cartella, isolamento del controller e ripresa dopo Esc validati il 17 nov 2026 («si funziona») | Invio nel selettore; ripetere con un alert nativo e con un dialogo interno (per esempio il controllo aggiornamenti), che deve continuare a ricevere i suoi comandi quando è in primo piano |
+| NUP: programma selezionato, base DLC e rebuild coerenti | in attesa | Con un engine capace: importare un NUP multiprogramma, scegliere update e ricostruire lo stesso programma; record storico mantiene programma zero; checkout precedente blocca selezioni non supportate senza impedire Play |
+| Newest engine: build, Play, controller, salvataggio e riapertura | validato il 17 nov 2026 su `a2c731e32ea5124055553aac62ccb10fab34805d` («funziona benissimo tutto»), con record di build riuscita sullo stesso hash | Conferma del percorso provato, non di tutti i giochi o del giroscopio; il pin ufficiale resta distinto. La scelta esplicita Newest engine registra `toolchainVerified=false` |
+| Prewarm: attività del primo avvio, tempi e avvisi | build e primo avvio confermati il 17 nov 2026 su `a2c731e3`; il log registra Prewarm pipelines concluso con successo. Altre varianti in attesa | Attività localizzata senza ETA ricavata dal vecchio porting, tempo trascorso aggiornato, Stop e ripresa; warning non fatale → app pronta e spiegazione del primo avvio più lungo; spazio sul volume di destinazione |
+| App con bundle dati firmati annidati | build reale e Play confermati il 17 nov 2026 su `a2c731e3`; altre varianti in attesa | Cambio/ripristino icona e relativo Play; ripetere su un volume esterno. Le fixture automatiche con firme reali provano il ramo di copia forzato, non un filesystem esterno |
+| Backup locali multiutente e compatibilità dei vecchi backup | creazione del backup con Back up now e apertura di Backup folder confermate il 17 nov 2026 («ho fatto tutte le verifiche»); casi multiutente e restore in attesa | Con gioco chiuso: backup completo e restore di utenti/registro; vecchio backup conserva gli utenti aggiuntivi; import cartella modifica solo User/Device; testi del limite cloud e conferme; fonti/app reali costruite altrove incluse |
+| Catalogo comune nella Dev (`CatalogRepository`, conversione da `library.json`, recupero) | in attesa | Prima apertura della Dev con libreria reale, recupero esplicito |
+| Updater: copie accanto all’app e guasti di sostituzione | in attesa | Prova A → B isolata: conservare eventuali copie `(new)` / `(old)`, nome dell’app e riavvio; Cestino non disponibile conserva la vecchia app. Le regressioni automatiche usano bundle sintetici, mai la copia pubblicata |
+| Conflitto con modifiche della vecchia libreria | in attesa | Su profilo di prova isolato: errore → Mantieni la libreria di Arcane; giochi e fonti invariati, archivio separato e riavvio. Retry dopo una modifica successiva ai file; nessuna fusione automatica. Non alterare il profilo pubblicato per provocare il caso |
+| Fonti e libreria mista (Steam + Switch, Manage sources) | in attesa | Attivazione e disattivazione delle fonti, persistenza delle scelte, conservazione delle voci e librerie su disco esterno |
+| Steam: metadati store e arte | in attesa | — |
+| Steam: pagina condivisa, Opzioni, personalizzazioni | in attesa | — |
+| Steam: Play, schermata di lancio, domande di Steam, Steam in background | Play/Resume validati il 17 nov 2026. Correzione dello sfarfallio accettata il 18 nov («Ok, ci siamo»). Varianti a freddo e domande in attesa. | Ripetere Play dopo Quit di Steam e verificare che la copertura resti visibile fino all'apertura del gioco. Verificare che Steam venga mostrato una volta se serve una risposta. |
+| Schermata d'attesa Steam e Switch con angolo libero | in attesa | Con Play di un gioco Steam e di un gioco Switch già installato, verificare che l'angolo inferiore destro resti libero durante l'attesa. |
+| Steam: ore di gioco | validato il 17 nov 2026 («le ore di Steam funzionano») | — |
+| Steam: giochi in download, osservazione dei manifest, ordine della riga | aspetto validato il 15 nov 2026 | Fine del download e controlli di accettazione |
+| Achievement Steam: lista, rarità, tier a cristallo, card Details | presenza e consultazione confermate il 17 nov 2026 («gli achievement ci sono»); dettagli in attesa | Rarità, tier e casi privati/offline o senza statistiche |
+| More like this nei giochi Steam | in attesa | Scendere sotto About e Details di un gioco Steam senza corrispondenze sulla sua fonte, ma con titoli Switch affini. Con corrispondenze Steam, verificare la precedenza della stessa fonte. Controllare immagini, focus e selezione con tastiera, controller e doppio clic. |
+| Achievement: la lista segue la riga scelta dopo chiusura e riapertura rapide | validato il 16 nov 2026 | — |
+| Achievement: video Arcane, medaglioni del dettaglio, lucchetto dei segreti, scorrimenti (`GlideGroup`) | in attesa | — |
+| Achievement: intestazione senza 100% (percentuale, barra larga e conteggio sotto i quattro trofei, 44 pt / 4) | in attesa | — |
+| Correzioni della revisione di sviluppo (focus della card, nuovi tentativi, piattaforma dei loghi, osservazione delle librerie Steam, lettori protetti) | in attesa | — |
+| Revisione 0.2.0: letture dal disco e residui | in attesa | Pagina di un gioco con cheat: "Cheats on" giusto; spegnerli in Game options → Cheats e tornare: l'etichetta sparisce. Game options: cambiare lingua, rumble e scala, chiudere e riaprire: valori salvati. Setup check aperto: cambiare Xcode con `xcode-select` e vedere la scheda aggiornarsi entro qualche secondo. Un gioco senza icona: dopo la build la tessera mostra la sua icona. Benvenuto e Setup all'avvio: chiuderli lascia lo stesso sfondo in movimento. |
+| Icona dell'app: cristallo nella sfera di vetro con pennellate blu e prugna | scelta dal maintainer il 18 nov 2026 (immagine fornita da lui); resa in attesa | Dock, Finder e Launchpad a dimensione piccola; App icon in Look: Light, Dark e Mono; README su GitHub |
+| Posizione condivisa dei comandi: `SeleneHintsBar` a 32 unità dal fondo | in attesa | La posizione dei Settings (`7adc0ad`) è validata; la via di mezzo a 32 no |
+| Pannello Details uguale per ogni fonte | validato il 16 nov 2026 | — |
+| Voto della critica con Wikidata | validato il 16 nov 2026, abbinamenti compresi | — |
+| IGDB facoltativo: credenziali, voti, minimo di 3 recensioni, media utenti come ripiego | in attesa (il ripiego utenti è approvato come scelta) | Ocarina con voto utenti, un gioco con voto della critica, cambio rapido di gioco, rimozione di IGDB |
+| Sezione Online services (IGDB e SteamGridDB) | in attesa | — |
+| IGDB in Change metadata | in attesa | Un gioco nxnative e uno Steam, scelta, Q/E e controller, Automatic, testo personale, persistenza, offline/retry, chiusura durante il caricamento |
+| LaunchBox e TheGamesDB in Change metadata (ambito approvato il 16 nov 2026) | in attesa | Source picker su Switch 2 e Steam, persistenza, righe uguali/assenti, controller, offline/retry, immagini TheGamesDB per Mac/PC |
+| Movimento del selettore dei metadati (`SeleneExpandableText`) | in attesa | Su/giù ripetuti fra descrizioni corte e lunghe, scroll fino alla fine, Q/E, Riduci movimento |
+| Lingua e regione (sei lingue) | validato nella Dev, compreso il cambio immediato e la sidebar senza spostare il focus | Le traduzioni sono bozze, non revisioni madrelingua; issue #10 aperta |
+| Spazio per gioco in Settings → Storage | validato il 9 nov 2026 | — |
+| Profilo Dev isolato | avvio e libreria Dev validati il 9 nov 2026 | Non copre ogni azione su giochi, mod o salvataggi reali |
+
+## Versioni pubblicate
+
+| Parte | Stato | Note |
+|---|---|---|
+| 0.1.2: scansione e cursore (revisione 2), menu nativi, dialogo aggiornamenti, avvio a schermo intero, riga di scansione, gate certificato | validato | — |
+| 0.1.4.2: tempo della fase e durate oltre i 60 minuti | in attesa | — |
+| 0.1.4.2: Play durante la firma dell'icona (Preparing / Cancel) | in attesa | — |
+| 0.1.4.2: icona sul Mac, Only here / Use on the Mac | in attesa | — |
+| 0.1.4.2: icone automatiche (`AutomaticIconResolver`) | in attesa | Switch Icon Showdown esclude `/images/` ai crawler (9 nov 2026): la fonte non è operativa e la issue #12 non è risolta |
+| Prova di aggiornamento A → B con l'app installata | in attesa | Vedi [development.md](development.md#first-installation-and-a--b-update-test) |
+
+## Pin dell'engine
+
+Il dettaglio di ogni revisione è in [upstream-upgrades](upstream-upgrades/README.md).
+
+| Pin | Versione | Stato |
+|---|---|---|
+| `461a5f9f` (Metal 32023.922, Xcode 27.2) | 0.2.0, attuale | adottato su richiesta del maintainer. Gate certificato e test automatici passati. Rebuild e avvio sull'esatto hash non eseguiti per la decisione del maintainer. |
+| `8a5c5e7e` (Metal 32023.922, Xcode 27.2) | 0.1.4.3 | adottato su richiesta del maintainer; build e avvio sull'esatto hash da confermare |
+| `79741184` | 0.1.4.2 | gate e test superati; build e avvio sull'esatto hash non confermati |
+| `bd979ced` | 0.1.4.1 | — |
+| `e5f03403`, `7fe9fc4d` | precedenti | confermati con un rebuild di Ocarina of Time |
+| `04df08d4` | precedente | confermato con un build di Ocarina of Time |
+| `4a0551e4` | precedente | gate certificato, build di Wonder con archivio pipeline e avvio confermati |
diff --git a/scripts/build_app.sh b/scripts/build_app.sh
index 43e60c9d..1430156c 100755
--- a/scripts/build_app.sh
+++ b/scripts/build_app.sh
@@ -3,18 +3,20 @@
# NX_VERSION sets the app version (default: the version in progress, from the VERSION file); NX_RELEASE=1
# marks a release copy, the only kind that updates itself. scripts/release.sh sets both; a plain build sets
# neither, so a development copy carries the version being worked on and says it is a development build.
-# A development copy is "NX Library Dev" (default ~/Applications/NXLibrary Dev.app), the maintainer's test copy,
-# beside the released "NX Library" that updates itself. Both keep the bundle ID local.nxlibrary, so they share the
-# library, keys and settings, and macOS runs only one of them at a time.
+# A development copy is "Arcane Dev" (default ~/Applications/Arcane Dev.app), the maintainer's test copy,
+# beside the released "Arcane" that updates itself. The development marker selects separate launcher
+# data/preferences and a distinct bundle ID, so framework-owned preferences are separate too.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
if [ "${NX_RELEASE:-0}" = "1" ]; then
- NAME="NX Library"
- APP="${1:-$HOME/Applications/NX Library.app}"
+ NAME="Arcane"
+ BUNDLE_ID="local.nxlibrary"
+ APP="${1:-$HOME/Applications/Arcane.app}"
else
- NAME="NX Library Dev"
- APP="${1:-$HOME/Applications/NXLibrary Dev.app}"
+ NAME="Arcane Dev"
+ BUNDLE_ID="local.nxlibrary.development"
+ APP="${1:-$HOME/Applications/Arcane Dev.app}"
fi
CONFIG="${NX_BUILD_CONFIG:-release}"
VERSION="${NX_VERSION:-$(tr -d '[:space:]' < "$ROOT/VERSION")}"
@@ -22,7 +24,7 @@ if ! [[ "$VERSION" =~ ^[0-9]+(\.[0-9]+){1,3}$ ]]; then
echo "error: NX_VERSION must be dotted numbers, got '$VERSION'" >&2
exit 1
fi
-RELEASE_KEY=""
+RELEASE_KEY=" NXLibraryDevelopmentProfile"
[ "${NX_RELEASE:-0}" = "1" ] && RELEASE_KEY=" NXLibraryRelease"
if [ -z "${DEVELOPER_DIR:-}" ]; then
if [ -d "/Applications/Xcode.app/Contents/Developer" ]; then
@@ -57,6 +59,7 @@ done
[ -f "$ROOT/NOTICE" ] && cp "$ROOT/NOTICE" "$APP/Contents/Resources/NOTICE"
cp "$ROOT/scripts/validate_update.py" "$APP/Contents/Resources/validate_update.py"
[ -d "$ROOT/Resources/Selene" ] && cp -R "$ROOT/Resources/Selene" "$APP/Contents/Resources/Selene"
+[ -d "$ROOT/Resources/Brands" ] && cp -R "$ROOT/Resources/Brands" "$APP/Contents/Resources/Brands"
# Python and build tools from scripts/bundle_runtime.sh. Without it, a developer
# build falls back to ~/nxnative/.venv and the PATH tools.
if [ -d "$ROOT/work/Runtime" ]; then
@@ -78,7 +81,7 @@ cat > "$APP/Contents/Info.plist" <CFBundleDisplayName$NAME
CFBundleExecutableNXLibrary
CFBundleIconFileAppIcon
- CFBundleIdentifierlocal.nxlibrary
+ CFBundleIdentifier$BUNDLE_ID
CFBundleInfoDictionaryVersion6.0
CFBundleName$NAME
CFBundlePackageTypeAPPL
@@ -96,6 +99,15 @@ $RELEASE_KEY
PLIST
+# Exercise the real profile/defaults accessor under this bundle identity, without
+# opening the app or importing data. Unit-test hosts have a different identity.
+PROFILE_PROBE="$STAGE/ProfileCheck.app"
+mkdir -p "$PROFILE_PROBE/Contents/MacOS"
+cp "$APP/Contents/Info.plist" "$PROFILE_PROBE/Contents/Info.plist"
+swiftc -I "$ROOT/.build/$CONFIG" "$ROOT/scripts/check_app_profile.swift" \
+ "$ROOT/.build/$CONFIG/NXLibraryCore.o" -o "$PROFILE_PROBE/Contents/MacOS/NXLibrary"
+"$PROFILE_PROBE/Contents/MacOS/NXLibrary"
+
python3 "$ROOT/scripts/check_localizations.py" --app "$APP"
codesign --force --deep --sign - "$APP"
codesign --verify --deep --strict "$APP"
diff --git a/scripts/build_dmg.sh b/scripts/build_dmg.sh
index 70b15c86..28105ac3 100755
--- a/scripts/build_dmg.sh
+++ b/scripts/build_dmg.sh
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
-# scripts/build_dmg.sh [app] — packs a built NX Library into dist/NXLibrary.dmg.
+# scripts/build_dmg.sh [app] — packs a built Arcane into dist/NXLibrary.dmg.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
@@ -12,15 +12,15 @@ codesign --verify --deep --strict "$APP"
STAGE="$(mktemp -d "${TMPDIR:-/tmp}/nxlibrary-dmg.XXXXXX")"
trap 'rm -rf "$STAGE"' EXIT
-cp -R "$APP" "$STAGE/NX Library.app"
+cp -R "$APP" "$STAGE/Arcane.app"
ln -s /Applications "$STAGE/Applications"
mkdir -p "$ROOT/dist"
rm -f "$OUT"
# macOS 26 deprecates `hdiutil create -volname`; `diskutil image` makes the same compressed image (APFS inside).
if diskutil image create from --help >/dev/null 2>&1; then
- diskutil image create from --format UDZO --volumeName "NX Library" "$STAGE" "$OUT" >/dev/null
+ diskutil image create from --format UDZO --volumeName "Arcane" "$STAGE" "$OUT" >/dev/null
else
- hdiutil create -volname "NX Library" -srcfolder "$STAGE" -ov -format UDZO "$OUT" >/dev/null
+ hdiutil create -volname "Arcane" -srcfolder "$STAGE" -ov -format UDZO "$OUT" >/dev/null
fi
echo "Built $OUT ($(du -h "$OUT" | awk '{print $1}'))"
diff --git a/scripts/check_app_profile.swift b/scripts/check_app_profile.swift
new file mode 100644
index 00000000..643ce46e
--- /dev/null
+++ b/scripts/check_app_profile.swift
@@ -0,0 +1,13 @@
+// Run as a headless executable inside a temporary app with the built app's Info.plist.
+// Reading the actual defaults accessor catches startup failures hidden by unmarked unit-test hosts.
+// This probe never runs the importer or writes preferences or launcher data.
+import Foundation
+import NXLibraryCore
+
+try AppData.validateBuildIdentity(Bundle.main.infoDictionary ?? [:])
+let defaults = AppData.preferences
+precondition(defaults === UserDefaults.standard, "The distinct bundle ID must select the app's own preferences")
+precondition(Bundle.main.bundleIdentifier == AppData.profile.preferencesDomain, "Preferences must belong to this profile")
+precondition(AppData.profile.isDevelopment == (AppData.supportRoot.lastPathComponent == "NXLibrary-Development"))
+precondition(AppData.profile.isDevelopment == (AppData.cacheRoot.lastPathComponent == "NXLibrary-Development"))
+print("Packaged profile identity, preferences and roots verified without UI or data writes.")
diff --git a/scripts/check_metadata_text_layout.swift b/scripts/check_metadata_text_layout.swift
new file mode 100644
index 00000000..80710827
--- /dev/null
+++ b/scripts/check_metadata_text_layout.swift
@@ -0,0 +1,133 @@
+import AppKit
+import SwiftUI
+
+// Offscreen geometry regression check (macOS 13+). No UI automation or snapshots.
+// xcrun swiftc Sources/NXLibrary/Views/Components/SeleneExpandableText.swift \
+// scripts/check_metadata_text_layout.swift -o /tmp/nxlibrary-text-layout
+// /tmp/nxlibrary-text-layout
+@main
+struct TextRevealProbe {
+ @MainActor static func main() {
+ _ = NSApplication.shared
+ let paragraph = "A long source description has paragraphs, punctuation, and explicit line breaks. Explore the world, restore what has been lost, and find a path through the mountains.\n\n"
+ let full = String(repeating: paragraph, count: 30)
+ let preview = String(full.prefix(240)) + "…"
+ var checks = 0
+ for width: CGFloat in [300, 720, 1040] {
+ func height(_ expanded: Bool) -> CGFloat {
+ autoreleasepool {
+ let view = SeleneExpandableText(text: full, preview: preview, expanded: expanded)
+ .font(.system(size: 15)).frame(width: width)
+ return NSHostingView(rootView: view).fittingSize.height
+ }
+ }
+ let compact = height(false), expanded = height(true)
+ let expectedCompact = NSHostingView(rootView: Text(preview).font(.system(size: 15)).frame(width: width)).fittingSize.height
+ let expectedFull = NSHostingView(rootView: Text(full).font(.system(size: 15)).frame(width: width)).fittingSize.height
+ precondition(expanded > compact * 5, "Probe must cover a row taller than the viewport")
+ precondition(abs(compact - expectedCompact) < 1, "Collapsed row must fit the preview")
+ precondition(abs(expanded - expectedFull) < 1, "Expanded row must fit all text")
+ checks += 2
+ print("width=\(Int(width)): preview=\(Int(compact))pt; full=\(Int(expanded))pt")
+ }
+ // Reusing a host after changing both width and content must not retain
+ // measurements from the previous source or window size.
+ let host = NSHostingView(rootView: SeleneExpandableText(text: full, preview: preview, expanded: true)
+ .font(.system(size: 15)).frame(width: 300))
+ let longHeight = host.fittingSize.height
+ host.rootView = SeleneExpandableText(text: "Short source", preview: "Short source", expanded: true)
+ .font(.system(size: 15)).frame(width: 720)
+ precondition(host.fittingSize.height < longHeight / 5, "Changed content must invalidate its measurements")
+ for reducedMotion in [false, true] {
+ checkScroll(reducedMotion: reducedMotion)
+ }
+ print("PASS: \(checks) text endpoints, content changes, repeated focus and reduced motion. No windows displayed.")
+ }
+}
+
+private final class ScrollProbeState: ObservableObject {
+ @Published var focus = 0
+ var frames: [Int: CGRect] = [:]
+}
+private struct RowFrames: PreferenceKey {
+ static var defaultValue: [Int: CGRect] = [:]
+ static func reduce(value: inout [Int: CGRect], nextValue: () -> [Int: CGRect]) {
+ value.merge(nextValue(), uniquingKeysWith: { _, new in new })
+ }
+}
+private struct ScrollProbe: View {
+ @ObservedObject var state: ScrollProbeState
+ let reducedMotion: Bool
+ private let full = String(repeating: "A long description about places and quests in the game.\n\n", count: 35)
+ private var motion: Animation? { reducedMotion ? nil : .timingCurve(0.22, 1, 0.36, 1, duration: 0.18) }
+
+ var body: some View {
+ ScrollViewReader { proxy in
+ ScrollView {
+ VStack(spacing: 8) {
+ ForEach(0..<5) { index in
+ VStack(alignment: .leading) {
+ Text("SOURCE \(index)")
+ SeleneExpandableText(text: full, preview: String(full.prefix(240)) + "…", expanded: state.focus == index)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading).padding(18).id(index)
+ .background(GeometryReader { geometry in
+ Color.clear.preference(key: RowFrames.self, value: [index: geometry.frame(in: .named("list"))])
+ })
+ }
+ }
+ .coordinateSpace(name: "list")
+ .onPreferenceChange(RowFrames.self) { state.frames = $0 }
+ .animation(motion, value: state.focus)
+ }
+ .onChange(of: state.focus) { index in
+ withAnimation(motion) { proxy.scrollTo(index, anchor: .top) }
+ }
+ }
+ .font(.system(size: 15)).frame(width: 600, height: 500)
+ }
+}
+
+@MainActor private func checkScroll(reducedMotion: Bool) {
+ let state = ScrollProbeState()
+ let host = NSHostingView(rootView: ScrollProbe(state: state, reducedMotion: reducedMotion))
+ host.frame = CGRect(x: 0, y: 0, width: 600, height: 500)
+ let window = NSWindow(contentRect: host.frame, styleMask: [.borderless], backing: .buffered, defer: false)
+ window.contentView = host
+ window.layoutIfNeeded()
+ precondition(!window.isVisible)
+ func scrollView(_ root: NSView) -> NSScrollView? {
+ if let scroll = root as? NSScrollView { return scroll }
+ return root.subviews.lazy.compactMap(scrollView).first
+ }
+ func settle() {
+ for _ in 0..<25 {
+ RunLoop.main.run(until: Date().addingTimeInterval(0.02))
+ host.layoutSubtreeIfNeeded()
+ }
+ }
+ settle()
+ guard let scroll = scrollView(host), let document = scroll.documentView else {
+ preconditionFailure("Scroll container did not initialise")
+ }
+ precondition(document.frame.height > 500)
+ for focus in [1, 2, 1, 3, 0] {
+ state.focus = focus
+ settle()
+ guard let target = state.frames[focus] else { preconditionFailure("Missing row geometry") }
+ let expected = min(target.minY, max(0, document.frame.height - scroll.contentView.bounds.height))
+ precondition(abs(scroll.contentView.bounds.minY - expected) < 2,
+ "Focus \(focus) must scroll to its final top, not the old expanded row position")
+ }
+ // An interrupted expansion must also settle on the last requested row.
+ for focus in [4, 1, 3, 2] {
+ state.focus = focus
+ RunLoop.main.run(until: Date().addingTimeInterval(0.03))
+ host.layoutSubtreeIfNeeded()
+ }
+ settle()
+ let expected = min(state.frames[2]!.minY, max(0, document.frame.height - scroll.contentView.bounds.height))
+ precondition(abs(scroll.contentView.bounds.minY - expected) < 2, "Rapid focus changes must settle on the last row")
+ print("scroll destinations and interruptions: PASS (reduced motion=\(reducedMotion))")
+ window.contentView = nil
+}
diff --git a/scripts/release.sh b/scripts/release.sh
index 678bb686..c2837b34 100755
--- a/scripts/release.sh
+++ b/scripts/release.sh
@@ -52,6 +52,10 @@ fi
# Every release is tested from its own tree.
DEVELOPER_DIR="${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer}" swift test --package-path "$ROOT" \
|| fail "swift test failed"
+for check in "$ROOT"/Tests/CatalogAppChecks/run_*.py; do
+ DEVELOPER_DIR="${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer}" python3 "$check" \
+ || fail "application regressions failed: ${check##*/}"
+done
(cd "$ROOT" && python3 -m unittest discover -s Tests/PublicationChecks >/dev/null 2>&1) \
|| fail "the publication checks' tests failed (python3 -m unittest discover -s Tests/PublicationChecks)"
[ -d "$ROOT/work/Runtime" ] || fail "no work/Runtime: run scripts/bundle_runtime.sh first (a release carries its Python and tools)"
@@ -73,6 +77,9 @@ mkdir -p "$OUT"
NX_VERSION="$VERSION" NX_RELEASE=1 bash "$ROOT/scripts/build_app.sh" "$APP"
codesign --verify --deep --strict "$APP"
+if /usr/libexec/PlistBuddy -c 'Print :NXLibraryDevelopmentProfile' "$APP/Contents/Info.plist" >/dev/null 2>&1; then
+ fail "a release must not select the development data profile"
+fi
[ "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$APP/Contents/Info.plist")" = "$VERSION" ] \
|| fail "the built app does not carry version $VERSION"
[ "$(/usr/libexec/PlistBuddy -c 'Print :NXLibraryRelease' "$APP/Contents/Info.plist")" = "true" ] \
@@ -98,7 +105,7 @@ if [ "$PUBLISH" = "1" ]; then
git push origin "$TAG"
{ cat "$NOTES"; printf '\n\n%s\n' "$REQUIRES"; } > "$OUT/notes.md"
gh release create "$TAG" "$ZIP" "$DMG" --repo "$REPOSITORY" \
- --title "NX Library $VERSION" --notes-file "$OUT/notes.md"
+ --title "Arcane $VERSION" --notes-file "$OUT/notes.md"
echo "Published $TAG"
else
echo "Not published (add --publish --notes to create the GitHub release)."