Skip to content

Commit 35baff2

Browse files
committed
fix(macos): recover node startup after legacy identity recreation
1 parent 876a3f0 commit 35baff2

12 files changed

Lines changed: 222 additions & 79 deletions

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,27 @@ enum CommandResolver {
254254
#endif
255255
}
256256

257+
static func projectNodeHostWorkerLaunch(
258+
projectRoot: URL? = nil,
259+
searchPaths: [String]? = nil) async throws -> MacNodeHostWorkerLaunch?
260+
{
261+
#if DEBUG
262+
let root = projectRoot ?? self.projectRoot()
263+
let sourceRunner = root.appendingPathComponent("scripts/run-node.mjs")
264+
guard FileManager().isReadableFile(atPath: sourceRunner.path) else { return nil }
265+
switch await self.runtimeResolution(searchPaths: searchPaths) {
266+
case let .success(runtime):
267+
return MacNodeHostWorkerLaunch(
268+
command: [runtime.path, sourceRunner.path, "node", "worker"],
269+
currentDirectoryURL: root)
270+
case let .failure(error):
271+
throw error
272+
}
273+
#else
274+
return nil
275+
#endif
276+
}
277+
257278
static func openclawNodeCommand(
258279
subcommand: String,
259280
extraArgs: [String] = [],

‎apps/macos/Sources/OpenClaw/NodeMode/MacNodeHostWorker.swift‎

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,18 @@ struct MacNodeHostManifest: Equatable, Sendable {
1616
let pathEnv: String
1717
}
1818

19+
struct MacNodeHostWorkerLaunch: Equatable, Sendable {
20+
let command: [String]
21+
let currentDirectoryURL: URL?
22+
23+
init(command: [String], currentDirectoryURL: URL? = nil) {
24+
self.command = command
25+
self.currentDirectoryURL = currentDirectoryURL
26+
}
27+
}
28+
1929
protocol MacNodeHostWorking: Sendable {
20-
func start(command: [String]) async throws -> MacNodeHostManifest
30+
func start(launch: MacNodeHostWorkerLaunch) async throws -> MacNodeHostManifest
2131
func supports(_ command: String) async -> Bool
2232
func invoke(_ request: BridgeInvokeRequest) async -> BridgeInvokeResponse
2333
func handleInput(invokeId: String, seq: Int, payloadJSON: String) async
@@ -63,7 +73,7 @@ final class MacNodeHostWorker: MacNodeHostWorking, @unchecked Sendable {
6373
private var stdoutSource: DispatchSourceRead?
6474
private var stderrSource: DispatchSourceRead?
6575
private var processGeneration: UUID?
66-
private var launchedCommand: [String]?
76+
private var launchedWorker: MacNodeHostWorkerLaunch?
6777
private var stdoutBuffer = Data()
6878
private var manifest: MacNodeHostManifest?
6979
private var inventoryData: Data?
@@ -89,12 +99,12 @@ final class MacNodeHostWorker: MacNodeHostWorking, @unchecked Sendable {
8999
self.onUnexpectedExit = onUnexpectedExit
90100
}
91101

92-
func start(command: [String]) async throws -> MacNodeHostManifest {
102+
func start(launch: MacNodeHostWorkerLaunch) async throws -> MacNodeHostManifest {
93103
try await withCheckedThrowingContinuation { continuation in
94104
self.queue.async {
95105
if let manifest = self.manifest,
96106
self.process?.isRunning == true,
97-
self.launchedCommand == command
107+
self.launchedWorker == launch
98108
{
99109
continuation.resume(returning: manifest)
100110
return
@@ -104,7 +114,7 @@ final class MacNodeHostWorker: MacNodeHostWorking, @unchecked Sendable {
104114
return
105115
}
106116
self.startContinuation = continuation
107-
self.startLocked(command: command)
117+
self.startLocked(launch: launch)
108118
}
109119
}
110120
}
@@ -285,7 +295,8 @@ final class MacNodeHostWorker: MacNodeHostWorking, @unchecked Sendable {
285295
}
286296
}
287297

288-
private func startLocked(command: [String]) {
298+
private func startLocked(launch: MacNodeHostWorkerLaunch) {
299+
let command = launch.command
289300
guard let executable = command.first, !executable.isEmpty else {
290301
self.finishStartLocked(.failure(WorkerError.unavailable("node-host worker command missing")))
291302
return
@@ -303,6 +314,7 @@ final class MacNodeHostWorker: MacNodeHostWorking, @unchecked Sendable {
303314
}
304315
process.executableURL = URL(fileURLWithPath: executable)
305316
process.arguments = Array(command.dropFirst())
317+
process.currentDirectoryURL = launch.currentDirectoryURL
306318
var environment = ProcessInfo.processInfo.environment
307319
environment["PATH"] = CommandResolver.preferredPaths().joined(separator: ":")
308320
environment["OPENCLAW_NODE_EXEC_HOST"] = "app"
@@ -312,7 +324,7 @@ final class MacNodeHostWorker: MacNodeHostWorking, @unchecked Sendable {
312324
process.standardOutput = stdoutPipe
313325
process.standardError = stderrPipe
314326
self.process = process
315-
self.launchedCommand = command
327+
self.launchedWorker = launch
316328
self.stdinPipe = stdinPipe
317329
self.stdoutPipe = stdoutPipe
318330
self.stderrPipe = stderrPipe
@@ -646,7 +658,7 @@ final class MacNodeHostWorker: MacNodeHostWorking, @unchecked Sendable {
646658
self.process?.terminate()
647659
}
648660
self.process = nil
649-
self.launchedCommand = nil
661+
self.launchedWorker = nil
650662
self.stdinPipe = nil
651663
self.stdoutPipe = nil
652664
self.stderrPipe = nil

‎apps/macos/Sources/OpenClaw/NodeMode/MacNodeHostWorkerRetryPolicy.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import Foundation
22

33
struct MacNodeHostWorkerRetryPolicy: Sendable {
44
struct Input: Equatable, Sendable {
5-
let command: [String]
5+
let launch: MacNodeHostWorkerLaunch
66
let configurationGeneration: UInt64
77
}
88

‎apps/macos/Sources/OpenClaw/NodeMode/MacNodeModeCoordinator.swift‎

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -753,7 +753,7 @@ final class MacNodeModeCoordinator: NSObject {
753753
throw MacNodeHostWorkerRetryPolicy.RetryBackoffPending()
754754
}
755755
let input = MacNodeHostWorkerRetryPolicy.Input(
756-
command: command,
756+
launch: MacNodeHostWorkerLaunch(command: command),
757757
configurationGeneration: self.nodeHostWorkerConfigurationGeneration)
758758
try self.nodeHostWorkerRetryPolicy.prepareForStart(input)
759759
self.activeNodeHostWorkerInput = input
@@ -823,23 +823,27 @@ final class MacNodeModeCoordinator: NSObject {
823823
guard self.nodeHostWorkerRetryTask == nil else {
824824
throw MacNodeHostWorkerRetryPolicy.RetryBackoffPending()
825825
}
826-
let executable: String
827-
if let projectExecutable = CommandResolver.projectOpenClawExecutable() {
828-
executable = projectExecutable
829-
} else {
830-
switch await CLIInstaller.status() {
831-
case let .ready(location, _): executable = location
832-
case let status:
833-
throw MacNodeHostWorker.WorkerError.unavailable(status.message)
826+
let launch: MacNodeHostWorkerLaunch
827+
do {
828+
if let projectLaunch = try await CommandResolver.projectNodeHostWorkerLaunch() {
829+
launch = projectLaunch
830+
} else {
831+
switch await CLIInstaller.status() {
832+
case let .ready(location, _):
833+
launch = MacNodeHostWorkerLaunch(command: [location, "node", "worker"])
834+
case let status:
835+
throw MacNodeHostWorker.WorkerError.unavailable(status.message)
836+
}
834837
}
838+
} catch let error as RuntimeResolutionError {
839+
throw MacNodeHostWorker.WorkerError.unavailable(RuntimeLocator.describeFailure(error))
835840
}
836-
let command = [executable, "node", "worker"]
837841
let input = MacNodeHostWorkerRetryPolicy.Input(
838-
command: command,
842+
launch: launch,
839843
configurationGeneration: self.nodeHostWorkerConfigurationGeneration)
840844
try self.nodeHostWorkerRetryPolicy.prepareForStart(input)
841845
self.activeNodeHostWorkerInput = input
842-
return try await nodeHostWorker.start(command: command)
846+
return try await nodeHostWorker.start(launch: launch)
843847
}
844848

845849
private func handleNodeHostWorkerFailure() {

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

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -40,23 +40,34 @@ import Testing
4040
#expect(cmd.prefix(2).elementsEqual([openclawPath.path, "gateway"]))
4141
}
4242

43-
@Test func `source checkout entrypoint wins when package bin link is absent`() async throws {
44-
let defaults = self.makeLocalDefaults()
43+
@Test func `source checkout worker uses the freshness aware runner`() async throws {
4544
let tmp = try makeTempDirForTests()
45+
let runner = tmp.appendingPathComponent("scripts/run-node.mjs")
4646
let sourceEntrypoint = tmp.appendingPathComponent("openclaw.mjs")
47-
let staleGlobalBin = tmp.appendingPathComponent("global/bin")
47+
let distEntrypoint = tmp.appendingPathComponent("dist/entry.js")
48+
let projectExecutable = tmp.appendingPathComponent("node_modules/.bin/openclaw")
49+
let runtimeBin = tmp.appendingPathComponent("runtime/bin")
50+
let node = runtimeBin.appendingPathComponent("node")
51+
try FileManager().createDirectory(
52+
at: runner.deletingLastPathComponent(),
53+
withIntermediateDirectories: true)
54+
try "// source runner\n".write(to: runner, atomically: true, encoding: .utf8)
4855
try makeExecutableForTests(at: sourceEntrypoint)
49-
try makeExecutableForTests(at: staleGlobalBin.appendingPathComponent("openclaw"))
50-
51-
let cmd = await CommandResolver.openclawCommand(
52-
subcommand: "node",
53-
extraArgs: ["worker"],
54-
defaults: defaults,
55-
configRoot: [:],
56-
searchPaths: [staleGlobalBin.path],
57-
projectRoot: tmp)
58-
59-
#expect(cmd == [sourceEntrypoint.path, "node", "worker"])
56+
try makeExecutableForTests(at: distEntrypoint)
57+
try makeExecutableForTests(at: projectExecutable)
58+
try makeExecutableForTests(at: node)
59+
try "#!/bin/sh\necho v22.22.3\n".write(to: node, atomically: true, encoding: .utf8)
60+
try FileManager().setAttributes([.posixPermissions: 0o755], ofItemAtPath: node.path)
61+
62+
let launch = try #require(try await CommandResolver.projectNodeHostWorkerLaunch(
63+
projectRoot: tmp,
64+
searchPaths: [runtimeBin.path]))
65+
66+
#expect(launch.command == [node.path, runner.path, "node", "worker"])
67+
#expect(launch.currentDirectoryURL == tmp)
68+
#expect(!launch.command.contains(sourceEntrypoint.path))
69+
#expect(!launch.command.contains(distEntrypoint.path))
70+
#expect(!launch.command.contains(projectExecutable.path))
6071
}
6172

6273
@Test func `falls back to node and script`() async throws {

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ struct MacNodeHostWorkerPipeTests {
1212
printf '%s\\n' '{"type":"ready","version":"test","manifest":{"caps":[],"commands":[],"pathEnv":"/bin"}}'
1313
sleep 1
1414
"""
15-
_ = try await worker.start(command: ["/bin/sh", "-c", script])
15+
_ = try await worker.start(launch: MacNodeHostWorkerLaunch(
16+
command: ["/bin/sh", "-c", script]))
1617

1718
let response = await worker.invoke(BridgeInvokeRequest(
1819
id: "closed",

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

Lines changed: 40 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import Darwin
12
import Foundation
23
import OpenClawKit
34
import Testing
@@ -17,7 +18,7 @@ private actor StubMacNodeHostWorker: MacNodeHostWorking {
1718
pathEnv: "/usr/bin:/bin")
1819
}
1920

20-
func start(command _: [String]) async throws -> MacNodeHostManifest { self.manifest }
21+
func start(launch _: MacNodeHostWorkerLaunch) async throws -> MacNodeHostManifest { self.manifest }
2122
func supports(_ command: String) async -> Bool { self.manifest.commands.contains(command) }
2223

2324
func invoke(_ request: BridgeInvokeRequest) async -> BridgeInvokeResponse {
@@ -38,7 +39,8 @@ private actor StubMacNodeHostWorker: MacNodeHostWorking {
3839
struct MacNodeHostWorkerTests {
3940
@Test func `worker crash retry budget is bounded and exponentially delayed`() throws {
4041
let input = MacNodeHostWorkerRetryPolicy.Input(
41-
command: ["/usr/local/bin/openclaw", "node", "worker"],
42+
launch: MacNodeHostWorkerLaunch(
43+
command: ["/usr/local/bin/openclaw", "node", "worker"]),
4244
configurationGeneration: 4)
4345
var policy = MacNodeHostWorkerRetryPolicy(maximumRetryCount: 5)
4446

@@ -62,10 +64,11 @@ struct MacNodeHostWorkerTests {
6264

6365
@Test func `new worker input resets an exhausted crash retry budget`() throws {
6466
let original = MacNodeHostWorkerRetryPolicy.Input(
65-
command: ["/usr/local/bin/openclaw", "node", "worker"],
67+
launch: MacNodeHostWorkerLaunch(
68+
command: ["/usr/local/bin/openclaw", "node", "worker"]),
6669
configurationGeneration: 4)
6770
let updated = MacNodeHostWorkerRetryPolicy.Input(
68-
command: original.command,
71+
launch: original.launch,
6972
configurationGeneration: 5)
7073
var policy = MacNodeHostWorkerRetryPolicy(maximumRetryCount: 1)
7174

@@ -89,11 +92,31 @@ struct MacNodeHostWorkerTests {
8992
while IFS= read -r line; do :; done
9093
"""
9194

92-
let manifest = try await worker.start(command: ["/bin/sh", "-c", script])
95+
let manifest = try await worker.start(launch: MacNodeHostWorkerLaunch(
96+
command: ["/bin/sh", "-c", script]))
9397
#expect(manifest.version == "test")
9498
await worker.stop()
9599
}
96100

101+
@Test func `worker launches in the selected checkout`() async throws {
102+
let checkout = try makeTempDirForTests().resolvingSymlinksInPath()
103+
let worker = MacNodeHostWorker(session: GatewayNodeSession(), startupTimeout: 1)
104+
let script = """
105+
printf '{"type":"ready","version":"test","manifest":{"caps":[],"commands":[],"pathEnv":"%s"}}\\n' \
106+
"$(/bin/pwd -P)"
107+
while IFS= read -r line; do :; done
108+
"""
109+
110+
let manifest = try await worker.start(launch: MacNodeHostWorkerLaunch(
111+
command: ["/bin/sh", "-c", script],
112+
currentDirectoryURL: checkout))
113+
114+
let expectedCurrentDirectory = try #require(realpath(checkout.path, nil))
115+
defer { free(expectedCurrentDirectory) }
116+
#expect(manifest.pathEnv == String(cString: expectedCurrentDirectory))
117+
await worker.stop()
118+
}
119+
97120
@Test(arguments: [
98121
OpenClawSystemCommand.run.rawValue,
99122
"mcp.tools.call.v1",
@@ -227,7 +250,8 @@ struct MacNodeHostWorkerTests {
227250
done
228251
"""
229252

230-
let manifest = try await worker.start(command: ["/bin/sh", "-c", script])
253+
let manifest = try await worker.start(launch: MacNodeHostWorkerLaunch(
254+
command: ["/bin/sh", "-c", script]))
231255
#expect(manifest.commands == ["system.run"])
232256
let response = await worker.invoke(BridgeInvokeRequest(
233257
id: "worker-run",
@@ -255,7 +279,8 @@ struct MacNodeHostWorkerTests {
255279
while IFS= read -r line; do :; done
256280
"""
257281

258-
_ = try await worker.start(command: ["/bin/sh", "-c", script])
282+
_ = try await worker.start(launch: MacNodeHostWorkerLaunch(
283+
command: ["/bin/sh", "-c", script]))
259284
await worker.handleInput(invokeId: "terminal-1", seq: 7, payloadJSON: #"{"data":"x"}"#)
260285
await worker.cancel(invokeId: "terminal-1")
261286
let response = await worker.invoke(BridgeInvokeRequest(
@@ -277,7 +302,8 @@ struct MacNodeHostWorkerTests {
277302
exit 7
278303
"""
279304

280-
_ = try await worker.start(command: ["/bin/sh", "-c", script])
305+
_ = try await worker.start(launch: MacNodeHostWorkerLaunch(
306+
command: ["/bin/sh", "-c", script]))
281307
try? await Task.sleep(for: .milliseconds(200))
282308
}
283309
}
@@ -293,8 +319,10 @@ struct MacNodeHostWorkerTests {
293319
while IFS= read -r line; do :; done
294320
"""
295321

296-
let first = try await worker.start(command: ["/bin/sh", "-c", firstScript])
297-
let second = try await worker.start(command: ["/bin/sh", "-c", secondScript])
322+
let first = try await worker.start(launch: MacNodeHostWorkerLaunch(
323+
command: ["/bin/sh", "-c", firstScript]))
324+
let second = try await worker.start(launch: MacNodeHostWorkerLaunch(
325+
command: ["/bin/sh", "-c", secondScript]))
298326

299327
#expect(first.version == "first")
300328
#expect(second.version == "second")
@@ -312,7 +340,8 @@ struct MacNodeHostWorkerTests {
312340
IFS= read -r second
313341
printf '%s\\n' '{"type":"invoke-result","result":{"id":"second","ok":true,"payload":{"done":true}}}'
314342
"""
315-
_ = try await worker.start(command: ["/bin/sh", "-c", script])
343+
_ = try await worker.start(launch: MacNodeHostWorkerLaunch(
344+
command: ["/bin/sh", "-c", script]))
316345

317346
let first = Task {
318347
await worker.invoke(BridgeInvokeRequest(

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ private actor CoordinatorDrainSnapshotProbe {
103103
private actor CoordinatorNodeHostWorkerProbe: MacNodeHostWorking {
104104
private var stopCount = 0
105105

106-
func start(command _: [String]) async throws -> MacNodeHostManifest {
106+
func start(launch _: MacNodeHostWorkerLaunch) async throws -> MacNodeHostManifest {
107107
MacNodeHostManifest(version: "test", caps: [], commands: [], pathEnv: "/usr/bin:/bin")
108108
}
109109

‎apps/shared/OpenClawKit/Sources/OpenClawKit/DeviceIdentitySQLiteStore.swift‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,12 @@ enum DeviceIdentitySQLiteStore {
130130
{
131131
try self.secureDirectory(destinationStateDirURL)
132132
try self.secureDirectory(databaseURL.deletingLastPathComponent())
133+
// SQLite owns an existing profile; leave any downgrade-recreated legacy source for Doctor.
134+
if self.pathMayExist(databaseURL),
135+
let existing = try self.loadExisting(databaseURL: databaseURL, profile: profile)
136+
{
137+
return existing
138+
}
133139
var claims: [LegacyClaim] = []
134140
do {
135141
for source in legacySources {

0 commit comments

Comments
 (0)