Skip to content

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

Move the app self-update into an AppUpdateStore, the reference store (#387)

v0lumehia96d6b35346e
diff --git a/.github/workflows/build-mac-app.yml b/.github/workflows/build-mac-app.yml
index 5543f7f0..c1b17e47 100644
--- a/.github/workflows/build-mac-app.yml
+++ b/.github/workflows/build-mac-app.yml
@@ -4,7 +4,7 @@
# the bundle, plutil the version, codesign, ditto) and uploaded by hand — and one release went
# out without it. The native app is the one macOS users actually run, so "the release has no
# nxnative-macOS-arm64.zip" is not a cosmetic gap: the app's own updater looks for exactly that
-# asset name (ContentView.checkAppUpdate), finds a newer tag with no such asset, and reports
+# asset name (AppUpdateStore.checkForUpdate), finds a newer tag with no such asset, and reports
# "up to date" — a silent failure of the update path for every existing install. Copies from before
# the app was renamed (NS Port Builder) look for NS-Port-Builder-macOS-arm64.zip, so that one goes up too.
#
@@ -199,11 +199,11 @@ jobs:
TAG: ${{ github.ref_name }}
run: |
set -euo pipefail
- # The app reads its version from ContentView.appVersion, and the bundle plist must agree or the updater compares the wrong number.
+ # The app reads its version from AppUpdateStore.appVersion, and the bundle plist must agree or the updater compares the wrong number.
# Take the tag, and fail loudly on a mismatch rather than shipping a bundle that calls itself something else.
# A release candidate vX.Y.Z-rcN is the build of the release X.Y.Z: its bundle says X.Y.Z, because the final tag ships these
# exact files and the updater (AppUpdate.bundleProblem) accepts only a bundle whose version is the release's.
- src=$(sed -n 's/.*static let appVersion = "\(.*\)".*/\1/p' frontend/Sources/NX2Apple/ContentView.swift)
+ src=$(sed -n 's/.*static let appVersion = "\(.*\)".*/\1/p' frontend/Sources/NXModel/AppUpdateStore.swift)
kind=build rc=""
if [ "$REF_TYPE" != "tag" ]; then
v="$src"
@@ -220,7 +220,7 @@ jobs:
fi
fi
if [ "$v" != "$src" ]; then
- echo "::error::tag says $v but ContentView.appVersion says $src: bump the source first"
+ echo "::error::tag says $v but AppUpdateStore.appVersion says $src: bump the source first"
exit 1
fi
echo "$kind: version $v${rc:+, release candidate $rc}"
diff --git a/.github/workflows/sync-upstream.yml b/.github/workflows/sync-upstream.yml
index 23500893..b47ea89c 100644
--- a/.github/workflows/sync-upstream.yml
+++ b/.github/workflows/sync-upstream.yml
@@ -188,7 +188,7 @@ jobs:
- name: Publish to the engine-experimental pre-release
if: steps.published.outputs.same != 'yes'
run: |
- APPV=$(sed -n 's/.*static let appVersion = "\(.*\)".*/\1/p' frontend/Sources/NX2Apple/ContentView.swift)
+ APPV=$(sed -n 's/.*static let appVersion = "\(.*\)".*/\1/p' frontend/Sources/NXModel/AppUpdateStore.swift)
python tools/release_manifest.py publish \
--engine-zip "$RUNNER_TEMP/engine-out/NX2Apple-engine.zip" \
--version "$APPV-experimental" --channel experimental --tag engine-experimental \
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index e62da50d..7dcd78ed 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -176,7 +176,7 @@ jobs:
- name: Install the signing tool's package (tools/release_manifest.py)
run: python -m pip install -r tools/requirements-release.txt
- name: Patch, engine and release tool tests
- run: python -m unittest -v tools/tests/test_patches.py tools/tests/test_engine.py tools/tests/test_release_manifest.py tools/tests/test_release_notes.py
+ run: python -m unittest -v tools/tests/test_patches.py tools/tests/test_engine.py tools/tests/test_release_manifest.py tools/tests/test_release_notes.py tools/tests/test_app_version.py
- name: Dry bump to seedds main (report only)
run: python tools/engine.py bump --dry --to main || true
diff --git a/RELEASING.md b/RELEASING.md
index 3ede48fc..2b5c48e6 100644
--- a/RELEASING.md
+++ b/RELEASING.md
@@ -7,7 +7,7 @@ A release starts as a release candidate. Players get the exact files of the cand
### Cutting a candidate
1. Before `-rc1`, bump the engine pin, so the candidate carries the current engine. The nightly sync job opens the pull request `sync/upstream-<sha>` when seedds/nxnative has news. If it has not, `python3 tools/engine.py bump --dry --to main` shows which patches would conflict, and `python3 tools/engine.py bump --to <sha>` moves the pin. Merge that pull request before the version bump.
-2. The version bump goes to `main` next: `static let appVersion` in `frontend/Sources/NX2Apple/ContentView.swift`, and the changelog.
+2. The version bump goes to `main` next: `static let appVersion` in `frontend/Sources/NXModel/AppUpdateStore.swift`, and the changelog.
3. Tag a commit on `main` as `vX.Y.Z-rcN`, with N from 1: `git tag v0.7.6-rc1 <commit> && git push origin v0.7.6-rc1`.
`build-mac-app.yml` checks that the tag without `-rcN` is `appVersion`. The app inside says `0.7.6`, not `0.7.6-rc1`. The final release ships this bundle, and the app's own update installs only a bundle whose version is the release's.
diff --git a/frontend/ARCHITECTURE.md b/frontend/ARCHITECTURE.md
index 244995ab..1c7be831 100644
--- a/frontend/ARCHITECTURE.md
+++ b/frontend/ARCHITECTURE.md
@@ -13,12 +13,14 @@ 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`. 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. 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: `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) and `AppUpdate` (ditto, xattr) with the `AppUpdateStore`, `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, `EngineUpdater` (ditto) with the engine store, 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: `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, `EngineUpdater` (ditto) with the engine store, 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.
+- Step 6 moved the self-update out of `BuildModel`. `AppUpdate` (`NXCore`) now also holds the release parsing (`release(fromJSON:)`, `check(latest:current:)`), the version compare (`isNewer`), the asset names, the staging of a download (`stage`, `StageFailure`) and the install, which clears the quarantine flag through a `ProcessRunner`. `ReleaseSource` is the second service (a protocol, with `GitHubReleases` as the real one): the latest release and the download. `Uninstall` moved to `NXCore` too, because the store holds its plan. `AppUpdate.relaunch` still starts its detached shell itself, and the store gets it as a closure.
- `NXCoreTests` tests `NXCore` alone. It links no other target, so these tests run without SwiftUI. New tests of pure logic go there.
- `NXModel` holds `Localizer`: `lang` and `t()`. The app creates one with each `BuildModel`, and `ContentView` hands it to every view as an environment object. A view that shows text declares `@EnvironmentObject var loc: Localizer` and calls `loc.t(...)`. A language change redraws these views and nothing else.
+- `NXModel` holds `AppUpdateStore`: the release check, the staged update, the update sheet, the uninstall plan and `appVersion`. `BuildModel` creates it with its localizer, runner and release source, and the views that show the update (the launcher's top bar and activity line, the Settings section, the update sheet) observe it and not `BuildModel`. `NXModelTests` tests it with a fake runner and a fake release source, without SwiftUI.
- `NXModel` also holds `BuildLog`: the log text, its tail trimming and the line buffer. `BuildModel` holds it in a `let` and does not publish it, and only `BuildLogView` (in `NXLauncher`) observes it. A log line redraws the log and no game card. `LauncherPerformanceTests` writes 1000 lines during a build and allows 0 cards. `BuildModel` is not `@MainActor` yet, so it reaches the log through `BuildLog.onMain`.
- `NXLauncher` holds the views and styles that do not need `BuildModel`: `LauncherPalette`, `Typography`, `LauncherStyles`, `LauncherDropdown`, `PadFocus` and `EmbeddedFonts`.
- `NX2Apple` holds everything else, including `BuildModel`.
@@ -43,6 +45,24 @@ Things a store needs from AppKit, such as file pickers and opening Finder, reach
A view observes only the stores it shows. A change in one store invalidates only the views that observe it.
+### The pattern: `AppUpdateStore`
+
+`Sources/NXModel/AppUpdateStore.swift` is the reference. A new store follows it:
+
+- **Declaration.** `@MainActor package final class XStore: ObservableObject`. It imports `Foundation`, `Combine` and `NXCore`, never SwiftUI or AppKit.
+- **State.** Everything a view shows is `@Published`. `package private(set)` when only the store changes it. `package var` when a view binds it (`showUpdateSheet`, `uninstallPlan`) or a test sets it up.
+- **`init` takes what the store works with.** The services as protocols (`ProcessRunner`, `ReleaseSource`), the `Localizer` for its text, and the facts of its environment with the real ones as defaults (`bundle`, `version`, `defaults`, `runningOS`). A test passes in fakes and temporary folders. Another store or the model's flags come as a narrow closure (`buildRunning`), never as the whole object.
+- **AppKit as closures.** Quitting and relaunching reach the store as `terminate` and `relaunch`. A system notification is forwarded by the app, which calls a method of the store (`appWillTerminate()`).
+- **Logic stays out.** What needs no state (parsing, comparing, deciding what may be installed) is a static function in `NXCore` (`AppUpdate`) with its own tests. The store only calls it and keeps the result.
+- **Actions check their own conditions.** `install` refuses while a build runs and for a copy that is not a released one. The view does not decide that.
+- **Async work.** The method that starts it sets its state synchronously (`busy = true`), runs a `Task` on the main actor, hops off it for blocking work (`Task.detached`) and returns the `Task`, so a test awaits `store.checkForUpdate().value`.
+- **Tests.** `NXModelTests`, a `@MainActor` test class, no SwiftUI. Fakes for the services, a `UserDefaults` suite of its own, files in a temporary folder.
+- **Wiring.** Until `BuildModel` is gone, it creates the store. The store is not published through the model: views take it as an `@ObservedObject` parameter (or as an environment object, as `Localizer`), so a change redraws the views that show it and nothing else.
+
+### `appVersion`
+
+`AppUpdateStore.appVersion` is the one line that says which release the launcher is: `nonisolated package static let appVersion = "x.y.z"`. `build-mac-app.yml` checks the tag against it, `sync-upstream.yml` names the experimental engine after it, `tools/try-local` builds `<appVersion>-local`, and `RELEASING.md` says where to bump it. They read the line with `sed`, so keep it in that form and in that file. `tools/tests/test_app_version.py` fails when a reader names a file without the line, or a new reader is not in its list. When the line moves again, move every reader with it.
+
## Where a new feature goes
- Parsing, formatting, classification, anything that is a function of its input: `NXCore`, as a value type or a static function, with a test.
diff --git a/frontend/Package.swift b/frontend/Package.swift
index db1e9f36..c8738177 100644
--- a/frontend/Package.swift
+++ b/frontend/Package.swift
@@ -14,6 +14,8 @@ let package = Package(
.executableTarget(name: "NX2Apple", dependencies: ["NXLauncher", "NXModel", "NXCore"], path: "Sources/NX2Apple"),
// Tests of the pure logic: they link NXCore only, so they run without SwiftUI.
.testTarget(name: "NXCoreTests", dependencies: ["NXCore"]),
+ // Tests of the stores: they link NXModel and NXCore, never SwiftUI.
+ .testTarget(name: "NXModelTests", dependencies: ["NXModel", "NXCore"]),
.testTarget(name: "NX2AppleTests", dependencies: ["NX2Apple", "NXLauncher", "NXModel", "NXCore"])
],
swiftLanguageModes: [.v5]
diff --git a/frontend/Sources/NX2Apple/ContentView.swift b/frontend/Sources/NX2Apple/ContentView.swift
index 35f2803a..fbad38b4 100644
--- a/frontend/Sources/NX2Apple/ContentView.swift
+++ b/frontend/Sources/NX2Apple/ContentView.swift
@@ -177,9 +177,13 @@ final class BuildModel: ObservableObject {
/// The services: the only places that start a process (`ProcessRunner`) and that run git (`GitCheckout`). Tests pass in fakes.
let runner: ProcessRunner
let gitCheckout: GitCheckout
- init(localizer: Localizer = Localizer(), runner: ProcessRunner = SystemProcessRunner(), gitCheckout: GitCheckout? = nil) {
+ /// Where the self-update looks for releases (the real one is GitHub's).
+ let releases: ReleaseSource
+ init(localizer: Localizer = Localizer(), runner: ProcessRunner = SystemProcessRunner(), gitCheckout: GitCheckout? = nil,
+ releases: ReleaseSource = GitHubReleases()) {
self.localizer = localizer
self.runner = runner
+ self.releases = releases
self.gitCheckout = gitCheckout ?? SystemGitCheckout(runner: runner)
_ = Self.endGroupsWhenQuitting
}
@@ -510,299 +514,25 @@ final class BuildModel: ObservableObject {
}
// ---- App self-update (GitHub Releases) ----
- // The rules (what is verified, which copies replace themselves, never during a build) are in AppUpdate.swift.
-
- /// Bump together with each release tag; the update check compares it with the latest release.
- static let appVersion = "1.0.1"
- /// The update checkAppUpdate found: the tag, the asset to download, its digest, and the release
- /// notes the sheet shows. The notes are why the sheet exists — "update available" alone told a
- /// user nothing about what they would get.
- @Published var appUpdate: AppUpdate.Release?
- @Published var appBusy = false
- /// Whether the "a new version is out" sheet is up: opened by the launch check and by Check for
- /// updates, so a user learns what changed before deciding, not after downloading.
- @Published var showUpdateSheet = false
- /// The uninstall row's dialog: computed when the row is pressed, run when the player confirms.
- @Published var uninstallPlan: Uninstall.Plan?
- @Published var appStatus = ""
- /// Set when the last update attempt was refused (a release this macOS cannot open, a bad download); the update sheet shows it.
- @Published var appUpdateBlocked: String?
- /// Download a new release by itself and install it when the app quits (Settings; on by default). Off, the
- /// Update button in Settings works as before: download, swap in, relaunch.
- @Published var autoUpdateApp = UserDefaults.standard.object(forKey: "autoUpdateApp") as? Bool ?? true {
- didSet {
- UserDefaults.standard.set(autoUpdateApp, forKey: "autoUpdateApp")
- if autoUpdateApp, appStaged == nil, let u = appUpdate { stageAppUpdate(u, automatic: true) }
- }
- }
- /// The release that is downloaded, verified and unpacked: it goes in when the app quits, or with Restart now.
- @Published var appStaged: AppUpdate.Staged?
- /// Where a rename-era install put the new app (the old bundle name is gone): Settings shows it,
- /// because the Dock entry pointing at the old path is stale until the player re-pins it.
- static var noteRenamedInstall: String?
- /// Whether this copy may replace itself; a launcher built from the repository never does (tests set it).
- var appInstallability = AppUpdate.installability(Bundle.main.bundleURL, appVersion: BuildModel.appVersion)
- private var quitObserver: NSObjectProtocol?
-
- /// The download names this build accepts, newest first. Every release must carry at least one of
- /// them or an install from that era cannot update itself: NX2Apple is current, nxnative is for
- /// installs from before the rename to NX2Apple, NS-Port-Builder for installs before that.
- nonisolated static let appAssetNames = ["NX2Apple-macOS-arm64.zip", "nxnative-macOS-arm64.zip",
- "NS-Port-Builder-macOS-arm64.zip"]
-
- nonisolated static func isNewer(_ tag: String, than current: String) -> Bool {
- func nums(_ s: String) -> [Int] { s.split(separator: ".").map { Int($0.filter { $0.isNumber }) ?? 0 } }
- let a = nums(tag), b = nums(current)
- for i in 0..<max(a.count, b.count) {
- let x = i < a.count ? a[i] : 0, y = i < b.count ? b[i] : 0
- if x != y { return x > y }
- }
- return false
- }
-
- /// The release's asset this app installs, with its digest: NX2Apple-macOS-arm64.zip, or the zip under an older
- /// name (releases from before each rename).
- nonisolated static func appRelease(fromJSON obj: [String: Any]) -> AppUpdate.Release? {
- let tag = obj["tag_name"] as? String ?? ""
- guard let assets = obj["assets"] as? [[String: Any]] else { return nil }
- for name in ["NX2Apple-macOS-arm64.zip", "nxnative-macOS-arm64.zip", "NS-Port-Builder-macOS-arm64.zip"] {
- for a in assets where (a["name"] as? String) == name {
- if let u = a["browser_download_url"] as? String { return AppUpdate.Release(tag: tag, url: u, digest: a["digest"] as? String) }
- }
- }
- return nil
- }
-
- /// Ask GitHub for the latest release. `silent` (the launch check) only surfaces a found update;
- /// "up to date" and network failures stay quiet. A slow or blocked network just times out.
- /// With automatic updates on, a found release is downloaded and staged in the background.
- func checkAppUpdate(silent: Bool = false) {
- guard !appBusy else { return }
- appBusy = true
- if !silent { appStatus = t("app.checking") }
- URLSession.shared.dataTask(with: URL(string: "https://api.github.com/repos/LNPANDY/NX2Apple/releases/latest")!) { data, _, _ in
- var found: AppUpdate.Release?
- // A newer release whose download this build cannot name is NOT "up to date". That
- // distinction is the difference between a user who updates and one who sits on 0.4.6
- // for ever: 0.4.6 and 0.4.7 look for exactly "NS-Port-Builder-macOS-arm64.zip", and if a
- // release ever ships without that name they report "已是最新" and stop.
- var newerTag: String?
- if let d = data, let obj = try? JSONSerialization.jsonObject(with: d) as? [String: Any] {
- let tag = obj["tag_name"] as? String ?? ""
- if Self.isNewer(tag, than: Self.appVersion) {
- newerTag = tag
- if var r = Self.appRelease(fromJSON: obj) {
- r.notes = (obj["body"] as? String) ?? ""
- found = r
- }
- }
- }
- DispatchQueue.main.async {
- self.appBusy = false
- if let f = found {
- self.appUpdate = f
- switch self.appInstallability {
- case .developer: self.appStatus = String(format: self.t("app.devBuild"), f.tag)
- case .readOnly: self.appStatus = String(format: self.t("app.readOnly"), f.tag)
- case .ok:
- if self.appStaged?.release == f { self.appStatus = String(format: self.t("app.ready"), f.tag) }
- else if self.autoUpdateApp { self.stageAppUpdate(f, automatic: true) }
- else { self.appStatus = String(format: self.t("app.found"), f.tag) }
- // The sheet opens either way: it is the only place the release notes appear,
- // and "a new version is out" without saying what changed is what made people
- // press Update blindly or not at all. In automatic mode it is also where
- // Restart now lives, and it says the download is already running.
- self.showUpdateSheet = true
- }
- } else if !silent {
- if data == nil {
- self.appStatus = self.t("app.netFail")
- } else if let tag = newerTag {
- // The release exists; this app just cannot find its own asset name in it.
- self.appStatus = String(format: self.t("app.noAsset"), tag)
- self.appUpdate = nil
- } else {
- self.appStatus = self.t("app.upToDate")
- }
- }
- }
- }.resume()
- }
-
- /// Download the release, check it against its digest, unpack it and check the app inside, all in the background;
- /// the result waits in appStaged. `automatic` (the switch) refuses a release whose digest GitHub did not give;
- /// the Update button accepts it, as before. `then` gets the staged copy (the button installs it at once).
- func stageAppUpdate(_ release: AppUpdate.Release, automatic: Bool, then: ((AppUpdate.Staged) -> Void)? = nil) {
- guard !appBusy, appInstallability == .ok, let url = URL(string: release.url) else { return }
- appBusy = true
- appUpdateBlocked = nil
- appStatus = String(format: t(automatic ? "app.staging" : "app.downloading"), release.tag)
- let expectedID = Bundle.main.bundleIdentifier ?? ""
- DispatchQueue.global().async {
- let result = Self.downloadAndStage(release, from: url, expectedID: expectedID, requireDigest: automatic)
- DispatchQueue.main.async {
- self.appBusy = false
- switch result {
- case .success(let staged):
- self.appStaged = staged
- self.appStatus = String(format: self.t("app.ready"), release.tag)
- self.installAtQuit()
- then?(staged)
- case .failure(let why):
- if case .needsNewerMacOS(let min) = why {
- // Nothing was installed: the running version stays, and says why
- let now = AppUpdate.describe(ProcessInfo.processInfo.operatingSystemVersion)
- self.appStatus = String(format: self.t(why.key), release.tag, min, now)
- } else {
- self.appStatus = String(format: self.t(why.key), release.tag)
- }
- self.appUpdateBlocked = self.appStatus
- }
- }
- }
- }
-
- /// Why staging stopped: each case is the localization key of its message (a format with the release's tag).
- enum StageFailure: Error, Equatable {
- case network, noDigest, mismatch, unpack, notOurApp
- /// The release's LSMinimumSystemVersion is above the running macOS (the string is that minimum).
- case needsNewerMacOS(String)
-
- var key: String {
- switch self {
- case .network: return "app.stageNetFail"
- case .noDigest: return "app.noDigest"
- case .mismatch: return "app.digestMismatch"
- case .unpack: return "app.unpackFail"
- case .notOurApp: return "app.notOurApp"
- case .needsNewerMacOS: return "app.needsNewerMacOS"
- }
- }
- }
-
- /// The background part of staging, in a folder of its own in the temporary directory (emptied first).
- nonisolated static func downloadAndStage(_ release: AppUpdate.Release, from url: URL, expectedID: String,
- requireDigest: Bool) -> Result<AppUpdate.Staged, StageFailure> {
- let fm = FileManager.default
- let root = fm.temporaryDirectory.appendingPathComponent("nspb-update", isDirectory: true)
- try? fm.removeItem(at: root)
- try? fm.createDirectory(at: root, withIntermediateDirectories: true)
- let zip = root.appendingPathComponent("update.zip")
- let sem = DispatchSemaphore(value: 0)
- URLSession.shared.downloadTask(with: url) { local, response, _ in
- if let local, (response as? HTTPURLResponse)?.statusCode ?? 200 == 200 { try? FileManager.default.moveItem(at: local, to: zip) }
- sem.signal()
- }.resume()
- sem.wait()
- guard fm.fileExists(atPath: zip.path) else { return .failure(.network) }
- return stage(zip: zip, release: release, in: root, expectedID: expectedID, requireDigest: requireDigest)
- }
-
- /// A downloaded zip to a staged app: its digest first, then unzip (ditto, as the release was packed), then the app inside.
- nonisolated static func stage(zip: URL, release: AppUpdate.Release, in root: URL, expectedID: String,
- requireDigest: Bool,
- runningOS: OperatingSystemVersion = ProcessInfo.processInfo.operatingSystemVersion,
- runner: ProcessRunner = SystemProcessRunner()) -> Result<AppUpdate.Staged, StageFailure> {
- let fm = FileManager.default
- switch AppUpdate.checkDigest(zip, expected: release.digest) {
- case .match: break
- case .mismatch: try? fm.removeItem(at: zip); return .failure(.mismatch)
- case .missing: if requireDigest { try? fm.removeItem(at: zip); return .failure(.noDigest) }
- }
- let dir = root.appendingPathComponent("app", isDirectory: true)
- try? fm.removeItem(at: dir)
- try? fm.createDirectory(at: dir, withIntermediateDirectories: true)
- let unzip = runner.capture(ProcessLaunch(executable: "/usr/bin/ditto", arguments: ["-x", "-k", zip.path, dir.path]))
- guard unzip.started else { return .failure(.unpack) }
- try? fm.removeItem(at: zip)
- // The archive holds one app: NX2Apple.app, or the bundle under an older name in a release from before a rename
- guard unzip.status == 0,
- let app = ((try? fm.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? []).first(where: { $0.pathExtension == "app" })
- else { return .failure(.unpack) }
- if AppUpdate.bundleProblem(app, expectedID: expectedID, tag: release.tag) != nil {
- try? fm.removeItem(at: dir)
- return .failure(.notOurApp)
- }
- // Not a release this Mac cannot open: it would replace a launcher that works with an app that will not start
- if let min = AppUpdate.minimumOSAbove(runningOS, app: app) {
- try? fm.removeItem(at: dir)
- return .failure(.needsNewerMacOS(min))
- }
- return .success(AppUpdate.Staged(release: release, app: app))
- }
-
- /// No build of this app is running: none in the model, and no process group of one still alive (a stopped
- /// build's tools can take a moment to go).
- var mayInstallAppUpdate: Bool { !running && !ProcessGroups.buildProcessesAlive }
-
- /// Swap the staged app in. `relaunch` (Restart now, the Update button) opens the new copy and exits; at quit
- /// the next launch is the new version. Refused while a build runs.
- @discardableResult
- func installStagedUpdate(relaunch: Bool, at current: URL = Bundle.main.bundleURL) -> Bool {
- guard let staged = appStaged, appInstallability == .ok else { return false }
- let placed: URL
- do {
- placed = try AppUpdate.install(staged.app, over: current, buildRunning: !mayInstallAppUpdate)
- } catch AppUpdate.InstallError.failed(let why) {
- appStatus = String(format: t("app.installFail"), why)
- return false
- } catch {
- appStatus = t("app.waitForBuild")
- return false
- }
- appStaged = nil
- // A rename era (nxnative → NS Port Builder → NX2Apple) installs under the release's own
- // bundle name; the Dock entry pointing at the old path goes stale once, so the log says
- // where the new copy landed instead of leaving the player to find it.
- if placed != current {
- fputs("launcher: the update was installed as \(placed.lastPathComponent) (the app was renamed); "
- + "the previous \(current.lastPathComponent) was removed — re-pin it in the Dock\n", stderr)
- Self.noteRenamedInstall = placed.path
- }
- if relaunch {
- appStatus = String(format: t("app.relaunching"), staged.release.tag)
- // The old instance is still running, so opening the same bundle now would only activate it:
- // a helper opens the new copy once this process has exited.
- if AppUpdate.relaunch(placed) {
+ // `AppUpdateStore` (NXModel) owns it: the check, the staged update, the update sheet, the uninstall plan and the version.
+ // The model creates it with its services and wires the two things that need AppKit, quitting and the quit notification.
+
+ /// Created on first use, on the main thread, because its closures reach back to this model (`running`).
+ private(set) lazy var appUpdates: AppUpdateStore = MainActor.assumeIsolated {
+ let store = AppUpdateStore(
+ localizer: localizer, runner: runner, releases: releases,
+ buildRunning: { [unowned self] in running || ProcessGroups.buildProcessesAlive },
+ terminate: {
NSApp.terminate(nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { exit(0) }
- } else {
- appStatus = String(format: t("app.relaunchFail"), staged.release.tag)
- }
- }
- return true
- }
-
- /// Restart now (Settings, the library's activity line): install and relaunch, never during a build.
- func restartToUpdate() {
- guard appStaged != nil else { return }
- guard mayInstallAppUpdate else { appStatus = t("app.waitForBuild"); return }
- installStagedUpdate(relaunch: true)
- }
-
- /// The staged update goes in as the app quits, so the next launch is the new version without interrupting
- /// anyone. A build running at that moment is being ended by the same quit (exitHandlers): the swap then waits
- /// for a later quit (the next launch stages the release again) rather than run while the build's tools are alive.
- private func installAtQuit() {
- guard quitObserver == nil else { return }
- quitObserver = NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: nil) { [weak self] _ in
- guard let self, self.autoUpdateApp, self.appStaged != nil, self.mayInstallAppUpdate else { return }
- self.installStagedUpdate(relaunch: false)
- }
- }
-
- /// The Update button (automatic updates off, or a release they would not take): download and verify, swap in,
- /// relaunch. A staged copy of the same release goes in as it is. Not during a build: the relaunch would end it.
- func performAppUpdate() {
- guard let upd = appUpdate, !appBusy, appInstallability == .ok else { return }
- guard mayInstallAppUpdate else { appStatus = t("app.waitForBuild"); return }
- if appStaged?.release == upd { installStagedUpdate(relaunch: true); return }
- stageAppUpdate(upd, automatic: false) { [weak self] _ in
- guard let self else { return }
- self.appStatus = self.t("app.installing")
- self.installStagedUpdate(relaunch: true)
+ })
+ // The staged update goes in as the app quits, so the next launch is the new version without interrupting anyone.
+ quitObserver = NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: nil) { [weak store] _ in
+ MainActor.assumeIsolated { store?.appWillTerminate() }
}
+ return store
}
+ private var quitObserver: NSObjectProtocol?
var basePath: String { slot("base").paths.first ?? "" }
var keysPath: String { slot("keys").paths.first ?? "" }
@@ -1978,7 +1708,7 @@ final class BuildModel: ObservableObject {
nonisolated static func writeDepsReport(_ deps: [Dep]) {
let dir = (Toolchain.venvDir as NSString).deletingLastPathComponent
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
- var out = "NX2Apple \(appVersion) dependency check\n"
+ var out = "NX2Apple \(AppUpdateStore.appVersion) dependency check\n"
out += "date: \(ISO8601DateFormatter().string(from: Date()))\n"
out += "HOME: \(NSHomeDirectory())\n"
out += "PATH: \(ProcessInfo.processInfo.environment["PATH"] ?? "(unset)")\n"
@@ -2073,6 +1803,7 @@ final class BuildModel: ObservableObject {
struct BuilderView: View {
@ObservedObject var m: BuildModel
+ @ObservedObject var updates: AppUpdateStore // the app's self-update (Settings, "NX2Apple" section)
@EnvironmentObject var loc: Localizer
@ObservedObject var library: GameLibrary
var settings = false
@@ -2507,7 +2238,7 @@ struct BuilderView: View {
}
}
tools
- group(loc.t("section.app"), footnote: m.appStatus) {
+ group(loc.t("section.app"), footnote: updates.status) {
// The interface language: the device default unless someone picks one here. Stored as
// "" (follow), "zh", "en", "sv", "de" or "fr" so a later system-language change still applies.
row(loc.t("settings.language"),
@@ -2542,37 +2273,37 @@ struct BuilderView: View {
.padTarget("set.returnAfterPlay", scope: "main") { returnAfterPlay.toggle() }
}
divider
- row("NX2Apple", detail: String(format: loc.t("app.version"), BuildModel.appVersion),
- dot: m.appStaged != nil ? LauncherPalette.ready : nil) {
- if m.appBusy { ProgressView().controlSize(.small) }
- if m.appStaged != nil {
+ row("NX2Apple", detail: String(format: loc.t("app.version"), updates.version),
+ dot: updates.staged != nil ? LauncherPalette.ready : nil) {
+ if updates.busy { ProgressView().controlSize(.small) }
+ if updates.staged != nil {
// Downloaded and verified: it goes in when the app quits; this restarts into it now (not during a build)
- Button(loc.t("app.restartNow")) { m.restartToUpdate() }.disabled(m.running)
- .padTarget("set.appRestart", scope: "main") { if !m.running { m.restartToUpdate() } }
- } else if let u = m.appUpdate, m.appInstallability == .ok {
- Button(String(format: loc.t("app.updateBtn"), u.tag)) { m.performAppUpdate() }.disabled(m.appBusy || m.running)
- .padTarget("set.appUpdate", scope: "main") { if !(m.appBusy || m.running) { m.performAppUpdate() } }
+ Button(loc.t("app.restartNow")) { updates.restartNow() }.disabled(m.running)
+ .padTarget("set.appRestart", scope: "main") { if !m.running { updates.restartNow() } }
+ } else if let u = updates.update, updates.installability == .ok {
+ Button(String(format: loc.t("app.updateBtn"), u.tag)) { updates.performUpdate() }.disabled(updates.busy || m.running)
+ .padTarget("set.appUpdate", scope: "main") { if !(updates.busy || m.running) { updates.performUpdate() } }
} else {
- Button(loc.t("repo.check")) { m.checkAppUpdate() }.disabled(m.appBusy)
- .padTarget("set.appCheck", scope: "main") { if !m.appBusy { m.checkAppUpdate() } }
+ Button(loc.t("repo.check")) { updates.checkForUpdate() }.disabled(updates.busy)
+ .padTarget("set.appCheck", scope: "main") { if !updates.busy { updates.checkForUpdate() } }
}
}
divider
- if m.appInstallability == .ok {
+ if updates.installability == .ok {
// The uninstaller (Uninstall.swift): state folders and the launcher's own checkout go; the
// games folder and prod.keys stay; the app itself goes to the Trash.
row(loc.t("uninstall.title"), detail: loc.t("uninstall.note")) {
- Button(loc.t("uninstall.button")) { m.uninstallPlan = uninstallPlan() }
+ Button(loc.t("uninstall.button")) { updates.uninstallPlan = uninstallPlan() }
.disabled(m.running)
- .padTarget("set.uninstall", scope: "main") { if !m.running { m.uninstallPlan = uninstallPlan() } }
+ .padTarget("set.uninstall", scope: "main") { if !m.running { updates.uninstallPlan = uninstallPlan() } }
}
divider
}
// A launcher built from the repository never replaces itself (AppUpdate.installability): the switch says so and stays off
- row(loc.t("app.auto"), detail: loc.t(m.appInstallability == .ok ? "app.autoNote" : m.appInstallability == .developer ? "app.autoDev" : "app.autoReadOnly")) {
- Toggle("", isOn: Binding(get: { m.autoUpdateApp && m.appInstallability == .ok }, set: { m.autoUpdateApp = $0 }))
- .labelsHidden().toggleStyle(LauncherSwitchStyle()).disabled(m.appInstallability != .ok)
- .padTarget("set.appAuto", scope: "main") { if m.appInstallability == .ok { m.autoUpdateApp.toggle() } }
+ row(loc.t("app.auto"), detail: loc.t(updates.installability == .ok ? "app.autoNote" : updates.installability == .developer ? "app.autoDev" : "app.autoReadOnly")) {
+ Toggle("", isOn: Binding(get: { updates.automatic && updates.installability == .ok }, set: { updates.automatic = $0 }))
+ .labelsHidden().toggleStyle(LauncherSwitchStyle()).disabled(updates.installability != .ok)
+ .padTarget("set.appAuto", scope: "main") { if updates.installability == .ok { updates.automatic.toggle() } }
}
}
}
diff --git a/frontend/Sources/NX2Apple/Diagnostics.swift b/frontend/Sources/NX2Apple/Diagnostics.swift
index de9ec1ff..2e5a5df6 100644
--- a/frontend/Sources/NX2Apple/Diagnostics.swift
+++ b/frontend/Sources/NX2Apple/Diagnostics.swift
@@ -311,7 +311,7 @@ extension BuildModel {
let read = { (file: String) in try? String(contentsOfFile: engine + "/" + file, encoding: .utf8) }
let pins = read("dm/gfx/tools/dmsh_chain.lock").map(Diagnostics.chainPins) ?? (nil, nil)
let inputs = Diagnostics.Inputs(
- appVersion: Self.appVersion,
+ appVersion: AppUpdateStore.appVersion,
macOS: ProcessInfo.processInfo.operatingSystemVersionString,
chip: Diagnostics.chip(),
repoPath: repo, commit: git.commit, branch: git.branch, behind: git.behind, lastFetch: git.lastFetch,
diff --git a/frontend/Sources/NX2Apple/EngineUpdateModel.swift b/frontend/Sources/NX2Apple/EngineUpdateModel.swift
index fbcec32e..0a8faca1 100644
--- a/frontend/Sources/NX2Apple/EngineUpdateModel.swift
+++ b/frontend/Sources/NX2Apple/EngineUpdateModel.swift
@@ -1,5 +1,6 @@
import Foundation
import NXCore
+import NXModel
import NXLauncher
// The release app's engine in the model: which tree the build reads, the launch check, the channel switch and what
@@ -12,7 +13,7 @@ extension BuildModel {
func prepareEngine() {
guard let bundled = engineBundle, !engineBusy, let id = EngineStore.identity(of: bundled) else { return }
let selected = engineSelection.engineID
- let appMovedOn = engineSelection.channel == .stable && selected != id && engineSelection.version != BuildModel.appVersion
+ let appMovedOn = engineSelection.channel == .stable && selected != id && engineSelection.version != AppUpdateStore.appVersion
if !appMovedOn, engineStore.isUsable(selected), let dir = engineStore.directory(for: selected) {
repoPath = dir.path
checkEngineUpdate(automatic: true)
@@ -28,7 +29,7 @@ extension BuildModel {
switch result {
case .success:
// The app's engine is the stable one of this release. A player on experimental gets theirs from the check.
- let engine = EngineUpdate.Engine(id: id, version: BuildModel.appVersion)
+ let engine = EngineUpdate.Engine(id: id, version: AppUpdateStore.appVersion)
if self.running { // a build started from the old folder while the copy ran
self.pendingEngine = (engine, self.engineSelection.channel)
self.engineStatus = ""
@@ -80,7 +81,7 @@ extension BuildModel {
if !quiet { engineStatus = t(channel == engineSelection.channel ? "engine.checking" : "engine.switching") }
let store = engineStore, bundled = engineBundle, current = engineSelection.engineID, transport = engineTransport
DispatchQueue.global(qos: .userInitiated).async {
- let outcome = EngineUpdate.run(channel: channel, appVersion: BuildModel.appVersion, current: current, store: store,
+ let outcome = EngineUpdate.run(channel: channel, appVersion: AppUpdateStore.appVersion, current: current, store: store,
bundled: bundled, install: install, transport: transport)
DispatchQueue.main.async {
self.engineBusy = false
diff --git a/frontend/Sources/NX2Apple/LauncherView.swift b/frontend/Sources/NX2Apple/LauncherView.swift
index 0604614d..38d6dd59 100644
--- a/frontend/Sources/NX2Apple/LauncherView.swift
+++ b/frontend/Sources/NX2Apple/LauncherView.swift
@@ -43,6 +43,7 @@ enum LibraryFilter: String, CaseIterable, Identifiable {
struct ContentView: View {
@StateObject private var m: BuildModel
@ObservedObject private var loc: Localizer // the strings: handed on to every view below through the environment
+ @ObservedObject private var updates: AppUpdateStore // the app's self-update: the update icon, the sheet, the uninstall dialog
@StateObject private var library: GameLibrary
@State private var page: LauncherPage = .library
@State private var search = ""
@@ -96,6 +97,7 @@ struct ContentView: View {
let model = model ?? BuildModel()
_m = StateObject(wrappedValue: model)
_loc = ObservedObject(wrappedValue: model.localizer)
+ _updates = ObservedObject(wrappedValue: model.appUpdates)
_library = StateObject(wrappedValue: library ?? GameLibrary())
_page = State(initialValue: initialPage)
_activeBuildID = State(initialValue: activeBuildID)
@@ -172,7 +174,7 @@ struct ContentView: View {
if page == .library {
libraryPage
} else {
- BuilderView(m: m, library: library, settings: page == .settings, onViewGame: { page = .library },
+ BuilderView(m: m, updates: updates, 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) }))
@@ -214,7 +216,7 @@ struct ContentView: View {
if m.usesEngineStore { m.prepareEngine() } // the release app: its engine store, never git (EngineUpdateModel.swift)
else { m.syncEngine() } // a checkout whose engine/ is missing or older than its pin (#214)
if m.repoOK && m.repoIsGit { m.checkRepoUpdates(silent: true) } else { m.adoptAtLaunch() }
- m.checkAppUpdate(silent: true)
+ updates.checkForUpdate(silent: true)
BuildNotifier.shared.watch(m, library: library) // BuildNotifications.swift
}
}
@@ -283,20 +285,12 @@ struct ContentView: View {
if let game = library.games.first(where: { $0.id == freeSpaceFor }) { FreeSpaceView(m: m, game: game).environmentObject(padFocus) }
}
.onChange(of: freeSpaceFor) { id in padFocus.scope = id != nil ? "free" : currentPadScope }
- .sheet(isPresented: $m.showUpdateSheet) { UpdateSheet(m: m) }
+ .sheet(isPresented: $updates.showUpdateSheet) { UpdateSheet(updates: updates) }
.confirmationDialog(loc.t("uninstall.title"), isPresented: Binding(
- get: { m.uninstallPlan != nil }, set: { if !$0 { m.uninstallPlan = nil } }
+ get: { updates.uninstallPlan != nil }, set: { if !$0 { updates.uninstallPlan = nil } }
), titleVisibility: .visible) {
Button(loc.t("uninstall.confirmButton"), role: .destructive) {
- if let plan = m.uninstallPlan {
- let result = Uninstall.run(plan)
- m.uninstallPlan = nil
- if result.failures.isEmpty {
- m.appStatus = String(format: loc.t("uninstall.done"), result.removed.count)
- } else {
- m.appStatus = loc.t("uninstall.failed") + "\n" + result.failures.joined(separator: "\n")
- }
- }
+ updates.confirmUninstall()
}
} message: { Text(loc.t("uninstall.confirm")) }
.sheet(isPresented: Binding(get: { savesFor != nil }, set: { if !$0 { savesFor = nil } })) {
@@ -364,16 +358,16 @@ struct ContentView: View {
.padding(.leading, 12)
// A newer release is out: a small icon, last in the bar, opens the update sheet. Without one the bar
// stays as it is.
- if let update = m.appUpdate {
- let readOnly = m.appInstallability == .readOnly
- Button { m.showUpdateSheet = true } label: {
+ if let update = updates.update {
+ let readOnly = updates.installability == .readOnly
+ Button { updates.showUpdateSheet = true } label: {
Image(systemName: readOnly ? "exclamationmark.arrow.circlepath" : "arrow.down.circle")
.font(.system(size: 18, weight: .medium))
.foregroundStyle(readOnly ? LauncherPalette.building : LauncherPalette.ready)
.frame(width: 34, height: 34).contentShape(Rectangle())
}
.buttonStyle(.plain)
- .padTarget("top.update", scope: "main", radius: 17) { m.showUpdateSheet = true }
+ .padTarget("top.update", scope: "main", radius: 17) { updates.showUpdateSheet = true }
.padding(.leading, 16.5).padding(.trailing, -7.5)
.help(String(format: loc.t("update.pill"), update.tag) + "\n" + loc.t(readOnly ? "update.readOnlyHint" : "update.pillHelp"))
.accessibilityLabel(String(format: loc.t("update.pill"), update.tag))
@@ -721,14 +715,14 @@ struct ContentView: View {
Text(loc.t("library.toolsAdopted")).font(.manrope(13)).foregroundStyle(.secondary)
}
Spacer()
- if let staged = m.appStaged {
- // A downloaded, verified update (BuildModel.stageAppUpdate): it goes in when the app quits, or now.
- // This branch only shows with no build running, and restartToUpdate checks again.
+ if let staged = updates.staged {
+ // A downloaded, verified update (AppUpdateStore.stage): it goes in when the app quits, or now.
+ // This branch only shows with no build running, and restartNow checks again.
HStack(spacing: 10) {
Circle().fill(LauncherPalette.ready).frame(width: 6, height: 6)
Text(String(format: loc.t("library.appReady"), staged.release.tag)).font(.manrope(13)).foregroundStyle(.secondary)
}
- Button(loc.t("app.restartNow")) { m.restartToUpdate() }.buttonStyle(LauncherSecondaryButtonStyle())
+ Button(loc.t("app.restartNow")) { updates.restartNow() }.buttonStyle(LauncherSecondaryButtonStyle())
}
if gamepad.connected {
// The buttons a controller has here, named as the game names them (A on the right)
diff --git a/frontend/Sources/NX2Apple/UpdateSheet.swift b/frontend/Sources/NX2Apple/UpdateSheet.swift
index 906cf416..414b8132 100644
--- a/frontend/Sources/NX2Apple/UpdateSheet.swift
+++ b/frontend/Sources/NX2Apple/UpdateSheet.swift
@@ -4,7 +4,7 @@ import NXModel
import NXLauncher
/// "A new version is out", with what it changes, shown when the app opens or Check for updates finds
-/// one. The app already had the update machinery (checkAppUpdate / performAppUpdate); what it lacked
+/// one. The app already had the update machinery (AppUpdateStore.checkForUpdate / performUpdate); what it lacked
/// was a reason to press the button: the status line said a tag name and nothing else, and a user who
/// was working fine had no way to tell whether the new version mattered to them.
///
@@ -13,18 +13,18 @@ import NXLauncher
/// match the interface language and falls back to the whole body when it cannot tell them apart.
/// ReleaseNotes turns them into blocks with links, and this file only styles those.
struct UpdateSheet: View {
- @ObservedObject var m: BuildModel
+ @ObservedObject var updates: AppUpdateStore
@EnvironmentObject var loc: Localizer
@Environment(\.dismiss) private var dismiss
- private var update: AppUpdate.Release? { m.appUpdate }
+ private var update: AppUpdate.Release? { updates.update }
var body: some View {
VStack(alignment: .leading, spacing: 0) {
VStack(alignment: .leading, spacing: 6) {
Text(loc.t("update.title"))
.font(.manrope(24, .heavy)).tracking(-0.5)
- Text(String(format: loc.t("update.fromTo"), BuildModel.appVersion, update?.tag ?? ""))
+ Text(String(format: loc.t("update.fromTo"), updates.version, update?.tag ?? ""))
.font(.manrope(13)).foregroundStyle(.secondary)
}
.padding(.horizontal, 28).padding(.top, 26).padding(.bottom, 18)
@@ -44,7 +44,7 @@ struct UpdateSheet: View {
}
.frame(maxHeight: 340)
- if let blocked = m.appUpdateBlocked {
+ if let blocked = updates.blocked {
Text(blocked).font(.manrope(12.5)).foregroundStyle(.orange)
.fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, 28).padding(.bottom, 12)
@@ -63,15 +63,15 @@ struct UpdateSheet: View {
// Automatic mode has already downloaded and staged the release, so the action is
// to swap it in now; otherwise this downloads, verifies and installs as before.
// The sheet stays up while it downloads, so a refusal (a macOS too old for the release) is seen here.
- if m.appStaged != nil { m.installStagedUpdate(relaunch: true); dismiss() } else { m.performAppUpdate() }
+ if updates.staged != nil { updates.install(relaunch: true); dismiss() } else { updates.performUpdate() }
} label: {
- Text(loc.t(m.appStaged != nil ? "app.restartNow" : "update.now"))
+ Text(loc.t(updates.staged != nil ? "app.restartNow" : "update.now"))
.font(.manrope(13.5, .bold)).foregroundStyle(.black)
.padding(.horizontal, 20).padding(.vertical, 9)
.background(LauncherPalette.cream, in: Capsule())
}
.buttonStyle(.plain)
- .disabled(m.appBusy)
+ .disabled(updates.busy)
.keyboardShortcut(.defaultAction)
}
.padding(.horizontal, 28).padding(.vertical, 16)
diff --git a/frontend/Sources/NXCore/AppUpdate.swift b/frontend/Sources/NXCore/AppUpdate.swift
index 2e130683..f8e17598 100644
--- a/frontend/Sources/NXCore/AppUpdate.swift
+++ b/frontend/Sources/NXCore/AppUpdate.swift
@@ -1,9 +1,9 @@
import Foundation
import CryptoKit
-// The launcher's self-update, the parts that decide what may be installed and when. BuildModel drives it
-// (checkAppUpdate, stageAppUpdate, installStagedUpdate); everything here works on paths it is given, so the
-// tests run it on bundles in a temporary folder, never on the running app or the network.
+// The launcher's self-update, the parts that decide what may be installed and when. `AppUpdateStore` (NXModel) drives it;
+// everything here works on data and paths it is given, so the tests run it on bundles in a temporary folder, never on the
+// running app or the network.
//
// The rules:
// - What is installed is what GitHub says the release is: the zip's SHA-256 matches the asset's `digest`
@@ -174,7 +174,8 @@ package enum AppUpdate {
}
/// Install the staged app and return where it ended up (the caller relaunches that path).
- package static func install(_ staged: URL, over current: URL, buildRunning: Bool, trashOld: Bool = true) throws -> URL {
+ package static func install(_ staged: URL, over current: URL, buildRunning: Bool, trashOld: Bool = true,
+ runner: ProcessRunner = SystemProcessRunner()) throws -> URL {
guard !buildRunning else { throw InstallError.buildRunning }
let fm = FileManager.default
let dir = current.deletingLastPathComponent()
@@ -186,7 +187,7 @@ package enum AppUpdate {
// app is exiting anyway.
try? fm.removeItem(at: target)
try fm.copyItem(at: staged, to: target)
- clearQuarantine(target)
+ clearQuarantine(target, runner: runner)
if trashOld { try? fm.trashItem(at: current, resultingItemURL: nil) }
return target
}
@@ -202,7 +203,7 @@ package enum AppUpdate {
if fm.fileExists(atPath: backup.path) {
if trashOld { try? fm.trashItem(at: backup, resultingItemURL: nil) } else { try? fm.removeItem(at: backup) }
}
- clearQuarantine(placed ?? current)
+ clearQuarantine(placed ?? current, runner: runner)
return current
} catch {
try? fm.removeItem(at: incoming)
@@ -235,10 +236,123 @@ package enum AppUpdate {
do { try p.run(); return true } catch { return false }
}
- private static func clearQuarantine(_ app: URL) {
- let x = Process()
- x.executableURL = URL(fileURLWithPath: "/usr/bin/xattr")
- x.arguments = ["-dr", "com.apple.quarantine", app.path]
- try? x.run(); x.waitUntilExit()
+ private static func clearQuarantine(_ app: URL, runner: ProcessRunner) {
+ _ = runner.capture(ProcessLaunch(executable: "/usr/bin/xattr", arguments: ["-dr", "com.apple.quarantine", app.path]))
+ }
+
+ // ---- Which release is the latest ----
+
+ /// The download names this build accepts, newest first. Every release must carry at least one of
+ /// them or an install from that era cannot update itself: NX2Apple is current, nxnative is for
+ /// installs from before the rename to NX2Apple, NS-Port-Builder for installs before that.
+ package static let assetNames = ["NX2Apple-macOS-arm64.zip", "nxnative-macOS-arm64.zip", "NS-Port-Builder-macOS-arm64.zip"]
+
+ /// `tag` ("v0.4.10") is a later version than `current` ("0.4.8"), compared number by number.
+ package static func isNewer(_ tag: String, than current: String) -> Bool {
+ func nums(_ s: String) -> [Int] { s.split(separator: ".").map { Int($0.filter { $0.isNumber }) ?? 0 } }
+ let a = nums(tag), b = nums(current)
+ for i in 0..<max(a.count, b.count) {
+ let x = i < a.count ? a[i] : 0, y = i < b.count ? b[i] : 0
+ if x != y { return x > y }
+ }
+ return false
+ }
+
+ /// The release's asset this app installs, with its digest: NX2Apple-macOS-arm64.zip, or the zip under an older
+ /// name (releases from before each rename).
+ package static func release(fromJSON obj: [String: Any]) -> Release? {
+ let tag = obj["tag_name"] as? String ?? ""
+ guard let assets = obj["assets"] as? [[String: Any]] else { return nil }
+ for name in assetNames {
+ for a in assets where (a["name"] as? String) == name {
+ if let u = a["browser_download_url"] as? String { return Release(tag: tag, url: u, digest: a["digest"] as? String) }
+ }
+ }
+ return nil
+ }
+
+ /// What the check of the latest release found.
+ package enum Check: Equatable {
+ /// The answer never came (no network, a timeout).
+ case unreachable
+ case upToDate
+ /// A newer release exists, with the asset this app installs and the notes.
+ case found(Release)
+ /// A newer release exists but carries no download this build can name. That is NOT "up to date": it is the
+ /// difference between a user who updates and one who sits on 0.4.6 for ever, because 0.4.6 and 0.4.7 look for
+ /// exactly "NS-Port-Builder-macOS-arm64.zip" and would report "up to date" and stop.
+ case noAsset(tag: String)
+ }
+
+ /// The answer of GitHub's "latest release" call (`nil` when there was none) against the running version.
+ package static func check(latest data: Data?, current: String) -> Check {
+ guard let data else { return .unreachable }
+ guard let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return .upToDate }
+ let tag = obj["tag_name"] as? String ?? ""
+ guard isNewer(tag, than: current) else { return .upToDate }
+ guard var r = release(fromJSON: obj) else { return .noAsset(tag: tag) }
+ r.notes = (obj["body"] as? String) ?? ""
+ return .found(r)
+ }
+
+ // ---- What was downloaded, to a staged app ----
+
+ /// Why staging stopped: each case is the localization key of its message (a format with the release's tag).
+ package enum StageFailure: Error, Equatable {
+ case network, noDigest, mismatch, unpack, notOurApp
+ /// The release's LSMinimumSystemVersion is above the running macOS (the string is that minimum).
+ case needsNewerMacOS(String)
+
+ package var key: String {
+ switch self {
+ case .network: return "app.stageNetFail"
+ case .noDigest: return "app.noDigest"
+ case .mismatch: return "app.digestMismatch"
+ case .unpack: return "app.unpackFail"
+ case .notOurApp: return "app.notOurApp"
+ case .needsNewerMacOS: return "app.needsNewerMacOS"
+ }
+ }
+ }
+
+ /// The folder staging works in, in the temporary directory and emptied first.
+ package static func freshStagingRoot(in temporary: URL = FileManager.default.temporaryDirectory) -> URL {
+ let fm = FileManager.default
+ let root = temporary.appendingPathComponent("nspb-update", isDirectory: true)
+ try? fm.removeItem(at: root)
+ try? fm.createDirectory(at: root, withIntermediateDirectories: true)
+ return root
+ }
+
+ /// A downloaded zip to a staged app: its digest first, then unzip (ditto, as the release was packed), then the app inside.
+ package static func stage(zip: URL, release: Release, in root: URL, expectedID: String, requireDigest: Bool,
+ runningOS: OperatingSystemVersion = ProcessInfo.processInfo.operatingSystemVersion,
+ runner: ProcessRunner = SystemProcessRunner()) -> Result<Staged, StageFailure> {
+ let fm = FileManager.default
+ switch checkDigest(zip, expected: release.digest) {
+ case .match: break
+ case .mismatch: try? fm.removeItem(at: zip); return .failure(.mismatch)
+ case .missing: if requireDigest { try? fm.removeItem(at: zip); return .failure(.noDigest) }
+ }
+ let dir = root.appendingPathComponent("app", isDirectory: true)
+ try? fm.removeItem(at: dir)
+ try? fm.createDirectory(at: dir, withIntermediateDirectories: true)
+ let unzip = runner.capture(ProcessLaunch(executable: "/usr/bin/ditto", arguments: ["-x", "-k", zip.path, dir.path]))
+ guard unzip.started else { return .failure(.unpack) }
+ try? fm.removeItem(at: zip)
+ // The archive holds one app: NX2Apple.app, or the bundle under an older name in a release from before a rename
+ guard unzip.status == 0,
+ let app = ((try? fm.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? []).first(where: { $0.pathExtension == "app" })
+ else { return .failure(.unpack) }
+ if bundleProblem(app, expectedID: expectedID, tag: release.tag) != nil {
+ try? fm.removeItem(at: dir)
+ return .failure(.notOurApp)
+ }
+ // Not a release this Mac cannot open: it would replace a launcher that works with an app that will not start
+ if let min = minimumOSAbove(runningOS, app: app) {
+ try? fm.removeItem(at: dir)
+ return .failure(.needsNewerMacOS(min))
+ }
+ return .success(Staged(release: release, app: app))
}
}
diff --git a/frontend/Sources/NXCore/ReleaseSource.swift b/frontend/Sources/NXCore/ReleaseSource.swift
new file mode 100644
index 00000000..d6d716c3
--- /dev/null
+++ b/frontend/Sources/NXCore/ReleaseSource.swift
@@ -0,0 +1,29 @@
+import Foundation
+
+/// Where the launcher learns about releases and fetches one: the second service of the self-update, next to `ProcessRunner`.
+/// `AppUpdateStore` takes one through its initializer, so a test passes in a fake that answers without a network.
+package protocol ReleaseSource {
+ /// The body of the latest release as the GitHub API gives it. nil when there was no answer (no network, a timeout).
+ func latestRelease() async -> Data?
+ /// Downloads `url` to `file`. false when it did not arrive or the server did not answer 200.
+ func download(_ url: URL, to file: URL) async -> Bool
+}
+
+/// The releases of a GitHub repository, over `URLSession.shared`.
+package struct GitHubReleases: ReleaseSource {
+ package let repository: String
+
+ package init(repository: String = "LNPANDY/NX2Apple") { self.repository = repository }
+
+ package func latestRelease() async -> Data? {
+ guard let url = URL(string: "https://api.github.com/repos/\(repository)/releases/latest") else { return nil }
+ return try? await URLSession.shared.data(from: url).0
+ }
+
+ package func download(_ url: URL, to file: URL) async -> Bool {
+ guard let (local, response) = try? await URLSession.shared.download(from: url),
+ (response as? HTTPURLResponse)?.statusCode ?? 200 == 200
+ else { return false }
+ return (try? FileManager.default.moveItem(at: local, to: file)) != nil
+ }
+}
diff --git a/frontend/Sources/NX2Apple/Uninstall.swift b/frontend/Sources/NXCore/Uninstall.swift
similarity index 80%
rename from frontend/Sources/NX2Apple/Uninstall.swift
rename to frontend/Sources/NXCore/Uninstall.swift
index de556386..3dae3cd9 100644
--- a/frontend/Sources/NX2Apple/Uninstall.swift
+++ b/frontend/Sources/NXCore/Uninstall.swift
@@ -1,5 +1,4 @@
-import AppKit
-import NXCore
+import Foundation
/// Uninstalling the launcher (NX Play's Uninstall): everything the app put outside its bundle, with the
/// player's games and keys left alone. What goes:
@@ -13,21 +12,25 @@ import NXCore
/// What stays: the games folder and everything in it, the build output folder, `prod.keys`, Homebrew, and the
/// app itself, which goes to the Trash when the player confirms — never deleted. A folder that holds the games
/// folder or the build output folder stays as a whole.
-enum Uninstall {
- struct Plan: Equatable {
- var stateFolders: [String] = []
- var checkouts: [String] = []
+package enum Uninstall {
+ package struct Plan: Equatable {
+ package var stateFolders: [String] = []
+ package var checkouts: [String] = []
/// The UserDefaults domain with the launcher's settings, nil when there is none to remove.
- var defaultsDomain: String?
+ package var defaultsDomain: String?
/// Where the app lives now (goes to the Trash, not deleted).
- var app: String = Bundle.main.bundlePath
+ package var app: String = Bundle.main.bundlePath
+
+ package init(stateFolders: [String] = [], checkouts: [String] = [], defaultsDomain: String? = nil, app: String = Bundle.main.bundlePath) {
+ self.stateFolders = stateFolders; self.checkouts = checkouts; self.defaultsDomain = defaultsDomain; self.app = app
+ }
}
/// The paths this install would remove, computed before anything is offered: the launcher's state
/// folders that exist, and a checkout that is the launcher's own download (the clone destination
/// `cloneRepo` uses) rather than one the player picked from anywhere on disk.
/// `home` is passed in (NSHomeDirectory() at the call site): a computed home is not testable.
- nonisolated static func plan(home: String, gamesFolder: String, outputFolder: String = "", checkouts: [String],
+ nonisolated package static func plan(home: String, gamesFolder: String, outputFolder: String = "", checkouts: [String],
defaultsDomain: String? = nil) -> Plan {
let fm = FileManager.default
var p = Plan(defaultsDomain: defaultsDomain)
@@ -48,13 +51,13 @@ enum Uninstall {
}
/// Whether `path` is `folder` or lies inside it, after resolving symbolic links and `..`.
- nonisolated static func contains(_ folder: String, _ path: String) -> Bool {
+ nonisolated package static func contains(_ folder: String, _ path: String) -> Bool {
let f = URL(fileURLWithPath: folder).resolvingSymlinksInPath().standardizedFileURL.pathComponents
let p = URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.pathComponents
return p.count >= f.count && Array(p.prefix(f.count)) == f
}
- nonisolated static func gitOrigin(_ checkout: String, git: GitCheckout = SystemGitCheckout()) -> String? {
+ nonisolated package static func gitOrigin(_ checkout: String, git: GitCheckout = SystemGitCheckout()) -> String? {
guard git.binary != nil else { return nil }
let r = git.run(checkout, ["remote", "get-url", "origin"])
let url = r.out.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -63,7 +66,7 @@ enum Uninstall {
/// Remove the plan's folders. The games folder and the app are never touched here. Returns what was
/// removed and what failed (in use, permissions), so the confirmation can say so honestly.
- nonisolated static func run(_ plan: Plan, movingAppToTrash: Bool = true) -> (removed: [String], failures: [String]) {
+ nonisolated package static func run(_ plan: Plan, movingAppToTrash: Bool = true) -> (removed: [String], failures: [String]) {
let fm = FileManager.default
var removed: [String] = [], failures: [String] = []
for folder in plan.stateFolders + plan.checkouts {
@@ -82,7 +85,7 @@ enum Uninstall {
}
/// To the Trash, like the Finder's delete: recoverable, never `removeItem`.
- nonisolated static func trash(_ path: String) -> Bool {
+ nonisolated package static func trash(_ path: String) -> Bool {
var url: NSURL?
do {
try FileManager.default.trashItem(at: URL(fileURLWithPath: path), resultingItemURL: &url)
diff --git a/frontend/Sources/NXModel/AppUpdateStore.swift b/frontend/Sources/NXModel/AppUpdateStore.swift
new file mode 100644
index 00000000..92584b2d
--- /dev/null
+++ b/frontend/Sources/NXModel/AppUpdateStore.swift
@@ -0,0 +1,278 @@
+import Foundation
+import Combine
+import NXCore
+
+/// The launcher's self-update (LNPANDY/NX2Apple#387): the release check, the staged update, the update sheet, the uninstall
+/// plan and the version the check compares. It is the reference store: `frontend/ARCHITECTURE.md` ("Stores") describes the
+/// pattern, and later stores follow it.
+///
+/// - It is `@MainActor`, an `ObservableObject`, and owns its `@Published` state. Views observe it and call its methods.
+/// - It gets what it works with through `init`: the `Localizer` for its status text, a `ProcessRunner` (ditto, xattr), a
+/// `ReleaseSource` (the network), the bundle it may replace and the defaults it saves its switch in. Tests pass in fakes.
+/// - It checks the conditions for its own actions: no install while a build runs, none for a copy built from the repository.
+/// - What needs AppKit reaches it as closures: quitting the app and relaunching it (`terminate`, `relaunch`). The app also
+/// calls `appWillTerminate()` from AppKit's notification.
+/// - The rules that need no state (what is verified, which copies replace themselves, parsing, the version compare) are
+/// `AppUpdate` in `NXCore`.
+///
+/// A check or a staging runs as a `Task` on the main actor. The method that starts one returns it, so a test awaits it.
+@MainActor package final class AppUpdateStore: ObservableObject {
+ /// Bump together with each release tag: the update check compares it with the latest release.
+ /// `build-mac-app.yml`, `sync-upstream.yml`, `tools/try-local` and `RELEASING.md` read this line. Keep it in this form.
+ nonisolated package static let appVersion = "1.0.1"
+
+ /// The version this store compares releases with: `appVersion`, unless a test passes another.
+ nonisolated package let version: String
+
+ /// The update the check found: the tag, the asset to download, its digest, and the release notes the sheet shows. The
+ /// notes are why the sheet exists: "update available" alone told a user nothing about what they would get.
+ @Published package var update: AppUpdate.Release?
+ /// A check or a download is running.
+ @Published package private(set) var busy = false
+ /// Whether the "a new version is out" sheet is up: opened by the launch check and by Check for updates, so a user learns
+ /// what changed before deciding, not after downloading.
+ @Published package var showUpdateSheet = false
+ /// The uninstall row's dialog: computed when the row is pressed, run when the player confirms.
+ @Published package var uninstallPlan: Uninstall.Plan?
+ /// The line under the app section of Settings.
+ @Published package var status = ""
+ /// Set when the last update attempt was refused (a release this macOS cannot open, a bad download): the sheet shows it.
+ @Published package private(set) var blocked: String?
+ /// The release that is downloaded, verified and unpacked: it goes in when the app quits, or with Restart now.
+ @Published package var staged: AppUpdate.Staged?
+ /// Where a rename-era install put the new app (the old bundle name is gone): the Dock entry that points at the old path
+ /// is stale until the player pins the new one again.
+ @Published package private(set) var renamedInstall: String?
+ /// Whether this copy may replace itself. A launcher built from the repository never does (tests set it).
+ @Published package var installability: AppUpdate.Installability
+
+ /// Download a new release by itself and install it when the app quits (Settings, on by default). Off, the Update button in
+ /// Settings downloads, swaps in and relaunches.
+ @Published package var automatic: Bool {
+ didSet {
+ defaults.set(automatic, forKey: Self.automaticKey)
+ if automatic, staged == nil, let u = update { stage(u, automatic: true) }
+ }
+ }
+ nonisolated package static let automaticKey = "autoUpdateApp"
+
+ private let localizer: Localizer
+ private let runner: ProcessRunner
+ private let releases: ReleaseSource
+ private let bundle: URL
+ private let bundleIdentifier: String
+ private let runningOS: OperatingSystemVersion
+ private let defaults: UserDefaults
+ private let buildRunning: () -> Bool
+ private let relaunch: (URL) -> Bool
+ private let terminate: () -> Void
+ private let uninstall: (Uninstall.Plan) -> (removed: [String], failures: [String])
+ private let trashOldApp: Bool
+
+ /// - Parameters:
+ /// - buildRunning: whether a build of this app runs (the model's flag, and any process group of one still alive).
+ /// - relaunch: starts the new copy once this process has exited.
+ /// - terminate: quits the app.
+ /// - uninstall: removes what a plan names and says what went and what failed.
+ /// - trashOldApp: the replaced bundle goes to the Trash (a test says false, so it leaves nothing there).
+ package init(localizer: Localizer, runner: ProcessRunner, releases: ReleaseSource,
+ version: String = AppUpdateStore.appVersion,
+ bundle: URL = Bundle.main.bundleURL, bundleIdentifier: String? = Bundle.main.bundleIdentifier,
+ runningOS: OperatingSystemVersion = ProcessInfo.processInfo.operatingSystemVersion,
+ defaults: UserDefaults = .standard,
+ buildRunning: @escaping () -> Bool = { ProcessGroups.buildProcessesAlive },
+ relaunch: @escaping (URL) -> Bool = { AppUpdate.relaunch($0) },
+ terminate: @escaping () -> Void = {},
+ uninstall: @escaping (Uninstall.Plan) -> (removed: [String], failures: [String]) = { Uninstall.run($0) },
+ trashOldApp: Bool = true) {
+ self.localizer = localizer
+ self.runner = runner
+ self.releases = releases
+ self.version = version
+ self.bundle = bundle
+ self.bundleIdentifier = bundleIdentifier ?? ""
+ self.runningOS = runningOS
+ self.defaults = defaults
+ self.buildRunning = buildRunning
+ self.relaunch = relaunch
+ self.terminate = terminate
+ self.uninstall = uninstall
+ self.trashOldApp = trashOldApp
+ installability = AppUpdate.installability(bundle, appVersion: version)
+ automatic = defaults.object(forKey: Self.automaticKey) as? Bool ?? true
+ }
+
+ private func t(_ key: String) -> String { localizer.t(key) }
+
+ /// No build of this app is running: none in the model, and no process group of one still alive (a stopped build's tools
+ /// can take a moment to go).
+ package var mayInstall: Bool { !buildRunning() }
+
+ // ---- The check ----
+
+ /// Ask GitHub for the latest release. `silent` (the launch check) only surfaces a found update: "up to date" and network
+ /// failures stay quiet. A slow or blocked network just times out. With automatic updates on, a found release is
+ /// downloaded and staged in the background.
+ @discardableResult
+ package func checkForUpdate(silent: Bool = false) -> Task<Void, Never> {
+ guard !busy else { return Task {} }
+ busy = true
+ if !silent { status = t("app.checking") }
+ return Task {
+ let data = await releases.latestRelease()
+ finishCheck(AppUpdate.check(latest: data, current: version), silent: silent)
+ }
+ }
+
+ private func finishCheck(_ outcome: AppUpdate.Check, silent: Bool) {
+ busy = false
+ switch outcome {
+ case .found(let f):
+ update = f
+ switch installability {
+ case .developer: status = String(format: t("app.devBuild"), f.tag)
+ case .readOnly: status = String(format: t("app.readOnly"), f.tag)
+ case .ok:
+ if staged?.release == f { status = String(format: t("app.ready"), f.tag) }
+ else if automatic { stage(f, automatic: true) }
+ else { status = String(format: t("app.found"), f.tag) }
+ // The sheet opens either way: it is the only place the release notes appear, and "a new version is out"
+ // without saying what changed is what made people press Update blindly or not at all. In automatic mode it
+ // is also where Restart now lives, and it says the download is already running.
+ showUpdateSheet = true
+ }
+ case .unreachable:
+ if !silent { status = t("app.netFail") }
+ case .noAsset(let tag):
+ // The release exists; this app just cannot find its own asset name in it.
+ if !silent { status = String(format: t("app.noAsset"), tag); update = nil }
+ case .upToDate:
+ if !silent { status = t("app.upToDate") }
+ }
+ }
+
+ // ---- Download, verify, unpack ----
+
+ /// Download the release, check it against its digest, unpack it and check the app inside, all in the background: the result
+ /// waits in `staged`. `automatic` (the switch) refuses a release whose digest GitHub did not give, the Update button
+ /// accepts it, as before. `then` gets the staged copy (the button installs it at once).
+ @discardableResult
+ package func stage(_ release: AppUpdate.Release, automatic: Bool, then: ((AppUpdate.Staged) -> Void)? = nil) -> Task<Void, Never> {
+ guard !busy, installability == .ok, let url = URL(string: release.url) else { return Task {} }
+ busy = true
+ blocked = nil
+ status = String(format: t(automatic ? "app.staging" : "app.downloading"), release.tag)
+ let expectedID = bundleIdentifier, runner = runner, runningOS = runningOS
+ return Task {
+ let root = AppUpdate.freshStagingRoot()
+ let zip = root.appendingPathComponent("update.zip")
+ let result: Result<AppUpdate.Staged, AppUpdate.StageFailure>
+ if await releases.download(url, to: zip) {
+ result = await Task.detached {
+ AppUpdate.stage(zip: zip, release: release, in: root, expectedID: expectedID, requireDigest: automatic,
+ runningOS: runningOS, runner: runner)
+ }.value
+ } else {
+ result = .failure(.network)
+ }
+ finishStaging(result, release: release, then: then)
+ }
+ }
+
+ private func finishStaging(_ result: Result<AppUpdate.Staged, AppUpdate.StageFailure>, release: AppUpdate.Release,
+ then: ((AppUpdate.Staged) -> Void)?) {
+ busy = false
+ switch result {
+ case .success(let s):
+ staged = s
+ status = String(format: t("app.ready"), release.tag)
+ then?(s)
+ case .failure(let why):
+ if case .needsNewerMacOS(let min) = why {
+ // Nothing was installed: the running version stays, and says why
+ status = String(format: t(why.key), release.tag, min, AppUpdate.describe(runningOS))
+ } else {
+ status = String(format: t(why.key), release.tag)
+ }
+ blocked = status
+ }
+ }
+
+ // ---- Install ----
+
+ /// Swap the staged app in. `relaunch` (Restart now, the Update button) opens the new copy and quits, at quit the next
+ /// launch is the new version. Refused while a build runs.
+ @discardableResult
+ package func install(relaunch relaunchNow: Bool, at current: URL? = nil) -> Bool {
+ guard let staged, installability == .ok else { return false }
+ let current = current ?? bundle
+ let placed: URL
+ do {
+ placed = try AppUpdate.install(staged.app, over: current, buildRunning: !mayInstall, trashOld: trashOldApp, runner: runner)
+ } catch AppUpdate.InstallError.failed(let why) {
+ status = String(format: t("app.installFail"), why)
+ return false
+ } catch {
+ status = t("app.waitForBuild")
+ return false
+ }
+ self.staged = nil
+ // A rename era (nxnative, NS Port Builder, NX2Apple) installs under the release's own bundle name. The Dock entry
+ // pointing at the old path goes stale once, so the log says where the new copy landed instead of leaving the player
+ // to find it.
+ if placed != current {
+ fputs("launcher: the update was installed as \(placed.lastPathComponent) (the app was renamed); "
+ + "the previous \(current.lastPathComponent) was removed - re-pin it in the Dock\n", stderr)
+ renamedInstall = placed.path
+ }
+ if relaunchNow {
+ status = String(format: t("app.relaunching"), staged.release.tag)
+ // The old instance is still running, so opening the same bundle now would only activate it: a helper opens the
+ // new copy once this process has exited.
+ if relaunch(placed) { terminate() } else { status = String(format: t("app.relaunchFail"), staged.release.tag) }
+ }
+ return true
+ }
+
+ /// Restart now (Settings, the library's activity line): install and relaunch, never during a build.
+ package func restartNow() {
+ guard staged != nil else { return }
+ guard mayInstall else { status = t("app.waitForBuild"); return }
+ install(relaunch: true)
+ }
+
+ /// The Update button (automatic updates off, or a release they would not take): download and verify, swap in, relaunch. A
+ /// staged copy of the same release goes in as it is. Not during a build: the relaunch would end it.
+ package func performUpdate() {
+ guard let upd = update, !busy, installability == .ok else { return }
+ guard mayInstall else { status = t("app.waitForBuild"); return }
+ if staged?.release == upd { install(relaunch: true); return }
+ stage(upd, automatic: false) { [weak self] _ in
+ guard let self else { return }
+ self.status = self.t("app.installing")
+ self.install(relaunch: true)
+ }
+ }
+
+ /// The app is quitting (AppKit's notification, forwarded by the app). The staged update goes in, so the next launch is the
+ /// new version without interrupting anyone. A build running at that moment is being ended by the same quit: the swap then
+ /// waits for a later quit (the next launch stages the release again) rather than run while the build's tools are alive.
+ package func appWillTerminate() {
+ guard automatic, staged != nil, mayInstall else { return }
+ install(relaunch: false)
+ }
+
+ // ---- Uninstall ----
+
+ /// The player confirmed the uninstall dialog: remove what the plan names and say what went and what did not.
+ package func confirmUninstall() {
+ guard let plan = uninstallPlan else { return }
+ let result = uninstall(plan)
+ uninstallPlan = nil
+ if result.failures.isEmpty {
+ status = String(format: t("uninstall.done"), result.removed.count)
+ } else {
+ status = t("uninstall.failed") + "\n" + result.failures.joined(separator: "\n")
+ }
+ }
+}
diff --git a/frontend/Tests/NX2AppleTests/DropFilesTests.swift b/frontend/Tests/NX2AppleTests/DropFilesTests.swift
index fffb7a7a..ffcbf71f 100644
--- a/frontend/Tests/NX2AppleTests/DropFilesTests.swift
+++ b/frontend/Tests/NX2AppleTests/DropFilesTests.swift
@@ -138,7 +138,7 @@ final class DropFilesTests: XCTestCase {
model.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, library: library).environmentObject(PadFocus()).environmentObject(model.localizer)
+ let page = BuilderView(m: model, updates: model.appUpdates, 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.swift
index 19ebb273..6f5d92bc 100644
--- a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
+++ b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
@@ -79,11 +79,11 @@ final class LauncherControlWidthTests: XCTestCase {
return [
Scenario(name: "settings without a repository", page: .settings, atLeast: 4) { m, _, _ in
m.repoPath = ""
- m.appInstallability = .ok
+ MainActor.assumeIsolated { m.appUpdates.installability = .ok }
},
Scenario(name: "settings with a ZIP copy and a library folder", page: .settings, atLeast: 6) { m, library, directory in
m.repoPath = try self.makeRepo(directory, git: false)
- m.appInstallability = .ok
+ MainActor.assumeIsolated { m.appUpdates.installability = .ok }
m.depsChecked = true
m.deps = [Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: [])]
library.setFolder(directory)
@@ -91,13 +91,13 @@ final class LauncherControlWidthTests: XCTestCase {
Scenario(name: "settings with a clone that is behind and an app update", page: .settings, atLeast: 6) { m, _, directory in
m.repoPath = try self.makeRepo(directory, git: true)
m.repoBehind = 2
- m.appInstallability = .ok
- m.appUpdate = release
+ MainActor.assumeIsolated { m.appUpdates.installability = .ok }
+ MainActor.assumeIsolated { m.appUpdates.update = release }
},
Scenario(name: "settings with an update ready to restart into", page: .settings, atLeast: 4) { m, _, directory in
m.repoPath = try self.makeRepo(directory, git: true)
- m.appInstallability = .ok
- m.appStaged = AppUpdate.Staged(release: release, app: directory.appendingPathComponent("NX2Apple.app"))
+ MainActor.assumeIsolated { m.appUpdates.installability = .ok }
+ MainActor.assumeIsolated { m.appUpdates.staged = AppUpdate.Staged(release: release, app: directory.appendingPathComponent("NX2Apple.app")) }
},
Scenario(name: "settings with every kind of missing tool", page: .settings, atLeast: 6) { m, _, directory in
m.repoPath = try self.makeRepo(directory, git: true)
diff --git a/frontend/Tests/NX2AppleTests/LibraryTests.swift b/frontend/Tests/NX2AppleTests/LibraryTests.swift
index eb56c27c..7d3252a4 100644
--- a/frontend/Tests/NX2AppleTests/LibraryTests.swift
+++ b/frontend/Tests/NX2AppleTests/LibraryTests.swift
@@ -837,15 +837,15 @@ final class LibraryTests: XCTestCase {
try capture("build-tools-old", height: 1500, page: .builds)
}
do { // a released copy with an update downloaded and verified: Restart now in Settings and in the activity line
- let previous = (model.appInstallability, model.appUpdate, model.appStaged, model.appStatus)
- defer { (model.appInstallability, model.appUpdate, model.appStaged, model.appStatus) = previous }
+ let previous = (model.appUpdates.installability, model.appUpdates.update, model.appUpdates.staged, model.appUpdates.status)
+ defer { (model.appUpdates.installability, model.appUpdates.update, model.appUpdates.staged, model.appUpdates.status) = previous }
let release = AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/NX2Apple-macOS-arm64.zip", digest: nil)
- model.appInstallability = .ok
- model.appUpdate = release
- model.appStatus = String(format: model.t("app.found"), release.tag)
+ model.appUpdates.installability = .ok
+ model.appUpdates.update = release
+ model.appUpdates.status = String(format: model.t("app.found"), release.tag)
try capture("settings-update-found", page: .settings)
- model.appStaged = AppUpdate.Staged(release: release, app: temporary.appendingPathComponent("NX2Apple.app"))
- model.appStatus = String(format: model.t("app.ready"), release.tag)
+ model.appUpdates.staged = AppUpdate.Staged(release: release, app: temporary.appendingPathComponent("NX2Apple.app"))
+ model.appUpdates.status = String(format: model.t("app.ready"), release.tag)
try capture("settings-update-ready", page: .settings)
try capture("library-update-ready")
}
diff --git a/frontend/Tests/NX2AppleTests/ReleaseNotesTests.swift b/frontend/Tests/NX2AppleTests/ReleaseNotesTests.swift
index 111c25df..410c36d9 100644
--- a/frontend/Tests/NX2AppleTests/ReleaseNotesTests.swift
+++ b/frontend/Tests/NX2AppleTests/ReleaseNotesTests.swift
@@ -204,9 +204,9 @@ final class ReleaseNotesTests: XCTestCase {
("update-sheet-notes-middle-en", Lang.en, middle, "v0.7.0"), ("update-sheet-notes-middle-zh", Lang.zh, middle, "v0.7.0")] {
let m = BuildModel()
m.lang = lang
- m.appUpdate = AppUpdate.Release(tag: tag, url: "", digest: nil, notes: notes)
+ m.appUpdates.update = AppUpdate.Release(tag: tag, url: "", digest: nil, notes: notes)
let width: CGFloat = 560, height: CGFloat = 640
- let host = NSHostingView(rootView: UpdateSheet(m: m).environmentObject(m.localizer).frame(width: width, height: height))
+ let host = NSHostingView(rootView: UpdateSheet(updates: m.appUpdates).environmentObject(m.localizer).frame(width: width, height: height))
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: width, height: height), styleMask: [.titled], backing: .buffered, defer: false)
window.contentView = host
window.appearance = NSAppearance(named: .darkAqua)
diff --git a/frontend/Tests/NX2AppleTests/SourceSizeTests.swift b/frontend/Tests/NX2AppleTests/SourceSizeTests.swift
index 8d79a3f6..116324d9 100644
--- a/frontend/Tests/NX2AppleTests/SourceSizeTests.swift
+++ b/frontend/Tests/NX2AppleTests/SourceSizeTests.swift
@@ -7,8 +7,8 @@ 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": 2763,
- "NX2Apple/LauncherView.swift": 973,
+ "NX2Apple/ContentView.swift": 2494,
+ "NX2Apple/LauncherView.swift": 967,
"NXCore/Localization.swift": 4237,
]
diff --git a/frontend/Tests/NX2AppleTests/AppUpdateTests.swift b/frontend/Tests/NXCoreTests/AppUpdateTests.swift
similarity index 87%
rename from frontend/Tests/NX2AppleTests/AppUpdateTests.swift
rename to frontend/Tests/NXCoreTests/AppUpdateTests.swift
index da41bb63..ba60583f 100644
--- a/frontend/Tests/NX2AppleTests/AppUpdateTests.swift
+++ b/frontend/Tests/NXCoreTests/AppUpdateTests.swift
@@ -1,8 +1,6 @@
import XCTest
import CryptoKit
-@testable import NX2Apple
@testable import NXCore
-@testable import NXLauncher
/// The self-update's rules on bundles in a temporary folder: never the running app, never the network.
final class AppUpdateTests: XCTestCase {
@@ -127,15 +125,15 @@ final class AppUpdateTests: XCTestCase {
let source = temporary.appendingPathComponent("source-os", isDirectory: true)
let archive = try zip(try makeApp(in: source, minOS: "26.6"))
let release = AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/a.zip", digest: try digest(archive))
- func attempt(_ running: OperatingSystemVersion) throws -> Result<AppUpdate.Staged, BuildModel.StageFailure> {
+ func attempt(_ running: OperatingSystemVersion) throws -> Result<AppUpdate.Staged, AppUpdate.StageFailure> {
let copy = temporary.appendingPathComponent("copy-" + UUID().uuidString + ".zip")
try FileManager.default.copyItem(at: archive, to: copy)
let root = temporary.appendingPathComponent("stage-" + UUID().uuidString, isDirectory: true)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
- return BuildModel.stage(zip: copy, release: release, in: root, expectedID: bundleID, requireDigest: true, runningOS: running)
+ return AppUpdate.stage(zip: copy, release: release, in: root, expectedID: bundleID, requireDigest: true, runningOS: running)
}
XCTAssertEqual(try attempt(os(15, 5)).failure, .needsNewerMacOS("26.6"))
- XCTAssertEqual(BuildModel.StageFailure.needsNewerMacOS("26.6").key, "app.needsNewerMacOS")
+ XCTAssertEqual(AppUpdate.StageFailure.needsNewerMacOS("26.6").key, "app.needsNewerMacOS")
XCTAssertNil(try attempt(os(26, 6)).failure)
}
@@ -145,7 +143,7 @@ final class AppUpdateTests: XCTestCase {
let release = AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/NX2Apple-macOS-arm64.zip", digest: try digest(archive))
let root = temporary.appendingPathComponent("stage-ok", isDirectory: true)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
- let staged = try BuildModel.stage(zip: archive, release: release, in: root, expectedID: bundleID, requireDigest: true).get()
+ let staged = try AppUpdate.stage(zip: archive, release: release, in: root, expectedID: bundleID, requireDigest: true).get()
XCTAssertEqual(staged.release, release)
XCTAssertEqual(staged.app.lastPathComponent, "NX2Apple.app")
XCTAssertEqual(try marker(staged.app), "new")
@@ -153,13 +151,13 @@ final class AppUpdateTests: XCTestCase {
func testStagingRefusesMismatchMissingDigestAndWrongApp() throws {
let source = temporary.appendingPathComponent("source", isDirectory: true)
- func attempt(_ digest: String?, automatic: Bool, id: String? = nil) throws -> Result<AppUpdate.Staged, BuildModel.StageFailure> {
+ func attempt(_ digest: String?, automatic: Bool, id: String? = nil) throws -> Result<AppUpdate.Staged, AppUpdate.StageFailure> {
let dir = source.appendingPathComponent(UUID().uuidString)
let archive = try zip(try makeApp(in: dir, id: id))
let root = temporary.appendingPathComponent("stage-" + UUID().uuidString, isDirectory: true)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
let release = AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/a.zip", digest: digest == "self" ? try self.digest(archive) : digest)
- return BuildModel.stage(zip: archive, release: release, in: root, expectedID: bundleID, requireDigest: automatic)
+ return AppUpdate.stage(zip: archive, release: release, in: root, expectedID: bundleID, requireDigest: automatic)
}
let wrong = "sha256:" + String(repeating: "0", count: 64)
XCTAssertEqual(try attempt(wrong, automatic: true).failure, .mismatch)
@@ -208,10 +206,10 @@ final class AppUpdateTests: XCTestCase {
["name": "nxnative-macOS-arm64.zip", "browser_download_url": "https://example.invalid/old.zip", "digest": "sha256:aa"],
["name": "NX2Apple-macOS-arm64.zip", "browser_download_url": "https://example.invalid/new.zip", "digest": "sha256:bb"],
]]
- XCTAssertEqual(BuildModel.appRelease(fromJSON: json), AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/new.zip", digest: "sha256:bb"))
+ XCTAssertEqual(AppUpdate.release(fromJSON: json), AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/new.zip", digest: "sha256:bb"))
let legacy: [String: Any] = ["tag_name": "v0.4.8", "assets": [["name": "NS-Port-Builder-macOS-arm64.zip", "browser_download_url": "https://example.invalid/legacy.zip"]]]
- XCTAssertEqual(BuildModel.appRelease(fromJSON: legacy)?.digest, nil)
- XCTAssertNil(BuildModel.appRelease(fromJSON: ["tag_name": "v0.4.8", "assets": []]))
+ XCTAssertEqual(AppUpdate.release(fromJSON: legacy)?.digest, nil)
+ XCTAssertNil(AppUpdate.release(fromJSON: ["tag_name": "v0.4.8", "assets": []]))
}
// ---- when ----
@@ -267,32 +265,6 @@ final class AppUpdateTests: XCTestCase {
XCTAssertEqual(try marker(current), "old")
}
- func testModelWaitsForTheBuild() throws {
- let current = try makeApp("Current", in: temporary.appendingPathComponent("Applications"), marker: "old")
- let staged = try makeApp("Staged", in: temporary.appendingPathComponent("staged"), marker: "new")
- let model = BuildModel()
- model.lang = .en
- model.appInstallability = .ok
- model.appStaged = AppUpdate.Staged(release: AppUpdate.Release(tag: "v0.4.8", url: "", digest: nil), app: staged)
- model.running = true
- XCTAssertFalse(model.mayInstallAppUpdate)
- XCTAssertFalse(model.installStagedUpdate(relaunch: false, at: current))
- model.restartToUpdate() // refused before it gets as far as a relaunch
- XCTAssertEqual(try marker(current), "old")
- XCTAssertNotNil(model.appStaged) // still waiting for the quit
- XCTAssertEqual(model.appStatus, L10n.string("app.waitForBuild", .en))
- }
-
- func testDeveloperModelNeverInstalls() throws {
- let current = try makeApp("Current", in: temporary.appendingPathComponent("Applications"), marker: "old")
- let staged = try makeApp("Staged", in: temporary.appendingPathComponent("staged"), marker: "new")
- let model = BuildModel()
- model.appInstallability = .developer
- model.appStaged = AppUpdate.Staged(release: AppUpdate.Release(tag: "v0.4.8", url: "", digest: nil), app: staged)
- XCTAssertFalse(model.installStagedUpdate(relaunch: false, at: current))
- XCTAssertEqual(try marker(current), "old")
- }
-
func testEveryUpdateStringHasBothLanguages() {
for key in ["app.staging", "app.ready", "app.restartNow", "app.waitForBuild", "app.stageNetFail", "app.noDigest",
"app.digestMismatch", "app.unpackFail", "app.notOurApp", "app.devBuild", "app.readOnly", "app.auto",
@@ -374,17 +346,17 @@ private extension Result {
/// date" leaves that install stuck for ever.
final class UpdateCheckTests: XCTestCase {
func testAVersionComparisonReadsTheNumbers() {
- XCTAssertTrue(BuildModel.isNewer("v0.4.8", than: "0.4.6"))
- XCTAssertTrue(BuildModel.isNewer("v0.4.10", than: "0.4.8"), "0.4.10 is newer than 0.4.8, not older")
- XCTAssertFalse(BuildModel.isNewer("v0.4.8", than: "0.4.8"))
- XCTAssertFalse(BuildModel.isNewer("v0.4.6", than: "0.4.8"))
+ XCTAssertTrue(AppUpdate.isNewer("v0.4.8", than: "0.4.6"))
+ XCTAssertTrue(AppUpdate.isNewer("v0.4.10", than: "0.4.8"), "0.4.10 is newer than 0.4.8, not older")
+ XCTAssertFalse(AppUpdate.isNewer("v0.4.8", than: "0.4.8"))
+ XCTAssertFalse(AppUpdate.isNewer("v0.4.6", than: "0.4.8"))
}
/// The asset names this app will accept, oldest first. A release that carries any of them can
/// update every install back to 0.4.5; one that carries none leaves those installs stuck, which
- /// is why checkAppUpdate has to say so rather than report "up to date".
+ /// is why the check has to say so rather than report "up to date".
func testTheAssetNamesCoverEveryInstallThatCanStillUpdate() {
- let names = BuildModel.appAssetNames
+ let names = AppUpdate.assetNames
XCTAssertTrue(names.contains("NX2Apple-macOS-arm64.zip"), "the current name")
XCTAssertTrue(names.contains("nxnative-macOS-arm64.zip"), "installs from before the rename to NX2Apple")
XCTAssertTrue(names.contains("NS-Port-Builder-macOS-arm64.zip"), "installs from before the rename to nxnative")
diff --git a/frontend/Tests/NX2AppleTests/UninstallTests.swift b/frontend/Tests/NXCoreTests/UninstallTests.swift
similarity index 99%
rename from frontend/Tests/NX2AppleTests/UninstallTests.swift
rename to frontend/Tests/NXCoreTests/UninstallTests.swift
index d130d216..9d014f04 100644
--- a/frontend/Tests/NX2AppleTests/UninstallTests.swift
+++ b/frontend/Tests/NXCoreTests/UninstallTests.swift
@@ -1,7 +1,5 @@
import XCTest
-@testable import NX2Apple
@testable import NXCore
-@testable import NXLauncher
/// The uninstall plan (Uninstall.swift): what goes, what stays. The removal runs in a temporary folder,
/// so the real state and checkout are never touched.
diff --git a/frontend/Tests/NXModelTests/AppUpdateStoreTests.swift b/frontend/Tests/NXModelTests/AppUpdateStoreTests.swift
new file mode 100644
index 00000000..a8ce1591
--- /dev/null
+++ b/frontend/Tests/NXModelTests/AppUpdateStoreTests.swift
@@ -0,0 +1,329 @@
+import XCTest
+import CryptoKit
+@testable import NXModel
+@testable import NXCore
+
+/// `AppUpdateStore` without SwiftUI: a fake `ProcessRunner` stands in for ditto and xattr, a fake `ReleaseSource` for GitHub, and the
+/// bundles are folders in a temporary directory. This is the pattern for the tests of a store (frontend/ARCHITECTURE.md).
+@MainActor final class AppUpdateStoreTests: XCTestCase {
+ private var temporary: URL!
+ private var suite: String!
+ private var defaults: UserDefaults!
+ private let runner = FakeProcessRunner()
+ private let source = FakeReleaseSource()
+ private let bundleID = "org.nxnative.NSPortBuilder"
+ private let zipData = Data("zip".utf8)
+
+ override func setUpWithError() throws {
+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxmodel-update-tests-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
+ suite = "nxmodel-update-tests-" + UUID().uuidString
+ defaults = UserDefaults(suiteName: suite)
+ // ditto: the fake unpacks a launcher bundle of the version the test names (its tag without the "v") into the last argument
+ runner.answer = { [bundleID] launch in
+ guard launch.executable.hasSuffix("ditto"), let dir = launch.arguments.last else { return ProcessResult() }
+ let macOS = URL(fileURLWithPath: dir).appendingPathComponent("NX2Apple.app/Contents/MacOS")
+ try? FileManager.default.createDirectory(at: macOS, withIntermediateDirectories: true)
+ let exe = macOS.appendingPathComponent("NSPortBuilder")
+ try? Data("new".utf8).write(to: exe)
+ try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: exe.path)
+ let info: [String: Any] = ["CFBundleIdentifier": bundleID, "CFBundleExecutable": "NSPortBuilder", "CFBundleShortVersionString": "0.4.8"]
+ try? (try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0))
+ .write(to: URL(fileURLWithPath: dir).appendingPathComponent("NX2Apple.app/Contents/Info.plist"))
+ return ProcessResult()
+ }
+ }
+
+ override func tearDownWithError() throws {
+ try FileManager.default.removeItem(at: temporary)
+ defaults.removePersistentDomain(forName: suite)
+ }
+
+ private func digest(_ data: Data) -> String { "sha256:" + SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }
+
+ private func makeStore(_ installability: AppUpdate.Installability = .ok, automatic: Bool = false, version: String = "0.4.6",
+ buildRunning: @escaping () -> Bool = { false }, relaunch: @escaping (URL) -> Bool = { _ in true },
+ terminate: @escaping () -> Void = {},
+ uninstall: @escaping (Uninstall.Plan) -> (removed: [String], failures: [String]) = { _ in ([], []) }) -> AppUpdateStore {
+ defaults.set(automatic, forKey: AppUpdateStore.automaticKey)
+ let store = AppUpdateStore(localizer: Localizer(.en), runner: runner, releases: source, version: version,
+ bundle: temporary.appendingPathComponent("Applications/NX2Apple.app"), bundleIdentifier: bundleID,
+ defaults: defaults, buildRunning: buildRunning, relaunch: relaunch, terminate: terminate,
+ uninstall: uninstall, trashOldApp: false)
+ store.installability = installability
+ return store
+ }
+
+ private func text(_ key: String, _ args: CVarArg...) -> String { String(format: L10n.string(key, .en), arguments: args) }
+
+ /// A launcher bundle in the folder, as the release workflow assembles it.
+ private func makeApp(_ name: String, in dir: URL, marker: String) throws -> URL {
+ let app = dir.appendingPathComponent(name + ".app")
+ let macOS = app.appendingPathComponent("Contents/MacOS")
+ try FileManager.default.createDirectory(at: macOS, withIntermediateDirectories: true)
+ try Data(marker.utf8).write(to: macOS.appendingPathComponent("NSPortBuilder"))
+ return app
+ }
+
+ private func marker(_ app: URL) throws -> String {
+ String(decoding: try Data(contentsOf: app.appendingPathComponent("Contents/MacOS/NSPortBuilder")), as: UTF8.self)
+ }
+
+ // ---- The version ----
+
+ func testTheVersionIsAReleaseVersion() {
+ XCTAssertTrue(AppUpdate.isReleaseVersion(AppUpdateStore.appVersion))
+ XCTAssertEqual(makeStore().version, "0.4.6")
+ XCTAssertEqual(AppUpdateStore(localizer: Localizer(.en), runner: runner, releases: source).version, AppUpdateStore.appVersion)
+ }
+
+ // ---- The check ----
+
+ func testAFoundReleaseIsOfferedInTheSheetAndWaitsForTheButton() async {
+ source.latest = FakeReleaseSource.release(tag: "v0.4.8", digest: "sha256:aa", notes: "What changed")
+ let store = makeStore()
+ await store.checkForUpdate().value
+ XCTAssertEqual(store.update, AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/NX2Apple-macOS-arm64.zip", digest: "sha256:aa", notes: "What changed"))
+ XCTAssertEqual(store.status, text("app.found", "v0.4.8"))
+ XCTAssertTrue(store.showUpdateSheet)
+ XCTAssertFalse(store.busy)
+ XCTAssertTrue(source.downloads.isEmpty, "with automatic updates off nothing is downloaded before the button")
+ XCTAssertNil(store.staged)
+ }
+
+ func testADeveloperBuildOnlySaysThatAReleaseExists() async {
+ source.latest = FakeReleaseSource.release(tag: "v0.4.8")
+ let store = makeStore(.developer, automatic: true)
+ await store.checkForUpdate().value
+ XCTAssertEqual(store.update?.tag, "v0.4.8")
+ XCTAssertEqual(store.status, text("app.devBuild", "v0.4.8"))
+ XCTAssertFalse(store.showUpdateSheet)
+ XCTAssertTrue(source.downloads.isEmpty)
+ }
+
+ func testAReadOnlyCopySaysSo() async {
+ source.latest = FakeReleaseSource.release(tag: "v0.4.8")
+ let store = makeStore(.readOnly)
+ await store.checkForUpdate().value
+ XCTAssertEqual(store.status, text("app.readOnly", "v0.4.8"))
+ }
+
+ func testTheCurrentVersionIsUpToDateAndSilentStaysQuiet() async {
+ source.latest = FakeReleaseSource.release(tag: "v0.4.6")
+ let store = makeStore()
+ await store.checkForUpdate(silent: true).value
+ XCTAssertEqual(store.status, "")
+ XCTAssertNil(store.update)
+ await store.checkForUpdate().value
+ XCTAssertEqual(store.status, text("app.upToDate"))
+ XCTAssertFalse(store.showUpdateSheet)
+ }
+
+ func testNoAnswerIsNotUpToDate() async {
+ let store = makeStore()
+ await store.checkForUpdate(silent: true).value
+ XCTAssertEqual(store.status, "")
+ await store.checkForUpdate().value
+ XCTAssertEqual(store.status, text("app.netFail"))
+ XCTAssertFalse(store.busy)
+ }
+
+ func testANewerReleaseWithoutOurDownloadIsNotUpToDate() async {
+ source.latest = FakeReleaseSource.release(tag: "v0.4.8", asset: "Something-else.zip")
+ let store = makeStore()
+ await store.checkForUpdate(silent: true).value
+ XCTAssertEqual(store.status, "")
+ await store.checkForUpdate().value
+ XCTAssertEqual(store.status, text("app.noAsset", "v0.4.8"))
+ XCTAssertNil(store.update)
+ }
+
+ func testACheckWhileOneRunsDoesNothing() async {
+ source.latest = FakeReleaseSource.release(tag: "v0.4.8")
+ let store = makeStore()
+ let first = store.checkForUpdate()
+ XCTAssertTrue(store.busy)
+ await store.checkForUpdate().value
+ await first.value
+ XCTAssertEqual(source.latestCalls, 1)
+ }
+
+ // ---- Staging ----
+
+ func testAutomaticUpdatesDownloadVerifyAndStageAFoundRelease() async throws {
+ source.latest = FakeReleaseSource.release(tag: "v0.4.8", digest: digest(zipData))
+ let store = makeStore(automatic: true)
+ await store.checkForUpdate().value
+ XCTAssertTrue(store.busy, "the download starts right behind the check")
+ XCTAssertEqual(store.status, text("app.staging", "v0.4.8"))
+ XCTAssertTrue(store.showUpdateSheet)
+ while store.busy { await Task.yield() }
+ XCTAssertEqual(source.downloads.map(\.lastPathComponent), ["NX2Apple-macOS-arm64.zip"])
+ XCTAssertEqual(store.staged?.release.tag, "v0.4.8")
+ XCTAssertEqual(store.staged?.app.lastPathComponent, "NX2Apple.app")
+ XCTAssertEqual(store.status, text("app.ready", "v0.4.8"))
+ XCTAssertNil(store.blocked)
+ XCTAssertTrue(runner.commands.first?.hasPrefix("ditto -x -k ") == true, "\(runner.commands)")
+ }
+
+ func testAChosenUpdateWithoutADigestIsStagedByHandButNotAutomatically() async {
+ let release = AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/NX2Apple-macOS-arm64.zip", digest: nil)
+ let store = makeStore()
+ await store.stage(release, automatic: true).value
+ XCTAssertNil(store.staged)
+ XCTAssertEqual(store.blocked, text("app.noDigest", "v0.4.8"))
+ await store.stage(release, automatic: false).value
+ XCTAssertEqual(store.staged?.release, release)
+ XCTAssertNil(store.blocked, "a new attempt clears the refusal")
+ }
+
+ func testADigestThatDoesNotMatchIsRefused() async {
+ let release = AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/a.zip", digest: "sha256:" + String(repeating: "0", count: 64))
+ let store = makeStore()
+ await store.stage(release, automatic: false).value
+ XCTAssertNil(store.staged)
+ XCTAssertEqual(store.status, text("app.digestMismatch", "v0.4.8"))
+ XCTAssertEqual(store.blocked, store.status)
+ XCTAssertFalse(store.busy)
+ }
+
+ func testADownloadThatFailsIsANetworkFailure() async {
+ source.file = nil
+ let release = AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/a.zip", digest: nil)
+ let store = makeStore()
+ await store.stage(release, automatic: false).value
+ XCTAssertEqual(store.status, text("app.stageNetFail", "v0.4.8"))
+ XCTAssertEqual(store.blocked, store.status)
+ XCTAssertTrue(runner.launches.isEmpty, "nothing to unpack")
+ }
+
+ func testOnlyAReleasedCopyStages() async {
+ let release = AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/a.zip", digest: nil)
+ for kind in [AppUpdate.Installability.developer, .readOnly] {
+ let store = makeStore(kind)
+ await store.stage(release, automatic: false).value
+ XCTAssertTrue(source.downloads.isEmpty)
+ XCTAssertNil(store.staged)
+ }
+ }
+
+ func testTurningAutomaticOnStagesTheKnownReleaseAndIsSaved() async {
+ let release = AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/a.zip", digest: nil)
+ let store = makeStore(automatic: false)
+ store.update = release
+ store.automatic = true
+ XCTAssertTrue(store.busy)
+ XCTAssertEqual(defaults.object(forKey: AppUpdateStore.automaticKey) as? Bool, true)
+ while store.busy { await Task.yield() }
+ // automatic refuses a release without a digest, and says so
+ XCTAssertNil(store.staged)
+ XCTAssertEqual(store.blocked, text("app.noDigest", "v0.4.8"))
+ store.automatic = false
+ XCTAssertEqual(defaults.object(forKey: AppUpdateStore.automaticKey) as? Bool, false)
+ }
+
+ // ---- Installing ----
+
+ private func stagedStore(_ installability: AppUpdate.Installability = .ok, buildRunning: @escaping () -> Bool = { false },
+ relaunch: @escaping (URL) -> Bool = { _ in true }, terminate: @escaping () -> Void = {},
+ automatic: Bool = true) throws -> (AppUpdateStore, current: URL) {
+ let current = try makeApp("NX2Apple", in: temporary.appendingPathComponent("Applications"), marker: "old")
+ let staged = try makeApp("NX2Apple", in: temporary.appendingPathComponent("staged"), marker: "new")
+ let store = makeStore(installability, automatic: automatic, buildRunning: buildRunning, relaunch: relaunch, terminate: terminate)
+ store.staged = AppUpdate.Staged(release: AppUpdate.Release(tag: "v0.4.8", url: "", digest: nil), app: staged)
+ return (store, current)
+ }
+
+ func testTheStoreWaitsForTheBuild() throws {
+ let (store, current) = try stagedStore(buildRunning: { true })
+ XCTAssertFalse(store.mayInstall)
+ XCTAssertFalse(store.install(relaunch: false, at: current))
+ store.restartNow() // refused before it gets as far as a relaunch
+ XCTAssertEqual(try marker(current), "old")
+ XCTAssertNotNil(store.staged, "still waiting for the quit")
+ XCTAssertEqual(store.status, text("app.waitForBuild"))
+ store.appWillTerminate()
+ XCTAssertEqual(try marker(current), "old", "quitting during a build leaves the swap for a later quit")
+ }
+
+ func testADeveloperCopyNeverInstalls() throws {
+ let (store, current) = try stagedStore(.developer)
+ XCTAssertFalse(store.install(relaunch: false, at: current))
+ XCTAssertEqual(try marker(current), "old")
+ }
+
+ func testRestartNowSwapsInRelaunchesAndQuits() throws {
+ var relaunched: URL?
+ var quit = 0
+ let (store, current) = try stagedStore(relaunch: { relaunched = $0; return true }, terminate: { quit += 1 })
+ XCTAssertTrue(store.install(relaunch: true, at: current))
+ XCTAssertEqual(try marker(current), "new")
+ XCTAssertNil(store.staged)
+ XCTAssertEqual(relaunched, current)
+ XCTAssertEqual(quit, 1)
+ XCTAssertEqual(store.status, text("app.relaunching", "v0.4.8"))
+ XCTAssertTrue(runner.commands.contains { $0.hasPrefix("xattr -dr com.apple.quarantine ") }, "the new copy loses the quarantine flag")
+ }
+
+ func testAFailedRelaunchSaysSoAndDoesNotQuit() throws {
+ var quit = 0
+ let (store, current) = try stagedStore(relaunch: { _ in false }, terminate: { quit += 1 })
+ XCTAssertTrue(store.install(relaunch: true, at: current))
+ XCTAssertEqual(quit, 0)
+ XCTAssertEqual(store.status, text("app.relaunchFail", "v0.4.8"))
+ }
+
+ func testTheStagedUpdateGoesInWhenTheAppQuitsWithAutomaticOn() throws {
+ var quit = 0
+ let (store, current) = try stagedStore(terminate: { quit += 1 })
+ store.appWillTerminate()
+ XCTAssertEqual(try marker(current), "new")
+ XCTAssertNil(store.staged)
+ XCTAssertEqual(quit, 0, "quitting never relaunches")
+ }
+
+ func testTheStagedUpdateWaitsForTheQuitWithAutomaticOff() throws {
+ let (store, current) = try stagedStore(automatic: false)
+ store.appWillTerminate()
+ XCTAssertNotNil(store.staged)
+ XCTAssertEqual(try marker(current), "old")
+ }
+
+ func testTheUpdateButtonInstallsAStagedCopyOfTheSameRelease() throws {
+ var quit = 0
+ let (store, current) = try stagedStore(terminate: { quit += 1 })
+ store.update = store.staged?.release
+ store.performUpdate()
+ XCTAssertEqual(try marker(current), "new", "it goes in over the store's own bundle")
+ XCTAssertEqual(quit, 1)
+ XCTAssertTrue(source.downloads.isEmpty, "nothing is downloaded twice")
+ }
+
+ // ---- Uninstall ----
+
+ func testConfirmingTheUninstallRunsThePlanAndSaysWhatWent() {
+ var ran: Uninstall.Plan?
+ let store = makeStore(uninstall: { ran = $0; return (["a", "b"], []) })
+ let plan = Uninstall.Plan(stateFolders: ["/x"], app: "/Applications/NX2Apple.app")
+ store.uninstallPlan = plan
+ store.confirmUninstall()
+ XCTAssertEqual(ran, plan)
+ XCTAssertNil(store.uninstallPlan)
+ XCTAssertEqual(store.status, text("uninstall.done", 2))
+ }
+
+ func testAnUninstallThatFailsListsWhatFailed() {
+ let store = makeStore(uninstall: { _ in ([], ["/x: in use"]) })
+ store.uninstallPlan = Uninstall.Plan(stateFolders: ["/x"])
+ store.confirmUninstall()
+ XCTAssertEqual(store.status, L10n.string("uninstall.failed", .en) + "\n/x: in use")
+ }
+
+ func testConfirmingWithoutAPlanDoesNothing() {
+ var ran = 0
+ let store = makeStore(uninstall: { _ in ran += 1; return ([], []) })
+ store.confirmUninstall()
+ XCTAssertEqual(ran, 0)
+ XCTAssertEqual(store.status, "")
+ }
+}
diff --git a/frontend/Tests/NXModelTests/Fakes.swift b/frontend/Tests/NXModelTests/Fakes.swift
new file mode 100644
index 00000000..a83f9cb4
--- /dev/null
+++ b/frontend/Tests/NXModelTests/Fakes.swift
@@ -0,0 +1,60 @@
+import Foundation
+import NXCore
+
+/// A `ProcessRunner` that starts nothing: it records what it was asked to run and answers from a script.
+final class FakeProcessRunner: ProcessRunner, @unchecked Sendable {
+ private let lock = NSLock()
+ private var recorded: [ProcessLaunch] = []
+ /// The answer for a launch. The default is a run that exits 0 and prints nothing.
+ var answer: (ProcessLaunch) -> ProcessResult = { _ in ProcessResult() }
+
+ var launches: [ProcessLaunch] { lock.lock(); defer { lock.unlock() }; return recorded }
+ /// Each launch as one line: the tool's name and its arguments.
+ var commands: [String] { launches.map { ([($0.executable as NSString).lastPathComponent] + $0.arguments).joined(separator: " ") } }
+
+ func capture(_ launch: ProcessLaunch) -> ProcessResult {
+ lock.lock(); recorded.append(launch); lock.unlock()
+ return answer(launch)
+ }
+
+ func stream(_ launch: ProcessLaunch, line: @escaping (String) -> Void) -> Bool {
+ lock.lock(); recorded.append(launch); lock.unlock()
+ return true
+ }
+
+ func start(_ launch: ProcessLaunch, onOutput: @escaping (Data) -> Void, onExit: @escaping (Int32) -> Void) throws -> RunningProcess {
+ throw CocoaError(.fileNoSuchFile)
+ }
+}
+
+/// A `ReleaseSource` without a network: the latest release and the downloads come from what the test sets.
+final class FakeReleaseSource: ReleaseSource, @unchecked Sendable {
+ private let lock = NSLock()
+ private var downloaded: [URL] = []
+ private var asked = 0
+ /// What the "latest release" call answers. nil: no answer.
+ var latest: Data?
+ /// What a download writes. nil: the download fails.
+ var file: Data? = Data("zip".utf8)
+
+ var downloads: [URL] { lock.lock(); defer { lock.unlock() }; return downloaded }
+ var latestCalls: Int { lock.lock(); defer { lock.unlock() }; return asked }
+
+ func latestRelease() async -> Data? {
+ lock.withLock { asked += 1 }
+ return latest
+ }
+
+ func download(_ url: URL, to file: URL) async -> Bool {
+ lock.withLock { downloaded.append(url) }
+ guard let data = self.file else { return false }
+ return (try? data.write(to: file)) != nil
+ }
+
+ /// The JSON GitHub gives for a release with the asset this app installs.
+ static func release(tag: String, digest: String? = nil, notes: String = "", asset: String = "NX2Apple-macOS-arm64.zip") -> Data {
+ var a: [String: Any] = ["name": asset, "browser_download_url": "https://example.invalid/\(asset)"]
+ if let digest { a["digest"] = digest }
+ return try! JSONSerialization.data(withJSONObject: ["tag_name": tag, "body": notes, "assets": [a]])
+ }
+}
diff --git a/tools/tests/test_app_version.py b/tools/tests/test_app_version.py
new file mode 100644
index 00000000..3335642d
--- /dev/null
+++ b/tools/tests/test_app_version.py
@@ -0,0 +1,57 @@
+"""`appVersion`: the one line that says which release the launcher is, and everything that reads it by path.
+
+The line is `static let appVersion = "x.y.z"` in frontend/Sources/NXModel/AppUpdateStore.swift (LNPANDY/NX2Apple#387). The release
+workflow, the engine sync workflow, tools/try-local and RELEASING.md read it there. When the line moves, a reader that still names the
+old file breaks the release build, so this test finds every reader and checks that it names a file that holds the line."""
+import re
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+LINE = re.compile(r'static let appVersion = "(\d+(?:\.\d+)+)"')
+READERS = [
+ '.github/workflows/build-mac-app.yml',
+ '.github/workflows/sync-upstream.yml',
+ 'tools/try-local',
+ 'tools/tests/test_try_local.py',
+ 'RELEASING.md',
+]
+
+
+def swift_paths(text):
+ """The Swift files named on the lines that read appVersion."""
+ return {path for line in text.splitlines() if 'appVersion' in line
+ for path in re.findall(r'frontend/Sources/[A-Za-z0-9_/]+\.swift', line)}
+
+
+class AppVersion(unittest.TestCase):
+ def test_exactly_one_swift_file_holds_the_line(self):
+ holders = [p for p in (ROOT / 'frontend/Sources').rglob('*.swift') if LINE.search(p.read_text())]
+ self.assertEqual([p.relative_to(ROOT).as_posix() for p in holders], ['frontend/Sources/NXModel/AppUpdateStore.swift'])
+
+ def test_every_reader_names_a_file_that_holds_it(self):
+ for name in READERS:
+ paths = swift_paths((ROOT / name).read_text())
+ self.assertTrue(paths, f'{name} names no Swift file for appVersion')
+ for rel in paths:
+ self.assertTrue((ROOT / rel).is_file(), f'{name} reads appVersion in {rel}, which does not exist')
+ self.assertRegex((ROOT / rel).read_text(), LINE, f'{name} reads appVersion in {rel}, which has no such line')
+
+ def test_no_other_file_reads_it_by_path(self):
+ # Anything that reads the version with sed or a regex is a reader: it must be in the list above, or it can break unseen.
+ found = set()
+ for base in ('.github', 'tools', 'frontend/tools', 'RELEASING.md', 'AGENTS.md', 'CONTRIBUTING.md'):
+ path = ROOT / base
+ files = [path] if path.is_file() else [p for p in path.rglob('*') if p.is_file()] if path.exists() else []
+ for f in files:
+ try:
+ text = f.read_text()
+ except UnicodeDecodeError:
+ continue
+ if 'static let appVersion' in text and f.name != Path(__file__).name:
+ found.add(f.relative_to(ROOT).as_posix())
+ self.assertEqual(found - set(READERS), set(), 'a new reader of appVersion: add it to READERS in tools/tests/test_app_version.py')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/tests/test_try_local.py b/tools/tests/test_try_local.py
index 6f9f7472..8286bb4f 100644
--- a/tools/tests/test_try_local.py
+++ b/tools/tests/test_try_local.py
@@ -21,7 +21,7 @@ def plist_keys(text):
class TryLocal(unittest.TestCase):
def test_version_is_app_version_plus_local(self):
- src = re.search(r'static let appVersion = "(.*)"', (ROOT / 'frontend/Sources/NX2Apple/ContentView.swift').read_text()).group(1)
+ src = re.search(r'static let appVersion = "(.*)"', (ROOT / 'frontend/Sources/NXModel/AppUpdateStore.swift').read_text()).group(1)
self.assertEqual(run('--print-version'), src + '-local')
def test_cache_key_follows_the_script_and_its_pins(self):
diff --git a/tools/try-local b/tools/try-local
index 87269df4..153bfc9e 100755
--- a/tools/try-local
+++ b/tools/try-local
@@ -40,8 +40,8 @@ cache_key() { # the bundled tools depend on the script, its pins file and the
}
app_version() {
local src
- src=$(sed -n 's/.*static let appVersion = "\(.*\)".*/\1/p' "$ROOT/frontend/Sources/NX2Apple/ContentView.swift")
- [ -n "$src" ] || die "no appVersion in ContentView.swift"
+ src=$(sed -n 's/.*static let appVersion = "\(.*\)".*/\1/p' "$ROOT/frontend/Sources/NXModel/AppUpdateStore.swift")
+ [ -n "$src" ] || die "no appVersion in AppUpdateStore.swift"
echo "$src-local"
}