Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(spaces-macos): ask to relaunch when the app was replaced under it, instead of a failing update (#4569)
ddupont5d1b240f7172
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdatesModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdatesModel.swiftindex 6c64011d1f..17cf5da7d6 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdatesModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdatesModel.swift@@ -42,6 +42,13 @@ public final class SparkleUpdater: NSObject, UpdaterDriving, SPUUpdaterDelegate,public var onChange: (() -> Void)?public var channels: [String] = []public var onUpdateEvent: ((String) -> Void)?+ /// The bundle this process runs from, as it was at launch.+ private let launched = LaunchedBundle(bundle: .main)+ /// The update the last check found (its disk image, for a manual+ /// download when Sparkle cannot install it).+ private var found: SUAppcastItem?+ /// The relaunch prompt is shown once per run.+ private var askedToRelaunch = falseprivate var updater: SPUUpdater { controller.updater }@@ -90,13 +97,40 @@ public final class SparkleUpdater: NSObject, UpdaterDriving, SPUUpdaterDelegate,public var lastCheck: Date? { updater.lastUpdateCheckDate }public var canCheck: Bool { updater.canCheckForUpdates }- public func checkNow() { updater.checkForUpdates() }+ public func checkNow() {+ // A copy replaced under this process cannot install updates; say so+ // instead of letting Sparkle fail at the installer.+ if let replaced = launched.replacement() {+ askedToRelaunch = true+ Self.askToRelaunch(replaced, launched: launched)+ return+ }+ updater.checkForUpdates()+ }/// Checks in the background (no window unless an update is found);/// end-to-end runs use it through `CUA_SPACES_UPDATE_CHECK`.public func checkInBackground() { updater.checkForUpdatesInBackground() }// Sparkle calls its delegate on the main thread.++ /// No scheduled check while the bundle on disk is not the one running:+ /// its installer could not start (see `LaunchedBundle`). The user is+ /// asked once to relaunch instead.+ public nonisolated func updater(_ updater: SPUUpdater, mayPerform updateCheck: SPUUpdateCheck) throws {+ try MainActor.assumeIsolated {+ guard let replaced = launched.replacement() else { return }+ if !askedToRelaunch {+ askedToRelaunch = true+ let launched = launched+ DispatchQueue.main.async { Self.askToRelaunch(replaced, launched: launched) }+ }+ throw NSError(domain: Self.errorDomain, code: 1, userInfo: [+ NSLocalizedDescriptionKey: "Cua Spaces was replaced on disk while it was running; relaunch it to update.",+ ])+ }+ }+public nonisolated func allowedChannels(for updater: SPUUpdater) -> Set<String> {MainActor.assumeIsolated { Set(channels) }}@@ -107,12 +141,85 @@ public final class SparkleUpdater: NSObject, UpdaterDriving, SPUUpdaterDelegate,MainActor.assumeIsolated { onUpdateEvent?(event) }}- public nonisolated func updater(_ updater: SPUUpdater, didFindValidUpdate item: SUAppcastItem) { tell("found") }+ public nonisolated func updater(_ updater: SPUUpdater, didFindValidUpdate item: SUAppcastItem) {+ MainActor.assumeIsolated { found = item }+ tell("found")+ }public nonisolated func updaterDidNotFindUpdate(_ updater: SPUUpdater) { tell("not_found") }public nonisolated func updater(_ updater: SPUUpdater, willInstallUpdate item: SUAppcastItem) { tell("installed") }public nonisolated func updater(_ updater: SPUUpdater, didAbortWithError error: any Error) {// "No update" also arrives here; only a real failure is one.- if (error as NSError).code != Int(SUError.noUpdateError.rawValue) { tell("failed") }+ let code = (error as NSError).code+ if code == Int(SUError.noUpdateError.rawValue) { return }+ tell("failed")+ // A check refused because this copy was replaced has asked already.+ guard code != Int(SUError.installationCanceledError.rawValue),+ (error as NSError).domain != Self.errorDomain else { return }+ // After Sparkle's own error alert, offer the way that still works:+ // relaunch when this copy was replaced on disk (whatever step+ // failed), else download the update when its installer could not+ // start or run.+ MainActor.assumeIsolated {+ if let replaced = launched.replacement() {+ askedToRelaunch = true+ Self.askToRelaunch(replaced, launched: launched)+ } else if code == Int(SUError.installationError.rawValue), let item = found {+ Self.offerDownload(item)+ }+ }+ }++ // MARK: - When Sparkle cannot install++ private nonisolated static let errorDomain = "com.trycua.spaces.macos.updates"++ /// "Relaunch Cua Spaces to update": the copy on disk is not the one+ /// running. Relaunching runs it, and it updates normally.+ private static func askToRelaunch(_ replaced: LaunchedBundle.Replacement, launched: LaunchedBundle) {+ let alert = NSAlert()+ alert.messageText = "Relaunch Cua Spaces to update"+ if let version = replaced.version {+ let what = version.isEmpty ? "A new copy of Cua Spaces" : "Cua Spaces \(version)"+ alert.informativeText = "\(what) was installed while this copy was running. "+ + "Relaunch to finish; updates install from there."+ alert.addButton(withTitle: "Relaunch")+ } else {+ alert.informativeText = "Cua Spaces was moved or deleted while it was running. "+ + "Quit it and open it again from Applications to update."+ }+ alert.addButton(withTitle: replaced.version == nil ? "OK" : "Later")+ NSApp.activate()+ guard replaced.version != nil, alert.runModal() == .alertFirstButtonReturn else { return }+ relaunch(launched.url)+ }++ /// "Download the update": the disk image, to drag over this copy.+ private static func offerDownload(_ item: SUAppcastItem) {+ guard let url = item.fileURL else { return }+ let alert = NSAlert()+ alert.messageText = "Download Cua Spaces \(item.displayVersionString)"+ alert.informativeText = "Cua Spaces could not install the update itself. Download it, quit Cua Spaces, "+ + "and drag the new copy to Applications."+ alert.addButton(withTitle: "Download")+ alert.addButton(withTitle: "Not Now")+ NSApp.activate()+ if alert.runModal() == .alertFirstButtonReturn { NSWorkspace.shared.open(url) }+ }++ /// Opens `bundle` again once this process has exited, then quits.+ private static func relaunch(_ bundle: URL) {+ let pid = ProcessInfo.processInfo.processIdentifier+ let waiter = Process()+ waiter.executableURL = URL(fileURLWithPath: "/bin/sh")+ waiter.arguments = ["-c", "while /bin/kill -0 \(pid) 2>/dev/null; do /bin/sleep 0.2; done; exec /usr/bin/open \"$0\"",+ bundle.path]+ do {+ try waiter.run()+ } catch {+ NSLog("Cua Spaces: could not relaunch: %@", error.localizedDescription)+ return+ }+ NSApp.terminate(nil)}// MARK: - Versions in Sparkle's windows@@ -142,6 +249,59 @@ public final class SparkleUpdater: NSObject, UpdaterDriving, SPUUpdaterDelegate,}}+/// The app bundle this process was launched from, and whether the copy on+/// disk is still that one.+///+/// Installing a new copy over a running Cua Spaces (dragging it from the+/// disk image, or any installer that replaces the bundle) leaves this+/// process running code whose files are gone. macOS can no longer check its+/// signature: authd refuses it (`failed to create code ref -67049`), so+/// Sparkle's installer cannot be authorized (`Failed to create authorization+/// reference: -60008`) and every update fails with "An error occurred while+/// launching the installer". Relaunching runs the new copy, which updates+/// normally.+public struct LaunchedBundle: Sendable {+ /// What is on disk now, when it is not what was launched.+ public struct Replacement: Equatable, Sendable {+ /// Its version (`CuaVersion`, else `CFBundleShortVersionString`);+ /// nil when the bundle is gone.+ public var version: String?+ }++ public let url: URL+ let executable: URL?+ /// The executable's file (device, inode) at launch.+ let file: [UInt64]?++ public init(bundle: Bundle) {+ self.init(url: bundle.bundleURL, executable: bundle.executableURL)+ }++ init(url: URL, executable: URL?) {+ self.url = url+ self.executable = executable+ file = executable.flatMap(Self.fileID)+ }++ static func fileID(_ url: URL) -> [UInt64]? {+ var st = stat()+ guard stat(url.path, &st) == 0 else { return nil }+ return [UInt64(UInt32(bitPattern: st.st_dev)), UInt64(st.st_ino)]+ }++ /// The copy on disk when it is no longer the one launched (its main+ /// executable is another file, or gone); nil while it is the same.+ public func replacement() -> Replacement? {+ guard let executable, let file else { return nil }+ let now = Self.fileID(executable)+ if now == file { return nil }+ guard now != nil else { return Replacement(version: nil) }+ let info = NSDictionary(contentsOf: url.appendingPathComponent("Contents/Info.plist")) as? [String: Any] ?? [:]+ let full = (info["CuaVersion"] as? String).flatMap { $0.isEmpty ? nil : $0 }+ return Replacement(version: full ?? info["CFBundleShortVersionString"] as? String ?? "")+ }+}+/// An in-memory updater (tests, captures): nothing is checked or stored.@MainActorpublic final class FixtureUpdater: UpdaterDriving {diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/UpdatesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/UpdatesTests.swiftindex eac6096fc0..adabf22bc0 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/UpdatesTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/UpdatesTests.swift@@ -238,3 +238,48 @@ struct UpdatesTests {#expect(blocks.contains { if case .verbatim(let t) = $0 { t.contains("Andy Matuschak") } else { false } })}}++/// A copy installed over the running app: Sparkle cannot authorize its+/// installer for a process whose files are gone, so the app asks to relaunch.+@Suite("Launched bundle")+struct LaunchedBundleTests {+ static func bundle(version: String) throws -> (URL, URL) {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("launched-\(UUID().uuidString)")+ let app = root.appendingPathComponent("Cua Spaces.app")+ try write(app, version: version)+ return (app, app.appendingPathComponent("Contents/MacOS/CuaSpacesMac"))+ }++ static func write(_ app: URL, version: String) throws {+ let macos = app.appendingPathComponent("Contents/MacOS")+ try FileManager.default.createDirectory(at: macos, withIntermediateDirectories: true)+ try Data("binary \(version)".utf8).write(to: macos.appendingPathComponent("CuaSpacesMac"))+ let info: NSDictionary = ["CFBundleShortVersionString": version, "CuaVersion": version]+ try info.write(to: app.appendingPathComponent("Contents/Info.plist"))+ }++ @Test func theLaunchedCopyIsNotAReplacement() throws {+ let (app, exe) = try Self.bundle(version: "0.5.0")+ defer { try? FileManager.default.removeItem(at: app.deletingLastPathComponent()) }+ #expect(LaunchedBundle(url: app, executable: exe).replacement() == nil)+ }++ @Test func aCopyInstalledOverTheRunningOneIsAReplacement() throws {+ let (app, exe) = try Self.bundle(version: "0.5.0")+ defer { try? FileManager.default.removeItem(at: app.deletingLastPathComponent()) }+ let launched = LaunchedBundle(url: app, executable: exe)+ // What dragging the new copy from the disk image does: the old+ // bundle goes, the new one's files arrive.+ try FileManager.default.removeItem(at: app)+ try Self.write(app, version: "0.6.0")+ #expect(launched.replacement() == LaunchedBundle.Replacement(version: "0.6.0"))+ }++ @Test func aDeletedCopyHasNoVersion() throws {+ let (app, exe) = try Self.bundle(version: "0.5.0")+ defer { try? FileManager.default.removeItem(at: app.deletingLastPathComponent()) }+ let launched = LaunchedBundle(url: app, executable: exe)+ try FileManager.default.removeItem(at: app)+ #expect(launched.replacement() == LaunchedBundle.Replacement(version: nil))+ }+}