Skip to content

Commit 9d9d431

Browse files
committed
fix(macos): sequence gateway startup persistence
1 parent 3347c31 commit 9d9d431

4 files changed

Lines changed: 160 additions & 11 deletions

File tree

‎apps/.i18n/native-source.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29595,15 +29595,15 @@
2959529595
},
2959629596
{
2959729597
"kind": "conditional-branch",
29598-
"line": 433,
29598+
"line": 459,
2959929599
"path": "apps/macos/Sources/OpenClaw/GatewayProcessManager.swift",
2960029600
"source": "not linked",
2960129601
"surface": "apple",
2960229602
"id": "native.apple.151e5b5ab7d08a2a"
2960329603
},
2960429604
{
2960529605
"kind": "conditional-branch",
29606-
"line": 446,
29606+
"line": 472,
2960729607
"path": "apps/macos/Sources/OpenClaw/GatewayProcessManager.swift",
2960829608
"source": "unknown error",
2960929609
"surface": "apple",

‎apps/macos/Sources/OpenClaw/ConnectionModeCoordinator.swift‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,13 @@ final class ConnectionModeCoordinator {
77

88
private let logger = Logger(subsystem: "ai.openclaw", category: "connection")
99
private var lastMode: AppState.ConnectionMode?
10+
private var applyGeneration: UInt64 = 0
1011

1112
/// Apply the requested connection mode by starting/stopping local gateway,
1213
/// managing the control-channel SSH tunnel, and cleaning up chat windows/panels.
1314
func apply(mode: AppState.ConnectionMode, paused: Bool) async {
15+
self.applyGeneration &+= 1
16+
let applyGeneration = self.applyGeneration
1417
if let lastMode = self.lastMode, lastMode != mode {
1518
GatewayProcessManager.shared.clearLastFailure()
1619
NodesStore.shared.lastError = nil
@@ -29,19 +32,26 @@ final class ConnectionModeCoordinator {
2932

3033
case .local:
3134
_ = await NodeServiceManager.stop()
35+
guard self.applyGeneration == applyGeneration else { return }
3236
NodesStore.shared.lastError = nil
3337
await RemoteTunnelManager.shared.stopAll()
38+
guard self.applyGeneration == applyGeneration else { return }
3439
WebChatManager.shared.resetTunnels()
3540
let shouldStart = GatewayAutostartPolicy.shouldStartGateway(mode: .local, paused: paused)
3641
if shouldStart {
3742
GatewayProcessManager.shared.setActive(true)
43+
await GatewayProcessManager.shared.waitForStartupAttempt()
44+
guard self.applyGeneration == applyGeneration else { return }
3845
if GatewayAutostartPolicy.shouldEnsureLaunchAgent(
3946
mode: .local,
4047
paused: paused)
4148
{
42-
Task { await GatewayProcessManager.shared.ensureLaunchAgentEnabledIfNeeded() }
49+
await GatewayProcessManager.shared.ensureLaunchAgentEnabledIfNeeded()
4350
}
51+
// Always finish the generation-aware health audit after persistence work. A newer
52+
// inactive lifecycle makes this return false without touching its repair marker.
4453
_ = await GatewayProcessManager.shared.waitForGatewayReady()
54+
guard self.applyGeneration == applyGeneration else { return }
4555
} else {
4656
GatewayProcessManager.shared.stop()
4757
}

‎apps/macos/Sources/OpenClaw/GatewayProcessManager.swift‎

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ final class GatewayProcessManager {
7171
/// Async readiness audits may outlive stop/restart. Only the current generation may publish
7272
/// their failure state or retain a PID for a later repair.
7373
private var gatewayStartGeneration: UInt64 = 0
74+
private var gatewayStartTask: Task<Void, Never>?
75+
private var gatewayStartTaskGeneration: UInt64?
7476
#if DEBUG
7577
private var testingConnection: GatewayConnection?
7678
private var testingSkipControlChannelRefresh = false
@@ -182,7 +184,21 @@ final class GatewayProcessManager {
182184
private func performLaunchAgentEnable(_ request: LaunchAgentEnableRequest) async -> String? {
183185
// App startup and onboarding can request persistence together. One drain owns all installs;
184186
// a second forced install would kill the first Gateway during startup migrations.
185-
if let pid = await GatewayLaunchAgentManager.reusableLoadedGatewayPID(port: request.port) {
187+
let reusablePID = await GatewayLaunchAgentManager.reusableLoadedGatewayPID(port: request.port)
188+
if let listener = await PortGuardian.shared.describe(port: request.port) {
189+
let managedPID = if let reusablePID {
190+
reusablePID
191+
} else {
192+
await GatewayLaunchAgentManager.runningGatewayPID()
193+
}
194+
guard listener.pid == managedPID else {
195+
// A healthy manually started Gateway may be attached without becoming app-owned.
196+
// Persistence checks and retained repair markers must not replace it.
197+
return nil
198+
}
199+
}
200+
201+
if let pid = reusablePID {
186202
let failure = LaunchAgentReadinessFailure(port: request.port, pid: pid)
187203
if self.launchAgentReadinessFailure != failure {
188204
// A new launchd PID may still be running migrations. It must fail one complete
@@ -191,12 +207,6 @@ final class GatewayProcessManager {
191207
return nil
192208
}
193209

194-
let listener = await PortGuardian.shared.describe(port: request.port)
195-
if let listener, listener.pid != pid {
196-
// A foreign listener must never be displaced. The attach path reports its failure.
197-
return nil
198-
}
199-
200210
self.appendLog(
201211
"[gateway] launchd pid \(pid) failed readiness on port \(request.port); repairing\n")
202212
self.logger.warning(
@@ -250,13 +260,29 @@ final class GatewayProcessManager {
250260
self.logger.debug("gateway start requested")
251261

252262
// First try to latch onto an already-running gateway to avoid spawning a duplicate.
253-
Task { [weak self] in
263+
let task = Task { [weak self] in
254264
guard let self else { return }
265+
defer {
266+
if self.gatewayStartTaskGeneration == startGeneration {
267+
self.gatewayStartTask = nil
268+
self.gatewayStartTaskGeneration = nil
269+
}
270+
}
255271
if await self.attachExistingGatewayAfterPendingDisable(startGeneration: startGeneration) {
256272
return
257273
}
258274
await self.enableLaunchdGateway(startGeneration: startGeneration)
259275
}
276+
self.gatewayStartTaskGeneration = startGeneration
277+
self.gatewayStartTask = task
278+
}
279+
280+
func waitForStartupAttempt() async {
281+
// Persistence/repair follows the complete attach-or-start decision. This prevents the
282+
// automatic ensure path from replacing a PID while startup is accepting that same PID.
283+
while let task = self.gatewayStartTask {
284+
await task.value
285+
}
260286
}
261287

262288
func stop() {
@@ -589,12 +615,17 @@ final class GatewayProcessManager {
589615
}
590616

591617
func waitForGatewayReady(timeout: TimeInterval = 6) async -> Bool {
618+
let startGeneration = self.gatewayStartGeneration
592619
let deadline = Date().addingTimeInterval(timeout)
593620
while Date() < deadline {
594621
if !self.desiredActive { return false }
595622
do {
596623
let remainingMs = max(1, deadline.timeIntervalSinceNow * 1000)
597624
_ = try await self.probeGatewayHealth(timeoutMs: min(1500, remainingMs))
625+
guard self.desiredActive, self.gatewayStartGeneration == startGeneration else {
626+
return false
627+
}
628+
self.launchAgentReadinessFailure = nil
598629
self.clearLastFailure()
599630
return true
600631
} catch {
@@ -698,6 +729,10 @@ extension GatewayProcessManager {
698729
self.launchAgentReadinessFailure = nil
699730
}
700731

732+
func _testSetLaunchAgentReadinessFailure(port: Int, pid: Int32) {
733+
self.launchAgentReadinessFailure = LaunchAgentReadinessFailure(port: port, pid: pid)
734+
}
735+
701736
func _testHasLaunchAgentReadinessFailure() -> Bool {
702737
self.launchAgentReadinessFailure != nil
703738
}

‎apps/macos/Tests/OpenClawIPCTests/GatewayProcessManagerTests.swift‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,27 @@ struct GatewayProcessManagerTests {
374374
}
375375
}
376376

377+
@Test func `inactive lifecycle skips persistence ensure`() async throws {
378+
let marker = FileManager.default.temporaryDirectory
379+
.appendingPathComponent("openclaw-launchagent-marker-\(UUID().uuidString)")
380+
try await self.withLocalGatewayConfig {
381+
GatewayLaunchAgentManager.setTestingDisableLaunchAgentMarkerURL(marker)
382+
GatewayLaunchAgentManager.setTestingInterceptDaemonCommands(true)
383+
GatewayLaunchAgentManager.clearTestingDaemonCommandCalls()
384+
defer {
385+
GatewayLaunchAgentManager.setTestingDisableLaunchAgentMarkerURL(nil)
386+
GatewayLaunchAgentManager.setTestingInterceptDaemonCommands(false)
387+
GatewayLaunchAgentManager.clearTestingDaemonCommandCalls()
388+
}
389+
390+
let manager = GatewayProcessManager.shared
391+
manager.setTestingDesiredActive(false)
392+
await manager.ensureLaunchAgentEnabledIfNeeded()
393+
394+
#expect(GatewayLaunchAgentManager.testingDaemonCommandCallsSnapshot().isEmpty)
395+
}
396+
}
397+
377398
@Test func `newer inactive lifecycle retains the pending disable`() async throws {
378399
let marker = FileManager.default.temporaryDirectory
379400
.appendingPathComponent("openclaw-launchagent-marker-\(UUID().uuidString)")
@@ -736,6 +757,40 @@ struct GatewayProcessManagerTests {
736757
}
737758
}
738759

760+
@Test func `protects an unmanaged listener during persistence ensure`() async throws {
761+
let port = 19100
762+
let marker = FileManager.default.temporaryDirectory
763+
.appendingPathComponent("openclaw-launchagent-marker-\(UUID().uuidString)")
764+
try await self.withLocalGatewayConfig {
765+
GatewayLaunchAgentManager.setTestingDisableLaunchAgentMarkerURL(marker)
766+
GatewayLaunchAgentManager.setTestingInterceptDaemonCommands(true)
767+
GatewayLaunchAgentManager.setTestingDaemonStatusPayload(
768+
#"{"ok":true,"service":{"loaded":false}}"#)
769+
GatewayLaunchAgentManager.clearTestingDaemonCommandCalls()
770+
defer {
771+
GatewayLaunchAgentManager.setTestingDisableLaunchAgentMarkerURL(nil)
772+
GatewayLaunchAgentManager.setTestingInterceptDaemonCommands(false)
773+
GatewayLaunchAgentManager.setTestingDaemonStatusPayload(nil)
774+
GatewayLaunchAgentManager.clearTestingDaemonCommandCalls()
775+
}
776+
777+
let listener = PortGuardian.Descriptor(
778+
pid: 4243,
779+
command: "manual-gateway",
780+
executablePath: "/tmp/manual-gateway")
781+
await PortGuardian.shared.setTestingDescriptor(listener, forPort: port)
782+
783+
_ = await GatewayProcessManager.shared._testEnableLaunchAgentIfNeeded(
784+
bundlePath: "/Applications/OpenClaw.app",
785+
port: port)
786+
787+
let calls = GatewayLaunchAgentManager.testingDaemonCommandCallsSnapshot()
788+
#expect(calls.filter { $0.first == "status" }.count == 2)
789+
#expect(calls.filter { $0.first == "install" }.isEmpty)
790+
await PortGuardian.shared.setTestingDescriptor(nil, forPort: port)
791+
}
792+
}
793+
739794
@Test func `repairs loaded launch agents that are not reusable`() async throws {
740795
let port = 19083
741796
let marker = FileManager.default.temporaryDirectory
@@ -811,15 +866,64 @@ struct GatewayProcessManagerTests {
811866
manager.setTestingConnection(connection)
812867
manager.setTestingDesiredActive(true)
813868
manager.setTestingLastFailureReason("health failed")
869+
manager._testSetLaunchAgentReadinessFailure(port: 19101, pid: 4242)
814870
defer {
815871
manager.setTestingConnection(nil)
816872
manager.setTestingDesiredActive(false)
817873
manager.setTestingLastFailureReason(nil)
874+
manager._testClearLaunchAgentReadinessFailure()
818875
}
819876

820877
let ready = await manager.waitForGatewayReady(timeout: 0.5)
821878
#expect(ready)
822879
#expect(manager.lastFailureReason == nil)
880+
#expect(!manager._testHasLaunchAgentReadinessFailure())
881+
}
882+
883+
@Test func `stale readiness wait cannot clear a newer launch failure`() async throws {
884+
let session = GatewayTestWebSocketSession(
885+
taskFactory: {
886+
GatewayTestWebSocketTask(
887+
sendHook: { task, message, sendIndex in
888+
guard sendIndex > 0 else { return }
889+
guard let id = GatewayWebSocketTestSupport.requestID(from: message) else { return }
890+
task.emitReceiveSuccess(.data(GatewayWebSocketTestSupport.okResponseData(id: id)))
891+
},
892+
receiveHook: { _, receiveIndex in
893+
if receiveIndex == 0 {
894+
try await Task.sleep(nanoseconds: 100_000_000)
895+
}
896+
return .data(GatewayWebSocketTestSupport.connectChallengeData())
897+
})
898+
})
899+
let url = try #require(URL(string: "ws://example.invalid"))
900+
let connection = GatewayConnection(
901+
configProvider: { (url: url, token: nil, password: nil) },
902+
sessionBox: WebSocketSessionBox(session: session))
903+
904+
let manager = GatewayProcessManager.shared
905+
manager.setTestingConnection(connection)
906+
manager._testBeginGatewayStartGeneration()
907+
defer {
908+
manager.setTestingConnection(nil)
909+
manager.setTestingDesiredActive(false)
910+
manager._testClearLaunchAgentReadinessFailure()
911+
}
912+
913+
let staleWait = Task { @MainActor in
914+
await manager.waitForGatewayReady(timeout: 0.5)
915+
}
916+
for _ in 0..<100 {
917+
if session.snapshotMakeCount() > 0 { break }
918+
try? await Task.sleep(nanoseconds: 1_000_000)
919+
}
920+
#expect(session.snapshotMakeCount() == 1)
921+
manager._testBeginGatewayStartGeneration()
922+
manager._testSetLaunchAgentReadinessFailure(port: 19101, pid: 4242)
923+
924+
#expect(await staleWait.value == false)
925+
#expect(manager._testHasLaunchAgentReadinessFailure())
926+
await connection.shutdown()
823927
}
824928

825929
@Test func `readiness timeout includes a stalled socket connect`() async throws {

0 commit comments

Comments
 (0)