Skip to content

Commit 8b5a02c

Browse files
authored
fix(mac): serialize persistent node service lifecycle operations (#127732)
1 parent fc42535 commit 8b5a02c

2 files changed

Lines changed: 103 additions & 30 deletions

File tree

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

Lines changed: 29 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -3,48 +3,22 @@ import OSLog
33

44
enum NodeServiceManager {
55
private static let logger = Logger(subsystem: "ai.openclaw", category: "node.service")
6+
private static let lifecycleQueue = LifecycleQueue()
67
private static var launchdPlistURL: URL {
78
FileManager.default.homeDirectoryForCurrentUser
89
.appendingPathComponent("Library/LaunchAgents/\(nodeLaunchdLabel).plist")
910
}
1011

1112
static func start(profile: AppProfile = .current) async -> String? {
12-
if self.skipUnderProfile(profile, action: "start") { return nil }
13-
let result = await self.runServiceCommandResult(
14-
["start"],
15-
timeout: 20,
16-
quiet: false)
17-
if let error = self.errorMessage(from: result, treatNotLoadedAsError: true) {
18-
self.logger.error("node service start failed: \(error, privacy: .public)")
19-
return error
20-
}
21-
return nil
13+
await self.lifecycleQueue.run("start", profile: profile)
2214
}
2315

2416
static func stop(profile: AppProfile = .current) async -> String? {
25-
if self.skipUnderProfile(profile, action: "stop") { return nil }
26-
let result = await self.runServiceCommandResult(
27-
["stop"],
28-
timeout: 15,
29-
quiet: false)
30-
if let error = self.errorMessage(from: result, treatNotLoadedAsError: false) {
31-
self.logger.error("node service stop failed: \(error, privacy: .public)")
32-
return error
33-
}
34-
return nil
17+
await self.lifecycleQueue.run("stop", profile: profile)
3518
}
3619

3720
static func restart(profile: AppProfile = .current) async -> String? {
38-
if self.skipUnderProfile(profile, action: "restart") { return nil }
39-
let result = await self.runServiceCommandResult(
40-
["restart"],
41-
timeout: 20,
42-
quiet: false)
43-
if let error = self.errorMessage(from: result, treatNotLoadedAsError: true) {
44-
self.logger.error("node service restart failed: \(error, privacy: .public)")
45-
return error
46-
}
47-
return nil
21+
await self.lifecycleQueue.run("restart", profile: profile)
4822
}
4923

5024
/// Empty means no node LaunchAgent. Nil means the on-disk ownership proof
@@ -82,6 +56,31 @@ enum NodeServiceManager {
8256
}
8357

8458
extension NodeServiceManager {
59+
private actor LifecycleQueue {
60+
private var tail: Task<String?, Never>?
61+
62+
func run(_ action: String, profile: AppProfile) async -> String? {
63+
if NodeServiceManager.skipUnderProfile(profile, action: action) { return nil }
64+
let predecessor = self.tail
65+
let task = Task<String?, Never> {
66+
_ = await predecessor?.value
67+
let result = await NodeServiceManager.runServiceCommandResult(
68+
[action],
69+
timeout: action == "stop" ? 15 : 20,
70+
quiet: false)
71+
guard let error = NodeServiceManager.errorMessage(
72+
from: result,
73+
treatNotLoadedAsError: action != "stop")
74+
else { return nil }
75+
NodeServiceManager.logger.error(
76+
"node service \(action, privacy: .public) failed: \(error, privacy: .public)")
77+
return error
78+
}
79+
self.tail = task
80+
return await task.value
81+
}
82+
}
83+
8584
private static func skipUnderProfile(_ profile: AppProfile, action: String) -> Bool {
8685
guard profile.isActive else { return false }
8786
self.logger.info("node service \(action, privacy: .public) skipped (unavailable under app profile)")

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

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,67 @@ import Testing
3636
}
3737
}
3838

39+
@Test(arguments: ["start:stop", "stop:start", "restart:stop"])
40+
func `node lifecycle commands finish in request order`(_ transition: String) async throws {
41+
let actions = transition.split(separator: ":").map(String.init)
42+
let previousAction = try #require(actions.first)
43+
let nextAction = try #require(actions.last)
44+
let root = try makeTempDirForTests()
45+
defer { try? FileManager.default.removeItem(at: root) }
46+
47+
try await TestIsolation.withIsolatedState(
48+
env: [
49+
"OPENCLAW_NODE_SERVICE_TEST_ROOT": root.path,
50+
"OPENCLAW_NODE_SERVICE_DELAYED_ACTION": previousAction,
51+
],
52+
defaults: ["openclaw.gatewayProjectRootPath": nil])
53+
{
54+
CommandResolver.setProjectRoot(root.path)
55+
let executable = root.appendingPathComponent("node_modules/.bin/openclaw")
56+
try makeExecutableForTests(at: executable)
57+
let script = """
58+
#!/bin/sh
59+
action="$2"
60+
: > "$OPENCLAW_NODE_SERVICE_TEST_ROOT/$action.entered"
61+
if [ "$action" = "$OPENCLAW_NODE_SERVICE_DELAYED_ACTION" ]; then
62+
while [ ! -f "$OPENCLAW_NODE_SERVICE_TEST_ROOT/release" ]; do
63+
sleep 0.01
64+
done
65+
fi
66+
if [ "$action" = "stop" ]; then
67+
printf stopped > "$OPENCLAW_NODE_SERVICE_TEST_ROOT/state"
68+
else
69+
printf running > "$OPENCLAW_NODE_SERVICE_TEST_ROOT/state"
70+
fi
71+
printf '{"ok":true}'
72+
"""
73+
try script.write(to: executable, atomically: false, encoding: .utf8)
74+
75+
let release = root.appendingPathComponent("release")
76+
defer { try? Data().write(to: release) }
77+
let profile = AppProfile(environment: [:])
78+
let previous = Task { await self.runNodeServiceAction(previousAction, profile: profile) }
79+
let previousEntered = root.appendingPathComponent("\(previousAction).entered")
80+
for _ in 0..<200 where !FileManager.default.fileExists(atPath: previousEntered.path) {
81+
try await Task.sleep(for: .milliseconds(10))
82+
}
83+
try #require(FileManager.default.fileExists(atPath: previousEntered.path))
84+
85+
let next = Task { await self.runNodeServiceAction(nextAction, profile: profile) }
86+
let nextEntered = root.appendingPathComponent("\(nextAction).entered")
87+
for _ in 0..<50 where !FileManager.default.fileExists(atPath: nextEntered.path) {
88+
try await Task.sleep(for: .milliseconds(10))
89+
}
90+
#expect(!FileManager.default.fileExists(atPath: nextEntered.path))
91+
92+
try Data().write(to: release)
93+
#expect(await previous.value == nil)
94+
#expect(await next.value == nil)
95+
let observed = try String(contentsOf: root.appendingPathComponent("state"), encoding: .utf8)
96+
#expect(observed == (nextAction == "stop" ? "stopped" : "running"))
97+
}
98+
}
99+
39100
@Test func `reads node service ownership command directly from launchd`() throws {
40101
let url = FileManager.default.temporaryDirectory
41102
.appendingPathComponent("openclaw-node-\(UUID().uuidString).plist")
@@ -70,4 +131,17 @@ import Testing
70131
{"service":{"loaded":true,"runtime":{"status":"stopped"}}}
71132
"""))
72133
}
134+
135+
private func runNodeServiceAction(_ action: String, profile: AppProfile) async -> String? {
136+
switch action {
137+
case "start":
138+
await NodeServiceManager.start(profile: profile)
139+
case "stop":
140+
await NodeServiceManager.stop(profile: profile)
141+
case "restart":
142+
await NodeServiceManager.restart(profile: profile)
143+
default:
144+
"Unknown node service action"
145+
}
146+
}
73147
}

0 commit comments

Comments
 (0)