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 devices, teams, the install target and the shell copy flow into a DeviceStore (#387)
v0lumehicde6b8971b7f
diff --git a/frontend/ARCHITECTURE.md b/frontend/ARCHITECTURE.mdindex 8ae62f3c..31331ddf 100644--- a/frontend/ARCHITECTURE.md+++ b/frontend/ARCHITECTURE.md@@ -13,10 +13,10 @@ 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, then the dependencies. 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 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.- `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: `AppSignature` (codesign) with the device store, `DeviceTools.run` (devicectl with a timeout and input) and `SaveTransfer` with the device store, `ShellInstaller.run` (a blocking read with start and end callbacks) with the build store, `EngineInstaller` (ditto, in `NXCore` since the engine sync store) still starts it itself, the administrator prompt in `LiveOnboardingDriver` and the game start in `LiveConsoleDriver`. The tests that stand in for `xcodebuild` and `devicectl` through `BuildModel.xcrunPath` stay too: `ShellInstaller` and `DeviceTools` run those tools themselves, so they move with the device store. 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.+- `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.- 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.@@ -25,6 +25,8 @@ Step 1 of #387 made the targets and moved the files that already fit. Step 2 mov- `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`.diff --git a/frontend/Sources/NX2Apple/CheatFiles.swift b/frontend/Sources/NX2Apple/CheatFiles.swiftindex 7267467e..075bce1e 100644--- a/frontend/Sources/NX2Apple/CheatFiles.swift+++ b/frontend/Sources/NX2Apple/CheatFiles.swift@@ -1,4 +1,5 @@import Foundation+import NXCore/// A game's cheat files, as the host reads them (dm/host/hle_cheats.c, and docs/frontends.md "Cheats", the contract for front/// ends): Atmosphere-format `<build ID>.txt` files in a folder, and the player's switches beside them in `<build ID>.enabled`.diff --git a/frontend/Sources/NX2Apple/ContentView.swift b/frontend/Sources/NX2Apple/ContentView.swiftindex b586b204..f527ba00 100644--- a/frontend/Sources/NX2Apple/ContentView.swift+++ b/frontend/Sources/NX2Apple/ContentView.swift@@ -117,46 +117,42 @@ final class BuildModel: ObservableObject {// (--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 devices: [AppleDevice] = []- @Published var teams: [SigningTeam] = []- @Published var devicesChecked = false- @Published var installDevice = UserDefaults.standard.string(forKey: "installDevice") ?? "" {- didSet { UserDefaults.standard.set(installDevice, forKey: "installDevice") }- }- @Published var signingTeam = UserDefaults.standard.string(forKey: "signingTeam") ?? "" {- didSet { UserDefaults.standard.set(signingTeam, forKey: "signingTeam") }- }@Published var installedOn = "" // the device the last build went to (its UDID)@Published var installedAppPath = "" // the signed app that went there- /// The shared app's copy question: the size and the connection (nil: none is up).- @Published var shellCopy: ShellCopyPlan?- @Published var shellWaiting = false // waiting for a cable before the game data goes over- fileprivate var shellCopyAnswer: ((ShellCopyDecision) -> Void)?- let shellWaitCancelled = LockedFlag()private var shellRetry: (framework: String, titleID: String, name: String, archive: String)?- var xcrunPath = "/usr/bin/xcrun" // tests stand in for xcodebuild and devicectl- var volumesRoot = "/Volumes" // where external drives are mounted- var teamsProvider: () -> [SigningTeam] = { DeviceTools.teams() } // the teams the Mac knows, read when a signing step failsvar chooseKeys: (() -> Void)? // tests stand in for the file pickervar 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 { devices.first { $0.id == udid }?.name ?? "iPhone" }-- /// The paired devices and the signing teams, read in the background (devicectl can take a few seconds).- func refreshDevices() {- let xcrun = xcrunPath- DispatchQueue.global(qos: .userInitiated).async {- let devices = DeviceTools.devices(xcrun: xcrun), teams = DeviceTools.teams()- DispatchQueue.main.async {- self.devices = devices; self.teams = teams; self.devicesChecked = true- if !teams.contains(where: { $0.id == self.signingTeam }) { self.signingTeam = teams.first?.id ?? "" }- }- }- }+ 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@@ -191,10 +187,15 @@ final class BuildModel: ObservableObject {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: Stringinit(localizer: Localizer = Localizer(), runner: ProcessRunner = SystemProcessRunner(), gitCheckout: GitCheckout? = nil,- releases: ReleaseSource = GitHubReleases()) {+ releases: ReleaseSource = GitHubReleases(), xcrun: String = "/usr/bin/xcrun", volumesRoot: String = "/Volumes") {self.localizer = localizerself.runner = runner+ self.xcrunPath = xcrun+ self.volumesRoot = volumesRootself.releases = releasesself.gitCheckout = gitCheckout ?? SystemGitCheckout(runner: runner)_ = Self.endGroupsWhenQuitting@@ -619,9 +620,9 @@ final class BuildModel: ObservableObject {/// 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+ let xcrun = xcrunPath, device = installDevice, runner = runnerDispatchQueue.global(qos: .userInitiated).async {- let link = ShellInstall.connection(of: device, in: DeviceTools.devices(xcrun: xcrun, timeout: 20))+ let link = ShellInstall.connection(of: device, in: DeviceTools.devices(xcrun: xcrun, timeout: 20, runner: runner))DispatchQueue.main.async {self.running = falseif link == .notPaired {@@ -664,7 +665,8 @@ final class BuildModel: ObservableObject {/// 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 listed = teamsProvider().contains { $0.id == signingTeam }+ 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 = fdoneNote = failureWhat(f)@@ -1102,28 +1104,19 @@ final class BuildModel: ObservableObject {started: s.state == .running ? Date() : nil))}} }- installer.processStarted = { p in DispatchQueue.main.async { self.proc = p; ProcessGroups.track(p) } }- installer.processEnded = { p in ProcessGroups.untrack(p) }+ 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)- installer.decideCopy = { plan in- let answered = DispatchSemaphore(value: 0)- var answer = ShellCopyDecision.skip- DispatchQueue.main.async {- self.shellWaitCancelled.set(false)- self.shellCopyAnswer = { answer = $0; answered.signal() }- self.shellCopy = plan- }- answered.wait()- return answer- }- installer.waiting = { on in DispatchQueue.main.async { self.shellWaiting = on } }- installer.waitCancelled = { self.shellWaitCancelled.value }+ let devices = deviceStore+ installer.decideCopy = { plan in devices.askCopy(plan) }+ installer.waiting = { on in devices.setWaiting(on) }+ installer.waitCancelled = { devices.waitCancelled }let device = installDeviceDispatchQueue.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 {- self.shellCopy = nil; self.shellWaiting = false+ MainActor.assumeIsolated { devices.copyEnded() }if self.stopping {self.stopping = false; self.running = falseself.resetProgress(); self.doneNote = self.t("msg.stopped"); self.cleanupStaging()@@ -1142,17 +1135,6 @@ final class BuildModel: ObservableObject {}}- /// What the player picked on the copy card (Continue, wait for a cable, not now), handed to the install waiting for it.- func answerShellCopy(_ decision: ShellCopyDecision) {- guard let answer = shellCopyAnswer else { return }- shellCopyAnswer = nil- shellCopy = nil- answer(decision)- }-- /// "Stop waiting" while the install waits for a cable: the poll ends at its next look and the game data stays for later.- func cancelShellWait() { shellWaitCancelled.set(true) }-/// 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 }@@ -1383,6 +1365,7 @@ struct BuilderView: View {@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@EnvironmentObject var loc: Localizer@ObservedObject var library: GameLibraryvar settings = false@@ -1513,7 +1496,7 @@ struct BuilderView: View {if m.target != BuildTarget.mac { install.disabled(m.running) }logPanelaction- ShellCopyCard(m: m)+ ShellCopyCard(devices: devices)BuildFailureCard(m: m)outcomeprogress@@ -1521,29 +1504,30 @@ struct BuilderView: View {/// Where an iPhone build goes: exported as an IPA (as before), or signed and installed on a paired device.private var install: some View {- let devices = [(value: "", label: loc.t("dev.none"))] + m.devices.map { d in+ let devices = devices+ let options = [(value: "", label: loc.t("dev.none"))] + devices.devices.map { d in(value: d.id, label: d.name + (d.reachable ? "" : " (" + loc.t("dev.notConnected") + ")"))}- let teams = m.teams.map { (value: $0.id, label: $0.label(personalTeam: loc.t("dev.personalTeam"))) }- let needsCertificate = m.teams.first { $0.id == m.signingTeam }.map { !$0.hasCertificate } ?? false- return group(loc.t("dev.section"), footnote: m.installDevice.isEmpty ? "" : (needsCertificate ? loc.t("dev.teamNoCert") + " " : "") + loc.t("dev.note")) {- row(loc.t("dev.target"), detail: m.devicesChecked && m.devices.isEmpty ? loc.t("dev.noDevices") : "") {- if !m.devicesChecked { ProgressView().controlSize(.small) }- Button(loc.t("dev.refresh")) { m.refreshDevices() }.buttonStyle(.plain).font(.manrope(13)).foregroundStyle(.secondary)- LauncherDropdown(options: devices, selection: m.installDevice, label: loc.t("dev.target")) { m.installDevice = $0 }+ let teams = devices.teams.map { (value: $0.id, label: $0.label(personalTeam: loc.t("dev.personalTeam"))) }+ let needsCertificate = devices.teams.first { $0.id == devices.signingTeam }.map { !$0.hasCertificate } ?? false+ return group(loc.t("dev.section"), footnote: devices.installDevice.isEmpty ? "" : (needsCertificate ? loc.t("dev.teamNoCert") + " " : "") + loc.t("dev.note")) {+ row(loc.t("dev.target"), detail: devices.checked && devices.devices.isEmpty ? loc.t("dev.noDevices") : "") {+ if !devices.checked { ProgressView().controlSize(.small) }+ Button(loc.t("dev.refresh")) { _ = devices.refresh() }.buttonStyle(.plain).font(.manrope(13)).foregroundStyle(.secondary)+ LauncherDropdown(options: options, selection: devices.installDevice, label: loc.t("dev.target")) { devices.installDevice = $0 }}- if !m.installDevice.isEmpty {+ if !devices.installDevice.isEmpty {dividerif teams.isEmpty {row(loc.t("dev.team"), detail: loc.t("dev.noTeam"), dot: LauncherPalette.building) { EmptyView() }} else {row(loc.t("dev.team")) {- LauncherDropdown(options: teams, selection: m.signingTeam, label: loc.t("dev.team")) { m.signingTeam = $0 }+ LauncherDropdown(options: teams, selection: devices.signingTeam, label: loc.t("dev.team")) { devices.signingTeam = $0 }}}}}- .onAppear { if !m.devicesChecked { m.refreshDevices() } }+ .onAppear { if !devices.checked { _ = devices.refresh() } }}private var files: some View {@@ -1717,7 +1701,7 @@ struct BuilderView: View {/// pointed ("see the log below") while the log itself was out of view on a short window (#52).@ViewBuilder private var logPanel: some View {group(loc.t("section.log")) {- if m.shellCopy != nil || m.shellWaiting {+ if devices.shellCopy != nil || devices.shellWaiting {// The log below is the build's own output; the data transfer is driven by the app, so// its questions and errors (a locked device, a failed listing) answer here, not in it.Text(loc.t("log.transferNote")).font(.manrope(12.5)).foregroundStyle(.secondary)@@ -2063,11 +2047,3 @@ struct BuilderView: View {if d.runModal() == .OK, let u = d.url { repo.path = u.path }}}--/// A flag two threads share (the cancel button on the main thread, the install's wait loop on a background one).-final class LockedFlag: @unchecked Sendable {- private let lock = NSLock()- private var flag = false- func set(_ value: Bool) { lock.lock(); flag = value; lock.unlock() }- var value: Bool { lock.lock(); defer { lock.unlock() }; return flag }-}diff --git a/frontend/Sources/NX2Apple/LauncherView.swift b/frontend/Sources/NX2Apple/LauncherView.swiftindex e154bf24..9c3477b9 100644--- a/frontend/Sources/NX2Apple/LauncherView.swift+++ b/frontend/Sources/NX2Apple/LauncherView.swift@@ -177,7 +177,7 @@ struct ContentView: View {if page == .library {libraryPage} else {- BuilderView(m: m, updates: updates, repo: repo, engine: engine, dependencies: m.dependencies, library: library, settings: page == .settings, onViewGame: { page = .library },+ BuilderView(m: m, updates: updates, repo: repo, engine: engine, dependencies: m.dependencies, devices: m.deviceStore, 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,7 +213,7 @@ struct ContentView: View {}refreshArtwork()readSignatures()- if performStartupChecks { library.discover(); fetchArtwork(); m.refreshDevices(); checkTools() }+ if performStartupChecks { library.discover(); fetchArtwork(); _ = m.deviceStore.refresh(); checkTools() }if performStartupChecks {_ = m.dependencies.check()if engine.usesEngineStore { engine.prepareEngine() } // the release app: its engine store, never git@@ -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.shellCopy != nil || m.shellWaiting || m.stages.contains { $0.id == 1003 && $0.state == .running }+ Text(loc.t(m.deviceStore.shellCopy != nil || m.deviceStore.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 })@@ -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) { found[id] = date } }+ for (id, path) in apps { if let date = AppSignature.expiration(ofApp: path, runner: m.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)+ signatureExpiry[game.id] = AppSignature.expiration(ofApp: game.iosAppPath, runner: m.runner)}}diff --git a/frontend/Sources/NX2Apple/SaveTransfer.swift b/frontend/Sources/NX2Apple/SaveTransfer.swiftindex c00a09ca..4953ae1c 100644--- a/frontend/Sources/NX2Apple/SaveTransfer.swift+++ b/frontend/Sources/NX2Apple/SaveTransfer.swift@@ -5,48 +5,6 @@ import NXCoreimport NXModelimport NXLauncher-/// `xcrun devicectl` for the save transfer, as one function: the tests hand in a stand-in, so no test ever reaches a device.-/// It takes devicectl's arguments and returns whether it exited 0 and what it printed.-struct DeviceControl {- let run: ([String]) -> (ok: Bool, output: String)-- /// What a command that ran out of time prints in place of devicectl's own output (and what a stand-in prints to say the same).- static let timedOut = "devicectl timed out"-- /// Every command has a deadline: devicectl's own (`--timeout`), and behind it one on the process, because CoreDevice can- /// stall on a paired device whose connection is not ready, and a command that never returns leaves the Saves sheet at- /// "Reading..." for good. A copy gets the longer deadline, a query the shorter one.- static func xcrun(_ path: String, queryTimeout: TimeInterval = 10, copyTimeout: TimeInterval = 180) -> DeviceControl {- DeviceControl { args in- let timeout = args.starts(with: ["device", "copy"]) ? copyTimeout : queryTimeout- let p = Process(), out = Pipe()- p.executableURL = URL(fileURLWithPath: path)- p.arguments = ["devicectl", "--timeout", String(max(1, Int(timeout.rounded(.up))))] + args- p.standardOutput = out; p.standardError = out; p.standardInput = FileHandle.nullDevice- do { try p.run() } catch { return (false, error.localizedDescription) }- let fired = Fired()- let deadline = DispatchWorkItem {- fired.set()- if p.isRunning { p.terminate() }- DispatchQueue.global().asyncAfter(deadline: .now() + 2) { if p.isRunning { kill(p.processIdentifier, SIGKILL) } }- }- DispatchQueue.global().asyncAfter(deadline: .now() + timeout + 2, execute: deadline)- let data = out.fileHandleForReading.readDataToEndOfFile()- p.waitUntilExit()- deadline.cancel()- if fired.value { return (false, timedOut) }- return (p.terminationStatus == 0, String(decoding: data, as: UTF8.self))- }- }-- private final class Fired {- private let lock = NSLock()- private var flag = false- func set() { lock.lock(); flag = true; lock.unlock() }- var value: Bool { lock.lock(); defer { lock.unlock() }; return flag }- }-}-/// A game's save on this Mac and in its app on a paired iPhone or iPad (#66), copied either way over the route the install/// takes (devicectl and the app's data container). The save that is replaced is backed up on the Mac/// first, so a copy in the wrong direction loses nothing.@@ -405,10 +363,10 @@ struct SavesView: View {let 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)+ let control = devicectl ?? .xcrun(m.xcrunPath, runner: m.runner)let template = SaveTransfer(titleID: game.titleID, macSave: mac.save, legacySave: mac.legacy, device: "", bundle: "", devicectl: control)- let known = m.devices, xcrun = m.xcrunPath- let list: () -> [AppleDevice] = listDevices ?? (devicectl == nil ? { DeviceTools.devices(xcrun: xcrun, timeout: 10) } : { known })+ let known = MainActor.assumeIsolated { m.deviceStore.devices }, xcrun = m.xcrunPath, runner = m.runner+ let 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,diff --git a/frontend/Sources/NX2Apple/ShellCopyView.swift b/frontend/Sources/NX2Apple/ShellCopyView.swiftindex ad273e92..e9d8cc8c 100644--- a/frontend/Sources/NX2Apple/ShellCopyView.swift+++ b/frontend/Sources/NX2Apple/ShellCopyView.swift@@ -7,11 +7,11 @@ import NXLauncher/// gets one short note. Wi-Fi gets an estimate with Continue and a way to wait for a cable (the copy then starts by itself when the/// device shows up wired). While it waits, the card says so and offers to stop.struct ShellCopyCard: View {- @ObservedObject var m: BuildModel+ @ObservedObject var devices: DeviceStore@EnvironmentObject var loc: Localizervar body: some View {- if let plan = m.shellCopy {+ if let plan = devices.shellCopy {card {Text(loc.t("shell.copyTitle")).font(.manrope(14, .semibold))Text(plan.sizeText).font(.manrope(13)).foregroundStyle(.secondary)@@ -19,19 +19,19 @@ struct ShellCopyCard: View {Text(loc.t("shell.copyExternalNote")).font(.manrope(12.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true).padding(.top, 1)HStack(spacing: 10) {- Button(loc.t("shell.copyStart")) { m.answerShellCopy(.copy) }- if plan.canWaitForCable { Button(loc.t("shell.copyWaitCable")) { m.answerShellCopy(.waitForCable) } }- Button(loc.t("shell.copySkip")) { m.answerShellCopy(.skip) }+ Button(loc.t("shell.copyStart")) { devices.answerCopy(.copy) }+ if plan.canWaitForCable { Button(loc.t("shell.copyWaitCable")) { devices.answerCopy(.waitForCable) } }+ Button(loc.t("shell.copySkip")) { devices.answerCopy(.skip) }}.buttonStyle(LauncherSecondaryButtonStyle()).padding(.top, 2)}- } else if m.shellWaiting {+ } else if devices.shellWaiting {card {HStack(spacing: 8) {ProgressView().controlSize(.small)- Text(String(format: loc.t("shell.copyWaiting"), m.deviceName(m.installDevice))).font(.manrope(13))+ Text(String(format: loc.t("shell.copyWaiting"), devices.deviceName(devices.installDevice))).font(.manrope(13))}- Button(loc.t("shell.copyStopWaiting")) { m.cancelShellWait() }+ Button(loc.t("shell.copyStopWaiting")) { devices.cancelWait() }.buttonStyle(LauncherSecondaryButtonStyle()).padding(.top, 2)}}diff --git a/frontend/Sources/NX2Apple/ShellInstall.swift b/frontend/Sources/NX2Apple/ShellInstall.swiftindex 4aabda9f..43fbd0ec 100644--- a/frontend/Sources/NX2Apple/ShellInstall.swift+++ b/frontend/Sources/NX2Apple/ShellInstall.swift@@ -290,12 +290,8 @@ enum ShellInstall {// ---- the connection of the copy ----- /// How the device is connected to this Mac, from `devicectl list devices` (connectionProperties.transportType: "wired" for a- /// cable, "localNetwork" for Wi-Fi, absent when the device is not reachable). A device the list does not show, or shows- /// unpaired, was never paired with this Mac.- enum Connection: Equatable {- case wired, network, other, notConnected, notPaired- }+ /// How the device is connected to this Mac (`ShellConnection`, NXCore).+ typealias Connection = ShellConnectionstatic func connection(of udid: String, in devices: [AppleDevice]) -> Connection {guard let device = devices.first(where: { $0.id == udid }) else { return .notPaired }@@ -329,23 +325,6 @@ enum ShellInstall {}}-/// What the player is told before the game data goes over: how much, and over which connection. The GUI shows it with its-/// buttons, the terminal prints it and copies.-struct ShellCopyPlan: Equatable {- var files: Int- var bytes: Int64- var connection: ShellInstall.Connection- var deviceName: String- /// "15 GB in 2 files."- var sizeText: String- /// The cable note, or the Wi-Fi hint with its estimate.- var connectionText: String- /// Whether waiting for a cable is offered (the device is on Wi-Fi, or not connected).- var canWaitForCable: Bool { connection == .network || connection == .notConnected }-}--enum ShellCopyDecision: Equatable { case copy, skip, waitForCable }-/// One stage of the install, as the model and the terminal show it.struct ShellStage {var id: Int@@ -373,8 +352,10 @@ struct ShellInstaller {var toolPath = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"var log: (String) -> Void = { _ in }var stage: (ShellStage) -> Void = { _ in }- var processStarted: (Process) -> Void = { _ in }- var processEnded: (Process) -> Void = { _ in }+ /// Told when a tool has started, so Stop can end it (the model keeps it).+ var processStarted: (RunningProcess) -> Void = { _ in }+ /// Starts every tool and the device listing (`ProcessRunner`, NXCore). A test passes in a fake.+ 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 }/// While waiting for a cable: told true when the wait starts and false when it ends, and asked between polls whether the@@ -549,7 +530,7 @@ struct ShellInstaller {}private func connection() -> ShellInstall.Connection {- ShellInstall.connection(of: device, in: DeviceTools.devices(xcrun: xcrun, timeout: 20))+ ShellInstall.connection(of: device, in: DeviceTools.devices(xcrun: xcrun, timeout: 20, runner: runner))}private func copyGameData(titleID: String, archive: String, app: String, bundleID: String, outcome start: Outcome) -> Outcome {@@ -649,35 +630,18 @@ struct ShellInstaller {private func run(_ command: [String], env: [String: String]?, label: String,step: (String) -> (detail: String, percent: Double?)?) -> ToolResult {log("[\(label)] \(command.joined(separator: " "))\n")- let p = Process()- p.executableURL = URL(fileURLWithPath: command[0])- p.arguments = Array(command.dropFirst())- p.environment = env ?? ["PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "HOME": NSHomeDirectory(), "USER": NSUserName(), "LANG": "en_US.UTF-8"]- p.standardInput = FileHandle.nullDevice- if ownGroup { ProcessGroups.inOwnGroup(p, python: python) }- let pipe = Pipe(); p.standardOutput = pipe; p.standardError = pipe- do { try p.run() } catch { return ToolResult(status: 127, output: error.localizedDescription, lastError: error.localizedDescription) }- processStarted(p)- var output = "", pending = "", lastError: String?- func consume(_ line: String) {+ var output = "", lastError: String?+ let launch = ProcessLaunch(+ executable: command[0], arguments: Array(command.dropFirst()),+ environment: env ?? ["PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "HOME": NSHomeDirectory(), "USER": NSUserName(), "LANG": "en_US.UTF-8"],+ groupPython: ownGroup ? python : nil)+ let result = runner.streamLines(launch, started: processStarted) { line inlog(line + "\n")output += line + "\n"if line.contains("error:") || line.hasPrefix("ERROR:") { lastError = line.trimmingCharacters(in: .whitespaces) }}- let handle = pipe.fileHandleForReading- while true {- let data = handle.availableData- if data.isEmpty { break }- pending += String(decoding: data, as: UTF8.self)- while let nl = pending.firstIndex(of: "\n") {- consume(String(pending[..<nl]))- pending = String(pending[pending.index(after: nl)...])- }- }- if !pending.isEmpty { consume(pending) }- p.waitUntilExit()- processEnded(p)- return ToolResult(status: p.terminationStatus, output: output, lastError: lastError)+ guard result.started else { return ToolResult(status: 127, output: result.out, lastError: result.out) }+ return ToolResult(status: result.status, output: output, lastError: lastError)}}diff --git a/frontend/Sources/NXCore/AppSignature.swift b/frontend/Sources/NXCore/AppSignature.swiftindex 8ef69416..9b774dab 100644--- a/frontend/Sources/NXCore/AppSignature.swift+++ b/frontend/Sources/NXCore/AppSignature.swift@@ -10,19 +10,11 @@ package enum AppSignature {/// `ExpirationDate` of the app's embedded.mobileprovision, read through `security cms -D` (the profile is a/// CMS-wrapped property list); nil when the app carries no profile or it cannot be read.- package static func expiration(ofApp app: String) -> Date? {+ package static func expiration(ofApp app: String, runner: ProcessRunner = SystemProcessRunner()) -> Date? {let profile = app + "/" + profileNameguard FileManager.default.fileExists(atPath: profile) else { return nil }- let p = Process(), out = Pipe()- p.executableURL = URL(fileURLWithPath: "/usr/bin/security")- p.arguments = ["cms", "-D", "-i", profile]- p.standardOutput = out- p.standardError = FileHandle.nullDevice- guard (try? p.run()) != nil else { return nil }- let data = out.fileHandleForReading.readDataToEndOfFile()- p.waitUntilExit()- guard p.terminationStatus == 0 else { return nil }- return expiration(fromProfile: data)+ guard let out = runner.output("/usr/bin/security", ["cms", "-D", "-i", profile]) else { return nil }+ return expiration(fromProfile: Data(out.utf8))}/// The profile plist's ExpirationDate. Split out so the parse is tested without a signed app.diff --git a/frontend/Sources/NXCore/DeviceControl.swift b/frontend/Sources/NXCore/DeviceControl.swiftnew file mode 100644index 00000000..453bf1a0--- /dev/null+++ b/frontend/Sources/NXCore/DeviceControl.swift@@ -0,0 +1,29 @@+import Foundation++/// `xcrun devicectl` for the save transfer, as one function: the tests hand in a stand-in, so no test ever reaches a device.+/// It takes devicectl's arguments and returns whether it exited 0 and what it printed.+package struct DeviceControl {+ package let run: ([String]) -> (ok: Bool, output: String)++ package init(run: @escaping ([String]) -> (ok: Bool, output: String)) { self.run = run }++ /// What a command that ran out of time prints in place of devicectl's own output (and what a stand-in prints to say the same).+ package static let timedOut = "devicectl timed out"++ /// Every command has a deadline: devicectl's own (`--timeout`), and behind it one on the process (`ProcessLaunch.timeout`),+ /// because CoreDevice can stall on a paired device whose connection is not ready, and a command that never returns leaves the+ /// Saves sheet at "Reading..." for good. A copy gets the longer deadline, a query the shorter one.+ package static func xcrun(_ path: String, queryTimeout: TimeInterval = 10, copyTimeout: TimeInterval = 180,+ runner: ProcessRunner = SystemProcessRunner()) -> DeviceControl {+ DeviceControl { args in+ let timeout = args.starts(with: ["device", "copy"]) ? copyTimeout : queryTimeout+ let launch = ProcessLaunch(executable: path,+ arguments: ["devicectl", "--timeout", String(max(1, Int(timeout.rounded(.up))))] + args,+ mergesErrors: true, timeout: timeout + 2)+ let r = runner.capture(launch)+ if !r.started { return (false, r.out) }+ if r.timedOut { return (false, timedOut) }+ return (r.status == 0, r.out)+ }+ }+}diff --git a/frontend/Sources/NXCore/Devices.swift b/frontend/Sources/NXCore/Devices.swiftindex ac19653b..4e48ab48 100644--- a/frontend/Sources/NXCore/Devices.swift+++ b/frontend/Sources/NXCore/Devices.swift@@ -54,10 +54,11 @@ package struct XcodeTeam: Equatable {package enum DeviceTools {/// The paired physical iPhones and iPads, reachable ones first./// `timeout` ends a listing that hangs (the Saves sheet asks with one), as no devices.- package static func devices(xcrun: String = "/usr/bin/xcrun", timeout: TimeInterval? = nil) -> [AppleDevice] {+ package static func devices(xcrun: String = "/usr/bin/xcrun", timeout: TimeInterval? = nil,+ runner: ProcessRunner = SystemProcessRunner()) -> [AppleDevice] {let file = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-devices-\(UUID().uuidString).json")defer { try? FileManager.default.removeItem(at: file) }- guard run(xcrun, ["devicectl", "list", "devices", "--json-output", file.path], timeout: timeout) != nil,+ guard run(xcrun, ["devicectl", "list", "devices", "--json-output", file.path], timeout: timeout, runner: runner) != nil,let data = try? Data(contentsOf: file) else { return [] }return parseDevices(data)}@@ -96,8 +97,8 @@ package enum DeviceTools {/// Every team the launcher can offer: the teams of the Apple IDs signed in to Xcode plus the teams of development/// certificates in the keychain, one entry per team ID. A team with a certificate comes first (it can sign at once).- package static func teams() -> [SigningTeam] {- merge(certificates: certificateTeams(), xcode: xcodeTeams())+ package static func teams(runner: ProcessRunner = SystemProcessRunner()) -> [SigningTeam] {+ merge(certificates: certificateTeams(runner: runner), xcode: xcodeTeams(runner: runner))}/// Pure: union by team ID. The certificate gives the identity, Xcode gives the team's name and whether it is a free one.@@ -115,8 +116,8 @@ package enum DeviceTools {/// The teams of the accounts signed in to Xcode, from its preferences (read only; nothing of the account but the/// teams is looked at).- package static func xcodeTeams() -> [XcodeTeam] {- guard let plist = run("/usr/bin/defaults", ["export", "com.apple.dt.Xcode", "-"]) else { return [] }+ package static func xcodeTeams(runner: ProcessRunner = SystemProcessRunner()) -> [XcodeTeam] {+ guard let plist = run("/usr/bin/defaults", ["export", "com.apple.dt.Xcode", "-"], runner: runner) else { return [] }return xcodeTeams(fromPlist: Data(plist.utf8))}@@ -145,12 +146,12 @@ package enum DeviceTools {}/// The development identities that can sign for a device, with their teams (one per team ID).- package static func certificateTeams() -> [SigningTeam] {- guard let list = run("/usr/bin/security", ["find-identity", "-v", "-p", "codesigning"]) else { return [] }+ package static func certificateTeams(runner: ProcessRunner = SystemProcessRunner()) -> [SigningTeam] {+ guard let list = run("/usr/bin/security", ["find-identity", "-v", "-p", "codesigning"], runner: runner) else { return [] }var seen = Set<String>()return identities(list).compactMap { identity in- guard let pem = run("/usr/bin/security", ["find-certificate", "-c", identity, "-p"]),- let subject = run("/usr/bin/openssl", ["x509", "-noout", "-subject"], input: pem),+ guard let pem = run("/usr/bin/security", ["find-certificate", "-c", identity, "-p"], runner: runner),+ let subject = run("/usr/bin/openssl", ["x509", "-noout", "-subject"], input: pem, runner: runner),let team = team(fromSubject: subject), seen.insert(team).inserted else { return nil }return SigningTeam(id: team, identity: identity)}@@ -171,23 +172,10 @@ package enum DeviceTools {return subject[range].split(separator: "=").last.map { $0.trimmingCharacters(in: .whitespaces) }}- private static func run(_ tool: String, _ args: [String], input: String? = nil, timeout: TimeInterval? = nil) -> String? {- let p = Process(), out = Pipe(), inPipe = Pipe()- p.executableURL = URL(fileURLWithPath: tool)- p.arguments = args- p.standardOutput = out- p.standardError = FileHandle.nullDevice- p.standardInput = input == nil ? FileHandle.nullDevice : inPipe- do { try p.run() } catch { return nil }- if let timeout {- DispatchQueue.global().asyncAfter(deadline: .now() + timeout) {- if p.isRunning { p.terminate() }- DispatchQueue.global().asyncAfter(deadline: .now() + 2) { if p.isRunning { kill(p.processIdentifier, SIGKILL) } }- }- }- if let input { inPipe.fileHandleForWriting.write(Data(input.utf8)); try? inPipe.fileHandleForWriting.close() }- let data = out.fileHandleForReading.readDataToEndOfFile()- p.waitUntilExit()- return p.terminationStatus == 0 ? String(decoding: data, as: UTF8.self) : nil+ /// The tool's stdout when it exits 0 within `timeout`, nil otherwise (its errors are thrown away).+ private static func run(_ tool: String, _ args: [String], input: String? = nil, timeout: TimeInterval? = nil,+ runner: ProcessRunner) -> String? {+ let r = runner.capture(ProcessLaunch(executable: tool, arguments: args, timeout: timeout, input: input))+ return r.ok ? r.out : nil}}diff --git a/frontend/Sources/NXCore/LockedFlag.swift b/frontend/Sources/NXCore/LockedFlag.swiftnew file mode 100644index 00000000..e15967f9--- /dev/null+++ b/frontend/Sources/NXCore/LockedFlag.swift@@ -0,0 +1,12 @@+import Foundation++/// A flag two threads share (the cancel button on the main thread, the install's wait loop on a background one).+package final class LockedFlag: @unchecked Sendable {+ private let lock = NSLock()+ private var flag = false++ package init() {}++ package func set(_ value: Bool) { lock.lock(); flag = value; lock.unlock() }+ package var value: Bool { lock.lock(); defer { lock.unlock() }; return flag }+}diff --git a/frontend/Sources/NXCore/ProcessRunner.swift b/frontend/Sources/NXCore/ProcessRunner.swiftindex d02a93ee..759d2438 100644--- a/frontend/Sources/NXCore/ProcessRunner.swift+++ b/frontend/Sources/NXCore/ProcessRunner.swift@@ -11,11 +11,15 @@ package struct ProcessLaunch {package var mergesErrors = false/// Start in a process group of its own, through this Python (`ProcessGroups`). nil: no group.package var groupPython: String?+ /// A captured run that is still going after this many seconds is ended (SIGTERM, then SIGKILL 2 s later) and reports `timedOut`.+ package var timeout: TimeInterval?+ /// Written to standard input of a captured run, which is then closed. nil: standard input is empty.+ package var input: String?package init(executable: String, arguments: [String] = [], environment: [String: String]? = nil, directory: String? = nil,- mergesErrors: Bool = false, groupPython: String? = nil) {+ mergesErrors: Bool = false, groupPython: String? = nil, timeout: TimeInterval? = nil, input: String? = nil) {self.executable = executable; self.arguments = arguments; self.environment = environment; self.directory = directory- self.mergesErrors = mergesErrors; self.groupPython = groupPython+ self.mergesErrors = mergesErrors; self.groupPython = groupPython; self.timeout = timeout; self.input = input}/// `command[0]` is the tool, the rest its arguments.@@ -32,10 +36,12 @@ package struct ProcessResult: Equatable {package var status: Int32package var out: Stringpackage var err: String- package var ok: Bool { started && status == 0 }+ /// The run was ended because it outlasted `ProcessLaunch.timeout`.+ package var timedOut: Bool+ package var ok: Bool { started && status == 0 && !timedOut }- package init(started: Bool = true, status: Int32 = 0, out: String = "", err: String = "") {- self.started = started; self.status = status; self.out = out; self.err = err+ package init(started: Bool = true, status: Int32 = 0, out: String = "", err: String = "", timedOut: Bool = false) {+ self.started = started; self.status = status; self.out = out; self.err = err; self.timedOut = timedOut}package static func failedToStart(_ reason: String) -> ProcessResult { ProcessResult(started: false, status: -1, out: reason) }@@ -56,6 +62,11 @@ package protocol ProcessRunner {func capture(_ launch: ProcessLaunch) -> ProcessResult/// Run to the end and hand each output line to `line` as it arrives (blocking). true when it exited 0.func stream(_ launch: ProcessLaunch, line: @escaping (String) -> Void) -> Bool+ /// Run to the end with stdout and stderr merged and hand out every whole line, empty ones too, a last line without its newline+ /// included (blocking). `started` gets the process right after it starts, for a caller that can end it (Stop). With+ /// `groupPython` the process leads a group of its own that `ProcessGroups` tracks until it exits. A process that could not+ /// start is `started == false` with the reason in `out`, and `started` is not called.+ func streamLines(_ launch: ProcessLaunch, started: @escaping (RunningProcess) -> Void, line: @escaping (String) -> Void) -> ProcessResult/// Start and return at once. `onOutput` gets the combined output in chunks on a background queue, `onExit` the exit status./// With `groupPython` the process is the leader of a group of its own that `ProcessGroups` tracks until it exits.func start(_ launch: ProcessLaunch, onOutput: @escaping (Data) -> Void, onExit: @escaping (Int32) -> Void) throws -> RunningProcess@@ -99,11 +110,17 @@ package struct SystemProcessRunner: ProcessRunner {package func capture(_ launch: ProcessLaunch) -> ProcessResult {let p = process(launch)- p.standardInput = FileHandle.nullDevice+ let stdin = Pipe()+ p.standardInput = launch.input == nil ? FileHandle.nullDevice : stdinlet out = Pipe(), err = Pipe()p.standardOutput = outp.standardError = launch.mergesErrors ? out : errdo { try p.run() } catch { return .failedToStart(error.localizedDescription) }+ let deadline = launch.timeout.map { Deadline(p, after: $0) }+ if let input = launch.input {+ stdin.fileHandleForWriting.write(Data(input.utf8))+ try? stdin.fileHandleForWriting.close()+ }// Both pipes are drained before the exit is awaited, so the child cannot block on a full pipe.let errData = LockedData()let drained = DispatchGroup()@@ -114,8 +131,34 @@ package struct SystemProcessRunner: ProcessRunner {let outData = out.fileHandleForReading.readDataToEndOfFile()drained.wait()p.waitUntilExit()+ deadline?.cancel()return ProcessResult(status: p.terminationStatus, out: String(data: outData, encoding: .utf8) ?? "",- err: String(data: errData.value, encoding: .utf8) ?? "")+ err: String(data: errData.value, encoding: .utf8) ?? "", timedOut: deadline?.fired ?? false)+ }++ package func streamLines(_ launch: ProcessLaunch, started: @escaping (RunningProcess) -> Void, line: @escaping (String) -> Void) -> ProcessResult {+ let p = process(launch)+ p.standardInput = FileHandle.nullDevice+ if let python = launch.groupPython { ProcessGroups.inOwnGroup(p, python: python) }+ let pipe = Pipe(); p.standardOutput = pipe; p.standardError = pipe+ do { try p.run() } catch { return .failedToStart(error.localizedDescription) }+ if launch.groupPython != nil { ProcessGroups.track(p) }+ started(p)+ var pending = ""+ let handle = pipe.fileHandleForReading+ while true {+ let data = handle.availableData+ if data.isEmpty { break }+ pending += String(decoding: data, as: UTF8.self)+ while let nl = pending.firstIndex(of: "\n") {+ line(String(pending[..<nl]))+ pending = String(pending[pending.index(after: nl)...])+ }+ }+ if !pending.isEmpty { line(pending) }+ p.waitUntilExit()+ if launch.groupPython != nil { ProcessGroups.untrack(p) }+ return ProcessResult(status: p.terminationStatus)}package func stream(_ launch: ProcessLaunch, line: @escaping (String) -> Void) -> Bool {@@ -158,3 +201,23 @@ private final class LockedData: @unchecked Sendable {func set(_ new: Data) { lock.lock(); data = new; lock.unlock() }var value: Data { lock.lock(); defer { lock.unlock() }; return data }}++/// Ends a process that outlasts its time: SIGTERM at the deadline, SIGKILL 2 s later when it still runs. Cancelled when the run ends.+private final class Deadline: @unchecked Sendable {+ private let lock = NSLock()+ private var didFire = false+ private var work: DispatchWorkItem?++ init(_ p: Process, after seconds: TimeInterval) {+ let item = DispatchWorkItem { [self] in+ lock.lock(); didFire = true; lock.unlock()+ if p.isRunning { p.terminate() }+ DispatchQueue.global().asyncAfter(deadline: .now() + 2) { if p.isRunning { kill(p.processIdentifier, SIGKILL) } }+ }+ work = item+ DispatchQueue.global().asyncAfter(deadline: .now() + seconds, execute: item)+ }++ func cancel() { work?.cancel() }+ var fired: Bool { lock.lock(); defer { lock.unlock() }; return didFire }+}diff --git a/frontend/Sources/NXCore/ShellCopy.swift b/frontend/Sources/NXCore/ShellCopy.swiftnew file mode 100644index 00000000..cc7ddafa--- /dev/null+++ b/frontend/Sources/NXCore/ShellCopy.swift@@ -0,0 +1,30 @@+import Foundation++/// How the device is connected to this Mac, from `devicectl list devices` (connectionProperties.transportType: "wired" for a+/// cable, "localNetwork" for Wi-Fi, absent when the device is not reachable). A device the list does not show, or shows+/// unpaired, was never paired with this Mac.+package enum ShellConnection: Equatable {+ case wired, network, other, notConnected, notPaired+}++/// What the player is told before the game data goes over: how much, and over which connection. The GUI shows it with its+/// buttons, the terminal prints it and copies.+package struct ShellCopyPlan: Equatable {+ package var files: Int+ package var bytes: Int64+ package var connection: ShellConnection+ package var deviceName: String+ /// "15 GB in 2 files."+ package var sizeText: String+ /// The cable note, or the Wi-Fi hint with its estimate.+ package var connectionText: String+ /// Whether waiting for a cable is offered (the device is on Wi-Fi, or not connected).+ package var canWaitForCable: Bool { connection == .network || connection == .notConnected }++ package init(files: Int, bytes: Int64, connection: ShellConnection, deviceName: String, sizeText: String, connectionText: String) {+ self.files = files; self.bytes = bytes; self.connection = connection; self.deviceName = deviceName+ self.sizeText = sizeText; self.connectionText = connectionText+ }+}++package enum ShellCopyDecision: Equatable { case copy, skip, waitForCable }diff --git a/frontend/Sources/NXModel/DeviceStore.swift b/frontend/Sources/NXModel/DeviceStore.swiftnew file mode 100644index 00000000..3edfb222--- /dev/null+++ b/frontend/Sources/NXModel/DeviceStore.swift@@ -0,0 +1,126 @@+import Foundation+import Combine+import NXCore++/// The devices (LNPANDY/NX2Apple#387, step 7): the iPhones and iPads paired with this Mac, the teams it can sign for, the device and+/// the team the player chose to install on, and the copy flow of the shared app (the question before the game data goes over, and+/// the wait for a cable). It follows `AppUpdateStore` (`frontend/ARCHITECTURE.md`, "Stores").+///+/// - What it works with comes through `init`: a `ProcessRunner` for devicectl and the keychain, the path of `xcrun` (a test points it+/// at a stand-in), the defaults the choices are saved in. The two listings are closures with the real ones as default, so a test+/// gives it devices and teams without a Mac that has them.+/// - The listings block (devicectl takes a few seconds), so they run off the main actor. `refresh()` returns the `Task`.+/// - The copy question is asked by the install, which runs on a background queue and waits for the answer: `askCopy` blocks that+/// queue, `answerCopy` (the card's buttons) lets it go on. `setWaiting` and `waitCancelled` are the same bridge for the cable wait.+/// - Not here, because they belong to the build run: the device the last build went to (`installedOn`, `installedAppPath`), whether+/// this build installs directly (it reads the build target), the retry of the game data, and the install itself (`installShell`),+/// the reinstall and the re-sign. They go with the build store.+@MainActor package final class DeviceStore: ObservableObject {+ nonisolated package static let deviceKey = "installDevice"+ nonisolated package static let teamKey = "signingTeam"++ @Published package var devices: [AppleDevice] = []+ @Published package var teams: [SigningTeam] = []+ /// The listing ran at least once, so the picker shows its spinner until then and "no devices" after.+ @Published package var checked = false+ /// The UDID of the device a build is installed on. Empty: the build stays an IPA. Saved when it changes.+ @Published package var installDevice: String {+ didSet { defaults.set(installDevice, forKey: Self.deviceKey) }+ }+ /// The team ID the build is signed for. Saved when it changes.+ @Published package var signingTeam: String {+ didSet { defaults.set(signingTeam, forKey: Self.teamKey) }+ }+ /// The shared app's copy question: the size and the connection (nil: none is up).+ @Published package private(set) var shellCopy: ShellCopyPlan?+ /// Waiting for a cable before the game data goes over.+ @Published package private(set) var shellWaiting = false++ /// The `xcrun` the device tools and the install run through.+ package let xcrun: String+ /// The teams the Mac knows, read by the refresh and again when a signing step fails.+ package var readTeams: @Sendable () -> [SigningTeam]++ private let defaults: UserDefaults+ private let listDevices: @Sendable (_ xcrun: String) -> [AppleDevice]+ private var copyAnswer: ((ShellCopyDecision) -> Void)?+ private let waitCancel = LockedFlag()++ /// - Parameters:+ /// - listDevices: the paired devices for an `xcrun` path. Runs off the main actor.+ /// - readTeams: the signing teams. Runs off the main actor.+ package init(runner: ProcessRunner, xcrun: String = "/usr/bin/xcrun", defaults: UserDefaults = .standard,+ listDevices: (@Sendable (String) -> [AppleDevice])? = nil,+ readTeams: (@Sendable () -> [SigningTeam])? = nil) {+ self.xcrun = xcrun+ self.defaults = defaults+ self.listDevices = listDevices ?? { DeviceTools.devices(xcrun: $0, runner: runner) }+ self.readTeams = readTeams ?? { DeviceTools.teams(runner: runner) }+ self.installDevice = defaults.string(forKey: Self.deviceKey) ?? ""+ self.signingTeam = defaults.string(forKey: Self.teamKey) ?? ""+ }++ /// A device's name for a message, "iPhone" when this Mac has not listed it.+ package func deviceName(_ udid: String) -> String { devices.first { $0.id == udid }?.name ?? "iPhone" }++ /// The paired devices and the signing teams, read in the background (devicectl can take a few seconds). A team that is no longer+ /// known is replaced by the first one.+ @discardableResult package func refresh() -> Task<Void, Never> {+ let xcrun = xcrun, list = listDevices, teamsOf = readTeams+ return Task { @MainActor in+ let (devices, teams) = await Task.detached(priority: .userInitiated) { (list(xcrun), teamsOf()) }.value+ self.devices = devices; self.teams = teams; self.checked = true+ if !teams.contains(where: { $0.id == self.signingTeam }) { self.signingTeam = teams.first?.id ?? "" }+ }+ }++ // MARK: The copy flow++ /// Asks the player whether the game data goes over now (the card shows the plan with Continue, "Wait for a cable" and "Not now")+ /// and blocks the calling queue until they answer. Called by the install on its background queue, never on the main thread.+ nonisolated package func askCopy(_ plan: ShellCopyPlan) -> ShellCopyDecision {+ let answered = DispatchSemaphore(value: 0)+ let box = Answer()+ DispatchQueue.main.async {+ MainActor.assumeIsolated {+ self.waitCancel.set(false)+ self.copyAnswer = { box.set($0); answered.signal() }+ self.shellCopy = plan+ }+ }+ answered.wait()+ return box.value+ }++ /// What the player picked on the copy card (Continue, wait for a cable, not now), handed to the install waiting for it.+ package func answerCopy(_ decision: ShellCopyDecision) {+ guard let answer = copyAnswer else { return }+ copyAnswer = nil+ shellCopy = nil+ answer(decision)+ }++ /// The install tells that the cable wait starts or ends. Called from its background queue.+ nonisolated package func setWaiting(_ on: Bool) {+ DispatchQueue.main.async { MainActor.assumeIsolated { self.shellWaiting = on } }+ }++ /// "Stop waiting" while the install waits for a cable: the poll ends at its next look and the game data stays for later.+ package func cancelWait() { waitCancel.set(true) }++ /// The install asks between two polls whether the player cancelled.+ nonisolated package var waitCancelled: Bool { waitCancel.value }++ /// The install ended: no question and no wait stay on the screen.+ package func copyEnded() {+ shellCopy = nil; shellWaiting = false+ }++ /// The answer the blocked queue reads after the semaphore.+ private final class Answer: @unchecked Sendable {+ private let lock = NSLock()+ private var decision = ShellCopyDecision.skip+ func set(_ new: ShellCopyDecision) { lock.lock(); decision = new; lock.unlock() }+ var value: ShellCopyDecision { lock.lock(); defer { lock.unlock() }; return decision }+ }+}diff --git a/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swift b/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swiftindex ccbcaa7d..7fe26a46 100644--- a/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swift+++ b/frontend/Tests/NX2AppleTests/BuildFailureRowsTests.swift@@ -185,19 +185,19 @@ final class BuildFailureRowsTests: XCTestCase {XCTAssertEqual(shown, ["/Users/x/Games/Zelda"], "the folder the message names")}- func testAnInstallStepThatFailedShowsItsRow() {+ @MainActor func testAnInstallStepThatFailedShowsItsRow() {let m = BuildModel()m.signingTeam = "TEAM123456"- m.teamsProvider = { [SigningTeam(id: "TEAM123456", identity: "")] }+ m.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.teamsProvider = { [] }+ m.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.teamsProvider = { [SigningTeam(id: "TEAM123456", identity: "")] }+ m.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")diff --git a/frontend/Tests/NX2AppleTests/DropFilesTests.swift b/frontend/Tests/NX2AppleTests/DropFilesTests.swiftindex 3329a1ef..330d9493 100644--- a/frontend/Tests/NX2AppleTests/DropFilesTests.swift+++ b/frontend/Tests/NX2AppleTests/DropFilesTests.swift@@ -138,7 +138,7 @@ final class DropFilesTests: XCTestCase {MainActor.assumeIsolated { model.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, library: library).environmentObject(PadFocus()).environmentObject(model.localizer)+ 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).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/LauncherControlWidthTests.swift b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swiftindex 3d7950cd..9f72f766 100644--- a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift+++ b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift@@ -120,9 +120,9 @@ final class LauncherControlWidthTests: XCTestCase {Scenario(name: "builds for an iPhone with a device and a team", page: .builds, atLeast: 6) { m, _, directory inm.repoPath = try self.makeRepo(directory, git: true)m.target = "ios"- m.devicesChecked = true- m.devices = [device]- m.teams = [team]+ MainActor.assumeIsolated { m.deviceStore.checked = true }+ MainActor.assumeIsolated { m.deviceStore.devices = [device] }+ MainActor.assumeIsolated { m.deviceStore.teams = [team] }m.installDevice = device.idm.signingTeam = team.id},@@ -136,8 +136,8 @@ final class LauncherControlWidthTests: XCTestCase {m.repoPath = try self.makeRepo(directory, git: true)m.target = "ios"m.done = true- m.devicesChecked = true- m.devices = [device]+ MainActor.assumeIsolated { m.deviceStore.checked = true }+ MainActor.assumeIsolated { m.deviceStore.devices = [device] }m.installedOn = device.idm.archivePath = directory.appendingPathComponent("romfs").path},@@ -145,7 +145,7 @@ final class LauncherControlWidthTests: XCTestCase {m.repoPath = try self.makeRepo(directory, git: true)m.target = "ios"m.done = true- m.devicesChecked = true+ MainActor.assumeIsolated { m.deviceStore.checked = true }m.archivePath = directory.appendingPathComponent("romfs").path},]diff --git a/frontend/Tests/NX2AppleTests/LibraryTests.swift b/frontend/Tests/NX2AppleTests/LibraryTests.swiftindex 677285b8..7be6daa5 100644--- a/frontend/Tests/NX2AppleTests/LibraryTests.swift+++ b/frontend/Tests/NX2AppleTests/LibraryTests.swift@@ -386,8 +386,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()- model.xcrunPath = "/usr/bin/true"+ let model = BuildModel(xcrun: "/usr/bin/true")model.installedOn = "00008150-AAAA"model.installedAppPath = temporary.path + "/gone/DmShell.app"var reported = expectation(description: "Reinstall says what is missing")@@ -867,21 +866,21 @@ final class LibraryTests: XCTestCase {// An iPhone build with a paired device and a team (example values)let previousTarget = model.targetmodel.target = "ios"- model.devicesChecked = true- model.devices = [AppleDevice(id: "00008150-AAAA", name: "iPhone", model: "iPhone 17 Pro Max", os: "27.0", reachable: true),+ model.deviceStore.checked = true+ model.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.teams = [SigningTeam(id: "TEAM123456", identity: "Apple Development: Jo Doe (ABCDE12345)")]+ model.deviceStore.teams = [SigningTeam(id: "TEAM123456", identity: "Apple Development: Jo Doe (ABCDE12345)")]let previousDevice = model.installDevice, previousTeam = model.signingTeammodel.installDevice = "00008150-AAAA"; model.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.teams = [SigningTeam(id: "FGHIJ67890", identity: "", name: "Jo Doe", personal: true),+ model.deviceStore.teams = [SigningTeam(id: "FGHIJ67890", identity: "", name: "Jo Doe", personal: true),SigningTeam(id: "KLMNO11111", identity: "", name: "Studio Ltd")]model.signingTeam = "FGHIJ67890"try capture("build-install-xcode-team", height: 1300, page: .builds)- model.teams = []; model.signingTeam = ""+ model.deviceStore.teams = []; model.signingTeam = ""try capture("build-install-no-team", height: 1300, page: .builds)- model.teams = [SigningTeam(id: "TEAM123456", identity: "Apple Development: Jo Doe (ABCDE12345)")]+ model.deviceStore.teams = [SigningTeam(id: "TEAM123456", identity: "Apple Development: Jo Doe (ABCDE12345)")]model.signingTeam = "TEAM123456"model.installDevice = previousDevice; model.signingTeam = previousTeam; model.target = previousTarget// The Free space sheet with a measured build folder (example sizes), two parts picked, then while a build runsdiff --git a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift b/frontend/Tests/NX2AppleTests/ShellInstallTests.swiftindex d5fa303b..0926aff0 100644--- a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift+++ b/frontend/Tests/NX2AppleTests/ShellInstallTests.swift@@ -771,7 +771,7 @@ 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()+ let model = BuildModel(xcrun: f.xcrun)model.repoPath = f.repomodel.target = "ios"model.outDir = path("out")@@ -781,7 +781,6 @@ final class ShellInstallTests: XCTestCase {model.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]model.installDevice = devicemodel.signingTeam = team- model.xcrunPath = f.xcruntry 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@@ -803,7 +802,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.$shellCopy.compactMap { $0 }.prefix(1).sink { _ in model.answerShellCopy(.copy) }+ let asked = model.deviceStore.$shellCopy.compactMap { $0 }.prefix(1).sink { _ in model.deviceStore.answerCopy(.copy) }model.startBuild()wait(for: [finished], timeout: 30)withExtendedLifetime(token) {}; withExtendedLifetime(asked) {}@@ -835,7 +834,7 @@ final class ShellInstallTests: XCTestCase {}@MainActor private func makeModel(_ f: Fixture) throws -> BuildModel {- let model = BuildModel()+ let model = BuildModel(xcrun: f.xcrun)model.repoPath = f.repomodel.target = "ios"model.outDir = path("out")@@ -845,7 +844,6 @@ final class ShellInstallTests: XCTestCase {model.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]model.installDevice = devicemodel.signingTeam = team- model.xcrunPath = f.xcruntry 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")@@ -881,7 +879,7 @@ final class ShellInstallTests: XCTestCase {let model = try makeModel(f)try write(state + "/fail-on", "romfs.img")var plans: [ShellCopyPlan] = []- let asked = model.$shellCopy.compactMap { $0 }.sink { plans.append($0); model.answerShellCopy(.copy) }+ let asked = model.deviceStore.$shellCopy.compactMap { $0 }.sink { plans.append($0); model.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() }diff --git a/frontend/Tests/NX2AppleTests/SourceSizeTests.swift b/frontend/Tests/NX2AppleTests/SourceSizeTests.swiftindex 46289ccf..b13801c3 100644--- a/frontend/Tests/NX2AppleTests/SourceSizeTests.swift+++ b/frontend/Tests/NX2AppleTests/SourceSizeTests.swift@@ -7,7 +7,7 @@ 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": 2073,+ "NX2Apple/ContentView.swift": 2049,"NX2Apple/LauncherView.swift": 967,"NXCore/Localization.swift": 4237,]diff --git a/frontend/Tests/NXCoreTests/DeviceToolsRunnerTests.swift b/frontend/Tests/NXCoreTests/DeviceToolsRunnerTests.swiftnew file mode 100644index 00000000..7d566d13--- /dev/null+++ b/frontend/Tests/NXCoreTests/DeviceToolsRunnerTests.swift@@ -0,0 +1,124 @@+import XCTest+@testable import NXCore++/// The device tools over a fake `ProcessRunner`: devicectl, the keychain, Xcode's preferences and the profile reader answer from the+/// test, so nothing here reaches a device or the keychain of this Mac.+final class DeviceToolsRunnerTests: XCTestCase {+ private let fake = FakeProcessRunner()++ private func listing(_ udid: String, name: String) -> Data {+ let device: [String: Any] = [+ "hardwareProperties": ["reality": "physical", "platform": "iOS", "udid": udid, "marketingName": "iPhone 17"],+ "deviceProperties": ["name": name, "osVersionNumber": "27.0"],+ "connectionProperties": ["pairingState": "paired", "transportType": "wired"]]+ return try! JSONSerialization.data(withJSONObject: ["result": ["devices": [device]]])+ }++ func testDevicesAskDevicectlForAJsonFileAndReadIt() {+ fake.answer = { launch in+ // devicectl writes its JSON to the file the argument names+ if let i = launch.arguments.firstIndex(of: "--json-output") { try? self.listing("UDID-1", name: "Jo's iPhone").write(to: URL(fileURLWithPath: launch.arguments[i + 1])) }+ return ProcessResult()+ }+ let devices = DeviceTools.devices(xcrun: "/fake/xcrun", timeout: 20, runner: fake)+ XCTAssertEqual(devices.map(\.id), ["UDID-1"])+ XCTAssertEqual(devices.first?.name, "Jo's iPhone")+ XCTAssertEqual(devices.first?.wired, true)+ let launch = fake.launches[0]+ XCTAssertEqual(launch.executable, "/fake/xcrun")+ XCTAssertEqual(Array(launch.arguments.prefix(3)), ["devicectl", "list", "devices"])+ XCTAssertEqual(launch.timeout, 20)+ let file = launch.arguments.last ?? ""+ XCTAssertFalse(FileManager.default.fileExists(atPath: file), "the temporary file is removed")+ }++ func testAListingThatFailsOrTimesOutGivesNoDevices() {+ fake.answer = { _ in ProcessResult(status: 1) }+ XCTAssertEqual(DeviceTools.devices(runner: fake), [])+ fake.answer = { _ in ProcessResult(status: 15, timedOut: true) }+ XCTAssertEqual(DeviceTools.devices(timeout: 1, runner: fake), [])+ fake.answer = { _ in .failedToStart("no xcrun") }+ XCTAssertEqual(DeviceTools.devices(runner: fake), [])+ }++ func testCertificateTeamsReadTheKeychainAndPipeTheCertificateToOpenssl() {+ fake.answer = { launch in+ switch (launch.executable as NSString).lastPathComponent {+ case "security" where launch.arguments.first == "find-identity":+ return ProcessResult(out: " 1) AAAA \"Apple Development: Jo Doe (ABCDE12345)\"\n 2) BBBB \"Developer ID Application: X (ZZZZZZZZZZ)\"\n")+ case "security": return ProcessResult(out: "PEM")+ case "openssl": return ProcessResult(out: "subject=UID=x, OU=ABCDE12345, CN=Apple Development")+ default: return ProcessResult(status: 1)+ }+ }+ XCTAssertEqual(DeviceTools.certificateTeams(runner: fake), [SigningTeam(id: "ABCDE12345", identity: "Apple Development: Jo Doe (ABCDE12345)")])+ let openssl = fake.launches.first { $0.executable.hasSuffix("openssl") }+ XCTAssertEqual(openssl?.input, "PEM", "the certificate goes in on standard input")+ }++ func testTeamsMergeTheKeychainAndXcodeAndTolerateBothMissing() {+ fake.answer = { _ in ProcessResult(status: 1) }+ XCTAssertEqual(DeviceTools.teams(runner: fake), [])+ XCTAssertEqual(DeviceTools.xcodeTeams(runner: fake), [])+ }++ func testAppSignatureReadsTheProfileThroughSecurity() throws {+ let app = NSTemporaryDirectory() + "sig-\(UUID().uuidString).app"+ try FileManager.default.createDirectory(atPath: app, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(atPath: app) }+ let profile = app + "/" + AppSignature.profileName+ FileManager.default.createFile(atPath: profile, contents: Data("cms".utf8))+ let date = Date(timeIntervalSince1970: 1_900_000_000)+ let plist = try PropertyListSerialization.data(fromPropertyList: ["ExpirationDate": date], format: .xml, options: 0)+ fake.answer = { _ in ProcessResult(out: String(decoding: plist, as: UTF8.self)) }+ XCTAssertEqual(AppSignature.expiration(ofApp: app, runner: fake), date)+ XCTAssertEqual(fake.commands, ["security cms -D -i \(profile)"])+ fake.answer = { _ in ProcessResult(status: 1) }+ XCTAssertNil(AppSignature.expiration(ofApp: app, runner: fake))+ }++ // MARK: DeviceControl++ func testDeviceControlGivesDevicectlItsDeadlineAndThenOneOnTheProcess() {+ fake.answer = { _ in ProcessResult(out: "listed") }+ let control = DeviceControl.xcrun("/fake/xcrun", queryTimeout: 10, copyTimeout: 180, runner: fake)+ let r = control.run(["list", "apps"])+ XCTAssertTrue(r.ok)+ XCTAssertEqual(r.output, "listed")+ XCTAssertEqual(fake.launches[0].arguments, ["devicectl", "--timeout", "10", "list", "apps"])+ XCTAssertEqual(fake.launches[0].timeout, 12, "two seconds behind devicectl's own")+ XCTAssertTrue(fake.launches[0].mergesErrors)+ _ = control.run(["device", "copy", "to", "x"])+ XCTAssertEqual(fake.launches[1].arguments.prefix(3), ["devicectl", "--timeout", "180"])+ XCTAssertEqual(fake.launches[1].timeout, 182)+ }++ func testDeviceControlSaysTimedOutWhenTheProcessWasEnded() {+ fake.answer = { _ in ProcessResult(status: 15, out: "partial", timedOut: true) }+ let r = DeviceControl.xcrun("/fake/xcrun", runner: fake).run(["list"])+ XCTAssertFalse(r.ok)+ XCTAssertEqual(r.output, DeviceControl.timedOut)+ }++ func testDeviceControlReportsAFailureAndAToolThatDoesNotStart() {+ fake.answer = { _ in ProcessResult(status: 1, out: "ERROR: locked") }+ var r = DeviceControl.xcrun("/fake/xcrun", runner: fake).run(["list"])+ XCTAssertEqual(r.ok, false)+ XCTAssertEqual(r.output, "ERROR: locked")+ fake.answer = { _ in .failedToStart("no such file") }+ r = DeviceControl.xcrun("/fake/xcrun", runner: fake).run(["list"])+ XCTAssertEqual(r.ok, false)+ XCTAssertEqual(r.output, "no such file")+ }++ func testTheRealRunnerEndsADevicectlThatHangs() {+ // A stand-in xcrun that ignores its arguments and never returns: the process deadline ends it.+ let script = NSTemporaryDirectory() + "hang-\(UUID().uuidString).sh"+ FileManager.default.createFile(atPath: script, contents: Data("#!/bin/sh\nexec sleep 30\n".utf8), attributes: [.posixPermissions: 0o755])+ defer { try? FileManager.default.removeItem(atPath: script) }+ let start = Date()+ let r = DeviceControl.xcrun(script, queryTimeout: 0.2).run(["list"])+ XCTAssertEqual(r.output, DeviceControl.timedOut)+ XCTAssertLessThan(Date().timeIntervalSince(start), 15)+ }+}diff --git a/frontend/Tests/NXCoreTests/FakeProcessRunner.swift b/frontend/Tests/NXCoreTests/FakeProcessRunner.swiftindex 19977ac8..d6750c91 100644--- a/frontend/Tests/NXCoreTests/FakeProcessRunner.swift+++ b/frontend/Tests/NXCoreTests/FakeProcessRunner.swift@@ -10,6 +10,8 @@ final class FakeProcessRunner: ProcessRunner, @unchecked Sendable {/// What `stream` prints, and whether it exits 0.var lines: [String] = []var streamOK = true+ /// The exit status of `streamLines`. nil: it fails to start.+ var lineStatus: Int32? = 0/// What `start` reports: the output chunks, then the exit status. nil: it fails to start.var startOutput: [String]? = []var startStatus: Int32 = 0@@ -28,6 +30,14 @@ final class FakeProcessRunner: ProcessRunner, @unchecked Sendable {return streamOK}+ func streamLines(_ launch: ProcessLaunch, started: @escaping (RunningProcess) -> Void, line: @escaping (String) -> Void) -> ProcessResult {+ record(launch)+ guard let status = lineStatus else { return .failedToStart("could not start") }+ started(FakeRunningProcess())+ lines.forEach(line)+ return ProcessResult(status: status)+ }+func start(_ launch: ProcessLaunch, onOutput: @escaping (Data) -> Void, onExit: @escaping (Int32) -> Void) throws -> RunningProcess {record(launch)guard let output = startOutput else { throw CocoaError(.fileNoSuchFile) }diff --git a/frontend/Tests/NXCoreTests/ProcessRunnerTests.swift b/frontend/Tests/NXCoreTests/ProcessRunnerTests.swiftindex cbcef38e..44e0ae59 100644--- a/frontend/Tests/NXCoreTests/ProcessRunnerTests.swift+++ b/frontend/Tests/NXCoreTests/ProcessRunnerTests.swift@@ -108,6 +108,65 @@ final class ProcessRunnerTests: XCTestCase {XCTAssertFalse(alive, "an ended process is no longer tracked")}+ // MARK: Timeout, input and whole lines++ func testCaptureEndsARunThatOutlastsItsTimeout() {+ let start = Date()+ let r = real.capture(ProcessLaunch(executable: "/bin/sleep", arguments: ["30"], timeout: 0.3))+ XCTAssertTrue(r.started)+ XCTAssertTrue(r.timedOut)+ XCTAssertFalse(r.ok)+ XCTAssertLessThan(Date().timeIntervalSince(start), 10)+ }++ func testCaptureWithATimeoutLeavesAFastRunAlone() {+ let r = real.capture(ProcessLaunch(executable: "/bin/echo", arguments: ["quick"], timeout: 30))+ XCTAssertTrue(r.ok)+ XCTAssertFalse(r.timedOut)+ XCTAssertEqual(r.out, "quick\n")+ }++ func testCaptureWritesTheInputToStandardInputAndClosesIt() {+ let r = real.capture(ProcessLaunch(executable: "/bin/cat", input: "from the test\nsecond"))+ XCTAssertTrue(r.ok)+ XCTAssertEqual(r.out, "from the test\nsecond")+ }++ func testStreamLinesAssemblesWholeLinesAcrossChunksAndKeepsEmptyOnes() {+ let lines = Collected()+ var started = 0+ let r = real.streamLines(ProcessLaunch(["/bin/sh", "-c", "printf 'a'; sleep 0.2; printf 'b\\n\\nc\\n'; echo err >&2; printf 'tail'"]),+ started: { _ in started += 1 }) { lines.add($0) }+ XCTAssertTrue(r.started)+ XCTAssertEqual(r.status, 0)+ XCTAssertEqual(started, 1)+ XCTAssertEqual(lines.values.filter { $0 != "err" }, ["ab", "", "c", "tail"], "stderr is merged in, so 'err' may sit anywhere")+ XCTAssertTrue(lines.values.contains("err"))+ }++ func testStreamLinesGivesTheExitStatusAndReportsAToolThatDoesNotStart() {+ XCTAssertEqual(real.streamLines(ProcessLaunch(["/bin/sh", "-c", "exit 7"]), started: { _ in }, line: { _ in }).status, 7)+ var started = false+ let r = real.streamLines(ProcessLaunch(["/nonexistent/tool"]), started: { _ in started = true }, line: { _ in })+ XCTAssertFalse(r.started)+ XCTAssertFalse(r.out.isEmpty)+ XCTAssertFalse(started)+ }++ func testStreamLinesInAGroupIsTrackedWhileItRunsAndLetGoAfter() throws {+ guard FileManager.default.isExecutableFile(atPath: "/usr/bin/python3") else { throw XCTSkip("System Python is required") }+ var alive = false+ let r = real.streamLines(ProcessLaunch(["/bin/sh", "-c", "sleep 0.3"], groupPython: "/usr/bin/python3"),+ started: { p in+ var tries = 0+ while getpgid(p.processIdentifier) != p.processIdentifier && tries < 100 { usleep(20_000); tries += 1 }+ alive = ProcessGroups.buildProcessesAlive+ }, line: { _ in })+ XCTAssertEqual(r.status, 0)+ XCTAssertTrue(alive, "the group is tracked while the tool runs")+ XCTAssertFalse(ProcessGroups.buildProcessesAlive)+ }+// MARK: The helpers over a fakefunc testRunQuietAsksForOneMergedRunWithTheGivenEnvironment() {diff --git a/frontend/Tests/NXModelTests/DeviceStoreTests.swift b/frontend/Tests/NXModelTests/DeviceStoreTests.swiftnew file mode 100644index 00000000..a78b564c--- /dev/null+++ b/frontend/Tests/NXModelTests/DeviceStoreTests.swift@@ -0,0 +1,196 @@+import XCTest+@testable import NXModel+@testable import NXCore++/// `DeviceStore` without SwiftUI: the listings are closures that answer from the test and the defaults are a suite of their own.+/// Nothing reaches devicectl or the keychain of this Mac. The copy question is answered from the test the way the card does it.+@MainActor final class DeviceStoreTests: XCTestCase {+ private var suite: String!+ private var defaults: UserDefaults!+ private let runner = FakeProcessRunner()+ private let phone = AppleDevice(id: "UDID-1", name: "Jo's iPhone", model: "iPhone 17", os: "27.0", reachable: true, transport: "wired")+ private let laptopTeam = SigningTeam(id: "ABCDE12345", identity: "Apple Development: Jo Doe (ABCDE12345)")+ private let freeTeam = SigningTeam(id: "FGHIJ67890", identity: "", name: "Jo Doe", personal: true)++ override func setUpWithError() throws {+ suite = "nxmodel-device-tests-" + UUID().uuidString+ defaults = UserDefaults(suiteName: suite)+ }++ override func tearDownWithError() throws {+ defaults.removePersistentDomain(forName: suite)+ }++ private func makeStore(devices: [AppleDevice]? = nil, teams: [SigningTeam]? = nil, xcrun: String = "/fake/xcrun") -> DeviceStore {+ let devices = devices ?? [phone], teams = teams ?? [laptopTeam, freeTeam]+ return DeviceStore(runner: runner, xcrun: xcrun, defaults: defaults, listDevices: { _ in devices }, readTeams: { teams })+ }++ private func plan() -> ShellCopyPlan {+ ShellCopyPlan(files: 2, bytes: 15_000_000_000, connection: .network, deviceName: "Jo's iPhone", sizeText: "15.0 GB in 2 files.", connectionText: "Wi-Fi")+ }++ // MARK: Devices and teams++ func testItStartsUnchecked() {+ let store = makeStore()+ XCTAssertEqual(store.devices, [])+ XCTAssertEqual(store.teams, [])+ XCTAssertFalse(store.checked)+ XCTAssertEqual(store.installDevice, "")+ XCTAssertEqual(store.signingTeam, "")+ XCTAssertNil(store.shellCopy)+ XCTAssertFalse(store.shellWaiting)+ }++ func testRefreshReadsDevicesAndTeamsAndMarksTheListingChecked() async {+ let store = makeStore()+ await store.refresh().value+ XCTAssertEqual(store.devices, [phone])+ XCTAssertEqual(store.teams, [laptopTeam, freeTeam])+ XCTAssertTrue(store.checked)+ }++ func testRefreshGivesTheListingTheXcrunItWasCreatedWith() async {+ final class Seen: @unchecked Sendable { var xcrun = "" }+ let seen = Seen()+ let store = DeviceStore(runner: runner, xcrun: "/stand/in/xcrun", defaults: defaults,+ listDevices: { seen.xcrun = $0; return [] }, readTeams: { [] })+ XCTAssertEqual(store.xcrun, "/stand/in/xcrun")+ await store.refresh().value+ XCTAssertEqual(seen.xcrun, "/stand/in/xcrun")+ }++ func testARefreshKeepsTheChosenTeamWhenTheMacStillKnowsIt() async {+ let store = makeStore()+ store.signingTeam = freeTeam.id+ await store.refresh().value+ XCTAssertEqual(store.signingTeam, freeTeam.id)+ }++ func testARefreshReplacesATeamTheMacNoLongerKnowsWithTheFirstOne() async {+ let store = makeStore()+ store.signingTeam = "GONE000000"+ await store.refresh().value+ XCTAssertEqual(store.signingTeam, laptopTeam.id)+ let none = makeStore(teams: [])+ none.signingTeam = freeTeam.id+ await none.refresh().value+ XCTAssertEqual(none.signingTeam, "", "no team at all clears it")+ }++ func testTheChosenDeviceAndTeamAreSavedAndComeBack() {+ let store = makeStore()+ store.installDevice = "UDID-1"+ store.signingTeam = "ABCDE12345"+ XCTAssertEqual(defaults.string(forKey: DeviceStore.deviceKey), "UDID-1")+ XCTAssertEqual(defaults.string(forKey: DeviceStore.teamKey), "ABCDE12345")+ let again = makeStore()+ XCTAssertEqual(again.installDevice, "UDID-1")+ XCTAssertEqual(again.signingTeam, "ABCDE12345")+ }++ func testADeviceNameFallsBackToIPhoneForOneThatIsNotListed() async {+ let store = makeStore()+ XCTAssertEqual(store.deviceName("UDID-1"), "iPhone")+ await store.refresh().value+ XCTAssertEqual(store.deviceName("UDID-1"), "Jo's iPhone")+ XCTAssertEqual(store.deviceName("other"), "iPhone")+ }++ func testTheTeamsReaderCanBeChangedForALaterRead() {+ let store = makeStore()+ store.readTeams = { [] }+ XCTAssertEqual(store.readTeams(), [])+ }++ func testTheDefaultListingsGoThroughTheRunner() async {+ let store = DeviceStore(runner: runner, xcrun: "/fake/xcrun", defaults: defaults)+ runner.answer = { _ in ProcessResult(status: 1) }+ await store.refresh().value+ XCTAssertTrue(store.checked)+ XCTAssertEqual(store.devices, [])+ XCTAssertTrue(runner.commands.contains { $0.hasPrefix("xcrun devicectl list devices") }, "devicectl was asked through the runner: \(runner.commands)")+ }++ // MARK: The copy flow++ /// Asks the question the way the install does: from a background queue, which waits for the answer.+ private func ask(_ store: DeviceStore, _ plan: ShellCopyPlan) -> (result: () -> ShellCopyDecision?, done: XCTestExpectation) {+ final class Box: @unchecked Sendable { var value: ShellCopyDecision? }+ let box = Box(), done = expectation(description: "answered")+ DispatchQueue.global().async { box.value = store.askCopy(plan); done.fulfill() }+ return ({ box.value }, done)+ }++ private func waitForQuestion(_ store: DeviceStore) {+ let deadline = Date().addingTimeInterval(5)+ while store.shellCopy == nil && Date() < deadline { RunLoop.main.run(until: Date().addingTimeInterval(0.01)) }+ }++ func testTheCopyQuestionShowsThePlanAndBlocksUntilItIsAnswered() {+ let store = makeStore()+ let asked = ask(store, plan())+ waitForQuestion(store)+ XCTAssertEqual(store.shellCopy, plan())+ XCTAssertNil(asked.result(), "the install waits")+ store.answerCopy(.waitForCable)+ XCTAssertNil(store.shellCopy, "the card is gone")+ wait(for: [asked.done], timeout: 5)+ XCTAssertEqual(asked.result(), .waitForCable)+ }++ func testEachAnswerReachesTheInstall() {+ for decision in [ShellCopyDecision.copy, .skip, .waitForCable] {+ let store = makeStore()+ let asked = ask(store, plan())+ waitForQuestion(store)+ store.answerCopy(decision)+ wait(for: [asked.done], timeout: 5)+ XCTAssertEqual(asked.result(), decision)+ }+ }++ func testAnAnswerWithNoQuestionDoesNothing() {+ let store = makeStore()+ store.answerCopy(.copy)+ XCTAssertNil(store.shellCopy)+ }++ func testAskingAgainClearsAnEarlierCancelOfTheWait() {+ let store = makeStore()+ store.cancelWait()+ XCTAssertTrue(store.waitCancelled)+ let asked = ask(store, plan())+ waitForQuestion(store)+ XCTAssertFalse(store.waitCancelled, "the next wait starts fresh")+ store.answerCopy(.copy)+ wait(for: [asked.done], timeout: 5)+ }++ func testTheCableWaitIsToldFromABackgroundQueueAndCanBeCancelled() {+ let store = makeStore()+ let told = expectation(description: "told")+ DispatchQueue.global().async { store.setWaiting(true); told.fulfill() }+ wait(for: [told], timeout: 5)+ let deadline = Date().addingTimeInterval(5)+ while !store.shellWaiting && Date() < deadline { RunLoop.main.run(until: Date().addingTimeInterval(0.01)) }+ XCTAssertTrue(store.shellWaiting)+ XCTAssertFalse(store.waitCancelled)+ store.cancelWait()+ XCTAssertTrue(store.waitCancelled, "the poll reads it between two looks")+ }++ func testWhenTheInstallEndsNoQuestionAndNoWaitStay() {+ let store = makeStore()+ let asked = ask(store, plan())+ waitForQuestion(store)+ store.setWaiting(true)+ RunLoop.main.run(until: Date().addingTimeInterval(0.1))+ store.copyEnded()+ XCTAssertNil(store.shellCopy)+ XCTAssertFalse(store.shellWaiting)+ store.answerCopy(.skip) // let the blocked queue go (copyEnded does not answer it: the install has ended by then)+ wait(for: [asked.done], timeout: 5)+ }+}diff --git a/frontend/Tests/NXModelTests/Fakes.swift b/frontend/Tests/NXModelTests/Fakes.swiftindex 15205ccc..88897c41 100644--- a/frontend/Tests/NXModelTests/Fakes.swift+++ b/frontend/Tests/NXModelTests/Fakes.swift@@ -26,6 +26,14 @@ final class FakeProcessRunner: ProcessRunner, @unchecked Sendable {return result.ok}+ func streamLines(_ launch: ProcessLaunch, started: @escaping (RunningProcess) -> Void, line: @escaping (String) -> Void) -> ProcessResult {+ lock.lock(); recorded.append(launch); lock.unlock()+ let result = streamAnswer(launch)+ started(FakeRunningProcess())+ result.lines.forEach(line)+ return ProcessResult(status: result.ok ? 0 : 1)+ }+func start(_ launch: ProcessLaunch, onOutput: @escaping (Data) -> Void, onExit: @escaping (Int32) -> Void) throws -> RunningProcess {throw CocoaError(.fileNoSuchFile)}@@ -62,3 +70,8 @@ final class FakeReleaseSource: ReleaseSource, @unchecked Sendable {return try! JSONSerialization.data(withJSONObject: ["tag_name": tag, "body": notes, "assets": [a]])}}++final class FakeRunningProcess: RunningProcess {+ var processIdentifier: Int32 { 0 }+ var isRunning: Bool { false }+}