Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

45.6 KB
Raw Blame
import Foundation
import Testing
import ShellUI
@testable import ShellControllers
@testable import ShellHost

struct FakePicker: FolderPicker {
    var url: URL?
    func pickFolder() async -> URL? { url }
}

/// Records launches and can fail them.
final class RecordingLauncher: GameLauncher, @unchecked Sendable {
    private(set) var launched: [LaunchableGame] = []
    var error: (any Error)?
    @MainActor func launch(_ game: LaunchableGame) async throws {
        launched.append(game)
        if let error { throw error }
    }
}

struct Failure: Error {}
final class Clock: @unchecked Sendable { var date: Date; init(_ d: Date) { date = d } }

@MainActor @Suite struct ShellHostModelTests {
    private func detail(_ model: ShellHostModel, _ id: String = Fixtures.orbit) throws -> GameDetail {
        try #require(model.details.first { $0.id == id })
    }
    private func value(_ model: ShellHostModel, _ setting: String, game: String = Fixtures.orbit) throws -> String? {
        try detail(model, game).sections.flatMap(\.rows).first { $0.id == setting }?.value
    }

    @Test func theTouchSizeReachesEveryGameAsDMTouchSize() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        let shell = shellSettings()
        let launcher = RecordingLauncher()
        let model = ShellHostModel(config: box.config(), launcher: launcher, shellSettings: shell)
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_TOUCH_SIZE"] == nil, "medium is the engine's own size")
        shell.storeTouchSize("large")
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_TOUCH_SIZE"] == "large")
        #expect(try !detail(model).hasModifiedSettings, "a shell setting is not a change in this game")
        shell.storeTouchSize("medium")
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_TOUCH_SIZE"] == nil)
        shell.storeTouchStick("higher")
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_TOUCH_STICK"] == "higher")
        #expect(launcher.launched.last?.environment["DM_TOUCH_LAYOUT"] == nil, "no arrangement: nothing is passed")
        var layout = TouchLayout()
        layout[.threeD, .face] = TouchLayout.Offset(dx: -2, dy: -1)
        shell.storeTouchLayout(layout)
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_TOUCH_LAYOUT"] == "1;3d/face:-2,-1")
        shell.resetTouchLayout(.threeD)
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_TOUCH_LAYOUT"] == nil, "reset: the engine's built-in layout")
    }

    /// The engine draws the right-stick hint's words as they come (patch 0067), so the shell hands them over in the player's language.
    @Test func everyGameGetsTheRightStickHintInThePlayersLanguage() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        let launcher = RecordingLauncher()
        let model = ShellHostModel(config: box.config(), launcher: launcher, shellSettings: shellSettings())
        await model.playNow(Fixtures.orbit)
        let hint = try #require(launcher.launched.last?.environment["DM_TOUCH_HINT"])
        #expect(hint == ShellHostModel.touchHint && !hint.isEmpty)
    }

    /// The quit prompt's words reach the engine with the game's name in the title, five lines in home_quit.h's order (patch 0068): the
    /// engine draws the prompt when Quit is picked in the in-game menu or Home is held.
    @Test func everyGameGetsTheQuitPromptInThePlayersLanguage() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        let launcher = RecordingLauncher()
        let model = ShellHostModel(config: box.config(), launcher: launcher, shellSettings: shellSettings())
        await model.playNow(Fixtures.orbit)
        let text = try #require(launcher.launched.last?.environment["DM_HOME_QUIT_TEXT"])
        let lines = text.components(separatedBy: "\n")
        let name = try #require(launcher.launched.last?.name)
        #expect(lines.count == 5 && lines.allSatisfy { !$0.isEmpty } && lines[1].contains(name))
    }

    /// #620: Exit Game closes the app and iOS does not let it start itself again, so the prompt's note says the player opens it again to get back.
    @Test func theQuitPromptNoteSaysTheAppClosesAndMustBeOpenedAgain() {
        let note = ShellHostModel.quitPromptText(gameName: "Orbit").components(separatedBy: "\n")[2]
        #expect(note.contains("The app closes.") && note.contains("Open it again"), "\(note)")
    }

    /// The prompt's texts in every language: no semicolon, no line break (one text per line in DM_HOME_QUIT_TEXT), the title keeps the game's name.
    @Test func theQuitPromptTextsFollowTheTextRules() throws {
        let l10n = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
            .deletingLastPathComponent().appendingPathComponent("frontend/l10n")
        let keys = ["ios.host.quitHold", "ios.host.quitTitle", "ios.host.quitNote", "ios.host.quitButton", "ios.host.quitCancel"]
        for file in try FileManager.default.contentsOfDirectory(at: l10n, includingPropertiesForKeys: nil) where file.pathExtension == "json" {
            let strings = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any])
            for key in keys {
                let text = try #require(strings[key] as? String, "\(file.lastPathComponent) lacks \(key)")
                #expect(!text.contains(";") && !text.contains(";") && !text.contains("\n"), "\(file.lastPathComponent) \(key): \(text)")
            }
            #expect((strings["ios.host.quitTitle"] as? String)?.contains("%@") == true, "\(file.lastPathComponent): the title names the game")
        }
    }

    /// Every language's words fit the right third of a small phone (the engine's test gives them about 30 characters) and follow
    /// the text rules: no semicolon, no line break.
    @Test func theRightStickHintIsShortInEveryLanguage() throws {
        let l10n = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
            .deletingLastPathComponent().appendingPathComponent("frontend/l10n")
        for file in try FileManager.default.contentsOfDirectory(at: l10n, includingPropertiesForKeys: nil) where file.pathExtension == "json" {
            let strings = try JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]
            guard let hint = strings?["ios.host.touchHint"] as? String else { continue }
            #expect(hint.count <= 30 && !hint.contains(";") && !hint.contains(";") && !hint.contains("\n"), "\(file.lastPathComponent): \(hint)")
        }
    }

    @Test func padOverridesPersistMergeAndReset() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        let shell = shellSettings()
        let launcher = RecordingLauncher()
        let model = ShellHostModel(config: box.config(), launcher: launcher, shellSettings: shell)
        func row(_ id: String) throws -> SettingRow {
            try #require(detail(model).sections.flatMap(\.rows).first { $0.id == id })
        }
        #expect(try row("pad.A").fromShell && row("pad.swapAB").value == "follow")
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_PAD_MAP"] == nil)
        model.actions.onGlobalPadMapChange("swapAB", "1")
        #expect(model.globalPadMap.swapAB)
        #expect(try !detail(model).hasModifiedSettings)
        // The game's row follows: the card shows what all games send there (B), from the shell's map.
        if case .choice(let options) = try row("pad.A").kind { #expect(options.first?.id == "follow" && options.first?.label == "Same as all games") }
        #expect(try row("pad.A").value == "follow" && model.globalPadMap.output(for: "A") == "B")
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_PAD_MAP"] == "A=B,B=A")
        model.actions.onChange(Fixtures.orbit, "pad.A", "Y")
        let gameStore = GamePadMapStore(defaults: box.defaults(Fixtures.orbit))
        #expect(gameStore.entries == ["A": "Y"] && gameStore.swapValue == "custom")
        #expect(try !row("pad.A").fromShell && row("pad.B").fromShell && detail(model).hasModifiedSettings)
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_PAD_MAP"] == "A=Y,B=A")
        model.actions.onChange(Fixtures.orbit, "pad.swapAB", "off")
        #expect(gameStore.entries == ["A": "A", "B": "B"])
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_PAD_MAP"] == nil)
        let again = ShellHostModel(config: box.config(), shellSettings: shell)
        #expect(try detail(again).hasModifiedSettings)
        model.actions.onChange(Fixtures.orbit, "pad.X", "none")
        model.actions.onChange(Fixtures.orbit, "pad.swapAB", "follow")
        #expect(gameStore.entries == ["X": "none"])
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_PAD_MAP"] == "A=B,B=A,X=none")
        #expect(GamePadMapStore(defaults: box.defaults(Fixtures.chain)).entries.isEmpty)
        model.actions.onResetDefaults(Fixtures.orbit)
        #expect(gameStore.entries.isEmpty)
        #expect(try !detail(model).hasModifiedSettings && row("pad.X").fromShell)
        model.actions.onGlobalPadMapReset()
        #expect(model.globalPadMap.entries.isEmpty)
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_PAD_MAP"] == nil)
    }

    @Test func padRowsFollowGlobalChangesAndRejectInvalidValues() throws {
        let box = try Sandbox()
        let shell = shellSettings()
        let model = ShellHostModel(config: box.config(), shellSettings: shell)
        model.actions.onGlobalPadMapChange("X", "none")
        for detail in model.details where detail.sections.contains(where: { $0.id == "pad" }) {
            let row = try #require(detail.sections.flatMap(\.rows).first { $0.id == "pad.X" })
            #expect(row.fromShell && row.value == "follow")
            if case .choice(let options) = row.kind { #expect(options.map(\.id) == ["follow"] + PadMap.buttons + ["none"]) }
        }
        #expect(model.globalPadMap.output(for: "X") == "none")
        let store = GamePadMapStore(defaults: box.defaults(Fixtures.orbit))
        model.change(Fixtures.orbit, setting: "pad.unknown", value: "A")
        model.change(Fixtures.orbit, setting: "pad.A", value: "bad")
        #expect(store.entries.isEmpty)
        model.change(Fixtures.orbit, setting: "pad.A", value: "A")
        #expect(store.entries == ["A": "A"])
        model.change(Fixtures.orbit, setting: "pad.A", value: "follow")
        #expect(store.entries.isEmpty)
        model.change(Fixtures.orbit, setting: "pad.swapAB", value: "on")
        #expect(store.swapValue == "on")
        // The mapping card's reset forgets the game's mapping only, not its other settings.
        model.change(Fixtures.orbit, setting: PadMappingRows.resetID, value: "")
        #expect(store.entries.isEmpty && store.swapValue == "follow")
    }

    @Test func profilePadMapRowWinsShellMapping() throws {
        let box = try Sandbox()
        let file = box.games.appendingPathComponent(Fixtures.orbit).appendingPathComponent("launcher.json")
        var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any])
        var settings = try #require(json["settings"] as? [[String: Any]])
        settings.append(["env": "DM_PAD_MAP", "kind": "choice", "label": "Buttons", "note": "", "default": "X=Y",
                         "options": [["X=Y", "Custom"], ["", "Default"]]])
        json["settings"] = settings
        try JSONSerialization.data(withJSONObject: json).write(to: file)
        let profile = try LauncherProfile.parse(Data(contentsOf: file))
        let shell = shellSettings()
        shell.setPadSwapAB(true)
        let model = ShellHostModel(config: box.config(), shellSettings: shell)
        #expect(model.launchEnvironment(profile: profile, id: Fixtures.orbit)["DM_PAD_MAP"] == "X=Y")
        #expect(try !detail(model).sections.contains { $0.id == "pad" })
        model.change(Fixtures.orbit, setting: "DM_PAD_MAP", value: "")
        #expect(model.launchEnvironment(profile: profile, id: Fixtures.orbit)["DM_PAD_MAP"] == "")
    }

    @Test func buildsTilesAndDetailsFromTheBundles() throws {
        let box = try Sandbox()
        let model = ShellHostModel(config: box.config())
        #expect(model.details.count == 8)
        let orbit = try detail(model)
        #expect(orbit.game.title == "Orbit Fixture" && orbit.game.subtitle == "Version 1.0.0" && orbit.game.recentlyPlayed == nil)
        #expect(orbit.game.state == .needsGameData)
        #expect(orbit.sections.map(\.title) == ["Game", "Performance", "Controller"])
        #expect(orbit.dataSource == "" && !orbit.dataNote.isEmpty)
        #expect(orbit.cloudSaves == nil && orbit.dlc == "No additional content")
        #expect(try detail(model, Fixtures.chain).game.state == .needsAppUpdate)
        #expect(try detail(model, Fixtures.noFramework).game.state == .broken(reason: "Game code missing", detail: "The game's code is missing from this app. Rebuild and reinstall it.",
                                                                                technical: "DmGame.framework is not in this game's folder. Install the game again."))
        #expect(try detail(model, Fixtures.badManifest).sections.isEmpty)
    }

    @Test func bannerAndIconBecomeArtwork() throws {
        let box = try Sandbox()
        let dir = box.games.appendingPathComponent(Fixtures.orbit)
        try pngData(width: 160, height: 90).write(to: dir.appendingPathComponent("banner.png"))
        try pngData(width: 64, height: 64).write(to: dir.appendingPathComponent("icon.png"))
        try Data("not an image".utf8).write(to: box.games.appendingPathComponent(Fixtures.chain).appendingPathComponent("banner.png"))
        let model = ShellHostModel(config: box.config())
        #expect(try detail(model).game.banner != nil && detail(model).game.icon != nil)
        #expect(try detail(model, Fixtures.chain).game.banner == nil, "an unreadable picture is left out, not an error")
    }

    @Test func appDataMakesTheGamePlayable() throws {
        let box = try Sandbox()
        try box.giveAppData()
        try box.write("", to: box.appData.appendingPathComponent(Fixtures.orbit).appendingPathComponent("aoc/0.img"))
        let model = ShellHostModel(config: box.config())
        let orbit = try detail(model)
        #expect(orbit.game.state == .playable)
        #expect(orbit.dataSource == "This app's folder" && orbit.dataNote == "")
        #expect(orbit.dlc == "1 additional content pack")
    }

    @Test func changesPersistAndResetRestoresDefaults() throws {
        let box = try Sandbox()
        let model = ShellHostModel(config: box.config())
        model.actions.onChange(Fixtures.orbit, "DM_SHOW_FPS", "1")
        #expect(try value(model, "DM_SHOW_FPS") == "1")
        #expect(try detail(model).hasModifiedSettings)
        #expect(box.defaults(Fixtures.orbit).object(forKey: "launcher.DM_SHOW_FPS") as? String == "1")
        // Another model over the same defaults, as after a relaunch.
        #expect(try value(ShellHostModel(config: box.config()), "DM_SHOW_FPS") == "1")
        model.actions.onChange(Fixtures.orbit, "DM_UPSCALER", "fsr")
        #expect(try detail(model).sections[1].rows.map(\.id).contains("DM_UPSCALER_SHARPNESS"))
        model.actions.onResetDefaults(Fixtures.orbit)
        #expect(try value(model, "DM_SHOW_FPS") == "0")
        #expect(try value(model, "DM_UPSCALER") == "off")
        #expect(try !detail(model).hasModifiedSettings)
        #expect(try detail(model).sections[1].rows.map(\.id) == ["DM_UPSCALER", "DM_RENDER_SCALE"])
    }

    @Test func aRefusedValueChangesNothing() throws {
        let box = try Sandbox()
        let model = ShellHostModel(config: box.config())
        model.change(Fixtures.orbit, setting: "DM_OPMODE", value: "7")
        model.change("0100000000999999", setting: "DM_OPMODE", value: "0")
        #expect(try value(model, "DM_OPMODE") == "1")
    }

    @Test func pickingGameDataStoresABookmarkAndMarksTheGameReady() async throws {
        let box = try Sandbox()
        let drive = box.root.appendingPathComponent("Drive/Orbit", isDirectory: true)
        try box.write("", to: drive.appendingPathComponent("fixture.marker"))
        let model = ShellHostModel(config: box.config(), picker: FakePicker(url: drive))
        #expect(try detail(model).game.state == .needsGameData)
        await model.pickGameDataNow(Fixtures.orbit)
        let orbit = try detail(model)
        #expect(orbit.game.state == .playable)
        #expect(orbit.dataSource == "Orbit")
        #expect(box.defaults(Fixtures.orbit).data(forKey: "pickedDataBookmark") != nil)
        // It survives a relaunch.
        #expect(try detail(ShellHostModel(config: box.config())).game.state == .playable)
        // Back to the app's own folder, which has nothing yet.
        model.actions.onUseAppData(Fixtures.orbit)
        #expect(try detail(model).game.state == .needsGameData)
        #expect(model.notice?.contains("games/\(Fixtures.orbit)") == true)
        #expect(box.defaults(Fixtures.orbit).data(forKey: "pickedDataBookmark") == nil)
    }

    @Test func aPickedFolderWithoutTheGameIsSaidSo() async throws {
        let box = try Sandbox()
        let empty = box.root.appendingPathComponent("Empty", isDirectory: true)
        try FileManager.default.createDirectory(at: empty, withIntermediateDirectories: true)
        let model = ShellHostModel(config: box.config(), picker: FakePicker(url: empty))
        await model.pickGameDataNow(Fixtures.orbit)
        #expect(try detail(model).game.state == .needsGameData)
        #expect(model.notice?.contains("No game data for Orbit Fixture") == true)
    }

    @Test func aCancelledPickChangesNothing() async throws {
        let box = try Sandbox()
        let model = ShellHostModel(config: box.config(), picker: FakePicker(url: nil))
        await model.pickGameDataNow(Fixtures.orbit)
        await model.pickCloudSavesNow(Fixtures.orbit)
        #expect(model.notice == nil)
        #expect(try detail(model).cloudSaves == nil)
    }

    @Test func useAppDataWithDataPresentIsPlayable() throws {
        let box = try Sandbox()
        try box.giveAppData()
        let model = ShellHostModel(config: box.config())
        model.useAppData(Fixtures.orbit)
        #expect(try detail(model).game.state == .playable)
        #expect(model.notice == nil)
    }

    @Test func cloudSavesAreChosenPerGameAndTurnedOff() async throws {
        let box = try Sandbox()
        let folder = box.root.appendingPathComponent("iCloud/Game Saves", isDirectory: true)
        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
        let model = ShellHostModel(config: box.config(), picker: FakePicker(url: folder))
        await model.pickCloudSavesNow(Fixtures.orbit)
        #expect(try detail(model).cloudSaves == "Game Saves")
        #expect(try detail(model, Fixtures.chain).cloudSaves == nil)
        #expect(box.defaults(Fixtures.orbit).data(forKey: "cloudSavesBookmark") != nil)
        #expect(try detail(ShellHostModel(config: box.config())).cloudSaves == "Game Saves")
        model.actions.onDisableCloudSaves(Fixtures.orbit)
        #expect(try detail(model).cloudSaves == nil)
        #expect(box.defaults(Fixtures.orbit).data(forKey: "cloudSavesBookmark") == nil)
    }

    @Test func aStaleCloudFolderAsksForANewChoice() throws {
        let box = try Sandbox()
        box.defaults(Fixtures.orbit).set(Data("junk".utf8), forKey: "cloudSavesBookmark")
        box.defaults(Fixtures.orbit).set(Data("junk".utf8), forKey: "pickedDataBookmark")
        let orbit = try detail(ShellHostModel(config: box.config()))
        #expect(orbit.cloudSaves == nil && orbit.cloudNote.contains("choose it again"))
        #expect(orbit.dataNote.contains("no longer readable"))
    }

    private func shellSettings() -> ShellSettingsStore { ShellSettingsStore(defaults: UserDefaults(suiteName: "t-shell-\(UUID().uuidString)")!) }

    /// The orbit fixture with a performance overlay row of its own, like a game whose list has `DM_METAL_HUD`.
    private func giveOrbitAnOverlayRow(_ box: Sandbox) throws {
        let url = box.games.appendingPathComponent(Fixtures.orbit).appendingPathComponent("launcher.json")
        var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])
        var settings = try #require(json["settings"] as? [[String: Any]])
        settings.append(["env": "DM_METAL_HUD", "kind": "toggle", "section": "Performance", "label": "Overlay", "note": "", "default": "0", "on": "1", "off": "0"])
        json["settings"] = settings
        try JSONSerialization.data(withJSONObject: json).write(to: url)
    }

    @Test func theShellOverlayChoiceReachesTheEngineUnlessTheGameChoseItself() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        try giveOrbitAnOverlayRow(box)
        let shell = shellSettings()
        shell.storePerformanceHUD(true)
        let launcher = RecordingLauncher()
        let model = ShellHostModel(config: box.config(), launcher: launcher, shellSettings: shell)
        #expect(try value(model, "DM_METAL_HUD") == "1", "the page shows what the engine will get")
        await model.playNow(Fixtures.orbit)
        let first = try #require(launcher.launched.last)
        #expect(first.environment["DM_METAL_HUD"] == "1")
        let plan = EngineLaunchPlan.make(game: first, appResources: box.root, documents: box.root, envFileText: "DM_METAL_HUD=0\n")
        #expect(plan.environment["DM_METAL_HUD"] == "1")
        model.actions.onChange(Fixtures.orbit, "DM_METAL_HUD", "0")
        #expect(try value(model, "DM_METAL_HUD") == "0")
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_METAL_HUD"] == "0", "the game's choice wins over the shell's")
    }

    @Test func aGameWithoutAnOverlayRowStillGetsTheShellChoice() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        let shell = shellSettings()
        let launcher = RecordingLauncher()
        let model = ShellHostModel(config: box.config(), launcher: launcher, shellSettings: shell)
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_METAL_HUD"] == nil, "no shell choice, nothing is set")
        shell.storePerformanceHUD(false)
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.environment["DM_METAL_HUD"] == "0")
    }

    @Test func aChangedShellOverlayChoiceUpdatesTheDetails() throws {
        let box = try Sandbox()
        try giveOrbitAnOverlayRow(box)
        let shell = shellSettings()
        let model = ShellHostModel(config: box.config(), shellSettings: shell)
        #expect(try value(model, "DM_METAL_HUD") == "0")
        shell.storePerformanceHUD(true)
        NotificationCenter.default.post(name: UserDefaults.didChangeNotification, object: nil)
        #expect(try value(model, "DM_METAL_HUD") == "1")
    }

    @Test func theShellCloudFolderBacksAGameWithoutOne() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        let shared = box.root.appendingPathComponent("iCloud/Shared Saves", isDirectory: true)
        let own = box.root.appendingPathComponent("iCloud/Own Saves", isDirectory: true)
        for folder in [shared, own] { try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) }
        let shell = shellSettings()
        let launcher = RecordingLauncher()
        let model = ShellHostModel(config: box.config(), launcher: launcher, picker: FakePicker(url: shared), shellSettings: shell)
        #expect(try detail(model).cloudSaves == nil)
        await model.pickShellCloudNow()
        #expect(shell.cloudSavesFolderName == "Shared Saves" && shell.cloudSavesBookmark != nil)
        var orbit = try detail(model)
        #expect(orbit.cloudSaves == "Shared Saves (from Settings)" && orbit.cloudFromShell)
        #expect(try detail(model, Fixtures.chain).cloudSaves == "Shared Saves (from Settings)")
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.cloudSavesURL?.lastPathComponent == "Shared Saves")
        // The game's own folder wins
        let own2 = ShellHostModel(config: box.config(), launcher: launcher, picker: FakePicker(url: own), shellSettings: shell)
        await own2.pickCloudSavesNow(Fixtures.orbit)
        orbit = try detail(own2)
        #expect(orbit.cloudSaves == "Own Saves" && !orbit.cloudFromShell)
        await own2.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.cloudSavesURL?.lastPathComponent == "Own Saves")
        // Turning the game's folder off means off, though the shell has a folder
        own2.actions.onDisableCloudSaves(Fixtures.orbit)
        #expect(try detail(own2).cloudSaves == nil)
    }

    @Test func aGameCanTurnCloudSavesOffAndFollowTheShellFolderAgain() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        let shared = box.root.appendingPathComponent("iCloud/Shared Saves", isDirectory: true)
        let own = box.root.appendingPathComponent("iCloud/Own Saves", isDirectory: true)
        for folder in [shared, own] { try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) }
        let launcher = RecordingLauncher()
        let shell = shellSettings()
        let model = ShellHostModel(config: box.config(), launcher: launcher, picker: FakePicker(url: shared), shellSettings: shell)
        #expect(try !detail(model).cloudCanUseShell, "no shell folder to follow")
        await model.pickShellCloudNow()
        model.actions.onDisableCloudSaves(Fixtures.orbit)
        var orbit = try detail(model)
        #expect(orbit.cloudSaves == nil && !orbit.cloudFromShell && orbit.cloudCanUseShell)
        #expect(try detail(model, Fixtures.chain).cloudSaves == "Shared Saves (from Settings)", "another game is not affected")
        await model.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.cloudSavesURL == nil)
        // The off choice survives a new session
        let again = ShellHostModel(config: box.config(), launcher: launcher, shellSettings: shell)
        #expect(try detail(again).cloudSaves == nil)
        // Choosing a folder for the game clears it
        let picking = ShellHostModel(config: box.config(), launcher: launcher, picker: FakePicker(url: own), shellSettings: shell)
        await picking.pickCloudSavesNow(Fixtures.orbit)
        orbit = try detail(picking)
        #expect(orbit.cloudSaves == "Own Saves" && orbit.cloudCanUseShell)
        await picking.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.cloudSavesURL?.lastPathComponent == "Own Saves")
        // Following the shell again
        picking.actions.onUseShellCloud(Fixtures.orbit)
        orbit = try detail(picking)
        #expect(orbit.cloudSaves == "Shared Saves (from Settings)" && orbit.cloudFromShell && !orbit.cloudCanUseShell)
        await picking.playNow(Fixtures.orbit)
        #expect(launcher.launched.last?.cloudSavesURL?.lastPathComponent == "Shared Saves")
        // Off with a game folder that the player picks later, and off again from the shell folder
        picking.actions.onDisableCloudSaves(Fixtures.orbit)
        picking.actions.onUseShellCloud(Fixtures.orbit)
        #expect(try detail(picking).cloudFromShell)
    }

    @Test func theShellFoldersCanBeRemoved() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        let drive = box.root.appendingPathComponent("Drive/Switch", isDirectory: true)
        try box.write("", to: drive.appendingPathComponent("fixture.marker"))
        let shared = box.root.appendingPathComponent("iCloud/Shared Saves", isDirectory: true)
        try FileManager.default.createDirectory(at: shared, withIntermediateDirectories: true)
        let shell = shellSettings()
        let model = ShellHostModel(config: box.config(), picker: FakePicker(url: shared), shellSettings: shell)
        await model.pickShellCloudNow()
        let data = ShellHostModel(config: box.config(), picker: FakePicker(url: drive), shellSettings: shell)
        await data.pickShellDataNow()
        #expect(shell.cloudSavesFolderName != nil && shell.cloudSavesBookmark != nil && shell.dataFolderName != nil && shell.dataBookmark != nil)
        model.actions.onClearShellCloud()
        #expect(shell.cloudSavesFolderName == nil && shell.cloudSavesBookmark == nil)
        #expect(try detail(model).cloudSaves == nil && !detail(model).cloudCanUseShell)
        #expect(shell.dataFolderName != nil, "the other folder stays")
        model.actions.onClearShellData()
        #expect(shell.dataFolderName == nil && shell.dataBookmark == nil)
        #expect(try detail(model).game.state == .playable, "the app folder has the data")
        #expect(try !detail(model).dataFromShell)
    }

    @Test func aRowShowsThatItsValueComesFromTheShellUntilTheGameChoosesItself() throws {
        let box = try Sandbox()
        try box.giveAppData()
        try giveOrbitAnOverlayRow(box)
        let shell = shellSettings()
        let model = ShellHostModel(config: box.config(), shellSettings: shell)
        func row() throws -> SettingRow { try #require(detail(model).sections.flatMap(\.rows).first { $0.id == "DM_METAL_HUD" }) }
        #expect(try !row().fromShell, "the shell has no choice")
        shell.storePerformanceHUD(true)
        model.refreshAll()
        #expect(try row().fromShell && row().value == "1")
        #expect(try !detail(model).hasModifiedSettings)
        model.actions.onChange(Fixtures.orbit, "DM_METAL_HUD", "0")
        #expect(try !row().fromShell && row().value == "0", "the game's own choice")
        #expect(try detail(model).hasModifiedSettings, "the explicit off can be reset")
        model.actions.onResetDefaults(Fixtures.orbit)
        #expect(try row().fromShell && row().value == "1" && !detail(model).hasModifiedSettings)
    }

    @Test func theShellDataFolderIsNotPresentedAsThePlayersPickForTheGame() async throws {
        let box = try Sandbox()
        let drive = box.root.appendingPathComponent("Drive/Switch", isDirectory: true)
        try box.write("", to: drive.appendingPathComponent("fixture.marker"))
        let shell = shellSettings()
        let model = ShellHostModel(config: box.config(), picker: FakePicker(url: drive), shellSettings: shell)
        #expect(try detail(model).game.state == .needsGameData)
        await model.pickShellDataNow()
        #expect(shell.dataFolderName == "Switch")
        let orbit = try detail(model)
        #expect(orbit.game.state == .playable && orbit.dataFromShell)
        #expect(orbit.dataSource == "Switch (from Settings)")
        #expect(box.defaults(Fixtures.orbit).data(forKey: "pickedDataBookmark") == nil, "nothing is stored for the game")
        // A folder the player picks for the game takes over
        let own = box.root.appendingPathComponent("Own/Orbit", isDirectory: true)
        try box.write("", to: own.appendingPathComponent("fixture.marker"))
        await ShellHostModel(config: box.config(), picker: FakePicker(url: own), shellSettings: shell).pickGameDataNow(Fixtures.orbit)
        let again = try detail(ShellHostModel(config: box.config(), shellSettings: shell))
        #expect(again.dataSource == "Orbit" && !again.dataFromShell)
    }

    @Test func theShellFolderPickersReportAFailureAndKeepTheOldChoice() async throws {
        let box = try Sandbox()
        let missing = box.root.appendingPathComponent("not-there", isDirectory: true)
        let shell = shellSettings()
        let model = ShellHostModel(config: box.config(), picker: FakePicker(url: missing), shellSettings: shell)
        await model.pickShellDataNow()
        #expect(model.notice != nil && shell.dataFolderName == nil && shell.dataBookmark == nil)
        await ShellHostModel(config: box.config(), picker: FakePicker(url: nil), shellSettings: shell).pickShellCloudNow()
        #expect(shell.cloudSavesFolderName == nil)
    }

    @Test func showLogReadsTheGamesLogOrSaysThereIsNone() throws {
        let box = try Sandbox()
        let model = ShellHostModel(config: box.config())
        model.actions.onShowLog(Fixtures.orbit)
        #expect(model.log?.title == "Orbit Fixture" && model.log?.text == nil)
        try box.write("boot ok\nframe 1\n", to: box.appData.appendingPathComponent(Fixtures.orbit).appendingPathComponent("log.txt"))
        model.actions.onShowLog(Fixtures.orbit)
        #expect(model.log?.text == "boot ok\nframe 1\n" && model.log?.truncated == false)
    }

    @Test func showLogReadsTheEngineLogOnlyForTheGameThatRanLast() throws {
        let box = try Sandbox()
        let model = ShellHostModel(config: box.config())
        let engine = box.root.appendingPathComponent("Documents/log.txt")
        try box.write("shell: starting /app/Frameworks/DmGame\(Fixtures.orbit).framework/dm\nboot ok\n", to: engine)
        model.actions.onShowLog(Fixtures.orbit)
        #expect(model.log?.text?.hasSuffix("boot ok\n") == true)
        try box.write("shell: starting /app/Frameworks/DmGame0100000000020000.framework/dm\nboot ok\n", to: engine)
        model.actions.onShowLog(Fixtures.orbit)
        #expect(model.log?.text == nil)
    }

    @Test func aLongLogShowsItsEnd() throws {
        let box = try Sandbox()
        let url = box.appData.appendingPathComponent("log.txt")
        try box.write(String(repeating: "a", count: 100) + "END", to: url)
        let read = try #require(LogReader.read(url, maxBytes: 10))
        #expect(read.text == "aaaaaaaEND" && read.truncated)
        #expect(LogReader.read(box.root.appendingPathComponent("nope.txt")) == nil)
    }

    @Test func appUpdateOpensTheConfiguredURL() throws {
        let box = try Sandbox()
        let opened = LogBox()
        let url = URL(string: "https://example.invalid/update")!
        let model = ShellHostModel(config: box.config(updateURL: url, open: { opened.add($0.absoluteString) }))
        model.actions.onAppUpdate()
        #expect(opened.all == ["https://example.invalid/update"])
        let none = ShellHostModel(config: box.config())
        none.actions.onAppUpdate()
        #expect(none.notice != nil)
    }

    @Test func playHandsAPlayableGameToTheLauncher() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        box.defaults(Fixtures.orbit).set("0", forKey: "launcher.DM_OPMODE")
        let launcher = RecordingLauncher()
        let model = ShellHostModel(config: box.config(), launcher: launcher)
        await model.playNow(Fixtures.orbit)
        let game = try #require(launcher.launched.first)
        #expect(game.titleID == Fixtures.orbit && game.environment["DM_OPMODE"] == "0" && game.environment["DM_SHOW_FPS"] == "0")
        #expect(game.dataURL.lastPathComponent == Fixtures.orbit && game.frameworkURL.lastPathComponent == "DmGame.framework")
        #expect(game.cloudSavesURL == nil && model.notice == nil)
    }

    /// What the player changes in the settings (the views' onChange) is what the engine gets: the launcher's environment, and the
    /// engine launch plan built from it, which the shell sets before the engine reads anything (front_hud_env, dm_profile, hle_oe).
    @Test func aChangedSettingReachesTheEngineEnvironment() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        let launcher = RecordingLauncher()
        let model = ShellHostModel(config: box.config(), launcher: launcher)
        model.actions.onChange(Fixtures.orbit, "DM_SHOW_FPS", "1")
        model.actions.onChange(Fixtures.orbit, "DM_OPMODE", "0")
        await model.playNow(Fixtures.orbit)
        let game = try #require(launcher.launched.first)
        #expect(game.environment["DM_SHOW_FPS"] == "1" && game.environment["DM_OPMODE"] == "0")
        let plan = EngineLaunchPlan.make(game: game, appResources: box.root.appendingPathComponent("App"), documents: box.root.appendingPathComponent("Documents"),
                                         envFileText: "DM_SHOW_FPS=0\nDM_OTHER=7\n")
        #expect(plan.environment["DM_SHOW_FPS"] == "1", "the player's choice wins over an env file")
        #expect(plan.environment["DM_OPMODE"] == "0" && plan.environment["DM_OTHER"] == "7")
        // A second model (the next start of the app) reads the same suite
        let again = RecordingLauncher()
        await ShellHostModel(config: box.config(), launcher: again).playNow(Fixtures.orbit)
        #expect(again.launched.first?.environment["DM_SHOW_FPS"] == "1")
    }

    @Test func theStubShowsThatLaunchingIsNotAvailable() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        let model = ShellHostModel(config: box.config(), launcher: StubGameLauncher(log: { _ in }))
        await model.playNow(Fixtures.orbit)
        #expect(model.notice == "Launching is not available yet.")
    }

    @Test func playIgnoresGamesThatCannotStart() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        let launcher = RecordingLauncher()
        let model = ShellHostModel(config: box.config(), launcher: launcher)
        for id in [Fixtures.chain, Fixtures.noFramework, Fixtures.badManifest, "0100000000999999"] { await model.playNow(id) }
        let needsData = ShellHostModel(config: try Sandbox().config(), launcher: launcher)
        await needsData.playNow(Fixtures.orbit)
        #expect(launcher.launched.isEmpty)
    }

    @Test func aFailingLauncherShowsItsError() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        let launcher = RecordingLauncher()
        launcher.error = GameProblem(reason: "Out of memory")
        let model = ShellHostModel(config: box.config(), launcher: launcher)
        await model.playNow(Fixtures.orbit)
        #expect(model.notice == "Out of memory")
    }

    @Test func connectedControllersBecomeControllerInfo() {
        let c = ConnectedController(id: "a", name: "Pro Controller", player: 2, family: .nintendo, batteryPercent: 40, charging: true)
        #expect(ShellHostModel.info(for: c) == ControllerInfo(id: "a", name: "Pro Controller", player: "Player 2", batteryPercent: 40, charging: true))
    }

    // MARK: Messages, order, last played

    @Test func brokenGamesShowPlayerSentencesAndKeepTheTechnicalMessage() throws {
        let box = try Sandbox()
        let model = ShellHostModel(config: box.config())
        func broken(_ id: String) throws -> (reason: String, detail: String, technical: String) {
            guard case .broken(let r, let d, let t) = try detail(model, id).game.state else { throw Failure() }
            return (r, d, t)
        }
        let settings = try broken(Fixtures.badSettings)
        #expect(settings.detail == "This game's settings list is damaged. Rebuild the game in the launcher on your Mac.")
        #expect(settings.technical == "DM_X is a choice without [value, label] options.")
        let code = try broken(Fixtures.noFramework)
        #expect(code.detail == "The game's code is missing from this app. Rebuild and reinstall it.")
        #expect(code.technical.contains("DmGame.framework"))
        #expect(try broken(Fixtures.badManifest).detail == "This game's manifest is damaged. Rebuild the game in the launcher on your Mac.")
        #expect(try broken(Fixtures.missingKey).detail == "This game's manifest is damaged. Rebuild the game in the launcher on your Mac.")
        #expect(try broken(Fixtures.badManifest).technical.contains("not valid JSON"))
        for id in [Fixtures.badSettings, Fixtures.noFramework, Fixtures.badManifest, Fixtures.missingKey] {
            let b = try broken(id)
            #expect(!b.detail.contains("DM_") && !b.detail.contains("json") && !b.detail.contains(";") && !b.detail.contains(";"))
        }
    }

    @Test func everyCauseHasItsOwnSentence() {
        let causes: [ProblemCause] = [.manifestMissing, .manifestDamaged, .manifestUnsupported, .settingsMissing, .settingsDamaged,
                                      .settingsUnsupported, .codeMissing, .filesDamaged]
        #expect(ProblemCause.manifestMissing.message == "This game's manifest is missing. Rebuild the game in the launcher on your Mac.")
        #expect(ProblemCause.settingsMissing.message == "This game's settings list is missing. Rebuild the game in the launcher on your Mac.")
        #expect(ProblemCause.manifestUnsupported.message == "This game was built for a different version of this app. Update the app or rebuild the game in the launcher on your Mac.")
        #expect(ProblemCause.settingsUnsupported.message == ProblemCause.manifestUnsupported.message)
        #expect(ProblemCause.filesDamaged.message == "This game's files are damaged. Rebuild the game in the launcher on your Mac.")
        #expect(causes.allSatisfy { !$0.message.isEmpty && !$0.message.contains(";") })
        let problem = GameProblem(cause: .settingsDamaged, reason: "Settings list damaged", detail: "raw")
        #expect(problem.state == .broken(reason: "Settings list damaged", detail: ProblemCause.settingsDamaged.message, technical: "raw"))
    }

    @Test func libraryStartsWithPlayableThenDataThenUpdateThenBroken() throws {
        let box = try Sandbox()
        try box.giveAppData()
        let model = ShellHostModel(config: box.config())
        // Orbit playable, Quiet and the missing-framework game and others by state, alphabetical within a group.
        let ids = model.details.map(\.id)
        #expect(ids.first == Fixtures.orbit)
        let rank = model.details.map { d -> Int in
            switch d.game.state { case .playable: 1; case .needsGameData: 2; case .needsAppUpdate: 3; case .broken: 4 }
        }
        #expect(rank == rank.sorted())
        let broken = model.details.filter { if case .broken = $0.game.state { true } else { false } }.map(\.game.title)
        #expect(broken == broken.sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending })
        #expect(model.details.map(\.id) == model.entries.map(\.id))
        #expect(model.details.first?.game.title != "Bad Settings Fixture")
    }

    @Test func recentlyPlayedComesFirstAndPlayRecordsTheDate() async throws {
        let box = try Sandbox()
        try box.giveAppData()
        let clock = Clock(Date(timeIntervalSince1970: 1_000_000))
        let config = box.config(now: { clock.date })
        let model = ShellHostModel(config: config)
        await model.playNow(Fixtures.orbit)   // the stub launcher fails, the date is stored anyway
        #expect(LastPlayedStore(defaults: box.defaults(Fixtures.orbit)).date == clock.date)
        #expect(try detail(model).game.recentlyPlayed == "Played today")
        #expect(model.details.first?.id == Fixtures.orbit, "no reorder under the player's finger")
        // A second playable game, played later, goes first after the next reload.
        try box.giveAppData(Fixtures.chain)
        let quiet = "0100000000080000"
        try box.giveAppData(quiet)
        clock.date = clock.date.addingTimeInterval(3600)
        let other = ShellHostModel(config: config)
        await other.playNow(quiet)
        #expect(other.details.first?.id == Fixtures.orbit || other.details.first?.id == quiet)
        other.reload()
        #expect(other.details.prefix(2).map(\.id) == [quiet, Fixtures.orbit])
        // A broken game is last even after its neighbours were played.
        #expect(other.details.last.map { if case .broken = $0.game.state { true } else { false } } == true)
    }

    @Test func selectionOrderStaysWhenOneGameChangesState() throws {
        let box = try Sandbox()
        let model = ShellHostModel(config: box.config())
        let before = model.details.map(\.id)
        try box.giveAppData()
        model.useAppData(Fixtures.orbit)   // refresh: orbit becomes playable without a re-sort
        #expect(model.details.map(\.id) == before)
        model.reload()
        #expect(model.details.first?.id == Fixtures.orbit)
    }

    @Test func anUnreadableManifestNeverShowsTheBareTitleID() throws {
        let box = try Sandbox()
        let model = ShellHostModel(config: box.config())
        // Truncated JSON: no name anywhere, so "Unknown game" and no subtitle.
        let unknown = try detail(model, Fixtures.badManifest).game
        #expect(unknown.title == "Unknown game" && unknown.subtitle.isEmpty)
        #expect(unknown.state == .broken(reason: "Can't read this game", detail: ProblemCause.manifestDamaged.message,
                                         technical: try #require({ () -> String? in if case .broken(_, _, let t) = unknown.state { t } else { nil } }())))
        // Valid JSON that fails validation keeps its own name.
        let partial = try detail(model, Fixtures.missingKey).game
        #expect(partial.title == "Missing Key Fixture" && partial.subtitle.isEmpty)
        // Nothing the player reads as a title is a 16 digit ID.
        for d in model.details { #expect(d.game.title.count != 16 || !d.game.title.allSatisfy(\.isNumber)) }
    }

    @Test func theStateLabelMatchesTheCause() throws {
        let box = try Sandbox()
        let model = ShellHostModel(config: box.config())
        func reason(_ id: String) throws -> String {
            guard case .broken(let r, _, _) = try detail(model, id).game.state else { throw Failure() }
            return r
        }
        #expect(try reason(Fixtures.badManifest) == "Can't read this game")
        #expect(try reason(Fixtures.missingKey) == "Can't read this game")
        #expect(try reason(Fixtures.badSettings) == "Settings list damaged")
        #expect(try reason(Fixtures.noFramework) == "Game code missing")
        for cause in [ProblemCause.manifestMissing, .manifestDamaged, .manifestUnsupported, .settingsMissing, .settingsDamaged,
                      .settingsUnsupported, .codeMissing, .filesDamaged] {
            #expect(!cause.label.isEmpty && !cause.label.contains(";"))
        }
    }
}