Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Launcher: install app updates by itself, when it quits and never during a build
v0lumehi060b9f516c1d
diff --git a/frontend/README.md b/frontend/README.mdindex 5a1cfcb9..8fc1ad06 100644--- a/frontend/README.md+++ b/frontend/README.md@@ -119,6 +119,26 @@ installed and no resource bundle beside the executable.The app icon is drawn by `make_icon.swift`; `./make_icon.sh` writes `icon.iconset/`and `AppIcon.icns` from it.+## App updates++When the app opens it asks GitHub for the latest release. With **Install updates+automatically** on (Settings → App, the default), a newer release is downloaded in+the background and staged: the zip's SHA-256 must match the `digest` GitHub gives+for the asset (a release without one is not installed automatically), and the app+inside must carry this app's bundle identifier, an executable and the release's+version. The staged copy replaces the app when you quit it, so the next launch is+the new version; **Restart now** in Settings and in the library's bottom line+installs it at once. Neither runs while a build does: the swap ends with a relaunch,+which would end the build's process group. If you quit during a build, the build is+stopped as before and the update waits for a later quit. With the switch off,+**Update to vX** in Settings downloads, verifies and relaunches as before (a+release without a digest is still accepted there; a wrong digest never is).++A launcher built from this repository never replaces itself: `swift run` (no+bundle), a bundle under `.build/` or `DerivedData/`, a bundle beside+`Package.swift` (the `NX2Apple.app` made here), or one whose Info.plist version+is not this binary's release number. `AppUpdate.swift` holds these rules.+## Run```bashdiff --git a/frontend/Sources/NSPortBuilder/AppUpdate.swift b/frontend/Sources/NSPortBuilder/AppUpdate.swiftnew file mode 100644index 00000000..da2e72ec--- /dev/null+++ b/frontend/Sources/NSPortBuilder/AppUpdate.swift@@ -0,0 +1,149 @@+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 rules:+// - What is installed is what GitHub says the release is: the zip's SHA-256 matches the asset's `digest`+// ("sha256:<hex>", in the release API since 2025), and the app inside it carries the running app's bundle+// identifier, an executable and the release's version. An automatic install also needs the digest to be+// there; the Update button, pressed by hand, still installs a release without one (older releases have none).+// - Only a released copy replaces itself: a launcher built from the repository (swift run, a bundle assembled in+// frontend/, an Xcode build) keeps the developer's build in place.+// - Never while a build runs: the swap ends with a relaunch (exit), and a build is a process group of the app's.++enum AppUpdate {+ /// The latest release, as the check found it.+ struct Release: Equatable {+ let tag: String+ let url: String+ let digest: String? // "sha256:<hex>"; nil when the API gave none+ }++ /// A release downloaded, verified and unpacked, waiting to be swapped in.+ struct Staged: Equatable {+ let release: Release+ let app: URL+ }++ // ---- What was downloaded ----++ enum DigestCheck: Equatable { case match, mismatch, missing }++ /// The SHA-256 of a file, as lowercase hex, read in pieces (the zip is tens of megabytes).+ static func sha256(of file: URL) -> String? {+ guard let handle = try? FileHandle(forReadingFrom: file) else { return nil }+ defer { try? handle.close() }+ var hasher = SHA256()+ while true {+ let chunk = handle.readData(ofLength: 1 << 20)+ if chunk.isEmpty { break }+ hasher.update(data: chunk)+ }+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()+ }++ /// The file against the asset's digest. A digest in any other algorithm, or none, counts as missing: there is+ /// nothing to compare with, which an automatic install refuses.+ static func checkDigest(_ file: URL, expected: String?) -> DigestCheck {+ guard let expected, expected.lowercased().hasPrefix("sha256:") else { return .missing }+ let want = expected.dropFirst("sha256:".count).trimmingCharacters(in: .whitespaces).lowercased()+ guard want.count == 64, let have = sha256(of: file) else { return want.isEmpty ? .missing : .mismatch }+ return have == want ? .match : .mismatch+ }++ enum BundleProblem: Error, Equatable { case noInfo, wrongIdentifier, noExecutable, wrongVersion }++ /// Whether `app` is an NX2Apple launcher of the release `tag`: the running app's bundle identifier (a zip of+ /// something else must not take its place), an executable where its Info.plist says, and the release's version+ /// (the release workflow writes the tag into the plist; another number would be a different build).+ static func bundleProblem(_ app: URL, expectedID: String, tag: String) -> BundleProblem? {+ let contents = app.appendingPathComponent("Contents")+ guard let data = try? Data(contentsOf: contents.appendingPathComponent("Info.plist")),+ let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]+ else { return .noInfo }+ guard !expectedID.isEmpty, info["CFBundleIdentifier"] as? String == expectedID else { return .wrongIdentifier }+ guard let exe = info["CFBundleExecutable"] as? String, !exe.isEmpty, !exe.contains("/"),+ FileManager.default.isExecutableFile(atPath: contents.appendingPathComponent("MacOS/" + exe).path)+ else { return .noExecutable }+ let version = tag.hasPrefix("v") ? String(tag.dropFirst()) : tag+ guard info["CFBundleShortVersionString"] as? String == version else { return .wrongVersion }+ return nil+ }++ // ---- What may replace itself ----++ enum Installability: Equatable {+ case ok+ case developer // built from the repository: never replaces itself+ case readOnly // a released copy that cannot be replaced where it is (translocated, or a folder without write access)+ }++ /// Whether the launcher at `bundle` may replace itself. A released copy is an `.app` whose Info.plist has a bundle+ /// identifier and, as its version, this binary's own release number (the release workflow stops when the two+ /// differ), and which is not where a developer's build sits: in SwiftPM's .build, Xcode's DerivedData, or beside+ /// the Package.swift it was built from (frontend/NX2Apple.app, which the README's own recipe makes). `swift run`+ /// runs a bare executable with no bundle at all.+ static func installability(_ bundle: URL, appVersion: String) -> Installability {+ let path = bundle.standardizedFileURL.path+ guard bundle.pathExtension == "app" else { return .developer }+ let parts = bundle.standardizedFileURL.pathComponents+ if parts.contains(".build") || parts.contains("DerivedData") { return .developer }+ let parent = bundle.standardizedFileURL.deletingLastPathComponent()+ if FileManager.default.fileExists(atPath: parent.appendingPathComponent("Package.swift").path) { return .developer }+ guard isReleaseVersion(appVersion),+ let data = try? Data(contentsOf: bundle.appendingPathComponent("Contents/Info.plist")),+ let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],+ let id = info["CFBundleIdentifier"] as? String, !id.isEmpty,+ info["CFBundleShortVersionString"] as? String == appVersion+ else { return .developer }+ // Gatekeeper runs a quarantined app opened from Downloads from a read-only copy: the swap cannot reach the real one+ if path.contains("/AppTranslocation/") { return .readOnly }+ if !FileManager.default.isWritableFile(atPath: parent.path) { return .readOnly }+ return .ok+ }++ /// "1.2.3": digits and dots, nothing else (a dev build might say "dev", "0.0.0-local" or nothing).+ static func isReleaseVersion(_ v: String) -> Bool {+ let parts = v.split(separator: ".", omittingEmptySubsequences: false)+ return parts.count >= 2 && parts.allSatisfy { !$0.isEmpty && $0.allSatisfy(\.isASCII) && $0.allSatisfy(\.isNumber) }+ }++ // ---- When ----++ enum InstallError: Error, Equatable { case buildRunning, failed(String) }++ /// Swap `staged` in at `current`: copied in beside it first (from there on every step stays on one volume), then+ /// exchanged with it in one replace, so a failure anywhere leaves a working app at `current`. The old bundle goes+ /// to the Trash (`trashOld`; the tests remove it instead), and the new one loses the quarantine flag, so its first+ /// launch shows no Gatekeeper prompt (the release is ad-hoc signed, not notarized).+ ///+ /// Refused while a build runs: the caller relaunches (or the app is quitting), and either ends the build's process group.+ static func install(_ staged: URL, over current: URL, buildRunning: Bool, trashOld: Bool = true) throws {+ guard !buildRunning else { throw InstallError.buildRunning }+ let fm = FileManager.default+ let dir = current.deletingLastPathComponent()+ let name = current.deletingPathExtension().lastPathComponent+ let incoming = dir.appendingPathComponent(name + " (new).app")+ let backupName = name + " (old).app"+ try? fm.removeItem(at: incoming)+ try? fm.removeItem(at: dir.appendingPathComponent(backupName))+ do {+ try fm.copyItem(at: staged, to: incoming)+ let placed = try fm.replaceItemAt(current, withItemAt: incoming, backupItemName: backupName, options: [.withoutDeletingBackupItem])+ let backup = dir.appendingPathComponent(backupName)+ if fm.fileExists(atPath: backup.path) {+ if trashOld { try? fm.trashItem(at: backup, resultingItemURL: nil) } else { try? fm.removeItem(at: backup) }+ }+ let x = Process()+ x.executableURL = URL(fileURLWithPath: "/usr/bin/xattr")+ x.arguments = ["-dr", "com.apple.quarantine", (placed ?? current).path]+ try? x.run(); x.waitUntilExit()+ } catch {+ try? fm.removeItem(at: incoming)+ throw InstallError.failed(error.localizedDescription)+ }+ }+}diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex 82795015..5d43310b 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -217,6 +217,12 @@ final class BuildModel: ObservableObject {groupsLock.lock(); groups.remove(p.processIdentifier); groupsLock.unlock()}+ /// A build's process group is still running (the app update waits for it: its relaunch would end the build).+ static var buildProcessesAlive: Bool {+ groupsLock.lock(); defer { groupsLock.unlock() }+ return groups.contains { killpg($0, 0) == 0 }+ }+/// SIGTERM to every process of the group, SIGKILL 5 s later to whatever is left of it.nonisolated static func endGroup(_ leader: pid_t) {guard leader > 1 else { return }@@ -432,12 +438,26 @@ 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 = "0.4.7"- @Published var appUpdate: (tag: String, url: String)?+ @Published var appUpdate: AppUpdate.Release?@Published var appBusy = false@Published var appStatus = ""+ /// 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?+ /// 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?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 } }@@ -449,31 +469,44 @@ final class BuildModel: ObservableObject {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 = trueif !silent { appStatus = t("app.checking") }URLSession.shared.dataTask(with: URL(string: "https://api.github.com/repos/LNPANDY/NX2Apple/releases/latest")!) { data, _, _ in- var found: (String, 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),- let assets = obj["assets"] as? [[String: Any]] {- // nxnative-macOS-arm64.zip; releases from before the rename name it NS-Port-Builder-macOS-arm64.zip- for name in ["NX2Apple-macOS-arm64.zip", "nxnative-macOS-arm64.zip", "NS-Port-Builder-macOS-arm64.zip"] where found == nil {- for a in assets where (a["name"] as? String) == name {- if let u = a["browser_download_url"] as? String { found = (tag, u) }- }- }- }+ var found: AppUpdate.Release?+ if let d = data, let obj = try? JSONSerialization.jsonObject(with: d) as? [String: Any],+ let r = Self.appRelease(fromJSON: obj), Self.isNewer(r.tag, than: Self.appVersion) {+ found = r}DispatchQueue.main.async {self.appBusy = falseif let f = found {self.appUpdate = f- self.appStatus = String(format: self.t("app.found"), f.0)+ 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) }+ }} else if !silent {self.appStatus = data == nil ? self.t("app.netFail") : self.t("app.upToDate")}@@ -481,68 +514,142 @@ final class BuildModel: ObservableObject {}.resume()}- /// Download the new release, unzip it beside the running app, swap it in and relaunch. The old- /// bundle goes to the Trash; a failure at any step leaves the current app running.- func performAppUpdate() {- guard let upd = appUpdate, let url = URL(string: upd.url), !appBusy else { return }- appBusy = true; appStatus = t("app.downloading")+ /// 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+ appStatus = String(format: t(automatic ? "app.staging" : "app.downloading"), release.tag)+ let expectedID = Bundle.main.bundleIdentifier ?? ""DispatchQueue.global().async {- let tmp = FileManager.default.temporaryDirectory.appendingPathComponent("nspb-update.zip")- try? FileManager.default.removeItem(at: tmp)- let sem = DispatchSemaphore(value: 0)- URLSession.shared.downloadTask(with: url) { local, _, _ in- if let local = local { try? FileManager.default.moveItem(at: local, to: tmp) }- sem.signal()- }.resume()- sem.wait()- guard FileManager.default.fileExists(atPath: tmp.path) else {- DispatchQueue.main.async { self.appBusy = false; self.appStatus = self.t("app.netFail") }- return- }- DispatchQueue.main.async { self.appStatus = self.t("app.installing") }- let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nspb-update", isDirectory: true)- try? FileManager.default.removeItem(at: dir)- try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)- let unzip = Process()- unzip.executableURL = URL(fileURLWithPath: "/usr/bin/ditto")- unzip.arguments = ["-x", "-k", tmp.path, dir.path]- try? unzip.run(); unzip.waitUntilExit()- // The archive holds one app: nxnative.app, or NS Port Builder.app in a release from before the rename- let newApp = ((try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? [])- .first { $0.pathExtension == "app" } ?? dir.appendingPathComponent("NX2Apple.app")- guard unzip.terminationStatus == 0, FileManager.default.fileExists(atPath: newApp.path) else {- DispatchQueue.main.async { self.appBusy = false; self.appStatus = self.t("app.netFail") }- return- }- // Copy the new bundle in beside the running one first: from there on every step is a- // same-volume move, and a failure anywhere leaves a working app on disk.- let cur = Bundle.main.bundleURL- let staging = cur.deletingLastPathComponent().appendingPathComponent("NX2Apple (new).app")- try? FileManager.default.removeItem(at: staging)- do {- try FileManager.default.copyItem(at: newApp, to: staging)- var trash: NSURL?- try FileManager.default.trashItem(at: cur, resultingItemURL: &trash)- try FileManager.default.moveItem(at: staging, to: cur)- } catch {- DispatchQueue.main.async {- self.appBusy = false- self.appStatus = String(format: self.t("app.installFail"), error.localizedDescription)- }- return- }- let x = Process() // no Gatekeeper prompt on the swapped-in copy's first launch- x.executableURL = URL(fileURLWithPath: "/usr/bin/xattr")- x.arguments = ["-dr", "com.apple.quarantine", cur.path]- try? x.run(); x.waitUntilExit()+ let result = Self.downloadAndStage(release, from: url, expectedID: expectedID, requireDigest: automatic)DispatchQueue.main.async {- self.appStatus = String(format: self.t("app.relaunching"), upd.tag)- NSWorkspace.shared.openApplication(at: cur, configuration: NSWorkspace.OpenConfiguration())- DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { exit(0) }+ 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):+ self.appStatus = String(format: self.t(why.rawValue), release.tag)+ }}}}+ /// Why staging stopped: each case is the localization key of its message (a format with the release's tag).+ enum StageFailure: String, Error {+ case network = "app.stageNetFail", noDigest = "app.noDigest", mismatch = "app.digestMismatch"+ case unpack = "app.unpackFail", notOurApp = "app.notOurApp"+ }++ /// 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) -> 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 = Process()+ unzip.executableURL = URL(fileURLWithPath: "/usr/bin/ditto")+ unzip.arguments = ["-x", "-k", zip.path, dir.path]+ do { try unzip.run() } catch { return .failure(.unpack) }+ unzip.waitUntilExit()+ 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.terminationStatus == 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)+ }+ 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 && !Self.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 }+ do {+ 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+ if relaunch {+ appStatus = String(format: t("app.relaunching"), staged.release.tag)+ NSWorkspace.shared.openApplication(at: current, configuration: NSWorkspace.OpenConfiguration())+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { exit(0) }+ }+ 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)+ }+ }+var basePath: String { slot("base").paths.first ?? "" }var keysPath: String { slot("keys").paths.first ?? "" }var updatePath: String { slot("update").paths.first ?? "" }@@ -2176,15 +2283,28 @@ struct BuilderView: View {.padTarget("set.language", scope: "main", activate: { cycleLanguage(1) }, adjust: { cycleLanguage($0) })}divider- row("NX2Apple", detail: String(format: m.t("app.version"), BuildModel.appVersion)) {- if let u = m.appUpdate {- Button(String(format: m.t("app.updateBtn"), u.tag)) { m.performAppUpdate() }.disabled(m.appBusy)- .padTarget("set.appUpdate", scope: "main") { if !m.appBusy { m.performAppUpdate() } }+ row("NX2Apple", detail: String(format: m.t("app.version"), BuildModel.appVersion),+ dot: m.appStaged != nil ? LauncherPalette.ready : nil) {+ if m.appBusy { ProgressView().controlSize(.small) }+ if m.appStaged != nil {+ // Downloaded and verified: it goes in when the app quits; this restarts into it now (not during a build)+ Button(m.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: m.t("app.updateBtn"), u.tag)) { m.performAppUpdate() }.disabled(m.appBusy || m.running)+ .padTarget("set.appUpdate", scope: "main") { if !(m.appBusy || m.running) { m.performAppUpdate() } }} else {Button(m.t("repo.check")) { m.checkAppUpdate() }.disabled(m.appBusy).padTarget("set.appCheck", scope: "main") { if !m.appBusy { m.checkAppUpdate() } }}}+ divider+ // A launcher built from the repository never replaces itself (AppUpdate.installability): the switch says so and stays off+ row(m.t("app.auto"), detail: m.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() } }+ }}}diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swiftindex 0da50194..fbe15ee1 100644--- a/frontend/Sources/NSPortBuilder/LauncherView.swift+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift@@ -456,6 +456,15 @@ struct ContentView: View {Image(systemName: "desktopcomputer").foregroundStyle(.secondary)Text(m.t("library.localNote")).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.+ HStack(spacing: 10) {+ Circle().fill(LauncherPalette.ready).frame(width: 6, height: 6)+ Text(String(format: m.t("library.appReady"), staged.release.tag)).font(.manrope(13)).foregroundStyle(.secondary)+ }+ Button(m.t("app.restartNow")) { m.restartToUpdate() }.buttonStyle(LauncherSecondaryButtonStyle())+ }if gamepad.connected {// The buttons a controller has here, named as the game names them (A on the right)HStack(spacing: 18) {diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 37bd99a8..57b1f77d 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -189,7 +189,23 @@ enum L10n {"app.upToDate": ("App 已是最新版本", "The app is up to date"),"app.found": ("App 有新版本 %@,点右上角按钮更新", "A new version %@ is out — update from the top-right button"),"app.updateBtn": ("更新到 %@", "Update to %@"),- "app.downloading": ("正在下载新版本…", "Downloading the new version…"),+ "app.downloading": ("正在下载 %@…", "Downloading %@…"),+ "app.staging": ("正在后台下载 %@…", "Downloading %@ in the background…"),+ "app.ready": ("%@ 已下载并校验:退出 App 时安装,或点「立即重启」", "%@ is downloaded and verified: it installs when you quit, or Restart now"),+ "app.restartNow": ("立即重启", "Restart now"),+ "app.waitForBuild": ("构建进行中:更新会等构建结束", "A build is running: the update waits until it is done"),+ "app.stageNetFail": ("%@ 下载失败(GitHub 不通?下次打开时再试)", "Could not download %@ (GitHub unreachable? it tries again next launch)"),+ "app.noDigest": ("%@ 已发布,但 GitHub 没有提供校验值,所以不会自动安装——可以手动更新", "%@ is out, but GitHub gave no checksum for it, so it is not installed automatically — update by hand"),+ "app.digestMismatch": ("%@ 的下载与校验值不符,已丢弃", "The download of %@ did not match its checksum and was discarded"),+ "app.unpackFail": ("%@ 的下载无法解压,已丢弃", "The download of %@ could not be unpacked and was discarded"),+ "app.notOurApp": ("%@ 的下载不是 NX2Apple,已丢弃", "The download of %@ is not an NX2Apple app and was discarded"),+ "app.devBuild": ("%@ 已发布。这个启动器是从仓库构建的,不会替换自己", "%@ is out. This launcher was built from the repository and does not replace itself"),+ "app.readOnly": ("%@ 已发布,但 App 无法在当前位置替换自己——请把它移到「应用程序」文件夹", "%@ is out, but the app cannot replace itself where it is — move it to Applications"),+ "app.auto": ("自动安装更新", "Install updates automatically"),+ "app.autoNote": ("在后台下载并校验,退出 App 时安装;构建进行中绝不安装", "Downloaded and verified in the background, installed when you quit; never during a build"),+ "app.autoDev": ("从仓库构建的启动器不会自动更新", "Not for a launcher built from the repository"),+ "app.autoReadOnly": ("App 所在的文件夹不可写,无法自动更新", "The app's folder is not writable, so it cannot update itself"),+ "library.appReady": ("NX2Apple %@ 已就绪", "NX2Apple %@ is ready"),"app.installing": ("正在安装…(旧版本会进废纸篓)", "Installing… (the old version goes to the Trash)"),"app.relaunching": ("已更新到 %@,正在重启 App…", "Updated to %@ — restarting…"),"app.installFail": ("安装失败:%@——新版本已下载,可手动替换", "Install failed: %@ — the new version was downloaded; replace by hand"),diff --git a/frontend/Tests/NSPortBuilderTests/AppUpdateTests.swift b/frontend/Tests/NSPortBuilderTests/AppUpdateTests.swiftnew file mode 100644index 00000000..b008a4c3--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/AppUpdateTests.swift@@ -0,0 +1,226 @@+import XCTest+import CryptoKit+@testable import NSPortBuilder++/// The self-update's rules on bundles in a temporary folder: never the running app, never the network.+final class AppUpdateTests: XCTestCase {+ private var temporary: URL!+ private let bundleID = "org.nxnative.NSPortBuilder"++ override func setUpWithError() throws {+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-update-tests-" + UUID().uuidString)+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)+ }++ override func tearDownWithError() throws {+ try FileManager.default.removeItem(at: temporary)+ }++ /// A launcher bundle as the release workflow assembles it.+ @discardableResult+ private func makeApp(_ name: String = "NX2Apple", in dir: URL? = nil, id: String? = nil, version: String = "0.4.8",+ executable: Bool = true, marker: String = "new") throws -> URL {+ let app = (dir ?? temporary).appendingPathComponent(name + ".app")+ let macOS = app.appendingPathComponent("Contents/MacOS")+ try FileManager.default.createDirectory(at: macOS, withIntermediateDirectories: true)+ let exe = macOS.appendingPathComponent("NSPortBuilder")+ try Data(marker.utf8).write(to: exe)+ try FileManager.default.setAttributes([.posixPermissions: executable ? 0o755 : 0o644], ofItemAtPath: exe.path)+ let info: [String: Any] = ["CFBundleIdentifier": id ?? bundleID, "CFBundleExecutable": "NSPortBuilder",+ "CFBundleShortVersionString": version, "CFBundlePackageType": "APPL"]+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0)+ .write(to: app.appendingPathComponent("Contents/Info.plist"))+ return app+ }++ private func digest(_ file: URL) throws -> String {+ "sha256:" + SHA256.hash(data: try Data(contentsOf: file)).map { String(format: "%02x", $0) }.joined()+ }++ /// The app zipped as the release workflow does (ditto -c -k --keepParent).+ private func zip(_ app: URL) throws -> URL {+ let out = temporary.appendingPathComponent("download-" + UUID().uuidString + ".zip")+ let p = Process()+ p.executableURL = URL(fileURLWithPath: "/usr/bin/ditto")+ p.arguments = ["-c", "-k", "--keepParent", app.path, out.path]+ try p.run(); p.waitUntilExit()+ XCTAssertEqual(p.terminationStatus, 0)+ return out+ }++ private func marker(_ app: URL) throws -> String {+ String(decoding: try Data(contentsOf: app.appendingPathComponent("Contents/MacOS/NSPortBuilder")), as: UTF8.self)+ }++ // ---- digest ----++ func testDigestMatches() throws {+ let file = temporary.appendingPathComponent("a.zip")+ try Data("release".utf8).write(to: file)+ XCTAssertEqual(AppUpdate.checkDigest(file, expected: try digest(file)), .match)+ XCTAssertEqual(AppUpdate.checkDigest(file, expected: try digest(file).uppercased().replacingOccurrences(of: "SHA256:", with: "sha256:")), .match)+ }++ func testDigestMismatch() throws {+ let file = temporary.appendingPathComponent("a.zip")+ try Data("release".utf8).write(to: file)+ let other = temporary.appendingPathComponent("b.zip")+ try Data("something else".utf8).write(to: other)+ XCTAssertEqual(AppUpdate.checkDigest(file, expected: try digest(other)), .mismatch)+ XCTAssertEqual(AppUpdate.checkDigest(file, expected: "sha256:1234"), .mismatch) // malformed: never a match+ }++ func testDigestMissing() throws {+ let file = temporary.appendingPathComponent("a.zip")+ try Data("release".utf8).write(to: file)+ XCTAssertEqual(AppUpdate.checkDigest(file, expected: nil), .missing)+ XCTAssertEqual(AppUpdate.checkDigest(file, expected: ""), .missing)+ XCTAssertEqual(AppUpdate.checkDigest(file, expected: "sha512:abcd"), .missing) // nothing to compare with+ }++ // ---- the app inside ----++ func testBundleValidation() throws {+ let good = try makeApp("Good")+ XCTAssertNil(AppUpdate.bundleProblem(good, expectedID: bundleID, tag: "v0.4.8"))+ XCTAssertEqual(AppUpdate.bundleProblem(try makeApp("Other", id: "com.example.Other"), expectedID: bundleID, tag: "v0.4.8"), .wrongIdentifier)+ XCTAssertEqual(AppUpdate.bundleProblem(good, expectedID: "", tag: "v0.4.8"), .wrongIdentifier) // the running app has no identifier+ XCTAssertEqual(AppUpdate.bundleProblem(try makeApp("NoExe", executable: false), expectedID: bundleID, tag: "v0.4.8"), .noExecutable)+ XCTAssertEqual(AppUpdate.bundleProblem(good, expectedID: bundleID, tag: "v0.4.9"), .wrongVersion)+ XCTAssertEqual(AppUpdate.bundleProblem(temporary.appendingPathComponent("Missing.app"), expectedID: bundleID, tag: "v0.4.8"), .noInfo)+ }++ func testStagingVerifiesDigestAndBundle() throws {+ let source = temporary.appendingPathComponent("source", isDirectory: true)+ let archive = try zip(try makeApp(in: source))+ 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()+ XCTAssertEqual(staged.release, release)+ XCTAssertEqual(staged.app.lastPathComponent, "NX2Apple.app")+ XCTAssertEqual(try marker(staged.app), "new")+ }++ 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> {+ 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)+ }+ let wrong = "sha256:" + String(repeating: "0", count: 64)+ XCTAssertEqual(try attempt(wrong, automatic: true).failure, .mismatch)+ XCTAssertEqual(try attempt(wrong, automatic: false).failure, .mismatch) // a wrong digest is refused by hand too+ XCTAssertEqual(try attempt(nil, automatic: true).failure, .noDigest)+ XCTAssertNil(try attempt(nil, automatic: false).failure) // by hand, a release without one installs as before+ XCTAssertEqual(try attempt("self", automatic: true, id: "com.example.Other").failure, .notOurApp)+ }++ // ---- which copies replace themselves ----++ func testReleaseInstallIsUpdatable() throws {+ let apps = temporary.appendingPathComponent("Applications", isDirectory: true)+ let app = try makeApp(in: apps, version: "0.4.7")+ XCTAssertEqual(AppUpdate.installability(app, appVersion: "0.4.7"), .ok)+ }++ func testDeveloperBuildsDoNotUpdate() throws {+ // swift run: a bare executable's folder, no bundle+ let release = temporary.appendingPathComponent("frontend/.build/arm64-apple-macosx/release", isDirectory: true)+ try FileManager.default.createDirectory(at: release, withIntermediateDirectories: true)+ XCTAssertEqual(AppUpdate.installability(release, appVersion: "0.4.7"), .developer)+ // a bundle under .build or DerivedData+ XCTAssertEqual(AppUpdate.installability(try makeApp(in: release, version: "0.4.7"), appVersion: "0.4.7"), .developer)+ let derived = temporary.appendingPathComponent("DerivedData/NX2Apple/Build/Products/Release", isDirectory: true)+ XCTAssertEqual(AppUpdate.installability(try makeApp(in: derived, version: "0.4.7"), appVersion: "0.4.7"), .developer)+ // frontend/NX2Apple.app, assembled beside the Package.swift it was built from+ let frontend = temporary.appendingPathComponent("frontend", isDirectory: true)+ try Data().write(to: frontend.appendingPathComponent("Package.swift"))+ XCTAssertEqual(AppUpdate.installability(try makeApp(in: frontend, version: "0.4.7"), appVersion: "0.4.7"), .developer)+ // a bundle whose plist does not carry this binary's release number, or a binary without one+ let elsewhere = temporary.appendingPathComponent("elsewhere", isDirectory: true)+ XCTAssertEqual(AppUpdate.installability(try makeApp("Stale", in: elsewhere, version: "0.4.6"), appVersion: "0.4.7"), .developer)+ XCTAssertEqual(AppUpdate.installability(try makeApp("Dev", in: elsewhere, version: "dev"), appVersion: "dev"), .developer)+ XCTAssertEqual(AppUpdate.installability(try makeApp("NoID", in: elsewhere, id: "", version: "0.4.7"), appVersion: "0.4.7"), .developer)+ }++ func testReleaseVersions() {+ XCTAssertTrue(AppUpdate.isReleaseVersion("0.4.7"))+ XCTAssertTrue(AppUpdate.isReleaseVersion("1.0"))+ for v in ["", "dev", "1", "0.4.7-local", "0..7", "v0.4.7", "0.4"] { XCTAssertFalse(AppUpdate.isReleaseVersion(v), v) }+ }++ func testReleaseParsingTakesTheDigest() {+ let json: [String: Any] = ["tag_name": "v0.4.8", "assets": [+ ["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"))+ 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": []]))+ }++ // ---- when ----++ func testInstallSwapsTheBundle() throws {+ let current = try makeApp("Current", in: temporary.appendingPathComponent("Applications"), marker: "old")+ let staged = try makeApp("Staged", in: temporary.appendingPathComponent("staged"), marker: "new")+ try AppUpdate.install(staged, over: current, buildRunning: false, trashOld: false)+ XCTAssertEqual(try marker(current), "new")+ let left = try FileManager.default.contentsOfDirectory(atPath: current.deletingLastPathComponent().path)+ XCTAssertEqual(left, ["Current.app"]) // no "(new)" or "(old)" copy beside it+ }++ func testInstallRefusedWhileBuildRuns() throws {+ let current = try makeApp("Current", in: temporary.appendingPathComponent("Applications"), marker: "old")+ let staged = try makeApp("Staged", in: temporary.appendingPathComponent("staged"), marker: "new")+ XCTAssertThrowsError(try AppUpdate.install(staged, over: current, buildRunning: true, trashOld: false)) {+ XCTAssertEqual($0 as? AppUpdate.InstallError, .buildRunning)+ }+ 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",+ "app.autoNote", "app.autoDev", "app.autoReadOnly", "library.appReady"] {+ XCTAssertNotNil(L10n.table[key], key)+ }+ XCTAssertTrue(L10n.selfCheck().isEmpty)+ }+}++private extension Result {+ var failure: Failure? { if case .failure(let f) = self { return f }; return nil }+}diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swiftindex 52696202..175956bd 100644--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift@@ -660,6 +660,19 @@ final class LibraryTests: XCTestCase {try capture("build", page: .builds)try capture("build-small", width: 900, height: 680, page: .builds)try capture("settings", page: .settings)+ 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 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)+ 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)+ try capture("settings-update-ready", page: .settings)+ try capture("library-update-ready")+ }// An iPhone build with a paired device and a team (example values)let previousTarget = model.targetmodel.target = "ios"