Skip to content

Commit 20f145f

Browse files
authored
fix(mac): enable terminal actions for paired-node sessions (#107361)
* fix(mac): enable paired-node terminal sessions * fix(ci): align node worker bridge checks
1 parent b9d0473 commit 20f145f

13 files changed

Lines changed: 379 additions & 59 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ Docs: https://docs.openclaw.ai
66

77
### Changes
88

9+
- **macOS paired-node terminals:** advertise duplex Codex and Claude terminal resume commands from the embedded node host and forward interactive input and cancellation through the native app bridge. (#107335)
910
- **Control UI catalog terminals:** open eligible Codex and Claude Code sessions in the native CLI on their Gateway or paired-node host, with viewer-versus-terminal preferences, validated resume commands, and an interactive PTY relay. (#107086)
1011
- **Skill Workshop history review:** add a manual, newest-first session scan that progressively searches older substantial work for conservative skill ideas, stores only SQLite cursor metadata, and leaves up to three results as pending proposals even when autonomous self-learning is disabled. (#106182)
1112
- **SQLite snapshots:** add `openclaw backup sqlite create|list|verify|restore` for compact, verified global and per-agent database artifacts with fresh-target-only restore. (#94805) Thanks @giodl73-repo.

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

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ protocol MacNodeHostWorking: Sendable {
1818
func start(command: [String]) async throws -> MacNodeHostManifest
1919
func supports(_ command: String) async -> Bool
2020
func invoke(_ request: BridgeInvokeRequest) async -> BridgeInvokeResponse
21+
func handleInput(invokeId: String, seq: Int, payloadJSON: String) async
22+
func cancel(invokeId: String) async
2123
func setRoute(_ route: GatewayNodeSessionRoute?, authorityGeneration: UInt64) async -> Bool
2224
func publishInventory(ifCurrentRoute route: GatewayNodeSessionRoute) async
2325
func stop() async
@@ -28,6 +30,13 @@ protocol MacNodeHostWorking: Sendable {
2830
/// and keeps TCC-sensitive execution behind the native exec-host socket.
2931
final class MacNodeHostWorker: MacNodeHostWorking, @unchecked Sendable {
3032
nonisolated static let defaultStartupTimeout: TimeInterval = 300
33+
private static let maxPendingInvokeControlIDs = 32
34+
private static let maxPendingInvokeControlsPerID = 64
35+
36+
private enum PendingInvokeControl {
37+
case input(seq: Int, payloadJSON: String)
38+
case cancel
39+
}
3140

3241
enum WorkerError: LocalizedError {
3342
case unavailable(String)
@@ -60,6 +69,8 @@ final class MacNodeHostWorker: MacNodeHostWorking, @unchecked Sendable {
6069
private var routeAuthorityGeneration: UInt64 = 0
6170
private var startContinuation: CheckedContinuation<MacNodeHostManifest, Error>?
6271
private var invokeContinuations: [String: CheckedContinuation<BridgeInvokeResponse, Never>] = [:]
72+
private var pendingInvokeControls: [String: [PendingInvokeControl]] = [:]
73+
private var pendingInvokeControlOrder: [String] = []
6374
private var startTimer: DispatchSourceTimer?
6475
private var eventDeliveryTask: Task<Void, Never>?
6576
private var inventoryPublicationTask: Task<Void, Never>?
@@ -131,6 +142,9 @@ final class MacNodeHostWorker: MacNodeHostWorking, @unchecked Sendable {
131142
"type": "invoke",
132143
"request": workerRequest,
133144
])
145+
for control in self.takePendingInvokeControlsLocked(invokeId: request.id) {
146+
try self.enqueueInvokeControlLocked(control, invokeId: request.id)
147+
}
134148
} catch {
135149
self.invokeContinuations.removeValue(forKey: request.id)?.resume(returning:
136150
Self.unavailableResponse(request.id, "UNAVAILABLE: node-host worker write failed"))
@@ -139,6 +153,83 @@ final class MacNodeHostWorker: MacNodeHostWorking, @unchecked Sendable {
139153
}
140154
}
141155

156+
func handleInput(invokeId: String, seq: Int, payloadJSON: String) async {
157+
await withCheckedContinuation { continuation in
158+
self.queue.async {
159+
let control = PendingInvokeControl.input(seq: seq, payloadJSON: payloadJSON)
160+
if self.invokeContinuations[invokeId] != nil {
161+
try? self.enqueueInvokeControlLocked(control, invokeId: invokeId)
162+
} else if self.process?.isRunning == true, self.manifest != nil {
163+
self.bufferInvokeControlLocked(control, invokeId: invokeId)
164+
}
165+
continuation.resume()
166+
}
167+
}
168+
}
169+
170+
func cancel(invokeId: String) async {
171+
await withCheckedContinuation { continuation in
172+
self.queue.async {
173+
let control = PendingInvokeControl.cancel
174+
if self.invokeContinuations[invokeId] != nil {
175+
try? self.enqueueInvokeControlLocked(control, invokeId: invokeId)
176+
} else if self.process?.isRunning == true, self.manifest != nil {
177+
self.bufferInvokeControlLocked(control, invokeId: invokeId)
178+
}
179+
continuation.resume()
180+
}
181+
}
182+
}
183+
184+
private func bufferInvokeControlLocked(_ control: PendingInvokeControl, invokeId: String) {
185+
// Gateway control events can overtake detached invoke dispatch. Keep the
186+
// short race window bounded, then flush controls after the invoke frame.
187+
if self.pendingInvokeControls[invokeId] == nil {
188+
if self.pendingInvokeControlOrder.count >= Self.maxPendingInvokeControlIDs,
189+
let oldest = self.pendingInvokeControlOrder.first
190+
{
191+
self.pendingInvokeControlOrder.removeFirst()
192+
self.pendingInvokeControls.removeValue(forKey: oldest)
193+
}
194+
self.pendingInvokeControlOrder.append(invokeId)
195+
self.pendingInvokeControls[invokeId] = []
196+
}
197+
var controls = self.pendingInvokeControls[invokeId] ?? []
198+
if controls.contains(where: {
199+
if case .cancel = $0 { return true }
200+
return false
201+
}) {
202+
return
203+
}
204+
if controls.count >= Self.maxPendingInvokeControlsPerID {
205+
controls.removeFirst()
206+
}
207+
controls.append(control)
208+
self.pendingInvokeControls[invokeId] = controls
209+
}
210+
211+
private func takePendingInvokeControlsLocked(invokeId: String) -> [PendingInvokeControl] {
212+
self.pendingInvokeControlOrder.removeAll { $0 == invokeId }
213+
return self.pendingInvokeControls.removeValue(forKey: invokeId) ?? []
214+
}
215+
216+
private func enqueueInvokeControlLocked(_ control: PendingInvokeControl, invokeId: String) throws {
217+
switch control {
218+
case let .input(seq, payloadJSON):
219+
try self.enqueueWriteLocked([
220+
"type": "invoke-input",
221+
"invokeId": invokeId,
222+
"seq": seq,
223+
"payloadJSON": payloadJSON,
224+
])
225+
case .cancel:
226+
try self.enqueueWriteLocked([
227+
"type": "invoke-cancel",
228+
"invokeId": invokeId,
229+
])
230+
}
231+
}
232+
142233
func setRoute(_ route: GatewayNodeSessionRoute?, authorityGeneration: UInt64) async -> Bool {
143234
await withCheckedContinuation { continuation in
144235
self.queue.async {
@@ -561,6 +652,8 @@ final class MacNodeHostWorker: MacNodeHostWorking, @unchecked Sendable {
561652
}
562653
let pending = self.invokeContinuations
563654
self.invokeContinuations.removeAll()
655+
self.pendingInvokeControls.removeAll()
656+
self.pendingInvokeControlOrder.removeAll()
564657
for (id, continuation) in pending {
565658
continuation.resume(returning: Self.unavailableResponse(id, "UNAVAILABLE: node-host worker stopped"))
566659
}

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -683,6 +683,21 @@ final class MacNodeModeCoordinator: NSObject {
683683
}
684684
return await self.runtime.handleInvoke(req)
685685
},
686+
onInvokeInput: { [weak self] input in
687+
guard let self,
688+
await self.routeAuthorityAllowsInvoke(attempt.routeAuthorityGeneration)
689+
else { return }
690+
await self.nodeHostWorker?.handleInput(
691+
invokeId: input.id,
692+
seq: input.seq,
693+
payloadJSON: input.payloadjson)
694+
},
695+
onInvokeCancel: { [weak self] invokeId in
696+
guard let self,
697+
await self.routeAuthorityAllowsInvoke(attempt.routeAuthorityGeneration)
698+
else { return }
699+
await self.nodeHostWorker?.cancel(invokeId: invokeId)
700+
},
686701
onRouteInvalidated: { [weak self] in
687702
await self?.invalidateRuntimeRoute(authorityGeneration: attempt.routeAuthorityGeneration)
688703
})

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ private actor StubMacNodeHostWorker: MacNodeHostWorking {
2121
return BridgeInvokeResponse(id: request.id, ok: true, payloadJSON: #"{"owner":"cli"}"#)
2222
}
2323

24+
func handleInput(invokeId _: String, seq _: Int, payloadJSON _: String) async {}
25+
func cancel(invokeId _: String) async {}
26+
2427
func setRoute(_: GatewayNodeSessionRoute?, authorityGeneration _: UInt64) async -> Bool { true }
2528
func publishInventory(ifCurrentRoute _: GatewayNodeSessionRoute) async {}
2629
func stop() async {}
@@ -98,6 +101,34 @@ struct MacNodeHostWorkerTests {
98101
await worker.stop()
99102
}
100103

104+
@Test func `worker forwards terminal input and cancellation frames`() async throws {
105+
let worker = MacNodeHostWorker(session: GatewayNodeSession())
106+
let script = """
107+
printf '%s\\n' '{"type":"ready","version":"test","manifest":{"caps":["terminal"],"commands":["codex.terminal.resume.v1"],"pathEnv":"/usr/bin:/bin"},"inventory":{"skills":null,"pluginTools":[]}}'
108+
IFS= read -r invoke
109+
IFS= read -r input
110+
IFS= read -r cancel
111+
printf '%s' "$invoke" | grep -q '"id":"terminal-1"' || exit 40
112+
printf '%s' "$input" | grep -q '"type":"invoke-input"' || exit 41
113+
printf '%s' "$input" | grep -q '"invokeId":"terminal-1"' || exit 42
114+
printf '%s' "$input" | grep -q '"seq":7' || exit 43
115+
printf '%s' "$cancel" | grep -q '"type":"invoke-cancel"' || exit 44
116+
printf '%s' "$cancel" | grep -q '"invokeId":"terminal-1"' || exit 45
117+
printf '%s\\n' '{"type":"invoke-result","result":{"id":"terminal-1","ok":true}}'
118+
while IFS= read -r line; do :; done
119+
"""
120+
121+
_ = try await worker.start(command: ["/bin/sh", "-c", script])
122+
await worker.handleInput(invokeId: "terminal-1", seq: 7, payloadJSON: #"{"data":"x"}"#)
123+
await worker.cancel(invokeId: "terminal-1")
124+
let response = await worker.invoke(BridgeInvokeRequest(
125+
id: "terminal-1",
126+
command: "codex.terminal.resume.v1"))
127+
128+
#expect(response.ok)
129+
await worker.stop()
130+
}
131+
101132
@Test func `ready worker exit notifies its route owner`() async throws {
102133
try await confirmation("unexpected worker exit") { confirmed in
103134
let worker = MacNodeHostWorker(session: GatewayNodeSession()) {

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,9 @@ private actor CoordinatorNodeHostWorkerProbe: MacNodeHostWorking {
111111
BridgeInvokeResponse(id: request.id, ok: false)
112112
}
113113

114+
func handleInput(invokeId _: String, seq _: Int, payloadJSON _: String) async {}
115+
func cancel(invokeId _: String) async {}
116+
114117
func setRoute(_: GatewayNodeSessionRoute?, authorityGeneration _: UInt64) async -> Bool { true }
115118
func publishInventory(ifCurrentRoute _: GatewayNodeSessionRoute) async {}
116119
func stop() async { self.stopCount += 1 }

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

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ private struct NodeInvokeRequestPayload: Codable {
1212
var idempotencyKey: String?
1313
}
1414

15+
private struct NodeInvokeCancelPayload: Codable {
16+
var invokeId: String
17+
}
18+
1519
func canonicalizeCanvasHostUrl(raw: String?, activeURL: URL?) -> String? {
1620
let trimmed = raw?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
1721
guard !trimmed.isEmpty else { return nil }
@@ -165,6 +169,8 @@ public actor GatewayNodeSession {
165169
private var onConnected: (@Sendable () async -> Void)?
166170
private var onDisconnected: (@Sendable (String) async -> Void)?
167171
private var onInvoke: (@Sendable (BridgeInvokeRequest) async -> BridgeInvokeResponse)?
172+
private var onInvokeInput: (@Sendable (NodeInvokeInputEvent) async -> Void)?
173+
private var onInvokeCancel: (@Sendable (String) async -> Void)?
168174
private var onRouteInvalidated: (@Sendable () async -> Void)?
169175
private var hasEverConnected = false
170176
private var hasNotifiedConnected = false
@@ -335,6 +341,8 @@ public actor GatewayNodeSession {
335341
onConnected: @escaping @Sendable () async -> Void,
336342
onDisconnected: @escaping @Sendable (String) async -> Void,
337343
onInvoke: @escaping @Sendable (BridgeInvokeRequest) async -> BridgeInvokeResponse,
344+
onInvokeInput: (@Sendable (NodeInvokeInputEvent) async -> Void)? = nil,
345+
onInvokeCancel: (@Sendable (String) async -> Void)? = nil,
338346
onRouteInvalidated: (@Sendable () async -> Void)? = nil) async throws
339347
{
340348
let nextOptionsKey = self.connectOptionsKey(connectOptions)
@@ -404,6 +412,8 @@ public actor GatewayNodeSession {
404412
self.onConnected = onConnected
405413
self.onDisconnected = onDisconnected
406414
self.onInvoke = onInvoke
415+
self.onInvokeInput = onInvokeInput
416+
self.onInvokeCancel = onInvokeCancel
407417
self.onRouteInvalidated = onRouteInvalidated
408418
self.activeURL = url
409419
self.activeCredentials = credentials
@@ -415,6 +425,8 @@ public actor GatewayNodeSession {
415425
self.onConnected = onConnected
416426
self.onDisconnected = onDisconnected
417427
self.onInvoke = onInvoke
428+
self.onInvokeInput = onInvokeInput
429+
self.onInvokeCancel = onInvokeCancel
418430
self.onRouteInvalidated = onRouteInvalidated
419431
}
420432

@@ -458,6 +470,8 @@ public actor GatewayNodeSession {
458470
onConnected: @escaping @Sendable () async -> Void,
459471
onDisconnected: @escaping @Sendable (String) async -> Void,
460472
onInvoke: @escaping @Sendable (BridgeInvokeRequest) async -> BridgeInvokeResponse,
473+
onInvokeInput: (@Sendable (NodeInvokeInputEvent) async -> Void)? = nil,
474+
onInvokeCancel: (@Sendable (String) async -> Void)? = nil,
461475
onRouteInvalidated: (@Sendable () async -> Void)? = nil) async throws
462476
{
463477
try await self.connect(
@@ -472,6 +486,8 @@ public actor GatewayNodeSession {
472486
onConnected: onConnected,
473487
onDisconnected: onDisconnected,
474488
onInvoke: onInvoke,
489+
onInvokeInput: onInvokeInput,
490+
onInvokeCancel: onInvokeCancel,
475491
onRouteInvalidated: onRouteInvalidated)
476492
}
477493

@@ -507,6 +523,8 @@ public actor GatewayNodeSession {
507523
self.onConnected = nil
508524
self.onDisconnected = nil
509525
self.onInvoke = nil
526+
self.onInvokeInput = nil
527+
self.onInvokeCancel = nil
510528
self.onRouteInvalidated = nil
511529
self.activeSocketGeneration = nil
512530
self.lastRetiredSocketGeneration = nil
@@ -992,6 +1010,26 @@ extension GatewayNodeSession {
9921010
socketGeneration: UInt64) async
9931011
{
9941012
self.broadcastServerEvent(evt)
1013+
if evt.event == "node.invoke.input" {
1014+
guard let payload = evt.payload, let onInvokeInput else { return }
1015+
do {
1016+
let input: NodeInvokeInputEvent = try self.decodeEventPayload(from: payload)
1017+
await onInvokeInput(input)
1018+
} catch {
1019+
self.logger.error("node invoke input decode failed: \(error.localizedDescription, privacy: .public)")
1020+
}
1021+
return
1022+
}
1023+
if evt.event == "node.invoke.cancel" {
1024+
guard let payload = evt.payload, let onInvokeCancel else { return }
1025+
do {
1026+
let cancel: NodeInvokeCancelPayload = try self.decodeEventPayload(from: payload)
1027+
await onInvokeCancel(cancel.invokeId)
1028+
} catch {
1029+
self.logger.error("node invoke cancel decode failed: \(error.localizedDescription, privacy: .public)")
1030+
}
1031+
return
1032+
}
9951033
guard evt.event == "node.invoke.request" else { return }
9961034
self.logger.info("node invoke request received")
9971035
guard let payload = evt.payload else { return }
@@ -1442,12 +1480,16 @@ extension GatewayNodeSession {
14421480
}
14431481

14441482
private func decodeInvokeRequest(from payload: OpenClawProtocol.AnyCodable) throws -> NodeInvokeRequestPayload {
1483+
try self.decodeEventPayload(from: payload)
1484+
}
1485+
1486+
private func decodeEventPayload<T: Decodable>(from payload: OpenClawProtocol.AnyCodable) throws -> T {
14451487
do {
14461488
let data = try encoder.encode(payload)
1447-
return try self.decoder.decode(NodeInvokeRequestPayload.self, from: data)
1489+
return try self.decoder.decode(T.self, from: data)
14481490
} catch {
14491491
if let raw = payload.value as? String, let data = raw.data(using: .utf8) {
1450-
return try self.decoder.decode(NodeInvokeRequestPayload.self, from: data)
1492+
return try self.decoder.decode(T.self, from: data)
14511493
}
14521494
throw error
14531495
}

0 commit comments

Comments
 (0)