diff --git a/apps/macos/Sources/Clawdbot/ConnectionModeCoordinator.swift b/apps/macos/Sources/Clawdbot/ConnectionModeCoordinator.swift index 1f6d829f1..b1f893b1e 100644 --- a/apps/macos/Sources/Clawdbot/ConnectionModeCoordinator.swift +++ b/apps/macos/Sources/Clawdbot/ConnectionModeCoordinator.swift @@ -12,6 +12,9 @@ final class ConnectionModeCoordinator { func apply(mode: AppState.ConnectionMode, paused: Bool) async { switch mode { case .unconfigured: + if let error = await NodeServiceManager.stop() { + NodesStore.shared.lastError = "Node service stop failed: \(error)" + } await RemoteTunnelManager.shared.stopAll() WebChatManager.shared.resetTunnels() GatewayProcessManager.shared.stop() @@ -20,6 +23,9 @@ final class ConnectionModeCoordinator { Task.detached { await PortGuardian.shared.sweep(mode: .unconfigured) } case .local: + if let error = await NodeServiceManager.stop() { + NodesStore.shared.lastError = "Node service stop failed: \(error)" + } await RemoteTunnelManager.shared.stopAll() WebChatManager.shared.resetTunnels() let shouldStart = GatewayAutostartPolicy.shouldStartGateway(mode: .local, paused: paused) @@ -50,6 +56,9 @@ final class ConnectionModeCoordinator { WebChatManager.shared.resetTunnels() do { + if let error = await NodeServiceManager.start() { + NodesStore.shared.lastError = "Node service start failed: \(error)" + } _ = try await GatewayEndpointStore.shared.ensureRemoteControlTunnel() let settings = CommandResolver.connectionSettings() try await ControlChannel.shared.configure(mode: .remote( diff --git a/apps/macos/Sources/Clawdbot/NodeServiceManager.swift b/apps/macos/Sources/Clawdbot/NodeServiceManager.swift new file mode 100644 index 000000000..2dd62d1e6 --- /dev/null +++ b/apps/macos/Sources/Clawdbot/NodeServiceManager.swift @@ -0,0 +1,150 @@ +import Foundation +import OSLog + +enum NodeServiceManager { + private static let logger = Logger(subsystem: "com.clawdbot", category: "node.service") + + static func start() async -> String? { + let result = await self.runServiceCommandResult( + ["node", "start"], + timeout: 20, + quiet: false) + if let error = self.errorMessage(from: result, treatNotLoadedAsError: true) { + self.logger.error("node service start failed: \(error, privacy: .public)") + return error + } + return nil + } + + static func stop() async -> String? { + let result = await self.runServiceCommandResult( + ["node", "stop"], + timeout: 15, + quiet: false) + if let error = self.errorMessage(from: result, treatNotLoadedAsError: false) { + self.logger.error("node service stop failed: \(error, privacy: .public)") + return error + } + return nil + } +} + +extension NodeServiceManager { + private struct CommandResult { + let success: Bool + let payload: Data? + let message: String? + let parsed: ParsedServiceJson? + } + + private struct ParsedServiceJson { + let text: String + let object: [String: Any] + let ok: Bool? + let result: String? + let message: String? + let error: String? + let hints: [String] + } + + private static func runServiceCommandResult( + _ args: [String], + timeout: Double, + quiet: Bool) async -> CommandResult + { + let command = CommandResolver.clawdbotCommand( + subcommand: "service", + extraArgs: self.withJsonFlag(args), + // Service management must always run locally, even if remote mode is configured. + configRoot: ["gateway": ["mode": "local"]]) + var env = ProcessInfo.processInfo.environment + env["PATH"] = CommandResolver.preferredPaths().joined(separator: ":") + let response = await ShellExecutor.runDetailed(command: command, cwd: nil, env: env, timeout: timeout) + let parsed = self.parseServiceJson(from: response.stdout) ?? self.parseServiceJson(from: response.stderr) + let ok = parsed?.ok + let message = parsed?.error ?? parsed?.message + let payload = parsed?.text.data(using: .utf8) + ?? (response.stdout.isEmpty ? response.stderr : response.stdout).data(using: .utf8) + let success = ok ?? response.success + if success { + return CommandResult(success: true, payload: payload, message: nil, parsed: parsed) + } + + if quiet { + return CommandResult(success: false, payload: payload, message: message, parsed: parsed) + } + + let detail = message ?? self.summarize(response.stderr) ?? self.summarize(response.stdout) + let exit = response.exitCode.map { "exit \($0)" } ?? (response.errorMessage ?? "failed") + let fullMessage = detail.map { "Node service command failed (\(exit)): \($0)" } + ?? "Node service command failed (\(exit))" + self.logger.error("\(fullMessage, privacy: .public)") + return CommandResult(success: false, payload: payload, message: detail, parsed: parsed) + } + + private static func errorMessage(from result: CommandResult, treatNotLoadedAsError: Bool) -> String? { + if !result.success { + return result.message ?? "Node service command failed" + } + guard let parsed = result.parsed else { return nil } + if parsed.ok == false { + return self.mergeHints(message: parsed.error ?? parsed.message, hints: parsed.hints) + } + if treatNotLoadedAsError, parsed.result == "not-loaded" { + let base = parsed.message ?? "Node service not loaded." + return self.mergeHints(message: base, hints: parsed.hints) + } + return nil + } + + private static func withJsonFlag(_ args: [String]) -> [String] { + if args.contains("--json") { return args } + return args + ["--json"] + } + + private static func parseServiceJson(from raw: String) -> ParsedServiceJson? { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard let start = trimmed.firstIndex(of: "{"), + let end = trimmed.lastIndex(of: "}") + else { + return nil + } + let jsonText = String(trimmed[start...end]) + guard let data = jsonText.data(using: .utf8) else { return nil } + guard let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil } + let ok = object["ok"] as? Bool + let result = object["result"] as? String + let message = object["message"] as? String + let error = object["error"] as? String + let hints = (object["hints"] as? [String]) ?? [] + return ParsedServiceJson( + text: jsonText, + object: object, + ok: ok, + result: result, + message: message, + error: error, + hints: hints) + } + + private static func mergeHints(message: String?, hints: [String]) -> String? { + let trimmed = message?.trimmingCharacters(in: .whitespacesAndNewlines) + let nonEmpty = trimmed?.isEmpty == false ? trimmed : nil + guard !hints.isEmpty else { return nonEmpty } + let hintText = hints.prefix(2).joined(separator: " · ") + if let nonEmpty { + return "\(nonEmpty) (\(hintText))" + } + return hintText + } + + private static func summarize(_ text: String) -> String? { + let lines = text + .split(whereSeparator: \.isNewline) + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + guard let last = lines.last else { return nil } + let normalized = last.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression) + return normalized.count > 200 ? String(normalized.prefix(199)) + "…" : normalized + } +} diff --git a/docs/platforms/mac/xpc.md b/docs/platforms/mac/xpc.md index 77b026a96..dab94c2de 100644 --- a/docs/platforms/mac/xpc.md +++ b/docs/platforms/mac/xpc.md @@ -5,9 +5,7 @@ read_when: --- # Clawdbot macOS IPC architecture -**Current model:** there is **no local control socket** and no `clawdbot-mac` CLI. All agent actions go through the Gateway WebSocket and `node.invoke`. UI automation still uses PeekabooBridge. - -**Planned model:** add a local Unix socket between the **node service** and the **macOS app**. The app owns `system.run` (UI/TCC context); the node service forwards exec requests over IPC. +**Current model:** a local Unix socket connects the **node service** to the **macOS app** for exec approvals + `system.run`. There is no `clawdbot-mac` CLI; agent actions still flow through the Gateway WebSocket and `node.invoke`. UI automation uses PeekabooBridge. ## Goals - Single GUI app instance that owns all TCC-facing work (notifications, screen recording, mic, speech, AppleScript). @@ -15,11 +13,11 @@ read_when: - Predictable permissions: always the same signed bundle ID, launched by launchd, so TCC grants stick. ## How it works -### Gateway + node bridge (current) +### Gateway + node bridge - The app runs the Gateway (local mode) and connects to it as a node. - Agent actions are performed via `node.invoke` (e.g. `system.run`, `system.notify`, `canvas.*`). -### Node service + app IPC (planned) +### Node service + app IPC - A headless node service connects to the Gateway bridge. - `system.run` requests are forwarded to the macOS app over a local Unix socket. - The app performs the exec in UI context, prompts if needed, and returns output. @@ -38,10 +36,6 @@ Agent -> Gateway -> Bridge -> Node Service (TS) - Security: bridge hosts require an allowed TeamID; DEBUG-only same-UID escape hatch is guarded by `PEEKABOO_ALLOW_UNSIGNED_SOCKET_CLIENTS=1` (Peekaboo convention). - See: [PeekabooBridge usage](/platforms/mac/peekaboo) for details. -### Mach/XPC -- Not required for automation; `node.invoke` + PeekabooBridge cover current needs. -- Planned IPC keeps Unix sockets (no XPC helper). - ## Operational flows - Restart/rebuild: `SIGN_IDENTITY="Apple Development: ()" scripts/restart-mac.sh` - Kills existing instances @@ -54,4 +48,4 @@ Agent -> Gateway -> Bridge -> Node Service (TS) - PeekabooBridge: `PEEKABOO_ALLOW_UNSIGNED_SOCKET_CLIENTS=1` (DEBUG-only) may allow same-UID callers for local development. - All communication remains local-only; no network sockets are exposed. - TCC prompts originate only from the GUI app bundle; keep the signed bundle ID stable across rebuilds. -- Planned IPC hardening: socket mode `0600`, token, peer-UID checks, HMAC challenge/response, short TTL. +- IPC hardening: socket mode `0600`, token, peer-UID checks, HMAC challenge/response, short TTL. diff --git a/docs/platforms/macos.md b/docs/platforms/macos.md index 2c8466e6c..5e642ebac 100644 --- a/docs/platforms/macos.md +++ b/docs/platforms/macos.md @@ -17,19 +17,17 @@ capabilities to the agent as a node. Speech Recognition, Automation/AppleScript). - Runs or connects to the Gateway (local or remote). - Exposes macOS‑only tools (Canvas, Camera, Screen Recording, `system.run`). +- Starts the local node host service in **remote** mode (launchd), and stops it in **local** mode. - Optionally hosts **PeekabooBridge** for UI automation. - Installs the global CLI (`clawdbot`) via npm/pnpm on request (bun not recommended for the Gateway runtime). -Planned: -- Run a headless **node service** locally (launchd). -- Keep `system.run` in the app (UI/TCC context), with the node service forwarding via IPC. - ## Local vs remote mode - **Local** (default): the app attaches to a running local Gateway if present; otherwise it enables the launchd service via `clawdbot daemon`. - **Remote**: the app connects to a Gateway over SSH/Tailscale and never starts a local process. + The app starts the local **node host service** so the remote Gateway can reach this Mac. The app does not spawn the Gateway as a child process. ## Launchd control @@ -58,9 +56,9 @@ The macOS app presents itself as a node. Common commands: The node reports a `permissions` map so agents can decide what’s allowed. -Planned split: -- Node service advertises the node surface to the Gateway. -- macOS app performs `system.run` in UI context over IPC. +Node service + app IPC: +- When the headless node service is running (remote mode), it connects to the Gateway bridge. +- `system.run` executes in the macOS app (UI/TCC context) over a local Unix socket; prompts + output stay in-app. Diagram (SCI): ```