Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Move the build into a BuildStore and remove BuildModel (#387)
v0lumehi7dbe759c6079
diff --git a/AGENTS.md b/AGENTS.mdindex 0a57d0c5..a30d9cdf 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -11,7 +11,7 @@ This is the fork's guide. The engine has its own, upstream's: [engine/AGENTS.md]- **Never add engine files to this repository.** Files under `dm/`, `scripts/`, `docs/` and `ref/` at the root are ignored by `.gitignore`, and the `pr-scope` check fails a PR that adds them. A direct edit of engine files is lost on the next sync.- **Issues and pull requests.** Follow [CONTRIBUTING.md](CONTRIBUTING.md), section "For AI agents and other tools", and the forms and the PR template in `.github/`. Fix or feature: every fix goes through a PR and merges when CI is green, unless a maintainer's "changes requested" review is unanswered (a plain review comment does not block, and @LNPANDY decides only when the maintainers disagree), a maintainer's own feature after 48 hours (a feature from outside never merges by waiting, a maintainer has to agree, try the app and review the code), a patch is renumbered by whoever merges it, releases and version bumps are the owner's ([RELEASING.md](RELEASING.md): a release candidate tag first, the final tag on its commit). `tools/try-pr <PR number|main|tag>` opens the app CI built. `tools/try-local` builds the app from your checkout without CI and opens it (engine tree, launcher, bundled tools, ad-hoc signed, version `<appVersion>-local`). The first run builds the bundled tools, which it caches (minutes), a later one takes about the time of `swift build`. It is not a release and cannot sign: an rc tag still needs CI and the owner's key. Never attach or commit keys, game files or data extracted from a game.- **Merging with admin rights.** An admin merge never goes over a red check. That holds even when @LNPANDY overrides an objection. If a re-review is slow, the other maintainer pings the reviewer and does not merge with admin rights.-- **Mac launcher layers.** `frontend/` is four SwiftPM targets (`NXCore`, `NXModel`, `NXLauncher`, `NX2Apple`) and the compiler enforces which may import which. Read [frontend/ARCHITECTURE.md](frontend/ARCHITECTURE.md) before you add a file to `frontend/Sources`. It says where a new feature goes. Do not add to `BuildModel`. No Swift file there is above 800 lines (`SourceSizeTests`), and the larger ones may only shrink.+- **Mac launcher layers.** `frontend/` is four SwiftPM targets (`NXCore`, `NXModel`, `NXLauncher`, `NX2Apple`) and the compiler enforces which may import which. Read [frontend/ARCHITECTURE.md](frontend/ARCHITECTURE.md) before you add a file to `frontend/Sources`. It says where a new feature goes. `BuildModel` is gone: the stores are in `NXModel` and `LauncherStores` only wires them. No Swift file there is above 800 lines (`SourceSizeTests`), and the larger ones may only shrink.- **Checks.** `cd frontend && swift build && swift test` for the Mac launcher (its tests read `engine/`, so sync first), `python3 -m unittest discover -s frontend-qt/tests` for the Qt front end (and `python3 frontend-qt/gen_localization.py` leaves `frontend-qt/nspb_qt/localization.py` unchanged), `python3 -m unittest discover tools/tests` for the tools. The engine's own tests run in `engine/` as `tests.yml` does. The pre-commit hook runs `python3 tools/engine.py check` when `patches/` or `.upstream-ref` is staged. The pre-push hook runs the checks above for the files the push changes, `tools/githooks.py` has the list. Fix the failure, do not bypass the hook.- **Language and text.** Everything is in English except the Chinese pages (`*.zh-CN.md`) and the launcher's strings. No semicolons in UI strings, READMEs and docs.- **Release notes.** They follow `.github/release_notes_template.md`, English first, then Chinese, no emojis.diff --git a/frontend-qt/tests/test_build_failure_hints.py b/frontend-qt/tests/test_build_failure_hints.pyindex 72ec2807..2f3f02d6 100644--- a/frontend-qt/tests/test_build_failure_hints.py+++ b/frontend-qt/tests/test_build_failure_hints.py@@ -28,7 +28,7 @@ from nspb_qt.localization import TABLE # noqa: E402FIXTURES = json.loads((ROOT / 'frontend/Tests/Fixtures/build_failures.json').read_text(encoding='utf-8'))# the table is the classifier's (the app target), the kinds and their override flags are NXCore'sSWIFT = ''.join((ROOT / 'frontend/Sources' / f).read_text(encoding='utf-8')- for f in ('NX2Apple/BuildFailure.swift', 'NXCore/BuildFailureKind.swift'))+ for f in ('NXCore/BuildFailureClassifier.swift', 'NXCore/BuildFailureKind.swift'))def fixture(pattern_id: str) -> dict:diff --git a/frontend/ARCHITECTURE.md b/frontend/ARCHITECTURE.mdindex 31331ddf..ca55963a 100644--- a/frontend/ARCHITECTURE.md+++ b/frontend/ARCHITECTURE.md@@ -13,24 +13,22 @@ The plan and the steps are in [LNPANDY/NX2Apple#387](https://github.com/LNPANDY/## Where it stands-Step 1 of #387 made the targets and moved the files that already fit. Step 2 moved the language out of `BuildModel` into the `Localizer` store. Step 3 moved the build log into the `BuildLog` store. Step 4 moved the pure logic into `NXCore`. Step 5 added the first services. Step 6 added the first store, `AppUpdateStore`, the reference for the others. Step 7 moves the rest one store per PR: the repository, the engine sync, the dependencies, then the devices. The rest still lives in the app target and moves with the later steps.+Step 1 of #387 made the targets and moved the files that already fit. Step 2 moved the language out of `BuildModel` into the `Localizer` store. Step 3 moved the build log into the `BuildLog` store. Step 4 moved the pure logic into `NXCore`. Step 5 added the first services. Step 6 added the first store, `AppUpdateStore`, the reference for the others. Step 7 moved the rest one store per PR: the repository, the engine sync, the dependencies, the devices, then the build. `BuildModel` is gone. The views still live in the app target and move with step 8.-- `BuildModel` is the model of the whole launcher and reaches into every layer, so the files that use it cannot leave the app target yet. It no longer owns the language: it holds the `Localizer` it was given and forwards `lang` and `t()` to it, for the text it writes itself (alerts, status, failures).-- `NXCore` holds the value types and static functions that need only Foundation: app and engine update parsing, `Localization.swift`, the release notes, the device and signing tools, the cloud folder and saves migration, the bundled tools, input staging, the build target and the pipe reader. Step 4 added four types: `TitleID` (parse a title ID from a file name, its owner, the update version, the build key), `GameInputs` (classify files into the four rows, row mismatch, allowed file types), `BuildProgress` (stage lines, progress details, durations, the steps of Xcode and the install, failure info) and `Toolchain` (probing Python, the venv, dotnet and Xcode, and the dependency rows `Dep`). `Stage` and `StepState` moved with `BuildProgress`. Step 5 added the first services (step 6 added `ReleaseSource`, see below): `ProcessRunner` (a protocol, with `SystemProcessRunner` as the real one), `ProcessGroups` (the process groups that Stop and quitting end) and `GitCheckout` (a protocol, with `SystemGitCheckout`, plus `GitRules` for the decisions that need no git). `ProcessRunner` is where a build process starts: `capture` runs to the end and keeps the output, `stream` hands out lines, `start` returns at once and can lead a process group. `BuildModel` holds a runner and a checkout, takes them in `init`, and uses them for the clone, fetch, pull, adoption of a ZIP copy, the build run, the tools of a stage, the archive step and `openOnDevice`. `Toolchain`, `Diagnostics`, `OlderTools`, `Uninstall`, `EngineLayout.runSync` and the update staging take a runner or a checkout as a parameter with the real one as default. Tests pass in a fake. These still start a `Process` themselves and move with the step that owns them: `EngineInstaller` (ditto, in `NXCore` since the engine sync store), the administrator prompt in `LiveOnboardingDriver` and the game start in `LiveConsoleDriver`. The tools of the device store (`DeviceTools`, `AppSignature`, `DeviceControl`, `ShellInstaller`) moved onto `ProcessRunner` with the device store, see below. What reads `MetalPin`, `EngineLayout` or `OnboardingDefaults` (`detectDepsSync`, `metalDep`, `needsIOSPlatform`) and the handling of the build's JSON events stay in `BuildModel` until the later store steps.+- `LauncherStores` (app target, `LauncherStores.swift`) is the wiring and nothing else: it creates the services and the stores, connects them and hands them to the views. Every store is a `let`. It holds no logic and no `@Published` state. The views that still live in the app target (`ContentView`, `BuilderView`, the sheets) take the stores they show as parameters, so they cannot leave the app target before step 8.+- `NXCore` holds the value types and static functions that need only Foundation: app and engine update parsing, `Localization.swift`, the release notes, the device and signing tools, the cloud folder and saves migration, the bundled tools, input staging, the build target and the pipe reader. Step 4 added four types: `TitleID` (parse a title ID from a file name, its owner, the update version, the build key), `GameInputs` (classify files into the four rows, row mismatch, allowed file types), `BuildProgress` (stage lines, progress details, durations, the steps of Xcode and the install, failure info) and `Toolchain` (probing Python, the venv, dotnet and Xcode, and the dependency rows `Dep`). `Stage` and `StepState` moved with `BuildProgress`. Step 5 added the first services (step 6 added `ReleaseSource`, see below): `ProcessRunner` (a protocol, with `SystemProcessRunner` as the real one), `ProcessGroups` (the process groups that Stop and quitting end) and `GitCheckout` (a protocol, with `SystemGitCheckout`, plus `GitRules` for the decisions that need no git). `ProcessRunner` is where a build process starts: `capture` runs to the end and keeps the output, `stream` hands out lines, `start` returns at once and can lead a process group. `LauncherStores` creates a runner and a checkout and hands them to the stores that use them: the clone, fetch, pull and adoption of a ZIP copy (`RepoStore`), the build run, the tools of a stage, the archive step and `openOnDevice` (`BuildStore`). `Toolchain`, `Diagnostics`, `OlderTools`, `Uninstall`, `EngineLayout.runSync` and the update staging take a runner or a checkout as a parameter with the real one as default. Tests pass in a fake. These still start a `Process` themselves and move with the step that owns them: `EngineInstaller` (ditto, in `NXCore` since the engine sync store), the administrator prompt in `LiveOnboardingDriver` and the game start in `LiveConsoleDriver`. The tools of the device store (`DeviceTools`, `AppSignature`, `DeviceControl`, `ShellInstaller`) moved onto `ProcessRunner` with the device store, see below. What reads `OnboardingDefaults` (`needsIOSPlatform`, the platform choice that asks for a new dependency check) stays in the app target, in `LauncherStores`, because the guided setup owns those keys.- Step 6 moved the self-update out of `BuildModel`. `AppUpdate` (`NXCore`) now also holds the release parsing (`release(fromJSON:)`, `check(latest:current:)`), the version compare (`isNewer`), the asset names, the staging of a download (`stage`, `StageFailure`) and the install, which clears the quarantine flag through a `ProcessRunner`. `ReleaseSource` is the second service (a protocol, with `GitHubReleases` as the real one): the latest release and the download. `Uninstall` moved to `NXCore` too, because the store holds its plan. `AppUpdate.relaunch` still starts its detached shell itself, and the store gets it as a closure.- `NXCoreTests` tests `NXCore` alone. It links no other target, so these tests run without SwiftUI. New tests of pure logic go there.-- `NXModel` holds `Localizer`: `lang` and `t()`. The app creates one with each `BuildModel`, and `ContentView` hands it to every view as an environment object. A view that shows text declares `@EnvironmentObject var loc: Localizer` and calls `loc.t(...)`. A language change redraws these views and nothing else.-- `NXModel` holds `AppUpdateStore`: the release check, the staged update, the update sheet, the uninstall plan and `appVersion`. `BuildModel` creates it with its localizer, runner and release source, and the views that show the update (the launcher's top bar and activity line, the Settings section, the update sheet) observe it and not `BuildModel`. `NXModelTests` tests it with a fake runner and a fake release source, without SwiftUI.-- `NXModel` holds `RepoStore` (step 7, repository): the repository path, the status line under it, how far it is behind origin/main, the clone, the update check, the pull, the automatic update when the app opens and the adoption of a ZIP copy. `BuildModel` creates it with its `Localizer` and `GitCheckout` and wires four closures: whether a build runs, whether this is a release app (which never clones or pulls), the build log, and `didMove`, which starts the engine sync after a clone, a pull or an adoption. The views that show the repository (Settings "Tools", the library's activity line, the setup hint) observe the store. `RepoLocation` is the narrow protocol (`path`, `isRepo`, `isGit`) for a store that needs only where the repository is. `NXCore` got the rules the store needs: `RepoLayout` (is it a repository, the tools a build needs, which checkout to use at start) and the file-system part of `EngineLayout` (`marker`, `root`, `isCheckout`, `hasEngineTool`). The stale check and the sync of `EngineLayout` stay in the app target with the engine.-- `NXModel` holds `EngineSyncStore` (step 7, engine sync): the engine selection (channel, engine ID, version, the one kept), the sync of a checkout's `engine/` (`tools/engine.py sync`, its status line and its failure row with Try again, the calls that wait for a running sync) and the engine of the release app (seeding the app's own engine, the check of the selected channel, the install, the channel switch after a confirmation, an engine that waits for the running build). `BuildModel` creates it with its localizer and runner, the `RepoStore` as the `RepoLocation` to read, the `DependencyStore` as the `PythonLocation` (a narrow protocol with `pythonPath`) and closures: where the build reads its tools from (`setRepoPath`, an installed engine tree), whether a build runs, the automatic update and the log. `RepoStore.didMove` starts its sync. The views that show the engine (Settings "Tools", the sync banner, the failure row's Try again, the launcher's checks after a sync) observe the store. `NXCore` got what the store needs: the stale check and the sync of `EngineLayout`, `EngineUpdater.swift` (`EngineChannel`, `EngineSelection`, `EngineUpdate`, `EngineInstaller`, `EngineTransport`) and `BuildFailureKind` with `BuildFailure` (the sync's failure row). The classifier `BuildFailureClassifier` stays in the app target. `NXModelTests` tests the store with a fake runner, without SwiftUI.-- Still in `BuildModel`, going to their store: `repoPath`, `repoOK` and `repoIsGit` are forwarders to `RepoStore`, because the build code (start, archive, install, diagnostics) reads the path and is not a store yet. `BuildModel` also forwards the objectWillChange of `RepoStore` and of `EngineSyncStore` to its own, because `canBuild` and the build views read the repository and the engine's paths through it. Both go with the build store (step 7, build). The synchronous calls of the build (`startBuild` waits for the sync, `Diagnostics` reads the selection) stay. `BuildModel` is not `@MainActor` yet, so it reaches the stores through `MainActor.assumeIsolated`.-- `NXModel` holds `DependencyStore` (step 7, dependencies): the rows of the tools panel (`deps`, `checked`, whether the list is expanded), the Python and dotnet paths the check finds, the check (`check()`) and the installs (`install(_:)`, with the failure kept on the row and a note for it). It is the `PythonLocation` that `EngineSyncStore` reads, and `DependencyStatus` (`checked`, `allPresent`, `pythonPath`, `dotnetPath`, `deps`) is the narrow protocol the build reads. `BuildModel` creates it with its localizer, runner and the `RepoStore` as the `RepoLocation`, and wires closures: the guided setup's platform choice (`needsIOS`), the App Store (a row with no command, Xcode), the log and the note after a failed install. The views that show the rows (Settings "Tools", the setup hint and the status line of the Builds page) observe the store. `NXCore` got what the store needs: `DependencyCheck` (the list of rows, the Metal row, the dotnet install command, `deps-check.txt`, the bash command and environment of an install) and `MetalPin`. `NXModelTests` tests the store with a fake runner and a fake detection, without SwiftUI. The Python row's venv install (`Toolchain.makeVenv`) is not tested there, because it reads and writes the real venv folder.-- `NXModel` holds `DeviceStore` (step 7, devices): the paired devices and their refresh (`devicectl list devices`), the signing teams, whether the listing ran (`checked`), the chosen install device and team (saved in the defaults), and the copy flow of the shared app: the question before the game data goes over (`shellCopy`, answered with `answerCopy`) and the wait for a cable (`shellWaiting`, `cancelWait`). The install runs on a background queue, so `askCopy`, `setWaiting` and `waitCancelled` are the blocking bridge it calls. `xcrun` is an injected value of the store (and of `BuildModel.init`), no longer a loose property that tests assign. `BuildModel` creates the store with its runner. The listings are closures with the real ones as default (`listDevices`, `readTeams`), so a test gives the store devices and teams. `BuildModel.init(xcrun:volumesRoot:)` takes the two values that were loose hooks. `volumesRoot` (where external drives are mounted) is read by the failure classifier, not by a device tool, so it stays on the model as an injected `let`. The views that show the install target (the Builds page) and the copy card observe the store. `NXCore` got what the store needs: `ShellCopyPlan`, `ShellCopyDecision` and `ShellConnection` (`ShellInstall.Connection` is an alias), `DeviceControl` (devicectl for the save transfer) and `LockedFlag`. `ProcessLaunch` got a `timeout` and an `input`, `ProcessResult` got `timedOut`, and `ProcessRunner` got one primitive, `streamLines` (merged output as whole lines, a callback when the process has started, an optional process group), with fakes and tests. `DeviceTools`, `AppSignature`, `DeviceControl` and `ShellInstaller` start their tools through a runner now. `NXModelTests` tests the store without SwiftUI, and `NXCoreTests` tests the tools against a fake runner.-- Still in `BuildModel`, going to the build store, because they belong to the build run: `installedOn` and `installedAppPath` (where the last build went), `installsDirectly` (it reads the build target), `shellRetry` and the retry of the game data, `installShell` (it feeds the build's stages and failure), the reinstall, the re-sign and `openOnDevice`. `installDevice`, `signingTeam` and `deviceName(_:)` are forwarders to the store, because the build code reads them. `BuildModel` forwards the store's objectWillChange to its own, like the other stores, and reaches the store through `MainActor.assumeIsolated` because it is not `@MainActor` yet.-- Still in `BuildModel`, going to the build store: `pythonPath`, `dotnetPath`, `depsChecked` and `allDepsPresent` are read-only forwarders to the store through `DependencyStatus`, because the build code (start, RomFS, diagnostics, `canBuild`) reads them. `BuildModel` forwards the store's objectWillChange to its own, like the other stores. The card's fix buttons (`fixBuildFailure`, `fixBusy`) call the store's `install` and `isInstalling`. `needsIOSPlatform` stays in the app target, because it reads `OnboardingDefaults` (the guided setup's keys), and goes to the store with the onboarding. `BuildModel` is not `@MainActor` yet, so it reaches the store through `MainActor.assumeIsolated`.-- `NXModel` also holds `BuildLog`: the log text, its tail trimming and the line buffer. `BuildModel` holds it in a `let` and does not publish it, and only `BuildLogView` (in `NXLauncher`) observes it. A log line redraws the log and no game card. `LauncherPerformanceTests` writes 1000 lines during a build and allows 0 cards. `BuildModel` is not `@MainActor` yet, so it reaches the log through `BuildLog.onMain`.-- `NXLauncher` holds the views and styles that do not need `BuildModel`: `LauncherPalette`, `Typography`, `LauncherStyles`, `LauncherDropdown`, `PadFocus` and `EmbeddedFonts`.-- `NX2Apple` holds everything else, including `BuildModel`.+- `NXModel` holds `Localizer`: `lang` and `t()`. `LauncherStores` creates one, and `ContentView` hands it to every view as an environment object. A view that shows text declares `@EnvironmentObject var loc: Localizer` and calls `loc.t(...)`. A language change redraws these views and nothing else.+- `NXModel` holds `AppUpdateStore`: the release check, the staged update, the update sheet, the uninstall plan and `appVersion`. `LauncherStores` creates it with its localizer, runner and release source, and the views that show the update (the launcher's top bar and activity line, the Settings section, the update sheet) observe it. `NXModelTests` tests it with a fake runner and a fake release source, without SwiftUI.+- `NXModel` holds `RepoStore` (step 7, repository): the repository path, the status line under it, how far it is behind origin/main, the clone, the update check, the pull, the automatic update when the app opens and the adoption of a ZIP copy. `LauncherStores` creates it with its `Localizer` and `GitCheckout` and wires four closures: whether a build runs, whether this is a release app (which never clones or pulls), the build log, and `didMove`, which starts the engine sync after a clone, a pull or an adoption. The views that show the repository (Settings "Tools", the library's activity line, the setup hint) observe the store. `RepoLocation` is the narrow protocol (`path`, `isRepo`, `isGit`) for a store that needs only where the repository is. `NXCore` got the rules the store needs: `RepoLayout` (is it a repository, the tools a build needs, which checkout to use at start) and the file-system part of `EngineLayout` (`marker`, `root`, `isCheckout`, `hasEngineTool`). The stale check and the sync of `EngineLayout` stay in the app target with the engine.+- `NXModel` holds `EngineSyncStore` (step 7, engine sync): the engine selection (channel, engine ID, version, the one kept), the sync of a checkout's `engine/` (`tools/engine.py sync`, its status line and its failure row with Try again, the calls that wait for a running sync) and the engine of the release app (seeding the app's own engine, the check of the selected channel, the install, the channel switch after a confirmation, an engine that waits for the running build). `LauncherStores` creates it with its localizer and runner, the `RepoStore` as the `RepoLocation` to read, the `DependencyStore` as the `PythonLocation` (a narrow protocol with `pythonPath`) and closures: where the build reads its tools from (`setRepoPath`, an installed engine tree), whether a build runs, the automatic update and the log. `RepoStore.didMove` starts its sync. The views that show the engine (Settings "Tools", the sync banner, the failure row's Try again, the launcher's checks after a sync) observe the store. `NXCore` got what the store needs: the stale check and the sync of `EngineLayout`, `EngineUpdater.swift` (`EngineChannel`, `EngineSelection`, `EngineUpdate`, `EngineInstaller`, `EngineTransport`) and `BuildFailureKind` with `BuildFailure` (the sync's failure row). The classifier `BuildFailureClassifier` moved to `NXCore` with the build store. `NXModelTests` tests the store with a fake runner, without SwiftUI.+- `NXModel` holds `DependencyStore` (step 7, dependencies): the rows of the tools panel (`deps`, `checked`, whether the list is expanded), the Python and dotnet paths the check finds, the check (`check()`) and the installs (`install(_:)`, with the failure kept on the row and a note for it). It is the `PythonLocation` that `EngineSyncStore` reads, and `DependencyStatus` (`checked`, `allPresent`, `pythonPath`, `dotnetPath`, `deps`) is the narrow protocol the build reads. `LauncherStores` creates it with its localizer, runner and the `RepoStore` as the `RepoLocation`, and wires closures: the guided setup's platform choice (`needsIOS`), the App Store (a row with no command, Xcode), the log and the note after a failed install. The views that show the rows (Settings "Tools", the setup hint and the status line of the Builds page) observe the store. `NXCore` got what the store needs: `DependencyCheck` (the list of rows, the Metal row, the dotnet install command, `deps-check.txt`, the bash command and environment of an install) and `MetalPin`. `NXModelTests` tests the store with a fake runner and a fake detection, without SwiftUI. The Python row's venv install (`Toolchain.makeVenv`) is not tested there, because it reads and writes the real venv folder.+- `NXModel` holds `DeviceStore` (step 7, devices): the paired devices and their refresh (`devicectl list devices`), the signing teams, whether the listing ran (`checked`), the chosen install device and team (saved in the defaults), and the copy flow of the shared app: the question before the game data goes over (`shellCopy`, answered with `answerCopy`) and the wait for a cable (`shellWaiting`, `cancelWait`). The install runs on a background queue, so `askCopy`, `setWaiting` and `waitCancelled` are the blocking bridge it calls. `xcrun` is an injected value of the store (and of `LauncherStores.init`), no longer a loose property that tests assign. `LauncherStores` creates the store with its runner. The listings are closures with the real ones as default (`listDevices`, `readTeams`), so a test gives the store devices and teams. `LauncherStores.init(xcrun:volumesRoot:)` takes the two values that were loose hooks. `volumesRoot` (where external drives are mounted) is read by the failure classifier, not by a device tool, so it is an injected `let` of the build store. The views that show the install target (the Builds page) and the copy card observe the store. `NXCore` got what the store needs: `ShellCopyPlan`, `ShellCopyDecision` and `ShellConnection` (`ShellInstall.Connection` is an alias), `DeviceControl` (devicectl for the save transfer) and `LockedFlag`. `ProcessLaunch` got a `timeout` and an `input`, `ProcessResult` got `timedOut`, and `ProcessRunner` got one primitive, `streamLines` (merged output as whole lines, a callback when the process has started, an optional process group), with fakes and tests. `DeviceTools`, `AppSignature`, `DeviceControl` and `ShellInstaller` start their tools through a runner now. `NXModelTests` tests the store without SwiftUI, and `NXCoreTests` tests the tools against a fake runner.+- `NXModel` holds `BuildStore` (step 7, build, the last store): the build inputs (the four rows `Slot`, the game folder, the output folder), the target, the stage list and whether a build runs, the handling of the script's JSON events (`ingest`), the run (the script's arguments and environment, stopping, the archive step), the install hand-off (`installShell`, the retry of the game data, the reinstall, the re-sign, the IPA, `openOnDevice`), the failure the card shows (`noteFailure`, `noteInstallFailure`), "Build anyway" and the fix buttons, the stale frameworks question and the files a drop adds. It decides whether a build may start (`canBuild`, and the checks at the top of `startBuild`). It is a class with six `BuildStore+` files, because no file may pass 800 lines. It gets what it needs through narrow protocols: `RepoLocation`, `DependencyInstalling` (`DependencyStatus` plus the install the fix buttons run), `EngineSyncing` (the sync a stale `engine/` needs) and `InstallTarget` (the device, the team, the teams the Mac knows and the copy flow). `DependencyStore`, `EngineSyncStore` and `DeviceStore` conform. AppKit reaches it as closures: the open, folder and save panels (`choosePaths`, `chooseFolder`, `chooseSaveLocation`), the notice (`showNotice`), the Finder (`revealFolder`, `openApp`) and `targetChanged`, which `LauncherStores` answers with a new dependency check when a Mac-only setup changes target. `NXCore` got what it needs: `ShellInstall`, `ShellLibrary`, `ShellInstaller` and `BannerCache` (the install of the shared app), `BuildFailureClassifier`, `VolumePath`, and `RomFSArchive` and `BuildCommands` (the archive stamp, the add-on content copy, the reinstall and IPA commands, the tools' PATH). `ShellCLI` (the terminal install) stays in the app target. `NXModelTests` tests the store with fake stores and a fake runner, without SwiftUI. The build's process start and its output callbacks are tested in the app target through the real build script stand-ins in `ShellInstallTests`.+- `NXModel` also holds `BuildLog`: the log text, its tail trimming and the line buffer. `BuildStore` holds it in a `let` and does not publish it, and only `BuildLogView` (in `NXLauncher`) observes it. A log line redraws the log and no game card. `LauncherPerformanceTests` writes 1000 lines during a build and allows 0 cards.+- `NXLauncher` holds the views and styles that do not need the stores: `LauncherPalette`, `Typography`, `LauncherStyles`, `LauncherDropdown`, `PadFocus` and `EmbeddedFonts`.+- `NX2Apple` holds everything else: the wiring (`LauncherStores`), the views, the panels and the drivers.## Access level@@ -64,7 +62,7 @@ A view observes only the stores it shows. A change in one store invalidates only- **Actions check their own conditions.** `install` refuses while a build runs and for a copy that is not a released one. The view does not decide that.- **Async work.** The method that starts it sets its state synchronously (`busy = true`), runs a `Task` on the main actor, hops off it for blocking work (`Task.detached`) and returns the `Task`, so a test awaits `store.checkForUpdate().value`.- **Tests.** `NXModelTests`, a `@MainActor` test class, no SwiftUI. Fakes for the services, a `UserDefaults` suite of its own, files in a temporary folder.-- **Wiring.** Until `BuildModel` is gone, it creates the store. The store is not published through the model: views take it as an `@ObservedObject` parameter (or as an environment object, as `Localizer`), so a change redraws the views that show it and nothing else.+- **Wiring.** `LauncherStores` creates the store and connects it to the others. Views take it as an `@ObservedObject` parameter (or as an environment object, as `Localizer`), so a change redraws the views that show it and nothing else.### `appVersion`@@ -78,7 +76,7 @@ A view observes only the stores it shows. A change in one store invalidates only- A view: `NXLauncher`, observing the stores it shows.- Creating the services and stores and handing them to the views: `NX2Apple`, nothing else.-Do not add to `BuildModel`. It only shrinks.+`BuildModel` is gone. Do not put logic in `LauncherStores`: it only creates and connects.## File sizediff --git a/frontend/Onboarding.md b/frontend/Onboarding.mdindex f36b45de..5abe7110 100644--- a/frontend/Onboarding.md+++ b/frontend/Onboarding.md@@ -1,6 +1,6 @@# First-run UI preview-With a recognized `NSPB_ONBOARDING_DEMO` value the app shows a scripted preview of the guided setup. The preview never instantiates `BuildModel`, detects tools, reads selected files, installs anything or opens the App Store. Its exit screen stands in for opening the library. Without it, `RootView` (`OnboardingRoot.swift`) runs the real flow described under "The real driver" below, or opens the launcher.+With a recognized `NSPB_ONBOARDING_DEMO` value the app shows a scripted preview of the guided setup. The preview never instantiates `LauncherStores`, detects tools, reads selected files, installs anything or opens the App Store. Its exit screen stands in for opening the library. Without it, `RootView` (`OnboardingRoot.swift`) runs the real flow described under "The real driver" below, or opens the launcher.From the repository root, enter `frontend`, then run one scenario:@@ -54,12 +54,12 @@ Persist the current step and selections before handling `skipForLater`, then inj## The real driver-`LiveOnboardingDriver` (`LiveOnboardingDriver.swift`) implements the contract over the launcher's own `BuildModel` and `GameLibrary`, which `RootView` shares with `ContentView`. Everything it does to the machine goes through `OnboardingEnvironment`, so the tests use fakes.+`LiveOnboardingDriver` (`LiveOnboardingDriver.swift`) implements the contract over the launcher's own `LauncherStores` (its `BuildStore` and `DependencyStore`) and `GameLibrary`, which `RootView` shares with `ContentView`. Everything it does to the machine goes through `OnboardingEnvironment`, so the tests use fakes.- When it shows: on launch, unless `onboarding.completed` is set or setup is already complete (all tools present, a keys file known, a games folder set, and a complete one is marked done without being shown). Settings has "Run setup again". Set up later stores the step, platform and an in-progress flag in `UserDefaults`, and the next launch resumes there and revalidates (a stored step past Xcode returns to Xcode when Xcode no longer holds).-- Detection and installs are `DependencyStore.check` / `deps` / `install`, one install at a time (Python, .NET, then Homebrew and the formulas). Homebrew waits for Xcode to be ready. The xcode row asks for the iOS SDK only when the stored platform is not Mac-only or builds target an iPhone (`BuildModel.needsIOSPlatform`).+- Detection and installs are `DependencyStore.check` / `deps` / `install`, one install at a time (Python, .NET, then Homebrew and the formulas). Homebrew waits for Xcode to be ready. The xcode row asks for the iOS SDK only when the stored platform is not Mac-only or builds target an iPhone (`LauncherStores.needsIOSPlatform`).- Xcode: missing opens the App Store and polls /Applications for it, and setup is one administrator prompt (`OnboardingAdmin.source`: `xcode-select -s`, `xcodebuild -license accept`, `-runFirstLaunch`), then the Metal Toolchain and, for iPhone or both, the iOS platform without it. A cancelled prompt returns to `needsSetup`.-- Keys are found in `~/.switch`, `~/Downloads` and the games folder, checked by `KeyCheck`, and only the path goes into the keys slot. Games use `GameLibrary.sourceGames`, `BuildModel.scan` and `GameLibrary.setFolder`.+- Keys are found in `~/.switch`, `~/Downloads` and the games folder, checked by `KeyCheck`, and only the path goes into the keys slot. Games use `GameLibrary.sourceGames`, `BuildStore.scan` and `GameLibrary.setFolder`.## NVN hintsdiff --git a/frontend/Sources/NX2Apple/Artwork.swift b/frontend/Sources/NX2Apple/Artwork.swiftindex 47f57a85..654b2e96 100644--- a/frontend/Sources/NX2Apple/Artwork.swift+++ b/frontend/Sources/NX2Apple/Artwork.swift@@ -1,12 +1,12 @@import AppKit+import NXCore/// Official key art for a game, by title ID: the eShop banner (1920×1080, Nintendo's image CDN) that the/// community title database blawar/titledb lists for each title. The region list is large (about 90 MB), so/// it is fetched only while a game in the library has no banner yet, reduced to title ID → banner URL and/// kept beside the library; each banner is downloaded once into the same folder.actor ArtworkStore {- static let shared = ArtworkStore(directory: FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]- .appendingPathComponent("NS Port Builder/artwork"))+ static let shared = ArtworkStore(directory: BannerCache.directory)static let titleListURL = URL(string: "https://raw.githubusercontent.com/blawar/titledb/master/US.en.json")!static let imageHosts: Set<String> = ["img-eshop.cdn.nintendo.net"]@@ -35,8 +35,7 @@ actor ArtworkStore {/// Where a title's banner is kept; nil while it has none.nonisolated static func cachedBanner(_ titleID: String, in directory: URL = ArtworkStore.shared.directory) -> URL? {- let url = directory.appendingPathComponent(titleID.uppercased() + ".jpg")- return FileManager.default.fileExists(atPath: url.path) ? url : nil+ BannerCache.cached(titleID, in: directory)}/// Download the banners the given titles lack. Returns the title IDs that got one.diff --git a/frontend/Sources/NX2Apple/BuildFailureView.swift b/frontend/Sources/NX2Apple/BuildFailureView.swiftindex ad78b4da..ccc5ab3f 100644--- a/frontend/Sources/NX2Apple/BuildFailureView.swift+++ b/frontend/Sources/NX2Apple/BuildFailureView.swift@@ -6,14 +6,14 @@ import NXLauncher/// Under the build button after a stop the script's early checks explain: what happened in plain words, the next step, and the/// button that does it (a dependency's own install command, or "Build anyway" for the three stops that have an override).struct BuildFailureCard: View {- @ObservedObject var m: BuildModel+ @ObservedObject var m: BuildStore/// Where the engine's failure row retries. nil for a failure of a build.var engine: EngineSyncStore?@EnvironmentObject var loc: Localizer/// The failure to show: the build's (`m.failure`) unless the caller passes another one, such as the engine sync's.var failure: BuildFailure?- init(m: BuildModel, engine: EngineSyncStore? = nil, failure: BuildFailure? = nil) {+ init(m: BuildStore, engine: EngineSyncStore? = nil, failure: BuildFailure? = nil) {self.m = mself.engine = engineself.failure = failure@@ -95,7 +95,7 @@ struct BuildFailureCard: View {/// updates), and its failure row when that stops: what happened, what to do, and Try again.struct EngineSyncBanner: View {@ObservedObject var engine: EngineSyncStore- let m: BuildModel+ let m: BuildStore@EnvironmentObject var loc: Localizervar body: some View {diff --git a/frontend/Sources/NX2Apple/BuildModelStrings.swift b/frontend/Sources/NX2Apple/BuildModelStrings.swiftdeleted file mode 100644index 51496acf..00000000--- a/frontend/Sources/NX2Apple/BuildModelStrings.swift+++ /dev/null@@ -1,9 +0,0 @@-import NXCore-import NXModel--// The language and the strings of `BuildModel` are the `Localizer`'s (LNPANDY/NX2Apple#387). `BuildModel` is not observed for them:-// a language change reaches the views through the environment. These two forward to it for the text the model writes itself.-extension BuildModel {- var lang: Lang { get { localizer.lang } set { localizer.lang = newValue } }- func t(_ key: String) -> String { localizer.t(key) }-}diff --git a/frontend/Sources/NX2Apple/BuildNotifications.swift b/frontend/Sources/NX2Apple/BuildNotifications.swiftindex 53e1d07c..abddf1f9 100644--- a/frontend/Sources/NX2Apple/BuildNotifications.swift+++ b/frontend/Sources/NX2Apple/BuildNotifications.swift@@ -1,6 +1,7 @@import AppKitimport Combineimport NXCore+import NXModelimport UserNotifications// A notification when a build finishes or fails (issue #64): a build takes long enough that people switch@@ -71,10 +72,10 @@ final class BuildNotifier: NSObject, ObservableObject, UNUserNotificationCenterD/// Follows the model's builds: asks for permission when one starts, notifies when it ends. Only from the real/// app's window (not previews or tests), and only with a bundle identifier (see the top of this file).- func watch(_ m: BuildModel, library: GameLibrary) {+ @MainActor func watch(_ m: BuildStore, library: GameLibrary) {guard watching == nil, BuildNotice.hasBundleID else { return }UNUserNotificationCenter.current().delegate = self- watching = m.$done.removeDuplicates().dropFirst().sink { [weak self, weak m, weak library] done in+ watching = m.$done.removeDuplicates().dropFirst().sink { [weak self, weak m, weak library] done in MainActor.assumeIsolated {guard let self, let m, let library else { return }if m.running { return } // a reset between builds: done flips false while nothing has ended yet// `done` is the chain's own verdict: the Mac target sets it when the .app exists, the iPhone target@@ -82,19 +83,21 @@ final class BuildNotifier: NSObject, ObservableObject, UNUserNotificationCenterD// on — a `running`-based notice read that window as a failure, and a done-based one missed nothing).let stopped = m.stoppingDispatchQueue.main.async {- let outcome: BuildNotice.Outcome = stopped ? .stopped- : done ? .finished : .failed(reason: BuildNotice.failureReason(note: m.doneNote, stages: m.stages))- guard BuildNotice.shouldNotify(outcome, enabled: BuildNotice.enabled, appActive: NSApp.isActive, hasBundleID: true) else { return }- self.post(outcome, m: m, library: library)+ MainActor.assumeIsolated {+ let outcome: BuildNotice.Outcome = stopped ? .stopped+ : done ? .finished : .failed(reason: BuildNotice.failureReason(note: m.doneNote, stages: m.stages))+ guard BuildNotice.shouldNotify(outcome, enabled: BuildNotice.enabled, appActive: NSApp.isActive, hasBundleID: true) else { return }+ self.post(outcome, m: m, library: library)+ }}- }+ } }}- private func post(_ outcome: BuildNotice.Outcome, m: BuildModel, library: GameLibrary) {+ @MainActor private func post(_ outcome: BuildNotice.Outcome, m: BuildStore, library: GameLibrary) {let titleID = TitleID.parse(m.basePath).map { String(format: "%016llX", $0) } ?? ""let game = library.games.first { $0.titleID == titleID }- let name = game?.name ?? GameLibrary.title(for: m.basePath, repo: m.repoPath, titleID: titleID)- let text = BuildNotice.text(outcome, game: name, target: m.target, device: m.installedOn.isEmpty ? nil : m.deviceName(m.installedOn), m.t)+ let name = game?.name ?? GameLibrary.title(for: m.basePath, repo: m.repo.path, titleID: titleID)+ let text = BuildNotice.text(outcome, game: name, target: m.target, device: m.installedOn.isEmpty ? nil : m.devices.deviceName(m.installedOn), m.t)let content = UNMutableNotificationContent()content.title = text.titlecontent.body = text.bodydiff --git a/frontend/Sources/NX2Apple/CheatsView.swift b/frontend/Sources/NX2Apple/CheatsView.swiftindex a31967ab..f3a70f4b 100644--- a/frontend/Sources/NX2Apple/CheatsView.swift+++ b/frontend/Sources/NX2Apple/CheatsView.swift@@ -9,7 +9,7 @@ import NXLauncher/// docs/frontends.md "Cheats"), so this is only the view. It never touches a running game: the host reads the files when it/// starts (or on its own Reload cheats).struct CheatsView: View {- @ObservedObject var m: BuildModel+ @ObservedObject var m: BuildStore@EnvironmentObject var loc: Localizer@ObservedObject var library: GameLibrarylet gameID: UUID@@ -28,7 +28,7 @@ struct CheatsView: View {@State private var result: (text: String, ok: Bool)?private var game: LibraryGame? { library.games.first { $0.id == gameID } }- private var deviceName: String { game.map { m.deviceName($0.installedDevice) } ?? "iPhone" }+ private var deviceName: String { game.map { m.devices.deviceName($0.installedDevice) } ?? "iPhone" }private var cheatFiles: CheatFiles? {guard let game else { return nil }@@ -303,7 +303,7 @@ struct CheatsView: View {private func copyToDevice() {guard let cheatFiles, let game else { return }- let transfer = CheatTransfer(files: cheatFiles, device: game.installedDevice, bundle: bundle, devicectl: devicectl ?? .xcrun(m.xcrunPath))+ let transfer = CheatTransfer(files: cheatFiles, device: game.installedDevice, bundle: bundle, devicectl: devicectl ?? .xcrun(m.devices.xcrun))busy = true; result = nilDispatchQueue.global(qos: .userInitiated).async {let outcome: (String, Bool)@@ -320,7 +320,7 @@ struct CheatsView: View {extension View {/// The Cheats sheet of the game `id` names, with the controller's scope following it (the launcher's other sheets do the same inline).- func cheatsSheet(for id: Binding<UUID?>, m: BuildModel, library: GameLibrary, pad: PadFocus, restoreScope: @escaping () -> String) -> some View {+ func cheatsSheet(for id: Binding<UUID?>, m: BuildStore, library: GameLibrary, pad: PadFocus, restoreScope: @escaping () -> String) -> some View {sheet(isPresented: Binding(get: { id.wrappedValue != nil }, set: { if !$0 { id.wrappedValue = nil } })) {if let game = id.wrappedValue { CheatsView(m: m, library: library, gameID: game).environmentObject(pad) }}diff --git a/frontend/Sources/NX2Apple/ConsoleEntryView.swift b/frontend/Sources/NX2Apple/ConsoleEntryView.swiftindex 3b6000cd..8c38309f 100644--- a/frontend/Sources/NX2Apple/ConsoleEntryView.swift+++ b/frontend/Sources/NX2Apple/ConsoleEntryView.swift@@ -96,7 +96,7 @@ struct ConsoleConnectionPrompt: View {}}-/// The demo reads covers from the repository's docs/images (RepoLayout.find, as the launcher does) and is otherwise isolated from ContentView: no BuildModel, library discovery, controller adapter or process is made.+/// The demo reads covers from the repository's docs/images (RepoLayout.find, as the launcher does) and is otherwise isolated from ContentView: no stores, library discovery, controller adapter or process is made.@MainActor struct ConsoleDemoView: View {@StateObject private var driver: MockConsoleDriverinit(scenario: MockConsoleDriver.Scenario) { _driver = StateObject(wrappedValue: MockConsoleDriver(scenario: scenario, artworkRepo: Optional(RepoLayout.find()).flatMap { $0.isEmpty ? nil : $0 })) }diff --git a/frontend/Sources/NX2Apple/ContentView.swift b/frontend/Sources/NX2Apple/ContentView.swiftindex a6c4574c..17c7cf71 100644--- a/frontend/Sources/NX2Apple/ContentView.swift+++ b/frontend/Sources/NX2Apple/ContentView.swift@@ -27,1345 +27,16 @@ extension StepState {}}-struct Slot: Identifiable {- let id: String- let kind: InputKind- let title: String- let optional: Bool- var paths: [String] = []- var problem: String = ""- /// A finished sentence shown beside the file name (the update row: which of several updates was taken).- var note: String = ""- var ok: Bool { paths.contains { FileManager.default.fileExists(atPath: $0) } }- /// `problem` holds either a finished message or a key + arguments, resolved by the model- /// (it needs the current language, which a struct cannot read).- var problemText: String { problem }- func summary(_ t: (String) -> String) -> String {- if !problem.isEmpty { return problem.hasPrefix("data.") ? t(problem) : problem }- if paths.isEmpty {- if kind == .dlc { return t("data.notSelectedDlc") }- return optional ? t("data.notSelectedOptional") : t("data.notSelected")- }- if paths.count == 1 {- let name = (paths[0] as NSString).lastPathComponent- return note.isEmpty ? name : name + "\n" + note- }- return String(format: t("data.files"), paths.count) + paths.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")- }-}--// MARK: - Model--final class BuildModel: ObservableObject {- @Published var gameDir = ""- @Published var slots: [Slot] = [- Slot(id: "base", kind: .base, title: "data.base", optional: false),- Slot(id: "update", kind: .update, title: "data.update", optional: true),- Slot(id: "dlc", kind: .dlc, title: "data.dlc", optional: true),- Slot(id: "keys", kind: .keys, title: "data.keys", optional: false),- ]- @Published var outDir = UserDefaults.standard.string(forKey: "buildOutputDirectory") ?? "" {- didSet { UserDefaults.standard.set(outDir, forKey: "buildOutputDirectory") }- }- @Published var stages: [Stage] = []- private var chainNoteShown = false // the shader-chain notice shows once per build- @Published var running = false- @Published var staleFrameworks: [StaleFrameworks.Entry] = [] // the prompt of StaleFrameworksPrompt.swift (#449)- /// The shell folder the cache row shows: the frameworks' mirror, shell.json and the banner cache live here.- var shellCachePath: String { shellRoot }- /// The shell folder of the install and of the cache row: the saved one, else next to the output folder (or the game's folder).- var shellRoot: String { ShellLibrary.resolveRoot(parent: outDir.isEmpty ? (basePath as NSString).deletingLastPathComponent : outDir) }- @Published var stopping = false- /// The build log. Not published: only `BuildLogView` observes it (#387), so a log line redraws the log and nothing else.- let log = BuildLog()- var logTail: String {- get { BuildLog.onMain { log.text } }- set { BuildLog.onMain { log.set(newValue) } }- }- @Published var done = false- @Published var doneNote = ""- /// What the NSP script stopped on, when it is one of the known early stops (BuildFailure.swift). nil for a build that- /// succeeded, is running, or failed some other way (the note then shows the last line of the log, as it always did).- @Published var failure: BuildFailure?- /// "Build anyway" asked for this stop and waiting for the confirmation dialog.- @Published var confirmingOverride: BuildFailureKind?- /// The one-off `--allow-*` of a confirmed "Build anyway": taken by the next build and never stored.- private(set) var armedOverride: BuildFailureKind?- @Published var macAppPath = "" // --platform mac-app: the .app this build produced- /// BuildTarget.ios = the game's framework in the one shared app on an iPhone or iPad; BuildTarget.mac = a double-clickable- /// Mac app (upstream's --platform mac-app). A Mac app is a different output of the same pipeline, not a- /// different pipeline: same extraction, rewrite and shaders, then dm/mac/pack_app.py.- @Published var target = BuildTarget.saved() {- didSet {- UserDefaults.standard.set(target, forKey: "buildTarget")- // A Mac-only setup needs no iOS SDK for a Mac build, but does for an iPhone one (needsIOSPlatform)- if oldValue != target, UserDefaults.standard.string(forKey: OnboardingDefaults.platform) == "mac" { MainActor.assumeIsolated { _ = dependencies.check() } }- }- }- /// Decode BC-compressed textures on the CPU. Only relevant for GPUs without BC support- /// (A15/A16 and older): on a device that has it the GPU path is always better, so the switch- /// is a compatibility option and defaults off. Passed as DM_TEX_BC_CPU through --env-file,- /// which the host reads at start-up — no rebuild of the host needed.- @Published var bcOnCPU = UserDefaults.standard.bool(forKey: "bcOnCPU") {- didSet { UserDefaults.standard.set(bcOnCPU, forKey: "bcOnCPU") }- }- @Published var archivePath = "" // the romfs folder the pack wrote- /// Where this build's folder actually is: --work-dir when the checkout has it, else the script's- /// default under the input folder (issue #5 — an upstream checkout has no --work-dir).- var effectiveWorkDir = ""- var lastBuildCommand: [String] = [] // this session's last build, for Copy diagnostics (Diagnostics.swift)-- // ---- Installing on an iPhone or iPad (Xcode with a development certificate) ----- // Optional: with a paired device and a signing team chosen, the script prepares the game's Xcode project- // (--prepare-xcode, the route its README gives developers), xcodebuild signs it for that device with the- // team (Xcode makes the provisioning profile) without the game files, devicectl installs it and copies the game's- // folder (romfs.img, aoc/) into its Documents, as a sideloaded copy has it. Without a device or a team the build stays an unsigned IPA, as before.- @Published var installedOn = "" // the device the last build went to (its UDID)- @Published var installedAppPath = "" // the signed app that went there- private var shellRetry: (framework: String, titleID: String, name: String, archive: String)?- var chooseKeys: (() -> Void)? // tests stand in for the file picker- var revealFolder: (URL) -> Void = { NSWorkspace.shared.open($0) }- var openApp: (URL) -> Void = { NSWorkspace.shared.openApplication(at: $0, configuration: NSWorkspace.OpenConfiguration()) }-- // ---- The devices (`DeviceStore`, NXModel) ----- // It owns the paired devices, the signing teams, the install target and the copy flow of the shared app (the question before the game- // data goes over, the wait for a cable). The model creates it with its runner and `xcrun`. The device the last build went to- // (`installedOn`), the retry and the install itself belong to the build run and stay here until the build store.-- /// Created on first use, on the main thread.- private(set) lazy var deviceStore: DeviceStore = MainActor.assumeIsolated {- let store = DeviceStore(runner: runner, xcrun: xcrunPath)- // The build state that reads the install target (`installsDirectly`, the start of a build) is still here: a change of the- // devices redraws what observes this model, as it did when they were published by it. Goes with the build store.- deviceChanges = store.objectWillChange.sink { [unowned self] _ in objectWillChange.send() }- return store- }- private var deviceChanges: AnyCancellable?-- /// The device and the team a build installs on, for the build code in this model. The views take the store.- var installDevice: String {- get { MainActor.assumeIsolated { deviceStore.installDevice } }- set { MainActor.assumeIsolated { deviceStore.installDevice = newValue } }- }- var signingTeam: String {- get { MainActor.assumeIsolated { deviceStore.signingTeam } }- set { MainActor.assumeIsolated { deviceStore.signingTeam = newValue } }- }-- /// This iPhone build goes straight to a device.- var installsDirectly: Bool { target != BuildTarget.mac && !installDevice.isEmpty && !signingTeam.isEmpty }-- func deviceName(_ udid: String) -> String { MainActor.assumeIsolated { deviceStore.deviceName(udid) } }-- // ---- The dependencies (`DependencyStore`, NXModel) ----- // It owns the rows of the tools panel, the Python and dotnet paths and the installs. The model creates it with its services and- // wires what reaches back here: the repository to read, the guided setup's platform choice, the App Store, the log and the note- // after a failed install. The build reads it through `DependencyStatus` (`depStatus`), not the store.-- /// Created on first use, on the main thread, because its closures reach back to this model.- private(set) lazy var dependencies: DependencyStore = MainActor.assumeIsolated {- let store = DependencyStore(- localizer: localizer, runner: runner, repo: repo,- needsIOS: { Self.needsIOSPlatform() },- openAppStore: { NSWorkspace.shared.open(URL(fileURLWithPath: "/Applications/App Store.app")) },- log: { [unowned self] in append($0) },- installFailed: { [unowned self] in doneNote = $0 })- // The build state that reads the tools (`canBuild`, the setup rows) is still here: a change of the rows redraws what observes- // this model, as it did when they were published by it. Goes with the build store.- dependencyChanges = store.objectWillChange.sink { [unowned self] _ in objectWillChange.send() }- return store- }- private var dependencyChanges: AnyCancellable?- /// What the build code in this model asks about the tools. The views take the store itself.- private var depStatus: DependencyStatus { MainActor.assumeIsolated { dependencies } }- var pythonPath: String { MainActor.assumeIsolated { depStatus.pythonPath } }- var dotnetPath: String { MainActor.assumeIsolated { depStatus.dotnetPath } }- var depsChecked: Bool { MainActor.assumeIsolated { depStatus.checked } }- var allDepsPresent: Bool { MainActor.assumeIsolated { depStatus.allPresent } }-- /// The language and the strings: views take them from the environment, this model only for the text it writes itself.- let localizer: Localizer- /// The services: the only places that start a process (`ProcessRunner`) and that run git (`GitCheckout`). Tests pass in fakes.- let runner: ProcessRunner- let gitCheckout: GitCheckout- /// Where the self-update looks for releases (the real one is GitHub's).- let releases: ReleaseSource- /// `xcrun`, which runs xcodebuild and devicectl: a test points it at a stand-in. `volumesRoot` is where external drives are mounted.- let xcrunPath: String- let volumesRoot: String- init(localizer: Localizer = Localizer(), runner: ProcessRunner = SystemProcessRunner(), gitCheckout: GitCheckout? = nil,- releases: ReleaseSource = GitHubReleases(), xcrun: String = "/usr/bin/xcrun", volumesRoot: String = "/Volumes") {- self.localizer = localizer- self.runner = runner- self.xcrunPath = xcrun- self.volumesRoot = volumesRoot- self.releases = releases- self.gitCheckout = gitCheckout ?? SystemGitCheckout(runner: runner)- _ = Self.endGroupsWhenQuitting- }-- private var proc: RunningProcess?- private var staging: String?-- /// The process groups of the builds are `ProcessGroups` (NXCore). Quitting the app ends them: the notification is AppKit's.- private static let endGroupsWhenQuitting: Void = {- NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: nil) { _ in ProcessGroups.endAll() }- }()-- // ---- The repository (`RepoStore`, NXModel) ----- // It owns the path, the status line, the update check, the pull and the automatic update. The model creates it with its services- // and wires what reaches back here: whether a build runs, the log, and the engine sync that follows a clone, a pull or an adoption.-- /// Created on first use, on the main thread, because its closures reach back to this model.- private(set) lazy var repo: RepoStore = MainActor.assumeIsolated {- let store = RepoStore(- localizer: localizer, git: gitCheckout,- buildRunning: { [unowned self] in running },- isReleaseApp: { [unowned self] in MainActor.assumeIsolated { engineSync.usesEngineStore } },- log: { [unowned self] in append($0) },- didMove: { [unowned self] in MainActor.assumeIsolated { _ = engineSync.syncEngine() } }) // the pull may have moved the pin or the patches- // The build state that reads the repository (`canBuild`, the setup rows) is still here: a change of the repository- // redraws what observes this model, as it did when the repository's state was published by it. Goes with the build store.- repoChanges = store.objectWillChange.sink { [unowned self] _ in objectWillChange.send() }- return store- }- private var repoChanges: AnyCancellable?-- /// The checkout the build reads, for the build code in this model. The views take it from `repo`.- var repoPath: String {- get { MainActor.assumeIsolated { repo.path } }- set { MainActor.assumeIsolated { repo.path = newValue } }- }- var repoOK: Bool { MainActor.assumeIsolated { repo.isRepo } }- var repoIsGit: Bool { MainActor.assumeIsolated { repo.isGit } }-- // ---- The engine (`EngineSyncStore`, NXModel) ----- // It owns the engine selection, the sync of a checkout's engine/ and the engine switch of the release app. The model creates it- // with its services and wires what reaches back here: the repository and the interpreter to read, where the build's tools- // are read from, whether a build runs, the automatic update and the log.-- /// Created on first use, on the main thread, because its closures reach back to this model.- private(set) lazy var engineSync: EngineSyncStore = MainActor.assumeIsolated {- let store = EngineSyncStore(- localizer: localizer, runner: runner, repo: repo, python: dependencies,- setRepoPath: { [unowned self] in repoPath = $0 },- buildRunning: { [unowned self] in running },- autoUpdate: { [unowned self] in MainActor.assumeIsolated { repo.autoUpdate } },- log: { [unowned self] in append($0) })- // The build state that reads the engine's paths (`canBuild`, the setup rows) is still here: a change of the engine redraws- // what observes this model, as it did when the engine's state was published by it. Goes with the build store.- engineChanges = store.objectWillChange.sink { [unowned self] _ in objectWillChange.send() }- return store- }- private var engineChanges: AnyCancellable?-- /// The PATH of the processes that run the build, installing packages and writing the RomFS image: the bundled tools in front of- /// `base` (BundledTools.swift), which is Homebrew's folders and the system's. One place, so that no environment forgets the bundle.- nonisolated static func toolPath(_ base: String = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin", python: String? = nil) -> String {- BundledTools.path(base, python: python)- }-- // ---- App self-update (GitHub Releases) ----- // `AppUpdateStore` (NXModel) owns it: the check, the staged update, the update sheet, the uninstall plan and the version.- // The model creates it with its services and wires the two things that need AppKit, quitting and the quit notification.-- /// Created on first use, on the main thread, because its closures reach back to this model (`running`).- private(set) lazy var appUpdates: AppUpdateStore = MainActor.assumeIsolated {- let store = AppUpdateStore(- localizer: localizer, runner: runner, releases: releases,- buildRunning: { [unowned self] in running || ProcessGroups.buildProcessesAlive },- terminate: {- NSApp.terminate(nil)- DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { exit(0) }- })- // The staged update goes in as the app quits, so the next launch is the new version without interrupting anyone.- quitObserver = NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: nil) { [weak store] _ in- MainActor.assumeIsolated { store?.appWillTerminate() }- }- return store- }- private var quitObserver: NSObjectProtocol?-- var basePath: String { slot("base").paths.first ?? "" }- var keysPath: String { slot("keys").paths.first ?? "" }- var updatePath: String { slot("update").paths.first ?? "" }- var dlcPaths: [String] { slot("dlc").paths }-- func slot(_ id: String) -> Slot { slots.first { $0.id == id } ?? slots[0] }- func updateSlot(_ id: String, _ body: (inout Slot) -> Void) {- if let i = slots.firstIndex(where: { $0.id == id }) { body(&slots[i]) }- }-- // MARK: Inputs-- /// Fill every slot from a folder: NSP/XCI classified by title ID (…000 base,- /// …800 update, anything above base+0x1000 add-on content), plus prod.keys.- /// Subfolders are scanned too — a dump usually arrives as 本体/ 更新/ DLC/ folders —- /// pruning the build folders this pipeline itself writes so a rescan is not slow.- func scan(folder: String) {- gameDir = folder- let found = GameInputs.classify(GameInputs.inputFiles(in: folder))- updateSlot("base") { $0.paths = found.base.map { [$0] } ?? []; $0.problem = found.base == nil ? "data.noBase" : "" }- updateSlot("update") { $0.paths = found.update.map { [$0] } ?? []; $0.problem = ""; $0.note = updateNote(found) }- updateSlot("dlc") { $0.paths = found.dlc; $0.problem = "" }- updateSlot("keys") { $0.paths = found.keys.map { [$0] } ?? []; $0.problem = "" }- if !found.anyGame {- updateSlot("base") { $0.problem = "data.noNsp" }- }- }-- /// The update row's note when the files held several updates: which one was taken and why one is enough.- func updateNote(_ found: GameInputs.Found) -> String {- guard found.update != nil, found.updateCount > 1 else { return "" }- return String(format: t("data.updateNewest"), found.updateVersion, found.updateCount)- }-- /// The row's message for a rejected file, as a finished sentence in the current language.- func rowProblemText(_ mismatch: GameInputs.RowMismatch, name: String) -> String {- func hex(_ tid: UInt64) -> String { String(format: "%016llX", tid) }- switch mismatch {- case .notBase(let tid): return String(format: t("data.rowNotBase"), name, hex(tid))- case .notUpdate(let tid): return String(format: t("data.rowNotUpdate"), name, hex(tid))- case .notDLC(let tid): return String(format: t("data.rowNotDLC"), name, hex(tid))- case .otherGame: return String(format: t("data.rowOtherGame"), name)- }- }-- func pickFiles(kind: InputKind) {- let p = NSOpenPanel()- p.canChooseDirectories = false- p.canChooseFiles = true- p.allowsMultipleSelection = (kind == .dlc)- p.allowedFileTypes = GameInputs.allowedFileTypes(for: kind)- switch kind {- case .dlc:- p.message = t("data.dlcPanelMessage")- p.prompt = t("data.dlcPanelPrompt")- case .update: p.message = t("data.updatePanelMessage")- default: break- }- guard p.runModal() == .OK, !p.urls.isEmpty else { return }- take(picked: p.urls.map(\.path), kind: kind)- }-- /// Files chosen for one row: those that fit it are taken, the first that does not is named on the row- /// and left out (it is not moved to another row: the row the user chose stays as they set it).- func take(picked: [String], kind: InputKind) {- let id = kind == .base ? "base" : kind == .update ? "update" : kind == .dlc ? "dlc" : "keys"- let baseName = kind == .base ? nil : (basePath as NSString).lastPathComponent- var fitting: [String] = [], problem = ""- for path in picked {- let name = (path as NSString).lastPathComponent- if let why = GameInputs.rowMismatch(kind, name: name, base: baseName) {- if problem.isEmpty { problem = rowProblemText(why, name: name) }- } else { fitting.append(path) }- }- updateSlot(id) { s in- if !fitting.isEmpty {- s.paths = kind == .dlc ? Array(Set(s.paths + fitting)).sorted() : Array(fitting.prefix(1))- s.note = ""- }- s.problem = problem- }- if kind == .base, let first = fitting.first { gameDir = (first as NSString).deletingLastPathComponent }- }-- func clear(_ id: String) { updateSlot(id) { $0.paths = []; $0.problem = "" } }-- var canBuild: Bool { repoOK && slot("base").ok && slot("keys").ok && allDepsPresent && !running }-- // MARK: Build-- func startBuild() {- guard !running else { return }- // The shared app needs a device this Mac knows. Found out here, before an hour of building, not after it.- if target != BuildTarget.mac, !shellDeviceChecked {- guard installsDirectly else { doneNote = t("shell.needsDevice"); done = false; return }- verifyShellDevice()- return- }- shellDeviceChecked = false- if target != BuildTarget.mac, askAboutStaleFrameworks() { return } // StaleFrameworksPrompt.swift (#449)- stopping = false- running = true; done = false; doneNote = ""; stages = []; BuildLog.onMain { log.clear() }; chainNoteShown = false- failure = nil; confirmingOverride = nil- let override = takeOverrideFlag() // for this build only: the next one asks again- installedOn = ""; installedAppPath = ""- guard repoOK else {- fail(repoPath.isEmpty ? t("msg.repoInvalidEmpty") : String(format: t("msg.repoInvalid"), shortPath(repoPath)))- return- }- // Resolve the interpreter here if the dependency check has not landed yet. checkDeps()- // runs on a background queue and startBuild() can beat it — for a moment pythonPath is- // empty, and the old fallback was Apple's /usr/bin/python3 (3.9), which the script then- // rejected with "require Python 3.12 or newer" whatever the machine actually had (#53).- let py = pythonPath.isEmpty ? Toolchain.findPython().path : pythonPath- // engine/ is the only engine and is stale or missing (#214): make it, then start again- if EngineLayout.needsSyncBeforeBuild(repoPath) {- MainActor.assumeIsolated {- engineSync.syncEngine { ok in- self.running = false- if ok && !EngineLayout.needsSyncBeforeBuild(self.repoPath) { self.startBuild() }- else { self.fail(String(format: self.t("msg.toolsOld"), "engine/ (python3 tools/engine.py sync, see the log)")) }- }- }- return- }- // The tools this app runs, before a build that takes an hour finds one missing at its last step (#87)- let missing = RepoLayout.missingTools(in: repoPath)- if !missing.isEmpty {- fail(String(format: t("msg.toolsOld"), missing.joined(separator: ", ")))- return- }-- // One folder when everything lives together; otherwise a staging folder of symlinks. A folder- // that holds other games too (a ROMs folder with one file per game) is staged as well: the- // script takes one game per folder and refuses one with several ("more than one game in the- // folder"), even when only the base game was picked (issue #58; ufooer's PR #31).- let baseDir = (basePath as NSString).deletingLastPathComponent- let allPaths = [basePath, updatePath] + dlcPaths- let dirs = Set(allPaths.filter { !$0.isEmpty }.map { ($0 as NSString).deletingLastPathComponent })- let picked = Set(allPaths.filter { !$0.isEmpty }.map { ($0 as NSString).lastPathComponent })- let unpicked = ((try? FileManager.default.contentsOfDirectory(atPath: baseDir)) ?? []).filter {- ["nsp", "xci", "nsz", "xcz"].contains(($0 as NSString).pathExtension.lowercased()) && !picked.contains($0)- }- // Staged, the folder's own update and add-on content would be left behind, where the script- // used to find them unpicked: bring along those whose file name carries this game's title ID- // exactly as build_ipa_from_nsp.py:445 reads it: the low 12 bits are 0x000 for a base game,- // 0x800 for its update, and anything else is add-on content below the base.- var staged = allPaths- if let base = TitleID.parse((basePath as NSString).lastPathComponent) {- let app = base & ~0xFFF- for f in unpicked {- guard let tid = TitleID.parse(f) else { continue }- let low = tid & 0xFFF- let owner = low == 0 ? tid : (low == 0x800 ? tid & ~0xFFF : (tid & ~0xFFF) - 0x1000)- guard owner == app else { continue }- if low == 0x800 && !updatePath.isEmpty { continue } // the update was picked already- if low != 0 && low != 0x800 && tid <= app { continue } // add-on content sits above its base- staged.append(baseDir + "/" + f)- }- }- let tidHex = TitleID.buildKey(basePath)- let workDir = (outDir.isEmpty ? baseDir : outDir) + "/" + tidHex + "_build"- // The build's signing step refuses the attributes a cloud folder adds, after the long steps: stop here instead.- if cloudFolderCheck(workDir) {- failure = BuildFailure(kind: .cloudFolder, gameName: nil, detail: workDir)- fail(failureWhat(failure!))- return- }- var inputDir = baseDir- if dirs.count > 1 || !unpicked.isEmpty {- // A stable folder per game (#132): the script's fingerprints name its files and its profile path.- let tmp = InputStaging.folder(workDir: workDir)- let linked = InputStaging.sync(files: staged, into: tmp)- if linked == 0 { fail(t("msg.stagingFailed")); return }- staging = tmp; inputDir = tmp- if !unpicked.isEmpty {- say(String(format: t("msg.stagedFromSharedFolder"), (basePath as NSString).lastPathComponent))- }- } else { staging = nil }-- // This fork's --work-dir keeps the build folder (extracted files, shader cache, the romfs- // archive) outside the NSPs' folder. An upstream checkout or an older ZIP does not have the- // option and would stop with "unrecognized arguments" (issue #5), so ask the script; without- // it the script's own default (<input>/<title ID>_build) is used and the archive step follows- // whatever folder the build reports.- let hasWorkDir = RepoLayout.supportsWorkDir(repoPath)- if !hasWorkDir {- say(t("msg.noWorkDir"))- }- // A compressed dump (NSZ / XCZ) needs nsz in the interpreter the build runs under; it is not- // part of the dependency probe (most builds never see one), so install it here, once, only- // when such a file is actually selected — otherwise the build stops with "pip install nsz".- let compressed = ([basePath, updatePath] + dlcPaths).contains {- let e = ($0 as NSString).pathExtension.lowercased()- return e == "nsz" || e == "xcz"- }- if compressed, !Toolchain.runOK(py, ["-c", "import nsz"]) {- say(t("msg.installingNsz"))- let r = runner.runCaptured([py, "-m", "pip", "install", "nsz"],- env: ["PATH": Self.toolPath(python: py),- "HOME": NSHomeDirectory()].merging(BundledTools.environment(for: py)) { $1 }) { line in- DispatchQueue.main.async { self.append(line + "\n") }- }- if !r {- fail(String(format: t("msg.nszFailed"), py))- return- }- }- let engine = EngineLayout.root(repoPath) // the checkout's engine/ (#214)- var args = [engine + "/" + RepoLayout.buildScript, inputDir, "-k", keysPath,- "--progress", "json"]- // A compatibility switch the player turned on: written to a small env file the pipeline- // copies into the app bundle (main.m sets one variable per line at boot). Only for an iPhone or iPad build;- // a Mac app runs on this Mac's GPU, which always has BC support.- if bcOnCPU && target != BuildTarget.mac {- let envPath = NSTemporaryDirectory() + "nspb-env-\(UUID().uuidString.prefix(8)).txt"- do {- try "DM_TEX_BC_CPU=1\n".write(toFile: envPath, atomically: true, encoding: .utf8)- args += ["--env-file", envPath]- say(t("msg.bcOn"))- } catch {- say(String(format: t("msg.bcEnvFailed"), error.localizedDescription))- }- }- if hasWorkDir { args += ["--work-dir", workDir] }- let macApp = target == BuildTarget.mac- if macApp {- // -o names the .app; the RomFS goes inside it, so the archive step is skipped below.- args += ["--platform", "mac-app"]- macAppPath = (outDir.isEmpty ? baseDir : outDir) + "/" + tidHex + ".app"- args += ["-o", macAppPath]- } else {- // Only the game's framework: the one shared app is made and signed after the script (installShell)- args += ShellInstall.buildArguments(workDir: workDir, team: signingTeam)- }- // The archive step packs whatever folder the build reported; without --work-dir that is the- // script's default, which is the same workDir unless a separate output folder was chosen.- effectiveWorkDir = hasWorkDir ? workDir : (inputDir as NSString).appendingPathComponent(tidHex + "_build")- args = BuildFailureClassifier.arguments(args, adding: override)- if let override { say(String(format: t("fail.override.note"), override)) }- say(String(format: t("msg.running"), py) + " " + args.joined(separator: " "))- lastBuildCommand = [py] + args-- // The root of the runtime the apphost looks for: derived from the detected installation,- // not assumed to be ~/.dotnet (Homebrew keeps it in …/opt/dotnet/libexec). Only set when the- // derivation actually answered — a wrong root is worse than none, and the pipeline derives- // and verifies its own (DOTNET_ROOT, build_ipa_from_nsp.py) when this is absent.- // TMPDIR as well: .NET 10 on macOS keeps the named mutex its first-run configure takes- // (NuGet-Migrations) under $TMPDIR/.dotnet/shm, and with no TMPDIR it stats "" and dies with- // 'NuGet-Migrations' + lstat("") == ENOENT before any project is read. NSTemporaryDirectory()- // is the per-user temp folder whether or not the app's own environment carries one.- var denv: [String: String] = ["PATH": Self.toolPath("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", python: py),- "USER": NSUserName(), "HOME": NSHomeDirectory(), "LANG": "en_US.UTF-8",- "TMPDIR": NSTemporaryDirectory()]- if let droot = Toolchain.dotnetRoot(for: dotnetPath.isEmpty ? "dotnet" : dotnetPath) {- denv["DOTNET_ROOT"] = droot // both variables carry the same root, as the apphost checks the arch-specific one first- denv["DOTNET_ROOT_ARM64"] = droot- }- // The bundled Python lives inside the signed app: a .pyc written there would change what the signature seals- // (the packages are compiled at bundle time), and a user site must not shadow its pinned packages.- denv.merge(BundledTools.environment(for: py)) { $1 }- let launch = ProcessLaunch(executable: py, arguments: args, environment: denv, directory: engine, groupPython: py)- let onExit: (Int32) -> Void = { [weak self] status in- DispatchQueue.main.async {- guard let self else { return }- self.running = false- self.flushLines()- if self.stopping {- self.stopping = false- self.resetProgress()- self.doneNote = self.t("msg.stopped")- self.cleanupStaging()- return- }- if status == 0 {- self.markAllDone()- if self.target == BuildTarget.mac {- // The .app is self-contained (its RomFS is inside), and the marker file- // beside it (.nx2apple-library, a dot file the Finder hides) tells the- // game's launcher that this folder is a library: its saves and log live- // here, and they follow the folder if it moves. No image copy — the .app- // already carries one, and a second multi-GB file was pure duplication.- let made = !self.macAppPath.isEmpty &&- FileManager.default.fileExists(atPath: self.macAppPath)- self.done = made- self.doneNote = self.t(made ? "msg.macAppDone" : "msg.macAppMissing")- if made {- try? Data().write(to: URL(fileURLWithPath:- (self.macAppPath as NSString).deletingLastPathComponent +- "/.nx2apple-library"))- }- self.running = false- self.cleanupStaging()- } else {- // The game's archive, then its framework into the one shared app on the device- let tid = TitleID.buildKey(self.basePath)- let name = ((self.basePath as NSString).lastPathComponent as NSString).deletingPathExtension- let fw = ShellInstall.frameworkPath(workDir: self.effectiveWorkDir, titleID: tid)- self.packArchive(workDir: self.effectiveWorkDir) {- self.installShell(framework: fw, titleID: tid, name: name, archive: $0)- }- }- } else {- if let i = self.stages.lastIndex(where: { $0.state == .running }) {- self.stages[i].state = .failed- self.stages[i].detail = String(format: self.t("msg.exitCode"), status)- self.noteFailure()- } else {- // The last real line says more than the exit code alone, and the message- // points at the log: "Build failed (exit code 1)" with nothing else sent a- // reporter looking for a log that a short window had below the fold (#52)- self.doneNote = String(format: self.t("msg.buildFailed"), status)- if let last = BuildProgress.lastMeaningfulLine(self.logTail) {- self.doneNote = String(format: self.t("msg.buildFailedReason"), last)- }- self.noteFailure()- }- self.cleanupStaging()- }- }- }- do {- proc = try runner.start(launch, onOutput: { [weak self] d in- guard let s = String(data: d, encoding: .utf8) else { return }- DispatchQueue.main.async { self?.ingest(s) }- }, onExit: onExit)- } catch { fail(String(format: t("msg.launchFailed"), error.localizedDescription)) }- }-- private var shellDeviceChecked = false-- /// Looks the device up in `devicectl list devices` (in the background), then starts the build, or says how to pair it.- private func verifyShellDevice() {- running = true; done = false; doneNote = ""; failure = nil; stages = []- let xcrun = xcrunPath, device = installDevice, runner = runner- DispatchQueue.global(qos: .userInitiated).async {- let link = ShellInstall.connection(of: device, in: DeviceTools.devices(xcrun: xcrun, timeout: 20, runner: runner))- DispatchQueue.main.async {- self.running = false- if link == .notPaired {- self.failure = BuildFailure(kind: .devicePairing, gameName: nil)- self.doneNote = String(format: self.t("shell.notPaired"), self.deviceName(device))- return- }- self.shellDeviceChecked = true- self.startBuild()- }- }- }-- /// A failed build's log read for the script's known early stops: the card under the build button then says what- /// happened and what to do. An unknown stop leaves the note (the last line of the log) as it is.- func noteFailure() {- let f = BuildFailureClassifier.classify(logTail, inputs: failureInputs())- guard f.kind != .unknown else { failure = nil; return }- failure = f- doneNote = failureWhat(f)- }-- /// Whether the build folder is in a cloud folder. Tests stand in for the system's answer.- var cloudFolderCheck: (String) -> Bool = { CloudFolder.contains($0) }-- /// The Save to folder, picked in a panel. Clears the cloud-folder stop, since the next build looks at the new folder.- func chooseBuildFolder() {- let d = NSOpenPanel(); d.canChooseDirectories = true; d.canChooseFiles = false- guard d.runModal() == .OK, let u = d.url else { return }- outDir = u.path- if failure?.kind == .cloudFolder { failure = nil; doneNote = "" }- }-- /// What the classifier may check besides the log: the keys file and where the game files are.- func failureInputs() -> BuildFailureClassifier.Inputs {- BuildFailureClassifier.Inputs(keysPath: keysPath, paths: ([basePath, updatePath, gameDir] + dlcPaths).filter { !$0.isEmpty },- volumes: volumesRoot)- }-- /// A failed step of an install on a device, as a card when the launcher can say more than the tool's line.- /// Called after `finishInstall`, which put the tool's own error into the note.- func noteInstallFailure(_ step: BuildFailureClassifier.InstallStep, error: String) {- let teamsOfMac = MainActor.assumeIsolated { deviceStore.readTeams }- let listed = teamsOfMac().contains { $0.id == signingTeam }- guard let f = BuildFailureClassifier.classifyInstall(step, error: error, teamListed: listed) else { failure = nil; return }- failure = f- doneNote = failureWhat(f)- }-- /// The first sentence of a failure's hint (it names the game of a 32-bit program when the message does).- func failureWhat(_ f: BuildFailure) -> String {- if f.kind == .a32Program, let name = f.gameName { return String(format: t("fail.a32Program.whatNamed"), name) }- if f.kind == .driveMissing, let name = f.detail { return String(format: t("fail.driveMissing.whatNamed"), name) }- if f.kind == .diskFull, let gb = f.detail { return String(format: t("fail.diskFull.whatNeeds"), gb) }- return t(f.kind.whatKey)- }-- /// "Build anyway": asks first. Nothing is armed until `confirmBuildAnyway`.- func requestBuildAnyway() {- guard !running, let kind = failure?.kind, kind.overrideFlag != nil else { return }- confirmingOverride = kind- }-- func cancelBuildAnyway() { confirmingOverride = nil }-- func confirmBuildAnyway() {- guard let kind = confirmingOverride else { return }- confirmingOverride = nil- armedOverride = kind- startBuild()- }-- /// The flag the next build runs with, once: the arm is cleared here, so a later build never inherits it.- func takeOverrideFlag() -> String? {- defer { armedOverride = nil }- return armedOverride?.overrideFlag- }-- /// The card's fix buttons run the dependency rows' own commands (the same installDep as Settings).- func fixBuildFailure(_ kind: BuildFailureKind) {- switch kind {- case .translator:- installRow("dotnet")- case .iosSDK:- installRow(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Toolchain.iosPlatformCmd))- case .cltSelected:- if let xcode = Toolchain.installedXcode() {- installRow(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Toolchain.selectXcodeCmd(xcode)))- }- case .zbic:- installRow("python") // the venv install, which now names zbic- case .keys:- if let chooseKeys { chooseKeys() } else { pickFiles(kind: .keys) } // the same picker as the keys row- case .severalGames, .noTitleID, .diskFull:- showFailureFolder()- case .cloudFolder:- chooseBuildFolder()- case .teamTaken, .noSigningAccount:- openXcode()- case .deviceTransfer, .devicePairing:- startBuild()- case .shellDataIncomplete:- retryShellData()- default: break- }- }-- /// The folder the failure is about, in the Finder: the folder of the game files, else the one the message names. For a full- /// disk the build folder (`<title ID>_build`, beside the game files) when it is there, since that is where the space went.- func showFailureFolder() {- guard let f = failure else { return }- var folder = gameDir.isEmpty ? (f.detail ?? "") : gameDir- if f.kind == .diskFull, !gameDir.isEmpty {- let built = ((try? FileManager.default.contentsOfDirectory(atPath: gameDir)) ?? []).sorted().first { $0.hasSuffix("_build") }- if let built { folder = gameDir + "/" + built }- }- guard !folder.isEmpty else { return }- revealFolder(URL(fileURLWithPath: folder))- }-- /// Xcode itself: its Settings > Accounts is where a team is signed in, and Xcode has no address that opens that pane.- func openXcode() {- guard let app = Toolchain.installedXcode() else { return }- openApp(URL(fileURLWithPath: app))- }-- /// Whether the card's fix button is already running its command.- func fixBusy(_ kind: BuildFailureKind) -> Bool {- guard [.translator, .iosSDK, .cltSelected, .zbic].contains(kind) else { return false }- let id = kind == .translator ? "dotnet" : kind == .zbic ? "python" : "xcode"- return MainActor.assumeIsolated { dependencies.isInstalling(id) }- }-- /// The row `id` of the tools panel installs, or the row given (a fix the panel has no row for).- private func installRow(_ id: String) {- MainActor.assumeIsolated { if let d = dependencies.deps.first(where: { $0.id == id }) { _ = dependencies.install(d) } }- }- private func installRow(_ dep: Dep) {- MainActor.assumeIsolated { _ = dependencies.install(dep) }- }-- /// (file count, bytes) of a RomFS tree — the reuse fingerprint's content part.- nonisolated static func treeStats(_ dir: String) -> (count: Int, bytes: Int)? {- let fm = FileManager.default- guard let en = fm.enumerator(atPath: dir) else { return nil }- var count = 0, bytes = 0- while let rel = en.nextObject() as? String {- let s = ((try? fm.attributesOfItem(atPath: dir + "/" + rel))?[.size] as? Int) ?? 0- count += 1; bytes += s- }- return (count, bytes)- }-- nonisolated static func writeStamp(source: String, version: String, to path: String) {- guard let s = treeStats(source) else { return }- try? FileManager.default.createDirectory(atPath: (path as NSString).deletingLastPathComponent,- withIntermediateDirectories: true)- try? "\(version)\t\(s.count)\t\(s.bytes)".write(toFile: path, atomically: true, encoding: .utf8)- }-- /// The stamped (version, count, bytes) versus the source tree's now: nil = pack again.- /// The newest version folder the extraction wrote, or nil when it wrote none.- ///- /// Either shape counts: RomFS/ from the older tools, RomFS.img from the current ones (the- /// rewriter packs the game files itself — build_ipa_from_nsp.py:876 tests for the image).- /// Looking only for the folder made every 0.4.8 build report "archive skipped" after a- /// successful extraction (issue #73).- nonisolated static func extractedVersion(in extract: String) -> String? {- let fm = FileManager.default- return ((try? fm.contentsOfDirectory(atPath: extract)) ?? [])- .filter { $0.hasPrefix("v") && (fm.fileExists(atPath: extract + "/" + $0 + "/RomFS") ||- fm.fileExists(atPath: extract + "/" + $0 + "/RomFS.img")) }- .sorted { (Int($0.dropFirst()) ?? 0) < (Int($1.dropFirst()) ?? 0) }- .last- }-- nonisolated static func archiveReusable(source: String, version: String, stamp: String) -> Int? {- guard let s = treeStats(source) else { return nil }- let parts = stamp.split(separator: "\t")- guard parts.count == 3, parts[0] == version,- Int(parts[1]) == s.count, Int(parts[2]) == s.bytes else { return nil }- return s.count- }-- private func fail(_ why: String) { running = false; doneNote = why; say("✗ " + why); cleanupStaging() }-- func stop() {- guard running, !stopping, let proc, proc.isRunning else { return }- stopping = true- ProcessGroups.endGroup(proc.processIdentifier) // the script and every tool it started- }-- private func cleanupStaging() {- staging = nil // the folder stays for the next build of this game (#132, InputStaging)- }-- /// A stopped build leaves no half-finished stages behind: the progress starts empty again.- private func resetProgress() { stages = []; BuildLog.onMain { log.clear() } }-- private func markAllDone() { for i in stages.indices where stages[i].state != .failed { stages[i].state = .done } }-- // MARK: Output parsing-- private func say(_ s: String) { append(s + "\n") }- private func append(_ s: String) { BuildLog.onMain { log.append(s) } }-- /// Split into lines (the pipe delivers arbitrary chunks) and turn the script's progress into the stage list.- /// `--progress json` writes one event per line (stage, step, progress with done / total / frac / eta, stage_end,- /// say), a count change at most every half second; anything else on the pipe (a tool's traceback) is log text.- /// The older `--progress lines` form is still understood:- /// [12:00:01] [2/7] extract v720896 …- /// [12:00:20] ✓ [2/7] extract v720896 (0:19): 30,000 files, 3.4 GB- func ingest(_ chunk: String) {- for line in BuildLog.onMain({ log.feed(chunk) }) { handle(line) }- }-- private func flushLines() {- if let rest = BuildLog.onMain({ log.flush() }) { handle(rest) }- }-- private func handle(_ line: String) {- if line.hasPrefix("{"), let data = line.data(using: .utf8),- let event = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], let kind = event["ev"] as? String {- return handleEvent(kind, event)- }- append(line + "\n")- noteChainChange(line)- guard let s = BuildProgress.parseStage(line) else { return }- if let i = stages.firstIndex(where: { $0.id == s.k }) {- if !s.name.isEmpty { stages[i].name = Stage.localizedName(s.name, t) }- if s.state != .pending { stages[i].state = s.state }- if !s.detail.isEmpty { stages[i].detail = s.detail }- stages[i].percent = s.percent- } else if s.state != .pending {- stages.append(Stage(id: s.k, name: Stage.localizedName(s.name, t), state: s.state, detail: s.detail, percent: s.percent, started: Date()))- stages.sort { $0.id < $1.id }- }- }-- /// The script marks a shader-chain bump with this tag: the cached libraries cannot be- /// reused and this build recompiles them. An alert, not a log line — the report's question- /// ("why is it building shaders again, the artifacts are on the drive") came from exactly- /// this moment passing unnoticed. Once per build: the pipe delivers arbitrary chunks.- /// (A plain line, or the message of a `say` event in `--progress json`.)- private func noteChainChange(_ text: String) {- guard text.contains("[NOTE] chain-changed"), !chainNoteShown else { return }- chainNoteShown = true- let a = NSAlert()- a.messageText = t("msg.chainChanged")- a.alertStyle = .informational- a.addButton(withTitle: "OK")- a.runModal()- }-- /// One event of `--progress json`: the stage list follows it, and the log gets a readable line (no count updates).- private func handleEvent(_ kind: String, _ e: [String: Any]) {- let k = (e["k"] as? NSNumber)?.intValue ?? 0- func stage(_ update: (inout Stage) -> Void) {- if let i = stages.firstIndex(where: { $0.id == k }) { update(&stages[i]) }- else { var s = Stage(id: k, name: Stage.localizedName(e["name"] as? String ?? "", t)); update(&s); stages.append(s); stages.sort { $0.id < $1.id } }- }- switch kind {- case "stage":- let name = e["name"] as? String ?? "", step = e["step"] as? String ?? ""- let n = (e["n"] as? NSNumber)?.intValue ?? 0- append("[\(k)/\(n)] \(name)" + (step.isEmpty ? "" : " · \(step)") + " …\n")- stage { $0.name = Stage.localizedName(name, t); $0.state = .running; $0.detail = step; $0.percent = nil; $0.started = Date(); $0.eta = nil }- case "step":- let step = e["step"] as? String ?? ""- append(" · \(step)\n")- stage { $0.detail = step; $0.percent = nil; $0.eta = nil }- case "progress":- let fraction = (e["frac"] as? NSNumber)?.doubleValue- let detail = BuildProgress.progressDetail(e)- let eta = (e["eta"] as? NSNumber)?.doubleValue- stage { $0.percent = fraction.map { $0 * 100 }; $0.detail = detail; $0.eta = eta; $0.etaAt = eta == nil ? nil : Date() }- case "stage_end":- let ok = e["ok"] as? Bool ?? true, summary = e["summary"] as? String ?? ""- let elapsed = BuildProgress.duration((e["elapsed"] as? NSNumber)?.doubleValue ?? 0)- append("\(ok ? "✓" : "✗") \(e["name"] as? String ?? "") (\(elapsed))" + (summary.isEmpty ? "" : ": \(summary)") + "\n")- stage { $0.state = ok ? .done : .failed; $0.detail = summary; $0.percent = ok ? 100 : $0.percent; $0.eta = nil }- case "say":- let msg = e["msg"] as? String ?? ""- append(msg + "\n")- noteChainChange(msg)- default: break- }- }-- // MARK: Archive-- /// The DLC images ride along: with the slim default the build script leaves them in the work folder- /// instead of packing them into the IPA, and the host mounts them from DM_AOC_DIR/<index>.img, so- /// they belong in this game's folder. Every way the archive step can end (folder pack, image copy,- /// image reuse, stamp reuse) goes through here (issue #202).- private func placeAddOnContent(workDir: String, in dest: String) {- let n = Self.copyAddOnContent(from: workDir + "/aoc", to: dest + "/aoc")- if n > 0 { say(String(format: t("msg.aocCopied"), n)) }- }-- /// Replace `to` with a copy of `from` when `from` exists. Returns how many entries `to` holds afterwards.- nonisolated static func copyAddOnContent(from: String, to: String) -> Int {- let fm = FileManager.default- guard fm.fileExists(atPath: from) else { return 0 }- try? fm.removeItem(atPath: to)- try? fm.copyItem(atPath: from, toPath: to)- return ((try? fm.contentsOfDirectory(atPath: to)) ?? []).count- }-- /// Pack the extracted RomFS into one romfs.img. The extracted folder is- /// <work>/extract/v<N>/RomFS where N is the profile's package version, so take- /// the highest v* that actually has a RomFS instead of hardcoding one game.- /// `then` continues the build with the archive's folder (installing on a device).- private func packArchive(workDir: String, then: @escaping (String) -> Void) {- running = true- let fm = FileManager.default- let extract = workDir + "/extract"- // The extraction writes either a RomFS folder (older tools) or RomFS.img, one image file- // (the rewriter packs it now: build_ipa_from_nsp.py:876 tests for exactly that). Looking- // only for the folder made every 0.4.8 build end with "archive skipped" on a machine where- // the extraction had in fact succeeded (issue #73). extractedVersion is the one authority:- // an inline copy of its predicate here drifted back to folder-only during a merge, and the- // archive skipped again while the test — which drives the function — stayed green.- guard let v = Self.extractedVersion(in: extract) else {- stages.append(Stage(id: 1000, name: t("prog.archiveShort"), state: .failed, detail: t("prog.noRomfs")))- doneNote = String(format: t("msg.archiveSkipped"), extract)- running = false; cleanupStaging(); return- }- let romfs = extract + "/" + v + "/RomFS"- let romfsImage = extract + "/" + v + "/RomFS.img"- // The output is Documents/games/<title ID>/romfs — the per-game layout the iOS app looks for- // first. Copying the whole `games` folder onto the phone (or into a folder the Files app- // exposes on an external drive) then needs no renaming, and several games' folders can sit- // side by side in one app.- let gamesRoot = (outDir.isEmpty ? (basePath as NSString).deletingLastPathComponent : outDir) + "/games"- let tid = TitleID.buildKey(basePath)- // games/<id>/ holds romfs.img and aoc/ side by side: main.m's per-game lookup takes the- // image, and the host mounts DLC from aoc/<index>.img (hle_fs.c aoc_dir). One folder, which- // the user copies to the phone or keeps on an external drive as a whole.- let gameDir = gamesRoot + "/" + tid- let dest = gameDir- try? fm.createDirectory(atPath: dest, withIntermediateDirectories: true)- // Reuse: packing is a multi-GB write, and the extracted RomFS is itself reused by the- // script — so when the source tree's (version, file count, bytes) matches the stamp left- // in the folder, the shards are already correct and the pack is skipped. A different- // version changes the extract; a same-version re-extract of the same NSPs reproduces the- // same tree.- let stampPath = dest + "/.packstamp"- if let stamp = try? String(contentsOfFile: stampPath, encoding: .utf8), !stamp.isEmpty,- let reused = Self.archiveReusable(source: romfs, version: v, stamp: stamp) {- archivePath = dest- stages.append(Stage(id: 1000, name: t("prog.archive"), state: .done,- detail: String(format: t("prog.archiveReused"), reused)))- say(String(format: t("msg.archiveReused"), dest))- placeAddOnContent(workDir: workDir, in: dest)- return then(dest)- }- // One romfs.img instead of a ROMFSARC shard set: upstream reads the image directly- // (hle_fs.c), one file copies to a phone at full speed where 300,000 did not, and it fits- // an external drive. A shard set from an earlier build of this game is removed first —- // main.m takes Documents/games/<id>/romfs.img before romfs/, so a stale archive would sit- // there confusingly.- for old in ((try? fm.contentsOfDirectory(atPath: dest)) ?? [])- where old == "romfs.img" || old == "romfs.idx" || (old.hasPrefix("romfs.") && old.dropFirst(6).allSatisfy(\.isNumber)) {- try? fm.removeItem(atPath: dest + "/" + old)- }- let idx = 1000- stages.append(Stage(id: idx, name: t("prog.archive"), state: .running, detail: v))- say(String(format: t("msg.archiveLog"), romfs, dest))-- // The extraction may already have packed the image (RomFS.img beside the code modules): then- // this is a copy, not a pack. Packing it again from a folder that no longer exists was the- // other half of issue #73.- if fm.fileExists(atPath: romfsImage) {- let to = dest + "/romfs.img"- // Reuse by the image's own identity: copying a multi-GB file on every build of an- // unchanged game is the cost this avoids. Size and modification date are enough — the- // extraction rewrites the file whenever the game's data changes.- if let src = try? fm.attributesOfItem(atPath: romfsImage),- let have = try? fm.attributesOfItem(atPath: to),- let a = src[.size] as? Int64, let b = have[.size] as? Int64, a == b,- let da = src[.modificationDate] as? Date, let db = have[.modificationDate] as? Date,- abs(da.timeIntervalSince(db)) < 1 {- stages.append(Stage(id: idx, name: t("prog.archive"), state: .done,- detail: String(format: t("prog.archiveReused"), 1)))- say(String(format: t("msg.archiveReused"), dest))- placeAddOnContent(workDir: workDir, in: dest)- archivePath = dest- return then(dest)- }- try? fm.removeItem(atPath: to)- do {- try fm.copyItem(atPath: romfsImage, toPath: to)- // The running stage is updated in place: there is no process here whose progress- // events would move it, and appending a second stage of the same name read as a- // duplicate in the stage list.- if let i = stages.firstIndex(where: { $0.id == idx }) {- stages[i].state = .done; stages[i].detail = v- }- say(String(format: t("msg.archiveLog"), romfsImage, dest))- placeAddOnContent(workDir: workDir, in: dest)- archivePath = dest- return then(dest)- } catch {- if let i = stages.firstIndex(where: { $0.id == idx }) {- stages[i].state = .failed; stages[i].detail = error.localizedDescription- }- doneNote = String(format: t("msg.archiveFailed"), 1)- running = false; cleanupStaging()- }- return- }- // dest/romfs.img: one file, which main.m's per-game lookup takes before any folder.- let engine = EngineLayout.root(repoPath)- let romfsPy = pythonPath.isEmpty ? "/usr/bin/python3" : pythonPath- let launch = ProcessLaunch(executable: romfsPy, arguments: [engine + "/" + RepoLayout.romfsImageTool, "--reuse", romfs, dest + "/romfs.img"],- environment: ["PATH": Self.toolPath("/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin", python: romfsPy), "PYTHONPATH": engine + "/dm/tools"]- .merging(BundledTools.environment(for: romfsPy)) { $1 },- groupPython: romfsPy)- let onExit: (Int32) -> Void = { [weak self] st in DispatchQueue.main.async {- guard let self else { return }- let cancelled = self.stopping- let succeeded = st == 0 && !cancelled- self.stopping = false- if succeeded {- self.archivePath = dest- Self.writeStamp(source: romfs, version: v, to: dest + "/.packstamp")- self.placeAddOnContent(workDir: workDir, in: dest)- }- if let i = self.stages.firstIndex(where: { $0.id == idx }) {- self.stages[i].state = succeeded ? .done : .failed- self.stages[i].detail = succeeded- ? String(format: self.t("prog.archiveDone"), dest)- : String(format: self.t("msg.archiveFailed"), st)- }- if succeeded { return then(dest) }- self.cleanupStaging()- self.running = false- self.done = false- if cancelled { self.resetProgress() }- self.doneNote = cancelled ? self.t("msg.stopped") : String(format: self.t("msg.archiveFailed"), st)- }}- do {- proc = try runner.start(launch, onOutput: { [weak self] d in- guard let s = String(data: d, encoding: .utf8) else { return }- DispatchQueue.main.async { self?.append(s) }- }, onExit: onExit)- } catch {- if let i = stages.firstIndex(where: { $0.id == idx }) {- stages[i].state = .failed; stages[i].detail = t("msg.archiveNoStart")- }- running = false; doneNote = t("msg.archiveNoStart"); cleanupStaging()- }- }-- // MARK: Installing on a device-- /// Steps 4 to 7 of the shared app (ShellInstall.swift) for a game whose framework is built and whose archive is packed: the- /// shell's project, signing, the install over the app that is already there, and the game data the device lacks.- func installShell(framework: String, titleID: String, name: String, archive: String, dataOnly: Bool = false) {- running = true- if dataOnly { failure = nil; done = false; doneNote = "" }- shellRetry = (framework, titleID, name, archive)- let python = pythonPath.isEmpty ? Toolchain.findPython().path : pythonPath- let root = shellRoot- var installer = ShellInstaller(xcrun: xcrunPath, repo: repoPath, python: python, root: root, device: installDevice, team: signingTeam)- installer.deviceName = deviceName(installDevice)- installer.lang = lang- installer.ownGroup = true- installer.toolPath = Self.toolPath("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", python: python)- installer.log = { s in DispatchQueue.main.async { self.append(s) } }- installer.stage = { s in DispatchQueue.main.async {- if let i = self.stages.firstIndex(where: { $0.id == s.id }) {- self.stages[i].name = s.name; self.stages[i].state = s.state; self.stages[i].detail = s.detail- if let percent = s.percent { self.stages[i].percent = percent }- if s.state == .running, self.stages[i].started == nil { self.stages[i].started = Date() }- } else {- self.stages.append(Stage(id: s.id, name: s.name, state: s.state, detail: s.detail, percent: s.percent,- started: s.state == .running ? Date() : nil))- }- } }- installer.runner = runner- installer.processStarted = { p in DispatchQueue.main.async { self.proc = p } }- // The size and the connection are shown with Continue, "Wait for a cable" and "Not now" (ShellCopyCard)- let devices = deviceStore- installer.decideCopy = { plan in devices.askCopy(plan) }- installer.waiting = { on in devices.setWaiting(on) }- installer.waitCancelled = { devices.waitCancelled }- let device = installDevice- DispatchQueue.global(qos: .userInitiated).async {- let result = dataOnly ? installer.installData(titleID: titleID, archive: archive)- : installer.install(framework: framework, titleID: titleID, name: name, archive: archive)- DispatchQueue.main.async {- MainActor.assumeIsolated { devices.copyEnded() }- if self.stopping {- self.stopping = false; self.running = false- self.resetProgress(); self.doneNote = self.t("msg.stopped"); self.cleanupStaging()- return- }- guard result.ok else {- self.finishInstall(result.message)- if let kind = result.failure { self.failure = BuildFailure(kind: kind, gameName: nil) }- else if let step = result.step { self.noteInstallFailure(step, error: result.message) }- return- }- self.installedOn = device- self.installedAppPath = result.appPath- self.finishInstall(nil, note: result.message)- }- }- }-- /// Retry after game data that went over in part: only the data step runs again (listing, diff, copy).- func retryShellData() {- guard !running, let r = shellRetry else { return }- installShell(framework: r.framework, titleID: r.titleID, name: r.name, archive: r.archive, dataOnly: true)- }-- private func finishInstall(_ failure: String?, note: String? = nil) {- running = false- done = failure == nil- doneNote = failure ?? note ?? String(format: t("dev.installed"), deviceName(installDevice))- cleanupStaging()- }-- /// Reinstall the signed app that is already in derived data, without unpacking, signing or packing again: the- /// device keeps the app's Documents (game data and saves), as the bundle ID does not change. A reinstall that- /// fails on an expired signature says so in devicectl's words; signing again is not this button's job.- func reinstallOnDevice(then: (() -> Void)? = nil) {- let device = installedOn, app = installedAppPath- guard !device.isEmpty, !app.isEmpty else { then?(); return }- guard FileManager.default.fileExists(atPath: app) else {- doneNote = String(format: t("dev.reinstallMissing"), shortPath(app))- then?(); return- }- running = true- runTool(id: 1004, name: String(format: t("dev.reinstallStage"), deviceName(device)),- Self.reinstallCommand(xcrun: xcrunPath, device: device, app: app), step: BuildProgress.installStep) { error in- if let error {- // The app is still on the device: a failed reinstall is a note, not a failed build- self.running = false- self.doneNote = String(format: self.t("dev.reinstallFailed"), error)- } else {- self.finishInstall(nil, note: String(format: self.t("dev.reinstalled"), self.deviceName(device)))- }- then?()- }- }-- nonisolated static func reinstallCommand(xcrun: String, device: String, app: String) -> [String] {- [xcrun, "devicectl", "device", "install", "app", "--device", device, app]- }-- /// Renew the shared app's signature (a free Apple ID's profile lasts 7 days). The same xcodebuild parameters as- /// the install, run on the cached project and derived data: Xcode reuses the compiled products and only signs- /// again, then devicectl installs the app over itself. PRODUCT_BUNDLE_IDENTIFIER is the one shell.json holds, so the- /// device keeps the app's Documents (game data, saves).- func resignOnDevice(app: String, device: String, then: (() -> Void)? = nil) {- guard !device.isEmpty, !app.isEmpty else { then?(); return }- guard !signingTeam.isEmpty else {- doneNote = t("dev.resignNoTeam")- then?(); return- }- // An app from before the shared app has its own project and cannot be signed again here: build the game again- guard let shell = ShellInstall.paths(ofApp: app) else {- doneNote = t("dev.resignOlder")- then?(); return- }- guard FileManager.default.fileExists(atPath: shell.project) else {- doneNote = String(format: t("dev.resignNoProject"), shortPath(shell.project))- then?(); return- }- let xcrun = xcrunPath, team = signingTeam, name = deviceName(device)- let bundle = ShellLibrary.load(root: shell.root).bundleID- running = true- // The shared app is signed again under the identifier shell.json holds, so the device keeps its Documents- let command = ShellInstall.buildCommand(xcrun: xcrun, root: shell.root, device: device, team: team, bundleID: bundle)- runTool(id: 1006, name: String(format: t("dev.resignStage"), name),- command, step: BuildProgress.xcodeStep) { error in- if let error, !error.isEmpty {- self.running = false- self.doneNote = String(format: self.t("dev.resignFailed"), error)- then?(); return- }- self.runTool(id: 1007, name: String(format: self.t("dev.installStage"), name),- Self.reinstallCommand(xcrun: xcrun, device: device, app: app), step: BuildProgress.installStep) { installError in- self.running = false- if let installError {- self.doneNote = String(format: self.t("dev.installFailed"), installError)- } else {- self.installedOn = device- self.installedAppPath = app- self.doneNote = String(format: self.t("dev.resigned"), name)- }- then?()- }- }- }-- /// Ask where to write the .ipa, then pack the signed app there.- func saveIPAPanel() {- let p = NSSavePanel()- p.title = t("dev.saveIPATitle")- p.allowedFileTypes = ["ipa"]- p.nameFieldStringValue = defaultIPAName()- p.canCreateDirectories = true- guard p.runModal() == .OK, let url = p.url else { return }- saveIPA(to: url)- }-- /// The signed app as an .ipa (Payload/<name>.app, the layout iOS and the sideloaders install): useful while the- /// signature lasts, and the thing to re-sign when it expires. The game data is not in it — it stays in the app's- /// Documents (romfs.img), as a normal iOS build has it.- func saveIPA(to url: URL, then: (() -> Void)? = nil) {- let app = installedAppPath, fm = FileManager.default- guard !app.isEmpty, fm.fileExists(atPath: app) else {- doneNote = String(format: t("dev.saveNeedsApp"), shortPath(app))- then?(); return- }- let stage = fm.temporaryDirectory.appendingPathComponent("nspb-ipa-" + UUID().uuidString)- let payload = stage.appendingPathComponent("Payload")- do {- try fm.createDirectory(at: payload, withIntermediateDirectories: true)- try fm.copyItem(atPath: app, toPath: payload.appendingPathComponent((app as NSString).lastPathComponent).path)- } catch {- try? fm.removeItem(at: stage)- doneNote = String(format: t("dev.saveFailed"), error.localizedDescription)- then?(); return- }- running = true- runTool(id: 1005, name: t("dev.saveStage"), Self.ipaCommand(payload: payload.path, ipa: url.path), step: { _ in nil }) { error in- try? fm.removeItem(at: stage)- self.running = false- self.doneNote = error.map { String(format: self.t("dev.saveFailed"), $0) }- ?? String(format: self.t("dev.savedIPA"), self.shortPath(url.path))- then?()- }- }-- /// ditto writes the archive the way Finder's "compress" does; the IPA's root must be Payload/, and --norsrc keeps- /// __MACOSX out (the signature itself lives in _CodeSignature inside the app).- nonisolated static func ipaCommand(payload: String, ipa: String) -> [String] {- ["/usr/bin/ditto", "-c", "-k", "--norsrc", "--keepParent", payload, ipa]- }-- /// The name the save panel offers: the app's display name, so two games' IPAs do not collide. A slash or colon in a- /// game's name would split the file name or show as a folder in Finder.- func defaultIPAName() -> String {- let plist = NSDictionary(contentsOfFile: installedAppPath + "/Info.plist")- let name = (plist?["CFBundleDisplayName"] as? String) ?? (plist?["CFBundleExecutable"] as? String) ?? "DmIOS"- return name.replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: ":", with: "_") + ".ipa"- }-- /// One of Xcode's tools as a stage of the build: in its own process group (Stop ends it), its output in the log,- /// its progress in the stage. `then` gets nil on success, else the last error line.- private func runTool(id: Int, name: String, _ command: [String], step: @escaping (String) -> (detail: String, percent: Double?)?,- then: @escaping (String?) -> Void) {- // A stage that runs again (the team-variant signing retry uses the same id) keeps its row:- // a second row with that id would never see an update again — every lookup takes the first- // match — and would spin for ever after the build moved on.- if let i = stages.firstIndex(where: { $0.id == id }) {- stages[i] = Stage(id: id, name: name, state: .running, started: Date())- } else {- stages.append(Stage(id: id, name: name, state: .running, started: Date()))- }- append("[\(name)] \(command.joined(separator: " "))\n")- let launch = ProcessLaunch(command, environment: ["PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "HOME": NSHomeDirectory(), "USER": NSUserName(), "LANG": "en_US.UTF-8"],- groupPython: pythonPath.isEmpty ? "/usr/bin/python3" : pythonPath)- var buffer = "", lastError = ""- let onOutput: (Data) -> Void = { [weak self] d in- guard let chunk = String(data: d, encoding: .utf8) else { return }- DispatchQueue.main.async {- guard let self else { return }- buffer += chunk- while let nl = buffer.firstIndex(of: "\n") {- let line = String(buffer[..<nl]); buffer = String(buffer[buffer.index(after: nl)...])- self.append(line + "\n")- if line.contains("error:") || line.hasPrefix("ERROR:") { lastError = line.trimmingCharacters(in: .whitespaces) }- if let s = step(line), let i = self.stages.firstIndex(where: { $0.id == id }) {- self.stages[i].detail = s.detail- if let percent = s.percent { self.stages[i].percent = percent }- }- }- }- }- let onExit: (Int32) -> Void = { [weak self] status in- DispatchQueue.main.async {- guard let self else { return }- if self.stopping {- self.stopping = false; self.running = false- self.resetProgress(); self.doneNote = self.t("msg.stopped"); self.cleanupStaging()- return- }- let ok = status == 0- if let i = self.stages.firstIndex(where: { $0.id == id }) {- self.stages[i].state = ok ? .done : .failed- if ok { self.stages[i].percent = 100; self.stages[i].detail = "" }- }- then(ok ? nil : (lastError.isEmpty ? String(format: self.t("msg.exitCode"), status) : lastError))- }- }- do { proc = try runner.start(launch, onOutput: onOutput, onExit: onExit) } catch { then(error.localizedDescription) }- }-- /// Start the game on the device it was installed on.- func openOnDevice(udid: String, app: String, completion: @escaping (String?) -> Void) {- let info = NSDictionary(contentsOfFile: app + "/Info.plist")- guard let bundle = info?["CFBundleIdentifier"] as? String else { return completion(String(format: t("dev.noProject"), shortPath(app))) }- let launch = ProcessLaunch(executable: xcrunPath, arguments: ["devicectl", "device", "process", "launch", "--device", udid, bundle], mergesErrors: true)- let runner = runner- DispatchQueue.global(qos: .userInitiated).async {- let r = runner.capture(launch)- var message: String?- if !r.started { message = r.out }- else if r.status != 0 { message = r.out.split(separator: "\n").last(where: { $0.contains("rror") }).map(String.init) ?? r.out }- DispatchQueue.main.async { completion(message) }- }- }-- // MARK: Dependencies-- /// Whether the xcode row asks for the iOS SDK. Always, as before, unless the guided setup stored a Mac-only choice- /// and builds are for the Mac: upstream no longer needs the iOS SDK for a Mac build (c464cb24).- nonisolated static func needsIOSPlatform(defaults: UserDefaults = .standard) -> Bool {- if OnboardingDefaults.sessionPlatform == "mac" { return false } // a forced run's choice, not stored yet- guard defaults.string(forKey: OnboardingDefaults.platform) == "mac" else { return true }- return BuildTarget.normalized(defaults.string(forKey: "buildTarget")) != BuildTarget.mac- }-- /// Home shown as ~ (shorter in a one-line row, and it keeps the account name out of- /// screenshots).- func shortPath(_ path: String) -> String { RepoLayout.shortPath(path) }-}-// MARK: - Viewstruct BuilderView: View {- @ObservedObject var m: BuildModel+ @ObservedObject var m: BuildStore@ObservedObject var updates: AppUpdateStore // the app's self-update (Settings, "NX2Apple" section)@ObservedObject var repo: RepoStore // the repository (Settings, "Tools" section, and the setup hint)@ObservedObject var engine: EngineSyncStore // the engine (Settings, "Tools" section)@ObservedObject var dependencies: DependencyStore // the tools (Settings, "Tools" section, and the setup hint and status)@ObservedObject var devices: DeviceStore // the install target (the Builds page) and the copy card+ var diagnostics: (LibraryGame?, @escaping (String) -> Void) -> Void = { _, _ in } // the report of Copy diagnostics (LauncherStores)@EnvironmentObject var loc: Localizer@ObservedObject var library: GameLibraryvar settings = false@@ -1646,9 +317,9 @@ struct BuilderView: View {}}if m.done && !m.installedOn.isEmpty {- group(String(format: loc.t("dev.installed"), m.deviceName(m.installedOn))) {+ group(String(format: loc.t("dev.installed"), devices.deviceName(m.installedOn))) {row(loc.t("dev.installedNote"), dot: LauncherPalette.ready) {- Button(String(format: loc.t("dev.open"), m.deviceName(m.installedOn))) {+ Button(String(format: loc.t("dev.open"), devices.deviceName(m.installedOn))) {m.openOnDevice(udid: m.installedOn, app: m.installedAppPath) { error in if let error { m.doneNote = error } }}}@@ -1991,7 +662,7 @@ struct BuilderView: View {}}divider- row(loc.t("diag.title"), detail: loc.t("diag.note")) { DiagnosticsButton(m: m, game: library.selected) }+ row(loc.t("diag.title"), detail: loc.t("diag.note")) { DiagnosticsButton(report: diagnostics, game: library.selected) }}}diff --git a/frontend/Sources/NX2Apple/Diagnostics.swift b/frontend/Sources/NX2Apple/Diagnostics.swiftindex e7f104db..303e6617 100644--- a/frontend/Sources/NX2Apple/Diagnostics.swift+++ b/frontend/Sources/NX2Apple/Diagnostics.swift@@ -294,13 +294,13 @@ struct Diagnostics {}}-extension BuildModel {+extension LauncherStores {/// The report, read in the background and handed back on the main thread.func diagnostics(game: LibraryGame? = nil, _ done: @escaping (String) -> Void) {- let repo = repoOK ? repoPath : "", python = pythonPath.isEmpty ? Toolchain.findPython().path : pythonPath, dotnet = dotnetPath- let checked = depsChecked, rows = checked ? MainActor.assumeIsolated { dependencies.deps }.map(Diagnostics.dependency) : []- let command = lastBuildCommand, log = logTail, xcrun = xcrunPath- let (sel, usesEngineStore) = MainActor.assumeIsolated { (engineSync.selection, engineSync.usesEngineStore) }+ let repo = self.repo.isRepo ? self.repo.path : "", python = dependencies.pythonPath.isEmpty ? Toolchain.findPython().path : dependencies.pythonPath, dotnet = dependencies.dotnetPath+ let checked = dependencies.checked, rows = checked ? dependencies.deps.map(Diagnostics.dependency) : []+ let command = build.lastBuildCommand, log = build.logTail, xcrun = deviceStore.xcrun+ let (sel, usesEngineStore) = (engineSync.selection, engineSync.usesEngineStore)let engine = usesEngineStore && !sel.engineID.isEmpty ? "\(sel.channel.rawValue) \(sel.version) (\(sel.engineID))" : nilDispatchQueue.global(qos: .userInitiated).async {let git = Diagnostics.git(repo)@@ -334,7 +334,7 @@ extension BuildModel {/// Settings' Copy diagnostics: the report goes to the clipboard and the button says Copied for a moment.struct DiagnosticsButton: View {- @ObservedObject var m: BuildModel+ let report: (LibraryGame?, @escaping (String) -> Void) -> Void@EnvironmentObject var loc: Localizervar game: LibraryGame? // the library's selected game: its log goes in the reportvar showCopied = false // the visual QA's confirmation@@ -352,7 +352,7 @@ struct DiagnosticsButton: View {private func copy() {busy = true- m.diagnostics(game: game) { report in+ report(game) { report inNSPasteboard.general.clearContents()NSPasteboard.general.setString(report, forType: .string)busy = falsediff --git a/frontend/Sources/NX2Apple/DropFiles.swift b/frontend/Sources/NX2Apple/DropFiles.swiftindex 89d53be3..5abcfbc6 100644--- a/frontend/Sources/NX2Apple/DropFiles.swift+++ b/frontend/Sources/NX2Apple/DropFiles.swift@@ -7,51 +7,6 @@ import NXLauncher// mix. They are sorted into the slots by the same classification as Choose game folder// (GameInputs.classify), so a drop and a picked folder never disagree about what is the update.-extension BuildModel {- /// One dropped folder is the same as choosing it; anything else (files, several folders, a mix) is added to- /// what is already chosen: a slot the drop has something for is replaced, add-on content is added to.- func take(dropped paths: [String]) {- func isFolder(_ p: String) -> Bool {- var d: ObjCBool = false- return FileManager.default.fileExists(atPath: p, isDirectory: &d) && d.boolValue- }- if paths.count == 1, isFolder(paths[0]) { scan(folder: paths[0]); return }- var found = GameInputs.classify(paths.flatMap { isFolder($0) ? GameInputs.inputFiles(in: $0) : [$0] })- // update and add-on files of another game than the base (the dropped one, else the one already chosen)- let baseName = (found.base ?? (basePath.isEmpty ? nil : basePath)).map { ($0 as NSString).lastPathComponent }- var rejected: [InputKind: String] = [:]- func fits(_ path: String, _ kind: InputKind) -> Bool {- let name = (path as NSString).lastPathComponent- guard let why = GameInputs.rowMismatch(kind, name: name, base: baseName) else { return true }- if rejected[kind] == nil { rejected[kind] = rowProblemText(why, name: name) }- return false- }- if let u = found.update, !fits(u, .update) { found.update = nil }- found.dlc = found.dlc.filter { fits($0, .dlc) }- slots = Self.merged(slots, with: found)- for (kind, text) in rejected { updateSlot(kind == .update ? "update" : "dlc") { $0.problem = text } }- if found.update != nil { updateSlot("update") { $0.note = updateNote(found) } }- if let base = found.base { gameDir = (base as NSString).deletingLastPathComponent }- }-- /// The slots after a drop of `found`. Nothing usable in it leaves the slots as they were, but says so on an empty base row.- nonisolated static func merged(_ slots: [Slot], with found: GameInputs.Found) -> [Slot] {- slots.map { s in- var s = s- switch s.id {- case "base":- if let base = found.base { s.paths = [base]; s.problem = "" }- else if !found.anyGame && found.keys == nil && s.paths.isEmpty { s.problem = "data.noNsp" }- case "update": if let update = found.update { s.paths = [update]; s.problem = "" }- case "dlc": if !found.dlc.isEmpty { s.paths = Array(Set(s.paths + found.dlc)).sorted(); s.problem = "" }- case "keys": if let keys = found.keys { s.paths = [keys]; s.problem = "" }- default: break- }- return s- }- }-}-/// The Builds page as a drop target: a highlight while files are dragged over it, the files to the model when dropped.struct GameFilesDrop: ViewModifier {let enabled: Booldiff --git a/frontend/Sources/NX2Apple/FreeSpace.swift b/frontend/Sources/NX2Apple/FreeSpace.swiftindex 685d4bda..215e0b2b 100644--- a/frontend/Sources/NX2Apple/FreeSpace.swift+++ b/frontend/Sources/NX2Apple/FreeSpace.swift@@ -207,7 +207,7 @@ enum BuildFolder {/// The game's Free space sheet: the parts of its build folder with their sizes and what removing each costs; the player/// picks parts and confirms.struct FreeSpaceView: View {- @ObservedObject var m: BuildModel+ @ObservedObject var m: BuildStore@EnvironmentObject var loc: Localizerlet game: LibraryGame@Environment(\.dismiss) private var dismiss@@ -218,7 +218,7 @@ struct FreeSpaceView: View {@State private var working = false@State private var outcome: String?- init(m: BuildModel, game: LibraryGame, survey: BuildFolderSurvey? = nil, chosen: Set<BuildFolderPart> = []) {+ init(m: BuildStore, game: LibraryGame, survey: BuildFolderSurvey? = nil, chosen: Set<BuildFolderPart> = []) {self.m = mself.game = game_survey = State(initialValue: survey) // visual QA: a measured folder without one on disk@@ -227,7 +227,7 @@ struct FreeSpaceView: View {/// The old shader versions are part of the shader output, so choosing both counts them once.private var chosenBytes: Int64 { chosen.reduce(0) { $0 + ($1 == .oldShaders && chosen.contains(.shaders) ? 0 : survey?.sizes[$1] ?? 0) } }- private var chain: String? { BuildFolder.currentChain(repo: m.repoPath) }+ private var chain: String? { BuildFolder.currentChain(repo: m.repo.path) }var body: some View {VStack(alignment: .leading, spacing: 0) {diff --git a/frontend/Sources/NX2Apple/LaunchOptionsView.swift b/frontend/Sources/NX2Apple/LaunchOptionsView.swiftindex 9d717561..3cf74550 100644--- a/frontend/Sources/NX2Apple/LaunchOptionsView.swift+++ b/frontend/Sources/NX2Apple/LaunchOptionsView.swift@@ -9,7 +9,7 @@ import NXLauncher/// under Advanced settings. A row of the list is a saved choice in the app's own preferences domain (SavedChoices.swift), which the/// app reads at every start; Play passes only the launch overrides (what the list has no row for, the mods) as its environment.struct LaunchOptionsView: View {- @ObservedObject var m: BuildModel+ @ObservedObject var m: BuildStore@EnvironmentObject var loc: Localizer@ObservedObject var library: GameLibrarylet gameID: UUID@@ -22,7 +22,7 @@ struct LaunchOptionsView: View {private var game: LibraryGame? { library.games.first { $0.id == gameID } }private var settings: [LaunchSetting]? {- game.flatMap { LaunchSetting.forMac(app: $0.appPath, titleID: $0.titleID, repo: m.repoPath, labels: loc.t) }+ game.flatMap { LaunchSetting.forMac(app: $0.appPath, titleID: $0.titleID, repo: m.repo.path, labels: loc.t) }}private var store: SavedChoices? { game.map { SavedChoices(app: $0.appPath, titleID: $0.titleID) } }/// A saved choice for a row of the list, else the tested default; what only this launcher has comes from the library.diff --git a/frontend/Sources/NX2Apple/LauncherStores.swift b/frontend/Sources/NX2Apple/LauncherStores.swiftnew file mode 100644index 00000000..0f015e87--- /dev/null+++ b/frontend/Sources/NX2Apple/LauncherStores.swift@@ -0,0 +1,137 @@+import AppKit+import NXCore+import NXModel++/// The app's wiring (LNPANDY/NX2Apple#387, step 7): it creates the services and the stores, connects them and hands them to the views.+/// It holds no logic and no state of its own. Every store is a `let`, and a view takes the stores it shows as its own parameters, so a+/// change in one store redraws only the views that observe it.+///+/// What reaches back from one store to another is wired here as closures and narrow protocols: the repository's `didMove` starts the+/// engine sync, the engine sync reads the repository and the interpreter, the build reads the repository, the tools, the engine and+/// the devices, and the stores that need to know whether a build runs ask the build store. What needs AppKit (the file panels, the+/// alert, the Finder, quitting) is wired here too.+@MainActor final class LauncherStores {+ let localizer: Localizer+ let runner: ProcessRunner+ let gitCheckout: GitCheckout+ let releases: ReleaseSource+ let repo: RepoStore+ let engineSync: EngineSyncStore+ let dependencies: DependencyStore+ let deviceStore: DeviceStore+ let appUpdates: AppUpdateStore+ let build: BuildStore+ private var quitObserver: NSObjectProtocol?++ /// - Parameters:+ /// - xcrun: runs xcodebuild and devicectl: a test points it at a stand-in.+ /// - volumesRoot: where external drives are mounted.+ init(localizer: Localizer = Localizer(), runner: ProcessRunner = SystemProcessRunner(), gitCheckout: GitCheckout? = nil,+ releases: ReleaseSource = GitHubReleases(), xcrun: String = "/usr/bin/xcrun", volumesRoot: String = "/Volumes") {+ _ = Self.endGroupsWhenQuitting+ let git = gitCheckout ?? SystemGitCheckout(runner: runner)+ self.localizer = localizer; self.runner = runner; self.gitCheckout = git; self.releases = releases+ let log = BuildLog()+ let laterBuild = Later<BuildStore>(), laterEngine = Later<EngineSyncStore>()++ let repo = RepoStore(+ localizer: localizer, git: git,+ buildRunning: { laterBuild.value?.running ?? false },+ isReleaseApp: { laterEngine.value?.usesEngineStore ?? false },+ log: { log.append($0) },+ didMove: { _ = laterEngine.value?.syncEngine() }) // the pull may have moved the pin or the patches+ let dependencies = DependencyStore(+ localizer: localizer, runner: runner, repo: repo,+ needsIOS: { Self.needsIOSPlatform() },+ openAppStore: { NSWorkspace.shared.open(URL(fileURLWithPath: "/Applications/App Store.app")) },+ log: { log.append($0) },+ installFailed: { laterBuild.value?.note($0) })+ let engineSync = EngineSyncStore(+ localizer: localizer, runner: runner, repo: repo, python: dependencies,+ setRepoPath: { repo.path = $0 },+ buildRunning: { laterBuild.value?.running ?? false },+ autoUpdate: { repo.autoUpdate },+ log: { log.append($0) })+ laterEngine.value = engineSync+ let devices = DeviceStore(runner: runner, xcrun: xcrun)+ let updates = AppUpdateStore(+ localizer: localizer, runner: runner, releases: releases,+ buildRunning: { (laterBuild.value?.running ?? false) || ProcessGroups.buildProcessesAlive },+ terminate: {+ NSApp.terminate(nil)+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { exit(0) }+ })+ let build = BuildStore(+ localizer: localizer, runner: runner, log: log, repo: repo, deps: dependencies, engine: engineSync, devices: devices,+ volumesRoot: volumesRoot,+ targetChanged: {+ // A Mac-only setup needs no iOS SDK for a Mac build, but does for an iPhone one (needsIOSPlatform)+ if UserDefaults.standard.string(forKey: OnboardingDefaults.platform) == "mac" { _ = dependencies.check() }+ })+ laterBuild.value = build+ self.repo = repo; self.engineSync = engineSync; self.dependencies = dependencies; self.deviceStore = devices+ self.appUpdates = updates; self.build = build++ // The staged update goes in as the app quits, so the next launch is the new version without interrupting anyone.+ quitObserver = NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: nil) { [weak updates] _ in+ MainActor.assumeIsolated { updates?.appWillTerminate() }+ }+ wirePanels()+ }++ /// The process groups of the builds are `ProcessGroups` (NXCore). Quitting the app ends them: the notification is AppKit's.+ private static let endGroupsWhenQuitting: Void = {+ NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: nil) { _ in ProcessGroups.endAll() }+ }()++ /// What the build store asks of AppKit: the open panel, the folder panel, the save panel, the alert and the Finder.+ private func wirePanels() {+ build.choosePaths = { pick in+ let p = NSOpenPanel()+ p.canChooseDirectories = false+ p.canChooseFiles = true+ p.allowsMultipleSelection = pick.allowsMultiple+ p.allowedFileTypes = pick.fileTypes+ if let message = pick.message { p.message = message }+ if let prompt = pick.prompt { p.prompt = prompt }+ guard p.runModal() == .OK, !p.urls.isEmpty else { return [] }+ return p.urls.map(\.path)+ }+ build.chooseFolder = {+ let d = NSOpenPanel(); d.canChooseDirectories = true; d.canChooseFiles = false+ guard d.runModal() == .OK, let u = d.url else { return nil }+ return u.path+ }+ build.chooseSaveLocation = { title, name in+ let p = NSSavePanel()+ p.title = title+ p.allowedFileTypes = ["ipa"]+ p.nameFieldStringValue = name+ p.canCreateDirectories = true+ guard p.runModal() == .OK else { return nil }+ return p.url+ }+ build.showNotice = { text in+ let a = NSAlert()+ a.messageText = text+ a.alertStyle = .informational+ a.addButton(withTitle: "OK")+ a.runModal()+ }+ build.revealFolder = { NSWorkspace.shared.open($0) }+ build.openApp = { NSWorkspace.shared.openApplication(at: $0, configuration: NSWorkspace.OpenConfiguration()) }+ }++ /// Whether the xcode row asks for the iOS SDK. Always, as before, unless the guided setup stored a Mac-only choice+ /// and builds are for the Mac: upstream no longer needs the iOS SDK for a Mac build (c464cb24).+ nonisolated static func needsIOSPlatform(defaults: UserDefaults = .standard) -> Bool {+ if OnboardingDefaults.sessionPlatform == "mac" { return false } // a forced run's choice, not stored yet+ guard defaults.string(forKey: OnboardingDefaults.platform) == "mac" else { return true }+ return BuildTarget.normalized(defaults.string(forKey: "buildTarget")) != BuildTarget.mac+ }+}++/// A store that a closure reaches before it exists: the closures of the stores created first read it, the app fills it in last.+@MainActor private final class Later<T: AnyObject> {+ weak var value: T?+}diff --git a/frontend/Sources/NX2Apple/LauncherView.swift b/frontend/Sources/NX2Apple/LauncherView.swiftindex 9c3477b9..d65f1e55 100644--- a/frontend/Sources/NX2Apple/LauncherView.swift+++ b/frontend/Sources/NX2Apple/LauncherView.swift@@ -41,7 +41,9 @@ enum LibraryFilter: String, CaseIterable, Identifiable {}struct ContentView: View {- @StateObject private var m: BuildModel+ private let stores: LauncherStores // the wiring: the stores below are its, the views take what they show+ @StateObject private var m: BuildStore // the build: the stages, the failure, the inputs+ @ObservedObject private var devices: DeviceStore // the copy card and the activity line while the data goes over@ObservedObject private var loc: Localizer // the strings: handed on to every view below through the environment@ObservedObject private var updates: AppUpdateStore // the app's self-update: the update icon, the sheet, the uninstall dialog@ObservedObject private var repo: RepoStore // the repository: the activity line, and the checks that follow a change of it@@ -80,7 +82,7 @@ struct ContentView: View {private let qaManage: (open: Bool, ring: Bool) // visual QA: the Manage menu open at launch, with the controller's focus ring or without@Environment(\.scenePhase) private var scenePhase- init(model: BuildModel? = nil, library: GameLibrary? = nil, initialPage: LauncherPage = .library,+ init(stores: LauncherStores? = nil, library: GameLibrary? = nil, initialPage: LauncherPage = .library,activeBuildID: UUID? = nil, performStartupChecks: Bool = true, search: String? = nil, olderTools: Set<UUID> = [],manageOpen: Bool = false, padRing: Bool = false, onRunSetup: (() -> Void)? = nil,enterConsole: (() -> Void)? = nil, controllerDriver: AnyConsoleDriver? = nil, controls sharedControls: ControlLayout? = nil, qaPrompt: Bool = false,@@ -96,14 +98,12 @@ struct ContentView: View {if let search { _search = State(initialValue: search); _searching = State(initialValue: true) } // visual QA: the bar with its field open_toolsAge = StateObject(wrappedValue: ToolsAge(older: olderTools)) // visual QA: games marked without a checkout to compare_gamepad = StateObject(wrappedValue: gamepad ?? LauncherGamepad()) // LauncherPerformanceTests presses its buttons- let model = model ?? BuildModel()- _m = StateObject(wrappedValue: model)- _loc = ObservedObject(wrappedValue: model.localizer)- _updates = ObservedObject(wrappedValue: model.appUpdates)- _repo = ObservedObject(wrappedValue: model.repo); _engine = ObservedObject(wrappedValue: model.engineSync)+ let stores = stores ?? LauncherStores(); self.stores = stores+ _m = StateObject(wrappedValue: stores.build); _loc = ObservedObject(wrappedValue: stores.localizer)+ _updates = ObservedObject(wrappedValue: stores.appUpdates); _devices = ObservedObject(wrappedValue: stores.deviceStore)+ _repo = ObservedObject(wrappedValue: stores.repo); _engine = ObservedObject(wrappedValue: stores.engineSync)_library = StateObject(wrappedValue: library ?? GameLibrary())- _page = State(initialValue: initialPage)- _activeBuildID = State(initialValue: activeBuildID)+ _page = State(initialValue: initialPage); _activeBuildID = State(initialValue: activeBuildID)self.performStartupChecks = performStartupChecks}@@ -177,7 +177,7 @@ struct ContentView: View {if page == .library {libraryPage} else {- BuilderView(m: m, updates: updates, repo: repo, engine: engine, dependencies: m.dependencies, devices: m.deviceStore, library: library, settings: page == .settings, onViewGame: { page = .library },+ BuilderView(m: m, updates: updates, repo: repo, engine: engine, dependencies: stores.dependencies, devices: devices, diagnostics: stores.diagnostics, library: library, settings: page == .settings, onViewGame: { page = .library },onOpenSettings: { page = .settings }, onChooseLibraryFolder: chooseLibraryFolder,onOpenControls: { controlsOpen = true }, onOpenControllers: { controllerSheet = true }, onRunSetup: onRunSetup, controlChanges: controls.changeCount,padMerge: Binding(get: { controls.padMerge }, set: { setPadMerge($0) }))@@ -213,9 +213,9 @@ struct ContentView: View {}refreshArtwork()readSignatures()- if performStartupChecks { library.discover(); fetchArtwork(); _ = m.deviceStore.refresh(); checkTools() }+ if performStartupChecks { library.discover(); fetchArtwork(); _ = stores.deviceStore.refresh(); checkTools() }if performStartupChecks {- _ = m.dependencies.check()+ _ = stores.dependencies.check()if engine.usesEngineStore { engine.prepareEngine() } // the release app: its engine store, never gitelse { engine.syncEngine() } // a checkout whose engine/ is missing or older than its pin (#214)if repo.isRepo && repo.isGit { repo.checkForUpdates(silent: true) } else { repo.adoptAtLaunch() }@@ -512,7 +512,7 @@ struct ContentView: View {Button { primaryAction(game) } label: {LauncherHeroActionLabel(title: game.primary == .play ? loc.t("library.play")- : (game.primary == .openOnDevice ? String(format: loc.t("dev.open"), m.deviceName(game.installedDevice))+ : (game.primary == .openOnDevice ? String(format: loc.t("dev.open"), devices.deviceName(game.installedDevice)): loc.t("library.newBuild")),symbol: game.primary == .play ? "play.fill" : (game.primary == .openOnDevice ? "iphone" : "hammer.fill"))}@@ -686,7 +686,7 @@ struct ContentView: View {if m.running {Image(systemName: "wrench.and.screwdriver").font(.system(size: 22, weight: .light)).foregroundStyle(.secondary)VStack(alignment: .leading, spacing: 4) {- Text(loc.t(m.deviceStore.shellCopy != nil || m.deviceStore.shellWaiting || m.stages.contains { $0.id == 1003 && $0.state == .running }+ Text(loc.t(devices.shellCopy != nil || devices.shellWaiting || m.stages.contains { $0.id == 1003 && $0.state == .running }? "activity.transfer" : (m.target == BuildTarget.mac ? "activity.mac" : "activity.ios"))).font(.manrope(15, .bold))TimelineView(.periodic(from: Date(), by: 1)) { context in // the clock ticks while a count may stand stillText(m.stages.last(where: { $0.state == .running })@@ -882,7 +882,7 @@ struct ContentView: View {// The launch options; the app's launcher (dm/mac/launcher.c) keeps a variable that is already set.// The keyboard and controller layout (Settings → Controls) goes to every game; a build whose host does not read it plays with the default keys.// They stay launch overrides (the environment) for now: DM_KEYMAP and DM_PAD_MAP become saved choices only when seedds/nxnative#386 merges.- let environment = GameStart.environment(for: game, library: library, controls: controls, repo: m.repoPath, labels: loc.t) // GameStart.swift: the console mode starts games with the same+ let environment = GameStart.environment(for: game, library: library, controls: controls, repo: stores.repo.path, labels: loc.t) // GameStart.swift: the console mode starts games with the samelet withRecording = environment.merging(FrameTimes.recordingEnvironment(for: game, library: library.folder)) { $1 } // FrameTimes.swift, as console mode doesif !withRecording.isEmpty { configuration.environment = withRecording }NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: game.appPath), configuration: configuration) { app, error in@@ -904,7 +904,7 @@ struct ContentView: View {guard !apps.isEmpty else { signatureExpiry = [:]; return }DispatchQueue.global(qos: .utility).async {var found: [UUID: Date] = [:]- for (id, path) in apps { if let date = AppSignature.expiration(ofApp: path, runner: m.runner) { found[id] = date } }+ for (id, path) in apps { if let date = AppSignature.expiration(ofApp: path, runner: stores.runner) { found[id] = date } }DispatchQueue.main.async { signatureExpiry = found }}}@@ -915,7 +915,7 @@ struct ContentView: View {resignNote = nilm.resignOnDevice(app: game.iosAppPath, device: game.installedDevice) {resignNote = m.doneNote- signatureExpiry[game.id] = AppSignature.expiration(ofApp: game.iosAppPath, runner: m.runner)+ signatureExpiry[game.id] = AppSignature.expiration(ofApp: game.iosAppPath, runner: stores.runner)}}@@ -927,11 +927,11 @@ struct ContentView: View {if performStartupChecks { checkTools() }}- private func checkTools() { toolsAge.check(games: library.games, repo: m.repoPath) }+ private func checkTools() { toolsAge.check(games: library.games, repo: stores.repo.path) }private func refreshArtwork() {artwork = Dictionary(uniqueKeysWithValues: library.games.compactMap { game in- GameLibrary.artwork(for: game, repo: m.repoPath).map { (game.id, $0) }+ GameLibrary.artwork(for: game, repo: stores.repo.path).map { (game.id, $0) }})}diff --git a/frontend/Sources/NX2Apple/Library.swift b/frontend/Sources/NX2Apple/Library.swiftindex 0c341990..345a78f1 100644--- a/frontend/Sources/NX2Apple/Library.swift+++ b/frontend/Sources/NX2Apple/Library.swift@@ -1,6 +1,7 @@import AppKitimport SwiftUIimport NXCore+import NXModelimport NXLauncher/// Only paths and presentation metadata live here. Game data stays on its original drive.@@ -296,9 +297,7 @@ final class GameLibrary: ObservableObject {/// A path on an external volume (`/Volumes/<name>/...`) whose mount point is absent: the drive is not connected, so the file is/// not known to be gone and its path must stay.static func onUnmountedVolume(_ path: String, volumes: String = "/Volumes") -> Bool {- let prefix = volumes.hasSuffix("/") ? volumes : volumes + "/"- guard path.hasPrefix(prefix), let name = path.dropFirst(prefix.count).split(separator: "/").first else { return false }- return !FileManager.default.fileExists(atPath: prefix + name)+ VolumePath.onUnmounted(path, volumes: volumes)}/// Forgets a remembered Mac app, IPA or iOS app that is gone from disk, so nothing points at it. A file on a drive that is not@@ -490,11 +489,11 @@ final class GameLibrary: ObservableObject {return game.id}- @discardableResult func rememberInputs(_ model: BuildModel) -> UUID? {+ @MainActor @discardableResult func rememberInputs(_ model: BuildStore) -> UUID? {guard !model.basePath.isEmpty else { return nil }let titleID = TitleID.parse(model.basePath).map { String(format: "%016llX", $0) }?? URL(fileURLWithPath: model.basePath).standardizedFileURL.path- var game = games.first { $0.titleID == titleID } ?? LibraryGame(titleID: titleID, name: Self.title(for: model.basePath, repo: model.repoPath, titleID: titleID))+ var game = games.first { $0.titleID == titleID } ?? LibraryGame(titleID: titleID, name: Self.title(for: model.basePath, repo: model.repo.path, titleID: titleID))game.inputs = Dictionary(uniqueKeysWithValues: model.slots.map { ($0.id, $0.paths) })game.outputDirectory = model.outDirif !model.gameDir.isEmpty { game.sourceFolder = model.gameDir }diff --git a/frontend/Sources/NX2Apple/LiveOnboardingDriver.swift b/frontend/Sources/NX2Apple/LiveOnboardingDriver.swiftindex 778069ea..acb3ad44 100644--- a/frontend/Sources/NX2Apple/LiveOnboardingDriver.swift+++ b/frontend/Sources/NX2Apple/LiveOnboardingDriver.swift@@ -1,9 +1,10 @@import AppKitimport Combineimport NXCore+import NXModelimport NXLauncher-/// UserDefaults keys of the guided setup. `platform` is also read by `BuildModel.needsIOSPlatform`.+/// UserDefaults keys of the guided setup. `platform` is also read by `LauncherStores.needsIOSPlatform`.enum OnboardingDefaults {/// An NSPB_ONBOARDING_FORCE run's platform choice, in memory only (nothing is stored until it finishes).static var sessionPlatform: String?@@ -44,9 +45,9 @@ struct OnboardingEnvironment {/// A tool without administrator rights; `line` gets its output as it comes. Returns success and the combined output.var run: (_ command: [String], _ line: @escaping (String) -> Void) async -> (ok: Bool, output: String) = { await OnboardingEnvironment.liveRun($0, $1) }/// Detection again, finished when it has published (`DependencyStore.check`).- var detectDeps: (BuildModel) async -> Void = { await $0.refreshDepsAndWait() }+ var detectDeps: (DependencyStore) async -> Void = { await $0.refreshDepsAndWait() }/// One install through the launcher's own mechanics (`DependencyStore.install`); its end shows as a new detection.- var installDep: (BuildModel, Dep) -> Void = { m, d in MainActor.assumeIsolated { _ = m.dependencies.install(d) } }+ var installDep: (DependencyStore, Dep) -> Void = { dependencies, d in MainActor.assumeIsolated { _ = dependencies.install(d) } }var openURL: (URL) -> Void = { NSWorkspace.shared.open($0) }var keyCheck: (_ keys: String, _ base: String) async -> KeyCheck.Outcome = { keys, base inawait Task.detached { KeyCheck.run(KeyCheck.Inputs(keys: keys, files: base.isEmpty ? [] : [base])) }.value@@ -157,11 +158,10 @@ enum OnboardingAdmin {}}-extension BuildModel {+extension DependencyStore {/// `DependencyStore.check()`, finished: returns once the new detection has been published.func refreshDepsAndWait() async {- let check = await MainActor.run { dependencies.check() }- await check.value+ await check().value}}@@ -175,15 +175,16 @@ enum OnboardingLaunch {static func forced(_ environment: [String: String] = ProcessInfo.processInfo.environment) -> Bool { environment["NSPB_ONBOARDING_FORCE"] == "1" }}-/// The real driver: the guided setup over the launcher's own `BuildModel` (detection and installs) and `GameLibrary`.+/// The real driver: the guided setup over the launcher's own `LauncherStores` (detection and installs) and `GameLibrary`.///-/// One value, `state`, is what the view draws. Detection comes from `model.dependencies.deps` (refreshed through `model.dependencies.check`),-/// installs run through `model.dependencies.install` one at a time, the keys and game slots are the ones the Builds page uses, and+/// One value, `state`, is what the view draws. Detection comes from `stores.dependencies.deps` (refreshed through `stores.dependencies.check`),+/// installs run through `stores.dependencies.install` one at a time, the keys and game slots are the ones the Builds page uses, and/// the games folder is the library's. Nothing about prod.keys' content is kept: the keys are checked by `KeyCheck`, and/// only their path is stored.@MainActor final class LiveOnboardingDriver: OnboardingDriver {@Published private(set) var state = OnboardingState()- let model: BuildModel+ let stores: LauncherStores+ var model: BuildStore { stores.build }let library: GameLibraryprivate let env: OnboardingEnvironment/// Called once when the setup closes: to the launcher, either way.@@ -221,14 +222,14 @@ enum OnboardingLaunch {if let target = pendingTarget { model.target = target; pendingTarget = nil }}- private func t(_ key: String) -> String { L10n.string(key, model.lang) }+ private func t(_ key: String) -> String { L10n.string(key, stores.localizer.lang) }/// `fresh` ignores a stored step (Run setup again); otherwise a stored, unfinished run resumes where it stopped./// `ephemeral` (NSPB_ONBOARDING_FORCE) starts from Welcome, keeps every preference write in memory until the player finishes/// or picks Set up later, and installs nothing until an install action is pressed, so a test leaves no trace.- init(model: BuildModel, library: GameLibrary, env: OnboardingEnvironment = OnboardingEnvironment(), fresh: Bool = false,+ init(stores: LauncherStores, library: GameLibrary, env: OnboardingEnvironment = OnboardingEnvironment(), fresh: Bool = false,ephemeral: Bool = false) {- self.model = model; self.library = library; self.env = env; self.ephemeral = ephemeral+ self.stores = stores; self.library = library; self.env = env; self.ephemeral = ephemeralinstallApproved = !ephemerallet d = env.defaultsif ephemeral {@@ -253,7 +254,7 @@ enum OnboardingLaunch {/// Starts watching the model and revalidates the stored step. Called once by whoever shows the view.func activate() {- subscription = model.dependencies.$checked.removeDuplicates().sink { [weak self] checked in+ subscription = stores.dependencies.$checked.removeDuplicates().sink { [weak self] checked inguard let self else { return }if !checked { self.sawRecheck = true; return }self.spawn("refresh") { d in await d.modelDidRefresh() }@@ -282,7 +283,7 @@ enum OnboardingLaunch {updateWelcome()backgroundStarted = truespawn("platform") { d in- await d.env.detectDeps(d.model) // the xcode row's iOS requirement just changed+ await d.env.detectDeps(d.stores.dependencies) // the xcode row's iOS requirement just changedawait d.modelDidRefresh()}}@@ -404,7 +405,7 @@ enum OnboardingLaunch {if state.selectedPlatform != nil { backgroundStarted = true }if waitingForXcode { pollForXcode() }spawn("enter.xcode") { d in- if !d.model.dependencies.checked { await d.env.detectDeps(d.model) }+ if !d.stores.dependencies.checked { await d.env.detectDeps(d.stores.dependencies) }await d.modelDidRefresh()}case .keys:@@ -425,7 +426,7 @@ enum OnboardingLaunch {/// A stored step past Xcode is only kept while Xcode and the tools still hold; otherwise the player returns to Xcode.func revalidate() async {guard state.step.index > OnboardingStep.xcode.index else { return }- if !model.dependencies.checked { await env.detectDeps(model) }+ if !stores.dependencies.checked { await env.detectDeps(stores.dependencies) }probe = await env.xcodeProbe(); probed = truelet (xcode, _) = OnboardingXcode.evaluate(probe: probe, metalReady: dep("metal")?.present ?? false,iosReady: dep("xcode")?.present ?? false, includesIOS: state.selectedPlatform?.includesIOS == true)@@ -455,11 +456,11 @@ enum OnboardingLaunch {// MARK: Xcode- private func dep(_ id: String) -> Dep? { model.dependencies.deps.first { $0.id == id } }+ private func dep(_ id: String) -> Dep? { stores.dependencies.deps.first { $0.id == id } }/// Every detection that finished: Xcode's state, the background tasks, and the next install.func modelDidRefresh() async {- guard model.dependencies.checked, state.exit == nil else { return }+ guard stores.dependencies.checked, state.exit == nil else { return }concludeInstall()await refreshXcode()recomputeBackground()@@ -521,7 +522,7 @@ enum OnboardingLaunch {}probe = await env.xcodeProbe()for task in [OnboardingSetupTask.selected, .license, .firstLaunch] { state.setup[task] = .done }- await env.detectDeps(model) // with Xcode selected, the Metal and iOS rows read differently+ await env.detectDeps(stores.dependencies) // with Xcode selected, the Metal and iOS rows read differently}let metalMissing = !(dep("metal")?.present ?? false)if metalMissing {@@ -533,7 +534,7 @@ enum OnboardingLaunch {let r = await download(.ios, Toolchain.iosPlatformCmd)if !r.ok { return fail("onboarding.error.ios", r.output) }}- await env.detectDeps(model)+ await env.detectDeps(stores.dependencies)xcodeBusy = falseawait refreshXcode()// A download that returned success but left the part missing is a failure, not an endless "set up" loop.@@ -573,14 +574,14 @@ enum OnboardingLaunch {private static let handled: Set<String> = ["xcode", "metal", "python", "dotnet"]private func deps(for task: OnboardingBackgroundTask) -> [Dep] {switch task {- case .python: return model.dependencies.deps.filter { $0.id == "python" }- case .dotnet: return model.dependencies.deps.filter { $0.id == "dotnet" }- case .tools: return model.dependencies.deps.filter { !Self.handled.contains($0.id) }+ case .python: return stores.dependencies.deps.filter { $0.id == "python" }+ case .dotnet: return stores.dependencies.deps.filter { $0.id == "dotnet" }+ case .tools: return stores.dependencies.deps.filter { !Self.handled.contains($0.id) }}}func recomputeBackground() {- guard backgroundStarted, model.dependencies.checked else { return }+ guard backgroundStarted, stores.dependencies.checked else { return }for task in OnboardingBackgroundTask.allCases {let rows = deps(for: task)if rows.allSatisfy(\.present) { state.background[task] = .done }@@ -593,14 +594,14 @@ enum OnboardingLaunch {/// One install at a time, in the order Python, .NET, tools. Homebrew and its formulas need Xcode's command line tools,/// so they wait for Xcode to be ready; the other two start at once.func pumpInstalls() {- guard installApproved, backgroundStarted, model.dependencies.checked, currentInstall == nil, state.exit == nil else { return }+ guard installApproved, backgroundStarted, stores.dependencies.checked, currentInstall == nil, state.exit == nil else { return }for task in OnboardingBackgroundTask.allCases {if task == .tools && state.xcode != .ready { continue }guard let next = deps(for: task).first(where: { !$0.present && failedDeps[$0.id] == nil && !$0.installing }) else { continue }currentInstall = next.idsawRecheck = falselogMark = model.logTail.count- env.installDep(model, next)+ env.installDep(stores.dependencies, next)recomputeBackground()return}@@ -656,7 +657,7 @@ enum OnboardingLaunch {func scanGames(_ url: URL) async {let scoped = url.startAccessingSecurityScopedResource()defer { if scoped { url.stopAccessingSecurityScopedResource() } }- let found = await env.scanGames(url, model.repoPath)+ let found = await env.scanGames(url, stores.repo.path)guard state.exit == nil else { return }guard !found.isEmpty else { state.games = .none; return }// The same slots and folder the main UI sets: the Builds page's inputs and the library's games folder.@@ -666,13 +667,13 @@ enum OnboardingLaunch {library.setFolder(url)if !model.running { model.outDir = url.path }state.games = .found(found.map { OnboardingGame(id: $0.titleID, title: $0.name, version: "",- cover: GameLibrary.artwork(for: $0, repo: model.repoPath)) })+ cover: GameLibrary.artwork(for: $0, repo: stores.repo.path)) })let ids = found.map(\.titleID)spawn("covers") { d inawait d.env.fetchArtwork(ids)guard case .found(var games) = d.state.games else { return }for i in games.indices where games[i].cover == nil {- if let g = found.first(where: { $0.titleID == games[i].id }) { games[i].cover = GameLibrary.artwork(for: g, repo: d.model.repoPath) }+ if let g = found.first(where: { $0.titleID == games[i].id }) { games[i].cover = GameLibrary.artwork(for: g, repo: d.stores.repo.path) }}d.state.games = .found(games)}diff --git a/frontend/Sources/NX2Apple/OnboardingRoot.swift b/frontend/Sources/NX2Apple/OnboardingRoot.swiftindex 383734d9..ff228fe0 100644--- a/frontend/Sources/NX2Apple/OnboardingRoot.swift+++ b/frontend/Sources/NX2Apple/OnboardingRoot.swift@@ -1,20 +1,21 @@import SwiftUIimport NXCore+import NXModelimport NXLauncher-/// The window's content: the launcher, or the guided setup before it. It owns the one `BuildModel` and `GameLibrary` both use,+/// The window's content: the launcher, or the guided setup before it. It owns the one `LauncherStores` and `GameLibrary` both use,/// so what the setup detects, installs and chooses is what the launcher shows.struct RootView: View {private enum Mode { case checking, onboarding, launcher }/// Holds the two objects without publishing, so this view does not redraw with every line of a build log.@MainActor private final class Shared: ObservableObject {- let model = BuildModel(); let library = GameLibrary(); let controls = ControlLayout()+ let stores = LauncherStores(); let library = GameLibrary(); let controls = ControlLayout()/// The console mode's driver over this window's model, library and controls.- lazy var console = LiveConsoleDriver(library: library, controls: controls, repo: { [model] in model.repoPath }, lang: { [model] in model.lang },- labels: { [model] in model.t($0) })+ lazy var console = LiveConsoleDriver(library: library, controls: controls, repo: { [stores] in stores.repo.path }, lang: { [stores] in stores.localizer.lang },+ labels: { [stores] in stores.localizer.t($0) })}@StateObject private var shared = Shared()- private var model: BuildModel { shared.model }+ private var stores: LauncherStores { shared.stores }private var library: GameLibrary { shared.library }@State private var mode: Mode = .checking@State private var driver: LiveOnboardingDriver?@@ -27,15 +28,15 @@ struct RootView: View {case .checking:LauncherPalette.background.overlay(ProgressView().controlSize(.small))case .onboarding:- if let driver { OnboardingView(driver: driver, lang: model.lang, gamepad: gamepad) }+ if let driver { OnboardingView(driver: driver, lang: stores.localizer.lang, gamepad: gamepad) }case .launcher:ZStack {if console.active {- ConsoleView(driver: shared.console, lang: model.lang, onExit: { console.exit(); shared.console.returnFromGame() })+ ConsoleView(driver: shared.console, lang: stores.localizer.lang, onExit: { console.exit(); shared.console.returnFromGame() }).onAppear { shared.console.reloadCovers() }.transition(CalmTransition.console)} else {- ContentView(model: model, library: library, onRunSetup: runSetupAgain, enterConsole: { console.enter() },+ ContentView(stores: stores, library: library, onRunSetup: runSetupAgain, enterConsole: { console.enter() },controllerDriver: AnyConsoleDriver(shared.console), controls: shared.controls).transition(CalmTransition.desktop)}@@ -62,11 +63,11 @@ struct RootView: View {// NSPB_ONBOARDING_FORCE=1: the real flow with real detection whatever the state, leaving no trace until it is finishedif OnboardingLaunch.forced() { show(fresh: false, ephemeral: true); return }if defaults.bool(forKey: OnboardingDefaults.completed) { mode = .launcher; return }- await model.refreshDepsAndWait()+ await stores.dependencies.refreshDepsAndWait()let env = OnboardingEnvironment()- let keysKnown = model.slot("keys").ok || !env.keyCandidates(gamesFolder: library.folder).isEmpty || library.games.contains(where: \.isReady)+ let keysKnown = stores.build.slot("keys").ok || !env.keyCandidates(gamesFolder: library.folder).isEmpty || library.games.contains(where: \.isReady)let gamesKnown = !library.folder.isEmpty || !library.games.isEmpty- let complete = OnboardingLaunch.setupComplete(depsPresent: model.dependencies.allPresent, keysKnown: keysKnown, gamesKnown: gamesKnown)+ let complete = OnboardingLaunch.setupComplete(depsPresent: stores.dependencies.allPresent, keysKnown: keysKnown, gamesKnown: gamesKnown)if OnboardingLaunch.shouldShow(completed: false, setupComplete: complete) {show(fresh: false)} else {@@ -76,7 +77,7 @@ struct RootView: View {}private func show(fresh: Bool, ephemeral: Bool = false) {- let d = LiveOnboardingDriver(model: model, library: library, fresh: fresh, ephemeral: ephemeral)+ let d = LiveOnboardingDriver(stores: stores, library: library, fresh: fresh, ephemeral: ephemeral)d.onExit = { _ in mode = .launcher; driver = nil }driver = dmode = .onboardingdiff --git a/frontend/Sources/NX2Apple/SaveTransfer.swift b/frontend/Sources/NX2Apple/SaveTransfer.swiftindex 4953ae1c..da2dbdc3 100644--- a/frontend/Sources/NX2Apple/SaveTransfer.swift+++ b/frontend/Sources/NX2Apple/SaveTransfer.swift@@ -342,7 +342,7 @@ struct SaveTransfer {/// The Saves sheet: the game's save on this Mac and on the device it was installed on, which is newer, and a copy either way./// A copy asks first, in the sheet itself (a controller reaches it), and says where the save it replaced went.struct SavesView: View {- @ObservedObject var m: BuildModel+ @ObservedObject var m: BuildStore@EnvironmentObject var loc: Localizer@ObservedObject var library: GameLibrarylet gameID: UUID@@ -357,21 +357,21 @@ struct SavesView: View {/// `devicectl` and `listDevices` are what tests and the visual QA hand in as stand-ins: with a stand-in devicectl and no/// device list, the devices are the ones the launcher already knows, so nothing asks the system for them.- init(m: BuildModel, library: GameLibrary, gameID: UUID, devicectl: DeviceControl? = nil, support: URL? = nil,+ init(m: BuildStore, library: GameLibrary, gameID: UUID, devicectl: DeviceControl? = nil, support: URL? = nil,listDevices: (() -> [AppleDevice])? = nil, timeout: TimeInterval = 30) {self.m = m; self.library = library; self.gameID = gameID; self.support = supportlet game = library.games.first { $0.id == gameID } ?? LibraryGame(titleID: "", name: "")let mac = support.map { SaveTransfer.macSave(titleID: game.titleID, appPath: game.appPath, support: $0) }?? SaveTransfer.macSave(titleID: game.titleID, appPath: game.appPath)- let control = devicectl ?? .xcrun(m.xcrunPath, runner: m.runner)+ let control = devicectl ?? .xcrun(m.devices.xcrun, runner: m.runner)let template = SaveTransfer(titleID: game.titleID, macSave: mac.save, legacySave: mac.legacy, device: "", bundle: "", devicectl: control)- let known = MainActor.assumeIsolated { m.deviceStore.devices }, xcrun = m.xcrunPath, runner = m.runner+ let known = m.devices.devices, xcrun = m.devices.xcrun, runner = m.runnerlet list: () -> [AppleDevice] = listDevices ?? (devicectl == nil ? { DeviceTools.devices(xcrun: xcrun, timeout: 10, runner: runner) } : { known })let key = "saveTransfer.device." + game.titleID_model = StateObject(wrappedValue: SavesModel(template: template, name: game.name,recordedBundle: NSDictionary(contentsOfFile: game.iosAppPath + "/Info.plist")?["CFBundleIdentifier"] as? String,- recordedDevice: game.installedDevice, installTarget: m.installDevice,+ recordedDevice: game.installedDevice, installTarget: m.devices.installDevice,remembered: UserDefaults.standard.string(forKey: key) ?? "",rememberChoice: { UserDefaults.standard.set($0, forKey: key) },listDevices: list, timeout: timeout))@@ -390,7 +390,7 @@ struct SavesView: View {}}/// The device the sheet asks: its name, or what the launcher recorded when the list has not come yet.- private var deviceName: String { model.selectedDevice?.name ?? game.map { m.deviceName($0.installedDevice) } ?? "iPhone" }+ private var deviceName: String { model.selectedDevice?.name ?? game.map { m.devices.deviceName($0.installedDevice) } ?? "iPhone" }private var transfer: SaveTransfer { model.found ?? model.template }var body: some View {diff --git a/frontend/Sources/NX2Apple/ShellCLI.swift b/frontend/Sources/NX2Apple/ShellCLI.swiftnew file mode 100644index 00000000..d1728fa7--- /dev/null+++ b/frontend/Sources/NX2Apple/ShellCLI.swift@@ -0,0 +1,52 @@+import Foundation+import NXCore++/// `NSPortBuilder --install-shell ...`: steps 3 to 7 without a window and without questions, for a terminal or a script.+enum ShellCLI {+ static let usage = "NSPortBuilder --install-shell --framework <path> --archive <games/TITLEID folder> --title-id <id> --name <name> "+ + "--device <udid> --team <team> --repo <repo> [--shell-root <dir>] [--python <path>]"++ /// The options as a dictionary, nil when an option has no value.+ static func parse(_ args: [String]) -> [String: String]? {+ var options: [String: String] = [:]+ var i = 0+ while i < args.count {+ let a = args[i]+ if a == "--install-shell" { i += 1; continue }+ guard a.hasPrefix("--"), i + 1 < args.count else { return nil }+ options[String(a.dropFirst(2))] = args[i + 1]+ i += 2+ }+ return options+ }++ /// Exit status: 0 installed, 1 failed (or wrong usage). `out` gets every line, stage lines and tool output alike.+ /// `--xcrun` is for the tests, which stand in for xcodebuild and devicectl.+ static func run(_ args: [String], defaults: UserDefaults = .standard, out: @escaping (String) -> Void = { fputs($0, stdout); fflush(stdout) }) -> Int32 {+ let required = ["framework", "archive", "title-id", "name", "device", "team", "repo"]+ guard let o = parse(args), required.allSatisfy({ !(o[$0] ?? "").isEmpty }) else {+ out("usage: " + usage + "\n")+ return 1+ }+ let archive = o["archive"]!+ let root = o["shell-root"] ?? ShellLibrary.resolveRoot(+ defaults: defaults, parent: ((archive as NSString).deletingLastPathComponent as NSString).deletingLastPathComponent)+ let python = o["python"] ?? Toolchain.findPython().path+ var installer = ShellInstaller(xcrun: o["xcrun"] ?? "/usr/bin/xcrun", repo: o["repo"]!, python: python, root: root,+ device: o["device"]!, team: o["team"]!)+ installer.deviceName = o["device"]!+ installer.toolPath = BundledTools.path("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", python: python)+ installer.log = out+ installer.stage = { s in+ switch s.state {+ case .running: if s.detail.isEmpty { out("==> \(s.name)\n") }+ case .done: out("==> \(s.name): done\n")+ case .failed: out("==> \(s.name): FAILED \(s.detail)\n")+ case .pending: break+ }+ }+ let result = installer.install(framework: o["framework"]!, titleID: o["title-id"]!, name: o["name"]!, archive: archive)+ out((result.ok ? "OK: " : "FAIL: ") + result.message + "\n")+ return result.ok ? 0 : 1+ }+}diff --git a/frontend/Sources/NX2Apple/StaleFrameworksPrompt.swift b/frontend/Sources/NX2Apple/StaleFrameworksPrompt.swiftindex f3953761..7392d7ab 100644--- a/frontend/Sources/NX2Apple/StaleFrameworksPrompt.swift+++ b/frontend/Sources/NX2Apple/StaleFrameworksPrompt.swift@@ -2,57 +2,8 @@ import SwiftUIimport NXCoreimport NXModel-// LNPANDY/NX2Apple#449: a build for the iPhone or iPad asks before the long steps when the shell folder holds frameworks of-// another shader chain than the engine this build uses. Stop leaves every file as it is. Continue deletes the stale frameworks-// (and their entries in the shell's library) and starts the build again. Without stale frameworks nothing is asked. A framework-// whose chain cannot be read is not decided here, build_shell.sh's own check at the last step stays for it.--extension BuildModel {- /// The stale frameworks of the shared app for the engine this build runs, nothing when the check cannot decide.- func staleFrameworkEntries() -> [StaleFrameworks.Entry] {- guard let chain = StaleFrameworks.currentChain(engineRoot: EngineLayout.root(repoPath)) else { return [] }- let root = shellRoot- let known = ShellLibrary.load(root: root).games.map { (titleID: $0.titleID, name: $0.name, framework: $0.framework) }- return StaleFrameworks.find(root: root, chain: chain, known: known, except: TitleID.buildKey(basePath))- }-- /// True when the build must wait for the player's answer: the prompt is showing (`staleFrameworks` is set).- func askAboutStaleFrameworks() -> Bool {- let entries = staleFrameworkEntries()- guard !entries.isEmpty else { return false }- staleFrameworks = entries- return true- }-- /// Stop the build: nothing was touched.- func stopForStaleFrameworks() { staleFrameworks = [] }-- /// Continue: delete the stale frameworks, drop their games from the shell's library, and start the build.- func continueWithStaleFrameworks(then start: (() -> Void)? = nil) {- let entries = staleFrameworks- staleFrameworks = []- let failed = Self.removeStaleFrameworks(entries, root: shellRoot)- if !failed.isEmpty {- done = false- doneNote = String(format: t("stale.removeFailed"), failed.map { ($0 as NSString).lastPathComponent }.joined(separator: ", "))- return- }- (start ?? startBuild)()- }-- /// The folders of `entries` are deleted and the games leave `<root>/shell.json`. Returns the folders that could not be deleted.- static func removeStaleFrameworks(_ entries: [StaleFrameworks.Entry], root: String) -> [String] {- let failed = StaleFrameworks.remove(entries)- var library = ShellLibrary.load(root: root)- let gone = Set(entries.map { $0.titleID.lowercased() })- library.games.removeAll { gone.contains($0.titleID.lowercased()) }- try? library.save(root: root)- return failed- }-}-private struct StaleFrameworksPrompt: ViewModifier {- @ObservedObject var m: BuildModel+ @ObservedObject var m: BuildStore@EnvironmentObject var loc: Localizerfunc body(content: Content) -> some View {@@ -67,5 +18,5 @@ private struct StaleFrameworksPrompt: ViewModifier {}extension View {- func staleFrameworksPrompt(_ m: BuildModel) -> some View { modifier(StaleFrameworksPrompt(m: m)) }+ func staleFrameworksPrompt(_ m: BuildStore) -> some View { modifier(StaleFrameworksPrompt(m: m)) }}diff --git a/frontend/Sources/NXCore/BannerCache.swift b/frontend/Sources/NXCore/BannerCache.swiftnew file mode 100644index 00000000..3387b423--- /dev/null+++ b/frontend/Sources/NXCore/BannerCache.swift@@ -0,0 +1,14 @@+import Foundation++/// Where the eShop banners are cached (the launcher's `ArtworkStore` downloads them). The shared app's install reads them to put a+/// game's banner into its framework, so the folder and the lookup are here, with no AppKit.+package enum BannerCache {+ package static let directory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+ .appendingPathComponent("NS Port Builder/artwork")++ /// Where a title's banner is kept; nil while it has none.+ package static func cached(_ titleID: String, in directory: URL = BannerCache.directory) -> URL? {+ let url = directory.appendingPathComponent(titleID.uppercased() + ".jpg")+ return FileManager.default.fileExists(atPath: url.path) ? url : nil+ }+}diff --git a/frontend/Sources/NXCore/BuildArchive.swift b/frontend/Sources/NXCore/BuildArchive.swiftnew file mode 100644index 00000000..ccbd19b7--- /dev/null+++ b/frontend/Sources/NXCore/BuildArchive.swift@@ -0,0 +1,75 @@+import Foundation++/// The RomFS tree a build extracts and the stamp that lets the next build skip the pack (pure file-system functions).+package enum RomFSArchive {+ /// (file count, bytes) of a RomFS tree — the reuse fingerprint's content part.+ package nonisolated static func treeStats(_ dir: String) -> (count: Int, bytes: Int)? {+ let fm = FileManager.default+ guard let en = fm.enumerator(atPath: dir) else { return nil }+ var count = 0, bytes = 0+ while let rel = en.nextObject() as? String {+ let s = ((try? fm.attributesOfItem(atPath: dir + "/" + rel))?[.size] as? Int) ?? 0+ count += 1; bytes += s+ }+ return (count, bytes)+ }++ package nonisolated static func writeStamp(source: String, version: String, to path: String) {+ guard let s = treeStats(source) else { return }+ try? FileManager.default.createDirectory(atPath: (path as NSString).deletingLastPathComponent,+ withIntermediateDirectories: true)+ try? "\(version)\t\(s.count)\t\(s.bytes)".write(toFile: path, atomically: true, encoding: .utf8)+ }++ /// The stamped (version, count, bytes) versus the source tree's now: nil = pack again.+ /// The newest version folder the extraction wrote, or nil when it wrote none.+ ///+ /// Either shape counts: RomFS/ from the older tools, RomFS.img from the current ones (the+ /// rewriter packs the game files itself — build_ipa_from_nsp.py:876 tests for the image).+ /// Looking only for the folder made every 0.4.8 build report "archive skipped" after a+ /// successful extraction (issue #73).+ package nonisolated static func extractedVersion(in extract: String) -> String? {+ let fm = FileManager.default+ return ((try? fm.contentsOfDirectory(atPath: extract)) ?? [])+ .filter { $0.hasPrefix("v") && (fm.fileExists(atPath: extract + "/" + $0 + "/RomFS") ||+ fm.fileExists(atPath: extract + "/" + $0 + "/RomFS.img")) }+ .sorted { (Int($0.dropFirst()) ?? 0) < (Int($1.dropFirst()) ?? 0) }+ .last+ }++ package nonisolated static func archiveReusable(source: String, version: String, stamp: String) -> Int? {+ guard let s = treeStats(source) else { return nil }+ let parts = stamp.split(separator: "\t")+ guard parts.count == 3, parts[0] == version,+ Int(parts[1]) == s.count, Int(parts[2]) == s.bytes else { return nil }+ return s.count+ }++ /// Replace `to` with a copy of `from` when `from` exists. Returns how many entries `to` holds afterwards.+ package nonisolated static func copyAddOnContent(from: String, to: String) -> Int {+ let fm = FileManager.default+ guard fm.fileExists(atPath: from) else { return 0 }+ try? fm.removeItem(atPath: to)+ try? fm.copyItem(atPath: from, toPath: to)+ return ((try? fm.contentsOfDirectory(atPath: to)) ?? []).count+ }+}++/// The command lines and the PATH of the build's tools.+package enum BuildCommands {+ /// The PATH of the processes that run the build, installing packages and writing the RomFS image: the bundled tools in front of+ /// `base` (BundledTools.swift), which is Homebrew's folders and the system's. One place, so that no environment forgets the bundle.+ package nonisolated static func toolPath(_ base: String = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin", python: String? = nil) -> String {+ BundledTools.path(base, python: python)+ }++ package nonisolated static func reinstallCommand(xcrun: String, device: String, app: String) -> [String] {+ [xcrun, "devicectl", "device", "install", "app", "--device", device, app]+ }++ /// ditto writes the archive the way Finder's "compress" does; the IPA's root must be Payload/, and --norsrc keeps+ /// __MACOSX out (the signature itself lives in _CodeSignature inside the app).+ package nonisolated static func ipaCommand(payload: String, ipa: String) -> [String] {+ ["/usr/bin/ditto", "-c", "-k", "--norsrc", "--keepParent", payload, ipa]+ }+}diff --git a/frontend/Sources/NX2Apple/BuildFailure.swift b/frontend/Sources/NXCore/BuildFailureClassifier.swiftsimilarity index 81%rename from frontend/Sources/NX2Apple/BuildFailure.swiftrename to frontend/Sources/NXCore/BuildFailureClassifier.swiftindex 66e01450..9abea799 100644--- a/frontend/Sources/NX2Apple/BuildFailure.swift+++ b/frontend/Sources/NXCore/BuildFailureClassifier.swift@@ -1,13 +1,12 @@import Foundation-import NXCore-enum BuildFailureClassifier {+package enum BuildFailureClassifier {/// One row per message of the script. The pattern is a stable part of the text in scripts/build_ipa_from_nsp.py,/// dm/gfx/tools/own_compilers.py or dm/tools/nx_extract/Program.cs (regular expressions, searched in the log)./// Frontend/Tests/Fixtures/build_failures.json holds the real message for every row, and a test checks that each/// fragment is still in the engine's script, so a sync that rewords a message fails there instead of turning a/// hint into the raw last line. The Qt front end has the same table (nspb_qt/build_failure.py, compared by a test).- static let table: [(id: String, kind: BuildFailureKind, pattern: String)] = [+ package static let table: [(id: String, kind: BuildFailureKind, pattern: String)] = [("rosetta.intel", .rosetta, "is an Intel one running under Rosetta"),("translator.run", .translator, "the shader translator does not run"),("translator.start", .translator, "the shader translator does not start"),@@ -28,16 +27,21 @@ enum BuildFailureClassifier {/// What the launcher itself knows when the log says nothing it can use. The keys file and the game files are checked/// first: a drive that is not connected makes every later message ("not a folder", a dangling link) a consequence.- struct Inputs {- var keysPath = ""- var paths: [String] = [] // the picked game files and the game folder- var volumes = "/Volumes"- var isReadable: (String) -> Bool = { FileManager.default.isReadableFile(atPath: $0) }+ package struct Inputs {+ package var keysPath = ""+ package var paths: [String] = [] // the picked game files and the game folder+ package var volumes = "/Volumes"+ package var isReadable: (String) -> Bool = { FileManager.default.isReadableFile(atPath: $0) }++ package init(keysPath: String = "", paths: [String] = [], volumes: String = "/Volumes",+ isReadable: @escaping (String) -> Bool = { FileManager.default.isReadableFile(atPath: $0) }) {+ self.keysPath = keysPath; self.paths = paths; self.volumes = volumes; self.isReadable = isReadable+ }}/// `unknown` when no row matches: the caller then keeps showing the last line of the log.- static func classify(_ log: String, inputs: Inputs = Inputs()) -> BuildFailure {- for path in [inputs.keysPath] + inputs.paths where !path.isEmpty && GameLibrary.onUnmountedVolume(path, volumes: inputs.volumes) {+ package static func classify(_ log: String, inputs: Inputs = Inputs()) -> BuildFailure {+ for path in [inputs.keysPath] + inputs.paths where !path.isEmpty && VolumePath.onUnmounted(path, volumes: inputs.volumes) {let prefix = inputs.volumes.hasSuffix("/") ? inputs.volumes : inputs.volumes + "/"let name = path.dropFirst(prefix.count).split(separator: "/").first.map(String.init)return BuildFailure(kind: .driveMissing, gameName: nil, detail: name)@@ -65,11 +69,11 @@ enum BuildFailureClassifier {/// A step of the install on a device that failed, with the tool's last error line. The sign step's own retry (the team's/// variant of the bundle ID) has run already when this is called.- enum InstallStep { case sign, install, copy }+ package enum InstallStep { case sign, install, copy }/// nil when the launcher has no better words than the tool's own line. `teamListed`: whether the chosen team is still one/// the Mac knows (an account signed in to Xcode, or a development certificate in the keychain).- static func classifyInstall(_ step: InstallStep, error: String, teamListed: Bool) -> BuildFailure? {+ package static func classifyInstall(_ step: InstallStep, error: String, teamListed: Bool) -> BuildFailure? {if error.contains("No space left on device") { return BuildFailure(kind: .diskFull, gameName: nil) }switch step {case .sign:@@ -81,12 +85,12 @@ enum BuildFailureClassifier {}/// xcodebuild's words when the app's identifier is registered to another team.- static func signingTeamTaken(_ error: String) -> Bool {+ package static func signingTeamTaken(_ error: String) -> Bool {error.contains("cannot be registered to your development team") || error.contains("No profiles for 'org.nxnative.")}/// "<name> (<title ID>) is a 32-bit ARM program": the name is "?" when the extraction has none.- static func gameName(in log: String) -> String? {+ package static func gameName(in log: String) -> String? {guard let r = log.range(of: #"(?m)^(?:\[RED\] )?.+? \([0-9A-Fa-f]{16}\) is a 32-bit ARM program"#, options: .regularExpression) else { return nil }var line = String(log[r])if line.hasPrefix("[RED] ") { line.removeFirst(6) }@@ -96,7 +100,7 @@ enum BuildFailureClassifier {}/// The build arguments with the one-off override added: exactly one `--allow-*`, or none.- static func arguments(_ args: [String], adding flag: String?) -> [String] {+ package static func arguments(_ args: [String], adding flag: String?) -> [String] {let rest = args.filter { !$0.hasPrefix("--allow-") }guard let flag, flag.hasPrefix("--allow-") else { return rest }return rest + [flag]diff --git a/frontend/Sources/NXCore/EngineManifest.swift b/frontend/Sources/NXCore/EngineManifest.swiftindex c2d3ea8e..96c119ff 100644--- a/frontend/Sources/NXCore/EngineManifest.swift+++ b/frontend/Sources/NXCore/EngineManifest.swift@@ -7,7 +7,7 @@ import Foundation/// The player no longer fetches the repository: the release ships an engine tree — the repository minus/// the launcher sources (`dm/`, `scripts/`, `docs/`, `ref/`, `.upstream-ref`, `dm/fork_patches.txt`) —/// and the launcher unpacks it next to its own Application Support folder. That folder then *is* the-/// checkout the build reads (`BuildModel.repoPath`), so `isRepo`, the build script and the RomFS tool+/// checkout the build reads (`RepoStore.path`), so `isRepo`, the build script and the RomFS tool/// keep working unchanged.////// Two channels, one manifest shape: `stable` is the engine that shipped with this release, `experimental` is thediff --git a/frontend/Sources/NXCore/EngineUpdater.swift b/frontend/Sources/NXCore/EngineUpdater.swiftindex e998d6ce..17fec41e 100644--- a/frontend/Sources/NXCore/EngineUpdater.swift+++ b/frontend/Sources/NXCore/EngineUpdater.swift@@ -208,7 +208,7 @@ package protocol EngineTransport {func download(from url: URL, to destination: URL) -> Bool}-/// URLSession, waited on from a background queue as the app update does (BuildModel.downloadAndStage).+/// URLSession, waited on from a background queue as the app update does (AppUpdateStore)./// Nothing is cached: the experimental release replaces its files under the same names.package struct URLSessionEngineTransport: EngineTransport {private let session: URLSession = {diff --git a/frontend/Sources/NX2Apple/ShellInstall.swift b/frontend/Sources/NXCore/ShellInstall.swiftsimilarity index 79%rename from frontend/Sources/NX2Apple/ShellInstall.swiftrename to frontend/Sources/NXCore/ShellInstall.swiftindex 9d957bed..1da8cc06 100644--- a/frontend/Sources/NX2Apple/ShellInstall.swift+++ b/frontend/Sources/NXCore/ShellInstall.swift@@ -1,6 +1,4 @@import Foundation-import NXCore-import NXLauncher// Route C: one app on the iPhone or iPad that holds several games. The build script makes only each game's framework// (`--shell-framework`), and this file does the rest: the shell's library file (shell.json), the shell's Xcode project@@ -9,43 +7,49 @@ import NXLauncher// runs under the build model (on a background queue) and from the terminal (`NSPortBuilder --install-shell`)./// The shell's library: which games are in it, and the bundle ID the app has on the device. It lives in `<shell root>/shell.json`.-struct ShellLibrary: Codable, Equatable {- struct Game: Codable, Equatable {- var titleID: String- var name: String- var framework: String+package struct ShellLibrary: Codable, Equatable {+ package struct Game: Codable, Equatable {+ package var titleID: String+ package var name: String+ package var framework: String++ package init(titleID: String, name: String, framework: String) { self.titleID = titleID; self.name = name; self.framework = framework }+ }++ package init(bundleID: String = ShellLibrary.defaultBundleID, team: String = "", games: [Game] = []) {+ self.bundleID = bundleID; self.team = team; self.games = games}- static let defaultBundleID = "org.nxnative.shell"+ package static let defaultBundleID = "org.nxnative.shell"- var bundleID = ShellLibrary.defaultBundleID- var team = ""- var games: [Game] = []+ package var bundleID = ShellLibrary.defaultBundleID+ package var team = ""+ package var games: [Game] = []/// The identifier a team falls back to when `org.nxnative.shell` is registered to another team (the same per-team variant the/// per-game install uses). Once stored in shell.json it stays: the app's Documents (game data, saves) belong to the identifier.- static func teamVariant(team: String) -> String { defaultBundleID + "." + team }+ package static func teamVariant(team: String) -> String { defaultBundleID + "." + team }/// Adding a game replaces the entry with the same title ID (a rebuilt game has a new framework folder), otherwise appends.- mutating func add(_ game: Game) {+ package mutating func add(_ game: Game) {if let i = games.firstIndex(where: { $0.titleID == game.titleID }) { games[i] = game } else { games.append(game) }}/// Drops the games whose framework folder is gone, so the shell is never built against a missing one.- mutating func dropMissing(exists: (String) -> Bool = { FileManager.default.fileExists(atPath: $0) }) {+ package mutating func dropMissing(exists: (String) -> Bool = { FileManager.default.fileExists(atPath: $0) }) {games = games.filter { exists($0.framework) }}- static func stateFile(root: String) -> String { root + "/shell.json" }+ package static func stateFile(root: String) -> String { root + "/shell.json" }/// The file's library, or a fresh one when there is none (or it cannot be read: the next save writes a valid one).- static func load(root: String) -> ShellLibrary {+ package static func load(root: String) -> ShellLibrary {guard let data = FileManager.default.contents(atPath: stateFile(root: root)),let library = try? JSONDecoder().decode(ShellLibrary.self, from: data) else { return ShellLibrary() }return library}- func save(root: String) throws {+ package func save(root: String) throws {try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true)let encoder = JSONEncoder()encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]@@ -54,7 +58,7 @@ struct ShellLibrary: Codable, Equatable {/// The shell root: the saved one (`shellRoot` in `defaults`), else `<parent>/NX2Apple-shell`, which is then saved so the shell/// stays where it was first made, whatever output folder a later build uses.- static func resolveRoot(defaults: UserDefaults = .standard, parent: String) -> String {+ package static func resolveRoot(defaults: UserDefaults = .standard, parent: String) -> String {if let saved = defaults.string(forKey: "shellRoot"), !saved.isEmpty { return saved }let root = parent + "/NX2Apple-shell"defaults.set(root, forKey: "shellRoot")@@ -63,25 +67,25 @@ struct ShellLibrary: Codable, Equatable {}/// The commands and parsers of the shell install, as pure functions.-enum ShellInstall {- static let appName = "DmShell.app"- static let scheme = "DmShell"- static let projectName = "DmShell.xcodeproj"+package enum ShellInstall {+ package static let appName = "DmShell.app"+ package static let scheme = "DmShell"+ package static let projectName = "DmShell.xcodeproj"- static func projectFolder(root: String) -> String { root + "/project" }- static func derivedData(root: String) -> String { root + "/derived-data" }- static func appPath(root: String) -> String { derivedData(root: root) + "/Build/Products/Release-iphoneos/" + appName }+ package static func projectFolder(root: String) -> String { root + "/project" }+ package static func derivedData(root: String) -> String { root + "/derived-data" }+ package static func appPath(root: String) -> String { derivedData(root: root) + "/Build/Products/Release-iphoneos/" + appName }/// The folder that mirrors every game's framework inside the shell folder: a game survives its build folder's deletion here.- static func frameworksMirror(root: String) -> String { root + "/frameworks" }- static func mirroredFramework(root: String, titleID: String) -> String {+ package static func frameworksMirror(root: String) -> String { root + "/frameworks" }+ package static func mirroredFramework(root: String, titleID: String) -> String {frameworksMirror(root: root) + "/DmGame\(titleID).framework"}/// Mirrors a framework into the shell folder as a copy. On APFS the copy is a clone: it costs no space, and a later write to/// the build folder does not reach it. On another volume it is a real copy. It replaces the previous mirror, so a rebuilt/// game's mirror follows, and a failed copy leaves no half mirror behind.- static func mirrorFramework(framework: String, root: String, titleID: String? = nil) throws {+ package static func mirrorFramework(framework: String, root: String, titleID: String? = nil) throws {let fm = FileManager.defaultlet mirror = mirroredFramework(root: root, titleID: titleID ?? Self.titleID(ofFramework: framework))try fm.createDirectory(atPath: (mirror as NSString).deletingLastPathComponent, withIntermediateDirectories: true)@@ -94,38 +98,38 @@ enum ShellInstall {}/// The title ID a framework path carries (`DmGame0100…framework`, the build script's name).- static func titleID(ofFramework framework: String) -> String {+ package static func titleID(ofFramework framework: String) -> String {let name = (framework as NSString).lastPathComponentreturn name.hasPrefix("DmGame") && name.hasSuffix(".framework")? String(name.dropFirst("DmGame".count).dropLast(".framework".count)) : ""}/// The framework the build script's `--shell-framework <folder>` writes for a game.- static func frameworkPath(workDir: String, titleID: String) -> String {+ package static func frameworkPath(workDir: String, titleID: String) -> String {workDir + "/shell-framework/DmGame\(titleID).framework"}/// The part of the build script's argument list that makes the game's framework instead of an Xcode project.- static func buildArguments(workDir: String, team: String) -> [String] {+ package static func buildArguments(workDir: String, team: String) -> [String] {["--shell-framework", workDir + "/shell-framework", "--team-id", team]}// ---- 4: the project ----- static func projectCommand(repo: String) -> [String] {+ package static func projectCommand(repo: String) -> [String] {["/bin/bash", repo + "/dm/ios/tools/build_shell.sh", "--prepare-xcode"]}/// The `frontend-ios` Swift package the shell project links (build_shell.sh's DM_SHELL_PACKAGE). The script defaults to/// `frontend-ios` beside `dm/`, which is the engine root, and an engine tree has none since #214. So: the release app's/// Contents/Resources/frontend-ios, else the source checkout's `frontend-ios` (`repo`). nil when neither has a Package.swift.- static func shellPackage(resources: String?, repo: String, fm: FileManager = .default) -> String? {+ package static func shellPackage(resources: String?, repo: String, fm: FileManager = .default) -> String? {([resources, repo].compactMap { $0 }.filter { !$0.isEmpty }).map { $0 + "/frontend-ios" }.first { fm.fileExists(atPath: $0 + "/Package.swift") }}/// What build_shell.sh reads. `path` is the build's own tool PATH (xcodegen must be found on it).- static func projectEnvironment(root: String, frameworks: [String], bundleID: String, team: String, python: String,+ package static func projectEnvironment(root: String, frameworks: [String], bundleID: String, team: String, python: String,path: String, home: String, user: String, tmp: String? = nil, package: String? = nil) -> [String: String] {var env = ["SHELL_DIR": projectFolder(root: root),"DM_SHELL_FRAMEWORKS": frameworks.joined(separator: "\n"),@@ -143,32 +147,32 @@ enum ShellInstall {/// `bundleID` goes in as PRODUCT_BUNDLE_IDENTIFIER every time: the identifier stored in shell.json is the one the device's/// copy of the app has, and installing under another would start an app with empty Documents.- static func buildCommand(xcrun: String, root: String, device: String, team: String, bundleID: String) -> [String] {+ package static func buildCommand(xcrun: String, root: String, device: String, team: String, bundleID: String) -> [String] {[xcrun, "xcodebuild", "-project", projectFolder(root: root) + "/" + projectName, "-scheme", scheme,"-configuration", "Release", "-destination", "id=\(device)", "-derivedDataPath", derivedData(root: root),"-allowProvisioningUpdates", "DEVELOPMENT_TEAM=\(team)", "PRODUCT_BUNDLE_IDENTIFIER=\(bundleID)", "build"]}/// Installing over the existing app keeps its Documents.- static func installCommand(xcrun: String, device: String, app: String) -> [String] {+ package static func installCommand(xcrun: String, device: String, app: String) -> [String] {[xcrun, "devicectl", "device", "install", "app", "--device", device, app]}// ---- 7: the game data ----- static func gameFolder(titleID: String) -> String { "Documents/games/\(titleID)" }+ package static func gameFolder(titleID: String) -> String { "Documents/games/\(titleID)" }/// Kept free beyond the data on the device (the game's saves, shader caches, the system).- static let freeSpaceMargin: Int64 = 2_000_000_000+ package static let freeSpaceMargin: Int64 = 2_000_000_000/// The shell's own log from the device (Documents/shell-log.txt, written at every start).- static func shellLogCommand(xcrun: String, device: String, bundleID: String, destination: String) -> [String] {+ package static func shellLogCommand(xcrun: String, device: String, bundleID: String, destination: String) -> [String] {[xcrun, "devicectl", "device", "copy", "from", "--device", device, "--domain-type", "appDataContainer","--domain-identifier", bundleID, "--source", "Documents/shell-log.txt", "--destination", destination]}/// The last "shell: free space <bytes> bytes" line of the shell's log, nil without one.- static func freeSpace(inShellLog text: String?) -> Int64? {+ package static func freeSpace(inShellLog text: String?) -> Int64? {guard let text else { return nil }return text.split(separator: "\n").reversed().lazy.compactMap { line -> Int64? inguard line.hasPrefix("shell: free space ") else { return nil }@@ -177,7 +181,7 @@ enum ShellInstall {}/// xcodebuild's words when the provisioning profile lacks the Increased Memory Limit the shell asks for.- static func memoryCapabilityMissing(_ output: String) -> Bool {+ package static func memoryCapabilityMissing(_ output: String) -> Bool {output.contains("doesn't include the Increased Memory Limit capability") || output.contains("doesn't include the com.apple.developer.kernel.increased-memory-limit entitlement")}@@ -186,7 +190,7 @@ enum ShellInstall {/// banner is removed and the library shows the framework's icon.png. Returns the picture used.@discardableResult static func placeBanner(titleID: String, framework: String, banners: URL, picked: String?,fm: FileManager = .default) -> String? {- let source = [picked, ArtworkStore.cachedBanner(titleID, in: banners)?.path].compactMap { $0 }.first { !$0.isEmpty && fm.fileExists(atPath: $0) }+ let source = [picked, BannerCache.cached(titleID, in: banners)?.path].compactMap { $0 }.first { !$0.isEmpty && fm.fileExists(atPath: $0) }for ext in ["png", "jpg", "jpeg", "heic", "webp"] { try? fm.removeItem(atPath: framework + "/banner." + ext) }guard let source else { return nil }let ext = (source as NSString).pathExtension.lowercased()@@ -195,14 +199,14 @@ enum ShellInstall {}/// devicectl's recursive listing of the game's folder in the app's container, written as JSON to `json`.- static func listCommand(xcrun: String, device: String, bundleID: String, titleID: String, json: String) -> [String] {+ package static func listCommand(xcrun: String, device: String, bundleID: String, titleID: String, json: String) -> [String] {[xcrun, "devicectl", "device", "info", "files", "--device", device, "--domain-type", "appDataContainer","--domain-identifier", bundleID, "--subdirectory", gameFolder(titleID: titleID), "--json-output", json]}/// One file into the game's folder. A file destination creates the parent folders and names the file. Never/// `--remove-existing-content true`: on a real device it deletes the destination's siblings too (#266).- static func copyCommand(xcrun: String, device: String, bundleID: String, titleID: String, source: String, relativePath: String) -> [String] {+ package static func copyCommand(xcrun: String, device: String, bundleID: String, titleID: String, source: String, relativePath: String) -> [String] {[xcrun, "devicectl", "device", "copy", "to", "--device", device, "--source", source,"--destination", gameFolder(titleID: titleID) + "/" + relativePath,"--domain-type", "appDataContainer", "--domain-identifier", bundleID]@@ -210,7 +214,7 @@ enum ShellInstall {/// The device's files (path relative to the game's folder → size) from the listing JSON. The error JSON of a folder that does/// not exist (or an app that is new) and anything unreadable mean "nothing on the device": an empty list.- static func parseListing(_ data: Data?) -> [String: Int64] {+ package static func parseListing(_ data: Data?) -> [String: Int64] {guard let data, let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],let files = (root["result"] as? [String: Any])?["files"] as? [[String: Any]] else { return [:] }var found: [String: Int64] = [:]@@ -224,7 +228,7 @@ enum ShellInstall {}/// The archive folder's files (relative path → size), without dot files (.packstamp) and without folders.- static func localFiles(in archive: String) -> [String: Int64] {+ package static func localFiles(in archive: String) -> [String: Int64] {let fm = FileManager.defaultvar found: [String: Int64] = [:]for case let path as String in fm.enumerator(atPath: archive) ?? FileManager.DirectoryEnumerator() {@@ -240,13 +244,13 @@ enum ShellInstall {/// The local files to copy: missing on the device, or of another size. Sorted, so the copies run in a stable order./// Path and size only: a file with the same size and other content stays. A hash comparison (a manifest the device keeps next to/// the game's folder) can close that gap later.- static func filesToCopy(local: [String: Int64], device: [String: Int64]) -> [String] {+ package static func filesToCopy(local: [String: Int64], device: [String: Int64]) -> [String] {local.filter { device[$0.key] != $0.value }.map(\.key).sorted()}/// The reason the build_shell.sh run failed, for the player: its last `[RED]` line (the refusals, for example two different/// games in one shell), else its last `FAIL:` line, else the last line it printed.- static func scriptFailure(_ output: String) -> String? {+ package static func scriptFailure(_ output: String) -> String? {let lines = output.split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }if let red = lines.last(where: { $0.contains("[RED]") }), let r = red.range(of: "[RED]") {return String(red[r.upperBound...]).trimmingCharacters(in: .whitespaces)@@ -260,9 +264,9 @@ enum ShellInstall {// ---- the connection of the copy ----/// How the device is connected to this Mac (`ShellConnection`, NXCore).- typealias Connection = ShellConnection+ package typealias Connection = ShellConnection- static func connection(of udid: String, in devices: [AppleDevice]) -> Connection {+ package static func connection(of udid: String, in devices: [AppleDevice]) -> Connection {guard let device = devices.first(where: { $0.id == udid }) else { return .notPaired }if device.wired { return .wired }if device.overNetwork { return .network }@@ -271,12 +275,12 @@ enum ShellInstall {/// Minutes a copy of `bytes` takes over Wi-Fi, as a range: devicectl over the local network does about 17 to 25 MB/s, so/// 15 GB is 10 to 15 minutes. At least one minute.- static func wifiEstimate(bytes: Int64) -> (low: Int, high: Int) {+ package static func wifiEstimate(bytes: Int64) -> (low: Int, high: Int) {let low = max(1, Int((Double(bytes) / 25e6 / 60).rounded()))return (low, max(low, Int((Double(bytes) / 17e6 / 60).rounded())))}- static func sizeText(_ bytes: Int64) -> String {+ package static func sizeText(_ bytes: Int64) -> String {// Decimal units as devicectl and the Finder count, and the same text in every localeif bytes >= 1_000_000_000 { return String(format: "%.1f GB", Double(bytes) / 1e9) }if bytes >= 1_000_000 { return String(format: "%.0f MB", Double(bytes) / 1e6) }@@ -285,7 +289,7 @@ enum ShellInstall {/// An installed app's shell paths, from its own path (<root>/derived-data/Build/Products/Release-iphoneos/DmShell.app), nil for/// any other app. A re-sign runs on that project and derived data.- static func paths(ofApp app: String) -> (root: String, project: String, derived: String)? {+ package static func paths(ofApp app: String) -> (root: String, project: String, derived: String)? {guard (app as NSString).lastPathComponent == appName, let marker = app.range(of: "/Build/Products/") else { return nil }let derived = String(app[..<marker.lowerBound])guard (derived as NSString).lastPathComponent == "derived-data" else { return nil }@@ -295,64 +299,77 @@ enum ShellInstall {}/// One stage of the install, as the model and the terminal show it.-struct ShellStage {- var id: Int- var name: String- var state: StepState- var detail = ""- var percent: Double? = nil+package struct ShellStage {+ package var id: Int+ package var name: String+ package var state: StepState+ package var detail = ""+ package var percent: Double? = nil++ package init(id: Int, name: String, state: StepState, detail: String = "", percent: Double? = nil) {+ self.id = id; self.name = name; self.state = state; self.detail = detail; self.percent = percent+ }}/// Steps 3 to 7: the shell's library, its project, signing, the install and the game data, blocking. A tool that fails ends the/// install with its own last error line.-struct ShellInstaller {- var xcrun = "/usr/bin/xcrun"- var repo: String+package struct ShellInstaller {+ package var xcrun = "/usr/bin/xcrun"+ package var repo: String/// The app's Contents/Resources, where a release app carries frontend-ios. Nil for a launcher run from a checkout.- var resources: String? = Bundle.main.resourceURL?.path- var python: String- var root: String- var device: String- var team: String- var deviceName = "iPhone"- var lang: Lang = .en+ package var resources: String? = Bundle.main.resourceURL?.path+ package var python: String+ package var root: String+ package var device: String+ package var team: String+ package var deviceName = "iPhone"+ package var lang: Lang = .en/// Run tools in a process group of their own (the model's Stop ends the group). The terminal does not need it.- var ownGroup = false- var toolPath = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"- var log: (String) -> Void = { _ in }- var stage: (ShellStage) -> Void = { _ in }+ package var ownGroup = false+ package var toolPath = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"+ package var log: (String) -> Void = { _ in }+ package var stage: (ShellStage) -> Void = { _ in }/// Told when a tool has started, so Stop can end it (the model keeps it).- var processStarted: (RunningProcess) -> Void = { _ in }+ package var processStarted: (RunningProcess) -> Void = { _ in }/// Starts every tool and the device listing (`ProcessRunner`, NXCore). A test passes in a fake.- var runner: ProcessRunner = SystemProcessRunner()+ package var runner: ProcessRunner = SystemProcessRunner()/// Asked once, only when something must be copied, with the size and the connection. The terminal answers `.copy`.- var decideCopy: (ShellCopyPlan) -> ShellCopyDecision = { _ in .copy }+ package var decideCopy: (ShellCopyPlan) -> ShellCopyDecision = { _ in .copy }/// While waiting for a cable: told true when the wait starts and false when it ends, and asked between polls whether the/// player cancelled.- var waiting: (Bool) -> Void = { _ in }- var waitCancelled: () -> Bool = { false }+ package var waiting: (Bool) -> Void = { _ in }+ package var waitCancelled: () -> Bool = { false }/// Seconds between two looks at `devicectl list devices` while waiting for a cable.- var pollInterval: TimeInterval = 4+ package var pollInterval: TimeInterval = 4/// Where the eShop banners are cached (ArtworkStore), read only: the game's goes into its framework for the shell's library.- var banners: URL = ArtworkStore.shared.directory+ package var banners: URL = BannerCache.directory/// A picture the player chose for the game in the library, which wins over the cached banner (nil: none).- var pickedArtwork: String? = nil-- struct Outcome {- var ok: Bool- var message: String- var step: BuildFailureClassifier.InstallStep? = nil // the failed device step, for the failure card- var appPath = ""- var bundleID = ""- var copied = 0- var copySkipped = false+ package var pickedArtwork: String? = nil++ package init(xcrun: String = "/usr/bin/xcrun", repo: String, python: String, root: String, device: String, team: String) {+ self.xcrun = xcrun; self.repo = repo; self.python = python; self.root = root; self.device = device; self.team = team+ }++ package struct Outcome {+ package var ok: Bool+ package var message: String+ package var step: BuildFailureClassifier.InstallStep? = nil // the failed device step, for the failure card+ package var appPath = ""+ package var bundleID = ""+ package var copied = 0+ package var copySkipped = false/// The card the launcher shows for the failure, when it has words for it.- var failure: BuildFailureKind? = nil+ package var failure: BuildFailureKind? = nil/// Signed without the Increased Memory Limit, because the team's profile cannot carry it yet.- var noMemoryCapability = false+ package var noMemoryCapability = false++ package init(ok: Bool, message: String, step: BuildFailureClassifier.InstallStep? = nil, appPath: String = "", bundleID: String = "", copied: Int = 0, copySkipped: Bool = false, failure: BuildFailureKind? = nil, noMemoryCapability: Bool = false) {+ self.ok = ok; self.message = message; self.step = step; self.appPath = appPath; self.bundleID = bundleID; self.copied = copied+ self.copySkipped = copySkipped; self.failure = failure; self.noMemoryCapability = noMemoryCapability+ }}- static let projectStageID = 1010, signStageID = 1001, installStageID = 1002, copyStageID = 1003, checkStageID = 1011+ package static let projectStageID = 1010, signStageID = 1001, installStageID = 1002, copyStageID = 1003, checkStageID = 1011private func t(_ key: String) -> String { L10n.string(key, lang) }private func fmt(_ key: String, _ args: CVarArg...) -> String { String(format: t(key), arguments: args) }@@ -382,7 +399,7 @@ struct ShellInstaller {}}- func install(framework: String, titleID: String, name: String, archive: String) -> Outcome {+ package func install(framework: String, titleID: String, name: String, archive: String) -> Outcome {guard FileManager.default.fileExists(atPath: framework) else {return Outcome(ok: false, message: fmt("shell.noFramework", framework))}@@ -485,7 +502,7 @@ struct ShellInstaller {/// Step 7 on its own, for a Retry after a copy that failed midway: the listing, the diff and the copy, nothing else. The app/// is on the device already, under the identifier shell.json holds.- func installData(titleID: String, archive: String) -> Outcome {+ package func installData(titleID: String, archive: String) -> Outcome {if let refused = pairingRefusal() { return refused }let bundleID = ShellLibrary.load(root: root).bundleID, app = ShellInstall.appPath(root: root)return copyGameData(titleID: titleID, archive: archive, app: app, bundleID: bundleID,@@ -614,52 +631,3 @@ struct ShellInstaller {}}-/// `NSPortBuilder --install-shell ...`: steps 3 to 7 without a window and without questions, for a terminal or a script.-enum ShellCLI {- static let usage = "NSPortBuilder --install-shell --framework <path> --archive <games/TITLEID folder> --title-id <id> --name <name> "- + "--device <udid> --team <team> --repo <repo> [--shell-root <dir>] [--python <path>]"-- /// The options as a dictionary, nil when an option has no value.- static func parse(_ args: [String]) -> [String: String]? {- var options: [String: String] = [:]- var i = 0- while i < args.count {- let a = args[i]- if a == "--install-shell" { i += 1; continue }- guard a.hasPrefix("--"), i + 1 < args.count else { return nil }- options[String(a.dropFirst(2))] = args[i + 1]- i += 2- }- return options- }-- /// Exit status: 0 installed, 1 failed (or wrong usage). `out` gets every line, stage lines and tool output alike.- /// `--xcrun` is for the tests, which stand in for xcodebuild and devicectl.- static func run(_ args: [String], defaults: UserDefaults = .standard, out: @escaping (String) -> Void = { fputs($0, stdout); fflush(stdout) }) -> Int32 {- let required = ["framework", "archive", "title-id", "name", "device", "team", "repo"]- guard let o = parse(args), required.allSatisfy({ !(o[$0] ?? "").isEmpty }) else {- out("usage: " + usage + "\n")- return 1- }- let archive = o["archive"]!- let root = o["shell-root"] ?? ShellLibrary.resolveRoot(- defaults: defaults, parent: ((archive as NSString).deletingLastPathComponent as NSString).deletingLastPathComponent)- let python = o["python"] ?? Toolchain.findPython().path- var installer = ShellInstaller(xcrun: o["xcrun"] ?? "/usr/bin/xcrun", repo: o["repo"]!, python: python, root: root,- device: o["device"]!, team: o["team"]!)- installer.deviceName = o["device"]!- installer.toolPath = BuildModel.toolPath("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", python: python)- installer.log = out- installer.stage = { s in- switch s.state {- case .running: if s.detail.isEmpty { out("==> \(s.name)\n") }- case .done: out("==> \(s.name): done\n")- case .failed: out("==> \(s.name): FAILED \(s.detail)\n")- case .pending: break- }- }- let result = installer.install(framework: o["framework"]!, titleID: o["title-id"]!, name: o["name"]!, archive: archive)- out((result.ok ? "OK: " : "FAIL: ") + result.message + "\n")- return result.ok ? 0 : 1- }-}diff --git a/frontend/Sources/NXCore/VolumePath.swift b/frontend/Sources/NXCore/VolumePath.swiftnew file mode 100644index 00000000..91a948c7--- /dev/null+++ b/frontend/Sources/NXCore/VolumePath.swift@@ -0,0 +1,11 @@+import Foundation++package enum VolumePath {+ /// A path on an external volume (`/Volumes/<name>/...`) whose mount point is absent: the drive is not connected, so the file is+ /// not known to be gone and its path must stay.+ package static func onUnmounted(_ path: String, volumes: String = "/Volumes") -> Bool {+ let prefix = volumes.hasSuffix("/") ? volumes : volumes + "/"+ guard path.hasPrefix(prefix), let name = path.dropFirst(prefix.count).split(separator: "/").first else { return false }+ return !FileManager.default.fileExists(atPath: prefix + name)+ }+}diff --git a/frontend/Sources/NXModel/BuildLog.swift b/frontend/Sources/NXModel/BuildLog.swiftindex 935b552f..1b80aa32 100644--- a/frontend/Sources/NXModel/BuildLog.swift+++ b/frontend/Sources/NXModel/BuildLog.swift@@ -2,7 +2,7 @@ import Foundationimport Combine/// The text of the build log (LNPANDY/NX2Apple#387). It is a store of its own, so a line from the build script invalidates-/// the views that show the log and nothing else: `BuildModel` holds it in a `let` and does not publish it, and no view above+/// the views that show the log and nothing else: `BuildStore` holds it in a `let` and does not publish it, and no view above/// the log observes it. The failure classifier reads `text` once, when a build stops.////// `text` keeps the tail: past `limit` characters it shrinks to the last `keep`. The pipe delivers arbitrary chunks, so@@ -49,13 +49,4 @@ import Combine/// Replaces the text (tests set a log to classify).package func set(_ s: String) { text = s }-- /// Runs `body` as the main actor's. `BuildModel` is not `@MainActor` yet and every call that reaches the log runs on the- /// main queue already (pipe output is hopped over, the rest is UI actions). This is `MainActor.assumeIsolated` for- /// macOS 13. Drop it when `BuildModel` is `@MainActor`.- nonisolated package static func onMain<T>(_ body: @MainActor () -> T) -> T {- dispatchPrecondition(condition: .onQueue(.main))- typealias Plain = () -> T- return withoutActuallyEscaping(body) { unsafeBitCast($0, to: Plain.self)() }- }}diff --git a/frontend/Sources/NXModel/BuildStore+Archive.swift b/frontend/Sources/NXModel/BuildStore+Archive.swiftnew file mode 100644index 00000000..782b8c8d--- /dev/null+++ b/frontend/Sources/NXModel/BuildStore+Archive.swift@@ -0,0 +1,164 @@+import Foundation+import Combine+import NXCore++// The archive step after the script: the RomFS image the game data goes over with (LNPANDY/NX2Apple#387).++extension BuildStore {+ // MARK: Archive++ /// The DLC images ride along: with the slim default the build script leaves them in the work folder+ /// instead of packing them into the IPA, and the host mounts them from DM_AOC_DIR/<index>.img, so+ /// they belong in this game's folder. Every way the archive step can end (folder pack, image copy,+ /// image reuse, stamp reuse) goes through here (issue #202).+ package func placeAddOnContent(workDir: String, in dest: String) {+ let n = RomFSArchive.copyAddOnContent(from: workDir + "/aoc", to: dest + "/aoc")+ if n > 0 { say(String(format: t("msg.aocCopied"), n)) }+ }++ /// Pack the extracted RomFS into one romfs.img. The extracted folder is+ /// <work>/extract/v<N>/RomFS where N is the profile's package version, so take+ /// the highest v* that actually has a RomFS instead of hardcoding one game.+ /// `then` continues the build with the archive's folder (installing on a device).+ package func packArchive(workDir: String, then: @escaping (String) -> Void) {+ running = true+ let fm = FileManager.default+ let extract = workDir + "/extract"+ // The extraction writes either a RomFS folder (older tools) or RomFS.img, one image file+ // (the rewriter packs it now: build_ipa_from_nsp.py:876 tests for exactly that). Looking+ // only for the folder made every 0.4.8 build end with "archive skipped" on a machine where+ // the extraction had in fact succeeded (issue #73). extractedVersion is the one authority:+ // an inline copy of its predicate here drifted back to folder-only during a merge, and the+ // archive skipped again while the test — which drives the function — stayed green.+ guard let v = RomFSArchive.extractedVersion(in: extract) else {+ stages.append(Stage(id: 1000, name: t("prog.archiveShort"), state: .failed, detail: t("prog.noRomfs")))+ doneNote = String(format: t("msg.archiveSkipped"), extract)+ running = false; cleanupStaging(); return+ }+ let romfs = extract + "/" + v + "/RomFS"+ let romfsImage = extract + "/" + v + "/RomFS.img"+ // The output is Documents/games/<title ID>/romfs — the per-game layout the iOS app looks for+ // first. Copying the whole `games` folder onto the phone (or into a folder the Files app+ // exposes on an external drive) then needs no renaming, and several games' folders can sit+ // side by side in one app.+ let gamesRoot = (outDir.isEmpty ? (basePath as NSString).deletingLastPathComponent : outDir) + "/games"+ let tid = TitleID.buildKey(basePath)+ // games/<id>/ holds romfs.img and aoc/ side by side: main.m's per-game lookup takes the+ // image, and the host mounts DLC from aoc/<index>.img (hle_fs.c aoc_dir). One folder, which+ // the user copies to the phone or keeps on an external drive as a whole.+ let gameDir = gamesRoot + "/" + tid+ let dest = gameDir+ try? fm.createDirectory(atPath: dest, withIntermediateDirectories: true)+ // Reuse: packing is a multi-GB write, and the extracted RomFS is itself reused by the+ // script — so when the source tree's (version, file count, bytes) matches the stamp left+ // in the folder, the shards are already correct and the pack is skipped. A different+ // version changes the extract; a same-version re-extract of the same NSPs reproduces the+ // same tree.+ let stampPath = dest + "/.packstamp"+ if let stamp = try? String(contentsOfFile: stampPath, encoding: .utf8), !stamp.isEmpty,+ let reused = RomFSArchive.archiveReusable(source: romfs, version: v, stamp: stamp) {+ archivePath = dest+ stages.append(Stage(id: 1000, name: t("prog.archive"), state: .done,+ detail: String(format: t("prog.archiveReused"), reused)))+ say(String(format: t("msg.archiveReused"), dest))+ placeAddOnContent(workDir: workDir, in: dest)+ return then(dest)+ }+ // One romfs.img instead of a ROMFSARC shard set: upstream reads the image directly+ // (hle_fs.c), one file copies to a phone at full speed where 300,000 did not, and it fits+ // an external drive. A shard set from an earlier build of this game is removed first —+ // main.m takes Documents/games/<id>/romfs.img before romfs/, so a stale archive would sit+ // there confusingly.+ for old in ((try? fm.contentsOfDirectory(atPath: dest)) ?? [])+ where old == "romfs.img" || old == "romfs.idx" || (old.hasPrefix("romfs.") && old.dropFirst(6).allSatisfy(\.isNumber)) {+ try? fm.removeItem(atPath: dest + "/" + old)+ }+ let idx = 1000+ stages.append(Stage(id: idx, name: t("prog.archive"), state: .running, detail: v))+ say(String(format: t("msg.archiveLog"), romfs, dest))++ // The extraction may already have packed the image (RomFS.img beside the code modules): then+ // this is a copy, not a pack. Packing it again from a folder that no longer exists was the+ // other half of issue #73.+ if fm.fileExists(atPath: romfsImage) {+ let to = dest + "/romfs.img"+ // Reuse by the image's own identity: copying a multi-GB file on every build of an+ // unchanged game is the cost this avoids. Size and modification date are enough — the+ // extraction rewrites the file whenever the game's data changes.+ if let src = try? fm.attributesOfItem(atPath: romfsImage),+ let have = try? fm.attributesOfItem(atPath: to),+ let a = src[.size] as? Int64, let b = have[.size] as? Int64, a == b,+ let da = src[.modificationDate] as? Date, let db = have[.modificationDate] as? Date,+ abs(da.timeIntervalSince(db)) < 1 {+ stages.append(Stage(id: idx, name: t("prog.archive"), state: .done,+ detail: String(format: t("prog.archiveReused"), 1)))+ say(String(format: t("msg.archiveReused"), dest))+ placeAddOnContent(workDir: workDir, in: dest)+ archivePath = dest+ return then(dest)+ }+ try? fm.removeItem(atPath: to)+ do {+ try fm.copyItem(atPath: romfsImage, toPath: to)+ // The running stage is updated in place: there is no process here whose progress+ // events would move it, and appending a second stage of the same name read as a+ // duplicate in the stage list.+ if let i = stages.firstIndex(where: { $0.id == idx }) {+ stages[i].state = .done; stages[i].detail = v+ }+ say(String(format: t("msg.archiveLog"), romfsImage, dest))+ placeAddOnContent(workDir: workDir, in: dest)+ archivePath = dest+ return then(dest)+ } catch {+ if let i = stages.firstIndex(where: { $0.id == idx }) {+ stages[i].state = .failed; stages[i].detail = error.localizedDescription+ }+ doneNote = String(format: t("msg.archiveFailed"), 1)+ running = false; cleanupStaging()+ }+ return+ }+ // dest/romfs.img: one file, which main.m's per-game lookup takes before any folder.+ let engine = EngineLayout.root(repo.path)+ let romfsPy = deps.pythonPath.isEmpty ? "/usr/bin/python3" : deps.pythonPath+ let launch = ProcessLaunch(executable: romfsPy, arguments: [engine + "/" + RepoLayout.romfsImageTool, "--reuse", romfs, dest + "/romfs.img"],+ environment: ["PATH": BuildCommands.toolPath("/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin", python: romfsPy), "PYTHONPATH": engine + "/dm/tools"]+ .merging(BundledTools.environment(for: romfsPy)) { $1 },+ groupPython: romfsPy)+ let onExit: @Sendable (Int32) -> Void = { [weak self] st in hop {+ guard let self else { return }+ let cancelled = self.stopping+ let succeeded = st == 0 && !cancelled+ self.stopping = false+ if succeeded {+ self.archivePath = dest+ RomFSArchive.writeStamp(source: romfs, version: v, to: dest + "/.packstamp")+ self.placeAddOnContent(workDir: workDir, in: dest)+ }+ if let i = self.stages.firstIndex(where: { $0.id == idx }) {+ self.stages[i].state = succeeded ? .done : .failed+ self.stages[i].detail = succeeded+ ? String(format: self.t("prog.archiveDone"), dest)+ : String(format: self.t("msg.archiveFailed"), st)+ }+ if succeeded { return then(dest) }+ self.cleanupStaging()+ self.running = false+ self.done = false+ if cancelled { self.resetProgress() }+ self.doneNote = cancelled ? self.t("msg.stopped") : String(format: self.t("msg.archiveFailed"), st)+ }}+ do {+ proc = try runner.start(launch, onOutput: { @Sendable [weak self] d in+ guard let s = String(data: d, encoding: .utf8) else { return }+ hop { self?.append(s) }+ }, onExit: onExit)+ } catch {+ if let i = stages.firstIndex(where: { $0.id == idx }) {+ stages[i].state = .failed; stages[i].detail = t("msg.archiveNoStart")+ }+ running = false; doneNote = t("msg.archiveNoStart"); cleanupStaging()+ }+ }+}diff --git a/frontend/Sources/NXModel/BuildStore+DropFiles.swift b/frontend/Sources/NXModel/BuildStore+DropFiles.swiftnew file mode 100644index 00000000..9d23713c--- /dev/null+++ b/frontend/Sources/NXModel/BuildStore+DropFiles.swift@@ -0,0 +1,51 @@+import Foundation+import NXCore++// Game files dropped on the Builds page (issue #68): NSP, NSZ and XCI files, a folder, prod.keys, in any+// mix. They are sorted into the slots by the same classification as Choose game folder+// (GameInputs.classify), so a drop and a picked folder never disagree about what is the update.++extension BuildStore {+ /// One dropped folder is the same as choosing it; anything else (files, several folders, a mix) is added to+ /// what is already chosen: a slot the drop has something for is replaced, add-on content is added to.+ package func take(dropped paths: [String]) {+ func isFolder(_ p: String) -> Bool {+ var d: ObjCBool = false+ return FileManager.default.fileExists(atPath: p, isDirectory: &d) && d.boolValue+ }+ if paths.count == 1, isFolder(paths[0]) { scan(folder: paths[0]); return }+ var found = GameInputs.classify(paths.flatMap { isFolder($0) ? GameInputs.inputFiles(in: $0) : [$0] })+ // update and add-on files of another game than the base (the dropped one, else the one already chosen)+ let baseName = (found.base ?? (basePath.isEmpty ? nil : basePath)).map { ($0 as NSString).lastPathComponent }+ var rejected: [InputKind: String] = [:]+ func fits(_ path: String, _ kind: InputKind) -> Bool {+ let name = (path as NSString).lastPathComponent+ guard let why = GameInputs.rowMismatch(kind, name: name, base: baseName) else { return true }+ if rejected[kind] == nil { rejected[kind] = rowProblemText(why, name: name) }+ return false+ }+ if let u = found.update, !fits(u, .update) { found.update = nil }+ found.dlc = found.dlc.filter { fits($0, .dlc) }+ slots = Self.merged(slots, with: found)+ for (kind, text) in rejected { updateSlot(kind == .update ? "update" : "dlc") { $0.problem = text } }+ if found.update != nil { updateSlot("update") { $0.note = updateNote(found) } }+ if let base = found.base { gameDir = (base as NSString).deletingLastPathComponent }+ }++ /// The slots after a drop of `found`. Nothing usable in it leaves the slots as they were, but says so on an empty base row.+ package nonisolated static func merged(_ slots: [Slot], with found: GameInputs.Found) -> [Slot] {+ slots.map { s in+ var s = s+ switch s.id {+ case "base":+ if let base = found.base { s.paths = [base]; s.problem = "" }+ else if !found.anyGame && found.keys == nil && s.paths.isEmpty { s.problem = "data.noNsp" }+ case "update": if let update = found.update { s.paths = [update]; s.problem = "" }+ case "dlc": if !found.dlc.isEmpty { s.paths = Array(Set(s.paths + found.dlc)).sorted(); s.problem = "" }+ case "keys": if let keys = found.keys { s.paths = [keys]; s.problem = "" }+ default: break+ }+ return s+ }+ }+}diff --git a/frontend/Sources/NXModel/BuildStore+Failure.swift b/frontend/Sources/NXModel/BuildStore+Failure.swiftnew file mode 100644index 00000000..7072fdde--- /dev/null+++ b/frontend/Sources/NXModel/BuildStore+Failure.swift@@ -0,0 +1,131 @@+import Foundation+import Combine+import NXCore++// What a failed build says and what its card offers: the classification, "Build anyway" and the fix buttons (LNPANDY/NX2Apple#387).++extension BuildStore {+ /// A failed build's log read for the script's known early stops: the card under the build button then says what+ /// happened and what to do. An unknown stop leaves the note (the last line of the log) as it is.+ package func noteFailure() {+ let f = BuildFailureClassifier.classify(logTail, inputs: failureInputs())+ guard f.kind != .unknown else { failure = nil; return }+ failure = f+ doneNote = failureWhat(f)+ }++ /// The Save to folder, picked in the app's folder panel (`chooseFolder`). Clears the cloud-folder stop, since the next build looks at the new folder.+ package func chooseBuildFolder() {+ guard let path = chooseFolder() else { return }+ outDir = path+ if failure?.kind == .cloudFolder { failure = nil; doneNote = "" }+ }++ /// What the classifier may check besides the log: the keys file and where the game files are.+ package func failureInputs() -> BuildFailureClassifier.Inputs {+ BuildFailureClassifier.Inputs(keysPath: keysPath, paths: ([basePath, updatePath, gameDir] + dlcPaths).filter { !$0.isEmpty },+ volumes: volumesRoot)+ }++ /// A failed step of an install on a device, as a card when the launcher can say more than the tool's line.+ /// Called after `finishInstall`, which put the tool's own error into the note.+ package func noteInstallFailure(_ step: BuildFailureClassifier.InstallStep, error: String) {+ let teamsOfMac = devices.readTeams+ let listed = teamsOfMac().contains { $0.id == devices.signingTeam }+ guard let f = BuildFailureClassifier.classifyInstall(step, error: error, teamListed: listed) else { failure = nil; return }+ failure = f+ doneNote = failureWhat(f)+ }++ /// The first sentence of a failure's hint (it names the game of a 32-bit program when the message does).+ package func failureWhat(_ f: BuildFailure) -> String {+ if f.kind == .a32Program, let name = f.gameName { return String(format: t("fail.a32Program.whatNamed"), name) }+ if f.kind == .driveMissing, let name = f.detail { return String(format: t("fail.driveMissing.whatNamed"), name) }+ if f.kind == .diskFull, let gb = f.detail { return String(format: t("fail.diskFull.whatNeeds"), gb) }+ return t(f.kind.whatKey)+ }++ /// "Build anyway": asks first. Nothing is armed until `confirmBuildAnyway`.+ package func requestBuildAnyway() {+ guard !running, let kind = failure?.kind, kind.overrideFlag != nil else { return }+ confirmingOverride = kind+ }++ package func cancelBuildAnyway() { confirmingOverride = nil }++ package func confirmBuildAnyway() {+ guard let kind = confirmingOverride else { return }+ confirmingOverride = nil+ armedOverride = kind+ startBuild()+ }++ /// The flag the next build runs with, once: the arm is cleared here, so a later build never inherits it.+ package func takeOverrideFlag() -> String? {+ defer { armedOverride = nil }+ return armedOverride?.overrideFlag+ }++ /// The card's fix buttons run the dependency rows' own commands (the same installDep as Settings).+ package func fixBuildFailure(_ kind: BuildFailureKind) {+ switch kind {+ case .translator:+ installRow("dotnet")+ case .iosSDK:+ installRow(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Toolchain.iosPlatformCmd))+ case .cltSelected:+ if let xcode = Toolchain.installedXcode() {+ installRow(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Toolchain.selectXcodeCmd(xcode)))+ }+ case .zbic:+ installRow("python") // the venv install, which now names zbic+ case .keys:+ if let chooseKeys { chooseKeys() } else { pickFiles(kind: .keys) } // the same picker as the keys row+ case .severalGames, .noTitleID, .diskFull:+ showFailureFolder()+ case .cloudFolder:+ chooseBuildFolder()+ case .teamTaken, .noSigningAccount:+ openXcode()+ case .deviceTransfer, .devicePairing:+ startBuild()+ case .shellDataIncomplete:+ retryShellData()+ default: break+ }+ }++ /// The folder the failure is about, in the Finder: the folder of the game files, else the one the message names. For a full+ /// disk the build folder (`<title ID>_build`, beside the game files) when it is there, since that is where the space went.+ package func showFailureFolder() {+ guard let f = failure else { return }+ var folder = gameDir.isEmpty ? (f.detail ?? "") : gameDir+ if f.kind == .diskFull, !gameDir.isEmpty {+ let built = ((try? FileManager.default.contentsOfDirectory(atPath: gameDir)) ?? []).sorted().first { $0.hasSuffix("_build") }+ if let built { folder = gameDir + "/" + built }+ }+ guard !folder.isEmpty else { return }+ revealFolder(URL(fileURLWithPath: folder))+ }++ /// Xcode itself: its Settings > Accounts is where a team is signed in, and Xcode has no address that opens that pane.+ package func openXcode() {+ guard let app = Toolchain.installedXcode() else { return }+ openApp(URL(fileURLWithPath: app))+ }++ /// Whether the card's fix button is already running its command.+ package func fixBusy(_ kind: BuildFailureKind) -> Bool {+ guard [.translator, .iosSDK, .cltSelected, .zbic].contains(kind) else { return false }+ let id = kind == .translator ? "dotnet" : kind == .zbic ? "python" : "xcode"+ return deps.isInstalling(id)+ }++ /// The row `id` of the tools panel installs, or the row given (a fix the panel has no row for).+ package func installRow(_ id: String) {+ if let d = deps.deps.first(where: { $0.id == id }) { _ = deps.install(d) }+ }+ package func installRow(_ dep: Dep) {+ _ = deps.install(dep)+ }+}diff --git a/frontend/Sources/NXModel/BuildStore+Inputs.swift b/frontend/Sources/NXModel/BuildStore+Inputs.swiftnew file mode 100644index 00000000..19d4d701--- /dev/null+++ b/frontend/Sources/NXModel/BuildStore+Inputs.swift@@ -0,0 +1,79 @@+import Foundation+import Combine+import NXCore++// The build inputs: the four rows (base game, update, add-on content, keys) and what fills them (LNPANDY/NX2Apple#387).++extension BuildStore {+ /// Fill every slot from a folder: NSP/XCI classified by title ID (…000 base,+ /// …800 update, anything above base+0x1000 add-on content), plus prod.keys.+ /// Subfolders are scanned too — a dump usually arrives as 本体/ 更新/ DLC/ folders —+ /// pruning the build folders this pipeline itself writes so a rescan is not slow.+ package func scan(folder: String) {+ gameDir = folder+ let found = GameInputs.classify(GameInputs.inputFiles(in: folder))+ updateSlot("base") { $0.paths = found.base.map { [$0] } ?? []; $0.problem = found.base == nil ? "data.noBase" : "" }+ updateSlot("update") { $0.paths = found.update.map { [$0] } ?? []; $0.problem = ""; $0.note = updateNote(found) }+ updateSlot("dlc") { $0.paths = found.dlc; $0.problem = "" }+ updateSlot("keys") { $0.paths = found.keys.map { [$0] } ?? []; $0.problem = "" }+ if !found.anyGame {+ updateSlot("base") { $0.problem = "data.noNsp" }+ }+ }++ /// The update row's note when the files held several updates: which one was taken and why one is enough.+ package func updateNote(_ found: GameInputs.Found) -> String {+ guard found.update != nil, found.updateCount > 1 else { return "" }+ return String(format: t("data.updateNewest"), found.updateVersion, found.updateCount)+ }++ /// The row's message for a rejected file, as a finished sentence in the current language.+ package func rowProblemText(_ mismatch: GameInputs.RowMismatch, name: String) -> String {+ func hex(_ tid: UInt64) -> String { String(format: "%016llX", tid) }+ switch mismatch {+ case .notBase(let tid): return String(format: t("data.rowNotBase"), name, hex(tid))+ case .notUpdate(let tid): return String(format: t("data.rowNotUpdate"), name, hex(tid))+ case .notDLC(let tid): return String(format: t("data.rowNotDLC"), name, hex(tid))+ case .otherGame: return String(format: t("data.rowOtherGame"), name)+ }+ }++ /// Asks the app's file picker for files for one row and takes them. The panel is AppKit's: it reaches the store as `pickFiles`.+ package func pickFiles(kind: InputKind) {+ var message: String?, prompt: String?+ switch kind {+ case .dlc:+ message = t("data.dlcPanelMessage")+ prompt = t("data.dlcPanelPrompt")+ case .update: message = t("data.updatePanelMessage")+ default: break+ }+ let picked = choosePaths(FilePick(allowsMultiple: kind == .dlc, fileTypes: GameInputs.allowedFileTypes(for: kind), message: message, prompt: prompt))+ guard !picked.isEmpty else { return }+ take(picked: picked, kind: kind)+ }++ /// Files chosen for one row: those that fit it are taken, the first that does not is named on the row+ /// and left out (it is not moved to another row: the row the user chose stays as they set it).+ package func take(picked: [String], kind: InputKind) {+ let id = kind == .base ? "base" : kind == .update ? "update" : kind == .dlc ? "dlc" : "keys"+ let baseName = kind == .base ? nil : (basePath as NSString).lastPathComponent+ var fitting: [String] = [], problem = ""+ for path in picked {+ let name = (path as NSString).lastPathComponent+ if let why = GameInputs.rowMismatch(kind, name: name, base: baseName) {+ if problem.isEmpty { problem = rowProblemText(why, name: name) }+ } else { fitting.append(path) }+ }+ updateSlot(id) { s in+ if !fitting.isEmpty {+ s.paths = kind == .dlc ? Array(Set(s.paths + fitting)).sorted() : Array(fitting.prefix(1))+ s.note = ""+ }+ s.problem = problem+ }+ if kind == .base, let first = fitting.first { gameDir = (first as NSString).deletingLastPathComponent }+ }++ package func clear(_ id: String) { updateSlot(id) { $0.paths = []; $0.problem = "" } }+}diff --git a/frontend/Sources/NXModel/BuildStore+Install.swift b/frontend/Sources/NXModel/BuildStore+Install.swiftnew file mode 100644index 00000000..23a47d74--- /dev/null+++ b/frontend/Sources/NXModel/BuildStore+Install.swift@@ -0,0 +1,256 @@+import Foundation+import Combine+import NXCore++// The install on a device after the archive: the shared app, the reinstall, the re-sign and the IPA (LNPANDY/NX2Apple#387).++extension BuildStore {+ // MARK: Installing on a device++ /// Steps 4 to 7 of the shared app (ShellInstall.swift) for a game whose framework is built and whose archive is packed: the+ /// shell's project, signing, the install over the app that is already there, and the game data the device lacks.+ package func installShell(framework: String, titleID: String, name: String, archive: String, dataOnly: Bool = false) {+ running = true+ if dataOnly { failure = nil; done = false; doneNote = "" }+ shellRetry = (framework, titleID, name, archive)+ let python = deps.pythonPath.isEmpty ? Toolchain.findPython().path : deps.pythonPath+ let root = shellRoot+ var installer = ShellInstaller(xcrun: devices.xcrun, repo: repo.path, python: python, root: root, device: devices.installDevice, team: devices.signingTeam)+ installer.deviceName = devices.deviceName(devices.installDevice)+ installer.lang = localizer.lang+ installer.ownGroup = true+ installer.toolPath = BuildCommands.toolPath("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", python: python)+ installer.log = { @Sendable s in hop { self.append(s) } }+ installer.stage = { @Sendable s in hop {+ if let i = self.stages.firstIndex(where: { $0.id == s.id }) {+ self.stages[i].name = s.name; self.stages[i].state = s.state; self.stages[i].detail = s.detail+ if let percent = s.percent { self.stages[i].percent = percent }+ if s.state == .running, self.stages[i].started == nil { self.stages[i].started = Date() }+ } else {+ self.stages.append(Stage(id: s.id, name: s.name, state: s.state, detail: s.detail, percent: s.percent,+ started: s.state == .running ? Date() : nil))+ }+ } }+ installer.runner = runner+ installer.processStarted = { @Sendable p in hop { self.proc = p } }+ // The size and the connection are shown with Continue, "Wait for a cable" and "Not now" (ShellCopyCard)+ let target = devices+ installer.decideCopy = { plan in target.askCopy(plan) }+ installer.waiting = { on in target.setWaiting(on) }+ installer.waitCancelled = { target.waitCancelled }+ let device = devices.installDevice+ DispatchQueue.global(qos: .userInitiated).async {+ let result = dataOnly ? installer.installData(titleID: titleID, archive: archive)+ : installer.install(framework: framework, titleID: titleID, name: name, archive: archive)+ hop {+ target.copyEnded()+ if self.stopping {+ self.stopping = false; self.running = false+ self.resetProgress(); self.doneNote = self.t("msg.stopped"); self.cleanupStaging()+ return+ }+ guard result.ok else {+ self.finishInstall(result.message)+ if let kind = result.failure { self.failure = BuildFailure(kind: kind, gameName: nil) }+ else if let step = result.step { self.noteInstallFailure(step, error: result.message) }+ return+ }+ self.installedOn = device+ self.installedAppPath = result.appPath+ self.finishInstall(nil, note: result.message)+ }+ }+ }++ /// Retry after game data that went over in part: only the data step runs again (listing, diff, copy).+ package func retryShellData() {+ guard !running, let r = shellRetry else { return }+ installShell(framework: r.framework, titleID: r.titleID, name: r.name, archive: r.archive, dataOnly: true)+ }++ package func finishInstall(_ failure: String?, note: String? = nil) {+ running = false+ done = failure == nil+ doneNote = failure ?? note ?? String(format: t("dev.installed"), devices.deviceName(devices.installDevice))+ cleanupStaging()+ }++ /// Reinstall the signed app that is already in derived data, without unpacking, signing or packing again: the+ /// device keeps the app's Documents (game data and saves), as the bundle ID does not change. A reinstall that+ /// fails on an expired signature says so in devicectl's words; signing again is not this button's job.+ package func reinstallOnDevice(then: (() -> Void)? = nil) {+ let device = installedOn, app = installedAppPath+ guard !device.isEmpty, !app.isEmpty else { then?(); return }+ guard FileManager.default.fileExists(atPath: app) else {+ doneNote = String(format: t("dev.reinstallMissing"), shortPath(app))+ then?(); return+ }+ running = true+ runTool(id: 1004, name: String(format: t("dev.reinstallStage"), devices.deviceName(device)),+ BuildCommands.reinstallCommand(xcrun: devices.xcrun, device: device, app: app), step: BuildProgress.installStep) { error in+ if let error {+ // The app is still on the device: a failed reinstall is a note, not a failed build+ self.running = false+ self.doneNote = String(format: self.t("dev.reinstallFailed"), error)+ } else {+ self.finishInstall(nil, note: String(format: self.t("dev.reinstalled"), self.devices.deviceName(device)))+ }+ then?()+ }+ }++ /// Renew the shared app's signature (a free Apple ID's profile lasts 7 days). The same xcodebuild parameters as+ /// the install, run on the cached project and derived data: Xcode reuses the compiled products and only signs+ /// again, then devicectl installs the app over itself. PRODUCT_BUNDLE_IDENTIFIER is the one shell.json holds, so the+ /// device keeps the app's Documents (game data, saves).+ package func resignOnDevice(app: String, device: String, then: (() -> Void)? = nil) {+ guard !device.isEmpty, !app.isEmpty else { then?(); return }+ guard !devices.signingTeam.isEmpty else {+ doneNote = t("dev.resignNoTeam")+ then?(); return+ }+ // An app from before the shared app has its own project and cannot be signed again here: build the game again+ guard let shell = ShellInstall.paths(ofApp: app) else {+ doneNote = t("dev.resignOlder")+ then?(); return+ }+ guard FileManager.default.fileExists(atPath: shell.project) else {+ doneNote = String(format: t("dev.resignNoProject"), shortPath(shell.project))+ then?(); return+ }+ let xcrun = devices.xcrun, team = devices.signingTeam, name = devices.deviceName(device)+ let bundle = ShellLibrary.load(root: shell.root).bundleID+ running = true+ // The shared app is signed again under the identifier shell.json holds, so the device keeps its Documents+ let command = ShellInstall.buildCommand(xcrun: xcrun, root: shell.root, device: device, team: team, bundleID: bundle)+ runTool(id: 1006, name: String(format: t("dev.resignStage"), name),+ command, step: BuildProgress.xcodeStep) { error in+ if let error, !error.isEmpty {+ self.running = false+ self.doneNote = String(format: self.t("dev.resignFailed"), error)+ then?(); return+ }+ self.runTool(id: 1007, name: String(format: self.t("dev.installStage"), name),+ BuildCommands.reinstallCommand(xcrun: xcrun, device: device, app: app), step: BuildProgress.installStep) { installError in+ self.running = false+ if let installError {+ self.doneNote = String(format: self.t("dev.installFailed"), installError)+ } else {+ self.installedOn = device+ self.installedAppPath = app+ self.doneNote = String(format: self.t("dev.resigned"), name)+ }+ then?()+ }+ }+ }++ /// The signed app as an .ipa, written to the place the app's save panel (`chooseSaveLocation`) returned.+ package func saveIPAPanel() {+ guard let url = chooseSaveLocation(t("dev.saveIPATitle"), defaultIPAName()) else { return }+ saveIPA(to: url)+ }++ /// The signed app as an .ipa (Payload/<name>.app, the layout iOS and the sideloaders install): useful while the+ /// signature lasts, and the thing to re-sign when it expires. The game data is not in it — it stays in the app's+ /// Documents (romfs.img), as a normal iOS build has it.+ package func saveIPA(to url: URL, then: (() -> Void)? = nil) {+ let app = installedAppPath, fm = FileManager.default+ guard !app.isEmpty, fm.fileExists(atPath: app) else {+ doneNote = String(format: t("dev.saveNeedsApp"), shortPath(app))+ then?(); return+ }+ let stage = fm.temporaryDirectory.appendingPathComponent("nspb-ipa-" + UUID().uuidString)+ let payload = stage.appendingPathComponent("Payload")+ do {+ try fm.createDirectory(at: payload, withIntermediateDirectories: true)+ try fm.copyItem(atPath: app, toPath: payload.appendingPathComponent((app as NSString).lastPathComponent).path)+ } catch {+ try? fm.removeItem(at: stage)+ doneNote = String(format: t("dev.saveFailed"), error.localizedDescription)+ then?(); return+ }+ running = true+ runTool(id: 1005, name: t("dev.saveStage"), BuildCommands.ipaCommand(payload: payload.path, ipa: url.path), step: { _ in nil }) { error in+ try? fm.removeItem(at: stage)+ self.running = false+ self.doneNote = error.map { String(format: self.t("dev.saveFailed"), $0) }+ ?? String(format: self.t("dev.savedIPA"), self.shortPath(url.path))+ then?()+ }+ }++ /// The name the save panel offers: the app's display name, so two games' IPAs do not collide. A slash or colon in a+ /// game's name would split the file name or show as a folder in Finder.+ package func defaultIPAName() -> String {+ let plist = NSDictionary(contentsOfFile: installedAppPath + "/Info.plist")+ let name = (plist?["CFBundleDisplayName"] as? String) ?? (plist?["CFBundleExecutable"] as? String) ?? "DmIOS"+ return name.replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: ":", with: "_") + ".ipa"+ }++ /// One of Xcode's tools as a stage of the build: in its own process group (Stop ends it), its output in the log,+ /// its progress in the stage. `then` gets nil on success, else the last error line.+ package func runTool(id: Int, name: String, _ command: [String], step: @escaping (String) -> (detail: String, percent: Double?)?,+ then: @escaping (String?) -> Void) {+ // A stage that runs again (the team-variant signing retry uses the same id) keeps its row:+ // a second row with that id would never see an update again — every lookup takes the first+ // match — and would spin for ever after the build moved on.+ if let i = stages.firstIndex(where: { $0.id == id }) {+ stages[i] = Stage(id: id, name: name, state: .running, started: Date())+ } else {+ stages.append(Stage(id: id, name: name, state: .running, started: Date()))+ }+ append("[\(name)] \(command.joined(separator: " "))\n")+ let launch = ProcessLaunch(command, environment: ["PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "HOME": NSHomeDirectory(), "USER": NSUserName(), "LANG": "en_US.UTF-8"],+ groupPython: deps.pythonPath.isEmpty ? "/usr/bin/python3" : deps.pythonPath)+ var buffer = "", lastError = ""+ let onOutput: @Sendable (Data) -> Void = { [weak self] d in+ guard let chunk = String(data: d, encoding: .utf8) else { return }+ hop {+ guard let self else { return }+ buffer += chunk+ while let nl = buffer.firstIndex(of: "\n") {+ let line = String(buffer[..<nl]); buffer = String(buffer[buffer.index(after: nl)...])+ self.append(line + "\n")+ if line.contains("error:") || line.hasPrefix("ERROR:") { lastError = line.trimmingCharacters(in: .whitespaces) }+ if let s = step(line), let i = self.stages.firstIndex(where: { $0.id == id }) {+ self.stages[i].detail = s.detail+ if let percent = s.percent { self.stages[i].percent = percent }+ }+ }+ }+ }+ let onExit: @Sendable (Int32) -> Void = { [weak self] status in+ hop {+ guard let self else { return }+ if self.stopping {+ self.stopping = false; self.running = false+ self.resetProgress(); self.doneNote = self.t("msg.stopped"); self.cleanupStaging()+ return+ }+ let ok = status == 0+ if let i = self.stages.firstIndex(where: { $0.id == id }) {+ self.stages[i].state = ok ? .done : .failed+ if ok { self.stages[i].percent = 100; self.stages[i].detail = "" }+ }+ then(ok ? nil : (lastError.isEmpty ? String(format: self.t("msg.exitCode"), status) : lastError))+ }+ }+ do { proc = try runner.start(launch, onOutput: onOutput, onExit: onExit) } catch { then(error.localizedDescription) }+ }++ /// Start the game on the device it was installed on.+ package func openOnDevice(udid: String, app: String, completion: @escaping (String?) -> Void) {+ let info = NSDictionary(contentsOfFile: app + "/Info.plist")+ guard let bundle = info?["CFBundleIdentifier"] as? String else { return completion(String(format: t("dev.noProject"), shortPath(app))) }+ let launch = ProcessLaunch(executable: devices.xcrun, arguments: ["devicectl", "device", "process", "launch", "--device", udid, bundle], mergesErrors: true)+ let runner = runner+ DispatchQueue.global(qos: .userInitiated).async {+ let r = runner.capture(launch)+ var message: String?+ if !r.started { message = r.out }+ else if r.status != 0 { message = r.out.split(separator: "\n").last(where: { $0.contains("rror") }).map(String.init) ?? r.out }+ hop { completion(message) }+ }+ }+}diff --git a/frontend/Sources/NXModel/BuildStore+Run.swift b/frontend/Sources/NXModel/BuildStore+Run.swiftnew file mode 100644index 00000000..78b92a39--- /dev/null+++ b/frontend/Sources/NXModel/BuildStore+Run.swift@@ -0,0 +1,263 @@+import Foundation+import Combine+import NXCore++// The build run: the script's arguments and environment, the process, and what happens when it ends (LNPANDY/NX2Apple#387).++extension BuildStore {+ package func startBuild() {+ guard !running else { return }+ // The shared app needs a device this Mac knows. Found out here, before an hour of building, not after it.+ if target != BuildTarget.mac, !shellDeviceChecked {+ guard installsDirectly else { doneNote = t("shell.needsDevice"); done = false; return }+ verifyShellDevice()+ return+ }+ shellDeviceChecked = false+ if target != BuildTarget.mac, askAboutStaleFrameworks() { return } // StaleFrameworksPrompt.swift (#449)+ stopping = false+ running = true; done = false; doneNote = ""; stages = []; log.clear(); chainNoteShown = false+ failure = nil; confirmingOverride = nil+ let override = takeOverrideFlag() // for this build only: the next one asks again+ installedOn = ""; installedAppPath = ""+ guard repo.isRepo else {+ fail(repo.path.isEmpty ? t("msg.repoInvalidEmpty") : String(format: t("msg.repoInvalid"), shortPath(repo.path)))+ return+ }+ // Resolve the interpreter here if the dependency check has not landed yet. checkDeps()+ // runs on a background queue and startBuild() can beat it — for a moment deps.pythonPath is+ // empty, and the old fallback was Apple's /usr/bin/python3 (3.9), which the script then+ // rejected with "require Python 3.12 or newer" whatever the machine actually had (#53).+ let py = deps.pythonPath.isEmpty ? Toolchain.findPython().path : deps.pythonPath+ // engine/ is the only engine and is stale or missing (#214): make it, then start again+ if EngineLayout.needsSyncBeforeBuild(repo.path) {+ _ = engine.syncEngine { ok in+ self.running = false+ if ok && !EngineLayout.needsSyncBeforeBuild(self.repo.path) { self.startBuild() }+ else { self.fail(String(format: self.t("msg.toolsOld"), "engine/ (python3 tools/engine.py sync, see the log)")) }+ }+ return+ }+ // The tools this app runs, before a build that takes an hour finds one missing at its last step (#87)+ let missing = RepoLayout.missingTools(in: repo.path)+ if !missing.isEmpty {+ fail(String(format: t("msg.toolsOld"), missing.joined(separator: ", ")))+ return+ }++ // One folder when everything lives together; otherwise a staging folder of symlinks. A folder+ // that holds other games too (a ROMs folder with one file per game) is staged as well: the+ // script takes one game per folder and refuses one with several ("more than one game in the+ // folder"), even when only the base game was picked (issue #58; ufooer's PR #31).+ let baseDir = (basePath as NSString).deletingLastPathComponent+ let allPaths = [basePath, updatePath] + dlcPaths+ let dirs = Set(allPaths.filter { !$0.isEmpty }.map { ($0 as NSString).deletingLastPathComponent })+ let picked = Set(allPaths.filter { !$0.isEmpty }.map { ($0 as NSString).lastPathComponent })+ let unpicked = ((try? FileManager.default.contentsOfDirectory(atPath: baseDir)) ?? []).filter {+ ["nsp", "xci", "nsz", "xcz"].contains(($0 as NSString).pathExtension.lowercased()) && !picked.contains($0)+ }+ // Staged, the folder's own update and add-on content would be left behind, where the script+ // used to find them unpicked: bring along those whose file name carries this game's title ID+ // exactly as build_ipa_from_nsp.py:445 reads it: the low 12 bits are 0x000 for a base game,+ // 0x800 for its update, and anything else is add-on content below the base.+ var staged = allPaths+ if let base = TitleID.parse((basePath as NSString).lastPathComponent) {+ let app = base & ~0xFFF+ for f in unpicked {+ guard let tid = TitleID.parse(f) else { continue }+ let low = tid & 0xFFF+ let owner = low == 0 ? tid : (low == 0x800 ? tid & ~0xFFF : (tid & ~0xFFF) - 0x1000)+ guard owner == app else { continue }+ if low == 0x800 && !updatePath.isEmpty { continue } // the update was picked already+ if low != 0 && low != 0x800 && tid <= app { continue } // add-on content sits above its base+ staged.append(baseDir + "/" + f)+ }+ }+ let tidHex = TitleID.buildKey(basePath)+ let workDir = (outDir.isEmpty ? baseDir : outDir) + "/" + tidHex + "_build"+ // The build's signing step refuses the attributes a cloud folder adds, after the long steps: stop here instead.+ if cloudFolderCheck(workDir) {+ failure = BuildFailure(kind: .cloudFolder, gameName: nil, detail: workDir)+ fail(failureWhat(failure!))+ return+ }+ var inputDir = baseDir+ if dirs.count > 1 || !unpicked.isEmpty {+ // A stable folder per game (#132): the script's fingerprints name its files and its profile path.+ let tmp = InputStaging.folder(workDir: workDir)+ let linked = InputStaging.sync(files: staged, into: tmp)+ if linked == 0 { fail(t("msg.stagingFailed")); return }+ staging = tmp; inputDir = tmp+ if !unpicked.isEmpty {+ say(String(format: t("msg.stagedFromSharedFolder"), (basePath as NSString).lastPathComponent))+ }+ } else { staging = nil }++ // This fork's --work-dir keeps the build folder (extracted files, shader cache, the romfs+ // archive) outside the NSPs' folder. An upstream checkout or an older ZIP does not have the+ // option and would stop with "unrecognized arguments" (issue #5), so ask the script; without+ // it the script's own default (<input>/<title ID>_build) is used and the archive step follows+ // whatever folder the build reports.+ let hasWorkDir = RepoLayout.supportsWorkDir(repo.path)+ if !hasWorkDir {+ say(t("msg.noWorkDir"))+ }+ // A compressed dump (NSZ / XCZ) needs nsz in the interpreter the build runs under; it is not+ // part of the dependency probe (most builds never see one), so install it here, once, only+ // when such a file is actually selected — otherwise the build stops with "pip install nsz".+ let compressed = ([basePath, updatePath] + dlcPaths).contains {+ let e = ($0 as NSString).pathExtension.lowercased()+ return e == "nsz" || e == "xcz"+ }+ if compressed, !Toolchain.runOK(py, ["-c", "import nsz"]) {+ say(t("msg.installingNsz"))+ let r = runner.runCaptured([py, "-m", "pip", "install", "nsz"],+ env: ["PATH": BuildCommands.toolPath(python: py),+ "HOME": NSHomeDirectory()].merging(BundledTools.environment(for: py)) { $1 }) { @Sendable line in+ hop { self.append(line + "\n") }+ }+ if !r {+ fail(String(format: t("msg.nszFailed"), py))+ return+ }+ }+ let engine = EngineLayout.root(repo.path) // the checkout's engine/ (#214)+ var args = [engine + "/" + RepoLayout.buildScript, inputDir, "-k", keysPath,+ "--progress", "json"]+ // A compatibility switch the player turned on: written to a small env file the pipeline+ // copies into the app bundle (main.m sets one variable per line at boot). Only for an iPhone or iPad build;+ // a Mac app runs on this Mac's GPU, which always has BC support.+ if bcOnCPU && target != BuildTarget.mac {+ let envPath = NSTemporaryDirectory() + "nspb-env-\(UUID().uuidString.prefix(8)).txt"+ do {+ try "DM_TEX_BC_CPU=1\n".write(toFile: envPath, atomically: true, encoding: .utf8)+ args += ["--env-file", envPath]+ say(t("msg.bcOn"))+ } catch {+ say(String(format: t("msg.bcEnvFailed"), error.localizedDescription))+ }+ }+ if hasWorkDir { args += ["--work-dir", workDir] }+ let macApp = target == BuildTarget.mac+ if macApp {+ // -o names the .app; the RomFS goes inside it, so the archive step is skipped below.+ args += ["--platform", "mac-app"]+ macAppPath = (outDir.isEmpty ? baseDir : outDir) + "/" + tidHex + ".app"+ args += ["-o", macAppPath]+ } else {+ // Only the game's framework: the one shared app is made and signed after the script (installShell)+ args += ShellInstall.buildArguments(workDir: workDir, team: devices.signingTeam)+ }+ // The archive step packs whatever folder the build reported; without --work-dir that is the+ // script's default, which is the same workDir unless a separate output folder was chosen.+ effectiveWorkDir = hasWorkDir ? workDir : (inputDir as NSString).appendingPathComponent(tidHex + "_build")+ args = BuildFailureClassifier.arguments(args, adding: override)+ if let override { say(String(format: t("fail.override.note"), override)) }+ say(String(format: t("msg.running"), py) + " " + args.joined(separator: " "))+ lastBuildCommand = [py] + args++ // The root of the runtime the apphost looks for: derived from the detected installation,+ // not assumed to be ~/.dotnet (Homebrew keeps it in …/opt/dotnet/libexec). Only set when the+ // derivation actually answered — a wrong root is worse than none, and the pipeline derives+ // and verifies its own (DOTNET_ROOT, build_ipa_from_nsp.py) when this is absent.+ // TMPDIR as well: .NET 10 on macOS keeps the named mutex its first-run configure takes+ // (NuGet-Migrations) under $TMPDIR/.dotnet/shm, and with no TMPDIR it stats "" and dies with+ // 'NuGet-Migrations' + lstat("") == ENOENT before any project is read. NSTemporaryDirectory()+ // is the per-user temp folder whether or not the app's own environment carries one.+ var denv: [String: String] = ["PATH": BuildCommands.toolPath("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", python: py),+ "USER": NSUserName(), "HOME": NSHomeDirectory(), "LANG": "en_US.UTF-8",+ "TMPDIR": NSTemporaryDirectory()]+ if let droot = Toolchain.dotnetRoot(for: deps.dotnetPath.isEmpty ? "dotnet" : deps.dotnetPath) {+ denv["DOTNET_ROOT"] = droot // both variables carry the same root, as the apphost checks the arch-specific one first+ denv["DOTNET_ROOT_ARM64"] = droot+ }+ // The bundled Python lives inside the signed app: a .pyc written there would change what the signature seals+ // (the packages are compiled at bundle time), and a user site must not shadow its pinned packages.+ denv.merge(BundledTools.environment(for: py)) { $1 }+ let launch = ProcessLaunch(executable: py, arguments: args, environment: denv, directory: engine, groupPython: py)+ let onExit: @Sendable (Int32) -> Void = { [weak self] status in+ hop {+ guard let self else { return }+ self.running = false+ self.flushLines()+ if self.stopping {+ self.stopping = false+ self.resetProgress()+ self.doneNote = self.t("msg.stopped")+ self.cleanupStaging()+ return+ }+ if status == 0 {+ self.markAllDone()+ if self.target == BuildTarget.mac {+ // The .app is self-contained (its RomFS is inside), and the marker file+ // beside it (.nx2apple-library, a dot file the Finder hides) tells the+ // game's launcher that this folder is a library: its saves and log live+ // here, and they follow the folder if it moves. No image copy — the .app+ // already carries one, and a second multi-GB file was pure duplication.+ let made = !self.macAppPath.isEmpty &&+ FileManager.default.fileExists(atPath: self.macAppPath)+ self.done = made+ self.doneNote = self.t(made ? "msg.macAppDone" : "msg.macAppMissing")+ if made {+ try? Data().write(to: URL(fileURLWithPath:+ (self.macAppPath as NSString).deletingLastPathComponent ++ "/.nx2apple-library"))+ }+ self.running = false+ self.cleanupStaging()+ } else {+ // The game's archive, then its framework into the one shared app on the device+ let tid = TitleID.buildKey(self.basePath)+ let name = ((self.basePath as NSString).lastPathComponent as NSString).deletingPathExtension+ let fw = ShellInstall.frameworkPath(workDir: self.effectiveWorkDir, titleID: tid)+ self.packArchive(workDir: self.effectiveWorkDir) {+ self.installShell(framework: fw, titleID: tid, name: name, archive: $0)+ }+ }+ } else {+ if let i = self.stages.lastIndex(where: { $0.state == .running }) {+ self.stages[i].state = .failed+ self.stages[i].detail = String(format: self.t("msg.exitCode"), status)+ self.noteFailure()+ } else {+ // The last real line says more than the exit code alone, and the message+ // points at the log: "Build failed (exit code 1)" with nothing else sent a+ // reporter looking for a log that a short window had below the fold (#52)+ self.doneNote = String(format: self.t("msg.buildFailed"), status)+ if let last = BuildProgress.lastMeaningfulLine(self.logTail) {+ self.doneNote = String(format: self.t("msg.buildFailedReason"), last)+ }+ self.noteFailure()+ }+ self.cleanupStaging()+ }+ }+ }+ do {+ proc = try runner.start(launch, onOutput: { @Sendable [weak self] d in+ guard let s = String(data: d, encoding: .utf8) else { return }+ hop { self?.ingest(s) }+ }, onExit: onExit)+ } catch { fail(String(format: t("msg.launchFailed"), error.localizedDescription)) }+ }++ /// Looks the device up in `devicectl list devices` (in the background), then starts the build, or says how to pair it.+ package func verifyShellDevice() {+ running = true; done = false; doneNote = ""; failure = nil; stages = []+ let xcrun = devices.xcrun, device = devices.installDevice, runner = runner+ DispatchQueue.global(qos: .userInitiated).async {+ let link = ShellInstall.connection(of: device, in: DeviceTools.devices(xcrun: xcrun, timeout: 20, runner: runner))+ hop {+ self.running = false+ if link == .notPaired {+ self.failure = BuildFailure(kind: .devicePairing, gameName: nil)+ self.doneNote = String(format: self.t("shell.notPaired"), self.devices.deviceName(device))+ return+ }+ self.shellDeviceChecked = true+ self.startBuild()+ }+ }+ }+}diff --git a/frontend/Sources/NXModel/BuildStore+Stale.swift b/frontend/Sources/NXModel/BuildStore+Stale.swiftnew file mode 100644index 00000000..36ae0b4c--- /dev/null+++ b/frontend/Sources/NXModel/BuildStore+Stale.swift@@ -0,0 +1,51 @@+import Foundation+import NXCore++// LNPANDY/NX2Apple#449: a build for the iPhone or iPad asks before the long steps when the shell folder holds frameworks of+// another shader chain than the engine this build uses. Stop leaves every file as it is. Continue deletes the stale frameworks+// (and their entries in the shell's library) and starts the build again. Without stale frameworks nothing is asked. A framework+// whose chain cannot be read is not decided here, build_shell.sh's own check at the last step stays for it.++extension BuildStore {+ /// The stale frameworks of the shared app for the engine this build runs, nothing when the check cannot decide.+ package func staleFrameworkEntries() -> [StaleFrameworks.Entry] {+ guard let chain = StaleFrameworks.currentChain(engineRoot: EngineLayout.root(repo.path)) else { return [] }+ let root = shellRoot+ let known = ShellLibrary.load(root: root).games.map { (titleID: $0.titleID, name: $0.name, framework: $0.framework) }+ return StaleFrameworks.find(root: root, chain: chain, known: known, except: TitleID.buildKey(basePath))+ }++ /// True when the build must wait for the player's answer: the prompt is showing (`staleFrameworks` is set).+ package func askAboutStaleFrameworks() -> Bool {+ let entries = staleFrameworkEntries()+ guard !entries.isEmpty else { return false }+ staleFrameworks = entries+ return true+ }++ /// Stop the build: nothing was touched.+ package func stopForStaleFrameworks() { staleFrameworks = [] }++ /// Continue: delete the stale frameworks, drop their games from the shell's library, and start the build.+ package func continueWithStaleFrameworks(then start: (() -> Void)? = nil) {+ let entries = staleFrameworks+ staleFrameworks = []+ let failed = Self.removeStaleFrameworks(entries, root: shellRoot)+ if !failed.isEmpty {+ done = false+ doneNote = String(format: t("stale.removeFailed"), failed.map { ($0 as NSString).lastPathComponent }.joined(separator: ", "))+ return+ }+ (start ?? startBuild)()+ }++ /// The folders of `entries` are deleted and the games leave `<root>/shell.json`. Returns the folders that could not be deleted.+ package static func removeStaleFrameworks(_ entries: [StaleFrameworks.Entry], root: String) -> [String] {+ let failed = StaleFrameworks.remove(entries)+ var library = ShellLibrary.load(root: root)+ let gone = Set(entries.map { $0.titleID.lowercased() })+ library.games.removeAll { gone.contains($0.titleID.lowercased()) }+ try? library.save(root: root)+ return failed+ }+}diff --git a/frontend/Sources/NXModel/BuildStore.swift b/frontend/Sources/NXModel/BuildStore.swiftnew file mode 100644index 00000000..b58c123d--- /dev/null+++ b/frontend/Sources/NXModel/BuildStore.swift@@ -0,0 +1,316 @@+import Foundation+import Combine+import NXCore++/// A file picker request: what the store asks the app's open panel for (`BuildStore.choosePaths`).+package struct FilePick: Equatable {+ package var allowsMultiple: Bool+ package var fileTypes: [String]+ package var message: String?+ package var prompt: String?++ package init(allowsMultiple: Bool, fileTypes: [String], message: String? = nil, prompt: String? = nil) {+ self.allowsMultiple = allowsMultiple; self.fileTypes = fileTypes; self.message = message; self.prompt = prompt+ }+}++/// What the build asks of the engine sync: make `engine/` of the checkout current, and tell when it is done.+@MainActor package protocol EngineSyncing: AnyObject {+ func syncEngine(then: ((Bool) -> Void)?) -> Task<Void, Never>+}++/// What the build asks of the dependency store besides its status: the rows, and the install the card's fix buttons run.+@MainActor package protocol DependencyInstalling: DependencyStatus {+ func isInstalling(_ id: String) -> Bool+ func install(_ dep: Dep) -> Task<Void, Never>+}++/// What the build reads from the device store: the device and the team to install on, the names, the listing of the teams, and the+/// copy flow the install blocks on (its queue is not the main one, so those four are `nonisolated`).+@MainActor package protocol InstallTarget: AnyObject {+ var installDevice: String { get }+ /// The paired devices the last listing found.+ var devices: [AppleDevice] { get }+ var signingTeam: String { get }+ var xcrun: String { get }+ var readTeams: @Sendable () -> [SigningTeam] { get }+ func deviceName(_ udid: String) -> String+ nonisolated func askCopy(_ plan: ShellCopyPlan) -> ShellCopyDecision+ nonisolated func setWaiting(_ on: Bool)+ nonisolated var waitCancelled: Bool { get }+ func copyEnded()+}++extension DeviceStore: InstallTarget {}+extension DependencyStore: DependencyInstalling {}+extension EngineSyncStore: EngineSyncing {}++/// Runs `body` on the main actor, from a queue that is not the main one: the pipe's callbacks and the background install land here.+func hop(_ body: @escaping @MainActor () -> Void) {+ DispatchQueue.main.async { MainActor.assumeIsolated(body) }+}++/// The build (LNPANDY/NX2Apple#387, step 7, the last store): the inputs (the four rows, the output folder), the target, the stages+/// and whether a build runs, the script's JSON events, the run itself with its archive step and its hand-off to the device, the+/// failure the card shows and "Build anyway". It follows `AppUpdateStore` (`frontend/ARCHITECTURE.md`, "Stores").+///+/// - What it works with comes through `init`: the `Localizer`, a `ProcessRunner`, the `BuildLog`, and three narrow views of the other+/// stores: `RepoLocation` (where the checkout is), `DependencyInstalling` (the tools: `DependencyStatus` and the install the fix+/// buttons run), `EngineSyncing` (the sync a stale `engine/` needs before a build) and `InstallTarget` (the device, the team and+/// the copy flow). The app wires them.+/// - AppKit reaches it as closures: the file and folder pickers (`choosePaths`, `chooseFolder`, `chooseSaveLocation`), the notice+/// (`showNotice`), the Finder (`revealFolder`, `openApp`), and `targetChanged`, which the app answers with a new dependency check.+/// - It checks the conditions for its own actions: `canBuild` and the start of a build (`startBuild`).+/// - The pieces live in the `BuildStore+` files: `Inputs`, `Run`, `Failure`, `Archive`, `Install`, `Stale`, `DropFiles`.+@MainActor package final class BuildStore: ObservableObject {+ nonisolated package static let outputKey = "buildOutputDirectory"+ nonisolated package static let targetKey = "buildTarget"+ nonisolated package static let bcOnCPUKey = "bcOnCPU"++ @Published package var gameDir = ""+ @Published package var slots: [Slot] = [+ Slot(id: "base", kind: .base, title: "data.base", optional: false),+ Slot(id: "update", kind: .update, title: "data.update", optional: true),+ Slot(id: "dlc", kind: .dlc, title: "data.dlc", optional: true),+ Slot(id: "keys", kind: .keys, title: "data.keys", optional: false),+ ]+ @Published package var outDir: String {+ didSet { defaults.set(outDir, forKey: Self.outputKey) }+ }+ @Published package var stages: [Stage] = []+ var chainNoteShown = false // the shader-chain notice shows once per build+ @Published package var running = false+ @Published package var staleFrameworks: [StaleFrameworks.Entry] = [] // the prompt of StaleFrameworksPrompt.swift (#449)+ /// The shell folder the cache row shows: the frameworks' mirror, shell.json and the banner cache live here.+ package var shellCachePath: String { shellRoot }+ /// The shell folder of the install and of the cache row: the saved one, else next to the output folder (or the game's folder).+ package var shellRoot: String { ShellLibrary.resolveRoot(defaults: defaults, parent: outDir.isEmpty ? (basePath as NSString).deletingLastPathComponent : outDir) }+ @Published package var stopping = false+ /// The build log. Not published: only `BuildLogView` observes it (#387), so a log line redraws the log and nothing else.+ package let log: BuildLog+ package var logTail: String {+ get { log.text }+ set { log.set(newValue) }+ }+ @Published package var done = false+ @Published package var doneNote = ""+ /// What the NSP script stopped on, when it is one of the known early stops (BuildFailureClassifier). nil for a build that+ /// succeeded, is running, or failed some other way (the note then shows the last line of the log, as it always did).+ @Published package var failure: BuildFailure?+ /// "Build anyway" asked for this stop and waiting for the confirmation dialog.+ @Published package var confirmingOverride: BuildFailureKind?+ /// The one-off `--allow-*` of a confirmed "Build anyway": taken by the next build and never stored.+ package var armedOverride: BuildFailureKind?+ @Published package var macAppPath = "" // --platform mac-app: the .app this build produced+ /// BuildTarget.ios = the game's framework in the one shared app on an iPhone or iPad; BuildTarget.mac = a double-clickable+ /// Mac app (upstream's --platform mac-app). A Mac app is a different output of the same pipeline, not a+ /// different pipeline: same extraction, rewrite and shaders, then dm/mac/pack_app.py.+ @Published package var target: String {+ didSet {+ defaults.set(target, forKey: Self.targetKey)+ if oldValue != target { targetChanged() }+ }+ }+ /// Decode BC-compressed textures on the CPU. Only relevant for GPUs without BC support+ /// (A15/A16 and older): on a device that has it the GPU path is always better, so the switch+ /// is a compatibility option and defaults off. Passed as DM_TEX_BC_CPU through --env-file,+ /// which the host reads at start-up — no rebuild of the host needed.+ @Published package var bcOnCPU: Bool {+ didSet { defaults.set(bcOnCPU, forKey: Self.bcOnCPUKey) }+ }+ @Published package var archivePath = "" // the romfs folder the pack wrote+ /// Where this build's folder actually is: --work-dir when the checkout has it, else the script's+ /// default under the input folder (issue #5 — an upstream checkout has no --work-dir).+ package var effectiveWorkDir = ""+ package var lastBuildCommand: [String] = [] // this session's last build, for Copy diagnostics (Diagnostics.swift)++ // ---- Installing on an iPhone or iPad (Xcode with a development certificate) ----+ // Optional: with a paired device and a signing team chosen, the script prepares the game's Xcode project+ // (--prepare-xcode, the route its README gives developers), xcodebuild signs it for that device with the+ // team (Xcode makes the provisioning profile) without the game files, devicectl installs it and copies the game's+ // folder (romfs.img, aoc/) into its Documents, as a sideloaded copy has it. Without a device or a team the build stays an unsigned IPA, as before.+ @Published package var installedOn = "" // the device the last build went to (its UDID)+ @Published package var installedAppPath = "" // the signed app that went there+ var shellRetry: (framework: String, titleID: String, name: String, archive: String)?+ var shellDeviceChecked = false++ // ---- The app's side: AppKit and the wiring, as closures ----+ package var chooseKeys: (() -> Void)? // tests stand in for the file picker+ /// The open panel: the paths the player picked, none when they cancelled.+ package var choosePaths: (FilePick) -> [String] = { _ in [] }+ /// The folder panel of "Save to": the folder's path, nil when they cancelled.+ package var chooseFolder: () -> String? = { nil }+ /// The save panel of "Save IPA" (title, the name offered): where to write, nil when they cancelled.+ package var chooseSaveLocation: (String, String) -> URL? = { _, _ in nil }+ /// A notice the player must see (the shader chain changed): an alert.+ package var showNotice: (String) -> Void = { _ in }+ package var revealFolder: (URL) -> Void = { _ in }+ package var openApp: (URL) -> Void = { _ in }+ /// Whether the build folder is in a cloud folder. Tests stand in for the system's answer.+ package var cloudFolderCheck: (String) -> Bool = { CloudFolder.contains($0) }+ /// The target changed: the app checks the tools again when a Mac-only setup now needs, or no longer needs, the iOS SDK.+ package var targetChanged: () -> Void++ // ---- What it works with ----+ package let localizer: Localizer+ package let runner: ProcessRunner+ package let repo: RepoLocation+ package let deps: DependencyInstalling+ package let engine: EngineSyncing+ package let devices: InstallTarget+ package let volumesRoot: String+ let defaults: UserDefaults++ var proc: RunningProcess?+ var staging: String?++ /// - Parameters:+ /// - volumesRoot: where external drives are mounted (the failure classifier reads it).+ /// - targetChanged: see the property of the same name.+ package init(localizer: Localizer, runner: ProcessRunner, log: BuildLog = BuildLog(), repo: RepoLocation, deps: DependencyInstalling,+ engine: EngineSyncing, devices: InstallTarget, defaults: UserDefaults = .standard, volumesRoot: String = "/Volumes",+ targetChanged: @escaping () -> Void = {}) {+ self.localizer = localizer+ self.runner = runner+ self.log = log+ self.repo = repo+ self.deps = deps+ self.engine = engine+ self.devices = devices+ self.defaults = defaults+ self.volumesRoot = volumesRoot+ self.targetChanged = targetChanged+ outDir = defaults.string(forKey: Self.outputKey) ?? ""+ target = BuildTarget.saved(defaults)+ bcOnCPU = defaults.bool(forKey: Self.bcOnCPUKey)+ }++ /// The language and the text this store writes itself: views take strings from the environment.+ package var lang: Lang { get { localizer.lang } set { localizer.lang = newValue } }+ package func t(_ key: String) -> String { localizer.t(key) }++ /// This iPhone build goes straight to a device.+ package var installsDirectly: Bool { target != BuildTarget.mac && !devices.installDevice.isEmpty && !devices.signingTeam.isEmpty }++ /// Home shown as ~ (shorter in a one-line row, and it keeps the account name out of screenshots).+ package func shortPath(_ path: String) -> String { RepoLayout.shortPath(path) }++ package var basePath: String { slot("base").paths.first ?? "" }+ package var keysPath: String { slot("keys").paths.first ?? "" }+ package var updatePath: String { slot("update").paths.first ?? "" }+ package var dlcPaths: [String] { slot("dlc").paths }++ package func slot(_ id: String) -> Slot { slots.first { $0.id == id } ?? slots[0] }+ package func updateSlot(_ id: String, _ body: (inout Slot) -> Void) {+ if let i = slots.firstIndex(where: { $0.id == id }) { body(&slots[i]) }+ }++ /// A build may start: the repository is usable, the base game and the keys are there, the tools are all present and none runs.+ package var canBuild: Bool { repo.isRepo && slot("base").ok && slot("keys").ok && deps.allPresent && !running }++ /// A line for the build card's note, from a store that has no card of its own (the dependency store's failed install).+ package func note(_ text: String) { doneNote = text }++ // MARK: Ending a build++ package func fail(_ why: String) { running = false; doneNote = why; say("✗ " + why); cleanupStaging() }++ package func stop() {+ guard running, !stopping, let proc, proc.isRunning else { return }+ stopping = true+ ProcessGroups.endGroup(proc.processIdentifier) // the script and every tool it started+ }++ package func cleanupStaging() {+ staging = nil // the folder stays for the next build of this game (#132, InputStaging)+ }++ /// A stopped build leaves no half-finished stages behind: the progress starts empty again.+ package func resetProgress() { stages = []; log.clear() }++ package func markAllDone() { for i in stages.indices where stages[i].state != .failed { stages[i].state = .done } }++ // MARK: Output parsing++ package func say(_ s: String) { append(s + "\n") }+ package func append(_ s: String) { log.append(s) }++ /// Split into lines (the pipe delivers arbitrary chunks) and turn the script's progress into the stage list.+ /// `--progress json` writes one event per line (stage, step, progress with done / total / frac / eta, stage_end,+ /// say), a count change at most every half second; anything else on the pipe (a tool's traceback) is log text.+ /// The older `--progress lines` form is still understood:+ /// [12:00:01] [2/7] extract v720896 …+ /// [12:00:20] ✓ [2/7] extract v720896 (0:19): 30,000 files, 3.4 GB+ package func ingest(_ chunk: String) {+ for line in log.feed(chunk) { handle(line) }+ }++ package func flushLines() {+ if let rest = log.flush() { handle(rest) }+ }++ package func handle(_ line: String) {+ if line.hasPrefix("{"), let data = line.data(using: .utf8),+ let event = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], let kind = event["ev"] as? String {+ return handleEvent(kind, event)+ }+ append(line + "\n")+ noteChainChange(line)+ guard let s = BuildProgress.parseStage(line) else { return }+ if let i = stages.firstIndex(where: { $0.id == s.k }) {+ if !s.name.isEmpty { stages[i].name = Stage.localizedName(s.name, t) }+ if s.state != .pending { stages[i].state = s.state }+ if !s.detail.isEmpty { stages[i].detail = s.detail }+ stages[i].percent = s.percent+ } else if s.state != .pending {+ stages.append(Stage(id: s.k, name: Stage.localizedName(s.name, t), state: s.state, detail: s.detail, percent: s.percent, started: Date()))+ stages.sort { $0.id < $1.id }+ }+ }++ /// The script marks a shader-chain bump with this tag: the cached libraries cannot be+ /// reused and this build recompiles them. An alert, not a log line — the report's question+ /// ("why is it building shaders again, the artifacts are on the drive") came from exactly+ /// this moment passing unnoticed. Once per build: the pipe delivers arbitrary chunks.+ /// (A plain line, or the message of a `say` event in `--progress json`.)+ package func noteChainChange(_ text: String) {+ guard text.contains("[NOTE] chain-changed"), !chainNoteShown else { return }+ chainNoteShown = true+ showNotice(t("msg.chainChanged"))+ }++ /// One event of `--progress json`: the stage list follows it, and the log gets a readable line (no count updates).+ package func handleEvent(_ kind: String, _ e: [String: Any]) {+ let k = (e["k"] as? NSNumber)?.intValue ?? 0+ func stage(_ update: (inout Stage) -> Void) {+ if let i = stages.firstIndex(where: { $0.id == k }) { update(&stages[i]) }+ else { var s = Stage(id: k, name: Stage.localizedName(e["name"] as? String ?? "", t)); update(&s); stages.append(s); stages.sort { $0.id < $1.id } }+ }+ switch kind {+ case "stage":+ let name = e["name"] as? String ?? "", step = e["step"] as? String ?? ""+ let n = (e["n"] as? NSNumber)?.intValue ?? 0+ append("[\(k)/\(n)] \(name)" + (step.isEmpty ? "" : " · \(step)") + " …\n")+ stage { $0.name = Stage.localizedName(name, t); $0.state = .running; $0.detail = step; $0.percent = nil; $0.started = Date(); $0.eta = nil }+ case "step":+ let step = e["step"] as? String ?? ""+ append(" · \(step)\n")+ stage { $0.detail = step; $0.percent = nil; $0.eta = nil }+ case "progress":+ let fraction = (e["frac"] as? NSNumber)?.doubleValue+ let detail = BuildProgress.progressDetail(e)+ let eta = (e["eta"] as? NSNumber)?.doubleValue+ stage { $0.percent = fraction.map { $0 * 100 }; $0.detail = detail; $0.eta = eta; $0.etaAt = eta == nil ? nil : Date() }+ case "stage_end":+ let ok = e["ok"] as? Bool ?? true, summary = e["summary"] as? String ?? ""+ let elapsed = BuildProgress.duration((e["elapsed"] as? NSNumber)?.doubleValue ?? 0)+ append("\(ok ? "✓" : "✗") \(e["name"] as? String ?? "") (\(elapsed))" + (summary.isEmpty ? "" : ": \(summary)") + "\n")+ stage { $0.state = ok ? .done : .failed; $0.detail = summary; $0.percent = ok ? 100 : $0.percent; $0.eta = nil }+ case "say":+ let msg = e["msg"] as? String ?? ""+ append(msg + "\n")+ noteChainChange(msg)+ default: break+ }+ }+}diff --git a/frontend/Sources/NXModel/Localizer.swift b/frontend/Sources/NXModel/Localizer.swiftindex 83336329..a98e9121 100644--- a/frontend/Sources/NXModel/Localizer.swift+++ b/frontend/Sources/NXModel/Localizer.swift@@ -3,11 +3,11 @@ import Combineimport NXCore/// The interface language and the strings for it (LNPANDY/NX2Apple#387). Views take it from the environment, so a language change-/// redraws the views that show text and nothing else. `BuildModel` gets it through its init for the strings it writes itself.+/// redraws the views that show text and nothing else. `BuildStore` gets it through its init for the strings it writes itself.////// The language choice is stored by `Lang.saved` (UserDefaults key `appLanguage`): "" follows the system. `choose()` writes it.///-/// `lang` and `t()` are not tied to the main actor, because `BuildModel` writes status text from background queues. The value is+/// `lang` and `t()` are not tied to the main actor, because the stores write status text from background queues. The value is/// behind a lock, and a change sends `objectWillChange` for the views.@MainActor package final class Localizer: ObservableObject {/// Holds the language where any thread may read it.diff --git a/frontend/Sources/NXModel/Slot.swift b/frontend/Sources/NXModel/Slot.swiftnew file mode 100644index 00000000..9a9cdb58--- /dev/null+++ b/frontend/Sources/NXModel/Slot.swift@@ -0,0 +1,36 @@+import Foundation+import NXCore++/// One row of the build's inputs: the base game, the update, the add-on content or the keys.+package struct Slot: Identifiable {+ package let id: String+ package let kind: InputKind+ package let title: String+ package let optional: Bool+ package var paths: [String] = []+ package var problem: String = ""+ /// A finished sentence shown beside the file name (the update row: which of several updates was taken).+ package var note: String = ""+ package var ok: Bool { paths.contains { FileManager.default.fileExists(atPath: $0) } }+ /// `problem` holds either a finished message or a key + arguments, resolved by the model+ /// (it needs the current language, which a struct cannot read).+ package var problemText: String { problem }++ package init(id: String, kind: InputKind, title: String, optional: Bool, paths: [String] = [], problem: String = "", note: String = "") {+ self.id = id; self.kind = kind; self.title = title; self.optional = optional+ self.paths = paths; self.problem = problem; self.note = note+ }++ package func summary(_ t: (String) -> String) -> String {+ if !problem.isEmpty { return problem.hasPrefix("data.") ? t(problem) : problem }+ if paths.isEmpty {+ if kind == .dlc { return t("data.notSelectedDlc") }+ return optional ? t("data.notSelectedOptional") : t("data.notSelected")+ }+ if paths.count == 1 {+ let name = (paths[0] as NSString).lastPathComponent+ return note.isEmpty ? name : name + "\n" + note+ }+ return String(format: t("data.files"), paths.count) + paths.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")+ }+}diff --git a/frontend/Tests/NX2AppleTests/AddOnContentCopyTests.swift b/frontend/Tests/NX2AppleTests/AddOnContentCopyTests.swiftindex 51ae2d74..2bf51b7c 100644--- a/frontend/Tests/NX2AppleTests/AddOnContentCopyTests.swift+++ b/frontend/Tests/NX2AppleTests/AddOnContentCopyTests.swift@@ -1,6 +1,7 @@import XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// The slim default leaves DLC images in the work folder, and the archive step copies them into the game folder@@ -15,7 +16,7 @@ final class AddOnContentCopyTests: XCTestCase {try fm.createDirectory(at: dest, withIntermediateDirectories: true)try Data([2]).write(to: work.appendingPathComponent("2.img"))try Data([9]).write(to: dest.appendingPathComponent("1.img")) // from an earlier build- XCTAssertEqual(BuildModel.copyAddOnContent(from: work.path, to: dest.path), 1)+ XCTAssertEqual(RomFSArchive.copyAddOnContent(from: work.path, to: dest.path), 1)XCTAssertEqual(try fm.contentsOfDirectory(atPath: dest.path), ["2.img"])}@@ -25,7 +26,7 @@ final class AddOnContentCopyTests: XCTestCase {defer { try? fm.removeItem(at: root) }let dest = root.appendingPathComponent("aoc")try fm.createDirectory(at: dest, withIntermediateDirectories: true)- XCTAssertEqual(BuildModel.copyAddOnContent(from: root.appendingPathComponent("none").path, to: dest.path), 0)+ XCTAssertEqual(RomFSArchive.copyAddOnContent(from: root.appendingPathComponent("none").path, to: dest.path), 0)XCTAssertTrue(fm.fileExists(atPath: dest.path))}}diff --git a/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swift b/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swiftindex 7fe26a46..a0ddb461 100644--- a/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swift+++ b/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swift@@ -1,11 +1,12 @@import XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// The failure rows for keys, game files and the build's own steps (issue #141): what sets each one, that its text names the/// action, and that its button does it. The log lines are the script's real messages (Tests/Fixtures/build_failures.json).-final class BuildFailureRowsTests: XCTestCase {+@MainActor final class BuildFailureRowsTests: XCTestCase {func fixture(_ id: String) throws -> BuildFailureTests.Fixture {try XCTUnwrap(BuildFailureTests().fixtures().first { $0.id == id }, id)}@@ -46,7 +47,7 @@ final class BuildFailureRowsTests: XCTestCase {XCTAssertEqual(BuildFailureClassifier.classify("[RED] the zbic package decoded it").kind, .unknown)XCTAssertTrue(L10n.table["fail.zbic.next"]?.en.contains("pip install zbic") ?? false)XCTAssertEqual(L10n.table["fail.zbic.button"]?.en, "Install zbic")- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildm.logTail = logm.noteFailure()XCTAssertEqual(m.failure?.kind, .zbic)@@ -67,7 +68,7 @@ final class BuildFailureRowsTests: XCTestCase {let low = BuildFailureClassifier.classify(try fixture("disk.low").text)XCTAssertEqual(low, BuildFailure(kind: .diskFull, gameName: nil, detail: try fixture("disk.low").gb))XCTAssertEqual(BuildFailureClassifier.classify(try fixture("disk.full").text), BuildFailure(kind: .diskFull, gameName: nil, detail: nil))- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildm.lang = .en // the English text, whatever the Mac's languageXCTAssertTrue(m.failureWhat(low).contains("40 GB"), m.failureWhat(low))XCTAssertFalse(m.failureWhat(BuildFailure(kind: .diskFull, gameName: nil)).contains("GB"))@@ -82,7 +83,7 @@ final class BuildFailureRowsTests: XCTestCase {try FileManager.default.createDirectory(at: volumes.appendingPathComponent("Games"), withIntermediateDirectories: true)XCTAssertEqual(BuildFailureClassifier.classify(log, inputs: .init(keysPath: "", paths: [gone], volumes: volumes.path)).kind, .noTitleID, "the drive is there")XCTAssertEqual(BuildFailureClassifier.classify(log, inputs: .init(keysPath: "/Users/x/prod.keys", paths: ["/Users/x/g.nsp"], volumes: volumes.path)).kind, .noTitleID, "a path off /Volumes is no drive")- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildm.lang = .en // the quotes are English ones whatever the device language isXCTAssertTrue(m.failureWhat(f).contains("“Games”"))}@@ -142,7 +143,7 @@ final class BuildFailureRowsTests: XCTestCase {func testAFailedBuildShowsTheRowForItsLogLine() throws {for (id, kind) in [("keys.missing", BuildFailureKind.keys), ("games.several", .severalGames), ("games.noTitleID", .noTitleID), ("disk.low", .diskFull), ("disk.full", .diskFull)] {- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildm.logTail = try fixture(id).text + "\n"m.noteFailure()XCTAssertEqual(m.failure?.kind, kind, id)@@ -151,7 +152,7 @@ final class BuildFailureRowsTests: XCTestCase {}func testTheKeysButtonOpensTheKeysPicker() {- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildvar opened = 0m.chooseKeys = { opened += 1 }m.failure = BuildFailure(kind: .keys, gameName: nil)@@ -161,7 +162,7 @@ final class BuildFailureRowsTests: XCTestCase {func testShowFolderRevealsTheGameFolderAndForAFullDiskTheBuildFolder() throws {let dir = try tempFolder()- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildvar shown: [String] = []m.revealFolder = { shown.append($0.path) }m.gameDir = dir.path@@ -186,25 +187,25 @@ final class BuildFailureRowsTests: XCTestCase {}@MainActor func testAnInstallStepThatFailedShowsItsRow() {- let m = BuildModel()- m.signingTeam = "TEAM123456"- m.deviceStore.readTeams = { [SigningTeam(id: "TEAM123456", identity: "")] }+ let mStores = LauncherStores(); let m = mStores.build+ mStores.deviceStore.signingTeam = "TEAM123456"+ mStores.deviceStore.readTeams = { [SigningTeam(id: "TEAM123456", identity: "")] }m.noteInstallFailure(.sign, error: "error: Failed to register bundle identifier: cannot be registered to your development team")XCTAssertEqual(m.failure?.kind, .teamTaken)XCTAssertEqual(m.doneNote, m.t("fail.teamTaken.what"))- m.deviceStore.readTeams = { [] }+ mStores.deviceStore.readTeams = { [] }m.noteInstallFailure(.sign, error: "error: x")XCTAssertEqual(m.failure?.kind, .noSigningAccount)m.noteInstallFailure(.install, error: "ERROR: The device is not connected.")XCTAssertEqual(m.failure?.kind, .deviceTransfer)- m.deviceStore.readTeams = { [SigningTeam(id: "TEAM123456", identity: "")] }+ mStores.deviceStore.readTeams = { [SigningTeam(id: "TEAM123456", identity: "")] }m.failure = BuildFailure(kind: .teamTaken, gameName: nil)m.noteInstallFailure(.sign, error: "error: x")XCTAssertNil(m.failure, "an unknown signing error leaves the tool's line")}func testTryAgainStartsANewBuildAndClearsTheCard() {- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildm.target = BuildTarget.mac // the iPhone / iPad target stops first, at the device checkm.failure = BuildFailure(kind: .deviceTransfer, gameName: nil)m.fixBuildFailure(.deviceTransfer) // no repository here: the build stops at once, but it has started and dropped the old card@@ -212,7 +213,7 @@ final class BuildFailureRowsTests: XCTestCase {}func testTheXcodeButtonOpensXcodeWhenItIsInstalled() {- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildvar opened: [URL] = []m.openApp = { opened.append($0) }m.failure = BuildFailure(kind: .teamTaken, gameName: nil)diff --git a/frontend/Tests/NX2AppleTests/BuildFailureTests.swift b/frontend/Tests/NX2AppleTests/BuildFailureTests.swiftindex 08a6a9af..b50a00a8 100644--- a/frontend/Tests/NX2AppleTests/BuildFailureTests.swift+++ b/frontend/Tests/NX2AppleTests/BuildFailureTests.swift@@ -2,11 +2,12 @@ import SwiftUIimport XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// The script's early stops, turned into hints. The fixture holds the real message of every pattern, copied from the script/// (Tests/Fixtures/build_failures.json, shared with the Qt front end's test).-final class BuildFailureTests: XCTestCase {+@MainActor final class BuildFailureTests: XCTestCase {struct Fixture: Decodable {let id: String, kind: String, source: String, fragment: String, text: Stringlet game: String?, folder: String?, gb: String?@@ -134,7 +135,7 @@ final class BuildFailureTests: XCTestCase {}func testNothingIsArmedUntilTheConfirmation() {- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildm.failure = BuildFailure(kind: .otherMetal, gameName: nil)m.requestBuildAnyway()XCTAssertEqual(m.confirmingOverride, .otherMetal)@@ -146,7 +147,7 @@ final class BuildFailureTests: XCTestCase {}func testAConfirmedOverrideServesOneBuildOnly() {- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildm.target = BuildTarget.mac // the iPhone / iPad target stops first, at the device checkm.failure = BuildFailure(kind: .damagedNSP, gameName: nil)m.requestBuildAnyway()@@ -158,7 +159,7 @@ final class BuildFailureTests: XCTestCase {}func testAStopWithoutAnOverrideCannotBeBuiltAnyway() {- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildfor k in BuildFailureKind.allCases where k.overrideFlag == nil {m.failure = BuildFailure(kind: k, gameName: nil)m.requestBuildAnyway()@@ -167,7 +168,7 @@ final class BuildFailureTests: XCTestCase {}func testAFailedBuildShowsTheHintInsteadOfTheLastLine() {- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildm.logTail = "[RED] the iOS SDK is not installed: install the iOS platform in Xcode\n"m.noteFailure()XCTAssertEqual(m.failure?.kind, .iosSDK)@@ -253,10 +254,10 @@ final class BuildFailureTests: XCTestCase {}@MainActor func testTheMetalRowsDetailReadsInTheLauncher() {- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildlet dep = DependencyCheck.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.other], needsIOS: false)- XCTAssertTrue(m.dependencies.detail(of: dep).contains(Self.other), m.dependencies.detail(of: dep))- XCTAssertTrue(m.dependencies.detail(of: dep).contains(Self.pinned), m.dependencies.detail(of: dep))+ XCTAssertTrue(mStores.dependencies.detail(of: dep).contains(Self.other), mStores.dependencies.detail(of: dep))+ XCTAssertTrue(mStores.dependencies.detail(of: dep).contains(Self.pinned), mStores.dependencies.detail(of: dep))}/// Opt-in native rendering for pull request screenshots (NX_LAUNCHER_CAPTURE_DIR), the way LibraryTests renders the launcher.@@ -283,41 +284,42 @@ final class BuildFailureTests: XCTestCase {("hint-other-metal-zh", .otherMetal, .zh)]+ [BuildFailureKind.keys, .severalGames, .noTitleID, .driveMissing, .diskFull, .teamTaken, .noSigningAccount, .deviceTransfer].flatMap { k in[("row-\(k.rawValue)", k, Lang.en), ("row-\(k.rawValue)-zh", k, Lang.zh)] } {- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildm.lang = CaptureLanguage.current(lang)m.failure = BuildFailure(kind: kind, gameName: nil, detail: kind == .diskFull ? "40" : kind == .driveMissing ? "Games" : nil)m.doneNote = m.failureWhat(m.failure!)try capture(name, width: 760, height: kind == .noTitleID ? 380 : 250, ZStack(alignment: .top) {LauncherPalette.background- BuildFailureCard(m: m).environmentObject(m.localizer).padding(24)+ BuildFailureCard(m: m).environmentObject(mStores.localizer).padding(24)})}- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildm.lang = .en- MainActor.assumeIsolated { m.dependencies.checked = true }- MainActor.assumeIsolated { m.dependencies.deps = [Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: []),+ MainActor.assumeIsolated { mStores.dependencies.checked = true }+ MainActor.assumeIsolated { mStores.dependencies.deps = [Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: []),DependencyCheck.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.other, "iphoneos": Self.other], needsIOS: true)] }try capture("deps-metal-warning", width: 760, height: 260, ZStack(alignment: .top) {LauncherPalette.background- MetalRowPreview(m: m).padding(24)+ MetalRowPreview(dependencies: mStores.dependencies, t: m.t).padding(24)})}}/// The dependency panel's rows as the Settings card draws them, for the screenshot (the card itself is private to BuilderView).private struct MetalRowPreview: View {- @ObservedObject var m: BuildModel+ @ObservedObject var dependencies: DependencyStore+ let t: (String) -> Stringvar body: some View {VStack(alignment: .leading, spacing: 0) {- ForEach(m.dependencies.deps, id: \.id) { d in+ ForEach(dependencies.deps, id: \.id) { d inHStack(alignment: .top, spacing: 12) {Circle().fill(d.present && !d.warning ? LauncherPalette.ready : LauncherPalette.building).frame(width: 7, height: 7).padding(.top, 6)VStack(alignment: .leading, spacing: 3) {- Text(m.t(d.name)).font(.manrope(14, .semibold))- Text(m.dependencies.detail(of: d)).font(.manrope(12.5)).foregroundStyle(.secondary)+ Text(t(d.name)).font(.manrope(14, .semibold))+ Text(dependencies.detail(of: d)).font(.manrope(12.5)).foregroundStyle(.secondary)if !d.lastError.isEmpty {Text(d.lastError).font(.mono(11)).foregroundStyle(LauncherPalette.building)- Text(m.t(d.fixHint)).font(.manrope(11.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ Text(t(d.fixHint)).font(.manrope(11.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)}}Spacer()diff --git a/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swift b/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swiftindex 7e88deff..f86f59cd 100644--- a/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swift+++ b/frontend/Tests/NX2AppleTests/BuildNotificationsTests.swift@@ -2,10 +2,11 @@ import XCTestimport SwiftUI@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// When a build notification is posted and what it says (issue #64). Nothing here touches the notification center.-final class BuildNotificationsTests: XCTestCase {+@MainActor final class BuildNotificationsTests: XCTestCase {private func en(_ key: String) -> String { L10n.string(key, .en) }func testOnlyAFinishedOrFailedBuildIsNotified() {@@ -57,12 +58,12 @@ final class BuildNotificationsTests: XCTestCase {let temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-notify-" + UUID().uuidString)try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(at: temporary) }- let model = BuildModel()+ let modelStores = LauncherStores(); let model = modelStores.buildmodel.lang = CaptureLanguage.current(.en)- MainActor.assumeIsolated { model.dependencies.checked = true }- MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }+ MainActor.assumeIsolated { modelStores.dependencies.checked = true }+ MainActor.assumeIsolated { modelStores.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))- let host = NSHostingView(rootView: ContentView(model: model, library: library, initialPage: .settings, performStartupChecks: false))+ let host = NSHostingView(rootView: ContentView(stores: modelStores, library: library, initialPage: .settings, performStartupChecks: false))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1440, height: 1500), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)window.contentView = hostwindow.orderFront(nil)diff --git a/frontend/Tests/NX2AppleTests/BundledToolsTests.swift b/frontend/Tests/NX2AppleTests/BundledToolsTests.swiftindex 69d70da5..cf9ffe21 100644--- a/frontend/Tests/NX2AppleTests/BundledToolsTests.swift+++ b/frontend/Tests/NX2AppleTests/BundledToolsTests.swift@@ -1,6 +1,7 @@import XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// The release app carries its build tools and a Python (BundledTools.swift): the dependency check prefers them to Homebrew's and to@@ -98,8 +99,8 @@ final class BundledToolsTests: XCTestCase {func testBuildToolPathKeepsTheHomebrewBaseWithoutABundle() {// under `swift test` there is no bundle: the helper is the old string- XCTAssertEqual(BuildModel.toolPath(), "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin")- XCTAssertEqual(BuildModel.toolPath("/usr/bin:/bin"), "/usr/bin:/bin")+ XCTAssertEqual(BuildCommands.toolPath(), "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin")+ XCTAssertEqual(BuildCommands.toolPath("/usr/bin:/bin"), "/usr/bin:/bin")}// ---- the dependency rows ----diff --git a/frontend/Tests/NX2AppleTests/CheatFilesTests.swift b/frontend/Tests/NX2AppleTests/CheatFilesTests.swiftindex e5adb188..6e0579f9 100644--- a/frontend/Tests/NX2AppleTests/CheatFilesTests.swift+++ b/frontend/Tests/NX2AppleTests/CheatFilesTests.swift@@ -2,12 +2,13 @@ import SwiftUIimport XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// Issue #97: the cheat files the launcher manages, as the host reads them (dm/host/hle_cheats.c, docs/frontends.md "Cheats"). The/// expectations are written by hand from the contract and from the host's parser, not generated by the code under test. Everything/// runs in a temporary folder, devicectl is a stand-in, and no test reaches a device or the real Application Support.-final class CheatFilesTests: XCTestCase {+@MainActor final class CheatFilesTests: XCTestCase {private var temporary: URL!private let titleID = "010015100B514000"private let build = "CD57B23FA4BBAD65"@@ -261,11 +262,11 @@ final class CheatFilesTests: XCTestCase {}func testTheImportMessageSaysWhatCameInAndWhatDidNot() {- let m = BuildModel(); m.lang = .en- XCTAssertEqual(CheatsView.importMessage(.init(imported: ["A", "B"]), loc: m.localizer).0, "Files imported: 2.")- XCTAssertTrue(CheatsView.importMessage(.init(imported: ["A"], skipped: ["x.txt"]), loc: m.localizer).0.contains("x.txt"))- XCTAssertFalse(CheatsView.importMessage(.init(), loc: m.localizer).1)- XCTAssertTrue(CheatsView.importMessage(.init(imported: ["A"]), loc: m.localizer).1)+ let mStores = LauncherStores(); let m = mStores.build; m.lang = .en+ XCTAssertEqual(CheatsView.importMessage(.init(imported: ["A", "B"]), loc: mStores.localizer).0, "Files imported: 2.")+ XCTAssertTrue(CheatsView.importMessage(.init(imported: ["A"], skipped: ["x.txt"]), loc: mStores.localizer).0.contains("x.txt"))+ XCTAssertFalse(CheatsView.importMessage(.init(), loc: mStores.localizer).1)+ XCTAssertTrue(CheatsView.importMessage(.init(imported: ["A"]), loc: mStores.localizer).1)}// ---- the copy to the device ----@@ -373,10 +374,10 @@ final class CheatFilesTests: XCTestCase {try fm.createDirectory(at: ios, withIntermediateDirectories: true)try PropertyListSerialization.data(fromPropertyList: ["CFBundleIdentifier": "com.example.zelda"], format: .xml, options: 0).write(to: ios.appendingPathComponent("Info.plist"))- let model = BuildModel()+ let modelStores = LauncherStores(); let model = modelStores.buildmodel.lang = .en- MainActor.assumeIsolated { model.dependencies.checked = true }- MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }+ MainActor.assumeIsolated { modelStores.dependencies.checked = true }+ MainActor.assumeIsolated { modelStores.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))let id = try library.addApp(app)library.recordCompletedIOS(archive: "", app: ios.path, device: "00008150-AAAA", for: id)@@ -417,21 +418,21 @@ final class CheatFilesTests: XCTestCase {try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent(name + ".png"))window.orderOut(nil)}- try shot("cheats", CheatsView(m: model, library: library, gameID: id, devicectl: DeviceControl { _ in (true, "") }, support: support).environmentObject(model.localizer))- try shot("cheats-drop", CheatsView(m: model, library: library, gameID: id, support: support, dropped: true).environmentObject(model.localizer))+ try shot("cheats", CheatsView(m: model, library: library, gameID: id, devicectl: DeviceControl { _ in (true, "") }, support: support).environmentObject(modelStores.localizer))+ try shot("cheats-drop", CheatsView(m: model, library: library, gameID: id, support: support, dropped: true).environmentObject(modelStores.localizer))model.lang = .de- try shot("cheats-de", CheatsView(m: model, library: library, gameID: id, support: support).environmentObject(model.localizer))+ try shot("cheats-de", CheatsView(m: model, library: library, gameID: id, support: support).environmentObject(modelStores.localizer))model.lang = .zh- try shot("cheats-zh", CheatsView(m: model, library: library, gameID: id, support: support).environmentObject(model.localizer))+ try shot("cheats-zh", CheatsView(m: model, library: library, gameID: id, support: support).environmentObject(modelStores.localizer))model.lang = .entry fm.removeItem(at: folder)try write("x", ".cheats-running-\(game)", under: folder)- try shot("cheats-empty", CheatsView(m: model, library: library, gameID: id, support: support).environmentObject(model.localizer))+ try shot("cheats-empty", CheatsView(m: model, library: library, gameID: id, support: support).environmentObject(modelStores.localizer))}}/// Issue #252: an iPhone or iPad game runs data cheats only, so the Cheats sheet carries a note for a game with an iOS build.-final class CheatsIOSNoteTests: XCTestCase {+@MainActor final class CheatsIOSNoteTests: XCTestCase {func testNoteShowsOnlyWithAnIOSBuild() throws {let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-iosnote-" + UUID().uuidString)try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)diff --git a/frontend/Tests/NX2AppleTests/CloudFolderTests.swift b/frontend/Tests/NX2AppleTests/CloudFolderTests.swiftindex 1822d9c8..d4f202b5 100644--- a/frontend/Tests/NX2AppleTests/CloudFolderTests.swift+++ b/frontend/Tests/NX2AppleTests/CloudFolderTests.swift@@ -1,11 +1,12 @@import XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// #263: a build folder in iCloud Drive fails at the signing step ("resource fork, Finder information, or similar detritus not/// allowed"). The launcher says so before the build starts, and reads the same words from a log.-final class CloudFolderTests: XCTestCase {+@MainActor final class CloudFolderTests: XCTestCase {private var home: URL!private var saved: [(String, Any?)] = []@@ -113,9 +114,9 @@ final class CloudFolderTests: XCTestCase {try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)try "x".write(to: url, atomically: true, encoding: .utf8)}- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildm.target = BuildTarget.mac // the iPhone / iPad target stops first, at the device check- m.repoPath = repo.path+ mStores.repo.path = repo.pathm.outDir = ""m.updateSlot("base") { $0.paths = ["/Games/Game [0100152000022000].nsp"] }var asked: [String] = []diff --git a/frontend/Tests/NX2AppleTests/ConsolePadTests.swift b/frontend/Tests/NX2AppleTests/ConsolePadTests.swiftindex 0611ca32..6dc0dac8 100644--- a/frontend/Tests/NX2AppleTests/ConsolePadTests.swift+++ b/frontend/Tests/NX2AppleTests/ConsolePadTests.swift@@ -3,11 +3,12 @@ import SwiftUIimport Combine@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// The player-mode setting's plumbing and the controller path into console mode (the same LauncherGamepad.perform/// closure the desktop launcher and the onboarding use). A real controller still needs a manual check.-final class ConsolePadTests: XCTestCase {+@MainActor final class ConsolePadTests: XCTestCase {private func freshDefaults() -> UserDefaults {let name = "ConsolePadTests.\(UUID().uuidString)"let defaults = UserDefaults(suiteName: name)!@@ -202,9 +203,9 @@ final class ConsolePadTests: XCTestCase {let library = GameLibrary(file: output.appendingPathComponent("unused-library.json"))// the bottom right shows the Home hint and the Console mode button while a controller is connected (this Mac's, when one is)for width: CGFloat in [1280, 900] {- try shot(AnyView(ContentView(model: BuildModel(), library: library, performStartupChecks: false, enterConsole: {})), "desktop-bar-\(Int(width))", width, 720)+ try shot(AnyView(ContentView(stores: LauncherStores(), library: library, performStartupChecks: false, enterConsole: {})), "desktop-bar-\(Int(width))", width, 720)}- try shot(AnyView(ContentView(model: BuildModel(), library: library, performStartupChecks: false, enterConsole: {}, qaPrompt: true)), "prompt-windowed", 1000, 720)+ try shot(AnyView(ContentView(stores: LauncherStores(), library: library, performStartupChecks: false, enterConsole: {}, qaPrompt: true)), "prompt-windowed", 1000, 720)for lang in [Lang.en, .zh] {try shot(AnyView(ConsoleConnectionPrompt(lang: lang, enterConsole: {}, dismissPrompt: {}).environmentObject(PadFocus()).preferredColorScheme(.dark)), "prompt-\(lang.rawValue)", 900, 500)}diff --git a/frontend/Tests/NX2AppleTests/ConsoleTests.swift b/frontend/Tests/NX2AppleTests/ConsoleTests.swiftindex e328b6db..4491cc77 100644--- a/frontend/Tests/NX2AppleTests/ConsoleTests.swift+++ b/frontend/Tests/NX2AppleTests/ConsoleTests.swift@@ -3,9 +3,10 @@ import SwiftUIimport Combine@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher-final class ConsoleTests: XCTestCase {+@MainActor final class ConsoleTests: XCTestCase {/// The games ready on this Mac come first. The rest follow in their own order, each with its status.func testReadyGamesComeFirst() {func game(_ id: String, _ status: ConsoleGame.Status) -> ConsoleGame {@@ -206,12 +207,12 @@ final class ConsoleTests: XCTestCase {try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)for lang in CaptureLanguage.all([.en, .zh]) {for width: CGFloat in [900, 1280] {- let model = BuildModel()+ let modelStores = LauncherStores(); let model = modelStores.buildmodel.lang = langlet library = GameLibrary(file: output.appendingPathComponent("unused-library.json"))let driver = MockConsoleDriver(scenario: .controllersMixed, lang: lang, animated: false)driver.back()- let view = ContentView(model: model, library: library, performStartupChecks: false, controllerDriver: AnyConsoleDriver(driver))+ let view = ContentView(stores: modelStores, library: library, performStartupChecks: false, controllerDriver: AnyConsoleDriver(driver))let host = NSHostingView(rootView: view)let window = NSWindow(contentRect: NSRect(x: -10000, y: 0, width: width, height: 800), styleMask: [.borderless], backing: .buffered, defer: false)window.isReleasedWhenClosed = falsediff --git a/frontend/Tests/NX2AppleTests/DropFilesTests.swift b/frontend/Tests/NX2AppleTests/DropFilesTests.swiftindex 330d9493..3a2930d9 100644--- a/frontend/Tests/NX2AppleTests/DropFilesTests.swift+++ b/frontend/Tests/NX2AppleTests/DropFilesTests.swift@@ -2,10 +2,11 @@ import XCTestimport SwiftUI@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// Files dropped on the Builds page (issue #68), sorted by the same classification as Choose game folder.-final class DropFilesTests: XCTestCase {+@MainActor final class DropFilesTests: XCTestCase {private var temporary: URL!override func setUpWithError() throws {@@ -25,7 +26,7 @@ final class DropFilesTests: XCTestCase {}func testPickedFilesThatDoNotFitTheRowAreNotTaken() throws {- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildlet base = try file("01007EF00011E000_v0_420d1c5034ab.nsp")let update = try file("01007EF00011E800_v1114112_038ff9df0888.nsp")let dlc1 = try file("01007EF00011F001_v196608_8a46aae731b8.nsp")@@ -62,7 +63,7 @@ final class DropFilesTests: XCTestCase {let new = try file("01007EF00011E800_v1114112_038ff9df0888.nsp", in: "reporter")_ = try file("01007EF00011F001_v196608_8a46aae731b8.nsp", in: "reporter")_ = try file("01007EF00011F002_v196608_193e5731baf2.nsp", in: "reporter")- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildm.lang = .enm.scan(folder: folder.path)XCTAssertEqual(m.updatePath, new)@@ -71,11 +72,11 @@ final class DropFilesTests: XCTestCase {XCTAssertTrue(m.slot("update").summary(m.t).contains("the newest of 2"))XCTAssertFalse(m.slot("update").note.contains(";"))XCTAssertTrue(m.slot("dlc").summary(m.t).hasPrefix("2 files"))- XCTAssertTrue(BuildModel().slot("dlc").summary(m.t).contains("several files"))+ XCTAssertTrue(LauncherStores().build.slot("dlc").summary(m.t).contains("several files"))}func testDroppedFilesJoinWhatIsAlreadyChosen() throws {- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildlet base = try file("Game [0100000000010000].nsp", in: "base")let dlc1 = try file("Game DLC [0100000000011001].nsp", in: "dlc")m.take(dropped: [base, dlc1])@@ -95,7 +96,7 @@ final class DropFilesTests: XCTestCase {m.take(dropped: [try file("cover.jpg")])XCTAssertEqual(m.basePath, base)XCTAssertEqual(m.slot("base").problem, "")- let empty = BuildModel()+ let emptyStores = LauncherStores(); let empty = emptyStores.buildempty.take(dropped: [try file("notes.txt")])XCTAssertEqual(empty.slot("base").problem, "data.noNsp")}@@ -106,7 +107,7 @@ final class DropFilesTests: XCTestCase {let keys = try file("prod.keys", in: "Game")try file("Game [0100000000010800][v999999].nsp", in: "Game/0100000000010000_build") // the pipeline's own folder is prunedlet folder = temporary.appendingPathComponent("Game").path- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildm.take(dropped: [folder])XCTAssertEqual(m.gameDir, folder)XCTAssertEqual(m.basePath, base)@@ -114,7 +115,7 @@ final class DropFilesTests: XCTestCase {XCTAssertEqual(m.keysPath, keys)// a folder with a file beside it: the folder's files and the file, added to what is chosen- let other = BuildModel()+ let otherStores = LauncherStores(); let other = otherStores.buildlet dlc = try file("Game DLC [0100000000011001].nsp", in: "elsewhere")other.take(dropped: [folder, dlc])XCTAssertEqual(other.basePath, base)@@ -131,14 +132,14 @@ final class DropFilesTests: XCTestCase {NSApplication.shared.setActivationPolicy(.accessory)let oldOutput = UserDefaults.standard.object(forKey: "buildOutputDirectory")defer { UserDefaults.standard.set(oldOutput, forKey: "buildOutputDirectory") }- let model = BuildModel()+ let modelStores = LauncherStores(); let model = modelStores.buildmodel.lang = CaptureLanguage.current(.en)model.outDir = temporary.path- MainActor.assumeIsolated { model.dependencies.checked = true }- MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }+ MainActor.assumeIsolated { modelStores.dependencies.checked = true }+ MainActor.assumeIsolated { modelStores.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))// the page as a drag shows it: the highlight drawn over the Builds page- let page = BuilderView(m: model, updates: model.appUpdates, repo: model.repo, engine: model.engineSync, dependencies: model.dependencies, devices: model.deviceStore, library: library).environmentObject(PadFocus()).environmentObject(model.localizer)+ let page = BuilderView(m: model, updates: modelStores.appUpdates, repo: modelStores.repo, engine: modelStores.engineSync, dependencies: modelStores.dependencies, devices: modelStores.deviceStore, library: library).environmentObject(PadFocus()).environmentObject(modelStores.localizer).modifier(GameFilesDrop(enabled: true, label: model.t("drop.hint"), targeted: true) { _ in }).frame(width: 1100, height: 760).background(LauncherPalette.background).environment(\.colorScheme, .dark)let host = NSHostingView(rootView: page)diff --git a/frontend/Tests/NX2AppleTests/EngineLayoutTests.swift b/frontend/Tests/NX2AppleTests/EngineLayoutTests.swiftindex 4d481d3a..c32f1a1f 100644--- a/frontend/Tests/NX2AppleTests/EngineLayoutTests.swift+++ b/frontend/Tests/NX2AppleTests/EngineLayoutTests.swift@@ -1,6 +1,7 @@import XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// #214: which engine the launcher builds from. A checkout of this repository builds from its engine/ (synced first when it is stale or@@ -107,49 +108,49 @@ import XCTest}/// A checkout whose tools/engine.py is `script` (a stand-in for the real one) and a model on it.- private func model(engineScript script: String) throws -> BuildModel {+ private func model(engineScript script: String) throws -> LauncherStores {try newLayout()try touch("tools/engine.py", script)- let m = BuildModel()- m.repoPath = repo- m.dependencies.pythonPath = "/usr/bin/python3"- return m+ let mStores = LauncherStores()+ mStores.repo.path = repo+ mStores.dependencies.pythonPath = "/usr/bin/python3"+ return mStores}- private func waitForSync(_ m: BuildModel, file: StaticString = #filePath, line: UInt = #line) {+ private func waitForSync(_ mStores: LauncherStores, file: StaticString = #filePath, line: UInt = #line) {let deadline = Date().addingTimeInterval(20)- while m.engineSync.syncing && Date() < deadline { RunLoop.current.run(until: Date().addingTimeInterval(0.05)) }- XCTAssertFalse(m.engineSync.syncing, "the sync did not end", file: file, line: line)+ while mStores.engineSync.syncing && Date() < deadline { RunLoop.current.run(until: Date().addingTimeInterval(0.05)) }+ XCTAssertFalse(mStores.engineSync.syncing, "the sync did not end", file: file, line: line)}func testNoNetworkShowsTheStatusThenTheOfflineRowAndRetryRunsTheSyncAgain() throws {let counter = root.appendingPathComponent("runs.txt").path- let m = try model(engineScript: """+ let mStores = try model(engineScript: """import sysopen(\(String(reflecting: counter)), 'a').write('x')print('engine: cannot fetch aaaaaaaaaaaa from https://github.com/seedds/nxnative.git: Could not resolve host: github.com')sys.exit(2)""")- XCTAssertNil(m.engineSync.failure)- m.engineSync.syncEngine()- XCTAssertTrue(m.engineSync.syncing, "the status line shows while the engine is fetched")- waitForSync(m)- XCTAssertEqual(m.engineSync.failure?.kind, .engineOffline)- XCTAssertTrue(m.logTail.contains("cannot fetch"), "the log has the tool's line")- m.engineSync.retrySync()- XCTAssertNil(m.engineSync.failure, "Try again clears the row")- XCTAssertTrue(m.engineSync.syncing)- waitForSync(m)- XCTAssertEqual(m.engineSync.failure?.kind, .engineOffline)+ XCTAssertNil(mStores.engineSync.failure)+ mStores.engineSync.syncEngine()+ XCTAssertTrue(mStores.engineSync.syncing, "the status line shows while the engine is fetched")+ waitForSync(mStores)+ XCTAssertEqual(mStores.engineSync.failure?.kind, .engineOffline)+ XCTAssertTrue(mStores.build.logTail.contains("cannot fetch"), "the log has the tool's line")+ mStores.engineSync.retrySync()+ XCTAssertNil(mStores.engineSync.failure, "Try again clears the row")+ XCTAssertTrue(mStores.engineSync.syncing)+ waitForSync(mStores)+ XCTAssertEqual(mStores.engineSync.failure?.kind, .engineOffline)XCTAssertEqual(try String(contentsOfFile: counter, encoding: .utf8), "xx", "the retry ran the tool again")}func testASyncThatWorksLeavesNoRow() throws {- let m = try model(engineScript: "print('engine: ready')\n")- m.engineSync.failure = BuildFailure(kind: .engineOffline, gameName: nil)- m.engineSync.syncEngine()- waitForSync(m)- XCTAssertNil(m.engineSync.failure)+ let mStores = try model(engineScript: "print('engine: ready')\n")+ mStores.engineSync.failure = BuildFailure(kind: .engineOffline, gameName: nil)+ mStores.engineSync.syncEngine()+ waitForSync(mStores)+ XCTAssertNil(mStores.engineSync.failure)}func testOfflineRowsHaveARetryButtonAndTheStatusLineHasText() {diff --git a/frontend/Tests/NX2AppleTests/EngineUpdateModelTests.swift b/frontend/Tests/NX2AppleTests/EngineUpdateModelTests.swiftindex 902e1107..7a9fea47 100644--- a/frontend/Tests/NX2AppleTests/EngineUpdateModelTests.swift+++ b/frontend/Tests/NX2AppleTests/EngineUpdateModelTests.swift@@ -1,24 +1,25 @@import XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// The engine in the model: that the release app never runs git, and the engine strings. What the app does with an update check's/// outcome is `EngineSyncStore`, tested in NXModelTests. Nothing here touches the network or the store.-final class EngineUpdateModelTests: XCTestCase {+@MainActor final class EngineUpdateModelTests: XCTestCase {private let root = URL(fileURLWithPath: "/nonexistent-engine-bundle")/// A launcher built from the repository keeps git, the release app never touches it.@MainActor func testTheReleaseAppNeverRunsGit() {- let m = BuildModel()- m.engineSync.bundle = root- m.repo.clone()- m.repo.pull()- m.repo.autoPull(3)- m.repo.adoptAsGit()- m.repo.checkForUpdates()- XCTAssertFalse(m.repo.busy)- XCTAssertEqual(m.repo.status, "")+ let mStores = LauncherStores(); let m = mStores.build+ mStores.engineSync.bundle = root+ mStores.repo.clone()+ mStores.repo.pull()+ mStores.repo.autoPull(3)+ mStores.repo.adoptAsGit()+ mStores.repo.checkForUpdates()+ XCTAssertFalse(mStores.repo.busy)+ XCTAssertEqual(mStores.repo.status, "")}// MARK: Stringsdiff --git a/frontend/Tests/NX2AppleTests/FrameTimesTests.swift b/frontend/Tests/NX2AppleTests/FrameTimesTests.swiftindex cca294e3..2a3d9a35 100644--- a/frontend/Tests/NX2AppleTests/FrameTimesTests.swift+++ b/frontend/Tests/NX2AppleTests/FrameTimesTests.swift@@ -2,10 +2,11 @@ import XCTestimport SwiftUI@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// Frame-time recordings (DM_NVN_TSV): reading the host's timing rows and summing them up as scripts/bench.py does.-final class FrameTimesTests: XCTestCase {+@MainActor final class FrameTimesTests: XCTestCase {/// Rows as the host writes them (dm/gfx/nvn/hle_nvn.c): frame, @metric, value; call-count rows and junk in between.private let tsv = """1\t@t_s\t0.000@@ -176,9 +177,9 @@ final class FrameTimesTests: XCTestCase {let saved = UserDefaults.standard.object(forKey: key)defer { UserDefaults.standard.set(saved, forKey: key) }FrameTimes.setEnabled(true, titleID: titleID)- let model = BuildModel()+ let modelStores = LauncherStores(); let model = modelStores.buildmodel.lang = .en- let host = NSHostingView(rootView: LaunchOptionsView(m: model, library: library, gameID: library.games[0].id).environmentObject(PadFocus()).environmentObject(model.localizer))+ let host = NSHostingView(rootView: LaunchOptionsView(m: model, library: library, gameID: library.games[0].id).environmentObject(PadFocus()).environmentObject(modelStores.localizer))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 900, height: 1300), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)window.contentView = hostwindow.orderFront(nil)diff --git a/frontend/Tests/NX2AppleTests/KeyCheckTests.swift b/frontend/Tests/NX2AppleTests/KeyCheckTests.swiftindex e94fdba4..bbb4d4f0 100644--- a/frontend/Tests/NX2AppleTests/KeyCheckTests.swift+++ b/frontend/Tests/NX2AppleTests/KeyCheckTests.swift@@ -2,10 +2,11 @@ import XCTestimport SwiftUI@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// prod.keys against the game files before a build (issue #63). Every key here is made up for the test.-final class KeyCheckTests: XCTestCase {+@MainActor final class KeyCheckTests: XCTestCase {private var temporary: URL!private let headerKey = (0..<32).map { UInt8(0xA0 ^ $0) }@@ -170,11 +171,11 @@ final class KeyCheckTests: XCTestCase {NSApplication.shared.setActivationPolicy(.accessory)let oldOutput = UserDefaults.standard.object(forKey: "buildOutputDirectory")defer { UserDefaults.standard.set(oldOutput, forKey: "buildOutputDirectory") }- let model = BuildModel()+ let modelStores = LauncherStores(); let model = modelStores.buildmodel.lang = CaptureLanguage.current(.en)model.outDir = temporary.path- MainActor.assumeIsolated { model.dependencies.checked = true }- MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }+ MainActor.assumeIsolated { modelStores.dependencies.checked = true }+ MainActor.assumeIsolated { modelStores.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))let base = try pfs0([("a.nca", ncaHeader(generation: 0x0C))], name: "Metroid Dread [010093801237C000].nsp")let update = try pfs0([("b.nca", ncaHeader(generation: 0x13))], name: "Metroid Dread [010093801237C800][v327680].nsp")@@ -182,7 +183,7 @@ final class KeyCheckTests: XCTestCase {model.slots[0].paths = [base]model.slots[1].paths = withUpdate ? [update] : []model.slots[3].paths = [try keysFile(keys)]- let host = NSHostingView(rootView: ContentView(model: model, library: library, initialPage: .builds, performStartupChecks: false))+ let host = NSHostingView(rootView: ContentView(stores: modelStores, library: library, initialPage: .builds, performStartupChecks: false))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1440, height: 1024), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)window.contentView = hostwindow.orderFront(nil)diff --git a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swiftindex 9f72f766..2f6b0203 100644--- a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift+++ b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift@@ -3,13 +3,14 @@ import SwiftUIimport XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// The buttons and dropdowns in the setting rows share one width and one height (LauncherControl) and show their label on one/// line. Nothing here lists labels: the real Settings and Builds pages are drawn in every language the launcher has, and each/// control reports what it measured (LauncherControlSample), so a new button, a new string or a new language is checked as soon as/// a page shows it.-final class LauncherControlWidthTests: XCTestCase {+@MainActor final class LauncherControlWidthTests: XCTestCase {private func width(_ text: String, size: CGFloat = 13) throws -> CGFloat {let font = try XCTUnwrap(Typography.manropeFont(size: size, weight: .semibold))let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: [.font: font]))@@ -56,7 +57,7 @@ final class LauncherControlWidthTests: XCTestCase {let page: LauncherPage/// The controls this state must show at least, so that a page that draws nothing cannot pass.let atLeast: Int- let set: (BuildModel, GameLibrary, URL) throws -> Void+ let set: (LauncherStores, GameLibrary, URL) throws -> Void}private func makeRepo(_ directory: URL, git: Bool) throws -> String {@@ -77,76 +78,76 @@ final class LauncherControlWidthTests: XCTestCase {Dep(id: id, name: "dep.xcode", hint: "dep.xcode.hint", present: false, actionLabel: action, installCmd: command)}return [- Scenario(name: "settings without a repository", page: .settings, atLeast: 4) { m, _, _ in- m.repoPath = ""- MainActor.assumeIsolated { m.appUpdates.installability = .ok }+ Scenario(name: "settings without a repository", page: .settings, atLeast: 4) { s, _, _ in+ s.repo.path = ""+ MainActor.assumeIsolated { s.appUpdates.installability = .ok }},- Scenario(name: "settings with a ZIP copy and a library folder", page: .settings, atLeast: 6) { m, library, directory in- m.repoPath = try self.makeRepo(directory, git: false)- MainActor.assumeIsolated { m.appUpdates.installability = .ok }- MainActor.assumeIsolated { m.dependencies.checked = true }- MainActor.assumeIsolated { m.dependencies.deps = [Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: [])] }+ Scenario(name: "settings with a ZIP copy and a library folder", page: .settings, atLeast: 6) { s, library, directory in+ s.repo.path = try self.makeRepo(directory, git: false)+ MainActor.assumeIsolated { s.appUpdates.installability = .ok }+ MainActor.assumeIsolated { s.dependencies.checked = true }+ MainActor.assumeIsolated { s.dependencies.deps = [Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: [])] }library.setFolder(directory)},- Scenario(name: "settings with a clone that is behind and an app update", page: .settings, atLeast: 6) { m, _, directory in- m.repoPath = try self.makeRepo(directory, git: true)- MainActor.assumeIsolated { m.repo.behind = 2 }- MainActor.assumeIsolated { m.appUpdates.installability = .ok }- MainActor.assumeIsolated { m.appUpdates.update = release }+ Scenario(name: "settings with a clone that is behind and an app update", page: .settings, atLeast: 6) { s, _, directory in+ s.repo.path = try self.makeRepo(directory, git: true)+ MainActor.assumeIsolated { s.repo.behind = 2 }+ MainActor.assumeIsolated { s.appUpdates.installability = .ok }+ MainActor.assumeIsolated { s.appUpdates.update = release }},- Scenario(name: "settings with an update ready to restart into", page: .settings, atLeast: 4) { m, _, directory in- m.repoPath = try self.makeRepo(directory, git: true)- MainActor.assumeIsolated { m.appUpdates.installability = .ok }- MainActor.assumeIsolated { m.appUpdates.staged = AppUpdate.Staged(release: release, app: directory.appendingPathComponent("NX2Apple.app")) }+ Scenario(name: "settings with an update ready to restart into", page: .settings, atLeast: 4) { s, _, directory in+ s.repo.path = try self.makeRepo(directory, git: true)+ MainActor.assumeIsolated { s.appUpdates.installability = .ok }+ MainActor.assumeIsolated { s.appUpdates.staged = AppUpdate.Staged(release: release, app: directory.appendingPathComponent("NX2Apple.app")) }},- Scenario(name: "settings with every kind of missing tool", page: .settings, atLeast: 6) { m, _, directory in- m.repoPath = try self.makeRepo(directory, git: true)- MainActor.assumeIsolated { m.dependencies.checked = true }- MainActor.assumeIsolated { m.dependencies.deps = [missing("a"), missing("b", command: ["brew", "install", "x"]), missing("c", action: "dep.xcode.fix", command: ["x"])] }- MainActor.assumeIsolated { m.dependencies.expanded = true }+ Scenario(name: "settings with every kind of missing tool", page: .settings, atLeast: 6) { s, _, directory in+ s.repo.path = try self.makeRepo(directory, git: true)+ MainActor.assumeIsolated { s.dependencies.checked = true }+ MainActor.assumeIsolated { s.dependencies.deps = [missing("a"), missing("b", command: ["brew", "install", "x"]), missing("c", action: "dep.xcode.fix", command: ["x"])] }+ MainActor.assumeIsolated { s.dependencies.expanded = true }},- Scenario(name: "builds without a repository", page: .builds, atLeast: 4) { m, _, _ in- m.repoPath = ""- m.target = "mac-app"+ Scenario(name: "builds without a repository", page: .builds, atLeast: 4) { s, _, _ in+ s.repo.path = ""+ s.build.target = "mac-app"},- Scenario(name: "builds with files chosen for a Mac app", page: .builds, atLeast: 5) { m, _, directory in- m.repoPath = try self.makeRepo(directory, git: true)- m.target = "mac-app"- m.gameDir = directory.path- m.outDir = directory.path- m.slots[0].paths = [directory.appendingPathComponent("Hades [0100535012974000].nsp").path]- m.slots[1].paths = [directory.appendingPathComponent("Hades update [0100535012974800].nsp").path]+ Scenario(name: "builds with files chosen for a Mac app", page: .builds, atLeast: 5) { s, _, directory in+ s.repo.path = try self.makeRepo(directory, git: true)+ s.build.target = "mac-app"+ s.build.gameDir = directory.path+ s.build.outDir = directory.path+ s.build.slots[0].paths = [directory.appendingPathComponent("Hades [0100535012974000].nsp").path]+ s.build.slots[1].paths = [directory.appendingPathComponent("Hades update [0100535012974800].nsp").path]},- Scenario(name: "builds for an iPhone with a device and a team", page: .builds, atLeast: 6) { m, _, directory in- m.repoPath = try self.makeRepo(directory, git: true)- m.target = "ios"- MainActor.assumeIsolated { m.deviceStore.checked = true }- MainActor.assumeIsolated { m.deviceStore.devices = [device] }- MainActor.assumeIsolated { m.deviceStore.teams = [team] }- m.installDevice = device.id- m.signingTeam = team.id+ Scenario(name: "builds for an iPhone with a device and a team", page: .builds, atLeast: 6) { s, _, directory in+ s.repo.path = try self.makeRepo(directory, git: true)+ s.build.target = "ios"+ MainActor.assumeIsolated { s.deviceStore.checked = true }+ MainActor.assumeIsolated { s.deviceStore.devices = [device] }+ MainActor.assumeIsolated { s.deviceStore.teams = [team] }+ s.deviceStore.installDevice = device.id+ s.deviceStore.signingTeam = team.id},- Scenario(name: "a finished Mac app build", page: .builds, atLeast: 6) { m, _, directory in- m.repoPath = try self.makeRepo(directory, git: true)- m.target = "mac-app"- m.done = true- m.macAppPath = directory.appendingPathComponent("Hades.app").path+ Scenario(name: "a finished Mac app build", page: .builds, atLeast: 6) { s, _, directory in+ s.repo.path = try self.makeRepo(directory, git: true)+ s.build.target = "mac-app"+ s.build.done = true+ s.build.macAppPath = directory.appendingPathComponent("Hades.app").path},- Scenario(name: "a build installed on an iPhone", page: .builds, atLeast: 6) { m, _, directory in- m.repoPath = try self.makeRepo(directory, git: true)- m.target = "ios"- m.done = true- MainActor.assumeIsolated { m.deviceStore.checked = true }- MainActor.assumeIsolated { m.deviceStore.devices = [device] }- m.installedOn = device.id- m.archivePath = directory.appendingPathComponent("romfs").path+ Scenario(name: "a build installed on an iPhone", page: .builds, atLeast: 6) { s, _, directory in+ s.repo.path = try self.makeRepo(directory, git: true)+ s.build.target = "ios"+ s.build.done = true+ MainActor.assumeIsolated { s.deviceStore.checked = true }+ MainActor.assumeIsolated { s.deviceStore.devices = [device] }+ s.build.installedOn = device.id+ s.build.archivePath = directory.appendingPathComponent("romfs").path},- Scenario(name: "a finished iPhone build without an install", page: .builds, atLeast: 6) { m, _, directory in- m.repoPath = try self.makeRepo(directory, git: true)- m.target = "ios"- m.done = true- MainActor.assumeIsolated { m.deviceStore.checked = true }- m.archivePath = directory.appendingPathComponent("romfs").path+ Scenario(name: "a finished iPhone build without an install", page: .builds, atLeast: 6) { s, _, directory in+ s.repo.path = try self.makeRepo(directory, git: true)+ s.build.target = "ios"+ s.build.done = true+ MainActor.assumeIsolated { s.deviceStore.checked = true }+ s.build.archivePath = directory.appendingPathComponent("romfs").path},]}@@ -156,12 +157,12 @@ final class LauncherControlWidthTests: XCTestCase {let directory = FileManager.default.temporaryDirectory.appendingPathComponent("control-width-\(UUID().uuidString)")try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(at: directory) }- let model = BuildModel()+ let modelStores = LauncherStores(); let model = modelStores.buildlet library = GameLibrary(file: directory.appendingPathComponent("library.json"))- try scenario.set(model, library, directory)+ try scenario.set(modelStores, library, directory)model.lang = langlet samples = Samples()- let view = ContentView(model: model, library: library, initialPage: scenario.page, activeBuildID: nil, performStartupChecks: false,+ let view = ContentView(stores: modelStores, library: library, initialPage: scenario.page, activeBuildID: nil, performStartupChecks: false,search: nil, olderTools: [], manageOpen: false, padRing: false).environment(\.measuresLauncherControls, true).onPreferenceChange(LauncherControlSamples.self) { samples.all = $0 }@@ -269,11 +270,11 @@ final class LauncherControlWidthTests: XCTestCase {let file = directory.appendingPathComponent("library.json")try JSONEncoder().encode(Snapshot(games: [game], folder: directory.path)).write(to: file)let library = GameLibrary(file: file)- let model = BuildModel()+ let modelStores = LauncherStores(); let model = modelStores.buildfor lang in Lang.allCases {model.lang = langlet samples = Samples()- let view = LaunchOptionsView(m: model, library: library, gameID: game.id).environmentObject(PadFocus()).environmentObject(model.localizer)+ let view = LaunchOptionsView(m: model, library: library, gameID: game.id).environmentObject(PadFocus()).environmentObject(modelStores.localizer).environment(\.measuresLauncherControls, true).onPreferenceChange(LauncherControlSamples.self) { samples.all = $0 }let host = NSHostingView(rootView: view)diff --git a/frontend/Tests/NX2AppleTests/LauncherPerformanceTests.swift b/frontend/Tests/NX2AppleTests/LauncherPerformanceTests.swiftindex e3ae297a..854ced6a 100644--- a/frontend/Tests/NX2AppleTests/LauncherPerformanceTests.swift+++ b/frontend/Tests/NX2AppleTests/LauncherPerformanceTests.swift@@ -3,6 +3,7 @@ import SwiftUIimport XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// Guards the launcher against changes that make it slow. A synthetic library (30 owned games with banners, every third one@@ -13,7 +14,7 @@ import XCTest/// Info.plist reads and frame time recordings parsed. The counts do not depend on the machine, so they catch work that grows/// with the library long before a stopwatch would. The second guard is the time the main thread is busy, the median of/// several rounds, with budgets far above what main needs on CI. See "Launcher performance test" in frontend/README.md.-final class LauncherPerformanceTests: XCTestCase {+@MainActor final class LauncherPerformanceTests: XCTestCase {private var temporary: URL!override func setUpWithError() throws {@@ -133,13 +134,13 @@ final class LauncherPerformanceTests: XCTestCase {NSApplication.shared.setActivationPolicy(.accessory)let saved = ["repoPath", "buildOutputDirectory"].map { ($0, UserDefaults.standard.object(forKey: $0)) }defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }- let model = BuildModel()- model.repoPath = world.repo.path+ let modelStores = LauncherStores(); let model = modelStores.build+ modelStores.repo.path = world.repo.pathmodel.lang = .enlet library = GameLibrary(file: world.libraryFile)library.selectedID = world.selectedlet pad = LauncherGamepad()- let host = NSHostingView(rootView: ContentView(model: model, library: library, performStartupChecks: false, gamepad: pad))+ let host = NSHostingView(rootView: ContentView(stores: modelStores, library: library, performStartupChecks: false, gamepad: pad))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1280, height: 900), styleMask: [.titled, .closable, .resizable],backing: .buffered, defer: false)window.isReleasedWhenClosed = falsediff --git a/frontend/Tests/NX2AppleTests/LibraryTests.swift b/frontend/Tests/NX2AppleTests/LibraryTests.swiftindex 6cf12214..9878a226 100644--- a/frontend/Tests/NX2AppleTests/LibraryTests.swift+++ b/frontend/Tests/NX2AppleTests/LibraryTests.swift@@ -3,9 +3,10 @@ import SwiftUIimport Combine@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher-final class LibraryTests: XCTestCase {+@MainActor final class LibraryTests: XCTestCase {private var temporary: URL!private let titleID = "0100535012974000"@@ -288,14 +289,14 @@ final class LibraryTests: XCTestCase {guard FileManager.default.isExecutableFile(atPath: "/usr/bin/python3") else { throw XCTSkip("System Python is required for the process fixture") }let saved = ["repoPath", "buildTarget", "buildOutputDirectory"].map { ($0, UserDefaults.standard.object(forKey: $0)) }defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }- let model = BuildModel()- model.repoPath = temporary.path+ let modelStores = LauncherStores(); let model = modelStores.build+ modelStores.repo.path = temporary.pathmodel.target = "mac-app"model.outDir = temporary.path- MainActor.assumeIsolated { model.dependencies.pythonPath = "/usr/bin/python3" }- MainActor.assumeIsolated { model.dependencies.dotnetPath = "/usr/bin/true" }- MainActor.assumeIsolated { model.dependencies.checked = true }- MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])] }+ MainActor.assumeIsolated { modelStores.dependencies.pythonPath = "/usr/bin/python3" }+ MainActor.assumeIsolated { modelStores.dependencies.dotnetPath = "/usr/bin/true" }+ MainActor.assumeIsolated { modelStores.dependencies.checked = true }+ MainActor.assumeIsolated { modelStores.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])] }let marker = temporary.appendingPathComponent("dm/tools/nx_extract/Program.cs")try FileManager.default.createDirectory(at: marker.deletingLastPathComponent(), withIntermediateDirectories: true)try Data().write(to: marker)@@ -358,7 +359,7 @@ final class LibraryTests: XCTestCase {/// An action on the installed app names what is missing instead of doing nothing, and a failed reinstall is a note on/// the installed app, not a failed build (the app is still on the device).@MainActor func testReinstallAndSaveReportAMissingSignedApp() throws {- let model = BuildModel(xcrun: "/usr/bin/true")+ let modelStores = LauncherStores(xcrun: "/usr/bin/true"); let model = modelStores.buildmodel.installedOn = "00008150-AAAA"model.installedAppPath = temporary.path + "/gone/DmShell.app"var reported = expectation(description: "Reinstall says what is missing")@@ -381,16 +382,16 @@ final class LibraryTests: XCTestCase {let info: [String: Any] = ["CFBundleDisplayName": "Zelda: Echoes/of Wisdom"]try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: app.appendingPathComponent("Info.plist"))- let model = BuildModel()+ let modelStores = LauncherStores(); let model = modelStores.buildmodel.installedAppPath = app.pathXCTAssertEqual(model.defaultIPAName(), "Zelda_ Echoes_of Wisdom.ipa")}/// The two commands the actions build: a plain devicectl install of the cached app, and ditto's Payload archive.func testTheReinstallAndIPARecipes() {- XCTAssertEqual(BuildModel.reinstallCommand(xcrun: "/x", device: "D", app: "/a/DmIOS.app"),+ XCTAssertEqual(BuildCommands.reinstallCommand(xcrun: "/x", device: "D", app: "/a/DmIOS.app"),["/x", "devicectl", "device", "install", "app", "--device", "D", "/a/DmIOS.app"])- XCTAssertEqual(BuildModel.ipaCommand(payload: "/t/Payload", ipa: "/o/Game.ipa"),+ XCTAssertEqual(BuildCommands.ipaCommand(payload: "/t/Payload", ipa: "/o/Game.ipa"),["/usr/bin/ditto", "-c", "-k", "--norsrc", "--keepParent", "/t/Payload", "/o/Game.ipa"])}@@ -399,15 +400,15 @@ final class LibraryTests: XCTestCase {@MainActor func testResignOfAnOlderAppAsksForANewBuild() throws {let savedTeam = UserDefaults.standard.string(forKey: "signingTeam")defer { UserDefaults.standard.set(savedTeam, forKey: "signingTeam") }- let model = BuildModel()+ let modelStores = LauncherStores(); let model = modelStores.buildlet older = temporary.appendingPathComponent("0100_build/xcode-derived-data/Build/Products/Release-iphoneos/DmIOS.app").path- model.signingTeam = "TEAM123456"+ modelStores.deviceStore.signingTeam = "TEAM123456"var reported = expectation(description: "Older app reported")model.resignOnDevice(app: older, device: "00008150-AAAA") { reported.fulfill() }wait(for: [reported], timeout: 10)XCTAssertEqual(model.doneNote, model.t("dev.resignOlder"))XCTAssertFalse(model.running)- model.signingTeam = ""+ modelStores.deviceStore.signingTeam = ""reported = expectation(description: "Missing team reported")model.resignOnDevice(app: older, device: "00008150-AAAA") { reported.fulfill() }wait(for: [reported], timeout: 10)@@ -418,8 +419,8 @@ final class LibraryTests: XCTestCase {@MainActor func testResignReportsAMissingSharedProject() throws {let savedTeam = UserDefaults.standard.string(forKey: "signingTeam")defer { UserDefaults.standard.set(savedTeam, forKey: "signingTeam") }- let model = BuildModel()- model.signingTeam = "TEAM123456"+ let modelStores = LauncherStores(); let model = modelStores.build+ modelStores.deviceStore.signingTeam = "TEAM123456"let shared = temporary.appendingPathComponent("shell/derived-data/Build/Products/Release-iphoneos/DmShell.app")let reported = expectation(description: "Missing project reported")model.resignOnDevice(app: shared.path, device: "00008150-AAAA") { reported.fulfill() }@@ -541,15 +542,15 @@ final class LibraryTests: XCTestCase {app.setActivationPolicy(.accessory)let saved = ["repoPath", "buildTarget", "buildOutputDirectory"].map { ($0, UserDefaults.standard.object(forKey: $0)) }defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }- let model = BuildModel()+ let modelStores = LauncherStores(); let model = modelStores.buildmodel.lang = .en // the script's stage name as English shows it, whatever the Mac's language- model.repoPath = temporary.path+ modelStores.repo.path = temporary.pathmodel.target = "mac-app"model.outDir = temporary.path- MainActor.assumeIsolated { model.dependencies.pythonPath = "/usr/bin/python3" }- MainActor.assumeIsolated { model.dependencies.dotnetPath = "/usr/bin/true" }- MainActor.assumeIsolated { model.dependencies.checked = true }- MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])] }+ MainActor.assumeIsolated { modelStores.dependencies.pythonPath = "/usr/bin/python3" }+ MainActor.assumeIsolated { modelStores.dependencies.dotnetPath = "/usr/bin/true" }+ MainActor.assumeIsolated { modelStores.dependencies.checked = true }+ MainActor.assumeIsolated { modelStores.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])] }let marker = temporary.appendingPathComponent("dm/tools/nx_extract/Program.cs")try FileManager.default.createDirectory(at: marker.deletingLastPathComponent(), withIntermediateDirectories: true)try Data().write(to: marker)@@ -583,7 +584,7 @@ final class LibraryTests: XCTestCase {model.slots[0].paths = [base.path]model.slots[3].paths = [keys.path]let library = GameLibrary(file: temporary.appendingPathComponent("library.json"))- let host = NSHostingView(rootView: ContentView(model: model, library: library, initialPage: .builds, performStartupChecks: false))+ let host = NSHostingView(rootView: ContentView(stores: modelStores, library: library, initialPage: .builds, performStartupChecks: false))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1100, height: 800), styleMask: [.titled], backing: .buffered, defer: false)window.contentView = hostwindow.orderFront(nil)@@ -632,11 +633,11 @@ final class LibraryTests: XCTestCase {let real_ = GameLibrary(file: real)let library = GameLibrary(file: copy)let botw = "01007EF00011E000", totk = "0100F2C0115B6000"- let model = BuildModel()- model.repoPath = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().path+ let modelStores = LauncherStores(); let model = modelStores.build+ modelStores.repo.path = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().pathmodel.lang = .en- MainActor.assumeIsolated { model.dependencies.checked = true }- MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }+ MainActor.assumeIsolated { modelStores.dependencies.checked = true }+ MainActor.assumeIsolated { modelStores.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }for game in real_.games.sorted(by: { $0.name < $1.name }) {let name = game.name.replacingOccurrences(of: #"\s*\([0-9.]+ GB\)"#, with: "", options: .regularExpression)if game.titleID == botw { _ = try library.addApp(makeApp(botw, name: name)) }@@ -702,7 +703,7 @@ final class LibraryTests: XCTestCase {Stage(id: 3, name: "rewrite", state: .done, detail: "main, subsdk0, sdk"),Stage(id: 4, name: "shader split", state: .running, detail: "splitting · 10,577 / 41,062 files · 41s left", percent: 26)]library.selectedID = botwID- try shot("library", ContentView(model: model, library: library, activeBuildID: totkID, performStartupChecks: false), size: window)+ try shot("library", ContentView(stores: modelStores, library: library, activeBuildID: totkID, performStartupChecks: false), size: window)model.running = false; model.stages = []// The build page, ready to start: example paths, not the user's@@ -715,12 +716,12 @@ final class LibraryTests: XCTestCase {model.slots[0].paths = [nsp.path]; model.slots[1].paths = [update.path]; model.slots[3].paths = [keys.path]model.gameDir = "/Volumes/Games/Tears of the Kingdom"model.outDir = "/Volumes/Games"- try shot("build", ContentView(model: model, library: library, initialPage: .builds, performStartupChecks: false), size: NSSize(width: 1280, height: 940))+ try shot("build", ContentView(stores: modelStores, library: library, initialPage: .builds, performStartupChecks: false), size: NSSize(width: 1280, height: 940))if let upscale = LaunchSetting.read(app: library.games.first { $0.id == botwID }!.appPath)?.first(where: { $0.env == "DM_PRESENT_UPSCALE" }) {SavedChoices(app: library.games.first { $0.id == botwID }!.appPath, titleID: "01007EF00011E000").set(upscale, "metalfx")}- try shot("launch-options", LaunchOptionsView(m: model, library: library, gameID: botwID).environmentObject(model.localizer), size: NSSize(width: 600, height: 700), trafficLights: false) // a sheet: no window controls of its own+ try shot("launch-options", LaunchOptionsView(m: model, library: library, gameID: botwID).environmentObject(modelStores.localizer), size: NSSize(width: 600, height: 700), trafficLights: false) // a sheet: no window controls of its own}/// Opt-in native rendering for visual QA; it never touches the user's saved library.@@ -731,7 +732,7 @@ final class LibraryTests: XCTestCase {let app = NSApplication.sharedapp.setActivationPolicy(.accessory)let repo = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().path- let model = BuildModel()+ let modelStores = LauncherStores(); let model = modelStores.build// Restore any preferences changed while preparing isolated preview data.let oldRepo = UserDefaults.standard.object(forKey: "repoPath")let oldOutput = UserDefaults.standard.object(forKey: "buildOutputDirectory")@@ -739,11 +740,11 @@ final class LibraryTests: XCTestCase {UserDefaults.standard.set(oldRepo, forKey: "repoPath")UserDefaults.standard.set(oldOutput, forKey: "buildOutputDirectory")}- model.repoPath = repo+ modelStores.repo.path = repomodel.lang = CaptureLanguage.current(.en)model.outDir = temporary.path- MainActor.assumeIsolated { model.dependencies.checked = true }- MainActor.assumeIsolated { model.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }+ MainActor.assumeIsolated { modelStores.dependencies.checked = true }+ MainActor.assumeIsolated { modelStores.dependencies.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])] }let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))let examples = [(titleID, "Hades"), ("01007EF00011E000", "The Legend of Zelda: Breath of the Wild"),("0100000000010000", "Super Mario Odyssey"), ("010093801237C000", "Metroid Dread")]@@ -759,7 +760,7 @@ final class LibraryTests: XCTestCase {func capture(_ name: String, width: CGFloat = 1440, height: CGFloat = 1024, page: LauncherPage = .library, activeID: UUID? = nil, empty: Bool = false,search: String? = nil, older: Set<UUID> = [], manageOpen: Bool = false, padRing: Bool = false, only: GameLibrary? = nil) throws {let store = only ?? (empty ? GameLibrary(file: temporary.appendingPathComponent("empty.json")) : library)- let view = ContentView(model: model, library: store, initialPage: page, activeBuildID: activeID, performStartupChecks: false, search: search,+ let view = ContentView(stores: modelStores, library: store, initialPage: page, activeBuildID: activeID, performStartupChecks: false, search: search,olderTools: older, manageOpen: manageOpen, padRing: padRing)let host = NSHostingView(rootView: view)let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: width, height: height),@@ -792,31 +793,31 @@ final class LibraryTests: XCTestCase {try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)try Data([0]).write(to: url)}- let previous = (model.repoPath, model.repo.autoUpdate, model.repo.status, model.repo.autoAdopted, model.doneNote)- defer { (model.repoPath, model.repo.autoUpdate, model.repo.status, model.repo.autoAdopted, model.doneNote) = previous }- model.repoPath = zip.path- model.repo.autoUpdate = false+ let previous = (modelStores.repo.path, modelStores.repo.autoUpdate, modelStores.repo.status, modelStores.repo.autoAdopted, model.doneNote)+ defer { (modelStores.repo.path, modelStores.repo.autoUpdate, modelStores.repo.status, modelStores.repo.autoAdopted, model.doneNote) = previous }+ modelStores.repo.path = zip.path+ modelStores.repo.autoUpdate = falsetry capture("settings-zip-auto-off", page: .settings)- model.repo.autoUpdate = true- model.repo.status = String(format: model.t("repo.adoptedAuto"), "zip-copy-2026-10-27")- model.repo.autoAdopted = true+ modelStores.repo.autoUpdate = true+ modelStores.repo.status = String(format: model.t("repo.adoptedAuto"), "zip-copy-2026-10-27")+ modelStores.repo.autoAdopted = truetry capture("library-adopted")- model.repo.autoAdopted = false- model.repo.status = ""+ modelStores.repo.autoAdopted = false+ modelStores.repo.status = ""try capture("settings-zip-old-tools", page: .settings)model.startBuild() // refuses: the copy lacks romfs_image.pytry capture("build-tools-old", height: 1500, page: .builds)}do { // a released copy with an update downloaded and verified: Restart now in Settings and in the activity line- let previous = (model.appUpdates.installability, model.appUpdates.update, model.appUpdates.staged, model.appUpdates.status)- defer { (model.appUpdates.installability, model.appUpdates.update, model.appUpdates.staged, model.appUpdates.status) = previous }+ let previous = (modelStores.appUpdates.installability, modelStores.appUpdates.update, modelStores.appUpdates.staged, modelStores.appUpdates.status)+ defer { (modelStores.appUpdates.installability, modelStores.appUpdates.update, modelStores.appUpdates.staged, modelStores.appUpdates.status) = previous }let release = AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/NX2Apple-macOS-arm64.zip", digest: nil)- model.appUpdates.installability = .ok- model.appUpdates.update = release- model.appUpdates.status = String(format: model.t("app.found"), release.tag)+ modelStores.appUpdates.installability = .ok+ modelStores.appUpdates.update = release+ modelStores.appUpdates.status = String(format: model.t("app.found"), release.tag)try capture("settings-update-found", page: .settings)- model.appUpdates.staged = AppUpdate.Staged(release: release, app: temporary.appendingPathComponent("NX2Apple.app"))- model.appUpdates.status = String(format: model.t("app.ready"), release.tag)+ modelStores.appUpdates.staged = AppUpdate.Staged(release: release, app: temporary.appendingPathComponent("NX2Apple.app"))+ modelStores.appUpdates.status = String(format: model.t("app.ready"), release.tag)try capture("settings-update-ready", page: .settings)try capture("library-update-ready")}@@ -838,23 +839,23 @@ final class LibraryTests: XCTestCase {// An iPhone build with a paired device and a team (example values)let previousTarget = model.targetmodel.target = "ios"- model.deviceStore.checked = true- model.deviceStore.devices = [AppleDevice(id: "00008150-AAAA", name: "iPhone", model: "iPhone 17 Pro Max", os: "27.0", reachable: true),+ modelStores.deviceStore.checked = true+ modelStores.deviceStore.devices = [AppleDevice(id: "00008150-AAAA", name: "iPhone", model: "iPhone 17 Pro Max", os: "27.0", reachable: true),AppleDevice(id: "00008110-BBBB", name: "iPad mini", model: "iPad mini", os: "26.2", reachable: false)]- model.deviceStore.teams = [SigningTeam(id: "TEAM123456", identity: "Apple Development: Jo Doe (ABCDE12345)")]- let previousDevice = model.installDevice, previousTeam = model.signingTeam- model.installDevice = "00008150-AAAA"; model.signingTeam = "TEAM123456"+ modelStores.deviceStore.teams = [SigningTeam(id: "TEAM123456", identity: "Apple Development: Jo Doe (ABCDE12345)")]+ let previousDevice = modelStores.deviceStore.installDevice, previousTeam = modelStores.deviceStore.signingTeam+ modelStores.deviceStore.installDevice = "00008150-AAAA"; modelStores.deviceStore.signingTeam = "TEAM123456"try capture("build-install", height: 1300, page: .builds)// #87: signed in to Xcode, no certificate yet (a free personal team and a paid one), and neither account nor certificate- model.deviceStore.teams = [SigningTeam(id: "FGHIJ67890", identity: "", name: "Jo Doe", personal: true),+ modelStores.deviceStore.teams = [SigningTeam(id: "FGHIJ67890", identity: "", name: "Jo Doe", personal: true),SigningTeam(id: "KLMNO11111", identity: "", name: "Studio Ltd")]- model.signingTeam = "FGHIJ67890"+ modelStores.deviceStore.signingTeam = "FGHIJ67890"try capture("build-install-xcode-team", height: 1300, page: .builds)- model.deviceStore.teams = []; model.signingTeam = ""+ modelStores.deviceStore.teams = []; modelStores.deviceStore.signingTeam = ""try capture("build-install-no-team", height: 1300, page: .builds)- model.deviceStore.teams = [SigningTeam(id: "TEAM123456", identity: "Apple Development: Jo Doe (ABCDE12345)")]- model.signingTeam = "TEAM123456"- model.installDevice = previousDevice; model.signingTeam = previousTeam; model.target = previousTarget+ modelStores.deviceStore.teams = [SigningTeam(id: "TEAM123456", identity: "Apple Development: Jo Doe (ABCDE12345)")]+ modelStores.deviceStore.signingTeam = "TEAM123456"+ modelStores.deviceStore.installDevice = previousDevice; modelStores.deviceStore.signingTeam = previousTeam; model.target = previousTarget// The Free space sheet with a measured build folder (example sizes), two parts picked, then while a build runslet measured = BuildFolderSurvey(folder: "/Volumes/Games/Hades/\(titleID)_build",sizes: [.extracted: 9_800_000_000, .shaders: 5_850_000_000, .oldShaders: 4_400_000_000, .xcode: 2_100_000_000, .caches: 610_000_000], kept: 48_000_000,@@ -862,7 +863,7 @@ final class LibraryTests: XCTestCase {for (name, running) in [("free-space", false), ("free-space-running", true)] {model.running = runninglet sheet = NSHostingView(rootView: FreeSpaceView(m: model, game: library.games[0], survey: measured, chosen: [.extracted, .oldShaders])- .environmentObject(PadFocus()).environmentObject(model.localizer))+ .environmentObject(PadFocus()).environmentObject(modelStores.localizer))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 560, height: 690), styleMask: [.titled], backing: .buffered, defer: false)window.contentView = sheetwindow.orderFront(nil)@@ -879,7 +880,7 @@ final class LibraryTests: XCTestCase {try FileManager.default.createDirectory(at: dm, withIntermediateDirectories: true)try FileManager.default.copyItem(at: URL(fileURLWithPath: json), to: dm.appendingPathComponent("launcher.json"))if let fps = LaunchSetting.read(app: first.appPath)?.first(where: { $0.env == "DM_FPS_TARGET" }) { SavedChoices(app: first.appPath, titleID: first.titleID).set(fps, "60") }- let host = NSHostingView(rootView: LaunchOptionsView(m: model, library: library, gameID: first.id).environmentObject(PadFocus()).environmentObject(model.localizer))+ let host = NSHostingView(rootView: LaunchOptionsView(m: model, library: library, gameID: first.id).environmentObject(PadFocus()).environmentObject(modelStores.localizer))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 700), styleMask: [.titled], backing: .buffered, defer: false)window.contentView = hostwindow.orderFront(nil)@@ -890,7 +891,7 @@ final class LibraryTests: XCTestCase {window.orderOut(nil)// The same sheet with a controller's focus on the console mode rowlet focus = PadFocus()- let focused = NSHostingView(rootView: LaunchOptionsView(m: model, library: library, gameID: first.id).environmentObject(focus).environmentObject(model.localizer))+ let focused = NSHostingView(rootView: LaunchOptionsView(m: model, library: library, gameID: first.id).environmentObject(focus).environmentObject(modelStores.localizer))window.contentView = focusedwindow.orderFront(nil)RunLoop.main.run(until: Date().addingTimeInterval(0.4))@@ -910,7 +911,7 @@ final class LibraryTests: XCTestCase {let layout = ControlLayout(defaults: defaults)if let up = ControlLayout.functions.first(where: { $0.id == "RUp" }) { layout.assign(up, key: 34) }layout.setSends("A", "B"); layout.setSends("B", "A")- let host = NSHostingView(rootView: ControlsView(layout: layout).environmentObject(PadFocus()).environmentObject(model.localizer))+ let host = NSHostingView(rootView: ControlsView(layout: layout).environmentObject(PadFocus()).environmentObject(modelStores.localizer))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 700), styleMask: [.titled], backing: .buffered, defer: false)window.contentView = hostwindow.orderFront(nil)@@ -926,7 +927,7 @@ final class LibraryTests: XCTestCase {_ = crowded.rememberInputs(model)}model.slots[0].paths = []- let view = ContentView(model: model, library: crowded, performStartupChecks: false)+ let view = ContentView(stores: modelStores, library: crowded, performStartupChecks: false)let crowdedHost = NSHostingView(rootView: view)let crowdedWindow = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1280, height: 900), styleMask: [.titled], backing: .buffered, defer: false)crowdedWindow.contentView = crowdedHost@@ -976,7 +977,7 @@ final class LibraryTests: XCTestCase {layout.controllerCategory = { category }layout.setPadMode(mode)let focus = PadFocus()- let host = NSHostingView(rootView: ControlsView(layout: layout).environmentObject(focus).environmentObject(model.localizer))+ let host = NSHostingView(rootView: ControlsView(layout: layout).environmentObject(focus).environmentObject(modelStores.localizer))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 700), styleMask: [.titled], backing: .buffered, defer: false)window.contentView = hostwindow.orderFront(nil)@@ -994,9 +995,9 @@ final class LibraryTests: XCTestCase {do {try capture("settings-diagnostics", height: 1500, page: .settings)let buttons = NSHostingView(rootView: HStack(spacing: 14) {- DiagnosticsButton(m: model)- DiagnosticsButton(m: model, showCopied: true)- }.launcherRowControls().padding(24).background(LauncherPalette.background).environmentObject(PadFocus()).environmentObject(model.localizer))+ DiagnosticsButton(report: modelStores.diagnostics)+ DiagnosticsButton(report: modelStores.diagnostics, showCopied: true)+ }.launcherRowControls().padding(24).background(LauncherPalette.background).environmentObject(PadFocus()).environmentObject(modelStores.localizer))buttons.frame = NSRect(x: 0, y: 0, width: 420, height: 90)let window = NSWindow(contentRect: buttons.frame, styleMask: [.titled], backing: .buffered, defer: false)window.contentView = buttons@@ -1034,7 +1035,7 @@ final class LibraryTests: XCTestCase {let host = NSHostingView(rootView: SavesView(m: model, library: library, gameID: game.id, devicectl: device, support: support, listDevices: {[AppleDevice(id: "00008150-AAAA", name: "Zijad\u{2019}s iPhone", model: "iPhone 17", os: "27.0", reachable: true),AppleDevice(id: "00008150-BBBB", name: "Zijad\u{2019}s iPad", model: "iPad Pro", os: "27.0", reachable: true)]- }).environmentObject(focus).environmentObject(model.localizer))+ }).environmentObject(focus).environmentObject(modelStores.localizer))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 520), styleMask: [.titled], backing: .buffered, defer: false)window.contentView = hostwindow.orderFront(nil)@@ -1128,21 +1129,21 @@ final class LibraryTests: XCTestCase {/// Issue #73: the extraction writes RomFS.img now, not a RomFS folder. The archive step looked/// only for the folder, so every build ended with "archive skipped" after a successful build.- /// This drives BuildModel.extractedVersion — the function the archive step calls — rather than+ /// This drives RomFSArchive.extractedVersion — the function the archive step calls — rather than/// restating its predicate, so changing the production code changes what this checks.func testTheExtractionIsFoundAsEitherAFolderOrAnImage() throws {let work = FileManager.default.temporaryDirectory.appendingPathComponent("nspb-extract-" + UUID().uuidString)let extract = work.appendingPathComponent("extract")defer { try? FileManager.default.removeItem(at: work) }try FileManager.default.createDirectory(at: extract.appendingPathComponent("v0"), withIntermediateDirectories: true)- XCTAssertNil(BuildModel.extractedVersion(in: extract.path), "an empty version folder holds neither shape")+ XCTAssertNil(RomFSArchive.extractedVersion(in: extract.path), "an empty version folder holds neither shape")// what the rewriter writes todaytry Data([0x44, 0x4d, 0x52, 0x4f, 0x4d, 0x46, 0x53, 0x31]).write(to: extract.appendingPathComponent("v0").appendingPathComponent("RomFS.img"))- XCTAssertEqual(BuildModel.extractedVersion(in: extract.path), "v0", "RomFS.img alone must count")+ XCTAssertEqual(RomFSArchive.extractedVersion(in: extract.path), "v0", "RomFS.img alone must count")// and the older shape still works, with the highest version winningtry FileManager.default.createDirectory(at: extract.appendingPathComponent("v1").appendingPathComponent("RomFS"),withIntermediateDirectories: true)- XCTAssertEqual(BuildModel.extractedVersion(in: extract.path), "v1")+ XCTAssertEqual(RomFSArchive.extractedVersion(in: extract.path), "v1")}}\ No newline at end of filediff --git a/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swift b/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swiftindex cce58f12..99cd1cb1 100644--- a/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swift+++ b/frontend/Tests/NX2AppleTests/LiveOnboardingDriverTests.swift@@ -1,6 +1,7 @@import XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// The real driver's logic over fakes: no xcodebuild, sudo, App Store, network or installs run here.@@ -13,7 +14,7 @@ import XCTestvar commandResult: (ok: Bool, output: String) = (true, "")var installed: [String] = []var opened: [URL] = []- var onDetect: (BuildModel) -> Void = { _ in }+ var onDetect: (DependencyStore) -> Void = { _ in }var keyOutcome = KeyCheck.Outcome.fitsvar games: [LibraryGame] = []var xcodeWorks: Bool? // nil: follows the probe@@ -39,11 +40,11 @@ import XCTestaddTeardownBlock { [home] in try? FileManager.default.removeItem(at: home!) }}- func make(_ fake: Fake, deps: [Dep], step: OnboardingStep? = nil, platform: OnboardingPlatform? = nil) -> (LiveOnboardingDriver, BuildModel) {+ func make(_ fake: Fake, deps: [Dep], step: OnboardingStep? = nil, platform: OnboardingPlatform? = nil) -> (LiveOnboardingDriver, BuildStore) {if let platform { defaults.set(platform.rawValue, forKey: OnboardingDefaults.platform) }if let step { defaults.set(step.rawValue, forKey: OnboardingDefaults.step); defaults.set(true, forKey: OnboardingDefaults.inProgress) }- let model = BuildModel()- model.dependencies.deps = deps; model.dependencies.checked = true+ let modelStores = LauncherStores(); let model = modelStores.build+ modelStores.dependencies.deps = deps; modelStores.dependencies.checked = truevar env = OnboardingEnvironment()env.defaults = defaultsenv.home = home.path@@ -55,9 +56,9 @@ import XCTestenv.runAdmin = { fake.adminCalls.append($0); return fake.admin }env.run = { cmd, line in fake.commands.append(cmd); line("Downloading Metal Toolchain: 45.5% (1 MB of 2 MB)"); return fake.commandResult }env.detectDeps = { m in fake.onDetect(m) }- env.installDep = { m, d in+ env.installDep = { dependencies, d infake.installed.append(d.id)- if let i = m.dependencies.deps.firstIndex(where: { $0.id == d.id }) { m.dependencies.deps[i].installing = true }+ if let i = dependencies.deps.firstIndex(where: { $0.id == d.id }) { dependencies.deps[i].installing = true }}env.openURL = { fake.opened.append($0) }env.keyCheck = { _, _ in fake.keyOutcome }@@ -65,21 +66,21 @@ import XCTestenv.fetchArtwork = { _ in }env.pollInterval = 0.01; env.advanceDelay = 0let library = GameLibrary(file: home.appendingPathComponent("library.json"))- return (LiveOnboardingDriver(model: model, library: library, env: env), model)+ return (LiveOnboardingDriver(stores: modelStores, library: library, env: env), model)}// MARK: Pure partsfunc testIOSRequirementFollowsThePlatformAndKeepsOldBehaviourWithoutAChoice() {- XCTAssertTrue(BuildModel.needsIOSPlatform(defaults: defaults), "no stored choice: the iOS SDK stays required")+ XCTAssertTrue(LauncherStores.needsIOSPlatform(defaults: defaults), "no stored choice: the iOS SDK stays required")defaults.set("mac", forKey: OnboardingDefaults.platform)defaults.set("mac-app", forKey: "buildTarget")- XCTAssertFalse(BuildModel.needsIOSPlatform(defaults: defaults), "Mac only, Mac builds: no iOS SDK")+ XCTAssertFalse(LauncherStores.needsIOSPlatform(defaults: defaults), "Mac only, Mac builds: no iOS SDK")defaults.set("ios", forKey: "buildTarget")- XCTAssertTrue(BuildModel.needsIOSPlatform(defaults: defaults), "an iPhone build still needs it")+ XCTAssertTrue(LauncherStores.needsIOSPlatform(defaults: defaults), "an iPhone build still needs it")for value in ["iphone", "both"] {defaults.set(value, forKey: OnboardingDefaults.platform); defaults.set("mac-app", forKey: "buildTarget")- XCTAssertTrue(BuildModel.needsIOSPlatform(defaults: defaults))+ XCTAssertTrue(LauncherStores.needsIOSPlatform(defaults: defaults))}}@@ -151,7 +152,7 @@ import XCTestenv.freeBytes = { 100_000_000_000 }; env.xcodeProbe = { fake.probe }; env.xcodeInstalled = { true }; env.xcodeFolderExists = { true }env.detectDeps = { _ in }; env.installDep = { _, d in fake.installed.append(d.id) }env.advanceDelay = 0- let driver = LiveOnboardingDriver(model: model, library: GameLibrary(file: home.appendingPathComponent("l.json")), env: env, ephemeral: true)+ let driver = LiveOnboardingDriver(stores: live.stores, library: GameLibrary(file: home.appendingPathComponent("l.json")), env: env, ephemeral: true)XCTAssertEqual(driver.state.step, .welcome, "a forced run starts from Welcome whatever is stored")driver.start(); driver.choosePlatform(.mac)driver.next()@@ -161,7 +162,7 @@ import XCTestXCTAssertNil(defaults.string(forKey: OnboardingDefaults.step))XCTAssertNil(defaults.string(forKey: OnboardingDefaults.platform))XCTAssertFalse(defaults.bool(forKey: OnboardingDefaults.inProgress))- XCTAssertTrue(BuildModel.needsIOSPlatform(defaults: defaults) == false, "the session's Mac-only choice is in effect")+ XCTAssertTrue(LauncherStores.needsIOSPlatform(defaults: defaults) == false, "the session's Mac-only choice is in effect")driver.retry(.xcode)await driver.settle()XCTAssertEqual(fake.installed, ["python"])@@ -198,7 +199,7 @@ import XCTestlet (driver, model) = make(fake, deps: [dep("metal", present: false), dep("xcode", present: false)], step: .xcode, platform: .both)fake.onDetect = { m in // what the admin step and the downloads changefake.probe.selectedIsXcode = true; fake.probe.licenseAccepted = true; fake.probe.firstLaunchDone = true- if !fake.commands.isEmpty { for i in m.dependencies.deps.indices { m.dependencies.deps[i].present = true } }+ if !fake.commands.isEmpty { for i in m.deps.indices { m.deps[i].present = true } }}await driver.refreshXcode()driver.finishXcodeSetup()@@ -215,7 +216,7 @@ import XCTestlet (driver, _) = make(fake, deps: [dep("metal", present: false), dep("xcode", present: true)], step: .xcode, platform: .mac)fake.onDetect = { m infake.probe.selectedIsXcode = true; fake.probe.licenseAccepted = true; fake.probe.firstLaunchDone = true- if !fake.commands.isEmpty { for i in m.dependencies.deps.indices { m.dependencies.deps[i].present = true } }+ if !fake.commands.isEmpty { for i in m.deps.indices { m.deps[i].present = true } }}await driver.refreshXcode()driver.finishXcodeSetup()@@ -290,9 +291,9 @@ import XCTestawait driver.settle()XCTAssertEqual(fake.installed, ["python"])func finish(_ id: String) async { // the install ended and detection ran again- model.dependencies.checked = false- for i in model.dependencies.deps.indices { model.dependencies.deps[i].installing = false; if model.dependencies.deps[i].id == id { model.dependencies.deps[i].present = true } }- model.dependencies.checked = true+ driver.stores.dependencies.checked = false+ for i in driver.stores.dependencies.deps.indices { driver.stores.dependencies.deps[i].installing = false; if driver.stores.dependencies.deps[i].id == id { driver.stores.dependencies.deps[i].present = true } }+ driver.stores.dependencies.checked = trueawait driver.settle()}await finish("python"); XCTAssertEqual(fake.installed, ["python", "dotnet"])@@ -322,9 +323,9 @@ import XCTestdep("dotnet", present: false), dep("python", present: false)], step: .xcode, platform: .mac)driver.activate()await driver.settle()- model.dependencies.checked = false- for i in model.dependencies.deps.indices { model.dependencies.deps[i].installing = false } // python's install ended, still missing- model.dependencies.checked = true+ driver.stores.dependencies.checked = false+ for i in driver.stores.dependencies.deps.indices { driver.stores.dependencies.deps[i].installing = false } // python's install ended, still missing+ driver.stores.dependencies.checked = trueawait driver.settle()guard case let .failed(failure) = driver.state.background[.python] else { return XCTFail("\(String(describing: driver.state.background[.python]))") }XCTAssertTrue(failure.message.contains(L10n.string("dep.python", model.lang)))diff --git a/frontend/Tests/NX2AppleTests/ReleaseNotesTests.swift b/frontend/Tests/NX2AppleTests/ReleaseNotesTests.swiftindex 410c36d9..7b80aab3 100644--- a/frontend/Tests/NX2AppleTests/ReleaseNotesTests.swift+++ b/frontend/Tests/NX2AppleTests/ReleaseNotesTests.swift@@ -3,11 +3,12 @@ import SwiftUIimport XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// The update sheet's Markdown: blocks and auto-links, on v0.7.0's real body/// (Tests/Fixtures/release_v0.7.0.md, copied from `gh release view v0.7.0`).-final class ReleaseNotesTests: XCTestCase {+@MainActor final class ReleaseNotesTests: XCTestCase {static let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()@@ -202,11 +203,11 @@ final class ReleaseNotesTests: XCTestCase {for (name, lang, notes, tag) in [("update-sheet-notes-v072-en", Lang.en, body072, "v0.7.2"), ("update-sheet-notes-v072-zh", Lang.zh, body072, "v0.7.2")]+ [("update-sheet-notes-en", Lang.en, body, "v0.7.0"), ("update-sheet-notes-zh", Lang.zh, body, "v0.7.0"),("update-sheet-notes-middle-en", Lang.en, middle, "v0.7.0"), ("update-sheet-notes-middle-zh", Lang.zh, middle, "v0.7.0")] {- let m = BuildModel()+ let mStores = LauncherStores(); let m = mStores.buildm.lang = lang- m.appUpdates.update = AppUpdate.Release(tag: tag, url: "", digest: nil, notes: notes)+ mStores.appUpdates.update = AppUpdate.Release(tag: tag, url: "", digest: nil, notes: notes)let width: CGFloat = 560, height: CGFloat = 640- let host = NSHostingView(rootView: UpdateSheet(updates: m.appUpdates).environmentObject(m.localizer).frame(width: width, height: height))+ let host = NSHostingView(rootView: UpdateSheet(updates: mStores.appUpdates).environmentObject(mStores.localizer).frame(width: width, height: height))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: width, height: height), styleMask: [.titled], backing: .buffered, defer: false)window.contentView = hostwindow.appearance = NSAppearance(named: .darkAqua)diff --git a/frontend/Tests/NX2AppleTests/RepoAutoUpdateTests.swift b/frontend/Tests/NX2AppleTests/RepoAutoUpdateTests.swiftindex d7efc614..48f27840 100644--- a/frontend/Tests/NX2AppleTests/RepoAutoUpdateTests.swift+++ b/frontend/Tests/NX2AppleTests/RepoAutoUpdateTests.swift@@ -1,11 +1,12 @@import XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher-/// The automatic update when the app opens (BuildModel.autoPull): a clean checkout on main fast-forwards to origin/main,+/// The automatic update when the app opens (RepoStore.autoPull): a clean checkout on main fast-forwards to origin/main,/// one with local changes is left as it is. A local bare repository stands in for GitHub.-final class RepoAutoUpdateTests: XCTestCase {+@MainActor final class RepoAutoUpdateTests: XCTestCase {private var temporary: URL!private var saved: [(String, Any?)] = []@@ -46,30 +47,32 @@ final class RepoAutoUpdateTests: XCTestCase {return checkout}- @MainActor private func open(_ checkout: URL) -> BuildModel {- let m = BuildModel()- m.repoPath = checkout.path- m.repo.autoUpdate = true- m.repo.checkForUpdates(silent: true) // what the library does when the app opens- let settled = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in !m.repo.busy && m.repo.behind != nil && (m.repo.autoPulled != nil || !m.repo.status.isEmpty) }, object: nil)+ @MainActor private func open(_ checkout: URL) -> LauncherStores {+ let mStores = LauncherStores(); let m = mStores.build+ mStores.repo.path = checkout.path+ mStores.repo.autoUpdate = true+ mStores.repo.checkForUpdates(silent: true) // what the library does when the app opens+ let settled = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in !mStores.repo.busy && mStores.repo.behind != nil && (mStores.repo.autoPulled != nil || !mStores.repo.status.isEmpty) }, object: nil)wait(for: [settled], timeout: 20)- return m+ return mStores}@MainActor func testACleanCheckoutOnMainIsUpdatedWhenTheAppOpens() throws {let checkout = try fixture()- let m = open(checkout)- XCTAssertEqual(m.repo.autoPulled, 1)- XCTAssertEqual(m.repo.behind, 0)+ let mStores = open(checkout)+ let m = mStores.build+ XCTAssertEqual(mStores.repo.autoPulled, 1)+ XCTAssertEqual(mStores.repo.behind, 0)XCTAssertEqual(try git("log", "-1", "--format=%s", in: checkout), "two")}@MainActor func testACheckoutWithLocalChangesIsLeftAsItIs() throws {let checkout = try fixture()try "mine".write(to: checkout.appendingPathComponent("dm/tools/nx_extract/Program.cs"), atomically: true, encoding: .utf8)- let m = open(checkout)- XCTAssertNil(m.repo.autoPulled)- XCTAssertEqual(m.repo.status, m.t("repo.autoSkipped"))+ let mStores = open(checkout)+ let m = mStores.build+ XCTAssertNil(mStores.repo.autoPulled)+ XCTAssertEqual(mStores.repo.status, m.t("repo.autoSkipped"))XCTAssertEqual(try git("log", "-1", "--format=%s", in: checkout), "one")}}diff --git a/frontend/Tests/NX2AppleTests/RepoToolsTests.swift b/frontend/Tests/NX2AppleTests/RepoToolsTests.swiftindex eecd3d52..e3667eb9 100644--- a/frontend/Tests/NX2AppleTests/RepoToolsTests.swift+++ b/frontend/Tests/NX2AppleTests/RepoToolsTests.swift@@ -1,11 +1,12 @@import XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// #87: a ZIP copy of the repository is connected to git when the app opens, and a build does not start with build tools/// older than the app. Temporary folders and a local repository stand in for the user's copy and for GitHub.-final class RepoToolsTests: XCTestCase {+@MainActor final class RepoToolsTests: XCTestCase {private var temporary: URL!private var saved: [(String, Any?)] = []@@ -56,8 +57,8 @@ final class RepoToolsTests: XCTestCase {@MainActor func testABuildWithOldToolsRefusesToStart() throws {let repo = temporary.appendingPathComponent("old")try write(["dm/tools/nx_extract/Program.cs", RepoLayout.buildScript], in: repo)- let m = BuildModel()- m.repoPath = repo.path+ let mStores = LauncherStores(); let m = mStores.build+ mStores.repo.path = repo.pathm.target = BuildTarget.macm.startBuild()XCTAssertFalse(m.running, "no build was started")@@ -82,25 +83,26 @@ final class RepoToolsTests: XCTestCase {return (origin, zip)}- @MainActor private func openZip(_ f: (origin: URL, zip: URL), auto: Bool, remote: String? = nil) -> BuildModel {- let m = BuildModel()- m.repoPath = f.zip.path- m.repo.autoUpdate = auto- m.repo.adoptAtLaunch(remote: remote ?? "file://" + f.origin.path)- guard auto else { return m } // nothing runs, nothing to wait for- let settled = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in !m.repo.busy && !m.repo.status.isEmpty && m.repo.status != m.t("repo.adopting") }, object: nil)+ @MainActor private func openZip(_ f: (origin: URL, zip: URL), auto: Bool, remote: String? = nil) -> LauncherStores {+ let mStores = LauncherStores(); let m = mStores.build+ mStores.repo.path = f.zip.path+ mStores.repo.autoUpdate = auto+ mStores.repo.adoptAtLaunch(remote: remote ?? "file://" + f.origin.path)+ guard auto else { return mStores } // nothing runs, nothing to wait for+ let settled = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in !mStores.repo.busy && !mStores.repo.status.isEmpty && mStores.repo.status != m.t("repo.adopting") }, object: nil)wait(for: [settled], timeout: 20)- return m+ return mStores}@MainActor func testAZipCopyIsConnectedAndUpdatedAtLaunch() throws {guard FileManager.default.isExecutableFile(atPath: "/usr/bin/git") else { throw XCTSkip("git is required for the fixture") }let f = try fixture()XCTAssertEqual(RepoLayout.missingTools(in: f.zip.path), [RepoLayout.romfsImageTool])- let m = openZip(f, auto: true)- XCTAssertTrue(m.repoIsGit)- XCTAssertTrue(m.repo.autoAdopted)- XCTAssertEqual(m.repo.status, String(format: m.t("repo.adoptedAuto"), GitRules.zipCopyBranch()))+ let mStores = openZip(f, auto: true)+ let m = mStores.build+ XCTAssertTrue(mStores.repo.isGit)+ XCTAssertTrue(mStores.repo.autoAdopted)+ XCTAssertEqual(mStores.repo.status, String(format: m.t("repo.adoptedAuto"), GitRules.zipCopyBranch()))XCTAssertEqual(RepoLayout.missingTools(in: f.zip.path), [], "the tools of origin/main are there now")XCTAssertEqual(try git("rev-parse", "--abbrev-ref", "HEAD", in: f.zip), "main")XCTAssertEqual(try String(contentsOf: f.zip.appendingPathComponent(RepoLayout.buildScript), encoding: .utf8), "new")@@ -112,7 +114,8 @@ final class RepoToolsTests: XCTestCase {try "my tweak".write(to: f.zip.appendingPathComponent(RepoLayout.buildScript), atomically: true, encoding: .utf8) // an edited tracked filetry write(["dm/mine/notes.txt"], in: f.zip, text: "mine") // a file origin does not havetry write(["dm/tools/build/huge.bin"], in: f.zip, text: "build output")- let m = openZip(f, auto: true)+ let mStores = openZip(f, auto: true)+ let m = mStores.buildlet branch = GitRules.zipCopyBranch()XCTAssertEqual(try git("show", "main:" + RepoLayout.buildScript, in: f.zip), "new", "main has origin's version")XCTAssertEqual(try String(contentsOf: f.zip.appendingPathComponent(RepoLayout.buildScript), encoding: .utf8), "new")@@ -121,25 +124,27 @@ final class RepoToolsTests: XCTestCase {["dm/tools/nx_extract/Program.cs", RepoLayout.buildScript].sorted(), "only paths origin tracks are recorded")XCTAssertEqual(try git("log", "-1", "--format=%an", branch, in: f.zip), "NX2Apple")XCTAssertTrue(FileManager.default.fileExists(atPath: f.zip.appendingPathComponent("dm/mine/notes.txt").path), "untracked files stay where they are")- XCTAssertTrue(m.repo.status.contains(branch), m.repo.status)+ XCTAssertTrue(mStores.repo.status.contains(branch), mStores.repo.status)}@MainActor func testWithTheAutomaticUpdateOffTheZipCopyIsLeftAlone() throws {guard FileManager.default.isExecutableFile(atPath: "/usr/bin/git") else { throw XCTSkip("git is required for the fixture") }let f = try fixture()- let m = openZip(f, auto: false)- XCTAssertFalse(m.repoIsGit)- XCTAssertFalse(m.repo.autoAdopted)- XCTAssertTrue(m.repo.status.isEmpty, "Settings says it next to the repository (repo.zipNoAuto), not as a status")+ let mStores = openZip(f, auto: false)+ let m = mStores.build+ XCTAssertFalse(mStores.repo.isGit)+ XCTAssertFalse(mStores.repo.autoAdopted)+ XCTAssertTrue(mStores.repo.status.isEmpty, "Settings says it next to the repository (repo.zipNoAuto), not as a status")XCTAssertEqual(RepoLayout.missingTools(in: f.zip.path), [RepoLayout.romfsImageTool])}@MainActor func testAnUnreachableOriginSaysWhyAndLeavesTheCopyUsable() throws {guard FileManager.default.isExecutableFile(atPath: "/usr/bin/git") else { throw XCTSkip("git is required for the fixture") }let f = try fixture()- let m = openZip(f, auto: true, remote: "file://" + temporary.appendingPathComponent("does-not-exist.git").path)- XCTAssertEqual(m.repo.status, m.t("repo.adoptFailAuto"))- XCTAssertFalse(m.repo.autoAdopted)+ let mStores = openZip(f, auto: true, remote: "file://" + temporary.appendingPathComponent("does-not-exist.git").path)+ let m = mStores.build+ XCTAssertEqual(mStores.repo.status, m.t("repo.adoptFailAuto"))+ XCTAssertFalse(mStores.repo.autoAdopted)XCTAssertTrue(RepoLayout.isRepo(f.zip.path), "the files are still there")XCTAssertEqual(try String(contentsOf: f.zip.appendingPathComponent(RepoLayout.buildScript), encoding: .utf8), "old", "nothing was changed")XCTAssertFalse(FileManager.default.fileExists(atPath: f.zip.appendingPathComponent(".git").path))diff --git a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift b/frontend/Tests/NX2AppleTests/ShellInstallTests.swiftindex 636dd03e..62ca961d 100644--- a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift+++ b/frontend/Tests/NX2AppleTests/ShellInstallTests.swift@@ -2,13 +2,14 @@ import XCTestimport Combine@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// Route C: one app on the device for several games. The commands and parsers are checked as pure functions, and the whole path/// after the build runs headless against a stand-in `xcrun` that models devicectl on a folder (a fake device container): an install/// keeps the container, a copy to a file creates the parents, and `--remove-existing-content true` wipes the destination's siblings,/// as it does on a real device. No test reaches a device or a real game.-final class ShellInstallTests: XCTestCase {+@MainActor final class ShellInstallTests: XCTestCase {private var temporary: URL!private let fm = FileManager.defaultprivate let titleID = "0100535012974000"@@ -731,16 +732,16 @@ final class ShellInstallTests: XCTestCase {let keysSaved = ["repoPath", "buildTarget", "buildOutputDirectory", "installDevice", "signingTeam", "shellRoot"].map { ($0, UserDefaults.standard.object(forKey: $0)) }defer { for (key, value) in keysSaved { UserDefaults.standard.set(value, forKey: key) } }UserDefaults.standard.set(f.root, forKey: "shellRoot")- let model = BuildModel(xcrun: f.xcrun)- model.repoPath = f.repo+ let modelStores = LauncherStores(xcrun: f.xcrun); let model = modelStores.build+ modelStores.repo.path = f.repomodel.target = "ios"model.outDir = path("out")- model.dependencies.pythonPath = "/usr/bin/python3"- model.dependencies.dotnetPath = "/usr/bin/true"- model.dependencies.checked = true- model.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]- model.installDevice = device- model.signingTeam = team+ modelStores.dependencies.pythonPath = "/usr/bin/python3"+ modelStores.dependencies.dotnetPath = "/usr/bin/true"+ modelStores.dependencies.checked = true+ modelStores.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]+ modelStores.deviceStore.installDevice = device+ modelStores.deviceStore.signingTeam = teamtry write(f.repo + "/dm/tools/nx_extract/Program.cs", "")for tool in RepoLayout.requiredTools.filter({ $0 != RepoLayout.buildScript }) { try write(f.repo + "/" + tool, "") }// the packer stand-in writes the image from the extracted RomFS@@ -762,7 +763,7 @@ final class ShellInstallTests: XCTestCase {let finished = expectation(description: "Installed")let token = model.$done.filter { $0 }.prefix(1).sink { _ in finished.fulfill() }- let asked = model.deviceStore.$shellCopy.compactMap { $0 }.prefix(1).sink { _ in model.deviceStore.answerCopy(.copy) }+ let asked = modelStores.deviceStore.$shellCopy.compactMap { $0 }.prefix(1).sink { _ in modelStores.deviceStore.answerCopy(.copy) }model.startBuild()wait(for: [finished], timeout: 30)withExtendedLifetime(token) {}; withExtendedLifetime(asked) {}@@ -793,24 +794,24 @@ final class ShellInstallTests: XCTestCase {XCTAssertEqual(model.doneNote, String(format: model.t("dev.resigned"), "iPhone"))}- @MainActor private func makeModel(_ f: Fixture) throws -> BuildModel {- let model = BuildModel(xcrun: f.xcrun)- model.repoPath = f.repo+ @MainActor private func makeModel(_ f: Fixture) throws -> LauncherStores {+ let modelStores = LauncherStores(xcrun: f.xcrun); let model = modelStores.build+ modelStores.repo.path = f.repomodel.target = "ios"model.outDir = path("out")- model.dependencies.pythonPath = "/usr/bin/python3"- model.dependencies.dotnetPath = "/usr/bin/true"- model.dependencies.checked = true- model.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]- model.installDevice = device- model.signingTeam = team+ modelStores.dependencies.pythonPath = "/usr/bin/python3"+ modelStores.dependencies.dotnetPath = "/usr/bin/true"+ modelStores.dependencies.checked = true+ modelStores.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]+ modelStores.deviceStore.installDevice = device+ modelStores.deviceStore.signingTeam = teamtry write(f.repo + "/dm/tools/nx_extract/Program.cs", "")for tool in RepoLayout.requiredTools.filter({ $0 != RepoLayout.buildScript }) { try write(f.repo + "/" + tool, "") }try write(f.repo + "/scripts/build_ipa_from_nsp.py", "open('\(state)/script.txt', 'w').write('ran')\n")let base = temporary.appendingPathComponent("Test [\(titleID)].nsp"), keys = temporary.appendingPathComponent("prod.keys")try Data([0]).write(to: base); try Data().write(to: keys)model.slots[0].paths = [base.path]; model.slots[3].paths = [keys.path]- return model+ return modelStores}/// An unknown device stops the build before the script runs: no hour of building for a device that cannot be installed on.@@ -819,14 +820,15 @@ final class ShellInstallTests: XCTestCase {try writeDevices(state + "/devices-default.json", [("00008150-OTHER", "wired")])let saved = ["repoPath", "buildTarget", "buildOutputDirectory", "installDevice", "signingTeam"].map { ($0, UserDefaults.standard.object(forKey: $0)) }defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }- let model = try makeModel(f)+ let modelStores = try makeModel(f)+ let model = modelStores.buildmodel.startBuild()let stopped = expectation(description: "Checked")let token = model.$running.dropFirst().filter { !$0 }.prefix(1).sink { _ in stopped.fulfill() }wait(for: [stopped], timeout: 20)withExtendedLifetime(token) {}XCTAssertEqual(model.failure?.kind, .devicePairing)- XCTAssertEqual(model.doneNote, String(format: model.t("shell.notPaired"), model.deviceName(model.installDevice)), "the pairing steps, in the app's language")+ XCTAssertEqual(model.doneNote, String(format: model.t("shell.notPaired"), modelStores.deviceStore.deviceName(modelStores.deviceStore.installDevice)), "the pairing steps, in the app's language")XCTAssertFalse(fm.fileExists(atPath: state + "/script.txt"), "the build script did not start")}@@ -836,10 +838,11 @@ final class ShellInstallTests: XCTestCase {let saved = ["repoPath", "buildTarget", "buildOutputDirectory", "installDevice", "signingTeam", "shellRoot"].map { ($0, UserDefaults.standard.object(forKey: $0)) }defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }UserDefaults.standard.set(f.root, forKey: "shellRoot")- let model = try makeModel(f)+ let modelStores = try makeModel(f)+ let model = modelStores.buildtry write(state + "/fail-on", "romfs.img")var plans: [ShellCopyPlan] = []- let asked = model.deviceStore.$shellCopy.compactMap { $0 }.sink { plans.append($0); model.deviceStore.answerCopy(.copy) }+ let asked = modelStores.deviceStore.$shellCopy.compactMap { $0 }.sink { plans.append($0); modelStores.deviceStore.answerCopy(.copy) }func finish(_ start: () -> Void) {let ended = expectation(description: "Ended")let token = model.$running.dropFirst().filter { !$0 }.prefix(1).sink { _ in ended.fulfill() }@@ -849,7 +852,7 @@ final class ShellInstallTests: XCTestCase {}finish { model.installShell(framework: f.framework, titleID: titleID, name: "Test Game", archive: f.archive) }XCTAssertEqual(model.failure?.kind, .shellDataIncomplete)- XCTAssertTrue(model.doneNote.hasPrefix(String(format: model.t("shell.copyIncomplete"), model.deviceName(model.installDevice), "").components(separatedBy: ": ").first ?? "-"), model.doneNote)+ XCTAssertTrue(model.doneNote.hasPrefix(String(format: model.t("shell.copyIncomplete"), modelStores.deviceStore.deviceName(modelStores.deviceStore.installDevice), "").components(separatedBy: ": ").first ?? "-"), model.doneNote)XCTAssertFalse(model.done)XCTAssertEqual(plans.count, 1)XCTAssertEqual(plans.first?.connection, .wired)@@ -868,11 +871,11 @@ final class ShellInstallTests: XCTestCase {@MainActor func testShellTargetWithoutDeviceStopsBeforeBuilding() throws {let saved = ["repoPath", "buildTarget", "installDevice", "signingTeam"].map { ($0, UserDefaults.standard.object(forKey: $0)) }defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }- let model = BuildModel()- model.repoPath = temporary.path+ let modelStores = LauncherStores(); let model = modelStores.build+ modelStores.repo.path = temporary.pathtry write(temporary.path + "/dm/tools/nx_extract/Program.cs", "")model.target = "ios"- model.installDevice = ""+ modelStores.deviceStore.installDevice = ""model.startBuild()XCTAssertFalse(model.running)XCTAssertEqual(model.doneNote, model.t("shell.needsDevice"))diff --git a/frontend/Tests/NX2AppleTests/SourceSizeTests.swift b/frontend/Tests/NX2AppleTests/SourceSizeTests.swiftindex b13801c3..bb146766 100644--- a/frontend/Tests/NX2AppleTests/SourceSizeTests.swift+++ b/frontend/Tests/NX2AppleTests/SourceSizeTests.swift@@ -7,7 +7,6 @@ final class SourceSizeTests: XCTestCase {/// Path under frontend/Sources → its line count when the limit came in. Lower the number when the file shrinks.private static let aboveTheLimit: [String: Int] = [- "NX2Apple/ContentView.swift": 2049,"NX2Apple/LauncherView.swift": 967,"NXCore/Localization.swift": 4237,]diff --git a/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swift b/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swiftindex 9d8d3861..b1ebf075 100644--- a/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swift+++ b/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swift@@ -2,9 +2,10 @@ import XCTestimport SwiftUI@testable import NX2Apple@testable import NXCore+import NXModel/// LNPANDY/NX2Apple#449: a shell folder with one framework of the current chain and one of the old chain.-final class StaleFrameworksTests: XCTestCase {+@MainActor final class StaleFrameworksTests: XCTestCase {private let current = "b-b7cd656abd7c"private let old = "b-e65a4ebd3322"private let oldID = "0100A00019DE0000"@@ -79,7 +80,7 @@ final class StaleFrameworksTests: XCTestCase {func testStopLeavesEveryFileAsItWas() throws {let (stale, fresh) = try shell()let before = try Data(contentsOf: URL(fileURLWithPath: ShellLibrary.stateFile(root: tmp + "/shell")))- let model = BuildModel()+ let modelStores = LauncherStores(); let model = modelStores.buildmodel.staleFrameworks = found()XCTAssertFalse(model.staleFrameworks.isEmpty)model.stopForStaleFrameworks()@@ -91,7 +92,7 @@ final class StaleFrameworksTests: XCTestCase {func testContinueRemovesTheStaleFrameworkAndKeepsTheCurrentOne() throws {let (stale, fresh) = try shell()- let failed = BuildModel.removeStaleFrameworks(found(), root: tmp + "/shell")+ let failed = BuildStore.removeStaleFrameworks(found(), root: tmp + "/shell")XCTAssertEqual(failed, [])XCTAssertFalse(exists(stale))XCTAssertTrue(exists(fresh))@@ -101,7 +102,7 @@ final class StaleFrameworksTests: XCTestCase {func testContinueStartsTheBuildAndTheModelEndsWithoutAPrompt() throws {_ = try shell()- let model = BuildModel()+ let modelStores = LauncherStores(); let model = modelStores.buildmodel.staleFrameworks = found()var started = falseUserDefaults.standard.set(tmp + "/shell", forKey: "shellRoot")diff --git a/frontend/Tests/NX2AppleTests/XcodeTeamsTests.swift b/frontend/Tests/NX2AppleTests/XcodeTeamsTests.swiftindex 5eded5d0..791bc377 100644--- a/frontend/Tests/NX2AppleTests/XcodeTeamsTests.swift+++ b/frontend/Tests/NX2AppleTests/XcodeTeamsTests.swift@@ -1,11 +1,12 @@import XCTest@testable import NX2Apple@testable import NXCore+import NXModel@testable import NXLauncher/// #87: the signing teams of the Apple IDs signed in to Xcode, read from Xcode's preferences (sample plists, not this/// Mac's), merged with the teams of development certificates.-final class XcodeTeamsTests: XCTestCase {+@MainActor final class XcodeTeamsTests: XCTestCase {private func plist(_ body: String) -> Data {Data("""<?xml version="1.0" encoding="UTF-8"?>@@ -94,12 +95,12 @@ final class XcodeTeamsTests: XCTestCase {func testTheNoTeamMessageNamesTheRealCause() {for lang in [Lang.en, .zh] {- let m = BuildModel(); m.lang = lang+ let mStores = LauncherStores(); let m = mStores.build; m.lang = langXCTAssertFalse(m.t("dev.noTeam").isEmpty)XCTAssertNotEqual(m.t("dev.teamNoCert"), "dev.teamNoCert")XCTAssertNotEqual(m.t("dev.personalTeam"), "dev.personalTeam")}- let m = BuildModel(); m.lang = .en+ let mStores = LauncherStores(); let m = mStores.build; m.lang = .enXCTAssertTrue(m.t("dev.noTeam").contains("Settings → Apple Accounts"))XCTAssertTrue(m.t("dev.noTeam").contains("no development certificate"))XCTAssertTrue(m.t("dev.noTeam").contains("Download Manual Profiles"))diff --git a/frontend/Tests/NXModelTests/BuildStoreTests.swift b/frontend/Tests/NXModelTests/BuildStoreTests.swiftnew file mode 100644index 00000000..42697864--- /dev/null+++ b/frontend/Tests/NXModelTests/BuildStoreTests.swift@@ -0,0 +1,327 @@+import XCTest+@testable import NXModel+@testable import NXCore++/// `BuildStore` without SwiftUI: the other stores are fakes behind the narrow protocols (`RepoLocation`, `DependencyInstalling`,+/// `EngineSyncing`, `InstallTarget`), the panels and the alert are closures that record, the defaults are a suite of their own and+/// the files are in a temporary folder. No process starts and nothing is built: these tests drive the inputs, the script's events,+/// the failure, "Build anyway" and the conditions that stop a build before it starts.+@MainActor final class BuildStoreTests: XCTestCase {+ private final class FakeRepo: RepoLocation {+ var path = "/repo"+ var isRepo = true+ var isGit = true+ }++ private final class FakeDeps: DependencyInstalling {+ var pythonPath = "/usr/bin/python3"+ var dotnetPath = "/usr/bin/true"+ var checked = true+ var allPresent = true+ var deps: [Dep] = []+ var installed: [String] = []+ var busy: Set<String> = []+ func isInstalling(_ id: String) -> Bool { busy.contains(id) }+ func install(_ dep: Dep) -> Task<Void, Never> { installed.append(dep.id); return Task {} }+ }++ private final class FakeEngine: EngineSyncing {+ var syncs = 0+ func syncEngine(then: ((Bool) -> Void)?) -> Task<Void, Never> { syncs += 1; then?(true); return Task {} }+ }++ private final class FakeDevices: InstallTarget {+ var installDevice = ""+ var signingTeam = ""+ var devices: [AppleDevice] = []+ var xcrun = "/usr/bin/true"+ var readTeams: @Sendable () -> [SigningTeam] = { [] }+ func deviceName(_ udid: String) -> String { devices.first { $0.id == udid }?.name ?? "iPhone" }+ nonisolated func askCopy(_ plan: ShellCopyPlan) -> ShellCopyDecision { .skip }+ nonisolated func setWaiting(_ on: Bool) {}+ nonisolated var waitCancelled: Bool { false }+ func copyEnded() {}+ }++ private var suite: String!+ private var defaults: UserDefaults!+ private var temporary: URL!+ private let repo = FakeRepo()+ private let deps = FakeDeps()+ private let engine = FakeEngine()+ private let devices = FakeDevices()+ private let localizer = Localizer(.en)++ override func setUpWithError() throws {+ suite = "nxmodel-build-tests-" + UUID().uuidString+ defaults = UserDefaults(suiteName: suite)+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)+ }++ override func tearDownWithError() throws {+ defaults.removePersistentDomain(forName: suite)+ try? FileManager.default.removeItem(at: temporary)+ }++ private func makeStore(targetChanged: @escaping () -> Void = {}) -> BuildStore {+ BuildStore(localizer: localizer, runner: FakeProcessRunner(), repo: repo, deps: deps, engine: engine, devices: devices,+ defaults: defaults, targetChanged: targetChanged)+ }++ private func file(_ name: String) throws -> String {+ let url = temporary.appendingPathComponent(name)+ try Data([0]).write(to: url)+ return url.path+ }++ // MARK: The conditions to start++ func testABuildMayStartOnlyWithARepositoryTheBaseGameTheKeysAndTheToolsAndNoRunningBuild() throws {+ let store = makeStore()+ XCTAssertFalse(store.canBuild, "no files yet")+ store.updateSlot("base") { $0.paths = [try! file("Game [0100000000001000].nsp")] }+ store.updateSlot("keys") { $0.paths = [try! file("prod.keys")] }+ XCTAssertTrue(store.canBuild)+ repo.isRepo = false+ XCTAssertFalse(store.canBuild, "the repository is not usable")+ repo.isRepo = true; deps.allPresent = false+ XCTAssertFalse(store.canBuild, "a tool is missing")+ deps.allPresent = true; store.running = true+ XCTAssertFalse(store.canBuild, "a build runs")+ }++ func testAnIPhoneBuildWithoutADeviceStopsBeforeTheLongSteps() {+ let store = makeStore()+ store.target = "ios"+ store.startBuild()+ XCTAssertFalse(store.running)+ XCTAssertEqual(store.doneNote, store.t("shell.needsDevice"))+ XCTAssertFalse(store.installsDirectly)+ devices.installDevice = "UDID"; devices.signingTeam = "TEAM"+ XCTAssertTrue(store.installsDirectly)+ store.target = "mac-app"+ XCTAssertFalse(store.installsDirectly, "a Mac app is not installed on a device")+ }++ func testABuildWithoutARepositoryEndsWithTheMessageAndRunsNothing() {+ let store = makeStore()+ store.target = "mac-app"+ repo.isRepo = false; repo.path = ""+ store.startBuild()+ XCTAssertFalse(store.running)+ XCTAssertEqual(store.doneNote, store.t("msg.repoInvalidEmpty"))+ XCTAssertTrue(store.log.text.contains("✗"), "the log says it too")+ }++ // MARK: The inputs++ func testTheTargetTheOutputFolderAndTheCompatibilitySwitchAreSavedAndTheTargetTellsTheApp() {+ var changes = 0+ let store = makeStore { changes += 1 }+ store.target = "mac-app"; store.outDir = "/out"; store.bcOnCPU = true+ XCTAssertEqual(defaults.string(forKey: BuildStore.targetKey), "mac-app")+ XCTAssertEqual(defaults.string(forKey: BuildStore.outputKey), "/out")+ XCTAssertTrue(defaults.bool(forKey: BuildStore.bcOnCPUKey))+ XCTAssertEqual(changes, 1)+ store.target = "mac-app"+ XCTAssertEqual(changes, 1, "the same target is no change")+ XCTAssertEqual(makeStore().outDir, "/out", "a new store starts from what was saved")+ }++ func testTakingFilesFillsTheRowAndNamesTheFirstFileThatDoesNotFit() {+ let store = makeStore()+ store.take(picked: ["/g/Game [0100000000001000].nsp"], kind: .base)+ XCTAssertEqual(store.basePath, "/g/Game [0100000000001000].nsp")+ XCTAssertEqual(store.gameDir, "/g")+ store.take(picked: ["/g/Other [0100000000002800].nsp", "/g/Game update [0100000000001800].nsp"], kind: .update)+ XCTAssertEqual(store.updatePath, "/g/Game update [0100000000001800].nsp", "the file that fits is taken")+ XCTAssertFalse(store.slot("update").problem.isEmpty, "the other one is named on the row")+ store.clear("update")+ XCTAssertEqual(store.updatePath, "")+ XCTAssertEqual(store.slot("update").problem, "")+ }++ func testThePickerIsTheAppsAndGetsTheRowsWordsAndFileTypes() {+ let store = makeStore()+ var asked: [FilePick] = []+ store.choosePaths = { asked.append($0); return ["/g/Game dlc [0100000000001001].nsp"] }+ store.pickFiles(kind: .dlc)+ XCTAssertEqual(asked.count, 1)+ XCTAssertTrue(asked[0].allowsMultiple)+ XCTAssertEqual(asked[0].fileTypes, GameInputs.allowedFileTypes(for: .dlc))+ XCTAssertEqual(asked[0].message, store.t("data.dlcPanelMessage"))+ store.choosePaths = { _ in [] }+ store.pickFiles(kind: .update)+ XCTAssertEqual(store.updatePath, "", "a cancelled panel changes nothing")+ }++ // MARK: The script's events++ func testTheScriptsJSONEventsBecomeStagesAndLogLines() {+ let store = makeStore()+ store.ingest("{\"ev\":\"stage\",\"k\":1,\"n\":3,\"name\":\"extract\",\"step\":\"keys\"}\n")+ XCTAssertEqual(store.stages.map(\.id), [1])+ XCTAssertEqual(store.stages[0].state, .running)+ XCTAssertEqual(store.stages[0].detail, "keys")+ store.ingest("{\"ev\":\"progress\",\"k\":1,\"frac\":0.5,\"done\":5,\"total\":10}\n{\"ev\":\"stage_end\",\"k\":1,\"name\":\"extract\",\"ok\":true,\"elapsed\":3,\"summary\":\"10 files\"}\n")+ XCTAssertEqual(store.stages[0].state, .done)+ XCTAssertEqual(store.stages[0].detail, "10 files")+ XCTAssertEqual(store.stages[0].percent, 100)+ XCTAssertTrue(store.log.text.contains("[1/3] extract · keys …"))+ XCTAssertTrue(store.log.text.contains("✓ extract (\(BuildProgress.duration(3))): 10 files"))+ }++ func testAChunkThatEndsInTheMiddleOfALineWaitsForTheRest() {+ let store = makeStore()+ store.ingest("{\"ev\":\"stage\",\"k\":2,\"n\":3,\"na")+ XCTAssertTrue(store.stages.isEmpty)+ store.ingest("me\":\"pack\"}\nplain line from a tool\n")+ XCTAssertEqual(store.stages.map(\.id), [2])+ XCTAssertTrue(store.log.text.contains("plain line from a tool\n"), "what is not an event is log text")+ }++ func testTheShaderChainNoticeShowsOncePerBuild() {+ let store = makeStore()+ var notices: [String] = []+ store.showNotice = { notices.append($0) }+ store.ingest("{\"ev\":\"say\",\"msg\":\"[NOTE] chain-changed: recompiling\"}\n")+ store.ingest("[NOTE] chain-changed again\n")+ XCTAssertEqual(notices, [store.t("msg.chainChanged")])+ }++ // MARK: The failure++ func testAFailedBuildsLogIsClassifiedAndAnUnknownStopLeavesTheNote() {+ let store = makeStore()+ store.logTail = "[RED] the iOS SDK is not installed\n"+ store.noteFailure()+ XCTAssertEqual(store.failure?.kind, .iosSDK)+ XCTAssertEqual(store.doneNote, store.t(BuildFailureKind.iosSDK.whatKey))+ store.doneNote = "Build failed: something else"+ store.logTail = "nothing the table knows"+ store.noteFailure()+ XCTAssertNil(store.failure)+ XCTAssertEqual(store.doneNote, "Build failed: something else")+ }++ func testBuildAnywayAsksFirstAndArmsTheFlagForOneBuildOnly() {+ let store = makeStore()+ store.target = "mac-app"+ repo.isRepo = false // the build that follows ends at once, which is all this test needs+ store.failure = BuildFailure(kind: .iosSDK, gameName: nil)+ store.requestBuildAnyway()+ XCTAssertNil(store.confirmingOverride, "this stop has no override")+ store.failure = BuildFailure(kind: .otherMetal, gameName: nil)+ store.running = true+ store.requestBuildAnyway()+ XCTAssertNil(store.confirmingOverride, "not while a build runs")+ store.running = false+ store.requestBuildAnyway()+ XCTAssertEqual(store.confirmingOverride, .otherMetal)+ XCTAssertNil(store.armedOverride, "nothing is armed before the confirmation")+ store.cancelBuildAnyway()+ XCTAssertNil(store.confirmingOverride)+ store.requestBuildAnyway()+ store.confirmBuildAnyway()+ XCTAssertNil(store.confirmingOverride)+ XCTAssertNil(store.armedOverride, "the build took the flag: the next one asks again")+ XCTAssertNil(store.takeOverrideFlag())+ store.armedOverride = .damagedNSP+ XCTAssertEqual(store.takeOverrideFlag(), "--allow-damaged")+ XCTAssertNil(store.takeOverrideFlag())+ }++ func testTheFixButtonsRunTheDependencyRowsOwnInstall() {+ let store = makeStore()+ deps.deps = [Dep(id: "dotnet", name: "dep.dotnet", hint: "", present: false, installCmd: ["/usr/bin/true"]),+ Dep(id: "python", name: "dep.python", hint: "", present: false, installCmd: ["/usr/bin/true"])]+ store.fixBuildFailure(.translator)+ store.fixBuildFailure(.zbic)+ store.fixBuildFailure(.iosSDK)+ XCTAssertEqual(deps.installed, ["dotnet", "python", "xcode"])+ XCTAssertFalse(store.fixBusy(.translator))+ deps.busy = ["dotnet"]+ XCTAssertTrue(store.fixBusy(.translator))+ XCTAssertFalse(store.fixBusy(.zbic))+ XCTAssertFalse(store.fixBusy(.keys), "a fix that is no install is never busy")+ }++ func testTheKeysFixUsesTheKeysPickerAndTheCloudFixTheFolderPanel() {+ let store = makeStore()+ var keysAsked = 0+ store.chooseKeys = { keysAsked += 1 }+ store.fixBuildFailure(.keys)+ XCTAssertEqual(keysAsked, 1)+ store.failure = BuildFailure(kind: .cloudFolder, gameName: nil, detail: "/iCloud/x")+ store.doneNote = "stopped"+ store.chooseFolder = { nil }+ store.fixBuildFailure(.cloudFolder)+ XCTAssertEqual(store.failure?.kind, .cloudFolder, "a cancelled panel keeps the stop")+ store.chooseFolder = { "/Users/x/Games" }+ store.fixBuildFailure(.cloudFolder)+ XCTAssertEqual(store.outDir, "/Users/x/Games")+ XCTAssertNil(store.failure, "the next build looks at the new folder")+ XCTAssertEqual(store.doneNote, "")+ }++ func testTheFailureFolderOpensInTheFinderForAFullDisk() throws {+ let store = makeStore()+ let built = temporary.appendingPathComponent("0100_build")+ try FileManager.default.createDirectory(at: built, withIntermediateDirectories: true)+ store.gameDir = temporary.path+ store.failure = BuildFailure(kind: .diskFull, gameName: nil, detail: "40")+ var shown: [URL] = []+ store.revealFolder = { shown.append($0) }+ store.showFailureFolder()+ XCTAssertEqual(shown.map(\.path), [built.path])+ }++ // MARK: The install on a device++ func testReinstallAndResignSayWhyTheyCannotRunInsteadOfStartingATool() {+ let store = makeStore()+ store.reinstallOnDevice()+ XCTAssertFalse(store.running, "nothing was installed: nothing to reinstall")+ store.installedOn = "UDID"; store.installedAppPath = temporary.path + "/gone/DmIOS.app"+ store.reinstallOnDevice()+ XCTAssertFalse(store.running)+ XCTAssertEqual(store.doneNote, String(format: store.t("dev.reinstallMissing"), store.shortPath(store.installedAppPath)))+ store.resignOnDevice(app: store.installedAppPath, device: "UDID")+ XCTAssertEqual(store.doneNote, store.t("dev.resignNoTeam"))+ devices.signingTeam = "TEAM"+ store.resignOnDevice(app: store.installedAppPath, device: "UDID")+ XCTAssertEqual(store.doneNote, store.t("dev.resignOlder"))+ XCTAssertFalse(store.running)+ }++ func testTheSavePanelIsTheAppsAndACancelWritesNothing() {+ let store = makeStore()+ var asked: [(String, String)] = []+ store.chooseSaveLocation = { asked.append(($0, $1)); return nil }+ store.saveIPAPanel()+ XCTAssertEqual(asked.count, 1)+ XCTAssertEqual(asked.first?.0, store.t("dev.saveIPATitle"))+ XCTAssertEqual(asked.first?.1, "DmIOS.ipa")+ XCTAssertFalse(store.running)+ }++ func testTheRetryOfTheGameDataNeedsAnInstallThatLeftOneToRetry() {+ let store = makeStore()+ store.retryShellData()+ XCTAssertFalse(store.running, "no install ran: nothing to retry")+ }++ func testWhatTheStoreWritesItselfIsInTheLanguageOfTheLocalizer() {+ let store = makeStore()+ localizer.lang = .de+ XCTAssertEqual(store.lang, .de)+ XCTAssertEqual(store.t("shell.needsDevice"), L10n.string("shell.needsDevice", .de))+ }++ func testAStoppedBuildWithNothingRunningDoesNothing() {+ let store = makeStore()+ store.stop()+ XCTAssertFalse(store.stopping)+ }+}diff --git a/frontend/Tests/NXModelTests/EngineSyncStoreTests.swift b/frontend/Tests/NXModelTests/EngineSyncStoreTests.swiftindex 1a81506e..b7fa17fc 100644--- a/frontend/Tests/NXModelTests/EngineSyncStoreTests.swift+++ b/frontend/Tests/NXModelTests/EngineSyncStoreTests.swift@@ -4,7 +4,7 @@ import XCTest/// `EngineSyncStore` without SwiftUI: a fake `ProcessRunner` stands in for `tools/engine.py sync`, the checkouts and the engine store are/// folders in a temporary directory and the defaults are a suite of their own. The model's wiring is tested in NX2AppleTests-/// (EngineLayoutTests runs a real script, EngineUpdateModelTests the release app's rules through `BuildModel`).+/// (EngineLayoutTests runs a real script, EngineUpdateModelTests the release app's rules through `LauncherStores`).@MainActor final class EngineSyncStoreTests: XCTestCase {private final class FakeRepo: RepoLocation {var path = ""