@@ -152,11 +152,6 @@ enum ApplicationRelocator {
152152 let launchCodeDirectoryHash : Data ?
153153 }
154154
155- private struct SpawnedReplacement : Sendable {
156- let processIdentifier : pid_t
157- let readyDescriptor : Int32
158- }
159-
160155 private enum ReplacementScheduleResult {
161156 case scheduled
162157 case failed ( supervisor : KeepAliveSupervisor ? )
@@ -188,7 +183,7 @@ enum ApplicationRelocator {
188183 " OPENCLAW_REPLACEMENT_SUPERVISOR_LABEL "
189184 private nonisolated static let replacementSupervisorPlistEnvironmentKey =
190185 " OPENCLAW_REPLACEMENT_SUPERVISOR_PLIST "
191- private nonisolated static let quarantineAttribute = " com.apple.quarantine "
186+ nonisolated static let relocationRelaunchArgument = " --openclaw-relocation-relaunch "
192187
193188 static func recommendation ( for environment : Environment ) -> Recommendation {
194189 guard ! environment . isDebugOrTesting ,
@@ -257,7 +252,16 @@ enum ApplicationRelocator {
257252 bundle : bundle ,
258253 fileManager : fileManager ,
259254 processInfo : processInfo )
260- switch self . recommendation ( for : environment ) {
255+ let recommendation = self . recommendation ( for : environment )
256+ if self . shouldStopRelocationRelaunch (
257+ recommendation : recommendation ,
258+ arguments : processInfo . arguments )
259+ {
260+ self . showFailure (
261+ " OpenClaw is installed in Applications, but couldn’t reopen automatically. Open it there manually. " )
262+ return . continueLaunch ( startUpdater : false )
263+ }
264+ switch recommendation {
261265 case . continueLaunch :
262266 #if DEBUG
263267 let monitorDebugReplacement = processInfo . environment [ " OPENCLAW_MONITOR_APP_REPLACEMENT " ] == " 1 "
@@ -272,11 +276,7 @@ enum ApplicationRelocator {
272276 }
273277 return . continueLaunch ( startUpdater : true )
274278 case let . handOff ( destination ) :
275- return relaunchAndTerminate (
276- at : destination ,
277- bundle : bundle ,
278- fileManager : fileManager ,
279- processInfo : processInfo )
279+ return relaunchAndTerminate ( at : destination )
280280 case let . offerInstall ( destination , replacing ) :
281281 guard confirmInstall ( replacing : replacing ) else {
282282 return . continueLaunch ( startUpdater : false )
@@ -287,11 +287,7 @@ enum ApplicationRelocator {
287287 destination : destination ,
288288 replacing : replacing ,
289289 fileManager : fileManager )
290- return relaunchAndTerminate (
291- at : destination ,
292- bundle : bundle ,
293- fileManager : fileManager ,
294- processInfo : processInfo )
290+ return relaunchAndTerminate ( at : destination )
295291 } catch {
296292 self . logger . error ( " Could not install app: \( error . localizedDescription , privacy : . public ) " )
297293 showFailure (
@@ -307,6 +303,19 @@ enum ApplicationRelocator {
307303 }
308304 }
309305
306+ static func shouldStopRelocationRelaunch (
307+ recommendation : Recommendation ,
308+ arguments : [ String ] ) -> Bool
309+ {
310+ guard arguments . contains ( self . relocationRelaunchArgument ) else { return false }
311+ switch recommendation {
312+ case . handOff , . offerInstall :
313+ return true
314+ case . continueLaunch , . cannotInstall :
315+ return false
316+ }
317+ }
318+
310319 static func currentBundleAllowsPersistentIntegration (
311320 bundle : Bundle = . main ,
312321 fileManager : FileManager = . default ,
@@ -1014,145 +1023,32 @@ extension ApplicationRelocator {
10141023 return alert . runModal ( ) == . alertFirstButtonReturn
10151024 }
10161025
1017- private static func relaunchAndTerminate (
1018- at destination : URL ,
1019- bundle : Bundle ,
1020- fileManager : FileManager ,
1021- processInfo : ProcessInfo ) -> LaunchDisposition
1022- {
1023- // Keep validation, quarantine release, and launch bound to one filesystem
1024- // object so a canonical-path replacement cannot receive the trusted write.
1025- guard let bundleIdentifier = bundle . bundleIdentifier ,
1026- let runningIdentity = runningCodeIdentity ( bundleIdentifier : bundleIdentifier ) ,
1027- let installedApp = applicationOnDisk ( at : destination ) ,
1028- installedApp . bundleIdentifier == bundleIdentifier ,
1029- let launchReference = bundleFileReference (
1030- bundleURL : destination ,
1031- executableURL : installedApp . executableURL ) ,
1032- let installedCodeDirectoryHash = trustedCodeDirectoryHash (
1033- at : launchReference . bundleURL ,
1034- executableURL : launchReference . executableURL ,
1035- matching : runningIdentity . requirementData )
1036- else {
1037- return self . relaunchFailure ( )
1038- }
1039- guard self . gatekeeperAllowsExecution ( at : launchReference . bundleURL ) else {
1040- self . logger . error ( " Gatekeeper rejected installed app before quarantine release " )
1041- return self . relaunchFailure ( )
1042- }
1043-
1044- do {
1045- try self . releaseQuarantine ( from : launchReference , fileManager : fileManager )
1046- } catch {
1047- self . logger . error (
1048- " Could not release installed app from quarantine: \( error . localizedDescription , privacy : . public ) " )
1049- return self . relaunchFailure ( )
1050- }
1051-
1052- // Quarantine metadata is outside the sealed code signature. Revalidate
1053- // the same filesystem object before granting the child handoff authority.
1054- guard self . bundleFileReference (
1055- bundleURL : destination ,
1056- executableURL : installedApp . executableURL ) == launchReference ,
1057- self . trustedCodeDirectoryHash (
1058- at : launchReference . bundleURL ,
1059- executableURL : launchReference . executableURL ,
1060- matching : runningIdentity . requirementData ) == installedCodeDirectoryHash ,
1061- let spawned = spawnReplacement (
1062- launchReference : launchReference ,
1063- sourceBundleURL : destination ,
1064- codeDirectoryHash : installedCodeDirectoryHash ,
1065- supervisor : nil ,
1066- bootoutTarget : nil ,
1067- forwardedArguments : Array ( processInfo . arguments . dropFirst ( ) ) )
1068- else {
1069- return self . relaunchFailure ( )
1070- }
1071-
1072- let timeoutMilliseconds = self . replacementHandoffPolicy . timeoutMilliseconds (
1073- loadAverage : self . currentSystemLoadAverage ( ) ,
1074- activeProcessorCount : processInfo . activeProcessorCount )
1075- let handoffReady = self . awaitReplacementHandoff (
1076- from : spawned ,
1077- timeoutMilliseconds : timeoutMilliseconds )
1078- guard handoffReady else {
1079- self . logger . error ( " Installed app handoff failed after \( timeoutMilliseconds ) ms " )
1080- return self . relaunchFailure ( )
1081- }
1082-
1083- TerminationSignalWatcher . scheduleExitFailsafe ( )
1084- AppDelegate . requestTermination ( )
1085- return . terminating
1086- }
1087-
1088- private nonisolated static func gatekeeperAllowsExecution ( at bundleURL : URL ) -> Bool {
1089- let assessment = Process ( )
1090- assessment . executableURL = URL ( fileURLWithPath : " /usr/sbin/spctl " )
1091- assessment . arguments = [ " --assess " , " --type " , " execute " , bundleURL . path ]
1092- assessment . standardOutput = FileHandle . nullDevice
1093- assessment . standardError = FileHandle . nullDevice
1026+ private static func relaunchAndTerminate ( at destination : URL ) -> LaunchDisposition {
1027+ let helper = Process ( )
1028+ helper . executableURL = URL ( fileURLWithPath : " /bin/sh " )
1029+ let processInfo = ProcessInfo . processInfo
1030+ helper . arguments = [
1031+ " -c " ,
1032+ " while /bin/kill -0 \" $2 \" 2>/dev/null; do /bin/sleep 0.1; done; " +
1033+ " exec /usr/bin/open -n \" $1 \" --args \" $3 \" " ,
1034+ " openclaw-relocation " ,
1035+ destination . path ,
1036+ String ( processInfo . processIdentifier ) ,
1037+ self . relocationRelaunchArgument ,
1038+ ]
10941039 do {
1095- try assessment . run ( )
1096- assessment . waitUntilExit ( )
1097- return assessment . terminationReason == . exit && assessment . terminationStatus == 0
1040+ try helper . run ( )
1041+ TerminationSignalWatcher . scheduleExitFailsafe ( )
1042+ AppDelegate . requestTermination ( )
1043+ return . terminating
10981044 } catch {
1099- return false
1100- }
1101- }
1102-
1103- static func releaseQuarantine (
1104- from launchReference : BundleFileReference ,
1105- fileManager : FileManager = . default ) throws
1106- {
1107- let rootURL = launchReference . bundleURL
1108- try self . removeQuarantineAttribute ( at : rootURL )
1109- var enumerationError : Error ?
1110- guard let enumerator = fileManager . enumerator (
1111- at : rootURL ,
1112- includingPropertiesForKeys : nil ,
1113- options : [ ] ,
1114- errorHandler : { _ , error in
1115- enumerationError = error
1116- return false
1117- } )
1118- else {
1119- throw CocoaError ( . fileReadUnknown )
1120- }
1121- while let url = enumerator . nextObject ( ) as? URL {
1122- try self . removeQuarantineAttribute ( at : url )
1123- }
1124- if let enumerationError {
1125- throw enumerationError
1126- }
1127- }
1128-
1129- private nonisolated static func removeQuarantineAttribute ( at url : URL ) throws {
1130- var attributeErrno : Int32 = 0
1131- let result : Int32 = url . withUnsafeFileSystemRepresentation { path in
1132- guard let path else {
1133- attributeErrno = EINVAL
1134- return - 1
1135- }
1136- return self . quarantineAttribute . withCString { attribute in
1137- let result = removexattr ( path , attribute , XATTR_NOFOLLOW )
1138- attributeErrno = errno
1139- return result
1140- }
1141- }
1142- guard result == 0 || attributeErrno == ENOATTR else {
1143- throw NSError (
1144- domain : NSPOSIXErrorDomain ,
1145- code : Int ( attributeErrno ) ,
1146- userInfo : [ NSFilePathErrorKey : url . path ] )
1045+ self . logger . error ( " Could not schedule relaunch: \( error . localizedDescription , privacy : . public ) " )
1046+ self . showFailure (
1047+ " OpenClaw is installed in Applications, but couldn’t reopen automatically. Open it there manually. " )
1048+ return . continueLaunch ( startUpdater : false )
11471049 }
11481050 }
11491051
1150- private static func relaunchFailure ( ) -> LaunchDisposition {
1151- self . showFailure (
1152- " OpenClaw is installed in Applications, but couldn’t reopen automatically. Open it there manually. " )
1153- return . continueLaunch ( startUpdater : false )
1154- }
1155-
11561052 private static func startSupervisorRestorationWatcher ( _ supervisor : KeepAliveSupervisor ) -> Bool {
11571053 guard self . supervisorRestorationWatcher == nil else { return true }
11581054 let watcher = Process ( )
@@ -1220,12 +1116,17 @@ extension ApplicationRelocator {
12201116 loadAverage : self . currentSystemLoadAverage ( ) ,
12211117 activeProcessorCount : processInfo . activeProcessorCount )
12221118 Task { @MainActor in
1223- let handoffReady = await Task . detached ( priority : . utility ) {
1119+ let handoffStatus = await Task . detached ( priority : . utility ) {
12241120 self . awaitReplacementHandoff (
1225- from : spawned ,
1121+ on : spawned . readyDescriptor ,
12261122 timeoutMilliseconds : timeoutMilliseconds )
12271123 } . value
1228- guard handoffReady else {
1124+ Darwin . close ( spawned . readyDescriptor )
1125+ guard handoffStatus == " READY " else {
1126+ Darwin . kill ( spawned . processIdentifier , SIGKILL )
1127+ await Task . detached ( priority : . utility ) {
1128+ self . reapProcess ( spawned . processIdentifier )
1129+ } . value
12291130 await self . handleReplacementHandoffFailure (
12301131 attempt : attempt ,
12311132 targetCodeDirectoryHash : codeDirectoryHash ,
@@ -1343,7 +1244,7 @@ extension ApplicationRelocator {
13431244 codeDirectoryHash : Data ,
13441245 supervisor : KeepAliveSupervisor ? ,
13451246 bootoutTarget : String ? ,
1346- forwardedArguments : [ String ] ) -> SpawnedReplacement ?
1247+ forwardedArguments : [ String ] ) -> ( processIdentifier : pid_t , readyDescriptor : Int32 ) ?
13471248 {
13481249 let childReadyDescriptor : Int32 = 19
13491250 var descriptors = [ Int32 ] ( repeating : - 1 , count : 2 )
@@ -1443,9 +1344,7 @@ extension ApplicationRelocator {
14431344 Darwin . close ( readDescriptor )
14441345 return nil
14451346 }
1446- return SpawnedReplacement (
1447- processIdentifier : processIdentifier ,
1448- readyDescriptor : readDescriptor )
1347+ return ( processIdentifier , readDescriptor )
14491348 }
14501349
14511350 private nonisolated static func currentSystemLoadAverage ( ) -> Double ? {
@@ -1454,27 +1353,17 @@ extension ApplicationRelocator {
14541353 }
14551354
14561355 private nonisolated static func awaitReplacementHandoff (
1457- from replacement : SpawnedReplacement ,
1458- timeoutMilliseconds : Int32 ) -> Bool
1356+ on descriptor : Int32 ,
1357+ timeoutMilliseconds : Int32 ) -> String ?
14591358 {
1460- defer { Darwin . close ( replacement . readyDescriptor ) }
1461- var event = pollfd (
1462- fd : replacement . readyDescriptor ,
1463- events : Int16 ( POLLIN | POLLHUP ) ,
1464- revents : 0 )
1465- var handoffReady = false
1466- if poll ( & event , 1 , timeoutMilliseconds ) > 0 {
1467- var bytes = [ UInt8 ] ( repeating : 0 , count : 16 )
1468- let count = bytes . withUnsafeMutableBytes { buffer in
1469- Darwin . read ( replacement . readyDescriptor , buffer . baseAddress , buffer . count )
1470- }
1471- handoffReady = count > 0 && String ( bytes : bytes . prefix ( count ) , encoding : . utf8 ) == " READY "
1472- }
1473- if ! handoffReady {
1474- Darwin . kill ( replacement . processIdentifier , SIGKILL )
1475- self . reapProcess ( replacement . processIdentifier )
1359+ var event = pollfd ( fd : descriptor , events : Int16 ( POLLIN | POLLHUP ) , revents : 0 )
1360+ guard poll ( & event , 1 , timeoutMilliseconds ) > 0 else { return nil }
1361+ var bytes = [ UInt8 ] ( repeating : 0 , count : 16 )
1362+ let count = bytes . withUnsafeMutableBytes { buffer in
1363+ Darwin . read ( descriptor , buffer . baseAddress , buffer . count )
14761364 }
1477- return handoffReady
1365+ guard count > 0 else { return nil }
1366+ return String ( bytes : bytes . prefix ( count ) , encoding : . utf8 )
14781367 }
14791368
14801369 private nonisolated static func reapProcess ( _ processIdentifier : pid_t ) {
0 commit comments