Skip to content

Commit 357891a

Browse files
authored
Merge pull request #676 from ngutman/fix/macos-bridge-tunnel-health
fix(macos): stabilize bridge tunnels
2 parents a6a9930 + 66bc003 commit 357891a

7 files changed

Lines changed: 215 additions & 49 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,8 @@
1212
- Gateway: add OpenAI-compatible `/v1/chat/completions` HTTP endpoint (auth, SSE streaming, per-agent routing). (#680) — thanks @steipete.
1313

1414
### Fixes
15-
- Block Streaming: enable for all providers, not just Telegram. (#684) — thanks @rubyrunsstuff.
15+
- macOS: stabilize bridge tunnels, guard invoke senders on disconnect, and drain stdout/stderr to avoid deadlocks. (#676) — thanks @ngutman.
1616
- Agents/System: clarify sandboxed runtime in system prompt and surface elevated availability when sandboxed.
17-
- Agents/System: add reasoning visibility hint + /reasoning and /status guidance in system prompt.
1817
- Auto-reply: prefer `RawBody` for command/directive parsing (WhatsApp + Discord) and prevent fallback runs from clobbering concurrent session updates. (#643) — thanks @mcinteerj.
1918
- WhatsApp: fix group reactions by preserving message IDs and sender JIDs in history; normalize participant phone numbers to JIDs in outbound reactions. (#640) — thanks @mcinteerj.
2019
- WhatsApp: expose group participant IDs to the model so reactions can target the right sender.

‎apps/macos/Sources/Clawdbot/NodeMode/MacNodeBridgeSession.swift‎

Lines changed: 87 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,14 @@ actor MacNodeBridgeSession {
2020
private let encoder = JSONEncoder()
2121
private let decoder = JSONDecoder()
2222
private let clock = ContinuousClock()
23+
private var disconnectHandler: (@Sendable (String) async -> Void)?
2324

2425
private var connection: NWConnection?
2526
private var queue: DispatchQueue?
2627
private var buffer = Data()
2728
private var pendingRPC: [String: CheckedContinuation<BridgeRPCResponse, Error>] = [:]
2829
private var serverEventSubscribers: [UUID: AsyncStream<BridgeEventFrame>.Continuation] = [:]
30+
private var invokeTasks: [UUID: Task<Void, Never>] = [:]
2931
private var pingTask: Task<Void, Never>?
3032
private var lastPongAt: ContinuousClock.Instant?
3133

@@ -35,10 +37,12 @@ actor MacNodeBridgeSession {
3537
endpoint: NWEndpoint,
3638
hello: BridgeHello,
3739
onConnected: (@Sendable (String) async -> Void)? = nil,
40+
onDisconnected: (@Sendable (String) async -> Void)? = nil,
3841
onInvoke: @escaping @Sendable (BridgeInvokeRequest) async -> BridgeInvokeResponse)
3942
async throws
4043
{
4144
await self.disconnect()
45+
self.disconnectHandler = onDisconnected
4246
self.state = .connecting
4347

4448
let params = NWParameters.tcp
@@ -83,6 +87,7 @@ actor MacNodeBridgeSession {
8387
let data = line.data(using: .utf8),
8488
let base = try? self.decoder.decode(BridgeBaseFrame.self, from: data)
8589
else {
90+
self.logger.error("node bridge hello failed (unexpected response)")
8691
await self.disconnect()
8792
throw NSError(domain: "Bridge", code: 1, userInfo: [
8893
NSLocalizedDescriptionKey: "Unexpected bridge response",
@@ -97,53 +102,67 @@ actor MacNodeBridgeSession {
97102
} else if base.type == "error" {
98103
let err = try self.decoder.decode(BridgeErrorFrame.self, from: data)
99104
self.state = .failed(message: "\(err.code): \(err.message)")
105+
self.logger.error("node bridge hello error: \(err.code, privacy: .public)")
100106
await self.disconnect()
101107
throw NSError(domain: "Bridge", code: 2, userInfo: [
102108
NSLocalizedDescriptionKey: "\(err.code): \(err.message)",
103109
])
104110
} else {
105111
self.state = .failed(message: "Unexpected bridge response")
112+
self.logger.error("node bridge hello failed (unexpected frame)")
106113
await self.disconnect()
107114
throw NSError(domain: "Bridge", code: 3, userInfo: [
108115
NSLocalizedDescriptionKey: "Unexpected bridge response",
109116
])
110117
}
111118

112-
while true {
113-
guard let next = try await self.receiveLine() else { break }
114-
guard let nextData = next.data(using: .utf8) else { continue }
115-
guard let nextBase = try? self.decoder.decode(BridgeBaseFrame.self, from: nextData) else { continue }
116-
117-
switch nextBase.type {
118-
case "res":
119-
let res = try self.decoder.decode(BridgeRPCResponse.self, from: nextData)
120-
if let cont = self.pendingRPC.removeValue(forKey: res.id) {
121-
cont.resume(returning: res)
122-
}
123-
124-
case "event":
125-
let evt = try self.decoder.decode(BridgeEventFrame.self, from: nextData)
126-
self.broadcastServerEvent(evt)
127-
128-
case "ping":
129-
let ping = try self.decoder.decode(BridgePing.self, from: nextData)
130-
try await self.send(BridgePong(type: "pong", id: ping.id))
131-
132-
case "pong":
133-
let pong = try self.decoder.decode(BridgePong.self, from: nextData)
134-
self.notePong(pong)
119+
do {
120+
while true {
121+
guard let next = try await self.receiveLine() else { break }
122+
guard let nextData = next.data(using: .utf8) else { continue }
123+
guard let nextBase = try? self.decoder.decode(BridgeBaseFrame.self, from: nextData) else { continue }
124+
125+
switch nextBase.type {
126+
case "res":
127+
let res = try self.decoder.decode(BridgeRPCResponse.self, from: nextData)
128+
if let cont = self.pendingRPC.removeValue(forKey: res.id) {
129+
cont.resume(returning: res)
130+
}
135131

136-
case "invoke":
137-
let req = try self.decoder.decode(BridgeInvokeRequest.self, from: nextData)
138-
let res = await onInvoke(req)
139-
try await self.send(res)
132+
case "event":
133+
let evt = try self.decoder.decode(BridgeEventFrame.self, from: nextData)
134+
self.broadcastServerEvent(evt)
135+
136+
case "ping":
137+
let ping = try self.decoder.decode(BridgePing.self, from: nextData)
138+
try await self.send(BridgePong(type: "pong", id: ping.id))
139+
140+
case "pong":
141+
let pong = try self.decoder.decode(BridgePong.self, from: nextData)
142+
self.notePong(pong)
143+
144+
case "invoke":
145+
let req = try self.decoder.decode(BridgeInvokeRequest.self, from: nextData)
146+
let taskID = UUID()
147+
let task = Task { [weak self] in
148+
let res = await onInvoke(req)
149+
guard let self else { return }
150+
await self.sendInvokeResponse(res, taskID: taskID)
151+
}
152+
self.invokeTasks[taskID] = task
140153

141-
default:
142-
continue
154+
default:
155+
continue
156+
}
143157
}
144-
}
145158

146-
await self.disconnect()
159+
await self.handleDisconnect(reason: "connection closed")
160+
} catch {
161+
self.logger.error(
162+
"node bridge receive failed: \(error.localizedDescription, privacy: .public)")
163+
await self.handleDisconnect(reason: "receive failed")
164+
throw error
165+
}
147166
}
148167

149168
func sendEvent(event: String, payloadJSON: String?) async throws {
@@ -205,6 +224,8 @@ actor MacNodeBridgeSession {
205224
self.pingTask?.cancel()
206225
self.pingTask = nil
207226
self.lastPongAt = nil
227+
self.disconnectHandler = nil
228+
self.cancelInvokeTasks()
208229

209230
self.connection?.cancel()
210231
self.connection = nil
@@ -312,6 +333,7 @@ actor MacNodeBridgeSession {
312333
private func startPingLoop() {
313334
self.pingTask?.cancel()
314335
self.lastPongAt = self.clock.now
336+
self.logger.debug("node bridge ping loop started")
315337
self.pingTask = Task { [weak self] in
316338
guard let self else { return }
317339
await self.runPingLoop()
@@ -336,7 +358,7 @@ actor MacNodeBridgeSession {
336358
"Node bridge heartbeat timed out; disconnecting " +
337359
"(age: \(ageDescription, privacy: .public))."
338360
self.logger.warning(message)
339-
await self.disconnect()
361+
await self.handleDisconnect(reason: "ping timeout")
340362
return
341363
}
342364
}
@@ -350,7 +372,7 @@ actor MacNodeBridgeSession {
350372
"Node bridge ping send failed; disconnecting " +
351373
"(error: \(errorDescription, privacy: .public))."
352374
self.logger.warning(message)
353-
await self.disconnect()
375+
await self.handleDisconnect(reason: "ping send failed")
354376
return
355377
}
356378
}
@@ -369,15 +391,45 @@ actor MacNodeBridgeSession {
369391
"Node bridge connection failed; disconnecting " +
370392
"(error: \(errorDescription, privacy: .public))."
371393
self.logger.warning(message)
372-
await self.disconnect()
394+
await self.handleDisconnect(reason: "connection failed")
373395
case .cancelled:
374396
self.logger.warning("Node bridge connection cancelled; disconnecting.")
375-
await self.disconnect()
397+
await self.handleDisconnect(reason: "connection cancelled")
376398
default:
377399
break
378400
}
379401
}
380402

403+
private func handleDisconnect(reason: String) async {
404+
self.logger.info("node bridge disconnect reason=\(reason, privacy: .public)")
405+
if let handler = self.disconnectHandler {
406+
await handler(reason)
407+
}
408+
await self.disconnect()
409+
}
410+
411+
private func logInvokeSendFailure(_ error: Error) {
412+
self.logger.error(
413+
"node bridge invoke response send failed: \(error.localizedDescription, privacy: .public)")
414+
}
415+
416+
private func sendInvokeResponse(_ response: BridgeInvokeResponse, taskID: UUID) async {
417+
defer { self.invokeTasks[taskID] = nil }
418+
if Task.isCancelled { return }
419+
do {
420+
try await self.send(response)
421+
} catch {
422+
await self.logInvokeSendFailure(error)
423+
}
424+
}
425+
426+
private func cancelInvokeTasks() {
427+
for task in self.invokeTasks.values {
428+
task.cancel()
429+
}
430+
self.invokeTasks.removeAll()
431+
}
432+
381433
private static func makeStateStream(
382434
for connection: NWConnection) -> AsyncStream<NWConnection.State>
383435
{

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

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,17 @@ final class MacNodeModeCoordinator {
6161
retryDelay = 1_000_000_000
6262
do {
6363
let hello = await self.makeHello()
64+
self.logger.info(
65+
"mac node bridge connecting endpoint=\(endpoint, privacy: .public)")
6466
try await self.session.connect(
6567
endpoint: endpoint,
6668
hello: hello,
6769
onConnected: { [weak self] serverName in
6870
self?.logger.info("mac node connected to \(serverName, privacy: .public)")
6971
},
72+
onDisconnected: { reason in
73+
await MacNodeModeCoordinator.handleBridgeDisconnect(reason: reason)
74+
},
7075
onInvoke: { [weak self] req in
7176
guard let self else {
7277
return BridgeInvokeResponse(
@@ -80,7 +85,8 @@ final class MacNodeModeCoordinator {
8085
if await self.tryPair(endpoint: endpoint, error: error) {
8186
continue
8287
}
83-
self.logger.error("mac node bridge connect failed: \(error.localizedDescription, privacy: .public)")
88+
self.logger.error(
89+
"mac node bridge connect failed: \(error.localizedDescription, privacy: .public)")
8490
try? await Task.sleep(nanoseconds: min(retryDelay, 5_000_000_000))
8591
retryDelay = min(retryDelay * 2, 10_000_000_000)
8692
}
@@ -285,15 +291,31 @@ final class MacNodeModeCoordinator {
285291
let mode = await MainActor.run(body: { AppStateStore.shared.connectionMode })
286292
if mode == .remote {
287293
do {
288-
if self.tunnel == nil || self.tunnel?.process.isRunning == false {
289-
let remotePort = Self.remoteBridgePort()
290-
self.tunnel = try await RemotePortTunnel.create(
291-
remotePort: remotePort,
292-
allowRemoteUrlOverride: false)
294+
if let tunnel = self.tunnel,
295+
tunnel.process.isRunning,
296+
let localPort = tunnel.localPort
297+
{
298+
let healthy = await self.bridgeTunnelHealthy(localPort: localPort, timeoutSeconds: 1.0)
299+
if healthy, let port = NWEndpoint.Port(rawValue: localPort) {
300+
self.logger.info(
301+
"reusing mac node bridge tunnel localPort=\(localPort, privacy: .public)")
302+
return .hostPort(host: "127.0.0.1", port: port)
303+
}
304+
self.logger.error(
305+
"mac node bridge tunnel unhealthy localPort=\(localPort, privacy: .public); restarting")
306+
tunnel.terminate()
307+
self.tunnel = nil
293308
}
309+
310+
let remotePort = Self.remoteBridgePort()
311+
self.tunnel = try await RemotePortTunnel.create(
312+
remotePort: remotePort,
313+
allowRemoteUrlOverride: false)
294314
if let localPort = self.tunnel?.localPort,
295315
let port = NWEndpoint.Port(rawValue: localPort)
296316
{
317+
self.logger.info(
318+
"mac node bridge tunnel ready localPort=\(localPort, privacy: .public) remotePort=\(remotePort, privacy: .public)")
297319
return .hostPort(host: "127.0.0.1", port: port)
298320
}
299321
} catch {
@@ -311,6 +333,21 @@ final class MacNodeModeCoordinator {
311333
return await Self.discoverBridgeEndpoint(timeoutSeconds: timeoutSeconds)
312334
}
313335

336+
@MainActor
337+
private static func handleBridgeDisconnect(reason: String) async {
338+
guard reason.localizedCaseInsensitiveContains("ping") else { return }
339+
let coordinator = MacNodeModeCoordinator.shared
340+
coordinator.logger.error(
341+
"mac node bridge disconnected (\(reason, privacy: .public)); resetting tunnel")
342+
coordinator.tunnel?.terminate()
343+
coordinator.tunnel = nil
344+
}
345+
346+
private func bridgeTunnelHealthy(localPort: UInt16, timeoutSeconds: Double) async -> Bool {
347+
guard let port = NWEndpoint.Port(rawValue: localPort) else { return false }
348+
return await Self.probeEndpoint(.hostPort(host: "127.0.0.1", port: port), timeoutSeconds: timeoutSeconds)
349+
}
350+
314351
private static func discoverBridgeEndpoint(timeoutSeconds: Double) async -> NWEndpoint? {
315352
final class DiscoveryState: @unchecked Sendable {
316353
let lock = NSLock()

‎apps/macos/Sources/Clawdbot/RemotePortTunnel.swift‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ final class RemotePortTunnel {
4141
static func create(
4242
remotePort: Int,
4343
preferredLocalPort: UInt16? = nil,
44-
allowRemoteUrlOverride: Bool = true) async throws -> RemotePortTunnel
44+
allowRemoteUrlOverride: Bool = true,
45+
allowRandomLocalPort: Bool = true) async throws -> RemotePortTunnel
4546
{
4647
let settings = CommandResolver.connectionSettings()
4748
guard settings.mode == .remote, let parsed = CommandResolver.parseSSHTarget(settings.target) else {
@@ -51,7 +52,9 @@ final class RemotePortTunnel {
5152
userInfo: [NSLocalizedDescriptionKey: "Remote mode is not configured"])
5253
}
5354

54-
let localPort = try await Self.findPort(preferred: preferredLocalPort)
55+
let localPort = try await Self.findPort(
56+
preferred: preferredLocalPort,
57+
allowRandom: allowRandomLocalPort)
5558
let sshHost = parsed.host.trimmingCharacters(in: .whitespacesAndNewlines)
5659
let remotePortOverride =
5760
allowRemoteUrlOverride && remotePort == GatewayEnvironment.gatewayPort()
@@ -172,8 +175,16 @@ final class RemotePortTunnel {
172175
return trimmed.split(separator: ".").first.map(String.init) ?? trimmed
173176
}
174177

175-
private static func findPort(preferred: UInt16?) async throws -> UInt16 {
178+
private static func findPort(preferred: UInt16?, allowRandom: Bool) async throws -> UInt16 {
176179
if let preferred, self.portIsFree(preferred) { return preferred }
180+
if let preferred, !allowRandom {
181+
throw NSError(
182+
domain: "RemotePortTunnel",
183+
code: 5,
184+
userInfo: [
185+
NSLocalizedDescriptionKey: "Local port \(preferred) is unavailable",
186+
])
187+
}
177188

178189
return try await withCheckedThrowingContinuation { cont in
179190
let queue = DispatchQueue(label: "com.clawdbot.remote.tunnel.port", qos: .utility)

0 commit comments

Comments
 (0)