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): the host service restarts onto an updated app (CUA-2457) (#6054)
ddupontdacf7e70d291
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swiftindex d6c226234f..b1f21d59b9 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift@@ -142,6 +142,9 @@ private func wait(_ pid: pid_t) -> Int32 {// the child is a failure launchd restarts (KeepAlive SuccessfulExit=false).private var serviceChild: pid_t = 0private var serviceStopping: sig_atomic_t = 0+// The app was updated in place: exit non-zero once the child is gone, so+// launchd starts the new build.+private var serviceRestarting: sig_atomic_t = 0enum ServiceLauncher {/// `CuaSpacesMac check-permissions` (and any other cua-spacesd command):@@ -190,27 +193,44 @@ enum ServiceLauncher {exit(1)}serviceChild = pid- // The app was replaced by one without the service (a downgrade) or- // the host was removed: the files are gone while this process still- // runs from them. Stop, so the service that replaced it can take the- // port; launchd does not start a program that is gone.+ // Its files, watched while it runs:+ // * gone (the app was replaced by one without the service, a+ // downgrade, or the host was removed): stop, so the service that+ // replaced it can take the port; launchd does not start a program+ // that is gone.+ // * replaced by an update (Sparkle, or the app dragged over): the+ // same paths with new files. Stop the old cua-spacesd and exit+ // non-zero, so launchd starts the new build's (CUA-2457: before,+ // the old helper and relay host ran until logout).let daemonFile = daemonPath()+ let selfFile = (Bundle.main.executablePath.map { URL(fileURLWithPath: $0).resolvingSymlinksInPath().path })+ ?? CommandLine.arguments[0]+ let files = [selfFile, daemonFile]+ let started = files.map(HelperService.identity)Thread.detachNewThread {var misses = 0while true {sleep(5)- let gone = !FileManager.default.fileExists(atPath: daemonFile)- || !FileManager.default.fileExists(atPath: specFile)- misses = gone ? misses + 1 : 0- if misses >= 2 {+ let now = files.map(HelperService.identity)+ let specPresent = FileManager.default.fileExists(atPath: specFile)+ switch HelperService.watch(started: started, now: now, specPresent: specPresent, misses: &misses) {+ case .keep:+ continue+ case .stop:log("the app's cua-spacesd or its spec is gone; stopping")serviceStopping = 1kill(pid, SIGTERM)return+ case .restart:+ log("the app was updated; restarting onto the new build")+ serviceRestarting = 1+ kill(pid, SIGTERM)+ return}}}let code = wait(pid)+ if serviceRestarting != 0 { exit(HelperService.restartExitCode) }exit(serviceStopping != 0 ? 0 : (code == 0 ? 1 : code))}}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swiftindex e93421090a..67cf7de6f9 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift@@ -3,6 +3,7 @@import AppKitimport CuaSpacesFFI+import Darwinimport Foundationimport ServiceManagement@@ -164,6 +165,130 @@ public enum HelperService {.appendingPathComponent(daemonInContents)}+ /// A file's identity (device and inode). An update (Sparkle, or the+ /// app dragged over) puts new files at the same paths, so the same path+ /// with a new identity is a new build.+ public struct FileIdentity: Equatable, Sendable {+ public let device: UInt64+ public let inode: UInt64+ public init(device: UInt64, inode: UInt64) {+ self.device = device+ self.inode = inode+ }+ }++ /// `path`'s identity, or `nil` when it is gone.+ public static func identity(_ path: String) -> FileIdentity? {+ var st = stat()+ guard stat(path, &st) == 0 else { return nil }+ return FileIdentity(device: UInt64(st.st_dev), inode: UInt64(st.st_ino))+ }++ /// What the running service does after one look at its files.+ public enum WatchVerdict: Equatable, Sendable {+ /// Nothing changed.+ case keep+ /// The app's files or the spec are gone (a downgrade to a build+ /// without the service, or the host was removed): stop, exit 0, and+ /// launchd leaves it stopped.+ case stop+ /// The app was updated in place: stop the old cua-spacesd and exit+ /// non-zero, so launchd starts the new build's (KeepAlive+ /// SuccessfulExit=false).+ case restart+ }++ /// One look at the service's files: `started` are the identities of the+ /// files it runs from (its own executable and Contents/Helpers/+ /// cua-spacesd) when it started, `now` the same files now (`nil` for one+ /// that is gone). Gone twice in a row stops (an update's swap is quick+ /// and is not mistaken for a removal); all there with any identity+ /// changed restarts.+ public static func watch(started: [FileIdentity?], now: [FileIdentity?], specPresent: Bool,+ misses: inout Int) -> WatchVerdict {+ if !specPresent || now.contains(where: { $0 == nil }) {+ misses += 1+ return misses >= 2 ? .stop : .keep+ }+ misses = 0+ return started != now ? .restart : .keep+ }++ /// The exit status of a service that restarts onto an updated app+ /// (EX_TEMPFAIL): non-zero, so launchd starts it again.+ public static let restartExitCode: Int32 = 75++ /// The service started from an older build than the one installed now:+ /// it started before this app's cua-spacesd was put in place. That is+ /// the file's status-change time (an update writes new files, and no+ /// copy keeps it), not its birth time, which an archive keeps from the+ /// build.+ public static func isStale(serviceStarted: Date, daemonInstalled: Date) -> Bool {+ serviceStarted < daemonInstalled+ }++ /// When `path` was put in place (`st_ctime`), or `nil` when it is gone.+ public static func placedTime(_ path: String) -> Date? {+ var st = stat()+ guard stat(path, &st) == 0 else { return nil }+ let t = st.st_ctimespec+ return Date(timeIntervalSince1970: TimeInterval(t.tv_sec) + TimeInterval(t.tv_nsec) / 1e9)+ }++ /// When process `pid` started, or `nil` when there is none.+ static func processStart(_ pid: pid_t) -> Date? {+ var info = proc_bsdinfo()+ let size = Int32(MemoryLayout<proc_bsdinfo>.size)+ guard proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, size) == size else { return nil }+ return Date(timeIntervalSince1970: TimeInterval(info.pbi_start_tvsec) + TimeInterval(info.pbi_start_tvusec) / 1e6)+ }++ /// The running service's pid, from `launchctl print` (`nil`: not loaded+ /// or not running).+ static func runningPid(target: String) -> pid_t? {+ let p = Process()+ p.executableURL = URL(fileURLWithPath: "/bin/launchctl")+ p.arguments = ["print", target]+ let out = Pipe()+ p.standardOutput = out+ p.standardError = FileHandle.nullDevice+ guard (try? p.run()) != nil else { return nil }+ let data = out.fileHandleForReading.readDataToEndOfFile()+ p.waitUntilExit()+ return parsePid(String(decoding: data, as: UTF8.self))+ }++ /// The `pid = N` line of `launchctl print`.+ static func parsePid(_ text: String) -> pid_t? {+ for line in text.split(separator: "\n") {+ let t = line.trimmingCharacters(in: .whitespaces)+ if t.hasPrefix("pid = "), let n = Int32(t.dropFirst(6)) { return n }+ }+ return nil+ }++ /// CUA-2457: at launch, the login item still running from before an+ /// update (Sparkle, or the app dragged over) is restarted onto this+ /// build (`launchctl kickstart -k`), so the host service runs the+ /// cua-spacesd that shipped with it. Services from this build watch+ /// their own files and restart themselves; this catches the ones that+ /// started before that watch existed. Off the main thread.+ public static func restartIfStale(executable: URL? = Bundle.main.executableURL) {+ guard let executable else { return }+ let target = "gui/\(getuid())/\(label)"+ DispatchQueue.global(qos: .utility).async {+ guard let pid = runningPid(target: target), let started = processStart(pid),+ let installed = placedTime(daemonPath(executable: executable).path),+ isStale(serviceStarted: started, daemonInstalled: installed) else { return }+ NSLog("cua-spaces: the host service (pid %d) is from before this build; restarting it", pid)+ let p = Process()+ p.executableURL = URL(fileURLWithPath: "/bin/launchctl")+ p.arguments = ["kickstart", "-k", target]+ try? p.run()+ p.waitUntilExit()+ }+ }+private static func stamped(_ info: [String: Any]?, _ key: String) -> String? {guard let value = (info?[key] as? String)?.trimmingCharacters(in: .whitespaces),!value.isEmpty else { return nil }diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swiftindex 9f4bda364f..88438daaae 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift@@ -236,6 +236,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {}func applicationDidFinishLaunching(_ notification: Notification) {+ // The host service still running from before an update: onto this build (CUA-2457).+ HelperService.restartIfStale()start(Self.model)// The menu bar's low-disk warning: read now, then every 5 minutes.LowDiskMonitor.shared.start()diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HelperServiceTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HelperServiceTests.swiftindex f79463ded4..32a0416752 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HelperServiceTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HelperServiceTests.swift@@ -60,4 +60,66 @@ struct HelperServiceTests {#expect(!daemon.path.contains("/Contents/MacOS/"))#expect(HelperService.daemonInContents == "Helpers/cua-spacesd")}++ /// CUA-2457: the running service follows its files. An update in place+ /// (new files at the same paths) restarts it onto the new build; files+ /// gone twice in a row stop it; a swap's moment without the file does not.+ @Test func theServiceRestartsOntoAnUpdatedApp() {+ typealias ID = HelperService.FileIdentity+ let old: [ID?] = [ID(device: 1, inode: 10), ID(device: 1, inode: 11)]+ let new: [ID?] = [ID(device: 1, inode: 20), ID(device: 1, inode: 21)]+ var misses = 0+ #expect(HelperService.watch(started: old, now: old, specPresent: true, misses: &misses) == .keep)+ #expect(HelperService.watch(started: old, now: new, specPresent: true, misses: &misses) == .restart)+ // Only the cua-spacesd replaced is an update too.+ #expect(HelperService.watch(started: old, now: [old[0], new[1]], specPresent: true, misses: &misses) == .restart)+ // The swap: gone once, then the new build.+ misses = 0+ #expect(HelperService.watch(started: old, now: [nil, old[1]], specPresent: true, misses: &misses) == .keep)+ #expect(HelperService.watch(started: old, now: new, specPresent: true, misses: &misses) == .restart)+ #expect(misses == 0)+ // Gone twice (a downgrade without the service, the host removed): stop.+ misses = 0+ #expect(HelperService.watch(started: old, now: [old[0], nil], specPresent: true, misses: &misses) == .keep)+ #expect(HelperService.watch(started: old, now: [old[0], nil], specPresent: true, misses: &misses) == .stop)+ misses = 0+ #expect(HelperService.watch(started: old, now: old, specPresent: false, misses: &misses) == .keep)+ #expect(HelperService.watch(started: old, now: old, specPresent: false, misses: &misses) == .stop)+ #expect(HelperService.restartExitCode != 0)+ }++ @Test func aFileReplacedAtTheSamePathHasANewIdentity() throws {+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cua-helper-id-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: dir) }+ let file = dir.appendingPathComponent("cua-spacesd")+ try Data("old".utf8).write(to: file)+ let before = HelperService.identity(file.path)+ #expect(before != nil)+ #expect(HelperService.identity(file.path) == before)+ // As an update swaps the bundle: the new file renamed over the old.+ let staged = dir.appendingPathComponent("cua-spacesd.new")+ try Data("new".utf8).write(to: staged)+ #expect(rename(staged.path, file.path) == 0)+ #expect(HelperService.identity(file.path) != before)+ try FileManager.default.removeItem(at: file)+ #expect(HelperService.identity(file.path) == nil)+ }++ /// CUA-2457: at launch, a host service that started before this build's+ /// cua-spacesd was put in place is from the old build, and is restarted.+ @Test func aServiceFromBeforeTheUpdateIsStale() {+ let installed = Date(timeIntervalSince1970: 1_800_000_000)+ #expect(HelperService.isStale(serviceStarted: installed.addingTimeInterval(-3600), daemonInstalled: installed))+ #expect(!HelperService.isStale(serviceStarted: installed.addingTimeInterval(5), daemonInstalled: installed))+ #expect(HelperService.parsePid("gui/501/com.trycua.spaces.helper = {\n\tstate = running\n\tpid = 72613\n}") == 72613)+ #expect(HelperService.parsePid("\tstate = not running\n") == nil)+ // This process started after its own executable was written.+ let me = Bundle.main.executablePath ?? CommandLine.arguments[0]+ let born = HelperService.placedTime(me)+ let started = HelperService.processStart(getpid())+ #expect(born != nil && started != nil)+ if let born, let started { #expect(!HelperService.isStale(serviceStarted: started, daemonInstalled: born)) }+ #expect(HelperService.processStart(-1) == nil)+ }}